summaryrefslogtreecommitdiff
path: root/app/models
diff options
context:
space:
mode:
Diffstat (limited to 'app/models')
-rw-r--r--app/models/ability.rb2
-rw-r--r--app/models/abuse_report.rb12
-rw-r--r--app/models/active_session.rb4
-rw-r--r--app/models/appearance.rb21
-rw-r--r--app/models/application_setting.rb206
-rw-r--r--app/models/audit_event.rb2
-rw-r--r--app/models/award_emoji.rb20
-rw-r--r--app/models/badge.rb10
-rw-r--r--app/models/blob.rb6
-rw-r--r--app/models/blob_viewer/auxiliary.rb2
-rw-r--r--app/models/blob_viewer/balsamiq.rb8
-rw-r--r--app/models/blob_viewer/base.rb4
-rw-r--r--app/models/blob_viewer/binary_stl.rb4
-rw-r--r--app/models/blob_viewer/cartfile.rb6
-rw-r--r--app/models/blob_viewer/changelog.rb4
-rw-r--r--app/models/blob_viewer/composer_json.rb8
-rw-r--r--app/models/blob_viewer/contributing.rb4
-rw-r--r--app/models/blob_viewer/dependency_manager.rb8
-rw-r--r--app/models/blob_viewer/download.rb2
-rw-r--r--app/models/blob_viewer/empty.rb2
-rw-r--r--app/models/blob_viewer/gemfile.rb6
-rw-r--r--app/models/blob_viewer/gemspec.rb10
-rw-r--r--app/models/blob_viewer/gitlab_ci_yml.rb6
-rw-r--r--app/models/blob_viewer/godeps_json.rb6
-rw-r--r--app/models/blob_viewer/image.rb6
-rw-r--r--app/models/blob_viewer/license.rb4
-rw-r--r--app/models/blob_viewer/markup.rb4
-rw-r--r--app/models/blob_viewer/notebook.rb8
-rw-r--r--app/models/blob_viewer/package_json.rb14
-rw-r--r--app/models/blob_viewer/pdf.rb8
-rw-r--r--app/models/blob_viewer/podfile.rb6
-rw-r--r--app/models/blob_viewer/podspec.rb10
-rw-r--r--app/models/blob_viewer/podspec_json.rb4
-rw-r--r--app/models/blob_viewer/readme.rb4
-rw-r--r--app/models/blob_viewer/requirements_txt.rb6
-rw-r--r--app/models/blob_viewer/rich.rb4
-rw-r--r--app/models/blob_viewer/route_map.rb6
-rw-r--r--app/models/blob_viewer/simple.rb4
-rw-r--r--app/models/blob_viewer/sketch.rb8
-rw-r--r--app/models/blob_viewer/svg.rb8
-rw-r--r--app/models/blob_viewer/text.rb2
-rw-r--r--app/models/blob_viewer/video.rb6
-rw-r--r--app/models/blob_viewer/yarn_lock.rb6
-rw-r--r--app/models/board_group_recent_visit.rb2
-rw-r--r--app/models/board_project_recent_visit.rb2
-rw-r--r--app/models/broadcast_message.rb14
-rw-r--r--app/models/chat_name.rb4
-rw-r--r--app/models/ci/artifact_blob.rb12
-rw-r--r--app/models/ci/bridge.rb2
-rw-r--r--app/models/ci/build.rb202
-rw-r--r--app/models/ci/build_metadata.rb12
-rw-r--r--app/models/ci/build_runner_session.rb12
-rw-r--r--app/models/ci/build_trace_chunk.rb24
-rw-r--r--app/models/ci/build_trace_section.rb4
-rw-r--r--app/models/ci/build_trace_section_name.rb4
-rw-r--r--app/models/ci/group.rb2
-rw-r--r--app/models/ci/group_variable.rb2
-rw-r--r--app/models/ci/job_artifact.rb48
-rw-r--r--app/models/ci/legacy_stage.rb2
-rw-r--r--app/models/ci/pipeline.rb148
-rw-r--r--app/models/ci/pipeline_chat_data.rb2
-rw-r--r--app/models/ci/pipeline_enums.rb6
-rw-r--r--app/models/ci/pipeline_schedule.rb19
-rw-r--r--app/models/ci/pipeline_schedule_variable.rb2
-rw-r--r--app/models/ci/pipeline_variable.rb4
-rw-r--r--app/models/ci/runner.rb62
-rw-r--r--app/models/ci/runner_namespace.rb6
-rw-r--r--app/models/ci/runner_project.rb2
-rw-r--r--app/models/ci/stage.rb28
-rw-r--r--app/models/ci/trigger.rb6
-rw-r--r--app/models/ci/trigger_request.rb2
-rw-r--r--app/models/ci/variable.rb2
-rw-r--r--app/models/clusters/applications/cert_manager.rb14
-rw-r--r--app/models/clusters/applications/helm.rb10
-rw-r--r--app/models/clusters/applications/ingress.rb13
-rw-r--r--app/models/clusters/applications/jupyter.rb30
-rw-r--r--app/models/clusters/applications/knative.rb25
-rw-r--r--app/models/clusters/applications/prometheus.rb12
-rw-r--r--app/models/clusters/applications/runner.rb16
-rw-r--r--app/models/clusters/cluster.rb70
-rw-r--r--app/models/clusters/concerns/application_core.rb6
-rw-r--r--app/models/clusters/concerns/application_data.rb4
-rw-r--r--app/models/clusters/concerns/application_status.rb4
-rw-r--r--app/models/clusters/group.rb6
-rw-r--r--app/models/clusters/kubernetes_namespace.rb27
-rw-r--r--app/models/clusters/platforms/kubernetes.rb55
-rw-r--r--app/models/clusters/project.rb10
-rw-r--r--app/models/clusters/providers/gcp.rb16
-rw-r--r--app/models/commit.rb47
-rw-r--r--app/models/commit_range.rb20
-rw-r--r--app/models/commit_status.rb14
-rw-r--r--app/models/commit_status_enums.rb2
-rw-r--r--app/models/compare.rb8
-rw-r--r--app/models/concerns/atomic_internal_id.rb2
-rw-r--r--app/models/concerns/avatarable.rb20
-rw-r--r--app/models/concerns/awardable.rb18
-rw-r--r--app/models/concerns/blob_language_from_git_attributes.rb2
-rw-r--r--app/models/concerns/blocks_json_serialization.rb2
-rw-r--r--app/models/concerns/bulk_member_access_load.rb6
-rw-r--r--app/models/concerns/cache_markdown_field.rb18
-rw-r--r--app/models/concerns/cacheable_attributes.rb2
-rw-r--r--app/models/concerns/case_sensitivity.rb8
-rw-r--r--app/models/concerns/chronic_duration_attribute.rb2
-rw-r--r--app/models/concerns/ci/metadatable.rb8
-rw-r--r--app/models/concerns/ci/processable.rb2
-rw-r--r--app/models/concerns/deployable.rb3
-rw-r--r--app/models/concerns/deployment_platform.rb6
-rw-r--r--app/models/concerns/diff_positionable_note.rb25
-rw-r--r--app/models/concerns/discussion_on_diff.rb27
-rw-r--r--app/models/concerns/each_batch.rb2
-rw-r--r--app/models/concerns/expirable.rb2
-rw-r--r--app/models/concerns/fast_destroy_all.rb2
-rw-r--r--app/models/concerns/ghost_user.rb2
-rw-r--r--app/models/concerns/group_descendant.rb18
-rw-r--r--app/models/concerns/has_status.rb68
-rw-r--r--app/models/concerns/has_variable.rb16
-rw-r--r--app/models/concerns/importable.rb4
-rw-r--r--app/models/concerns/issuable.rb100
-rw-r--r--app/models/concerns/loaded_in_group_list.rb16
-rw-r--r--app/models/concerns/maskable.rb4
-rw-r--r--app/models/concerns/mentionable.rb12
-rw-r--r--app/models/concerns/mentionable/reference_regexes.rb8
-rw-r--r--app/models/concerns/milestoneish.rb10
-rw-r--r--app/models/concerns/mirror_authentication.rb16
-rw-r--r--app/models/concerns/noteable.rb4
-rw-r--r--app/models/concerns/participable.rb4
-rw-r--r--app/models/concerns/project_features_compatibility.rb2
-rw-r--r--app/models/concerns/project_services_loggable.rb2
-rw-r--r--app/models/concerns/prometheus_adapter.rb4
-rw-r--r--app/models/concerns/protected_ref.rb12
-rw-r--r--app/models/concerns/protected_ref_access.rb16
-rw-r--r--app/models/concerns/reactive_caching.rb4
-rw-r--r--app/models/concerns/redactable.rb2
-rw-r--r--app/models/concerns/redis_cacheable.rb4
-rw-r--r--app/models/concerns/referable.rb4
-rw-r--r--app/models/concerns/relative_positioning.rb34
-rw-r--r--app/models/concerns/resolvable_discussion.rb17
-rw-r--r--app/models/concerns/resolvable_note.rb4
-rw-r--r--app/models/concerns/routable.rb16
-rw-r--r--app/models/concerns/sha_attribute.rb2
-rw-r--r--app/models/concerns/sortable.rb20
-rw-r--r--app/models/concerns/spammable.rb26
-rw-r--r--app/models/concerns/storage/legacy_namespace.rb12
-rw-r--r--app/models/concerns/storage/legacy_project_wiki.rb2
-rw-r--r--app/models/concerns/strip_attribute.rb2
-rw-r--r--app/models/concerns/subscribable.rb4
-rw-r--r--app/models/concerns/taskable.rb20
-rw-r--r--app/models/concerns/time_trackable.rb6
-rw-r--r--app/models/concerns/token_authenticatable_strategies/base.rb6
-rw-r--r--app/models/concerns/token_authenticatable_strategies/encrypted.rb6
-rw-r--r--app/models/concerns/triggerable_hooks.rb20
-rw-r--r--app/models/concerns/valid_attribute.rb2
-rw-r--r--app/models/concerns/with_uploads.rb4
-rw-r--r--app/models/container_repository.rb18
-rw-r--r--app/models/conversational_development_index/idea_to_production_step.rb4
-rw-r--r--app/models/conversational_development_index/metric.rb2
-rw-r--r--app/models/cycle_analytics.rb4
-rw-r--r--app/models/dashboard_group_milestone.rb7
-rw-r--r--app/models/deploy_key.rb8
-rw-r--r--app/models/deploy_keys_project.rb8
-rw-r--r--app/models/deploy_token.rb4
-rw-r--r--app/models/deployment.rb30
-rw-r--r--app/models/diff_discussion.rb13
-rw-r--r--app/models/diff_note.rb44
-rw-r--r--app/models/diff_viewer/added.rb2
-rw-r--r--app/models/diff_viewer/base.rb8
-rw-r--r--app/models/diff_viewer/deleted.rb2
-rw-r--r--app/models/diff_viewer/image.rb6
-rw-r--r--app/models/diff_viewer/mode_changed.rb2
-rw-r--r--app/models/diff_viewer/no_preview.rb2
-rw-r--r--app/models/diff_viewer/not_diffable.rb2
-rw-r--r--app/models/diff_viewer/renamed.rb2
-rw-r--r--app/models/diff_viewer/rich.rb4
-rw-r--r--app/models/diff_viewer/server_side.rb4
-rw-r--r--app/models/diff_viewer/simple.rb4
-rw-r--r--app/models/diff_viewer/text.rb2
-rw-r--r--app/models/discussion.rb26
-rw-r--r--app/models/discussion_note.rb4
-rw-r--r--app/models/email.rb4
-rw-r--r--app/models/environment.rb81
-rw-r--r--app/models/environment_status.rb6
-rw-r--r--app/models/epic.rb4
-rw-r--r--app/models/error_tracking/project_error_tracking_setting.rb24
-rw-r--r--app/models/event.rb68
-rw-r--r--app/models/event_collection.rb10
-rw-r--r--app/models/external_issue.rb2
-rw-r--r--app/models/fork_network.rb2
-rw-r--r--app/models/fork_network_member.rb2
-rw-r--r--app/models/generic_commit_status.rb6
-rw-r--r--app/models/global_milestone.rb31
-rw-r--r--app/models/gpg_key.rb22
-rw-r--r--app/models/gpg_signature.rb2
-rw-r--r--app/models/group.rb66
-rw-r--r--app/models/group_custom_attribute.rb2
-rw-r--r--app/models/group_label.rb2
-rw-r--r--app/models/group_milestone.rb5
-rw-r--r--app/models/hooks/project_hook.rb2
-rw-r--r--app/models/hooks/service_hook.rb2
-rw-r--r--app/models/hooks/system_hook.rb2
-rw-r--r--app/models/hooks/web_hook.rb18
-rw-r--r--app/models/hooks/web_hook_log.rb2
-rw-r--r--app/models/identity.rb6
-rw-r--r--app/models/instance_configuration.rb34
-rw-r--r--app/models/internal_id.rb6
-rw-r--r--app/models/issue.rb70
-rw-r--r--app/models/issue/metrics.rb6
-rw-r--r--app/models/issue_collection.rb2
-rw-r--r--app/models/key.rb16
-rw-r--r--app/models/label.rb64
-rw-r--r--app/models/label_note.rb16
-rw-r--r--app/models/label_priority.rb4
-rw-r--r--app/models/legacy_diff_discussion.rb2
-rw-r--r--app/models/legacy_diff_note.rb16
-rw-r--r--app/models/lfs_download_object.rb6
-rw-r--r--app/models/lfs_object.rb6
-rw-r--r--app/models/lfs_objects_project.rb2
-rw-r--r--app/models/license_template.rb2
-rw-r--r--app/models/list.rb6
-rw-r--r--app/models/member.rb66
-rw-r--r--app/models/members/group_member.rb10
-rw-r--r--app/models/members/project_member.rb22
-rw-r--r--app/models/merge_request.rb194
-rw-r--r--app/models/merge_request/metrics.rb6
-rw-r--r--app/models/merge_request_diff.rb40
-rw-r--r--app/models/merge_request_diff_commit.rb6
-rw-r--r--app/models/merge_request_diff_file.rb4
-rw-r--r--app/models/merge_requests_closing_issues.rb4
-rw-r--r--app/models/milestone.rb68
-rw-r--r--app/models/namespace.rb40
-rw-r--r--app/models/network/graph.rb20
-rw-r--r--app/models/note.rb56
-rw-r--r--app/models/note_diff_file.rb6
-rw-r--r--app/models/notification_reason.rb8
-rw-r--r--app/models/notification_recipient.rb2
-rw-r--r--app/models/notification_setting.rb22
-rw-r--r--app/models/oauth_access_grant.rb4
-rw-r--r--app/models/oauth_access_token.rb4
-rw-r--r--app/models/pages_domain.rb24
-rw-r--r--app/models/personal_access_token.rb2
-rw-r--r--app/models/pool_repository.rb6
-rw-r--r--app/models/postgresql/replication_slot.rb2
-rw-r--r--app/models/project.rb478
-rw-r--r--app/models/project_authorization.rb12
-rw-r--r--app/models/project_auto_devops.rb14
-rw-r--r--app/models/project_custom_attribute.rb2
-rw-r--r--app/models/project_daily_statistic.rb4
-rw-r--r--app/models/project_deploy_token.rb2
-rw-r--r--app/models/project_feature.rb12
-rw-r--r--app/models/project_group_link.rb12
-rw-r--r--app/models/project_import_data.rb16
-rw-r--r--app/models/project_import_state.rb4
-rw-r--r--app/models/project_label.rb6
-rw-r--r--app/models/project_services/asana_service.rb26
-rw-r--r--app/models/project_services/assembla_service.rb14
-rw-r--r--app/models/project_services/bamboo_service.rb60
-rw-r--r--app/models/project_services/bugzilla_service.rb14
-rw-r--r--app/models/project_services/buildkite_service.rb40
-rw-r--r--app/models/project_services/builds_email_service.rb2
-rw-r--r--app/models/project_services/campfire_service.rb28
-rw-r--r--app/models/project_services/chat_message/base_message.rb8
-rw-r--r--app/models/project_services/chat_message/issue_message.rb6
-rw-r--r--app/models/project_services/chat_message/merge_message.rb4
-rw-r--r--app/models/project_services/chat_message/note_message.rb10
-rw-r--r--app/models/project_services/chat_message/pipeline_message.rb20
-rw-r--r--app/models/project_services/chat_message/push_message.rb16
-rw-r--r--app/models/project_services/chat_message/wiki_page_message.rb4
-rw-r--r--app/models/project_services/chat_notification_service.rb40
-rw-r--r--app/models/project_services/ci_service.rb6
-rw-r--r--app/models/project_services/custom_issue_tracker_service.rb26
-rw-r--r--app/models/project_services/deployment_service.rb4
-rw-r--r--app/models/project_services/discord_service.rb6
-rw-r--r--app/models/project_services/drone_ci_service.rb40
-rw-r--r--app/models/project_services/emails_on_push_service.rb24
-rw-r--r--app/models/project_services/external_wiki_service.rb16
-rw-r--r--app/models/project_services/flowdock_service.rb10
-rw-r--r--app/models/project_services/gitlab_issue_tracker_service.rb2
-rw-r--r--app/models/project_services/hangouts_chat_service.rb16
-rw-r--r--app/models/project_services/irker_service.rb60
-rw-r--r--app/models/project_services/issue_tracker_service.rb35
-rw-r--r--app/models/project_services/jira_service.rb101
-rw-r--r--app/models/project_services/kubernetes_service.rb81
-rw-r--r--app/models/project_services/mattermost_service.rb8
-rw-r--r--app/models/project_services/mattermost_slash_commands_service.rb11
-rw-r--r--app/models/project_services/microsoft_teams_service.rb14
-rw-r--r--app/models/project_services/mock_ci_service.rb28
-rw-r--r--app/models/project_services/mock_deployment_service.rb6
-rw-r--r--app/models/project_services/mock_monitoring_service.rb8
-rw-r--r--app/models/project_services/monitoring_service.rb4
-rw-r--r--app/models/project_services/packagist_service.rb24
-rw-r--r--app/models/project_services/pipelines_email_service.rb30
-rw-r--r--app/models/project_services/pivotaltracker_service.rb46
-rw-r--r--app/models/project_services/prometheus_service.rb30
-rw-r--r--app/models/project_services/pushover_service.rb84
-rw-r--r--app/models/project_services/redmine_service.rb14
-rw-r--r--app/models/project_services/slack_service.rb8
-rw-r--r--app/models/project_services/slack_slash_commands_service.rb4
-rw-r--r--app/models/project_services/slash_commands_service.rb8
-rw-r--r--app/models/project_services/teamcity_service.rb58
-rw-r--r--app/models/project_services/youtrack_service.rb16
-rw-r--r--app/models/project_statistics.rb4
-rw-r--r--app/models/project_team.rb16
-rw-r--r--app/models/project_wiki.rb36
-rw-r--r--app/models/prometheus_metric.rb68
-rw-r--r--app/models/protectable_dropdown.rb2
-rw-r--r--app/models/protected_branch.rb2
-rw-r--r--app/models/protected_tag.rb4
-rw-r--r--app/models/push_event.rb18
-rw-r--r--app/models/push_event_payload.rb6
-rw-r--r--app/models/redirect_route.rb14
-rw-r--r--app/models/ref_matcher.rb6
-rw-r--r--app/models/release.rb4
-rw-r--r--app/models/releases/link.rb6
-rw-r--r--app/models/releases/source.rb8
-rw-r--r--app/models/remote_mirror.rb40
-rw-r--r--app/models/repository.rb137
-rw-r--r--app/models/repository_language.rb4
-rw-r--r--app/models/resource_label_event.rb20
-rw-r--r--app/models/route.rb10
-rw-r--r--app/models/sent_notification.rb34
-rw-r--r--app/models/service.rb20
-rw-r--r--app/models/snippet.rb28
-rw-r--r--app/models/snippet_blob.rb2
-rw-r--r--app/models/spam_log.rb2
-rw-r--r--app/models/ssh_host_key.rb22
-rw-r--r--app/models/storage/hashed_project.rb4
-rw-r--r--app/models/subscription.rb2
-rw-r--r--app/models/suggestion.rb6
-rw-r--r--app/models/system_note_metadata.rb2
-rw-r--r--app/models/term_agreement.rb2
-rw-r--r--app/models/timelog.rb4
-rw-r--r--app/models/todo.rb34
-rw-r--r--app/models/tree.rb18
-rw-r--r--app/models/u2f_registration.rb4
-rw-r--r--app/models/upload.rb10
-rw-r--r--app/models/uploads/local.rb2
-rw-r--r--app/models/user.rb220
-rw-r--r--app/models/user_callout.rb4
-rw-r--r--app/models/user_callout_enums.rb2
-rw-r--r--app/models/user_custom_attribute.rb2
-rw-r--r--app/models/user_interacted_project.rb20
-rw-r--r--app/models/user_preference.rb12
-rw-r--r--app/models/user_status.rb6
-rw-r--r--app/models/users_star_project.rb2
-rw-r--r--app/models/wiki_directory.rb2
-rw-r--r--app/models/wiki_page.rb20
345 files changed, 3126 insertions, 3123 deletions
diff --git a/app/models/ability.rb b/app/models/ability.rb
index 1466407d0d1..2d861c909ef 100644
--- a/app/models/ability.rb
+++ b/app/models/ability.rb
@@ -1,6 +1,6 @@
# frozen_string_literal: true
-require_dependency 'declarative_policy'
+require_dependency "declarative_policy"
class Ability
class << self
diff --git a/app/models/abuse_report.rb b/app/models/abuse_report.rb
index 1b78fd04ebb..d40e0edf194 100644
--- a/app/models/abuse_report.rb
+++ b/app/models/abuse_report.rb
@@ -5,24 +5,24 @@ class AbuseReport < ActiveRecord::Base
cache_markdown_field :message, pipeline: :single_line
- belongs_to :reporter, class_name: 'User'
+ belongs_to :reporter, class_name: "User"
belongs_to :user
validates :reporter, presence: true
validates :user, presence: true
validates :message, presence: true
- validates :user_id, uniqueness: { message: 'has already been reported' }
+ validates :user_id, uniqueness: {message: "has already been reported"}
# For CacheMarkdownField
- alias_method :author, :reporter
+ alias author reporter
def remove_user(deleted_by:)
- user.delete_async(deleted_by: deleted_by, params: { hard_delete: true })
+ user.delete_async(deleted_by: deleted_by, params: {hard_delete: true})
end
def notify
- return unless self.persisted?
+ return unless persisted?
- AbuseReportMailer.notify(self.id).deliver_later
+ AbuseReportMailer.notify(id).deliver_later
end
end
diff --git a/app/models/active_session.rb b/app/models/active_session.rb
index 0d9c6a4a1f0..b2d7735d877 100644
--- a/app/models/active_session.rb
+++ b/app/models/active_session.rb
@@ -37,7 +37,7 @@ class ActiveSession
redis.pipelined do
redis.setex(
key_name(user.id, session_id),
- Settings.gitlab['session_expire_delay'] * 60,
+ Settings.gitlab["session_expire_delay"] * 60,
Marshal.dump(active_user_session)
)
@@ -80,7 +80,7 @@ class ActiveSession
end
end
- def self.key_name(user_id, session_id = '*')
+ def self.key_name(user_id, session_id = "*")
"#{Gitlab::Redis::SharedState::USER_SESSIONS_NAMESPACE}:#{user_id}:#{session_id}"
end
diff --git a/app/models/appearance.rb b/app/models/appearance.rb
index bdee9b2b73c..1ddb021dadb 100644
--- a/app/models/appearance.rb
+++ b/app/models/appearance.rb
@@ -11,15 +11,15 @@ class Appearance < ActiveRecord::Base
cache_markdown_field :header_message, pipeline: :broadcast_message
cache_markdown_field :footer_message, pipeline: :broadcast_message
- validates :logo, file_size: { maximum: 1.megabyte }
- validates :header_logo, file_size: { maximum: 1.megabyte }
+ validates :logo, file_size: {maximum: 1.megabyte}
+ validates :header_logo, file_size: {maximum: 1.megabyte}
validates :message_background_color, allow_blank: true, color: true
validates :message_font_color, allow_blank: true, color: true
validate :single_appearance_row, on: :create
- default_value_for :message_background_color, '#E75E40'
- default_value_for :message_font_color, '#FFFFFF'
+ default_value_for :message_background_color, "#E75E40"
+ default_value_for :message_font_color, "#FFFFFF"
default_value_for :email_header_and_footer_enabled, false
mount_uploader :logo, AttachmentUploader
@@ -33,20 +33,20 @@ class Appearance < ActiveRecord::Base
def single_appearance_row
if self.class.any?
- errors.add(:single_appearance_row, 'Only 1 appearances row can exist')
+ errors.add(:single_appearance_row, "Only 1 appearances row can exist")
end
end
def logo_path
- logo_system_path(logo, 'logo')
+ logo_system_path(logo, "logo")
end
def header_logo_path
- logo_system_path(header_logo, 'header_logo')
+ logo_system_path(header_logo, "header_logo")
end
def favicon_path
- logo_system_path(favicon, 'favicon')
+ logo_system_path(favicon, "favicon")
end
def show_header?
@@ -71,8 +71,9 @@ class Appearance < ActiveRecord::Base
local_path = Gitlab::Routing.url_helpers.appearance_upload_path(
filename: logo.filename,
id: logo.upload.model_id,
- model: 'appearance',
- mounted_as: mount_type)
+ model: "appearance",
+ mounted_as: mount_type
+ )
Gitlab::Utils.append_path(asset_host, local_path)
end
diff --git a/app/models/application_setting.rb b/app/models/application_setting.rb
index daadf9427ba..1faa3d83f8f 100644
--- a/app/models/application_setting.rb
+++ b/app/models/application_setting.rb
@@ -51,154 +51,154 @@ class ApplicationSetting < ActiveRecord::Base
validates :uuid, presence: true
validates :session_expire_delay,
- presence: true,
- numericality: { only_integer: true, greater_than_or_equal_to: 0 }
+ presence: true,
+ numericality: {only_integer: true, greater_than_or_equal_to: 0}
validates :home_page_url,
- allow_blank: true,
- url: true,
- if: :home_page_url_column_exists?
+ allow_blank: true,
+ url: true,
+ if: :home_page_url_column_exists?
validates :help_page_support_url,
- allow_blank: true,
- url: true,
- if: :help_page_support_url_column_exists?
+ allow_blank: true,
+ url: true,
+ if: :help_page_support_url_column_exists?
validates :after_sign_out_path,
- allow_blank: true,
- url: true
+ allow_blank: true,
+ url: true
validates :admin_notification_email,
- email: true,
- allow_blank: true
+ email: true,
+ allow_blank: true
validates :two_factor_grace_period,
- numericality: { greater_than_or_equal_to: 0 }
+ numericality: {greater_than_or_equal_to: 0}
validates :recaptcha_site_key,
- presence: true,
- if: :recaptcha_enabled
+ presence: true,
+ if: :recaptcha_enabled
validates :recaptcha_private_key,
- presence: true,
- if: :recaptcha_enabled
+ presence: true,
+ if: :recaptcha_enabled
validates :sentry_dsn,
- presence: true,
- if: :sentry_enabled
+ presence: true,
+ if: :sentry_enabled
validates :clientside_sentry_dsn,
- presence: true,
- if: :clientside_sentry_enabled
+ presence: true,
+ if: :clientside_sentry_enabled
validates :akismet_api_key,
- presence: true,
- if: :akismet_enabled
+ presence: true,
+ if: :akismet_enabled
validates :unique_ips_limit_per_user,
- numericality: { greater_than_or_equal_to: 1 },
- presence: true,
- if: :unique_ips_limit_enabled
+ numericality: {greater_than_or_equal_to: 1},
+ presence: true,
+ if: :unique_ips_limit_enabled
validates :unique_ips_limit_time_window,
- numericality: { greater_than_or_equal_to: 0 },
- presence: true,
- if: :unique_ips_limit_enabled
+ numericality: {greater_than_or_equal_to: 0},
+ presence: true,
+ if: :unique_ips_limit_enabled
validates :plantuml_url,
- presence: true,
- if: :plantuml_enabled
+ presence: true,
+ if: :plantuml_enabled
validates :max_attachment_size,
- presence: true,
- numericality: { only_integer: true, greater_than: 0 }
+ presence: true,
+ numericality: {only_integer: true, greater_than: 0}
validates :max_artifacts_size,
- presence: true,
- numericality: { only_integer: true, greater_than: 0 }
+ presence: true,
+ numericality: {only_integer: true, greater_than: 0}
validates :default_artifacts_expire_in, presence: true, duration: true
validates :container_registry_token_expire_delay,
- presence: true,
- numericality: { only_integer: true, greater_than: 0 }
+ presence: true,
+ numericality: {only_integer: true, greater_than: 0}
validates :repository_storages, presence: true
validate :check_repository_storages
validates :auto_devops_domain,
- allow_blank: true,
- hostname: { allow_numeric_hostname: true, require_valid_tld: true },
- if: :auto_devops_enabled?
+ allow_blank: true,
+ hostname: {allow_numeric_hostname: true, require_valid_tld: true},
+ if: :auto_devops_enabled?
validates :enabled_git_access_protocol,
- inclusion: { in: %w(ssh http), allow_blank: true, allow_nil: true }
+ inclusion: {in: %w[ssh http], allow_blank: true, allow_nil: true}
validates :domain_blacklist,
- presence: { message: 'Domain blacklist cannot be empty if Blacklist is enabled.' },
- if: :domain_blacklist_enabled?
+ presence: {message: "Domain blacklist cannot be empty if Blacklist is enabled."},
+ if: :domain_blacklist_enabled?
validates :housekeeping_incremental_repack_period,
- presence: true,
- numericality: { only_integer: true, greater_than: 0 }
+ presence: true,
+ numericality: {only_integer: true, greater_than: 0}
validates :housekeeping_full_repack_period,
- presence: true,
- numericality: { only_integer: true, greater_than_or_equal_to: :housekeeping_incremental_repack_period }
+ presence: true,
+ numericality: {only_integer: true, greater_than_or_equal_to: :housekeeping_incremental_repack_period}
validates :housekeeping_gc_period,
- presence: true,
- numericality: { only_integer: true, greater_than_or_equal_to: :housekeeping_full_repack_period }
+ presence: true,
+ numericality: {only_integer: true, greater_than_or_equal_to: :housekeeping_full_repack_period}
validates :terminal_max_session_time,
- presence: true,
- numericality: { only_integer: true, greater_than_or_equal_to: 0 }
+ presence: true,
+ numericality: {only_integer: true, greater_than_or_equal_to: 0}
validates :polling_interval_multiplier,
- presence: true,
- numericality: { greater_than_or_equal_to: 0 }
+ presence: true,
+ numericality: {greater_than_or_equal_to: 0}
validates :gitaly_timeout_default,
- presence: true,
- numericality: { only_integer: true, greater_than_or_equal_to: 0 }
+ presence: true,
+ numericality: {only_integer: true, greater_than_or_equal_to: 0}
validates :gitaly_timeout_medium,
- presence: true,
- numericality: { only_integer: true, greater_than_or_equal_to: 0 }
+ presence: true,
+ numericality: {only_integer: true, greater_than_or_equal_to: 0}
validates :gitaly_timeout_medium,
- numericality: { less_than_or_equal_to: :gitaly_timeout_default },
- if: :gitaly_timeout_default
+ numericality: {less_than_or_equal_to: :gitaly_timeout_default},
+ if: :gitaly_timeout_default
validates :gitaly_timeout_medium,
- numericality: { greater_than_or_equal_to: :gitaly_timeout_fast },
- if: :gitaly_timeout_fast
+ numericality: {greater_than_or_equal_to: :gitaly_timeout_fast},
+ if: :gitaly_timeout_fast
validates :gitaly_timeout_fast,
- presence: true,
- numericality: { only_integer: true, greater_than_or_equal_to: 0 }
+ presence: true,
+ numericality: {only_integer: true, greater_than_or_equal_to: 0}
validates :gitaly_timeout_fast,
- numericality: { less_than_or_equal_to: :gitaly_timeout_default },
- if: :gitaly_timeout_default
+ numericality: {less_than_or_equal_to: :gitaly_timeout_default},
+ if: :gitaly_timeout_default
validates :diff_max_patch_bytes,
- presence: true,
- numericality: { only_integer: true,
- greater_than_or_equal_to: Gitlab::Git::Diff::DEFAULT_MAX_PATCH_BYTES,
- less_than_or_equal_to: Gitlab::Git::Diff::MAX_PATCH_BYTES_UPPER_BOUND }
+ presence: true,
+ numericality: {only_integer: true,
+ greater_than_or_equal_to: Gitlab::Git::Diff::DEFAULT_MAX_PATCH_BYTES,
+ less_than_or_equal_to: Gitlab::Git::Diff::MAX_PATCH_BYTES_UPPER_BOUND,}
validates :user_default_internal_regex, js_regex: true, allow_nil: true
- validates :commit_email_hostname, format: { with: /\A[^@]+\z/ }
+ validates :commit_email_hostname, format: {with: /\A[^@]+\z/}
validates :archive_builds_in_seconds,
- allow_nil: true,
- numericality: { only_integer: true, greater_than_or_equal_to: 1.day.seconds }
+ allow_nil: true,
+ numericality: {only_integer: true, greater_than_or_equal_to: 1.day.seconds}
validates :local_markdown_version,
- allow_nil: true,
- numericality: { only_integer: true, greater_than_or_equal_to: 0, less_than: 65536 }
+ allow_nil: true,
+ numericality: {only_integer: true, greater_than_or_equal_to: 0, less_than: 65536}
SUPPORTED_KEY_TYPES.each do |type|
- validates :"#{type}_key_restriction", presence: true, key_restriction: { type: type }
+ validates :"#{type}_key_restriction", presence: true, key_restriction: {type: type}
end
validates :allowed_key_types, presence: true
@@ -230,7 +230,7 @@ class ApplicationSetting < ActiveRecord::Base
after_commit do
reset_memoized_terms
end
- after_commit :expire_performance_bar_allowed_user_ids_cache, if: -> { previous_changes.key?('performance_bar_allowed_group_id') }
+ after_commit :expire_performance_bar_allowed_user_ids_cache, if: -> { previous_changes.key?("performance_bar_allowed_group_id") }
def self.defaults
{
@@ -239,14 +239,14 @@ class ApplicationSetting < ActiveRecord::Base
allow_local_requests_from_hooks_and_services: false,
authorized_keys_enabled: true, # TODO default to false if the instance is configured to use AuthorizedKeysCommand
container_registry_token_expire_delay: 5,
- default_artifacts_expire_in: '30 days',
- default_branch_protection: Settings.gitlab['default_branch_protection'],
- default_group_visibility: Settings.gitlab.default_projects_features['visibility_level'],
- default_project_visibility: Settings.gitlab.default_projects_features['visibility_level'],
- default_projects_limit: Settings.gitlab['default_projects_limit'],
- default_snippet_visibility: Settings.gitlab.default_projects_features['visibility_level'],
+ default_artifacts_expire_in: "30 days",
+ default_branch_protection: Settings.gitlab["default_branch_protection"],
+ default_group_visibility: Settings.gitlab.default_projects_features["visibility_level"],
+ default_project_visibility: Settings.gitlab.default_projects_features["visibility_level"],
+ default_projects_limit: Settings.gitlab["default_projects_limit"],
+ default_snippet_visibility: Settings.gitlab.default_projects_features["visibility_level"],
disabled_oauth_sign_in_sources: [],
- domain_whitelist: Settings.gitlab['domain_whitelist'],
+ domain_whitelist: Settings.gitlab["domain_whitelist"],
dsa_key_restriction: 0,
ecdsa_key_restriction: 0,
ed25519_key_restriction: 0,
@@ -254,7 +254,7 @@ class ApplicationSetting < ActiveRecord::Base
gitaly_timeout_default: 55,
gitaly_timeout_fast: 10,
gitaly_timeout_medium: 30,
- gravatar_enabled: Settings.gravatar['enabled'],
+ gravatar_enabled: Settings.gravatar["enabled"],
help_page_hide_commercial_content: false,
help_page_text: nil,
hide_third_party_offers: false,
@@ -263,12 +263,12 @@ class ApplicationSetting < ActiveRecord::Base
housekeeping_full_repack_period: 50,
housekeeping_gc_period: 200,
housekeeping_incremental_repack_period: 10,
- import_sources: Settings.gitlab['import_sources'],
- max_artifacts_size: Settings.artifacts['max_size'],
- max_attachment_size: Settings.gitlab['max_attachment_size'],
+ import_sources: Settings.gitlab["import_sources"],
+ max_artifacts_size: Settings.artifacts["max_size"],
+ max_attachment_size: Settings.gitlab["max_attachment_size"],
mirror_available: true,
password_authentication_enabled_for_git: true,
- password_authentication_enabled_for_web: Settings.gitlab['signin_enabled'],
+ password_authentication_enabled_for_web: Settings.gitlab["signin_enabled"],
performance_bar_allowed_group_id: nil,
rsa_key_restriction: 0,
plantuml_enabled: false,
@@ -277,15 +277,15 @@ class ApplicationSetting < ActiveRecord::Base
project_export_enabled: true,
recaptcha_enabled: false,
repository_checks_enabled: true,
- repository_storages: ['default'],
+ repository_storages: ["default"],
require_two_factor_authentication: false,
- restricted_visibility_levels: Settings.gitlab['restricted_visibility_levels'],
- session_expire_delay: Settings.gitlab['session_expire_delay'],
+ restricted_visibility_levels: Settings.gitlab["restricted_visibility_levels"],
+ session_expire_delay: Settings.gitlab["session_expire_delay"],
send_user_confirmation_email: false,
- shared_runners_enabled: Settings.gitlab_ci['shared_runners_enabled'],
+ shared_runners_enabled: Settings.gitlab_ci["shared_runners_enabled"],
shared_runners_text: nil,
sign_in_text: nil,
- signup_enabled: Settings.gitlab['signup_enabled'],
+ signup_enabled: Settings.gitlab["signup_enabled"],
terminal_max_session_time: 0,
throttle_authenticated_api_enabled: false,
throttle_authenticated_api_period_in_seconds: 3600,
@@ -300,7 +300,7 @@ class ApplicationSetting < ActiveRecord::Base
unique_ips_limit_enabled: false,
unique_ips_limit_per_user: 10,
unique_ips_limit_time_window: 3600,
- usage_ping_enabled: Settings.gitlab['usage_ping_enabled'],
+ usage_ping_enabled: Settings.gitlab["usage_ping_enabled"],
instance_statistics_visibility_private: false,
user_default_external: false,
user_default_internal_regex: nil,
@@ -309,7 +309,7 @@ class ApplicationSetting < ActiveRecord::Base
diff_max_patch_bytes: Gitlab::Git::Diff::DEFAULT_MAX_PATCH_BYTES,
commit_email_hostname: default_commit_email_hostname,
protected_ci_variables: false,
- local_markdown_version: 0
+ local_markdown_version: 0,
}
end
@@ -323,7 +323,7 @@ class ApplicationSetting < ActiveRecord::Base
def self.human_attribute_name(attr, _options = {})
if attr == :default_artifacts_expire_in
- 'Default artifacts expiration'
+ "Default artifacts expiration"
else
super
end
@@ -343,25 +343,25 @@ class ApplicationSetting < ActiveRecord::Base
end
def domain_whitelist_raw
- self.domain_whitelist&.join("\n")
+ domain_whitelist&.join("\n")
end
def domain_blacklist_raw
- self.domain_blacklist&.join("\n")
+ domain_blacklist&.join("\n")
end
def domain_whitelist_raw=(values)
self.domain_whitelist = []
self.domain_whitelist = values.split(DOMAIN_LIST_SEPARATOR)
- self.domain_whitelist.reject! { |d| d.empty? }
- self.domain_whitelist
+ domain_whitelist.reject! { |d| d.empty? }
+ domain_whitelist
end
def domain_blacklist_raw=(values)
self.domain_blacklist = []
self.domain_blacklist = values.split(DOMAIN_LIST_SEPARATOR)
- self.domain_blacklist.reject! { |d| d.empty? }
- self.domain_blacklist
+ domain_blacklist.reject! { |d| d.empty? }
+ domain_blacklist
end
def domain_blacklist_file=(file)
@@ -467,7 +467,7 @@ class ApplicationSetting < ActiveRecord::Base
end
def archive_builds_older_than
- archive_builds_in_seconds.seconds.ago if archive_builds_in_seconds
+ archive_builds_in_seconds&.seconds&.ago
end
private
diff --git a/app/models/audit_event.rb b/app/models/audit_event.rb
index 8508c88d406..2704acc76b4 100644
--- a/app/models/audit_event.rb
+++ b/app/models/audit_event.rb
@@ -16,6 +16,6 @@ class AuditEvent < ActiveRecord::Base
end
def author_name
- self.user.name
+ user.name
end
end
diff --git a/app/models/award_emoji.rb b/app/models/award_emoji.rb
index ddc516ccb60..008929d0478 100644
--- a/app/models/award_emoji.rb
+++ b/app/models/award_emoji.rb
@@ -1,8 +1,8 @@
# frozen_string_literal: true
class AwardEmoji < ActiveRecord::Base
- DOWNVOTE_NAME = "thumbsdown".freeze
- UPVOTE_NAME = "thumbsup".freeze
+ DOWNVOTE_NAME = "thumbsdown"
+ UPVOTE_NAME = "thumbsup"
include Participable
include GhostUser
@@ -11,8 +11,8 @@ class AwardEmoji < ActiveRecord::Base
belongs_to :user
validates :awardable, :user, presence: true
- validates :name, presence: true, inclusion: { in: Gitlab::Emoji.emojis_names }
- validates :name, uniqueness: { scope: [:user, :awardable_type, :awardable_id] }, unless: :ghost_user?
+ validates :name, presence: true, inclusion: {in: Gitlab::Emoji.emojis_names}
+ validates :name, uniqueness: {scope: [:user, :awardable_type, :awardable_id]}, unless: :ghost_user?
participant :user
@@ -24,9 +24,9 @@ class AwardEmoji < ActiveRecord::Base
class << self
def votes_for_collection(ids, type)
- select('name', 'awardable_id', 'COUNT(*) as count')
- .where('name IN (?) AND awardable_type = ? AND awardable_id IN (?)', [DOWNVOTE_NAME, UPVOTE_NAME], type, ids)
- .group('name', 'awardable_id')
+ select("name", "awardable_id", "COUNT(*) as count")
+ .where("name IN (?) AND awardable_type = ? AND awardable_id IN (?)", [DOWNVOTE_NAME, UPVOTE_NAME], type, ids)
+ .group("name", "awardable_id")
end
# Returns the top 100 emoji awarded by the given user.
@@ -42,17 +42,17 @@ class AwardEmoji < ActiveRecord::Base
limit(limit)
.where(user: user)
.group(:name)
- .order('count_all DESC, name ASC')
+ .order("count_all DESC, name ASC")
.count
end
end
def downvote?
- self.name == DOWNVOTE_NAME
+ name == DOWNVOTE_NAME
end
def upvote?
- self.name == UPVOTE_NAME
+ name == UPVOTE_NAME
end
def expire_etag_cache
diff --git a/app/models/badge.rb b/app/models/badge.rb
index f016654206b..469915bc460 100644
--- a/app/models/badge.rb
+++ b/app/models/badge.rb
@@ -7,10 +7,10 @@ class Badge < ActiveRecord::Base
# can have. This hash also sets which action to ask when
# the placeholder is found.
PLACEHOLDERS = {
- 'project_path' => :full_path,
- 'project_id' => :id,
- 'default_branch' => :default_branch,
- 'commit_sha' => ->(project) { project.commit&.sha }
+ "project_path" => :full_path,
+ "project_id" => :id,
+ "default_branch" => :default_branch,
+ "commit_sha" => ->(project) { project.commit&.sha },
}.freeze
# This regex is built dynamically using the keys from the PLACEHOLDER struct.
@@ -22,7 +22,7 @@ class Badge < ActiveRecord::Base
scope :order_created_at_asc, -> { reorder(created_at: :asc) }
- validates :link_url, :image_url, url: { protocols: %w(http https) }
+ validates :link_url, :image_url, url: {protocols: %w[http https]}
validates :type, presence: true
def rendered_link_url(project = nil)
diff --git a/app/models/blob.rb b/app/models/blob.rb
index c5766eb0327..eac766827b3 100644
--- a/app/models/blob.rb
+++ b/app/models/blob.rb
@@ -36,7 +36,7 @@ class Blob < SimpleDelegator
BlobViewer::PDF,
BlobViewer::BinarySTL,
- BlobViewer::TextSTL
+ BlobViewer::TextSTL,
].sort_by { |v| v.binary? ? 0 : 1 }.freeze
AUXILIARY_VIEWERS = [
@@ -58,7 +58,7 @@ class Blob < SimpleDelegator
BlobViewer::Podspec,
BlobViewer::PodspecJson,
BlobViewer::RequirementsTxt,
- BlobViewer::YarnLock
+ BlobViewer::YarnLock,
].freeze
attr_reader :project
@@ -166,7 +166,7 @@ class Blob < SimpleDelegator
end
def extension
- @extension ||= extname.downcase.delete('.')
+ @extension ||= extname.downcase.delete(".")
end
def file_type
diff --git a/app/models/blob_viewer/auxiliary.rb b/app/models/blob_viewer/auxiliary.rb
index 263d51b4e36..aa432d51026 100644
--- a/app/models/blob_viewer/auxiliary.rb
+++ b/app/models/blob_viewer/auxiliary.rb
@@ -7,7 +7,7 @@ module BlobViewer
include Gitlab::Allowable
included do
- self.loading_partial_name = 'loading_auxiliary'
+ self.loading_partial_name = "loading_auxiliary"
self.type = :auxiliary
self.collapse_limit = 100.kilobytes
self.size_limit = 100.kilobytes
diff --git a/app/models/blob_viewer/balsamiq.rb b/app/models/blob_viewer/balsamiq.rb
index 1af6c5474d7..b98b3e39026 100644
--- a/app/models/blob_viewer/balsamiq.rb
+++ b/app/models/blob_viewer/balsamiq.rb
@@ -5,10 +5,10 @@ module BlobViewer
include Rich
include ClientSide
- self.partial_name = 'balsamiq'
- self.extensions = %w(bmpr)
+ self.partial_name = "balsamiq"
+ self.extensions = %w[bmpr]
self.binary = true
- self.switcher_icon = 'file-image-o'
- self.switcher_title = 'preview'
+ self.switcher_icon = "file-image-o"
+ self.switcher_title = "preview"
end
end
diff --git a/app/models/blob_viewer/base.rb b/app/models/blob_viewer/base.rb
index df6b9bb2f0b..d1e45d3d160 100644
--- a/app/models/blob_viewer/base.rb
+++ b/app/models/blob_viewer/base.rb
@@ -2,11 +2,11 @@
module BlobViewer
class Base
- PARTIAL_PATH_PREFIX = 'projects/blob/viewers'.freeze
+ PARTIAL_PATH_PREFIX = "projects/blob/viewers"
class_attribute :partial_name, :loading_partial_name, :type, :extensions, :file_types, :load_async, :binary, :switcher_icon, :switcher_title, :collapse_limit, :size_limit
- self.loading_partial_name = 'loading'
+ self.loading_partial_name = "loading"
delegate :partial_path, :loading_partial_path, :rich?, :simple?, :load_async?, :text?, :binary?, to: :class
diff --git a/app/models/blob_viewer/binary_stl.rb b/app/models/blob_viewer/binary_stl.rb
index 425f72decae..5d4098d7733 100644
--- a/app/models/blob_viewer/binary_stl.rb
+++ b/app/models/blob_viewer/binary_stl.rb
@@ -5,8 +5,8 @@ module BlobViewer
include Rich
include ClientSide
- self.partial_name = 'stl'
- self.extensions = %w(stl)
+ self.partial_name = "stl"
+ self.extensions = %w[stl]
self.binary = true
end
end
diff --git a/app/models/blob_viewer/cartfile.rb b/app/models/blob_viewer/cartfile.rb
index ea0494033bf..0932075db30 100644
--- a/app/models/blob_viewer/cartfile.rb
+++ b/app/models/blob_viewer/cartfile.rb
@@ -4,14 +4,14 @@ module BlobViewer
class Cartfile < DependencyManager
include Static
- self.file_types = %i(cartfile)
+ self.file_types = %i[cartfile]
def manager_name
- 'Carthage'
+ "Carthage"
end
def manager_url
- 'https://github.com/Carthage/Carthage'
+ "https://github.com/Carthage/Carthage"
end
end
end
diff --git a/app/models/blob_viewer/changelog.rb b/app/models/blob_viewer/changelog.rb
index 8810bd25809..f552fa588ba 100644
--- a/app/models/blob_viewer/changelog.rb
+++ b/app/models/blob_viewer/changelog.rb
@@ -5,8 +5,8 @@ module BlobViewer
include Auxiliary
include Static
- self.partial_name = 'changelog'
- self.file_types = %i(changelog)
+ self.partial_name = "changelog"
+ self.file_types = %i[changelog]
self.binary = false
def render_error
diff --git a/app/models/blob_viewer/composer_json.rb b/app/models/blob_viewer/composer_json.rb
index 9d1376de0cb..b39e2e4b530 100644
--- a/app/models/blob_viewer/composer_json.rb
+++ b/app/models/blob_viewer/composer_json.rb
@@ -4,18 +4,18 @@ module BlobViewer
class ComposerJson < DependencyManager
include ServerSide
- self.file_types = %i(composer_json)
+ self.file_types = %i[composer_json]
def manager_name
- 'Composer'
+ "Composer"
end
def manager_url
- 'https://getcomposer.org/'
+ "https://getcomposer.org/"
end
def package_name
- @package_name ||= package_name_from_json('name')
+ @package_name ||= package_name_from_json("name")
end
def package_url
diff --git a/app/models/blob_viewer/contributing.rb b/app/models/blob_viewer/contributing.rb
index fa224309e31..8918026abd0 100644
--- a/app/models/blob_viewer/contributing.rb
+++ b/app/models/blob_viewer/contributing.rb
@@ -5,8 +5,8 @@ module BlobViewer
include Auxiliary
include Static
- self.partial_name = 'contributing'
- self.file_types = %i(contributing)
+ self.partial_name = "contributing"
+ self.file_types = %i[contributing]
self.binary = false
end
end
diff --git a/app/models/blob_viewer/dependency_manager.rb b/app/models/blob_viewer/dependency_manager.rb
index 711465c7c79..240416c1e6a 100644
--- a/app/models/blob_viewer/dependency_manager.rb
+++ b/app/models/blob_viewer/dependency_manager.rb
@@ -4,7 +4,7 @@ module BlobViewer
class DependencyManager < Base
include Auxiliary
- self.partial_name = 'dependency_manager'
+ self.partial_name = "dependency_manager"
self.binary = false
def manager_name
@@ -16,7 +16,7 @@ module BlobViewer
end
def package_type
- 'package'
+ "package"
end
def package_name
@@ -33,8 +33,8 @@ module BlobViewer
@json_data ||= begin
prepare!
JSON.parse(blob.data)
- rescue
- {}
+ rescue
+ {}
end
end
diff --git a/app/models/blob_viewer/download.rb b/app/models/blob_viewer/download.rb
index 8228a83c2b1..537c6728bc1 100644
--- a/app/models/blob_viewer/download.rb
+++ b/app/models/blob_viewer/download.rb
@@ -5,7 +5,7 @@ module BlobViewer
include Simple
include Static
- self.partial_name = 'download'
+ self.partial_name = "download"
self.binary = true
end
end
diff --git a/app/models/blob_viewer/empty.rb b/app/models/blob_viewer/empty.rb
index 766be349d83..045933c8f1f 100644
--- a/app/models/blob_viewer/empty.rb
+++ b/app/models/blob_viewer/empty.rb
@@ -5,6 +5,6 @@ module BlobViewer
include Simple
include ServerSide
- self.partial_name = 'empty'
+ self.partial_name = "empty"
end
end
diff --git a/app/models/blob_viewer/gemfile.rb b/app/models/blob_viewer/gemfile.rb
index 77220cdbd08..6fa39517837 100644
--- a/app/models/blob_viewer/gemfile.rb
+++ b/app/models/blob_viewer/gemfile.rb
@@ -4,14 +4,14 @@ module BlobViewer
class Gemfile < DependencyManager
include Static
- self.file_types = %i(gemfile gemfile_lock)
+ self.file_types = %i[gemfile gemfile_lock]
def manager_name
- 'Bundler'
+ "Bundler"
end
def manager_url
- 'http://bundler.io/'
+ "http://bundler.io/"
end
end
end
diff --git a/app/models/blob_viewer/gemspec.rb b/app/models/blob_viewer/gemspec.rb
index 274859a7710..2f7e17345d6 100644
--- a/app/models/blob_viewer/gemspec.rb
+++ b/app/models/blob_viewer/gemspec.rb
@@ -4,22 +4,22 @@ module BlobViewer
class Gemspec < DependencyManager
include ServerSide
- self.file_types = %i(gemspec)
+ self.file_types = %i[gemspec]
def manager_name
- 'RubyGems'
+ "RubyGems"
end
def manager_url
- 'https://rubygems.org/'
+ "https://rubygems.org/"
end
def package_type
- 'gem'
+ "gem"
end
def package_name
- @package_name ||= package_name_from_method_call('name')
+ @package_name ||= package_name_from_method_call("name")
end
def package_url
diff --git a/app/models/blob_viewer/gitlab_ci_yml.rb b/app/models/blob_viewer/gitlab_ci_yml.rb
index 11228e620c9..f20484061bd 100644
--- a/app/models/blob_viewer/gitlab_ci_yml.rb
+++ b/app/models/blob_viewer/gitlab_ci_yml.rb
@@ -5,9 +5,9 @@ module BlobViewer
include ServerSide
include Auxiliary
- self.partial_name = 'gitlab_ci_yml'
- self.loading_partial_name = 'gitlab_ci_yml_loading'
- self.file_types = %i(gitlab_ci)
+ self.partial_name = "gitlab_ci_yml"
+ self.loading_partial_name = "gitlab_ci_yml_loading"
+ self.file_types = %i[gitlab_ci]
self.binary = false
def validation_message(opts)
diff --git a/app/models/blob_viewer/godeps_json.rb b/app/models/blob_viewer/godeps_json.rb
index 743c759aea5..bcddce7280d 100644
--- a/app/models/blob_viewer/godeps_json.rb
+++ b/app/models/blob_viewer/godeps_json.rb
@@ -4,14 +4,14 @@ module BlobViewer
class GodepsJson < DependencyManager
include Static
- self.file_types = %i(godeps_json)
+ self.file_types = %i[godeps_json]
def manager_name
- 'godep'
+ "godep"
end
def manager_url
- 'https://github.com/tools/godep'
+ "https://github.com/tools/godep"
end
end
end
diff --git a/app/models/blob_viewer/image.rb b/app/models/blob_viewer/image.rb
index 56e27839fca..92d7067dcd3 100644
--- a/app/models/blob_viewer/image.rb
+++ b/app/models/blob_viewer/image.rb
@@ -5,10 +5,10 @@ module BlobViewer
include Rich
include ClientSide
- self.partial_name = 'image'
+ self.partial_name = "image"
self.extensions = UploaderHelper::IMAGE_EXT
self.binary = true
- self.switcher_icon = 'picture-o'
- self.switcher_title = 'image'
+ self.switcher_icon = "picture-o"
+ self.switcher_title = "image"
end
end
diff --git a/app/models/blob_viewer/license.rb b/app/models/blob_viewer/license.rb
index 3427227ad26..bf2d64686ec 100644
--- a/app/models/blob_viewer/license.rb
+++ b/app/models/blob_viewer/license.rb
@@ -5,8 +5,8 @@ module BlobViewer
include Auxiliary
include Static
- self.partial_name = 'license'
- self.file_types = %i(license)
+ self.partial_name = "license"
+ self.file_types = %i[license]
self.binary = false
def license
diff --git a/app/models/blob_viewer/markup.rb b/app/models/blob_viewer/markup.rb
index f525180048e..55e0ef3f0e7 100644
--- a/app/models/blob_viewer/markup.rb
+++ b/app/models/blob_viewer/markup.rb
@@ -5,9 +5,9 @@ module BlobViewer
include Rich
include ServerSide
- self.partial_name = 'markup'
+ self.partial_name = "markup"
self.extensions = Gitlab::MarkupHelper::EXTENSIONS
- self.file_types = %i(readme)
+ self.file_types = %i[readme]
self.binary = false
end
end
diff --git a/app/models/blob_viewer/notebook.rb b/app/models/blob_viewer/notebook.rb
index 57d6d802db3..e0e74520622 100644
--- a/app/models/blob_viewer/notebook.rb
+++ b/app/models/blob_viewer/notebook.rb
@@ -5,10 +5,10 @@ module BlobViewer
include Rich
include ClientSide
- self.partial_name = 'notebook'
- self.extensions = %w(ipynb)
+ self.partial_name = "notebook"
+ self.extensions = %w[ipynb]
self.binary = false
- self.switcher_icon = 'file-text-o'
- self.switcher_title = 'notebook'
+ self.switcher_icon = "file-text-o"
+ self.switcher_title = "notebook"
end
end
diff --git a/app/models/blob_viewer/package_json.rb b/app/models/blob_viewer/package_json.rb
index 7cae60a74d6..c0e578bd2bc 100644
--- a/app/models/blob_viewer/package_json.rb
+++ b/app/models/blob_viewer/package_json.rb
@@ -4,22 +4,22 @@ module BlobViewer
class PackageJson < DependencyManager
include ServerSide
- self.file_types = %i(package_json)
+ self.file_types = %i[package_json]
def manager_name
- 'npm'
+ "npm"
end
def manager_url
- 'https://www.npmjs.com/'
+ "https://www.npmjs.com/"
end
def package_name
- @package_name ||= package_name_from_json('name')
+ @package_name ||= package_name_from_json("name")
end
def package_type
- private? ? 'private package' : super
+ private? ? "private package" : super
end
def package_url
@@ -29,11 +29,11 @@ module BlobViewer
private
def private?
- !!json_data['private']
+ !!json_data["private"]
end
def homepage
- url = json_data['homepage']
+ url = json_data["homepage"]
url if Gitlab::UrlSanitizer.valid?(url)
end
diff --git a/app/models/blob_viewer/pdf.rb b/app/models/blob_viewer/pdf.rb
index 2cf7752585c..04fafc2d1b8 100644
--- a/app/models/blob_viewer/pdf.rb
+++ b/app/models/blob_viewer/pdf.rb
@@ -5,10 +5,10 @@ module BlobViewer
include Rich
include ClientSide
- self.partial_name = 'pdf'
- self.extensions = %w(pdf)
+ self.partial_name = "pdf"
+ self.extensions = %w[pdf]
self.binary = true
- self.switcher_icon = 'file-pdf-o'
- self.switcher_title = 'PDF'
+ self.switcher_icon = "file-pdf-o"
+ self.switcher_title = "PDF"
end
end
diff --git a/app/models/blob_viewer/podfile.rb b/app/models/blob_viewer/podfile.rb
index 73d714f48ca..9bf40c54408 100644
--- a/app/models/blob_viewer/podfile.rb
+++ b/app/models/blob_viewer/podfile.rb
@@ -4,14 +4,14 @@ module BlobViewer
class Podfile < DependencyManager
include Static
- self.file_types = %i(podfile)
+ self.file_types = %i[podfile]
def manager_name
- 'CocoaPods'
+ "CocoaPods"
end
def manager_url
- 'https://cocoapods.org/'
+ "https://cocoapods.org/"
end
end
end
diff --git a/app/models/blob_viewer/podspec.rb b/app/models/blob_viewer/podspec.rb
index 2303471583d..66779369aad 100644
--- a/app/models/blob_viewer/podspec.rb
+++ b/app/models/blob_viewer/podspec.rb
@@ -4,22 +4,22 @@ module BlobViewer
class Podspec < DependencyManager
include ServerSide
- self.file_types = %i(podspec)
+ self.file_types = %i[podspec]
def manager_name
- 'CocoaPods'
+ "CocoaPods"
end
def manager_url
- 'https://cocoapods.org/'
+ "https://cocoapods.org/"
end
def package_type
- 'pod'
+ "pod"
end
def package_name
- @package_name ||= package_name_from_method_call('name')
+ @package_name ||= package_name_from_method_call("name")
end
def package_url
diff --git a/app/models/blob_viewer/podspec_json.rb b/app/models/blob_viewer/podspec_json.rb
index d3f6ae269da..6efe88aa506 100644
--- a/app/models/blob_viewer/podspec_json.rb
+++ b/app/models/blob_viewer/podspec_json.rb
@@ -2,10 +2,10 @@
module BlobViewer
class PodspecJson < Podspec
- self.file_types = %i(podspec_json)
+ self.file_types = %i[podspec_json]
def package_name
- @package_name ||= package_name_from_json('name')
+ @package_name ||= package_name_from_json("name")
end
end
end
diff --git a/app/models/blob_viewer/readme.rb b/app/models/blob_viewer/readme.rb
index f1a5c6a6acc..d93baa9de7b 100644
--- a/app/models/blob_viewer/readme.rb
+++ b/app/models/blob_viewer/readme.rb
@@ -5,8 +5,8 @@ module BlobViewer
include Auxiliary
include Static
- self.partial_name = 'readme'
- self.file_types = %i(readme)
+ self.partial_name = "readme"
+ self.file_types = %i[readme]
self.binary = false
def visible_to?(current_user)
diff --git a/app/models/blob_viewer/requirements_txt.rb b/app/models/blob_viewer/requirements_txt.rb
index 58161e83493..dacd2bc842c 100644
--- a/app/models/blob_viewer/requirements_txt.rb
+++ b/app/models/blob_viewer/requirements_txt.rb
@@ -4,14 +4,14 @@ module BlobViewer
class RequirementsTxt < DependencyManager
include Static
- self.file_types = %i(requirements_txt)
+ self.file_types = %i[requirements_txt]
def manager_name
- 'pip'
+ "pip"
end
def manager_url
- 'https://pip.pypa.io/'
+ "https://pip.pypa.io/"
end
end
end
diff --git a/app/models/blob_viewer/rich.rb b/app/models/blob_viewer/rich.rb
index 0f66a672102..a3b690f940e 100644
--- a/app/models/blob_viewer/rich.rb
+++ b/app/models/blob_viewer/rich.rb
@@ -6,8 +6,8 @@ module BlobViewer
included do
self.type = :rich
- self.switcher_icon = 'file-text-o'
- self.switcher_title = 'rendered file'
+ self.switcher_icon = "file-text-o"
+ self.switcher_title = "rendered file"
end
end
end
diff --git a/app/models/blob_viewer/route_map.rb b/app/models/blob_viewer/route_map.rb
index 6731536dfe1..4a6e3a2fac7 100644
--- a/app/models/blob_viewer/route_map.rb
+++ b/app/models/blob_viewer/route_map.rb
@@ -5,9 +5,9 @@ module BlobViewer
include ServerSide
include Auxiliary
- self.partial_name = 'route_map'
- self.loading_partial_name = 'route_map_loading'
- self.file_types = %i(route_map)
+ self.partial_name = "route_map"
+ self.loading_partial_name = "route_map_loading"
+ self.file_types = %i[route_map]
self.binary = false
def validation_message
diff --git a/app/models/blob_viewer/simple.rb b/app/models/blob_viewer/simple.rb
index c176784df46..47874789e5e 100644
--- a/app/models/blob_viewer/simple.rb
+++ b/app/models/blob_viewer/simple.rb
@@ -6,8 +6,8 @@ module BlobViewer
included do
self.type = :simple
- self.switcher_icon = 'code'
- self.switcher_title = 'source'
+ self.switcher_icon = "code"
+ self.switcher_title = "source"
end
end
end
diff --git a/app/models/blob_viewer/sketch.rb b/app/models/blob_viewer/sketch.rb
index 659ab11f30b..89745f1a7f1 100644
--- a/app/models/blob_viewer/sketch.rb
+++ b/app/models/blob_viewer/sketch.rb
@@ -5,10 +5,10 @@ module BlobViewer
include Rich
include ClientSide
- self.partial_name = 'sketch'
- self.extensions = %w(sketch)
+ self.partial_name = "sketch"
+ self.extensions = %w[sketch]
self.binary = true
- self.switcher_icon = 'file-image-o'
- self.switcher_title = 'preview'
+ self.switcher_icon = "file-image-o"
+ self.switcher_title = "preview"
end
end
diff --git a/app/models/blob_viewer/svg.rb b/app/models/blob_viewer/svg.rb
index 454c6a57568..e1914c48acd 100644
--- a/app/models/blob_viewer/svg.rb
+++ b/app/models/blob_viewer/svg.rb
@@ -5,10 +5,10 @@ module BlobViewer
include Rich
include ServerSide
- self.partial_name = 'svg'
- self.extensions = %w(svg)
+ self.partial_name = "svg"
+ self.extensions = %w[svg]
self.binary = false
- self.switcher_icon = 'picture-o'
- self.switcher_title = 'image'
+ self.switcher_icon = "picture-o"
+ self.switcher_title = "image"
end
end
diff --git a/app/models/blob_viewer/text.rb b/app/models/blob_viewer/text.rb
index e0c586a6680..d24ad376694 100644
--- a/app/models/blob_viewer/text.rb
+++ b/app/models/blob_viewer/text.rb
@@ -5,7 +5,7 @@ module BlobViewer
include Simple
include ServerSide
- self.partial_name = 'text'
+ self.partial_name = "text"
self.binary = false
self.collapse_limit = 1.megabyte
self.size_limit = 10.megabytes
diff --git a/app/models/blob_viewer/video.rb b/app/models/blob_viewer/video.rb
index 48bb2a13518..09e43d16a4f 100644
--- a/app/models/blob_viewer/video.rb
+++ b/app/models/blob_viewer/video.rb
@@ -5,10 +5,10 @@ module BlobViewer
include Rich
include ClientSide
- self.partial_name = 'video'
+ self.partial_name = "video"
self.extensions = UploaderHelper::VIDEO_EXT
self.binary = true
- self.switcher_icon = 'film'
- self.switcher_title = 'video'
+ self.switcher_icon = "film"
+ self.switcher_title = "video"
end
end
diff --git a/app/models/blob_viewer/yarn_lock.rb b/app/models/blob_viewer/yarn_lock.rb
index 196d9f96f23..99eb99939b6 100644
--- a/app/models/blob_viewer/yarn_lock.rb
+++ b/app/models/blob_viewer/yarn_lock.rb
@@ -4,14 +4,14 @@ module BlobViewer
class YarnLock < DependencyManager
include Static
- self.file_types = %i(yarn_lock)
+ self.file_types = %i[yarn_lock]
def manager_name
- 'Yarn'
+ "Yarn"
end
def manager_url
- 'https://yarnpkg.com/'
+ "https://yarnpkg.com/"
end
end
end
diff --git a/app/models/board_group_recent_visit.rb b/app/models/board_group_recent_visit.rb
index 92abbb67222..d9f24a877ff 100644
--- a/app/models/board_group_recent_visit.rb
+++ b/app/models/board_group_recent_visit.rb
@@ -10,7 +10,7 @@ class BoardGroupRecentVisit < ActiveRecord::Base
validates :group, presence: true
validates :board, presence: true
- scope :by_user_group, -> (user, group) { where(user: user, group: group).order(:updated_at) }
+ scope :by_user_group, ->(user, group) { where(user: user, group: group).order(:updated_at) }
def self.visited!(user, board)
visit = find_or_create_by(user: user, group: board.group, board: board)
diff --git a/app/models/board_project_recent_visit.rb b/app/models/board_project_recent_visit.rb
index 7cffff906d8..963720f349f 100644
--- a/app/models/board_project_recent_visit.rb
+++ b/app/models/board_project_recent_visit.rb
@@ -10,7 +10,7 @@ class BoardProjectRecentVisit < ActiveRecord::Base
validates :project, presence: true
validates :board, presence: true
- scope :by_user_project, -> (user, project) { where(user: user, project: project).order(:updated_at) }
+ scope :by_user_project, ->(user, project) { where(user: user, project: project).order(:updated_at) }
def self.visited!(user, board)
visit = find_or_create_by(user: user, project: board.project, board: board)
diff --git a/app/models/broadcast_message.rb b/app/models/broadcast_message.rb
index 2d237383e60..8ee663b5e01 100644
--- a/app/models/broadcast_message.rb
+++ b/app/models/broadcast_message.rb
@@ -13,19 +13,19 @@ class BroadcastMessage < ActiveRecord::Base
validates :color, allow_blank: true, color: true
validates :font, allow_blank: true, color: true
- default_value_for :color, '#E75E40'
- default_value_for :font, '#FFFFFF'
+ default_value_for :color, "#E75E40"
+ default_value_for :font, "#FFFFFF"
- CACHE_KEY = 'broadcast_message_current_json'.freeze
- LEGACY_CACHE_KEY = 'broadcast_message_current'.freeze
+ CACHE_KEY = "broadcast_message_current_json"
+ LEGACY_CACHE_KEY = "broadcast_message_current"
after_commit :flush_redis_cache
def self.current
- messages = cache.fetch(CACHE_KEY, as: BroadcastMessage, expires_in: cache_expires_in) do
+ messages = cache.fetch(CACHE_KEY, as: BroadcastMessage, expires_in: cache_expires_in) {
remove_legacy_cache_key
current_and_future_messages
- end
+ }
return [] unless messages&.present?
@@ -39,7 +39,7 @@ class BroadcastMessage < ActiveRecord::Base
end
def self.current_and_future_messages
- where('ends_at > :now', now: Time.zone.now).order_id_asc
+ where("ends_at > :now", now: Time.zone.now).order_id_asc
end
def self.cache
diff --git a/app/models/chat_name.rb b/app/models/chat_name.rb
index 03b0af53046..8a97134c6a5 100644
--- a/app/models/chat_name.rb
+++ b/app/models/chat_name.rb
@@ -11,8 +11,8 @@ class ChatName < ActiveRecord::Base
validates :team_id, presence: true
validates :chat_id, presence: true
- validates :user_id, uniqueness: { scope: [:service_id] }
- validates :chat_id, uniqueness: { scope: [:service_id, :team_id] }
+ validates :user_id, uniqueness: {scope: [:service_id]}
+ validates :chat_id, uniqueness: {scope: [:service_id, :team_id]}
# Updates the "last_used_timestamp" but only if it wasn't already updated
# recently.
diff --git a/app/models/ci/artifact_blob.rb b/app/models/ci/artifact_blob.rb
index d87d6a5cb2f..32809bbd1a3 100644
--- a/app/models/ci/artifact_blob.rb
+++ b/app/models/ci/artifact_blob.rb
@@ -21,7 +21,7 @@ module Ci
def size
entry.metadata[:size]
end
- alias_method :external_size, :size
+ alias external_size size
def data
"Build artifact #{path}"
@@ -38,13 +38,13 @@ module Ci
def external_url(project, job)
return unless external_link?(job)
- url_project_path = project.full_path.partition('/').last
+ url_project_path = project.full_path.partition("/").last
artifact_path = [
- '-', url_project_path, '-',
- 'jobs', job.id,
- 'artifacts', path
- ].join('/')
+ "-", url_project_path, "-",
+ "jobs", job.id,
+ "artifacts", path,
+ ].join("/")
"#{project.pages_group_url}/#{artifact_path}"
end
diff --git a/app/models/ci/bridge.rb b/app/models/ci/bridge.rb
index 5450d40ea95..5659c0a2557 100644
--- a/app/models/ci/bridge.rb
+++ b/app/models/ci/bridge.rb
@@ -49,7 +49,7 @@ module Ci
end
def to_partial_path
- 'projects/generic_commit_statuses/generic_commit_status'
+ "projects/generic_commit_statuses/generic_commit_status"
end
end
end
diff --git a/app/models/ci/build.rb b/app/models/ci/build.rb
index c902e49ee6d..e1fe32a40a7 100644
--- a/app/models/ci/build.rb
+++ b/app/models/ci/build.rb
@@ -22,23 +22,23 @@ module Ci
belongs_to :project, inverse_of: :builds
belongs_to :runner
belongs_to :trigger_request
- belongs_to :erased_by, class_name: 'User'
+ belongs_to :erased_by, class_name: "User"
RUNNER_FEATURES = {
- upload_multiple_artifacts: -> (build) { build.publishes_artifacts_reports? }
+ upload_multiple_artifacts: ->(build) { build.publishes_artifacts_reports? },
}.freeze
- has_one :deployment, as: :deployable, class_name: 'Deployment'
- has_many :trace_sections, class_name: 'Ci::BuildTraceSection'
- has_many :trace_chunks, class_name: 'Ci::BuildTraceChunk', foreign_key: :build_id
+ has_one :deployment, as: :deployable, class_name: "Deployment"
+ has_many :trace_sections, class_name: "Ci::BuildTraceSection"
+ has_many :trace_chunks, class_name: "Ci::BuildTraceChunk", foreign_key: :build_id
- has_many :job_artifacts, class_name: 'Ci::JobArtifact', foreign_key: :job_id, dependent: :destroy, inverse_of: :job # rubocop:disable Cop/ActiveRecordDependent
+ has_many :job_artifacts, class_name: "Ci::JobArtifact", foreign_key: :job_id, dependent: :destroy, inverse_of: :job # rubocop:disable Cop/ActiveRecordDependent
Ci::JobArtifact.file_types.each do |key, value|
- has_one :"job_artifacts_#{key}", -> { where(file_type: value) }, class_name: 'Ci::JobArtifact', inverse_of: :job, foreign_key: :job_id
+ has_one :"job_artifacts_#{key}", -> { where(file_type: value) }, class_name: "Ci::JobArtifact", inverse_of: :job, foreign_key: :job_id
end
- has_one :runner_session, class_name: 'Ci::BuildRunnerSession', validate: true, inverse_of: :build
+ has_one :runner_session, class_name: "Ci::BuildRunnerSession", validate: true, inverse_of: :build
accepts_nested_attributes_for :runner_session
@@ -77,26 +77,26 @@ module Ci
validates :coverage, numericality: true, allow_blank: true
validates :ref, presence: true
- scope :unstarted, ->() { where(runner_id: nil) }
- scope :ignore_failures, ->() { where(allow_failure: false) }
- scope :with_artifacts_archive, ->() do
- where('(artifacts_file IS NOT NULL AND artifacts_file <> ?) OR EXISTS (?)',
- '', Ci::JobArtifact.select(1).where('ci_builds.id = ci_job_artifacts.job_id').archive)
+ scope :unstarted, -> { where(runner_id: nil) }
+ scope :ignore_failures, -> { where(allow_failure: false) }
+ scope :with_artifacts_archive, -> do
+ where("(artifacts_file IS NOT NULL AND artifacts_file <> ?) OR EXISTS (?)",
+ "", Ci::JobArtifact.select(1).where("ci_builds.id = ci_job_artifacts.job_id").archive)
end
scope :with_existing_job_artifacts, ->(query) do
- where('EXISTS (?)', ::Ci::JobArtifact.select(1).where('ci_builds.id = ci_job_artifacts.job_id').merge(query))
+ where("EXISTS (?)", ::Ci::JobArtifact.select(1).where("ci_builds.id = ci_job_artifacts.job_id").merge(query))
end
- scope :with_archived_trace, ->() do
+ scope :with_archived_trace, -> do
with_existing_job_artifacts(Ci::JobArtifact.trace)
end
- scope :without_archived_trace, ->() do
- where('NOT EXISTS (?)', Ci::JobArtifact.select(1).where('ci_builds.id = ci_job_artifacts.job_id').trace)
+ scope :without_archived_trace, -> do
+ where("NOT EXISTS (?)", Ci::JobArtifact.select(1).where("ci_builds.id = ci_job_artifacts.job_id").trace)
end
- scope :with_test_reports, ->() do
+ scope :with_test_reports, -> do
with_existing_job_artifacts(Ci::JobArtifact.test_reports)
.eager_load_job_artifacts
end
@@ -105,20 +105,20 @@ module Ci
scope :with_artifacts_stored_locally, -> { with_artifacts_archive.where(artifacts_file_store: [nil, LegacyArtifactUploader::Store::LOCAL]) }
scope :with_archived_trace_stored_locally, -> { with_archived_trace.where(artifacts_file_store: [nil, LegacyArtifactUploader::Store::LOCAL]) }
- scope :with_artifacts_not_expired, ->() { with_artifacts_archive.where('artifacts_expire_at IS NULL OR artifacts_expire_at > ?', Time.now) }
- scope :with_expired_artifacts, ->() { with_artifacts_archive.where('artifacts_expire_at < ?', Time.now) }
- scope :last_month, ->() { where('created_at > ?', Date.today - 1.month) }
- scope :manual_actions, ->() { where(when: :manual, status: COMPLETED_STATUSES + %i[manual]) }
- scope :scheduled_actions, ->() { where(when: :delayed, status: COMPLETED_STATUSES + %i[scheduled]) }
+ scope :with_artifacts_not_expired, -> { with_artifacts_archive.where("artifacts_expire_at IS NULL OR artifacts_expire_at > ?", Time.now) }
+ scope :with_expired_artifacts, -> { with_artifacts_archive.where("artifacts_expire_at < ?", Time.now) }
+ scope :last_month, -> { where("created_at > ?", Date.today - 1.month) }
+ scope :manual_actions, -> { where(when: :manual, status: COMPLETED_STATUSES + %i[manual]) }
+ scope :scheduled_actions, -> { where(when: :delayed, status: COMPLETED_STATUSES + %i[scheduled]) }
scope :ref_protected, -> { where(protected: true) }
- scope :with_live_trace, -> { where('EXISTS (?)', Ci::BuildTraceChunk.where('ci_builds.id = ci_build_trace_chunks.build_id').select(1)) }
+ scope :with_live_trace, -> { where("EXISTS (?)", Ci::BuildTraceChunk.where("ci_builds.id = ci_build_trace_chunks.build_id").select(1)) }
- scope :matches_tag_ids, -> (tag_ids) do
+ scope :matches_tag_ids, ->(tag_ids) do
matcher = ::ActsAsTaggableOn::Tagging
.where(taggable_type: CommitStatus.name)
- .where(context: 'tags')
- .where('taggable_id = ci_builds.id')
- .where.not(tag_id: tag_ids).select('1')
+ .where(context: "tags")
+ .where("taggable_id = ci_builds.id")
+ .where.not(tag_id: tag_ids).select("1")
where("NOT EXISTS (?)", matcher)
end
@@ -126,8 +126,8 @@ module Ci
scope :with_any_tags, -> do
matcher = ::ActsAsTaggableOn::Tagging
.where(taggable_type: CommitStatus.name)
- .where(context: 'tags')
- .where('taggable_id = ci_builds.id').select('1')
+ .where(context: "tags")
+ .where("taggable_id = ci_builds.id").select("1")
where("EXISTS (?)", matcher)
end
@@ -154,11 +154,11 @@ module Ci
# This is needed for url_for to work,
# as the controller is JobsController
def model_name
- ActiveModel::Name.new(self, nil, 'job')
+ ActiveModel::Name.new(self, nil, "job")
end
def first_pending
- pending.unstarted.order('created_at ASC').first
+ pending.unstarted.order("created_at ASC").first
end
def retry(build, current_user)
@@ -239,7 +239,7 @@ module Ci
begin
build.deployment.drop!
rescue => e
- Gitlab::Sentry.track_exception(e, extra: { build_id: build.id })
+ Gitlab::Sentry.track_exception(e, extra: {build_id: build.id})
end
true
@@ -286,7 +286,7 @@ module Ci
def pages_generator?
Gitlab.config.pages.enabled &&
- self.name == 'pages'
+ name == "pages"
end
def archived?
@@ -301,7 +301,7 @@ module Ci
end
def schedulable?
- self.when == 'delayed' && options[:start_in].present?
+ self.when == "delayed" && options[:start_in].present?
end
def options_scheduled_at
@@ -329,7 +329,7 @@ module Ci
end
def retries_count
- pipeline.builds.retried.where(name: self.name).count
+ pipeline.builds.retried.where(name: name).count
end
def retries_max
@@ -337,13 +337,13 @@ module Ci
end
def retry_when
- normalized_retry.fetch(:when, ['always'])
+ normalized_retry.fetch(:when, ["always"])
end
def retry_failure?
return false if retries_max.zero? || retries_count >= retries_max
- retry_when.include?('always') || retry_when.include?(failure_reason.to_s)
+ retry_when.include?("always") || retry_when.include?(failure_reason.to_s)
end
def latest?
@@ -363,19 +363,19 @@ module Ci
end
def starts_environment?
- has_environment? && self.environment_action == 'start'
+ has_environment? && environment_action == "start"
end
def stops_environment?
- has_environment? && self.environment_action == 'stop'
+ has_environment? && environment_action == "stop"
end
def environment_action
- self.options.fetch(:environment, {}).fetch(:action, 'start') if self.options
+ options&.fetch(:environment, {})&.fetch(:action, "start")
end
def has_deployment?
- !!self.deployment
+ !!deployment
end
def outdated_deployment?
@@ -384,10 +384,10 @@ module Ci
def depends_on_builds
# Get builds of the same type
- latest_builds = self.pipeline.builds.latest
+ latest_builds = pipeline.builds.latest
# Return builds from previous stages
- latest_builds.where('stage_idx < ?', stage_idx)
+ latest_builds.where("stage_idx < ?", stage_idx)
end
def triggered_by?(current_user)
@@ -460,7 +460,7 @@ module Ci
end
def features
- { trace_sections: true }
+ {trace_sections: true}
end
def merge_request
@@ -570,7 +570,8 @@ module Ci
metadata = Gitlab::Ci::Build::Artifacts::Metadata.new(
metadata_stream,
path,
- **options)
+ **options
+ )
metadata.to_entry
end
@@ -596,7 +597,7 @@ module Ci
end
def erased?
- !self.erased_at.nil?
+ !erased_at.nil?
end
def artifacts_expired?
@@ -619,8 +620,8 @@ module Ci
end
def keep_artifacts!
- self.update(artifacts_expire_at: nil)
- self.job_artifacts.update_all(expire_at: nil)
+ update(artifacts_expire_at: nil)
+ job_artifacts.update_all(expire_at: nil)
end
def artifacts_file_for_type(type)
@@ -638,10 +639,10 @@ module Ci
Gitlab::Ci::Variables::Collection.new.tap do |variables|
break variables if user.blank?
- variables.append(key: 'GITLAB_USER_ID', value: user.id.to_s)
- variables.append(key: 'GITLAB_USER_EMAIL', value: user.email)
- variables.append(key: 'GITLAB_USER_LOGIN', value: user.username)
- variables.append(key: 'GITLAB_USER_NAME', value: user.name)
+ variables.append(key: "GITLAB_USER_ID", value: user.id.to_s)
+ variables.append(key: "GITLAB_USER_EMAIL", value: user.email)
+ variables.append(key: "GITLAB_USER_LOGIN", value: user.username)
+ variables.append(key: "GITLAB_USER_NAME", value: user.name)
end
end
@@ -657,7 +658,7 @@ module Ci
def steps
[Gitlab::Ci::Build::Step.from_commands(self),
- Gitlab::Ci::Build::Step.from_after_script(self)].compact
+ Gitlab::Ci::Build::Step.from_after_script(self),].compact
end
def image
@@ -673,7 +674,8 @@ module Ci
if cache && project.jobs_cache_index
cache = cache.merge(
- key: "#{cache[:key]}-#{project.jobs_cache_index}")
+ key: "#{cache[:key]}-#{project.jobs_cache_index}"
+ )
end
[cache]
@@ -700,7 +702,7 @@ module Ci
end
def has_valid_build_dependencies?
- return true if Feature.enabled?('ci_disable_validates_dependencies')
+ return true if Feature.enabled?("ci_disable_validates_dependencies")
dependencies.all?(&:valid_dependency?)
end
@@ -714,9 +716,9 @@ module Ci
def runner_required_feature_names
strong_memoize(:runner_required_feature_names) do
- RUNNER_FEATURES.select do |feature, method|
+ RUNNER_FEATURES.select { |feature, method|
method.call(self)
- end.keys
+ }.keys
end
end
@@ -807,14 +809,14 @@ module Ci
end
def update_erased!(user = nil)
- self.update(erased_by: user, erased_at: Time.now, artifacts_expire_at: nil)
+ update(erased_by: user, erased_at: Time.now, artifacts_expire_at: nil)
end
def unscoped_project
@unscoped_project ||= Project.unscoped.find_by(id: project_id)
end
- CI_REGISTRY_USER = 'gitlab-ci-token'.freeze
+ CI_REGISTRY_USER = "gitlab-ci-token"
def persisted_variables
Gitlab::Ci::Variables::Collection.new.tap do |variables|
@@ -822,56 +824,56 @@ module Ci
variables
.concat(pipeline.persisted_variables)
- .append(key: 'CI_JOB_ID', value: id.to_s)
- .append(key: 'CI_JOB_URL', value: Gitlab::Routing.url_helpers.project_job_url(project, self))
- .append(key: 'CI_JOB_TOKEN', value: token.to_s, public: false)
- .append(key: 'CI_BUILD_ID', value: id.to_s)
- .append(key: 'CI_BUILD_TOKEN', value: token.to_s, public: false)
- .append(key: 'CI_REGISTRY_USER', value: CI_REGISTRY_USER)
- .append(key: 'CI_REGISTRY_PASSWORD', value: token.to_s, public: false)
- .append(key: 'CI_REPOSITORY_URL', value: repo_url.to_s, public: false)
+ .append(key: "CI_JOB_ID", value: id.to_s)
+ .append(key: "CI_JOB_URL", value: Gitlab::Routing.url_helpers.project_job_url(project, self))
+ .append(key: "CI_JOB_TOKEN", value: token.to_s, public: false)
+ .append(key: "CI_BUILD_ID", value: id.to_s)
+ .append(key: "CI_BUILD_TOKEN", value: token.to_s, public: false)
+ .append(key: "CI_REGISTRY_USER", value: CI_REGISTRY_USER)
+ .append(key: "CI_REGISTRY_PASSWORD", value: token.to_s, public: false)
+ .append(key: "CI_REPOSITORY_URL", value: repo_url.to_s, public: false)
.concat(deploy_token_variables)
end
end
def predefined_variables # rubocop:disable Metrics/AbcSize
Gitlab::Ci::Variables::Collection.new.tap do |variables|
- variables.append(key: 'CI', value: 'true')
- variables.append(key: 'GITLAB_CI', value: 'true')
- variables.append(key: 'GITLAB_FEATURES', value: project.licensed_features.join(','))
- variables.append(key: 'CI_SERVER_NAME', value: 'GitLab')
- variables.append(key: 'CI_SERVER_VERSION', value: Gitlab::VERSION)
- variables.append(key: 'CI_SERVER_VERSION_MAJOR', value: Gitlab.version_info.major.to_s)
- variables.append(key: 'CI_SERVER_VERSION_MINOR', value: Gitlab.version_info.minor.to_s)
- variables.append(key: 'CI_SERVER_VERSION_PATCH', value: Gitlab.version_info.patch.to_s)
- variables.append(key: 'CI_SERVER_REVISION', value: Gitlab.revision)
- variables.append(key: 'CI_JOB_NAME', value: name)
- variables.append(key: 'CI_JOB_STAGE', value: stage)
- variables.append(key: 'CI_COMMIT_SHA', value: sha)
- variables.append(key: 'CI_COMMIT_SHORT_SHA', value: short_sha)
- variables.append(key: 'CI_COMMIT_BEFORE_SHA', value: before_sha)
- variables.append(key: 'CI_COMMIT_REF_NAME', value: ref)
- variables.append(key: 'CI_COMMIT_REF_SLUG', value: ref_slug)
+ variables.append(key: "CI", value: "true")
+ variables.append(key: "GITLAB_CI", value: "true")
+ variables.append(key: "GITLAB_FEATURES", value: project.licensed_features.join(","))
+ variables.append(key: "CI_SERVER_NAME", value: "GitLab")
+ variables.append(key: "CI_SERVER_VERSION", value: Gitlab::VERSION)
+ variables.append(key: "CI_SERVER_VERSION_MAJOR", value: Gitlab.version_info.major.to_s)
+ variables.append(key: "CI_SERVER_VERSION_MINOR", value: Gitlab.version_info.minor.to_s)
+ variables.append(key: "CI_SERVER_VERSION_PATCH", value: Gitlab.version_info.patch.to_s)
+ variables.append(key: "CI_SERVER_REVISION", value: Gitlab.revision)
+ variables.append(key: "CI_JOB_NAME", value: name)
+ variables.append(key: "CI_JOB_STAGE", value: stage)
+ variables.append(key: "CI_COMMIT_SHA", value: sha)
+ variables.append(key: "CI_COMMIT_SHORT_SHA", value: short_sha)
+ variables.append(key: "CI_COMMIT_BEFORE_SHA", value: before_sha)
+ variables.append(key: "CI_COMMIT_REF_NAME", value: ref)
+ variables.append(key: "CI_COMMIT_REF_SLUG", value: ref_slug)
variables.append(key: "CI_COMMIT_TAG", value: ref) if tag?
- variables.append(key: "CI_PIPELINE_TRIGGERED", value: 'true') if trigger_request
- variables.append(key: "CI_JOB_MANUAL", value: 'true') if action?
- variables.append(key: "CI_NODE_INDEX", value: self.options[:instance].to_s) if self.options&.include?(:instance)
- variables.append(key: "CI_NODE_TOTAL", value: (self.options&.dig(:parallel) || 1).to_s)
+ variables.append(key: "CI_PIPELINE_TRIGGERED", value: "true") if trigger_request
+ variables.append(key: "CI_JOB_MANUAL", value: "true") if action?
+ variables.append(key: "CI_NODE_INDEX", value: options[:instance].to_s) if options&.include?(:instance)
+ variables.append(key: "CI_NODE_TOTAL", value: (options&.dig(:parallel) || 1).to_s)
variables.concat(legacy_variables)
end
end
def legacy_variables
Gitlab::Ci::Variables::Collection.new.tap do |variables|
- variables.append(key: 'CI_BUILD_REF', value: sha)
- variables.append(key: 'CI_BUILD_BEFORE_SHA', value: before_sha)
- variables.append(key: 'CI_BUILD_REF_NAME', value: ref)
- variables.append(key: 'CI_BUILD_REF_SLUG', value: ref_slug)
- variables.append(key: 'CI_BUILD_NAME', value: name)
- variables.append(key: 'CI_BUILD_STAGE', value: stage)
+ variables.append(key: "CI_BUILD_REF", value: sha)
+ variables.append(key: "CI_BUILD_BEFORE_SHA", value: before_sha)
+ variables.append(key: "CI_BUILD_REF_NAME", value: ref)
+ variables.append(key: "CI_BUILD_REF_SLUG", value: ref_slug)
+ variables.append(key: "CI_BUILD_NAME", value: name)
+ variables.append(key: "CI_BUILD_STAGE", value: stage)
variables.append(key: "CI_BUILD_TAG", value: ref) if tag?
- variables.append(key: "CI_BUILD_TRIGGERED", value: 'true') if trigger_request
- variables.append(key: "CI_BUILD_MANUAL", value: 'true') if action?
+ variables.append(key: "CI_BUILD_TRIGGERED", value: "true") if trigger_request
+ variables.append(key: "CI_BUILD_MANUAL", value: "true") if action?
end
end
@@ -884,7 +886,7 @@ module Ci
# Here we're passing unexpanded environment_url for runner to expand,
# and we need to make sure that CI_ENVIRONMENT_NAME and
# CI_ENVIRONMENT_SLUG so on are available for the URL be expanded.
- variables.append(key: 'CI_ENVIRONMENT_URL', value: environment_url) if environment_url
+ variables.append(key: "CI_ENVIRONMENT_URL", value: environment_url) if environment_url
end
end
@@ -892,8 +894,8 @@ module Ci
Gitlab::Ci::Variables::Collection.new.tap do |variables|
break variables unless gitlab_deploy_token
- variables.append(key: 'CI_DEPLOY_USER', value: gitlab_deploy_token.username)
- variables.append(key: 'CI_DEPLOY_PASSWORD', value: gitlab_deploy_token.token, public: false)
+ variables.append(key: "CI_DEPLOY_USER", value: gitlab_deploy_token.username)
+ variables.append(key: "CI_DEPLOY_PASSWORD", value: gitlab_deploy_token.token, public: false)
end
end
@@ -909,7 +911,7 @@ module Ci
def normalized_retry
strong_memoize(:normalized_retry) do
value = options&.dig(:retry)
- value = value.is_a?(Integer) ? { max: value } : value.to_h
+ value = value.is_a?(Integer) ? {max: value} : value.to_h
value.with_indifferent_access
end
end
diff --git a/app/models/ci/build_metadata.rb b/app/models/ci/build_metadata.rb
index cd8eb774cf5..ff4a5bfaa7c 100644
--- a/app/models/ci/build_metadata.rb
+++ b/app/models/ci/build_metadata.rb
@@ -8,9 +8,9 @@ module Ci
include Presentable
include ChronicDurationAttribute
- self.table_name = 'ci_builds_metadata'
+ self.table_name = "ci_builds_metadata"
- belongs_to :build, class_name: 'CommitStatus'
+ belongs_to :build, class_name: "CommitStatus"
belongs_to :project
before_create :set_build_project
@@ -23,9 +23,9 @@ module Ci
chronic_duration_attr_reader :timeout_human_readable, :timeout
enum timeout_source: {
- unknown_timeout_source: 1,
- project_timeout_source: 2,
- runner_timeout_source: 3
+ unknown_timeout_source: 1,
+ project_timeout_source: 2,
+ runner_timeout_source: 3,
}
def update_timeout_state
@@ -41,7 +41,7 @@ module Ci
private
def set_build_project
- self.project_id ||= self.build.project_id
+ self.project_id ||= build.project_id
end
end
end
diff --git a/app/models/ci/build_runner_session.rb b/app/models/ci/build_runner_session.rb
index 457d7eeab6a..bda127b930e 100644
--- a/app/models/ci/build_runner_session.rb
+++ b/app/models/ci/build_runner_session.rb
@@ -6,21 +6,21 @@ module Ci
class BuildRunnerSession < ActiveRecord::Base
extend Gitlab::Ci::Model
- self.table_name = 'ci_builds_runner_session'
+ self.table_name = "ci_builds_runner_session"
- belongs_to :build, class_name: 'Ci::Build', inverse_of: :runner_session
+ belongs_to :build, class_name: "Ci::Build", inverse_of: :runner_session
validates :build, presence: true
- validates :url, url: { protocols: %w(https) }
+ validates :url, url: {protocols: %w[https]}
def terminal_specification
return {} unless url.present?
{
- subprotocols: ['terminal.gitlab.com'].freeze,
+ subprotocols: ["terminal.gitlab.com"].freeze,
url: "#{url}/exec".sub("https://", "wss://"),
- headers: { Authorization: [authorization.presence] }.compact,
- ca_pem: certificate.presence
+ headers: {Authorization: [authorization.presence]}.compact,
+ ca_pem: certificate.presence,
}
end
end
diff --git a/app/models/ci/build_trace_chunk.rb b/app/models/ci/build_trace_chunk.rb
index 75017f224a0..dd02e884af8 100644
--- a/app/models/ci/build_trace_chunk.rb
+++ b/app/models/ci/build_trace_chunk.rb
@@ -22,12 +22,12 @@ module Ci
enum data_store: {
redis: 1,
database: 2,
- fog: 3
+ fog: 3,
}
class << self
def all_stores
- @all_stores ||= self.data_stores.keys
+ @all_stores ||= data_stores.keys
end
def persistable_store
@@ -67,16 +67,16 @@ module Ci
end
def truncate(offset = 0)
- raise ArgumentError, 'Offset is out of range' if offset > size || offset < 0
+ raise ArgumentError, "Offset is out of range" if offset > size || offset < 0
return if offset == size # Skip the following process as it doesn't affect anything
- self.append("", offset)
+ append("", offset)
end
def append(new_data, offset)
- raise ArgumentError, 'New data is missing' unless new_data
- raise ArgumentError, 'Offset is out of range' if offset > size || offset < 0
- raise ArgumentError, 'Chunk size overflow' if CHUNK_SIZE < (offset + new_data.bytesize)
+ raise ArgumentError, "New data is missing" unless new_data
+ raise ArgumentError, "Offset is out of range" if offset > size || offset < 0
+ raise ArgumentError, "Chunk size overflow" if CHUNK_SIZE < (offset + new_data.bytesize)
in_lock(*lock_params) do # Write operation is atomic
unsafe_set_data!(data.byteslice(0, offset) + new_data)
@@ -115,7 +115,7 @@ module Ci
current_data = get_data
unless current_data&.bytesize.to_i == CHUNK_SIZE
- raise FailedToPersistDataError, 'Data is not fulfilled in a bucket'
+ raise FailedToPersistDataError, "Data is not fulfilled in a bucket"
end
old_store_class = self.class.get_store_class(data_store)
@@ -134,7 +134,7 @@ module Ci
end
def unsafe_set_data!(value)
- raise ArgumentError, 'New data size exceeds chunk size' if value.bytesize > CHUNK_SIZE
+ raise ArgumentError, "New data size exceeds chunk size" if value.bytesize > CHUNK_SIZE
self.class.get_store_class(data_store).set_data(self, value)
@data = value
@@ -158,9 +158,9 @@ module Ci
def lock_params
["trace_write:#{build_id}:chunks:#{chunk_index}",
- { ttl: WRITE_LOCK_TTL,
- retries: WRITE_LOCK_RETRY,
- sleep_sec: WRITE_LOCK_SLEEP }]
+ {ttl: WRITE_LOCK_TTL,
+ retries: WRITE_LOCK_RETRY,
+ sleep_sec: WRITE_LOCK_SLEEP,},]
end
end
end
diff --git a/app/models/ci/build_trace_section.rb b/app/models/ci/build_trace_section.rb
index a4bee59c83b..f19cd721f99 100644
--- a/app/models/ci/build_trace_section.rb
+++ b/app/models/ci/build_trace_section.rb
@@ -4,9 +4,9 @@ module Ci
class BuildTraceSection < ActiveRecord::Base
extend Gitlab::Ci::Model
- belongs_to :build, class_name: 'Ci::Build'
+ belongs_to :build, class_name: "Ci::Build"
belongs_to :project
- belongs_to :section_name, class_name: 'Ci::BuildTraceSectionName'
+ belongs_to :section_name, class_name: "Ci::BuildTraceSectionName"
validates :section_name, :build, :project, presence: true, allow_blank: false
end
diff --git a/app/models/ci/build_trace_section_name.rb b/app/models/ci/build_trace_section_name.rb
index cbdf3c4b673..8c6834f6514 100644
--- a/app/models/ci/build_trace_section_name.rb
+++ b/app/models/ci/build_trace_section_name.rb
@@ -5,9 +5,9 @@ module Ci
extend Gitlab::Ci::Model
belongs_to :project
- has_many :trace_sections, class_name: 'Ci::BuildTraceSection', foreign_key: :section_name_id
+ has_many :trace_sections, class_name: "Ci::BuildTraceSection", foreign_key: :section_name_id
validates :name, :project, presence: true, allow_blank: false
- validates :name, uniqueness: { scope: :project_id }
+ validates :name, uniqueness: {scope: :project_id}
end
end
diff --git a/app/models/ci/group.rb b/app/models/ci/group.rb
index 9b2c3c807ac..d601ea120d9 100644
--- a/app/models/ci/group.rb
+++ b/app/models/ci/group.rb
@@ -37,7 +37,7 @@ module Ci
stage.statuses.ordered.latest
.sort_by(&:sortable_name).group_by(&:group_name)
.map do |group_name, grouped_statuses|
- self.new(stage, name: group_name, jobs: grouped_statuses)
+ new(stage, name: group_name, jobs: grouped_statuses)
end
end
diff --git a/app/models/ci/group_variable.rb b/app/models/ci/group_variable.rb
index 323ff560564..98326d3af8b 100644
--- a/app/models/ci/group_variable.rb
+++ b/app/models/ci/group_variable.rb
@@ -13,7 +13,7 @@ module Ci
validates :key, uniqueness: {
scope: :group_id,
- message: "(%{value}) has already been taken"
+ message: "(%{value}) has already been taken",
}
scope :unprotected, -> { where(protected: false) }
diff --git a/app/models/ci/job_artifact.rb b/app/models/ci/job_artifact.rb
index 789bb293811..da262666637 100644
--- a/app/models/ci/job_artifact.rb
+++ b/app/models/ci/job_artifact.rb
@@ -14,14 +14,14 @@ module Ci
archive: nil,
metadata: nil,
trace: nil,
- junit: 'junit.xml',
- codequality: 'gl-code-quality-report.json',
- sast: 'gl-sast-report.json',
- dependency_scanning: 'gl-dependency-scanning-report.json',
- container_scanning: 'gl-container-scanning-report.json',
- dast: 'gl-dast-report.json',
- license_management: 'gl-license-management-report.json',
- performance: 'performance.json'
+ junit: "junit.xml",
+ codequality: "gl-code-quality-report.json",
+ sast: "gl-sast-report.json",
+ dependency_scanning: "gl-dependency-scanning-report.json",
+ container_scanning: "gl-container-scanning-report.json",
+ dast: "gl-dast-report.json",
+ license_management: "gl-license-management-report.json",
+ performance: "performance.json",
}.freeze
TYPE_AND_FORMAT_PAIRS = {
@@ -39,7 +39,7 @@ module Ci
container_scanning: :raw,
dast: :raw,
license_management: :raw,
- performance: :raw
+ performance: :raw,
}.freeze
belongs_to :project
@@ -57,7 +57,7 @@ module Ci
scope :with_files_stored_locally, -> { where(file_store: [nil, ::JobArtifactUploader::Store::LOCAL]) }
- scope :with_file_types, -> (file_types) do
+ scope :with_file_types, ->(file_types) do
types = self.file_types.select { |file_type| file_types.include?(file_type) }.values
where(file_type: types)
@@ -68,12 +68,12 @@ module Ci
end
scope :erasable, -> do
- types = self.file_types.reject { |file_type| NON_ERASABLE_FILE_TYPES.include?(file_type) }.values
+ types = file_types.reject { |file_type| NON_ERASABLE_FILE_TYPES.include?(file_type) }.values
where(file_type: types)
end
- scope :expired, -> (limit) { where('expire_at < ?', Time.now).limit(limit) }
+ scope :expired, ->(limit) { where("expire_at < ?", Time.now).limit(limit) }
delegate :filename, :exists?, :open, to: :file
@@ -88,13 +88,13 @@ module Ci
dast: 8, ## EE-specific
codequality: 9, ## EE-specific
license_management: 10, ## EE-specific
- performance: 11 ## EE-specific
+ performance: 11, ## EE-specific
}
enum file_format: {
raw: 1,
zip: 2,
- gzip: 3
+ gzip: 3,
}
# `file_location` indicates where actual files are stored.
@@ -108,38 +108,38 @@ module Ci
# This is the default value.
enum file_location: {
legacy_path: 1,
- hashed_path: 2
+ hashed_path: 2,
}
FILE_FORMAT_ADAPTERS = {
gzip: Gitlab::Ci::Build::Artifacts::Adapters::GzipStream,
- raw: Gitlab::Ci::Build::Artifacts::Adapters::RawStream
+ raw: Gitlab::Ci::Build::Artifacts::Adapters::RawStream,
}.freeze
def valid_file_format?
- unless TYPE_AND_FORMAT_PAIRS[self.file_type&.to_sym] == self.file_format&.to_sym
- errors.add(:file_format, 'Invalid file format with specified file type')
+ unless TYPE_AND_FORMAT_PAIRS[file_type&.to_sym] == file_format&.to_sym
+ errors.add(:file_format, "Invalid file format with specified file type")
end
end
def update_file_store
# The file.object_store is set during `uploader.store!`
# which happens after object is inserted/updated
- self.update_column(:file_store, file.object_store)
+ update_column(:file_store, file.object_store)
end
def self.artifacts_size_for(project)
- self.where(project: project).sum(:size)
+ where(project: project).sum(:size)
end
def local_store?
- [nil, ::JobArtifactUploader::Store::LOCAL].include?(self.file_store)
+ [nil, ::JobArtifactUploader::Store::LOCAL].include?(file_store)
end
def hashed_path?
return true if trace? # ArchiveLegacyTraces background migration might not have `file_location` column
- super || self.file_location.nil?
+ super || file_location.nil?
end
def expire_in
@@ -155,7 +155,7 @@ module Ci
def each_blob(&blk)
unless file_format_adapter_class
- raise NotSupportedAdapterError, 'This file format requires a dedicated adapter'
+ raise NotSupportedAdapterError, "This file format requires a dedicated adapter"
end
file.open do |stream|
@@ -178,7 +178,7 @@ module Ci
end
def update_project_statistics_after_destroy
- update_project_statistics(-self.size.to_i)
+ update_project_statistics(-size.to_i)
end
def update_project_statistics(difference)
diff --git a/app/models/ci/legacy_stage.rb b/app/models/ci/legacy_stage.rb
index 96dbc7b6895..d81c473e7be 100644
--- a/app/models/ci/legacy_stage.rb
+++ b/app/models/ci/legacy_stage.rb
@@ -48,7 +48,7 @@ module Ci
end
def success?
- status.to_s == 'success'
+ status.to_s == "success"
end
def has_warnings?
diff --git a/app/models/ci/pipeline.rb b/app/models/ci/pipeline.rb
index d4586219333..56c425867b9 100644
--- a/app/models/ci/pipeline.rb
+++ b/app/models/ci/pipeline.rb
@@ -19,21 +19,21 @@ module Ci
belongs_to :project, inverse_of: :all_pipelines
belongs_to :user
- belongs_to :auto_canceled_by, class_name: 'Ci::Pipeline'
- belongs_to :pipeline_schedule, class_name: 'Ci::PipelineSchedule'
- belongs_to :merge_request, class_name: 'MergeRequest'
+ belongs_to :auto_canceled_by, class_name: "Ci::Pipeline"
+ belongs_to :pipeline_schedule, class_name: "Ci::PipelineSchedule"
+ belongs_to :merge_request, class_name: "MergeRequest"
has_internal_id :iid, scope: :project, presence: false, init: ->(s) do
s&.project&.all_pipelines&.maximum(:iid) || s&.project&.all_pipelines&.count
end
has_many :stages, -> { order(position: :asc) }, inverse_of: :pipeline
- has_many :statuses, class_name: 'CommitStatus', foreign_key: :commit_id, inverse_of: :pipeline
+ has_many :statuses, class_name: "CommitStatus", foreign_key: :commit_id, inverse_of: :pipeline
has_many :processables, -> { processables },
- class_name: 'CommitStatus', foreign_key: :commit_id, inverse_of: :pipeline
+ class_name: "CommitStatus", foreign_key: :commit_id, inverse_of: :pipeline
has_many :builds, foreign_key: :commit_id, inverse_of: :pipeline
has_many :trigger_requests, dependent: :destroy, foreign_key: :commit_id # rubocop:disable Cop/ActiveRecordDependent
- has_many :variables, class_name: 'Ci::PipelineVariable'
+ has_many :variables, class_name: "Ci::PipelineVariable"
has_many :deployments, through: :builds
has_many :environments, -> { distinct }, through: :deployments
@@ -41,31 +41,31 @@ module Ci
# the merge request's latest commit.
has_many :merge_requests, foreign_key: "head_pipeline_id"
- has_many :pending_builds, -> { pending }, foreign_key: :commit_id, class_name: 'Ci::Build'
- has_many :retryable_builds, -> { latest.failed_or_canceled.includes(:project) }, foreign_key: :commit_id, class_name: 'Ci::Build'
- has_many :cancelable_statuses, -> { cancelable }, foreign_key: :commit_id, class_name: 'CommitStatus'
- has_many :manual_actions, -> { latest.manual_actions.includes(:project) }, foreign_key: :commit_id, class_name: 'Ci::Build'
- has_many :scheduled_actions, -> { latest.scheduled_actions.includes(:project) }, foreign_key: :commit_id, class_name: 'Ci::Build'
- has_many :artifacts, -> { latest.with_artifacts_not_expired.includes(:project) }, foreign_key: :commit_id, class_name: 'Ci::Build'
+ has_many :pending_builds, -> { pending }, foreign_key: :commit_id, class_name: "Ci::Build"
+ has_many :retryable_builds, -> { latest.failed_or_canceled.includes(:project) }, foreign_key: :commit_id, class_name: "Ci::Build"
+ has_many :cancelable_statuses, -> { cancelable }, foreign_key: :commit_id, class_name: "CommitStatus"
+ has_many :manual_actions, -> { latest.manual_actions.includes(:project) }, foreign_key: :commit_id, class_name: "Ci::Build"
+ has_many :scheduled_actions, -> { latest.scheduled_actions.includes(:project) }, foreign_key: :commit_id, class_name: "Ci::Build"
+ has_many :artifacts, -> { latest.with_artifacts_not_expired.includes(:project) }, foreign_key: :commit_id, class_name: "Ci::Build"
- has_many :auto_canceled_pipelines, class_name: 'Ci::Pipeline', foreign_key: 'auto_canceled_by_id'
- has_many :auto_canceled_jobs, class_name: 'CommitStatus', foreign_key: 'auto_canceled_by_id'
+ has_many :auto_canceled_pipelines, class_name: "Ci::Pipeline", foreign_key: "auto_canceled_by_id"
+ has_many :auto_canceled_jobs, class_name: "CommitStatus", foreign_key: "auto_canceled_by_id"
- has_one :chat_data, class_name: 'Ci::PipelineChatData'
+ has_one :chat_data, class_name: "Ci::PipelineChatData"
accepts_nested_attributes_for :variables, reject_if: :persisted?
delegate :id, to: :project, prefix: true
delegate :full_path, to: :project, prefix: true
- validates :sha, presence: { unless: :importing? }
- validates :ref, presence: { unless: :importing? }
- validates :merge_request, presence: { if: :merge_request? }
- validates :merge_request, absence: { unless: :merge_request? }
- validates :tag, inclusion: { in: [false], if: :merge_request? }
- validates :status, presence: { unless: :importing? }
+ validates :sha, presence: {unless: :importing?}
+ validates :ref, presence: {unless: :importing?}
+ validates :merge_request, presence: {if: :merge_request?}
+ validates :merge_request, absence: {unless: :merge_request?}
+ validates :tag, inclusion: {in: [false], if: :merge_request?}
+ validates :status, presence: {unless: :importing?}
validate :valid_commit_sha, unless: :importing?
- validates :source, exclusion: { in: %w(unknown), unless: :importing? }, on: :create
+ validates :source, exclusion: {in: %w[unknown], unless: :importing?}, on: :create
after_create :keep_around_commits, unless: :importing?
@@ -178,15 +178,15 @@ module Ci
scope :ci_sources, -> { where(config_source: ci_sources_values) }
scope :sort_by_merge_request_pipelines, -> do
- sql = 'CASE ci_pipelines.source WHEN (?) THEN 0 ELSE 1 END, ci_pipelines.id DESC'
+ sql = "CASE ci_pipelines.source WHEN (?) THEN 0 ELSE 1 END, ci_pipelines.id DESC"
query = ActiveRecord::Base.send(:sanitize_sql_array, [sql, sources[:merge_request]]) # rubocop:disable GitlabSecurity/PublicSend
order(query)
end
- scope :for_user, -> (user) { where(user: user) }
+ scope :for_user, ->(user) { where(user: user) }
- scope :for_merge_request, -> (merge_request, ref, sha) do
+ scope :for_merge_request, ->(merge_request, ref, sha) do
##
# We have to filter out unrelated MR pipelines.
# When merge request is empty, it selects general pipelines, such as push sourced pipelines.
@@ -195,19 +195,19 @@ module Ci
.sort_by_merge_request_pipelines
end
- scope :triggered_by_merge_request, -> (merge_request) do
+ scope :triggered_by_merge_request, ->(merge_request) do
where(source: :merge_request, merge_request: merge_request)
end
- scope :detached_merge_request_pipelines, -> (merge_request) do
+ scope :detached_merge_request_pipelines, ->(merge_request) do
triggered_by_merge_request(merge_request).where(target_sha: nil)
end
- scope :merge_request_pipelines, -> (merge_request) do
+ scope :merge_request_pipelines, ->(merge_request) do
triggered_by_merge_request(merge_request).where.not(target_sha: nil)
end
- scope :mergeable_merge_request_pipelines, -> (merge_request) do
+ scope :mergeable_merge_request_pipelines, ->(merge_request) do
triggered_by_merge_request(merge_request).where(target_sha: merge_request.target_branch_sha)
end
@@ -283,7 +283,7 @@ module Ci
end
def self.latest_successful_ids_per_project
- success.group(:project_id).select('max(id) as id')
+ success.group(:project_id).select("max(id) as id")
end
def self.truncate_sha(sha)
@@ -337,7 +337,7 @@ module Ci
def ordered_stages
return legacy_stages unless complete?
- if Feature.enabled?('ci_pipeline_persisted_stages', default_enabled: true)
+ if Feature.enabled?("ci_pipeline_persisted_stages", default_enabled: true)
stages
else
legacy_stages
@@ -348,15 +348,15 @@ module Ci
# TODO, this needs refactoring, see gitlab-ce#26481.
stages_query = statuses
- .group('stage').select(:stage).order('max(stage_idx)')
+ .group("stage").select(:stage).order("max(stage_idx)")
- status_sql = statuses.latest.where('stage=sg.stage').status_sql
+ status_sql = statuses.latest.where("stage=sg.stage").status_sql
- warnings_sql = statuses.latest.select('COUNT(*)')
- .where('stage=sg.stage').failed_but_allowed.to_sql
+ warnings_sql = statuses.latest.select("COUNT(*)")
+ .where("stage=sg.stage").failed_but_allowed.to_sql
stages_with_statuses = CommitStatus.from(stages_query, :sg)
- .pluck('sg.stage', status_sql, "(#{warnings_sql})")
+ .pluck("sg.stage", status_sql, "(#{warnings_sql})")
stages_with_statuses.map do |stage|
Ci::LegacyStage.new(self, Hash[%i[name status warnings].zip(stage)])
@@ -364,8 +364,8 @@ module Ci
end
def valid_commit_sha
- if self.sha == Gitlab::Git::BLANK_SHA
- self.errors.add(:sha, " cant be 00000000 (branch removal)")
+ if sha == Gitlab::Git::BLANK_SHA
+ errors.add(:sha, " cant be 00000000 (branch removal)")
end
end
@@ -478,7 +478,7 @@ module Ci
def coverage
coverage_array = statuses.latest.map(&:coverage).compact
if coverage_array.size >= 1
- '%.2f' % (coverage_array.reduce(:+) / coverage_array.size)
+ "%.2f" % (coverage_array.reduce(:+) / coverage_array.size)
end
end
@@ -486,9 +486,9 @@ module Ci
return [] unless config_processor
strong_memoize(:stage_seeds) do
- seeds = config_processor.stages_attributes.map do |attributes|
+ seeds = config_processor.stages_attributes.map { |attributes|
Gitlab::Ci::Pipeline::Seed::Stage.new(self, attributes)
- end
+ }
seeds.select(&:included?)
end
@@ -533,13 +533,13 @@ module Ci
return @config_processor if defined?(@config_processor)
@config_processor ||= begin
- ::Gitlab::Ci::YamlProcessor.new(ci_yaml_file, { project: project, sha: sha, user: user })
- rescue Gitlab::Ci::YamlProcessor::ValidationError => e
- self.yaml_errors = e.message
- nil
- rescue
- self.yaml_errors = 'Undefined error'
- nil
+ ::Gitlab::Ci::YamlProcessor.new(ci_yaml_file, {project: project, sha: sha, user: user})
+ rescue Gitlab::Ci::YamlProcessor::ValidationError => e
+ self.yaml_errors = e.message
+ nil
+ rescue
+ self.yaml_errors = "Undefined error"
+ nil
end
end
@@ -547,7 +547,7 @@ module Ci
return unless repository_source? || unknown_source?
if project.ci_config_path.blank?
- '.gitlab-ci.yml'
+ ".gitlab-ci.yml"
else
project.ci_config_path
end
@@ -583,7 +583,7 @@ module Ci
notes.each do |note|
note[:id] = nil
note[:commit_id] = sha
- note[:noteable_id] = self['id']
+ note[:noteable_id] = self["id"]
note.save!
end
end
@@ -601,18 +601,18 @@ module Ci
def update_status
retry_optimistic_lock(self) do
case latest_builds_status.to_s
- when 'created' then nil
- when 'pending' then enqueue
- when 'running' then run
- when 'success' then succeed
- when 'failed' then drop
- when 'canceled' then cancel
- when 'skipped' then skip
- when 'manual' then block
- when 'scheduled' then delay
+ when "created" then nil
+ when "pending" then enqueue
+ when "running" then run
+ when "success" then succeed
+ when "failed" then drop
+ when "canceled" then cancel
+ when "skipped" then skip
+ when "manual" then block
+ when "scheduled" then delay
else
raise HasStatus::UnknownStatusError,
- "Unknown status `#{latest_builds_status}`"
+ "Unknown status `#{latest_builds_status}`"
end
end
end
@@ -629,23 +629,23 @@ module Ci
Gitlab::Ci::Variables::Collection.new.tap do |variables|
break variables unless persisted?
- variables.append(key: 'CI_PIPELINE_ID', value: id.to_s)
- variables.append(key: 'CI_PIPELINE_URL', value: Gitlab::Routing.url_helpers.project_pipeline_url(project, self))
+ variables.append(key: "CI_PIPELINE_ID", value: id.to_s)
+ variables.append(key: "CI_PIPELINE_URL", value: Gitlab::Routing.url_helpers.project_pipeline_url(project, self))
end
end
def predefined_variables
Gitlab::Ci::Variables::Collection.new.tap do |variables|
- variables.append(key: 'CI_PIPELINE_IID', value: iid.to_s)
- variables.append(key: 'CI_CONFIG_PATH', value: ci_yaml_file_path)
- variables.append(key: 'CI_PIPELINE_SOURCE', value: source.to_s)
- variables.append(key: 'CI_COMMIT_MESSAGE', value: git_commit_message.to_s)
- variables.append(key: 'CI_COMMIT_TITLE', value: git_commit_full_title.to_s)
- variables.append(key: 'CI_COMMIT_DESCRIPTION', value: git_commit_description.to_s)
+ variables.append(key: "CI_PIPELINE_IID", value: iid.to_s)
+ variables.append(key: "CI_CONFIG_PATH", value: ci_yaml_file_path)
+ variables.append(key: "CI_PIPELINE_SOURCE", value: source.to_s)
+ variables.append(key: "CI_COMMIT_MESSAGE", value: git_commit_message.to_s)
+ variables.append(key: "CI_COMMIT_TITLE", value: git_commit_full_title.to_s)
+ variables.append(key: "CI_COMMIT_DESCRIPTION", value: git_commit_description.to_s)
if merge_request? && merge_request
- variables.append(key: 'CI_MERGE_REQUEST_SOURCE_BRANCH_SHA', value: source_sha.to_s)
- variables.append(key: 'CI_MERGE_REQUEST_TARGET_BRANCH_SHA', value: target_sha.to_s)
+ variables.append(key: "CI_MERGE_REQUEST_SOURCE_BRANCH_SHA", value: source_sha.to_s)
+ variables.append(key: "CI_MERGE_REQUEST_TARGET_BRANCH_SHA", value: target_sha.to_s)
variables.concat(merge_request.predefined_variables)
end
end
@@ -762,7 +762,7 @@ module Ci
return unless project
if project.auto_devops_enabled?
- Gitlab::Template::GitlabCiYmlTemplate.find('Auto-DevOps').content
+ Gitlab::Template::GitlabCiYmlTemplate.find("Auto-DevOps").content
end
end
@@ -791,15 +791,15 @@ module Ci
end
def latest_builds_status
- return 'failed' unless yaml_errors.blank?
+ return "failed" unless yaml_errors.blank?
- statuses.latest.status || 'skipped'
+ statuses.latest.status || "skipped"
end
def keep_around_commits
return unless project
- project.repository.keep_around(self.sha, self.before_sha)
+ project.repository.keep_around(sha, before_sha)
end
end
end
diff --git a/app/models/ci/pipeline_chat_data.rb b/app/models/ci/pipeline_chat_data.rb
index 8d37500fec5..0a8c2a75980 100644
--- a/app/models/ci/pipeline_chat_data.rb
+++ b/app/models/ci/pipeline_chat_data.rb
@@ -2,7 +2,7 @@
module Ci
class PipelineChatData < ActiveRecord::Base
- self.table_name = 'ci_pipeline_chat_data'
+ self.table_name = "ci_pipeline_chat_data"
belongs_to :chat_name
diff --git a/app/models/ci/pipeline_enums.rb b/app/models/ci/pipeline_enums.rb
index 4be4fdb1ff2..da28b8d3613 100644
--- a/app/models/ci/pipeline_enums.rb
+++ b/app/models/ci/pipeline_enums.rb
@@ -7,7 +7,7 @@ module Ci
def self.failure_reasons
{
unknown_failure: 0,
- config_error: 1
+ config_error: 1,
}
end
@@ -23,7 +23,7 @@ module Ci
api: 5,
external: 6,
chat: 8,
- merge_request: 10
+ merge_request: 10,
}
end
@@ -33,7 +33,7 @@ module Ci
{
unknown_source: nil,
repository_source: 1,
- auto_devops_source: 2
+ auto_devops_source: 2,
}
end
end
diff --git a/app/models/ci/pipeline_schedule.rb b/app/models/ci/pipeline_schedule.rb
index 1c1f203bdb2..7c4f6e83bb0 100644
--- a/app/models/ci/pipeline_schedule.rb
+++ b/app/models/ci/pipeline_schedule.rb
@@ -9,14 +9,14 @@ module Ci
ignore_column :deleted_at
belongs_to :project
- belongs_to :owner, class_name: 'User'
- has_one :last_pipeline, -> { order(id: :desc) }, class_name: 'Ci::Pipeline'
+ belongs_to :owner, class_name: "User"
+ has_one :last_pipeline, -> { order(id: :desc) }, class_name: "Ci::Pipeline"
has_many :pipelines
- has_many :variables, class_name: 'Ci::PipelineScheduleVariable', validate: false
+ has_many :variables, class_name: "Ci::PipelineScheduleVariable", validate: false
- validates :cron, unless: :importing?, cron: true, presence: { unless: :importing? }
- validates :cron_timezone, cron_timezone: true, presence: { unless: :importing? }
- validates :ref, presence: { unless: :importing? }
+ validates :cron, unless: :importing?, cron: true, presence: {unless: :importing?}
+ validates :cron_timezone, cron_timezone: true, presence: {unless: :importing?}
+ validates :ref, presence: {unless: :importing?}
validates :description, presence: true
validates :variables, variable_duplicates: true
@@ -54,10 +54,11 @@ module Ci
end
def real_next_run(
- worker_cron: Settings.cron_jobs['pipeline_schedule_worker']['cron'],
- worker_time_zone: Time.zone.name)
+ worker_cron: Settings.cron_jobs["pipeline_schedule_worker"]["cron"],
+ worker_time_zone: Time.zone.name
+ )
Gitlab::Ci::CronParser.new(worker_cron, worker_time_zone)
- .next_time_from(next_run_at)
+ .next_time_from(next_run_at)
end
def job_variables
diff --git a/app/models/ci/pipeline_schedule_variable.rb b/app/models/ci/pipeline_schedule_variable.rb
index fbb9987cab2..6886876341d 100644
--- a/app/models/ci/pipeline_schedule_variable.rb
+++ b/app/models/ci/pipeline_schedule_variable.rb
@@ -9,6 +9,6 @@ module Ci
alias_attribute :secret_value, :value
- validates :key, uniqueness: { scope: :pipeline_schedule_id }
+ validates :key, uniqueness: {scope: :pipeline_schedule_id}
end
end
diff --git a/app/models/ci/pipeline_variable.rb b/app/models/ci/pipeline_variable.rb
index 08514d6af4e..0f5b6c17739 100644
--- a/app/models/ci/pipeline_variable.rb
+++ b/app/models/ci/pipeline_variable.rb
@@ -9,10 +9,10 @@ module Ci
alias_attribute :secret_value, :value
- validates :key, uniqueness: { scope: :pipeline_id }
+ validates :key, uniqueness: {scope: :pipeline_id}
def hook_attrs
- { key: key, value: value }
+ {key: key, value: value}
end
end
end
diff --git a/app/models/ci/runner.rb b/app/models/ci/runner.rb
index d82e11bbb89..efcc6e8a938 100644
--- a/app/models/ci/runner.rb
+++ b/app/models/ci/runner.rb
@@ -14,13 +14,13 @@ module Ci
enum access_level: {
not_protected: 0,
- ref_protected: 1
+ ref_protected: 1,
}
enum runner_type: {
instance_type: 1,
group_type: 2,
- project_type: 3
+ project_type: 3,
}
RUNNER_QUEUE_EXPIRY_TIME = 60.minutes
@@ -40,13 +40,13 @@ module Ci
has_many :runner_namespaces, inverse_of: :runner
has_many :groups, through: :runner_namespaces
- has_one :last_build, ->() { order('id DESC') }, class_name: 'Ci::Build'
+ has_one :last_build, -> { order("id DESC") }, class_name: "Ci::Build"
before_save :ensure_token
scope :active, -> { where(active: true) }
scope :paused, -> { where(active: false) }
- scope :online, -> { where('contacted_at > ?', contact_time_deadline) }
+ scope :online, -> { where("contacted_at > ?", contact_time_deadline) }
# The following query using negation is cheaper than using `contacted_at <= ?`
# because there are less runners online than have been created. The
# resulting query is quickly finding online ones and then uses the regular
@@ -60,23 +60,23 @@ module Ci
scope :deprecated_shared, -> { instance_type }
scope :deprecated_specific, -> { project_type.or(group_type) }
- scope :belonging_to_project, -> (project_id) {
- joins(:runner_projects).where(ci_runner_projects: { project_id: project_id })
+ scope :belonging_to_project, ->(project_id) {
+ joins(:runner_projects).where(ci_runner_projects: {project_id: project_id})
}
- scope :belonging_to_parent_group_of_project, -> (project_id) {
- project_groups = ::Group.joins(:projects).where(projects: { id: project_id })
+ scope :belonging_to_parent_group_of_project, ->(project_id) {
+ project_groups = ::Group.joins(:projects).where(projects: {id: project_id})
hierarchy_groups = Gitlab::ObjectHierarchy.new(project_groups).base_and_ancestors
- joins(:groups).where(namespaces: { id: hierarchy_groups })
+ joins(:groups).where(namespaces: {id: hierarchy_groups})
}
- scope :owned_or_instance_wide, -> (project_id) do
+ scope :owned_or_instance_wide, ->(project_id) do
from_union(
[
belonging_to_project(project_id),
belonging_to_parent_group_of_project(project_id),
- instance_type
+ instance_type,
],
remove_duplicates: false
)
@@ -115,11 +115,11 @@ module Ci
cached_attr_reader :version, :revision, :platform, :architecture, :ip_address, :contacted_at
chronic_duration_attr :maximum_timeout_human_readable, :maximum_timeout,
- error_message: 'Maximum job timeout has a value which could not be accepted'
+ error_message: "Maximum job timeout has a value which could not be accepted"
validates :maximum_timeout, allow_nil: true,
- numericality: { greater_than_or_equal_to: 600,
- message: 'needs to be at least 10 minutes' }
+ numericality: {greater_than_or_equal_to: 600,
+ message: "needs to be at least 10 minutes",}
# Searches for runners matching the given query.
#
@@ -142,7 +142,7 @@ module Ci
end
def self.order_by(order)
- if order == 'contacted_asc'
+ if order == "contacted_asc"
order_contacted_at_asc
else
order_created_at_desc
@@ -153,16 +153,16 @@ module Ci
if instance_type?
self.runner_type = :project_type
elsif group_type?
- raise ArgumentError, 'Transitioning a group runner to a project runner is not supported'
+ raise ArgumentError, "Transitioning a group runner to a project runner is not supported"
end
begin
transaction do
- self.projects << project
- self.save!
+ projects << project
+ save!
end
rescue ActiveRecord::RecordInvalid => e
- self.errors.add(:assign_to, e.message)
+ errors.add(:assign_to, e.message)
false
end
end
@@ -200,7 +200,7 @@ module Ci
end
def can_pick?(build)
- return false if self.ref_protected? && !build.protected?
+ return false if ref_protected? && !build.protected?
assignable_for?(build.project_id) && accepting_tags?(build)
end
@@ -219,9 +219,9 @@ module Ci
def predefined_variables
Gitlab::Ci::Variables::Collection.new
- .append(key: 'CI_RUNNER_ID', value: id.to_s)
- .append(key: 'CI_RUNNER_DESCRIPTION', value: description)
- .append(key: 'CI_RUNNER_TAGS', value: tag_list.to_s)
+ .append(key: "CI_RUNNER_ID", value: id.to_s)
+ .append(key: "CI_RUNNER_DESCRIPTION", value: description)
+ .append(key: "CI_RUNNER_TAGS", value: tag_list.to_s)
end
def tick_runner_queue
@@ -248,7 +248,7 @@ module Ci
cache_attributes(values)
# We save data without validation, it will always change due to `contacted_at`
- self.update_columns(values) if persist_cached_data?
+ update_columns(values) if persist_cached_data?
end
def pick_build!(build)
@@ -270,7 +270,7 @@ module Ci
end
def runner_queue_key
- "runner:build_queue:#{self.token}"
+ "runner:build_queue:#{token}"
end
def persist_cached_data?
@@ -287,35 +287,35 @@ module Ci
def tag_constraints
unless has_tags? || run_untagged?
errors.add(:tags_list,
- 'can not be empty when runner is not allowed to pick untagged jobs')
+ "can not be empty when runner is not allowed to pick untagged jobs")
end
end
def assignable_for?(project_id)
- self.class.owned_or_instance_wide(project_id).where(id: self.id).any?
+ self.class.owned_or_instance_wide(project_id).where(id: id).any?
end
def no_projects
if projects.any?
- errors.add(:runner, 'cannot have projects assigned')
+ errors.add(:runner, "cannot have projects assigned")
end
end
def no_groups
if groups.any?
- errors.add(:runner, 'cannot have groups assigned')
+ errors.add(:runner, "cannot have groups assigned")
end
end
def any_project
unless projects.any?
- errors.add(:runner, 'needs to be assigned to at least one project')
+ errors.add(:runner, "needs to be assigned to at least one project")
end
end
def exactly_one_group
unless groups.one?
- errors.add(:runner, 'needs to be assigned to exactly one group')
+ errors.add(:runner, "needs to be assigned to exactly one group")
end
end
diff --git a/app/models/ci/runner_namespace.rb b/app/models/ci/runner_namespace.rb
index 22b80b98551..ca638f0b502 100644
--- a/app/models/ci/runner_namespace.rb
+++ b/app/models/ci/runner_namespace.rb
@@ -5,9 +5,9 @@ module Ci
extend Gitlab::Ci::Model
belongs_to :runner, inverse_of: :runner_namespaces, validate: true
- belongs_to :namespace, inverse_of: :runner_namespaces, class_name: '::Namespace'
- belongs_to :group, class_name: '::Group', foreign_key: :namespace_id
+ belongs_to :namespace, inverse_of: :runner_namespaces, class_name: "::Namespace"
+ belongs_to :group, class_name: "::Group", foreign_key: :namespace_id
- validates :runner_id, uniqueness: { scope: :namespace_id }
+ validates :runner_id, uniqueness: {scope: :namespace_id}
end
end
diff --git a/app/models/ci/runner_project.rb b/app/models/ci/runner_project.rb
index 1a718d24141..8359e9af20f 100644
--- a/app/models/ci/runner_project.rb
+++ b/app/models/ci/runner_project.rb
@@ -7,6 +7,6 @@ module Ci
belongs_to :runner, inverse_of: :runner_projects
belongs_to :project, inverse_of: :runner_projects
- validates :runner_id, uniqueness: { scope: :project_id }
+ validates :runner_id, uniqueness: {scope: :project_id}
end
end
diff --git a/app/models/ci/stage.rb b/app/models/ci/stage.rb
index 0389945191e..2505aa79f2d 100644
--- a/app/models/ci/stage.rb
+++ b/app/models/ci/stage.rb
@@ -12,7 +12,7 @@ module Ci
belongs_to :project
belongs_to :pipeline
- has_many :statuses, class_name: 'CommitStatus', foreign_key: :stage_id
+ has_many :statuses, class_name: "CommitStatus", foreign_key: :stage_id
has_many :builds, foreign_key: :stage_id
has_many :bridges, foreign_key: :stage_id
@@ -24,16 +24,16 @@ module Ci
end
after_initialize do
- self.status = DEFAULT_STATUS if self.status.nil?
+ self.status = DEFAULT_STATUS if status.nil?
end
before_validation unless: :importing? do
next if position.present?
self.position = statuses.select(:stage_idx)
- .where('stage_idx IS NOT NULL')
+ .where("stage_idx IS NOT NULL")
.group(:stage_idx)
- .order('COUNT(*) DESC')
+ .order("COUNT(*) DESC")
.first&.stage_idx.to_i
end
@@ -75,18 +75,18 @@ module Ci
def update_status
retry_optimistic_lock(self) do
case statuses.latest.status
- when 'created' then nil
- when 'pending' then enqueue
- when 'running' then run
- when 'success' then succeed
- when 'failed' then drop
- when 'canceled' then cancel
- when 'manual' then block
- when 'scheduled' then delay
- when 'skipped', nil then skip
+ when "created" then nil
+ when "pending" then enqueue
+ when "running" then run
+ when "success" then succeed
+ when "failed" then drop
+ when "canceled" then cancel
+ when "manual" then block
+ when "scheduled" then delay
+ when "skipped", nil then skip
else
raise HasStatus::UnknownStatusError,
- "Unknown status `#{statuses.latest.status}`"
+ "Unknown status `#{statuses.latest.status}`"
end
end
end
diff --git a/app/models/ci/trigger.rb b/app/models/ci/trigger.rb
index 637148c4ce4..a83826fbc43 100644
--- a/app/models/ci/trigger.rb
+++ b/app/models/ci/trigger.rb
@@ -18,7 +18,7 @@ module Ci
before_validation :set_default_values
def set_default_values
- self.token = SecureRandom.hex(15) if self.token.blank?
+ self.token = SecureRandom.hex(15) if token.blank?
end
def last_trigger_request
@@ -34,11 +34,11 @@ module Ci
end
def legacy?
- self.owner_id.blank?
+ owner_id.blank?
end
def can_access_project?
- self.owner_id.blank? || Ability.allowed?(self.owner, :create_build, project)
+ owner_id.blank? || Ability.allowed?(owner, :create_build, project)
end
end
end
diff --git a/app/models/ci/trigger_request.rb b/app/models/ci/trigger_request.rb
index 0b52c690e93..d6eb4723b13 100644
--- a/app/models/ci/trigger_request.rb
+++ b/app/models/ci/trigger_request.rb
@@ -20,7 +20,7 @@ module Ci
return [] unless variables
variables.map do |key, value|
- { key: key, value: value, public: false }
+ {key: key, value: value, public: false}
end
end
end
diff --git a/app/models/ci/variable.rb b/app/models/ci/variable.rb
index 64836ea4fa4..ccc7ce6d268 100644
--- a/app/models/ci/variable.rb
+++ b/app/models/ci/variable.rb
@@ -13,7 +13,7 @@ module Ci
validates :key, uniqueness: {
scope: [:project_id, :environment_scope],
- message: "(%{value}) has already been taken"
+ message: "(%{value}) has already been taken",
}
scope :unprotected, -> { where(protected: false) }
diff --git a/app/models/clusters/applications/cert_manager.rb b/app/models/clusters/applications/cert_manager.rb
index c758577815a..edc90b372ff 100644
--- a/app/models/clusters/applications/cert_manager.rb
+++ b/app/models/clusters/applications/cert_manager.rb
@@ -3,9 +3,9 @@
module Clusters
module Applications
class CertManager < ActiveRecord::Base
- VERSION = 'v0.5.2'.freeze
+ VERSION = "v0.5.2"
- self.table_name = 'clusters_applications_cert_managers'
+ self.table_name = "clusters_applications_cert_managers"
include ::Clusters::Concerns::ApplicationCore
include ::Clusters::Concerns::ApplicationStatus
@@ -21,12 +21,12 @@ module Clusters
validates :email, presence: true
def chart
- 'stable/cert-manager'
+ "stable/cert-manager"
end
def install_command
Gitlab::Kubernetes::Helm::InstallCommand.new(
- name: 'certmanager',
+ name: "certmanager",
version: VERSION,
rbac: cluster.platform_kubernetes_rbac?,
chart: chart,
@@ -43,7 +43,7 @@ module Clusters
def cluster_issuer_file
{
- 'cluster_issuer.yaml': cluster_issuer_yaml_content
+ 'cluster_issuer.yaml': cluster_issuer_yaml_content,
}
end
@@ -56,11 +56,11 @@ module Clusters
end
def cluster_issue_overlay
- { "spec" => { "acme" => { "email" => self.email } } }
+ {"spec" => {"acme" => {"email" => email}}}
end
def cluster_issuer_file_path
- Rails.root.join('vendor', 'cert_manager', 'cluster_issuer.yaml')
+ Rails.root.join("vendor", "cert_manager", "cluster_issuer.yaml")
end
end
end
diff --git a/app/models/clusters/applications/helm.rb b/app/models/clusters/applications/helm.rb
index 423071ec024..321802c98fe 100644
--- a/app/models/clusters/applications/helm.rb
+++ b/app/models/clusters/applications/helm.rb
@@ -1,16 +1,16 @@
# frozen_string_literal: true
-require 'openssl'
+require "openssl"
module Clusters
module Applications
class Helm < ActiveRecord::Base
- self.table_name = 'clusters_applications_helm'
+ self.table_name = "clusters_applications_helm"
attr_encrypted :ca_key,
mode: :per_attribute_iv,
key: Settings.attr_encrypted_db_key_base_truncated,
- algorithm: 'aes-256-cbc'
+ algorithm: "aes-256-cbc"
include ::Clusters::Concerns::ApplicationCore
include ::Clusters::Concerns::ApplicationStatus
@@ -26,7 +26,7 @@ module Clusters
def set_initial_status
return unless not_installable?
- self.status = 'installable' if cluster&.platform_kubernetes_active?
+ self.status = "installable" if cluster&.platform_kubernetes_active?
end
def install_command
@@ -47,7 +47,7 @@ module Clusters
{
'ca.pem': ca_cert,
'cert.pem': tiller_cert.cert_string,
- 'key.pem': tiller_cert.key_string
+ 'key.pem': tiller_cert.key_string,
}
end
diff --git a/app/models/clusters/applications/ingress.rb b/app/models/clusters/applications/ingress.rb
index 7c15aaa4825..5c3aa094c17 100644
--- a/app/models/clusters/applications/ingress.rb
+++ b/app/models/clusters/applications/ingress.rb
@@ -3,9 +3,9 @@
module Clusters
module Applications
class Ingress < ActiveRecord::Base
- VERSION = '1.1.2'.freeze
+ VERSION = "1.1.2"
- self.table_name = 'clusters_applications_ingress'
+ self.table_name = "clusters_applications_ingress"
include ::Clusters::Concerns::ApplicationCore
include ::Clusters::Concerns::ApplicationStatus
@@ -17,7 +17,7 @@ module Clusters
default_value_for :version, VERSION
enum ingress_type: {
- nginx: 1
+ nginx: 1,
}
FETCH_IP_ADDRESS_DELAY = 30.seconds
@@ -26,13 +26,14 @@ module Clusters
after_transition any => [:installed] do |application|
application.run_after_commit do
ClusterWaitForIngressIpAddressWorker.perform_in(
- FETCH_IP_ADDRESS_DELAY, application.name, application.id)
+ FETCH_IP_ADDRESS_DELAY, application.name, application.id
+ )
end
end
end
def chart
- 'stable/nginx-ingress'
+ "stable/nginx-ingress"
end
def install_command
@@ -53,7 +54,7 @@ module Clusters
end
def ingress_service
- cluster.kubeclient.get_service('ingress-nginx-ingress-controller', Gitlab::Kubernetes::Helm::NAMESPACE)
+ cluster.kubeclient.get_service("ingress-nginx-ingress-controller", Gitlab::Kubernetes::Helm::NAMESPACE)
end
end
end
diff --git a/app/models/clusters/applications/jupyter.rb b/app/models/clusters/applications/jupyter.rb
index 421a923d386..82d0b35759a 100644
--- a/app/models/clusters/applications/jupyter.rb
+++ b/app/models/clusters/applications/jupyter.rb
@@ -3,16 +3,16 @@
module Clusters
module Applications
class Jupyter < ActiveRecord::Base
- VERSION = 'v0.6'.freeze
+ VERSION = "v0.6"
- self.table_name = 'clusters_applications_jupyter'
+ self.table_name = "clusters_applications_jupyter"
include ::Clusters::Concerns::ApplicationCore
include ::Clusters::Concerns::ApplicationStatus
include ::Clusters::Concerns::ApplicationVersion
include ::Clusters::Concerns::ApplicationData
- belongs_to :oauth_application, class_name: 'Doorkeeper::Application'
+ belongs_to :oauth_application, class_name: "Doorkeeper::Application"
default_value_for :version, VERSION
@@ -20,7 +20,7 @@ module Clusters
return unless not_installable?
if cluster&.application_ingress_available? && cluster.application_ingress.external_ip
- self.status = 'installable'
+ self.status = "installable"
end
end
@@ -29,7 +29,7 @@ module Clusters
end
def repository
- 'https://jupyterhub.github.io/helm-chart/'
+ "https://jupyterhub.github.io/helm-chart/"
end
def values
@@ -59,30 +59,30 @@ module Clusters
"hosts" => [hostname],
"tls" => [{
"hosts" => [hostname],
- "secretName" => "jupyter-cert"
- }]
+ "secretName" => "jupyter-cert",
+ }],
},
"hub" => {
"extraEnv" => {
- "GITLAB_HOST" => gitlab_url
+ "GITLAB_HOST" => gitlab_url,
},
- "cookieSecret" => cookie_secret
+ "cookieSecret" => cookie_secret,
},
"proxy" => {
- "secretToken" => secret_token
+ "secretToken" => secret_token,
},
"auth" => {
"gitlab" => {
"clientId" => oauth_application.uid,
"clientSecret" => oauth_application.secret,
- "callbackUrl" => callback_url
- }
+ "callbackUrl" => callback_url,
+ },
},
"singleuser" => {
"extraEnv" => {
- "GITLAB_CLUSTER_ID" => cluster.id
- }
- }
+ "GITLAB_CLUSTER_ID" => cluster.id,
+ },
+ },
}
end
diff --git a/app/models/clusters/applications/knative.rb b/app/models/clusters/applications/knative.rb
index 8d79b041b64..4ef709f3119 100644
--- a/app/models/clusters/applications/knative.rb
+++ b/app/models/clusters/applications/knative.rb
@@ -3,12 +3,12 @@
module Clusters
module Applications
class Knative < ActiveRecord::Base
- VERSION = '0.2.2'.freeze
- REPOSITORY = 'https://storage.googleapis.com/triggermesh-charts'.freeze
- METRICS_CONFIG = 'https://storage.googleapis.com/triggermesh-charts/istio-metrics.yaml'.freeze
+ VERSION = "0.2.2"
+ REPOSITORY = "https://storage.googleapis.com/triggermesh-charts"
+ METRICS_CONFIG = "https://storage.googleapis.com/triggermesh-charts/istio-metrics.yaml"
FETCH_IP_ADDRESS_DELAY = 30.seconds
- self.table_name = 'clusters_applications_knative'
+ self.table_name = "clusters_applications_knative"
include ::Clusters::Concerns::ApplicationCore
include ::Clusters::Concerns::ApplicationStatus
@@ -23,14 +23,15 @@ module Clusters
return unless not_installable?
return unless verify_cluster?
- self.status = 'installable'
+ self.status = "installable"
end
state_machine :status do
after_transition any => [:installed] do |application|
application.run_after_commit do
ClusterWaitForIngressIpAddressWorker.perform_in(
- FETCH_IP_ADDRESS_DELAY, application.name, application.id)
+ FETCH_IP_ADDRESS_DELAY, application.name, application.id
+ )
end
end
end
@@ -39,16 +40,16 @@ module Clusters
validates :hostname, presence: true, hostname: true
- scope :for_cluster, -> (cluster) { where(cluster: cluster) }
+ scope :for_cluster, ->(cluster) { where(cluster: cluster) }
after_save :clear_reactive_cache!
def chart
- 'knative/knative'
+ "knative/knative"
end
def values
- { "domain" => hostname }.to_yaml
+ {"domain" => hostname}.to_yaml
end
def install_command
@@ -81,11 +82,11 @@ module Clusters
end
def calculate_reactive_cache
- { services: read_services, pods: read_pods }
+ {services: read_services, pods: read_pods}
end
def ingress_service
- cluster.kubeclient.get_service('knative-ingressgateway', 'istio-system')
+ cluster.kubeclient.get_service("knative-ingressgateway", "istio-system")
end
def services_for(ns: namespace)
@@ -93,7 +94,7 @@ module Clusters
return [] unless ns
services.select do |service|
- service.dig('metadata', 'namespace') == ns
+ service.dig("metadata", "namespace") == ns
end
end
diff --git a/app/models/clusters/applications/prometheus.rb b/app/models/clusters/applications/prometheus.rb
index fa7ce363531..51c5c3d5c06 100644
--- a/app/models/clusters/applications/prometheus.rb
+++ b/app/models/clusters/applications/prometheus.rb
@@ -5,9 +5,9 @@ module Clusters
class Prometheus < ActiveRecord::Base
include PrometheusAdapter
- VERSION = '6.7.3'
+ VERSION = "6.7.3"
- self.table_name = 'clusters_applications_prometheus'
+ self.table_name = "clusters_applications_prometheus"
include ::Clusters::Concerns::ApplicationCore
include ::Clusters::Concerns::ApplicationStatus
@@ -19,17 +19,17 @@ module Clusters
state_machine :status do
after_transition any => [:installed] do |application|
application.cluster.projects.each do |project|
- project.find_or_initialize_service('prometheus').update(active: true)
+ project.find_or_initialize_service("prometheus").update(active: true)
end
end
end
def chart
- 'stable/prometheus'
+ "stable/prometheus"
end
def service_name
- 'prometheus-prometheus-server'
+ "prometheus-prometheus-server"
end
def service_port
@@ -68,7 +68,7 @@ module Clusters
def prometheus_client
return unless kube_client
- proxy_url = kube_client.proxy_url('service', service_name, service_port, Gitlab::Kubernetes::Helm::NAMESPACE)
+ proxy_url = kube_client.proxy_url("service", service_name, service_port, Gitlab::Kubernetes::Helm::NAMESPACE)
# ensures headers containing auth data are appended to original k8s client options
options = kube_client.rest_client.options.merge(headers: kube_client.headers)
diff --git a/app/models/clusters/applications/runner.rb b/app/models/clusters/applications/runner.rb
index 941551dadaa..a0271b5de6a 100644
--- a/app/models/clusters/applications/runner.rb
+++ b/app/models/clusters/applications/runner.rb
@@ -3,16 +3,16 @@
module Clusters
module Applications
class Runner < ActiveRecord::Base
- VERSION = '0.2.0'.freeze
+ VERSION = "0.2.0"
- self.table_name = 'clusters_applications_runners'
+ self.table_name = "clusters_applications_runners"
include ::Clusters::Concerns::ApplicationCore
include ::Clusters::Concerns::ApplicationStatus
include ::Clusters::Concerns::ApplicationVersion
include ::Clusters::Concerns::ApplicationData
- belongs_to :runner, class_name: 'Ci::Runner', foreign_key: :runner_id
+ belongs_to :runner, class_name: "Ci::Runner", foreign_key: :runner_id
delegate :project, to: :cluster
default_value_for :version, VERSION
@@ -22,7 +22,7 @@ module Clusters
end
def repository
- 'https://charts.gitlab.io'
+ "https://charts.gitlab.io"
end
def values
@@ -56,10 +56,10 @@ module Clusters
def runner_create_params
{
- name: 'kubernetes-cluster',
+ name: "kubernetes-cluster",
runner_type: :project_type,
- tag_list: %w(kubernetes cluster),
- projects: [project]
+ tag_list: %w[kubernetes cluster],
+ projects: [project],
}
end
@@ -71,7 +71,7 @@ module Clusters
{
"gitlabUrl" => gitlab_url,
"runnerToken" => ensure_runner.token,
- "runners" => { "privileged" => privileged }
+ "runners" => {"privileged" => privileged},
}
end
diff --git a/app/models/clusters/cluster.rb b/app/models/clusters/cluster.rb
index be3e6a05e1e..685575dd7b7 100644
--- a/app/models/clusters/cluster.rb
+++ b/app/models/clusters/cluster.rb
@@ -6,7 +6,7 @@ module Clusters
include Gitlab::Utils::StrongMemoize
include FromUnion
- self.table_name = 'clusters'
+ self.table_name = "clusters"
APPLICATIONS = {
Applications::Helm.application_name => Applications::Helm,
@@ -15,42 +15,42 @@ module Clusters
Applications::Prometheus.application_name => Applications::Prometheus,
Applications::Runner.application_name => Applications::Runner,
Applications::Jupyter.application_name => Applications::Jupyter,
- Applications::Knative.application_name => Applications::Knative
+ Applications::Knative.application_name => Applications::Knative,
}.freeze
- DEFAULT_ENVIRONMENT = '*'.freeze
- KUBE_INGRESS_BASE_DOMAIN = 'KUBE_INGRESS_BASE_DOMAIN'.freeze
+ DEFAULT_ENVIRONMENT = "*"
+ KUBE_INGRESS_BASE_DOMAIN = "KUBE_INGRESS_BASE_DOMAIN"
belongs_to :user
- has_many :cluster_projects, class_name: 'Clusters::Project'
- has_many :projects, through: :cluster_projects, class_name: '::Project'
- has_one :cluster_project, -> { order(id: :desc) }, class_name: 'Clusters::Project'
+ has_many :cluster_projects, class_name: "Clusters::Project"
+ has_many :projects, through: :cluster_projects, class_name: "::Project"
+ has_one :cluster_project, -> { order(id: :desc) }, class_name: "Clusters::Project"
- has_many :cluster_groups, class_name: 'Clusters::Group'
- has_many :groups, through: :cluster_groups, class_name: '::Group'
+ has_many :cluster_groups, class_name: "Clusters::Group"
+ has_many :groups, through: :cluster_groups, class_name: "::Group"
# we force autosave to happen when we save `Cluster` model
- has_one :provider_gcp, class_name: 'Clusters::Providers::Gcp', autosave: true
+ has_one :provider_gcp, class_name: "Clusters::Providers::Gcp", autosave: true
- has_one :platform_kubernetes, class_name: 'Clusters::Platforms::Kubernetes', inverse_of: :cluster, autosave: true
+ has_one :platform_kubernetes, class_name: "Clusters::Platforms::Kubernetes", inverse_of: :cluster, autosave: true
- has_one :application_helm, class_name: 'Clusters::Applications::Helm'
- has_one :application_ingress, class_name: 'Clusters::Applications::Ingress'
- has_one :application_cert_manager, class_name: 'Clusters::Applications::CertManager'
- has_one :application_prometheus, class_name: 'Clusters::Applications::Prometheus'
- has_one :application_runner, class_name: 'Clusters::Applications::Runner'
- has_one :application_jupyter, class_name: 'Clusters::Applications::Jupyter'
- has_one :application_knative, class_name: 'Clusters::Applications::Knative'
+ has_one :application_helm, class_name: "Clusters::Applications::Helm"
+ has_one :application_ingress, class_name: "Clusters::Applications::Ingress"
+ has_one :application_cert_manager, class_name: "Clusters::Applications::CertManager"
+ has_one :application_prometheus, class_name: "Clusters::Applications::Prometheus"
+ has_one :application_runner, class_name: "Clusters::Applications::Runner"
+ has_one :application_jupyter, class_name: "Clusters::Applications::Jupyter"
+ has_one :application_knative, class_name: "Clusters::Applications::Knative"
has_many :kubernetes_namespaces
- has_one :kubernetes_namespace, -> { order(id: :desc) }, class_name: 'Clusters::KubernetesNamespace'
+ has_one :kubernetes_namespace, -> { order(id: :desc) }, class_name: "Clusters::KubernetesNamespace"
accepts_nested_attributes_for :provider_gcp, update_only: true
accepts_nested_attributes_for :platform_kubernetes, update_only: true
validates :name, cluster_name: true
validates :cluster_type, presence: true
- validates :domain, allow_blank: true, hostname: { allow_numeric_hostname: true }
+ validates :domain, allow_blank: true, hostname: {allow_numeric_hostname: true}
validate :restrict_modification, on: :update
validate :no_groups, unless: :group_type?
@@ -73,30 +73,30 @@ module Clusters
enum cluster_type: {
instance_type: 1,
group_type: 2,
- project_type: 3
+ project_type: 3,
}
enum platform_type: {
- kubernetes: 1
+ kubernetes: 1,
}
enum provider_type: {
user: 0,
- gcp: 1
+ gcp: 1,
}
scope :enabled, -> { where(enabled: true) }
scope :disabled, -> { where(enabled: false) }
scope :user_provided, -> { where(provider_type: ::Clusters::Cluster.provider_types[:user]) }
scope :gcp_provided, -> { where(provider_type: ::Clusters::Cluster.provider_types[:gcp]) }
- scope :gcp_installed, -> { gcp_provided.includes(:provider_gcp).where(cluster_providers_gcp: { status: ::Clusters::Providers::Gcp.state_machines[:status].states[:created].value }) }
+ scope :gcp_installed, -> { gcp_provided.includes(:provider_gcp).where(cluster_providers_gcp: {status: ::Clusters::Providers::Gcp.state_machines[:status].states[:created].value}) }
scope :default_environment, -> { where(environment_scope: DEFAULT_ENVIRONMENT) }
- scope :missing_kubernetes_namespace, -> (kubernetes_namespaces) do
- subquery = kubernetes_namespaces.select('1').where('clusters_kubernetes_namespaces.cluster_id = clusters.id')
+ scope :missing_kubernetes_namespace, ->(kubernetes_namespaces) do
+ subquery = kubernetes_namespaces.select("1").where("clusters_kubernetes_namespaces.cluster_id = clusters.id")
- where('NOT EXISTS (?)', subquery)
+ where("NOT EXISTS (?)", subquery)
end
scope :with_knative_installed, -> { joins(:application_knative).merge(Clusters::Applications::Knative.available) }
@@ -136,7 +136,7 @@ module Clusters
application_prometheus || build_application_prometheus,
application_runner || build_application_runner,
application_jupyter || build_application_jupyter,
- application_knative || build_application_knative
+ application_knative || build_application_knative,
]
end
@@ -167,14 +167,14 @@ module Clusters
projects.first
end
end
- alias_method :project, :first_project
+ alias project first_project
def first_group
strong_memoize(:first_group) do
groups.first
end
end
- alias_method :group, :first_group
+ alias group first_group
def kubeclient
platform_kubernetes.kubeclient if kubernetes?
@@ -226,10 +226,10 @@ module Clusters
def legacy_auto_devops_domain
if project_type?
project&.auto_devops&.domain.presence ||
- project.variables.find_by(key: 'AUTO_DEVOPS_DOMAIN')&.value.presence ||
- project.group&.variables&.find_by(key: 'AUTO_DEVOPS_DOMAIN')&.value.presence
+ project.variables.find_by(key: "AUTO_DEVOPS_DOMAIN")&.value.presence ||
+ project.group&.variables&.find_by(key: "AUTO_DEVOPS_DOMAIN")&.value.presence
elsif group_type?
- group.variables.find_by(key: 'AUTO_DEVOPS_DOMAIN')&.value.presence
+ group.variables.find_by(key: "AUTO_DEVOPS_DOMAIN")&.value.presence
end
end
@@ -244,13 +244,13 @@ module Clusters
def no_groups
if groups.any?
- errors.add(:cluster, 'cannot have groups assigned')
+ errors.add(:cluster, "cannot have groups assigned")
end
end
def no_projects
if projects.any?
- errors.add(:cluster, 'cannot have projects assigned')
+ errors.add(:cluster, "cannot have projects assigned")
end
end
end
diff --git a/app/models/clusters/concerns/application_core.rb b/app/models/clusters/concerns/application_core.rb
index 683b45331f6..8f69779f1e7 100644
--- a/app/models/clusters/concerns/application_core.rb
+++ b/app/models/clusters/concerns/application_core.rb
@@ -6,7 +6,7 @@ module Clusters
extend ActiveSupport::Concern
included do
- belongs_to :cluster, class_name: 'Clusters::Cluster', foreign_key: :cluster_id
+ belongs_to :cluster, class_name: "Clusters::Cluster", foreign_key: :cluster_id
validates :cluster, presence: true
@@ -15,11 +15,11 @@ module Clusters
def set_initial_status
return unless not_installable?
- self.status = 'installable' if cluster&.application_helm_available?
+ self.status = "installable" if cluster&.application_helm_available?
end
def self.application_name
- self.to_s.demodulize.underscore
+ to_s.demodulize.underscore
end
def name
diff --git a/app/models/clusters/concerns/application_data.rb b/app/models/clusters/concerns/application_data.rb
index 52498f123ff..b6bf71ed972 100644
--- a/app/models/clusters/concerns/application_data.rb
+++ b/app/models/clusters/concerns/application_data.rb
@@ -16,7 +16,7 @@ module Clusters
def files
@files ||= begin
- files = { 'values.yaml': values }
+ files = {'values.yaml': values}
files.merge!(certificate_files) if cluster.application_helm.has_ssl?
@@ -30,7 +30,7 @@ module Clusters
{
'ca.pem': ca_cert,
'cert.pem': helm_cert.cert_string,
- 'key.pem': helm_cert.key_string
+ 'key.pem': helm_cert.key_string,
}
end
diff --git a/app/models/clusters/concerns/application_status.rb b/app/models/clusters/concerns/application_status.rb
index 1273ed83abe..7c068460aa2 100644
--- a/app/models/clusters/concerns/application_status.rb
+++ b/app/models/clusters/concerns/application_status.rb
@@ -9,8 +9,8 @@ module Clusters
scope :available, -> do
where(
status: [
- self.state_machines[:status].states[:installed].value,
- self.state_machines[:status].states[:updated].value
+ state_machines[:status].states[:installed].value,
+ state_machines[:status].states[:updated].value,
]
)
end
diff --git a/app/models/clusters/group.rb b/app/models/clusters/group.rb
index 2b08a9e47f0..8c1d46d935c 100644
--- a/app/models/clusters/group.rb
+++ b/app/models/clusters/group.rb
@@ -2,9 +2,9 @@
module Clusters
class Group < ActiveRecord::Base
- self.table_name = 'cluster_groups'
+ self.table_name = "cluster_groups"
- belongs_to :cluster, class_name: 'Clusters::Cluster'
- belongs_to :group, class_name: '::Group'
+ belongs_to :cluster, class_name: "Clusters::Cluster"
+ belongs_to :group, class_name: "::Group"
end
end
diff --git a/app/models/clusters/kubernetes_namespace.rb b/app/models/clusters/kubernetes_namespace.rb
index 73da6cb37d7..f5629a7b53d 100644
--- a/app/models/clusters/kubernetes_namespace.rb
+++ b/app/models/clusters/kubernetes_namespace.rb
@@ -4,17 +4,17 @@ module Clusters
class KubernetesNamespace < ActiveRecord::Base
include Gitlab::Kubernetes
- self.table_name = 'clusters_kubernetes_namespaces'
+ self.table_name = "clusters_kubernetes_namespaces"
- belongs_to :cluster_project, class_name: 'Clusters::Project'
- belongs_to :cluster, class_name: 'Clusters::Cluster'
- belongs_to :project, class_name: '::Project'
+ belongs_to :cluster_project, class_name: "Clusters::Project"
+ belongs_to :cluster, class_name: "Clusters::Cluster"
+ belongs_to :project, class_name: "::Project"
has_one :platform_kubernetes, through: :cluster
before_validation :set_defaults
validates :namespace, presence: true
- validates :namespace, uniqueness: { scope: :cluster_id }
+ validates :namespace, uniqueness: {scope: :cluster_id}
validates :service_account_name, presence: true
@@ -22,9 +22,9 @@ module Clusters
delegate :api_url, to: :platform_kubernetes, allow_nil: true
attr_encrypted :service_account_token,
- mode: :per_attribute_iv,
- key: Settings.attr_encrypted_db_key_base_truncated,
- algorithm: 'aes-256-cbc'
+ mode: :per_attribute_iv,
+ key: Settings.attr_encrypted_db_key_base_truncated,
+ algorithm: "aes-256-cbc"
scope :has_service_account_token, -> { where.not(encrypted_service_account_token: nil) }
@@ -35,10 +35,10 @@ module Clusters
def predefined_variables
Gitlab::Ci::Variables::Collection.new.tap do |variables|
variables
- .append(key: 'KUBE_SERVICE_ACCOUNT', value: service_account_name.to_s)
- .append(key: 'KUBE_NAMESPACE', value: namespace.to_s)
- .append(key: 'KUBE_TOKEN', value: service_account_token.to_s, public: false)
- .append(key: 'KUBECONFIG', value: kubeconfig, public: false, file: true)
+ .append(key: "KUBE_SERVICE_ACCOUNT", value: service_account_name.to_s)
+ .append(key: "KUBE_NAMESPACE", value: namespace.to_s)
+ .append(key: "KUBE_TOKEN", value: service_account_token.to_s, public: false)
+ .append(key: "KUBECONFIG", value: kubeconfig, public: false, file: true)
end
end
@@ -75,7 +75,8 @@ module Clusters
url: api_url,
namespace: namespace,
token: service_account_token,
- ca_pem: ca_pem)
+ ca_pem: ca_pem
+ )
end
end
end
diff --git a/app/models/clusters/platforms/kubernetes.rb b/app/models/clusters/platforms/kubernetes.rb
index 46d0898014e..c99aa82a559 100644
--- a/app/models/clusters/platforms/kubernetes.rb
+++ b/app/models/clusters/platforms/kubernetes.rb
@@ -8,22 +8,22 @@ module Clusters
include EnumWithNil
include AfterCommitQueue
- RESERVED_NAMESPACES = %w(gitlab-managed-apps).freeze
+ RESERVED_NAMESPACES = %w[gitlab-managed-apps].freeze
- self.table_name = 'cluster_platforms_kubernetes'
+ self.table_name = "cluster_platforms_kubernetes"
self.reactive_cache_key = ->(kubernetes) { [kubernetes.class.model_name.singular, kubernetes.id] }
- belongs_to :cluster, inverse_of: :platform_kubernetes, class_name: 'Clusters::Cluster'
+ belongs_to :cluster, inverse_of: :platform_kubernetes, class_name: "Clusters::Cluster"
attr_encrypted :password,
mode: :per_attribute_iv,
key: Settings.attr_encrypted_db_key_base_truncated,
- algorithm: 'aes-256-cbc'
+ algorithm: "aes-256-cbc"
attr_encrypted :token,
mode: :per_attribute_iv,
key: Settings.attr_encrypted_db_key_base_truncated,
- algorithm: 'aes-256-cbc'
+ algorithm: "aes-256-cbc"
before_validation :enforce_namespace_to_lower_case
before_validation :enforce_ca_whitespace_trimming
@@ -33,10 +33,10 @@ module Clusters
length: 1..63,
format: {
with: Gitlab::Regex.kubernetes_namespace_regex,
- message: Gitlab::Regex.kubernetes_namespace_regex_message
+ message: Gitlab::Regex.kubernetes_namespace_regex_message,
}
- validates :namespace, exclusion: { in: RESERVED_NAMESPACES }
+ validates :namespace, exclusion: {in: RESERVED_NAMESPACES}
validate :no_namespace, unless: :allow_user_defined_namespace?
@@ -58,12 +58,12 @@ module Clusters
delegate :allow_user_defined_namespace?, to: :cluster, allow_nil: true
delegate :kubernetes_namespace, to: :cluster
- alias_method :active?, :enabled?
+ alias active? enabled?
enum_with_nil authorization_type: {
unknown_authorization: nil,
rbac: 1,
- abac: 2
+ abac: 2,
}
default_value_for :authorization_type, :rbac
@@ -78,12 +78,12 @@ module Clusters
def predefined_variables(project:)
Gitlab::Ci::Variables::Collection.new.tap do |variables|
- variables.append(key: 'KUBE_URL', value: api_url)
+ variables.append(key: "KUBE_URL", value: api_url)
if ca_pem.present?
variables
- .append(key: 'KUBE_CA_PEM', value: ca_pem)
- .append(key: 'KUBE_CA_PEM_FILE', value: ca_pem, file: true)
+ .append(key: "KUBE_CA_PEM", value: ca_pem)
+ .append(key: "KUBE_CA_PEM_FILE", value: ca_pem, file: true)
end
if kubernetes_namespace = cluster.kubernetes_namespaces.has_service_account_token.find_by(project: project)
@@ -94,10 +94,10 @@ module Clusters
# this 'else' branch will be removed. For more information, please see
# https://gitlab.com/gitlab-org/gitlab-ce/merge_requests/22433
variables
- .append(key: 'KUBE_URL', value: api_url)
- .append(key: 'KUBE_TOKEN', value: token, public: false)
- .append(key: 'KUBE_NAMESPACE', value: actual_namespace)
- .append(key: 'KUBECONFIG', value: kubeconfig, public: false, file: true)
+ .append(key: "KUBE_URL", value: api_url)
+ .append(key: "KUBE_TOKEN", value: token, public: false)
+ .append(key: "KUBE_NAMESPACE", value: actual_namespace)
+ .append(key: "KUBECONFIG", value: kubeconfig, public: false, file: true)
end
variables.concat(cluster.predefined_variables)
@@ -122,7 +122,7 @@ module Clusters
return unless enabled? && project && !project.pending_delete?
# We may want to cache extra things in the future
- { pods: read_pods }
+ {pods: read_pods}
end
def kubeclient
@@ -136,7 +136,8 @@ module Clusters
url: api_url,
namespace: actual_namespace,
token: token,
- ca_pem: ca_pem)
+ ca_pem: ca_pem
+ )
end
def default_namespace
@@ -167,7 +168,7 @@ module Clusters
api_url,
auth_options: kubeclient_auth_options,
ssl_options: kubeclient_ssl_options,
- http_proxy_uri: ENV['http_proxy']
+ http_proxy_uri: ENV["http_proxy"]
)
end
@@ -181,7 +182,7 @@ module Clusters
end
def kubeclient_ssl_options
- opts = { verify_ssl: OpenSSL::SSL::VERIFY_PEER }
+ opts = {verify_ssl: OpenSSL::SSL::VERIFY_PEER}
if ca_pem.present?
opts[:cert_store] = OpenSSL::X509::Store.new
@@ -192,29 +193,29 @@ module Clusters
end
def kubeclient_auth_options
- { bearer_token: token }
+ {bearer_token: token}
end
def terminal_auth
{
token: token,
ca_pem: ca_pem,
- max_session_time: Gitlab::CurrentSettings.terminal_max_session_time
+ max_session_time: Gitlab::CurrentSettings.terminal_max_session_time,
}
end
def enforce_namespace_to_lower_case
- self.namespace = self.namespace&.downcase
+ self.namespace = namespace&.downcase
end
def enforce_ca_whitespace_trimming
- self.ca_pem = self.ca_pem&.strip
- self.token = self.token&.strip
+ self.ca_pem = ca_pem&.strip
+ self.token = token&.strip
end
def no_namespace
if namespace
- errors.add(:namespace, 'only allowed for project cluster')
+ errors.add(:namespace, "only allowed for project cluster")
end
end
@@ -222,7 +223,7 @@ module Clusters
return unless managed?
if api_url_changed? || token_changed? || ca_pem_changed?
- errors.add(:base, _('Cannot modify managed Kubernetes cluster'))
+ errors.add(:base, _("Cannot modify managed Kubernetes cluster"))
return false
end
diff --git a/app/models/clusters/project.rb b/app/models/clusters/project.rb
index 15092b1c9d2..8cf7d2dea82 100644
--- a/app/models/clusters/project.rb
+++ b/app/models/clusters/project.rb
@@ -2,12 +2,12 @@
module Clusters
class Project < ActiveRecord::Base
- self.table_name = 'cluster_projects'
+ self.table_name = "cluster_projects"
- belongs_to :cluster, class_name: 'Clusters::Cluster'
- belongs_to :project, class_name: '::Project'
+ belongs_to :cluster, class_name: "Clusters::Cluster"
+ belongs_to :project, class_name: "::Project"
- has_many :kubernetes_namespaces, class_name: 'Clusters::KubernetesNamespace', foreign_key: :cluster_project_id
- has_one :kubernetes_namespace, -> { order(id: :desc) }, class_name: 'Clusters::KubernetesNamespace', foreign_key: :cluster_project_id
+ has_many :kubernetes_namespaces, class_name: "Clusters::KubernetesNamespace", foreign_key: :cluster_project_id
+ has_one :kubernetes_namespace, -> { order(id: :desc) }, class_name: "Clusters::KubernetesNamespace", foreign_key: :cluster_project_id
end
end
diff --git a/app/models/clusters/providers/gcp.rb b/app/models/clusters/providers/gcp.rb
index 16b59cd9d14..500f62f874f 100644
--- a/app/models/clusters/providers/gcp.rb
+++ b/app/models/clusters/providers/gcp.rb
@@ -3,24 +3,24 @@
module Clusters
module Providers
class Gcp < ActiveRecord::Base
- self.table_name = 'cluster_providers_gcp'
+ self.table_name = "cluster_providers_gcp"
- belongs_to :cluster, inverse_of: :provider_gcp, class_name: 'Clusters::Cluster'
+ belongs_to :cluster, inverse_of: :provider_gcp, class_name: "Clusters::Cluster"
- default_value_for :zone, 'us-central1-a'
+ default_value_for :zone, "us-central1-a"
default_value_for :num_nodes, 3
- default_value_for :machine_type, 'n1-standard-2'
+ default_value_for :machine_type, "n1-standard-2"
attr_encrypted :access_token,
mode: :per_attribute_iv,
key: Settings.attr_encrypted_db_key_base_truncated,
- algorithm: 'aes-256-cbc'
+ algorithm: "aes-256-cbc"
validates :gcp_project_id,
length: 1..63,
format: {
with: Gitlab::Regex.kubernetes_namespace_regex,
- message: Gitlab::Regex.kubernetes_namespace_regex_message
+ message: Gitlab::Regex.kubernetes_namespace_regex_message,
}
validates :zone, presence: true
@@ -29,7 +29,7 @@ module Clusters
presence: true,
numericality: {
only_integer: true,
- greater_than: 0
+ greater_than: 0,
}
state_machine :status, initial: :scheduled do
@@ -57,7 +57,7 @@ module Clusters
before_transition any => [:creating] do |provider, transition|
operation_id = transition.args.first
- raise ArgumentError.new('operation_id is required') unless operation_id.present?
+ raise ArgumentError.new("operation_id is required") unless operation_id.present?
provider.operation_id = operation_id
end
diff --git a/app/models/commit.rb b/app/models/commit.rb
index f412d252e5c..38ed1d8d85e 100644
--- a/app/models/commit.rb
+++ b/app/models/commit.rb
@@ -1,4 +1,3 @@
-# coding: utf-8
# frozen_string_literal: true
class Commit
@@ -39,8 +38,8 @@ class Commit
def banzai_render_context(field)
pipeline = field == :description ? :commit_description : :single_line
- context = { pipeline: pipeline, project: self.project }
- context[:author] = self.author if self.author
+ context = {pipeline: pipeline, project: project}
+ context[:author] = author if author
context
end
@@ -51,7 +50,7 @@ class Commit
if commit.is_a?(Commit)
commit
else
- self.new(commit, project)
+ new(commit, project)
end
end
end
@@ -66,7 +65,7 @@ class Commit
return collection unless %w[asc desc].include?(sort)
collection.sort do |a, b|
- operands = [a, b].tap { |o| o.reverse! if sort == 'desc' }
+ operands = [a, b].tap { |o| o.reverse! if sort == "desc" }
attr1, attr2 = operands.first.public_send(order_by), operands.second.public_send(order_by) # rubocop:disable PublicSend
@@ -83,7 +82,7 @@ class Commit
def max_diff_options
{
max_files: DIFF_HARD_LIMIT_FILES,
- max_lines: DIFF_HARD_LIMIT_LINES
+ max_lines: DIFF_HARD_LIMIT_LINES,
}
end
@@ -97,14 +96,14 @@ class Commit
end
def lazy(project, oid)
- BatchLoader.for({ project: project, oid: oid }).batch do |items, loader|
+ BatchLoader.for({project: project, oid: oid}).batch do |items, loader|
items_by_project = items.group_by { |i| i[:project] }
items_by_project.each do |project, commit_ids|
oids = commit_ids.map { |i| i[:oid] }
project.repository.commits_by(oids: oids).each do |commit|
- loader.call({ project: commit.project, oid: commit.id }, commit) if commit
+ loader.call({project: commit.project, oid: commit.id}, commit) if commit
end
end
end
@@ -139,7 +138,7 @@ class Commit
end
def self.reference_prefix
- '@'
+ "@"
end
# Pattern used to extract commit references from text
@@ -180,7 +179,7 @@ class Commit
# Use three dots instead of the ellipsis Unicode character because
# some clients show the raw Unicode value in the merge commit.
- full_title.truncate(81, separator: ' ', omission: '...')
+ full_title.truncate(81, separator: " ", omission: "...")
end
# Returns the full commits title
@@ -214,8 +213,8 @@ class Commit
url: Gitlab::UrlBuilder.build(self),
author: {
name: author_name,
- email: author_email
- }
+ email: author_email,
+ },
}
if with_changed_files
@@ -227,7 +226,7 @@ class Commit
# Discover issues should be closed when this commit is pushed to a project's
# default branch.
- def closes_issues(current_user = self.committer)
+ def closes_issues(current_user = committer)
Gitlab::ClosingIssueExtractor.new(project, current_user).closed_by_message(safe_message)
end
@@ -261,12 +260,12 @@ class Commit
def parent
strong_memoize(:parent) do
- project.commit_by(oid: self.parent_id) if self.parent_id
+ project.commit_by(oid: parent_id) if parent_id
end
end
def notes
- project.notes.for_commit_id(self.id)
+ project.notes.for_commit_id(id)
end
def discussion_notes
@@ -295,8 +294,8 @@ class Commit
def diff_refs
Gitlab::Diff::DiffRefs.new(
- base_sha: self.parent_id || Gitlab::Git::BLANK_SHA,
- head_sha: self.sha
+ base_sha: parent_id || Gitlab::Git::BLANK_SHA,
+ head_sha: sha
)
end
@@ -349,7 +348,7 @@ class Commit
if commits_in_merge_request.present?
message_body << ""
- commits_in_merge_request.reverse.each do |commit_in_merge|
+ commits_in_merge_request.reverse_each do |commit_in_merge|
message_body << "#{commit_in_merge.short_id} #{commit_in_merge.title}"
end
end
@@ -359,7 +358,7 @@ class Commit
end
def cherry_pick_message(user)
- %Q{#{message}\n\n#{cherry_pick_description(user)}}
+ %(#{message}\n\n#{cherry_pick_description(user)})
end
def revert_description(user)
@@ -371,7 +370,7 @@ class Commit
end
def revert_message(user)
- %Q{Revert "#{title.strip}"\n\n#{revert_description(user)}}
+ %(Revert "#{title.strip}"\n\n#{revert_description(user)})
end
def reverts_commit?(commit, user)
@@ -384,9 +383,9 @@ class Commit
def merged_merge_request(current_user)
# Memoize with per-user access check
- @merged_merge_request_hash ||= Hash.new do |hash, user|
+ @merged_merge_request_hash ||= Hash.new { |hash, user|
hash[user] = merged_merge_request_no_cache(user)
- end
+ }
@merged_merge_request_hash[current_user]
end
@@ -403,7 +402,7 @@ class Commit
end
def change_type_title(user)
- merged_merge_request?(user) ? 'merge request' : 'commit'
+ merged_merge_request?(user) ? "merge request" : "commit"
end
# Get the URI type of the given path
@@ -489,7 +488,7 @@ class Commit
end
def repo_changes
- changes = { added: [], modified: [], removed: [] }
+ changes = {added: [], modified: [], removed: []}
raw_deltas.each do |diff|
if diff.deleted_file
diff --git a/app/models/commit_range.rb b/app/models/commit_range.rb
index 094747ee48d..1489a330be3 100644
--- a/app/models/commit_range.rb
+++ b/app/models/commit_range.rb
@@ -36,7 +36,7 @@ class CommitRange
STRICT_PATTERN = /\h{7,40}\.{2,3}\h{7,40}/
def self.reference_prefix
- '@'
+ "@"
end
# Pattern used to extract commit range references from text
@@ -64,7 +64,7 @@ class CommitRange
range_string = range_string.strip
- unless range_string =~ /\A#{PATTERN}\z/
+ unless /\A#{PATTERN}\z/.match?(range_string)
raise ArgumentError, "invalid CommitRange string format: #{range_string}"
end
@@ -89,15 +89,15 @@ class CommitRange
sha_from + notation + sha_to
end
- alias_method :id, :to_s
+ alias id to_s
def to_reference(from = nil, full: false)
project_reference = project.to_reference(from, full: full)
if project_reference.present?
- project_reference + self.class.reference_prefix + self.id
+ project_reference + self.class.reference_prefix + id
else
- self.id
+ id
end
end
@@ -116,11 +116,11 @@ class CommitRange
#
# See `namespace_project_compare_url`
def to_param
- { from: sha_start, to: sha_to }
+ {from: sha_start, to: sha_to}
end
def exclude_start?
- @notation == '..'
+ @notation == ".."
end
# Check if both the starting and ending commit IDs exist in a project's
@@ -148,7 +148,7 @@ class CommitRange
def sha_start
return nil unless sha_from
- exclude_start? ? sha_from + '^' : sha_from
+ exclude_start? ? sha_from + "^" : sha_from
end
def commit_start
@@ -161,6 +161,6 @@ class CommitRange
end
end
- alias_method :sha_end, :sha_to
- alias_method :commit_end, :commit_to
+ alias sha_end sha_to
+ alias commit_end commit_to
end
diff --git a/app/models/commit_status.rb b/app/models/commit_status.rb
index 7f6562b63e5..012085bebd8 100644
--- a/app/models/commit_status.rb
+++ b/app/models/commit_status.rb
@@ -7,12 +7,12 @@ class CommitStatus < ActiveRecord::Base
include Presentable
include EnumWithNil
- self.table_name = 'ci_builds'
+ self.table_name = "ci_builds"
belongs_to :user
belongs_to :project
- belongs_to :pipeline, class_name: 'Ci::Pipeline', foreign_key: :commit_id
- belongs_to :auto_canceled_by, class_name: 'Ci::Pipeline'
+ belongs_to :pipeline, class_name: "Ci::Pipeline", foreign_key: :commit_id
+ belongs_to :auto_canceled_by, class_name: "Ci::Pipeline"
delegate :commit, to: :pipeline
delegate :sha, :short_sha, to: :pipeline
@@ -40,7 +40,7 @@ class CommitStatus < ActiveRecord::Base
scope :ordered, -> { order(:name) }
scope :latest_ordered, -> { latest.ordered.includes(project: :namespace) }
scope :retried_ordered, -> { retried.ordered.includes(project: :namespace) }
- scope :after_stage, -> (index) { where('stage_idx > ?', index) }
+ scope :after_stage, ->(index) { where("stage_idx > ?", index) }
scope :processables, -> { where(type: %w[Ci::Build Ci::Bridge]) }
# We use `CommitStatusEnums.failure_reasons` here so that EE can more easily
@@ -55,7 +55,7 @@ class CommitStatus < ActiveRecord::Base
before_create unless: :importing? do
# rubocop: disable CodeReuse/ServiceClass
Ci::EnsureStageService.new(project, user).execute(self) do |stage|
- self.run_after_commit { StageUpdateWorker.perform_async(stage.id) }
+ run_after_commit { StageUpdateWorker.perform_async(stage.id) }
end
# rubocop: enable CodeReuse/ServiceClass
end
@@ -145,7 +145,7 @@ class CommitStatus < ActiveRecord::Base
end
def group_name
- name.to_s.gsub(%r{\d+[\s:/\\]+\d+\s*}, '').strip
+ name.to_s.gsub(%r{\d+[\s:/\\]+\d+\s*}, "").strip
end
def failed_but_allowed?
@@ -192,7 +192,7 @@ class CommitStatus < ActiveRecord::Base
def sortable_name
name.to_s.split(/(\d+)/).map do |v|
- v =~ /\d+/ ? v.to_i : v
+ /\d+/.match?(v) ? v.to_i : v
end
end
end
diff --git a/app/models/commit_status_enums.rb b/app/models/commit_status_enums.rb
index 152105d9429..2d2ace1521c 100644
--- a/app/models/commit_status_enums.rb
+++ b/app/models/commit_status_enums.rb
@@ -14,7 +14,7 @@ module CommitStatusEnums
runner_unsupported: 6,
stale_schedule: 7,
job_execution_timeout: 8,
- archived_failure: 9
+ archived_failure: 9,
}
end
end
diff --git a/app/models/compare.rb b/app/models/compare.rb
index f1ed84ab5a5..a448867c238 100644
--- a/app/models/compare.rb
+++ b/app/models/compare.rb
@@ -1,6 +1,6 @@
# frozen_string_literal: true
-require 'set'
+require "set"
class Compare
include Gitlab::Utils::StrongMemoize
@@ -13,7 +13,7 @@ class Compare
if compare.is_a?(Compare)
compare
else
- self.new(compare, project)
+ new(compare, project)
end
end
@@ -43,7 +43,7 @@ class Compare
::Commit.new(commit, project) if commit
end
end
- alias_method :commit, :head_commit
+ alias commit head_commit
def start_commit_sha
start_commit&.sha
@@ -74,7 +74,7 @@ class Compare
def diff_refs
Gitlab::Diff::DiffRefs.new(
- base_sha: @straight ? start_commit_sha : base_commit_sha,
+ base_sha: @straight ? start_commit_sha : base_commit_sha,
start_sha: start_commit_sha,
head_sha: head_commit_sha
)
diff --git a/app/models/concerns/atomic_internal_id.rb b/app/models/concerns/atomic_internal_id.rb
index 4e15b60ccd1..1e26abd947a 100644
--- a/app/models/concerns/atomic_internal_id.rb
+++ b/app/models/concerns/atomic_internal_id.rb
@@ -41,7 +41,7 @@ module AtomicInternalId
return value unless scope_value
- scope_attrs = { scope_value.class.table_name.singularize.to_sym => scope_value }
+ scope_attrs = {scope_value.class.table_name.singularize.to_sym => scope_value}
usage = self.class.table_name.to_sym
if value.present?
diff --git a/app/models/concerns/avatarable.rb b/app/models/concerns/avatarable.rb
index 4687ec7d166..0be3fa992fd 100644
--- a/app/models/concerns/avatarable.rb
+++ b/app/models/concerns/avatarable.rb
@@ -9,7 +9,7 @@ module Avatarable
include Gitlab::Utils::StrongMemoize
validate :avatar_type, if: ->(user) { user.avatar.present? && user.avatar_changed? }
- validates :avatar, file_size: { maximum: 200.kilobytes.to_i }, if: :avatar_changed?
+ validates :avatar, file_size: {maximum: 200.kilobytes.to_i}, if: :avatar_changed?
mount_uploader :avatar, AvatarUploader
@@ -37,24 +37,24 @@ module Avatarable
end
def avatar_type
- unless self.avatar.image?
- errors.add :avatar, "file format is not supported. Please try one of the following supported formats: #{AvatarUploader::IMAGE_EXT.join(', ')}"
+ unless avatar.image?
+ errors.add :avatar, "file format is not supported. Please try one of the following supported formats: #{AvatarUploader::IMAGE_EXT.join(", ")}"
end
end
def avatar_path(only_path: true, size: nil)
- unless self.try(:id)
+ unless try(:id)
return uncached_avatar_path(only_path: only_path, size: size)
end
# Cache this avatar path only within the request because avatars in
# object storage may be generated with time-limited, signed URLs.
- key = "#{self.class.name}:#{self.id}:#{only_path}:#{size}"
+ key = "#{self.class.name}:#{id}:#{only_path}:#{size}"
Gitlab::SafeRequestStore[key] ||= uncached_avatar_path(only_path: only_path, size: size)
end
def uncached_avatar_path(only_path: true, size: nil)
- return unless self.try(:avatar).present?
+ return unless try(:avatar).present?
asset_host = ActionController::Base.asset_host
use_asset_host = asset_host.present?
@@ -93,14 +93,14 @@ module Avatarable
def retrieve_upload_from_batch(identifier)
BatchLoader.for(identifier: identifier, model: self).batch(key: self.class) do |upload_params, loader, args|
model_class = args[:key]
- paths = upload_params.flat_map do |params|
+ paths = upload_params.flat_map { |params|
params[:model].upload_paths(params[:identifier])
- end
+ }
Upload.where(uploader: AvatarUploader.name, path: paths).find_each do |upload|
- model = model_class.instantiate('id' => upload.model_id)
+ model = model_class.instantiate("id" => upload.model_id)
- loader.call({ model: model, identifier: File.basename(upload.path) }, upload)
+ loader.call({model: model, identifier: File.basename(upload.path)}, upload)
end
end
end
diff --git a/app/models/concerns/awardable.rb b/app/models/concerns/awardable.rb
index 14bc56f0eee..96092fcfbd1 100644
--- a/app/models/concerns/awardable.rb
+++ b/app/models/concerns/awardable.rb
@@ -21,7 +21,7 @@ module Awardable
WHERE user_id = :user_id AND
#{"name = :name AND" if name.present?}
awardable_type = :awardable_type AND
- awardable_id = #{self.arel_table.name}.id
+ awardable_id = #{arel_table.name}.id
)
EOL
@@ -35,33 +35,33 @@ module Awardable
FROM award_emoji
WHERE user_id = :user_id AND
awardable_type = :awardable_type AND
- awardable_id = #{self.arel_table.name}.id
+ awardable_id = #{arel_table.name}.id
)
EOL
- where(sql, user_id: user.id, awardable_type: self.name)
+ where(sql, user_id: user.id, awardable_type: name)
end
def order_upvotes_desc
- order_votes(AwardEmoji::UPVOTE_NAME, 'DESC')
+ order_votes(AwardEmoji::UPVOTE_NAME, "DESC")
end
def order_upvotes_asc
- order_votes(AwardEmoji::UPVOTE_NAME, 'ASC')
+ order_votes(AwardEmoji::UPVOTE_NAME, "ASC")
end
def order_downvotes_desc
- order_votes(AwardEmoji::DOWNVOTE_NAME, 'DESC')
+ order_votes(AwardEmoji::DOWNVOTE_NAME, "DESC")
end
# Order votes by emoji, optional sort order param `descending` defaults to true
def order_votes(emoji_name, direction)
- awardable_table = self.arel_table
+ awardable_table = arel_table
awards_table = AwardEmoji.arel_table
join_clause = awardable_table.join(awards_table, Arel::Nodes::OuterJoin).on(
awards_table[:awardable_id].eq(awardable_table[:id]).and(
- awards_table[:awardable_type].eq(self.name).and(
+ awards_table[:awardable_type].eq(name).and(
awards_table[:name].eq(emoji_name)
)
)
@@ -100,7 +100,7 @@ module Awardable
end
def user_authored?(current_user)
- author = self.respond_to?(:author) ? self.author : self.user
+ author = respond_to?(:author) ? self.author : user
author == current_user
end
diff --git a/app/models/concerns/blob_language_from_git_attributes.rb b/app/models/concerns/blob_language_from_git_attributes.rb
index 70213d22147..45ff64d83de 100644
--- a/app/models/concerns/blob_language_from_git_attributes.rb
+++ b/app/models/concerns/blob_language_from_git_attributes.rb
@@ -8,6 +8,6 @@ module BlobLanguageFromGitAttributes
return nil unless project
repository = project.repository
- repository.gitattribute(path, 'gitlab-language')
+ repository.gitattribute(path, "gitlab-language")
end
end
diff --git a/app/models/concerns/blocks_json_serialization.rb b/app/models/concerns/blocks_json_serialization.rb
index 18c00532d78..5cbfd5e11d7 100644
--- a/app/models/concerns/blocks_json_serialization.rb
+++ b/app/models/concerns/blocks_json_serialization.rb
@@ -14,5 +14,5 @@ module BlocksJsonSerialization
"JSON serialization has been disabled on #{self.class.name}"
end
- alias_method :as_json, :to_json
+ alias as_json to_json
end
diff --git a/app/models/concerns/bulk_member_access_load.rb b/app/models/concerns/bulk_member_access_load.rb
index 041ed3755e0..384adefa838 100644
--- a/app/models/concerns/bulk_member_access_load.rb
+++ b/app/models/concerns/bulk_member_access_load.rb
@@ -9,8 +9,8 @@ module BulkMemberAccessLoad
# Determine the maximum access level for a group of resources in bulk.
#
# Returns a Hash mapping resource ID -> maximum access level.
- def max_member_access_for_resource_ids(resource_klass, resource_ids, memoization_index = self.id, &block)
- raise 'Block is mandatory' unless block_given?
+ def max_member_access_for_resource_ids(resource_klass, resource_ids, memoization_index = id, &block)
+ raise "Block is mandatory" unless block_given?
resource_ids = resource_ids.uniq
key = max_member_access_for_resource_key(resource_klass, memoization_index)
@@ -22,7 +22,7 @@ module BulkMemberAccessLoad
end
# Look up only the IDs we need
- resource_ids = resource_ids - access.keys
+ resource_ids -= access.keys
return access if resource_ids.empty?
diff --git a/app/models/concerns/cache_markdown_field.rb b/app/models/concerns/cache_markdown_field.rb
index 1a8570b80c3..191bd418c2e 100644
--- a/app/models/concerns/cache_markdown_field.rb
+++ b/app/models/concerns/cache_markdown_field.rb
@@ -51,12 +51,12 @@ module CacheMarkdownField
cached_markdown_fields.markdown_fields.include?(field)
# Always include a project key, or Banzai complains
- project = self.project if self.respond_to?(:project)
- group = self.group if self.respond_to?(:group)
+ project = self.project if respond_to?(:project)
+ group = self.group if respond_to?(:group)
context = cached_markdown_fields[field].merge(project: project, group: group)
# Banzai is less strict about authors, so don't always have an author key
- context[:author] = self.author if self.respond_to?(:author)
+ context[:author] = author if respond_to?(:author)
context[:markdown_engine] = :common_mark
@@ -66,15 +66,15 @@ module CacheMarkdownField
# Update every column in a row if any one is invalidated, as we only store
# one version per row
def refresh_markdown_cache
- options = { skip_project_check: skip_project_check? }
+ options = {skip_project_check: skip_project_check?}
- updates = cached_markdown_fields.markdown_fields.map do |markdown_field|
+ updates = cached_markdown_fields.markdown_fields.map { |markdown_field|
[
cached_markdown_fields.html_field(markdown_field),
- Banzai::Renderer.cacheless_render_field(self, markdown_field, options)
+ Banzai::Renderer.cacheless_render_field(self, markdown_field, options),
]
- end.to_h
- updates['cached_markdown_version'] = latest_cached_markdown_version
+ }.to_h
+ updates["cached_markdown_version"] = latest_cached_markdown_version
updates.each {|html_field, data| write_attribute(html_field, data) }
end
@@ -150,7 +150,7 @@ module CacheMarkdownField
def attributes
attrs = attributes_before_markdown_cache
- attrs.delete('cached_markdown_version')
+ attrs.delete("cached_markdown_version")
cached_markdown_fields.html_fields.each do |field|
attrs.delete(field)
diff --git a/app/models/concerns/cacheable_attributes.rb b/app/models/concerns/cacheable_attributes.rb
index 3d60f6924c1..ffba6e8fb92 100644
--- a/app/models/concerns/cacheable_attributes.rb
+++ b/app/models/concerns/cacheable_attributes.rb
@@ -9,7 +9,7 @@ module CacheableAttributes
class_methods do
def cache_key
- "#{name}:#{Gitlab::VERSION}:#{Rails.version}".freeze
+ "#{name}:#{Gitlab::VERSION}:#{Rails.version}"
end
# Can be overridden
diff --git a/app/models/concerns/case_sensitivity.rb b/app/models/concerns/case_sensitivity.rb
index c93b6589ee7..325ddc58bf0 100644
--- a/app/models/concerns/case_sensitivity.rb
+++ b/app/models/concerns/case_sensitivity.rb
@@ -17,7 +17,7 @@ module CaseSensitivity
criteria.where(value_in(key, value))
else
criteria.where(value_equal(key, value))
- end
+ end
end
criteria
@@ -32,9 +32,9 @@ module CaseSensitivity
end
def value_in(column, values)
- lower_values = values.map do |value|
+ lower_values = values.map { |value|
lower_value(value)
- end
+ }
lower_column(arel_table[column]).in(lower_values).to_sql
end
@@ -42,7 +42,7 @@ module CaseSensitivity
def lower_value(value)
return value if Gitlab::Database.mysql?
- Arel::Nodes::NamedFunction.new('LOWER', [Arel::Nodes.build_quoted(value)])
+ Arel::Nodes::NamedFunction.new("LOWER", [Arel::Nodes.build_quoted(value)])
end
def lower_column(column)
diff --git a/app/models/concerns/chronic_duration_attribute.rb b/app/models/concerns/chronic_duration_attribute.rb
index af4905115b1..e4fd20bc654 100644
--- a/app/models/concerns/chronic_duration_attribute.rb
+++ b/app/models/concerns/chronic_duration_attribute.rb
@@ -24,7 +24,7 @@ module ChronicDurationAttribute
end
end
- validates virtual_attribute, allow_nil: true, duration: { message: parameters[:error_message] }
+ validates virtual_attribute, allow_nil: true, duration: {message: parameters[:error_message]}
end
alias_method :chronic_duration_attr, :chronic_duration_attr_writer
diff --git a/app/models/concerns/ci/metadatable.rb b/app/models/concerns/ci/metadatable.rb
index 9eed9492b37..cb1a8ce423d 100644
--- a/app/models/concerns/ci/metadatable.rb
+++ b/app/models/concerns/ci/metadatable.rb
@@ -9,7 +9,7 @@ module Ci
extend ActiveSupport::Concern
included do
- has_one :metadata, class_name: 'Ci::BuildMetadata',
+ has_one :metadata, class_name: "Ci::BuildMetadata",
foreign_key: :build_id,
inverse_of: :build,
autosave: true
@@ -23,13 +23,13 @@ module Ci
end
def degenerated?
- self.options.blank?
+ options.blank?
end
def degenerate!
self.class.transaction do
- self.update!(options: nil, yaml_variables: nil)
- self.metadata&.destroy
+ update!(options: nil, yaml_variables: nil)
+ metadata&.destroy
end
end
diff --git a/app/models/concerns/ci/processable.rb b/app/models/concerns/ci/processable.rb
index 1c78b1413a8..f84f9f12dfe 100644
--- a/app/models/concerns/ci/processable.rb
+++ b/app/models/concerns/ci/processable.rb
@@ -17,7 +17,7 @@ module Ci
end
def when
- read_attribute(:when) || 'on_success'
+ read_attribute(:when) || "on_success"
end
def expanded_environment_name
diff --git a/app/models/concerns/deployable.rb b/app/models/concerns/deployable.rb
index bc12b06b5af..6330de41e5b 100644
--- a/app/models/concerns/deployable.rb
+++ b/app/models/concerns/deployable.rb
@@ -24,7 +24,8 @@ module Deployable
tag: tag,
sha: sha,
user: user,
- on_stop: on_stop)
+ on_stop: on_stop
+ )
end
end
end
diff --git a/app/models/concerns/deployment_platform.rb b/app/models/concerns/deployment_platform.rb
index 0107af5f8ec..5d86a7fbb27 100644
--- a/app/models/concerns/deployment_platform.rb
+++ b/app/models/concerns/deployment_platform.rb
@@ -53,12 +53,12 @@ module DeploymentPlatform
def cluster_attributes_from_service_template
{
- name: 'kubernetes-template',
+ name: "kubernetes-template",
projects: [self],
cluster_type: :project_type,
provider_type: :user,
platform_type: :kubernetes,
- platform_kubernetes_attributes: platform_kubernetes_attributes_from_service_template
+ platform_kubernetes_attributes: platform_kubernetes_attributes_from_service_template,
}
end
@@ -67,7 +67,7 @@ module DeploymentPlatform
api_url: kubernetes_service_template.api_url,
ca_pem: kubernetes_service_template.ca_pem,
token: kubernetes_service_template.token,
- namespace: kubernetes_service_template.namespace
+ namespace: kubernetes_service_template.namespace,
}
end
end
diff --git a/app/models/concerns/diff_positionable_note.rb b/app/models/concerns/diff_positionable_note.rb
index b61bf29e6ad..1cae121b024 100644
--- a/app/models/concerns/diff_positionable_note.rb
+++ b/app/models/concerns/diff_positionable_note.rb
@@ -1,4 +1,5 @@
# frozen_string_literal: true
+
module DiffPositionableNote
extend ActiveSupport::Concern
@@ -11,10 +12,14 @@ module DiffPositionableNote
serialize :change_position, Gitlab::Diff::Position # rubocop:disable Cop/ActiveRecordSerialize
end
- %i(original_position position change_position).each do |meth|
+ %i[original_position position change_position].each do |meth|
define_method "#{meth}=" do |new_position|
if new_position.is_a?(String)
- new_position = JSON.parse(new_position) rescue nil
+ new_position = begin
+ JSON.parse(new_position)
+ rescue
+ nil
+ end
end
if new_position.is_a?(Hash)
@@ -37,7 +42,7 @@ module DiffPositionableNote
end
def supported?
- for_commit? || self.noteable.has_complete_diff_refs?
+ for_commit? || noteable.has_complete_diff_refs?
end
def active?(diff_refs = nil)
@@ -46,13 +51,13 @@ module DiffPositionableNote
diff_refs ||= noteable.diff_refs
- self.position.diff_refs == diff_refs
+ position.diff_refs == diff_refs
end
def set_original_position
return unless position
- self.original_position = self.position.dup unless self.original_position&.complete?
+ self.original_position = position.dup unless original_position&.complete?
end
def update_position
@@ -63,13 +68,13 @@ module DiffPositionableNote
return unless position
tracer = Gitlab::Diff::PositionTracer.new(
- project: self.project,
- old_diff_refs: self.position.diff_refs,
- new_diff_refs: self.noteable.diff_refs,
- paths: self.position.paths
+ project: project,
+ old_diff_refs: position.diff_refs,
+ new_diff_refs: noteable.diff_refs,
+ paths: position.paths
)
- result = tracer.trace(self.position)
+ result = tracer.trace(position)
return unless result
if result[:outdated]
diff --git a/app/models/concerns/discussion_on_diff.rb b/app/models/concerns/discussion_on_diff.rb
index e4e5928f5cf..74488919b62 100644
--- a/app/models/concerns/discussion_on_diff.rb
+++ b/app/models/concerns/discussion_on_diff.rb
@@ -8,21 +8,19 @@ module DiscussionOnDiff
included do
delegate :line_code,
- :original_line_code,
- :note_diff_file,
- :diff_line,
- :active?,
- :created_at_diff?,
-
- to: :first_note
+ :original_line_code,
+ :note_diff_file,
+ :diff_line,
+ :active?,
+ :created_at_diff?,
+ to: :first_note
delegate :file_path,
- :blob,
- :highlighted_diff_lines,
- :diff_lines,
-
- to: :diff_file,
- allow_nil: true
+ :blob,
+ :highlighted_diff_lines,
+ :diff_lines,
+ to: :diff_file,
+ allow_nil: true
end
def diff_discussion?
@@ -79,8 +77,7 @@ module DiscussionOnDiff
def fetch_preloaded_diff_file
fetch_preloaded_diff =
- context_noteable &&
- context_noteable.preloads_discussion_diff_highlighting? &&
+ context_noteable&.preloads_discussion_diff_highlighting? &&
note_diff_file
context_noteable.discussions_diffs.find_by_id(note_diff_file.id) if fetch_preloaded_diff
diff --git a/app/models/concerns/each_batch.rb b/app/models/concerns/each_batch.rb
index 6314b46a7e3..3472c9dea9b 100644
--- a/app/models/concerns/each_batch.rb
+++ b/app/models/concerns/each_batch.rb
@@ -50,7 +50,7 @@ module EachBatch
def each_batch(of: 1000, column: primary_key, order_hint: nil)
unless column
raise ArgumentError,
- 'the column: argument must be set to a column name to use for ordering rows'
+ "the column: argument must be set to a column name to use for ordering rows"
end
start = except(:select)
diff --git a/app/models/concerns/expirable.rb b/app/models/concerns/expirable.rb
index 1f274487935..592f9d8fabf 100644
--- a/app/models/concerns/expirable.rb
+++ b/app/models/concerns/expirable.rb
@@ -4,7 +4,7 @@ module Expirable
extend ActiveSupport::Concern
included do
- scope :expired, -> { where('expires_at <= ?', Time.current) }
+ scope :expired, -> { where("expires_at <= ?", Time.current) }
end
def expired?
diff --git a/app/models/concerns/fast_destroy_all.rb b/app/models/concerns/fast_destroy_all.rb
index f862031bce0..e641c1237aa 100644
--- a/app/models/concerns/fast_destroy_all.rb
+++ b/app/models/concerns/fast_destroy_all.rb
@@ -34,7 +34,7 @@ module FastDestroyAll
included do
before_destroy do
- raise ForbiddenActionError, '`destroy` and `destroy_all` are forbidden. Please use `fast_destroy_all`'
+ raise ForbiddenActionError, "`destroy` and `destroy_all` are forbidden. Please use `fast_destroy_all`"
end
end
diff --git a/app/models/concerns/ghost_user.rb b/app/models/concerns/ghost_user.rb
index 15278c431fb..e7255ae710a 100644
--- a/app/models/concerns/ghost_user.rb
+++ b/app/models/concerns/ghost_user.rb
@@ -4,6 +4,6 @@ module GhostUser
extend ActiveSupport::Concern
def ghost_user?
- user && user.ghost?
+ user&.ghost?
end
end
diff --git a/app/models/concerns/group_descendant.rb b/app/models/concerns/group_descendant.rb
index 05cd4265133..68ab20f1371 100644
--- a/app/models/concerns/group_descendant.rb
+++ b/app/models/concerns/group_descendant.rb
@@ -22,12 +22,12 @@ module GroupDescendant
return [] if descendants.empty?
unless descendants.all? { |hierarchy| hierarchy.is_a?(GroupDescendant) }
- raise ArgumentError.new('element is not a hierarchy')
+ raise ArgumentError.new("element is not a hierarchy")
end
- all_hierarchies = descendants.map do |descendant|
+ all_hierarchies = descendants.map { |descendant|
descendant.hierarchy(hierarchy_top, descendants)
- end
+ }
Gitlab::Utils::MergeHash.merge(all_hierarchies)
end
@@ -48,22 +48,22 @@ module GroupDescendant
extras = {
parent: parent.inspect,
child: child.inspect,
- preloaded: preloaded.map(&:full_path)
+ preloaded: preloaded.map(&:full_path),
}
- issue_url = 'https://gitlab.com/gitlab-org/gitlab-ce/issues/40785'
+ issue_url = "https://gitlab.com/gitlab-org/gitlab-ce/issues/40785"
Gitlab::Sentry.track_exception(exception, issue_url: issue_url, extra: extras)
end
if parent.nil? && hierarchy_top.present?
- raise ArgumentError.new('specified top is not part of the tree')
+ raise ArgumentError.new("specified top is not part of the tree")
end
if parent && parent != hierarchy_top
expand_hierarchy_for_child(parent,
- { parent => hierarchy },
- hierarchy_top,
- preloaded)
+ {parent => hierarchy},
+ hierarchy_top,
+ preloaded)
else
hierarchy
end
diff --git a/app/models/concerns/has_status.rb b/app/models/concerns/has_status.rb
index 0d2be4c61ab..c8436fe74f7 100644
--- a/app/models/concerns/has_status.rb
+++ b/app/models/concerns/has_status.rb
@@ -3,16 +3,16 @@
module HasStatus
extend ActiveSupport::Concern
- DEFAULT_STATUS = 'created'.freeze
+ DEFAULT_STATUS = "created"
BLOCKED_STATUS = %w[manual scheduled].freeze
AVAILABLE_STATUSES = %w[created pending running success failed canceled skipped manual scheduled].freeze
STARTED_STATUSES = %w[running success failed skipped manual scheduled].freeze
ACTIVE_STATUSES = %w[pending running].freeze
COMPLETED_STATUSES = %w[success failed canceled skipped].freeze
ORDERED_STATUSES = %w[failed pending running manual scheduled canceled success skipped created].freeze
- STATUSES_ENUM = { created: 0, pending: 1, running: 2, success: 3,
- failed: 4, canceled: 5, skipped: 6, manual: 7,
- scheduled: 8 }.freeze
+ STATUSES_ENUM = {created: 0, pending: 1, running: 2, success: 3,
+ failed: 4, canceled: 5, skipped: 6, manual: 7,
+ scheduled: 8,}.freeze
UnknownStatusError = Class.new(StandardError)
@@ -21,16 +21,16 @@ module HasStatus
scope_relevant = respond_to?(:exclude_ignored) ? exclude_ignored : all
scope_warnings = respond_to?(:failed_but_allowed) ? failed_but_allowed : none
- 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
- scheduled = scope_relevant.scheduled.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.presence || 'false'
+ 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
+ scheduled = scope_relevant.scheduled.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.presence || "false"
"(CASE
WHEN (#{builds})=(#{skipped}) AND (#{warnings}) THEN 'success'
@@ -66,30 +66,30 @@ module HasStatus
end
included do
- validates :status, inclusion: { in: AVAILABLE_STATUSES }
+ validates :status, inclusion: {in: AVAILABLE_STATUSES}
state_machine :status, initial: :created do
- state :created, value: 'created'
- state :pending, value: 'pending'
- state :running, value: 'running'
- state :failed, value: 'failed'
- state :success, value: 'success'
- state :canceled, value: 'canceled'
- state :skipped, value: 'skipped'
- state :manual, value: 'manual'
- state :scheduled, value: 'scheduled'
+ state :created, value: "created"
+ state :pending, value: "pending"
+ state :running, value: "running"
+ state :failed, value: "failed"
+ state :success, value: "success"
+ state :canceled, value: "canceled"
+ state :skipped, value: "skipped"
+ state :manual, value: "manual"
+ state :scheduled, value: "scheduled"
end
- scope :created, -> { where(status: 'created') }
- scope :relevant, -> { where(status: AVAILABLE_STATUSES - ['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 :scheduled, -> { where(status: 'scheduled') }
+ scope :created, -> { where(status: "created") }
+ scope :relevant, -> { where(status: AVAILABLE_STATUSES - ["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 :scheduled, -> { where(status: "scheduled") }
scope :alive, -> { where(status: [:created, :pending, :running]) }
scope :created_or_pending, -> { where(status: [:created, :pending]) }
scope :running_or_pending, -> { where(status: [:running, :pending]) }
diff --git a/app/models/concerns/has_variable.rb b/app/models/concerns/has_variable.rb
index 2ec42a1029b..342b255347e 100644
--- a/app/models/concerns/has_variable.rb
+++ b/app/models/concerns/has_variable.rb
@@ -6,17 +6,17 @@ module HasVariable
included do
validates :key,
presence: true,
- length: { maximum: 255 },
- format: { with: /\A[a-zA-Z0-9_]+\z/,
- message: "can contain only letters, digits and '_'." }
+ length: {maximum: 255},
+ format: {with: /\A[a-zA-Z0-9_]+\z/,
+ message: "can contain only letters, digits and '_'.",}
scope :order_key_asc, -> { reorder(key: :asc) }
attr_encrypted :value,
- mode: :per_attribute_iv_and_salt,
- insecure_mode: true,
- key: Settings.attr_encrypted_db_key_base,
- algorithm: 'aes-256-cbc'
+ mode: :per_attribute_iv_and_salt,
+ insecure_mode: true,
+ key: Settings.attr_encrypted_db_key_base,
+ algorithm: "aes-256-cbc"
def key=(new_key)
super(new_key.to_s.strip)
@@ -24,6 +24,6 @@ module HasVariable
end
def to_runner_variable
- { key: key, value: value, public: false }
+ {key: key, value: value, public: false}
end
end
diff --git a/app/models/concerns/importable.rb b/app/models/concerns/importable.rb
index 4d2707b08ab..451bae34575 100644
--- a/app/models/concerns/importable.rb
+++ b/app/models/concerns/importable.rb
@@ -4,8 +4,8 @@ module Importable
extend ActiveSupport::Concern
attr_accessor :importing
- alias_method :importing?, :importing
+ alias importing? importing
attr_accessor :imported
- alias_method :imported?, :imported
+ alias imported? imported
end
diff --git a/app/models/concerns/issuable.rb b/app/models/concerns/issuable.rb
index 670103bc3f3..82264983cef 100644
--- a/app/models/concerns/issuable.rb
+++ b/app/models/concerns/issuable.rb
@@ -36,9 +36,9 @@ module Issuable
redact_field :description
- belongs_to :author, class_name: 'User'
- belongs_to :updated_by, class_name: 'User'
- belongs_to :last_edited_by, class_name: 'User'
+ belongs_to :author, class_name: "User"
+ belongs_to :updated_by, class_name: "User"
+ belongs_to :last_edited_by, class_name: "User"
belongs_to :milestone
has_many :notes, as: :noteable, inverse_of: :noteable, dependent: :destroy do # rubocop:disable Cop/ActiveRecordDependent
@@ -60,42 +60,42 @@ module Issuable
has_one :metrics
delegate :name,
- :email,
- :public_email,
- to: :author,
- allow_nil: true,
- prefix: true
+ :email,
+ :public_email,
+ to: :author,
+ allow_nil: true,
+ prefix: true
delegate :name,
- :email,
- :public_email,
- to: :assignee,
- allow_nil: true,
- prefix: true
+ :email,
+ :public_email,
+ to: :assignee,
+ allow_nil: true,
+ prefix: true
validates :author, presence: true
- validates :title, presence: true, length: { maximum: 255 }
+ validates :title, presence: true, length: {maximum: 255}
scope :authored, ->(user) { where(author_id: user) }
scope :recent, -> { reorder(id: :desc) }
scope :of_projects, ->(ids) { where(project_id: ids) }
scope :of_milestones, ->(ids) { where(milestone_id: ids) }
- scope :any_milestone, -> { where('milestone_id IS NOT NULL') }
- scope :with_milestone, ->(title) { left_joins_milestones.where(milestones: { title: title }) }
+ scope :any_milestone, -> { where("milestone_id IS NOT NULL") }
+ scope :with_milestone, ->(title) { left_joins_milestones.where(milestones: {title: title}) }
scope :opened, -> { with_state(:opened) }
scope :only_opened, -> { with_state(:opened) }
scope :closed, -> { with_state(:closed) }
scope :left_joins_milestones, -> { joins("LEFT OUTER JOIN milestones ON #{table_name}.milestone_id = milestones.id") }
- scope :order_milestone_due_desc, -> { left_joins_milestones.reorder('milestones.due_date IS NULL, milestones.id IS NULL, milestones.due_date DESC') }
- scope :order_milestone_due_asc, -> { left_joins_milestones.reorder('milestones.due_date IS NULL, milestones.id IS NULL, milestones.due_date ASC') }
+ scope :order_milestone_due_desc, -> { left_joins_milestones.reorder("milestones.due_date IS NULL, milestones.id IS NULL, milestones.due_date DESC") }
+ scope :order_milestone_due_asc, -> { left_joins_milestones.reorder("milestones.due_date IS NULL, milestones.id IS NULL, milestones.due_date ASC") }
- scope :without_label, -> { joins("LEFT OUTER JOIN label_links ON label_links.target_type = '#{name}' AND label_links.target_id = #{table_name}.id").where(label_links: { id: nil }) }
+ scope :without_label, -> { joins("LEFT OUTER JOIN label_links ON label_links.target_type = '#{name}' AND label_links.target_id = #{table_name}.id").where(label_links: {id: nil}) }
scope :any_label, -> { joins(:label_links).group(:id) }
scope :join_project, -> { joins(:project) }
scope :inc_notes_with_associations, -> { includes(notes: [:project, :author, :award_emoji]) }
scope :references_project, -> { references(:project) }
- scope :non_archived, -> { join_project.where(projects: { archived: false }) }
+ scope :non_archived, -> { join_project.where(projects: {archived: false}) }
attr_mentionable :title, pipeline: :single_line
attr_mentionable :description
@@ -140,9 +140,9 @@ module Issuable
# matched_columns - Modify the scope of the query. 'title', 'description' or joining them with a comma.
#
# Returns an ActiveRecord::Relation.
- def full_search(query, matched_columns: 'title,description')
+ def full_search(query, matched_columns: "title,description")
allowed_columns = [:title, :description]
- matched_columns = matched_columns.to_s.split(',').map(&:to_sym)
+ matched_columns = matched_columns.to_s.split(",").map(&:to_sym)
matched_columns &= allowed_columns
# Matching title or description if the matched_columns did not contain any allowed columns.
@@ -154,16 +154,16 @@ module Issuable
def sort_by_attribute(method, excluded_labels: [])
sorted =
case method.to_s
- when 'downvotes_desc' then order_downvotes_desc
- when 'label_priority' then order_labels_priority(excluded_labels: excluded_labels)
- when 'label_priority_desc' then order_labels_priority('DESC', excluded_labels: excluded_labels)
- when 'milestone', 'milestone_due_asc' then order_milestone_due_asc
- when 'milestone_due_desc' then order_milestone_due_desc
- when 'popularity', 'popularity_desc' then order_upvotes_desc
- when 'popularity_asc' then order_upvotes_asc
- when 'priority', 'priority_asc' then order_due_date_and_labels_priority(excluded_labels: excluded_labels)
- when 'priority_desc' then order_due_date_and_labels_priority('DESC', excluded_labels: excluded_labels)
- when 'upvotes_desc' then order_upvotes_desc
+ when "downvotes_desc" then order_downvotes_desc
+ when "label_priority" then order_labels_priority(excluded_labels: excluded_labels)
+ when "label_priority_desc" then order_labels_priority("DESC", excluded_labels: excluded_labels)
+ when "milestone", "milestone_due_asc" then order_milestone_due_asc
+ when "milestone_due_desc" then order_milestone_due_desc
+ when "popularity", "popularity_desc" then order_upvotes_desc
+ when "popularity_asc" then order_upvotes_asc
+ when "priority", "priority_asc" then order_due_date_and_labels_priority(excluded_labels: excluded_labels)
+ when "priority_desc" then order_due_date_and_labels_priority("DESC", excluded_labels: excluded_labels)
+ when "upvotes_desc" then order_upvotes_desc
else order_by(method)
end
@@ -171,7 +171,7 @@ module Issuable
sorted.with_order_id_desc
end
- def order_due_date_and_labels_priority(direction = 'ASC', excluded_labels: [])
+ def order_due_date_and_labels_priority(direction = "ASC", excluded_labels: [])
# The order_ methods also modify the query in other ways:
#
# - For milestones, we add a JOIN.
@@ -184,39 +184,39 @@ module Issuable
# 2. We can't ORDER BY a column that isn't in the GROUP BY and doesn't
# have an aggregate function applied, so we do a useless MIN() instead.
#
- milestones_due_date = 'MIN(milestones.due_date)'
+ milestones_due_date = "MIN(milestones.due_date)"
order_milestone_due_asc
.order_labels_priority(excluded_labels: excluded_labels, extra_select_columns: [milestones_due_date])
.reorder(Gitlab::Database.nulls_last_order(milestones_due_date, direction),
- Gitlab::Database.nulls_last_order('highest_priority', direction))
+ Gitlab::Database.nulls_last_order("highest_priority", direction))
end
- def order_labels_priority(direction = 'ASC', excluded_labels: [], extra_select_columns: [])
+ def order_labels_priority(direction = "ASC", excluded_labels: [], extra_select_columns: [])
params = {
target_type: name,
target_column: "#{table_name}.id",
project_column: "#{table_name}.#{project_foreign_key}",
- excluded_labels: excluded_labels
+ excluded_labels: excluded_labels,
}
highest_priority = highest_label_priority(params).to_sql
select_columns = [
"#{table_name}.*",
- "(#{highest_priority}) AS highest_priority"
+ "(#{highest_priority}) AS highest_priority",
] + extra_select_columns
- select(select_columns.join(', '))
+ select(select_columns.join(", "))
.group(arel_table[:id])
- .reorder(Gitlab::Database.nulls_last_order('highest_priority', direction))
+ .reorder(Gitlab::Database.nulls_last_order("highest_priority", direction))
end
def with_label(title, sort = nil)
if title.is_a?(Array) && title.size > 1
- joins(:labels).where(labels: { title: title }).group(*grouping_columns(sort)).having("COUNT(DISTINCT labels.title) = #{title.size}")
+ joins(:labels).where(labels: {title: title}).group(*grouping_columns(sort)).having("COUNT(DISTINCT labels.title) = #{title.size}")
else
- joins(:labels).where(labels: { title: title })
+ joins(:labels).where(labels: {title: title})
end
end
@@ -227,7 +227,7 @@ module Issuable
def grouping_columns(sort)
grouping_columns = [arel_table[:id]]
- if %w(milestone_due_desc milestone_due_asc milestone).include?(sort)
+ if %w[milestone_due_desc milestone_due_asc milestone].include?(sort)
milestone_table = Milestone.arel_table
grouping_columns << milestone_table[:id]
grouping_columns << milestone_table[:due_date]
@@ -289,14 +289,14 @@ module Issuable
end
if old_assignees != assignees
- if self.is_a?(Issue)
+ if is_a?(Issue)
changes[:assignees] = [old_assignees.map(&:hook_attrs), assignees.map(&:hook_attrs)]
else
changes[:assignee] = [old_assignees&.first&.hook_attrs, assignee&.hook_attrs]
end
end
- if self.respond_to?(:total_time_spent)
+ if respond_to?(:total_time_spent)
old_total_time_spent = old_associations.fetch(:total_time_spent, nil)
if old_total_time_spent != total_time_spent
@@ -313,7 +313,7 @@ module Issuable
end
def label_names
- labels.order('title ASC').pluck(:title)
+ labels.order("title ASC").pluck(:title)
end
# Convert this Issuable class name to a format usable by Ability definitions
@@ -329,8 +329,8 @@ module Issuable
# Returns a Hash of attributes to be used for Twitter card metadata
def card_attributes
{
- 'Author' => author.try(:name),
- 'Assignee' => assignee.try(:name)
+ "Author" => author.try(:name),
+ "Assignee" => assignee.try(:name),
}
end
@@ -353,7 +353,7 @@ module Issuable
end
def updated_tasks
- Taskable.get_updated_tasks(old_content: previous_changes['description'].first,
+ Taskable.get_updated_tasks(old_content: previous_changes["description"].first,
new_content: description)
end
@@ -374,7 +374,7 @@ module Issuable
end
def ensure_metrics
- self.metrics || create_metrics
+ metrics || create_metrics
end
##
diff --git a/app/models/concerns/loaded_in_group_list.rb b/app/models/concerns/loaded_in_group_list.rb
index fc15c6d55ed..143ff09b88d 100644
--- a/app/models/concerns/loaded_in_group_list.rb
+++ b/app/models/concerns/loaded_in_group_list.rb
@@ -6,10 +6,10 @@ module LoadedInGroupList
class_methods do
def with_counts(archived:)
selects_including_counts = [
- 'namespaces.*',
+ "namespaces.*",
"(#{project_count_sql(archived).to_sql}) AS preloaded_project_count",
"(#{member_count_sql.to_sql}) AS preloaded_member_count",
- "(#{subgroup_count_sql.to_sql}) AS preloaded_subgroup_count"
+ "(#{subgroup_count_sql.to_sql}) AS preloaded_subgroup_count",
]
select(selects_including_counts)
@@ -25,10 +25,10 @@ module LoadedInGroupList
projects = Project.arel_table
namespaces = Namespace.arel_table
- base_count = projects.project(Arel.star.count.as('preloaded_project_count'))
- .where(projects[:namespace_id].eq(namespaces[:id]))
+ base_count = projects.project(Arel.star.count.as("preloaded_project_count"))
+ .where(projects[:namespace_id].eq(namespaces[:id]))
- if archived == 'only'
+ if archived == "only"
base_count.where(projects[:archived].eq(true))
elsif Gitlab::Utils.to_boolean(archived)
base_count
@@ -39,9 +39,9 @@ module LoadedInGroupList
def subgroup_count_sql
namespaces = Namespace.arel_table
- children = namespaces.alias('children')
+ children = namespaces.alias("children")
- namespaces.project(Arel.star.count.as('preloaded_subgroup_count'))
+ namespaces.project(Arel.star.count.as("preloaded_subgroup_count"))
.from(children)
.where(children[:parent_id].eq(namespaces[:id]))
end
@@ -50,7 +50,7 @@ module LoadedInGroupList
members = Member.arel_table
namespaces = Namespace.arel_table
- members.project(Arel.star.count.as('preloaded_member_count'))
+ members.project(Arel.star.count.as("preloaded_member_count"))
.where(members[:source_type].eq(Namespace.name))
.where(members[:source_id].eq(namespaces[:id]))
.where(members[:requested_at].eq(nil))
diff --git a/app/models/concerns/maskable.rb b/app/models/concerns/maskable.rb
index 8793f0ec965..311847411a9 100644
--- a/app/models/concerns/maskable.rb
+++ b/app/models/concerns/maskable.rb
@@ -12,8 +12,8 @@ module Maskable
REGEX = /\A\w{8,}\z/
included do
- validates :masked, inclusion: { in: [true, false] }
- validates :value, format: { with: REGEX }, if: :masked?
+ validates :masked, inclusion: {in: [true, false]}
+ validates :value, format: {with: REGEX}, if: :masked?
end
def to_runner_variable
diff --git a/app/models/concerns/mentionable.rb b/app/models/concerns/mentionable.rb
index 0d88b34fb48..cc6891d74d9 100644
--- a/app/models/concerns/mentionable.rb
+++ b/app/models/concerns/mentionable.rb
@@ -25,7 +25,7 @@ module Mentionable
end
if self < Participable
- participant -> (user, ext) { all_references(user, extractor: ext) }
+ participant ->(user, ext) { all_references(user, extractor: ext) }
end
end
@@ -82,7 +82,7 @@ module Mentionable
end
# Extract GFM references to other Mentionables from this Mentionable. Always excludes its #local_reference.
- def referenced_mentionables(current_user = self.author)
+ def referenced_mentionables(current_user = author)
return [] unless matches_cross_reference_regex?
refs = all_references(current_user)
@@ -97,10 +97,10 @@ module Mentionable
# Allows heavy processing to be skipped
def matches_cross_reference_regex?
reference_pattern = if !project || project.default_issues_tracker?
- ReferenceRegexes.default_pattern
- else
- ReferenceRegexes.external_pattern
- end
+ ReferenceRegexes.default_pattern
+ else
+ ReferenceRegexes.external_pattern
+ end
self.class.mentionable_attrs.any? do |attr, _|
__send__(attr) =~ reference_pattern # rubocop:disable GitlabSecurity/PublicSend
diff --git a/app/models/concerns/mentionable/reference_regexes.rb b/app/models/concerns/mentionable/reference_regexes.rb
index b8fb3f71925..ffb4f8233c8 100644
--- a/app/models/concerns/mentionable/reference_regexes.rb
+++ b/app/models/concerns/mentionable/reference_regexes.rb
@@ -6,14 +6,14 @@ module Mentionable
def self.reference_pattern(link_patterns, issue_pattern)
Regexp.union(link_patterns,
- issue_pattern,
- *other_patterns)
+ issue_pattern,
+ *other_patterns)
end
def self.other_patterns
[
Commit.reference_pattern,
- MergeRequest.reference_pattern
+ MergeRequest.reference_pattern,
]
end
@@ -28,7 +28,7 @@ module Mentionable
def self.external_pattern
strong_memoize(:external_pattern) do
issue_pattern = IssueTrackerService.reference_pattern
- link_patterns = URI.regexp(%w(http https))
+ link_patterns = URI.regexp(%w[http https])
reference_pattern(link_patterns, issue_pattern)
end
end
diff --git a/app/models/concerns/milestoneish.rb b/app/models/concerns/milestoneish.rb
index 055ffe04646..05aa8ba098e 100644
--- a/app/models/concerns/milestoneish.rb
+++ b/app/models/concerns/milestoneish.rb
@@ -3,7 +3,7 @@
module Milestoneish
def closed_items_count(user)
memoize_per_user(user, :closed_items_count) do
- (count_issues_by_state(user)['closed'] || 0) + merge_requests.closed_and_merged.size
+ (count_issues_by_state(user)["closed"] || 0) + merge_requests.closed_and_merged.size
end
end
@@ -47,15 +47,15 @@ module Milestoneish
end
def sorted_issues(user)
- issues_visible_to_user(user).preload_associations.sort_by_attribute('label_priority')
+ issues_visible_to_user(user).preload_associations.sort_by_attribute("label_priority")
end
def sorted_merge_requests
- merge_requests.sort_by_attribute('label_priority')
+ merge_requests.sort_by_attribute("label_priority")
end
def upcoming?
- start_date && start_date.future?
+ start_date&.future?
end
def expires_at
@@ -69,7 +69,7 @@ module Milestoneish
end
def expired?
- due_date && due_date.past?
+ due_date&.past?
end
def group_milestone?
diff --git a/app/models/concerns/mirror_authentication.rb b/app/models/concerns/mirror_authentication.rb
index e3e1a0441f8..a2a7e1bf862 100644
--- a/app/models/concerns/mirror_authentication.rb
+++ b/app/models/concerns/mirror_authentication.rb
@@ -5,18 +5,18 @@
# serialized attribute. It also needs an `url` method to be defined
module MirrorAuthentication
SSH_PRIVATE_KEY_OPTS = {
- type: 'RSA',
- bits: 4096
+ type: "RSA",
+ bits: 4096,
}.freeze
extend ActiveSupport::Concern
included do
- validates :auth_method, inclusion: { in: %w[password ssh_public_key] }, allow_blank: true
+ validates :auth_method, inclusion: {in: %w[password ssh_public_key]}, allow_blank: true
# We should generate a key even if there's no SSH URL present
before_validation :generate_ssh_private_key!, if: -> {
- regenerate_ssh_private_key || ( auth_method == 'ssh_public_key' && ssh_private_key.blank? )
+ regenerate_ssh_private_key || (auth_method == "ssh_public_key" && ssh_private_key.blank?)
}
credentials_field :auth_method, reader: false
@@ -53,15 +53,15 @@ module MirrorAuthentication
attr_accessor :regenerate_ssh_private_key
def ssh_key_auth?
- ssh_mirror_url? && auth_method == 'ssh_public_key'
+ ssh_mirror_url? && auth_method == "ssh_public_key"
end
def password_auth?
- auth_method == 'password'
+ auth_method == "password"
end
def ssh_mirror_url?
- url&.start_with?('ssh://')
+ url&.start_with?("ssh://")
end
def ssh_known_hosts_verified_by
@@ -75,7 +75,7 @@ module MirrorAuthentication
def auth_method
auth_method = credentials.fetch(:auth_method, nil) if credentials.present?
- auth_method.presence || 'password'
+ auth_method.presence || "password"
end
def ssh_public_key
diff --git a/app/models/concerns/noteable.rb b/app/models/concerns/noteable.rb
index 3c74034b527..0d8b6d15980 100644
--- a/app/models/concerns/noteable.rb
+++ b/app/models/concerns/noteable.rb
@@ -4,12 +4,12 @@ module Noteable
extend ActiveSupport::Concern
# `Noteable` class names that support resolvable notes.
- RESOLVABLE_TYPES = %w(MergeRequest).freeze
+ RESOLVABLE_TYPES = %w[MergeRequest].freeze
class_methods do
# `Noteable` class names that support replying to individual notes.
def replyable_types
- %w(Issue MergeRequest)
+ %w[Issue MergeRequest]
end
end
diff --git a/app/models/concerns/participable.rb b/app/models/concerns/participable.rb
index 614c3242874..b78b3329673 100644
--- a/app/models/concerns/participable.rb
+++ b/app/models/concerns/participable.rb
@@ -64,9 +64,9 @@ module Participable
private
def all_participants
- @all_participants ||= Hash.new do |hash, user|
+ @all_participants ||= Hash.new { |hash, user|
hash[user] = raw_participants(user)
- end
+ }
end
def raw_participants(current_user = nil)
diff --git a/app/models/concerns/project_features_compatibility.rb b/app/models/concerns/project_features_compatibility.rb
index f268a842db4..19c830fe569 100644
--- a/app/models/concerns/project_features_compatibility.rb
+++ b/app/models/concerns/project_features_compatibility.rb
@@ -4,7 +4,7 @@
#
# After migrating issues_enabled merge_requests_enabled builds_enabled snippets_enabled and wiki_enabled
# fields to a new table "project_features", support for the old fields is still needed in the API.
-require 'gitlab/utils'
+require "gitlab/utils"
module ProjectFeaturesCompatibility
extend ActiveSupport::Concern
diff --git a/app/models/concerns/project_services_loggable.rb b/app/models/concerns/project_services_loggable.rb
index fecd77cdc98..af1a2d4a99e 100644
--- a/app/models/concerns/project_services_loggable.rb
+++ b/app/models/concerns/project_services_loggable.rb
@@ -18,7 +18,7 @@ module ProjectServicesLoggable
service_class: self.class.name,
project_id: project.id,
project_path: project.full_path,
- message: message
+ message: message,
}.merge(params)
end
diff --git a/app/models/concerns/prometheus_adapter.rb b/app/models/concerns/prometheus_adapter.rb
index a29e80fe0c1..86bc522c418 100644
--- a/app/models/concerns/prometheus_adapter.rb
+++ b/app/models/concerns/prometheus_adapter.rb
@@ -40,10 +40,10 @@ module PrometheusAdapter
{
success: true,
data: data,
- last_update: Time.now.utc
+ last_update: Time.now.utc,
}
rescue Gitlab::PrometheusClient::Error => err
- { success: false, result: err.message }
+ {success: false, result: err.message}
end
def query_klass_for(query_name)
diff --git a/app/models/concerns/protected_ref.rb b/app/models/concerns/protected_ref.rb
index af387c99f3d..26adb6cfc44 100644
--- a/app/models/concerns/protected_ref.rb
+++ b/app/models/concerns/protected_ref.rb
@@ -13,7 +13,7 @@ module ProtectedRef
end
def commit
- project.commit(self.name)
+ project.commit(name)
end
class_methods do
@@ -25,9 +25,9 @@ module ProtectedRef
# If we don't `protected_branch` or `protected_tag` would be empty and
# `project` cannot be delegated to it, which in turn would cause validations
# to fail.
- has_many :"#{type}_access_levels", inverse_of: self.model_name.singular
+ has_many :"#{type}_access_levels", inverse_of: model_name.singular
- validates :"#{type}_access_levels", length: { is: 1, message: "are restricted to a single instance per #{self.model_name.human}." }
+ validates :"#{type}_access_levels", length: {is: 1, message: "are restricted to a single instance per #{model_name.human}."}
accepts_nested_attributes_for :"#{type}_access_levels", allow_destroy: true
end
@@ -46,7 +46,7 @@ module ProtectedRef
end
def access_levels_for_ref(ref, action:, protected_refs: nil)
- self.matching(ref, protected_refs: protected_refs)
+ matching(ref, protected_refs: protected_refs)
.map(&:"#{action}_access_levels").flatten
end
@@ -57,13 +57,13 @@ module ProtectedRef
# This method optionally takes in a list of `protected_refs` to search
# through, to avoid calling out to the database.
def matching(ref_name, protected_refs: nil)
- (protected_refs || self.all).select { |protected_ref| protected_ref.matches?(ref_name) }
+ (protected_refs || all).select { |protected_ref| protected_ref.matches?(ref_name) }
end
end
private
def ref_matcher
- @ref_matcher ||= RefMatcher.new(self.name)
+ @ref_matcher ||= RefMatcher.new(name)
end
end
diff --git a/app/models/concerns/protected_ref_access.rb b/app/models/concerns/protected_ref_access.rb
index 583751ea6ac..60e0ab45f11 100644
--- a/app/models/concerns/protected_ref_access.rb
+++ b/app/models/concerns/protected_ref_access.rb
@@ -4,9 +4,9 @@ module ProtectedRefAccess
extend ActiveSupport::Concern
HUMAN_ACCESS_LEVELS = {
- Gitlab::Access::MAINTAINER => "Maintainers".freeze,
- Gitlab::Access::DEVELOPER => "Developers + Maintainers".freeze,
- Gitlab::Access::NO_ACCESS => "No one".freeze
+ Gitlab::Access::MAINTAINER => "Maintainers",
+ Gitlab::Access::DEVELOPER => "Developers + Maintainers",
+ Gitlab::Access::NO_ACCESS => "No one",
}.freeze
class_methods do
@@ -14,7 +14,7 @@ module ProtectedRefAccess
[
Gitlab::Access::MAINTAINER,
Gitlab::Access::DEVELOPER,
- Gitlab::Access::NO_ACCESS
+ Gitlab::Access::NO_ACCESS,
]
end
end
@@ -23,19 +23,19 @@ module ProtectedRefAccess
scope :master, -> { maintainer } # @deprecated
scope :maintainer, -> { where(access_level: Gitlab::Access::MAINTAINER) }
scope :developer, -> { where(access_level: Gitlab::Access::DEVELOPER) }
- scope :by_user, -> (user) { where(user_id: user ) }
- scope :by_group, -> (group) { where(group_id: group ) }
+ scope :by_user, ->(user) { where(user_id: user) }
+ scope :by_group, ->(group) { where(group_id: group) }
scope :for_role, -> { where(user_id: nil, group_id: nil) }
scope :for_user, -> { where.not(user_id: nil) }
scope :for_group, -> { where.not(group_id: nil) }
validates :access_level, presence: true, if: :role?, inclusion: {
- in: self.allowed_access_levels
+ in: allowed_access_levels,
}
end
def humanize
- HUMAN_ACCESS_LEVELS[self.access_level]
+ HUMAN_ACCESS_LEVELS[access_level]
end
# CE access levels are always role-based,
diff --git a/app/models/concerns/reactive_caching.rb b/app/models/concerns/reactive_caching.rb
index de77ca3e963..bc686828aa2 100644
--- a/app/models/concerns/reactive_caching.rb
+++ b/app/models/concerns/reactive_caching.rb
@@ -118,11 +118,11 @@ module ReactiveCaching
prefix = self.class.reactive_cache_key
prefix = prefix.call(self) if prefix.respond_to?(:call)
- ([prefix].flatten + qualifiers).join(':')
+ ([prefix].flatten + qualifiers).join(":")
end
def alive_reactive_cache_key(*qualifiers)
- full_reactive_cache_key(*(qualifiers + ['alive']))
+ full_reactive_cache_key(*(qualifiers + ["alive"]))
end
def locking_reactive_cache(*args)
diff --git a/app/models/concerns/redactable.rb b/app/models/concerns/redactable.rb
index 5ad96d6cc46..fbbb88f5935 100644
--- a/app/models/concerns/redactable.rb
+++ b/app/models/concerns/redactable.rb
@@ -26,7 +26,7 @@ module Redactable
text = public_send(field) # rubocop:disable GitlabSecurity/PublicSend
return unless text.present?
- redacted = text.gsub(UNSUBSCRIBE_PATTERN, '/sent_notifications/REDACTED/unsubscribe')
+ redacted = text.gsub(UNSUBSCRIBE_PATTERN, "/sent_notifications/REDACTED/unsubscribe")
public_send("#{field}=", redacted) # rubocop:disable GitlabSecurity/PublicSend
end
diff --git a/app/models/concerns/redis_cacheable.rb b/app/models/concerns/redis_cacheable.rb
index 4bb4ffe2a8e..0e7d8a1af09 100644
--- a/app/models/concerns/redis_cacheable.rb
+++ b/app/models/concerns/redis_cacheable.rb
@@ -10,7 +10,7 @@ module RedisCacheable
def cached_attr_reader(*attributes)
attributes.each do |attribute|
define_method(attribute) do
- unless self.has_attribute?(attribute)
+ unless has_attribute?(attribute)
raise ArgumentError, "`cached_attr_reader` requires the #{self.class.name}\##{attribute} attribute to have a database column"
end
@@ -36,7 +36,7 @@ module RedisCacheable
private
def cache_attribute_key
- "cache:#{self.class.name}:#{self.id}:attributes"
+ "cache:#{self.class.name}:#{id}:attributes"
end
def cached_attributes
diff --git a/app/models/concerns/referable.rb b/app/models/concerns/referable.rb
index 58143a32fdc..5d21719fdff 100644
--- a/app/models/concerns/referable.rb
+++ b/app/models/concerns/referable.rb
@@ -20,7 +20,7 @@ module Referable
#
# Returns a String
def to_reference(_from = nil, full:)
- ''
+ ""
end
def reference_link_text(from = nil)
@@ -52,7 +52,7 @@ module Referable
#
# Returns a String
def reference_prefix
- ''
+ ""
end
# Regexp pattern used to match references to this object
diff --git a/app/models/concerns/relative_positioning.rb b/app/models/concerns/relative_positioning.rb
index 46d2c345758..3cd21888a92 100644
--- a/app/models/concerns/relative_positioning.rb
+++ b/app/models/concerns/relative_positioning.rb
@@ -20,7 +20,7 @@ module RelativePositioning
max_relative_position = objects.first.max_relative_position
- self.transaction do
+ transaction do
objects.each do |object|
relative_position = position_between(max_relative_position, MAX_POSITION)
object.relative_position = relative_position
@@ -58,20 +58,20 @@ module RelativePositioning
end
def min_relative_position(&block)
- calculate_relative_position('MIN', &block)
+ calculate_relative_position("MIN", &block)
end
def max_relative_position(&block)
- calculate_relative_position('MAX', &block)
+ calculate_relative_position("MAX", &block)
end
def prev_relative_position
prev_pos = nil
- if self.relative_position
- prev_pos = max_relative_position do |relation|
- relation.where('relative_position < ?', self.relative_position)
- end
+ if relative_position
+ prev_pos = max_relative_position { |relation|
+ relation.where("relative_position < ?", relative_position)
+ }
end
prev_pos
@@ -80,10 +80,10 @@ module RelativePositioning
def next_relative_position
next_pos = nil
- if self.relative_position
- next_pos = min_relative_position do |relation|
- relation.where('relative_position > ?', self.relative_position)
- end
+ if relative_position
+ next_pos = min_relative_position { |relation|
+ relation.where("relative_position > ?", relative_position)
+ }
end
next_pos
@@ -171,16 +171,16 @@ module RelativePositioning
# MAX(relative_position) without the GROUP BY, due to index usage:
# https://gitlab.com/gitlab-org/gitlab-ce/issues/54276#note_119340977
relation = self.class
- .in_parents(parent_ids)
- .order(Gitlab::Database.nulls_last_order('position', 'DESC'))
- .limit(1)
- .group(self.class.parent_column)
+ .in_parents(parent_ids)
+ .order(Gitlab::Database.nulls_last_order("position", "DESC"))
+ .limit(1)
+ .group(self.class.parent_column)
relation = yield relation if block_given?
relation
.pluck(self.class.parent_column, "#{calculation}(relative_position) AS position")
- .first&.
- last
+ .first
+ &.last
end
end
diff --git a/app/models/concerns/resolvable_discussion.rb b/app/models/concerns/resolvable_discussion.rb
index c0490af2453..f017ffa585c 100644
--- a/app/models/concerns/resolvable_discussion.rb
+++ b/app/models/concerns/resolvable_discussion.rb
@@ -25,12 +25,11 @@ module ResolvableDiscussion
delegate :potentially_resolvable?, to: :first_note
- delegate :resolved_at,
- :resolved_by,
- :resolved_by_push?,
-
- to: :last_resolved_note,
- allow_nil: true
+ delegate :resolved_at,
+ :resolved_by,
+ :resolved_by_push?,
+ to: :last_resolved_note,
+ allow_nil: true
end
def resolvable?
@@ -63,7 +62,7 @@ module ResolvableDiscussion
return unless resolved?
strong_memoize(:last_resolved_note) do
- resolved_notes.sort_by(&:resolved_at).last
+ resolved_notes.max_by(&:resolved_at)
end
end
@@ -79,8 +78,8 @@ module ResolvableDiscussion
return false unless current_user
return false unless resolvable?
- current_user == self.noteable.author ||
- current_user.can?(:resolve_note, self.project)
+ current_user == noteable.author ||
+ current_user.can?(:resolve_note, project)
end
def resolve!(current_user)
diff --git a/app/models/concerns/resolvable_note.rb b/app/models/concerns/resolvable_note.rb
index 16ea330701d..878f6cc18c4 100644
--- a/app/models/concerns/resolvable_note.rb
+++ b/app/models/concerns/resolvable_note.rb
@@ -4,7 +4,7 @@ module ResolvableNote
extend ActiveSupport::Concern
# Names of all subclasses of `Note` that can be resolvable.
- RESOLVABLE_TYPES = %w(DiffNote DiscussionNote).freeze
+ RESOLVABLE_TYPES = %w[DiffNote DiscussionNote].freeze
included do
belongs_to :resolved_by, class_name: "User"
@@ -45,7 +45,7 @@ module ResolvableNote
def resolved?
return false unless resolvable?
- self.resolved_at.present?
+ resolved_at.present?
end
def to_be_resolved?
diff --git a/app/models/concerns/routable.rb b/app/models/concerns/routable.rb
index b9ffc64e4a9..cbe4b3e239b 100644
--- a/app/models/concerns/routable.rb
+++ b/app/models/concerns/routable.rb
@@ -45,7 +45,7 @@ module Routable
# clients' DBs) that have the same path with different cases.
# See https://gitlab.com/gitlab-org/gitlab-ce/issues/18603. Also note that
# our unique index is case-sensitive in Postgres.
- 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)"
found = where_full_path_in([path]).reorder(order_sql).take
return found if found
@@ -54,7 +54,7 @@ module Routable
if Gitlab::Database.postgresql?
joins(:redirect_routes).find_by("LOWER(redirect_routes.path) = LOWER(?)", path)
else
- joins(:redirect_routes).find_by(redirect_routes: { path: path })
+ joins(:redirect_routes).find_by(redirect_routes: {path: path})
end
end
end
@@ -86,7 +86,7 @@ module Routable
if wheres.empty?
none
else
- joins(:route).where(wheres.join(' OR '))
+ joins(:route).where(wheres.join(" OR "))
end
end
end
@@ -100,12 +100,12 @@ module Routable
end
def full_path_components
- full_path.split('/')
+ full_path.split("/")
end
def build_full_path
if parent && path
- parent.full_path + '/' + path
+ parent.full_path + "/" + path
else
path
end
@@ -119,8 +119,8 @@ module Routable
private
def set_path_errors
- route_path_errors = self.errors.delete(:"route.path")
- self.errors[:path].concat(route_path_errors) if route_path_errors
+ route_path_errors = errors.delete(:"route.path")
+ errors[:path].concat(route_path_errors) if route_path_errors
end
def full_name_changed?
@@ -133,7 +133,7 @@ module Routable
def build_full_name
if parent && name
- parent.human_name + ' / ' + name
+ parent.human_name + " / " + name
else
name
end
diff --git a/app/models/concerns/sha_attribute.rb b/app/models/concerns/sha_attribute.rb
index a479bef993c..7ec07d2fc4e 100644
--- a/app/models/concerns/sha_attribute.rb
+++ b/app/models/concerns/sha_attribute.rb
@@ -5,7 +5,7 @@ module ShaAttribute
class_methods do
def sha_attribute(name)
- return if ENV['STATIC_VERIFICATION']
+ return if ENV["STATIC_VERIFICATION"]
validate_binary_column_exists!(name) unless Rails.env.production?
diff --git a/app/models/concerns/sortable.rb b/app/models/concerns/sortable.rb
index 29e48f0c5f7..c1c8210f759 100644
--- a/app/models/concerns/sortable.rb
+++ b/app/models/concerns/sortable.rb
@@ -22,15 +22,15 @@ module Sortable
class_methods do
def order_by(method)
case method.to_s
- when 'created_asc' then order_created_asc
- when 'created_date' then order_created_desc
- when 'created_desc' then order_created_desc
- when 'id_asc' then order_id_asc
- when 'id_desc' then order_id_desc
- when 'name_asc' then order_name_asc
- when 'name_desc' then order_name_desc
- when 'updated_asc' then order_updated_asc
- when 'updated_desc' then order_updated_desc
+ when "created_asc" then order_created_asc
+ when "created_date" then order_created_desc
+ when "created_desc" then order_created_desc
+ when "id_asc" then order_id_asc
+ when "id_desc" then order_id_desc
+ when "name_asc" then order_name_asc
+ when "name_desc" then order_name_desc
+ when "updated_asc" then order_updated_asc
+ when "updated_desc" then order_updated_desc
else
all
end
@@ -50,7 +50,7 @@ module Sortable
if target_type_column
query.where("label_links.target_type = #{target_type_column}")
else
- query.where(label_links: { target_type: target_type })
+ query.where(label_links: {target_type: target_type})
end
query = query.where.not(title: excluded_labels) if excluded_labels.present?
diff --git a/app/models/concerns/spammable.rb b/app/models/concerns/spammable.rb
index 3ff4b4046d3..079ab6d693d 100644
--- a/app/models/concerns/spammable.rb
+++ b/app/models/concerns/spammable.rb
@@ -26,7 +26,7 @@ module Spammable
end
def submittable_as_spam_by?(current_user)
- current_user && current_user.admin? && submittable_as_spam?
+ current_user&.admin? && submittable_as_spam?
end
def submittable_as_spam?
@@ -39,13 +39,13 @@ module Spammable
def check_for_spam
error_msg = if Gitlab::Recaptcha.enabled?
- "Your #{spammable_entity_type} has been recognized as spam. "\
- "Please, change the content or solve the reCAPTCHA to proceed."
- else
- "Your #{spammable_entity_type} has been recognized as spam and has been discarded."
- end
+ "Your #{spammable_entity_type} has been recognized as spam. "\
+ "Please, change the content or solve the reCAPTCHA to proceed."
+ else
+ "Your #{spammable_entity_type} has been recognized as spam and has been discarded."
+ end
- self.errors.add(:base, error_msg) if spam?
+ errors.add(:base, error_msg) if spam?
end
def spammable_entity_type
@@ -53,25 +53,25 @@ module Spammable
end
def spam_title
- attr = self.class.spammable_attrs.find do |_, options|
+ attr = self.class.spammable_attrs.find { |_, options|
options.fetch(:spam_title, false)
- end
+ }
public_send(attr.first) if attr && respond_to?(attr.first.to_sym) # rubocop:disable GitlabSecurity/PublicSend
end
def spam_description
- attr = self.class.spammable_attrs.find do |_, options|
+ attr = self.class.spammable_attrs.find { |_, options|
options.fetch(:spam_description, false)
- end
+ }
public_send(attr.first) if attr && respond_to?(attr.first.to_sym) # rubocop:disable GitlabSecurity/PublicSend
end
def spammable_text
- result = self.class.spammable_attrs.map do |attr|
+ result = self.class.spammable_attrs.map { |attr|
public_send(attr.first) # rubocop:disable GitlabSecurity/PublicSend
- end
+ }
result.reject(&:blank?).join("\n")
end
diff --git a/app/models/concerns/storage/legacy_namespace.rb b/app/models/concerns/storage/legacy_namespace.rb
index 498996f4f80..fefc3b4a1c6 100644
--- a/app/models/concerns/storage/legacy_namespace.rb
+++ b/app/models/concerns/storage/legacy_namespace.rb
@@ -14,8 +14,8 @@ module Storage
end
parent_was = if parent_changed? && parent_id_was.present?
- Namespace.find(parent_id_was) # raise NotFound early if needed
- end
+ Namespace.find(parent_id_was) # raise NotFound early if needed
+ end
move_repositories
@@ -38,7 +38,7 @@ module Storage
write_projects_repository_config
rescue => e
# Raise if development/test environment, else just notify Sentry
- Gitlab::Sentry.track_exception(e, extra: { full_path_was: full_path_was, full_path: full_path, action: 'move_dir' })
+ Gitlab::Sentry.track_exception(e, extra: {full_path_was: full_path_was, full_path: full_path, action: "move_dir"})
end
true # false would cancel later callbacks but not rollback
@@ -68,7 +68,7 @@ module Storage
# if we cannot move namespace directory we should rollback
# db changes in order to prevent out of sync between db and fs
- raise Gitlab::UpdatePathError.new('namespace directory cannot be moved')
+ raise Gitlab::UpdatePathError.new("namespace directory cannot be moved")
end
end
end
@@ -82,7 +82,7 @@ module Storage
# pending delete. Unscoping also get rids of the default order, which causes
# problems with SELECT DISTINCT.
Project.unscoped do
- all_projects.select('distinct(repository_storage)').to_a.map(&:repository_storage)
+ all_projects.select("distinct(repository_storage)").to_a.map(&:repository_storage)
end
end
@@ -94,7 +94,7 @@ module Storage
new_path = "#{full_path}+#{id}+deleted"
if gitlab_shell.mv_namespace(repository_storage, full_path, new_path)
- Gitlab::AppLogger.info %Q(Namespace directory "#{full_path}" moved to "#{new_path}")
+ Gitlab::AppLogger.info %(Namespace directory "#{full_path}" moved to "#{new_path}")
# Remove namespace directory async with delay so
# GitLab has time to remove all projects first
diff --git a/app/models/concerns/storage/legacy_project_wiki.rb b/app/models/concerns/storage/legacy_project_wiki.rb
index a377fa1e5de..7c308ac9efa 100644
--- a/app/models/concerns/storage/legacy_project_wiki.rb
+++ b/app/models/concerns/storage/legacy_project_wiki.rb
@@ -5,7 +5,7 @@ module Storage
extend ActiveSupport::Concern
def disk_path
- project.disk_path + '.wiki'
+ project.disk_path + ".wiki"
end
end
end
diff --git a/app/models/concerns/strip_attribute.rb b/app/models/concerns/strip_attribute.rb
index c9f5ba7793d..af05b3c71d3 100644
--- a/app/models/concerns/strip_attribute.rb
+++ b/app/models/concerns/strip_attribute.rb
@@ -30,7 +30,7 @@ module StripAttribute
def strip_attributes
self.class.strip_attrs.each do |attr|
- self[attr].strip! if self[attr] && self[attr].respond_to?(:strip!)
+ self[attr].strip! if self[attr]&.respond_to?(:strip!)
end
end
end
diff --git a/app/models/concerns/subscribable.rb b/app/models/concerns/subscribable.rb
index 92a5c1112af..1f74f54e1db 100644
--- a/app/models/concerns/subscribable.rb
+++ b/app/models/concerns/subscribable.rb
@@ -32,8 +32,8 @@ module Subscribable
def subscribers(project)
relation = subscriptions_available(project)
- .where(subscribed: true)
- .select(:user_id)
+ .where(subscribed: true)
+ .select(:user_id)
User.where(id: relation)
end
diff --git a/app/models/concerns/taskable.rb b/app/models/concerns/taskable.rb
index f147ce8ad6b..c27792486dd 100644
--- a/app/models/concerns/taskable.rb
+++ b/app/models/concerns/taskable.rb
@@ -1,7 +1,7 @@
# frozen_string_literal: true
-require 'task_list'
-require 'task_list/filter'
+require "task_list"
+require "task_list/filter"
# Contains functionality for objects that can have task lists in their
# descriptions. Task list items can be added with Markdown like "* [x] Fix
@@ -9,8 +9,8 @@ require 'task_list/filter'
#
# Used by MergeRequest and Issue
module Taskable
- COMPLETED = 'completed'.freeze
- INCOMPLETE = 'incomplete'.freeze
+ COMPLETED = "completed"
+ INCOMPLETE = "incomplete"
COMPLETE_PATTERN = /(\[[xX]\])/.freeze
INCOMPLETE_PATTERN = /(\[[\s]\])/.freeze
ITEM_PATTERN = %r{
@@ -58,16 +58,16 @@ module Taskable
# Return a string that describes the current state of this Taskable's task
# list items, e.g. "12 of 20 tasks completed"
def task_status(short: false)
- return '' if description.blank?
+ return "" if description.blank?
prep, completed = if short
- ['/', '']
- else
- [' of ', ' completed']
- end
+ ["/", ""]
+ else
+ [" of ", " completed"]
+ end
sum = tasks.summary
- "#{sum.complete_count}#{prep}#{sum.item_count} #{'task'.pluralize(sum.item_count)}#{completed}"
+ "#{sum.complete_count}#{prep}#{sum.item_count} #{"task".pluralize(sum.item_count)}#{completed}"
end
# Return a short string that describes the current state of this Taskable's
diff --git a/app/models/concerns/time_trackable.rb b/app/models/concerns/time_trackable.rb
index f61a0bbc65b..364bb6b7745 100644
--- a/app/models/concerns/time_trackable.rb
+++ b/app/models/concerns/time_trackable.rb
@@ -17,7 +17,7 @@ module TimeTrackable
default_value_for :time_estimate, value: 0, allows_nil: false
- validates :time_estimate, numericality: { message: 'has an invalid format' }, allow_nil: false
+ validates :time_estimate, numericality: {message: "has an invalid format"}, allow_nil: false
validate :check_negative_time_spent
has_many :timelogs, dependent: :destroy # rubocop:disable Cop/ActiveRecordDependent
@@ -38,7 +38,7 @@ module TimeTrackable
add_or_subtract_spent_time
end
end
- alias_method :spend_time=, :spend_time
+ alias spend_time= spend_time
# rubocop:enable Gitlab/ModuleWithInstanceVariables
def total_time_spent
@@ -77,7 +77,7 @@ module TimeTrackable
return if time_spent.nil? || time_spent == :reset
if time_spent < 0 && (time_spent.abs > original_total_time_spent)
- errors.add(:time_spent, 'Time to subtract exceeds the total time spent')
+ errors.add(:time_spent, "Time to subtract exceeds the total time spent")
end
end
diff --git a/app/models/concerns/token_authenticatable_strategies/base.rb b/app/models/concerns/token_authenticatable_strategies/base.rb
index 01fb194281a..690bb5975a7 100644
--- a/app/models/concerns/token_authenticatable_strategies/base.rb
+++ b/app/models/concerns/token_authenticatable_strategies/base.rb
@@ -41,7 +41,7 @@ module TokenAuthenticatableStrategies
def fallback?
unless options[:fallback].in?([true, false, nil])
- raise ArgumentError, 'fallback: needs to be a boolean value!'
+ raise ArgumentError, "fallback: needs to be a boolean value!"
end
options[:fallback] == true
@@ -49,7 +49,7 @@ module TokenAuthenticatableStrategies
def migrating?
unless options[:migrating].in?([true, false, nil])
- raise ArgumentError, 'migrating: needs to be a boolean value!'
+ raise ArgumentError, "migrating: needs to be a boolean value!"
end
options[:migrating] == true
@@ -57,7 +57,7 @@ module TokenAuthenticatableStrategies
def self.fabricate(model, field, options)
if options[:digest] && options[:encrypted]
- raise ArgumentError, 'Incompatible options set!'
+ raise ArgumentError, "Incompatible options set!"
end
if options[:digest]
diff --git a/app/models/concerns/token_authenticatable_strategies/encrypted.rb b/app/models/concerns/token_authenticatable_strategies/encrypted.rb
index 152491aa6e9..92a7da92c39 100644
--- a/app/models/concerns/token_authenticatable_strategies/encrypted.rb
+++ b/app/models/concerns/token_authenticatable_strategies/encrypted.rb
@@ -6,7 +6,7 @@ module TokenAuthenticatableStrategies
super
if migrating? && fallback?
- raise ArgumentError, '`fallback` and `migrating` options are not compatible!'
+ raise ArgumentError, "`fallback` and `migrating` options are not compatible!"
end
end
@@ -23,7 +23,7 @@ module TokenAuthenticatableStrategies
elsif migrating?
find_by_plaintext_token(token, unscoped)
else
- raise ArgumentError, 'Unknown encryption phase!'
+ raise ArgumentError, "Unknown encryption phase!"
end
end
@@ -42,7 +42,7 @@ module TokenAuthenticatableStrategies
return super if instance.has_attribute?(encrypted_field)
if fully_encrypted?
- raise ArgumentError, 'Using encrypted strategy when encrypted field is missing!'
+ raise ArgumentError, "Using encrypted strategy when encrypted field is missing!"
else
insecure_strategy.ensure_token(instance)
end
diff --git a/app/models/concerns/triggerable_hooks.rb b/app/models/concerns/triggerable_hooks.rb
index c52baa0524c..c1bd157b4db 100644
--- a/app/models/concerns/triggerable_hooks.rb
+++ b/app/models/concerns/triggerable_hooks.rb
@@ -2,17 +2,17 @@
module TriggerableHooks
AVAILABLE_TRIGGERS = {
- repository_update_hooks: :repository_update_events,
- push_hooks: :push_events,
- tag_push_hooks: :tag_push_events,
- issue_hooks: :issues_events,
- confidential_note_hooks: :confidential_note_events,
+ repository_update_hooks: :repository_update_events,
+ push_hooks: :push_events,
+ tag_push_hooks: :tag_push_events,
+ issue_hooks: :issues_events,
+ confidential_note_hooks: :confidential_note_events,
confidential_issue_hooks: :confidential_issues_events,
- note_hooks: :note_events,
- merge_request_hooks: :merge_requests_events,
- job_hooks: :job_events,
- pipeline_hooks: :pipeline_events,
- wiki_page_hooks: :wiki_page_events
+ note_hooks: :note_events,
+ merge_request_hooks: :merge_requests_events,
+ job_hooks: :job_events,
+ pipeline_hooks: :pipeline_events,
+ wiki_page_hooks: :wiki_page_events,
}.freeze
extend ActiveSupport::Concern
diff --git a/app/models/concerns/valid_attribute.rb b/app/models/concerns/valid_attribute.rb
index 251db9ce30b..07e9a284d8b 100644
--- a/app/models/concerns/valid_attribute.rb
+++ b/app/models/concerns/valid_attribute.rb
@@ -7,6 +7,6 @@ module ValidAttribute
#
# +attribute+ The symbolised name of the attribute i.e :name
def valid_attribute?(attribute)
- self.errors.empty? || self.errors.messages[attribute].nil?
+ errors.empty? || errors.messages[attribute].nil?
end
end
diff --git a/app/models/concerns/with_uploads.rb b/app/models/concerns/with_uploads.rb
index 6c6febd186c..87ab13b80bd 100644
--- a/app/models/concerns/with_uploads.rb
+++ b/app/models/concerns/with_uploads.rb
@@ -23,12 +23,12 @@ module WithUploads
# Currently there is no simple way how to select only not-mounted
# uploads, it should be all FileUploaders so we select them by
# `uploader` class
- FILE_UPLOADERS = %w(PersonalFileUploader NamespaceFileUploader FileUploader).freeze
+ FILE_UPLOADERS = %w[PersonalFileUploader NamespaceFileUploader FileUploader].freeze
included do
has_many :uploads, as: :model
has_many :file_uploads, -> { where(uploader: FILE_UPLOADERS) },
- class_name: 'Upload', as: :model,
+ class_name: "Upload", as: :model,
dependent: :delete_all # rubocop:disable Cop/ActiveRecordDependent
use_fast_destroy :file_uploads
diff --git a/app/models/container_repository.rb b/app/models/container_repository.rb
index cf057d774cf..56a971d6d78 100644
--- a/app/models/container_repository.rb
+++ b/app/models/container_repository.rb
@@ -5,8 +5,8 @@ class ContainerRepository < ActiveRecord::Base
belongs_to :project
- validates :name, length: { minimum: 0, allow_nil: false }
- validates :name, uniqueness: { scope: :project_id }
+ validates :name, length: {minimum: 0, allow_nil: false}
+ validates :name, uniqueness: {scope: :project_id}
delegate :client, to: :registry
@@ -27,7 +27,7 @@ class ContainerRepository < ActiveRecord::Base
def path
@path ||= [project.full_path, name]
- .select(&:present?).join('/').downcase
+ .select(&:present?).join("/").downcase
end
def location
@@ -43,10 +43,10 @@ class ContainerRepository < ActiveRecord::Base
end
def tags
- return [] unless manifest && manifest['tags']
+ return [] unless manifest && manifest["tags"]
strong_memoize(:tags) do
- manifest['tags'].sort.map do |tag|
+ manifest["tags"].sort.map do |tag|
ContainerRegistry::Tag.new(self, tag)
end
end
@@ -70,13 +70,13 @@ class ContainerRepository < ActiveRecord::Base
digests = tags.map { |tag| tag.digest }.to_set
digests.all? do |digest|
- client.delete_repository_tag(self.path, digest)
+ client.delete_repository_tag(path, digest)
end
end
def self.build_from_path(path)
- self.new(project: path.repository_project,
- name: path.repository_name)
+ new(project: path.repository_project,
+ name: path.repository_name)
end
def self.create_from_path!(path)
@@ -84,6 +84,6 @@ class ContainerRepository < ActiveRecord::Base
end
def self.build_root_repository(project)
- self.new(project: project, name: '')
+ new(project: project, name: "")
end
end
diff --git a/app/models/conversational_development_index/idea_to_production_step.rb b/app/models/conversational_development_index/idea_to_production_step.rb
index e78a734693c..536c3fb1f33 100644
--- a/app/models/conversational_development_index/idea_to_production_step.rb
+++ b/app/models/conversational_development_index/idea_to_production_step.rb
@@ -11,9 +11,9 @@ module ConversationalDevelopmentIndex
end
def percentage_score
- sum = features.sum do |feature|
+ sum = features.sum { |feature|
metric.percentage_score(feature)
- end
+ }
sum / features.size.to_f
end
diff --git a/app/models/conversational_development_index/metric.rb b/app/models/conversational_development_index/metric.rb
index c54537572d6..cad73ad1659 100644
--- a/app/models/conversational_development_index/metric.rb
+++ b/app/models/conversational_development_index/metric.rb
@@ -4,7 +4,7 @@ module ConversationalDevelopmentIndex
class Metric < ActiveRecord::Base
include Presentable
- self.table_name = 'conversational_development_index_metrics'
+ self.table_name = "conversational_development_index_metrics"
def instance_score(feature)
self["instance_#{feature}"]
diff --git a/app/models/cycle_analytics.rb b/app/models/cycle_analytics.rb
index d0f5b6970b1..c678d1a1fcd 100644
--- a/app/models/cycle_analytics.rb
+++ b/app/models/cycle_analytics.rb
@@ -16,8 +16,8 @@ class CycleAnalytics
def summary
@summary ||= ::Gitlab::CycleAnalytics::StageSummary.new(@project,
- from: @options[:from],
- current_user: @options[:current_user]).data
+ from: @options[:from],
+ current_user: @options[:current_user]).data
end
def stats
diff --git a/app/models/dashboard_group_milestone.rb b/app/models/dashboard_group_milestone.rb
index 74aa04ab7d0..70aa21614e0 100644
--- a/app/models/dashboard_group_milestone.rb
+++ b/app/models/dashboard_group_milestone.rb
@@ -1,4 +1,5 @@
# frozen_string_literal: true
+
# Dashboard Group Milestones are milestones that allow us to pull more info out for the UI that the Milestone object doesn't allow for
class DashboardGroupMilestone < GlobalMilestone
extend ::Gitlab::Utils::Override
@@ -13,9 +14,9 @@ class DashboardGroupMilestone < GlobalMilestone
def self.build_collection(groups, params)
milestones = Milestone.of_groups(groups.select(:id))
- .reorder_by_due_date_asc
- .order_by_name_asc
- .active
+ .reorder_by_due_date_asc
+ .order_by_name_asc
+ .active
milestones = milestones.search_title(params[:search_title]) if params[:search_title].present?
milestones.map { |m| new(m) }
end
diff --git a/app/models/deploy_key.rb b/app/models/deploy_key.rb
index db501b4b506..aab4535db1e 100644
--- a/app/models/deploy_key.rb
+++ b/app/models/deploy_key.rb
@@ -6,7 +6,7 @@ class DeployKey < Key
has_many :deploy_keys_projects, inverse_of: :deploy_key, dependent: :destroy # rubocop:disable Cop/ActiveRecordDependent
has_many :projects, through: :deploy_keys_projects
- scope :in_projects, ->(projects) { joins(:deploy_keys_projects).where('deploy_keys_projects.project_id in (?)', projects) }
+ scope :in_projects, ->(projects) { joins(:deploy_keys_projects).where("deploy_keys_projects.project_id in (?)", projects) }
scope :are_public, -> { where(public: true) }
ignore_column :can_push
@@ -18,15 +18,15 @@ class DeployKey < Key
end
def orphaned?
- self.deploy_keys_projects.empty?
+ deploy_keys_projects.empty?
end
def almost_orphaned?
- self.deploy_keys_projects.length == 1
+ deploy_keys_projects.length == 1
end
def destroyed_when_orphaned?
- self.private?
+ private?
end
def user
diff --git a/app/models/deploy_keys_project.rb b/app/models/deploy_keys_project.rb
index 71fd02fac86..06ae342c381 100644
--- a/app/models/deploy_keys_project.rb
+++ b/app/models/deploy_keys_project.rb
@@ -4,14 +4,14 @@ class DeployKeysProject < ActiveRecord::Base
belongs_to :project
belongs_to :deploy_key, inverse_of: :deploy_keys_projects
- scope :without_project_deleted, -> { joins(:project).where(projects: { pending_delete: false }) }
+ scope :without_project_deleted, -> { joins(:project).where(projects: {pending_delete: false}) }
scope :in_project, ->(project) { where(project: project) }
scope :with_write_access, -> { where(can_push: true) }
accepts_nested_attributes_for :deploy_key
validates :deploy_key, presence: true
- validates :deploy_key_id, uniqueness: { scope: [:project_id], message: "already exists in project" }
+ validates :deploy_key_id, uniqueness: {scope: [:project_id], message: "already exists in project"}
validates :project_id, presence: true
after_destroy :destroy_orphaned_deploy_key
@@ -19,8 +19,8 @@ class DeployKeysProject < ActiveRecord::Base
private
def destroy_orphaned_deploy_key
- return unless self.deploy_key.destroyed_when_orphaned? && self.deploy_key.orphaned?
+ return unless deploy_key.destroyed_when_orphaned? && deploy_key.orphaned?
- self.deploy_key.destroy
+ deploy_key.destroy
end
end
diff --git a/app/models/deploy_token.rb b/app/models/deploy_token.rb
index e3524305346..3b0a4f5c203 100644
--- a/app/models/deploy_token.rb
+++ b/app/models/deploy_token.rb
@@ -7,8 +7,8 @@ class DeployToken < ActiveRecord::Base
include Gitlab::Utils::StrongMemoize
add_authentication_token_field :token
- AVAILABLE_SCOPES = %i(read_repository read_registry).freeze
- GITLAB_DEPLOY_TOKEN_NAME = 'gitlab-deploy-token'.freeze
+ AVAILABLE_SCOPES = %i[read_repository read_registry].freeze
+ GITLAB_DEPLOY_TOKEN_NAME = "gitlab-deploy-token"
default_value_for(:expires_at) { Forever.date }
diff --git a/app/models/deployment.rb b/app/models/deployment.rb
index 811e623b7f7..41f3bb84da1 100644
--- a/app/models/deployment.rb
+++ b/app/models/deployment.rb
@@ -19,7 +19,7 @@ class Deployment < ActiveRecord::Base
delegate :name, to: :environment, prefix: true
- scope :for_environment, -> (environment) { where(environment_id: environment) }
+ scope :for_environment, ->(environment) { where(environment_id: environment) }
state_machine :status, initial: :created do
event :run do
@@ -54,15 +54,15 @@ class Deployment < ActiveRecord::Base
running: 1,
success: 2,
failed: 3,
- canceled: 4
+ canceled: 4,
}
def self.last_for_environment(environment)
- ids = self
- .for_environment(environment)
- .select('MAX(id) AS id')
- .group(:environment_id)
- .map(&:id)
+ ids =
+ for_environment(environment)
+ .select("MAX(id) AS id")
+ .group(:environment_id)
+ .map(&:id)
find(ids)
end
@@ -108,9 +108,9 @@ class Deployment < ActiveRecord::Base
return unless environment.update_merge_request_metrics? && success?
merge_requests = project.merge_requests
- .joins(:metrics)
- .where(target_branch: self.ref, merge_request_metrics: { first_deployed_to_production_at: nil })
- .where("merge_request_metrics.merged_at <= ?", finished_at)
+ .joins(:metrics)
+ .where(target_branch: ref, merge_request_metrics: {first_deployed_to_production_at: nil})
+ .where("merge_request_metrics.merged_at <= ?", finished_at)
if previous_deployment
merge_requests = merge_requests.where("merge_request_metrics.merged_at >= ?", previous_deployment.finished_at)
@@ -133,9 +133,9 @@ class Deployment < ActiveRecord::Base
def previous_deployment
@previous_deployment ||=
project.deployments.joins(:environment)
- .where(environments: { name: self.environment.name }, ref: self.ref)
- .where.not(id: self.id)
- .take
+ .where(environments: {name: environment.name}, ref: ref)
+ .where.not(id: id)
+ .take
end
def stop_action
@@ -184,10 +184,10 @@ class Deployment < ActiveRecord::Base
end
def ref_path
- File.join(environment.ref_path, 'deployments', iid.to_s)
+ File.join(environment.ref_path, "deployments", iid.to_s)
end
def legacy_finished_at
- self.created_at if success? && !read_attribute(:finished_at)
+ created_at if success? && !read_attribute(:finished_at)
end
end
diff --git a/app/models/diff_discussion.rb b/app/models/diff_discussion.rb
index 93e3ebf7896..d6803f10902 100644
--- a/app/models/diff_discussion.rb
+++ b/app/models/diff_discussion.rb
@@ -10,13 +10,12 @@ class DiffDiscussion < Discussion
DiffNote
end
- delegate :position,
- :original_position,
- :change_position,
- :on_text?,
- :on_image?,
-
- to: :first_note
+ delegate :position,
+ :original_position,
+ :change_position,
+ :on_text?,
+ :on_image?,
+ to: :first_note
def legacy_diff_discussion?
false
diff --git a/app/models/diff_note.rb b/app/models/diff_note.rb
index 805092e527a..ef6e6cfe120 100644
--- a/app/models/diff_note.rb
+++ b/app/models/diff_note.rb
@@ -9,13 +9,13 @@ class DiffNote < Note
include Gitlab::Utils::StrongMemoize
def self.noteable_types
- %w(MergeRequest Commit)
+ %w[MergeRequest Commit]
end
validates :original_position, presence: true
validates :position, presence: true
validates :line_code, presence: true, line_code: true, if: :on_text?
- validates :noteable_type, inclusion: { in: noteable_types }
+ validates :noteable_type, inclusion: {in: noteable_types}
validate :positions_complete
validate :verify_supported
validate :diff_refs_match_commit, if: :for_commit?
@@ -32,7 +32,7 @@ class DiffNote < Note
return unless should_create_diff_file?
diff_file = fetch_diff_file
- diff_line = diff_file.line_for_position(self.original_position)
+ diff_line = diff_file.line_for_position(original_position)
creation_params = diff_file.diff.to_hash
.except(:too_large)
@@ -58,27 +58,27 @@ class DiffNote < Note
end
def diff_line
- @diff_line ||= diff_file&.line_for_position(self.original_position)
+ @diff_line ||= diff_file&.line_for_position(original_position)
end
def original_line_code
return unless on_text?
- self.diff_file.line_code(self.diff_line)
+ diff_file.line_code(diff_line)
end
def created_at_diff?(diff_refs)
return false unless supported?
return true if for_commit?
- self.original_position.diff_refs == diff_refs
+ original_position.diff_refs == diff_refs
end
def supports_suggestion?
return false unless noteable.supports_suggestion? && on_text?
# We don't want to trigger side-effects of `diff_file` call.
return false unless file = fetch_diff_file
- return false unless line = file.line_for_position(self.original_position)
+ return false unless line = file.line_for_position(original_position)
line&.suggestible?
end
@@ -111,8 +111,8 @@ class DiffNote < Note
if note_diff_file
diff = Gitlab::Git::Diff.new(note_diff_file.to_hash)
Gitlab::Diff::File.new(diff,
- repository: project.repository,
- diff_refs: original_position.diff_refs)
+ repository: project.repository,
+ diff_refs: original_position.diff_refs)
elsif created_at_diff?(noteable.diff_refs)
# We're able to use the already persisted diffs (Postgres) if we're
# presenting a "current version" of the MR discussion diff.
@@ -122,7 +122,7 @@ class DiffNote < Note
# `Diff::FileCollection::MergeRequestDiff`.
noteable.diffs(original_position.diff_options).diff_files.first
else
- original_position.diff_file(self.project.repository)
+ original_position.diff_file(project.repository)
end
# Since persisted diff files already have its content "unfolded"
@@ -133,11 +133,11 @@ class DiffNote < Note
end
def supported?
- for_commit? || self.noteable.has_complete_diff_refs?
+ for_commit? || noteable.has_complete_diff_refs?
end
def set_line_code
- self.line_code = self.position.line_code(self.project.repository)
+ self.line_code = position.line_code(project.repository)
end
def verify_supported
@@ -147,28 +147,28 @@ class DiffNote < Note
end
def positions_complete
- return if self.original_position.complete? && self.position.complete?
+ return if original_position.complete? && position.complete?
errors.add(:position, "is invalid")
end
def diff_refs_match_commit
- return if self.original_position.diff_refs == self.commit.diff_refs
+ return if original_position.diff_refs == commit.diff_refs
- errors.add(:commit_id, 'does not match the diff refs')
+ errors.add(:commit_id, "does not match the diff refs")
end
def keep_around_commits
shas = [
- self.original_position.base_sha,
- self.original_position.start_sha,
- self.original_position.head_sha
+ original_position.base_sha,
+ original_position.start_sha,
+ original_position.head_sha,
]
- if self.position != self.original_position
- shas << self.position.base_sha
- shas << self.position.start_sha
- shas << self.position.head_sha
+ if position != original_position
+ shas << position.base_sha
+ shas << position.start_sha
+ shas << position.head_sha
end
project.repository.keep_around(*shas)
diff --git a/app/models/diff_viewer/added.rb b/app/models/diff_viewer/added.rb
index 70d13e3478c..1a24cad299e 100644
--- a/app/models/diff_viewer/added.rb
+++ b/app/models/diff_viewer/added.rb
@@ -5,6 +5,6 @@ module DiffViewer
include Simple
include Static
- self.partial_name = 'added'
+ self.partial_name = "added"
end
end
diff --git a/app/models/diff_viewer/base.rb b/app/models/diff_viewer/base.rb
index 527ee33b83b..40e27aa0c22 100644
--- a/app/models/diff_viewer/base.rb
+++ b/app/models/diff_viewer/base.rb
@@ -2,7 +2,7 @@
module DiffViewer
class Base
- PARTIAL_PATH_PREFIX = 'projects/diffs/viewers'.freeze
+ PARTIAL_PATH_PREFIX = "projects/diffs/viewers"
class_attribute :partial_name, :type, :extensions, :file_types, :binary, :switcher_icon, :switcher_title
@@ -89,7 +89,7 @@ module DiffViewer
{
viewer: switcher_title,
reason: render_error_reason,
- options: render_error_options.to_sentence(two_words_connector: _(' or '), last_word_connector: _(', or '))
+ options: render_error_options.to_sentence(two_words_connector: _(" or "), last_word_connector: _(", or ")),
}
end
@@ -103,8 +103,8 @@ module DiffViewer
options = []
blob_url = Gitlab::Routing.url_helpers.project_blob_path(diff_file.repository.project,
- File.join(diff_file.content_sha, diff_file.file_path))
- options << ActionController::Base.helpers.link_to(_('view the blob'), blob_url)
+ File.join(diff_file.content_sha, diff_file.file_path))
+ options << ActionController::Base.helpers.link_to(_("view the blob"), blob_url)
options
end
diff --git a/app/models/diff_viewer/deleted.rb b/app/models/diff_viewer/deleted.rb
index 78671084eeb..bdd36f98625 100644
--- a/app/models/diff_viewer/deleted.rb
+++ b/app/models/diff_viewer/deleted.rb
@@ -5,6 +5,6 @@ module DiffViewer
include Simple
include Static
- self.partial_name = 'deleted'
+ self.partial_name = "deleted"
end
end
diff --git a/app/models/diff_viewer/image.rb b/app/models/diff_viewer/image.rb
index 350bef1d42a..9ee75a7bc0c 100644
--- a/app/models/diff_viewer/image.rb
+++ b/app/models/diff_viewer/image.rb
@@ -5,10 +5,10 @@ module DiffViewer
include Rich
include ClientSide
- self.partial_name = 'image'
+ self.partial_name = "image"
self.extensions = UploaderHelper::IMAGE_EXT
self.binary = true
- self.switcher_icon = 'picture-o'
- self.switcher_title = _('image diff')
+ self.switcher_icon = "picture-o"
+ self.switcher_title = _("image diff")
end
end
diff --git a/app/models/diff_viewer/mode_changed.rb b/app/models/diff_viewer/mode_changed.rb
index bd07d1e21b9..aa9691476b6 100644
--- a/app/models/diff_viewer/mode_changed.rb
+++ b/app/models/diff_viewer/mode_changed.rb
@@ -5,6 +5,6 @@ module DiffViewer
include Simple
include Static
- self.partial_name = 'mode_changed'
+ self.partial_name = "mode_changed"
end
end
diff --git a/app/models/diff_viewer/no_preview.rb b/app/models/diff_viewer/no_preview.rb
index b0dd5fd151d..62d02cb76dc 100644
--- a/app/models/diff_viewer/no_preview.rb
+++ b/app/models/diff_viewer/no_preview.rb
@@ -5,7 +5,7 @@ module DiffViewer
include Simple
include Static
- self.partial_name = 'no_preview'
+ self.partial_name = "no_preview"
self.binary = true
end
end
diff --git a/app/models/diff_viewer/not_diffable.rb b/app/models/diff_viewer/not_diffable.rb
index dc86599e722..9a2fc459a88 100644
--- a/app/models/diff_viewer/not_diffable.rb
+++ b/app/models/diff_viewer/not_diffable.rb
@@ -5,7 +5,7 @@ module DiffViewer
include Simple
include Static
- self.partial_name = 'not_diffable'
+ self.partial_name = "not_diffable"
self.binary = true
end
end
diff --git a/app/models/diff_viewer/renamed.rb b/app/models/diff_viewer/renamed.rb
index 70ab9d4ca2c..0b39afedfc8 100644
--- a/app/models/diff_viewer/renamed.rb
+++ b/app/models/diff_viewer/renamed.rb
@@ -5,6 +5,6 @@ module DiffViewer
include Simple
include Static
- self.partial_name = 'renamed'
+ self.partial_name = "renamed"
end
end
diff --git a/app/models/diff_viewer/rich.rb b/app/models/diff_viewer/rich.rb
index 5caefa2031c..49c4aff8368 100644
--- a/app/models/diff_viewer/rich.rb
+++ b/app/models/diff_viewer/rich.rb
@@ -6,8 +6,8 @@ module DiffViewer
included do
self.type = :rich
- self.switcher_icon = 'file-text-o'
- self.switcher_title = _('rendered diff')
+ self.switcher_icon = "file-text-o"
+ self.switcher_title = _("rendered diff")
end
end
end
diff --git a/app/models/diff_viewer/server_side.rb b/app/models/diff_viewer/server_side.rb
index 0877c9dddec..4294d4c6a67 100644
--- a/app/models/diff_viewer/server_side.rb
+++ b/app/models/diff_viewer/server_side.rb
@@ -31,9 +31,9 @@ module DiffViewer
return super unless render_error == :server_side_but_stored_externally
if diff_file.external_storage == :lfs
- _('it is stored in LFS')
+ _("it is stored in LFS")
else
- _('it is stored externally')
+ _("it is stored externally")
end
end
end
diff --git a/app/models/diff_viewer/simple.rb b/app/models/diff_viewer/simple.rb
index 929d8ad5a7e..949e9ef32c9 100644
--- a/app/models/diff_viewer/simple.rb
+++ b/app/models/diff_viewer/simple.rb
@@ -6,8 +6,8 @@ module DiffViewer
included do
self.type = :simple
- self.switcher_icon = 'code'
- self.switcher_title = _('source diff')
+ self.switcher_icon = "code"
+ self.switcher_title = _("source diff")
end
end
end
diff --git a/app/models/diff_viewer/text.rb b/app/models/diff_viewer/text.rb
index d3d5055c402..8197204b65a 100644
--- a/app/models/diff_viewer/text.rb
+++ b/app/models/diff_viewer/text.rb
@@ -5,7 +5,7 @@ module DiffViewer
include Simple
include ServerSide
- self.partial_name = 'text'
+ self.partial_name = "text"
self.binary = false
# Since the text diff viewer doesn't render the old and new blobs in full,
diff --git a/app/models/discussion.rb b/app/models/discussion.rb
index 32529ebf71d..f5f96b3d52e 100644
--- a/app/models/discussion.rb
+++ b/app/models/discussion.rb
@@ -8,16 +8,14 @@ class Discussion
attr_reader :notes, :context_noteable
- delegate :created_at,
- :project,
- :author,
-
- :noteable,
- :commit_id,
- :for_commit?,
- :for_merge_request?,
-
- to: :first_note
+ delegate :created_at,
+ :project,
+ :author,
+ :noteable,
+ :commit_id,
+ :for_commit?,
+ :for_merge_request?,
+ to: :first_note
def project_id
project&.id
@@ -79,9 +77,9 @@ class Discussion
def ==(other)
other.class == self.class &&
- other.context_noteable == self.context_noteable &&
- other.id == self.id &&
- other.notes == self.notes
+ other.context_noteable == context_noteable &&
+ other.id == id &&
+ other.notes == notes
end
def last_updated_at
@@ -106,7 +104,7 @@ class Discussion
first_note.discussion_id
end
- alias_method :to_param, :id
+ alias to_param id
def diff_discussion?
false
diff --git a/app/models/discussion_note.rb b/app/models/discussion_note.rb
index 142cbdcdfa6..d4b38d58941 100644
--- a/app/models/discussion_note.rb
+++ b/app/models/discussion_note.rb
@@ -6,10 +6,10 @@
class DiscussionNote < Note
# Names of all implementers of `Noteable` that support discussions.
def self.noteable_types
- %w(MergeRequest Issue Commit Snippet)
+ %w[MergeRequest Issue Commit Snippet]
end
- validates :noteable_type, inclusion: { in: noteable_types }
+ validates :noteable_type, inclusion: {in: noteable_types}
def discussion_class(*)
Discussion
diff --git a/app/models/email.rb b/app/models/email.rb
index 3ce6e792fa8..bfbdccef9a3 100644
--- a/app/models/email.rb
+++ b/app/models/email.rb
@@ -12,7 +12,7 @@ class Email < ActiveRecord::Base
scope :confirmed, -> { where.not(confirmed_at: nil) }
- after_commit :update_invalid_gpg_signatures, if: -> { previous_changes.key?('confirmed_at') }
+ after_commit :update_invalid_gpg_signatures, if: -> { previous_changes.key?("confirmed_at") }
devise :confirmable
self.reconfirmable = false # currently email can't be changed, no need to reconfirm
@@ -24,7 +24,7 @@ class Email < ActiveRecord::Base
end
def unique_email
- self.errors.add(:email, 'has already been taken') if User.exists?(email: self.email)
+ errors.add(:email, "has already been taken") if User.exists?(email: email)
end
def accept_pending_invitations!
diff --git a/app/models/environment.rb b/app/models/environment.rb
index 87bdb52b58b..8671285be1a 100644
--- a/app/models/environment.rb
+++ b/app/models/environment.rb
@@ -3,15 +3,15 @@
class Environment < ActiveRecord::Base
include Gitlab::Utils::StrongMemoize
# Used to generate random suffixes for the slug
- LETTERS = 'a'..'z'
- NUMBERS = '0'..'9'
+ LETTERS = "a".."z"
+ NUMBERS = "0".."9"
SUFFIX_CHARS = LETTERS.to_a + NUMBERS.to_a
belongs_to :project, required: true
has_many :deployments, -> { success }, dependent: :destroy # rubocop:disable Cop/ActiveRecordDependent
- has_one :last_deployment, -> { success.order('deployments.id DESC') }, class_name: 'Deployment'
+ has_one :last_deployment, -> { success.order("deployments.id DESC") }, class_name: "Deployment"
before_validation :nullify_external_url
before_validation :generate_slug, if: ->(env) { env.slug.blank? }
@@ -19,23 +19,23 @@ class Environment < ActiveRecord::Base
before_save :set_environment_type
validates :name,
- presence: true,
- uniqueness: { scope: :project_id },
- length: { maximum: 255 },
- format: { with: Gitlab::Regex.environment_name_regex,
- message: Gitlab::Regex.environment_name_regex_message }
+ presence: true,
+ uniqueness: {scope: :project_id},
+ length: {maximum: 255},
+ format: {with: Gitlab::Regex.environment_name_regex,
+ message: Gitlab::Regex.environment_name_regex_message,}
validates :slug,
- presence: true,
- uniqueness: { scope: :project_id },
- length: { maximum: 24 },
- format: { with: Gitlab::Regex.environment_slug_regex,
- message: Gitlab::Regex.environment_slug_regex_message }
+ presence: true,
+ uniqueness: {scope: :project_id},
+ length: {maximum: 24},
+ format: {with: Gitlab::Regex.environment_slug_regex,
+ message: Gitlab::Regex.environment_slug_regex_message,}
validates :external_url,
- length: { maximum: 255 },
- allow_nil: true,
- url: true
+ length: {maximum: 255},
+ allow_nil: true,
+ url: true
delegate :stop_action, :manual_actions, to: :last_deployment, allow_nil: true
@@ -44,22 +44,22 @@ class Environment < ActiveRecord::Base
scope :order_by_last_deployed_at, -> do
max_deployment_id_sql =
Deployment.select(Deployment.arel_table[:id].maximum)
- .where(Deployment.arel_table[:environment_id].eq(arel_table[:id]))
- .to_sql
- order(Gitlab::Database.nulls_first_order("(#{max_deployment_id_sql})", 'ASC'))
+ .where(Deployment.arel_table[:environment_id].eq(arel_table[:id]))
+ .to_sql
+ order(Gitlab::Database.nulls_first_order("(#{max_deployment_id_sql})", "ASC"))
end
scope :in_review_folder, -> { where(environment_type: "review") }
- scope :for_name, -> (name) { where(name: name) }
+ scope :for_name, ->(name) { where(name: name) }
##
# Search environments which have names like the given query.
# Do not set a large limit unless you've confirmed that it works on gitlab.com scale.
- scope :for_name_like, -> (query, limit: 5) do
- where('name LIKE ?', "#{sanitize_sql_like(query)}%").limit(limit)
+ scope :for_name_like, ->(query, limit: 5) do
+ where("name LIKE ?", "#{sanitize_sql_like(query)}%").limit(limit)
end
- scope :for_project, -> (project) { where(project_id: project) }
- scope :with_deployment, -> (sha) { where('EXISTS (?)', Deployment.select(1).where('deployments.environment_id = environments.id').where(sha: sha)) }
+ scope :for_project, ->(project) { where(project_id: project) }
+ scope :with_deployment, ->(sha) { where("EXISTS (?)", Deployment.select(1).where("deployments.environment_id = environments.id").where(sha: sha)) }
state_machine :state, initial: :available do
event :start do
@@ -84,8 +84,8 @@ class Environment < ActiveRecord::Base
def predefined_variables
Gitlab::Ci::Variables::Collection.new
- .append(key: 'CI_ENVIRONMENT_NAME', value: name)
- .append(key: 'CI_ENVIRONMENT_SLUG', value: slug)
+ .append(key: "CI_ENVIRONMENT_NAME", value: name)
+ .append(key: "CI_ENVIRONMENT_SLUG", value: slug)
end
def recently_updated_on_branch?(ref)
@@ -93,11 +93,11 @@ class Environment < ActiveRecord::Base
end
def nullify_external_url
- self.external_url = nil if self.external_url.blank?
+ self.external_url = nil if external_url.blank?
end
def set_environment_type
- names = name.split('/')
+ names = name.split("/")
self.environment_type = names.many? ? names.first : nil
end
@@ -121,7 +121,7 @@ class Environment < ActiveRecord::Base
return nil unless ref
- deployment_iid = ref.split('/').last
+ deployment_iid = ref.split("/").last
deployments.find_by(iid: deployment_iid)
end
@@ -132,7 +132,7 @@ class Environment < ActiveRecord::Base
def formatted_external_url
return nil unless external_url
- external_url.gsub(%r{\A.*?://}, '')
+ external_url.gsub(%r{\A.*?://}, "")
end
def stop_action_available?
@@ -193,25 +193,25 @@ class Environment < ActiveRecord::Base
# * cannot end with `-`
def generate_slug
# Lowercase letters and numbers only
- slugified = +name.to_s.downcase.gsub(/[^a-z0-9]/, '-')
+ slugified = +name.to_s.downcase.gsub(/[^a-z0-9]/, "-")
# Must start with a letter
- slugified = 'env-' + slugified unless LETTERS.cover?(slugified[0])
+ slugified = "env-" + slugified unless LETTERS.cover?(slugified[0])
# Repeated dashes are invalid (OpenShift limitation)
- slugified.gsub!(/\-+/, '-')
+ slugified.gsub!(/\-+/, "-")
# Maximum length: 24 characters (OpenShift limitation)
slugified = slugified[0..23]
# Cannot end with a dash (Kubernetes label limitation)
- slugified.chop! if slugified.end_with?('-')
+ slugified.chop! if slugified.end_with?("-")
# Add a random suffix, shortening the current string if necessary, if it
# has been slugified. This ensures uniqueness.
if slugified != name
slugified = slugified[0..16]
- slugified << '-' unless slugified.end_with?('-')
+ slugified << "-" unless slugified.end_with?("-")
slugified << random_suffix
end
@@ -219,12 +219,12 @@ class Environment < ActiveRecord::Base
end
def external_url_for(path, commit_sha)
- return unless self.external_url
+ return unless external_url
public_path = project.public_path_for_source_path(path, commit_sha)
return unless public_path
- [external_url, public_path].join('/')
+ [external_url, public_path].join("/")
end
def expire_etag_cache
@@ -236,11 +236,12 @@ class Environment < ActiveRecord::Base
def etag_cache_key
Gitlab::Routing.url_helpers.project_environments_path(
project,
- format: :json)
+ format: :json
+ )
end
def folder_name
- self.environment_type || self.name
+ environment_type || name
end
def name_without_type
@@ -249,7 +250,7 @@ class Environment < ActiveRecord::Base
def deployment_platform
strong_memoize(:deployment_platform) do
- project.deployment_platform(environment: self.name)
+ project.deployment_platform(environment: name)
end
end
diff --git a/app/models/environment_status.rb b/app/models/environment_status.rb
index 2fb6cadc8cd..a508bcc3230 100644
--- a/app/models/environment_status.rb
+++ b/app/models/environment_status.rb
@@ -57,18 +57,18 @@ class EnvironmentStatus
{
path: public_path,
- external_url: environment.external_url_for(file.new_path, sha)
+ external_url: environment.external_url_for(file.new_path, sha),
}
end
def self.build_environments_status(mr, user, pipeline)
return [] unless pipeline
- pipeline.environments.available.map do |environment|
+ pipeline.environments.available.map { |environment|
next unless Ability.allowed?(user, :read_environment, environment)
EnvironmentStatus.new(environment, mr, pipeline.sha)
- end.compact
+ }.compact
end
private_class_method :build_environments_status
end
diff --git a/app/models/epic.rb b/app/models/epic.rb
index ccd10593434..e711f610586 100644
--- a/app/models/epic.rb
+++ b/app/models/epic.rb
@@ -8,10 +8,10 @@ class Epic < ActiveRecord::Base
end
def self.reference_prefix
- '&'
+ "&"
end
def self.reference_prefix_escaped
- '&amp;'
+ "&amp;"
end
end
diff --git a/app/models/error_tracking/project_error_tracking_setting.rb b/app/models/error_tracking/project_error_tracking_setting.rb
index 57283a78ea9..867fff2de6d 100644
--- a/app/models/error_tracking/project_error_tracking_setting.rb
+++ b/app/models/error_tracking/project_error_tracking_setting.rb
@@ -8,7 +8,7 @@ module ErrorTracking
belongs_to :project
- validates :api_url, length: { maximum: 255 }, public_url: true, url: { enforce_sanitization: true, ascii_only: true }, allow_nil: true
+ validates :api_url, length: {maximum: 255}, public_url: true, url: {enforce_sanitization: true, ascii_only: true}, allow_nil: true
validates :api_url, presence: true, if: :enabled
@@ -19,7 +19,7 @@ module ErrorTracking
attr_encrypted :token,
mode: :per_attribute_iv,
key: Settings.attr_encrypted_db_key_base_truncated,
- algorithm: 'aes-256-gcm'
+ algorithm: "aes-256-gcm"
after_save :clear_reactive_cache!
@@ -41,7 +41,7 @@ module ErrorTracking
def self.build_api_url_from(api_host:, project_slug:, organization_slug:)
uri = Addressable::URI.parse("#{api_host}/api/0/projects/#{organization_slug}/#{project_slug}/")
- uri.path = uri.path.squeeze('/')
+ uri.path = uri.path.squeeze("/")
uri.to_s
rescue Addressable::URI::InvalidURIError
@@ -57,36 +57,36 @@ module ErrorTracking
end
def list_sentry_issues(opts = {})
- with_reactive_cache('list_issues', opts.stringify_keys) do |result|
+ with_reactive_cache("list_issues", opts.stringify_keys) do |result|
result
end
end
def list_sentry_projects
- { projects: sentry_client.list_projects }
+ {projects: sentry_client.list_projects}
end
def calculate_reactive_cache(request, opts)
case request
- when 'list_issues'
- { issues: sentry_client.list_issues(**opts.symbolize_keys) }
+ when "list_issues"
+ {issues: sentry_client.list_issues(**opts.symbolize_keys)}
end
rescue Sentry::Client::Error => e
- { error: e.message }
+ {error: e.message}
end
# http://HOST/api/0/projects/ORG/PROJECT
# ->
# http://HOST/ORG/PROJECT
def self.extract_sentry_external_url(url)
- url.sub('api/0/projects/', '')
+ url.sub("api/0/projects/", "")
end
def api_host
return if api_url.blank?
# This returns http://example.com/
- Addressable::URI.join(api_url, '/').to_s
+ Addressable::URI.join(api_url, "/").to_s
end
private
@@ -124,8 +124,8 @@ module ErrorTracking
return if api_url.blank?
begin
- unless Addressable::URI.parse(api_url).path.starts_with?('/api/0/projects')
- errors.add(:api_url, 'path needs to start with /api/0/projects')
+ unless Addressable::URI.parse(api_url).path.starts_with?("/api/0/projects")
+ errors.add(:api_url, "path needs to start with /api/0/projects")
end
rescue Addressable::URI::InvalidURIError
end
diff --git a/app/models/event.rb b/app/models/event.rb
index 6a35bca72c5..a0d86c9ebe7 100644
--- a/app/models/event.rb
+++ b/app/models/event.rb
@@ -19,27 +19,27 @@ class Event < ActiveRecord::Base
EXPIRED = 11 # User left project due to expiry
ACTIONS = HashWithIndifferentAccess.new(
- created: CREATED,
- updated: UPDATED,
- closed: CLOSED,
- reopened: REOPENED,
- pushed: PUSHED,
- commented: COMMENTED,
- merged: MERGED,
- joined: JOINED,
- left: LEFT,
- destroyed: DESTROYED,
- expired: EXPIRED
+ created: CREATED,
+ updated: UPDATED,
+ closed: CLOSED,
+ reopened: REOPENED,
+ pushed: PUSHED,
+ commented: COMMENTED,
+ merged: MERGED,
+ joined: JOINED,
+ left: LEFT,
+ destroyed: DESTROYED,
+ expired: EXPIRED
).freeze
TARGET_TYPES = HashWithIndifferentAccess.new(
- issue: Issue,
- milestone: Milestone,
- merge_request: MergeRequest,
- note: Note,
- project: Project,
- snippet: Snippet,
- user: User
+ issue: Issue,
+ milestone: Milestone,
+ merge_request: MergeRequest,
+ note: Note,
+ project: Project,
+ snippet: Snippet,
+ user: User
).freeze
RESET_PROJECT_ACTIVITY_INTERVAL = 1.hour
@@ -57,9 +57,9 @@ class Event < ActiveRecord::Base
# If the association for "target" defines an "author" association we want to
# eager-load this so Banzai & friends don't end up performing N+1 queries to
# get the authors of notes, issues, etc. (likewise for "noteable").
- incs = %i(author noteable).select do |a|
- reflections['events'].active_record.reflect_on_association(a)
- end
+ incs = %i[author noteable].select { |a|
+ reflections["events"].active_record.reflect_on_association(a)
+ }
incs.reduce(self) { |obj, a| obj.includes(a) }
}, polymorphic: true # rubocop:disable Cop/PolymorphicAssociations
@@ -75,13 +75,13 @@ class Event < ActiveRecord::Base
scope :recent, -> { reorder(id: :desc) }
scope :code_push, -> { where(action: PUSHED) }
- scope :in_projects, -> (projects) do
+ scope :in_projects, ->(projects) do
sub_query = projects
.except(:order)
.select(1)
- .where('projects.id = events.project_id')
+ .where("projects.id = events.project_id")
- where('EXISTS (?)', sub_query).recent
+ where("EXISTS (?)", sub_query).recent
end
scope :with_associations, -> do
@@ -99,11 +99,11 @@ class Event < ActiveRecord::Base
# should ensure the ID points to a valid user.
validates :author_id, presence: true
- self.inheritance_column = 'action'
+ self.inheritance_column = "action"
class << self
def model_name
- ActiveModel::Name.new(self, nil, 'event')
+ ActiveModel::Name.new(self, nil, "event")
end
def find_sti_class(action)
@@ -117,9 +117,9 @@ class Event < ActiveRecord::Base
# Update Gitlab::ContributionsCalendar#activity_dates if this changes
def contributions
where("action = ? OR (target_type IN (?) AND action IN (?)) OR (target_type = ? AND action = ?)",
- Event::PUSHED,
- %w(MergeRequest Issue), [Event::CREATED, Event::CLOSED, Event::MERGED],
- "Note", Event::COMMENTED)
+ Event::PUSHED,
+ %w[MergeRequest Issue], [Event::CREATED, Event::CLOSED, Event::MERGED],
+ "Note", Event::COMMENTED)
end
def limit_recent(limit = 20, offset = nil)
@@ -265,13 +265,13 @@ class Event < ActiveRecord::Base
elsif merged?
"accepted"
elsif joined?
- 'joined'
+ "joined"
elsif left?
- 'left'
+ "left"
elsif expired?
- 'removed due to membership expiration from'
+ "removed due to membership expiration from"
elsif destroyed?
- 'destroyed'
+ "destroyed"
elsif commented?
"commented on"
elsif created_project?
@@ -356,7 +356,7 @@ class Event < ActiveRecord::Base
# update the project. Only one query should actually perform the update,
# hence we add the extra WHERE clause for last_activity_at.
Project.unscoped.where(id: project_id)
- .where('last_activity_at <= ?', RESET_PROJECT_ACTIVITY_INTERVAL.ago)
+ .where("last_activity_at <= ?", RESET_PROJECT_ACTIVITY_INTERVAL.ago)
.update_all(last_activity_at: created_at)
end
diff --git a/app/models/event_collection.rb b/app/models/event_collection.rb
index a4c69b11781..8a3cfb12c3c 100644
--- a/app/models/event_collection.rb
+++ b/app/models/event_collection.rb
@@ -25,10 +25,10 @@ class EventCollection
return [] if current_page > MAX_PAGE
relation = if Gitlab::Database.join_lateral_supported?
- relation_with_join_lateral
- else
- relation_without_join_lateral
- end
+ relation_with_join_lateral
+ else
+ relation_without_join_lateral
+ end
relation.with_associations.to_a
end
@@ -54,7 +54,7 @@ class EventCollection
lateral = filtered_events
.limit(limit_for_join_lateral)
- .where('events.project_id = projects_for_lateral.id')
+ .where("events.project_id = projects_for_lateral.id")
.to_sql
# The outer query does not need to re-apply the filters since the JOIN
diff --git a/app/models/external_issue.rb b/app/models/external_issue.rb
index 68b2353556e..3f03b1b5afa 100644
--- a/app/models/external_issue.rb
+++ b/app/models/external_issue.rb
@@ -28,7 +28,7 @@ class ExternalIssue
def ==(other)
other.is_a?(self.class) && (to_s == other.to_s)
end
- alias_method :eql?, :==
+ alias eql? ==
def hash
[self.class, to_s].hash
diff --git a/app/models/fork_network.rb b/app/models/fork_network.rb
index 1b9bf93cbbc..4d8ca3e7291 100644
--- a/app/models/fork_network.rb
+++ b/app/models/fork_network.rb
@@ -1,7 +1,7 @@
# frozen_string_literal: true
class ForkNetwork < ActiveRecord::Base
- belongs_to :root_project, class_name: 'Project'
+ belongs_to :root_project, class_name: "Project"
has_many :fork_network_members
has_many :projects, through: :fork_network_members
diff --git a/app/models/fork_network_member.rb b/app/models/fork_network_member.rb
index 36c66f21b0b..32c6e3d08a2 100644
--- a/app/models/fork_network_member.rb
+++ b/app/models/fork_network_member.rb
@@ -3,7 +3,7 @@
class ForkNetworkMember < ActiveRecord::Base
belongs_to :fork_network
belongs_to :project
- belongs_to :forked_from_project, class_name: 'Project'
+ belongs_to :forked_from_project, class_name: "Project"
validates :fork_network, :project, presence: true
diff --git a/app/models/generic_commit_status.rb b/app/models/generic_commit_status.rb
index 3028bf21301..93c16bc7d47 100644
--- a/app/models/generic_commit_status.rb
+++ b/app/models/generic_commit_status.rb
@@ -4,15 +4,15 @@ class GenericCommitStatus < CommitStatus
before_validation :set_default_values
validates :target_url, url: true,
- length: { maximum: 255 },
+ length: {maximum: 255},
allow_nil: true
# GitHub compatible API
alias_attribute :context, :name
def set_default_values
- self.context ||= 'default'
- self.stage ||= 'external'
+ self.context ||= "default"
+ self.stage ||= "external"
self.stage_idx ||= 1000000
end
diff --git a/app/models/global_milestone.rb b/app/models/global_milestone.rb
index fd17745b035..794a8cd51ba 100644
--- a/app/models/global_milestone.rb
+++ b/app/models/global_milestone.rb
@@ -1,9 +1,10 @@
# frozen_string_literal: true
+
# Global Milestones are milestones that can be shared across multiple projects
class GlobalMilestone
include Milestoneish
- STATE_COUNT_HASH = { opened: 0, closed: 0, all: 0 }.freeze
+ STATE_COUNT_HASH = {opened: 0, closed: 0, all: 0}.freeze
attr_reader :milestone
alias_attribute :name, :title
@@ -12,10 +13,10 @@ class GlobalMilestone
def to_hash
{
- name: title,
- title: title,
- group_name: group&.full_name,
- project_name: project&.full_name
+ name: title,
+ title: title,
+ group_name: group&.full_name,
+ project_name: project&.full_name,
}
end
@@ -25,8 +26,8 @@ class GlobalMilestone
def self.build_collection(projects, params)
items = Milestone.of_projects(projects)
- .reorder_by_due_date_asc
- .order_by_name_asc
+ .reorder_by_due_date_asc
+ .order_by_name_asc
items = items.search_title(params[:search_title]) if params[:search_title].present?
Milestone.filter_by_state(items, params[:state]).map { |m| new(m) }
@@ -55,9 +56,9 @@ class GlobalMilestone
counts_by_state = Milestone.of_groups(group).count_by_state
{
- opened: counts_by_state['active'] || 0,
- closed: counts_by_state['closed'] || 0,
- all: counts_by_state.values.sum
+ opened: counts_by_state["active"] || 0,
+ closed: counts_by_state["closed"] || 0,
+ all: counts_by_state.values.sum,
}
end
@@ -68,9 +69,9 @@ class GlobalMilestone
relation = Milestone.of_projects(projects.reorder(nil)).count_by_state
{
- opened: relation['active'] || 0,
- closed: relation['closed'] || 0,
- all: relation.values.sum
+ opened: relation["active"] || 0,
+ closed: relation["closed"] || 0,
+ all: relation.values.sum,
}
end
@@ -79,11 +80,11 @@ class GlobalMilestone
end
def active?
- state == 'active'
+ state == "active"
end
def closed?
- state == 'closed'
+ state == "closed"
end
def issues
diff --git a/app/models/gpg_key.rb b/app/models/gpg_key.rb
index 077afffd358..b14053b4c03 100644
--- a/app/models/gpg_key.rb
+++ b/app/models/gpg_key.rb
@@ -1,8 +1,8 @@
# frozen_string_literal: true
class GpgKey < ActiveRecord::Base
- KEY_PREFIX = '-----BEGIN PGP PUBLIC KEY BLOCK-----'.freeze
- KEY_SUFFIX = '-----END PGP PUBLIC KEY BLOCK-----'.freeze
+ KEY_PREFIX = "-----BEGIN PGP PUBLIC KEY BLOCK-----"
+ KEY_SUFFIX = "-----END PGP PUBLIC KEY BLOCK-----"
include ShaAttribute
@@ -11,7 +11,7 @@ class GpgKey < ActiveRecord::Base
belongs_to :user
has_many :gpg_signatures
- has_many :subkeys, class_name: 'GpgKeySubkey'
+ has_many :subkeys, class_name: "GpgKeySubkey"
scope :with_subkeys, -> { includes(:subkeys) }
@@ -22,7 +22,7 @@ class GpgKey < ActiveRecord::Base
uniqueness: true,
format: {
with: /\A#{KEY_PREFIX}((?!#{KEY_PREFIX})(?!#{KEY_SUFFIX}).)+#{KEY_SUFFIX}\Z/m,
- message: "is invalid. A valid public GPG key begins with '#{KEY_PREFIX}' and ends with '#{KEY_SUFFIX}'"
+ message: "is invalid. A valid public GPG key begins with '#{KEY_PREFIX}' and ends with '#{KEY_SUFFIX}'",
}
validates :fingerprint,
@@ -30,14 +30,14 @@ class GpgKey < ActiveRecord::Base
uniqueness: true,
# only validate when the `key` is valid, as we don't want the user to show
# the error about the fingerprint
- unless: -> { errors.has_key?(:key) }
+ unless: -> { errors.key?(:key) }
validates :primary_keyid,
presence: true,
uniqueness: true,
# only validate when the `key` is valid, as we don't want the user to show
# the error about the fingerprint
- unless: -> { errors.has_key?(:key) }
+ unless: -> { errors.key?(:key) }
before_validation :extract_fingerprint, :extract_primary_keyid
after_commit :update_invalid_gpg_signatures, on: :create
@@ -46,7 +46,7 @@ class GpgKey < ActiveRecord::Base
def primary_keyid
super&.upcase
end
- alias_method :keyid, :primary_keyid
+ alias keyid primary_keyid
def fingerprint
super&.upcase
@@ -71,12 +71,12 @@ class GpgKey < ActiveRecord::Base
end
def emails_with_verified_status
- user_infos.map do |user_info|
+ user_infos.map { |user_info|
[
user_info[:email],
- user.verified_email?(user_info[:email])
+ user.verified_email?(user_info[:email]),
]
- end.to_h
+ }.to_h
end
def verified?
@@ -88,7 +88,7 @@ class GpgKey < ActiveRecord::Base
end
def update_invalid_gpg_signatures
- InvalidGpgSignatureUpdateWorker.perform_async(self.id)
+ InvalidGpgSignatureUpdateWorker.perform_async(id)
end
def revoke
diff --git a/app/models/gpg_signature.rb b/app/models/gpg_signature.rb
index 7f9ff7bbda6..dfe93e3d8ab 100644
--- a/app/models/gpg_signature.rb
+++ b/app/models/gpg_signature.rb
@@ -12,7 +12,7 @@ class GpgSignature < ApplicationRecord
same_user_different_email: 2,
other_user: 3,
unverified_key: 4,
- unknown_key: 5
+ unknown_key: 5,
}
belongs_to :project
diff --git a/app/models/group.rb b/app/models/group.rb
index 52f503404af..5ef7a211318 100644
--- a/app/models/group.rb
+++ b/app/models/group.rb
@@ -1,6 +1,6 @@
# frozen_string_literal: true
-require 'carrierwave/orm/activerecord'
+require "carrierwave/orm/activerecord"
class Group < Namespace
include Gitlab::ConfigHelper
@@ -17,15 +17,15 @@ class Group < Namespace
include Gitlab::Utils::StrongMemoize
has_many :group_members, -> { where(requested_at: nil) }, dependent: :destroy, as: :source # rubocop:disable Cop/ActiveRecordDependent
- alias_method :members, :group_members
+ alias members group_members
has_many :users, through: :group_members
has_many :owners,
- -> { where(members: { access_level: Gitlab::Access::OWNER }) },
+ -> { where(members: {access_level: Gitlab::Access::OWNER}) },
through: :group_members,
source: :user
- has_many :requesters, -> { where.not(requested_at: nil) }, dependent: :destroy, as: :source, class_name: 'GroupMember' # rubocop:disable Cop/ActiveRecordDependent
- has_many :members_and_requesters, as: :source, class_name: 'GroupMember'
+ has_many :requesters, -> { where.not(requested_at: nil) }, dependent: :destroy, as: :source, class_name: "GroupMember" # rubocop:disable Cop/ActiveRecordDependent
+ has_many :members_and_requesters, as: :source, class_name: "GroupMember"
has_many :milestones
has_many :project_group_links, dependent: :destroy # rubocop:disable Cop/ActiveRecordDependent
@@ -35,15 +35,15 @@ class Group < Namespace
# Left here just to be dependent: :destroy
has_many :notification_settings, dependent: :destroy, as: :source # rubocop:disable Cop/ActiveRecordDependent
- has_many :labels, class_name: 'GroupLabel'
- has_many :variables, class_name: 'Ci::GroupVariable'
- has_many :custom_attributes, class_name: 'GroupCustomAttribute'
+ has_many :labels, class_name: "GroupLabel"
+ has_many :variables, class_name: "Ci::GroupVariable"
+ has_many :custom_attributes, class_name: "GroupCustomAttribute"
has_many :boards
- has_many :badges, class_name: 'GroupBadge'
+ has_many :badges, class_name: "GroupBadge"
- has_many :cluster_groups, class_name: 'Clusters::Group'
- has_many :clusters, through: :cluster_groups, class_name: 'Clusters::Cluster'
+ has_many :cluster_groups, class_name: "Clusters::Group"
+ has_many :clusters, through: :cluster_groups, class_name: "Clusters::Cluster"
has_many :todos
@@ -54,7 +54,7 @@ class Group < Namespace
validate :visibility_level_allowed_by_parent
validates :variables, variable_duplicates: true
- validates :two_factor_grace_period, presence: true, numericality: { greater_than_or_equal_to: 0 }
+ validates :two_factor_grace_period, presence: true, numericality: {greater_than_or_equal_to: 0}
add_authentication_token_field :runners_token, encrypted: true, migrating: true
@@ -65,10 +65,10 @@ class Group < Namespace
class << self
def sort_by_attribute(method)
- if method == 'storage_size_desc'
+ if method == "storage_size_desc"
# storage_size is a virtual column so we need to
# pass a string to avoid AR adding the table name
- reorder('storage_size DESC, namespaces.id DESC')
+ reorder("storage_size DESC, namespaces.id DESC")
else
order_by(method)
end
@@ -97,8 +97,8 @@ class Group < Namespace
def select_for_project_authorization
if current_scope.joins_values.include?(:shared_projects)
- joins('INNER JOIN namespaces project_namespace ON project_namespace.id = projects.namespace_id')
- .where('project_namespace.share_with_group_lock = ?', false)
+ joins("INNER JOIN namespaces project_namespace ON project_namespace.id = projects.namespace_id")
+ .where("project_namespace.share_with_group_lock = ?", false)
.select("projects.id AS project_id, LEAST(project_group_links.group_access, members.access_level) AS access_level")
else
super
@@ -108,13 +108,13 @@ class Group < Namespace
private
def public_to_user_arel(user)
- self.arel_table[:visibility_level]
+ arel_table[:visibility_level]
.in(Gitlab::VisibilityLevel.levels_for_user(user))
end
def visible_to_user_arel(user)
- groups_table = self.arel_table
- authorized_groups = user.authorized_groups.as('authorized')
+ groups_table = arel_table
+ authorized_groups = user.authorized_groups.as("authorized")
groups_table.project(1)
.from(authorized_groups)
@@ -144,21 +144,21 @@ class Group < Namespace
full_name
end
- def visibility_level_allowed_by_parent?(level = self.visibility_level)
- return true unless parent_id && parent_id.nonzero?
+ def visibility_level_allowed_by_parent?(level = visibility_level)
+ return true unless parent_id&.nonzero?
level <= parent.visibility_level
end
- def visibility_level_allowed_by_projects?(level = self.visibility_level)
- !projects.where('visibility_level > ?', level).exists?
+ def visibility_level_allowed_by_projects?(level = visibility_level)
+ !projects.where("visibility_level > ?", level).exists?
end
- def visibility_level_allowed_by_sub_groups?(level = self.visibility_level)
- !children.where('visibility_level > ?', level).exists?
+ def visibility_level_allowed_by_sub_groups?(level = visibility_level)
+ !children.where("visibility_level > ?", level).exists?
end
- def visibility_level_allowed?(level = self.visibility_level)
+ def visibility_level_allowed?(level = visibility_level)
visibility_level_allowed_by_parent?(level) &&
visibility_level_allowed_by_projects?(level) &&
visibility_level_allowed_by_sub_groups?(level)
@@ -213,7 +213,7 @@ class Group < Namespace
end
# @deprecated
- alias_method :add_master, :add_maintainer
+ alias add_master add_maintainer
def add_owner(user, current_user = nil)
add_user(user, :owner, current_user: current_user)
@@ -238,7 +238,7 @@ class Group < Namespace
end
# @deprecated
- alias_method :has_master?, :has_maintainer?
+ alias has_master? has_maintainer?
# Check if user is a last owner of the group.
# Parent owners are ignored for nested groups.
@@ -334,7 +334,7 @@ class Group < Namespace
User
.where(id: direct_and_indirect_members.select(:user_id))
.reorder(nil),
- project_users_with_descendants
+ project_users_with_descendants,
])
end
@@ -343,7 +343,7 @@ class Group < Namespace
def project_users_with_descendants
User
.joins(projects: :group)
- .where(namespaces: { id: self_and_descendants.select(:id) })
+ .where(namespaces: {id: self_and_descendants.select(:id)})
end
def max_member_access_for_user(user)
@@ -352,8 +352,8 @@ class Group < Namespace
members_with_parents
.where(user_id: user)
.reorder(access_level: :desc)
- .first&.
- access_level || GroupMember::NO_ACCESS
+ .first
+ &.access_level || GroupMember::NO_ACCESS
end
def mattermost_team_params
@@ -362,7 +362,7 @@ class Group < Namespace
{
name: path[0..max_length],
display_name: name[0..max_length],
- type: public? ? 'O' : 'I' # Open vs Invite-only
+ type: public? ? "O" : "I", # Open vs Invite-only
}
end
diff --git a/app/models/group_custom_attribute.rb b/app/models/group_custom_attribute.rb
index 22f14885657..1915f6914e8 100644
--- a/app/models/group_custom_attribute.rb
+++ b/app/models/group_custom_attribute.rb
@@ -4,5 +4,5 @@ class GroupCustomAttribute < ActiveRecord::Base
belongs_to :group
validates :group, :key, :value, presence: true
- validates :key, uniqueness: { scope: [:group_id] }
+ validates :key, uniqueness: {scope: [:group_id]}
end
diff --git a/app/models/group_label.rb b/app/models/group_label.rb
index ff14529c6e6..26b69277118 100644
--- a/app/models/group_label.rb
+++ b/app/models/group_label.rb
@@ -8,6 +8,6 @@ class GroupLabel < Label
alias_attribute :subject, :group
def subject_foreign_key
- 'group_id'
+ "group_id"
end
end
diff --git a/app/models/group_milestone.rb b/app/models/group_milestone.rb
index 97cb26c6ea9..8b8f09bee9e 100644
--- a/app/models/group_milestone.rb
+++ b/app/models/group_milestone.rb
@@ -1,11 +1,12 @@
# frozen_string_literal: true
+
# Group Milestones are milestones that can be shared among many projects within the same group
class GroupMilestone < GlobalMilestone
attr_reader :group, :milestones
def self.build_collection(group, projects, params)
params =
- { state: params[:state], search_title: params[:search_title] }
+ {state: params[:state], search_title: params[:search_title]}
project_milestones = Milestone.of_projects(projects)
project_milestones = project_milestones.search_title(params[:search_title]) if params[:search_title].present?
@@ -34,7 +35,7 @@ class GroupMilestone < GlobalMilestone
end
def issues_finder_params
- { group_id: group.id }
+ {group_id: group.id}
end
def legacy_group_milestone?
diff --git a/app/models/hooks/project_hook.rb b/app/models/hooks/project_hook.rb
index 18c387f0d34..42e1fb18347 100644
--- a/app/models/hooks/project_hook.rb
+++ b/app/models/hooks/project_hook.rb
@@ -13,7 +13,7 @@ class ProjectHook < WebHook
:merge_request_hooks,
:job_hooks,
:pipeline_hooks,
- :wiki_page_hooks
+ :wiki_page_hooks,
]
belongs_to :project
diff --git a/app/models/hooks/service_hook.rb b/app/models/hooks/service_hook.rb
index 8f305dd7c22..78a53658b9a 100644
--- a/app/models/hooks/service_hook.rb
+++ b/app/models/hooks/service_hook.rb
@@ -5,7 +5,7 @@ class ServiceHook < WebHook
validates :service, presence: true
# rubocop: disable CodeReuse/ServiceClass
- def execute(data, hook_name = 'service_hook')
+ def execute(data, hook_name = "service_hook")
WebHookService.new(self, data, hook_name).execute
end
# rubocop: enable CodeReuse/ServiceClass
diff --git a/app/models/hooks/system_hook.rb b/app/models/hooks/system_hook.rb
index 90b4588a325..c67bcb223e8 100644
--- a/app/models/hooks/system_hook.rb
+++ b/app/models/hooks/system_hook.rb
@@ -7,7 +7,7 @@ class SystemHook < WebHook
:repository_update_hooks,
:push_hooks,
:tag_push_hooks,
- :merge_request_hooks
+ :merge_request_hooks,
]
default_value_for :push_events, false
diff --git a/app/models/hooks/web_hook.rb b/app/models/hooks/web_hook.rb
index 1a8662db9fb..4c5bdd1a148 100644
--- a/app/models/hooks/web_hook.rb
+++ b/app/models/hooks/web_hook.rb
@@ -4,21 +4,21 @@ class WebHook < ActiveRecord::Base
include Sortable
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
has_many :web_hook_logs, dependent: :destroy # rubocop:disable Cop/ActiveRecordDependent
- validates :url, presence: true, public_url: { allow_localhost: lambda(&:allow_local_requests?),
- allow_local_network: lambda(&:allow_local_requests?) }
+ validates :url, presence: true, public_url: {allow_localhost: lambda(&:allow_local_requests?),
+ allow_local_network: lambda(&:allow_local_requests?),}
- validates :token, format: { without: /\n/ }
+ validates :token, format: {without: /\n/}
validates :push_events_branch_filter, branch_filter: true
# rubocop: disable CodeReuse/ServiceClass
diff --git a/app/models/hooks/web_hook_log.rb b/app/models/hooks/web_hook_log.rb
index 2d9f7594e8c..e9671efcd6a 100644
--- a/app/models/hooks/web_hook_log.rb
+++ b/app/models/hooks/web_hook_log.rb
@@ -10,7 +10,7 @@ class WebHookLog < ActiveRecord::Base
validates :web_hook, presence: true
def self.recent
- where('created_at >= ?', 2.days.ago.beginning_of_day)
+ where("created_at >= ?", 2.days.ago.beginning_of_day)
.order(created_at: :desc)
end
diff --git a/app/models/identity.rb b/app/models/identity.rb
index acdde4f296b..c8833db9d64 100644
--- a/app/models/identity.rb
+++ b/app/models/identity.rb
@@ -7,8 +7,8 @@ class Identity < ActiveRecord::Base
belongs_to :user
validates :provider, presence: true
- validates :extern_uid, allow_blank: true, uniqueness: { scope: UniquenessScopes.scopes, case_sensitive: false }
- validates :user, uniqueness: { scope: UniquenessScopes.scopes }
+ validates :extern_uid, allow_blank: true, uniqueness: {scope: UniquenessScopes.scopes, case_sensitive: false}
+ validates :user, uniqueness: {scope: UniquenessScopes.scopes}
before_save :ensure_normalized_extern_uid, if: :extern_uid_changed?
after_destroy :clear_user_synced_attributes, if: :user_synced_attributes_metadata_from_provider?
@@ -35,7 +35,7 @@ class Identity < ActiveRecord::Base
def ensure_normalized_extern_uid
return if extern_uid.nil?
- self.extern_uid = Identity.normalize_uid(self.provider, self.extern_uid)
+ self.extern_uid = Identity.normalize_uid(provider, extern_uid)
end
def user_synced_attributes_metadata_from_provider?
diff --git a/app/models/instance_configuration.rb b/app/models/instance_configuration.rb
index 11289887e00..aa4d8d1737d 100644
--- a/app/models/instance_configuration.rb
+++ b/app/models/instance_configuration.rb
@@ -1,20 +1,20 @@
# frozen_string_literal: true
-require 'resolv'
+require "resolv"
class InstanceConfiguration
- SSH_ALGORITHMS = %w(DSA ECDSA ED25519 RSA).freeze
- SSH_ALGORITHMS_PATH = '/etc/ssh/'.freeze
- CACHE_KEY = 'instance_configuration'.freeze
+ SSH_ALGORITHMS = %w[DSA ECDSA ED25519 RSA].freeze
+ SSH_ALGORITHMS_PATH = "/etc/ssh/"
+ CACHE_KEY = "instance_configuration"
EXPIRATION_TIME = 24.hours
def settings
- @configuration ||= Rails.cache.fetch(CACHE_KEY, expires_in: EXPIRATION_TIME) do
- { ssh_algorithms_hashes: ssh_algorithms_hashes,
- host: host,
- gitlab_pages: gitlab_pages,
- gitlab_ci: gitlab_ci }.deep_symbolize_keys
- end
+ @configuration ||= Rails.cache.fetch(CACHE_KEY, expires_in: EXPIRATION_TIME) {
+ {ssh_algorithms_hashes: ssh_algorithms_hashes,
+ host: host,
+ gitlab_pages: gitlab_pages,
+ gitlab_ci: gitlab_ci,}.deep_symbolize_keys
+ }
end
private
@@ -38,9 +38,9 @@ class InstanceConfiguration
def gitlab_ci
Settings.gitlab_ci
- .to_h
- .merge(artifacts_max_size: { value: Settings.artifacts.max_size&.megabytes,
- default: 100.megabytes })
+ .to_h
+ .merge(artifacts_max_size: {value: Settings.artifacts.max_size&.megabytes,
+ default: 100.megabytes,})
end
def ssh_algorithm_file(algorithm)
@@ -51,9 +51,9 @@ class InstanceConfiguration
content = ssh_algorithm_file_content(algorithm)
return unless content.present?
- { name: algorithm,
- md5: ssh_algorithm_md5(content),
- sha256: ssh_algorithm_sha256(content) }
+ {name: algorithm,
+ md5: ssh_algorithm_md5(content),
+ sha256: ssh_algorithm_sha256(content),}
end
def ssh_algorithm_file_content(algorithm)
@@ -68,6 +68,6 @@ class InstanceConfiguration
end
def ssh_algorithm_sha256(ssh_file_content)
- Gitlab::SSHPublicKey.new(ssh_file_content).fingerprint('SHA256')
+ Gitlab::SSHPublicKey.new(ssh_file_content).fingerprint("SHA256")
end
end
diff --git a/app/models/internal_id.rb b/app/models/internal_id.rb
index e75c6eb2331..6171767fd43 100644
--- a/app/models/internal_id.rb
+++ b/app/models/internal_id.rb
@@ -19,7 +19,7 @@ class InternalId < ActiveRecord::Base
belongs_to :project
belongs_to :namespace
- enum usage: { issues: 0, merge_requests: 1, deployments: 2, milestones: 3, epics: 4, ci_pipelines: 5 }
+ enum usage: {issues: 0, merge_requests: 1, deployments: 2, milestones: 3, epics: 4, ci_pipelines: 5}
validates :usage, presence: true
@@ -113,9 +113,9 @@ class InternalId < ActiveRecord::Base
@init = init
@usage = usage
- raise ArgumentError, 'Scope is not well-defined, need at least one column for scope (given: 0)' if scope.empty?
+ raise ArgumentError, "Scope is not well-defined, need at least one column for scope (given: 0)" if scope.empty?
- unless InternalId.usages.has_key?(usage.to_s)
+ unless InternalId.usages.key?(usage.to_s)
raise ArgumentError, "Usage '#{usage}' is unknown. Supported values are #{InternalId.usages.keys} from InternalId.usages"
end
end
diff --git a/app/models/issue.rb b/app/models/issue.rb
index 071ad50fddc..d2b4fbba526 100644
--- a/app/models/issue.rb
+++ b/app/models/issue.rb
@@ -1,6 +1,6 @@
# frozen_string_literal: true
-require 'carrierwave/orm/activerecord'
+require "carrierwave/orm/activerecord"
class Issue < ActiveRecord::Base
include AtomicInternalId
@@ -19,25 +19,25 @@ class Issue < ActiveRecord::Base
ignore_column :assignee_id, :branch_name, :deleted_at
DueDateStruct = Struct.new(:title, :name).freeze
- NoDueDate = DueDateStruct.new('No Due Date', '0').freeze
- AnyDueDate = DueDateStruct.new('Any Due Date', '').freeze
- Overdue = DueDateStruct.new('Overdue', 'overdue').freeze
- DueThisWeek = DueDateStruct.new('Due This Week', 'week').freeze
- DueThisMonth = DueDateStruct.new('Due This Month', 'month').freeze
- DueNextMonthAndPreviousTwoWeeks = DueDateStruct.new('Due Next Month And Previous Two Weeks', 'next_month_and_previous_two_weeks').freeze
+ NoDueDate = DueDateStruct.new("No Due Date", "0").freeze
+ AnyDueDate = DueDateStruct.new("Any Due Date", "").freeze
+ Overdue = DueDateStruct.new("Overdue", "overdue").freeze
+ DueThisWeek = DueDateStruct.new("Due This Week", "week").freeze
+ DueThisMonth = DueDateStruct.new("Due This Month", "month").freeze
+ DueNextMonthAndPreviousTwoWeeks = DueDateStruct.new("Due Next Month And Previous Two Weeks", "next_month_and_previous_two_weeks").freeze
SORTING_PREFERENCE_FIELD = :issues_sort
belongs_to :project
- belongs_to :moved_to, class_name: 'Issue'
- belongs_to :closed_by, class_name: 'User'
+ belongs_to :moved_to, class_name: "Issue"
+ belongs_to :closed_by, class_name: "User"
has_internal_id :iid, scope: :project, init: ->(s) { s&.project&.issues&.maximum(:iid) }
has_many :events, as: :target, dependent: :destroy # rubocop:disable Cop/ActiveRecordDependent
has_many :merge_requests_closing_issues,
- class_name: 'MergeRequestsClosingIssues',
+ class_name: "MergeRequestsClosingIssues",
dependent: :delete_all # rubocop:disable Cop/ActiveRecordDependent
has_many :issue_assignees
@@ -49,19 +49,19 @@ class Issue < ActiveRecord::Base
scope :in_projects, ->(project_ids) { where(project_id: project_ids) }
- scope :assigned, -> { where('EXISTS (SELECT TRUE FROM issue_assignees WHERE issue_id = issues.id)') }
- scope :unassigned, -> { where('NOT EXISTS (SELECT TRUE FROM issue_assignees WHERE issue_id = issues.id)') }
- scope :assigned_to, ->(u) { where('EXISTS (SELECT TRUE FROM issue_assignees WHERE user_id = ? AND issue_id = issues.id)', u.id)}
+ scope :assigned, -> { where("EXISTS (SELECT TRUE FROM issue_assignees WHERE issue_id = issues.id)") }
+ scope :unassigned, -> { where("NOT EXISTS (SELECT TRUE FROM issue_assignees WHERE issue_id = issues.id)") }
+ scope :assigned_to, ->(u) { where("EXISTS (SELECT TRUE FROM issue_assignees WHERE user_id = ? AND issue_id = issues.id)", u.id)}
scope :with_due_date, -> { where.not(due_date: nil) }
scope :without_due_date, -> { where(due_date: nil) }
- scope :due_before, ->(date) { where('issues.due_date < ?', date) }
- scope :due_between, ->(from_date, to_date) { where('issues.due_date >= ?', from_date).where('issues.due_date <= ?', to_date) }
+ scope :due_before, ->(date) { where("issues.due_date < ?", date) }
+ scope :due_between, ->(from_date, to_date) { where("issues.due_date >= ?", from_date).where("issues.due_date <= ?", to_date) }
scope :due_tomorrow, -> { where(due_date: Date.tomorrow) }
- scope :order_due_date_asc, -> { reorder('issues.due_date IS NULL, issues.due_date ASC') }
- scope :order_due_date_desc, -> { reorder('issues.due_date IS NULL, issues.due_date DESC') }
- scope :order_closest_future_date, -> { reorder('CASE WHEN issues.due_date >= CURRENT_DATE THEN 0 ELSE 1 END ASC, ABS(CURRENT_DATE - issues.due_date) ASC') }
+ scope :order_due_date_asc, -> { reorder("issues.due_date IS NULL, issues.due_date ASC") }
+ scope :order_due_date_desc, -> { reorder("issues.due_date IS NULL, issues.due_date DESC") }
+ scope :order_closest_future_date, -> { reorder("CASE WHEN issues.due_date >= CURRENT_DATE THEN 0 ELSE 1 END ASC, ABS(CURRENT_DATE - issues.due_date) ASC") }
scope :preload_associations, -> { preload(:labels, project: :namespace) }
@@ -99,7 +99,7 @@ class Issue < ActiveRecord::Base
end
class << self
- alias_method :in_parents, :in_projects
+ alias in_parents in_projects
end
def self.parent_column
@@ -107,7 +107,7 @@ class Issue < ActiveRecord::Base
end
def self.reference_prefix
- '#'
+ "#"
end
# Pattern used to extract `#123` issue references from text
@@ -129,15 +129,15 @@ class Issue < ActiveRecord::Base
end
def self.project_foreign_key
- 'project_id'
+ "project_id"
end
def self.sort_by_attribute(method, excluded_labels: [])
case method.to_s
- when 'closest_future_date' then order_closest_future_date
- when 'due_date' then order_due_date_asc
- when 'due_date_asc' then order_due_date_asc
- when 'due_date_desc' then order_due_date_desc
+ when "closest_future_date" then order_closest_future_date
+ when "due_date" then order_due_date_asc
+ when "due_date_asc" then order_due_date_asc
+ when "due_date_desc" then order_due_date_desc
else
super
end
@@ -145,9 +145,9 @@ class Issue < ActiveRecord::Base
def self.order_by_position_and_priority
order_labels_priority
- .reorder(Gitlab::Database.nulls_last_order('relative_position', 'ASC'),
- Gitlab::Database.nulls_last_order('highest_priority', 'ASC'),
- "id DESC")
+ .reorder(Gitlab::Database.nulls_last_order("relative_position", "ASC"),
+ Gitlab::Database.nulls_last_order("highest_priority", "ASC"),
+ "id DESC")
end
def hook_attrs
@@ -157,8 +157,8 @@ class Issue < ActiveRecord::Base
# Returns a Hash of attributes to be used for Twitter card metadata
def card_attributes
{
- 'Author' => author.try(:name),
- 'Assignee' => assignee_list
+ "Author" => author.try(:name),
+ "Assignee" => assignee_list,
}
end
@@ -181,7 +181,7 @@ class Issue < ActiveRecord::Base
return to_branch_name unless project.repository.branch_exists?(to_branch_name)
start_counting_from = 2
- Uniquify.new(start_counting_from).string(-> (counter) { "#{to_branch_name}-#{counter}" }) do |suggested_branch_name|
+ Uniquify.new(start_counting_from).string(->(counter) { "#{to_branch_name}-#{counter}" }) do |suggested_branch_name|
project.repository.branch_exists?(suggested_branch_name)
end
end
@@ -209,11 +209,11 @@ class Issue < ActiveRecord::Base
end
!moved? && persisted? &&
- user.can?(:admin_issue, self.project)
+ user.can?(:admin_issue, project)
end
def to_branch_name
- if self.confidential?
+ if confidential?
"#{iid}-confidential-issue"
else
"#{iid}-#{title.parameterize}"
@@ -221,13 +221,13 @@ class Issue < ActiveRecord::Base
end
def can_be_worked_on?
- !self.closed? && !self.project.forked?
+ !closed? && !project.forked?
end
# Returns `true` if the current issue can be viewed by either a logged in User
# or an anonymous user.
def visible_to_user?(user = nil)
- return false unless project && project.feature_available?(:issues, user)
+ return false unless project&.feature_available?(:issues, user)
user ? readable_by?(user) : publicly_visible?
end
diff --git a/app/models/issue/metrics.rb b/app/models/issue/metrics.rb
index 0f5ee957ec9..0b3d507dc00 100644
--- a/app/models/issue/metrics.rb
+++ b/app/models/issue/metrics.rb
@@ -4,15 +4,15 @@ class Issue::Metrics < ActiveRecord::Base
belongs_to :issue
def record!
- if issue.milestone_id.present? && self.first_associated_with_milestone_at.blank?
+ if issue.milestone_id.present? && first_associated_with_milestone_at.blank?
self.first_associated_with_milestone_at = Time.now
end
- if issue_assigned_to_list_label? && self.first_added_to_board_at.blank?
+ if issue_assigned_to_list_label? && first_added_to_board_at.blank?
self.first_added_to_board_at = Time.now
end
- self.save
+ save
end
private
diff --git a/app/models/issue_collection.rb b/app/models/issue_collection.rb
index 05607fc3a08..c3be71bbffc 100644
--- a/app/models/issue_collection.rb
+++ b/app/models/issue_collection.rb
@@ -34,7 +34,7 @@ class IssueCollection
end
end
- alias_method :visible_to, :updatable_by_user
+ alias visible_to updatable_by_user
private
diff --git a/app/models/key.rb b/app/models/key.rb
index 8f93418b88b..e6174182198 100644
--- a/app/models/key.rb
+++ b/app/models/key.rb
@@ -1,6 +1,6 @@
# frozen_string_literal: true
-require 'digest/md5'
+require "digest/md5"
class Key < ActiveRecord::Base
include AfterCommitQueue
@@ -12,16 +12,16 @@ class Key < ActiveRecord::Base
validates :title,
presence: true,
- length: { maximum: 255 }
+ length: {maximum: 255}
validates :key,
presence: true,
- length: { maximum: 5000 },
- format: { with: /\A(ssh|ecdsa)-.*\Z/ }
+ length: {maximum: 5000},
+ format: {with: /\A(ssh|ecdsa)-.*\Z/}
validates :fingerprint,
uniqueness: true,
- presence: { message: 'cannot be generated' }
+ presence: {message: "cannot be generated"}
validate :key_meets_restrictions
@@ -35,7 +35,7 @@ class Key < ActiveRecord::Base
after_destroy :refresh_user_cache
def self.regular_keys
- where(type: ['Key', nil])
+ where(type: ["Key", nil])
end
def key=(value)
@@ -47,7 +47,7 @@ class Key < ActiveRecord::Base
def publishable_key
# Strip out the keys comment so we don't leak email addresses
# Replace with simple ident of user_name (hostname)
- self.key.split[0..1].push("#{self.user_name} (#{Gitlab.config.gitlab.host})").join(' ')
+ key.split[0..1].push("#{user_name} (#{Gitlab.config.gitlab.host})").join(" ")
end
# projects that has this key
@@ -130,7 +130,7 @@ class Key < ActiveRecord::Base
Gitlab::CurrentSettings
.allowed_key_types
.map(&:upcase)
- .to_sentence(last_word_connector: ', or ', two_words_connector: ' or ')
+ .to_sentence(last_word_connector: ", or ", two_words_connector: " or ")
"type is forbidden. Must be #{allowed_types}"
end
diff --git a/app/models/label.rb b/app/models/label.rb
index 1c3db3eb35d..3237350ff04 100644
--- a/app/models/label.rb
+++ b/app/models/label.rb
@@ -11,41 +11,41 @@ class Label < ActiveRecord::Base
cache_markdown_field :description, pipeline: :single_line
- DEFAULT_COLOR = '#428BCA'
- NONE = 'no label'
+ DEFAULT_COLOR = "#428BCA"
+ NONE = "no label"
default_value_for :color, DEFAULT_COLOR
has_many :lists, dependent: :destroy # rubocop:disable Cop/ActiveRecordDependent
- has_many :priorities, class_name: 'LabelPriority'
+ has_many :priorities, class_name: "LabelPriority"
has_many :label_links, dependent: :destroy # rubocop:disable Cop/ActiveRecordDependent
- has_many :issues, through: :label_links, source: :target, source_type: 'Issue'
- has_many :merge_requests, through: :label_links, source: :target, source_type: 'MergeRequest'
+ has_many :issues, through: :label_links, source: :target, source_type: "Issue"
+ has_many :merge_requests, through: :label_links, source: :target, source_type: "MergeRequest"
before_validation :strip_whitespace_from_title_and_color
validates :color, color: true, allow_blank: false
# Don't allow ',' for label titles
- validates :title, presence: true, format: { with: /\A[^,]+\z/ }
- validates :title, uniqueness: { scope: [:group_id, :project_id] }
- validates :title, length: { maximum: 255 }
+ validates :title, presence: true, format: {with: /\A[^,]+\z/}
+ validates :title, uniqueness: {scope: [:group_id, :project_id]}
+ validates :title, length: {maximum: 255}
default_scope { order(title: :asc) }
scope :templates, -> { where(template: true) }
scope :with_title, ->(title) { where(title: title) }
scope :with_lists_and_board, -> { joins(lists: :board).merge(List.movable) }
- scope :on_project_boards, ->(project_id) { with_lists_and_board.where(boards: { project_id: project_id }) }
- scope :on_board, ->(board_id) { with_lists_and_board.where(boards: { id: board_id }) }
+ scope :on_project_boards, ->(project_id) { with_lists_and_board.where(boards: {project_id: project_id}) }
+ scope :on_board, ->(board_id) { with_lists_and_board.where(boards: {id: board_id}) }
scope :order_name_asc, -> { reorder(title: :asc) }
scope :order_name_desc, -> { reorder(title: :desc) }
- scope :subscribed_by, ->(user_id) { joins(:subscriptions).where(subscriptions: { user_id: user_id, subscribed: true }) }
+ scope :subscribed_by, ->(user_id) { joins(:subscriptions).where(subscriptions: {user_id: user_id, subscribed: true}) }
def self.prioritized(project)
joins(:priorities)
- .where(label_priorities: { project_id: project })
- .reorder('label_priorities.priority ASC, labels.title ASC')
+ .where(label_priorities: {project_id: project})
+ .reorder("label_priorities.priority ASC, labels.title ASC")
end
def self.unprioritized(project)
@@ -53,8 +53,8 @@ class Label < ActiveRecord::Base
priorities = LabelPriority.arel_table
label_priorities = labels.join(priorities, Arel::Nodes::OuterJoin)
- .on(labels[:id].eq(priorities[:label_id]).and(priorities[:project_id].eq(project.id)))
- .join_sources
+ .on(labels[:id].eq(priorities[:label_id]).and(priorities[:project_id].eq(project.id)))
+ .join_sources
joins(label_priorities).where(priorities[:priority].eq(nil))
end
@@ -64,8 +64,8 @@ class Label < ActiveRecord::Base
priorities = LabelPriority.arel_table
label_priorities = labels.join(priorities, Arel::Nodes::OuterJoin)
- .on(labels[:id].eq(priorities[:label_id]))
- .join_sources
+ .on(labels[:id].eq(priorities[:label_id]))
+ .join_sources
joins(label_priorities)
end
@@ -81,7 +81,7 @@ class Label < ActiveRecord::Base
alias_attribute :name, :title
def self.reference_prefix
- '~'
+ "~"
end
##
@@ -127,19 +127,19 @@ class Label < ActiveRecord::Base
end
def open_issues_count(user = nil)
- issues_count(user, state: 'opened')
+ issues_count(user, state: "opened")
end
def closed_issues_count(user = nil)
- issues_count(user, state: 'closed')
+ issues_count(user, state: "closed")
end
def open_merge_requests_count(user = nil)
params = {
subject_foreign_key => subject.id,
- label_name: title,
- scope: 'all',
- state: 'opened'
+ :label_name => title,
+ :scope => "all",
+ :state => "opened",
}
MergeRequestsFinder.new(user, params.with_indifferent_access).execute.count
@@ -157,10 +157,10 @@ class Label < ActiveRecord::Base
def priority(project)
priority = if priorities.loaded?
- priorities.first { |p| p.project == project }
- else
- priorities.find_by(project: project)
- end
+ priorities.first { |p| p.project == project }
+ else
+ priorities.find_by(project: project)
+ end
priority.try(:priority)
end
@@ -178,7 +178,7 @@ class Label < ActiveRecord::Base
end
def text_color
- LabelsHelper.text_color_for_bg(self.color)
+ LabelsHelper.text_color_for_bg(color)
end
def title=(value)
@@ -212,7 +212,7 @@ class Label < ActiveRecord::Base
def as_json(options = {})
super(options).tap do |json|
- json[:type] = self.try(:type)
+ json[:type] = try(:type)
json[:priority] = priority(options[:project]) if options.key?(:project)
json[:textColor] = text_color
end
@@ -225,12 +225,12 @@ class Label < ActiveRecord::Base
private
def issues_count(user, params = {})
- params.merge!(subject_foreign_key => subject.id, label_name: title, scope: 'all')
+ params.merge!(subject_foreign_key => subject.id, :label_name => title, :scope => "all")
IssuesFinder.new(user, params.with_indifferent_access).execute.count
end
def label_format_reference(format = :id)
- raise StandardError, 'Unknown format' unless [:id, :name].include?(format)
+ raise StandardError, "Unknown format" unless [:id, :name].include?(format)
if format == :name && !name.include?('"')
%("#{name}")
@@ -244,6 +244,6 @@ class Label < ActiveRecord::Base
end
def strip_whitespace_from_title_and_color
- %w(color title).each { |attr| self[attr] = self[attr]&.strip }
+ %w[color title].each { |attr| self[attr] = self[attr]&.strip }
end
end
diff --git a/app/models/label_note.rb b/app/models/label_note.rb
index 680952cf421..e9fd31c3572 100644
--- a/app/models/label_note.rb
+++ b/app/models/label_note.rb
@@ -13,9 +13,9 @@ class LabelNote < Note
created_at: events.first.created_at,
discussion_id: events.first.discussion_id,
noteable: resource,
- system_note_metadata: SystemNoteMetadata.new(action: 'label'),
+ system_note_metadata: SystemNoteMetadata.new(action: "label"),
events: events,
- resource_parent: resource_parent
+ resource_parent: resource_parent,
}
if resource_parent.is_a?(Project)
@@ -62,10 +62,10 @@ class LabelNote < Note
end
def note_text(html: false)
- added = labels_str('added', label_refs_by_action('add', html))
- removed = labels_str('removed', label_refs_by_action('remove', html))
+ added = labels_str("added", label_refs_by_action("add", html))
+ removed = labels_str("removed", label_refs_by_action("remove", html))
- [added, removed].compact.join(' and ')
+ [added, removed].compact.join(" and ")
end
# returns string containing added/removed labels including
@@ -76,15 +76,15 @@ class LabelNote < Note
# added ~1 ~2 labels
def labels_str(prefix, label_refs)
existing_refs = label_refs.select { |ref| ref.present? }.sort
- refs_str = existing_refs.empty? ? nil : existing_refs.join(' ')
+ refs_str = existing_refs.empty? ? nil : existing_refs.join(" ")
deleted = label_refs.count - existing_refs.count
deleted_str = deleted == 0 ? nil : "#{deleted} deleted"
return nil unless refs_str || deleted_str
- label_list_str = [refs_str, deleted_str].compact.join(' + ')
- suffix = 'label'.pluralize(deleted > 0 ? deleted : existing_refs.count)
+ label_list_str = [refs_str, deleted_str].compact.join(" + ")
+ suffix = "label".pluralize(deleted > 0 ? deleted : existing_refs.count)
"#{prefix} #{label_list_str} #{suffix}"
end
diff --git a/app/models/label_priority.rb b/app/models/label_priority.rb
index 8ed8bb7577f..4d91b4edd21 100644
--- a/app/models/label_priority.rb
+++ b/app/models/label_priority.rb
@@ -5,6 +5,6 @@ class LabelPriority < ActiveRecord::Base
belongs_to :label
validates :project, :label, :priority, presence: true
- validates :label_id, uniqueness: { scope: :project_id }
- validates :priority, numericality: { only_integer: true, greater_than_or_equal_to: 0 }
+ validates :label_id, uniqueness: {scope: :project_id}
+ validates :priority, numericality: {only_integer: true, greater_than_or_equal_to: 0}
end
diff --git a/app/models/legacy_diff_discussion.rb b/app/models/legacy_diff_discussion.rb
index 7d78c580fa2..50fd7ce1f68 100644
--- a/app/models/legacy_diff_discussion.rb
+++ b/app/models/legacy_diff_discussion.rb
@@ -42,8 +42,6 @@ class LegacyDiffDiscussion < Discussion
if active?
{}
- else
- nil
end
end
diff --git a/app/models/legacy_diff_note.rb b/app/models/legacy_diff_note.rb
index 00dec6bb92b..92b9b38e507 100644
--- a/app/models/legacy_diff_note.rb
+++ b/app/models/legacy_diff_note.rb
@@ -20,11 +20,11 @@ class LegacyDiffNote < Note
end
def project_repository
- Gitlab::SafeRequestStore.fetch("project:#{project_id}:repository") { self.project.repository }
+ Gitlab::SafeRequestStore.fetch("project:#{project_id}:repository") { project.repository }
end
def diff_file_hash
- line_code.split('_')[0] if line_code
+ line_code.split("_")[0] if line_code
end
def diff
@@ -36,11 +36,11 @@ class LegacyDiffNote < Note
end
def diff_line
- @diff_line ||= diff_file&.line_for_line_code(self.line_code)
+ @diff_line ||= diff_file&.line_for_line_code(line_code)
end
def original_line_code
- self.line_code
+ line_code
end
# Check if this note is part of an "active" discussion
@@ -76,9 +76,9 @@ class LegacyDiffNote < Note
return nil unless noteable
return @diff if defined?(@diff)
- @diff = noteable.raw_diffs(Commit.max_diff_options).find do |d|
+ @diff = noteable.raw_diffs(Commit.max_diff_options).find { |d|
d.new_path && Digest::SHA1.hexdigest(d.new_path) == diff_file_hash
- end
+ }
end
def set_diff
@@ -93,7 +93,7 @@ class LegacyDiffNote < Note
def diff_for_line_code
attributes = {
noteable_type: noteable_type,
- line_code: line_code
+ line_code: line_code,
}
if for_commit?
@@ -108,6 +108,6 @@ class LegacyDiffNote < Note
# Find the diff on noteable that matches our own
def find_noteable_diff
diffs = noteable.raw_diffs(Commit.max_diff_options)
- diffs.find { |d| d.new_path == self.diff.new_path }
+ diffs.find { |d| d.new_path == diff.new_path }
end
end
diff --git a/app/models/lfs_download_object.rb b/app/models/lfs_download_object.rb
index 6383f95d546..e59a2d40280 100644
--- a/app/models/lfs_download_object.rb
+++ b/app/models/lfs_download_object.rb
@@ -6,9 +6,9 @@ class LfsDownloadObject
attr_accessor :oid, :size, :link
delegate :sanitized_url, :credentials, to: :sanitized_uri
- validates :oid, format: { with: /\A\h{64}\z/ }
- validates :size, numericality: { greater_than_or_equal_to: 0 }
- validates :link, public_url: { protocols: %w(http https) }
+ validates :oid, format: {with: /\A\h{64}\z/}
+ validates :size, numericality: {greater_than_or_equal_to: 0}
+ validates :link, public_url: {protocols: %w[http https]}
def initialize(oid:, size:, link:)
@oid = oid
diff --git a/app/models/lfs_object.rb b/app/models/lfs_object.rb
index 69c563545bb..3e08a616bd2 100644
--- a/app/models/lfs_object.rb
+++ b/app/models/lfs_object.rb
@@ -18,7 +18,7 @@ class LfsObject < ActiveRecord::Base
def update_file_store
# The file.object_store is set during `uploader.store!`
# which happens after object is inserted/updated
- self.update_column(:file_store, file.object_store)
+ update_column(:file_store, file.object_store)
end
def project_allowed_access?(project)
@@ -32,8 +32,8 @@ class LfsObject < ActiveRecord::Base
# rubocop: disable DestroyAll
def self.destroy_unreferenced
joins("LEFT JOIN lfs_objects_projects ON lfs_objects_projects.lfs_object_id = #{table_name}.id")
- .where(lfs_objects_projects: { id: nil })
- .destroy_all
+ .where(lfs_objects_projects: {id: nil})
+ .destroy_all
end
# rubocop: enable DestroyAll
diff --git a/app/models/lfs_objects_project.rb b/app/models/lfs_objects_project.rb
index 353602800d7..6140126aca6 100644
--- a/app/models/lfs_objects_project.rb
+++ b/app/models/lfs_objects_project.rb
@@ -5,7 +5,7 @@ class LfsObjectsProject < ActiveRecord::Base
belongs_to :lfs_object
validates :lfs_object_id, presence: true
- validates :lfs_object_id, uniqueness: { scope: [:project_id], message: "already exists in project" }
+ validates :lfs_object_id, uniqueness: {scope: [:project_id], message: "already exists in project"}
validates :project_id, presence: true
after_commit :update_project_statistics, on: [:create, :destroy]
diff --git a/app/models/license_template.rb b/app/models/license_template.rb
index 73e403f98b4..ad00d45560e 100644
--- a/app/models/license_template.rb
+++ b/app/models/license_template.rb
@@ -27,7 +27,7 @@ class LicenseTemplate
def popular?
category == :Popular
end
- alias_method :featured?, :popular?
+ alias featured? popular?
# Returns the text of the license
def content
diff --git a/app/models/list.rb b/app/models/list.rb
index 682af761ba0..c9dfc6a2afd 100644
--- a/app/models/list.rb
+++ b/app/models/list.rb
@@ -4,12 +4,12 @@ class List < ActiveRecord::Base
belongs_to :board
belongs_to :label
- enum list_type: { backlog: 0, label: 1, closed: 2, assignee: 3, milestone: 4 }
+ enum list_type: {backlog: 0, label: 1, closed: 2, assignee: 3, milestone: 4}
validates :board, :list_type, presence: true
validates :label, :position, presence: true, if: :label?
- validates :label_id, uniqueness: { scope: :board_id }, if: :label?
- validates :position, numericality: { only_integer: true, greater_than_or_equal_to: 0 }, if: :movable?
+ validates :label_id, uniqueness: {scope: :board_id}, if: :label?
+ validates :position, numericality: {only_integer: true, greater_than_or_equal_to: 0}, if: :movable?
before_destroy :can_be_destroyed
diff --git a/app/models/member.rb b/app/models/member.rb
index 8e071a8ff21..4e4842e2e46 100644
--- a/app/models/member.rb
+++ b/app/models/member.rb
@@ -19,21 +19,21 @@ class Member < ActiveRecord::Base
validates :user, presence: true, unless: :invite?
validates :source, presence: true
- validates :user_id, uniqueness: { scope: [:source_type, :source_id],
- message: "already exists in source",
- allow_nil: true }
- validates :access_level, inclusion: { in: Gitlab::Access.all_values }, presence: true
+ validates :user_id, uniqueness: {scope: [:source_type, :source_id],
+ message: "already exists in source",
+ allow_nil: true,}
+ validates :access_level, inclusion: {in: Gitlab::Access.all_values}, presence: true
validate :higher_access_level_than_group, unless: :importing?
validates :invite_email,
presence: {
- if: :invite?
+ if: :invite?,
},
email: {
- allow_nil: true
+ allow_nil: true,
},
uniqueness: {
scope: [:source_type, :source_id],
- allow_nil: true
+ allow_nil: true,
}
# This scope encapsulates (most of) the conditions a row in the member table
@@ -58,7 +58,7 @@ class Member < ActiveRecord::Base
# Like active, but without invites. For when a User is required.
scope :active_without_invites_and_requests, -> do
left_join_users
- .where(users: { state: 'active' })
+ .where(users: {state: "active"})
.non_request
.reorder(nil)
end
@@ -68,7 +68,7 @@ class Member < ActiveRecord::Base
scope :request, -> { where.not(requested_at: nil) }
scope :non_request, -> { where(requested_at: nil) }
- scope :has_access, -> { active.where('access_level > 0') }
+ scope :has_access, -> { active.where("access_level > 0") }
scope :guests, -> { active.where(access_level: GUEST) }
scope :reporters, -> { active.where(access_level: REPORTER) }
@@ -77,17 +77,17 @@ class Member < ActiveRecord::Base
scope :masters, -> { maintainers } # @deprecated
scope :owners, -> { active.where(access_level: OWNER) }
scope :owners_and_maintainers, -> { active.where(access_level: [OWNER, MAINTAINER]) }
- scope :owners_and_masters, -> { owners_and_maintainers } # @deprecated
- scope :with_user, -> (user) { where(user: user) }
+ scope :owners_and_masters, -> { owners_and_maintainers } # @deprecated
+ scope :with_user, ->(user) { where(user: user) }
- scope :order_name_asc, -> { left_join_users.reorder(Gitlab::Database.nulls_last_order('users.name', 'ASC')) }
- scope :order_name_desc, -> { left_join_users.reorder(Gitlab::Database.nulls_last_order('users.name', 'DESC')) }
- scope :order_recent_sign_in, -> { left_join_users.reorder(Gitlab::Database.nulls_last_order('users.last_sign_in_at', 'DESC')) }
- scope :order_oldest_sign_in, -> { left_join_users.reorder(Gitlab::Database.nulls_last_order('users.last_sign_in_at', 'ASC')) }
+ scope :order_name_asc, -> { left_join_users.reorder(Gitlab::Database.nulls_last_order("users.name", "ASC")) }
+ scope :order_name_desc, -> { left_join_users.reorder(Gitlab::Database.nulls_last_order("users.name", "DESC")) }
+ scope :order_recent_sign_in, -> { left_join_users.reorder(Gitlab::Database.nulls_last_order("users.last_sign_in_at", "DESC")) }
+ scope :order_oldest_sign_in, -> { left_join_users.reorder(Gitlab::Database.nulls_last_order("users.last_sign_in_at", "ASC")) }
scope :on_project_and_ancestors, ->(project) { where(source: [project] + project.ancestors) }
- before_validation :generate_invite_token, on: :create, if: -> (member) { member.invite_email.present? }
+ before_validation :generate_invite_token, on: :create, if: ->(member) { member.invite_email.present? }
after_create :send_invite, if: :invite?, unless: :importing?
after_create :send_request, if: :request?, unless: :importing?
@@ -107,9 +107,9 @@ class Member < ActiveRecord::Base
def filter_by_2fa(value)
case value
- when 'enabled'
+ when "enabled"
left_join_users.merge(User.with_two_factor)
- when 'disabled'
+ when "disabled"
left_join_users.merge(User.without_two_factor)
else
all
@@ -118,12 +118,12 @@ class Member < ActiveRecord::Base
def sort_by_attribute(method)
case method.to_s
- when 'access_level_asc' then reorder(access_level: :asc)
- when 'access_level_desc' then reorder(access_level: :desc)
- when 'recent_sign_in' then order_recent_sign_in
- when 'oldest_sign_in' then order_oldest_sign_in
- when 'last_joined' then order_created_desc
- when 'oldest_joined' then order_created_asc
+ when "access_level_asc" then reorder(access_level: :asc)
+ when "access_level_desc" then reorder(access_level: :desc)
+ when "recent_sign_in" then order_recent_sign_in
+ when "oldest_sign_in" then order_oldest_sign_in
+ when "last_joined" then order_created_desc
+ when "oldest_joined" then order_created_asc
else
order_by(method)
end
@@ -134,8 +134,8 @@ class Member < ActiveRecord::Base
members = Member.arel_table
member_users = members.join(users, Arel::Nodes::OuterJoin)
- .on(members[:user_id].eq(users[:id]))
- .join_sources
+ .on(members[:user_id].eq(users[:id]))
+ .join_sources
joins(member_users)
end
@@ -190,7 +190,7 @@ class Member < ActiveRecord::Base
member.attributes = {
created_by: member.created_by || current_user,
access_level: access_level,
- expires_at: expires_at
+ expires_at: expires_at,
}
end
@@ -199,7 +199,7 @@ class Member < ActiveRecord::Base
emails, users, existing_members = parse_users_list(source, users)
- self.transaction do
+ transaction do
(emails + users).map! do |user|
add_user(
source,
@@ -285,7 +285,7 @@ class Member < ActiveRecord::Base
end
def invite?
- self.invite_token.present?
+ invite_token.present?
end
def request?
@@ -299,7 +299,7 @@ class Member < ActiveRecord::Base
def accept_request
return false unless request?
- updated = self.update(requested_at: nil)
+ updated = update(requested_at: nil)
after_accept_request if updated
updated
@@ -313,7 +313,7 @@ class Member < ActiveRecord::Base
self.user = new_user
- saved = self.save
+ saved = save
after_accept_invite if saved
@@ -323,7 +323,7 @@ class Member < ActiveRecord::Base
def decline_invite!
return false unless invite?
- destroyed = self.destroy
+ destroyed = destroy
after_decline_invite if destroyed
@@ -447,7 +447,7 @@ class Member < ActiveRecord::Base
def higher_access_level_than_group
if highest_group_member && highest_group_member.access_level >= access_level
- error_parameters = { access: highest_group_member.human_access, group_name: highest_group_member.group.name }
+ error_parameters = {access: highest_group_member.human_access, group_name: highest_group_member.group.name}
errors.add(:access_level, s_("should be higher than %{access} inherited membership from group %{group_name}") % error_parameters)
end
diff --git a/app/models/members/group_member.rb b/app/models/members/group_member.rb
index 2c9e1ba1d80..1bd91baa75f 100644
--- a/app/models/members/group_member.rb
+++ b/app/models/members/group_member.rb
@@ -1,15 +1,15 @@
# frozen_string_literal: true
class GroupMember < Member
- SOURCE_TYPE = 'Namespace'.freeze
+ SOURCE_TYPE = "Namespace"
- belongs_to :group, foreign_key: 'source_id'
+ belongs_to :group, foreign_key: "source_id"
delegate :update_two_factor_requirement, to: :user
# Make sure group member points only to group as it source
default_value_for :source_type, SOURCE_TYPE
- validates :source_type, format: { with: /\ANamespace\z/ }
+ validates :source_type, format: {with: /\ANamespace\z/}
default_scope { where(source_type: SOURCE_TYPE) }
scope :in_groups, ->(groups) { where(source_id: groups.select(:id)) }
@@ -31,11 +31,11 @@ class GroupMember < Member
# Because source_type is `Namespace`...
def real_source_type
- 'Group'
+ "Group"
end
def notifiable_options
- { group: group }
+ {group: group}
end
private
diff --git a/app/models/members/project_member.rb b/app/models/members/project_member.rb
index 5372c6084f4..cdb7eb8bb53 100644
--- a/app/models/members/project_member.rb
+++ b/app/models/members/project_member.rb
@@ -1,20 +1,20 @@
# frozen_string_literal: true
class ProjectMember < Member
- SOURCE_TYPE = 'Project'.freeze
+ SOURCE_TYPE = "Project"
- belongs_to :project, foreign_key: 'source_id'
+ belongs_to :project, foreign_key: "source_id"
# Make sure project member points only to project as it source
default_value_for :source_type, SOURCE_TYPE
- validates :source_type, format: { with: /\AProject\z/ }
- validates :access_level, inclusion: { in: Gitlab::Access.values }
+ validates :source_type, format: {with: /\AProject\z/}
+ validates :access_level, inclusion: {in: Gitlab::Access.values}
default_scope { where(source_type: SOURCE_TYPE) }
scope :in_project, ->(project) { where(source_id: project.id) }
scope :in_namespaces, ->(groups) do
- joins('INNER JOIN projects ON projects.id = members.source_id')
- .where('projects.namespace_id in (?)', groups.select(:id))
+ joins("INNER JOIN projects ON projects.id = members.source_id")
+ .where("projects.namespace_id in (?)", groups.select(:id))
end
class << self
@@ -37,7 +37,7 @@ class ProjectMember < Member
# )
#
def add_users_to_projects(project_ids, users, access_level, current_user: nil, expires_at: nil)
- self.transaction do
+ transaction do
project_ids.each do |project_id|
project = Project.find(project_id)
@@ -90,7 +90,7 @@ class ProjectMember < Member
end
def notifiable_options
- { project: project }
+ {project: project}
end
private
@@ -103,7 +103,7 @@ class ProjectMember < Member
def post_create_hook
unless owner?
- event_service.join_project(self.project, self.user)
+ event_service.join_project(project, user)
run_after_commit_or_now { notification_service.new_project_member(self) }
end
@@ -120,9 +120,9 @@ class ProjectMember < Member
def post_destroy_hook
if expired?
- event_service.expired_leave_project(self.project, self.user)
+ event_service.expired_leave_project(project, user)
else
- event_service.leave_project(self.project, self.user)
+ event_service.leave_project(project, user)
end
super
diff --git a/app/models/merge_request.rb b/app/models/merge_request.rb
index 1468ae1c34a..7bdd3c64d29 100644
--- a/app/models/merge_request.rb
+++ b/app/models/merge_request.rb
@@ -24,8 +24,8 @@ class MergeRequest < ActiveRecord::Base
SORTING_PREFERENCE_FIELD = :merge_requests_sort
ignore_column :locked_at,
- :ref_fetched,
- :deleted_at
+ :ref_fetched,
+ :deleted_at
belongs_to :target_project, class_name: "Project"
belongs_to :source_project, class_name: "Project"
@@ -36,9 +36,9 @@ class MergeRequest < ActiveRecord::Base
has_many :merge_request_diffs
has_one :merge_request_diff,
- -> { order('merge_request_diffs.id DESC') }, inverse_of: :merge_request
+ -> { order("merge_request_diffs.id DESC") }, inverse_of: :merge_request
- belongs_to :latest_merge_request_diff, class_name: 'MergeRequestDiff'
+ belongs_to :latest_merge_request_diff, class_name: "MergeRequestDiff"
manual_inverse_association :latest_merge_request_diff, :merge_request
# This is the same as latest_merge_request_diff unless:
@@ -61,11 +61,11 @@ class MergeRequest < ActiveRecord::Base
has_many :events, as: :target, dependent: :destroy # rubocop:disable Cop/ActiveRecordDependent
has_many :merge_requests_closing_issues,
- class_name: 'MergeRequestsClosingIssues',
+ class_name: "MergeRequestsClosingIssues",
dependent: :delete_all # rubocop:disable Cop/ActiveRecordDependent
has_many :cached_closes_issues, through: :merge_requests_closing_issues, source: :issue
- has_many :merge_request_pipelines, foreign_key: 'merge_request_id', class_name: 'Ci::Pipeline'
+ has_many :merge_request_pipelines, foreign_key: "merge_request_id", class_name: "Ci::Pipeline"
belongs_to :assignee, class_name: "User"
@@ -177,7 +177,7 @@ class MergeRequest < ActiveRecord::Base
scope :closed_and_merged, -> { with_states(:closed, :merged) }
scope :from_source_branches, ->(branches) { where(source_branch: branches) }
scope :by_commit_sha, ->(sha) do
- where('EXISTS (?)', MergeRequestDiff.select(1).where('merge_requests.latest_merge_request_diff_id = merge_request_diffs.id').by_commit_sha(sha)).reorder(nil)
+ where("EXISTS (?)", MergeRequestDiff.select(1).where("merge_requests.latest_merge_request_diff_id = merge_request_diffs.id").by_commit_sha(sha)).reorder(nil)
end
scope :join_project, -> { joins(:target_project) }
scope :references_project, -> { references(:target_project) }
@@ -190,7 +190,7 @@ class MergeRequest < ActiveRecord::Base
after_save :keep_around_commit
def self.reference_prefix
- '!'
+ "!"
end
def rebase_in_progress?
@@ -234,7 +234,7 @@ class MergeRequest < ActiveRecord::Base
end
def self.project_foreign_key
- 'target_project_id'
+ "target_project_id"
end
# Returns all the merge requests from an ActiveRecord:Relation.
@@ -267,7 +267,7 @@ class MergeRequest < ActiveRecord::Base
WHERE merge_requests.id = merge_request_diffs.merge_request_id
)'.squish
- self.each_batch do |batch|
+ each_batch do |batch|
batch.update_all(update)
end
end
@@ -291,13 +291,13 @@ class MergeRequest < ActiveRecord::Base
end
def authors
- User.from_union([commit_authors, User.where(id: self.author_id)])
+ User.from_union([commit_authors, User.where(id: author_id)])
end
# Verifies if title has changed not taking into account WIP prefix
# for merge requests.
def wipless_title_changed(old_title)
- self.class.wipless_title(old_title) != self.wipless_title
+ self.class.wipless_title(old_title) != wipless_title
end
def hook_attrs
@@ -307,8 +307,8 @@ class MergeRequest < ActiveRecord::Base
# Returns a Hash of attributes to be used for Twitter card metadata
def card_attributes
{
- 'Author' => author.try(:name),
- 'Assignee' => assignee.try(:name)
+ "Author" => author.try(:name),
+ "Assignee" => assignee.try(:name),
}
end
@@ -340,10 +340,10 @@ class MergeRequest < ActiveRecord::Base
return merge_request_diff.commits if persisted?
commits_arr = if compare_commits
- compare_commits.reverse
- else
- []
- end
+ compare_commits.reverse
+ else
+ []
+ end
CommitCollection.new(source_project, commits_arr, source_branch)
end
@@ -452,12 +452,12 @@ class MergeRequest < ActiveRecord::Base
def modified_paths(past_merge_request_diff: nil)
diffs = if past_merge_request_diff
- past_merge_request_diff
- elsif compare
- compare
- else
- self.merge_request_diff
- end
+ past_merge_request_diff
+ elsif compare
+ compare
+ else
+ merge_request_diff
+ end
diffs.modified_paths
end
@@ -571,9 +571,9 @@ class MergeRequest < ActiveRecord::Base
# most recent data possible.
def repository_diff_refs
Gitlab::Diff::DiffRefs.new(
- base_sha: branch_merge_base_sha,
+ base_sha: branch_merge_base_sha,
start_sha: target_branch_sha,
- head_sha: source_branch_sha
+ head_sha: source_branch_sha
)
end
@@ -610,7 +610,7 @@ class MergeRequest < ActiveRecord::Base
def validate_target_project
return true if target_project.merge_requests_enabled?
- errors.add :base, 'Target project has disabled merge requests'
+ errors.add :base, "Target project has disabled merge requests"
end
def validate_fork
@@ -619,7 +619,7 @@ class MergeRequest < ActiveRecord::Base
return true unless source_project_missing?
errors.add :validate_fork,
- 'Source project is not a fork of the target project'
+ "Source project is not a fork of the target project"
end
def merge_ongoing?
@@ -667,12 +667,12 @@ class MergeRequest < ActiveRecord::Base
matcher =
if diff_refs_or_sha.is_a?(Gitlab::Diff::DiffRefs)
{
- 'start_commit_sha' => diff_refs_or_sha.start_sha,
- 'head_commit_sha' => diff_refs_or_sha.head_sha,
- 'base_commit_sha' => diff_refs_or_sha.base_sha
+ "start_commit_sha" => diff_refs_or_sha.start_sha,
+ "head_commit_sha" => diff_refs_or_sha.head_sha,
+ "base_commit_sha" => diff_refs_or_sha.base_sha,
}
else
- { 'head_commit_sha' => diff_refs_or_sha }
+ {"head_commit_sha" => diff_refs_or_sha}
end
viewable_diffs.find do |diff|
@@ -682,11 +682,11 @@ class MergeRequest < ActiveRecord::Base
def version_params_for(diff_refs)
if diff = merge_request_diff_for(diff_refs)
- { diff_id: diff.id }
+ {diff_id: diff.id}
elsif diff = merge_request_diff_for(diff_refs.head_sha)
{
diff_id: diff.id,
- start_sha: diff_refs.start_sha
+ start_sha: diff_refs.start_sha,
}
end
end
@@ -727,11 +727,11 @@ class MergeRequest < ActiveRecord::Base
end
def merge_event
- @merge_event ||= target_project.events.where(target_id: self.id, target_type: "MergeRequest", action: Event::MERGED).last
+ @merge_event ||= target_project.events.where(target_id: id, target_type: "MergeRequest", action: Event::MERGED).last
end
def closed_event
- @closed_event ||= target_project.events.where(target_id: self.id, target_type: "MergeRequest", action: Event::CLOSED).last
+ @closed_event ||= target_project.events.where(target_id: id, target_type: "MergeRequest", action: Event::CLOSED).last
end
def work_in_progress?
@@ -739,11 +739,11 @@ class MergeRequest < ActiveRecord::Base
end
def wipless_title
- self.class.wipless_title(self.title)
+ self.class.wipless_title(title)
end
def wip_title
- self.class.wip_title(self.title)
+ self.class.wip_title(title)
end
def mergeable?(skip_ci_check: false)
@@ -783,7 +783,7 @@ class MergeRequest < ActiveRecord::Base
end
def can_cancel_merge_when_pipeline_succeeds?(current_user)
- can_be_merged_by?(current_user) || self.author == current_user
+ can_be_merged_by?(current_user) || author == current_user
end
def can_remove_source_branch?(current_user)
@@ -794,11 +794,11 @@ class MergeRequest < ActiveRecord::Base
end
def should_remove_source_branch?
- Gitlab::Utils.to_boolean(merge_params['should_remove_source_branch'])
+ Gitlab::Utils.to_boolean(merge_params["should_remove_source_branch"])
end
def force_remove_source_branch?
- Gitlab::Utils.to_boolean(merge_params['force_remove_source_branch'])
+ Gitlab::Utils.to_boolean(merge_params["force_remove_source_branch"])
end
def remove_source_branch?
@@ -835,7 +835,7 @@ class MergeRequest < ActiveRecord::Base
.includes(:noteable)
end
- alias_method :discussion_notes, :related_notes
+ alias discussion_notes related_notes
def mergeable_discussions_state?
return true unless project.only_allow_merge_if_all_discussions_are_resolved?
@@ -856,24 +856,24 @@ class MergeRequest < ActiveRecord::Base
# Calculating this information for a number of merge requests requires
# running `ReferenceExtractor` on each of them separately.
# This optimization does not apply to issues from external sources.
- def cache_merge_request_closes_issues!(current_user = self.author)
+ def cache_merge_request_closes_issues!(current_user = author)
return unless project.issues_enabled?
return if closed? || merged?
transaction do
- self.merge_requests_closing_issues.delete_all
+ merge_requests_closing_issues.delete_all
closes_issues(current_user).each do |issue|
next if issue.is_a?(ExternalIssue)
- self.merge_requests_closing_issues.create!(issue: issue)
+ merge_requests_closing_issues.create!(issue: issue)
end
end
end
- def visible_closing_issues_for(current_user = self.author)
+ def visible_closing_issues_for(current_user = author)
strong_memoize(:visible_closing_issues_for) do
- if self.target_project.has_external_issue_tracker?
+ if target_project.has_external_issue_tracker?
closes_issues(current_user)
else
cached_closes_issues.select do |issue|
@@ -884,7 +884,7 @@ class MergeRequest < ActiveRecord::Base
end
# Return the set of issues that will be closed if this merge request is accepted.
- def closes_issues(current_user = self.author)
+ def closes_issues(current_user = author)
if target_branch == project.default_branch
messages = [title, description]
messages.concat(commits.map(&:safe_message)) if merge_request_diff
@@ -922,7 +922,7 @@ class MergeRequest < ActiveRecord::Base
end
def source_project_namespace
- if source_project && source_project.namespace
+ if source_project&.namespace
source_project.namespace.full_path
else
"(removed)"
@@ -930,7 +930,7 @@ class MergeRequest < ActiveRecord::Base
end
def target_project_namespace
- if target_project && target_project.namespace
+ if target_project&.namespace
target_project.namespace.full_path
else
"(removed)"
@@ -938,32 +938,32 @@ class MergeRequest < ActiveRecord::Base
end
def source_branch_exists?
- return false unless self.source_project
+ return false unless source_project
- self.source_project.repository.branch_exists?(self.source_branch)
+ source_project.repository.branch_exists?(source_branch)
end
def target_branch_exists?
- return false unless self.target_project
+ return false unless target_project
- self.target_project.repository.branch_exists?(self.target_branch)
+ target_project.repository.branch_exists?(target_branch)
end
def default_merge_commit_message(include_description: false)
- closes_issues_references = visible_closing_issues_for.map do |issue|
+ closes_issues_references = visible_closing_issues_for.map { |issue|
issue.to_reference(target_project)
- end
+ }
message = [
"Merge branch '#{source_branch}' into '#{target_branch}'",
- title
+ title,
]
if !include_description && closes_issues_references.present?
message << "Closes #{closes_issues_references.to_sentence}"
end
- message << "#{description}" if include_description && description.present?
+ message << description.to_s if include_description && description.present?
message << "See merge request #{to_reference(full: true)}"
message.join("\n\n")
@@ -982,12 +982,12 @@ class MergeRequest < ActiveRecord::Base
self.merge_when_pipeline_succeeds = false
self.merge_user = nil
if merge_params
- merge_params.delete('should_remove_source_branch')
- merge_params.delete('commit_message')
- merge_params.delete('squash_commit_message')
+ merge_params.delete("should_remove_source_branch")
+ merge_params.delete("commit_message")
+ merge_params.delete("squash_commit_message")
end
- self.save
+ save
end
# Return array of possible target branches
@@ -1044,7 +1044,7 @@ class MergeRequest < ActiveRecord::Base
def environments_for(current_user)
return [] unless diff_head_commit
- @environments ||= Hash.new do |h, current_user|
+ @environments ||= Hash.new { |h, current_user|
envs = EnvironmentsFinder.new(target_project, current_user,
ref: target_branch, commit: diff_head_commit, with_tags: true).execute
@@ -1054,7 +1054,7 @@ class MergeRequest < ActiveRecord::Base
end
h[current_user] = envs.uniq
- end
+ }
@environments[current_user]
end
@@ -1092,12 +1092,10 @@ class MergeRequest < ActiveRecord::Base
end
def in_locked_state
- begin
- lock_mr
- yield
- ensure
- unlock_mr
- end
+ lock_mr
+ yield
+ ensure
+ unlock_mr
end
def diverged_commits_count
@@ -1107,7 +1105,7 @@ class MergeRequest < ActiveRecord::Base
cache = {
source_sha: source_branch_sha,
target_sha: target_branch_sha,
- diverged_commits_count: compute_diverged_commits_count
+ diverged_commits_count: compute_diverged_commits_count,
}
Rails.cache.write(:"merge_request_#{id}_diverged_commits", cache)
end
@@ -1132,7 +1130,7 @@ class MergeRequest < ActiveRecord::Base
@all_pipelines ||=
source_project.ci_pipelines
- .for_merge_request(self, source_branch, all_commit_shas)
+ .for_merge_request(self, source_branch, all_commit_shas)
end
def update_head_pipeline
@@ -1152,35 +1150,35 @@ class MergeRequest < ActiveRecord::Base
def predefined_variables
Gitlab::Ci::Variables::Collection.new.tap do |variables|
- variables.append(key: 'CI_MERGE_REQUEST_ID', value: id.to_s)
- variables.append(key: 'CI_MERGE_REQUEST_IID', value: iid.to_s)
+ variables.append(key: "CI_MERGE_REQUEST_ID", value: id.to_s)
+ variables.append(key: "CI_MERGE_REQUEST_IID", value: iid.to_s)
- variables.append(key: 'CI_MERGE_REQUEST_REF_PATH',
+ variables.append(key: "CI_MERGE_REQUEST_REF_PATH",
value: ref_path.to_s)
- variables.append(key: 'CI_MERGE_REQUEST_PROJECT_ID',
+ variables.append(key: "CI_MERGE_REQUEST_PROJECT_ID",
value: project.id.to_s)
- variables.append(key: 'CI_MERGE_REQUEST_PROJECT_PATH',
+ variables.append(key: "CI_MERGE_REQUEST_PROJECT_PATH",
value: project.full_path)
- variables.append(key: 'CI_MERGE_REQUEST_PROJECT_URL',
+ variables.append(key: "CI_MERGE_REQUEST_PROJECT_URL",
value: project.web_url)
- variables.append(key: 'CI_MERGE_REQUEST_TARGET_BRANCH_NAME',
+ variables.append(key: "CI_MERGE_REQUEST_TARGET_BRANCH_NAME",
value: target_branch.to_s)
if source_project
- variables.append(key: 'CI_MERGE_REQUEST_SOURCE_PROJECT_ID',
+ variables.append(key: "CI_MERGE_REQUEST_SOURCE_PROJECT_ID",
value: source_project.id.to_s)
- variables.append(key: 'CI_MERGE_REQUEST_SOURCE_PROJECT_PATH',
+ variables.append(key: "CI_MERGE_REQUEST_SOURCE_PROJECT_PATH",
value: source_project.full_path)
- variables.append(key: 'CI_MERGE_REQUEST_SOURCE_PROJECT_URL',
+ variables.append(key: "CI_MERGE_REQUEST_SOURCE_PROJECT_URL",
value: source_project.web_url)
- variables.append(key: 'CI_MERGE_REQUEST_SOURCE_BRANCH_NAME',
+ variables.append(key: "CI_MERGE_REQUEST_SOURCE_BRANCH_NAME",
value: source_branch.to_s)
end
end
@@ -1188,7 +1186,7 @@ class MergeRequest < ActiveRecord::Base
def compare_test_reports
unless has_test_reports?
- return { status: :error, status_reason: 'This merge request does not have test reports' }
+ return {status: :error, status_reason: "This merge request does not have test reports"}
end
compare_reports(Ci::CompareTestReportsService)
@@ -1197,12 +1195,12 @@ class MergeRequest < ActiveRecord::Base
def compare_reports(service_class)
with_reactive_cache(service_class.name) do |data|
unless service_class.new(project)
- .latest?(base_pipeline, actual_head_pipeline, data)
+ .latest?(base_pipeline, actual_head_pipeline, data)
raise InvalidateReactiveCache
end
data
- end || { status: :parsing }
+ end || {status: :parsing}
end
def calculate_reactive_cache(identifier, *args)
@@ -1216,10 +1214,10 @@ class MergeRequest < ActiveRecord::Base
def all_commits
# MySQL doesn't support LIMIT in a subquery.
diffs_relation = if Gitlab::Database.postgresql?
- merge_request_diffs.recent
- else
- merge_request_diffs
- end
+ merge_request_diffs.recent
+ else
+ merge_request_diffs
+ end
MergeRequestDiffCommit
.where(merge_request_diff: diffs_relation)
@@ -1254,7 +1252,7 @@ class MergeRequest < ActiveRecord::Base
# synchronized. Add a minute's leeway to compensate for both possibilities
cutoff = merged_at - 1.minute
- notes_association = notes_with_associations.where('created_at >= ?', cutoff)
+ notes_association = notes_with_associations.where("created_at >= ?", cutoff)
!merge_commit.has_been_reverted?(current_user, notes_association)
end
@@ -1265,7 +1263,7 @@ class MergeRequest < ActiveRecord::Base
metrics&.merged_at ||
merge_event&.created_at ||
- notes.system.reorder(nil).find_by(note: 'merged')&.created_at
+ notes.system.reorder(nil).find_by(note: "merged")&.created_at
end
end
@@ -1274,7 +1272,7 @@ class MergeRequest < ActiveRecord::Base
end
def has_complete_diff_refs?
- diff_refs && diff_refs.complete?
+ diff_refs&.complete?
end
# rubocop: disable CodeReuse/ServiceClass
@@ -1282,15 +1280,15 @@ class MergeRequest < ActiveRecord::Base
return unless has_complete_diff_refs?
return if new_diff_refs == old_diff_refs
- active_diff_discussions = self.notes.new_diff_notes.discussions.select do |discussion|
+ active_diff_discussions = notes.new_diff_notes.discussions.select { |discussion|
discussion.active?(old_diff_refs)
- end
+ }
return if active_diff_discussions.empty?
paths = active_diff_discussions.flat_map { |n| n.diff_file.paths }.uniq
service = Discussions::UpdateDiffPositionService.new(
- self.project,
+ project,
current_user,
old_diff_refs: old_diff_refs,
new_diff_refs: new_diff_refs,
@@ -1310,7 +1308,7 @@ class MergeRequest < ActiveRecord::Base
# rubocop: enable CodeReuse/ServiceClass
def keep_around_commit
- project.repository.keep_around(self.merge_commit_sha)
+ project.repository.keep_around(merge_commit_sha)
end
def has_commits?
@@ -1362,7 +1360,7 @@ class MergeRequest < ActiveRecord::Base
collaborative_push_possible? && allow_maintainer_to_push
end
- alias_method :allow_collaboration?, :allow_collaboration
+ alias allow_collaboration? allow_collaboration
def collaborative_push_possible?
source_project.present? && for_fork? &&
diff --git a/app/models/merge_request/metrics.rb b/app/models/merge_request/metrics.rb
index 65e94a97b0a..14d57a1389b 100644
--- a/app/models/merge_request/metrics.rb
+++ b/app/models/merge_request/metrics.rb
@@ -2,7 +2,7 @@
class MergeRequest::Metrics < ActiveRecord::Base
belongs_to :merge_request
- belongs_to :pipeline, class_name: 'Ci::Pipeline', foreign_key: :pipeline_id
- belongs_to :latest_closed_by, class_name: 'User'
- belongs_to :merged_by, class_name: 'User'
+ belongs_to :pipeline, class_name: "Ci::Pipeline", foreign_key: :pipeline_id
+ belongs_to :latest_closed_by, class_name: "User"
+ belongs_to :merged_by, class_name: "User"
end
diff --git a/app/models/merge_request_diff.rb b/app/models/merge_request_diff.rb
index e286a4e57f2..0d0a388bc02 100644
--- a/app/models/merge_request_diff.rb
+++ b/app/models/merge_request_diff.rb
@@ -42,7 +42,7 @@ class MergeRequestDiff < ActiveRecord::Base
scope :with_files, -> { without_states(:without_files, :empty) }
scope :viewable, -> { without_state(:empty) }
scope :by_commit_sha, ->(sha) do
- joins(:merge_request_diff_commits).where(merge_request_diff_commits: { sha: sha }).reorder(nil)
+ joins(:merge_request_diff_commits).where(merge_request_diff_commits: {sha: sha}).reorder(nil)
end
scope :recent, -> { order(id: :desc).limit(100) }
@@ -67,8 +67,8 @@ class MergeRequestDiff < ActiveRecord::Base
# and save it to the database as serialized data
def save_git_content
MergeRequest
- .where('id = ? AND COALESCE(latest_merge_request_diff_id, 0) < ?', self.merge_request_id, self.id)
- .update_all(latest_merge_request_diff_id: self.id)
+ .where("id = ? AND COALESCE(latest_merge_request_diff_id, 0) < ?", merge_request_id, id)
+ .update_all(latest_merge_request_diff_id: id)
ensure_commit_shas
save_commits
@@ -163,9 +163,9 @@ class MergeRequestDiff < ActiveRecord::Base
return unless start_commit_sha || base_commit_sha
Gitlab::Diff::DiffRefs.new(
- base_sha: base_commit_sha,
+ base_sha: base_commit_sha,
start_sha: start_commit_sha,
- head_sha: head_commit_sha
+ head_sha: head_commit_sha
)
end
@@ -186,9 +186,9 @@ class MergeRequestDiff < ActiveRecord::Base
likely_base_commit_sha = (first_commit&.parent || first_commit)&.sha
Gitlab::Diff::DiffRefs.new(
- base_sha: likely_base_commit_sha,
+ base_sha: likely_base_commit_sha,
start_sha: safe_start_commit_sha,
- head_sha: head_commit_sha
+ head_sha: head_commit_sha
)
end
@@ -229,7 +229,7 @@ class MergeRequestDiff < ActiveRecord::Base
end
def latest?
- self.id == merge_request.latest_merge_request_diff_id
+ id == merge_request.latest_merge_request_diff_id
end
# rubocop: disable CodeReuse/ServiceClass
@@ -249,7 +249,7 @@ class MergeRequestDiff < ActiveRecord::Base
# Carrierwave defines `write_uploader` dynamically on this class, so `super`
# does not work. Alias the carrierwave method so we can call it when needed
- alias_method :carrierwave_write_uploader, :write_uploader
+ alias carrierwave_write_uploader write_uploader
# The `external_diff`, `external_diff_store`, and `stored_externally`
# columns were introduced in GitLab 11.8, but some background migration specs
@@ -274,7 +274,7 @@ class MergeRequestDiff < ActiveRecord::Base
def stored_externally
super if has_attribute?(:stored_externally)
end
- alias_method :stored_externally?, :stored_externally
+ alias stored_externally? stored_externally
# If enabled, yields the external file containing the diff. Otherwise, yields
# nil. This method is not thread-safe, but it *is* re-entrant, which allows
@@ -284,13 +284,11 @@ class MergeRequestDiff < ActiveRecord::Base
return yield(@external_diff_file) if @external_diff_file
external_diff.open do |file|
- begin
- @external_diff_file = file
+ @external_diff_file = file
- yield(@external_diff_file)
- ensure
- @external_diff_file = nil
- end
+ yield(@external_diff_file)
+ ensure
+ @external_diff_file = nil
end
end
@@ -305,7 +303,7 @@ class MergeRequestDiff < ActiveRecord::Base
end
# Faster inserts
- Gitlab::Database.bulk_insert('merge_request_diff_files', rows)
+ Gitlab::Database.bulk_insert("merge_request_diff_files", rows)
end
def build_external_merge_request_diff_files(diffs)
@@ -340,7 +338,7 @@ class MergeRequestDiff < ActiveRecord::Base
diffs.map.with_index do |diff, index|
diff_hash = diff.to_hash.merge(
binary: false,
- merge_request_diff_id: self.id,
+ merge_request_diff_id: id,
relative_order: index
)
@@ -350,7 +348,7 @@ class MergeRequestDiff < ActiveRecord::Base
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
@@ -363,7 +361,7 @@ class MergeRequestDiff < ActiveRecord::Base
collection = merge_request_diff_files
if paths = options[:paths]
- collection = collection.where('old_path IN (?) OR new_path IN (?)', paths, paths)
+ collection = collection.where("old_path IN (?) OR new_path IN (?)", paths, paths)
end
Gitlab::Git::DiffCollection.new(collection.map(&:to_hash), options)
@@ -404,7 +402,7 @@ class MergeRequestDiff < ActiveRecord::Base
end
def save_commits
- MergeRequestDiffCommit.create_bulk(self.id, compare.commits.reverse)
+ MergeRequestDiffCommit.create_bulk(id, compare.commits.reverse)
# merge_request_diff_commits.reload is preferred way to reload associated
# objects but it returns cached result for some reason in this case
diff --git a/app/models/merge_request_diff_commit.rb b/app/models/merge_request_diff_commit.rb
index 4ad3690512d..e9e01a20aa8 100644
--- a/app/models/merge_request_diff_commit.rb
+++ b/app/models/merge_request_diff_commit.rb
@@ -11,7 +11,7 @@ class MergeRequestDiffCommit < ActiveRecord::Base
def self.create_bulk(merge_request_diff_id, commits)
sha_attribute = Gitlab::Database::ShaAttribute.new
- rows = commits.map.with_index do |commit, index|
+ rows = commits.map.with_index { |commit, index|
# See #parent_ids.
commit_hash = commit.to_hash.except(:parent_ids)
sha = commit_hash.delete(:id)
@@ -23,9 +23,9 @@ class MergeRequestDiffCommit < ActiveRecord::Base
authored_date: Gitlab::Database.sanitize_timestamp(commit_hash[:authored_date]),
committed_date: Gitlab::Database.sanitize_timestamp(commit_hash[:committed_date])
)
- end
+ }
- Gitlab::Database.bulk_insert(self.table_name, rows)
+ Gitlab::Database.bulk_insert(table_name, rows)
end
def to_hash
diff --git a/app/models/merge_request_diff_file.rb b/app/models/merge_request_diff_file.rb
index e8d936e265c..0ee789e609a 100644
--- a/app/models/merge_request_diff_file.rb
+++ b/app/models/merge_request_diff_file.rb
@@ -7,7 +7,7 @@ class MergeRequestDiffFile < ActiveRecord::Base
belongs_to :merge_request_diff, inverse_of: :merge_request_diff_files
def utf8_diff
- return '' if diff.blank?
+ return "" if diff.blank?
encode_utf8(diff) if diff.respond_to?(:encoding)
end
@@ -23,6 +23,6 @@ class MergeRequestDiffFile < ActiveRecord::Base
super
end
- binary? ? content.unpack('m0').first : content
+ binary? ? content.unpack1("m0") : content
end
end
diff --git a/app/models/merge_requests_closing_issues.rb b/app/models/merge_requests_closing_issues.rb
index 242b65bedc0..80e0af9cd11 100644
--- a/app/models/merge_requests_closing_issues.rb
+++ b/app/models/merge_requests_closing_issues.rb
@@ -4,14 +4,14 @@ class MergeRequestsClosingIssues < ActiveRecord::Base
belongs_to :merge_request
belongs_to :issue
- validates :merge_request_id, uniqueness: { scope: :issue_id }, presence: true
+ validates :merge_request_id, uniqueness: {scope: :issue_id}, presence: true
validates :issue_id, presence: true
class << self
def count_for_collection(ids)
group(:issue_id)
.where(issue_id: ids)
- .pluck('issue_id', 'COUNT(*) as count')
+ .pluck("issue_id", "COUNT(*) as count")
end
end
end
diff --git a/app/models/milestone.rb b/app/models/milestone.rb
index 26cfdc5ef30..c72c6d58135 100644
--- a/app/models/milestone.rb
+++ b/app/models/milestone.rb
@@ -4,10 +4,10 @@ class Milestone < ActiveRecord::Base
# Represents a "No Milestone" state used for filtering Issues and Merge
# Requests that have no milestone assigned.
MilestoneStruct = Struct.new(:title, :name, :id)
- None = MilestoneStruct.new('No Milestone', 'No Milestone', 0)
- Any = MilestoneStruct.new('Any Milestone', '', -1)
- Upcoming = MilestoneStruct.new('Upcoming', '#upcoming', -2)
- Started = MilestoneStruct.new('Started', '#started', -3)
+ None = MilestoneStruct.new("No Milestone", "No Milestone", 0)
+ Any = MilestoneStruct.new("Any Milestone", "", -1)
+ Upcoming = MilestoneStruct.new("Upcoming", "#upcoming", -2)
+ Started = MilestoneStruct.new("Started", "#started", -3)
include CacheMarkdownField
include AtomicInternalId
@@ -28,7 +28,7 @@ class Milestone < ActiveRecord::Base
has_internal_id :iid, scope: :group, init: ->(s) { s&.group&.milestones&.maximum(:iid) }
has_many :issues
- has_many :labels, -> { distinct.reorder('labels.title') }, through: :issues
+ has_many :labels, -> { distinct.reorder("labels.title") }, through: :issues
has_many :merge_requests
has_many :events, as: :target, dependent: :destroy # rubocop:disable Cop/ActiveRecordDependent
@@ -38,7 +38,7 @@ class Milestone < ActiveRecord::Base
scope :closed, -> { with_state(:closed) }
scope :for_projects, -> { where(group: nil).includes(:project) }
- scope :for_projects_and_groups, -> (projects, groups) do
+ scope :for_projects_and_groups, ->(projects, groups) do
projects = projects.compact if projects.is_a? Array
projects = [] if projects.nil?
@@ -49,7 +49,7 @@ class Milestone < ActiveRecord::Base
end
scope :order_by_name_asc, -> { order(Arel::Nodes::Ascending.new(arel_table[:title].lower)) }
- scope :reorder_by_due_date_asc, -> { reorder(Gitlab::Database.nulls_last_order('due_date', 'ASC')) }
+ scope :reorder_by_due_date_asc, -> { reorder(Gitlab::Database.nulls_last_order("due_date", "ASC")) }
validates :group, presence: true, unless: :project
validates :project, presence: true, unless: :group
@@ -101,8 +101,8 @@ class Milestone < ActiveRecord::Base
def filter_by_state(milestones, state)
case state
- when 'closed' then milestones.closed
- when 'all' then milestones
+ when "closed" then milestones.closed
+ when "all" then milestones
else milestones.active
end
end
@@ -120,7 +120,7 @@ class Milestone < ActiveRecord::Base
end
def self.reference_prefix
- '%'
+ "%"
end
def self.reference_pattern
@@ -148,11 +148,11 @@ class Milestone < ActiveRecord::Base
def self.upcoming_ids(projects, groups)
rel = unscoped
- .for_projects_and_groups(projects, groups)
- .active.where('milestones.due_date > NOW()')
+ .for_projects_and_groups(projects, groups)
+ .active.where("milestones.due_date > NOW()")
if Gitlab::Database.postgresql?
- rel.order(:project_id, :group_id, :due_date).select('DISTINCT ON (project_id, group_id) id')
+ rel.order(:project_id, :group_id, :due_date).select("DISTINCT ON (project_id, group_id) id")
else
# We need to use MySQL's NULL-safe comparison operator `<=>` here
# because one of `project_id` or `group_id` is always NULL
@@ -167,7 +167,7 @@ class Milestone < ActiveRecord::Base
rel
.joins(join_clause)
- .where('earlier_milestones.id IS NULL')
+ .where("earlier_milestones.id IS NULL")
.select(:id)
end
end
@@ -179,18 +179,18 @@ class Milestone < ActiveRecord::Base
def self.sort_by_attribute(method)
sorted =
case method.to_s
- when 'due_date_asc'
+ when "due_date_asc"
reorder_by_due_date_asc
- when 'due_date_desc'
- reorder(Gitlab::Database.nulls_last_order('due_date', 'DESC'))
- when 'name_asc'
+ when "due_date_desc"
+ reorder(Gitlab::Database.nulls_last_order("due_date", "DESC"))
+ when "name_asc"
reorder(Arel::Nodes::Ascending.new(arel_table[:title].lower))
- when 'name_desc'
+ when "name_desc"
reorder(Arel::Nodes::Descending.new(arel_table[:title].lower))
- when 'start_date_asc'
- reorder(Gitlab::Database.nulls_last_order('start_date', 'ASC'))
- when 'start_date_desc'
- reorder(Gitlab::Database.nulls_last_order('start_date', 'DESC'))
+ when "start_date_asc"
+ reorder(Gitlab::Database.nulls_last_order("start_date", "ASC"))
+ when "start_date_desc"
+ reorder(Gitlab::Database.nulls_last_order("start_date", "DESC"))
else
order_by(method)
end
@@ -202,15 +202,15 @@ class Milestone < ActiveRecord::Base
return STATE_COUNT_HASH unless projects || groups
counts = Milestone
- .for_projects_and_groups(projects, groups)
- .reorder(nil)
- .group(:state)
- .count
+ .for_projects_and_groups(projects, groups)
+ .reorder(nil)
+ .group(:state)
+ .count
{
- opened: counts['active'] || 0,
- closed: counts['closed'] || 0,
- all: counts.values.sum
+ opened: counts["active"] || 0,
+ closed: counts["closed"] || 0,
+ all: counts.values.sum,
}
end
@@ -240,7 +240,7 @@ class Milestone < ActiveRecord::Base
end
def reference_link_text(from = nil)
- self.class.reference_prefix + self.title
+ self.class.reference_prefix + title
end
def milestoneish_id
@@ -302,10 +302,10 @@ class Milestone < ActiveRecord::Base
end
def milestone_format_reference(format = :iid)
- raise ArgumentError, 'Unknown format' unless [:iid, :name].include?(format)
+ raise ArgumentError, "Unknown format" unless [:iid, :name].include?(format)
if group_milestone? && format == :iid
- raise ArgumentError, 'Cannot refer to a group milestone by an internal id!'
+ raise ArgumentError, "Cannot refer to a group milestone by an internal id!"
end
if format == :name && !name.include?('"')
@@ -326,6 +326,6 @@ class Milestone < ActiveRecord::Base
end
def issues_finder_params
- { project_id: project_id }
+ {project_id: project_id}
end
end
diff --git a/app/models/namespace.rb b/app/models/namespace.rb
index f7592532c5b..6e173e2549b 100644
--- a/app/models/namespace.rb
+++ b/app/models/namespace.rb
@@ -24,8 +24,8 @@ class Namespace < ApplicationRecord
has_many :projects, dependent: :destroy # rubocop:disable Cop/ActiveRecordDependent
has_many :project_statistics
- has_many :runner_namespaces, inverse_of: :namespace, class_name: 'Ci::RunnerNamespace'
- has_many :runners, through: :runner_namespaces, source: :runner, class_name: 'Ci::Runner'
+ has_many :runner_namespaces, inverse_of: :namespace, class_name: "Ci::RunnerNamespace"
+ has_many :runners, through: :runner_namespaces, source: :runner, class_name: "Ci::Runner"
# This should _not_ be `inverse_of: :namespace`, because that would also set
# `user.namespace` when this user creates a group with themselves as `owner`.
@@ -38,20 +38,20 @@ class Namespace < ApplicationRecord
validates :owner, presence: true, unless: ->(n) { n.type == "Group" }
validates :name,
presence: true,
- length: { maximum: 255 },
+ length: {maximum: 255},
namespace_name: true
- validates :description, length: { maximum: 255 }
+ validates :description, length: {maximum: 255}
validates :path,
presence: true,
- length: { maximum: 255 },
+ length: {maximum: 255},
namespace_path: true
validate :nesting_level_allowed
delegate :name, to: :owner, allow_nil: true, prefix: true
- after_commit :refresh_access_of_projects_invited_groups, on: :update, if: -> { previous_changes.key?('share_with_group_lock') }
+ after_commit :refresh_access_of_projects_invited_groups, on: :update, if: -> { previous_changes.key?("share_with_group_lock") }
before_create :sync_share_with_group_lock_with_parent
before_update :sync_share_with_group_lock_with_parent, if: :parent_changed?
@@ -63,23 +63,23 @@ class Namespace < ApplicationRecord
before_destroy(prepend: true) { prepare_for_destroy }
after_destroy :rm_dir
- scope :for_user, -> { where('type IS NULL') }
+ scope :for_user, -> { where("type IS NULL") }
scope :with_statistics, -> do
- joins('LEFT JOIN project_statistics ps ON ps.namespace_id = namespaces.id')
- .group('namespaces.id')
+ joins("LEFT JOIN project_statistics ps ON ps.namespace_id = namespaces.id")
+ .group("namespaces.id")
.select(
- 'namespaces.*',
- 'COALESCE(SUM(ps.storage_size), 0) AS storage_size',
- 'COALESCE(SUM(ps.repository_size), 0) AS repository_size',
- 'COALESCE(SUM(ps.lfs_objects_size), 0) AS lfs_objects_size',
- 'COALESCE(SUM(ps.build_artifacts_size), 0) AS build_artifacts_size'
+ "namespaces.*",
+ "COALESCE(SUM(ps.storage_size), 0) AS storage_size",
+ "COALESCE(SUM(ps.repository_size), 0) AS repository_size",
+ "COALESCE(SUM(ps.lfs_objects_size), 0) AS lfs_objects_size",
+ "COALESCE(SUM(ps.build_artifacts_size), 0) AS build_artifacts_size"
)
end
class << self
def by_path(path)
- find_by('lower(path) = :value', value: path.downcase)
+ find_by("lower(path) = :value", value: path.downcase)
end
# Case insensitive search for namespace by path or name
@@ -145,18 +145,18 @@ class Namespace < ApplicationRecord
end
def kind
- type == 'Group' ? 'group' : 'user'
+ type == "Group" ? "group" : "user"
end
def find_fork_of(project)
return nil unless project.fork_network
if Gitlab::SafeRequestStore.active?
- forks_in_namespace = Gitlab::SafeRequestStore.fetch("namespaces:#{id}:forked_projects") do
+ forks_in_namespace = Gitlab::SafeRequestStore.fetch("namespaces:#{id}:forked_projects") {
Hash.new do |found_forks, project|
found_forks[project] = project.fork_network.find_forks_in(projects).first
end
- end
+ }
forks_in_namespace[project]
else
@@ -259,7 +259,7 @@ class Namespace < ApplicationRecord
path_was
else
previous_parent = Group.find_by(id: parent_id_was)
- previous_parent.full_path + '/' + path_was
+ previous_parent.full_path + "/" + path_was
end
end
@@ -276,7 +276,7 @@ class Namespace < ApplicationRecord
def refresh_access_of_projects_invited_groups
Group
.joins(project_group_links: :project)
- .where(projects: { namespace_id: id })
+ .where(projects: {namespace_id: id})
.find_each(&:refresh_members_authorized_projects)
end
diff --git a/app/models/network/graph.rb b/app/models/network/graph.rb
index ecbeb24ee0a..d696eef1244 100644
--- a/app/models/network/graph.rb
+++ b/app/models/network/graph.rb
@@ -27,9 +27,9 @@ module Network
@project
.notes
- .where('noteable_type = ?', 'Commit')
- .group('notes.commit_id')
- .select('notes.commit_id, count(notes.id) as note_count')
+ .where("noteable_type = ?", "Commit")
+ .group("notes.commit_id")
+ .select("notes.commit_id, count(notes.id) as note_count")
.each do |item|
h[item.commit_id] = item.note_count.to_i
end
@@ -85,9 +85,9 @@ module Network
while offset == -1
tmp_commits = find_commits(skip)
if tmp_commits.present?
- index = tmp_commits.index do |c|
+ index = tmp_commits.index { |c|
c.id == @commit.id
- end
+ }
if index
# Find the target commit
@@ -113,7 +113,7 @@ module Network
opts = {
max_count: self.class.max_count,
skip: skip,
- order: :date
+ order: :date,
}
opts[:ref] = @commit.id if @filter_ref
@@ -144,10 +144,10 @@ module Network
range = commit.time..parent.time
space = if commit.space >= parent.space
- find_free_parent_space(range, parent.space, -1, commit.space)
- else
- find_free_parent_space(range, commit.space, -1, parent.space)
- end
+ find_free_parent_space(range, parent.space, -1, commit.space)
+ else
+ find_free_parent_space(range, commit.space, -1, parent.space)
+ end
mark_reserved(range, space)
spaces << space
diff --git a/app/models/note.rb b/app/models/note.rb
index 1578ae9c4cc..e8e3a106f1d 100644
--- a/app/models/note.rb
+++ b/app/models/note.rb
@@ -25,7 +25,7 @@ class Note < ActiveRecord::Base
class << self
def values
- constants.map {|const| self.const_get(const)}
+ constants.map {|const| const_get(const)}
end
end
end
@@ -66,7 +66,7 @@ class Note < ActiveRecord::Base
belongs_to :noteable, polymorphic: true # rubocop:disable Cop/PolymorphicAssociations
belongs_to :author, class_name: "User"
belongs_to :updated_by, class_name: "User"
- belongs_to :last_edited_by, class_name: 'User'
+ belongs_to :last_edited_by, class_name: "User"
has_many :todos
@@ -88,17 +88,17 @@ class Note < ActiveRecord::Base
validates :project, presence: true, if: :for_project_noteable?
# Attachments are deprecated and are handled by Markdown uploader
- validates :attachment, file_size: { maximum: :max_attachment_size }
+ validates :attachment, file_size: {maximum: :max_attachment_size}
validates :noteable_type, presence: true
validates :noteable_id, presence: true, unless: [:for_commit?, :importing?]
validates :commit_id, presence: true, if: :for_commit?
validates :author, presence: true
- validates :discussion_id, presence: true, format: { with: /\A\h{40}\z/ }
+ validates :discussion_id, presence: true, format: {with: /\A\h{40}\z/}
validate unless: [:for_commit?, :importing?, :skip_project_check?] do |note|
unless note.noteable.try(:project) == note.project
- errors.add(:project, 'does not match noteable project')
+ errors.add(:project, "does not match noteable project")
end
end
@@ -111,15 +111,15 @@ class Note < ActiveRecord::Base
scope :user, -> { where(system: false) }
scope :common, -> { where(noteable_type: ["", nil]) }
scope :fresh, -> { order(created_at: :asc, id: :asc) }
- scope :updated_after, ->(time) { where('updated_at > ?', time) }
+ scope :updated_after, ->(time) { where("updated_at > ?", time) }
scope :inc_author_project, -> { includes(:project, :author) }
scope :inc_author, -> { includes(:author) }
scope :inc_relations_for_view, -> do
- includes(:project, { author: :status }, :updated_by, :resolved_by, :award_emoji,
- :system_note_metadata, :note_diff_file, :suggestions)
+ includes(:project, {author: :status}, :updated_by, :resolved_by, :award_emoji,
+ :system_note_metadata, :note_diff_file, :suggestions)
end
- scope :with_notes_filter, -> (notes_filter) do
+ scope :with_notes_filter, ->(notes_filter) do
case notes_filter
when UserPreference::NOTES_FILTERS[:only_comments]
user
@@ -130,14 +130,14 @@ class Note < ActiveRecord::Base
end
end
- scope :diff_notes, -> { where(type: %w(LegacyDiffNote DiffNote)) }
- scope :new_diff_notes, -> { where(type: 'DiffNote') }
- scope :non_diff_notes, -> { where(type: ['Note', 'DiscussionNote', nil]) }
+ scope :diff_notes, -> { where(type: %w[LegacyDiffNote DiffNote]) }
+ scope :new_diff_notes, -> { where(type: "DiffNote") }
+ scope :non_diff_notes, -> { where(type: ["Note", "DiscussionNote", nil]) }
scope :with_associations, -> do
# FYI noteable cannot be loaded for LegacyDiffNote for commits
includes(:author, :noteable, :updated_by,
- project: [:project_members, :namespace, { group: [:group_members] }])
+ project: [:project_members, :namespace, {group: [:group_members]}])
end
scope :with_metadata, -> { includes(:system_note_metadata) }
@@ -151,7 +151,7 @@ class Note < ActiveRecord::Base
class << self
def model_name
- ActiveModel::Name.new(self, nil, 'note')
+ ActiveModel::Name.new(self, nil, "note")
end
def discussions(context_noteable = nil)
@@ -190,7 +190,7 @@ class Note < ActiveRecord::Base
end
def count_for_collection(ids, type)
- user.select('noteable_id', 'COUNT(*) as count')
+ user.select("noteable_id", "COUNT(*) as count")
.group(:noteable_id)
.where(noteable_type: type, noteable_id: ids)
end
@@ -290,7 +290,7 @@ class Note < ActiveRecord::Base
end
def special_role=(role)
- raise "Role is undefined, #{role} not found in #{SpecialRole.values}" unless SpecialRole.values.include?(role)
+ raise "Role is undefined, #{role} not found in #{SpecialRole.values}" unless SpecialRole.value?(role)
@special_role = role
end
@@ -300,7 +300,7 @@ class Note < ActiveRecord::Base
end
def specialize_for_first_contribution!(noteable)
- return unless noteable.author_id == self.author_id
+ return unless noteable.author_id == author_id
self.special_role = Note::SpecialRole::FIRST_TIME_CONTRIBUTOR
end
@@ -338,7 +338,7 @@ class Note < ActiveRecord::Base
end
def can_be_discussion_note?
- self.noteable.supports_discussions? && !part_of_discussion?
+ noteable.supports_discussions? && !part_of_discussion?
end
def can_create_todo?
@@ -374,7 +374,7 @@ class Note < ActiveRecord::Base
# Consider using `#to_discussion` if we do not need to render the discussion
# and all its notes and if we don't care about the discussion's resolvability status.
def discussion
- full_discussion = self.noteable.notes.find_discussion(self.discussion_id) if part_of_discussion?
+ full_discussion = noteable.notes.find_discussion(discussion_id) if part_of_discussion?
full_discussion || to_discussion
end
@@ -391,9 +391,9 @@ class Note < ActiveRecord::Base
in_reply_to?(other.noteable)
end
when Discussion
- self.discussion_id == other.id
+ discussion_id == other.id
when Noteable
- self.noteable == other
+ noteable == other
else
false
end
@@ -463,25 +463,25 @@ class Note < ActiveRecord::Base
private
def keep_around_commit
- project.repository.keep_around(self.commit_id)
+ project.repository.keep_around(commit_id)
end
def nullify_blank_type
- self.type = nil if self.type.blank?
+ self.type = nil if type.blank?
end
def nullify_blank_line_code
- self.line_code = nil if self.line_code.blank?
+ self.line_code = nil if line_code.blank?
end
def ensure_discussion_id
- return unless self.persisted?
+ return unless persisted?
# Needed in case the SELECT statement doesn't ask for `discussion_id`
- return unless self.has_attribute?(:discussion_id)
- return if self.discussion_id
+ return unless has_attribute?(:discussion_id)
+ return if discussion_id
set_discussion_id
- update_column(:discussion_id, self.discussion_id)
+ update_column(:discussion_id, discussion_id)
end
def set_discussion_id
diff --git a/app/models/note_diff_file.rb b/app/models/note_diff_file.rb
index e369122003e..22a70154c97 100644
--- a/app/models/note_diff_file.rb
+++ b/app/models/note_diff_file.rb
@@ -17,8 +17,8 @@ class NoteDiffFile < ActiveRecord::Base
raw_diff = Gitlab::Git::Diff.new(to_hash)
Gitlab::Diff::File.new(raw_diff,
- repository: project.repository,
- diff_refs: original_position.diff_refs,
- unique_identifier: id)
+ repository: project.repository,
+ diff_refs: original_position.diff_refs,
+ unique_identifier: id)
end
end
diff --git a/app/models/notification_reason.rb b/app/models/notification_reason.rb
index 0a13487574f..88cd0134e57 100644
--- a/app/models/notification_reason.rb
+++ b/app/models/notification_reason.rb
@@ -3,15 +3,15 @@
# Holds reasons for a notification to have been sent as well as a priority list to select which reason to use
# above the rest
class NotificationReason
- OWN_ACTIVITY = 'own_activity'.freeze
- ASSIGNED = 'assigned'.freeze
- MENTIONED = 'mentioned'.freeze
+ OWN_ACTIVITY = "own_activity"
+ ASSIGNED = "assigned"
+ MENTIONED = "mentioned"
# Priority list for selecting which reason to return in the notification
REASON_PRIORITY = [
OWN_ACTIVITY,
ASSIGNED,
- MENTIONED
+ MENTIONED,
].freeze
# returns the priority of a reason as an integer
diff --git a/app/models/notification_recipient.rb b/app/models/notification_recipient.rb
index 481c1d963c6..d9657e24a57 100644
--- a/app/models/notification_recipient.rb
+++ b/app/models/notification_recipient.rb
@@ -130,8 +130,6 @@ class NotificationRecipient
:read_build # We have build trace in pipeline emails
when ActiveRecord::Base
:"read_#{@target.class.model_name.name.underscore}"
- else
- nil
end
end
diff --git a/app/models/notification_setting.rb b/app/models/notification_setting.rb
index e82eaf4e069..8db7519f342 100644
--- a/app/models/notification_setting.rb
+++ b/app/models/notification_setting.rb
@@ -5,27 +5,27 @@ class NotificationSetting < ActiveRecord::Base
ignore_column :events
- enum level: { global: 3, watch: 2, participating: 1, mention: 4, disabled: 0, custom: 5 }
+ enum level: {global: 3, watch: 2, participating: 1, mention: 4, disabled: 0, custom: 5}
default_value_for :level, NotificationSetting.levels[:global]
belongs_to :user
belongs_to :source, polymorphic: true # rubocop:disable Cop/PolymorphicAssociations
- belongs_to :project, foreign_key: 'source_id'
+ belongs_to :project, foreign_key: "source_id"
validates :user, presence: true
validates :level, presence: true
- validates :user_id, uniqueness: { scope: [:source_type, :source_id],
- message: "already exists in source",
- allow_nil: true }
+ validates :user_id, uniqueness: {scope: [:source_type, :source_id],
+ message: "already exists in source",
+ allow_nil: true,}
- scope :for_groups, -> { where(source_type: 'Namespace') }
+ scope :for_groups, -> { where(source_type: "Namespace") }
# Exclude projects not included by the Project model's default scope (those that are
# pending delete).
#
scope :for_projects, -> do
- includes(:project).references(:projects).where(source_type: 'Project').where.not(projects: { id: nil, pending_delete: true })
+ includes(:project).references(:projects).where(source_type: "Project").where.not(projects: {id: nil, pending_delete: true})
end
EMAIL_EVENTS = [
@@ -42,7 +42,7 @@ class NotificationSetting < ActiveRecord::Base
:reassign_merge_request,
:merge_merge_request,
:failed_pipeline,
- :success_pipeline
+ :success_pipeline,
].freeze
# Update unfound_translations.rb when events are changed
@@ -55,12 +55,12 @@ class NotificationSetting < ActiveRecord::Base
end
EXCLUDED_PARTICIPATING_EVENTS = [
- :success_pipeline
+ :success_pipeline,
].freeze
EXCLUDED_WATCHER_EVENTS = [
:push_to_merge_request,
- :issue_due
+ :issue_due,
].push(*EXCLUDED_PARTICIPATING_EVENTS).freeze
def self.find_or_create_for(source)
@@ -81,7 +81,7 @@ class NotificationSetting < ActiveRecord::Base
bool.nil? || bool
end
- alias_method :failed_pipeline?, :failed_pipeline
+ alias failed_pipeline? failed_pipeline
def event_enabled?(event)
respond_to?(event) && !!public_send(event) # rubocop:disable GitlabSecurity/PublicSend
diff --git a/app/models/oauth_access_grant.rb b/app/models/oauth_access_grant.rb
index d5a8a1a25b6..cb43a41e7dc 100644
--- a/app/models/oauth_access_grant.rb
+++ b/app/models/oauth_access_grant.rb
@@ -1,6 +1,6 @@
# frozen_string_literal: true
class OauthAccessGrant < Doorkeeper::AccessGrant
- belongs_to :resource_owner, class_name: 'User'
- belongs_to :application, class_name: 'Doorkeeper::Application'
+ belongs_to :resource_owner, class_name: "User"
+ belongs_to :application, class_name: "Doorkeeper::Application"
end
diff --git a/app/models/oauth_access_token.rb b/app/models/oauth_access_token.rb
index 0aa920fa828..7ce5ddac096 100644
--- a/app/models/oauth_access_token.rb
+++ b/app/models/oauth_access_token.rb
@@ -1,8 +1,8 @@
# frozen_string_literal: true
class OauthAccessToken < Doorkeeper::AccessToken
- belongs_to :resource_owner, class_name: 'User'
- belongs_to :application, class_name: 'Doorkeeper::Application'
+ belongs_to :resource_owner, class_name: "User"
+ belongs_to :application, class_name: "Doorkeeper::Application"
alias_attribute :user, :resource_owner
diff --git a/app/models/pages_domain.rb b/app/models/pages_domain.rb
index 7a33ade826b..0f24e0a9fda 100644
--- a/app/models/pages_domain.rb
+++ b/app/models/pages_domain.rb
@@ -1,16 +1,16 @@
# frozen_string_literal: true
class PagesDomain < ActiveRecord::Base
- VERIFICATION_KEY = 'gitlab-pages-verification-code'.freeze
+ VERIFICATION_KEY = "gitlab-pages-verification-code"
VERIFICATION_THRESHOLD = 3.days.freeze
belongs_to :project
- validates :domain, hostname: { allow_numeric_hostname: true }
- validates :domain, uniqueness: { case_sensitive: false }
- validates :certificate, presence: { message: 'must be present if HTTPS-only is enabled' }, if: ->(domain) { domain.project&.pages_https_only? }
+ validates :domain, hostname: {allow_numeric_hostname: true}
+ validates :domain, uniqueness: {case_sensitive: false}
+ validates :certificate, presence: {message: "must be present if HTTPS-only is enabled"}, if: ->(domain) { domain.project&.pages_https_only? }
validates :certificate, certificate: true, if: ->(domain) { domain.certificate.present? }
- validates :key, presence: { message: 'must be present if HTTPS-only is enabled' }, if: ->(domain) { domain.project&.pages_https_only? }
+ validates :key, presence: {message: "must be present if HTTPS-only is enabled"}, if: ->(domain) { domain.project&.pages_https_only? }
validates :key, certificate_key: true, if: ->(domain) { domain.key.present? }
validates :verification_code, presence: true, allow_blank: false
@@ -22,14 +22,14 @@ class PagesDomain < ActiveRecord::Base
mode: :per_attribute_iv_and_salt,
insecure_mode: true,
key: Settings.attr_encrypted_db_key_base,
- algorithm: 'aes-256-cbc'
+ algorithm: "aes-256-cbc"
after_initialize :set_verification_code
after_create :update_daemon
after_update :update_daemon, if: :pages_config_changed?
after_destroy :update_daemon
- scope :enabled, -> { where('enabled_until >= ?', Time.now ) }
+ scope :enabled, -> { where("enabled_until >= ?", Time.now) }
scope :needs_verification, -> do
verified_at = arel_table[:verified_at]
enabled_until = arel_table[:enabled_until]
@@ -86,7 +86,7 @@ class PagesDomain < ActiveRecord::Base
store.set_default_paths
# This forces to load all intermediate certificates stored in `certificate`
- Tempfile.open('certificate_chain') do |f|
+ Tempfile.open("certificate_chain") do |f|
f.write(certificate)
f.flush
store.add_file(f.path)
@@ -135,7 +135,7 @@ class PagesDomain < ActiveRecord::Base
private
def set_verification_code
- return if self.verification_code.present?
+ return if verification_code.present?
self.verification_code = SecureRandom.hex(16)
end
@@ -165,13 +165,13 @@ class PagesDomain < ActiveRecord::Base
def validate_matching_key
unless has_matching_key?
- self.errors.add(:key, "doesn't match the certificate")
+ errors.add(:key, "doesn't match the certificate")
end
end
def validate_intermediates
unless has_intermediates?
- self.errors.add(:certificate, 'misses intermediates')
+ errors.add(:certificate, "misses intermediates")
end
end
@@ -179,7 +179,7 @@ class PagesDomain < ActiveRecord::Base
return unless domain
if domain.downcase.ends_with?(Settings.pages.host.downcase)
- self.errors.add(:domain, "*.#{Settings.pages.host} is restricted")
+ errors.add(:domain, "*.#{Settings.pages.host} is restricted")
end
end
diff --git a/app/models/personal_access_token.rb b/app/models/personal_access_token.rb
index ed78a46eaf3..552e741639c 100644
--- a/app/models/personal_access_token.rb
+++ b/app/models/personal_access_token.rb
@@ -64,7 +64,7 @@ class PersonalAccessToken < ActiveRecord::Base
end
def set_default_scopes
- self.scopes = Gitlab::Auth::DEFAULT_SCOPES if self.scopes.empty?
+ self.scopes = Gitlab::Auth::DEFAULT_SCOPES if scopes.empty?
end
def self.redis_shared_state_key(user_id)
diff --git a/app/models/pool_repository.rb b/app/models/pool_repository.rb
index 4635fc72dc7..5d52d4b60bc 100644
--- a/app/models/pool_repository.rb
+++ b/app/models/pool_repository.rb
@@ -7,10 +7,10 @@ class PoolRepository < ActiveRecord::Base
include Shardable
include AfterCommitQueue
- has_one :source_project, class_name: 'Project'
+ has_one :source_project, class_name: "Project"
validates :source_project, presence: true
- has_many :member_projects, class_name: 'Project'
+ has_many :member_projects, class_name: "Project"
after_create :correct_disk_path
@@ -95,7 +95,7 @@ class PoolRepository < ActiveRecord::Base
def object_pool
@object_pool ||= Gitlab::Git::ObjectPool.new(
shard.name,
- disk_path + '.git',
+ disk_path + ".git",
source_project.repository.raw,
source_project.full_path
)
diff --git a/app/models/postgresql/replication_slot.rb b/app/models/postgresql/replication_slot.rb
index e264fe88e47..6a7503ce798 100644
--- a/app/models/postgresql/replication_slot.rb
+++ b/app/models/postgresql/replication_slot.rb
@@ -2,7 +2,7 @@
module Postgresql
class ReplicationSlot < ActiveRecord::Base
- self.table_name = 'pg_replication_slots'
+ self.table_name = "pg_replication_slots"
# Returns true if there are any replication slots in use.
# PostgreSQL-compatible databases such as Aurora don't support
diff --git a/app/models/project.rb b/app/models/project.rb
index 47baf899222..49118e877e1 100644
--- a/app/models/project.rb
+++ b/app/models/project.rb
@@ -1,6 +1,6 @@
# frozen_string_literal: true
-require 'carrierwave/orm/activerecord'
+require "carrierwave/orm/activerecord"
class Project < ActiveRecord::Base
include Gitlab::ConfigHelper
@@ -37,9 +37,9 @@ class Project < ActiveRecord::Base
BoardLimitExceeded = Class.new(StandardError)
- STATISTICS_ATTRIBUTE = 'repositories_count'.freeze
+ STATISTICS_ATTRIBUTE = "repositories_count"
NUMBER_OF_PERMITTED_BOARDS = 1
- UNKNOWN_IMPORT_URL = 'http://unknown.git'.freeze
+ UNKNOWN_IMPORT_URL = "http://unknown.git"
# Hashed Storage versions handle rolling out new storage to project and dependents models:
# nil: legacy
# 1: repository
@@ -47,22 +47,22 @@ class Project < ActiveRecord::Base
LATEST_STORAGE_VERSION = 2
HASHED_STORAGE_FEATURES = {
repository: 1,
- attachments: 2
+ attachments: 2,
}.freeze
VALID_IMPORT_PORTS = [80, 443].freeze
- VALID_IMPORT_PROTOCOLS = %w(http https git).freeze
+ VALID_IMPORT_PROTOCOLS = %w[http https git].freeze
VALID_MIRROR_PORTS = [22, 80, 443].freeze
- VALID_MIRROR_PROTOCOLS = %w(http https ssh git).freeze
+ VALID_MIRROR_PROTOCOLS = %w[http https ssh git].freeze
ignore_column :import_status, :import_jid, :import_error
cache_markdown_field :description, pipeline: :description
delegate :feature_available?, :builds_enabled?, :wiki_enabled?,
- :merge_requests_enabled?, :issues_enabled?, :pages_enabled?, :public_pages?,
- to: :project_feature, allow_nil: true
+ :merge_requests_enabled?, :issues_enabled?, :pages_enabled?, :public_pages?,
+ to: :project_feature, allow_nil: true
delegate :base_dir, :disk_path, :ensure_storage_path_exists, to: :storage
@@ -130,13 +130,13 @@ class Project < ActiveRecord::Base
# Relations
belongs_to :pool_repository
- belongs_to :creator, class_name: 'User'
- belongs_to :group, -> { where(type: 'Group') }, foreign_key: 'namespace_id'
+ belongs_to :creator, class_name: "User"
+ belongs_to :group, -> { where(type: "Group") }, foreign_key: "namespace_id"
belongs_to :namespace
- alias_method :parent, :namespace
+ alias parent namespace
alias_attribute :parent_id, :namespace_id
- has_one :last_event, -> {order 'events.created_at DESC'}, class_name: 'Event'
+ has_one :last_event, -> {order "events.created_at DESC"}, class_name: "Event"
has_many :boards, before_add: :validate_board_limit
# Project services
@@ -175,46 +175,46 @@ class Project < ActiveRecord::Base
has_one :hangouts_chat_service
has_one :root_of_fork_network,
- foreign_key: 'root_project_id',
- inverse_of: :root_project,
- class_name: 'ForkNetwork'
+ foreign_key: "root_project_id",
+ inverse_of: :root_project,
+ class_name: "ForkNetwork"
has_one :fork_network_member
has_one :fork_network, through: :fork_network_member
has_one :forked_from_project, through: :fork_network_member
- has_many :forked_to_members, class_name: 'ForkNetworkMember', foreign_key: 'forked_from_project_id'
+ has_many :forked_to_members, class_name: "ForkNetworkMember", foreign_key: "forked_from_project_id"
has_many :forks, through: :forked_to_members, source: :project, inverse_of: :forked_from_project
- has_one :import_state, autosave: true, class_name: 'ProjectImportState', inverse_of: :project
+ has_one :import_state, autosave: true, class_name: "ProjectImportState", inverse_of: :project
has_one :import_export_upload, dependent: :destroy # rubocop:disable Cop/ActiveRecordDependent
has_one :project_repository, inverse_of: :project
- has_one :error_tracking_setting, inverse_of: :project, class_name: 'ErrorTracking::ProjectErrorTrackingSetting'
+ has_one :error_tracking_setting, inverse_of: :project, class_name: "ErrorTracking::ProjectErrorTrackingSetting"
# Merge Requests for target project should be removed with it
- has_many :merge_requests, foreign_key: 'target_project_id', inverse_of: :target_project
- has_many :source_of_merge_requests, foreign_key: 'source_project_id', class_name: 'MergeRequest'
+ has_many :merge_requests, foreign_key: "target_project_id", inverse_of: :target_project
+ has_many :source_of_merge_requests, foreign_key: "source_project_id", class_name: "MergeRequest"
has_many :issues
- has_many :labels, class_name: 'ProjectLabel'
+ has_many :labels, class_name: "ProjectLabel"
has_many :services
has_many :events
has_many :milestones
has_many :notes
- has_many :snippets, class_name: 'ProjectSnippet'
- has_many :hooks, class_name: 'ProjectHook'
+ has_many :snippets, class_name: "ProjectSnippet"
+ has_many :hooks, class_name: "ProjectHook"
has_many :protected_branches
has_many :protected_tags
has_many :repository_languages, -> { order "share DESC" }
has_many :project_authorizations
- has_many :authorized_users, through: :project_authorizations, source: :user, class_name: 'User'
+ has_many :authorized_users, through: :project_authorizations, source: :user, class_name: "User"
has_many :project_members, -> { where(requested_at: nil) },
as: :source, dependent: :delete_all # rubocop:disable Cop/ActiveRecordDependent
- alias_method :members, :project_members
+ alias members project_members
has_many :users, through: :project_members
has_many :requesters, -> { where.not(requested_at: nil) },
- as: :source, class_name: 'ProjectMember', dependent: :delete_all # rubocop:disable Cop/ActiveRecordDependent
- has_many :members_and_requesters, as: :source, class_name: 'ProjectMember'
+ as: :source, class_name: "ProjectMember", dependent: :delete_all # rubocop:disable Cop/ActiveRecordDependent
+ has_many :members_and_requesters, as: :source, class_name: "ProjectMember"
has_many :deploy_keys_projects
has_many :deploy_keys, through: :deploy_keys_projects
@@ -232,14 +232,14 @@ class Project < ActiveRecord::Base
has_many :internal_ids
- has_one :import_data, class_name: 'ProjectImportData', inverse_of: :project, autosave: true
+ has_one :import_data, class_name: "ProjectImportData", inverse_of: :project, autosave: true
has_one :project_feature, inverse_of: :project
- has_one :statistics, class_name: 'ProjectStatistics'
+ has_one :statistics, class_name: "ProjectStatistics"
- has_one :cluster_project, class_name: 'Clusters::Project'
- has_many :clusters, through: :cluster_project, class_name: 'Clusters::Cluster'
- has_many :cluster_ingresses, through: :clusters, source: :application_ingress, class_name: 'Clusters::Applications::Ingress'
- has_many :kubernetes_namespaces, class_name: 'Clusters::KubernetesNamespace'
+ has_one :cluster_project, class_name: "Clusters::Project"
+ has_many :clusters, through: :cluster_project, class_name: "Clusters::Cluster"
+ has_many :cluster_ingresses, through: :clusters, source: :application_ingress, class_name: "Clusters::Applications::Ingress"
+ has_many :kubernetes_namespaces, class_name: "Clusters::KubernetesNamespace"
has_many :prometheus_metrics
@@ -251,39 +251,39 @@ class Project < ActiveRecord::Base
has_many :commit_statuses
# The relation :all_pipelines is intended to be used when we want to get the
# whole list of pipelines associated to the project
- has_many :all_pipelines, class_name: 'Ci::Pipeline', inverse_of: :project
+ has_many :all_pipelines, class_name: "Ci::Pipeline", inverse_of: :project
# The relation :ci_pipelines is intended to be used when we want to get only
# those pipeline which are directly related to CI. There are
# other pipelines, like webide ones, that we won't retrieve
# if we use this relation.
has_many :ci_pipelines,
- -> { ci_sources },
- class_name: 'Ci::Pipeline',
- inverse_of: :project
- has_many :stages, class_name: 'Ci::Stage', inverse_of: :project
+ -> { ci_sources },
+ class_name: "Ci::Pipeline",
+ inverse_of: :project
+ has_many :stages, class_name: "Ci::Stage", inverse_of: :project
# Ci::Build objects store data on the file system such as artifact files and
# build traces. Currently there's no efficient way of removing this data in
# bulk that doesn't involve loading the rows into memory. As a result we're
# still using `dependent: :destroy` here.
- has_many :builds, class_name: 'Ci::Build', inverse_of: :project, dependent: :destroy # rubocop:disable Cop/ActiveRecordDependent
- has_many :build_trace_section_names, class_name: 'Ci::BuildTraceSectionName'
- has_many :build_trace_chunks, class_name: 'Ci::BuildTraceChunk', through: :builds, source: :trace_chunks
- has_many :runner_projects, class_name: 'Ci::RunnerProject', inverse_of: :project
- has_many :runners, through: :runner_projects, source: :runner, class_name: 'Ci::Runner'
- has_many :variables, class_name: 'Ci::Variable'
- has_many :triggers, class_name: 'Ci::Trigger'
+ has_many :builds, class_name: "Ci::Build", inverse_of: :project, dependent: :destroy # rubocop:disable Cop/ActiveRecordDependent
+ has_many :build_trace_section_names, class_name: "Ci::BuildTraceSectionName"
+ has_many :build_trace_chunks, class_name: "Ci::BuildTraceChunk", through: :builds, source: :trace_chunks
+ has_many :runner_projects, class_name: "Ci::RunnerProject", inverse_of: :project
+ has_many :runners, through: :runner_projects, source: :runner, class_name: "Ci::Runner"
+ has_many :variables, class_name: "Ci::Variable"
+ has_many :triggers, class_name: "Ci::Trigger"
has_many :environments
has_many :deployments, -> { success }
- has_many :pipeline_schedules, class_name: 'Ci::PipelineSchedule'
+ has_many :pipeline_schedules, class_name: "Ci::PipelineSchedule"
has_many :project_deploy_tokens
has_many :deploy_tokens, through: :project_deploy_tokens
- has_one :auto_devops, class_name: 'ProjectAutoDevops'
- has_many :custom_attributes, class_name: 'ProjectCustomAttribute'
+ has_one :auto_devops, class_name: "ProjectAutoDevops"
+ has_many :custom_attributes, class_name: "ProjectCustomAttribute"
- has_many :project_badges, class_name: 'ProjectBadge'
- has_one :ci_cd_settings, class_name: 'ProjectCiCdSetting', inverse_of: :project, autosave: true, dependent: :destroy # rubocop:disable Cop/ActiveRecordDependent
+ has_many :project_badges, class_name: "ProjectBadge"
+ has_one :ci_cd_settings, class_name: "ProjectCiCdSetting", inverse_of: :project, autosave: true, dependent: :destroy # rubocop:disable Cop/ActiveRecordDependent
has_many :remote_mirrors, inverse_of: :project
@@ -293,8 +293,8 @@ class Project < ActiveRecord::Base
accepts_nested_attributes_for :auto_devops, update_only: true
accepts_nested_attributes_for :remote_mirrors,
- allow_destroy: true,
- reject_if: ->(attrs) { attrs[:id].blank? && attrs[:url].blank? }
+ allow_destroy: true,
+ reject_if: ->(attrs) { attrs[:id].blank? && attrs[:url].blank? }
accepts_nested_attributes_for :error_tracking_setting, update_only: true
@@ -310,47 +310,47 @@ class Project < ActiveRecord::Base
# Validations
validates :creator, presence: true, on: :create
- validates :description, length: { maximum: 2000 }, allow_blank: true
+ validates :description, length: {maximum: 2000}, allow_blank: true
validates :ci_config_path,
- format: { without: %r{(\.{2}|\A/)},
- message: 'cannot include leading slash or directory traversal.' },
- length: { maximum: 255 },
+ format: {without: %r{(\.{2}|\A/)},
+ message: "cannot include leading slash or directory traversal.",},
+ length: {maximum: 255},
allow_blank: true
validates :name,
presence: true,
- length: { maximum: 255 },
- format: { with: Gitlab::Regex.project_name_regex,
- message: Gitlab::Regex.project_name_regex_message }
+ length: {maximum: 255},
+ format: {with: Gitlab::Regex.project_name_regex,
+ message: Gitlab::Regex.project_name_regex_message,}
validates :path,
presence: true,
project_path: true,
- length: { maximum: 255 }
+ length: {maximum: 255}
validates :namespace, presence: true
- validates :name, uniqueness: { scope: :namespace_id }
- validates :import_url, public_url: { protocols: ->(project) { project.persisted? ? VALID_MIRROR_PROTOCOLS : VALID_IMPORT_PROTOCOLS },
- ports: ->(project) { project.persisted? ? VALID_MIRROR_PORTS : VALID_IMPORT_PORTS },
- enforce_user: true }, if: [:external_import?, :import_url_changed?]
- validates :star_count, numericality: { greater_than_or_equal_to: 0 }
+ validates :name, uniqueness: {scope: :namespace_id}
+ validates :import_url, public_url: {protocols: ->(project) { project.persisted? ? VALID_MIRROR_PROTOCOLS : VALID_IMPORT_PROTOCOLS },
+ ports: ->(project) { project.persisted? ? VALID_MIRROR_PORTS : VALID_IMPORT_PORTS },
+ enforce_user: true,}, if: [:external_import?, :import_url_changed?]
+ validates :star_count, numericality: {greater_than_or_equal_to: 0}
validate :check_personal_projects_limit, on: :create
validate :check_repository_path_availability, on: :update, if: ->(project) { project.renamed? }
- validate :visibility_level_allowed_by_group, if: -> { changes.has_key?(:visibility_level) }
- validate :visibility_level_allowed_as_fork, if: -> { changes.has_key?(:visibility_level) }
+ validate :visibility_level_allowed_by_group, if: -> { changes.key?(:visibility_level) }
+ validate :visibility_level_allowed_as_fork, if: -> { changes.key?(:visibility_level) }
validate :check_wiki_path_conflict
- validate :validate_pages_https_only, if: -> { changes.has_key?(:pages_https_only) }
+ validate :validate_pages_https_only, if: -> { changes.key?(:pages_https_only) }
validates :repository_storage,
presence: true,
- inclusion: { in: ->(_object) { Gitlab.config.repositories.storages.keys } }
- validates :variables, variable_duplicates: { scope: :environment_scope }
- validates :bfg_object_map, file_size: { maximum: :max_attachment_size }
+ inclusion: {in: ->(_object) { Gitlab.config.repositories.storages.keys }}
+ validates :variables, variable_duplicates: {scope: :environment_scope}
+ validates :bfg_object_map, file_size: {maximum: :max_attachment_size}
# Scopes
scope :pending_delete, -> { where(pending_delete: true) }
scope :without_deleted, -> { where(pending_delete: false) }
- scope :with_storage_feature, ->(feature) { where('storage_version >= :version', version: HASHED_STORAGE_FEATURES[feature]) }
- scope :without_storage_feature, ->(feature) { where('storage_version < :version OR storage_version IS NULL', version: HASHED_STORAGE_FEATURES[feature]) }
- scope :with_unmigrated_storage, -> { where('storage_version < :version OR storage_version IS NULL', version: LATEST_STORAGE_VERSION) }
+ scope :with_storage_feature, ->(feature) { where("storage_version >= :version", version: HASHED_STORAGE_FEATURES[feature]) }
+ scope :without_storage_feature, ->(feature) { where("storage_version < :version OR storage_version IS NULL", version: HASHED_STORAGE_FEATURES[feature]) }
+ scope :with_unmigrated_storage, -> { where("storage_version < :version OR storage_version IS NULL", version: LATEST_STORAGE_VERSION) }
# last_activity_at is throttled every minute, but last_repository_updated_at is updated with every push
scope :sorted_by_activity, -> { reorder("GREATEST(COALESCE(last_activity_at, '1970-01-01'), COALESCE(last_repository_updated_at, '1970-01-01')) DESC") }
@@ -358,22 +358,22 @@ class Project < ActiveRecord::Base
scope :in_namespace, ->(namespace_ids) { where(namespace_id: namespace_ids) }
scope :personal, ->(user) { where(namespace_id: user.namespace_id) }
- scope :joined, ->(user) { where('namespace_id != ?', user.namespace_id) }
+ scope :joined, ->(user) { where("namespace_id != ?", user.namespace_id) }
scope :starred_by, ->(user) { joins(:users_star_projects).where('users_star_projects.user_id': user.id) }
scope :visible_to_user, ->(user) { where(id: user.authorized_projects.select(:id).reorder(nil)) }
- scope :visible_to_user_and_access_level, ->(user, access_level) { where(id: user.authorized_projects.where('project_authorizations.access_level >= ?', access_level).select(:id).reorder(nil)) }
+ scope :visible_to_user_and_access_level, ->(user, access_level) { where(id: user.authorized_projects.where("project_authorizations.access_level >= ?", access_level).select(:id).reorder(nil)) }
scope :archived, -> { where(archived: true) }
scope :non_archived, -> { where(archived: false) }
- scope :for_milestones, ->(ids) { joins(:milestones).where('milestones.id' => ids).distinct }
- scope :with_push, -> { joins(:events).where('events.action = ?', Event::PUSHED) }
- scope :with_project_feature, -> { joins('LEFT JOIN project_features ON projects.id = project_features.project_id') }
+ scope :for_milestones, ->(ids) { joins(:milestones).where("milestones.id" => ids).distinct }
+ scope :with_push, -> { joins(:events).where("events.action = ?", Event::PUSHED) }
+ scope :with_project_feature, -> { joins("LEFT JOIN project_features ON projects.id = project_features.project_id") }
scope :with_statistics, -> { includes(:statistics) }
scope :with_shared_runners, -> { where(shared_runners_enabled: true) }
scope :inside_path, ->(path) do
# We need routes alias rs for JOIN so it does not conflict with
# includes(:route) which we use in ProjectsFinder.
joins("INNER JOIN routes rs ON rs.source_id = projects.id AND rs.source_type = 'Project'")
- .where('rs.path LIKE ?', "#{sanitize_sql_like(path)}/%")
+ .where("rs.path LIKE ?", "#{sanitize_sql_like(path)}/%")
end
# "enabled" here means "not disabled". It includes private features!
@@ -387,46 +387,46 @@ class Project < ActiveRecord::Base
# Picks a feature where the level is exactly that given.
scope :with_feature_access_level, ->(feature, level) {
access_level_attribute = ProjectFeature.access_level_attribute(feature)
- with_project_feature.where(project_features: { access_level_attribute => level })
+ with_project_feature.where(project_features: {access_level_attribute => level})
}
# Picks projects which use the given programming language
scope :with_programming_language, ->(language_name) do
lang_id_query = ProgrammingLanguage
- .with_name_case_insensitive(language_name)
- .select(:id)
+ .with_name_case_insensitive(language_name)
+ .select(:id)
joins(:repository_languages)
- .where(repository_languages: { programming_language_id: lang_id_query })
+ .where(repository_languages: {programming_language_id: lang_id_query})
end
scope :with_builds_enabled, -> { with_feature_enabled(:builds) }
scope :with_issues_enabled, -> { with_feature_enabled(:issues) }
scope :with_issues_available_for_user, ->(current_user) { with_feature_available_for_user(:issues, current_user) }
scope :with_merge_requests_enabled, -> { with_feature_enabled(:merge_requests) }
- scope :with_remote_mirrors, -> { joins(:remote_mirrors).where(remote_mirrors: { enabled: true }).distinct }
+ scope :with_remote_mirrors, -> { joins(:remote_mirrors).where(remote_mirrors: {enabled: true}).distinct }
scope :with_group_runners_enabled, -> do
joins(:ci_cd_settings)
- .where(project_ci_cd_settings: { group_runners_enabled: true })
+ .where(project_ci_cd_settings: {group_runners_enabled: true})
end
- scope :missing_kubernetes_namespace, -> (kubernetes_namespaces) do
- subquery = kubernetes_namespaces.select('1').where('clusters_kubernetes_namespaces.project_id = projects.id')
+ scope :missing_kubernetes_namespace, ->(kubernetes_namespaces) do
+ subquery = kubernetes_namespaces.select("1").where("clusters_kubernetes_namespaces.project_id = projects.id")
- where('NOT EXISTS (?)', subquery)
+ where("NOT EXISTS (?)", subquery)
end
- enum auto_cancel_pending_pipelines: { disabled: 0, enabled: 1 }
+ enum auto_cancel_pending_pipelines: {disabled: 0, enabled: 1}
chronic_duration_attr :build_timeout_human_readable, :build_timeout,
- default: 3600, error_message: 'Maximum job timeout has a value which could not be accepted'
+ default: 3600, error_message: "Maximum job timeout has a value which could not be accepted"
validates :build_timeout, allow_nil: true,
- numericality: { greater_than_or_equal_to: 10.minutes,
- less_than: 1.month,
- only_integer: true,
- message: 'needs to be beetween 10 minutes and 1 month' }
+ numericality: {greater_than_or_equal_to: 10.minutes,
+ less_than: 1.month,
+ only_integer: true,
+ message: "needs to be beetween 10 minutes and 1 month",}
# Used by Projects::CleanupService to hold a map of rewritten object IDs
mount_uploader :bfg_object_map, AttachmentUploader
@@ -449,7 +449,7 @@ class Project < ActiveRecord::Base
limit: Kaminari.config.default_per_page
)
relation = order_id_desc.limit(limit)
- relation = relation.where('projects.id < ?', before) if before
+ relation = relation.where("projects.id < ?", before) if before
relation
end
@@ -462,9 +462,9 @@ class Project < ActiveRecord::Base
# logged in user.
def self.public_or_visible_to_user(user = nil)
if user
- where('EXISTS (?) OR projects.visibility_level IN (?)',
- user.authorizations_for_projects,
- Gitlab::VisibilityLevel.levels_for_user(user))
+ where("EXISTS (?) OR projects.visibility_level IN (?)",
+ user.authorizations_for_projects,
+ Gitlab::VisibilityLevel.levels_for_user(user))
else
public_to_user
end
@@ -494,21 +494,22 @@ class Project < ActiveRecord::Base
private: Gitlab::VisibilityLevel::PRIVATE,
public_visible: ProjectFeature::ENABLED,
private_visible: ProjectFeature::PRIVATE,
- authorizations: user.authorizations_for_projects(min_access_level: min_access_level)
- })
+ authorizations: user.authorizations_for_projects(min_access_level: min_access_level),
+ }
+ )
else
with_feature_access_level(feature, visible)
end
end
- scope :active, -> { joins(:issues, :notes, :merge_requests).order('issues.created_at, notes.created_at, merge_requests.created_at DESC') }
- scope :abandoned, -> { where('projects.last_activity_at < ?', 6.months.ago) }
+ scope :active, -> { joins(:issues, :notes, :merge_requests).order("issues.created_at, notes.created_at, merge_requests.created_at DESC") }
+ scope :abandoned, -> { where("projects.last_activity_at < ?", 6.months.ago) }
scope :excluding_project, ->(project) { where.not(id: project) }
# We require an alias to the project_mirror_data_table in order to use import_state in our queries
scope :joins_import_state, -> { joins("INNER JOIN project_mirror_data import_state ON import_state.project_id = projects.id") }
- scope :for_group, -> (group) { where(group: group) }
+ scope :for_group, ->(group) { where(group: group) }
class << self
# Searches for a list of projects based on the query given in `query`.
@@ -532,15 +533,15 @@ class Project < ActiveRecord::Base
def sort_by_attribute(method)
case method.to_s
- when 'storage_size_desc'
+ when "storage_size_desc"
# storage_size is a joined column so we need to
# pass a string to avoid AR adding the table name
- reorder('project_statistics.storage_size DESC, projects.id DESC')
- when 'latest_activity_desc'
+ reorder("project_statistics.storage_size DESC, projects.id DESC")
+ when "latest_activity_desc"
reorder(last_activity_at: :desc)
- when 'latest_activity_asc'
+ when "latest_activity_asc"
reorder(last_activity_at: :asc)
- when 'stars_desc'
+ when "stars_desc"
sorted_by_stars
else
order_by(method)
@@ -556,11 +557,11 @@ class Project < ActiveRecord::Base
end
def reference_postfix
- '>'
+ ">"
end
def reference_postfix_escaped
- '&gt;'
+ "&gt;"
end
# Pattern used to extract `namespace/project>` project references from text.
@@ -574,18 +575,18 @@ class Project < ActiveRecord::Base
end
def trending
- joins('INNER JOIN trending_projects ON projects.id = trending_projects.project_id')
- .reorder('trending_projects.id ASC')
+ joins("INNER JOIN trending_projects ON projects.id = trending_projects.project_id")
+ .reorder("trending_projects.id ASC")
end
def cached_count
- Rails.cache.fetch('total_project_count', expires_in: 5.minutes) do
+ Rails.cache.fetch("total_project_count", expires_in: 5.minutes) do
Project.count
end
end
def group_ids
- joins(:namespace).where(namespaces: { type: 'Group' }).select(:namespace_id)
+ joins(:namespace).where(namespaces: {type: "Group"}).select(:namespace_id)
end
end
@@ -612,7 +613,7 @@ class Project < ActiveRecord::Base
.base_and_ancestors(upto: top, hierarchy_order: hierarchy_order)
end
- alias_method :ancestors, :ancestors_upto
+ alias ancestors ancestors_upto
def lfs_enabled?
return namespace.lfs_enabled? if self[:lfs_enabled].nil?
@@ -620,7 +621,7 @@ class Project < ActiveRecord::Base
self[:lfs_enabled] && Gitlab.config.lfs.enabled
end
- alias_method :lfs_enabled, :lfs_enabled?
+ alias lfs_enabled lfs_enabled?
def auto_devops_enabled?
if auto_devops&.enabled.nil?
@@ -659,7 +660,7 @@ class Project < ActiveRecord::Base
@repository = nil
end
- alias_method :reload_repository!, :cleanup
+ alias reload_repository! cleanup
def container_registry_url
if Gitlab.config.registry.enabled
@@ -674,7 +675,7 @@ class Project < ActiveRecord::Base
has_root_container_repository_tags?
end
- def commit(ref = 'HEAD')
+ def commit(ref = "HEAD")
repository.commit(ref)
end
@@ -708,11 +709,11 @@ class Project < ActiveRecord::Base
end
def import_status
- import_state&.status || 'none'
+ import_state&.status || "none"
end
def human_import_status_name
- import_state&.human_status_name || 'none'
+ import_state&.human_status_name || "none"
end
def add_import_job
@@ -721,9 +722,9 @@ class Project < ActiveRecord::Base
RepositoryForkWorker.perform_async(id)
elsif gitlab_project_import?
# Do not retry on Import/Export until https://gitlab.com/gitlab-org/gitlab-ce/issues/26189 is solved.
- RepositoryImportWorker.set(retry: false).perform_async(self.id)
+ RepositoryImportWorker.set(retry: false).perform_async(id)
else
- RepositoryImportWorker.perform_async(self.id)
+ RepositoryImportWorker.perform_async(id)
end
log_import_activity(job_id)
@@ -743,7 +744,7 @@ class Project < ActiveRecord::Base
def reset_cache_and_import_attrs
run_after_commit do
- ProjectCacheWorker.perform_async(self.id)
+ ProjectCacheWorker.perform_async(id)
end
import_state.update(last_error: nil)
@@ -809,15 +810,15 @@ class Project < ActiveRecord::Base
end
def bare_repository_import?
- import_type == 'bare_repository'
+ import_type == "bare_repository"
end
def gitlab_project_import?
- import_type == 'gitlab_project'
+ import_type == "gitlab_project"
end
def gitea_import?
- import_type == 'gitea'
+ import_type == "gitea"
end
def has_remote_mirror?
@@ -837,7 +838,7 @@ class Project < ActiveRecord::Base
def mark_stuck_remote_mirrors_as_failed!
remote_mirrors.stuck.update_all(
update_status: :failed,
- last_error: 'The remote mirror took to long to complete.',
+ last_error: "The remote mirror took to long to complete.",
last_update_at: Time.now
)
end
@@ -856,41 +857,41 @@ class Project < ActiveRecord::Base
# present. Since the validation for that will fail, we can just return
# early.
return if !creator || creator.can_create_project? ||
- namespace.kind == 'group'
+ namespace.kind == "group"
limit = creator.projects_limit
error =
if limit.zero?
- _('Personal project creation is not allowed. Please contact your administrator with questions')
+ _("Personal project creation is not allowed. Please contact your administrator with questions")
else
- _('Your project limit is %{limit} projects! Please contact your administrator to increase it')
+ _("Your project limit is %{limit} projects! Please contact your administrator to increase it")
end
- self.errors.add(:limit_reached, error % { limit: limit })
+ errors.add(:limit_reached, error % {limit: limit})
end
def visibility_level_allowed_by_group
return if visibility_level_allowed_by_group?
- level_name = Gitlab::VisibilityLevel.level_name(self.visibility_level).downcase
- group_level_name = Gitlab::VisibilityLevel.level_name(self.group.visibility_level).downcase
- self.errors.add(:visibility_level, "#{level_name} is not allowed in a #{group_level_name} group.")
+ level_name = Gitlab::VisibilityLevel.level_name(visibility_level).downcase
+ group_level_name = Gitlab::VisibilityLevel.level_name(group.visibility_level).downcase
+ errors.add(:visibility_level, "#{level_name} is not allowed in a #{group_level_name} group.")
end
def visibility_level_allowed_as_fork
return if visibility_level_allowed_as_fork?
- level_name = Gitlab::VisibilityLevel.level_name(self.visibility_level).downcase
- self.errors.add(:visibility_level, "#{level_name} is not allowed since the fork source project has lower visibility.")
+ level_name = Gitlab::VisibilityLevel.level_name(visibility_level).downcase
+ errors.add(:visibility_level, "#{level_name} is not allowed since the fork source project has lower visibility.")
end
def check_wiki_path_conflict
return if path.blank?
- path_to_check = path.ends_with?('.wiki') ? path.chomp('.wiki') : "#{path}.wiki"
+ path_to_check = path.ends_with?(".wiki") ? path.chomp(".wiki") : "#{path}.wiki"
if Project.where(namespace_id: namespace_id, path: path_to_check).exists?
- errors.add(:name, 'has already been taken')
+ errors.add(:name, "has already been taken")
end
end
@@ -958,7 +959,7 @@ class Project < ActiveRecord::Base
return unless Gitlab::IncomingEmail.supports_issue_creation? && author
# check since this can come from a request parameter
- return unless %w(issue merge_request).include?(address_type)
+ return unless %w[issue merge_request].include?(address_type)
author.ensure_incoming_email_token!
@@ -970,7 +971,7 @@ class Project < ActiveRecord::Base
end
def build_commit_note(commit)
- notes.new(commit_id: commit.id, noteable_type: 'Commit')
+ notes.new(commit_id: commit.id, noteable_type: "Commit")
end
def last_activity
@@ -982,7 +983,7 @@ class Project < ActiveRecord::Base
end
def project_id
- self.id
+ id
end
def get_issue(issue_id, current_user)
@@ -1004,11 +1005,7 @@ class Project < ActiveRecord::Base
end
def issues_tracker
- if external_issue_tracker
- external_issue_tracker
- else
- default_issue_tracker
- end
+ external_issue_tracker || default_issue_tracker
end
def external_issue_reference_pattern
@@ -1028,8 +1025,6 @@ class Project < ActiveRecord::Base
return @external_issue_tracker if defined?(@external_issue_tracker)
@external_issue_tracker = services.external_issue_trackers.first
- else
- nil
end
end
@@ -1048,8 +1043,6 @@ class Project < ActiveRecord::Base
if has_external_wiki
@external_wiki ||= services.external_wikis.first
- else
- nil
end
end
@@ -1060,9 +1053,9 @@ class Project < ActiveRecord::Base
def find_or_initialize_services(exceptions: [])
available_services_names = Service.available_services_names - exceptions
- available_services = available_services_names.map do |service_name|
+ available_services = available_services_names.map { |service_name|
find_or_initialize_service(service_name)
- end
+ }
available_services.compact
end
@@ -1091,7 +1084,7 @@ class Project < ActiveRecord::Base
# rubocop: disable CodeReuse/ServiceClass
def create_labels
Label.templates.each do |label|
- params = label.attributes.except('id', 'template', 'created_at', 'updated_at', 'type')
+ params = label.attributes.except("id", "template", "created_at", "updated_at", "type")
Labels::FindOrCreateService.new(nil, self, params).execute(skip_authorization: true)
end
end
@@ -1118,7 +1111,7 @@ class Project < ActiveRecord::Base
end
def jira_tracker?
- issues_tracker.to_param == 'jira'
+ issues_tracker.to_param == "jira"
end
def avatar_in_git
@@ -1135,16 +1128,16 @@ class Project < ActiveRecord::Base
end
def all_clusters
- group_clusters = Clusters::Cluster.joins(:groups).where(cluster_groups: { group_id: ancestors_upto } )
+ group_clusters = Clusters::Cluster.joins(:groups).where(cluster_groups: {group_id: ancestors_upto})
Clusters::Cluster.from_union([clusters, group_clusters])
end
def items_for(entity)
case entity
- when 'issue' then
+ when "issue" then
issues
- when 'merge_request' then
+ when "merge_request" then
merge_requests
end
end
@@ -1160,11 +1153,7 @@ class Project < ActiveRecord::Base
# rubocop: enable CodeReuse/ServiceClass
def owner
- if group
- group
- else
- namespace.try(:owner)
- end
+ group || namespace.try(:owner)
end
# rubocop: disable CodeReuse/ServiceClass
@@ -1190,7 +1179,7 @@ class Project < ActiveRecord::Base
def valid_repo?
repository.exists?
rescue
- errors.add(:path, 'Invalid repository path')
+ errors.add(:path, "Invalid repository path")
false
end
@@ -1200,11 +1189,9 @@ class Project < ActiveRecord::Base
def repo_exists?
strong_memoize(:repo_exists) do
- begin
- repository.exists?
- rescue
- false
- end
+ repository.exists?
+ rescue
+ false
end
end
@@ -1283,7 +1270,7 @@ class Project < ActiveRecord::Base
# Check if repository with same path already exists on disk we can
# skip this for the hashed storage because the path does not change
if legacy_storage? && repository_with_same_path_already_exists?
- errors.add(:base, 'There is already a repository with that name on disk')
+ errors.add(:base, "There is already a repository with that name on disk")
return false
end
@@ -1305,7 +1292,7 @@ class Project < ActiveRecord::Base
repository.after_create
true
else
- errors.add(:base, 'Failed to create repository via gitlab-shell')
+ errors.add(:base, "Failed to create repository via gitlab-shell")
false
end
end
@@ -1323,17 +1310,17 @@ class Project < ActiveRecord::Base
visibility_level: visibility_level,
path_with_namespace: full_path,
default_branch: default_branch,
- ci_config_path: ci_config_path
+ ci_config_path: ci_config_path,
}
# Backward compatibility
if backward
attrs.merge!({
- homepage: web_url,
- url: url_to_repo,
- ssh_url: ssh_url_to_repo,
- http_url: http_url_to_repo
- })
+ homepage: web_url,
+ url: url_to_repo,
+ ssh_url: ssh_url_to_repo,
+ http_url: http_url_to_repo,
+ })
end
attrs
@@ -1354,7 +1341,7 @@ class Project < ActiveRecord::Base
else
return [] if users.empty?
- user_ids = authorized_users.where(users: { id: users.map(&:id) }).pluck(:id)
+ user_ids = authorized_users.where(users: {id: users.map(&:id)}).pluck(:id)
users.select { |user| user_ids.include?(user.id) }
end
end
@@ -1375,7 +1362,7 @@ class Project < ActiveRecord::Base
def change_head(branch)
if repository.branch_exists?(branch)
repository.before_change_head
- repository.raw_repository.write_ref('HEAD', "refs/heads/#{branch}")
+ repository.raw_repository.write_ref("HEAD", "refs/heads/#{branch}")
repository.copy_gitattributes(branch)
repository.after_change_head
reload_default_branch
@@ -1401,7 +1388,7 @@ class Project < ActiveRecord::Base
end
def origin_merge_requests
- merge_requests.where(source_project_id: self.id)
+ merge_requests.where(source_project_id: id)
end
def ensure_repository
@@ -1429,15 +1416,15 @@ class Project < ActiveRecord::Base
end
def create_wiki
- ProjectWiki.new(self, self.owner).wiki
+ ProjectWiki.new(self, owner).wiki
true
rescue ProjectWiki::CouldNotCreateWikiError
- errors.add(:base, 'Failed create wiki')
+ errors.add(:base, "Failed create wiki")
false
end
def wiki
- @wiki ||= ProjectWiki.new(self, self.owner)
+ @wiki ||= ProjectWiki.new(self, owner)
end
def jira_tracker_active?
@@ -1486,7 +1473,7 @@ class Project < ActiveRecord::Base
end
def group_runners
- @group_runners ||= group_runners_enabled? ? Ci::Runner.belonging_to_parent_group_of_project(self.id) : Ci::Runner.none
+ @group_runners ||= group_runners_enabled? ? Ci::Runner.belonging_to_parent_group_of_project(id) : Ci::Runner.none
end
def all_runners
@@ -1504,7 +1491,7 @@ class Project < ActiveRecord::Base
end
def valid_runners_token?(token)
- self.runners_token && ActiveSupport::SecurityUtils.variable_size_secure_compare(token, self.runners_token)
+ runners_token && ActiveSupport::SecurityUtils.variable_size_secure_compare(token, runners_token)
end
# rubocop: disable CodeReuse/ServiceClass
@@ -1519,7 +1506,7 @@ class Project < ActiveRecord::Base
end
# rubocop: enable CodeReuse/ServiceClass
- def visibility_level_allowed_as_fork?(level = self.visibility_level)
+ def visibility_level_allowed_as_fork?(level = visibility_level)
return true unless forked?
original_project = fork_source
@@ -1528,13 +1515,13 @@ class Project < ActiveRecord::Base
level <= original_project.visibility_level
end
- def visibility_level_allowed_by_group?(level = self.visibility_level)
+ def visibility_level_allowed_by_group?(level = visibility_level)
return true unless group
level <= group.visibility_level
end
- def visibility_level_allowed?(level = self.visibility_level)
+ def visibility_level_allowed?(level = visibility_level)
visibility_level_allowed_as_fork?(level) && visibility_level_allowed_by_group?(level)
end
@@ -1548,14 +1535,14 @@ class Project < ActiveRecord::Base
def pages_group_url
# The host in URL always needs to be downcased
- Gitlab.config.pages.url.sub(%r{^https?://}) do |prefix|
+ Gitlab.config.pages.url.sub(%r{^https?://}) { |prefix|
"#{prefix}#{pages_subdomain}."
- end.downcase
+ }.downcase
end
def pages_url
url = pages_group_url
- url_path = full_path.partition('/').last
+ url_path = full_path.partition("/").last
# If the project path is the same as host, we serve it as group page
return url if url == "#{Settings.pages.protocol}://#{url_path}"
@@ -1564,7 +1551,7 @@ class Project < ActiveRecord::Base
end
def pages_subdomain
- full_path.partition('/').first
+ full_path.partition("/").first
end
def pages_path
@@ -1573,7 +1560,7 @@ class Project < ActiveRecord::Base
end
def public_pages_path
- File.join(pages_path, 'public')
+ File.join(pages_path, "public")
end
def pages_available?
@@ -1591,8 +1578,8 @@ class Project < ActiveRecord::Base
SQL
deploy_keys.where(public: false)
- .where(exclude_keys_linked_to_other_projects)
- .delete_all
+ .where(exclude_keys_linked_to_other_projects)
+ .delete_all
end
# TODO: what to do here when not using Legacy Storage? Do we still need to rename and delay removal?
@@ -1645,7 +1632,7 @@ class Project < ActiveRecord::Base
def update_project_counter_caches
classes = [
Projects::OpenIssuesCountService,
- Projects::OpenMergeRequestsCountService
+ Projects::OpenMergeRequestsCountService,
]
classes.each do |klass|
@@ -1665,12 +1652,12 @@ class Project < ActiveRecord::Base
end
def add_export_job(current_user:, after_export_strategy: nil, params: {})
- job_id = ProjectExportWorker.perform_async(current_user.id, self.id, after_export_strategy, params)
+ job_id = ProjectExportWorker.perform_async(current_user.id, id, after_export_strategy, params)
if job_id
- Rails.logger.info "Export job started for project ID #{self.id} with job ID #{job_id}"
+ Rails.logger.info "Export job started for project ID #{id} with job ID #{job_id}"
else
- Rails.logger.error "Export job failed to start for project ID #{self.id}"
+ Rails.logger.error "Export job failed to start for project ID #{id}"
end
end
@@ -1731,13 +1718,13 @@ class Project < ActiveRecord::Base
visibility = Gitlab::VisibilityLevel.string_level(visibility_level)
Gitlab::Ci::Variables::Collection.new
- .append(key: 'CI_PROJECT_ID', value: id.to_s)
- .append(key: 'CI_PROJECT_NAME', value: path)
- .append(key: 'CI_PROJECT_PATH', value: full_path)
- .append(key: 'CI_PROJECT_PATH_SLUG', value: full_path_slug)
- .append(key: 'CI_PROJECT_NAMESPACE', value: namespace.full_path)
- .append(key: 'CI_PROJECT_URL', value: web_url)
- .append(key: 'CI_PROJECT_VISIBILITY', value: visibility)
+ .append(key: "CI_PROJECT_ID", value: id.to_s)
+ .append(key: "CI_PROJECT_NAME", value: path)
+ .append(key: "CI_PROJECT_PATH", value: full_path)
+ .append(key: "CI_PROJECT_PATH_SLUG", value: full_path_slug)
+ .append(key: "CI_PROJECT_NAMESPACE", value: namespace.full_path)
+ .append(key: "CI_PROJECT_URL", value: web_url)
+ .append(key: "CI_PROJECT_VISIBILITY", value: visibility)
.concat(pages_variables)
.concat(container_registry_variables)
.concat(auto_devops_variables)
@@ -1746,14 +1733,14 @@ class Project < ActiveRecord::Base
def pages_variables
Gitlab::Ci::Variables::Collection.new.tap do |variables|
- variables.append(key: 'CI_PAGES_DOMAIN', value: Gitlab.config.pages.host)
- variables.append(key: 'CI_PAGES_URL', value: pages_url)
+ variables.append(key: "CI_PAGES_DOMAIN", value: Gitlab.config.pages.host)
+ variables.append(key: "CI_PAGES_URL", value: pages_url)
end
end
def api_variables
Gitlab::Ci::Variables::Collection.new.tap do |variables|
- variables.append(key: 'CI_API_V4_URL', value: API::Helpers::Version.new('v4').root_url)
+ variables.append(key: "CI_API_V4_URL", value: API::Helpers::Version.new("v4").root_url)
end
end
@@ -1761,10 +1748,10 @@ class Project < ActiveRecord::Base
Gitlab::Ci::Variables::Collection.new.tap do |variables|
break variables unless Gitlab.config.registry.enabled
- variables.append(key: 'CI_REGISTRY', value: Gitlab.config.registry.host_port)
+ variables.append(key: "CI_REGISTRY", value: Gitlab.config.registry.host_port)
if container_registry_enabled?
- variables.append(key: 'CI_REGISTRY_IMAGE', value: container_registry_url)
+ variables.append(key: "CI_REGISTRY_IMAGE", value: container_registry_url)
end
end
end
@@ -1794,10 +1781,10 @@ class Project < ActiveRecord::Base
return false unless Gitlab::Git.tag_ref?(resolved_ref) || Gitlab::Git.branch_ref?(resolved_ref)
ref_name = if resolved_ref == ref
- Gitlab::Git.ref_name(resolved_ref)
- else
- ref
- end
+ Gitlab::Git.ref_name(resolved_ref)
+ else
+ ref
+ end
if Gitlab::Git.branch_ref?(resolved_ref)
ProtectedBranch.protected?(self, ref_name)
@@ -1824,7 +1811,6 @@ class Project < ActiveRecord::Base
else
update_attribute(name, value)
end
-
rescue ActiveRecord::RecordNotSaved => e
handle_update_attribute_error(e, value)
end
@@ -1860,16 +1846,16 @@ class Project < ActiveRecord::Base
end
def route_map_for(commit_sha)
- @route_maps_by_commit ||= Hash.new do |h, sha|
+ @route_maps_by_commit ||= Hash.new { |h, sha|
h[sha] = begin
data = repository.route_map_for(sha)
next unless data
Gitlab::RouteMap.new(data)
- rescue Gitlab::RouteMap::FormatError
- nil
+ rescue Gitlab::RouteMap::FormatError
+ nil
end
- end
+ }
@route_maps_by_commit[commit_sha]
end
@@ -1899,13 +1885,13 @@ class Project < ActiveRecord::Base
end
def full_path_was
- File.join(namespace.full_path, previous_changes['path'].first)
+ File.join(namespace.full_path, previous_changes["path"].first)
end
- alias_method :name_with_namespace, :full_name
- alias_method :human_name, :full_name
+ alias name_with_namespace full_name
+ alias human_name full_name
# @deprecated cannot remove yet because it has an index with its name in elasticsearch
- alias_method :path_with_namespace, :full_path
+ alias path_with_namespace full_path
# rubocop: disable CodeReuse/ServiceClass
def forks_count
@@ -1914,7 +1900,7 @@ class Project < ActiveRecord::Base
# rubocop: enable CodeReuse/ServiceClass
def legacy_storage?
- [nil, 0].include?(self.storage_version)
+ [nil, 0].include?(storage_version)
end
# Check if Hashed Storage is enabled for the project with at least informed feature rolled out
@@ -1923,7 +1909,7 @@ class Project < ActiveRecord::Base
def hashed_storage?(feature)
raise ArgumentError, "Invalid feature" unless HASHED_STORAGE_FEATURES.include?(feature)
- self.storage_version && self.storage_version >= HASHED_STORAGE_FEATURES[feature]
+ storage_version && storage_version >= HASHED_STORAGE_FEATURES[feature]
end
def renamed?
@@ -1932,16 +1918,16 @@ class Project < ActiveRecord::Base
def human_merge_method
if merge_method == :ff
- 'Fast-forward'
+ "Fast-forward"
else
merge_method.to_s.humanize
end
end
def merge_method
- if self.merge_requests_ff_only_enabled
+ if merge_requests_ff_only_enabled
:ff
- elsif self.merge_requests_rebase_enabled
+ elsif merge_requests_rebase_enabled
:rebase_merge
else
:merge
@@ -1963,7 +1949,7 @@ class Project < ActiveRecord::Base
end
def ff_merge_must_be_possible?
- self.merge_requests_ff_only_enabled || self.merge_requests_rebase_enabled
+ merge_requests_ff_only_enabled || merge_requests_rebase_enabled
end
def migrate_to_hashed_storage!
@@ -1999,7 +1985,7 @@ class Project < ActiveRecord::Base
Badge.from_union([
project_badges,
- GroupBadge.where(group: group.self_and_ancestors)
+ GroupBadge.where(group: group.self_and_ancestors),
])
end
@@ -2007,11 +1993,11 @@ class Project < ActiveRecord::Base
return MergeRequest.none unless user
developer_access_exists = user.project_authorizations
- .where('access_level >= ? ', Gitlab::Access::DEVELOPER)
- .where('project_authorizations.project_id = merge_requests.target_project_id')
- .limit(1)
- .select(1)
- merge_requests_allowing_collaboration.where('EXISTS (?)', developer_access_exists)
+ .where("access_level >= ? ", Gitlab::Access::DEVELOPER)
+ .where("project_authorizations.project_id = merge_requests.target_project_id")
+ .limit(1)
+ .select(1)
+ merge_requests_allowing_collaboration.where("EXISTS (?)", developer_access_exists)
end
def any_branch_allows_collaboration?(user)
@@ -2037,10 +2023,10 @@ class Project < ActiveRecord::Base
def any_lfs_file_locks?
lfs_file_locks.any?
end
- request_cache(:any_lfs_file_locks?) { self.id }
+ request_cache(:any_lfs_file_locks?) { id }
def auto_cancel_pending_pipelines?
- auto_cancel_pending_pipelines == 'enabled'
+ auto_cancel_pending_pipelines == "enabled"
end
def storage
@@ -2069,7 +2055,7 @@ class Project < ActiveRecord::Base
{
repository_storage: repository_storage,
- pool_repository: pool_repository || create_new_pool_repository
+ pool_repository: pool_repository || create_new_pool_repository,
}
end
@@ -2121,11 +2107,11 @@ class Project < ActiveRecord::Base
def join_pool_repository
return unless pool_repository
- ObjectPool::JoinWorker.perform_async(pool_repository.id, self.id)
+ ObjectPool::JoinWorker.perform_async(pool_repository.id, id)
end
def use_hashed_storage
- if self.new_record? && Gitlab::CurrentSettings.hashed_storage_enabled
+ if new_record? && Gitlab::CurrentSettings.hashed_storage_enabled
self.storage_version = LATEST_STORAGE_VERSION
end
end
@@ -2142,7 +2128,7 @@ class Project < ActiveRecord::Base
return if skip_disk_validation
if repository_storage.blank? || repository_with_same_path_already_exists?
- errors.add(:base, 'There is already a repository with that name on disk')
+ errors.add(:base, "There is already a repository with that name on disk")
throw :abort
end
end
@@ -2152,7 +2138,7 @@ class Project < ActiveRecord::Base
end
def set_timestamps_for_create
- update_columns(last_activity_at: self.created_at, last_repository_updated_at: self.created_at)
+ update_columns(last_activity_at: created_at, last_repository_updated_at: created_at)
end
def cross_namespace_reference?(from)
@@ -2183,7 +2169,7 @@ class Project < ActiveRecord::Base
# already have 1, 2, or n it will fail, but it if you have 0 that is lower
# than the number of permitted boards per project it won't fail.
def validate_board_limit(board)
- raise BoardLimitExceeded, 'Number of permitted boards exceeded' if boards.size >= NUMBER_OF_PERMITTED_BOARDS
+ raise BoardLimitExceeded, "Number of permitted boards exceeded" if boards.size >= NUMBER_OF_PERMITTED_BOARDS
end
def update_project_statistics
@@ -2220,11 +2206,11 @@ class Project < ActiveRecord::Base
end
def handle_update_attribute_error(ex, value)
- if ex.message.start_with?('Failed to replace')
+ if ex.message.start_with?("Failed to replace")
if value.respond_to?(:each)
invalid = value.detect(&:invalid?)
- raise ex, ([ex.message] + invalid.errors.full_messages).join(' ') if invalid
+ raise ex, ([ex.message] + invalid.errors.full_messages).join(" ") if invalid
end
end
diff --git a/app/models/project_authorization.rb b/app/models/project_authorization.rb
index 2c590008db2..b0961f9529d 100644
--- a/app/models/project_authorization.rb
+++ b/app/models/project_authorization.rb
@@ -7,24 +7,24 @@ class ProjectAuthorization < ActiveRecord::Base
belongs_to :project
validates :project, presence: true
- validates :access_level, inclusion: { in: Gitlab::Access.all_values }, presence: true
- validates :user, uniqueness: { scope: [:project, :access_level] }, presence: true
+ validates :access_level, inclusion: {in: Gitlab::Access.all_values}, presence: true
+ validates :user, uniqueness: {scope: [:project, :access_level]}, presence: true
def self.select_from_union(relations)
from_union(relations)
- .select(['project_id', 'MAX(access_level) AS access_level'])
+ .select(["project_id", "MAX(access_level) AS access_level"])
.group(:project_id)
end
def self.insert_authorizations(rows, per_batch = 1000)
rows.each_slice(per_batch) do |slice|
- tuples = slice.map do |tuple|
+ tuples = slice.map { |tuple|
tuple.map { |value| connection.quote(value) }
- end
+ }
connection.execute <<-EOF.strip_heredoc
INSERT INTO project_authorizations (user_id, project_id, access_level)
- VALUES #{tuples.map { |tuple| "(#{tuple.join(', ')})" }.join(', ')}
+ VALUES #{tuples.map { |tuple| "(#{tuple.join(", ")})" }.join(", ")}
EOF
end
end
diff --git a/app/models/project_auto_devops.rb b/app/models/project_auto_devops.rb
index e353a6443c4..d865c8832ed 100644
--- a/app/models/project_auto_devops.rb
+++ b/app/models/project_auto_devops.rb
@@ -6,13 +6,13 @@ class ProjectAutoDevops < ActiveRecord::Base
enum deploy_strategy: {
continuous: 0,
manual: 1,
- timed_incremental: 2
+ timed_incremental: 2,
}
scope :enabled, -> { where(enabled: true) }
scope :disabled, -> { where(enabled: false) }
- validates :domain, allow_blank: true, hostname: { allow_numeric_hostname: true }
+ validates :domain, allow_blank: true, hostname: {allow_numeric_hostname: true}
after_save :create_gitlab_deploy_token, if: :needs_to_create_deploy_token?
@@ -33,7 +33,7 @@ class ProjectAutoDevops < ActiveRecord::Base
def predefined_variables
Gitlab::Ci::Variables::Collection.new.tap do |variables|
if has_domain?
- variables.append(key: 'AUTO_DEVOPS_DOMAIN',
+ variables.append(key: "AUTO_DEVOPS_DOMAIN",
value: domain.presence || instance_domain)
end
@@ -59,11 +59,11 @@ class ProjectAutoDevops < ActiveRecord::Base
def deployment_strategy_default_variables
Gitlab::Ci::Variables::Collection.new.tap do |variables|
if manual?
- variables.append(key: 'STAGING_ENABLED', value: '1')
- variables.append(key: 'INCREMENTAL_ROLLOUT_ENABLED', value: '1') # deprecated
- variables.append(key: 'INCREMENTAL_ROLLOUT_MODE', value: 'manual')
+ variables.append(key: "STAGING_ENABLED", value: "1")
+ variables.append(key: "INCREMENTAL_ROLLOUT_ENABLED", value: "1") # deprecated
+ variables.append(key: "INCREMENTAL_ROLLOUT_MODE", value: "manual")
elsif timed_incremental?
- variables.append(key: 'INCREMENTAL_ROLLOUT_MODE', value: 'timed')
+ variables.append(key: "INCREMENTAL_ROLLOUT_MODE", value: "timed")
end
end
end
diff --git a/app/models/project_custom_attribute.rb b/app/models/project_custom_attribute.rb
index 4e767cb3b26..2c6690c6c78 100644
--- a/app/models/project_custom_attribute.rb
+++ b/app/models/project_custom_attribute.rb
@@ -4,5 +4,5 @@ class ProjectCustomAttribute < ActiveRecord::Base
belongs_to :project
validates :project, :key, :value, presence: true
- validates :key, uniqueness: { scope: [:project_id] }
+ validates :key, uniqueness: {scope: [:project_id]}
end
diff --git a/app/models/project_daily_statistic.rb b/app/models/project_daily_statistic.rb
index ff115dd010f..8e14ad35dac 100644
--- a/app/models/project_daily_statistic.rb
+++ b/app/models/project_daily_statistic.rb
@@ -3,8 +3,8 @@
class ProjectDailyStatistic < ActiveRecord::Base
belongs_to :project
- scope :of_project, -> (project) { where(project: project) }
- scope :of_last_30_days, -> { where('date >= ?', 29.days.ago.utc.to_date) }
+ scope :of_project, ->(project) { where(project: project) }
+ scope :of_last_30_days, -> { where("date >= ?", 29.days.ago.utc.to_date) }
scope :sorted_by_date_desc, -> { order(project_id: :desc, date: :desc) }
scope :sum_fetch_count, -> { sum(:fetch_count) }
end
diff --git a/app/models/project_deploy_token.rb b/app/models/project_deploy_token.rb
index 719c492a1ff..eeb71065323 100644
--- a/app/models/project_deploy_token.rb
+++ b/app/models/project_deploy_token.rb
@@ -6,5 +6,5 @@ class ProjectDeployToken < ActiveRecord::Base
validates :deploy_token, presence: true
validates :project, presence: true
- validates :deploy_token_id, uniqueness: { scope: [:project_id] }
+ validates :deploy_token_id, uniqueness: {scope: [:project_id]}
end
diff --git a/app/models/project_feature.rb b/app/models/project_feature.rb
index f700090a493..41de4b6d131 100644
--- a/app/models/project_feature.rb
+++ b/app/models/project_feature.rb
@@ -22,8 +22,8 @@ class ProjectFeature < ActiveRecord::Base
ENABLED = 20
PUBLIC = 30
- FEATURES = %i(issues merge_requests wiki snippets builds repository pages).freeze
- PRIVATE_FEATURES_MIN_ACCESS_LEVEL = { merge_requests: Gitlab::Access::REPORTER }.freeze
+ FEATURES = %i[issues merge_requests wiki snippets builds repository pages].freeze
+ PRIVATE_FEATURES_MIN_ACCESS_LEVEL = {merge_requests: Gitlab::Access::REPORTER}.freeze
class << self
def access_level_attribute(feature)
@@ -117,10 +117,10 @@ class ProjectFeature < ActiveRecord::Base
validator = lambda do |field|
level = public_send(field) || ProjectFeature::ENABLED # rubocop:disable GitlabSecurity/PublicSend
not_allowed = level > repository_access_level
- self.errors.add(field, "cannot have higher visibility level than repository access level") if not_allowed
+ errors.add(field, "cannot have higher visibility level than repository access level") if not_allowed
end
- %i(merge_requests_access_level builds_access_level).each(&validator)
+ %i[merge_requests_access_level builds_access_level].each(&validator)
end
# Validates access level for other than pages cannot be PUBLIC
@@ -128,10 +128,10 @@ class ProjectFeature < ActiveRecord::Base
validator = lambda do |field|
level = public_send(field) || ProjectFeature::ENABLED # rubocop:disable GitlabSecurity/PublicSend
not_allowed = level > ProjectFeature::ENABLED
- self.errors.add(field, "cannot have public visibility level") if not_allowed
+ errors.add(field, "cannot have public visibility level") if not_allowed
end
- (FEATURES - %i(pages)).each {|f| validator.call("#{f}_access_level")}
+ (FEATURES - %i[pages]).each {|f| validator.call("#{f}_access_level")}
end
def get_permission(user, level)
diff --git a/app/models/project_group_link.rb b/app/models/project_group_link.rb
index bc3759142ae..9021a2b8f66 100644
--- a/app/models/project_group_link.rb
+++ b/app/models/project_group_link.rb
@@ -14,9 +14,9 @@ class ProjectGroupLink < ActiveRecord::Base
validates :project_id, presence: true
validates :group, presence: true
- validates :group_id, uniqueness: { scope: [:project_id], message: "already shared with this group" }
+ validates :group_id, uniqueness: {scope: [:project_id], message: "already shared with this group"}
validates :group_access, presence: true
- validates :group_access, inclusion: { in: Gitlab::Access.values }, presence: true
+ validates :group_access, inclusion: {in: Gitlab::Access.values}, presence: true
validate :different_group
after_commit :refresh_group_members_authorized_projects
@@ -30,20 +30,20 @@ class ProjectGroupLink < ActiveRecord::Base
end
def human_access
- self.class.access_options.key(self.group_access)
+ self.class.access_options.key(group_access)
end
private
def different_group
- return unless self.group && self.project
+ return unless group && project
- project_group = self.project.group
+ project_group = project.group
return unless project_group
group_ids = project_group.ancestors.map(&:id).push(project_group.id)
- if group_ids.include?(self.group.id)
+ if group_ids.include?(group.id)
errors.add(:base, "Project cannot be shared with the group it is in or one of its ancestors.")
end
end
diff --git a/app/models/project_import_data.rb b/app/models/project_import_data.rb
index aa0c121fe99..9ec8422523e 100644
--- a/app/models/project_import_data.rb
+++ b/app/models/project_import_data.rb
@@ -1,16 +1,16 @@
# frozen_string_literal: true
-require 'carrierwave/orm/activerecord'
+require "carrierwave/orm/activerecord"
class ProjectImportData < ActiveRecord::Base
belongs_to :project, inverse_of: :import_data
attr_encrypted :credentials,
- key: Settings.attr_encrypted_db_key_base,
- marshal: true,
- encode: true,
- mode: :per_attribute_iv_and_salt,
- insecure_mode: true,
- algorithm: 'aes-256-cbc'
+ key: Settings.attr_encrypted_db_key_base,
+ marshal: true,
+ encode: true,
+ mode: :per_attribute_iv_and_salt,
+ insecure_mode: true,
+ algorithm: "aes-256-cbc"
serialize :data, JSON # rubocop:disable Cop/ActiveRecordSerialize
@@ -20,7 +20,7 @@ class ProjectImportData < ActiveRecord::Base
def symbolize_credentials
# bang doesn't work here - attr_encrypted makes it not to work
- self.credentials = self.credentials.deep_symbolize_keys unless self.credentials.blank?
+ self.credentials = credentials.deep_symbolize_keys unless credentials.blank?
end
def merge_data(hash)
diff --git a/app/models/project_import_state.rb b/app/models/project_import_state.rb
index 488f0cb5971..4f2d499c77c 100644
--- a/app/models/project_import_state.rb
+++ b/app/models/project_import_state.rb
@@ -70,7 +70,7 @@ class ProjectImportState < ActiveRecord::Base
@errors = original_errors
end
- alias_method :no_import?, :none?
+ alias no_import? none?
def in_progress?
scheduled? || started?
@@ -78,7 +78,7 @@ class ProjectImportState < ActiveRecord::Base
def started?
# import? does SQL work so only run it if it looks like there's an import running
- status == 'started' && project.import?
+ status == "started" && project.import?
end
def remove_jid
diff --git a/app/models/project_label.rb b/app/models/project_label.rb
index d0b16cc98b4..0b5c6ce7916 100644
--- a/app/models/project_label.rb
+++ b/app/models/project_label.rb
@@ -15,7 +15,7 @@ class ProjectLabel < Label
alias_attribute :subject, :project
def subject_foreign_key
- 'project_id'
+ "project_id"
end
def to_reference(target_project = nil, format: :id, full: false)
@@ -27,14 +27,14 @@ class ProjectLabel < Label
def title_must_not_exist_at_group_level
return unless group.present? && title_changed?
- if group.labels.with_title(self.title).exists?
+ if group.labels.with_title(title).exists?
errors.add(:title, :label_already_exists_at_group_level, group: group.name)
end
end
def permitted_numbers_of_priorities
if priorities && priorities.size > MAX_NUMBER_OF_PRIORITIES
- errors.add(:priorities, 'Number of permitted priorities exceeded')
+ errors.add(:priorities, "Number of permitted priorities exceeded")
end
end
end
diff --git a/app/models/project_services/asana_service.rb b/app/models/project_services/asana_service.rb
index cc5f1207653..b02fac2994a 100644
--- a/app/models/project_services/asana_service.rb
+++ b/app/models/project_services/asana_service.rb
@@ -1,17 +1,17 @@
# frozen_string_literal: true
-require 'asana'
+require "asana"
class AsanaService < Service
prop_accessor :api_key, :restrict_to_branch
validates :api_key, presence: true, if: :activated?
def title
- 'Asana'
+ "Asana"
end
def description
- 'Asana - Teamwork without email'
+ "Asana - Teamwork without email"
end
def help
@@ -28,27 +28,27 @@ http://app.asana.com/-/account_api'
end
def self.to_param
- 'asana'
+ "asana"
end
def fields
[
{
- type: 'text',
- name: 'api_key',
- placeholder: 'User Personal Access Token. User must have access to task, all comments will be attributed to this user.',
- required: true
+ type: "text",
+ name: "api_key",
+ placeholder: "User Personal Access Token. User must have access to task, all comments will be attributed to this user.",
+ required: true,
},
{
- type: 'text',
- name: 'restrict_to_branch',
- placeholder: 'Comma-separated list of branches which will be automatically inspected. Leave blank to include all branches.'
- }
+ type: "text",
+ name: "restrict_to_branch",
+ placeholder: "Comma-separated list of branches which will be automatically inspected. Leave blank to include all branches.",
+ },
]
end
def self.supported_events
- %w(push)
+ %w[push]
end
def client
diff --git a/app/models/project_services/assembla_service.rb b/app/models/project_services/assembla_service.rb
index 60575e45a90..a627c31363a 100644
--- a/app/models/project_services/assembla_service.rb
+++ b/app/models/project_services/assembla_service.rb
@@ -5,32 +5,32 @@ class AssemblaService < Service
validates :token, presence: true, if: :activated?
def title
- 'Assembla'
+ "Assembla"
end
def description
- 'Project Management Software (Source Commits Endpoint)'
+ "Project Management Software (Source Commits Endpoint)"
end
def self.to_param
- 'assembla'
+ "assembla"
end
def fields
[
- { type: 'text', name: 'token', placeholder: '', required: true },
- { type: 'text', name: 'subdomain', placeholder: '' }
+ {type: "text", name: "token", placeholder: "", required: true},
+ {type: "text", name: "subdomain", placeholder: ""},
]
end
def self.supported_events
- %w(push)
+ %w[push]
end
def execute(data)
return unless supported_events.include?(data[:object_kind])
url = "https://atlas.assembla.com/spaces/#{subdomain}/github_tool?secret_key=#{token}"
- Gitlab::HTTP.post(url, body: { payload: data }.to_json, headers: { 'Content-Type' => 'application/json' })
+ Gitlab::HTTP.post(url, body: {payload: data}.to_json, headers: {"Content-Type" => "application/json"})
end
end
diff --git a/app/models/project_services/bamboo_service.rb b/app/models/project_services/bamboo_service.rb
index 71f5607dbdb..1fce9af9deb 100644
--- a/app/models/project_services/bamboo_service.rb
+++ b/app/models/project_services/bamboo_service.rb
@@ -31,30 +31,30 @@ class BambooService < CiService
end
def title
- 'Atlassian Bamboo CI'
+ "Atlassian Bamboo CI"
end
def description
- 'A continuous integration and build server'
+ "A continuous integration and build server"
end
def help
- 'You must set up automatic revision labeling and a repository trigger in Bamboo.'
+ "You must set up automatic revision labeling and a repository trigger in Bamboo."
end
def self.to_param
- 'bamboo'
+ "bamboo"
end
def fields
[
- { type: 'text', name: 'bamboo_url',
- placeholder: 'Bamboo root URL like https://bamboo.example.com', required: true },
- { type: 'text', name: 'build_key',
- placeholder: 'Bamboo build plan key like KEY', required: true },
- { type: 'text', name: 'username',
- placeholder: 'A user with API access, if applicable' },
- { type: 'password', name: 'password' }
+ {type: "text", name: "bamboo_url",
+ placeholder: "Bamboo root URL like https://bamboo.example.com", required: true,},
+ {type: "text", name: "build_key",
+ placeholder: "Bamboo build plan key like KEY", required: true,},
+ {type: "text", name: "username",
+ placeholder: "A user with API access, if applicable",},
+ {type: "password", name: "password"},
]
end
@@ -69,13 +69,13 @@ class BambooService < CiService
def execute(data)
return unless supported_events.include?(data[:object_kind])
- get_path("updateAndBuild.action", { buildKey: build_key })
+ get_path("updateAndBuild.action", {buildKey: build_key})
end
def calculate_reactive_cache(sha, ref)
response = get_path("rest/api/latest/result/byChangeset/#{sha}")
- { build_page: read_build_page(response), commit_status: read_commit_status(response) }
+ {build_page: read_build_page(response), commit_status: read_commit_status(response)}
end
private
@@ -84,7 +84,7 @@ class BambooService < CiService
return if response.code != 200
# May be nil if no result, a single result hash, or an array if multiple results for a given changeset.
- result = response.dig('results', 'results', 'result')
+ result = response.dig("results", "results", "result")
# In case of multiple results, arbitrarily assume the last one is the most relevant.
return result.last if result.is_a?(Array)
@@ -100,7 +100,7 @@ class BambooService < CiService
build_key
else
# If actual build link is available, go to build result page.
- result.dig('planResultKey', 'key')
+ result.dig("planResultKey", "key")
end
build_url("browse/#{key}")
@@ -112,19 +112,19 @@ class BambooService < CiService
result = get_build_result(response)
status =
if result.blank?
- 'Pending'
+ "Pending"
else
- result.dig('buildState')
+ result.dig("buildState")
end
return :error unless status.present?
- if status.include?('Success')
- 'success'
- elsif status.include?('Failed')
- 'failed'
- elsif status.include?('Pending')
- 'pending'
+ if status.include?("Success")
+ "success"
+ elsif status.include?("Failed")
+ "failed"
+ elsif status.include?("Pending")
+ "pending"
else
:error
end
@@ -140,14 +140,14 @@ class BambooService < CiService
if username.blank? && password.blank?
Gitlab::HTTP.get(url, verify: false, query: query_params)
else
- query_params[:os_authType] = 'basic'
+ query_params[:os_authType] = "basic"
Gitlab::HTTP.get(url,
- verify: false,
- query: query_params,
- basic_auth: {
- username: username,
- password: password
- })
+ verify: false,
+ query: query_params,
+ basic_auth: {
+ username: username,
+ password: password,
+ })
end
end
end
diff --git a/app/models/project_services/bugzilla_service.rb b/app/models/project_services/bugzilla_service.rb
index 1a2bb6a171b..e5828db3af6 100644
--- a/app/models/project_services/bugzilla_service.rb
+++ b/app/models/project_services/bugzilla_service.rb
@@ -6,22 +6,22 @@ class BugzillaService < IssueTrackerService
prop_accessor :title, :description, :project_url, :issues_url, :new_issue_url
def title
- if self.properties && self.properties['title'].present?
- self.properties['title']
+ if properties && properties["title"].present?
+ properties["title"]
else
- 'Bugzilla'
+ "Bugzilla"
end
end
def description
- if self.properties && self.properties['description'].present?
- self.properties['description']
+ if properties && properties["description"].present?
+ properties["description"]
else
- 'Bugzilla issue tracker'
+ "Bugzilla issue tracker"
end
end
def self.to_param
- 'bugzilla'
+ "bugzilla"
end
end
diff --git a/app/models/project_services/buildkite_service.rb b/app/models/project_services/buildkite_service.rb
index 43edfde851c..c34da0d155d 100644
--- a/app/models/project_services/buildkite_service.rb
+++ b/app/models/project_services/buildkite_service.rb
@@ -5,7 +5,7 @@ require "addressable/uri"
class BuildkiteService < CiService
include ReactiveService
- ENDPOINT = "https://buildkite.com".freeze
+ ENDPOINT = "https://buildkite.com"
prop_accessor :project_url, :token
boolean_accessor :enable_ssl_verification
@@ -16,7 +16,7 @@ class BuildkiteService < CiService
after_save :compose_service_hook, if: :activated?
def webhook_url
- "#{buildkite_endpoint('webhook')}/deliver/#{webhook_token}"
+ "#{buildkite_endpoint("webhook")}/deliver/#{webhook_token}"
end
def compose_service_hook
@@ -37,7 +37,7 @@ class BuildkiteService < CiService
end
def commit_status_path(sha)
- "#{buildkite_endpoint('gitlab')}/status/#{status_token}.json?commit=#{sha}"
+ "#{buildkite_endpoint("gitlab")}/status/#{status_token}.json?commit=#{sha}"
end
def build_page(sha, ref)
@@ -45,30 +45,30 @@ class BuildkiteService < CiService
end
def title
- 'Buildkite'
+ "Buildkite"
end
def description
- 'Continuous integration and deployments'
+ "Continuous integration and deployments"
end
def self.to_param
- 'buildkite'
+ "buildkite"
end
def fields
[
- { type: 'text',
- name: 'token',
- placeholder: 'Buildkite project GitLab token', required: true },
+ {type: "text",
+ name: "token",
+ placeholder: "Buildkite project GitLab token", required: true,},
- { type: 'text',
- name: 'project_url',
- placeholder: "#{ENDPOINT}/example/project", required: true },
+ {type: "text",
+ name: "project_url",
+ placeholder: "#{ENDPOINT}/example/project", required: true,},
- { type: 'checkbox',
- name: 'enable_ssl_verification',
- title: "Enable SSL verification" }
+ {type: "checkbox",
+ name: "enable_ssl_verification",
+ title: "Enable SSL verification",},
]
end
@@ -76,13 +76,13 @@ class BuildkiteService < CiService
response = Gitlab::HTTP.get(commit_status_path(sha), verify: false)
status =
- if response.code == 200 && response['status']
- response['status']
+ if response.code == 200 && response["status"]
+ response["status"]
else
:error
end
- { commit_status: status }
+ {commit_status: status}
end
private
@@ -97,7 +97,7 @@ class BuildkiteService < CiService
def token_parts
if token.present?
- token.split(':')
+ token.split(":")
else
[]
end
@@ -106,7 +106,7 @@ class BuildkiteService < CiService
def buildkite_endpoint(subdomain = nil)
if subdomain.present?
uri = Addressable::URI.parse(ENDPOINT)
- new_endpoint = "#{uri.scheme || 'http'}://#{subdomain}.#{uri.host}"
+ new_endpoint = "#{uri.scheme || "http"}://#{subdomain}.#{uri.host}"
if uri.port.present?
"#{new_endpoint}:#{uri.port}"
diff --git a/app/models/project_services/builds_email_service.rb b/app/models/project_services/builds_email_service.rb
index f2295a95b60..8adf3cd5fcf 100644
--- a/app/models/project_services/builds_email_service.rb
+++ b/app/models/project_services/builds_email_service.rb
@@ -4,7 +4,7 @@
# We should also by then remove BuildsEmailService from database
class BuildsEmailService < Service
def self.to_param
- 'builds_email'
+ "builds_email"
end
def self.supported_events
diff --git a/app/models/project_services/campfire_service.rb b/app/models/project_services/campfire_service.rb
index 1d7877a1fb5..fdd38ef8a73 100644
--- a/app/models/project_services/campfire_service.rb
+++ b/app/models/project_services/campfire_service.rb
@@ -5,34 +5,34 @@ class CampfireService < Service
validates :token, presence: true, if: :activated?
def title
- 'Campfire'
+ "Campfire"
end
def description
- 'Simple web-based real-time group chat'
+ "Simple web-based real-time group chat"
end
def self.to_param
- 'campfire'
+ "campfire"
end
def fields
[
- { type: 'text', name: 'token', placeholder: '', required: true },
- { type: 'text', name: 'subdomain', placeholder: '' },
- { type: 'text', name: 'room', placeholder: '' }
+ {type: "text", name: "token", placeholder: "", required: true},
+ {type: "text", name: "subdomain", placeholder: ""},
+ {type: "text", name: "room", placeholder: ""},
]
end
def self.supported_events
- %w(push)
+ %w[push]
end
def execute(data)
return unless supported_events.include?(data[:object_kind])
message = build_message(data)
- speak(self.room, message, auth)
+ speak(room, message, auth)
end
private
@@ -47,8 +47,8 @@ class CampfireService < Service
@auth ||= {
basic_auth: {
username: token,
- password: 'X'
- }
+ password: "X",
+ },
}
end
@@ -63,10 +63,10 @@ class CampfireService < Service
body = {
body: {
message: {
- type: 'TextMessage',
- body: message
- }
- }
+ type: "TextMessage",
+ body: message,
+ },
+ },
}
res = Gitlab::HTTP.post(path, base_uri: base_uri, **auth.merge(body))
res.code == 201 ? res : nil
diff --git a/app/models/project_services/chat_message/base_message.rb b/app/models/project_services/chat_message/base_message.rb
index 8c68ddc40f2..4b75b95f82e 100644
--- a/app/models/project_services/chat_message/base_message.rb
+++ b/app/models/project_services/chat_message/base_message.rb
@@ -1,6 +1,6 @@
# frozen_string_literal: true
-require 'slack-notifier'
+require "slack-notifier"
module ChatMessage
class BaseMessage
@@ -61,7 +61,7 @@ module ChatMessage
end
def attachment_color
- '#345'
+ "#345"
end
def link(text, url)
@@ -71,9 +71,9 @@ module ChatMessage
def pretty_duration(seconds)
parse_string =
if duration < 1.hour
- '%M:%S'
+ "%M:%S"
else
- '%H:%M:%S'
+ "%H:%M:%S"
end
Time.at(seconds).utc.strftime(parse_string)
diff --git a/app/models/project_services/chat_message/issue_message.rb b/app/models/project_services/chat_message/issue_message.rb
index 0cdcfcf0237..f97b41f01b7 100644
--- a/app/models/project_services/chat_message/issue_message.rb
+++ b/app/models/project_services/chat_message/issue_message.rb
@@ -19,7 +19,7 @@ module ChatMessage
@issue_url = obj_attr[:url]
@action = obj_attr[:action]
@state = obj_attr[:state]
- @description = obj_attr[:description] || ''
+ @description = obj_attr[:description] || ""
end
def attachments
@@ -34,7 +34,7 @@ module ChatMessage
title: "Issue #{state} by #{user_combined_name}",
subtitle: "in #{project_link}",
text: issue_link,
- image: user_avatar
+ image: user_avatar,
}
end
@@ -57,7 +57,7 @@ module ChatMessage
title: issue_title,
title_link: issue_url,
text: format(description),
- color: "#C95823"
+ color: "#C95823",
}]
end
diff --git a/app/models/project_services/chat_message/merge_message.rb b/app/models/project_services/chat_message/merge_message.rb
index 6b7a35aaa75..18f1e6e3058 100644
--- a/app/models/project_services/chat_message/merge_message.rb
+++ b/app/models/project_services/chat_message/merge_message.rb
@@ -29,14 +29,14 @@ module ChatMessage
title: "Merge Request #{state_or_action_text} by #{user_combined_name}",
subtitle: "in #{project_link}",
text: merge_request_link,
- image: user_avatar
+ image: user_avatar,
}
end
private
def format_title(title)
- '*' + title.lines.first.chomp + '*'
+ "*" + title.lines.first.chomp + "*"
end
def message
diff --git a/app/models/project_services/chat_message/note_message.rb b/app/models/project_services/chat_message/note_message.rb
index 741474fb27b..f83a4d58ae1 100644
--- a/app/models/project_services/chat_message/note_message.rb
+++ b/app/models/project_services/chat_message/note_message.rb
@@ -23,7 +23,7 @@ module ChatMessage
create_merge_note(params[:merge_request])
when "Snippet"
create_snippet_note(params[:snippet])
- end
+ end
end
def attachments
@@ -34,17 +34,17 @@ module ChatMessage
def activity
{
- title: "#{user_combined_name} #{link('commented on ' + target, note_url)}",
+ title: "#{user_combined_name} #{link("commented on " + target, note_url)}",
subtitle: "in #{project_link}",
text: formatted_title,
- image: user_avatar
+ image: user_avatar,
}
end
private
def message
- "#{user_combined_name} #{link('commented on ' + target, note_url)} in #{project_link}: *#{formatted_title}*"
+ "#{user_combined_name} #{link("commented on " + target, note_url)} in #{project_link}: *#{formatted_title}*"
end
def format_title(title)
@@ -74,7 +74,7 @@ module ChatMessage
end
def description_message
- [{ text: format(note), color: attachment_color }]
+ [{text: format(note), color: attachment_color}]
end
def project_link
diff --git a/app/models/project_services/chat_message/pipeline_message.rb b/app/models/project_services/chat_message/pipeline_message.rb
index 62aec4351db..325d036dc3a 100644
--- a/app/models/project_services/chat_message/pipeline_message.rb
+++ b/app/models/project_services/chat_message/pipeline_message.rb
@@ -11,10 +11,10 @@ module ChatMessage
def initialize(data)
super
- @user_name = data.dig(:user, :username) || 'API'
+ @user_name = data.dig(:user, :username) || "API"
pipeline_attributes = data[:object_attributes]
- @ref_type = pipeline_attributes[:tag] ? 'tag' : 'branch'
+ @ref_type = pipeline_attributes[:tag] ? "tag" : "branch"
@ref = pipeline_attributes[:ref]
@status = pipeline_attributes[:status]
@duration = pipeline_attributes[:duration].to_i
@@ -22,13 +22,13 @@ module ChatMessage
end
def pretext
- ''
+ ""
end
def attachments
return message if markdown
- [{ text: format(message), color: attachment_color }]
+ [{text: format(message), color: attachment_color}]
end
def activity
@@ -36,7 +36,7 @@ module ChatMessage
title: "Pipeline #{pipeline_link} of #{ref_type} #{branch_link} by #{user_combined_name} #{humanized_status}",
subtitle: "in #{project_link}",
text: "in #{pretty_duration(duration)}",
- image: user_avatar || ''
+ image: user_avatar || "",
}
end
@@ -48,18 +48,18 @@ module ChatMessage
def humanized_status
case status
- when 'success'
- 'passed'
+ when "success"
+ "passed"
else
status
end
end
def attachment_color
- if status == 'success'
- 'good'
+ if status == "success"
+ "good"
else
- 'danger'
+ "danger"
end
end
diff --git a/app/models/project_services/chat_message/push_message.rb b/app/models/project_services/chat_message/push_message.rb
index 5dd0414b7e6..413fb907796 100644
--- a/app/models/project_services/chat_message/push_message.rb
+++ b/app/models/project_services/chat_message/push_message.rb
@@ -14,7 +14,7 @@ module ChatMessage
@after = params[:after]
@before = params[:before]
@commits = params.fetch(:commits, [])
- @ref_type = Gitlab::Git.tag_ref?(params[:ref]) ? 'tag' : 'branch'
+ @ref_type = Gitlab::Git.tag_ref?(params[:ref]) ? "tag" : "branch"
@ref = Gitlab::Git.ref_name(params[:ref])
end
@@ -30,7 +30,7 @@ module ChatMessage
title: humanized_action(short: true),
subtitle: "in #{project_link}",
text: compare_link,
- image: user_avatar
+ image: user_avatar,
}
end
@@ -40,7 +40,7 @@ module ChatMessage
action, ref_link, target_link = compose_action_details
text = [user_combined_name, action, ref_type, ref_link]
text << target_link unless short
- text.join(' ')
+ text.join(" ")
end
def message
@@ -56,7 +56,7 @@ module ChatMessage
end
def commit_message_attachments
- [{ text: format(commit_messages), color: attachment_color }]
+ [{text: format(commit_messages), color: attachment_color}]
end
def compose_commit_message(commit)
@@ -98,16 +98,16 @@ module ChatMessage
def compose_action_details
if new_branch?
- ['pushed new', branch_link, "to #{project_link}"]
+ ["pushed new", branch_link, "to #{project_link}"]
elsif removed_branch?
- ['removed', ref, "from #{project_link}"]
+ ["removed", ref, "from #{project_link}"]
else
- ['pushed to', branch_link, "of #{project_link} (#{compare_link})"]
+ ["pushed to", branch_link, "of #{project_link} (#{compare_link})"]
end
end
def attachment_color
- '#345'
+ "#345"
end
end
end
diff --git a/app/models/project_services/chat_message/wiki_page_message.rb b/app/models/project_services/chat_message/wiki_page_message.rb
index b605d289278..fe60d40bc2b 100644
--- a/app/models/project_services/chat_message/wiki_page_message.rb
+++ b/app/models/project_services/chat_message/wiki_page_message.rb
@@ -36,7 +36,7 @@ module ChatMessage
title: "#{user_combined_name} #{action} #{wiki_page_link}",
subtitle: "in #{project_link}",
text: title,
- image: user_avatar
+ image: user_avatar,
}
end
@@ -47,7 +47,7 @@ module ChatMessage
end
def description_message
- [{ text: format(@description), color: attachment_color }]
+ [{text: format(@description), color: attachment_color}]
end
def project_link
diff --git a/app/models/project_services/chat_notification_service.rb b/app/models/project_services/chat_notification_service.rb
index c10ee07ccf4..b1b8fbea763 100644
--- a/app/models/project_services/chat_notification_service.rb
+++ b/app/models/project_services/chat_notification_service.rb
@@ -5,7 +5,7 @@
class ChatNotificationService < Service
include ChatMessage
- default_value_for :category, 'chat'
+ default_value_for :category, "chat"
prop_accessor :webhook, :username, :channel
boolean_accessor :notify_only_broken_pipelines, :notify_only_default_branch
@@ -14,7 +14,7 @@ class ChatNotificationService < Service
def initialize_properties
# Custom serialized properties initialization
- self.supported_events.each { |event| self.class.prop_accessor(event_channel_name(event)) }
+ supported_events.each { |event| self.class.prop_accessor(event_channel_name(event)) }
if properties.nil?
self.properties = {}
@@ -24,11 +24,11 @@ class ChatNotificationService < Service
end
def confidential_issue_channel
- properties['confidential_issue_channel'].presence || properties['issue_channel']
+ properties["confidential_issue_channel"].presence || properties["issue_channel"]
end
def confidential_note_channel
- properties['confidential_note_channel'].presence || properties['note_channel']
+ properties["confidential_note_channel"].presence || properties["note_channel"]
end
def self.supported_events
@@ -42,10 +42,10 @@ class ChatNotificationService < Service
def default_fields
[
- { type: 'text', name: 'webhook', placeholder: "e.g. #{webhook_placeholder}", required: true },
- { type: 'text', name: 'username', placeholder: 'e.g. GitLab' },
- { type: 'checkbox', name: 'notify_only_broken_pipelines' },
- { type: 'checkbox', name: 'notify_only_default_branch' }
+ {type: "text", name: "webhook", placeholder: "e.g. #{webhook_placeholder}", required: true},
+ {type: "text", name: "username", placeholder: "e.g. GitLab"},
+ {type: "checkbox", name: "notify_only_broken_pipelines"},
+ {type: "checkbox", name: "notify_only_default_branch"},
]
end
@@ -87,7 +87,7 @@ class ChatNotificationService < Service
end
def global_fields
- fields.reject { |field| field[:name].end_with?('channel') }
+ fields.reject { |field| field[:name].end_with?("channel") }
end
def default_channel_placeholder
@@ -127,12 +127,12 @@ class ChatNotificationService < Service
def get_channel_field(event)
field_name = event_channel_name(event)
- self.public_send(field_name) # rubocop:disable GitlabSecurity/PublicSend
+ public_send(field_name) # rubocop:disable GitlabSecurity/PublicSend
end
def build_event_channels
supported_events.reduce([]) do |channels, event|
- channels << { type: 'text', name: event_channel_name(event), placeholder: default_channel_placeholder }
+ channels << {type: "text", name: event_channel_name(event), placeholder: default_channel_placeholder}
end
end
@@ -141,7 +141,7 @@ class ChatNotificationService < Service
end
def project_name
- project.full_name.gsub(/\s/, '')
+ project.full_name.gsub(/\s/, "")
end
def project_url
@@ -149,7 +149,7 @@ class ChatNotificationService < Service
end
def update?(data)
- data[:object_attributes][:action] == 'update'
+ data[:object_attributes][:action] == "update"
end
def should_pipeline_be_notified?(data)
@@ -157,24 +157,24 @@ class ChatNotificationService < Service
end
def notify_for_ref?(data)
- return true if data[:object_kind] == 'tag_push'
+ return true if data[:object_kind] == "tag_push"
return true if data.dig(:object_attributes, :tag)
return true unless notify_only_default_branch?
ref = if data[:ref]
- Gitlab::Git.ref_name(data[:ref])
- else
- data.dig(:object_attributes, :ref)
- end
+ Gitlab::Git.ref_name(data[:ref])
+ else
+ data.dig(:object_attributes, :ref)
+ end
ref == project.default_branch
end
def notify_for_pipeline?(data)
case data[:object_attributes][:status]
- when 'success'
+ when "success"
!notify_only_broken_pipelines?
- when 'failed'
+ when "failed"
true
else
false
diff --git a/app/models/project_services/ci_service.rb b/app/models/project_services/ci_service.rb
index f0ef2d925ab..c59f8d46504 100644
--- a/app/models/project_services/ci_service.rb
+++ b/app/models/project_services/ci_service.rb
@@ -4,14 +4,14 @@
# List methods you need to implement to get your CI service
# working with GitLab Merge Requests
class CiService < Service
- default_value_for :category, 'ci'
+ default_value_for :category, "ci"
def valid_token?(token)
- self.respond_to?(:token) && self.token.present? && ActiveSupport::SecurityUtils.variable_size_secure_compare(token, self.token)
+ respond_to?(:token) && self.token.present? && ActiveSupport::SecurityUtils.variable_size_secure_compare(token, self.token)
end
def self.supported_events
- %w(push)
+ %w[push]
end
# Return complete url to build page
diff --git a/app/models/project_services/custom_issue_tracker_service.rb b/app/models/project_services/custom_issue_tracker_service.rb
index b8f8072869c..f09a82d25c9 100644
--- a/app/models/project_services/custom_issue_tracker_service.rb
+++ b/app/models/project_services/custom_issue_tracker_service.rb
@@ -6,36 +6,36 @@ class CustomIssueTrackerService < IssueTrackerService
prop_accessor :title, :description, :project_url, :issues_url, :new_issue_url
def title
- if self.properties && self.properties['title'].present?
- self.properties['title']
+ if properties && properties["title"].present?
+ properties["title"]
else
- 'Custom Issue Tracker'
+ "Custom Issue Tracker"
end
end
def title=(value)
- self.properties['title'] = value if self.properties
+ properties["title"] = value if properties
end
def description
- if self.properties && self.properties['description'].present?
- self.properties['description']
+ if properties && properties["description"].present?
+ properties["description"]
else
- 'Custom issue tracker'
+ "Custom issue tracker"
end
end
def self.to_param
- 'custom_issue_tracker'
+ "custom_issue_tracker"
end
def fields
[
- { type: 'text', name: 'title', placeholder: title },
- { type: 'text', name: 'description', placeholder: description },
- { type: 'text', name: 'project_url', placeholder: 'Project url', required: true },
- { type: 'text', name: 'issues_url', placeholder: 'Issue url', required: true },
- { type: 'text', name: 'new_issue_url', placeholder: 'New Issue url', required: true }
+ {type: "text", name: "title", placeholder: title},
+ {type: "text", name: "description", placeholder: description},
+ {type: "text", name: "project_url", placeholder: "Project url", required: true},
+ {type: "text", name: "issues_url", placeholder: "Issue url", required: true},
+ {type: "text", name: "new_issue_url", placeholder: "New Issue url", required: true},
]
end
end
diff --git a/app/models/project_services/deployment_service.rb b/app/models/project_services/deployment_service.rb
index 80aa2101509..f1bc78a3736 100644
--- a/app/models/project_services/deployment_service.rb
+++ b/app/models/project_services/deployment_service.rb
@@ -5,10 +5,10 @@
# These services integrate with a deployment solution like Kubernetes/OpenShift,
# Mesosphere, etc, to provide additional features to environments.
class DeploymentService < Service
- default_value_for :category, 'deployment'
+ default_value_for :category, "deployment"
def self.supported_events
- %w()
+ %w[]
end
def predefined_variables(project:)
diff --git a/app/models/project_services/discord_service.rb b/app/models/project_services/discord_service.rb
index 21afd14dbff..fcecdafe3e8 100644
--- a/app/models/project_services/discord_service.rb
+++ b/app/models/project_services/discord_service.rb
@@ -35,9 +35,9 @@ class DiscordService < ChatNotificationService
def default_fields
[
- { type: "text", name: "webhook", placeholder: "e.g. https://discordapp.com/api/webhooks/…" },
- { type: "checkbox", name: "notify_only_broken_pipelines" },
- { type: "checkbox", name: "notify_only_default_branch" }
+ {type: "text", name: "webhook", placeholder: "e.g. https://discordapp.com/api/webhooks/…"},
+ {type: "checkbox", name: "notify_only_broken_pipelines"},
+ {type: "checkbox", name: "notify_only_default_branch"},
]
end
diff --git a/app/models/project_services/drone_ci_service.rb b/app/models/project_services/drone_ci_service.rb
index 5ccc2f019cb..6fc476b34cf 100644
--- a/app/models/project_services/drone_ci_service.rb
+++ b/app/models/project_services/drone_ci_service.rb
@@ -21,11 +21,11 @@ class DroneCiService < CiService
def execute(data)
case data[:object_kind]
- when 'push'
+ when "push"
service_hook.execute(data) if push_valid?(data)
- when 'merge_request'
+ when "merge_request"
service_hook.execute(data) if merge_request_valid?(data)
- when 'tag_push'
+ when "tag_push"
service_hook.execute(data) if tag_push_valid?(data)
end
end
@@ -35,13 +35,14 @@ class DroneCiService < CiService
end
def self.supported_events
- %w(push merge_request tag_push)
+ %w[push merge_request tag_push]
end
def commit_status_path(sha, ref)
Gitlab::Utils.append_path(
drone_url,
- "gitlab/#{project.full_path}/commits/#{sha}?branch=#{URI.encode(ref.to_s)}&access_token=#{token}")
+ "gitlab/#{project.full_path}/commits/#{sha}?branch=#{URI.encode(ref.to_s)}&access_token=#{token}"
+ )
end
def commit_status(sha, ref)
@@ -52,11 +53,11 @@ class DroneCiService < CiService
response = Gitlab::HTTP.get(commit_status_path(sha, ref), verify: enable_ssl_verification)
status =
- if response.code == 200 && response['status']
- case response['status']
- when 'killed'
+ if response.code == 200 && response["status"]
+ case response["status"]
+ when "killed"
:canceled
- when 'failure', 'error'
+ when "failure", "error"
# Because drone return error if some test env failed
:failed
else
@@ -66,34 +67,35 @@ class DroneCiService < CiService
:error
end
- { commit_status: status }
+ {commit_status: status}
rescue Errno::ECONNREFUSED
- { commit_status: :error }
+ {commit_status: :error}
end
def build_page(sha, ref)
Gitlab::Utils.append_path(
drone_url,
- "gitlab/#{project.full_path}/redirect/commits/#{sha}?branch=#{URI.encode(ref.to_s)}")
+ "gitlab/#{project.full_path}/redirect/commits/#{sha}?branch=#{URI.encode(ref.to_s)}"
+ )
end
def title
- 'Drone CI'
+ "Drone CI"
end
def description
- 'Drone is a Continuous Integration platform built on Docker, written in Go'
+ "Drone is a Continuous Integration platform built on Docker, written in Go"
end
def self.to_param
- 'drone_ci'
+ "drone_ci"
end
def fields
[
- { type: 'text', name: 'token', placeholder: 'Drone CI project specific token', required: true },
- { type: 'text', name: 'drone_url', placeholder: 'http://drone.example.com', required: true },
- { type: 'checkbox', name: 'enable_ssl_verification', title: "Enable SSL verification" }
+ {type: "text", name: "token", placeholder: "Drone CI project specific token", required: true},
+ {type: "text", name: "drone_url", placeholder: "http://drone.example.com", required: true},
+ {type: "checkbox", name: "enable_ssl_verification", title: "Enable SSL verification"},
]
end
@@ -112,7 +114,7 @@ class DroneCiService < CiService
end
def merge_request_valid?(data)
- data[:object_attributes][:state] == 'opened' &&
+ data[:object_attributes][:state] == "opened" &&
MergeRequest.state_machines[:merge_status].check_state?(data[:object_attributes][:merge_status])
end
end
diff --git a/app/models/project_services/emails_on_push_service.rb b/app/models/project_services/emails_on_push_service.rb
index fb73d430fb1..cd1ff179243 100644
--- a/app/models/project_services/emails_on_push_service.rb
+++ b/app/models/project_services/emails_on_push_service.rb
@@ -7,19 +7,19 @@ class EmailsOnPushService < Service
validates :recipients, presence: true, if: :valid_recipients?
def title
- 'Emails on push'
+ "Emails on push"
end
def description
- 'Email the commits and diff of each push to a list of recipients.'
+ "Email the commits and diff of each push to a list of recipients."
end
def self.to_param
- 'emails_on_push'
+ "emails_on_push"
end
def self.supported_events
- %w(push tag_push)
+ %w[push tag_push]
end
def execute(push_data)
@@ -30,26 +30,26 @@ class EmailsOnPushService < Service
recipients,
push_data,
send_from_committer_email: send_from_committer_email?,
- disable_diffs: disable_diffs?
+ disable_diffs: disable_diffs?
)
end
def send_from_committer_email?
- Gitlab::Utils.to_boolean(self.send_from_committer_email)
+ Gitlab::Utils.to_boolean(send_from_committer_email)
end
def disable_diffs?
- Gitlab::Utils.to_boolean(self.disable_diffs)
+ Gitlab::Utils.to_boolean(disable_diffs)
end
def fields
domains = Notify.allowed_email_domains.map { |domain| "user@#{domain}" }.join(", ")
[
- { type: 'checkbox', name: 'send_from_committer_email', title: "Send from committer",
- help: "Send notifications from the committer's email address if the domain is part of the domain GitLab is running on (e.g. #{domains})." },
- { type: 'checkbox', name: 'disable_diffs', title: "Disable code diffs",
- help: "Don't include possibly sensitive code diffs in notification body." },
- { type: 'textarea', name: 'recipients', placeholder: 'Emails separated by whitespace' }
+ {type: "checkbox", name: "send_from_committer_email", title: "Send from committer",
+ help: "Send notifications from the committer's email address if the domain is part of the domain GitLab is running on (e.g. #{domains}).",},
+ {type: "checkbox", name: "disable_diffs", title: "Disable code diffs",
+ help: "Don't include possibly sensitive code diffs in notification body.",},
+ {type: "textarea", name: "recipients", placeholder: "Emails separated by whitespace"},
]
end
end
diff --git a/app/models/project_services/external_wiki_service.rb b/app/models/project_services/external_wiki_service.rb
index d2835c6ac82..b073af4a73c 100644
--- a/app/models/project_services/external_wiki_service.rb
+++ b/app/models/project_services/external_wiki_service.rb
@@ -6,31 +6,35 @@ class ExternalWikiService < Service
validates :external_wiki_url, presence: true, public_url: true, if: :activated?
def title
- 'External Wiki'
+ "External Wiki"
end
def description
- 'Replaces the link to the internal wiki with a link to an external wiki.'
+ "Replaces the link to the internal wiki with a link to an external wiki."
end
def self.to_param
- 'external_wiki'
+ "external_wiki"
end
def fields
[
- { type: 'text', name: 'external_wiki_url', placeholder: 'The URL of the external Wiki', required: true }
+ {type: "text", name: "external_wiki_url", placeholder: "The URL of the external Wiki", required: true},
]
end
def execute(_data)
- @response = Gitlab::HTTP.get(properties['external_wiki_url'], verify: true) rescue nil
+ @response = begin
+ Gitlab::HTTP.get(properties["external_wiki_url"], verify: true)
+ rescue
+ nil
+ end
if @response != 200
nil
end
end
def self.supported_events
- %w()
+ %w[]
end
end
diff --git a/app/models/project_services/flowdock_service.rb b/app/models/project_services/flowdock_service.rb
index 76624263aab..055941d1a62 100644
--- a/app/models/project_services/flowdock_service.rb
+++ b/app/models/project_services/flowdock_service.rb
@@ -5,25 +5,25 @@ class FlowdockService < Service
validates :token, presence: true, if: :activated?
def title
- 'Flowdock'
+ "Flowdock"
end
def description
- 'Flowdock is a collaboration web app for technical teams.'
+ "Flowdock is a collaboration web app for technical teams."
end
def self.to_param
- 'flowdock'
+ "flowdock"
end
def fields
[
- { type: 'text', name: 'token', placeholder: 'Flowdock Git source token', required: true }
+ {type: "text", name: "token", placeholder: "Flowdock Git source token", required: true},
]
end
def self.supported_events
- %w(push)
+ %w[push]
end
def execute(data)
diff --git a/app/models/project_services/gitlab_issue_tracker_service.rb b/app/models/project_services/gitlab_issue_tracker_service.rb
index fa9abf58e62..5af972c20b8 100644
--- a/app/models/project_services/gitlab_issue_tracker_service.rb
+++ b/app/models/project_services/gitlab_issue_tracker_service.rb
@@ -10,7 +10,7 @@ class GitlabIssueTrackerService < IssueTrackerService
default_value_for :default, true
def self.to_param
- 'gitlab'
+ "gitlab"
end
def project_url
diff --git a/app/models/project_services/hangouts_chat_service.rb b/app/models/project_services/hangouts_chat_service.rb
index 272cd0f4e47..ea42d64ede9 100644
--- a/app/models/project_services/hangouts_chat_service.rb
+++ b/app/models/project_services/hangouts_chat_service.rb
@@ -1,18 +1,18 @@
# frozen_string_literal: true
-require 'hangouts_chat'
+require "hangouts_chat"
class HangoutsChatService < ChatNotificationService
def title
- 'Hangouts Chat'
+ "Hangouts Chat"
end
def description
- 'Receive event notifications in Google Hangouts Chat'
+ "Receive event notifications in Google Hangouts Chat"
end
def self.to_param
- 'hangouts_chat'
+ "hangouts_chat"
end
def help
@@ -32,14 +32,14 @@ class HangoutsChatService < ChatNotificationService
end
def webhook_placeholder
- 'https://chat.googleapis.com/v1/spaces…'
+ "https://chat.googleapis.com/v1/spaces…"
end
def default_fields
[
- { type: 'text', name: 'webhook', placeholder: "e.g. #{webhook_placeholder}" },
- { type: 'checkbox', name: 'notify_only_broken_pipelines' },
- { type: 'checkbox', name: 'notify_only_default_branch' }
+ {type: "text", name: "webhook", placeholder: "e.g. #{webhook_placeholder}"},
+ {type: "checkbox", name: "notify_only_broken_pipelines"},
+ {type: "checkbox", name: "notify_only_default_branch"},
]
end
diff --git a/app/models/project_services/irker_service.rb b/app/models/project_services/irker_service.rb
index 83fd9a34438..47be8dbe029 100644
--- a/app/models/project_services/irker_service.rb
+++ b/app/models/project_services/irker_service.rb
@@ -1,6 +1,6 @@
# frozen_string_literal: true
-require 'uri'
+require "uri"
class IrkerService < Service
prop_accessor :server_host, :server_port, :default_irc_uri
@@ -11,64 +11,64 @@ class IrkerService < Service
before_validation :get_channels
def title
- 'Irker (IRC gateway)'
+ "Irker (IRC gateway)"
end
def description
- 'Send IRC messages, on update, to a list of recipients through an Irker '\
- 'gateway.'
+ "Send IRC messages, on update, to a list of recipients through an Irker "\
+ "gateway."
end
def self.to_param
- 'irker'
+ "irker"
end
def self.supported_events
- %w(push)
+ %w[push]
end
def execute(data)
return unless supported_events.include?(data[:object_kind])
IrkerWorker.perform_async(project_id, channels,
- colorize_messages, data, settings)
+ colorize_messages, data, settings)
end
def settings
{
- server_host: server_host.present? ? server_host : 'localhost',
- server_port: server_port.present? ? server_port : 6659
+ server_host: server_host.present? ? server_host : "localhost",
+ server_port: server_port.present? ? server_port : 6659,
}
end
def fields
[
- { type: 'text', name: 'server_host', placeholder: 'localhost',
- help: 'Irker daemon hostname (defaults to localhost)' },
- { type: 'text', name: 'server_port', placeholder: 6659,
- help: 'Irker daemon port (defaults to 6659)' },
- { type: 'text', name: 'default_irc_uri', title: 'Default IRC URI',
- help: 'A default IRC URI to prepend before each recipient (optional)',
- placeholder: 'irc://irc.network.net:6697/' },
- { type: 'textarea', name: 'recipients',
- placeholder: 'Recipients/channels separated by whitespaces', required: true,
- help: 'Recipients have to be specified with a full URI: '\
- 'irc[s]://irc.network.net[:port]/#channel. Special cases: if '\
+ {type: "text", name: "server_host", placeholder: "localhost",
+ help: "Irker daemon hostname (defaults to localhost)",},
+ {type: "text", name: "server_port", placeholder: 6659,
+ help: "Irker daemon port (defaults to 6659)",},
+ {type: "text", name: "default_irc_uri", title: "Default IRC URI",
+ help: "A default IRC URI to prepend before each recipient (optional)",
+ placeholder: "irc://irc.network.net:6697/",},
+ {type: "textarea", name: "recipients",
+ placeholder: "Recipients/channels separated by whitespaces", required: true,
+ help: "Recipients have to be specified with a full URI: "\
+ "irc[s]://irc.network.net[:port]/#channel. Special cases: if "\
'you want the channel to be a nickname instead, append ",isnick" to ' \
- 'the channel name; if the channel is protected by a secret password, ' \
+ "the channel name; if the channel is protected by a secret password, " \
' append "?key=secretpassword" to the URI (Note that due to a bug, if you ' \
' want to use a password, you have to omit the "#" on the channel). If you ' \
- ' specify a default IRC URI to prepend before each recipient, you can just ' \
- ' give a channel name.' },
- { type: 'checkbox', name: 'colorize_messages' }
+ " specify a default IRC URI to prepend before each recipient, you can just " \
+ " give a channel name.",},
+ {type: "checkbox", name: "colorize_messages"},
]
end
def help
- ' NOTE: Irker does NOT have built-in authentication, which makes it' \
- ' vulnerable to spamming IRC channels if it is hosted outside of a ' \
- ' firewall. Please make sure you run the daemon within a secured network ' \
- ' to prevent abuse. For more details, read: http://www.catb.org/~esr/irker/security.html.'
+ " NOTE: Irker does NOT have built-in authentication, which makes it" \
+ " vulnerable to spamming IRC channels if it is hosted outside of a " \
+ " firewall. Please make sure you run the daemon within a secured network " \
+ " to prevent abuse. For more details, read: http://www.catb.org/~esr/irker/security.html."
end
private
@@ -79,7 +79,7 @@ class IrkerService < Service
map_recipients
- errors.add(:recipients, 'are all invalid') if channels.empty?
+ errors.add(:recipients, "are all invalid") if channels.empty?
true
end
@@ -101,7 +101,7 @@ class IrkerService < Service
unless uri.present? && default_irc_uri.nil?
begin
- new_recipient = URI.join(default_irc_uri, '/', recipient).to_s
+ new_recipient = URI.join(default_irc_uri, "/", recipient).to_s
uri = consider_uri(URI.parse(new_recipient))
rescue
log_error("Unable to create a valid URL", default_irc_uri: default_irc_uri, recipient: recipient)
diff --git a/app/models/project_services/issue_tracker_service.rb b/app/models/project_services/issue_tracker_service.rb
index f54497fc6d8..d3d1d676d53 100644
--- a/app/models/project_services/issue_tracker_service.rb
+++ b/app/models/project_services/issue_tracker_service.rb
@@ -3,7 +3,7 @@
class IssueTrackerService < Service
validate :one_issue_tracker, if: :activated?, on: :manual_change
- default_value_for :category, 'issue_tracker'
+ default_value_for :category, "issue_tracker"
# Pattern used to extract links from comments
# Override this method on services that uses different patterns
@@ -23,7 +23,7 @@ class IssueTrackerService < Service
end
def issue_url(iid)
- self.issues_url.gsub(':id', iid.to_s)
+ issues_url.gsub(":id", iid.to_s)
end
def issue_tracker_path
@@ -40,10 +40,10 @@ class IssueTrackerService < Service
def fields
[
- { type: 'text', name: 'description', placeholder: description },
- { type: 'text', name: 'project_url', placeholder: 'Project url', required: true },
- { type: 'text', name: 'issues_url', placeholder: 'Issue url', required: true },
- { type: 'text', name: 'new_issue_url', placeholder: 'New Issue url', required: true }
+ {type: "text", name: "description", placeholder: description},
+ {type: "text", name: "project_url", placeholder: "Project url", required: true},
+ {type: "text", name: "issues_url", placeholder: "Issue url", required: true},
+ {type: "text", name: "new_issue_url", placeholder: "New Issue url", required: true},
]
end
@@ -57,10 +57,10 @@ class IssueTrackerService < Service
yield
else
self.properties = {
- title: issues_tracker['title'],
- project_url: issues_tracker['project_url'],
- issues_url: issues_tracker['issues_url'],
- new_issue_url: issues_tracker['new_issue_url']
+ title: issues_tracker["title"],
+ project_url: issues_tracker["project_url"],
+ issues_url: issues_tracker["issues_url"],
+ new_issue_url: issues_tracker["new_issue_url"],
}
end
else
@@ -69,24 +69,24 @@ class IssueTrackerService < Service
end
def self.supported_events
- %w(push)
+ %w[push]
end
def execute(data)
return unless supported_events.include?(data[:object_kind])
- message = "#{self.type} was unable to reach #{self.project_url}. Check the url and try again."
+ message = "#{type} was unable to reach #{project_url}. Check the url and try again."
result = false
begin
- response = Gitlab::HTTP.head(self.project_url, verify: true)
+ response = Gitlab::HTTP.head(project_url, verify: true)
if response
- message = "#{self.type} received response #{response.code} when attempting to connect to #{self.project_url}"
+ message = "#{type} received response #{response.code} when attempting to connect to #{project_url}"
result = true
end
rescue Gitlab::HTTP::Error, Timeout::Error, SocketError, Errno::ECONNRESET, Errno::ECONNREFUSED, OpenSSL::SSL::SSLError => error
- message = "#{self.type} had an error when trying to connect to #{self.project_url}: #{error.message}"
+ message = "#{type} had an error when trying to connect to #{project_url}: #{error.message}"
end
log_info(message)
result
@@ -95,8 +95,7 @@ class IssueTrackerService < Service
private
def enabled_in_gitlab_config
- Gitlab.config.issues_tracker &&
- Gitlab.config.issues_tracker.values.any? &&
+ Gitlab.config.issues_tracker&.values&.any? &&
issues_tracker
end
@@ -109,7 +108,7 @@ class IssueTrackerService < Service
return if project.blank?
if project.services.external_issue_trackers.where.not(id: id).any?
- errors.add(:base, 'Another issue tracker is already in use. Only one issue tracker service can be active at a time')
+ errors.add(:base, "Another issue tracker is already in use. Only one issue tracker service can be active at a time")
end
end
end
diff --git a/app/models/project_services/jira_service.rb b/app/models/project_services/jira_service.rb
index f7064d5aaea..de04d3ec2b8 100644
--- a/app/models/project_services/jira_service.rb
+++ b/app/models/project_services/jira_service.rb
@@ -11,8 +11,8 @@ class JiraService < IssueTrackerService
validates :password, presence: true, if: :activated?
validates :jira_issue_transition_id,
- format: { with: Gitlab::Regex.jira_transition_id_regex, message: "transition ids can have only numbers which can be split with , or ;" },
- allow_blank: true
+ format: {with: Gitlab::Regex.jira_transition_id_regex, message: "transition ids can have only numbers which can be split with , or ;"},
+ allow_blank: true
# JIRA cloud version is deprecating authentication via username and password.
# We should use username/password for JIRA server and email/api_token for JIRA cloud,
@@ -21,12 +21,12 @@ class JiraService < IssueTrackerService
before_update :reset_password
- alias_method :project_url, :url
+ alias project_url url
# When these are false GitLab does not create cross reference
# comments on JIRA except when an issue gets transitioned.
def self.supported_events
- %w(commit merge_request)
+ %w[commit merge_request]
end
# {PROJECT-KEY}-{NUMBER} Examples: JIRA-1, PROJECT-1
@@ -37,9 +37,9 @@ class JiraService < IssueTrackerService
def initialize_properties
super do
self.properties = {
- title: issues_tracker['title'],
- url: issues_tracker['url'],
- api_url: issues_tracker['api_url']
+ title: issues_tracker["title"],
+ url: issues_tracker["url"],
+ api_url: issues_tracker["api_url"],
}
end
end
@@ -52,15 +52,15 @@ class JiraService < IssueTrackerService
url = URI.parse(client_url)
{
- username: self.username,
- password: self.password,
- site: URI.join(url, '/').to_s, # Intended to find the root
- context_path: url.path.chomp('/'),
+ username: username,
+ password: password,
+ site: URI.join(url, "/").to_s, # Intended to find the root
+ context_path: url.path.chomp("/"),
auth_type: :basic,
read_timeout: 120,
use_cookies: true,
- additional_cookies: ['OBBasicAuth=fromDialog'],
- use_ssl: url.scheme == 'https'
+ additional_cookies: ["OBBasicAuth=fromDialog"],
+ use_ssl: url.scheme == "https",
}
end
@@ -71,36 +71,36 @@ class JiraService < IssueTrackerService
def help
"You need to configure JIRA before enabling this service. For more details
read the
- [JIRA service documentation](#{help_page_url('user/project/integrations/jira')})."
+ [JIRA service documentation](#{help_page_url("user/project/integrations/jira")})."
end
def title
- if self.properties && self.properties['title'].present?
- self.properties['title']
+ if properties && properties["title"].present?
+ properties["title"]
else
- 'JIRA'
+ "JIRA"
end
end
def description
- if self.properties && self.properties['description'].present?
- self.properties['description']
+ if properties && properties["description"].present?
+ properties["description"]
else
- 'Jira issue tracker'
+ "Jira issue tracker"
end
end
def self.to_param
- 'jira'
+ "jira"
end
def fields
[
- { type: 'text', name: 'url', title: 'Web URL', placeholder: 'https://jira.example.com', required: true },
- { type: 'text', name: 'api_url', title: 'JIRA API URL', placeholder: 'If different from Web URL' },
- { type: 'text', name: 'username', title: 'Username or Email', placeholder: 'Use a username for server version and an email for cloud version', required: true },
- { type: 'password', name: 'password', title: 'Password or API token', placeholder: 'Use a password for server version and an API token for cloud version', required: true },
- { type: 'text', name: 'jira_issue_transition_id', title: 'Transition ID(s)', placeholder: 'Use , or ; to separate multiple transition IDs' }
+ {type: "text", name: "url", title: "Web URL", placeholder: "https://jira.example.com", required: true},
+ {type: "text", name: "api_url", title: "JIRA API URL", placeholder: "If different from Web URL"},
+ {type: "text", name: "username", title: "Username or Email", placeholder: "Use a username for server version and an email for cloud version", required: true},
+ {type: "password", name: "password", title: "Password or API token", placeholder: "Use a password for server version and an API token for cloud version", required: true},
+ {type: "text", name: "jira_issue_transition_id", title: "Transition ID(s)", placeholder: "Use , or ; to separate multiple transition IDs"},
]
end
@@ -123,10 +123,10 @@ class JiraService < IssueTrackerService
return if issue.nil? || has_resolution?(issue) || !jira_issue_transition_id.present?
commit_id = if entity.is_a?(Commit)
- entity.id
- elsif entity.is_a?(MergeRequest)
- entity.diff_head_sha
- end
+ entity.id
+ elsif entity.is_a?(MergeRequest)
+ entity.diff_head_sha
+ end
commit_url = build_entity_url(:commit, commit_id)
@@ -153,17 +153,17 @@ class JiraService < IssueTrackerService
data = {
user: {
name: author.name,
- url: resource_url(user_path(author))
+ url: resource_url(user_path(author)),
},
project: {
name: project.full_path,
- url: resource_url(namespace_project_path(project.namespace, project)) # rubocop:disable Cop/ProjectPathHelper
+ url: resource_url(namespace_project_path(project.namespace, project)), # rubocop:disable Cop/ProjectPathHelper
},
entity: {
name: noteable_type.humanize.downcase,
url: entity_url,
- title: noteable.title
- }
+ title: noteable.title,
+ },
}
add_comment(data, jira_issue)
@@ -174,7 +174,7 @@ class JiraService < IssueTrackerService
success = result.present?
result = @error if @error && !success
- { success: success, result: result }
+ {success: success, result: result}
end
# JIRA does not need test data.
@@ -205,12 +205,10 @@ class JiraService < IssueTrackerService
# if any transition fails it will log the error message and stop the transition sequence
def transition_issue(issue)
jira_issue_transition_id.scan(Gitlab::Regex.jira_transition_id_regex).each do |transition_id|
- begin
- issue.transitions.build.save!(transition: { id: transition_id })
- rescue => error
- log_error("Issue transition failed", error: error.message, client_url: client_url)
- return false
- end
+ issue.transitions.build.save!(transition: {id: transition_id})
+ rescue => error
+ log_error("Issue transition failed", error: error.message, client_url: client_url)
+ return false
end
end
@@ -273,20 +271,20 @@ class JiraService < IssueTrackerService
def build_remote_link_props(url:, title:, resolved: false)
status = {
- resolved: resolved
+ resolved: resolved,
}
{
- GlobalID: 'GitLab',
- relationship: 'mentioned on',
+ GlobalID: "GitLab",
+ relationship: "mentioned on",
object: {
url: url,
title: title,
status: status,
icon: {
- title: 'GitLab', url16x16: asset_url(Gitlab::Favicon.main, host: gitlab_config.url)
- }
- }
+ title: "GitLab", url16x16: asset_url(Gitlab::Favicon.main, host: gitlab_config.url),
+ },
+ },
}
end
@@ -297,11 +295,11 @@ class JiraService < IssueTrackerService
def build_entity_url(noteable_type, entity_id)
polymorphic_url(
[
- self.project.namespace.becomes(Namespace),
- self.project,
- noteable_type.to_sym
+ project.namespace.becomes(Namespace),
+ project,
+ noteable_type.to_sym,
],
- id: entity_id,
+ id: entity_id,
host: Settings.gitlab.base_url
)
end
@@ -317,7 +315,6 @@ class JiraService < IssueTrackerService
# Handle errors when doing JIRA API calls
def jira_request
yield
-
rescue Timeout::Error, Errno::EINVAL, Errno::ECONNRESET, Errno::ECONNREFUSED, URI::InvalidURIError, JIRA::HTTPError, OpenSSL::SSL::SSLError => e
@error = e.message
log_error("Error sending message", client_url: client_url, error: @error)
diff --git a/app/models/project_services/kubernetes_service.rb b/app/models/project_services/kubernetes_service.rb
index f69edd60003..1d19880beab 100644
--- a/app/models/project_services/kubernetes_service.rb
+++ b/app/models/project_services/kubernetes_service.rb
@@ -39,7 +39,7 @@ class KubernetesService < DeploymentService
if: :activated?,
format: {
with: Gitlab::Regex.kubernetes_namespace_regex,
- message: Gitlab::Regex.kubernetes_namespace_regex_message
+ message: Gitlab::Regex.kubernetes_namespace_regex_message,
}
after_save :clear_reactive_cache!
@@ -49,40 +49,40 @@ class KubernetesService < DeploymentService
end
def title
- 'Kubernetes'
+ "Kubernetes"
end
def description
- 'Kubernetes / OpenShift integration'
+ "Kubernetes / OpenShift integration"
end
def help
- 'To enable terminal access to Kubernetes environments, label your ' \
- 'deployments with `app=$CI_ENVIRONMENT_SLUG`'
+ "To enable terminal access to Kubernetes environments, label your " \
+ "deployments with `app=$CI_ENVIRONMENT_SLUG`"
end
def self.to_param
- 'kubernetes'
+ "kubernetes"
end
def fields
[
- { type: 'text',
- name: 'api_url',
- title: 'API URL',
- placeholder: 'Kubernetes API URL, like https://kube.example.com/' },
- { type: 'textarea',
- name: 'ca_pem',
- title: 'CA Certificate',
- placeholder: 'Certificate Authority bundle (PEM format)' },
- { type: 'text',
- name: 'namespace',
- title: 'Project namespace (optional/unique)',
- placeholder: namespace_placeholder },
- { type: 'text',
- name: 'token',
- title: 'Token',
- placeholder: 'Service token' }
+ {type: "text",
+ name: "api_url",
+ title: "API URL",
+ placeholder: "Kubernetes API URL, like https://kube.example.com/",},
+ {type: "textarea",
+ name: "ca_pem",
+ title: "CA Certificate",
+ placeholder: "Certificate Authority bundle (PEM format)",},
+ {type: "text",
+ name: "namespace",
+ title: "Project namespace (optional/unique)",
+ placeholder: namespace_placeholder,},
+ {type: "text",
+ name: "token",
+ title: "Token",
+ placeholder: "Service token",},
]
end
@@ -99,9 +99,9 @@ class KubernetesService < DeploymentService
kubeclient = build_kube_client!
kubeclient.core_client.discover
- { success: kubeclient.core_client.discovered, result: "Checked API discovery endpoint" }
+ {success: kubeclient.core_client.discovered, result: "Checked API discovery endpoint"}
rescue => err
- { success: false, result: err }
+ {success: false, result: err}
end
# Project param was added on
@@ -112,15 +112,15 @@ class KubernetesService < DeploymentService
def predefined_variables(project:)
Gitlab::Ci::Variables::Collection.new.tap do |variables|
variables
- .append(key: 'KUBE_URL', value: api_url)
- .append(key: 'KUBE_TOKEN', value: token, public: false)
- .append(key: 'KUBE_NAMESPACE', value: actual_namespace)
- .append(key: 'KUBECONFIG', value: kubeconfig, public: false, file: true)
+ .append(key: "KUBE_URL", value: api_url)
+ .append(key: "KUBE_TOKEN", value: token, public: false)
+ .append(key: "KUBE_NAMESPACE", value: actual_namespace)
+ .append(key: "KUBECONFIG", value: kubeconfig, public: false, file: true)
if ca_pem.present?
variables
- .append(key: 'KUBE_CA_PEM', value: ca_pem)
- .append(key: 'KUBE_CA_PEM_FILE', value: ca_pem, file: true)
+ .append(key: "KUBE_CA_PEM", value: ca_pem)
+ .append(key: "KUBE_CA_PEM_FILE", value: ca_pem, file: true)
end
end
end
@@ -143,7 +143,7 @@ class KubernetesService < DeploymentService
return unless active? && project && !project.pending_delete?
# We may want to cache extra things in the future
- { pods: read_pods }
+ {pods: read_pods}
end
def kubeclient
@@ -157,12 +157,12 @@ class KubernetesService < DeploymentService
def deprecation_message
content = _("Kubernetes service integration has been deprecated. %{deprecated_message_content} your Kubernetes clusters using the new <a href=\"%{url}\"/>Kubernetes Clusters</a> page") % {
deprecated_message_content: deprecated_message_content,
- url: Gitlab::Routing.url_helpers.project_clusters_path(project)
+ url: Gitlab::Routing.url_helpers.project_clusters_path(project),
}
content.html_safe
end
- TEMPLATE_PLACEHOLDER = 'Kubernetes namespace'.freeze
+ TEMPLATE_PLACEHOLDER = "Kubernetes namespace"
private
@@ -171,7 +171,8 @@ class KubernetesService < DeploymentService
url: api_url,
namespace: actual_namespace,
token: token,
- ca_pem: ca_pem)
+ ca_pem: ca_pem
+ )
end
def namespace_placeholder
@@ -182,7 +183,7 @@ class KubernetesService < DeploymentService
return unless project
slug = "#{project.path}-#{project.id}".downcase
- slug.gsub(/[^-a-z0-9]/, '-').gsub(/^-+/, '')
+ slug.gsub(/[^-a-z0-9]/, "-").gsub(/^-+/, "")
end
def build_kube_client!
@@ -192,7 +193,7 @@ class KubernetesService < DeploymentService
api_url,
auth_options: kubeclient_auth_options,
ssl_options: kubeclient_ssl_options,
- http_proxy_uri: ENV['http_proxy']
+ http_proxy_uri: ENV["http_proxy"]
)
end
@@ -206,7 +207,7 @@ class KubernetesService < DeploymentService
end
def kubeclient_ssl_options
- opts = { verify_ssl: OpenSSL::SSL::VERIFY_PEER }
+ opts = {verify_ssl: OpenSSL::SSL::VERIFY_PEER}
if ca_pem.present?
opts[:cert_store] = OpenSSL::X509::Store.new
@@ -217,19 +218,19 @@ class KubernetesService < DeploymentService
end
def kubeclient_auth_options
- { bearer_token: token }
+ {bearer_token: token}
end
def terminal_auth
{
token: token,
ca_pem: ca_pem,
- max_session_time: Gitlab::CurrentSettings.terminal_max_session_time
+ max_session_time: Gitlab::CurrentSettings.terminal_max_session_time,
}
end
def enforce_namespace_to_lower_case
- self.namespace = self.namespace&.downcase
+ self.namespace = namespace&.downcase
end
def deprecation_validation
diff --git a/app/models/project_services/mattermost_service.rb b/app/models/project_services/mattermost_service.rb
index b8bc83b870e..5c245c56d5a 100644
--- a/app/models/project_services/mattermost_service.rb
+++ b/app/models/project_services/mattermost_service.rb
@@ -2,15 +2,15 @@
class MattermostService < ChatNotificationService
def title
- 'Mattermost notifications'
+ "Mattermost notifications"
end
def description
- 'Receive event notifications in Mattermost'
+ "Receive event notifications in Mattermost"
end
def self.to_param
- 'mattermost'
+ "mattermost"
end
def help
@@ -29,6 +29,6 @@ class MattermostService < ChatNotificationService
end
def webhook_placeholder
- 'http://mattermost.example.com/hooks/…'
+ "http://mattermost.example.com/hooks/…"
end
end
diff --git a/app/models/project_services/mattermost_slash_commands_service.rb b/app/models/project_services/mattermost_slash_commands_service.rb
index ca324f68d2d..14e5cc3171d 100644
--- a/app/models/project_services/mattermost_slash_commands_service.rb
+++ b/app/models/project_services/mattermost_slash_commands_service.rb
@@ -10,7 +10,7 @@ class MattermostSlashCommandsService < SlashCommandsService
end
def title
- 'Mattermost slash commands'
+ "Mattermost slash commands"
end
def description
@@ -18,7 +18,7 @@ class MattermostSlashCommandsService < SlashCommandsService
end
def self.to_param
- 'mattermost_slash_commands'
+ "mattermost_slash_commands"
end
def configure(user, params)
@@ -44,10 +44,11 @@ class MattermostSlashCommandsService < SlashCommandsService
params.merge(
auto_complete: true,
auto_complete_desc: "Perform common operations on: #{pretty_project_name}",
- auto_complete_hint: '[help]',
+ auto_complete_hint: "[help]",
description: "Perform common operations on: #{pretty_project_name}",
display_name: "GitLab / #{pretty_project_name}",
- method: 'P',
- username: 'GitLab')
+ method: "P",
+ username: "GitLab"
+ )
end
end
diff --git a/app/models/project_services/microsoft_teams_service.rb b/app/models/project_services/microsoft_teams_service.rb
index c34078f13c1..46e0bdd078e 100644
--- a/app/models/project_services/microsoft_teams_service.rb
+++ b/app/models/project_services/microsoft_teams_service.rb
@@ -2,15 +2,15 @@
class MicrosoftTeamsService < ChatNotificationService
def title
- 'Microsoft Teams Notification'
+ "Microsoft Teams Notification"
end
def description
- 'Receive event notifications in Microsoft Teams'
+ "Receive event notifications in Microsoft Teams"
end
def self.to_param
- 'microsoft_teams'
+ "microsoft_teams"
end
def help
@@ -24,7 +24,7 @@ class MicrosoftTeamsService < ChatNotificationService
end
def webhook_placeholder
- 'https://outlook.office.com/webhook/…'
+ "https://outlook.office.com/webhook/…"
end
def event_field(event)
@@ -35,9 +35,9 @@ class MicrosoftTeamsService < ChatNotificationService
def default_fields
[
- { type: 'text', name: 'webhook', placeholder: "e.g. #{webhook_placeholder}" },
- { type: 'checkbox', name: 'notify_only_broken_pipelines' },
- { type: 'checkbox', name: 'notify_only_default_branch' }
+ {type: "text", name: "webhook", placeholder: "e.g. #{webhook_placeholder}"},
+ {type: "checkbox", name: "notify_only_broken_pipelines"},
+ {type: "checkbox", name: "notify_only_default_branch"},
]
end
diff --git a/app/models/project_services/mock_ci_service.rb b/app/models/project_services/mock_ci_service.rb
index d8bba58dcbf..5d99553f2ed 100644
--- a/app/models/project_services/mock_ci_service.rb
+++ b/app/models/project_services/mock_ci_service.rb
@@ -8,23 +8,23 @@ class MockCiService < CiService
validates :mock_service_url, presence: true, public_url: true, if: :activated?
def title
- 'MockCI'
+ "MockCI"
end
def description
- 'Mock an external CI'
+ "Mock an external CI"
end
def self.to_param
- 'mock_ci'
+ "mock_ci"
end
def fields
[
- { type: 'text',
- name: 'mock_service_url',
- placeholder: 'http://localhost:4004',
- required: true }
+ {type: "text",
+ name: "mock_service_url",
+ placeholder: "http://localhost:4004",
+ required: true,},
]
end
@@ -36,7 +36,8 @@ class MockCiService < CiService
def build_page(sha, ref)
Gitlab::Utils.append_path(
mock_service_url,
- "#{project.namespace.path}/#{project.path}/status/#{sha}")
+ "#{project.namespace.path}/#{project.path}/status/#{sha}"
+ )
end
# Return string with build status or :error symbol
@@ -62,17 +63,18 @@ class MockCiService < CiService
def commit_status_path(sha)
Gitlab::Utils.append_path(
mock_service_url,
- "#{project.namespace.path}/#{project.path}/status/#{sha}.json")
+ "#{project.namespace.path}/#{project.path}/status/#{sha}.json"
+ )
end
def read_commit_status(response)
return :error unless response.code == 200 || response.code == 404
status = if response.code == 404
- 'pending'
- else
- response['status']
- end
+ "pending"
+ else
+ response["status"]
+ end
if status.present? && ALLOWED_STATES.include?(status)
status
diff --git a/app/models/project_services/mock_deployment_service.rb b/app/models/project_services/mock_deployment_service.rb
index 7ab1687f8ba..4b5736c4f96 100644
--- a/app/models/project_services/mock_deployment_service.rb
+++ b/app/models/project_services/mock_deployment_service.rb
@@ -2,15 +2,15 @@
class MockDeploymentService < DeploymentService
def title
- 'Mock deployment'
+ "Mock deployment"
end
def description
- 'Mock deployment service'
+ "Mock deployment service"
end
def self.to_param
- 'mock_deployment'
+ "mock_deployment"
end
# No terminals support
diff --git a/app/models/project_services/mock_monitoring_service.rb b/app/models/project_services/mock_monitoring_service.rb
index bcf8f1df5da..0b799627316 100644
--- a/app/models/project_services/mock_monitoring_service.rb
+++ b/app/models/project_services/mock_monitoring_service.rb
@@ -2,19 +2,19 @@
class MockMonitoringService < MonitoringService
def title
- 'Mock monitoring'
+ "Mock monitoring"
end
def description
- 'Mock monitoring service'
+ "Mock monitoring service"
end
def self.to_param
- 'mock_monitoring'
+ "mock_monitoring"
end
def metrics(environment)
- JSON.parse(File.read(Rails.root + 'spec/fixtures/metrics.json'))
+ JSON.parse(File.read(Rails.root + "spec/fixtures/metrics.json"))
end
def can_test?
diff --git a/app/models/project_services/monitoring_service.rb b/app/models/project_services/monitoring_service.rb
index 1b530a8247b..725c27c6190 100644
--- a/app/models/project_services/monitoring_service.rb
+++ b/app/models/project_services/monitoring_service.rb
@@ -5,10 +5,10 @@
# These services integrate with a deployment solution like Prometheus
# to provide additional features for environments.
class MonitoringService < Service
- default_value_for :category, 'monitoring'
+ default_value_for :category, "monitoring"
def self.supported_events
- %w()
+ %w[]
end
def can_query?
diff --git a/app/models/project_services/packagist_service.rb b/app/models/project_services/packagist_service.rb
index 003884bb7ac..4cff62d6429 100644
--- a/app/models/project_services/packagist_service.rb
+++ b/app/models/project_services/packagist_service.rb
@@ -12,27 +12,27 @@ class PackagistService < Service
after_save :compose_service_hook, if: :activated?
def title
- 'Packagist'
+ "Packagist"
end
def description
- 'Update your project on Packagist, the main Composer repository'
+ "Update your project on Packagist, the main Composer repository"
end
def self.to_param
- 'packagist'
+ "packagist"
end
def fields
[
- { type: 'text', name: 'username', placeholder: '', required: true },
- { type: 'text', name: 'token', placeholder: '', required: true },
- { type: 'text', name: 'server', placeholder: 'https://packagist.org', required: false }
+ {type: "text", name: "username", placeholder: "", required: true},
+ {type: "text", name: "token", placeholder: "", required: true},
+ {type: "text", name: "server", placeholder: "https://packagist.org", required: false},
]
end
def self.supported_events
- %w(push merge_request tag_push)
+ %w[push merge_request tag_push]
end
def execute(data)
@@ -44,12 +44,12 @@ class PackagistService < Service
def test(data)
begin
result = execute(data)
- return { success: false, result: result[:message] } if result[:http_status] != 202
- rescue StandardError => error
- return { success: false, result: error }
+ return {success: false, result: result[:message]} if result[:http_status] != 202
+ rescue => error
+ return {success: false, result: error}
end
- { success: true, result: result[:message] }
+ {success: true, result: result[:message]}
end
def compose_service_hook
@@ -59,7 +59,7 @@ class PackagistService < Service
end
def hook_url
- base_url = server.present? ? server : 'https://packagist.org'
+ base_url = server.present? ? server : "https://packagist.org"
"#{base_url}/api/update-package?username=#{username}&apiToken=#{token}"
end
end
diff --git a/app/models/project_services/pipelines_email_service.rb b/app/models/project_services/pipelines_email_service.rb
index d60a6a7efa3..e17b51c1d31 100644
--- a/app/models/project_services/pipelines_email_service.rb
+++ b/app/models/project_services/pipelines_email_service.rb
@@ -6,19 +6,19 @@ class PipelinesEmailService < Service
validates :recipients, presence: true, if: :valid_recipients?
def initialize_properties
- self.properties ||= { notify_only_broken_pipelines: true }
+ self.properties ||= {notify_only_broken_pipelines: true}
end
def title
- 'Pipelines emails'
+ "Pipelines emails"
end
def description
- 'Email the pipelines status to a list of recipients.'
+ "Email the pipelines status to a list of recipients."
end
def self.to_param
- 'pipelines_email'
+ "pipelines_email"
end
def self.supported_events
@@ -49,28 +49,28 @@ class PipelinesEmailService < Service
def fields
[
- { type: 'textarea',
- name: 'recipients',
- placeholder: 'Emails separated by comma',
- required: true },
- { type: 'checkbox',
- name: 'notify_only_broken_pipelines' }
+ {type: "textarea",
+ name: "recipients",
+ placeholder: "Emails separated by comma",
+ required: true,},
+ {type: "checkbox",
+ name: "notify_only_broken_pipelines",},
]
end
def test(data)
result = execute(data, force: true)
- { success: true, result: result }
- rescue StandardError => error
- { success: false, result: error }
+ {success: true, result: result}
+ rescue => error
+ {success: false, result: error}
end
def should_pipeline_be_notified?(data)
case data[:object_attributes][:status]
- when 'success'
+ when "success"
!notify_only_broken_pipelines?
- when 'failed'
+ when "failed"
true
else
false
diff --git a/app/models/project_services/pivotaltracker_service.rb b/app/models/project_services/pivotaltracker_service.rb
index 617e502b639..e53fe85b1e8 100644
--- a/app/models/project_services/pivotaltracker_service.rb
+++ b/app/models/project_services/pivotaltracker_service.rb
@@ -1,42 +1,42 @@
# frozen_string_literal: true
class PivotaltrackerService < Service
- API_ENDPOINT = 'https://www.pivotaltracker.com/services/v5/source_commits'.freeze
+ API_ENDPOINT = "https://www.pivotaltracker.com/services/v5/source_commits"
prop_accessor :token, :restrict_to_branch
validates :token, presence: true, if: :activated?
def title
- 'PivotalTracker'
+ "PivotalTracker"
end
def description
- 'Project Management Software (Source Commits Endpoint)'
+ "Project Management Software (Source Commits Endpoint)"
end
def self.to_param
- 'pivotaltracker'
+ "pivotaltracker"
end
def fields
[
{
- type: 'text',
- name: 'token',
- placeholder: 'Pivotal Tracker API token.',
- required: true
+ type: "text",
+ name: "token",
+ placeholder: "Pivotal Tracker API token.",
+ required: true,
},
{
- type: 'text',
- name: 'restrict_to_branch',
- placeholder: 'Comma-separated list of branches which will be ' \
- 'automatically inspected. Leave blank to include all branches.'
- }
+ type: "text",
+ name: "restrict_to_branch",
+ placeholder: "Comma-separated list of branches which will be " \
+ "automatically inspected. Leave blank to include all branches.",
+ },
]
end
def self.supported_events
- %w(push)
+ %w[push]
end
def execute(data)
@@ -45,19 +45,19 @@ class PivotaltrackerService < Service
data[:commits].each do |commit|
message = {
- 'source_commit' => {
- 'commit_id' => commit[:id],
- 'author' => commit[:author][:name],
- 'url' => commit[:url],
- 'message' => commit[:message]
- }
+ "source_commit" => {
+ "commit_id" => commit[:id],
+ "author" => commit[:author][:name],
+ "url" => commit[:url],
+ "message" => commit[:message],
+ },
}
Gitlab::HTTP.post(
API_ENDPOINT,
body: message.to_json,
headers: {
- 'Content-Type' => 'application/json',
- 'X-TrackerToken' => token
+ "Content-Type" => "application/json",
+ "X-TrackerToken" => token,
}
)
end
@@ -69,7 +69,7 @@ class PivotaltrackerService < Service
return true unless ref.present? && restrict_to_branch.present?
branch = Gitlab::Git.ref_name(ref)
- allowed_branches = restrict_to_branch.split(',').map(&:strip)
+ allowed_branches = restrict_to_branch.split(",").map(&:strip)
branch.present? && allowed_branches.include?(branch)
end
diff --git a/app/models/project_services/prometheus_service.rb b/app/models/project_services/prometheus_service.rb
index 60cb2d380d5..1cc52e26243 100644
--- a/app/models/project_services/prometheus_service.rb
+++ b/app/models/project_services/prometheus_service.rb
@@ -30,15 +30,15 @@ class PrometheusService < MonitoringService
end
def title
- 'Prometheus'
+ "Prometheus"
end
def description
- s_('PrometheusService|Time-series monitoring service')
+ s_("PrometheusService|Time-series monitoring service")
end
def self.to_param
- 'prometheus'
+ "prometheus"
end
def fields
@@ -46,18 +46,18 @@ class PrometheusService < MonitoringService
[
{
- type: 'checkbox',
- name: 'manual_configuration',
- title: s_('PrometheusService|Active'),
- required: true
+ type: "checkbox",
+ name: "manual_configuration",
+ title: s_("PrometheusService|Active"),
+ required: true,
},
{
- type: 'text',
- name: 'api_url',
- title: 'API URL',
- placeholder: s_('PrometheusService|Prometheus API Base URL, like http://prometheus.example.com/'),
- required: true
- }
+ type: "text",
+ name: "api_url",
+ title: "API URL",
+ placeholder: s_("PrometheusService|Prometheus API Base URL, like http://prometheus.example.com/"),
+ required: true,
+ },
]
end
@@ -65,9 +65,9 @@ class PrometheusService < MonitoringService
def test(*args)
Gitlab::PrometheusClient.new(prometheus_client).ping
- { success: true, result: 'Checked API endpoint' }
+ {success: true, result: "Checked API endpoint"}
rescue Gitlab::PrometheusClient::Error => err
- { success: false, result: err }
+ {success: false, result: err}
end
def prometheus_client
diff --git a/app/models/project_services/pushover_service.rb b/app/models/project_services/pushover_service.rb
index 4e48c348b45..08a6ac3e296 100644
--- a/app/models/project_services/pushover_service.rb
+++ b/app/models/project_services/pushover_service.rb
@@ -1,67 +1,67 @@
# frozen_string_literal: true
class PushoverService < Service
- BASE_URI = 'https://api.pushover.net/1'.freeze
+ BASE_URI = "https://api.pushover.net/1"
prop_accessor :api_key, :user_key, :device, :priority, :sound
validates :api_key, :user_key, :priority, presence: true, if: :activated?
def title
- 'Pushover'
+ "Pushover"
end
def description
- 'Pushover makes it easy to get real-time notifications on your Android device, iPhone, iPad, and Desktop.'
+ "Pushover makes it easy to get real-time notifications on your Android device, iPhone, iPad, and Desktop."
end
def self.to_param
- 'pushover'
+ "pushover"
end
def fields
[
- { type: 'text', name: 'api_key', placeholder: 'Your application key', required: true },
- { type: 'text', name: 'user_key', placeholder: 'Your user key', required: true },
- { type: 'text', name: 'device', placeholder: 'Leave blank for all active devices' },
- { type: 'select', name: 'priority', required: true, choices:
+ {type: "text", name: "api_key", placeholder: "Your application key", required: true},
+ {type: "text", name: "user_key", placeholder: "Your user key", required: true},
+ {type: "text", name: "device", placeholder: "Leave blank for all active devices"},
+ {type: "select", name: "priority", required: true, choices:
[
- ['Lowest Priority', -2],
- ['Low Priority', -1],
- ['Normal Priority', 0],
- ['High Priority', 1]
+ ["Lowest Priority", -2],
+ ["Low Priority", -1],
+ ["Normal Priority", 0],
+ ["High Priority", 1],
],
- default_choice: 0 },
- { type: 'select', name: 'sound', choices:
+ default_choice: 0,},
+ {type: "select", name: "sound", choices:
[
- ['Device default sound', nil],
- ['Pushover (default)', 'pushover'],
- %w(Bike bike),
- %w(Bugle bugle),
- ['Cash Register', 'cashregister'],
- %w(Classical classical),
- %w(Cosmic cosmic),
- %w(Falling falling),
- %w(Gamelan gamelan),
- %w(Incoming incoming),
- %w(Intermission intermission),
- %w(Magic magic),
- %w(Mechanical mechanical),
- ['Piano Bar', 'pianobar'],
- %w(Siren siren),
- ['Space Alarm', 'spacealarm'],
- ['Tug Boat', 'tugboat'],
- ['Alien Alarm (long)', 'alien'],
- ['Climb (long)', 'climb'],
- ['Persistent (long)', 'persistent'],
- ['Pushover Echo (long)', 'echo'],
- ['Up Down (long)', 'updown'],
- ['None (silent)', 'none']
- ] }
+ ["Device default sound", nil],
+ ["Pushover (default)", "pushover"],
+ %w[Bike bike],
+ %w[Bugle bugle],
+ ["Cash Register", "cashregister"],
+ %w[Classical classical],
+ %w[Cosmic cosmic],
+ %w[Falling falling],
+ %w[Gamelan gamelan],
+ %w[Incoming incoming],
+ %w[Intermission intermission],
+ %w[Magic magic],
+ %w[Mechanical mechanical],
+ ["Piano Bar", "pianobar"],
+ %w[Siren siren],
+ ["Space Alarm", "spacealarm"],
+ ["Tug Boat", "tugboat"],
+ ["Alien Alarm (long)", "alien"],
+ ["Climb (long)", "climb"],
+ ["Persistent (long)", "persistent"],
+ ["Pushover Echo (long)", "echo"],
+ ["Up Down (long)", "updown"],
+ ["None (silent)", "none"],
+ ],},
]
end
def self.supported_events
- %w(push)
+ %w[push]
end
def execute(data)
@@ -89,10 +89,10 @@ class PushoverService < Service
user: user_key,
device: device,
priority: priority,
- title: "#{project.full_name}",
+ title: project.full_name.to_s,
message: message,
url: data[:project][:web_url],
- url_title: "See project #{project.full_name}"
+ url_title: "See project #{project.full_name}",
}
# Sound parameter MUST NOT be sent to API if not selected
@@ -100,6 +100,6 @@ class PushoverService < Service
pushover_data[:sound] = sound
end
- Gitlab::HTTP.post('/messages.json', base_uri: BASE_URI, body: pushover_data)
+ Gitlab::HTTP.post("/messages.json", base_uri: BASE_URI, body: pushover_data)
end
end
diff --git a/app/models/project_services/redmine_service.rb b/app/models/project_services/redmine_service.rb
index a80be4b06da..96de7243701 100644
--- a/app/models/project_services/redmine_service.rb
+++ b/app/models/project_services/redmine_service.rb
@@ -6,22 +6,22 @@ class RedmineService < IssueTrackerService
prop_accessor :title, :description, :project_url, :issues_url, :new_issue_url
def title
- if self.properties && self.properties['title'].present?
- self.properties['title']
+ if properties && properties["title"].present?
+ properties["title"]
else
- 'Redmine'
+ "Redmine"
end
end
def description
- if self.properties && self.properties['description'].present?
- self.properties['description']
+ if properties && properties["description"].present?
+ properties["description"]
else
- 'Redmine issue tracker'
+ "Redmine issue tracker"
end
end
def self.to_param
- 'redmine'
+ "redmine"
end
end
diff --git a/app/models/project_services/slack_service.rb b/app/models/project_services/slack_service.rb
index 482808255f9..e2f847817db 100644
--- a/app/models/project_services/slack_service.rb
+++ b/app/models/project_services/slack_service.rb
@@ -2,15 +2,15 @@
class SlackService < ChatNotificationService
def title
- 'Slack notifications'
+ "Slack notifications"
end
def description
- 'Receive event notifications in Slack'
+ "Receive event notifications in Slack"
end
def self.to_param
- 'slack'
+ "slack"
end
def help
@@ -28,6 +28,6 @@ class SlackService < ChatNotificationService
end
def webhook_placeholder
- 'https://hooks.slack.com/services/…'
+ "https://hooks.slack.com/services/…"
end
end
diff --git a/app/models/project_services/slack_slash_commands_service.rb b/app/models/project_services/slack_slash_commands_service.rb
index 6a454070fe2..194d5d53bf1 100644
--- a/app/models/project_services/slack_slash_commands_service.rb
+++ b/app/models/project_services/slack_slash_commands_service.rb
@@ -4,7 +4,7 @@ class SlackSlashCommandsService < SlashCommandsService
include TriggersHelper
def title
- 'Slack slash commands'
+ "Slack slash commands"
end
def description
@@ -12,7 +12,7 @@ class SlackSlashCommandsService < SlashCommandsService
end
def self.to_param
- 'slack_slash_commands'
+ "slack_slash_commands"
end
def trigger(params)
diff --git a/app/models/project_services/slash_commands_service.rb b/app/models/project_services/slash_commands_service.rb
index bfabc6d262c..091e3389ac5 100644
--- a/app/models/project_services/slash_commands_service.rb
+++ b/app/models/project_services/slash_commands_service.rb
@@ -3,20 +3,20 @@
# Base class for Chat services
# This class is not meant to be used directly, but only to inherrit from.
class SlashCommandsService < Service
- default_value_for :category, 'chat'
+ default_value_for :category, "chat"
prop_accessor :token
has_many :chat_names, foreign_key: :service_id, dependent: :destroy # rubocop:disable Cop/ActiveRecordDependent
def valid_token?(token)
- self.respond_to?(:token) &&
+ respond_to?(:token) &&
self.token.present? &&
ActiveSupport::SecurityUtils.variable_size_secure_compare(token, self.token)
end
def self.supported_events
- %w()
+ %w[]
end
def can_test?
@@ -25,7 +25,7 @@ class SlashCommandsService < Service
def fields
[
- { type: 'text', name: 'token', placeholder: 'XXxxXXxxXXxxXXxxXXxxXXxx' }
+ {type: "text", name: "token", placeholder: "XXxxXXxxXXxxXXxxXXxxXXxx"},
]
end
diff --git a/app/models/project_services/teamcity_service.rb b/app/models/project_services/teamcity_service.rb
index 3245cd22e73..7f60d83de98 100644
--- a/app/models/project_services/teamcity_service.rb
+++ b/app/models/project_services/teamcity_service.rb
@@ -31,31 +31,31 @@ class TeamcityService < CiService
end
def title
- 'JetBrains TeamCity CI'
+ "JetBrains TeamCity CI"
end
def description
- 'A continuous integration and build server'
+ "A continuous integration and build server"
end
def help
- 'You will want to configure monitoring of all branches so merge '\
- 'requests build, that setting is in the vsc root advanced settings.'
+ "You will want to configure monitoring of all branches so merge "\
+ "requests build, that setting is in the vsc root advanced settings."
end
def self.to_param
- 'teamcity'
+ "teamcity"
end
def fields
[
- { type: 'text', name: 'teamcity_url',
- placeholder: 'TeamCity root URL like https://teamcity.example.com', required: true },
- { type: 'text', name: 'build_type',
- placeholder: 'Build configuration ID', required: true },
- { type: 'text', name: 'username',
- placeholder: 'A user with permissions to trigger a manual build' },
- { type: 'password', name: 'password' }
+ {type: "text", name: "teamcity_url",
+ placeholder: "TeamCity root URL like https://teamcity.example.com", required: true,},
+ {type: "text", name: "build_type",
+ placeholder: "Build configuration ID", required: true,},
+ {type: "text", name: "username",
+ placeholder: "A user with permissions to trigger a manual build",},
+ {type: "password", name: "password"},
]
end
@@ -70,7 +70,7 @@ class TeamcityService < CiService
def calculate_reactive_cache(sha, ref)
response = get_path("httpAuth/app/rest/builds/branch:unspecified:any,revision:#{sha}")
- { build_page: read_build_page(response), commit_status: read_commit_status(response) }
+ {build_page: read_build_page(response), commit_status: read_commit_status(response)}
end
def execute(data)
@@ -78,17 +78,17 @@ class TeamcityService < CiService
auth = {
username: username,
- password: password
+ password: password,
}
branch = Gitlab::Git.ref_name(data[:ref])
Gitlab::HTTP.post(
- build_url('httpAuth/app/rest/buildQueue'),
+ build_url("httpAuth/app/rest/buildQueue"),
body: "<build branchName=\"#{branch}\">"\
"<buildType id=\"#{build_type}\"/>"\
- '</build>',
- headers: { 'Content-type' => 'application/xml' },
+ "</build>",
+ headers: {"Content-type" => "application/xml"},
basic_auth: auth
)
end
@@ -102,7 +102,7 @@ class TeamcityService < CiService
build_url("viewLog.html?buildTypeId=#{build_type}")
else
# If actual build link is available, go to build result page.
- built_id = response['build']['id']
+ built_id = response["build"]["id"]
build_url("viewLog.html?buildId=#{built_id}&buildTypeId=#{build_type}")
end
end
@@ -111,19 +111,19 @@ class TeamcityService < CiService
return :error unless response.code == 200 || response.code == 404
status = if response.code == 404
- 'Pending'
- else
- response['build']['status']
- end
+ "Pending"
+ else
+ response["build"]["status"]
+ end
return :error unless status.present?
- if status.include?('SUCCESS')
- 'success'
- elsif status.include?('FAILURE')
- 'failed'
- elsif status.include?('Pending')
- 'pending'
+ if status.include?("SUCCESS")
+ "success"
+ elsif status.include?("FAILURE")
+ "failed"
+ elsif status.include?("Pending")
+ "pending"
else
:error
end
@@ -137,7 +137,7 @@ class TeamcityService < CiService
Gitlab::HTTP.get(build_url(path), verify: false,
basic_auth: {
username: username,
- password: password
+ password: password,
})
end
end
diff --git a/app/models/project_services/youtrack_service.rb b/app/models/project_services/youtrack_service.rb
index 957be685aea..56f21a4e40e 100644
--- a/app/models/project_services/youtrack_service.rb
+++ b/app/models/project_services/youtrack_service.rb
@@ -15,26 +15,26 @@ class YoutrackService < IssueTrackerService
end
def title
- 'YouTrack'
+ "YouTrack"
end
def description
- if self.properties && self.properties['description'].present?
- self.properties['description']
+ if properties && properties["description"].present?
+ properties["description"]
else
- 'YouTrack issue tracker'
+ "YouTrack issue tracker"
end
end
def self.to_param
- 'youtrack'
+ "youtrack"
end
def fields
[
- { type: 'text', name: 'description', placeholder: description },
- { type: 'text', name: 'project_url', placeholder: 'Project url', required: true },
- { type: 'text', name: 'issues_url', placeholder: 'Issue url', required: true }
+ {type: "text", name: "description", placeholder: description},
+ {type: "text", name: "project_url", placeholder: "Project url", required: true},
+ {type: "text", name: "issues_url", placeholder: "Issue url", required: true},
]
end
end
diff --git a/app/models/project_statistics.rb b/app/models/project_statistics.rb
index 781a197d56f..026ed278ec9 100644
--- a/app/models/project_statistics.rb
+++ b/app/models/project_statistics.rb
@@ -7,7 +7,7 @@ class ProjectStatistics < ActiveRecord::Base
before_save :update_storage_size
COLUMNS_TO_REFRESH = [:repository_size, :lfs_objects_size, :commit_count].freeze
- INCREMENTABLE_COLUMNS = { build_artifacts_size: %i[storage_size] }.freeze
+ INCREMENTABLE_COLUMNS = {build_artifacts_size: %i[storage_size]}.freeze
def total_repository_size
repository_size + lfs_objects_size
@@ -62,6 +62,6 @@ class ProjectStatistics < ActiveRecord::Base
end
end
- update_all(updates.join(', '))
+ update_all(updates.join(", "))
end
end
diff --git a/app/models/project_team.rb b/app/models/project_team.rb
index aeba2843e5d..f09bcbe9062 100644
--- a/app/models/project_team.rb
+++ b/app/models/project_team.rb
@@ -26,7 +26,7 @@ class ProjectTeam
end
# @deprecated
- alias_method :add_master, :add_maintainer
+ alias add_master add_maintainer
def add_role(user, role, current_user: nil)
public_send(:"add_#{role}", user, current_user: current_user) # rubocop:disable GitlabSecurity/PublicSend
@@ -72,7 +72,7 @@ class ProjectTeam
def members
@members ||= fetch_members
end
- alias_method :users, :members
+ alias users members
# `members` method uses project_authorizations table which
# is updated asynchronously, on project move it still contains
@@ -99,7 +99,7 @@ class ProjectTeam
end
# @deprecated
- alias_method :masters, :maintainers
+ alias masters maintainers
def owners
@owners ||=
@@ -157,7 +157,7 @@ class ProjectTeam
end
# @deprecated
- alias_method :master?, :maintainer?
+ alias master? maintainer?
# Checks if `user` is authorized for this project, with at least the
# `min_access_level` (if given).
@@ -177,9 +177,9 @@ class ProjectTeam
def max_member_access_for_user_ids(user_ids)
max_member_access_for_resource_ids(User, user_ids, project.id) do |user_ids|
project.project_authorizations
- .where(user: user_ids)
- .group(:user_id)
- .maximum(:access_level)
+ .where(user: user_ids)
+ .group(:user_id)
+ .maximum(:access_level)
end
end
@@ -191,7 +191,7 @@ class ProjectTeam
def fetch_members(level = nil)
members = project.authorized_users
- members = members.where(project_authorizations: { access_level: level }) if level
+ members = members.where(project_authorizations: {access_level: level}) if level
members
end
diff --git a/app/models/project_wiki.rb b/app/models/project_wiki.rb
index c43bd45a62f..dcecb14f707 100644
--- a/app/models/project_wiki.rb
+++ b/app/models/project_wiki.rb
@@ -4,14 +4,16 @@ class ProjectWiki
include Gitlab::ShellAdapter
include Storage::LegacyProjectWiki
- MARKUPS = {
- 'Markdown' => :markdown,
- 'RDoc' => :rdoc,
- 'AsciiDoc' => :asciidoc
- }.freeze unless defined?(MARKUPS)
+ unless defined?(MARKUPS)
+ MARKUPS = {
+ "Markdown" => :markdown,
+ "RDoc" => :rdoc,
+ "AsciiDoc" => :asciidoc,
+ }.freeze
+ end
CouldNotCreateWikiError = Class.new(StandardError)
- SIDEBAR = '_sidebar'
+ SIDEBAR = "_sidebar"
# Returns a string describing what went wrong after
# an operation fails.
@@ -26,15 +28,15 @@ class ProjectWiki
delegate :repository_storage, :hashed_storage?, to: :project
def path
- @project.path + '.wiki'
+ @project.path + ".wiki"
end
def full_path
- @project.full_path + '.wiki'
+ @project.full_path + ".wiki"
end
# @deprecated use full_path when you need it for an URL route or disk_path when you want to point to the filesystem
- alias_method :path_with_namespace, :full_path
+ alias path_with_namespace full_path
def web_url
Gitlab::Routing.url_helpers.project_wiki_url(@project, :home)
@@ -53,14 +55,14 @@ class ProjectWiki
end
def wiki_base_path
- [Gitlab.config.gitlab.relative_url_root, '/', @project.full_path, '/wikis'].join('')
+ [Gitlab.config.gitlab.relative_url_root, "/", @project.full_path, "/wikis"].join("")
end
# Returns the Gitlab::Git::Wiki object.
def wiki
@wiki ||= begin
gl_repository = Gitlab::GlRepository.gl_repository(project, true)
- raw_repository = Gitlab::Git::Repository.new(project.repository_storage, disk_path + '.git', gl_repository, full_path)
+ raw_repository = Gitlab::Git::Repository.new(project.repository_storage, disk_path + ".git", gl_repository, full_path)
create_repo!(raw_repository) unless raw_repository.exists?
@@ -73,7 +75,7 @@ class ProjectWiki
end
def has_home_page?
- !!find_page('home')
+ !!find_page("home")
end
def empty?
@@ -168,7 +170,7 @@ class ProjectWiki
git_ssh_url: ssh_url_to_repo,
git_http_url: http_url_to_repo,
path_with_namespace: full_path,
- default_branch: default_branch
+ default_branch: default_branch,
}
end
@@ -187,10 +189,10 @@ class ProjectWiki
git_user = Gitlab::Git::User.from_gitlab(@user)
Gitlab::Git::Wiki::CommitDetails.new(@user.id,
- git_user.username,
- git_user.name,
- git_user.email,
- commit_message)
+ git_user.username,
+ git_user.name,
+ git_user.email,
+ commit_message)
end
def default_message(action, title)
diff --git a/app/models/prometheus_metric.rb b/app/models/prometheus_metric.rb
index 5594594a48d..e49b28c61eb 100644
--- a/app/models/prometheus_metric.rb
+++ b/app/models/prometheus_metric.rb
@@ -15,55 +15,55 @@ class PrometheusMetric < ActiveRecord::Base
# custom/user groups
business: 0,
response: 1,
- system: 2
+ system: 2,
}
GROUP_DETAILS = {
# built-in groups
nginx_ingress_vts: {
- group_title: _('Response metrics (NGINX Ingress VTS)'),
- required_metrics: %w(nginx_upstream_responses_total nginx_upstream_response_msecs_avg),
- priority: 10
+ group_title: _("Response metrics (NGINX Ingress VTS)"),
+ required_metrics: %w[nginx_upstream_responses_total nginx_upstream_response_msecs_avg],
+ priority: 10,
}.freeze,
nginx_ingress: {
- group_title: _('Response metrics (NGINX Ingress)'),
- required_metrics: %w(nginx_ingress_controller_requests nginx_ingress_controller_ingress_upstream_latency_seconds_sum),
- priority: 10
+ group_title: _("Response metrics (NGINX Ingress)"),
+ required_metrics: %w[nginx_ingress_controller_requests nginx_ingress_controller_ingress_upstream_latency_seconds_sum],
+ priority: 10,
}.freeze,
ha_proxy: {
- group_title: _('Response metrics (HA Proxy)'),
- required_metrics: %w(haproxy_frontend_http_requests_total haproxy_frontend_http_responses_total),
- priority: 10
+ group_title: _("Response metrics (HA Proxy)"),
+ required_metrics: %w[haproxy_frontend_http_requests_total haproxy_frontend_http_responses_total],
+ priority: 10,
}.freeze,
aws_elb: {
- group_title: _('Response metrics (AWS ELB)'),
- required_metrics: %w(aws_elb_request_count_sum aws_elb_latency_average aws_elb_httpcode_backend_5_xx_sum),
- priority: 10
+ group_title: _("Response metrics (AWS ELB)"),
+ required_metrics: %w[aws_elb_request_count_sum aws_elb_latency_average aws_elb_httpcode_backend_5_xx_sum],
+ priority: 10,
}.freeze,
nginx: {
- group_title: _('Response metrics (NGINX)'),
- required_metrics: %w(nginx_server_requests nginx_server_requestMsec),
- priority: 10
+ group_title: _("Response metrics (NGINX)"),
+ required_metrics: %w[nginx_server_requests nginx_server_requestMsec],
+ priority: 10,
}.freeze,
kubernetes: {
- group_title: _('System metrics (Kubernetes)'),
- required_metrics: %w(container_memory_usage_bytes container_cpu_usage_seconds_total),
- priority: 5
+ group_title: _("System metrics (Kubernetes)"),
+ required_metrics: %w[container_memory_usage_bytes container_cpu_usage_seconds_total],
+ priority: 5,
}.freeze,
# custom/user groups
business: {
- group_title: _('Business metrics (Custom)'),
- priority: 0
+ group_title: _("Business metrics (Custom)"),
+ priority: 0,
}.freeze,
response: {
- group_title: _('Response metrics (Custom)'),
- priority: -5
+ group_title: _("Response metrics (Custom)"),
+ priority: -5,
}.freeze,
system: {
- group_title: _('System metrics (Custom)'),
- priority: -10
- }.freeze
+ group_title: _("System metrics (Custom)"),
+ priority: -10,
+ }.freeze,
}.freeze
validates :title, presence: true
@@ -99,21 +99,21 @@ class PrometheusMetric < ActiveRecord::Base
query_range: query,
unit: unit,
label: legend,
- series: query_series
- }.compact
+ series: query_series,
+ }.compact,
]
end
def query_series
case legend
- when 'Status Code'
+ when "Status Code"
[{
- label: 'status_code',
+ label: "status_code",
when: [
- { value: '2xx', color: 'green' },
- { value: '4xx', color: 'orange' },
- { value: '5xx', color: 'red' }
- ]
+ {value: "2xx", color: "green"},
+ {value: "4xx", color: "orange"},
+ {value: "5xx", color: "red"},
+ ],
}]
end
end
diff --git a/app/models/protectable_dropdown.rb b/app/models/protectable_dropdown.rb
index 25e70ab406c..78348dccb30 100644
--- a/app/models/protectable_dropdown.rb
+++ b/app/models/protectable_dropdown.rb
@@ -16,7 +16,7 @@ class ProtectableDropdown
end
def hash
- protectable_ref_names.map { |ref_name| { text: ref_name, id: ref_name, title: ref_name } }
+ protectable_ref_names.map { |ref_name| {text: ref_name, id: ref_name, title: ref_name} }
end
private
diff --git a/app/models/protected_branch.rb b/app/models/protected_branch.rb
index d075440b147..559c90eba86 100644
--- a/app/models/protected_branch.rb
+++ b/app/models/protected_branch.rb
@@ -20,7 +20,7 @@ class ProtectedBranch < ActiveRecord::Base
refs = project.protected_branches.select(:name)
- self.matching(ref_name, protected_refs: refs).present?
+ matching(ref_name, protected_refs: refs).present?
end
def self.default_branch_protected?
diff --git a/app/models/protected_tag.rb b/app/models/protected_tag.rb
index d28ebabfe49..901dacee18c 100644
--- a/app/models/protected_tag.rb
+++ b/app/models/protected_tag.rb
@@ -3,13 +3,13 @@
class ProtectedTag < ActiveRecord::Base
include ProtectedRef
- validates :name, uniqueness: { scope: :project_id }
+ validates :name, uniqueness: {scope: :project_id}
protected_ref_access_levels :create
def self.protected?(project, ref_name)
refs = project.protected_tags.select(:name)
- self.matching(ref_name, protected_refs: refs).present?
+ matching(ref_name, protected_refs: refs).present?
end
end
diff --git a/app/models/push_event.rb b/app/models/push_event.rb
index 9c0267c3140..dc9410930f8 100644
--- a/app/models/push_event.rb
+++ b/app/models/push_event.rb
@@ -24,18 +24,18 @@ class PushEvent < Event
delegate :commit_title, to: :push_event_payload
delegate :commit_count, to: :push_event_payload
- alias_method :commits_count, :commit_count
+ alias commits_count commit_count
# Returns events of pushes that either pushed to an existing ref or created a
# new one.
def self.created_or_pushed
actions = [
PushEventPayload.actions[:pushed],
- PushEventPayload.actions[:created]
+ PushEventPayload.actions[:created],
]
joins(:push_event_payload)
- .where(push_event_payloads: { action: actions })
+ .where(push_event_payloads: {action: actions})
end
# Returns events of pushes to a branch.
@@ -43,15 +43,15 @@ class PushEvent < Event
ref_type = PushEventPayload.ref_types[:branch]
joins(:push_event_payload)
- .where(push_event_payloads: { ref_type: ref_type })
+ .where(push_event_payloads: {ref_type: ref_type})
end
# Returns PushEvent instances for which no merge requests have been created.
def self.without_existing_merge_requests
existing_mrs = MergeRequest.except(:order, :where)
.select(1)
- .where('merge_requests.source_project_id = events.project_id')
- .where('merge_requests.source_branch = push_event_payloads.ref')
+ .where("merge_requests.source_project_id = events.project_id")
+ .where("merge_requests.source_branch = push_event_payloads.ref")
.where(state: :opened)
# For reasons unknown the use of #eager_load will result in the
@@ -60,7 +60,7 @@ class PushEvent < Event
# executed in order to retrieve the "push_event_association" when the
# returned PushEvent is used.
joins(:push_event_payload)
- .where('NOT EXISTS (?)', existing_mrs)
+ .where("NOT EXISTS (?)", existing_mrs)
.created_or_pushed
.branch_events
end
@@ -97,8 +97,8 @@ class PushEvent < Event
push_event_payload.ref
end
- alias_method :branch_name, :ref_name
- alias_method :tag_name, :ref_name
+ alias branch_name ref_name
+ alias tag_name ref_name
def commit_id
commit_to || commit_from
diff --git a/app/models/push_event_payload.rb b/app/models/push_event_payload.rb
index c7769edf055..449a7fef123 100644
--- a/app/models/push_event_payload.rb
+++ b/app/models/push_event_payload.rb
@@ -6,7 +6,7 @@ class PushEventPayload < ActiveRecord::Base
belongs_to :event, inverse_of: :push_event_payload
validates :event_id, :commit_count, :action, :ref_type, presence: true
- validates :commit_title, length: { maximum: 70 }
+ validates :commit_title, length: {maximum: 70}
sha_attribute :commit_from
sha_attribute :commit_to
@@ -14,11 +14,11 @@ class PushEventPayload < ActiveRecord::Base
enum action: {
created: 0,
removed: 1,
- pushed: 2
+ pushed: 2,
}
enum ref_type: {
branch: 0,
- tag: 1
+ tag: 1,
}
end
diff --git a/app/models/redirect_route.rb b/app/models/redirect_route.rb
index c6bd4bb6dfa..055ba2f4dc3 100644
--- a/app/models/redirect_route.rb
+++ b/app/models/redirect_route.rb
@@ -6,16 +6,16 @@ class RedirectRoute < ActiveRecord::Base
validates :source, presence: true
validates :path,
- length: { within: 1..255 },
+ length: {within: 1..255},
presence: true,
- uniqueness: { case_sensitive: false }
+ uniqueness: {case_sensitive: false}
- scope :matching_path_and_descendants, -> (path) do
+ scope :matching_path_and_descendants, ->(path) do
wheres = if Gitlab::Database.postgresql?
- 'LOWER(redirect_routes.path) = LOWER(?) OR LOWER(redirect_routes.path) LIKE LOWER(?)'
- else
- 'redirect_routes.path = ? OR redirect_routes.path LIKE ?'
- end
+ "LOWER(redirect_routes.path) = LOWER(?) OR LOWER(redirect_routes.path) LIKE LOWER(?)"
+ else
+ "redirect_routes.path = ? OR redirect_routes.path LIKE ?"
+ end
where(wheres, path, "#{sanitize_sql_like(path)}/%")
end
diff --git a/app/models/ref_matcher.rb b/app/models/ref_matcher.rb
index fa7d2c0f06c..fdd33ca3567 100644
--- a/app/models/ref_matcher.rb
+++ b/app/models/ref_matcher.rb
@@ -20,7 +20,7 @@ class RefMatcher
# Checks if this protected ref contains a wildcard
def wildcard?
- @ref_name_or_pattern && @ref_name_or_pattern.include?('*')
+ @ref_name_or_pattern&.include?("*")
end
protected
@@ -37,9 +37,9 @@ class RefMatcher
def wildcard_regex
@wildcard_regex ||= begin
- name = @ref_name_or_pattern.gsub('*', 'STAR_DONT_ESCAPE')
+ name = @ref_name_or_pattern.gsub("*", "STAR_DONT_ESCAPE")
quoted_name = Regexp.quote(name)
- regex_string = quoted_name.gsub('STAR_DONT_ESCAPE', '.*?')
+ regex_string = quoted_name.gsub("STAR_DONT_ESCAPE", ".*?")
/\A#{regex_string}\z/
end
end
diff --git a/app/models/release.rb b/app/models/release.rb
index 0dae5c90394..cc53f13a780 100644
--- a/app/models/release.rb
+++ b/app/models/release.rb
@@ -8,9 +8,9 @@ class Release < ActiveRecord::Base
belongs_to :project
# releases prior to 11.7 have no author
- belongs_to :author, class_name: 'User'
+ belongs_to :author, class_name: "User"
- has_many :links, class_name: 'Releases::Link'
+ has_many :links, class_name: "Releases::Link"
accepts_nested_attributes_for :links, allow_destroy: true
diff --git a/app/models/releases/link.rb b/app/models/releases/link.rb
index 6c507c47752..38ba8a2c90d 100644
--- a/app/models/releases/link.rb
+++ b/app/models/releases/link.rb
@@ -2,12 +2,12 @@
module Releases
class Link < ActiveRecord::Base
- self.table_name = 'release_links'
+ self.table_name = "release_links"
belongs_to :release
- validates :url, presence: true, url: { protocols: %w(http https ftp) }, uniqueness: { scope: :release }
- validates :name, presence: true, uniqueness: { scope: :release }
+ validates :url, presence: true, url: {protocols: %w[http https ftp]}, uniqueness: {scope: :release}
+ validates :name, presence: true, uniqueness: {scope: :release}
scope :sorted, -> { order(created_at: :desc) }
diff --git a/app/models/releases/source.rb b/app/models/releases/source.rb
index 4d3d54457af..4ed08315b54 100644
--- a/app/models/releases/source.rb
+++ b/app/models/releases/source.rb
@@ -6,7 +6,7 @@ module Releases
attr_accessor :project, :tag_name, :format
- FORMATS = %w(zip tar.gz tar.bz2 tar).freeze
+ FORMATS = %w[zip tar.gz tar.bz2 tar].freeze
class << self
def all(project, tag_name)
@@ -22,14 +22,14 @@ module Releases
Gitlab::Routing
.url_helpers
.project_archive_url(project,
- id: File.join(tag_name, archive_prefix),
- format: format)
+ id: File.join(tag_name, archive_prefix),
+ format: format)
end
private
def archive_prefix
- "#{project.path}-#{tag_name.tr('/', '-')}"
+ "#{project.path}-#{tag_name.tr("/", "-")}"
end
end
end
diff --git a/app/models/remote_mirror.rb b/app/models/remote_mirror.rb
index 5eba7ddd75c..78b4689338a 100644
--- a/app/models/remote_mirror.rb
+++ b/app/models/remote_mirror.rb
@@ -8,16 +8,16 @@ class RemoteMirror < ActiveRecord::Base
UNPROTECTED_BACKOFF_DELAY = 5.minutes
attr_encrypted :credentials,
- key: Settings.attr_encrypted_db_key_base,
- marshal: true,
- encode: true,
- mode: :per_attribute_iv_and_salt,
- insecure_mode: true,
- algorithm: 'aes-256-cbc'
+ key: Settings.attr_encrypted_db_key_base,
+ marshal: true,
+ encode: true,
+ mode: :per_attribute_iv_and_salt,
+ insecure_mode: true,
+ algorithm: "aes-256-cbc"
belongs_to :project, inverse_of: :remote_mirrors
- validates :url, presence: true, public_url: { protocols: %w(ssh git http https), allow_blank: true, enforce_user: true }
+ validates :url, presence: true, public_url: {protocols: %w[ssh git http https], allow_blank: true, enforce_user: true}
before_save :set_new_remote_name, if: :mirror_url_changed?
@@ -31,7 +31,7 @@ class RemoteMirror < ActiveRecord::Base
scope :enabled, -> { where(enabled: true) }
scope :started, -> { with_update_status(:started) }
- scope :stuck, -> { started.where('last_update_at < ? OR (last_update_at IS NULL AND updated_at < ?)', 1.day.ago, 1.day.ago) }
+ scope :stuck, -> { started.where("last_update_at < ? OR (last_update_at IS NULL AND updated_at < ?)", 1.day.ago, 1.day.ago) }
state_machine :update_status, initial: :none do
event :update_start do
@@ -84,11 +84,11 @@ class RemoteMirror < ActiveRecord::Base
end
def update_failed?
- update_status == 'failed'
+ update_status == "failed"
end
def update_in_progress?
- update_status == 'started'
+ update_status == "started"
end
def update_repository(options)
@@ -117,9 +117,9 @@ class RemoteMirror < ActiveRecord::Base
return unless sync?
if recently_scheduled?
- RepositoryUpdateRemoteMirrorWorker.perform_in(backoff_delay, self.id, Time.now)
+ RepositoryUpdateRemoteMirrorWorker.perform_in(backoff_delay, id, Time.now)
else
- RepositoryUpdateRemoteMirrorWorker.perform_async(self.id, Time.now)
+ RepositoryUpdateRemoteMirrorWorker.perform_async(id, Time.now)
end
end
@@ -131,7 +131,7 @@ class RemoteMirror < ActiveRecord::Base
true
end
- alias_method :enabled?, :enabled
+ alias enabled? enabled
def updated_since?(timestamp)
last_update_started_at && last_update_started_at > timestamp && !update_failed?
@@ -168,8 +168,8 @@ class RemoteMirror < ActiveRecord::Base
return if url.nil?
result = URI.parse(url)
- result.password = '*****' if result.password
- result.user = '*****' if result.user && result.user != "git" # tokens or other data may be saved as user
+ result.password = "*****" if result.password
+ result.user = "*****" if result.user && result.user != "git" # tokens or other data may be saved as user
result.to_s
end
@@ -198,7 +198,7 @@ class RemoteMirror < ActiveRecord::Base
def remote_url
return url unless ssh_key_auth? && password.present?
- Gitlab::UrlSanitizer.new(read_attribute(:url), credentials: { user: user }).full_url
+ Gitlab::UrlSanitizer.new(read_attribute(:url), credentials: {user: user}).full_url
rescue
super
end
@@ -210,13 +210,13 @@ class RemoteMirror < ActiveRecord::Base
end
def recently_scheduled?
- return false unless self.last_update_started_at
+ return false unless last_update_started_at
- self.last_update_started_at >= Time.now - backoff_delay
+ last_update_started_at >= Time.now - backoff_delay
end
def backoff_delay
- if self.only_protected_branches
+ if only_protected_branches
PROTECTED_BACKOFF_DELAY
else
UNPROTECTED_BACKOFF_DELAY
@@ -228,7 +228,7 @@ class RemoteMirror < ActiveRecord::Base
last_error: nil,
last_update_at: nil,
last_successful_update_at: nil,
- update_status: 'finished',
+ update_status: "finished",
error_notification_sent: false
)
end
diff --git a/app/models/repository.rb b/app/models/repository.rb
index cd761a29618..2e42709452b 100644
--- a/app/models/repository.rb
+++ b/app/models/repository.rb
@@ -1,11 +1,11 @@
# frozen_string_literal: true
-require 'securerandom'
+require "securerandom"
class Repository
- REF_MERGE_REQUEST = 'merge-requests'.freeze
- REF_KEEP_AROUND = 'keep-around'.freeze
- REF_ENVIRONMENTS = 'environments'.freeze
+ REF_MERGE_REQUEST = "merge-requests"
+ REF_KEEP_AROUND = "keep-around"
+ REF_ENVIRONMENTS = "environments"
MAX_DIVERGING_COUNT = 1000
RESERVED_REFS_NAMES = %W[
@@ -35,29 +35,29 @@ class Repository
#
# For example, for entry `:commit_count` there's a method called `commit_count` which
# stores its data in the `commit_count` cache key.
- CACHED_METHODS = %i(size commit_count rendered_readme readme_path contribution_guide
+ CACHED_METHODS = %i[size commit_count rendered_readme readme_path contribution_guide
changelog license_blob license_key gitignore
gitlab_ci_yml branch_names tag_names branch_count
tag_count avatar exists? root_ref has_visible_content?
- issue_template_names merge_request_template_names xcode_project?).freeze
+ issue_template_names merge_request_template_names xcode_project?].freeze
# Methods that use cache_method but only memoize the value
- MEMOIZED_CACHED_METHODS = %i(license).freeze
+ MEMOIZED_CACHED_METHODS = %i[license].freeze
# Certain method caches should be refreshed when certain types of files are
# changed. This Hash maps file types (as returned by Gitlab::FileDetector) to
# the corresponding methods to call for refreshing caches.
METHOD_CACHES_FOR_FILE_TYPES = {
- readme: %i(rendered_readme readme_path),
+ readme: %i[rendered_readme readme_path],
changelog: :changelog,
- license: %i(license_blob license_key license),
+ license: %i[license_blob license_key license],
contributing: :contribution_guide,
gitignore: :gitignore,
gitlab_ci: :gitlab_ci_yml,
avatar: :avatar,
issue_template: :issue_template_names,
merge_request_template: :merge_request_template_names,
- xcode_config: :xcode_project?
+ xcode_config: :xcode_project?,
}.freeze
def initialize(full_path, project, disk_path: nil, is_wiki: false)
@@ -72,7 +72,7 @@ class Repository
other.is_a?(self.class) && @disk_path == other.disk_path
end
- alias_method :eql?, :==
+ alias eql? ==
def hash
[self.class, @disk_path].hash
@@ -84,7 +84,7 @@ class Repository
@raw_repository ||= initialize_raw_repository
end
- alias_method :raw, :raw_repository
+ alias raw raw_repository
# Don't use this! It's going away. Use Gitaly to read or write from repos.
def path_to_repo
@@ -93,7 +93,7 @@ class Repository
storage = Gitlab.config.repositories.storages[@project.repository_storage]
File.expand_path(
- File.join(storage.legacy_disk_path, disk_path + '.git')
+ File.join(storage.legacy_disk_path, disk_path + ".git")
)
end
end
@@ -140,7 +140,7 @@ class Repository
before: before,
follow: Array(path).length == 1,
skip_merges: skip_merges,
- all: all
+ all: all,
}
commits = Gitlab::Git::Commit.where(options)
@@ -168,9 +168,9 @@ class Repository
return []
end
- commits = raw_repository.find_commits_by_message(query, ref, path, limit, offset).map do |c|
+ commits = raw_repository.find_commits_by_message(query, ref, path, limit, offset).map { |c|
commit(c)
- end
+ }
CommitCollection.new(project, commits, ref)
end
@@ -265,16 +265,14 @@ class Repository
# to avoid unnecessary syncing.
def keep_around(*shas)
shas.each do |sha|
- begin
- next unless sha.present? && commit_by(oid: sha)
+ next unless sha.present? && commit_by(oid: sha)
- next if kept_around?(sha)
+ next if kept_around?(sha)
- # This will still fail if the file is corrupted (e.g. 0 bytes)
- raw_repository.write_ref(keep_around_ref_name(sha), sha)
- rescue Gitlab::Git::CommandError => ex
- Rails.logger.error "Unable to create keep-around reference for repository #{disk_path}: #{ex}"
- end
+ # This will still fail if the file is corrupted (e.g. 0 bytes)
+ raw_repository.write_ref(keep_around_ref_name(sha), sha)
+ rescue Gitlab::Git::CommandError => ex
+ Rails.logger.error "Unable to create keep-around reference for repository #{disk_path}: #{ex}"
end
end
@@ -291,12 +289,13 @@ class Repository
raw_repository.diverging_commit_count(
@root_ref_hash,
branch.dereferenced_target.sha,
- max_count: MAX_DIVERGING_COUNT)
+ max_count: MAX_DIVERGING_COUNT
+ )
if number_commits_behind + number_commits_ahead >= MAX_DIVERGING_COUNT
- { distance: MAX_DIVERGING_COUNT }
+ {distance: MAX_DIVERGING_COUNT}
else
- { behind: number_commits_behind, ahead: number_commits_ahead }
+ {behind: number_commits_behind, ahead: number_commits_ahead}
end
end
end
@@ -316,18 +315,18 @@ class Repository
end
def expire_tags_cache
- expire_method_caches(%i(tag_names tag_count))
+ expire_method_caches(%i[tag_names tag_count])
@tags = nil
end
def expire_branches_cache
- expire_method_caches(%i(branch_names branch_count has_visible_content?))
+ expire_method_caches(%i[branch_names branch_count has_visible_content?])
@local_branches = nil
@branch_exists_memo = nil
end
def expire_statistics_caches
- expire_method_caches(%i(size commit_count))
+ expire_method_caches(%i[size commit_count])
end
def expire_all_method_caches
@@ -335,7 +334,7 @@ class Repository
end
def expire_avatar_cache
- expire_method_caches(%i(avatar))
+ expire_method_caches(%i[avatar])
end
# Refreshes the method caches of this repository.
@@ -376,14 +375,14 @@ class Repository
end
def expire_root_ref_cache
- expire_method_caches(%i(root_ref))
+ expire_method_caches(%i[root_ref])
end
# Expires the cache(s) used to determine if a repository is empty or not.
def expire_emptiness_caches
return unless empty?
- expire_method_caches(%i(has_visible_content?))
+ expire_method_caches(%i[has_visible_content?])
raw_repository.expire_has_local_branches_cache
end
@@ -392,7 +391,7 @@ class Repository
end
def expire_exists_cache
- expire_method_caches(%i(exists?))
+ expire_method_caches(%i[exists?])
end
# expire cache that doesn't depend on repository data (when expiring)
@@ -616,7 +615,7 @@ class Repository
def rendered_readme
return unless readme
- context = { project: project }
+ context = {project: project}
MarkupHelper.markup_unsafe(readme.name, readme.data, context)
end
@@ -667,7 +666,7 @@ class Repository
cache_method :xcode_project?
def head_commit
- @head_commit ||= commit(self.root_ref)
+ @head_commit ||= commit(root_ref)
end
def head_tree
@@ -695,8 +694,6 @@ class Repository
if last_commit
blob_at(last_commit.sha, path)
- else
- nil
end
end
@@ -722,16 +719,16 @@ class Repository
end
def next_branch(name, opts = {})
- branch_ids = self.branch_names.map do |n|
+ branch_ids = branch_names.map { |n|
next 1 if n == name
result = n.match(/\A#{name}-([0-9]+)\z/)
result[1].to_i if result
- end.compact
+ }.compact
highest_branch_id = branch_ids.max || 0
- return name if opts[:mild] && 0 == highest_branch_id
+ return name if opts[:mild] && highest_branch_id == 0
"#{name}-#{highest_branch_id + 1}"
end
@@ -742,13 +739,13 @@ class Repository
def tags_sorted_by(value)
case value
- when 'name_asc'
+ when "name_asc"
VersionSorter.sort(tags) { |tag| tag.name }
- when 'name_desc'
+ when "name_desc"
VersionSorter.rsort(tags) { |tag| tag.name }
- when 'updated_desc'
+ when "updated_desc"
tags_sorted_by_committed_date.reverse
- when 'updated_asc'
+ when "updated_asc"
tags_sorted_by_committed_date
else
tags
@@ -759,10 +756,10 @@ class Repository
#
# order_by: name|email|commits
# sort: asc|desc default: 'asc'
- def contributors(order_by: nil, sort: 'asc')
+ def contributors(order_by: nil, sort: "asc")
commits = self.commits(nil, limit: 2000, offset: 0, skip_merges: true)
- commits = commits.group_by(&:author_email).map do |email, commits|
+ commits = commits.group_by(&:author_email).map { |email, commits|
contributor = Gitlab::Contributor.new
contributor.email = email
@@ -775,7 +772,7 @@ class Repository
end
contributor
- end
+ }
Commit.order_by(collection: commits, order_by: order_by, sort: sort)
end
@@ -791,20 +788,20 @@ class Repository
@local_branches ||= raw_repository.local_branches
end
- alias_method :branches, :local_branches
+ alias branches local_branches
def tags
@tags ||= raw_repository.tags
end
def create_dir(user, path, **options)
- options[:actions] = [{ action: :create_dir, file_path: path }]
+ options[:actions] = [{action: :create_dir, file_path: path}]
multi_action(user, **options)
end
def create_file(user, path, content, **options)
- options[:actions] = [{ action: :create, file_path: path, content: content }]
+ options[:actions] = [{action: :create, file_path: path, content: content}]
multi_action(user, **options)
end
@@ -813,13 +810,13 @@ class Repository
previous_path = options.delete(:previous_path)
action = previous_path && previous_path != path ? :move : :update
- options[:actions] = [{ action: action, file_path: path, previous_path: previous_path, content: content }]
+ options[:actions] = [{action: action, file_path: path, previous_path: previous_path, content: content}]
multi_action(user, **options)
end
def delete_file(user, path, **options)
- options[:actions] = [{ action: :delete, file_path: path }]
+ options[:actions] = [{action: :delete, file_path: path}]
multi_action(user, **options)
end
@@ -862,7 +859,7 @@ class Repository
def ff_merge(user, source, target_branch, merge_request: nil)
their_commit_id = commit(source)&.id
- raise 'Invalid merge source' if their_commit_id.nil?
+ raise "Invalid merge source" if their_commit_id.nil?
merge_request&.update(in_progress_merge_commit_sha: their_commit_id)
@@ -871,7 +868,8 @@ class Repository
def revert(
user, commit, branch_name, message,
- start_branch_name: nil, start_project: project)
+ start_branch_name: nil, start_project: project
+ )
with_cache_hooks do
raw_repository.revert(
@@ -887,7 +885,8 @@ class Repository
def cherry_pick(
user, commit, branch_name, message,
- start_branch_name: nil, start_project: project)
+ start_branch_name: nil, start_project: project
+ )
with_cache_hooks do
raw_repository.cherry_pick(
@@ -908,8 +907,6 @@ class Repository
same_head = branch.target == root_ref_sha
merged = ancestor?(branch.target, root_ref_sha)
!same_head && merged
- else
- nil
end
end
@@ -920,9 +917,9 @@ class Repository
delegate :merged_branch_names, to: :raw_repository
def merge_base(*commits_or_ids)
- commit_ids = commits_or_ids.map do |commit_or_id|
+ commit_ids = commits_or_ids.map { |commit_or_id|
commit_or_id.is_a?(::Commit) ? commit_or_id.id : commit_or_id
- end
+ }
raw_repository.merge_base(*commit_ids)
end
@@ -1017,15 +1014,15 @@ class Repository
end
def route_map_for(sha)
- blob_data_at(sha, '.gitlab/route-map.yml')
+ blob_data_at(sha, ".gitlab/route-map.yml")
end
- def gitlab_ci_yml_for(sha, path = '.gitlab-ci.yml')
+ def gitlab_ci_yml_for(sha, path = ".gitlab-ci.yml")
blob_data_at(sha, path)
end
def lfsconfig_for(sha)
- blob_data_at(sha, '.lfsconfig')
+ blob_data_at(sha, ".lfsconfig")
end
def fetch_ref(source_repository, source_ref:, target_ref:)
@@ -1073,10 +1070,10 @@ class Repository
# gitlab-org/gitlab-ce#39239
def find_commit(oid_or_ref)
commit = if oid_or_ref.is_a?(Gitlab::Git::Commit)
- oid_or_ref
- else
- Gitlab::Git::Commit.find(raw_repository, oid_or_ref)
- end
+ oid_or_ref
+ else
+ Gitlab::Git::Commit.find(raw_repository, oid_or_ref)
+ end
::Commit.new(commit, @project) if commit
end
@@ -1114,8 +1111,8 @@ class Repository
def initialize_raw_repository
Gitlab::Git::Repository.new(project.repository_storage,
- disk_path + '.git',
- Gitlab::GlRepository.gl_repository(project, is_wiki),
- project.full_path)
+ disk_path + ".git",
+ Gitlab::GlRepository.gl_repository(project, is_wiki),
+ project.full_path)
end
end
diff --git a/app/models/repository_language.rb b/app/models/repository_language.rb
index b18142a2ac4..72a900cbf86 100644
--- a/app/models/repository_language.rb
+++ b/app/models/repository_language.rb
@@ -7,8 +7,8 @@ class RepositoryLanguage < ActiveRecord::Base
default_scope { includes(:programming_language) }
validates :project, presence: true
- validates :share, inclusion: { in: 0..100, message: "The share of a lanuage is between 0 and 100" }
- validates :programming_language, uniqueness: { scope: :project_id }
+ validates :share, inclusion: {in: 0..100, message: "The share of a lanuage is between 0 and 100"}
+ validates :programming_language, uniqueness: {scope: :project_id}
delegate :name, :color, to: :programming_language
end
diff --git a/app/models/resource_label_event.rb b/app/models/resource_label_event.rb
index 3fd96b9dc18..3ae550035d8 100644
--- a/app/models/resource_label_event.rb
+++ b/app/models/resource_label_event.rb
@@ -14,10 +14,10 @@ class ResourceLabelEvent < ActiveRecord::Base
belongs_to :merge_request
belongs_to :label
- scope :created_after, ->(time) { where('created_at > ?', time) }
+ scope :created_after, ->(time) { where("created_at > ?", time) }
- validates :user, presence: { unless: :importing? }, on: :create
- validates :label, presence: { unless: :importing? }, on: :create
+ validates :user, presence: {unless: :importing?}, on: :create
+ validates :label, presence: {unless: :importing?}, on: :create
validate :exactly_one_issuable
after_save :expire_etag_cache
@@ -25,11 +25,11 @@ class ResourceLabelEvent < ActiveRecord::Base
enum action: {
add: 1,
- remove: 2
+ remove: 2,
}
def self.issuable_attrs
- %i(issue merge_request).freeze
+ %i[issue merge_request].freeze
end
def issuable
@@ -58,12 +58,12 @@ class ResourceLabelEvent < ActiveRecord::Base
end
def banzai_render_context(field)
- super.merge(pipeline: 'label', only_path: true)
+ super.merge(pipeline: "label", only_path: true)
end
def refresh_invalid_reference
# label_id could be nullified on label delete
- self.reference = '' if label_id.nil?
+ self.reference = "" if label_id.nil?
# reference is not set for events which were not rendered yet
self.reference ||= label_reference
@@ -95,12 +95,12 @@ class ResourceLabelEvent < ActiveRecord::Base
# if none of issuable IDs is set, check explicitly if nested issuable
# object is set, this is used during project import
if issuable_count == 0 && importing?
- issuable_count = self.class.issuable_attrs.count { |attr| self.public_send(attr) } # rubocop:disable GitlabSecurity/PublicSend
+ issuable_count = self.class.issuable_attrs.count { |attr| public_send(attr) } # rubocop:disable GitlabSecurity/PublicSend
return true if issuable_count == 1
end
- errors.add(:base, "Exactly one of #{self.class.issuable_attrs.join(', ')} is required")
+ errors.add(:base, "Exactly one of #{self.class.issuable_attrs.join(", ")} is required")
end
def expire_etag_cache
@@ -108,7 +108,7 @@ class ResourceLabelEvent < ActiveRecord::Base
end
def local_label?
- params = { include_ancestor_groups: true }
+ params = {include_ancestor_groups: true}
if resource_parent.is_a?(Project)
params[:project_id] = resource_parent.id
else
diff --git a/app/models/route.rb b/app/models/route.rb
index 4b23dfa5778..a68949f9a9f 100644
--- a/app/models/route.rb
+++ b/app/models/route.rb
@@ -8,9 +8,9 @@ class Route < ActiveRecord::Base
validates :source, presence: true
validates :path,
- length: { within: 1..255 },
+ length: {within: 1..255},
presence: true,
- uniqueness: { case_sensitive: false }
+ uniqueness: {case_sensitive: false}
before_validation :delete_conflicting_orphaned_routes
after_create :delete_conflicting_redirects
@@ -18,7 +18,7 @@ class Route < ActiveRecord::Base
after_update :create_redirect_for_old_path
after_update :rename_descendants
- scope :inside_path, -> (path) { where('routes.path LIKE ?', "#{sanitize_sql_like(path)}/%") }
+ scope :inside_path, ->(path) { where("routes.path LIKE ?", "#{sanitize_sql_like(path)}/%") }
def rename_descendants
return unless path_changed? || name_changed?
@@ -70,9 +70,9 @@ class Route < ActiveRecord::Base
def delete_conflicting_orphaned_routes
conflicting = self.class.iwhere(path: path)
- conflicting_orphaned_routes = conflicting.select do |route|
+ conflicting_orphaned_routes = conflicting.select { |route|
route.source.nil?
- end
+ }
conflicting_orphaned_routes.each(&:destroy)
end
diff --git a/app/models/sent_notification.rb b/app/models/sent_notification.rb
index 6caab24143b..31a6ba2191f 100644
--- a/app/models/sent_notification.rb
+++ b/app/models/sent_notification.rb
@@ -11,7 +11,7 @@ class SentNotification < ActiveRecord::Base
validates :reply_key, presence: true, uniqueness: true
validates :noteable_id, presence: true, unless: :for_commit?
validates :commit_id, presence: true, if: :for_commit?
- validates :in_reply_to_discussion_id, format: { with: /\A\h{40}\z/, allow_nil: true }
+ validates :in_reply_to_discussion_id, format: {with: /\A\h{40}\z/, allow_nil: true}
validate :note_valid
after_save :keep_around_commit, if: :for_commit?
@@ -63,12 +63,16 @@ class SentNotification < ActiveRecord::Base
end
def for_snippet?
- noteable_type.end_with?('Snippet')
+ noteable_type.end_with?("Snippet")
end
def noteable
if for_commit?
- project.commit(commit_id) rescue nil
+ begin
+ project.commit(commit_id)
+ rescue
+ nil
+ end
else
super
end
@@ -76,7 +80,11 @@ class SentNotification < ActiveRecord::Base
def position=(new_position)
if new_position.is_a?(String)
- new_position = JSON.parse(new_position) rescue nil
+ new_position = begin
+ JSON.parse(new_position)
+ rescue
+ nil
+ end
end
if new_position.is_a?(Hash)
@@ -88,34 +96,34 @@ class SentNotification < ActiveRecord::Base
end
def to_param
- self.reply_key
+ reply_key
end
def create_reply(message, dryrun: false)
klass = dryrun ? Notes::BuildService : Notes::CreateService
- klass.new(self.project, self.recipient, reply_params.merge(note: message)).execute
+ klass.new(project, recipient, reply_params.merge(note: message)).execute
end
private
def reply_params
{
- noteable_type: self.noteable_type,
- noteable_id: self.noteable_id,
- commit_id: self.commit_id,
- in_reply_to_discussion_id: self.in_reply_to_discussion_id
+ noteable_type: noteable_type,
+ noteable_id: noteable_id,
+ commit_id: commit_id,
+ in_reply_to_discussion_id: in_reply_to_discussion_id,
}
end
def note_valid
- note = create_reply('Test', dryrun: true)
+ note = create_reply("Test", dryrun: true)
unless note.valid?
- self.errors.add(:base, "Note parameters are invalid: #{note.errors.full_messages.to_sentence}")
+ errors.add(:base, "Note parameters are invalid: #{note.errors.full_messages.to_sentence}")
end
end
def keep_around_commit
- project.repository.keep_around(self.commit_id)
+ project.repository.keep_around(commit_id)
end
end
diff --git a/app/models/service.rb b/app/models/service.rb
index da523bfa426..3185be9129e 100644
--- a/app/models/service.rb
+++ b/app/models/service.rb
@@ -34,9 +34,9 @@ class Service < ActiveRecord::Base
validates :project_id, presence: true, unless: proc { |service| service.template? }
validates :type, presence: true
- scope :visible, -> { where.not(type: 'GitlabIssueTrackerService') }
- scope :issue_trackers, -> { where(category: 'issue_tracker') }
- scope :external_wikis, -> { where(type: 'ExternalWikiService').active }
+ scope :visible, -> { where.not(type: "GitlabIssueTrackerService") }
+ scope :issue_trackers, -> { where(category: "issue_tracker") }
+ scope :external_wikis, -> { where(type: "ExternalWikiService").active }
scope :active, -> { where(active: true) }
scope :without_defaults, -> { where(default: false) }
@@ -51,9 +51,9 @@ class Service < ActiveRecord::Base
scope :pipeline_hooks, -> { where(pipeline_events: true, active: true) }
scope :wiki_page_hooks, -> { where(wiki_page_events: true, active: true) }
scope :external_issue_trackers, -> { issue_trackers.active.without_defaults }
- scope :deployment, -> { where(category: 'deployment') }
+ scope :deployment, -> { where(category: "deployment") }
- default_value_for :category, 'common'
+ default_value_for :category, "common"
def activated?
active
@@ -118,7 +118,7 @@ class Service < ActiveRecord::Base
end
def self.event_names
- self.supported_events.map { |event| "#{event}_events" }
+ supported_events.map { |event| "#{event}_events" }
end
def event_field(event)
@@ -150,7 +150,7 @@ class Service < ActiveRecord::Base
end
def self.supported_events
- %w(push tag_push issue confidential_issue merge_request wiki_page)
+ %w[push tag_push issue confidential_issue merge_request wiki_page]
end
def execute(data)
@@ -160,7 +160,7 @@ class Service < ActiveRecord::Base
def test(data)
# default implementation
result = execute(data)
- { success: result.present?, result: result }
+ {success: result.present?, result: result}
end
def can_test?
@@ -204,7 +204,7 @@ class Service < ActiveRecord::Base
# for each serialized property.
# Also keep track of updated properties in a similar way as ActiveModel::Dirty
def self.boolean_accessor(*args)
- self.prop_accessor(*args)
+ prop_accessor(*args)
args.each do |arg|
class_eval %{
@@ -237,7 +237,7 @@ class Service < ActiveRecord::Base
end
def issue_tracker?
- self.category == :issue_tracker
+ category == :issue_tracker
end
def self.available_services_names
diff --git a/app/models/snippet.rb b/app/models/snippet.rb
index f23ddd64fe3..9337b822936 100644
--- a/app/models/snippet.rb
+++ b/app/models/snippet.rb
@@ -27,14 +27,14 @@ class Snippet < ActiveRecord::Base
alias_attribute :last_edited_by, :updated_by
# If file_name changes, it invalidates content
- alias_method :default_content_html_invalidator, :content_html_invalidated?
+ alias default_content_html_invalidator content_html_invalidated?
def content_html_invalidated?
default_content_html_invalidator || file_name_changed?
end
default_value_for(:visibility_level) { Gitlab::CurrentSettings.default_snippet_visibility }
- belongs_to :author, class_name: 'User'
+ belongs_to :author, class_name: "User"
belongs_to :project
has_many :notes, as: :noteable, dependent: :destroy # rubocop:disable Cop/ActiveRecordDependent
@@ -42,12 +42,12 @@ class Snippet < ActiveRecord::Base
delegate :name, :email, to: :author, prefix: true, allow_nil: true
validates :author, presence: true
- validates :title, presence: true, length: { maximum: 255 }
+ validates :title, presence: true, length: {maximum: 255}
validates :file_name,
- length: { maximum: 255 }
+ length: {maximum: 255}
validates :content, presence: true
- validates :visibility_level, inclusion: { in: Gitlab::VisibilityLevel.values }
+ validates :visibility_level, inclusion: {in: Gitlab::VisibilityLevel.values}
# Scopes
scope :are_internal, -> { where(visibility_level: Snippet::INTERNAL) }
@@ -78,7 +78,7 @@ class Snippet < ActiveRecord::Base
def self.only_include_projects_visible_to(current_user = nil)
levels = Gitlab::VisibilityLevel.levels_for_user(current_user)
- joins(:project).where('projects.visibility_level IN (?)', levels)
+ joins(:project).where("projects.visibility_level IN (?)", levels)
end
def self.only_include_projects_with_snippets_enabled(include_private: false)
@@ -88,15 +88,15 @@ class Snippet < ActiveRecord::Base
levels << ProjectFeature::PRIVATE if include_private
joins(project: :project_feature)
- .where(project_features: { column => levels })
+ .where(project_features: {column => levels})
end
def self.only_include_authorized_projects(current_user)
where(
- 'EXISTS (?)',
+ "EXISTS (?)",
ProjectAuthorization
.select(1)
- .where('project_id = snippets.project_id')
+ .where("project_id = snippets.project_id")
.where(user_id: current_user.id)
)
end
@@ -113,14 +113,14 @@ class Snippet < ActiveRecord::Base
def self.visible_to_or_authored_by(user)
where(
- 'snippets.visibility_level IN (?) OR snippets.author_id = ?',
+ "snippets.visibility_level IN (?) OR snippets.author_id = ?",
Gitlab::VisibilityLevel.levels_for_user(user),
user.id
)
end
def self.reference_prefix
- '$'
+ "$"
end
# Pattern used to extract `$123` snippet references from text
@@ -151,7 +151,7 @@ class Snippet < ActiveRecord::Base
[
".rb", ".py", ".pl", ".scala", ".c", ".cpp", ".java",
".haml", ".html", ".sass", ".scss", ".xml", ".php", ".erb",
- ".js", ".sh", ".coffee", ".yml", ".md"
+ ".js", ".sh", ".coffee", ".yml", ".md",
]
end
@@ -168,7 +168,7 @@ class Snippet < ActiveRecord::Base
end
def sanitized_file_name
- file_name.gsub(/[^a-zA-Z0-9_\-\.]+/, '')
+ file_name.gsub(/[^a-zA-Z0-9_\-\.]+/, "")
end
def visibility_level_field
@@ -191,7 +191,7 @@ class Snippet < ActiveRecord::Base
end
def spammable_entity_type
- 'snippet'
+ "snippet"
end
class << self
diff --git a/app/models/snippet_blob.rb b/app/models/snippet_blob.rb
index cf1ab089829..b90ae096473 100644
--- a/app/models/snippet_blob.rb
+++ b/app/models/snippet_blob.rb
@@ -15,7 +15,7 @@ class SnippetBlob
snippet.file_name
end
- alias_method :path, :name
+ alias path name
def size
data.bytesize
diff --git a/app/models/spam_log.rb b/app/models/spam_log.rb
index ef3f974b959..63329c1a28a 100644
--- a/app/models/spam_log.rb
+++ b/app/models/spam_log.rb
@@ -6,7 +6,7 @@ class SpamLog < ActiveRecord::Base
validates :user, presence: true
def remove_user(deleted_by:)
- user.delete_async(deleted_by: deleted_by, params: { hard_delete: true })
+ user.delete_async(deleted_by: deleted_by, params: {hard_delete: true})
end
def text
diff --git a/app/models/ssh_host_key.rb b/app/models/ssh_host_key.rb
index fd23cc9ac87..f4dfaf93c2f 100644
--- a/app/models/ssh_host_key.rb
+++ b/app/models/ssh_host_key.rb
@@ -12,7 +12,7 @@ class SshHostKey
end
def as_json(*)
- { bits: bits, fingerprint: fingerprint, type: type, index: index }
+ {bits: bits, fingerprint: fingerprint, type: type, index: index}
end
end
@@ -29,7 +29,7 @@ class SshHostKey
opts = HashWithIndifferentAccess.new(opts)
return nil unless opts.key?(:id)
- project_id, url = opts[:id].split(':', 2)
+ project_id, url = opts[:id].split(":", 2)
project = Project.find_by(id: project_id)
project.presence && new(project: project, url: url)
@@ -59,14 +59,14 @@ class SshHostKey
end
def id
- [project.id, url].join(':')
+ [project.id, url].join(":")
end
def as_json(*)
{
host_keys_changed: host_keys_changed?,
fingerprints: fingerprints,
- known_hosts: known_hosts
+ known_hosts: known_hosts,
}
end
@@ -90,25 +90,25 @@ class SshHostKey
def calculate_reactive_cache
known_hosts, errors, status =
- Open3.popen3({}, *%W[ssh-keyscan -T 5 -p #{url.port} -f-]) do |stdin, stdout, stderr, wait_thr|
+ Open3.popen3({}, "ssh-keyscan", "-T", "5", "-p", url.port.to_s, "-f-") { |stdin, stdout, stderr, wait_thr|
stdin.puts(url.host)
stdin.close
[
cleanup(stdout.read),
cleanup(stderr.read),
- wait_thr.value
+ wait_thr.value,
]
- end
+ }
# ssh-keyscan returns an exit code 0 in several error conditions, such as an
# unknown hostname, so check both STDERR and the exit code
if status.success? && !errors.present?
- { known_hosts: known_hosts }
+ {known_hosts: known_hosts}
else
Rails.logger.debug("Failed to detect SSH host keys for #{id}: #{errors}")
- { error: 'Failed to detect SSH host keys' }
+ {error: "Failed to detect SSH host keys"}
end
end
@@ -119,7 +119,7 @@ class SshHostKey
data
.to_s
.each_line
- .reject { |line| line.start_with?('#') || line.chomp.empty? }
+ .reject { |line| line.start_with?("#") || line.chomp.empty? }
.uniq
.sort
.join
@@ -127,7 +127,7 @@ class SshHostKey
def normalize_url(url)
full_url = ::Addressable::URI.parse(url)
- raise ArgumentError.new("Invalid URL") unless full_url&.scheme == 'ssh'
+ raise ArgumentError.new("Invalid URL") unless full_url&.scheme == "ssh"
Addressable::URI.parse("ssh://#{full_url.host}:#{full_url.inferred_port}")
rescue Addressable::URI::InvalidURIError
diff --git a/app/models/storage/hashed_project.rb b/app/models/storage/hashed_project.rb
index f5d0d6fab3b..39a9b009611 100644
--- a/app/models/storage/hashed_project.rb
+++ b/app/models/storage/hashed_project.rb
@@ -5,8 +5,8 @@ module Storage
attr_accessor :project
delegate :gitlab_shell, :repository_storage, to: :project
- REPOSITORY_PATH_PREFIX = '@hashed'
- POOL_PATH_PREFIX = '@pools'
+ REPOSITORY_PATH_PREFIX = "@hashed"
+ POOL_PATH_PREFIX = "@pools"
def initialize(project, prefix: REPOSITORY_PATH_PREFIX)
@project = project
diff --git a/app/models/subscription.rb b/app/models/subscription.rb
index 0f6ee0ddf7e..52d8a1d898b 100644
--- a/app/models/subscription.rb
+++ b/app/models/subscription.rb
@@ -7,5 +7,5 @@ class Subscription < ActiveRecord::Base
validates :user, :subscribable, presence: true
- validates :project_id, uniqueness: { scope: [:subscribable_id, :subscribable_type, :user_id] }
+ validates :project_id, uniqueness: {scope: [:subscribable_id, :subscribable_type, :user_id]}
end
diff --git a/app/models/suggestion.rb b/app/models/suggestion.rb
index 09034646bff..9ac7fdde7a2 100644
--- a/app/models/suggestion.rb
+++ b/app/models/suggestion.rb
@@ -27,19 +27,19 @@ class Suggestion < ApplicationRecord
def from_line
position.new_line
end
- alias_method :to_line, :from_line
+ alias to_line from_line
def from_original_line
original_position.new_line
end
- alias_method :to_original_line, :from_original_line
+ alias to_original_line from_original_line
# `from_line_index` and `to_line_index` represents diff/blob line numbers in
# index-like way (N-1).
def from_line_index
from_line - 1
end
- alias_method :to_line_index, :from_line_index
+ alias to_line_index from_line_index
def appliable?
return false unless note.supports_suggestion?
diff --git a/app/models/system_note_metadata.rb b/app/models/system_note_metadata.rb
index d555ebe5322..0c2a59d1aa6 100644
--- a/app/models/system_note_metadata.rb
+++ b/app/models/system_note_metadata.rb
@@ -20,7 +20,7 @@ class SystemNoteMetadata < ActiveRecord::Base
].freeze
validates :note, presence: true
- validates :action, inclusion: { in: :icon_types }, allow_nil: true
+ validates :action, inclusion: {in: :icon_types}, allow_nil: true
belongs_to :note
diff --git a/app/models/term_agreement.rb b/app/models/term_agreement.rb
index 9b3c8ac68bd..679fc28f46e 100644
--- a/app/models/term_agreement.rb
+++ b/app/models/term_agreement.rb
@@ -1,7 +1,7 @@
# frozen_string_literal: true
class TermAgreement < ActiveRecord::Base
- belongs_to :term, class_name: 'ApplicationSetting::Term'
+ belongs_to :term, class_name: "ApplicationSetting::Term"
belongs_to :user
scope :accepted, -> { where(accepted: true) }
diff --git a/app/models/timelog.rb b/app/models/timelog.rb
index e04c644a53a..8b8a0eb40ab 100644
--- a/app/models/timelog.rb
+++ b/app/models/timelog.rb
@@ -16,9 +16,9 @@ class Timelog < ActiveRecord::Base
def issuable_id_is_present
if issue_id && merge_request_id
- errors.add(:base, 'Only Issue ID or Merge Request ID is required')
+ errors.add(:base, "Only Issue ID or Merge Request ID is required")
elsif issuable.nil?
- errors.add(:base, 'Issue or Merge Request ID is required')
+ errors.add(:base, "Issue or Merge Request ID is required")
end
end
diff --git a/app/models/todo.rb b/app/models/todo.rb
index d9b86d941b6..534db99b9a0 100644
--- a/app/models/todo.rb
+++ b/app/models/todo.rb
@@ -24,7 +24,7 @@ class Todo < ActiveRecord::Base
MARKED => :marked,
APPROVAL_REQUIRED => :approval_required,
UNMERGEABLE => :unmergeable,
- DIRECTLY_ADDRESSED => :directly_addressed
+ DIRECTLY_ADDRESSED => :directly_addressed,
}.freeze
belongs_to :author, class_name: "User"
@@ -45,13 +45,13 @@ class Todo < ActiveRecord::Base
scope :pending, -> { with_state(:pending) }
scope :done, -> { with_state(:done) }
- scope :for_action, -> (action) { where(action: action) }
- scope :for_author, -> (author) { where(author: author) }
- scope :for_project, -> (project) { where(project: project) }
- scope :for_group, -> (group) { where(group: group) }
- scope :for_type, -> (type) { where(target_type: type) }
- scope :for_target, -> (id) { where(target_id: id) }
- scope :for_commit, -> (id) { where(commit_id: id) }
+ scope :for_action, ->(action) { where(action: action) }
+ scope :for_author, ->(author) { where(author: author) }
+ scope :for_project, ->(project) { where(project: project) }
+ scope :for_group, ->(group) { where(group: group) }
+ scope :for_type, ->(type) { where(target_type: type) }
+ scope :for_target, ->(id) { where(target_id: id) }
+ scope :for_commit, ->(id) { where(commit_id: id) }
state_machine :state, initial: :pending do
event :done do
@@ -75,7 +75,7 @@ class Todo < ActiveRecord::Base
from_union([
for_project(Project.for_group(groups)),
- for_group(groups)
+ for_group(groups),
])
end
@@ -107,7 +107,7 @@ class Todo < ActiveRecord::Base
def sort_by_attribute(method)
sorted =
case method.to_s
- when 'priority', 'label_priority' then order_by_labels_priority
+ when "priority", "label_priority" then order_by_labels_priority
else order_by(method)
end
@@ -122,14 +122,14 @@ class Todo < ActiveRecord::Base
params = {
target_type_column: "todos.target_type",
target_column: "todos.target_id",
- project_column: "todos.project_id"
+ project_column: "todos.project_id",
}
highest_priority = highest_label_priority(params).to_sql
select("#{table_name}.*, (#{highest_priority}) AS highest_priority")
- .order(Gitlab::Database.nulls_last_order('highest_priority', 'ASC'))
- .order('todos.created_at')
+ .order(Gitlab::Database.nulls_last_order("highest_priority", "ASC"))
+ .order("todos.created_at")
end
end
@@ -168,7 +168,11 @@ class Todo < ActiveRecord::Base
# override to return commits, which are not active record
def target
if for_commit?
- project.commit(commit_id) rescue nil
+ begin
+ project.commit(commit_id)
+ rescue
+ nil
+ end
else
super
end
@@ -193,6 +197,6 @@ class Todo < ActiveRecord::Base
private
def keep_around_commit
- project.repository.keep_around(self.commit_id)
+ project.repository.keep_around(commit_id)
end
end
diff --git a/app/models/tree.rb b/app/models/tree.rb
index cd385872171..e078eed5122 100644
--- a/app/models/tree.rb
+++ b/app/models/tree.rb
@@ -6,8 +6,8 @@ class Tree
attr_accessor :repository, :sha, :path, :entries
- def initialize(repository, sha, path = '/', recursive: false)
- path = '/' if path.blank?
+ def initialize(repository, sha, path = "/", recursive: false)
+ path = "/" if path.blank?
@repository = repository
@sha = sha
@@ -19,23 +19,23 @@ class Tree
def readme_path
strong_memoize(:readme_path) do
- available_readmes = blobs.select do |blob|
+ available_readmes = blobs.select { |blob|
Gitlab::FileDetector.type_of(blob.name) == :readme
- end
+ }
- previewable_readmes = available_readmes.select do |blob|
+ previewable_readmes = available_readmes.select { |blob|
previewable?(blob.name)
- end
+ }
- plain_readmes = available_readmes.select do |blob|
+ plain_readmes = available_readmes.select { |blob|
plain?(blob.name)
- end
+ }
# Prioritize previewable over plain readmes
entry = previewable_readmes.first || plain_readmes.first
next nil unless entry
- if path == '/'
+ if path == "/"
entry.name
else
File.join(path, entry.name)
diff --git a/app/models/u2f_registration.rb b/app/models/u2f_registration.rb
index 37598173fd1..351fc0a7454 100644
--- a/app/models/u2f_registration.rb
+++ b/app/models/u2f_registration.rb
@@ -7,7 +7,7 @@ class U2fRegistration < ActiveRecord::Base
def self.register(user, app_id, params, challenges)
u2f = U2F::U2F.new(app_id)
- registration = self.new
+ registration = new
begin
response = U2F::RegisterResponse.load_from_json(params[:device_response])
@@ -19,7 +19,7 @@ class U2fRegistration < ActiveRecord::Base
user: user,
name: params[:name])
rescue JSON::ParserError, NoMethodError, ArgumentError
- registration.errors.add(:base, 'Your U2F device did not send a valid JSON response.')
+ registration.errors.add(:base, "Your U2F device did not send a valid JSON response.")
rescue U2F::Error => e
registration.errors.add(:base, e.message)
end
diff --git a/app/models/upload.rb b/app/models/upload.rb
index 20860f14b83..d83a5b31659 100644
--- a/app/models/upload.rb
+++ b/app/models/upload.rb
@@ -31,7 +31,7 @@ class Upload < ActiveRecord::Base
def begin_fast_destroy
{
Uploads::Local => Uploads::Local.new.keys(with_files_stored_locally),
- Uploads::Fog => Uploads::Fog.new.keys(with_files_stored_remotely)
+ Uploads::Fog => Uploads::Fog.new.keys(with_files_stored_remotely),
}
end
@@ -71,10 +71,10 @@ class Upload < ActiveRecord::Base
# Help sysadmins find missing upload files
if persisted? && !exist
if Gitlab::Sentry.enabled?
- Raven.capture_message("Upload file does not exist", extra: self.attributes)
+ Raven.capture_message("Upload file does not exist", extra: attributes)
end
- Gitlab::Metrics.counter(:upload_file_does_not_exist_total, 'The number of times an upload record could not find its file').increment
+ Gitlab::Metrics.counter(:upload_file_does_not_exist_total, "The number of times an upload record could not find its file").increment
end
exist
@@ -83,7 +83,7 @@ class Upload < ActiveRecord::Base
def uploader_context
{
identifier: identifier,
- secret: secret
+ secret: secret,
}.compact
end
@@ -110,7 +110,7 @@ class Upload < ActiveRecord::Base
end
def relative_path?
- !path.start_with?('/')
+ !path.start_with?("/")
end
def uploader_class
diff --git a/app/models/uploads/local.rb b/app/models/uploads/local.rb
index 2901c33c359..30cb69b721e 100644
--- a/app/models/uploads/local.rb
+++ b/app/models/uploads/local.rb
@@ -23,7 +23,7 @@ module Uploads
unless in_uploads?(path)
message = "Path '#{path}' is not in uploads dir, skipping"
logger.warn(message)
- Gitlab::Sentry.track_exception(RuntimeError.new(message), extra: { uploads_dir: storage_dir })
+ Gitlab::Sentry.track_exception(RuntimeError.new(message), extra: {uploads_dir: storage_dir})
return
end
diff --git a/app/models/user.rb b/app/models/user.rb
index ee51c35d576..b9b6084b56d 100644
--- a/app/models/user.rb
+++ b/app/models/user.rb
@@ -1,6 +1,6 @@
# frozen_string_literal: true
-require 'carrierwave/orm/activerecord'
+require "carrierwave/orm/activerecord"
class User < ApplicationRecord
extend Gitlab::ConfigHelper
@@ -43,22 +43,22 @@ class User < ApplicationRecord
default_value_for :theme_id, gitlab_config.default_theme
attr_encrypted :otp_secret,
- key: Gitlab::Application.secrets.otp_key_base,
- mode: :per_attribute_iv_and_salt,
+ key: Gitlab::Application.secrets.otp_key_base,
+ mode: :per_attribute_iv_and_salt,
insecure_mode: true,
- algorithm: 'aes-256-cbc'
+ algorithm: "aes-256-cbc"
devise :two_factor_authenticatable,
- otp_secret_encryption_key: Gitlab::Application.secrets.otp_key_base
+ otp_secret_encryption_key: Gitlab::Application.secrets.otp_key_base
devise :two_factor_backupable, otp_number_of_backup_codes: 10
serialize :otp_backup_codes, JSON # rubocop:disable Cop/ActiveRecordSerialize
devise :lockable, :recoverable, :rememberable, :trackable,
- :validatable, :omniauthable, :confirmable, :registerable
+ :validatable, :omniauthable, :confirmable, :registerable
BLOCKED_MESSAGE = "Your account has been blocked. Please contact your GitLab " \
- "administrator if you think this is an error.".freeze
+ "administrator if you think this is an error."
# Override Devise::Models::Trackable#update_tracked_fields!
# to limit database writes to at most once every hour
@@ -89,7 +89,7 @@ class User < ApplicationRecord
# Profile
has_many :keys, -> { regular_keys }, dependent: :destroy # rubocop:disable Cop/ActiveRecordDependent
- has_many :deploy_keys, -> { where(type: 'DeployKey') }, dependent: :nullify # rubocop:disable Cop/ActiveRecordDependent
+ has_many :deploy_keys, -> { where(type: "DeployKey") }, dependent: :nullify # rubocop:disable Cop/ActiveRecordDependent
has_many :gpg_keys
has_many :emails, dependent: :destroy # rubocop:disable Cop/ActiveRecordDependent
@@ -101,14 +101,14 @@ class User < ApplicationRecord
# Groups
has_many :members
- has_many :group_members, -> { where(requested_at: nil) }, source: 'GroupMember'
+ has_many :group_members, -> { where(requested_at: nil) }, source: "GroupMember"
has_many :groups, through: :group_members
- has_many :owned_groups, -> { where(members: { access_level: Gitlab::Access::OWNER }) }, through: :group_members, source: :group
- has_many :maintainers_groups, -> { where(members: { access_level: Gitlab::Access::MAINTAINER }) }, through: :group_members, source: :group
+ has_many :owned_groups, -> { where(members: {access_level: Gitlab::Access::OWNER}) }, through: :group_members, source: :group
+ has_many :maintainers_groups, -> { where(members: {access_level: Gitlab::Access::MAINTAINER}) }, through: :group_members, source: :group
has_many :owned_or_maintainers_groups,
- -> { where(members: { access_level: [Gitlab::Access::MAINTAINER, Gitlab::Access::OWNER] }) },
- through: :group_members,
- source: :group
+ -> { where(members: {access_level: [Gitlab::Access::MAINTAINER, Gitlab::Access::OWNER]}) },
+ through: :group_members,
+ source: :group
alias_attribute :masters_groups, :maintainers_groups
# Projects
@@ -116,14 +116,14 @@ class User < ApplicationRecord
has_many :personal_projects, through: :namespace, source: :projects
has_many :project_members, -> { where(requested_at: nil) }
has_many :projects, through: :project_members
- has_many :created_projects, foreign_key: :creator_id, class_name: 'Project'
+ has_many :created_projects, foreign_key: :creator_id, class_name: "Project"
has_many :users_star_projects, dependent: :destroy # rubocop:disable Cop/ActiveRecordDependent
has_many :starred_projects, through: :users_star_projects, source: :project
has_many :project_authorizations, dependent: :delete_all # rubocop:disable Cop/ActiveRecordDependent
has_many :authorized_projects, through: :project_authorizations, source: :project
has_many :user_interacted_projects
- has_many :project_interactions, through: :user_interacted_projects, source: :project, class_name: 'Project'
+ has_many :project_interactions, through: :user_interacted_projects, source: :project, class_name: "Project"
has_many :snippets, dependent: :destroy, foreign_key: :author_id # rubocop:disable Cop/ActiveRecordDependent
has_many :notes, dependent: :destroy, foreign_key: :author_id # rubocop:disable Cop/ActiveRecordDependent
@@ -132,27 +132,27 @@ class User < ApplicationRecord
has_many :events, dependent: :destroy, foreign_key: :author_id # rubocop:disable Cop/ActiveRecordDependent
has_many :releases, dependent: :nullify, foreign_key: :author_id # rubocop:disable Cop/ActiveRecordDependent
has_many :subscriptions, dependent: :destroy # rubocop:disable Cop/ActiveRecordDependent
- has_many :oauth_applications, class_name: 'Doorkeeper::Application', as: :owner, dependent: :destroy # rubocop:disable Cop/ActiveRecordDependent
+ has_many :oauth_applications, class_name: "Doorkeeper::Application", as: :owner, dependent: :destroy # rubocop:disable Cop/ActiveRecordDependent
has_one :abuse_report, dependent: :destroy, foreign_key: :user_id # rubocop:disable Cop/ActiveRecordDependent
has_many :reported_abuse_reports, dependent: :destroy, foreign_key: :reporter_id, class_name: "AbuseReport" # rubocop:disable Cop/ActiveRecordDependent
has_many :spam_logs, dependent: :destroy # rubocop:disable Cop/ActiveRecordDependent
- has_many :builds, dependent: :nullify, class_name: 'Ci::Build' # rubocop:disable Cop/ActiveRecordDependent
- has_many :pipelines, dependent: :nullify, class_name: 'Ci::Pipeline' # rubocop:disable Cop/ActiveRecordDependent
+ has_many :builds, dependent: :nullify, class_name: "Ci::Build" # rubocop:disable Cop/ActiveRecordDependent
+ has_many :pipelines, dependent: :nullify, class_name: "Ci::Pipeline" # rubocop:disable Cop/ActiveRecordDependent
has_many :todos
has_many :notification_settings
has_many :award_emoji, dependent: :destroy # rubocop:disable Cop/ActiveRecordDependent
- has_many :triggers, dependent: :destroy, class_name: 'Ci::Trigger', foreign_key: :owner_id # rubocop:disable Cop/ActiveRecordDependent
+ has_many :triggers, dependent: :destroy, class_name: "Ci::Trigger", foreign_key: :owner_id # rubocop:disable Cop/ActiveRecordDependent
has_many :issue_assignees
has_many :assigned_issues, class_name: "Issue", through: :issue_assignees, source: :issue
has_many :assigned_merge_requests, dependent: :nullify, foreign_key: :assignee_id, class_name: "MergeRequest" # rubocop:disable Cop/ActiveRecordDependent
- has_many :custom_attributes, class_name: 'UserCustomAttribute'
- has_many :callouts, class_name: 'UserCallout'
+ has_many :custom_attributes, class_name: "UserCustomAttribute"
+ has_many :callouts, class_name: "UserCallout"
has_many :term_agreements
- belongs_to :accepted_term, class_name: 'ApplicationSetting::Term'
+ belongs_to :accepted_term, class_name: "ApplicationSetting::Term"
- has_one :status, class_name: 'UserStatus'
+ has_one :status, class_name: "UserStatus"
has_one :user_preference
#
@@ -165,10 +165,10 @@ class User < ApplicationRecord
validates :notification_email, email: true, if: ->(user) { user.notification_email != user.email }
validates :public_email, presence: true, uniqueness: true, email: true, allow_blank: true
validates :commit_email, email: true, allow_nil: true, if: ->(user) { user.commit_email != user.email }
- validates :bio, length: { maximum: 255 }, allow_blank: true
+ validates :bio, length: {maximum: 255}, allow_blank: true
validates :projects_limit,
presence: true,
- numericality: { greater_than_or_equal_to: 0, less_than_or_equal_to: Gitlab::Database::MAX_INT_VALUE }
+ numericality: {greater_than_or_equal_to: 0, less_than_or_equal_to: Gitlab::Database::MAX_INT_VALUE}
validates :username, presence: true
validates :namespace, presence: true
@@ -197,7 +197,7 @@ class User < ApplicationRecord
after_destroy :post_destroy_hook
after_destroy :remove_key_cache
after_commit(on: :update) do
- if previous_changes.key?('email')
+ if previous_changes.key?("email")
# Grab previous_email here since previous_changes changes after
# #update_emails_with_primary_email and #update_notification_email are called
previous_email = previous_changes[:email][0]
@@ -267,14 +267,14 @@ class User < ApplicationRecord
scope :blocked, -> { with_states(:blocked, :ldap_blocked) }
scope :external, -> { where(external: true) }
scope :active, -> { with_state(:active).non_internal }
- scope :without_projects, -> { joins('LEFT JOIN project_authorizations ON users.id = project_authorizations.user_id').where(project_authorizations: { user_id: nil }) }
- scope :order_recent_sign_in, -> { reorder(Gitlab::Database.nulls_last_order('current_sign_in_at', 'DESC')) }
- scope :order_oldest_sign_in, -> { reorder(Gitlab::Database.nulls_last_order('current_sign_in_at', 'ASC')) }
- scope :order_recent_last_activity, -> { reorder(Gitlab::Database.nulls_last_order('last_activity_on', 'DESC')) }
- scope :order_oldest_last_activity, -> { reorder(Gitlab::Database.nulls_first_order('last_activity_on', 'ASC')) }
+ scope :without_projects, -> { joins("LEFT JOIN project_authorizations ON users.id = project_authorizations.user_id").where(project_authorizations: {user_id: nil}) }
+ scope :order_recent_sign_in, -> { reorder(Gitlab::Database.nulls_last_order("current_sign_in_at", "DESC")) }
+ scope :order_oldest_sign_in, -> { reorder(Gitlab::Database.nulls_last_order("current_sign_in_at", "ASC")) }
+ scope :order_recent_last_activity, -> { reorder(Gitlab::Database.nulls_last_order("last_activity_on", "DESC")) }
+ scope :order_oldest_last_activity, -> { reorder(Gitlab::Database.nulls_first_order("last_activity_on", "ASC")) }
scope :confirmed, -> { where.not(confirmed_at: nil) }
- scope :by_username, -> (usernames) { iwhere(username: Array(usernames).map(&:to_s)) }
- scope :for_todos, -> (todos) { where(id: todos.select(:user_id)) }
+ scope :by_username, ->(usernames) { iwhere(username: Array(usernames).map(&:to_s)) }
+ scope :for_todos, ->(todos) { where(id: todos.select(:user_id)) }
scope :with_emails, -> { preload(:emails) }
# Limits the users to those that have TODOs, optionally in the given state.
@@ -338,13 +338,13 @@ class User < ApplicationRecord
end
def sort_by_attribute(method)
- order_method = method || 'id_desc'
+ order_method = method || "id_desc"
case order_method.to_s
- when 'recent_sign_in' then order_recent_sign_in
- when 'oldest_sign_in' then order_oldest_sign_in
- when 'last_activity_on_desc' then order_recent_last_activity
- when 'last_activity_on_asc' then order_oldest_last_activity
+ when "recent_sign_in" then order_recent_sign_in
+ when "oldest_sign_in" then order_oldest_sign_in
+ when "last_activity_on_desc" then order_recent_last_activity
+ when "last_activity_on_asc" then order_oldest_last_activity
else
order_by(order_method)
end
@@ -371,7 +371,7 @@ class User < ApplicationRecord
from_users = where(email: emails)
from_users = from_users.confirmed if confirmed
- from_emails = joins(:emails).where(emails: { email: emails })
+ from_emails = joins(:emails).where(emails: {email: emails})
from_emails = from_emails.confirmed.merge(Email.confirmed) if confirmed
items = [from_users, from_emails]
@@ -390,17 +390,17 @@ class User < ApplicationRecord
def filter_items(filter_name)
case filter_name
- when 'admins'
+ when "admins"
admins
- when 'blocked'
+ when "blocked"
blocked
- when 'two_factor_disabled'
+ when "two_factor_disabled"
without_two_factor
- when 'two_factor_enabled'
+ when "two_factor_enabled"
with_two_factor
- when 'wop'
+ when "wop"
without_projects
- when 'external'
+ when "external"
external
else
active
@@ -432,7 +432,7 @@ class User < ApplicationRecord
fuzzy_arel_match(:name, query, lower_exact_match: true)
.or(fuzzy_arel_match(:username, query, lower_exact_match: true))
.or(arel_table[:email].eq(query))
- ).reorder(order % { query: ActiveRecord::Base.connection.quote(query) }, :name)
+ ).reorder(order % {query: ActiveRecord::Base.connection.quote(query)}, :name)
end
# Limits the result set to users _not_ in the given query/list of IDs.
@@ -472,7 +472,7 @@ class User < ApplicationRecord
def by_login(login)
return nil unless login
- if login.include?('@'.freeze)
+ if login.include?("@")
unscoped.iwhere(email: login).take
else
unscoped.iwhere(username: login).take
@@ -498,7 +498,7 @@ class User < ApplicationRecord
end
def reference_prefix
- '@'
+ "@"
end
# Pattern used to extract `@user` user references from text
@@ -513,10 +513,10 @@ class User < ApplicationRecord
# Return (create if necessary) the ghost user. The ghost user
# owns records previously belonging to deleted users.
def ghost
- email = 'ghost%s@example.com'
- unique_internal(where(ghost: true), 'ghost', email) do |u|
+ email = "ghost%s@example.com"
+ unique_internal(where(ghost: true), "ghost", email) do |u|
u.bio = 'This is a "Ghost User", created to hold all issues authored by users that have since been deleted. This user cannot be removed.'
- u.name = 'Ghost User'
+ u.name = "Ghost User"
end
end
@@ -595,14 +595,14 @@ class User < ApplicationRecord
def disable_two_factor!
transaction do
update(
- otp_required_for_login: false,
- encrypted_otp_secret: nil,
- encrypted_otp_secret_iv: nil,
- encrypted_otp_secret_salt: nil,
+ otp_required_for_login: false,
+ encrypted_otp_secret: nil,
+ encrypted_otp_secret_iv: nil,
+ encrypted_otp_secret_salt: nil,
otp_grace_period_started_at: nil,
- otp_backup_codes: nil
+ otp_backup_codes: nil
)
- self.u2f_registrations.destroy_all # rubocop: disable DestroyAll
+ u2f_registrations.destroy_all # rubocop: disable DestroyAll
end
end
@@ -624,13 +624,13 @@ class User < ApplicationRecord
def namespace_move_dir_allowed
if namespace&.any_project_has_container_registry_tags?
- errors.add(:username, 'cannot be changed if a personal project has container registry tags.')
+ errors.add(:username, "cannot be changed if a personal project has container registry tags.")
end
end
def unique_email
if !emails.exists?(email: email) && Email.exists?(email: email)
- errors.add(:email, 'has already been taken')
+ errors.add(:email, "has already been taken")
end
end
@@ -658,14 +658,14 @@ class User < ApplicationRecord
# possibility of the commit_email column not existing.
def commit_email
- return self.email unless has_attribute?(:commit_email)
+ return email unless has_attribute?(:commit_email)
if super == Gitlab::PrivateCommitEmail::TOKEN
return private_commit_email
end
# The commit email is the same as the primary email if undefined
- super.presence || self.email
+ super.presence || email
end
def commit_email=(email)
@@ -682,7 +682,7 @@ class User < ApplicationRecord
# see if the new email is already a verified secondary email
def check_for_verified_email
- skip_reconfirmation! if emails.confirmed.where(email: self.email).any?
+ skip_reconfirmation! if emails.confirmed.where(email: email).any?
end
# Note: the use of the Emails services will cause `saves` on the user object, running
@@ -710,7 +710,7 @@ class User < ApplicationRecord
Group.unscoped do
Group.from_union([
groups,
- authorized_projects.joins(:namespace).select('namespaces.*')
+ authorized_projects.joins(:namespace).select("namespaces.*"),
])
end
end
@@ -747,14 +747,14 @@ class User < ApplicationRecord
if min_access_level
projects = projects
- .where('project_authorizations.access_level >= ?', min_access_level)
+ .where("project_authorizations.access_level >= ?", min_access_level)
end
projects
end
def authorized_project?(project, min_access_level = nil)
- authorized_projects(min_access_level).exists?({ id: project.id })
+ authorized_projects(min_access_level).exists?({id: project.id})
end
# Typically used in conjunction with projects table to get projects
@@ -763,11 +763,11 @@ class User < ApplicationRecord
# Example use:
# `Project.where('EXISTS(?)', user.authorizations_for_projects)`
def authorizations_for_projects(min_access_level: nil)
- authorizations = project_authorizations.select(1).where('project_authorizations.project_id = projects.id')
+ authorizations = project_authorizations.select(1).where("project_authorizations.project_id = projects.id")
return authorizations unless min_access_level.present?
- authorizations.where('project_authorizations.access_level >= ?', min_access_level)
+ authorizations.where("project_authorizations.access_level >= ?", min_access_level)
end
# Returns the projects this user has reporter (or greater) access to, limited
@@ -786,7 +786,7 @@ class User < ApplicationRecord
Project.where(namespace: namespace),
Project.joins(:project_authorizations)
.where("projects.namespace_id <> ?", namespace.id)
- .where(project_authorizations: { user_id: id, access_level: Gitlab::Access::OWNER })
+ .where(project_authorizations: {user_id: id, access_level: Gitlab::Access::OWNER}),
],
remove_duplicates: false
)
@@ -803,7 +803,7 @@ class User < ApplicationRecord
def require_ssh_key?
count = Users::KeysCountService.new(self).count
- count.zero? && Gitlab::ProtocolAccess.allowed?('ssh')
+ count.zero? && Gitlab::ProtocolAccess.allowed?("ssh")
end
# rubocop: enable CodeReuse/ServiceClass
@@ -818,7 +818,7 @@ class User < ApplicationRecord
def require_personal_access_token_creation_for_git_auth?
return false if allow_password_authentication_for_git? || ldap_user?
- PersonalAccessTokensFinder.new(user: self, impersonation: false, state: 'active').execute.none?
+ PersonalAccessTokensFinder.new(user: self, impersonation: false, state: "active").execute.none?
end
def require_extra_setup_for_git_auth?
@@ -944,7 +944,7 @@ class User < ApplicationRecord
def set_public_email
if public_email.blank? || all_emails.exclude?(public_email)
- self.public_email = ''
+ self.public_email = ""
end
end
@@ -993,9 +993,9 @@ class User < ApplicationRecord
end
def solo_owned_groups
- @solo_owned_groups ||= owned_groups.select do |group|
+ @solo_owned_groups ||= owned_groups.select { |group|
group.owners == [self]
- end
+ }
end
def with_defaults
@@ -1018,7 +1018,7 @@ class User < ApplicationRecord
end
def short_website_url
- website_url.sub(%r{\Ahttps?://}, '')
+ website_url.sub(%r{\Ahttps?://}, "")
end
def all_ssh_keys
@@ -1026,7 +1026,7 @@ class User < ApplicationRecord
end
def temp_oauth_email?
- email.start_with?('temp-email-for-oauth')
+ email.start_with?("temp-email-for-oauth")
end
# rubocop: disable CodeReuse/ServiceClass
@@ -1070,7 +1070,7 @@ class User < ApplicationRecord
# handle the outdated private commit email case
return true if persisted? &&
- id == Gitlab::PrivateCommitEmail.user_id_for_email(downcased)
+ id == Gitlab::PrivateCommitEmail.user_id_for_email(downcased)
all_emails.include?(check_email.downcase)
end
@@ -1080,7 +1080,7 @@ class User < ApplicationRecord
# handle the outdated private commit email case
return true if persisted? &&
- id == Gitlab::PrivateCommitEmail.user_id_for_email(downcased)
+ id == Gitlab::PrivateCommitEmail.user_id_for_email(downcased)
verified_emails.include?(check_email.downcase)
end
@@ -1089,7 +1089,7 @@ class User < ApplicationRecord
{
name: name,
username: username,
- avatar_url: avatar_url(only_path: false)
+ avatar_url: avatar_url(only_path: false),
}
end
@@ -1102,8 +1102,8 @@ class User < ApplicationRecord
end
def set_username_errors
- namespace_path_errors = self.errors.delete(:"namespace.path")
- self.errors[:username].concat(namespace_path_errors) if namespace_path_errors
+ namespace_path_errors = errors.delete(:"namespace.path")
+ errors[:username].concat(namespace_path_errors) if namespace_path_errors
end
def username_changed_hook
@@ -1150,7 +1150,7 @@ class User < ApplicationRecord
def toggle_star(project)
UsersStarProject.transaction do
user_star_project = users_star_projects
- .where(project: project, user: self).lock(true).first
+ .where(project: project, user: self).lock(true).first
if user_star_project
user_star_project.destroy
@@ -1169,7 +1169,7 @@ class User < ApplicationRecord
end
def manageable_groups_with_routes
- manageable_groups.eager_load(:route).order('routes.path')
+ manageable_groups.eager_load(:route).order("routes.path")
end
def namespaces
@@ -1212,12 +1212,12 @@ class User < ApplicationRecord
project_runners = Ci::RunnerProject
.where(project: authorized_projects(Gitlab::Access::MAINTAINER))
.joins(:runner)
- .select('ci_runners.*')
+ .select("ci_runners.*")
group_runners = Ci::RunnerNamespace
.where(namespace_id: owned_or_maintainers_groups.select(:id))
.joins(:runner)
- .select('ci_runners.*')
+ .select("ci_runners.*")
Ci::Runner.from_union([project_runners, group_runners])
end
@@ -1246,33 +1246,33 @@ class User < ApplicationRecord
end
def assigned_open_merge_requests_count(force: false)
- Rails.cache.fetch(['users', id, 'assigned_open_merge_requests_count'], force: force, expires_in: 20.minutes) do
- MergeRequestsFinder.new(self, assignee_id: self.id, state: 'opened', non_archived: true).execute.count
+ Rails.cache.fetch(["users", id, "assigned_open_merge_requests_count"], force: force, expires_in: 20.minutes) do
+ MergeRequestsFinder.new(self, assignee_id: id, state: "opened", non_archived: true).execute.count
end
end
def assigned_open_issues_count(force: false)
- Rails.cache.fetch(['users', id, 'assigned_open_issues_count'], force: force, expires_in: 20.minutes) do
- IssuesFinder.new(self, assignee_id: self.id, state: 'opened', non_archived: true).execute.count
+ Rails.cache.fetch(["users", id, "assigned_open_issues_count"], force: force, expires_in: 20.minutes) do
+ IssuesFinder.new(self, assignee_id: id, state: "opened", non_archived: true).execute.count
end
end
def todos_done_count(force: false)
- Rails.cache.fetch(['users', id, 'todos_done_count'], force: force, expires_in: 20.minutes) do
+ Rails.cache.fetch(["users", id, "todos_done_count"], force: force, expires_in: 20.minutes) do
TodosFinder.new(self, state: :done).execute.count
end
end
def todos_pending_count(force: false)
- Rails.cache.fetch(['users', id, 'todos_pending_count'], force: force, expires_in: 20.minutes) do
+ Rails.cache.fetch(["users", id, "todos_pending_count"], force: force, expires_in: 20.minutes) do
TodosFinder.new(self, state: :pending).execute.count
end
end
def personal_projects_count(force: false)
- Rails.cache.fetch(['users', id, 'personal_projects_count'], force: force, expires_in: 24.hours, raw: true) do
+ Rails.cache.fetch(["users", id, "personal_projects_count"], force: force, expires_in: 24.hours, raw: true) {
personal_projects.count
- end.to_i
+ }.to_i
end
def update_todos_count_cache
@@ -1289,23 +1289,23 @@ class User < ApplicationRecord
end
def invalidate_issue_cache_counts
- Rails.cache.delete(['users', id, 'assigned_open_issues_count'])
+ Rails.cache.delete(["users", id, "assigned_open_issues_count"])
end
def invalidate_merge_request_cache_counts
- Rails.cache.delete(['users', id, 'assigned_open_merge_requests_count'])
+ Rails.cache.delete(["users", id, "assigned_open_merge_requests_count"])
end
def invalidate_todos_done_count
- Rails.cache.delete(['users', id, 'todos_done_count'])
+ Rails.cache.delete(["users", id, "todos_done_count"])
end
def invalidate_todos_pending_count
- Rails.cache.delete(['users', id, 'todos_pending_count'])
+ Rails.cache.delete(["users", id, "todos_pending_count"])
end
def invalidate_personal_projects_count
- Rails.cache.delete(['users', id, 'personal_projects_count'])
+ Rails.cache.delete(["users", id, "personal_projects_count"])
end
# This is copied from Devise::Models::Lockable#valid_for_authentication?, as our auth
@@ -1339,9 +1339,9 @@ class User < ApplicationRecord
def access_level=(new_level)
new_level = new_level.to_s
- return unless %w(admin regular).include?(new_level)
+ return unless %w[admin regular].include?(new_level)
- self.admin = (new_level == 'admin')
+ self.admin = (new_level == "admin")
end
# Does the user have access to all private groups & projects?
@@ -1354,7 +1354,7 @@ class User < ApplicationRecord
periods = expanded_groups_requiring_two_factor_authentication.pluck(:two_factor_grace_period)
self.require_two_factor_authentication_from_group = periods.any?
- self.two_factor_grace_period = periods.min || User.column_defaults['two_factor_grace_period']
+ self.two_factor_grace_period = periods.min || User.column_defaults["two_factor_grace_period"]
save
end
@@ -1394,8 +1394,8 @@ class User < ApplicationRecord
def max_member_access_for_project_ids(project_ids)
max_member_access_for_resource_ids(Project, project_ids) do |project_ids|
project_authorizations.where(project: project_ids)
- .group(:project_id)
- .maximum(:access_level)
+ .group(:project_id)
+ .maximum(:access_level)
end
end
@@ -1426,7 +1426,7 @@ class User < ApplicationRecord
end
def requires_usage_stats_consent?
- !consented_usage_stats? && 7.days.ago > self.created_at && !has_current_license? && User.single_user?
+ !consented_usage_stats? && 7.days.ago > created_at && !has_current_license? && User.single_user?
end
# Avoid migrations only building user preference object when needed.
@@ -1443,7 +1443,7 @@ class User < ApplicationRecord
end
# @deprecated
- alias_method :owned_or_masters_groups, :owned_or_maintainers_groups
+ alias owned_or_masters_groups owned_or_maintainers_groups
protected
@@ -1461,7 +1461,7 @@ class User < ApplicationRecord
end
def consented_usage_stats?
- Gitlab::CurrentSettings.usage_stats_set_by_user_id == self.id
+ Gitlab::CurrentSettings.usage_stats_set_by_user_id == id
end
# Added according to https://github.com/plataformatec/devise/blob/7df57d5081f9884849ca15e4fde179ef164a575f/README.md#activejob-integration
@@ -1498,7 +1498,7 @@ class User < ApplicationRecord
if Gitlab::CurrentSettings.domain_blacklist_enabled?
blocked_domains = Gitlab::CurrentSettings.domain_blacklist
if domain_matches?(blocked_domains, email)
- error = 'is not from an allowed domain.'
+ error = "is not from an allowed domain."
valid = false
end
end
@@ -1521,7 +1521,7 @@ class User < ApplicationRecord
def domain_matches?(email_domains, email)
signup_domain = Mail::Address.new(email).domain
email_domains.any? do |domain|
- escaped = Regexp.escape(domain).gsub('\*', '.*?')
+ escaped = Regexp.escape(domain).gsub('\*', ".*?")
regexp = Regexp.new "^#{escaped}$", Regexp::IGNORECASE
signup_domain =~ regexp
end
@@ -1553,9 +1553,9 @@ class User < ApplicationRecord
username = uniquify.string(username) { |s| User.find_by_username(s) }
- email = uniquify.string(-> (n) { Kernel.sprintf(email_pattern, n) }) do |s|
+ email = uniquify.string(->(n) { Kernel.sprintf(email_pattern, n) }) { |s|
User.find_by_email(s)
- end
+ }
user = scope.build(
username: username,
diff --git a/app/models/user_callout.rb b/app/models/user_callout.rb
index 76e7bc06b4e..f0270dfbde4 100644
--- a/app/models/user_callout.rb
+++ b/app/models/user_callout.rb
@@ -10,6 +10,6 @@ class UserCallout < ActiveRecord::Base
validates :user, presence: true
validates :feature_name,
presence: true,
- uniqueness: { scope: :user_id },
- inclusion: { in: UserCallout.feature_names.keys }
+ uniqueness: {scope: :user_id},
+ inclusion: {in: UserCallout.feature_names.keys}
end
diff --git a/app/models/user_callout_enums.rb b/app/models/user_callout_enums.rb
index b9373ae6166..68199909b92 100644
--- a/app/models/user_callout_enums.rb
+++ b/app/models/user_callout_enums.rb
@@ -10,7 +10,7 @@ module UserCalloutEnums
{
gke_cluster_integration: 1,
gcp_signup_offer: 2,
- cluster_security_warning: 3
+ cluster_security_warning: 3,
}
end
end
diff --git a/app/models/user_custom_attribute.rb b/app/models/user_custom_attribute.rb
index e0ffe8ebbfd..c4d6fea9a4e 100644
--- a/app/models/user_custom_attribute.rb
+++ b/app/models/user_custom_attribute.rb
@@ -4,5 +4,5 @@ class UserCustomAttribute < ActiveRecord::Base
belongs_to :user
validates :user_id, :key, :value, presence: true
- validates :key, uniqueness: { scope: [:user_id] }
+ validates :key, uniqueness: {scope: [:user_id]}
end
diff --git a/app/models/user_interacted_project.rb b/app/models/user_interacted_project.rb
index ae6778e49be..308211c0b96 100644
--- a/app/models/user_interacted_project.rb
+++ b/app/models/user_interacted_project.rb
@@ -21,21 +21,19 @@ class UserInteractedProject < ActiveRecord::Base
attributes = {
project_id: event.project_id,
- user_id: event.author_id
+ user_id: event.author_id,
}
cached_exists?(attributes) do
transaction(requires_new: true) do
- begin
- where(attributes).select(1).first || create!(attributes)
- true # not caching the whole record here for now
- rescue ActiveRecord::RecordNotUnique
- # Note, above queries are not atomic and prone
- # to race conditions (similar like #find_or_create!).
- # In the case where we hit this, the record we want
- # already exists - shortcut and return.
- true
- end
+ where(attributes).select(1).first || create!(attributes)
+ true # not caching the whole record here for now
+ rescue ActiveRecord::RecordNotUnique
+ # Note, above queries are not atomic and prone
+ # to race conditions (similar like #find_or_create!).
+ # In the case where we hit this, the record we want
+ # already exists - shortcut and return.
+ true
end
end
end
diff --git a/app/models/user_preference.rb b/app/models/user_preference.rb
index 32d0407800f..c3ec04ea12e 100644
--- a/app/models/user_preference.rb
+++ b/app/models/user_preference.rb
@@ -4,25 +4,25 @@ class UserPreference < ActiveRecord::Base
# We could use enums, but Rails 4 doesn't support multiple
# enum options with same name for multiple fields, also it creates
# extra methods that aren't really needed here.
- NOTES_FILTERS = { all_notes: 0, only_comments: 1, only_activity: 2 }.freeze
+ NOTES_FILTERS = {all_notes: 0, only_comments: 1, only_activity: 2}.freeze
belongs_to :user
- validates :issue_notes_filter, :merge_request_notes_filter, inclusion: { in: NOTES_FILTERS.values }, presence: true
+ validates :issue_notes_filter, :merge_request_notes_filter, inclusion: {in: NOTES_FILTERS.values}, presence: true
class << self
def notes_filters
{
- s_('Notes|Show all activity') => NOTES_FILTERS[:all_notes],
- s_('Notes|Show comments only') => NOTES_FILTERS[:only_comments],
- s_('Notes|Show history only') => NOTES_FILTERS[:only_activity]
+ s_("Notes|Show all activity") => NOTES_FILTERS[:all_notes],
+ s_("Notes|Show comments only") => NOTES_FILTERS[:only_comments],
+ s_("Notes|Show history only") => NOTES_FILTERS[:only_activity],
}
end
end
def set_notes_filter(filter_id, issuable)
# No need to update the column if the value is already set.
- if filter_id && NOTES_FILTERS.values.include?(filter_id)
+ if filter_id && NOTES_FILTERS.value?(filter_id)
field = notes_filter_field_for(issuable)
self[field] = filter_id
diff --git a/app/models/user_status.rb b/app/models/user_status.rb
index 2bbb0c59ac1..3f19dec1cf4 100644
--- a/app/models/user_status.rb
+++ b/app/models/user_status.rb
@@ -5,13 +5,13 @@ class UserStatus < ActiveRecord::Base
self.primary_key = :user_id
- DEFAULT_EMOJI = 'speech_balloon'.freeze
+ DEFAULT_EMOJI = "speech_balloon"
belongs_to :user
validates :user, presence: true
- validates :emoji, inclusion: { in: Gitlab::Emoji.emojis_names }
- validates :message, length: { maximum: 100 }, allow_blank: true
+ validates :emoji, inclusion: {in: Gitlab::Emoji.emojis_names}
+ validates :message, length: {maximum: 100}, allow_blank: true
cache_markdown_field :message, pipeline: :emoji
end
diff --git a/app/models/users_star_project.rb b/app/models/users_star_project.rb
index bdaf58ae1c1..cd8a2cb57ed 100644
--- a/app/models/users_star_project.rb
+++ b/app/models/users_star_project.rb
@@ -5,6 +5,6 @@ class UsersStarProject < ActiveRecord::Base
belongs_to :user
validates :user, presence: true
- validates :user_id, uniqueness: { scope: [:project_id] }
+ validates :user_id, uniqueness: {scope: [:project_id]}
validates :project, presence: true
end
diff --git a/app/models/wiki_directory.rb b/app/models/wiki_directory.rb
index 712ba79bbd2..3bb18c764c9 100644
--- a/app/models/wiki_directory.rb
+++ b/app/models/wiki_directory.rb
@@ -15,6 +15,6 @@ class WikiDirectory
# Relative path to the partial to be used when rendering collections
# of this object.
def to_partial_path
- 'projects/wikis/wiki_directory'
+ "projects/wikis/wiki_directory"
end
end
diff --git a/app/models/wiki_page.rb b/app/models/wiki_page.rb
index b1d6d461928..1405c097828 100644
--- a/app/models/wiki_page.rb
+++ b/app/models/wiki_page.rb
@@ -11,11 +11,11 @@ class WikiPage
extend ActiveModel::Naming
def self.primary_key
- 'slug'
+ "slug"
end
def self.model_name
- ActiveModel::Name.new(self, nil, 'wiki')
+ ActiveModel::Name.new(self, nil, "wiki")
end
# Sorts and groups pages by directory.
@@ -30,18 +30,18 @@ class WikiPage
pages.sort_by { |page| [page.directory, page.slug] }
.group_by(&:directory)
- .map do |dir, pages|
+ .map { |dir, pages|
if dir.present?
WikiDirectory.new(dir, pages)
else
pages
end
- end
+ }
.flatten
end
def self.unhyphenize(name)
- name.gsub(/-+/, ' ')
+ name.gsub(/-+/, " ")
end
def to_key
@@ -83,10 +83,10 @@ class WikiPage
end
end
- alias_method :to_param, :slug
+ alias to_param slug
def human_title
- return 'Home' if title == 'home'
+ return "Home" if title == "home"
title
end
@@ -256,7 +256,7 @@ class WikiPage
# Relative path to the partial to be used when rendering collections
# of this object.
def to_partial_path
- 'projects/wikis/wiki_page'
+ "projects/wikis/wiki_page"
end
def id
@@ -286,8 +286,8 @@ class WikiPage
current_dirname = File.dirname(title)
if @page.present?
- return title[1..-1] if current_dirname == '/'
- return File.join([directory.presence, title].compact) if current_dirname == '.'
+ return title[1..-1] if current_dirname == "/"
+ return File.join([directory.presence, title].compact) if current_dirname == "."
end
title