diff options
Diffstat (limited to 'app')
1061 files changed, 7765 insertions, 7742 deletions
diff --git a/app/controllers/abuse_reports_controller.rb b/app/controllers/abuse_reports_controller.rb index 68e14f0c2e5..10c9de2d177 100644 --- a/app/controllers/abuse_reports_controller.rb +++ b/app/controllers/abuse_reports_controller.rb @@ -6,7 +6,7 @@ class AbuseReportsController < ApplicationController def new @abuse_report = AbuseReport.new @abuse_report.user_id = @user.id - @ref_url = params.fetch(:ref_url, '') + @ref_url = params.fetch(:ref_url, "") end def create @@ -26,10 +26,10 @@ class AbuseReportsController < ApplicationController private def report_params - params.require(:abuse_report).permit(%i( + params.require(:abuse_report).permit(%i[ message user_id - )) + ]) end # rubocop: disable CodeReuse/ActiveRecord diff --git a/app/controllers/admin/appearances_controller.rb b/app/controllers/admin/appearances_controller.rb index 189fee98aa0..664bb99c95c 100644 --- a/app/controllers/admin/appearances_controller.rb +++ b/app/controllers/admin/appearances_controller.rb @@ -7,24 +7,24 @@ class Admin::AppearancesController < Admin::ApplicationController end def preview_sign_in - render 'preview_sign_in', layout: 'devise' + render "preview_sign_in", layout: "devise" end def create @appearance = Appearance.new(appearance_params) if @appearance.save - redirect_to admin_appearances_path, notice: 'Appearance was successfully created.' + redirect_to admin_appearances_path, notice: "Appearance was successfully created." else - render action: 'show' + render action: "show" end end def update if @appearance.update(appearance_params) - redirect_to admin_appearances_path, notice: 'Appearance was successfully updated.' + redirect_to admin_appearances_path, notice: "Appearance was successfully updated." else - render action: 'show' + render action: "show" end end @@ -33,21 +33,21 @@ class Admin::AppearancesController < Admin::ApplicationController @appearance.save - redirect_to admin_appearances_path, notice: 'Logo was successfully removed.' + redirect_to admin_appearances_path, notice: "Logo was successfully removed." end def header_logos @appearance.remove_header_logo! @appearance.save - redirect_to admin_appearances_path, notice: 'Header logo was successfully removed.' + redirect_to admin_appearances_path, notice: "Header logo was successfully removed." end def favicon @appearance.remove_favicon! @appearance.save - redirect_to admin_appearances_path, notice: 'Favicon was successfully removed.' + redirect_to admin_appearances_path, notice: "Favicon was successfully removed." end private diff --git a/app/controllers/admin/application_controller.rb b/app/controllers/admin/application_controller.rb index ef182b981f1..2466b8c68df 100644 --- a/app/controllers/admin/application_controller.rb +++ b/app/controllers/admin/application_controller.rb @@ -5,7 +5,7 @@ # Automatically sets the layout and ensures an administrator is logged in class Admin::ApplicationController < ApplicationController before_action :authenticate_admin! - layout 'admin' + layout "admin" def authenticate_admin! render_404 unless current_user.admin? diff --git a/app/controllers/admin/application_settings_controller.rb b/app/controllers/admin/application_settings_controller.rb index 8f267eccc8a..eb8fddbb626 100644 --- a/app/controllers/admin/application_settings_controller.rb +++ b/app/controllers/admin/application_settings_controller.rb @@ -48,7 +48,7 @@ class Admin::ApplicationSettingsController < Admin::ApplicationController respond_to do |format| if successful format.json { head :ok } - format.html { redirect_to redirect_path, notice: 'Application settings saved successfully' } + format.html { redirect_to redirect_path, notice: "Application settings saved successfully" } else format.json { head :bad_request } format.html { render :show } @@ -61,7 +61,7 @@ class Admin::ApplicationSettingsController < Admin::ApplicationController format.html do usage_data_json = JSON.pretty_generate(Gitlab::UsageData.data) - render html: Gitlab::Highlight.highlight('payload.json', usage_data_json, language: 'json') + render html: Gitlab::Highlight.highlight("payload.json", usage_data_json, language: "json") end format.json { render json: Gitlab::UsageData.to_json } end @@ -70,13 +70,13 @@ class Admin::ApplicationSettingsController < Admin::ApplicationController def reset_registration_token @application_setting.reset_runners_registration_token! - flash[:notice] = 'New runners registration token has been generated!' + flash[:notice] = "New runners registration token has been generated!" redirect_to admin_runners_path end def reset_health_check_token @application_setting.reset_health_check_access_token! - flash[:notice] = 'New health check access token has been generated!' + flash[:notice] = "New health check access token has been generated!" redirect_back_or_default end @@ -85,7 +85,7 @@ class Admin::ApplicationSettingsController < Admin::ApplicationController redirect_to( admin_application_settings_path, - notice: 'Started asynchronous removal of all repository check states.' + notice: "Started asynchronous removal of all repository check states." ) end @@ -129,7 +129,7 @@ class Admin::ApplicationSettingsController < Admin::ApplicationController disabled_oauth_sign_in_sources: [], import_sources: [], repository_storages: [], - restricted_visibility_levels: [] + restricted_visibility_levels: [], ] end end diff --git a/app/controllers/admin/applications_controller.rb b/app/controllers/admin/applications_controller.rb index 6fc336714b6..6489fa8f376 100644 --- a/app/controllers/admin/applications_controller.rb +++ b/app/controllers/admin/applications_controller.rb @@ -34,7 +34,7 @@ class Admin::ApplicationsController < Admin::ApplicationController def update if @application.update(application_params) - redirect_to admin_application_path(@application), notice: 'Application was successfully updated.' + redirect_to admin_application_path(@application), notice: "Application was successfully updated." else render :edit end @@ -42,7 +42,7 @@ class Admin::ApplicationsController < Admin::ApplicationController def destroy @application.destroy - redirect_to admin_applications_url, status: 302, notice: 'Application was successfully destroyed.' + redirect_to admin_applications_url, status: 302, notice: "Application was successfully destroyed." end private diff --git a/app/controllers/admin/broadcast_messages_controller.rb b/app/controllers/admin/broadcast_messages_controller.rb index a91d9a534cd..dbd3469f232 100644 --- a/app/controllers/admin/broadcast_messages_controller.rb +++ b/app/controllers/admin/broadcast_messages_controller.rb @@ -19,7 +19,7 @@ class Admin::BroadcastMessagesController < Admin::ApplicationController @broadcast_message = BroadcastMessage.new(broadcast_message_params) if @broadcast_message.save - redirect_to admin_broadcast_messages_path, notice: 'Broadcast Message was successfully created.' + redirect_to admin_broadcast_messages_path, notice: "Broadcast Message was successfully created." else render :index end @@ -27,7 +27,7 @@ class Admin::BroadcastMessagesController < Admin::ApplicationController def update if @broadcast_message.update(broadcast_message_params) - redirect_to admin_broadcast_messages_path, notice: 'Broadcast Message was successfully updated.' + redirect_to admin_broadcast_messages_path, notice: "Broadcast Message was successfully updated." else render :edit end @@ -37,14 +37,14 @@ class Admin::BroadcastMessagesController < Admin::ApplicationController @broadcast_message.destroy respond_to do |format| - format.html { redirect_back_or_default(default: { action: 'index' }) } + format.html { redirect_back_or_default(default: {action: "index"}) } format.js { head :ok } end end def preview broadcast_message = BroadcastMessage.new(broadcast_message_params) - render json: { message: render_broadcast_message(broadcast_message) } + render json: {message: render_broadcast_message(broadcast_message)} end protected @@ -54,12 +54,12 @@ class Admin::BroadcastMessagesController < Admin::ApplicationController end def broadcast_message_params - params.require(:broadcast_message).permit(%i( + params.require(:broadcast_message).permit(%i[ color ends_at font message starts_at - )) + ]) end end diff --git a/app/controllers/admin/dashboard_controller.rb b/app/controllers/admin/dashboard_controller.rb index 23cc9ee247a..b59844bff58 100644 --- a/app/controllers/admin/dashboard_controller.rb +++ b/app/controllers/admin/dashboard_controller.rb @@ -4,7 +4,7 @@ class Admin::DashboardController < Admin::ApplicationController include CountHelper COUNTED_ITEMS = [Project, User, Group, ForkNetworkMember, ForkNetwork, Issue, - MergeRequest, Note, Snippet, Key, Milestone].freeze + MergeRequest, Note, Snippet, Key, Milestone,].freeze # rubocop: disable CodeReuse/ActiveRecord def index diff --git a/app/controllers/admin/deploy_keys_controller.rb b/app/controllers/admin/deploy_keys_controller.rb index 49ce275ad14..c76adcc1852 100644 --- a/app/controllers/admin/deploy_keys_controller.rb +++ b/app/controllers/admin/deploy_keys_controller.rb @@ -16,7 +16,7 @@ class Admin::DeployKeysController < Admin::ApplicationController if @deploy_key.persisted? redirect_to admin_deploy_keys_path else - render 'new' + render "new" end end @@ -25,10 +25,10 @@ class Admin::DeployKeysController < Admin::ApplicationController def update if deploy_key.update(update_params) - flash[:notice] = 'Deploy key was successfully updated.' + flash[:notice] = "Deploy key was successfully updated." redirect_to admin_deploy_keys_path else - render 'edit' + render "edit" end end diff --git a/app/controllers/admin/groups_controller.rb b/app/controllers/admin/groups_controller.rb index 46e85e1424f..a2f3b2b8e52 100644 --- a/app/controllers/admin/groups_controller.rb +++ b/app/controllers/admin/groups_controller.rb @@ -14,11 +14,13 @@ class Admin::GroupsController < Admin::ApplicationController # rubocop: disable CodeReuse/ActiveRecord def show - @group = Group.with_statistics.joins(:route).group('routes.path').find_by_full_path(params[:id]) + @group = Group.with_statistics.joins(:route).group("routes.path").find_by_full_path(params[:id]) @members = present_members( - @group.members.order("access_level DESC").page(params[:members_page])) + @group.members.order("access_level DESC").page(params[:members_page]) + ) @requesters = present_members( - AccessRequestsFinder.new(@group).execute(current_user)) + AccessRequestsFinder.new(@group).execute(current_user) + ) @projects = @group.projects.with_statistics.page(params[:projects_page]) end # rubocop: enable CodeReuse/ActiveRecord @@ -44,7 +46,7 @@ class Admin::GroupsController < Admin::ApplicationController def update if @group.update(group_params) - redirect_to [:admin, @group], notice: 'Group was successfully updated.' + redirect_to [:admin, @group], notice: "Group was successfully updated." else render "edit" end @@ -55,7 +57,7 @@ class Admin::GroupsController < Admin::ApplicationController result = Members::CreateService.new(current_user, member_params.merge(limit: -1)).execute(@group) if result[:status] == :success - redirect_to [:admin, @group], notice: 'Users were successfully added.' + redirect_to [:admin, @group], notice: "Users were successfully added." else redirect_to [:admin, @group], alert: result[:message] end @@ -65,8 +67,8 @@ class Admin::GroupsController < Admin::ApplicationController Groups::DestroyService.new(@group, current_user).async_execute redirect_to admin_groups_path, - status: 302, - alert: "Group '#{@group.name}' was scheduled for deletion." + status: 302, + alert: "Group '#{@group.name}' was scheduled for deletion." end private @@ -89,7 +91,7 @@ class Admin::GroupsController < Admin::ApplicationController :request_access_enabled, :visibility_level, :require_two_factor_authentication, - :two_factor_grace_period + :two_factor_grace_period, ] end end diff --git a/app/controllers/admin/health_check_controller.rb b/app/controllers/admin/health_check_controller.rb index 7cd80e8b5e1..daf19f2aa63 100644 --- a/app/controllers/admin/health_check_controller.rb +++ b/app/controllers/admin/health_check_controller.rb @@ -8,6 +8,6 @@ class Admin::HealthCheckController < Admin::ApplicationController private def checks - ['standard'] + ["standard"] end end diff --git a/app/controllers/admin/hooks_controller.rb b/app/controllers/admin/hooks_controller.rb index d0abdec50ae..1100bf8c9f6 100644 --- a/app/controllers/admin/hooks_controller.rb +++ b/app/controllers/admin/hooks_controller.rb @@ -14,7 +14,7 @@ class Admin::HooksController < Admin::ApplicationController @hook = SystemHook.new(hook_params.to_h) if @hook.save - redirect_to admin_hooks_path, notice: 'Hook was successfully created.' + redirect_to admin_hooks_path, notice: "Hook was successfully created." else @hooks = SystemHook.all render :index @@ -26,10 +26,10 @@ class Admin::HooksController < Admin::ApplicationController def update if hook.update(hook_params) - flash[:notice] = 'System hook was successfully updated.' + flash[:notice] = "System hook was successfully updated." redirect_to admin_hooks_path else - render 'edit' + render "edit" end end diff --git a/app/controllers/admin/identities_controller.rb b/app/controllers/admin/identities_controller.rb index b51c2f678ca..714f7838eca 100644 --- a/app/controllers/admin/identities_controller.rb +++ b/app/controllers/admin/identities_controller.rb @@ -13,7 +13,7 @@ class Admin::IdentitiesController < Admin::ApplicationController @identity.user_id = user.id if @identity.save - redirect_to admin_user_identities_path(@user), notice: 'User identity was successfully created.' + redirect_to admin_user_identities_path(@user), notice: "User identity was successfully created." else render :new end @@ -29,7 +29,7 @@ class Admin::IdentitiesController < Admin::ApplicationController def update if @identity.update(identity_params) RepairLdapBlockedUserService.new(@user).execute - redirect_to admin_user_identities_path(@user), notice: 'User identity was successfully updated.' + redirect_to admin_user_identities_path(@user), notice: "User identity was successfully updated." else render :edit end @@ -38,9 +38,9 @@ class Admin::IdentitiesController < Admin::ApplicationController def destroy if @identity.destroy RepairLdapBlockedUserService.new(@user).execute - redirect_to admin_user_identities_path(@user), status: 302, notice: 'User identity was successfully removed.' + redirect_to admin_user_identities_path(@user), status: 302, notice: "User identity was successfully removed." else - redirect_to admin_user_identities_path(@user), status: 302, alert: 'Failed to remove user identity.' + redirect_to admin_user_identities_path(@user), status: 302, alert: "Failed to remove user identity." end end diff --git a/app/controllers/admin/impersonation_tokens_controller.rb b/app/controllers/admin/impersonation_tokens_controller.rb index 706bcc1e549..bbb7e76d918 100644 --- a/app/controllers/admin/impersonation_tokens_controller.rb +++ b/app/controllers/admin/impersonation_tokens_controller.rb @@ -40,7 +40,7 @@ class Admin::ImpersonationTokensController < Admin::ApplicationController # rubocop: enable CodeReuse/ActiveRecord def finder(options = {}) - PersonalAccessTokensFinder.new({ user: user, impersonation: true }.merge(options)) + PersonalAccessTokensFinder.new({user: user, impersonation: true}.merge(options)) end def impersonation_token_params @@ -52,8 +52,8 @@ class Admin::ImpersonationTokensController < Admin::ApplicationController @scopes = Gitlab::Auth.available_scopes(current_user) @impersonation_token ||= finder.build - @inactive_impersonation_tokens = finder(state: 'inactive').execute - @active_impersonation_tokens = finder(state: 'active').execute.order(:expires_at) + @inactive_impersonation_tokens = finder(state: "inactive").execute + @active_impersonation_tokens = finder(state: "active").execute.order(:expires_at) @new_impersonation_token = PersonalAccessToken.redis_getdel(current_user.id) end diff --git a/app/controllers/admin/impersonations_controller.rb b/app/controllers/admin/impersonations_controller.rb index 65fe22bd8f4..f0e160258f8 100644 --- a/app/controllers/admin/impersonations_controller.rb +++ b/app/controllers/admin/impersonations_controller.rb @@ -12,6 +12,6 @@ class Admin::ImpersonationsController < Admin::ApplicationController private def authenticate_impersonator! - render_404 unless impersonator && impersonator.admin? && !impersonator.blocked? + render_404 unless impersonator&.admin? && !impersonator.blocked? end end diff --git a/app/controllers/admin/jobs_controller.rb b/app/controllers/admin/jobs_controller.rb index 0c1afdc3d3b..fc8e9f5b5e3 100644 --- a/app/controllers/admin/jobs_controller.rb +++ b/app/controllers/admin/jobs_controller.rb @@ -5,14 +5,14 @@ class Admin::JobsController < Admin::ApplicationController def index @scope = params[:scope] @all_builds = Ci::Build - @builds = @all_builds.order('id DESC') + @builds = @all_builds.order("id DESC") @builds = case @scope - when 'pending' + when "pending" @builds.pending.reverse_order - when 'running' + when "running" @builds.running.reverse_order - when 'finished' + when "finished" @builds.finished else @builds diff --git a/app/controllers/admin/keys_controller.rb b/app/controllers/admin/keys_controller.rb index 4e9262ccc96..5dfcac07988 100644 --- a/app/controllers/admin/keys_controller.rb +++ b/app/controllers/admin/keys_controller.rb @@ -17,9 +17,9 @@ class Admin::KeysController < Admin::ApplicationController respond_to do |format| if key.destroy - format.html { redirect_to keys_admin_user_path(user), status: 302, notice: 'User key was successfully removed.' } + format.html { redirect_to keys_admin_user_path(user), status: 302, notice: "User key was successfully removed." } else - format.html { redirect_to keys_admin_user_path(user), status: 302, alert: 'Failed to remove user key.' } + format.html { redirect_to keys_admin_user_path(user), status: 302, alert: "Failed to remove user key." } end end end diff --git a/app/controllers/admin/labels_controller.rb b/app/controllers/admin/labels_controller.rb index aa5eae7a474..8a29bff9bbc 100644 --- a/app/controllers/admin/labels_controller.rb +++ b/app/controllers/admin/labels_controller.rb @@ -31,7 +31,7 @@ class Admin::LabelsController < Admin::ApplicationController @label = Labels::UpdateService.new(label_params).execute(@label) if @label.valid? - redirect_to admin_labels_path, notice: 'Label was successfully updated.' + redirect_to admin_labels_path, notice: "Label was successfully updated." else render :edit end @@ -43,7 +43,7 @@ class Admin::LabelsController < Admin::ApplicationController respond_to do |format| format.html do - redirect_to admin_labels_path, status: 302, notice: 'Label was removed' + redirect_to admin_labels_path, status: 302, notice: "Label was removed" end format.js end diff --git a/app/controllers/admin/logs_controller.rb b/app/controllers/admin/logs_controller.rb index 06b0e6a15a3..65cfe926cb5 100644 --- a/app/controllers/admin/logs_controller.rb +++ b/app/controllers/admin/logs_controller.rb @@ -15,7 +15,7 @@ class Admin::LogsController < Admin::ApplicationController Gitlab::EnvironmentLogger, Gitlab::SidekiqLogger, Gitlab::RepositoryCheckLogger, - Gitlab::ProjectServiceLogger + Gitlab::ProjectServiceLogger, ] end end diff --git a/app/controllers/admin/projects_controller.rb b/app/controllers/admin/projects_controller.rb index 550f29a58d2..34a7de84802 100644 --- a/app/controllers/admin/projects_controller.rb +++ b/app/controllers/admin/projects_controller.rb @@ -7,7 +7,7 @@ class Admin::ProjectsController < Admin::ApplicationController before_action :group, only: [:show, :transfer] def index - params[:sort] ||= 'latest_activity_desc' + params[:sort] ||= "latest_activity_desc" @sort = params[:sort] @projects = Admin::ProjectsFinder.new(params: params, current_user: current_user).execute @@ -15,7 +15,7 @@ class Admin::ProjectsController < Admin::ApplicationController format.html format.json do render json: { - html: view_to_html_string("admin/projects/_projects", locals: { projects: @projects }) + html: view_to_html_string("admin/projects/_projects", locals: {projects: @projects}), } end end @@ -25,13 +25,16 @@ class Admin::ProjectsController < Admin::ApplicationController def show if @group @group_members = present_members( - @group.members.order("access_level DESC").page(params[:group_members_page])) + @group.members.order("access_level DESC").page(params[:group_members_page]) + ) end @project_members = present_members( - @project.members.page(params[:project_members_page])) + @project.members.page(params[:project_members_page]) + ) @requesters = present_members( - AccessRequestsFinder.new(@project).execute(current_user)) + AccessRequestsFinder.new(@project).execute(current_user) + ) end # rubocop: enable CodeReuse/ActiveRecord @@ -50,7 +53,7 @@ class Admin::ProjectsController < Admin::ApplicationController redirect_to( admin_project_path(@project), - notice: 'Repository check was triggered.' + notice: "Repository check was triggered." ) end @@ -58,7 +61,7 @@ class Admin::ProjectsController < Admin::ApplicationController def project @project = Project.find_by_full_path( - [params[:namespace_id], '/', params[:id]].join('') + [params[:namespace_id], "/", params[:id]].join("") ) @project || render_404 end diff --git a/app/controllers/admin/requests_profiles_controller.rb b/app/controllers/admin/requests_profiles_controller.rb index 89d4c4f18d9..205447f5b9e 100644 --- a/app/controllers/admin/requests_profiles_controller.rb +++ b/app/controllers/admin/requests_profiles_controller.rb @@ -13,7 +13,7 @@ class Admin::RequestsProfilesController < Admin::ApplicationController if profile render html: profile.content.html_safe else - redirect_to admin_requests_profiles_path, alert: 'Profile not found' + redirect_to admin_requests_profiles_path, alert: "Profile not found" end end end diff --git a/app/controllers/admin/runner_projects_controller.rb b/app/controllers/admin/runner_projects_controller.rb index 774ce04d079..877ac68f8bc 100644 --- a/app/controllers/admin/runner_projects_controller.rb +++ b/app/controllers/admin/runner_projects_controller.rb @@ -9,7 +9,7 @@ class Admin::RunnerProjectsController < Admin::ApplicationController if @runner.assign_to(@project, current_user) redirect_to admin_runner_path(@runner) else - redirect_to admin_runner_path(@runner), alert: 'Failed adding runner to project' + redirect_to admin_runner_path(@runner), alert: "Failed adding runner to project" end end @@ -25,7 +25,7 @@ class Admin::RunnerProjectsController < Admin::ApplicationController def project @project = Project.find_by_full_path( - [params[:namespace_id], '/', params[:project_id]].join('') + [params[:namespace_id], "/", params[:project_id]].join("") ) @project || render_404 end diff --git a/app/controllers/admin/runners_controller.rb b/app/controllers/admin/runners_controller.rb index 8a00408001e..049f4246abc 100644 --- a/app/controllers/admin/runners_controller.rb +++ b/app/controllers/admin/runners_controller.rb @@ -22,7 +22,7 @@ class Admin::RunnersController < Admin::ApplicationController end else assign_builds_and_projects - render 'show' + render "show" end end @@ -34,17 +34,17 @@ class Admin::RunnersController < Admin::ApplicationController def resume if Ci::UpdateRunnerService.new(@runner).update(active: true) - redirect_to admin_runners_path, notice: 'Runner was successfully updated.' + redirect_to admin_runners_path, notice: "Runner was successfully updated." else - redirect_to admin_runners_path, alert: 'Runner was not updated.' + redirect_to admin_runners_path, alert: "Runner was not updated." end end def pause if Ci::UpdateRunnerService.new(@runner).update(active: false) - redirect_to admin_runners_path, notice: 'Runner was successfully updated.' + redirect_to admin_runners_path, notice: "Runner was successfully updated." else - redirect_to admin_runners_path, alert: 'Runner was not updated.' + redirect_to admin_runners_path, alert: "Runner was not updated." end end @@ -66,7 +66,7 @@ class Admin::RunnersController < Admin::ApplicationController # rubocop: disable CodeReuse/ActiveRecord def assign_builds_and_projects - @builds = runner.builds.order('id DESC').first(30) + @builds = runner.builds.order("id DESC").first(30) @projects = if params[:search].present? ::Project.search(params[:search]) diff --git a/app/controllers/admin/services_controller.rb b/app/controllers/admin/services_controller.rb index c455930c044..c4581eebf44 100644 --- a/app/controllers/admin/services_controller.rb +++ b/app/controllers/admin/services_controller.rb @@ -22,7 +22,7 @@ class Admin::ServicesController < Admin::ApplicationController PropagateServiceTemplateWorker.perform_async(service.id) if service.active? redirect_to admin_application_settings_services_path, - notice: 'Application settings saved successfully' + notice: "Application settings saved successfully" else render :edit end @@ -46,6 +46,6 @@ class Admin::ServicesController < Admin::ApplicationController # rubocop: enable CodeReuse/ActiveRecord def whitelist_query_limiting - Gitlab::QueryLimiting.whitelist('https://gitlab.com/gitlab-org/gitlab-ce/issues/42430') + Gitlab::QueryLimiting.whitelist("https://gitlab.com/gitlab-org/gitlab-ce/issues/42430") end end diff --git a/app/controllers/admin/spam_logs_controller.rb b/app/controllers/admin/spam_logs_controller.rb index 18d22c95b61..60f4ca018d8 100644 --- a/app/controllers/admin/spam_logs_controller.rb +++ b/app/controllers/admin/spam_logs_controller.rb @@ -13,8 +13,8 @@ class Admin::SpamLogsController < Admin::ApplicationController if params[:remove_user] spam_log.remove_user(deleted_by: current_user) redirect_to admin_spam_logs_path, - status: 302, - notice: "User #{spam_log.user.username} was successfully removed." + status: 302, + notice: "User #{spam_log.user.username} was successfully removed." else spam_log.destroy head :ok @@ -25,9 +25,9 @@ class Admin::SpamLogsController < Admin::ApplicationController spam_log = SpamLog.find(params[:id]) if HamService.new(spam_log).mark_as_ham! - redirect_to admin_spam_logs_path, notice: 'Spam log successfully submitted as ham.' + redirect_to admin_spam_logs_path, notice: "Spam log successfully submitted as ham." else - redirect_to admin_spam_logs_path, alert: 'Error with Akismet. Please check the logs for more info.' + redirect_to admin_spam_logs_path, alert: "Error with Akismet. Please check the logs for more info." end end end diff --git a/app/controllers/admin/system_info_controller.rb b/app/controllers/admin/system_info_controller.rb index 244fc2b31bb..bc4268fb8db 100644 --- a/app/controllers/admin/system_info_controller.rb +++ b/app/controllers/admin/system_info_controller.rb @@ -2,43 +2,51 @@ class Admin::SystemInfoController < Admin::ApplicationController EXCLUDED_MOUNT_OPTIONS = [ - 'nobrowse', - 'read-only', - 'ro' + "nobrowse", + "read-only", + "ro", ].freeze EXCLUDED_MOUNT_TYPES = [ - 'autofs', - 'binfmt_misc', - 'cgroup', - 'debugfs', - 'devfs', - 'devpts', - 'devtmpfs', - 'efivarfs', - 'fuse.gvfsd-fuse', - 'fuseblk', - 'fusectl', - 'hugetlbfs', - 'mqueue', - 'proc', - 'pstore', - 'rpc_pipefs', - 'securityfs', - 'sysfs', - 'tmpfs', - 'tracefs', - 'vfat' + "autofs", + "binfmt_misc", + "cgroup", + "debugfs", + "devfs", + "devpts", + "devtmpfs", + "efivarfs", + "fuse.gvfsd-fuse", + "fuseblk", + "fusectl", + "hugetlbfs", + "mqueue", + "proc", + "pstore", + "rpc_pipefs", + "securityfs", + "sysfs", + "tmpfs", + "tracefs", + "vfat", ].freeze def show - @cpus = Vmstat.cpu rescue nil - @memory = Vmstat.memory rescue nil + @cpus = begin + Vmstat.cpu + rescue + nil + end + @memory = begin + Vmstat.memory + rescue + nil + end mounts = Sys::Filesystem.mounts @disks = [] mounts.each do |mount| - mount_options = mount.options.split(',') + mount_options = mount.options.split(",") next if (EXCLUDED_MOUNT_OPTIONS & mount_options).any? next if (EXCLUDED_MOUNT_TYPES & [mount.mount_type]).any? @@ -47,9 +55,9 @@ class Admin::SystemInfoController < Admin::ApplicationController disk = Sys::Filesystem.stat(mount.mount_point) @disks.push({ bytes_total: disk.bytes_total, - bytes_used: disk.bytes_used, - disk_name: mount.name, - mount_path: disk.path + bytes_used: disk.bytes_used, + disk_name: mount.name, + mount_path: disk.path, }) rescue Sys::Filesystem::Error end diff --git a/app/controllers/admin/users_controller.rb b/app/controllers/admin/users_controller.rb index bfa7c7d0109..17a2c7924ab 100644 --- a/app/controllers/admin/users_controller.rb +++ b/app/controllers/admin/users_controller.rb @@ -96,20 +96,20 @@ class Admin::UsersController < Admin::ApplicationController update_user { |user| user.disable_two_factor! } redirect_to admin_user_path(user), - notice: 'Two-factor Authentication has been disabled for this user' + notice: "Two-factor Authentication has been disabled for this user" end def create opts = { reset_password: true, - skip_confirmation: true + skip_confirmation: true, } @user = Users::CreateService.new(current_user, user_params.merge(opts)).execute respond_to do |format| if @user.persisted? - format.html { redirect_to [:admin, @user], notice: 'User was successfully created.' } + format.html { redirect_to [:admin, @user], notice: "User was successfully created." } format.json { render json: @user, status: :created, location: @user } else format.html { render "new" } @@ -124,7 +124,7 @@ class Admin::UsersController < Admin::ApplicationController if params[:user][:password].present? password_params = { password: params[:user][:password], - password_confirmation: params[:user][:password_confirmation] + password_confirmation: params[:user][:password_confirmation], } password_params[:password_expires_at] = Time.now unless changing_own_password? @@ -133,12 +133,12 @@ class Admin::UsersController < Admin::ApplicationController end respond_to do |format| - result = Users::UpdateService.new(current_user, user_params_with_pass.merge(user: user)).execute do |user| + result = Users::UpdateService.new(current_user, user_params_with_pass.merge(user: user)).execute { |user| user.skip_reconfirmation! - end + } if result[:status] == :success - format.html { redirect_to [:admin, user], notice: 'User was successfully updated.' } + format.html { redirect_to [:admin, user], notice: "User was successfully updated." } format.json { head :ok } else # restore username to keep form action url. @@ -164,11 +164,11 @@ class Admin::UsersController < Admin::ApplicationController respond_to do |format| if success - format.html { redirect_back_or_admin_user(notice: 'Successfully removed email.') } + format.html { redirect_back_or_admin_user(notice: "Successfully removed email.") } format.json { head :ok } else - format.html { redirect_back_or_admin_user(alert: 'There was an error removing the e-mail.') } - format.json { render json: 'There was an error removing the e-mail.', status: :bad_request } + format.html { redirect_back_or_admin_user(alert: "There was an error removing the e-mail.") } + format.json { render json: "There was an error removing the e-mail.", status: :bad_request } end end end @@ -223,7 +223,7 @@ class Admin::UsersController < Admin::ApplicationController :theme_id, :twitter, :username, - :website_url + :website_url, ] end diff --git a/app/controllers/application_controller.rb b/app/controllers/application_controller.rb index b7eb6af6d67..9f94d5eb3af 100644 --- a/app/controllers/application_controller.rb +++ b/app/controllers/application_controller.rb @@ -1,7 +1,7 @@ # frozen_string_literal: true -require 'gon' -require 'fogbugz' +require "gon" +require "fogbugz" class ApplicationController < ActionController::Base include Gitlab::GonHelper @@ -45,8 +45,8 @@ class ApplicationController < ActionController::Base # Adds `no-store` to the DEFAULT_CACHE_CONTROL, to prevent security # concerns due to caching private data. - DEFAULT_GITLAB_CACHE_CONTROL = "#{ActionDispatch::Http::Cache::Response::DEFAULT_CACHE_CONTROL}, no-store".freeze - DEFAULT_GITLAB_CONTROL_NO_CACHE = "#{DEFAULT_GITLAB_CACHE_CONTROL}, no-cache".freeze + DEFAULT_GITLAB_CACHE_CONTROL = "#{ActionDispatch::Http::Cache::Response::DEFAULT_CACHE_CONTROL}, no-store" + DEFAULT_GITLAB_CONTROL_NO_CACHE = "#{DEFAULT_GITLAB_CACHE_CONTROL}, no-cache" rescue_from Encoding::CompatibilityError do |exception| log_exception(exception) @@ -73,7 +73,7 @@ class ApplicationController < ActionController::Base rescue_from GRPC::Unavailable, Gitlab::Git::CommandError do |exception| log_exception(exception) - headers['Retry-After'] = exception.retry_after if exception.respond_to?(:retry_after) + headers["Retry-After"] = exception.retry_after if exception.respond_to?(:retry_after) render_503 end @@ -105,18 +105,18 @@ class ApplicationController < ActionController::Base return if current_user # Rack sets this header, but not all tests may have it: https://github.com/rack/rack/blob/fdcd03a3c5a1c51d1f96fc97f9dfa1a9deac0c77/lib/rack/session/abstract/id.rb#L251-L259 - return unless request.env['rack.session.options'] + return unless request.env["rack.session.options"] # This works because Rack uses these options every time a request is handled: # https://github.com/rack/rack/blob/fdcd03a3c5a1c51d1f96fc97f9dfa1a9deac0c77/lib/rack/session/abstract/id.rb#L342 - request.env['rack.session.options'][:expire_after] = Settings.gitlab['unauthenticated_session_expire_delay'] + request.env["rack.session.options"][:expire_after] = Settings.gitlab["unauthenticated_session_expire_delay"] end def render(*args) super.tap do # Set a header for custom error pages to prevent them from being intercepted by gitlab-workhorse - if response.content_type == 'text/html' && (400..599).cover?(response.status) - response.headers['X-GitLab-Custom-Error'] = '1' + if response.content_type == "text/html" && (400..599).cover?(response.status) + response.headers["X-GitLab-Custom-Error"] = "1" end end end @@ -137,7 +137,7 @@ class ApplicationController < ActionController::Base payload[:username] = logged_user.try(:username) end - if response.status == 422 && response.body.present? && response.content_type == 'application/json'.freeze + if response.status == 422 && response.body.present? && response.content_type == "application/json" payload[:response] = response.body end @@ -193,9 +193,9 @@ class ApplicationController < ActionController::Base format.any { head status } format.html do render template, - layout: "errors", - status: status, - locals: { message: message } + layout: "errors", + status: status, + locals: {message: message} end end end @@ -215,7 +215,7 @@ class ApplicationController < ActionController::Base respond_to do |format| format.html { render "errors/not_found", layout: "errors", status: 404 } # Prevent the Rails CSRF protector from thinking a missing .js file is a JavaScript file - format.js { render json: '', status: :not_found, content_type: 'application/json' } + format.js { render json: "", status: :not_found, content_type: "application/json" } format.any { head :not_found } end end @@ -238,20 +238,20 @@ class ApplicationController < ActionController::Base end def no_cache_headers - headers['Cache-Control'] = DEFAULT_GITLAB_CONTROL_NO_CACHE - headers['Pragma'] = 'no-cache' # HTTP 1.0 compatibility - headers['Expires'] = 'Fri, 01 Jan 1990 00:00:00 GMT' + headers["Cache-Control"] = DEFAULT_GITLAB_CONTROL_NO_CACHE + headers["Pragma"] = "no-cache" # HTTP 1.0 compatibility + headers["Expires"] = "Fri, 01 Jan 1990 00:00:00 GMT" end def default_headers - headers['X-Frame-Options'] = 'DENY' - headers['X-XSS-Protection'] = '1; mode=block' - headers['X-UA-Compatible'] = 'IE=edge' - headers['X-Content-Type-Options'] = 'nosniff' + headers["X-Frame-Options"] = "DENY" + headers["X-XSS-Protection"] = "1; mode=block" + headers["X-UA-Compatible"] = "IE=edge" + headers["X-Content-Type-Options"] = "nosniff" if current_user - headers['Cache-Control'] = default_cache_control - headers['Pragma'] = 'no-cache' # HTTP 1.0 compatibility + headers["Cache-Control"] = default_cache_control + headers["Pragma"] = "no-cache" # HTTP 1.0 compatibility end end @@ -266,9 +266,9 @@ class ApplicationController < ActionController::Base def validate_user_service_ticket! return unless signed_in? && session[:service_tickets] - valid = session[:service_tickets].all? do |provider, ticket| + valid = session[:service_tickets].all? { |provider, ticket| Gitlab::Auth::OAuth::Session.valid?(provider, ticket) - end + } unless valid session[:service_tickets] = nil @@ -288,7 +288,7 @@ class ApplicationController < ActionController::Base end def ldap_security_check - if current_user && current_user.requires_ldap_check? + if current_user&.requires_ldap_check? return unless current_user.try_obtain_ldap_lease unless Gitlab::Auth::LDAP::Access.allowed?(current_user) @@ -317,7 +317,7 @@ class ApplicationController < ActionController::Base render json: { html: html, - count: count + count: count, } end @@ -339,8 +339,8 @@ class ApplicationController < ActionController::Base end def require_email - if current_user && current_user.temp_oauth_email? && session[:impersonator_id].nil? - return redirect_to profile_path, notice: 'Please complete your profile with email address' + if current_user&.temp_oauth_email? && session[:impersonator_id].nil? + redirect_to profile_path, notice: "Please complete your profile with email address" end end @@ -357,10 +357,10 @@ class ApplicationController < ActionController::Base # Redirect to the source if it was a post, so the user can re-submit after # accepting the terms. redirect_path = if request.get? - request.fullpath - else - URI(request.referer).path if request.referer - end + request.fullpath + else + URI(request.referer).path if request.referer + end flash[:notice] = message redirect_to terms_path(redirect: redirect_path), status: :found @@ -372,15 +372,15 @@ class ApplicationController < ActionController::Base end def bitbucket_server_import_enabled? - Gitlab::CurrentSettings.import_sources.include?('bitbucket_server') + Gitlab::CurrentSettings.import_sources.include?("bitbucket_server") end def github_import_enabled? - Gitlab::CurrentSettings.import_sources.include?('github') + Gitlab::CurrentSettings.import_sources.include?("github") end def gitea_import_enabled? - Gitlab::CurrentSettings.import_sources.include?('gitea') + Gitlab::CurrentSettings.import_sources.include?("gitea") end def github_import_configured? @@ -388,7 +388,7 @@ class ApplicationController < ActionController::Base end def gitlab_import_enabled? - request.host != 'gitlab.com' && Gitlab::CurrentSettings.import_sources.include?('gitlab') + request.host != "gitlab.com" && Gitlab::CurrentSettings.import_sources.include?("gitlab") end def gitlab_import_configured? @@ -396,7 +396,7 @@ class ApplicationController < ActionController::Base end def bitbucket_import_enabled? - Gitlab::CurrentSettings.import_sources.include?('bitbucket') + Gitlab::CurrentSettings.import_sources.include?("bitbucket") end def bitbucket_import_configured? @@ -404,23 +404,23 @@ class ApplicationController < ActionController::Base end def google_code_import_enabled? - Gitlab::CurrentSettings.import_sources.include?('google_code') + Gitlab::CurrentSettings.import_sources.include?("google_code") end def fogbugz_import_enabled? - Gitlab::CurrentSettings.import_sources.include?('fogbugz') + Gitlab::CurrentSettings.import_sources.include?("fogbugz") end def git_import_enabled? - Gitlab::CurrentSettings.import_sources.include?('git') + Gitlab::CurrentSettings.import_sources.include?("git") end def gitlab_project_import_enabled? - Gitlab::CurrentSettings.import_sources.include?('gitlab_project') + Gitlab::CurrentSettings.import_sources.include?("gitlab_project") end def manifest_import_enabled? - Group.supports_nested_objects? && Gitlab::CurrentSettings.import_sources.include?('manifest') + Group.supports_nested_objects? && Gitlab::CurrentSettings.import_sources.include?("manifest") end # U2F (universal 2nd factor) devices need a unique identifier for the application @@ -436,11 +436,11 @@ class ApplicationController < ActionController::Base def set_page_title_header # Per https://tools.ietf.org/html/rfc5987, headers need to be ISO-8859-1, not UTF-8 - response.headers['Page-Title'] = URI.escape(page_title('GitLab')) + response.headers["Page-Title"] = URI.escape(page_title("GitLab")) end def peek_request? - request.path.start_with?('/-/peek') + request.path.start_with?("/-/peek") end def json_request? @@ -456,7 +456,7 @@ class ApplicationController < ActionController::Base def set_usage_stats_consent_flag return unless current_user return if sessionless_user? - return if session.has_key?(:ask_for_usage_stats_consent) + return if session.key?(:ask_for_usage_stats_consent) session[:ask_for_usage_stats_consent] = current_user.requires_usage_stats_consent? @@ -469,7 +469,7 @@ class ApplicationController < ActionController::Base application_setting_params = { usage_ping_enabled: false, version_check_enabled: false, - skip_usage_stats_user: true + skip_usage_stats_user: true, } settings = Gitlab::CurrentSettings.current_application_settings @@ -483,7 +483,7 @@ class ApplicationController < ActionController::Base unless Gitlab.config.gitlab.impersonation_enabled stop_impersonation - access_denied! _('Impersonation has been disabled') + access_denied! _("Impersonation has been disabled") end end diff --git a/app/controllers/boards/application_controller.rb b/app/controllers/boards/application_controller.rb index eab908ba5ed..67b70d54a3d 100644 --- a/app/controllers/boards/application_controller.rb +++ b/app/controllers/boards/application_controller.rb @@ -17,7 +17,7 @@ module Boards end def record_not_found(exception) - render json: { error: exception.message }, status: :not_found + render json: {error: exception.message}, status: :not_found end end end diff --git a/app/controllers/boards/issues_controller.rb b/app/controllers/boards/issues_controller.rb index 0dd7500623d..5afa5be8957 100644 --- a/app/controllers/boards/issues_controller.rb +++ b/app/controllers/boards/issues_controller.rb @@ -20,16 +20,15 @@ module Boards issues = issues.page(params[:page]).per(params[:per] || 20).without_count Issue.move_to_end(issues) if Gitlab::Database.read_write? issues = issues.preload(:milestone, - :assignees, - project: [ - :route, - { - namespace: [:route] - } - ], - labels: [:priorities], - notes: [:award_emoji, :author] - ) + :assignees, + project: [ + :route, + { + namespace: [:route], + }, + ], + labels: [:priorities], + notes: [:award_emoji, :author]) render_issues(issues, list_service.metadata) end @@ -59,7 +58,7 @@ module Boards private def render_issues(issues, metadata) - data = { issues: serialize_as_json(issues) } + data = {issues: serialize_as_json(issues)} data.merge!(metadata) render json: data @@ -84,10 +83,10 @@ module Boards def project @project ||= if board.group_board? - Project.find(issue_params[:project_id]) - else - board_parent - end + Project.find(issue_params[:project_id]) + else + board_parent + end end def move_params @@ -105,12 +104,12 @@ module Boards end def serialize_as_json(resource) - serializer.represent(resource, serializer: 'board', include_full_project_path: board.group_board?) + serializer.represent(resource, serializer: "board", include_full_project_path: board.group_board?) end def whitelist_query_limiting # Also see https://gitlab.com/gitlab-org/gitlab-ce/issues/42439 - Gitlab::QueryLimiting.whitelist('https://gitlab.com/gitlab-org/gitlab-ce/issues/42428') + Gitlab::QueryLimiting.whitelist("https://gitlab.com/gitlab-org/gitlab-ce/issues/42428") end end end diff --git a/app/controllers/boards/lists_controller.rb b/app/controllers/boards/lists_controller.rb index ccd02144671..fc9b35e1380 100644 --- a/app/controllers/boards/lists_controller.rb +++ b/app/controllers/boards/lists_controller.rb @@ -78,7 +78,7 @@ module Boards { only: [:id, :list_type, :position], methods: [:title], - label: true + label: true, } end end diff --git a/app/controllers/chaos_controller.rb b/app/controllers/chaos_controller.rb index 8d518c14b90..2be1fed43ec 100644 --- a/app/controllers/chaos_controller.rb +++ b/app/controllers/chaos_controller.rb @@ -41,7 +41,7 @@ class ChaosController < ActionController::Base private def validate_request - secret = ENV['GITLAB_CHAOS_SECRET'] + secret = ENV["GITLAB_CHAOS_SECRET"] # GITLAB_CHAOS_SECRET is required unless you're running in Development mode if !secret && !Rails.env.development? render plain: "chaos misconfigured: please configure GITLAB_CHAOS_SECRET when using GITLAB_ENABLE_CHAOS_ENDPOINTS outside of a development environment", status: :internal_server_error diff --git a/app/controllers/clusters/applications_controller.rb b/app/controllers/clusters/applications_controller.rb index c4e7fc950f9..54d9a36bbd2 100644 --- a/app/controllers/clusters/applications_controller.rb +++ b/app/controllers/clusters/applications_controller.rb @@ -12,7 +12,7 @@ class Clusters::ApplicationsController < Clusters::BaseController head :no_content rescue Clusters::Applications::CreateService::InvalidApplicationError render_404 - rescue StandardError + rescue head :bad_request end diff --git a/app/controllers/clusters/base_controller.rb b/app/controllers/clusters/base_controller.rb index ef42f7c4074..5a86ca39daa 100644 --- a/app/controllers/clusters/base_controller.rb +++ b/app/controllers/clusters/base_controller.rb @@ -12,7 +12,7 @@ class Clusters::BaseController < ApplicationController def cluster @cluster ||= clusterable.clusters.find(params[:id]) - .present(current_user: current_user) + .present(current_user: current_user) end def authorize_update_cluster! diff --git a/app/controllers/clusters/clusters_controller.rb b/app/controllers/clusters/clusters_controller.rb index 68a2a83f0de..9e38c74cad3 100644 --- a/app/controllers/clusters/clusters_controller.rb +++ b/app/controllers/clusters/clusters_controller.rb @@ -64,7 +64,7 @@ class Clusters::ClustersController < Clusters::BaseController head :no_content end format.html do - flash[:notice] = _('Kubernetes cluster was successfully updated.') + flash[:notice] = _("Kubernetes cluster was successfully updated.") redirect_to cluster.show_path end end @@ -78,10 +78,10 @@ class Clusters::ClustersController < Clusters::BaseController def destroy if cluster.destroy - flash[:notice] = _('Kubernetes cluster integration was successfully removed.') + flash[:notice] = _("Kubernetes cluster integration was successfully removed.") redirect_to clusterable.index_path, status: :found else - flash[:notice] = _('Kubernetes cluster integration was not removed.') + flash[:notice] = _("Kubernetes cluster integration was not removed.") render :show end end @@ -99,7 +99,7 @@ class Clusters::ClustersController < Clusters::BaseController validate_gcp_token user_cluster - render :new, locals: { active_tab: 'gcp' } + render :new, locals: {active_tab: "gcp"} end end @@ -116,7 +116,7 @@ class Clusters::ClustersController < Clusters::BaseController validate_gcp_token gcp_cluster - render :new, locals: { active_tab: 'user' } + render :new, locals: {active_tab: "user"} end end @@ -129,7 +129,7 @@ class Clusters::ClustersController < Clusters::BaseController :environment_scope, :base_domain, platform_kubernetes_attributes: [ - :namespace + :namespace, ] ) else @@ -142,7 +142,7 @@ class Clusters::ClustersController < Clusters::BaseController :api_url, :token, :ca_cert, - :namespace + :namespace, ] ) end @@ -158,12 +158,13 @@ class Clusters::ClustersController < Clusters::BaseController :zone, :num_nodes, :machine_type, - :legacy_abac - ]).merge( - provider_type: :gcp, - platform_type: :kubernetes, - clusterable: clusterable.subject - ) + :legacy_abac, + ] + ).merge( + provider_type: :gcp, + platform_type: :kubernetes, + clusterable: clusterable.subject + ) end def create_user_cluster_params @@ -176,12 +177,13 @@ class Clusters::ClustersController < Clusters::BaseController :api_url, :token, :ca_cert, - :authorization_type - ]).merge( - provider_type: :user, - platform_type: :kubernetes, - clusterable: clusterable.subject - ) + :authorization_type, + ] + ).merge( + provider_type: :user, + platform_type: :kubernetes, + clusterable: clusterable.subject + ) end def generate_gcp_authorize_url @@ -189,7 +191,8 @@ class Clusters::ClustersController < Clusters::BaseController @authorize_url = GoogleApi::CloudPlatform::Client.new( nil, callback_google_api_auth_url, - state: state).authorize_url + state: state + ).authorize_url rescue GoogleApi::Auth::ConfigMissingError # no-op end diff --git a/app/controllers/concerns/authenticates_with_two_factor.rb b/app/controllers/concerns/authenticates_with_two_factor.rb index 5507328f8ae..147267258ee 100644 --- a/app/controllers/concerns/authenticates_with_two_factor.rb +++ b/app/controllers/concerns/authenticates_with_two_factor.rb @@ -32,12 +32,12 @@ module AuthenticatesWithTwoFactor session[:otp_user_id] = user.id setup_u2f_authentication(user) - render 'devise/sessions/two_factor' + render "devise/sessions/two_factor" end def locked_user_redirect(user) - flash.now[:alert] = 'Invalid Login or password' - render 'devise/sessions/new' + flash.now[:alert] = "Invalid Login or password" + render "devise/sessions/new" end def authenticate_with_two_factor @@ -48,7 +48,7 @@ module AuthenticatesWithTwoFactor authenticate_with_two_factor_via_otp(user) elsif user_params[:device_response].present? && session[:otp_user_id] authenticate_with_two_factor_via_u2f(user) - elsif user && user.valid_password?(user_params[:password]) + elsif user&.valid_password?(user_params[:password]) prompt_for_two_factor(user) end end @@ -60,13 +60,13 @@ module AuthenticatesWithTwoFactor # Remove any lingering user data from login session.delete(:otp_user_id) - remember_me(user) if user_params[:remember_me] == '1' + remember_me(user) if user_params[:remember_me] == "1" user.save! sign_in(user, message: :two_factor_authenticated) else user.increment_failed_attempts! Gitlab::AppLogger.info("Failed Login: user=#{user.username} ip=#{request.remote_ip} method=OTP") - flash.now[:alert] = 'Invalid two-factor code.' + flash.now[:alert] = "Invalid two-factor code." prompt_for_two_factor(user) end end @@ -78,12 +78,12 @@ module AuthenticatesWithTwoFactor session.delete(:otp_user_id) session.delete(:challenge) - remember_me(user) if user_params[:remember_me] == '1' + remember_me(user) if user_params[:remember_me] == "1" sign_in(user, message: :two_factor_authenticated) else user.increment_failed_attempts! Gitlab::AppLogger.info("Failed Login: user=#{user.username} ip=#{request.remote_ip} method=U2F") - flash.now[:alert] = 'Authentication via U2F device failed.' + flash.now[:alert] = "Authentication via U2F device failed." prompt_for_two_factor(user) end end @@ -98,8 +98,8 @@ module AuthenticatesWithTwoFactor if key_handles.present? sign_requests = u2f.authentication_requests(key_handles) session[:challenge] ||= u2f.challenge - gon.push(u2f: { challenge: session[:challenge], app_id: u2f_app_id, - sign_requests: sign_requests }) + gon.push(u2f: {challenge: session[:challenge], app_id: u2f_app_id, + sign_requests: sign_requests,}) end end # rubocop: enable CodeReuse/ActiveRecord diff --git a/app/controllers/concerns/creates_commit.rb b/app/controllers/concerns/creates_commit.rb index b3777fd2b0f..7cdbe068f4d 100644 --- a/app/controllers/concerns/creates_commit.rb +++ b/app/controllers/concerns/creates_commit.rb @@ -11,7 +11,7 @@ module CreatesCommit @branch_name ||= @ref else @project_to_commit_into = current_user.fork_of(@project) - @branch_name ||= @project_to_commit_into.repository.next_branch('patch') + @branch_name ||= @project_to_commit_into.repository.next_branch("patch") end @start_branch ||= @ref || @branch_name @@ -31,7 +31,7 @@ module CreatesCommit respond_to do |format| format.html { redirect_to success_path } - format.json { render json: { message: "success", filePath: success_path } } + format.json { render json: {message: "success", filePath: success_path} } end else flash[:alert] = result[:message] @@ -45,7 +45,7 @@ module CreatesCommit redirect_to failure_path end end - format.json { render json: { message: "failed", filePath: failure_path } } + format.json { render json: {message: "failed", filePath: failure_path} } end end end @@ -90,7 +90,7 @@ module CreatesCommit source_project_id: @project_to_commit_into.id, target_project_id: @project.id, source_branch: @branch_name, - target_branch: @start_branch + target_branch: @start_branch, } ) end @@ -110,7 +110,8 @@ module CreatesCommit .find_by( source_project_id: @project_to_commit_into, source_branch: @branch_name, - target_branch: @start_branch) + target_branch: @start_branch + ) end end # rubocop: enable CodeReuse/ActiveRecord diff --git a/app/controllers/concerns/cycle_analytics_params.rb b/app/controllers/concerns/cycle_analytics_params.rb index c1ef848e1e7..6a74d660d24 100644 --- a/app/controllers/concerns/cycle_analytics_params.rb +++ b/app/controllers/concerns/cycle_analytics_params.rb @@ -4,14 +4,14 @@ module CycleAnalyticsParams extend ActiveSupport::Concern def options(params) - @options ||= { from: start_date(params), current_user: current_user } + @options ||= {from: start_date(params), current_user: current_user} end def start_date(params) case params[:start_date] - when '7' + when "7" 7.days.ago - when '30' + when "30" 30.days.ago else 90.days.ago diff --git a/app/controllers/concerns/diff_for_path.rb b/app/controllers/concerns/diff_for_path.rb index 6be7a2a18a2..b83d1a948cd 100644 --- a/app/controllers/concerns/diff_for_path.rb +++ b/app/controllers/concerns/diff_for_path.rb @@ -4,12 +4,12 @@ module DiffForPath extend ActiveSupport::Concern def render_diff_for_path(diffs) - diff_file = diffs.diff_files.find do |diff| + diff_file = diffs.diff_files.find { |diff| diff.file_identifier == params[:file_identifier] - end + } return render_404 unless diff_file - render json: { html: view_to_html_string('projects/diffs/_content', diff_file: diff_file) } + render json: {html: view_to_html_string("projects/diffs/_content", diff_file: diff_file)} end end diff --git a/app/controllers/concerns/group_tree.rb b/app/controllers/concerns/group_tree.rb index e9a7d6a3152..f6868e67c4f 100644 --- a/app/controllers/concerns/group_tree.rb +++ b/app/controllers/concerns/group_tree.rb @@ -7,11 +7,11 @@ module GroupTree groups = groups.sort_by_attribute(@sort = params[:sort]) groups = if params[:filter].present? - filtered_groups_with_ancestors(groups) - else - # If `params[:parent_id]` is `nil`, we will only show root-groups - groups.where(parent_id: params[:parent_id]).page(params[:page]) - end + filtered_groups_with_ancestors(groups) + else + # If `params[:parent_id]` is `nil`, we will only show root-groups + groups.where(parent_id: params[:parent_id]).page(params[:page]) + end @groups = groups.with_selects_for_list(archived: params[:archived]) @@ -19,7 +19,7 @@ module GroupTree format.html format.json do serializer = GroupChildSerializer.new(current_user: current_user) - .with_pagination(request, response) + .with_pagination(request, response) serializer.expand_hierarchy if params[:filter].present? render json: serializer.represent(@groups) end diff --git a/app/controllers/concerns/internal_redirect.rb b/app/controllers/concerns/internal_redirect.rb index 6785e6972d0..335fb3c1a14 100644 --- a/app/controllers/concerns/internal_redirect.rb +++ b/app/controllers/concerns/internal_redirect.rb @@ -35,7 +35,7 @@ module InternalRedirect end def full_path_for_uri(uri) - path_with_query = [uri.path, uri.query].compact.join('?') + path_with_query = [uri.path, uri.query].compact.join("?") [path_with_query, uri.fragment].compact.join("#") end diff --git a/app/controllers/concerns/issuable_actions.rb b/app/controllers/concerns/issuable_actions.rb index cd3fa641e89..c261601c95b 100644 --- a/app/controllers/concerns/issuable_actions.rb +++ b/app/controllers/concerns/issuable_actions.rb @@ -21,14 +21,14 @@ module IssuableActions :subscription_event, label_ids: [], add_label_ids: [], - remove_label_ids: [] + remove_label_ids: [], ] end def show respond_to do |format| format.html do - @issuable_sidebar = serializer.represent(issuable, serializer: 'sidebar') # rubocop:disable Gitlab/ModuleWithInstanceVariables + @issuable_sidebar = serializer.represent(issuable, serializer: "sidebar") # rubocop:disable Gitlab/ModuleWithInstanceVariables end format.json do @@ -48,7 +48,6 @@ module IssuableActions recaptcha_check_if_spammable(false) { render_entity_json } end end - rescue ActiveRecord::StaleObjectError render_conflict_response end @@ -62,7 +61,7 @@ module IssuableActions description: view_context.markdown_field(issuable, :description), description_text: issuable.description, task_status: issuable.task_status, - lock_version: issuable.lock_version + lock_version: issuable.lock_version, } if issuable.edited? @@ -85,7 +84,7 @@ module IssuableActions format.html { redirect_to index_path } format.json do render json: { - web_url: index_path + web_url: index_path, } end end @@ -95,7 +94,7 @@ module IssuableActions result = Issuable::BulkUpdateService.new(project, current_user, bulk_update_params).execute(resource_name) quantity = result[:count] - render json: { notice: "#{quantity} #{resource_name.pluralize(quantity)} updated" } + render json: {notice: "#{quantity} #{resource_name.pluralize(quantity)} updated"} end # rubocop: disable CodeReuse/ActiveRecord @@ -167,8 +166,8 @@ module IssuableActions format.json do render json: { errors: [ - "Someone edited this #{issuable.human_class_name} at the same time you did. Please refresh your browser and make sure your changes will not unintentionally remove theirs." - ] + "Someone edited this #{issuable.human_class_name} at the same time you did. Please refresh your browser and make sure your changes will not unintentionally remove theirs.", + ], }, status: :conflict end end @@ -176,13 +175,13 @@ module IssuableActions def authorize_destroy_issuable! unless can?(current_user, :"destroy_#{issuable.to_ability_name}", issuable) - return access_denied! + access_denied! end end def authorize_admin_issuable! unless can?(current_user, :"admin_#{resource_name}", @project) # rubocop:disable Gitlab/ModuleWithInstanceVariables - return access_denied! + access_denied! end end @@ -193,8 +192,8 @@ module IssuableActions def bulk_update_params permitted_keys_array = permitted_keys.dup - if resource_name == 'issue' - permitted_keys_array << { assignee_ids: [] } + if resource_name == "issue" + permitted_keys_array << {assignee_ids: []} else permitted_keys_array.unshift(:assignee_id) end @@ -211,7 +210,7 @@ module IssuableActions if @issuable.valid? render json: serializer.represent(@issuable) else - render json: { errors: @issuable.errors.full_messages }, status: :unprocessable_entity + render json: {errors: @issuable.errors.full_messages}, status: :unprocessable_entity end end # rubocop:enable Gitlab/ModuleWithInstanceVariables diff --git a/app/controllers/concerns/issuable_collections.rb b/app/controllers/concerns/issuable_collections.rb index c529aabf797..a83006ee952 100644 --- a/app/controllers/concerns/issuable_collections.rb +++ b/app/controllers/concerns/issuable_collections.rb @@ -21,7 +21,7 @@ module IssuableCollections return if redirect_out_of_range(@total_pages) if params[:label_name].present? && @project - labels_params = { project_id: @project.id, title: params[:label_name] } + labels_params = {project_id: @project.id, title: params[:label_name]} @labels = LabelsFinder.new(current_user, labels_params).execute end @@ -92,7 +92,7 @@ module IssuableCollections scope: params[:scope], state: params[:state], confidential: Gitlab::Utils.to_boolean(params[:confidential]), - sort: set_sort_order + sort: set_sort_order, } # Used by view to highlight active option @@ -111,7 +111,7 @@ module IssuableCollections # rubocop:enable Gitlab/ModuleWithInstanceVariables def default_state - 'opened' + "opened" end def set_sort_order @@ -145,7 +145,7 @@ module IssuableCollections def set_sort_order_from_cookie sort_param = params[:sort] if params[:sort].present? # fallback to legacy cookie value for backward compatibility - sort_param ||= cookies['issuable_sort'] + sort_param ||= cookies["issuable_sort"] sort_param ||= cookies[remember_sorting_key] sort_value = update_cookie_value(sort_param) @@ -159,8 +159,8 @@ module IssuableCollections def default_sort_order case params[:state] - when 'opened', 'all' then sort_value_created_date - when 'merged', 'closed' then sort_value_recently_updated + when "opened", "all" then sort_value_created_date + when "merged", "closed" then sort_value_recently_updated else sort_value_created_date end end @@ -168,10 +168,10 @@ module IssuableCollections # Update old values to the actual ones. def update_cookie_value(value) case value - when 'id_asc' then sort_value_oldest_created - when 'id_desc' then sort_value_recently_created - when 'downvotes_asc' then sort_value_popularity - when 'downvotes_desc' then sort_value_popularity + when "id_asc" then sort_value_oldest_created + when "id_desc" then sort_value_recently_created + when "downvotes_asc" then sort_value_popularity + when "downvotes_desc" then sort_value_popularity else value end end @@ -182,22 +182,22 @@ module IssuableCollections def collection_type @collection_type ||= case finder_type.name - when 'IssuesFinder' - 'Issue' - when 'MergeRequestsFinder' - 'MergeRequest' - end + when "IssuesFinder" + "Issue" + when "MergeRequestsFinder" + "MergeRequest" + end end def preload_for_collection @preload_for_collection ||= case collection_type - when 'Issue' + when "Issue" [:project, :author, :assignees, :labels, :milestone, project: :namespace] - when 'MergeRequest' + when "MergeRequest" [ :target_project, :author, :assignee, :labels, :milestone, - source_project: :route, head_pipeline: :project, target_project: :namespace, latest_merge_request_diff: :merge_request_diff_commits + source_project: :route, head_pipeline: :project, target_project: :namespace, latest_merge_request_diff: :merge_request_diff_commits, ] - end + end end end diff --git a/app/controllers/concerns/issuable_collections_action.rb b/app/controllers/concerns/issuable_collections_action.rb index 18ed4027eac..f3fb1b4cd0d 100644 --- a/app/controllers/concerns/issuable_collections_action.rb +++ b/app/controllers/concerns/issuable_collections_action.rb @@ -8,14 +8,14 @@ module IssuableCollectionsAction # rubocop:disable Gitlab/ModuleWithInstanceVariables def issues @issues = issuables_collection - .non_archived - .page(params[:page]) + .non_archived + .page(params[:page]) @issuable_meta_data = issuable_meta_data(@issues, collection_type) respond_to do |format| format.html - format.atom { render layout: 'xml.atom' } + format.atom { render layout: "xml.atom" } end end @@ -34,23 +34,19 @@ module IssuableCollectionsAction def issuable_sorting_field case action_name - when 'issues' + when "issues" Issue::SORTING_PREFERENCE_FIELD - when 'merge_requests' + when "merge_requests" MergeRequest::SORTING_PREFERENCE_FIELD - else - nil end end def finder_type case action_name - when 'issues', 'issues_calendar' + when "issues", "issues_calendar" IssuesFinder - when 'merge_requests' + when "merge_requests" MergeRequestsFinder - else - nil end end diff --git a/app/controllers/concerns/issues_calendar.rb b/app/controllers/concerns/issues_calendar.rb index 1fdfde4c869..138de7918c1 100644 --- a/app/controllers/concerns/issues_calendar.rb +++ b/app/controllers/concerns/issues_calendar.rb @@ -7,9 +7,9 @@ module IssuesCalendar # rubocop: disable CodeReuse/ActiveRecord def render_issues_calendar(issuables) @issues = issuables - .non_archived - .with_due_date - .limit(100) + .non_archived + .with_due_date + .limit(100) respond_to do |format| format.ics do @@ -18,7 +18,7 @@ module IssuesCalendar # header). We want to display the content inline when accessed # from GitLab, similarly to the RSS feed. if request.referer&.start_with?(::Settings.gitlab.base_url) - response.headers['Content-Type'] = 'text/plain' + response.headers["Content-Type"] = "text/plain" end end end diff --git a/app/controllers/concerns/labels_as_hash.rb b/app/controllers/concerns/labels_as_hash.rb index 1171aa9cf44..56bec5ce32e 100644 --- a/app/controllers/concerns/labels_as_hash.rb +++ b/app/controllers/concerns/labels_as_hash.rb @@ -16,7 +16,7 @@ module LabelsAsHash if already_set_labels.present? titles = already_set_labels.map(&:title) label_hashes.each do |hash| - if titles.include?(hash['title']) + if titles.include?(hash["title"]) hash[:set] = true end end diff --git a/app/controllers/concerns/lfs_request.rb b/app/controllers/concerns/lfs_request.rb index 57e444319e0..06f7700f079 100644 --- a/app/controllers/concerns/lfs_request.rb +++ b/app/controllers/concerns/lfs_request.rb @@ -12,7 +12,7 @@ module LfsRequest extend ActiveSupport::Concern - CONTENT_TYPE = 'application/vnd.git-lfs+json'.freeze + CONTENT_TYPE = "application/vnd.git-lfs+json" included do before_action :require_lfs_enabled! @@ -26,8 +26,8 @@ module LfsRequest render( json: { - message: 'Git LFS is not enabled on this GitLab server, contact your admin.', - documentation_url: help_url + message: "Git LFS is not enabled on this GitLab server, contact your admin.", + documentation_url: help_url, }, status: :not_implemented ) @@ -51,8 +51,8 @@ module LfsRequest def render_lfs_forbidden render( json: { - message: 'Access forbidden. Check your access level.', - documentation_url: help_url + message: "Access forbidden. Check your access level.", + documentation_url: help_url, }, content_type: CONTENT_TYPE, status: 403 @@ -62,8 +62,8 @@ module LfsRequest def render_lfs_not_found render( json: { - message: 'Not found.', - documentation_url: help_url + message: "Not found.", + documentation_url: help_url, }, content_type: CONTENT_TYPE, status: 404 @@ -84,7 +84,7 @@ module LfsRequest end def deploy_token_present? - user && user.is_a?(DeployToken) + user&.is_a?(DeployToken) end def deploy_token diff --git a/app/controllers/concerns/membership_actions.rb b/app/controllers/concerns/membership_actions.rb index 6402e01ddc0..143b9dc5494 100644 --- a/app/controllers/concerns/membership_actions.rb +++ b/app/controllers/concerns/membership_actions.rb @@ -9,7 +9,7 @@ module MembershipActions result = Members::CreateService.new(current_user, create_params).execute(membershipable) if result[:status] == :success - redirect_to members_page_url, notice: 'Users were successfully added.' + redirect_to members_page_url, notice: "Users were successfully added." else redirect_to members_page_url, alert: result[:message] end @@ -25,7 +25,7 @@ module MembershipActions present_members([member]) respond_to do |format| - format.js { render 'shared/members/update', locals: { member: member } } + format.js { render "shared/members/update", locals: {member: member} } end end @@ -35,7 +35,7 @@ module MembershipActions respond_to do |format| format.html do - source = source_type == 'group' ? 'group and any subresources' : source_type + source = source_type == "group" ? "group and any subresources" : source_type message = "User was successfully removed from #{source}." redirect_to members_page_url, notice: message @@ -49,7 +49,7 @@ module MembershipActions membershipable.request_access(current_user) redirect_to polymorphic_path(membershipable), - notice: 'Your request for access has been queued for review.' + notice: "Your request for access has been queued for review." end def approve_access_request @@ -79,7 +79,7 @@ module MembershipActions redirect_to redirect_path, notice: notice end - format.json { render json: { notice: notice } } + format.json { render json: {notice: notice} } end end # rubocop: enable CodeReuse/ActiveRecord @@ -90,9 +90,9 @@ module MembershipActions if member.invite? member.resend_invite - redirect_to members_page_url, notice: 'The invitation was successfully resent.' + redirect_to members_page_url, notice: "The invitation was successfully resent." else - redirect_to members_page_url, alert: 'The invitation has already been accepted.' + redirect_to members_page_url, alert: "The invitation has already been accepted." end end diff --git a/app/controllers/concerns/milestone_actions.rb b/app/controllers/concerns/milestone_actions.rb index eccbe35577b..45ad9a12aca 100644 --- a/app/controllers/concerns/milestone_actions.rb +++ b/app/controllers/concerns/milestone_actions.rb @@ -9,7 +9,7 @@ module MilestoneActions format.json do render json: tabs_json("shared/milestones/_merge_requests_tab", { merge_requests: @milestone.sorted_merge_requests, # rubocop:disable Gitlab/ModuleWithInstanceVariables - show_project_name: true + show_project_name: true, }) end end @@ -20,7 +20,7 @@ module MilestoneActions format.html { redirect_to milestone_redirect_path } format.json do render json: tabs_json("shared/milestones/_participants_tab", { - users: @milestone.participants # rubocop:disable Gitlab/ModuleWithInstanceVariables + users: @milestone.participants, # rubocop:disable Gitlab/ModuleWithInstanceVariables }) end end @@ -31,7 +31,7 @@ module MilestoneActions format.html { redirect_to milestone_redirect_path } format.json do render json: tabs_json("shared/milestones/_labels_tab", { - labels: @milestone.labels # rubocop:disable Gitlab/ModuleWithInstanceVariables + labels: @milestone.labels, # rubocop:disable Gitlab/ModuleWithInstanceVariables }) end end @@ -41,7 +41,7 @@ module MilestoneActions def tabs_json(partial, data = {}) { - html: view_to_html_string(partial, data) + html: view_to_html_string(partial, data), } end diff --git a/app/controllers/concerns/notes_actions.rb b/app/controllers/concerns/notes_actions.rb index b4fee93713b..337c8c809e7 100644 --- a/app/controllers/concerns/notes_actions.rb +++ b/app/controllers/concerns/notes_actions.rb @@ -15,11 +15,11 @@ module NotesActions def index current_fetched_at = Time.now.to_i - notes_json = { notes: [], last_fetched_at: current_fetched_at } + notes_json = {notes: [], last_fetched_at: current_fetched_at} notes = notes_finder - .execute - .inc_relations_for_view + .execute + .inc_relations_for_view if notes_filter != UserPreference::NOTES_FILTERS[:only_comments] notes = @@ -48,7 +48,7 @@ module NotesActions respond_to do |format| format.json do json = { - commands_changes: @note.commands_changes + commands_changes: @note.commands_changes, } if @note.persisted? && return_discussion? @@ -99,7 +99,7 @@ module NotesActions "shared/notes/_note", layout: false, formats: [:html], - locals: { note: note } + locals: {note: note} ) end @@ -138,10 +138,8 @@ module NotesActions end end else - attrs.merge!( - valid: false, - errors: note.errors - ) + attrs[:valid] = false + attrs[:errors] = note.errors end attrs @@ -152,19 +150,19 @@ module NotesActions on_image = discussion.on_image? - if params[:view] == 'parallel' && !on_image + if params[:view] == "parallel" && !on_image template = "discussions/_parallel_diff_discussion" locals = - if params[:line_type] == 'old' - { discussions_left: [discussion], discussions_right: nil } + if params[:line_type] == "old" + {discussions_left: [discussion], discussions_right: nil} else - { discussions_left: nil, discussions_right: [discussion] } + {discussions_left: nil, discussions_right: [discussion]} end else template = "discussions/_diff_discussion" @fresh_discussion = true # rubocop:disable Gitlab/ModuleWithInstanceVariables - locals = { discussions: [discussion], on_image: on_image } + locals = {discussions: [discussion], on_image: on_image} end render_to_string( @@ -182,7 +180,7 @@ module NotesActions "discussions/_discussion", layout: false, formats: [:html], - locals: { discussion: discussion } + locals: {discussion: discussion} ) end @@ -206,9 +204,9 @@ module NotesActions create_params[:noteable_type] = params[:target_type].classify case params[:target_type] - when 'commit' + when "commit" create_params[:commit_id] = params[:target_id] - when 'merge_request' + when "merge_request" create_params[:noteable_id] = params[:target_id] # Notes on MergeRequest can have an extra `commit_id` context create_params[:commit_id] = params.dig(:note, :commit_id) @@ -235,7 +233,7 @@ module NotesActions end def last_fetched_at - request.headers['X-Last-Fetched-At'] + request.headers["X-Last-Fetched-At"] end def notes_filter @@ -278,7 +276,7 @@ module NotesActions end def use_note_serializer? - return false if params['html'] + return false if params["html"] noteable.discussions_rendered_on_frontend? end diff --git a/app/controllers/concerns/oauth_applications.rb b/app/controllers/concerns/oauth_applications.rb index d97e22df472..055b3e938bd 100644 --- a/app/controllers/concerns/oauth_applications.rb +++ b/app/controllers/concerns/oauth_applications.rb @@ -11,7 +11,7 @@ module OauthApplications scopes = params.fetch(:doorkeeper_application, {}).fetch(:scopes, nil) if scopes - params[:doorkeeper_application][:scopes] = scopes.join(' ') + params[:doorkeeper_application][:scopes] = scopes.join(" ") end end diff --git a/app/controllers/concerns/preview_markdown.rb b/app/controllers/concerns/preview_markdown.rb index f72d25fc54c..a603c5cf0f1 100644 --- a/app/controllers/concerns/preview_markdown.rb +++ b/app/controllers/concerns/preview_markdown.rb @@ -9,10 +9,10 @@ module PreviewMarkdown markdown_params = case controller_name - when 'wikis' then { pipeline: :wiki, project_wiki: @project_wiki, page_slug: params[:id] } - when 'snippets' then { skip_project_check: true } - when 'groups' then { group: group } - when 'projects' then projects_filter_params + when "wikis" then {pipeline: :wiki, project_wiki: @project_wiki, page_slug: params[:id]} + when "snippets" then {skip_project_check: true} + when "groups" then {group: group} + when "projects" then projects_filter_params else {} end @@ -21,15 +21,15 @@ module PreviewMarkdown references: { users: result[:users], suggestions: result[:suggestions], - commands: view_context.markdown(result[:commands]) - } + commands: view_context.markdown(result[:commands]), + }, } end def projects_filter_params { issuable_state_filter_enabled: true, - suggestions_filter_enabled: params[:preview_suggestions].present? + suggestions_filter_enabled: params[:preview_suggestions].present?, } end # rubocop:enable Gitlab/ModuleWithInstanceVariables diff --git a/app/controllers/concerns/renders_blob.rb b/app/controllers/concerns/renders_blob.rb index b8026c7a01d..2f1c87f0a38 100644 --- a/app/controllers/concerns/renders_blob.rb +++ b/app/controllers/concerns/renders_blob.rb @@ -6,9 +6,9 @@ module RendersBlob def blob_json(blob) viewer = case params[:viewer] - when 'rich' + when "rich" blob.rich_viewer - when 'auxiliary' + when "auxiliary" blob.auxiliary_viewer else blob.simple_viewer @@ -17,7 +17,7 @@ module RendersBlob return unless viewer { - html: view_to_html_string("projects/blob/_viewer", viewer: viewer, load_async: false) + html: view_to_html_string("projects/blob/_viewer", viewer: viewer, load_async: false), } end @@ -29,6 +29,6 @@ module RendersBlob end def conditionally_expand_blob(blob) - blob.expand! if params[:expanded] == 'true' + blob.expand! if params[:expanded] == "true" end end diff --git a/app/controllers/concerns/renders_commits.rb b/app/controllers/concerns/renders_commits.rb index ed9b898a2a3..cf95c4b18cd 100644 --- a/app/controllers/concerns/renders_commits.rb +++ b/app/controllers/concerns/renders_commits.rb @@ -5,7 +5,7 @@ module RendersCommits if commits.size > MergeRequestDiff::COMMITS_SAFE_SIZE [ commits.first(MergeRequestDiff::COMMITS_SAFE_SIZE), - commits.size - MergeRequestDiff::COMMITS_SAFE_SIZE + commits.size - MergeRequestDiff::COMMITS_SAFE_SIZE, ] else [commits, 0] diff --git a/app/controllers/concerns/renders_notes.rb b/app/controllers/concerns/renders_notes.rb index ce36da6b715..1dc66324eba 100644 --- a/app/controllers/concerns/renders_notes.rb +++ b/app/controllers/concerns/renders_notes.rb @@ -36,7 +36,7 @@ module RendersNotes # rubocop: disable CodeReuse/ActiveRecord def preload_author_status(notes) - ActiveRecord::Associations::Preloader.new.preload(notes, { author: :status }) + ActiveRecord::Associations::Preloader.new.preload(notes, {author: :status}) end # rubocop: enable CodeReuse/ActiveRecord end diff --git a/app/controllers/concerns/requires_whitelisted_monitoring_client.rb b/app/controllers/concerns/requires_whitelisted_monitoring_client.rb index 426f224d26b..35256673aad 100644 --- a/app/controllers/concerns/requires_whitelisted_monitoring_client.rb +++ b/app/controllers/concerns/requires_whitelisted_monitoring_client.rb @@ -22,7 +22,7 @@ module RequiresWhitelistedMonitoringClient end def valid_token? - token = params[:token].presence || request.headers['TOKEN'] + token = params[:token].presence || request.headers["TOKEN"] token.present? && ActiveSupport::SecurityUtils.variable_size_secure_compare( token, @@ -31,6 +31,6 @@ module RequiresWhitelistedMonitoringClient end def render_404 - render file: Rails.root.join('public', '404'), layout: false, status: '404' + render file: Rails.root.join("public", "404"), layout: false, status: "404" end end diff --git a/app/controllers/concerns/routable_actions.rb b/app/controllers/concerns/routable_actions.rb index 5624eb3aa45..237967d01e3 100644 --- a/app/controllers/concerns/routable_actions.rb +++ b/app/controllers/concerns/routable_actions.rb @@ -9,9 +9,7 @@ module RoutableActions ensure_canonical_path(routable, requested_full_path) routable else - if not_found_or_authorized_proc - not_found_or_authorized_proc.call(routable) - end + not_found_or_authorized_proc&.call(routable) route_not_found unless performed? diff --git a/app/controllers/concerns/send_file_upload.rb b/app/controllers/concerns/send_file_upload.rb index 28e4cece548..36372cd6ac1 100644 --- a/app/controllers/concerns/send_file_upload.rb +++ b/app/controllers/concerns/send_file_upload.rb @@ -1,21 +1,22 @@ # frozen_string_literal: true module SendFileUpload - def send_upload(file_upload, send_params: {}, redirect_params: {}, attachment: nil, proxy: false, disposition: 'attachment') + def send_upload(file_upload, send_params: {}, redirect_params: {}, attachment: nil, proxy: false, disposition: "attachment") if attachment response_disposition = ::Gitlab::ContentDisposition.format(disposition: disposition, filename: attachment) # Response-Content-Type will not override an existing Content-Type in # Google Cloud Storage, so the metadata needs to be cleared on GCS for # this to work. However, this override works with AWS. - redirect_params[:query] = { "response-content-disposition" => response_disposition, - "response-content-type" => guess_content_type(attachment) } + redirect_params[:query] = {"response-content-disposition" => response_disposition, + "response-content-type" => guess_content_type(attachment),} # By default, Rails will send uploads with an extension of .js with a # content-type of text/javascript, which will trigger Rails' # cross-origin JavaScript protection. - send_params[:content_type] = 'text/plain' if File.extname(attachment) == '.js' + send_params[:content_type] = "text/plain" if File.extname(attachment) == ".js" - send_params.merge!(filename: attachment, disposition: utf8_encoded_disposition(disposition, attachment)) + send_params[:filename] = attachment + send_params[:disposition] = utf8_encoded_disposition(disposition, attachment) end if file_upload.file_storage? diff --git a/app/controllers/concerns/sends_blob.rb b/app/controllers/concerns/sends_blob.rb index 8ecdaced9f5..50d88504b7c 100644 --- a/app/controllers/concerns/sends_blob.rb +++ b/app/controllers/concerns/sends_blob.rb @@ -10,7 +10,7 @@ module SendsBlob def send_blob(repository, blob, params = {}) if blob - headers['X-Content-Type-Options'] = 'nosniff' + headers["X-Content-Type-Options"] = "nosniff" return if cached_blob?(blob) @@ -51,7 +51,7 @@ module SendsBlob def send_lfs_object(blob) lfs_object = find_lfs_object(blob) - if lfs_object && lfs_object.project_allowed_access?(project) + if lfs_object&.project_allowed_access?(project) send_upload(lfs_object.file, attachment: blob.name) else render_404 @@ -60,10 +60,8 @@ module SendsBlob def find_lfs_object(blob) lfs_object = LfsObject.find_by_oid(blob.lfs_oid) - if lfs_object && lfs_object.file.exists? + if lfs_object&.file&.exists? lfs_object - else - nil end end end diff --git a/app/controllers/concerns/service_params.rb b/app/controllers/concerns/service_params.rb index 48451bedcc2..0f64cb04635 100644 --- a/app/controllers/concerns/service_params.rb +++ b/app/controllers/concerns/service_params.rb @@ -62,7 +62,7 @@ module ServiceParams :url, :user_key, :username, - :webhook + :webhook, ].freeze # Parameters to ignore if no value is specified diff --git a/app/controllers/concerns/sessionless_authentication.rb b/app/controllers/concerns/sessionless_authentication.rb index 590eefc6dab..c718f4303df 100644 --- a/app/controllers/concerns/sessionless_authentication.rb +++ b/app/controllers/concerns/sessionless_authentication.rb @@ -13,7 +13,7 @@ module SessionlessAuthentication end def sessionless_user? - current_user && !session.keys.include?('warden.user.user.key') + current_user && !session.key?("warden.user.user.key") end def sessionless_sign_in(user) diff --git a/app/controllers/concerns/snippets_actions.rb b/app/controllers/concerns/snippets_actions.rb index 014232a7d05..bf2683034a8 100644 --- a/app/controllers/concerns/snippets_actions.rb +++ b/app/controllers/concerns/snippets_actions.rb @@ -8,13 +8,13 @@ module SnippetsActions # rubocop:disable Gitlab/ModuleWithInstanceVariables def raw - disposition = params[:inline] == 'false' ? 'attachment' : 'inline' + disposition = params[:inline] == "false" ? "attachment" : "inline" workhorse_set_content_type! send_data( convert_line_endings(@snippet.content), - type: 'text/plain; charset=utf-8', + type: "text/plain; charset=utf-8", disposition: disposition, filename: @snippet.sanitized_file_name ) @@ -28,6 +28,6 @@ module SnippetsActions private def convert_line_endings(content) - params[:line_ending] == 'raw' ? content : content.gsub(/\r\n/, "\n") + params[:line_ending] == "raw" ? content : content.gsub(/\r\n/, "\n") end end diff --git a/app/controllers/concerns/spammable_actions.rb b/app/controllers/concerns/spammable_actions.rb index c3a1b12af84..26847e03550 100644 --- a/app/controllers/concerns/spammable_actions.rb +++ b/app/controllers/concerns/spammable_actions.rb @@ -14,7 +14,7 @@ module SpammableActions if SpamService.new(spammable).mark_as_spam! redirect_to spammable_path, notice: "#{spammable.spammable_entity_type.titlecase} was submitted to Akismet successfully." else - redirect_to spammable_path, alert: 'Error with Akismet. Please check the logs for more info.' + redirect_to spammable_path, alert: "Error with Akismet. Please check the logs for more info." end end @@ -33,7 +33,7 @@ module SpammableActions ensure_spam_config_loaded! if params[:recaptcha_verification] - flash[:alert] = 'There was an error with the reCAPTCHA. Please solve the reCAPTCHA again.' + flash[:alert] = "There was an error with the reCAPTCHA. Please solve the reCAPTCHA again." end respond_to do |format| @@ -42,10 +42,10 @@ module SpammableActions end format.json do - locals = { spammable: spammable, script: false, has_submit: false } - recaptcha_html = render_to_string(partial: 'shared/recaptcha_form', formats: :html, locals: locals) + locals = {spammable: spammable, script: false, has_submit: false} + recaptcha_html = render_to_string(partial: "shared/recaptcha_form", formats: :html, locals: locals) - render json: { recaptcha_html: recaptcha_html } + render json: {recaptcha_html: recaptcha_html} end end else @@ -54,7 +54,7 @@ module SpammableActions end def spammable_params - default_params = { request: request } + default_params = {request: request} recaptcha_check = params[:recaptcha_verification] && ensure_spam_config_loaded! && @@ -62,8 +62,8 @@ module SpammableActions return default_params unless recaptcha_check - { recaptcha_verified: true, - spam_log_id: params[:spam_log_id] }.merge(default_params) + {recaptcha_verified: true, + spam_log_id: params[:spam_log_id],}.merge(default_params) end def spammable diff --git a/app/controllers/concerns/todos_actions.rb b/app/controllers/concerns/todos_actions.rb index 78b65f7961b..c486a65445a 100644 --- a/app/controllers/concerns/todos_actions.rb +++ b/app/controllers/concerns/todos_actions.rb @@ -8,7 +8,7 @@ module TodosActions render json: { count: TodosFinder.new(current_user, state: :pending).execute.count, - delete_path: dashboard_todo_path(todo) + delete_path: dashboard_todo_path(todo), } end end diff --git a/app/controllers/concerns/toggle_award_emoji.rb b/app/controllers/concerns/toggle_award_emoji.rb index 97b343f8b1a..e7bbf2c4baa 100644 --- a/app/controllers/concerns/toggle_award_emoji.rb +++ b/app/controllers/concerns/toggle_award_emoji.rb @@ -13,9 +13,9 @@ module ToggleAwardEmoji todoable = to_todoable(awardable) TodoService.new.new_award_emoji(todoable, current_user) if todoable - render json: { ok: true } + render json: {ok: true} else - render json: { ok: false } + render json: {ok: false} end end diff --git a/app/controllers/concerns/uploads_actions.rb b/app/controllers/concerns/uploads_actions.rb index 4ec0e94df9a..5657bdf916d 100644 --- a/app/controllers/concerns/uploads_actions.rb +++ b/app/controllers/concerns/uploads_actions.rb @@ -4,7 +4,7 @@ module UploadsActions include Gitlab::Utils::StrongMemoize include SendFileUpload - UPLOAD_MOUNTS = %w(avatar attachment file logo header_logo favicon).freeze + UPLOAD_MOUNTS = %w[avatar attachment file logo header_logo favicon].freeze def create uploader = UploadService.new(model, params[:file], uploader_class).execute @@ -12,11 +12,11 @@ module UploadsActions respond_to do |format| if uploader format.json do - render json: { link: uploader.to_h } + render json: {link: uploader.to_h} end else format.json do - render json: 'Invalid file.', status: :unprocessable_entity + render json: "Invalid file.", status: :unprocessable_entity end end end @@ -31,13 +31,13 @@ module UploadsActions if cache_publicly? # We need to reset caching from the applications controller to get rid of the no-store value - headers['Cache-Control'] = '' + headers["Cache-Control"] = "" expires_in 5.minutes, public: true, must_revalidate: false else expires_in 0.seconds, must_revalidate: true, private: true end - disposition = uploader.image_or_video? ? 'inline' : 'attachment' + disposition = uploader.image_or_video? ? "inline" : "attachment" uploaders = [uploader, *uploader.versions.values] uploader = uploaders.find { |version| version.filename == params[:filename] } @@ -53,7 +53,8 @@ module UploadsActions authorized = uploader_class.workhorse_authorize( has_length: false, - maximum_size: Gitlab::CurrentSettings.max_attachment_size.megabytes.to_i) + maximum_size: Gitlab::CurrentSettings.max_attachment_size.megabytes.to_i + ) render json: authorized rescue SocketError @@ -113,7 +114,7 @@ module UploadsActions end def image_or_video? - uploader && uploader.exists? && uploader.image_or_video? + uploader&.exists? && uploader&.image_or_video? end def find_model diff --git a/app/controllers/concerns/with_performance_bar.rb b/app/controllers/concerns/with_performance_bar.rb index 77c3d476ac6..bcce144ef49 100644 --- a/app/controllers/concerns/with_performance_bar.rb +++ b/app/controllers/concerns/with_performance_bar.rb @@ -17,9 +17,9 @@ module WithPerformanceBar def cookie_or_default_value if cookies[:perf_bar_enabled].present? - cookies[:perf_bar_enabled] == 'true' + cookies[:perf_bar_enabled] == "true" else - cookies[:perf_bar_enabled] = 'true' if Rails.env.development? + cookies[:perf_bar_enabled] = "true" if Rails.env.development? end end end diff --git a/app/controllers/confirmations_controller.rb b/app/controllers/confirmations_controller.rb index 2c4aab67448..23d020fba3a 100644 --- a/app/controllers/confirmations_controller.rb +++ b/app/controllers/confirmations_controller.rb @@ -23,7 +23,7 @@ class ConfirmationsController < Devise::ConfirmationsController else Gitlab::AppLogger.info("Email Confirmed: username=#{resource.username} email=#{resource.email} ip=#{request.remote_ip}") flash[:notice] = flash[:notice] + " Please sign in." - new_session_path(:user, anchor: 'login-pane') + new_session_path(:user, anchor: "login-pane") end end diff --git a/app/controllers/dashboard/application_controller.rb b/app/controllers/dashboard/application_controller.rb index 0e9fdc60363..63bba1a156e 100644 --- a/app/controllers/dashboard/application_controller.rb +++ b/app/controllers/dashboard/application_controller.rb @@ -4,7 +4,7 @@ class Dashboard::ApplicationController < ApplicationController include ControllerWithCrossProjectAccessCheck include RecordUserLastActivity - layout 'dashboard' + layout "dashboard" requires_cross_project_access diff --git a/app/controllers/dashboard/labels_controller.rb b/app/controllers/dashboard/labels_controller.rb index 89d87c2d5c8..3a266fa2a72 100644 --- a/app/controllers/dashboard/labels_controller.rb +++ b/app/controllers/dashboard/labels_controller.rb @@ -8,7 +8,7 @@ class Dashboard::LabelsController < Dashboard::ApplicationController end def labels - finder_params = { project_ids: projects.select(:id) } + finder_params = {project_ids: projects.select(:id)} labels = LabelsFinder.new(current_user, finder_params).execute GlobalLabel.build_collection(labels) diff --git a/app/controllers/dashboard/projects_controller.rb b/app/controllers/dashboard/projects_controller.rb index b044affd4e8..a10f7366a97 100644 --- a/app/controllers/dashboard/projects_controller.rb +++ b/app/controllers/dashboard/projects_controller.rb @@ -22,11 +22,11 @@ class Dashboard::ProjectsController < Dashboard::ApplicationController end format.atom do load_events - render layout: 'xml.atom' + render layout: "xml.atom" end format.json do render json: { - html: view_to_html_string("dashboard/projects/_projects", locals: { projects: @projects }) + html: view_to_html_string("dashboard/projects/_projects", locals: {projects: @projects}), } end end @@ -43,7 +43,7 @@ class Dashboard::ProjectsController < Dashboard::ApplicationController format.html format.json do render json: { - html: view_to_html_string("dashboard/projects/_projects", locals: { projects: @projects }) + html: view_to_html_string("dashboard/projects/_projects", locals: {projects: @projects}), } end end @@ -53,20 +53,20 @@ class Dashboard::ProjectsController < Dashboard::ApplicationController private def default_sorting - params[:sort] ||= 'latest_activity_desc' + params[:sort] ||= "latest_activity_desc" @sort = params[:sort] end # rubocop: disable CodeReuse/ActiveRecord def load_projects(finder_params) - @total_user_projects_count = ProjectsFinder.new(params: { non_public: true }, current_user: current_user).execute - @total_starred_projects_count = ProjectsFinder.new(params: { starred: true }, current_user: current_user).execute + @total_user_projects_count = ProjectsFinder.new(params: {non_public: true}, current_user: current_user).execute + @total_starred_projects_count = ProjectsFinder.new(params: {starred: true}, current_user: current_user).execute projects = ProjectsFinder - .new(params: finder_params, current_user: current_user) - .execute - .includes(:route, :creator, :group, namespace: [:route, :owner]) - .page(finder_params[:page]) + .new(params: finder_params, current_user: current_user) + .execute + .includes(:route, :creator, :group, namespace: [:route, :owner]) + .page(finder_params[:page]) prepare_projects_for_rendering(projects) end diff --git a/app/controllers/dashboard/todos_controller.rb b/app/controllers/dashboard/todos_controller.rb index 3fa582cf25b..36063ef23e9 100644 --- a/app/controllers/dashboard/todos_controller.rb +++ b/app/controllers/dashboard/todos_controller.rb @@ -20,8 +20,8 @@ class Dashboard::TodosController < Dashboard::ApplicationController respond_to do |format| format.html do redirect_to dashboard_todos_path, - status: 302, - notice: 'Todo was successfully marked as done.' + status: 302, + notice: "Todo was successfully marked as done." end format.js { head :ok } format.json { render json: todos_counts } @@ -32,7 +32,7 @@ class Dashboard::TodosController < Dashboard::ApplicationController updated_ids = TodoService.new.mark_todos_as_done(@todos, current_user) respond_to do |format| - format.html { redirect_to dashboard_todos_path, status: 302, notice: 'All todos were marked as done.' } + format.html { redirect_to dashboard_todos_path, status: 302, notice: "All todos were marked as done." } format.js { head :ok } format.json { render json: todos_counts.merge(updated_ids: updated_ids) } end @@ -77,7 +77,7 @@ class Dashboard::TodosController < Dashboard::ApplicationController def todos_counts { count: number_with_delimiter(current_user.todos_pending_count), - done_count: number_with_delimiter(current_user.todos_done_count) + done_count: number_with_delimiter(current_user.todos_done_count), } end diff --git a/app/controllers/dashboard_controller.rb b/app/controllers/dashboard_controller.rb index 75329b05a6f..0f9a0a9d824 100644 --- a/app/controllers/dashboard_controller.rb +++ b/app/controllers/dashboard_controller.rb @@ -29,7 +29,7 @@ class DashboardController < Dashboard::ApplicationController def load_events projects = if params[:filter] == "starred" - ProjectsFinder.new(current_user: current_user, params: { starred: true }).execute + ProjectsFinder.new(current_user: current_user, params: {starred: true}).execute else current_user.authorized_projects end diff --git a/app/controllers/explore/application_controller.rb b/app/controllers/explore/application_controller.rb index 8eee3742d89..effe9028d10 100644 --- a/app/controllers/explore/application_controller.rb +++ b/app/controllers/explore/application_controller.rb @@ -3,5 +3,5 @@ class Explore::ApplicationController < ApplicationController skip_before_action :authenticate_user! - layout 'explore' + layout "explore" end diff --git a/app/controllers/explore/projects_controller.rb b/app/controllers/explore/projects_controller.rb index f3d76c5a478..d33ccca1898 100644 --- a/app/controllers/explore/projects_controller.rb +++ b/app/controllers/explore/projects_controller.rb @@ -7,7 +7,7 @@ class Explore::ProjectsController < Explore::ApplicationController before_action :set_non_archived_param def index - params[:sort] ||= 'latest_activity_desc' + params[:sort] ||= "latest_activity_desc" @sort = params[:sort] @projects = load_projects @@ -15,7 +15,7 @@ class Explore::ProjectsController < Explore::ApplicationController format.html format.json do render json: { - html: view_to_html_string("explore/projects/_projects", locals: { projects: @projects }) + html: view_to_html_string("explore/projects/_projects", locals: {projects: @projects}), } end end @@ -30,7 +30,7 @@ class Explore::ProjectsController < Explore::ApplicationController format.html format.json do render json: { - html: view_to_html_string("explore/projects/_projects", locals: { projects: @projects }) + html: view_to_html_string("explore/projects/_projects", locals: {projects: @projects}), } end end @@ -38,13 +38,13 @@ class Explore::ProjectsController < Explore::ApplicationController # rubocop: disable CodeReuse/ActiveRecord def starred - @projects = load_projects.reorder('star_count DESC') + @projects = load_projects.reorder("star_count DESC") respond_to do |format| format.html format.json do render json: { - html: view_to_html_string("explore/projects/_projects", locals: { projects: @projects }) + html: view_to_html_string("explore/projects/_projects", locals: {projects: @projects}), } end end @@ -55,14 +55,14 @@ class Explore::ProjectsController < Explore::ApplicationController # rubocop: disable CodeReuse/ActiveRecord def load_projects - @total_user_projects_count = ProjectsFinder.new(params: { non_public: true }, current_user: current_user).execute - @total_starred_projects_count = ProjectsFinder.new(params: { starred: true }, current_user: current_user).execute + @total_user_projects_count = ProjectsFinder.new(params: {non_public: true}, current_user: current_user).execute + @total_starred_projects_count = ProjectsFinder.new(params: {starred: true}, current_user: current_user).execute projects = ProjectsFinder.new(current_user: current_user, params: params) - .execute - .includes(:route, :creator, :group, namespace: [:route, :owner]) - .page(params[:page]) - .without_count + .execute + .includes(:route, :creator, :group, namespace: [:route, :owner]) + .page(params[:page]) + .without_count prepare_projects_for_rendering(projects) end diff --git a/app/controllers/graphql_controller.rb b/app/controllers/graphql_controller.rb index 3ef03bc9622..8d8cb44e07e 100644 --- a/app/controllers/graphql_controller.rb +++ b/app/controllers/graphql_controller.rb @@ -12,7 +12,7 @@ class GraphqlController < ApplicationController query = params[:query] operation_name = params[:operationName] context = { - current_user: current_user + current_user: current_user, } result = GitlabSchema.execute(query, variables: variables, context: context, operation_name: operation_name) render json: result @@ -37,7 +37,7 @@ class GraphqlController < ApplicationController end def render_error(message, status: 500) - error = { errors: [message: message] } + error = {errors: [message: message]} render json: error, status: status end diff --git a/app/controllers/groups/application_controller.rb b/app/controllers/groups/application_controller.rb index 5f92333c2c3..10abdcc3365 100644 --- a/app/controllers/groups/application_controller.rb +++ b/app/controllers/groups/application_controller.rb @@ -4,7 +4,7 @@ class Groups::ApplicationController < ApplicationController include RoutableActions include ControllerWithCrossProjectAccessCheck - layout 'group' + layout "group" skip_before_action :authenticate_user! before_action :group @@ -22,13 +22,13 @@ class Groups::ApplicationController < ApplicationController def authorize_admin_group! unless can?(current_user, :admin_group, group) - return render_404 + render_404 end end def authorize_admin_group_member! unless can?(current_user, :admin_group_member, group) - return render_403 + render_403 end end diff --git a/app/controllers/groups/children_controller.rb b/app/controllers/groups/children_controller.rb index 236a19a8dc4..b13c543084d 100644 --- a/app/controllers/groups/children_controller.rb +++ b/app/controllers/groups/children_controller.rb @@ -7,10 +7,10 @@ module Groups def index parent = if params[:parent_id].present? - GroupFinder.new(current_user).execute(id: params[:parent_id]) - else - @group - end + GroupFinder.new(current_user).execute(id: params[:parent_id]) + else + @group + end if parent.nil? render_404 @@ -22,8 +22,8 @@ module Groups respond_to do |format| format.json do serializer = GroupChildSerializer - .new(current_user: current_user) - .with_pagination(request, response) + .new(current_user: current_user) + .with_pagination(request, response) serializer.expand_hierarchy(parent) if params[:filter].present? render json: serializer.represent(@children) end diff --git a/app/controllers/groups/clusters_controller.rb b/app/controllers/groups/clusters_controller.rb index b846fb21266..f659d4c3991 100644 --- a/app/controllers/groups/clusters_controller.rb +++ b/app/controllers/groups/clusters_controller.rb @@ -7,7 +7,7 @@ class Groups::ClustersController < Clusters::ClustersController prepend_before_action :check_group_clusters_feature_flag! requires_cross_project_access - layout 'group' + layout "group" private diff --git a/app/controllers/groups/group_members_controller.rb b/app/controllers/groups/group_members_controller.rb index 0bc082246a1..5cbebae5a44 100644 --- a/app/controllers/groups/group_members_controller.rb +++ b/app/controllers/groups/group_members_controller.rb @@ -13,8 +13,8 @@ class Groups::GroupMembersController < Groups::ApplicationController before_action :authorize_admin_group_member!, except: admin_not_required_endpoints skip_cross_project_access_check :index, :create, :update, :destroy, :request_access, - :approve_access_request, :leave, :resend_invite, - :override + :approve_access_request, :leave, :resend_invite, + :override def index can_manage_members = can?(current_user, :admin_group_member, @group) @@ -35,11 +35,12 @@ class Groups::GroupMembersController < Groups::ApplicationController @members = present_members(@members) @requesters = present_members( - AccessRequestsFinder.new(@group).execute(current_user)) + AccessRequestsFinder.new(@group).execute(current_user) + ) @group_member = @group.group_members.new end # MembershipActions concern - alias_method :membershipable, :group + alias membershipable group end diff --git a/app/controllers/groups/labels_controller.rb b/app/controllers/groups/labels_controller.rb index 26768c628ca..dd80c8ebbc5 100644 --- a/app/controllers/groups/labels_controller.rb +++ b/app/controllers/groups/labels_controller.rb @@ -82,7 +82,7 @@ class Groups::LabelsController < Groups::ApplicationController def label @label ||= @group.labels.find(params[:id]) end - alias_method :subscribable_resource, :label + alias subscribable_resource label def subscribable_project nil @@ -105,7 +105,7 @@ class Groups::LabelsController < Groups::ApplicationController end def save_previous_label_path - session[:previous_labels_path] = URI(request.referer || '').path + session[:previous_labels_path] = URI(request.referer || "").path end def available_labels @@ -116,10 +116,11 @@ class Groups::LabelsController < Groups::ApplicationController only_group_labels: params[:only_group_labels], include_ancestor_groups: params[:include_ancestor_groups], include_descendant_groups: params[:include_descendant_groups], - search: params[:search]).execute + search: params[:search] + ).execute end def sort - @sort ||= params[:sort] || 'name_asc' + @sort ||= params[:sort] || "name_asc" end end diff --git a/app/controllers/groups/milestones_controller.rb b/app/controllers/groups/milestones_controller.rb index 7ed4384089b..cf9510dfb50 100644 --- a/app/controllers/groups/milestones_controller.rb +++ b/app/controllers/groups/milestones_controller.rb @@ -95,7 +95,7 @@ class Groups::MilestonesController < Groups::ApplicationController def milestones milestones = MilestonesFinder.new(search_params).execute - @sort = params[:sort] || 'due_date_asc' + @sort = params[:sort] || "due_date_asc" MilestoneArray.sort(milestones + legacy_milestones, @sort) end diff --git a/app/controllers/groups/runners_controller.rb b/app/controllers/groups/runners_controller.rb index dd8fbf7a029..15349446b9a 100644 --- a/app/controllers/groups/runners_controller.rb +++ b/app/controllers/groups/runners_controller.rb @@ -8,7 +8,7 @@ class Groups::RunnersController < Groups::ApplicationController before_action :runner, only: [:edit, :update, :destroy, :pause, :resume, :show] def show - render 'shared/runners/show' + render "shared/runners/show" end def edit @@ -16,31 +16,31 @@ class Groups::RunnersController < Groups::ApplicationController def update if Ci::UpdateRunnerService.new(@runner).update(runner_params) - redirect_to group_runner_path(@group, @runner), notice: 'Runner was successfully updated.' + redirect_to group_runner_path(@group, @runner), notice: "Runner was successfully updated." else - render 'edit' + render "edit" end end def destroy @runner.destroy - redirect_to group_settings_ci_cd_path(@group, anchor: 'runners-settings'), status: :found + redirect_to group_settings_ci_cd_path(@group, anchor: "runners-settings"), status: :found end def resume if Ci::UpdateRunnerService.new(@runner).update(active: true) - redirect_to group_settings_ci_cd_path(@group, anchor: 'runners-settings'), notice: 'Runner was successfully updated.' + redirect_to group_settings_ci_cd_path(@group, anchor: "runners-settings"), notice: "Runner was successfully updated." else - redirect_to group_settings_ci_cd_path(@group, anchor: 'runners-settings'), alert: 'Runner was not updated.' + redirect_to group_settings_ci_cd_path(@group, anchor: "runners-settings"), alert: "Runner was not updated." end end def pause if Ci::UpdateRunnerService.new(@runner).update(active: false) - redirect_to group_settings_ci_cd_path(@group, anchor: 'runners-settings'), notice: 'Runner was successfully updated.' + redirect_to group_settings_ci_cd_path(@group, anchor: "runners-settings"), notice: "Runner was successfully updated." else - redirect_to group_settings_ci_cd_path(@group, anchor: 'runners-settings'), alert: 'Runner was not updated.' + redirect_to group_settings_ci_cd_path(@group, anchor: "runners-settings"), alert: "Runner was not updated." end end diff --git a/app/controllers/groups/settings/ci_cd_controller.rb b/app/controllers/groups/settings/ci_cd_controller.rb index f476f428fdb..d8b909f73f7 100644 --- a/app/controllers/groups/settings/ci_cd_controller.rb +++ b/app/controllers/groups/settings/ci_cd_controller.rb @@ -13,7 +13,7 @@ module Groups def reset_registration_token @group.reset_runners_token! - flash[:notice] = 'New runners registration token has been generated!' + flash[:notice] = "New runners registration token has been generated!" redirect_to group_settings_ci_cd_path end diff --git a/app/controllers/groups/shared_projects_controller.rb b/app/controllers/groups/shared_projects_controller.rb index 30b7bfc70ae..1096af84cb2 100644 --- a/app/controllers/groups/shared_projects_controller.rb +++ b/app/controllers/groups/shared_projects_controller.rb @@ -11,10 +11,10 @@ module Groups group: group, current_user: current_user, params: finder_params, - options: { only_shared: true } + options: {only_shared: true} ).execute serializer = GroupChildSerializer.new(current_user: current_user) - .with_pagination(request, response) + .with_pagination(request, response) render json: serializer.represent(shared_projects) end diff --git a/app/controllers/groups/uploads_controller.rb b/app/controllers/groups/uploads_controller.rb index 7e5cdae0ce3..2af007e4f57 100644 --- a/app/controllers/groups/uploads_controller.rb +++ b/app/controllers/groups/uploads_controller.rb @@ -4,7 +4,7 @@ class Groups::UploadsController < Groups::ApplicationController include UploadsActions include WorkhorseRequest - skip_before_action :group, if: -> { action_name == 'show' && image_or_video? } + skip_before_action :group, if: -> { action_name == "show" && image_or_video? } before_action :authorize_upload_file!, only: [:create, :authorize] before_action :verify_workhorse_api!, only: [:authorize] diff --git a/app/controllers/groups/variables_controller.rb b/app/controllers/groups/variables_controller.rb index 4f641de0357..35c760f10c8 100644 --- a/app/controllers/groups/variables_controller.rb +++ b/app/controllers/groups/variables_controller.rb @@ -9,7 +9,7 @@ module Groups def show respond_to do |format| format.json do - render status: :ok, json: { variables: GroupVariableSerializer.new.represent(@group.variables) } + render status: :ok, json: {variables: GroupVariableSerializer.new.represent(@group.variables)} end end end @@ -29,7 +29,7 @@ module Groups private def render_group_variables - render status: :ok, json: { variables: GroupVariableSerializer.new.represent(@group.variables) } + render status: :ok, json: {variables: GroupVariableSerializer.new.represent(@group.variables)} end def render_error diff --git a/app/controllers/groups_controller.rb b/app/controllers/groups_controller.rb index 4e50106398a..a078cb2b000 100644 --- a/app/controllers/groups_controller.rb +++ b/app/controllers/groups_controller.rb @@ -25,7 +25,7 @@ class GroupsController < Groups::ApplicationController before_action :user_actions, only: [:show] skip_cross_project_access_check :index, :new, :create, :edit, :update, - :destroy, :projects + :destroy, :projects # When loading show as an atom feed, we render events that could leak cross # project information skip_cross_project_access_check :show, if: -> { request.format.html? } @@ -45,10 +45,10 @@ class GroupsController < Groups::ApplicationController if @group.persisted? notice = if @group.chat_team.present? - "Group '#{@group.name}' and its Mattermost team were successfully created." - else - "Group '#{@group.name}' was successfully created." - end + "Group '#{@group.name}' and its Mattermost team were successfully created." + else + "Group '#{@group.name}' was successfully created." + end redirect_to @group, notice: notice else @@ -62,7 +62,7 @@ class GroupsController < Groups::ApplicationController format.atom do load_events - render layout: 'xml.atom' + render layout: "xml.atom" end end end @@ -122,11 +122,11 @@ class GroupsController < Groups::ApplicationController # rubocop: disable CodeReuse/ActiveRecord def authorize_create_group! allowed = if params[:parent_id].present? - parent = Group.find_by(id: params[:parent_id]) - can?(current_user, :create_subgroup, parent) - else - can?(current_user, :create_group) - end + parent = Group.find_by(id: params[:parent_id]) + can?(current_user, :create_subgroup, parent) + else + can?(current_user, :create_group) + end render_404 unless allowed end @@ -134,11 +134,11 @@ class GroupsController < Groups::ApplicationController def determine_layout if [:new, :create].include?(action_name.to_sym) - 'application' + "application" elsif [:edit, :update, :projects].include?(action_name.to_sym) - 'group_settings' + "group_settings" else - 'group' + "group" end end @@ -161,21 +161,21 @@ class GroupsController < Groups::ApplicationController :create_chat_team, :chat_team_name, :require_two_factor_authentication, - :two_factor_grace_period + :two_factor_grace_period, ] end # rubocop: disable CodeReuse/ActiveRecord def load_events - params[:sort] ||= 'latest_activity_desc' + params[:sort] ||= "latest_activity_desc" options = {} - options[:only_owned] = true if params[:shared] == '0' - options[:only_shared] = true if params[:shared] == '1' + options[:only_owned] = true if params[:shared] == "0" + options[:only_shared] = true if params[:shared] == "1" @projects = GroupProjectsFinder.new(params: params, group: group, options: options, current_user: current_user) - .execute - .includes(:namespace) + .execute + .includes(:namespace) @events = EventCollection .new(@projects, offset: params[:offset].to_i, filter: event_filter) @@ -194,7 +194,7 @@ class GroupsController < Groups::ApplicationController end def build_canonical_path(group) - return group_path(group) if action_name == 'show' # root group path + return group_path(group) if action_name == "show" # root group path params[:id] = group.to_param diff --git a/app/controllers/health_controller.rb b/app/controllers/health_controller.rb index dc9a52f8da5..b930e651fed 100644 --- a/app/controllers/health_controller.rb +++ b/app/controllers/health_controller.rb @@ -10,7 +10,7 @@ class HealthController < ActionController::Base Gitlab::HealthChecks::Redis::CacheCheck, Gitlab::HealthChecks::Redis::QueuesCheck, Gitlab::HealthChecks::Redis::SharedStateCheck, - Gitlab::HealthChecks::GitalyCheck + Gitlab::HealthChecks::GitalyCheck, ].freeze def readiness @@ -28,21 +28,21 @@ class HealthController < ActionController::Base private def render_check_results(results) - flattened = results.flat_map do |name, result| + flattened = results.flat_map { |name, result| if result.is_a?(Gitlab::HealthChecks::Result) [[name, result]] else result.map { |r| [name, r] } end - end + } success = flattened.all? { |name, r| r.success } - response = flattened.map do |name, r| - info = { status: r.success ? 'ok' : 'failed' } - info['message'] = r.message if r.message + response = flattened.map { |name, r| + info = {status: r.success ? "ok" : "failed"} + info["message"] = r.message if r.message info[:labels] = r.labels if r.labels [name, info] - end + } render json: response.to_h, status: success ? :ok : :service_unavailable end end diff --git a/app/controllers/help_controller.rb b/app/controllers/help_controller.rb index a9d6addd4a4..ae585e795dd 100644 --- a/app/controllers/help_controller.rb +++ b/app/controllers/help_controller.rb @@ -3,7 +3,7 @@ class HelpController < ApplicationController skip_before_action :authenticate_user! - layout 'help' + layout "help" # Taken from Jekyll # https://github.com/jekyll/jekyll/blob/3.5-stable/lib/jekyll/document.rb#L13 @@ -11,7 +11,7 @@ class HelpController < ApplicationController def index # Remove YAML frontmatter so that it doesn't look weird - @help_index = File.read(Rails.root.join('doc', 'README.md')).sub(YAML_FRONT_MATTER_REGEXP, '') + @help_index = File.read(Rails.root.join("doc", "README.md")).sub(YAML_FRONT_MATTER_REGEXP, "") # Prefix Markdown links with `help/` unless they are external links. # '//' not necessarily part of URL, e.g., mailto:mail@example.com @@ -27,26 +27,26 @@ class HelpController < ApplicationController respond_to do |format| format.any(:markdown, :md, :html) do # Note: We are purposefully NOT using `Rails.root.join` - path = File.join(Rails.root, 'doc', "#{@path}.md") + path = File.join(Rails.root, "doc", "#{@path}.md") if File.exist?(path) # Remove YAML frontmatter so that it doesn't look weird - @markdown = File.read(path).gsub(YAML_FRONT_MATTER_REGEXP, '') + @markdown = File.read(path).gsub(YAML_FRONT_MATTER_REGEXP, "") - render 'show.html.haml' + render "show.html.haml" else # Force template to Haml - render 'errors/not_found.html.haml', layout: 'errors', status: 404 + render "errors/not_found.html.haml", layout: "errors", status: 404 end end # Allow access to images in the doc folder format.any(:png, :gif, :jpeg, :mp4) do # Note: We are purposefully NOT using `Rails.root.join` - path = File.join(Rails.root, 'doc', "#{@path}.#{params[:format]}") + path = File.join(Rails.root, "doc", "#{@path}.#{params[:format]}") if File.exist?(path) - send_file(path, disposition: 'inline') + send_file(path, disposition: "inline") else head :not_found end @@ -65,7 +65,7 @@ class HelpController < ApplicationController end def ui - @user = User.new(id: 0, name: 'John Doe', username: '@johndoe') + @user = User.new(id: 0, name: "John Doe", username: "@johndoe") end private @@ -88,9 +88,9 @@ class HelpController < ApplicationController # Walk over each part of the path parts.each do |part| # Turn `one//two` or `one/./two` into `one/two`. - next if part.empty? || part == '.' + next if part.empty? || part == "." - if part == '..' + if part == ".." # Turn `one/two/../` into `one` clean.pop else @@ -101,7 +101,7 @@ class HelpController < ApplicationController # If the path was an absolute path (i.e. `/` or `/one/two`), # add `/` to the front of the clean path. - clean.unshift '/' if parts.empty? || parts.first.empty? + clean.unshift "/" if parts.empty? || parts.first.empty? # Join all the clean path parts by the path separator. ::File.join(*clean) diff --git a/app/controllers/ide_controller.rb b/app/controllers/ide_controller.rb index eeeebe430a7..02ad604d87f 100644 --- a/app/controllers/ide_controller.rb +++ b/app/controllers/ide_controller.rb @@ -1,7 +1,7 @@ # frozen_string_literal: true class IdeController < ApplicationController - layout 'fullscreen' + layout "fullscreen" def index end diff --git a/app/controllers/import/base_controller.rb b/app/controllers/import/base_controller.rb index 9b45be6db99..27389018507 100644 --- a/app/controllers/import/base_controller.rb +++ b/app/controllers/import/base_controller.rb @@ -35,6 +35,6 @@ class Import::BaseController < ApplicationController # deprecated: being replaced by app/services/import/base_service.rb def project_save_error(project) - project.errors.full_messages.join(', ') + project.errors.full_messages.join(", ") end end diff --git a/app/controllers/import/bitbucket_controller.rb b/app/controllers/import/bitbucket_controller.rb index 2b1395f364f..70be7aa143b 100644 --- a/app/controllers/import/bitbucket_controller.rb +++ b/app/controllers/import/bitbucket_controller.rb @@ -25,7 +25,7 @@ class Import::BitbucketController < Import::BaseController @repos, @incompatible_repos = repos.partition { |repo| repo.valid? } - @already_added_projects = find_already_added_projects('bitbucket') + @already_added_projects = find_already_added_projects("bitbucket") already_added_projects_names = @already_added_projects.pluck(:import_source) @repos.to_a.reject! { |repo| already_added_projects_names.include?(repo.full_name) } @@ -33,14 +33,14 @@ class Import::BitbucketController < Import::BaseController # rubocop: enable CodeReuse/ActiveRecord def jobs - render json: find_jobs('bitbucket') + render json: find_jobs("bitbucket") end def create bitbucket_client = Bitbucket::Client.new(credentials) repo_id = params[:repo_id].to_s - name = repo_id.gsub('___', '/') + name = repo_id.gsub("___", "/") repo = bitbucket_client.repo(name) project_name = params[:new_name].presence || repo.name @@ -59,10 +59,10 @@ class Import::BitbucketController < Import::BaseController if project.persisted? render json: ProjectSerializer.new.represent(project) else - render json: { errors: project_save_error(project) }, status: :unprocessable_entity + render json: {errors: project_save_error(project)}, status: :unprocessable_entity end else - render json: { errors: 'This namespace has already been taken! Please choose another one.' }, status: :unprocessable_entity + render json: {errors: "This namespace has already been taken! Please choose another one."}, status: :unprocessable_entity end end @@ -73,7 +73,7 @@ class Import::BitbucketController < Import::BaseController end def provider - Gitlab::Auth::OAuth::Provider.config_for('bitbucket') + Gitlab::Auth::OAuth::Provider.config_for("bitbucket") end def options @@ -101,7 +101,7 @@ class Import::BitbucketController < Import::BaseController token: session[:bitbucket_token], expires_at: session[:bitbucket_expires_at], expires_in: session[:bitbucket_expires_in], - refresh_token: session[:bitbucket_refresh_token] + refresh_token: session[:bitbucket_refresh_token], } end end diff --git a/app/controllers/import/bitbucket_server_controller.rb b/app/controllers/import/bitbucket_server_controller.rb index f333e43b892..c495d2945a4 100644 --- a/app/controllers/import/bitbucket_server_controller.rb +++ b/app/controllers/import/bitbucket_server_controller.rb @@ -25,7 +25,7 @@ class Import::BitbucketServerController < Import::BaseController repo = bitbucket_client.repo(@project_key, @repo_slug) unless repo - return render json: { errors: "Project #{@project_key}/#{@repo_slug} could not be found" }, status: :unprocessable_entity + return render json: {errors: "Project #{@project_key}/#{@repo_slug} could not be found"}, status: :unprocessable_entity end project_name = params[:new_name].presence || repo.name @@ -38,13 +38,13 @@ class Import::BitbucketServerController < Import::BaseController if project.persisted? render json: ProjectSerializer.new.represent(project) else - render json: { errors: project_save_error(project) }, status: :unprocessable_entity + render json: {errors: project_save_error(project)}, status: :unprocessable_entity end else - render json: { errors: 'This namespace has already been taken! Please choose another one.' }, status: :unprocessable_entity + render json: {errors: "This namespace has already been taken! Please choose another one."}, status: :unprocessable_entity end rescue BitbucketServer::Connection::ConnectionError => e - render json: { errors: "Unable to connect to server: #{e}" }, status: :unprocessable_entity + render json: {errors: "Unable to connect to server: #{e}"}, status: :unprocessable_entity end def configure @@ -61,7 +61,7 @@ class Import::BitbucketServerController < Import::BaseController @repos, @incompatible_repos = @collection.partition { |repo| repo.valid? } # Use the import URL to filter beyond what BaseService#find_already_added_projects - @already_added_projects = filter_added_projects('bitbucket_server', @repos.map(&:browse_url)) + @already_added_projects = filter_added_projects("bitbucket_server", @repos.map(&:browse_url)) already_added_projects_names = @already_added_projects.pluck(:import_source) @repos.reject! { |repo| already_added_projects_names.include?(repo.browse_url) } @@ -73,7 +73,7 @@ class Import::BitbucketServerController < Import::BaseController # rubocop: enable CodeReuse/ActiveRecord def jobs - render json: find_jobs('bitbucket_server') + render json: find_jobs("bitbucket_server") end private @@ -92,14 +92,14 @@ class Import::BitbucketServerController < Import::BaseController @project_key = params[:project] @repo_slug = params[:repository] - return render_validation_error('Missing project key') unless @project_key.present? && @repo_slug.present? - return render_validation_error('Missing repository slug') unless @repo_slug.present? - return render_validation_error('Invalid project key') unless @project_key =~ VALID_BITBUCKET_PROJECT_CHARS - return render_validation_error('Invalid repository slug') unless @repo_slug =~ VALID_BITBUCKET_CHARS + return render_validation_error("Missing project key") unless @project_key.present? && @repo_slug.present? + return render_validation_error("Missing repository slug") unless @repo_slug.present? + return render_validation_error("Invalid project key") unless @project_key =~ VALID_BITBUCKET_PROJECT_CHARS + return render_validation_error("Invalid repository slug") unless @repo_slug =~ VALID_BITBUCKET_CHARS end def render_validation_error(message) - render json: { errors: message }, status: :unprocessable_entity + render json: {errors: message}, status: :unprocessable_entity end def bitbucket_auth @@ -136,7 +136,7 @@ class Import::BitbucketServerController < Import::BaseController { base_uri: session[bitbucket_server_url_key], user: session[bitbucket_server_username_key], - password: session[personal_access_token_key] + password: session[personal_access_token_key], } end diff --git a/app/controllers/import/fogbugz_controller.rb b/app/controllers/import/fogbugz_controller.rb index 5a439e6de78..a961f9c2d16 100644 --- a/app/controllers/import/fogbugz_controller.rb +++ b/app/controllers/import/fogbugz_controller.rb @@ -14,7 +14,7 @@ class Import::FogbugzController < Import::BaseController res = Gitlab::FogbugzImport::Client.new(import_params.symbolize_keys) rescue # If the URI is invalid various errors can occur - return redirect_to new_import_fogbugz_path, alert: 'Could not connect to FogBugz, check your URL' + return redirect_to new_import_fogbugz_path, alert: "Could not connect to FogBugz, check your URL" end session[:fogbugz_token] = res.get_token session[:fogbugz_uri] = params[:uri] @@ -29,14 +29,14 @@ class Import::FogbugzController < Import::BaseController user_map = params[:users] unless user_map.is_a?(Hash) && user_map.all? { |k, v| !v[:name].blank? } - flash.now[:alert] = 'All users must have a name.' + flash.now[:alert] = "All users must have a name." - return render 'new_user_map' + return render "new_user_map" end session[:fogbugz_user_map] = user_map - flash[:notice] = 'The user map has been saved. Continue by selecting the projects you want to import.' + flash[:notice] = "The user map has been saved. Continue by selecting the projects you want to import." redirect_to status_import_fogbugz_path end @@ -49,7 +49,7 @@ class Import::FogbugzController < Import::BaseController @repos = client.repos - @already_added_projects = find_already_added_projects('fogbugz') + @already_added_projects = find_already_added_projects("fogbugz") already_added_projects_names = @already_added_projects.pluck(:import_source) @repos.reject! { |repo| already_added_projects_names.include? repo.name } @@ -57,12 +57,12 @@ class Import::FogbugzController < Import::BaseController # rubocop: enable CodeReuse/ActiveRecord def jobs - render json: find_jobs('fogbugz') + render json: find_jobs("fogbugz") end def create repo = client.repo(params[:repo_id]) - fb_session = { uri: session[:fogbugz_uri], token: session[:fogbugz_token] } + fb_session = {uri: session[:fogbugz_uri], token: session[:fogbugz_token]} umap = session[:fogbugz_user_map] || client.user_map project = Gitlab::FogbugzImport::ProjectCreator.new(repo, fb_session, current_user.namespace, current_user, umap).execute @@ -70,7 +70,7 @@ class Import::FogbugzController < Import::BaseController if project.persisted? render json: ProjectSerializer.new.represent(project) else - render json: { errors: project_save_error(project) }, status: :unprocessable_entity + render json: {errors: project_save_error(project)}, status: :unprocessable_entity end end diff --git a/app/controllers/import/gitea_controller.rb b/app/controllers/import/gitea_controller.rb index 68ad8650dba..06fbd5ecae1 100644 --- a/app/controllers/import/gitea_controller.rb +++ b/app/controllers/import/gitea_controller.rb @@ -46,12 +46,12 @@ class Import::GiteaController < Import::GithubController def provider_auth if session[access_token_key].blank? || provider_url.blank? redirect_to new_import_gitea_url, - alert: 'You need to specify both an Access Token and a Host URL.' + alert: "You need to specify both an Access Token and a Host URL." end end override :client_options def client_options - { host: provider_url, api_version: 'v1' } + {host: provider_url, api_version: "v1"} end end diff --git a/app/controllers/import/github_controller.rb b/app/controllers/import/github_controller.rb index aa4aa0fbdac..1bb8c035659 100644 --- a/app/controllers/import/github_controller.rb +++ b/app/controllers/import/github_controller.rb @@ -34,9 +34,9 @@ class Import::GithubController < Import::BaseController respond_to do |format| format.json do - render json: { imported_projects: serialized_imported_projects, - provider_repos: serialized_provider_repos, - namespaces: serialized_namespaces } + render json: {imported_projects: serialized_imported_projects, + provider_repos: serialized_provider_repos, + namespaces: serialized_namespaces,} end format.html end @@ -48,7 +48,7 @@ class Import::GithubController < Import::BaseController if result[:status] == :success render json: serialized_imported_projects(result[:project]) else - render json: { errors: result[:message] }, status: result[:http_status] + render json: {errors: result[:message]}, status: result[:http_status] end end @@ -146,7 +146,7 @@ class Import::GithubController < Import::BaseController end def access_params - { github_access_token: session[access_token_key] } + {github_access_token: session[access_token_key]} end # The following methods are overridden in subclasses @@ -156,9 +156,9 @@ class Import::GithubController < Import::BaseController def provider_url strong_memoize(:provider_url) do - provider = Gitlab::Auth::OAuth::Provider.config_for('github') + provider = Gitlab::Auth::OAuth::Provider.config_for("github") - provider&.dig('url').presence || 'https://github.com' + provider&.dig("url").presence || "https://github.com" end end diff --git a/app/controllers/import/gitlab_controller.rb b/app/controllers/import/gitlab_controller.rb index 498de0b07b8..c07632f66cb 100644 --- a/app/controllers/import/gitlab_controller.rb +++ b/app/controllers/import/gitlab_controller.rb @@ -18,7 +18,7 @@ class Import::GitlabController < Import::BaseController def status @repos = client.projects(starting_page: 1, page_limit: MAX_PROJECT_PAGES, per_page: PER_PAGE_PROJECTS) - @already_added_projects = find_already_added_projects('gitlab') + @already_added_projects = find_already_added_projects("gitlab") already_added_projects_names = @already_added_projects.pluck(:import_source) @repos = @repos.to_a.reject { |repo| already_added_projects_names.include? repo["path_with_namespace"] } @@ -26,12 +26,12 @@ class Import::GitlabController < Import::BaseController # rubocop: enable CodeReuse/ActiveRecord def jobs - render json: find_jobs('gitlab') + render json: find_jobs("gitlab") end def create repo = client.project(params[:repo_id].to_i) - target_namespace = find_or_create_namespace(repo['namespace']['path'], client.user['username']) + target_namespace = find_or_create_namespace(repo["namespace"]["path"], client.user["username"]) if current_user.can?(:create_projects, target_namespace) project = Gitlab::GitlabImport::ProjectCreator.new(repo, target_namespace, current_user, access_params).execute @@ -39,10 +39,10 @@ class Import::GitlabController < Import::BaseController if project.persisted? render json: ProjectSerializer.new.represent(project) else - render json: { errors: project_save_error(project) }, status: :unprocessable_entity + render json: {errors: project_save_error(project)}, status: :unprocessable_entity end else - render json: { errors: 'This namespace has already been taken! Please choose another one.' }, status: :unprocessable_entity + render json: {errors: "This namespace has already been taken! Please choose another one."}, status: :unprocessable_entity end end @@ -71,6 +71,6 @@ class Import::GitlabController < Import::BaseController end def access_params - { gitlab_access_token: session[:gitlab_access_token] } + {gitlab_access_token: session[:gitlab_access_token]} end end diff --git a/app/controllers/import/gitlab_projects_controller.rb b/app/controllers/import/gitlab_projects_controller.rb index 354fba5d204..fc63db08a97 100644 --- a/app/controllers/import/gitlab_projects_controller.rb +++ b/app/controllers/import/gitlab_projects_controller.rb @@ -13,7 +13,7 @@ class Import::GitlabProjectsController < Import::BaseController def create unless file_is_valid? - return redirect_back_or_default(options: { alert: "You need to upload a GitLab project export archive (ending in .gz)." }) + return redirect_back_or_default(options: {alert: "You need to upload a GitLab project export archive (ending in .gz)."}) end @project = ::Projects::GitlabProjectsImportService.new(current_user, project_params).execute @@ -24,18 +24,18 @@ class Import::GitlabProjectsController < Import::BaseController notice: "Project '#{@project.name}' is being imported." ) else - redirect_back_or_default(options: { alert: "Project could not be imported: #{@project.errors.full_messages.join(', ')}" }) + redirect_back_or_default(options: {alert: "Project could not be imported: #{@project.errors.full_messages.join(", ")}"}) end end private def file_is_valid? - return false unless project_params[:file] && project_params[:file].respond_to?(:read) + return false unless project_params[:file]&.respond_to?(:read) filename = project_params[:file].original_filename - ImportExportUploader::EXTENSION_WHITELIST.include?(File.extname(filename).delete('.')) + ImportExportUploader::EXTENSION_WHITELIST.include?(File.extname(filename).delete(".")) end def verify_gitlab_project_import_enabled @@ -49,6 +49,6 @@ class Import::GitlabProjectsController < Import::BaseController end def whitelist_query_limiting - Gitlab::QueryLimiting.whitelist('https://gitlab.com/gitlab-org/gitlab-ce/issues/42437') + Gitlab::QueryLimiting.whitelist("https://gitlab.com/gitlab-org/gitlab-ce/issues/42437") end end diff --git a/app/controllers/import/google_code_controller.rb b/app/controllers/import/google_code_controller.rb index 331f06c3dd6..c00ee4b9ff8 100644 --- a/app/controllers/import/google_code_controller.rb +++ b/app/controllers/import/google_code_controller.rb @@ -11,18 +11,18 @@ class Import::GoogleCodeController < Import::BaseController dump_file = params[:dump_file] unless dump_file.respond_to?(:read) - return redirect_back_or_default(options: { alert: "You need to upload a Google Takeout archive." }) + return redirect_back_or_default(options: {alert: "You need to upload a Google Takeout archive."}) end begin dump = JSON.parse(dump_file.read) rescue - return redirect_back_or_default(options: { alert: "The uploaded file is not a valid Google Takeout archive." }) + return redirect_back_or_default(options: {alert: "The uploaded file is not a valid Google Takeout archive."}) end client = Gitlab::GoogleCodeImport::Client.new(dump) unless client.valid? - return redirect_back_or_default(options: { alert: "The uploaded file is not a valid Google Takeout archive." }) + return redirect_back_or_default(options: {alert: "The uploaded file is not a valid Google Takeout archive."}) end session[:google_code_dump] = dump @@ -76,7 +76,7 @@ class Import::GoogleCodeController < Import::BaseController @repos = client.repos @incompatible_repos = client.incompatible_repos - @already_added_projects = find_already_added_projects('google_code') + @already_added_projects = find_already_added_projects("google_code") already_added_projects_names = @already_added_projects.pluck(:import_source) @repos.reject! { |repo| already_added_projects_names.include? repo.name } @@ -84,7 +84,7 @@ class Import::GoogleCodeController < Import::BaseController # rubocop: enable CodeReuse/ActiveRecord def jobs - render json: find_jobs('google_code') + render json: find_jobs("google_code") end def create @@ -96,7 +96,7 @@ class Import::GoogleCodeController < Import::BaseController if project.persisted? render json: ProjectSerializer.new.represent(project) else - render json: { errors: project_save_error(project) }, status: :unprocessable_entity + render json: {errors: project_save_error(project)}, status: :unprocessable_entity end end diff --git a/app/controllers/import/manifest_controller.rb b/app/controllers/import/manifest_controller.rb index 320cd45b925..f27f5bcee42 100644 --- a/app/controllers/import/manifest_controller.rb +++ b/app/controllers/import/manifest_controller.rb @@ -13,9 +13,9 @@ class Import::ManifestController < Import::BaseController @already_added_projects = find_already_added_projects already_added_import_urls = @already_added_projects.pluck(:import_url) - @pending_repositories = repositories.to_a.reject do |repository| + @pending_repositories = repositories.to_a.reject { |repository| already_added_import_urls.include?(repository[:url]) - end + } end # rubocop: enable CodeReuse/ActiveRecord @@ -47,16 +47,16 @@ class Import::ManifestController < Import::BaseController end def create - repository = repositories.find do |project| + repository = repositories.find { |project| project[:id] == params[:repo_id].to_i - end + } project = Gitlab::ManifestImport::ProjectCreator.new(repository, group, current_user).execute if project.persisted? render json: ProjectSerializer.new.represent(project) else - render json: { errors: project_save_error(project) }, status: :unprocessable_entity + render json: {errors: project_save_error(project)}, status: :unprocessable_entity end end @@ -85,7 +85,7 @@ class Import::ManifestController < Import::BaseController # rubocop: disable CodeReuse/ActiveRecord def find_already_added_projects group.all_projects - .where(import_type: 'manifest') + .where(import_type: "manifest") .where(creator_id: current_user) .includes(:import_state) end @@ -96,6 +96,6 @@ class Import::ManifestController < Import::BaseController end def whitelist_query_limiting - Gitlab::QueryLimiting.whitelist('https://gitlab.com/gitlab-org/gitlab-ce/issues/48939') + Gitlab::QueryLimiting.whitelist("https://gitlab.com/gitlab-org/gitlab-ce/issues/48939") end end diff --git a/app/controllers/instance_statistics/application_controller.rb b/app/controllers/instance_statistics/application_controller.rb index a273dde105c..caeda57df26 100644 --- a/app/controllers/instance_statistics/application_controller.rb +++ b/app/controllers/instance_statistics/application_controller.rb @@ -2,7 +2,7 @@ class InstanceStatistics::ApplicationController < ApplicationController before_action :authorize_read_instance_statistics! - layout 'instance_statistics' + layout "instance_statistics" def authorize_read_instance_statistics! render_404 unless can?(current_user, :read_instance_statistics) diff --git a/app/controllers/instance_statistics/cohorts_controller.rb b/app/controllers/instance_statistics/cohorts_controller.rb index 4b4e39db2e1..574c4f1479b 100644 --- a/app/controllers/instance_statistics/cohorts_controller.rb +++ b/app/controllers/instance_statistics/cohorts_controller.rb @@ -5,9 +5,9 @@ class InstanceStatistics::CohortsController < InstanceStatistics::ApplicationCon def index if Gitlab::CurrentSettings.usage_ping_enabled - cohorts_results = Rails.cache.fetch('cohorts', expires_in: 1.day) do + cohorts_results = Rails.cache.fetch("cohorts", expires_in: 1.day) { CohortsService.new.execute - end + } @cohorts = CohortsSerializer.new.represent(cohorts_results) end diff --git a/app/controllers/invites_controller.rb b/app/controllers/invites_controller.rb index 315d1375e02..89e4a3486ae 100644 --- a/app/controllers/invites_controller.rb +++ b/app/controllers/invites_controller.rb @@ -15,7 +15,7 @@ class InvitesController < ApplicationController redirect_to path, notice: "You have been granted #{member.human_access} access to #{label}." else - redirect_back_or_default(options: { alert: "The invitation could not be accepted." }) + redirect_back_or_default(options: {alert: "The invitation could not be accepted."}) end end @@ -32,7 +32,7 @@ class InvitesController < ApplicationController redirect_to path, notice: "You have declined the invitation to join #{label}." else - redirect_back_or_default(options: { alert: "The invitation could not be declined." }) + redirect_back_or_default(options: {alert: "The invitation could not be declined."}) end end @@ -54,7 +54,7 @@ class InvitesController < ApplicationController notice = ["To accept this invitation, sign in"] notice << "or create an account" if Gitlab::CurrentSettings.allow_signup? - notice = notice.join(' ') + "." + notice = notice.join(" ") + "." store_location_for :user, request.fullpath redirect_to new_user_session_path, notice: notice diff --git a/app/controllers/jwt_controller.rb b/app/controllers/jwt_controller.rb index f9008a5b67e..83e98d3fb18 100644 --- a/app/controllers/jwt_controller.rb +++ b/app/controllers/jwt_controller.rb @@ -6,7 +6,7 @@ class JwtController < ApplicationController before_action :authenticate_project_or_user SERVICES = { - Auth::ContainerRegistryAuthenticationService::AUDIENCE => Auth::ContainerRegistryAuthenticationService + Auth::ContainerRegistryAuthenticationService::AUDIENCE => Auth::ContainerRegistryAuthenticationService, }.freeze def auth @@ -38,30 +38,30 @@ class JwtController < ApplicationController def render_missing_personal_access_token render json: { errors: [ - { code: 'UNAUTHORIZED', - message: "HTTP Basic: Access denied\n" \ + {code: "UNAUTHORIZED", + message: "HTTP Basic: Access denied\n" \ "You must use a personal access token with 'api' scope for Git over HTTP.\n" \ - "You can generate one at #{profile_personal_access_tokens_url}" } - ] + "You can generate one at #{profile_personal_access_tokens_url}",}, + ], }, status: :unauthorized end def render_unauthorized render json: { errors: [ - { code: 'UNAUTHORIZED', - message: 'HTTP Basic: Access denied' } - ] + {code: "UNAUTHORIZED", + message: "HTTP Basic: Access denied",}, + ], }, status: :unauthorized end def auth_params params.permit(:service, :account, :client_id) - .merge(additional_params) + .merge(additional_params) end def additional_params - { scopes: scopes_param }.compact + {scopes: scopes_param}.compact end # We have to parse scope here, because Docker Client does not send an array of scopes, @@ -72,6 +72,6 @@ class JwtController < ApplicationController def scopes_param return unless params[:scope].present? - Array(Rack::Utils.parse_query(request.query_string)['scope']) + Array(Rack::Utils.parse_query(request.query_string)["scope"]) end end diff --git a/app/controllers/ldap/omniauth_callbacks_controller.rb b/app/controllers/ldap/omniauth_callbacks_controller.rb index 5e872804448..0f64c1cc242 100644 --- a/app/controllers/ldap/omniauth_callbacks_controller.rb +++ b/app/controllers/ldap/omniauth_callbacks_controller.rb @@ -7,7 +7,7 @@ class Ldap::OmniauthCallbacksController < OmniauthCallbacksController return unless Gitlab::Auth::LDAP::Config.enabled? Gitlab::Auth::LDAP::Config.available_servers.each do |server| - alias_method server['provider_name'], :ldap + alias_method server["provider_name"], :ldap end end @@ -26,7 +26,7 @@ class Ldap::OmniauthCallbacksController < OmniauthCallbacksController override :fail_login def fail_login(user) - flash[:alert] = 'Access denied for your LDAP account.' + flash[:alert] = "Access denied for your LDAP account." redirect_to new_user_session_path end diff --git a/app/controllers/metrics_controller.rb b/app/controllers/metrics_controller.rb index c2089a0fca3..d39987615fd 100644 --- a/app/controllers/metrics_controller.rb +++ b/app/controllers/metrics_controller.rb @@ -7,15 +7,14 @@ class MetricsController < ActionController::Base def index response = if Gitlab::Metrics.prometheus_metrics_enabled? - metrics_service.metrics_text - else - help_page = help_page_url('administration/monitoring/prometheus/gitlab_metrics', - anchor: 'gitlab-prometheus-metrics' - ) - "# Metrics are disabled, see: #{help_page}\n" - end + metrics_service.metrics_text + else + help_page = help_page_url("administration/monitoring/prometheus/gitlab_metrics", + anchor: "gitlab-prometheus-metrics") + "# Metrics are disabled, see: #{help_page}\n" + end - render plain: response, content_type: 'text/plain; version=0.0.4' + render plain: response, content_type: "text/plain; version=0.0.4" end private diff --git a/app/controllers/notification_settings_controller.rb b/app/controllers/notification_settings_controller.rb index 43c4f4d220e..2a2e8af35a7 100644 --- a/app/controllers/notification_settings_controller.rb +++ b/app/controllers/notification_settings_controller.rb @@ -17,7 +17,7 @@ class NotificationSettingsController < ApplicationController @saved = @notification_setting.update(notification_setting_params_for(@notification_setting.source)) if params[:hide_label].present? - btn_class = params[:project_id].present? ? 'btn-xs' : '' + btn_class = params[:project_id].present? ? "btn-xs" : "" render_response("shared/notifications/_new_button", btn_class) else render_response @@ -45,7 +45,7 @@ class NotificationSettingsController < ApplicationController def render_response(response_template = "shared/notifications/_button", btn_class = nil) render json: { html: view_to_html_string(response_template, notification_setting: @notification_setting, btn_class: btn_class), - saved: @saved + saved: @saved, } end diff --git a/app/controllers/oauth/applications_controller.rb b/app/controllers/oauth/applications_controller.rb index ab4ca56bb49..91218dc5676 100644 --- a/app/controllers/oauth/applications_controller.rb +++ b/app/controllers/oauth/applications_controller.rb @@ -13,7 +13,7 @@ class Oauth::ApplicationsController < Doorkeeper::ApplicationsController helper_method :can? - layout 'profile' + layout "profile" def index set_index_vars diff --git a/app/controllers/oauth/authorizations_controller.rb b/app/controllers/oauth/authorizations_controller.rb index 705389749d8..dc0cb563458 100644 --- a/app/controllers/oauth/authorizations_controller.rb +++ b/app/controllers/oauth/authorizations_controller.rb @@ -1,7 +1,7 @@ # frozen_string_literal: true class Oauth::AuthorizationsController < Doorkeeper::AuthorizationsController - layout 'profile' + layout "profile" # Overridden from Doorkeeper::AuthorizationsController to # include the call to session.delete diff --git a/app/controllers/oauth/authorized_applications_controller.rb b/app/controllers/oauth/authorized_applications_controller.rb index a59ade559b3..801d3583360 100644 --- a/app/controllers/oauth/authorized_applications_controller.rb +++ b/app/controllers/oauth/authorized_applications_controller.rb @@ -3,7 +3,7 @@ class Oauth::AuthorizedApplicationsController < Doorkeeper::AuthorizedApplicationsController include PageLayoutHelper - layout 'profile' + layout "profile" def destroy if params[:token_id].present? @@ -13,7 +13,7 @@ class Oauth::AuthorizedApplicationsController < Doorkeeper::AuthorizedApplicatio end redirect_to applications_profile_url, - status: 302, - notice: I18n.t(:notice, scope: [:doorkeeper, :flash, :authorized_applications, :destroy]) + status: 302, + notice: I18n.t(:notice, scope: [:doorkeeper, :flash, :authorized_applications, :destroy]) end end diff --git a/app/controllers/omniauth_callbacks_controller.rb b/app/controllers/omniauth_callbacks_controller.rb index cc2bb99f55b..eda404acce7 100644 --- a/app/controllers/omniauth_callbacks_controller.rb +++ b/app/controllers/omniauth_callbacks_controller.rb @@ -34,7 +34,7 @@ class OmniauthCallbacksController < Devise::OmniauthCallbacksController error ||= exception.message if exception.respond_to?(:message) error ||= request.env["omniauth.error.type"].to_s - error.to_s.humanize if error + error&.to_s&.humanize end def saml @@ -44,28 +44,28 @@ class OmniauthCallbacksController < Devise::OmniauthCallbacksController def omniauth_error @provider = params[:provider] @error = params[:error] - render 'errors/omniauth_error', layout: "oauth_error", status: 422 + render "errors/omniauth_error", layout: "oauth_error", status: 422 end def cas3 - ticket = params['ticket'] + ticket = params["ticket"] if ticket - handle_service_ticket oauth['provider'], ticket + handle_service_ticket oauth["provider"], ticket end handle_omniauth end def authentiq - if params['sid'] - handle_service_ticket oauth['provider'], params['sid'] + if params["sid"] + handle_service_ticket oauth["provider"], params["sid"] end handle_omniauth end def auth0 - if oauth['uid'].blank? + if oauth["uid"].blank? fail_auth0_login else handle_omniauth @@ -75,12 +75,12 @@ class OmniauthCallbacksController < Devise::OmniauthCallbacksController private def omniauth_flow(auth_module, identity_linker: nil) - if fragment = request.env.dig('omniauth.params', 'redirect_fragment').presence + if fragment = request.env.dig("omniauth.params", "redirect_fragment").presence store_redirect_fragment(fragment) end if current_user - log_audit_event(current_user, with: oauth['provider']) + log_audit_event(current_user, with: oauth["provider"]) identity_linker ||= auth_module::IdentityLinker.new(current_user, oauth) @@ -107,7 +107,7 @@ class OmniauthCallbacksController < Devise::OmniauthCallbacksController end def redirect_identity_linked - redirect_to profile_account_path, notice: 'Authentication method updated' + redirect_to profile_account_path, notice: "Authentication method updated" end def handle_service_ticket(provider, ticket) @@ -125,7 +125,7 @@ class OmniauthCallbacksController < Devise::OmniauthCallbacksController user = auth_user.find_and_update! if auth_user.valid_sign_in? - log_audit_event(user, with: oauth['provider']) + log_audit_event(user, with: oauth["provider"]) set_remember_me(user) @@ -144,35 +144,35 @@ class OmniauthCallbacksController < Devise::OmniauthCallbacksController end def handle_signup_error - label = Gitlab::Auth::OAuth::Provider.label_for(oauth['provider']) + label = Gitlab::Auth::OAuth::Provider.label_for(oauth["provider"]) message = ["Signing in using your #{label} account without a pre-existing GitLab account is not allowed."] if Gitlab::CurrentSettings.allow_signup? message << "Create a GitLab account first, and then connect it to your #{label} account." end - flash[:notice] = message.join(' ') + flash[:notice] = message.join(" ") redirect_to new_user_session_path end def oauth - @oauth ||= request.env['omniauth.auth'] + @oauth ||= request.env["omniauth.auth"] end def fail_login(user) error_message = user.errors.full_messages.to_sentence - return redirect_to omniauth_error_path(oauth['provider'], error: error_message) + redirect_to omniauth_error_path(oauth["provider"], error: error_message) end def fail_auth0_login - flash[:alert] = 'Wrong extern UID provided. Make sure Auth0 is configured correctly.' + flash[:alert] = "Wrong extern UID provided. Make sure Auth0 is configured correctly." redirect_to new_user_session_path end def handle_disabled_provider - label = Gitlab::Auth::OAuth::Provider.label_for(oauth['provider']) + label = Gitlab::Auth::OAuth::Provider.label_for(oauth["provider"]) flash[:alert] = "Signing in using #{label} has been disabled" redirect_to new_user_session_path @@ -187,15 +187,15 @@ class OmniauthCallbacksController < Devise::OmniauthCallbacksController return unless remember_me? if user.two_factor_enabled? - params[:remember_me] = '1' + params[:remember_me] = "1" else remember_me(user) end end def remember_me? - request_params = request.env['omniauth.params'] - (request_params['remember_me'] == '1') if request_params.present? + request_params = request.env["omniauth.params"] + (request_params["remember_me"] == "1") if request_params.present? end def store_redirect_fragment(redirect_fragment) diff --git a/app/controllers/passwords_controller.rb b/app/controllers/passwords_controller.rb index 28f113b5cbe..924acca53ea 100644 --- a/app/controllers/passwords_controller.rb +++ b/app/controllers/passwords_controller.rb @@ -22,8 +22,8 @@ class PasswordsController < Devise::PasswordsController ).first_or_initialize unless user.reset_password_period_valid? - flash[:alert] = 'Your password reset token has expired.' - redirect_to(new_user_password_url(user_email: user['email'])) + flash[:alert] = "Your password reset token has expired." + redirect_to(new_user_password_url(user_email: user["email"])) end end end @@ -56,11 +56,11 @@ class PasswordsController < Devise::PasswordsController end def throttle_reset - return unless resource && resource.recently_sent_password_reset? + return unless resource&.recently_sent_password_reset? # Throttle reset attempts, but return a normal message to # avoid user enumeration attack. redirect_to new_user_session_path, - notice: I18n.t('devise.passwords.send_paranoid_instructions') + notice: I18n.t("devise.passwords.send_paranoid_instructions") end end diff --git a/app/controllers/profiles/application_controller.rb b/app/controllers/profiles/application_controller.rb index 52b046ef64f..6d8aecd75f3 100644 --- a/app/controllers/profiles/application_controller.rb +++ b/app/controllers/profiles/application_controller.rb @@ -1,5 +1,5 @@ # frozen_string_literal: true class Profiles::ApplicationController < ApplicationController - layout 'profile' + layout "profile" end diff --git a/app/controllers/profiles/keys_controller.rb b/app/controllers/profiles/keys_controller.rb index 055d900eece..927514a6727 100644 --- a/app/controllers/profiles/keys_controller.rb +++ b/app/controllers/profiles/keys_controller.rb @@ -48,7 +48,7 @@ class Profiles::KeysController < Profiles::ApplicationController render html: e.message end else - return render_404 + render_404 end end diff --git a/app/controllers/profiles/passwords_controller.rb b/app/controllers/profiles/passwords_controller.rb index a0391d677c4..318c1cfc66b 100644 --- a/app/controllers/profiles/passwords_controller.rb +++ b/app/controllers/profiles/passwords_controller.rb @@ -14,14 +14,14 @@ class Profiles::PasswordsController < Profiles::ApplicationController def create unless @user.password_automatically_set || @user.valid_password?(user_params[:current_password]) - redirect_to new_profile_password_path, alert: 'You must provide a valid current password' + redirect_to new_profile_password_path, alert: "You must provide a valid current password" return end password_attributes = { password: user_params[:password], password_confirmation: user_params[:password_confirmation], - password_automatically_set: false + password_automatically_set: false, } result = Users::UpdateService.new(current_user, password_attributes.merge(user: @user)).execute @@ -29,7 +29,7 @@ class Profiles::PasswordsController < Profiles::ApplicationController if result[:status] == :success Users::UpdateService.new(current_user, user: @user, password_expires_at: nil).execute - redirect_to root_path, notice: 'Password successfully changed' + redirect_to root_path, notice: "Password successfully changed" else render :new end @@ -39,13 +39,13 @@ class Profiles::PasswordsController < Profiles::ApplicationController end def update - password_attributes = user_params.select do |key, value| - %w(password password_confirmation).include?(key.to_s) - end + password_attributes = user_params.select { |key, value| + %w[password password_confirmation].include?(key.to_s) + } password_attributes[:password_automatically_set] = false unless @user.password_automatically_set || @user.valid_password?(user_params[:current_password]) - redirect_to edit_profile_password_path, alert: 'You must provide a valid current password' + redirect_to edit_profile_password_path, alert: "You must provide a valid current password" return end @@ -56,13 +56,13 @@ class Profiles::PasswordsController < Profiles::ApplicationController redirect_to new_user_session_path else @user.reload - render 'edit' + render "edit" end end def reset current_user.send_reset_password_instructions - redirect_to edit_profile_password_path, notice: 'We sent you an email with reset password instructions' + redirect_to edit_profile_password_path, notice: "We sent you an email with reset password instructions" end private @@ -73,9 +73,9 @@ class Profiles::PasswordsController < Profiles::ApplicationController def determine_layout if [:new, :create].include?(action_name.to_sym) - 'application' + "application" else - 'profile' + "profile" end end diff --git a/app/controllers/profiles/personal_access_tokens_controller.rb b/app/controllers/profiles/personal_access_tokens_controller.rb index 4b6ec2697b7..c516a7f74b7 100644 --- a/app/controllers/profiles/personal_access_tokens_controller.rb +++ b/app/controllers/profiles/personal_access_tokens_controller.rb @@ -33,7 +33,7 @@ class Profiles::PersonalAccessTokensController < Profiles::ApplicationController private def finder(options = {}) - PersonalAccessTokensFinder.new({ user: current_user, impersonation: false }.merge(options)) + PersonalAccessTokensFinder.new({user: current_user, impersonation: false}.merge(options)) end def personal_access_token_params @@ -44,8 +44,8 @@ class Profiles::PersonalAccessTokensController < Profiles::ApplicationController def set_index_vars @scopes = Gitlab::Auth.available_scopes(current_user) - @inactive_personal_access_tokens = finder(state: 'inactive').execute - @active_personal_access_tokens = finder(state: 'active').execute.order(:expires_at) + @inactive_personal_access_tokens = finder(state: "inactive").execute + @active_personal_access_tokens = finder(state: "active").execute.order(:expires_at) @new_personal_access_token = PersonalAccessToken.redis_getdel(current_user.id) end diff --git a/app/controllers/profiles/preferences_controller.rb b/app/controllers/profiles/preferences_controller.rb index 0227af2c266..80679ac168d 100644 --- a/app/controllers/profiles/preferences_controller.rb +++ b/app/controllers/profiles/preferences_controller.rb @@ -11,9 +11,9 @@ class Profiles::PreferencesController < Profiles::ApplicationController result = Users::UpdateService.new(current_user, preferences_params.merge(user: user)).execute if result[:status] == :success - flash[:notice] = 'Preferences saved.' + flash[:notice] = "Preferences saved." else - flash[:alert] = 'Failed to save preferences.' + flash[:alert] = "Failed to save preferences." end rescue ArgumentError => e # Raised when `dashboard` is given an invalid value. @@ -44,7 +44,7 @@ class Profiles::PreferencesController < Profiles::ApplicationController :project_view, :theme_id, :first_day_of_week, - :preferred_language + :preferred_language, ] end end diff --git a/app/controllers/profiles/two_factor_auths_controller.rb b/app/controllers/profiles/two_factor_auths_controller.rb index ba94196b2f9..49772d6c2a4 100644 --- a/app/controllers/profiles/two_factor_auths_controller.rb +++ b/app/controllers/profiles/two_factor_auths_controller.rb @@ -18,15 +18,15 @@ class Profiles::TwoFactorAuthsController < Profiles::ApplicationController two_factor_authentication_reason( global: lambda do flash.now[:alert] = - 'The global settings require you to enable Two-Factor Authentication for your account.' + "The global settings require you to enable Two-Factor Authentication for your account." end, group: lambda do |groups| group_links = groups.map { |group| view_context.link_to group.full_name, group_path(group) }.to_sentence - flash.now[:alert] = %{ + flash.now[:alert] = %( The group settings for #{group_links} require you to enable Two-Factor Authentication for your account. - }.html_safe + ).html_safe end ) @@ -47,12 +47,12 @@ class Profiles::TwoFactorAuthsController < Profiles::ApplicationController @codes = user.generate_otp_backup_codes! end - render 'create' + render "create" else - @error = 'Invalid pin code' + @error = "Invalid pin code" @qr_code = build_qr_code setup_u2f_registration - render 'show' + render "show" end end @@ -85,7 +85,7 @@ class Profiles::TwoFactorAuthsController < Profiles::ApplicationController def skip if two_factor_grace_period_expired? - redirect_to new_profile_two_factor_auth_path, alert: 'Cannot skip two factor authentication setup' + redirect_to new_profile_two_factor_auth_path, alert: "Cannot skip two factor authentication setup" else session[:skip_two_factor] = current_user.otp_grace_period_started_at + two_factor_grace_period.hours redirect_to root_path @@ -118,9 +118,9 @@ class Profiles::TwoFactorAuthsController < Profiles::ApplicationController sign_requests = u2f.authentication_requests(@u2f_registrations.map(&:key_handle)) session[:challenges] = registration_requests.map(&:challenge) - gon.push(u2f: { challenges: session[:challenges], app_id: u2f_app_id, - register_requests: registration_requests, - sign_requests: sign_requests }) + gon.push(u2f: {challenges: session[:challenges], app_id: u2f_app_id, + register_requests: registration_requests, + sign_requests: sign_requests,}) end def u2f_registration_params diff --git a/app/controllers/profiles_controller.rb b/app/controllers/profiles_controller.rb index b9c52618d4b..d112fe6aef0 100644 --- a/app/controllers/profiles_controller.rb +++ b/app/controllers/profiles_controller.rb @@ -17,10 +17,10 @@ class ProfilesController < Profiles::ApplicationController if result[:status] == :success message = "Profile was successfully updated" - format.html { redirect_back_or_default(default: { action: 'show' }, options: { notice: message }) } - format.json { render json: { message: message } } + format.html { redirect_back_or_default(default: {action: "show"}, options: {notice: message}) } + format.json { render json: {message: message} } else - format.html { redirect_back_or_default(default: { action: 'show' }, options: { alert: result[:message] }) } + format.html { redirect_back_or_default(default: {action: "show"}, options: {alert: result[:message]}) } format.json { render json: result } end end @@ -41,7 +41,7 @@ class ProfilesController < Profiles::ApplicationController user.reset_feed_token! end - flash[:notice] = 'Feed token was successfully reset' + flash[:notice] = "Feed token was successfully reset" redirect_to profile_personal_access_tokens_path end @@ -61,13 +61,13 @@ class ProfilesController < Profiles::ApplicationController if result[:status] == :success message = s_("Profiles|Username successfully changed") - format.html { redirect_back_or_default(default: { action: 'show' }, options: { notice: message }) } - format.json { render json: { message: message }, status: :ok } + format.html { redirect_back_or_default(default: {action: "show"}, options: {notice: message}) } + format.json { render json: {message: message}, status: :ok } else - message = s_("Profiles|Username change failed - %{message}") % { message: result[:message] } + message = s_("Profiles|Username change failed - %{message}") % {message: result[:message]} - format.html { redirect_back_or_default(default: { action: 'show' }, options: { alert: message }) } - format.json { render json: { message: message }, status: :unprocessable_entity } + format.html { redirect_back_or_default(default: {action: "show"}, options: {alert: message}) } + format.json { render json: {message: message}, status: :unprocessable_entity } end end end diff --git a/app/controllers/projects/application_controller.rb b/app/controllers/projects/application_controller.rb index e0677ce3fbc..87484068eeb 100644 --- a/app/controllers/projects/application_controller.rb +++ b/app/controllers/projects/application_controller.rb @@ -9,7 +9,7 @@ class Projects::ApplicationController < ApplicationController skip_before_action :authenticate_user! before_action :project before_action :repository - layout 'project' + layout "project" helper_method :repository, :can_collaborate_with_project?, :user_access @@ -38,7 +38,7 @@ class Projects::ApplicationController < ApplicationController def authorize_action!(action) unless can?(current_user, action, project) - return access_denied! + access_denied! end end @@ -48,7 +48,7 @@ class Projects::ApplicationController < ApplicationController def check_issuables_available! render_404 unless project.feature_available?(:issues, current_user) || - project.feature_available?(:merge_requests, current_user) + project.feature_available?(:merge_requests, current_user) end def method_missing(method_sym, *arguments, &block) diff --git a/app/controllers/projects/artifacts_controller.rb b/app/controllers/projects/artifacts_controller.rb index 2ef18d900f2..2f7025d44fc 100644 --- a/app/controllers/projects/artifacts_controller.rb +++ b/app/controllers/projects/artifacts_controller.rb @@ -5,7 +5,7 @@ class Projects::ArtifactsController < Projects::ApplicationController include RendersBlob include SendFileUpload - layout 'project' + layout "project" before_action :authorize_read_build! before_action :authorize_update_build!, only: [:keep] before_action :extract_ref_name_and_path @@ -20,7 +20,7 @@ class Projects::ArtifactsController < Projects::ApplicationController def browse @path = params[:path] - directory = @path ? "#{@path}/" : '' + directory = @path ? "#{@path}/" : "" @entry = build.artifacts_metadata_entry(directory) render_404 unless @entry.exists? @@ -35,7 +35,7 @@ class Projects::ArtifactsController < Projects::ApplicationController else respond_to do |format| format.html do - render 'file' + render "file" end format.json do diff --git a/app/controllers/projects/avatars_controller.rb b/app/controllers/projects/avatars_controller.rb index 1f4a25f82e9..e490cb64a73 100644 --- a/app/controllers/projects/avatars_controller.rb +++ b/app/controllers/projects/avatars_controller.rb @@ -15,6 +15,6 @@ class Projects::AvatarsController < Projects::ApplicationController @project.remove_avatar! @project.save - redirect_to edit_project_path(@project, anchor: 'js-general-project-settings'), status: :found + redirect_to edit_project_path(@project, anchor: "js-general-project-settings"), status: :found end end diff --git a/app/controllers/projects/badges_controller.rb b/app/controllers/projects/badges_controller.rb index 09a384e89ab..d8630114070 100644 --- a/app/controllers/projects/badges_controller.rb +++ b/app/controllers/projects/badges_controller.rb @@ -1,7 +1,7 @@ # frozen_string_literal: true class Projects::BadgesController < Projects::ApplicationController - layout 'project_settings' + layout "project_settings" before_action :authorize_admin_project!, only: [:index] before_action :no_cache_headers, except: [:index] @@ -23,12 +23,12 @@ class Projects::BadgesController < Projects::ApplicationController def badge_layout case params[:style] - when 'flat' - 'badge' - when 'flat-square' - 'badge_flat-square' + when "flat" + "badge" + when "flat-square" + "badge_flat-square" else - 'badge' + "badge" end end @@ -36,7 +36,7 @@ class Projects::BadgesController < Projects::ApplicationController respond_to do |format| format.html { render_404 } format.svg do - render badge_layout, locals: { badge: badge.template } + render badge_layout, locals: {badge: badge.template} end end end diff --git a/app/controllers/projects/blame_controller.rb b/app/controllers/projects/blame_controller.rb index 9076bdb9f04..c0836f8ae85 100644 --- a/app/controllers/projects/blame_controller.rb +++ b/app/controllers/projects/blame_controller.rb @@ -13,7 +13,7 @@ class Projects::BlameController < Projects::ApplicationController return render_404 unless @blob - environment_params = @repository.branch_exists?(@ref) ? { ref: @ref } : { commit: @commit } + environment_params = @repository.branch_exists?(@ref) ? {ref: @ref} : {commit: @commit} @environment = EnvironmentsFinder.new(@project, current_user, environment_params).execute.last @blame_groups = Gitlab::Blame.new(@blob, @commit).groups diff --git a/app/controllers/projects/blob_controller.rb b/app/controllers/projects/blob_controller.rb index 77672e7d9fc..0fc343336cc 100644 --- a/app/controllers/projects/blob_controller.rb +++ b/app/controllers/projects/blob_controller.rb @@ -55,7 +55,7 @@ class Projects::BlobController < Projects::ApplicationController if can_collaborate_with_project?(project, ref: @ref) blob.load_all_data! else - redirect_to action: 'show' + redirect_to action: "show" end end @@ -72,7 +72,7 @@ class Projects::BlobController < Projects::ApplicationController def preview @content = params[:content] @blob.load_all_data! - diffy = Diffy::Diff.new(@blob.data, @content, diff: '-U 3', include_diff_info: true) + diffy = Diffy::Diff.new(@blob.data, @content, diff: "-U 3", include_diff_info: true) diff_lines = diffy.diff.scan(/.*\n/)[2..-1] diff_lines = Gitlab::Diff::Parser.new.parse(diff_lines) @diff_lines = Gitlab::Diff::Highlight.new(diff_lines, repository: @repository).highlight @@ -98,10 +98,10 @@ class Projects::BlobController < Projects::ApplicationController @lines = @lines[@form.since - 1..@form.to - 1].map(&:html_safe) if @form.bottom? - @match_line = '' + @match_line = "" else lines_length = @lines.length - 1 - line = [@form.since, lines_length].join(',') + line = [@form.since, lines_length].join(",") @match_line = "@@ -#{line}+#{line} @@" end @@ -144,7 +144,7 @@ class Projects::BlobController < Projects::ApplicationController # Match line is not needed when it reaches the top limit or bottom limit of the file. return unless new_pos - @match_line = Gitlab::Diff::Line.new(@match_line, 'match', nil, old_pos, new_pos) + @match_line = Gitlab::Diff::Line.new(@match_line, "match", nil, old_pos, new_pos) @form.bottom? ? @lines.push(@match_line) : @lines.unshift(@match_line) end @@ -203,7 +203,7 @@ class Projects::BlobController < Projects::ApplicationController @branch_name = params[:branch_name] @file_path = - if action_name.to_s == 'create' + if action_name.to_s == "create" if params[:file].present? params[:file_name] = params[:file].original_filename end @@ -217,7 +217,7 @@ class Projects::BlobController < Projects::ApplicationController if params[:file].present? params[:content] = Base64.encode64(params[:file].read) - params[:encoding] = 'base64' + params[:encoding] = "base64" end @commit_params = { @@ -226,7 +226,7 @@ class Projects::BlobController < Projects::ApplicationController previous_path: @path, file_content: params[:content], file_content_encoding: params[:encoding], - last_commit_sha: params[:last_commit_sha] + last_commit_sha: params[:last_commit_sha], } end @@ -242,11 +242,11 @@ class Projects::BlobController < Projects::ApplicationController end def show_html - environment_params = @repository.branch_exists?(@ref) ? { ref: @ref } : { commit: @commit } + environment_params = @repository.branch_exists?(@ref) ? {ref: @ref} : {commit: @commit} @environment = EnvironmentsFinder.new(@project, current_user, environment_params).execute.last @last_commit = @repository.last_commit_for_path(@commit.id, @blob.path) - render 'show' + render "show" end def show_json @@ -269,15 +269,15 @@ class Projects::BlobController < Projects::ApplicationController blame_path: project_blame_path(project, @id), commits_path: project_commits_path(project, @id), tree_path: project_tree_path(project, File.join(@ref, tree_path)), - permalink: project_blob_path(project, File.join(@commit.id, @path)) + permalink: project_blob_path(project, File.join(@commit.id, @path)), } - json.merge!(blob_json(@blob) || {}) unless params[:viewer] == 'none' + json.merge!(blob_json(@blob) || {}) unless params[:viewer] == "none" render json: json end def tree_path - @path.rpartition('/').first + @path.rpartition("/").first end end diff --git a/app/controllers/projects/branches_controller.rb b/app/controllers/projects/branches_controller.rb index 32b7f3207ef..00c7fd9d000 100644 --- a/app/controllers/projects/branches_controller.rb +++ b/app/controllers/projects/branches_controller.rb @@ -16,7 +16,7 @@ class Projects::BranchesController < Projects::ApplicationController respond_to do |format| format.html do @sort = params[:sort].presence || sort_value_recently_updated - @mode = params[:state].presence || 'overview' + @mode = params[:state].presence || "overview" @overview_max_branches = 5 # Fetch branches for the specified mode @@ -27,11 +27,11 @@ class Projects::BranchesController < Projects::ApplicationController # n+1: https://gitlab.com/gitlab-org/gitaly/issues/992 Gitlab::GitalyClient.allow_n_plus_1_calls do - @max_commits = @branches.reduce(0) do |memo, branch| + @max_commits = @branches.reduce(0) { |memo, branch| diverging_commit_counts = repository.diverging_commit_counts(branch) [memo, diverging_commit_counts.values_at(:behind, :ahead, :distance)] .flatten.compact.max - end + } end # https://gitlab.com/gitlab-org/gitlab-ce/issues/48097 @@ -59,7 +59,7 @@ class Projects::BranchesController < Projects::ApplicationController redirect_to_autodeploy = project.empty_repo? && project.deployment_platform.present? result = CreateBranchService.new(project, current_user) - .execute(branch_name, ref) + .execute(branch_name, ref) success = (result[:status] == :success) @@ -79,13 +79,13 @@ class Projects::BranchesController < Projects::ApplicationController end else @error = result[:message] - render action: 'new' + render action: "new" end end format.json do if success - render json: { name: branch_name, url: project_tree_url(@project, branch_name) } + render json: {name: branch_name, url: project_tree_url(@project, branch_name)} else render json: result[:messsage], status: :unprocessable_entity end @@ -107,7 +107,7 @@ class Projects::BranchesController < Projects::ApplicationController end format.js { head result[:return_code] } - format.json { render json: { message: result[:message] }, status: result[:return_code] } + format.json { render json: {message: result[:message]}, status: result[:return_code] } end end @@ -115,7 +115,7 @@ class Projects::BranchesController < Projects::ApplicationController DeleteMergedBranchesService.new(@project, current_user).async_execute redirect_to project_branches_path(@project), - notice: 'Merged branches are being deleted. This can take some time depending on the number of branches. Please refresh the page to see changes.' + notice: "Merged branches are being deleted. This can take some time depending on the number of branches. Please refresh the page to see changes." end private @@ -125,7 +125,7 @@ class Projects::BranchesController < Projects::ApplicationController ref_escaped = sanitize(strip_tags(params[:ref])) Addressable::URI.unescape(ref_escaped) else - @project.default_branch || 'master' + @project.default_branch || "master" end end @@ -133,22 +133,22 @@ class Projects::BranchesController < Projects::ApplicationController project_new_blob_path( project, branch_name, - file_name: '.gitlab-ci.yml', - commit_message: 'Set up auto deploy', + file_name: ".gitlab-ci.yml", + commit_message: "Set up auto deploy", target_branch: branch_name, - context: 'autodeploy' + context: "autodeploy" ) end def redirect_for_legacy_index_sort_or_search # Normalize a legacy URL with redirect if request.format != :json && !params[:state].presence && [:sort, :search, :page].any? { |key| params[key].presence } - redirect_to project_branches_filtered_path(@project, state: 'all'), notice: 'Update your bookmarked URLs as filtered/sorted branches URL has been changed.' + redirect_to project_branches_filtered_path(@project, state: "all"), notice: "Update your bookmarked URLs as filtered/sorted branches URL has been changed." end end def fetch_branches_by_mode - if @mode == 'overview' + if @mode == "overview" # overview mode @active_branches, @stale_branches = BranchesFinder.new(@repository, sort: sort_value_recently_updated).execute.partition(&:active?) # Here we get one more branch to indicate if there are more data we're not showing diff --git a/app/controllers/projects/build_artifacts_controller.rb b/app/controllers/projects/build_artifacts_controller.rb index 4274c356227..7c1b98930f8 100644 --- a/app/controllers/projects/build_artifacts_controller.rb +++ b/app/controllers/projects/build_artifacts_controller.rb @@ -31,7 +31,7 @@ class Projects::BuildArtifactsController < Projects::ApplicationController private def validate_artifacts! - render_404 unless job && job.artifacts? + render_404 unless job&.artifacts? end def extract_ref_name_and_path diff --git a/app/controllers/projects/ci/lints_controller.rb b/app/controllers/projects/ci/lints_controller.rb index d7a0b7ece14..1a5841ea13a 100644 --- a/app/controllers/projects/ci/lints_controller.rb +++ b/app/controllers/projects/ci/lints_controller.rb @@ -27,7 +27,7 @@ class Projects::Ci::LintsController < Projects::ApplicationController { project: @project, user: current_user, - sha: project.repository.commit.sha + sha: project.repository.commit.sha, } end end diff --git a/app/controllers/projects/clusters_controller.rb b/app/controllers/projects/clusters_controller.rb index feda6deeaa6..b0d779a596c 100644 --- a/app/controllers/projects/clusters_controller.rb +++ b/app/controllers/projects/clusters_controller.rb @@ -6,7 +6,7 @@ class Projects::ClustersController < Clusters::ClustersController prepend_before_action :project before_action :repository - layout 'project' + layout "project" private diff --git a/app/controllers/projects/commit_controller.rb b/app/controllers/projects/commit_controller.rb index b13c0ae3967..59a0f43622c 100644 --- a/app/controllers/projects/commit_controller.rb +++ b/app/controllers/projects/commit_controller.rb @@ -56,8 +56,8 @@ class Projects::CommitController < Projects::ApplicationController .with_pagination(request, response) .represent(@pipelines), count: { - all: @pipelines.count - } + all: @pipelines.count, + }, } end end @@ -65,9 +65,9 @@ class Projects::CommitController < Projects::ApplicationController # rubocop: enable CodeReuse/ActiveRecord def merge_requests - @merge_requests = @commit.merge_requests.map do |mr| - { iid: mr.iid, path: merge_request_path(mr), title: mr.title } - end + @merge_requests = @commit.merge_requests.map { |mr| + {iid: mr.iid, path: merge_request_path(mr), title: mr.title} + } respond_to do |format| format.json do @@ -141,7 +141,7 @@ class Projects::CommitController < Projects::ApplicationController return git_not_found! unless commit opts = diff_options - opts[:ignore_whitespace_change] = true if params[:format] == 'diff' + opts[:ignore_whitespace_change] = true if params[:format] == "diff" @diffs = commit.diffs(opts) @notes_count = commit.notes.count @@ -155,8 +155,8 @@ class Projects::CommitController < Projects::ApplicationController @note = @project.build_commit_note(commit) @new_diff_note_attrs = { - noteable_type: 'Commit', - commit_id: @commit.id + noteable_type: "Commit", + commit_id: @commit.id, } @grouped_diff_discussions = commit.grouped_diff_discussions @@ -166,10 +166,8 @@ class Projects::CommitController < Projects::ApplicationController @merge_request = MergeRequestsFinder.new(current_user, project_id: @project.id).find_by(iid: merge_request_iid) if @merge_request - @new_diff_note_attrs.merge!( - noteable_type: 'MergeRequest', - noteable_id: @merge_request.id - ) + @new_diff_note_attrs[:noteable_type] = "MergeRequest" + @new_diff_note_attrs[:noteable_id] = @merge_request.id merge_request_commit_notes = @merge_request.notes.where(commit_id: @commit.id).inc_relations_for_view merge_request_commit_diff_discussions = merge_request_commit_notes.grouped_diff_discussions(@commit.diff_refs) @@ -186,6 +184,6 @@ class Projects::CommitController < Projects::ApplicationController def assign_change_commit_vars @start_branch = params[:start_branch] - @commit_params = { commit: @commit } + @commit_params = {commit: @commit} end end diff --git a/app/controllers/projects/commits_controller.rb b/app/controllers/projects/commits_controller.rb index 2510a31c9b3..62fa9b7c31e 100644 --- a/app/controllers/projects/commits_controller.rb +++ b/app/controllers/projects/commits_controller.rb @@ -25,14 +25,15 @@ class Projects::CommitsController < Projects::ApplicationController respond_to do |format| format.html - format.atom { render layout: 'xml.atom' } + format.atom { render layout: "xml.atom" } format.json do pager_json( - 'projects/commits/_commits', + "projects/commits/_commits", @commits.size, project: @project, - ref: @ref) + ref: @ref + ) end end end @@ -45,9 +46,9 @@ class Projects::CommitsController < Projects::ApplicationController signatures: @commits.select(&:has_signature?).map do |commit| { commit_sha: commit.sha, - html: view_to_html_string('projects/commit/_signature', signature: commit.signature) + html: view_to_html_string("projects/commit/_signature", signature: commit.signature), } - end + end, } end end @@ -76,6 +77,6 @@ class Projects::CommitsController < Projects::ApplicationController end def whitelist_query_limiting - Gitlab::QueryLimiting.whitelist('https://gitlab.com/gitlab-org/gitlab-ce/issues/42330') + Gitlab::QueryLimiting.whitelist("https://gitlab.com/gitlab-org/gitlab-ce/issues/42330") end end diff --git a/app/controllers/projects/compare_controller.rb b/app/controllers/projects/compare_controller.rb index 5586c2fc631..92a3a276d63 100644 --- a/app/controllers/projects/compare_controller.rb +++ b/app/controllers/projects/compare_controller.rb @@ -1,6 +1,6 @@ # frozen_string_literal: true -require 'addressable/uri' +require "addressable/uri" class Projects::CompareController < Projects::ApplicationController include DiffForPath @@ -39,12 +39,12 @@ class Projects::CompareController < Projects::ApplicationController flash[:alert] = "You must select a Source and a Target revision" from_to_vars = { from: params[:from].presence, - to: params[:to].presence + to: params[:to].presence, } redirect_to project_compare_index_path(@project, from_to_vars) else redirect_to project_compare_path(@project, - params[:from], params[:to]) + params[:from], params[:to]) end end @@ -55,9 +55,9 @@ class Projects::CompareController < Projects::ApplicationController signatures: @commits.select(&:has_signature?).map do |commit| { commit_sha: commit.sha, - html: view_to_html_string('projects/commit/_signature', signature: commit.signature) + html: view_to_html_string("projects/commit/_signature", signature: commit.signature), } - end + end, } end end @@ -100,7 +100,7 @@ class Projects::CompareController < Projects::ApplicationController def define_environment if compare - environment_params = @repository.branch_exists?(head_ref) ? { ref: head_ref } : { commit: compare.commit } + environment_params = @repository.branch_exists?(head_ref) ? {ref: head_ref} : {commit: compare.commit} @environment = EnvironmentsFinder.new(@project, current_user, environment_params).execute.last end end diff --git a/app/controllers/projects/cycle_analytics/events_controller.rb b/app/controllers/projects/cycle_analytics/events_controller.rb index fb43356ff10..47eebc34595 100644 --- a/app/controllers/projects/cycle_analytics/events_controller.rb +++ b/app/controllers/projects/cycle_analytics/events_controller.rb @@ -45,7 +45,7 @@ module Projects def render_events(events) respond_to do |format| format.html - format.json { render json: { events: events } } + format.json { render json: {events: events} } end end diff --git a/app/controllers/projects/cycle_analytics_controller.rb b/app/controllers/projects/cycle_analytics_controller.rb index 8c071496ba9..fc2afc74bf8 100644 --- a/app/controllers/projects/cycle_analytics_controller.rb +++ b/app/controllers/projects/cycle_analytics_controller.rb @@ -31,11 +31,11 @@ class Projects::CycleAnalyticsController < Projects::ApplicationController { summary: @cycle_analytics.summary, stats: @cycle_analytics.stats, - permissions: @cycle_analytics.permissions(user: current_user) + permissions: @cycle_analytics.permissions(user: current_user), } end def whitelist_query_limiting - Gitlab::QueryLimiting.whitelist('https://gitlab.com/gitlab-org/gitlab-ce/issues/42671') + Gitlab::QueryLimiting.whitelist("https://gitlab.com/gitlab-org/gitlab-ce/issues/42671") end end diff --git a/app/controllers/projects/deploy_keys_controller.rb b/app/controllers/projects/deploy_keys_controller.rb index 6824a07dc76..a087eef2617 100644 --- a/app/controllers/projects/deploy_keys_controller.rb +++ b/app/controllers/projects/deploy_keys_controller.rb @@ -8,11 +8,11 @@ class Projects::DeployKeysController < Projects::ApplicationController before_action :authorize_admin_project! before_action :authorize_update_deploy_key!, only: [:edit, :update] - layout 'project_settings' + layout "project_settings" def index respond_to do |format| - format.html { redirect_to_repository_settings(@project, anchor: 'js-deploy-keys-settings') } + format.html { redirect_to_repository_settings(@project, anchor: "js-deploy-keys-settings") } format.json do render json: Projects::Settings::DeployKeysPresenter.new(@project, current_user: current_user).as_json end @@ -20,17 +20,17 @@ class Projects::DeployKeysController < Projects::ApplicationController end def new - redirect_to_repository_settings(@project, anchor: 'js-deploy-keys-settings') + redirect_to_repository_settings(@project, anchor: "js-deploy-keys-settings") end def create @key = DeployKeys::CreateService.new(current_user, create_params).execute(project: @project) unless @key.valid? - flash[:alert] = @key.errors.full_messages.join(', ').html_safe + flash[:alert] = @key.errors.full_messages.join(", ").html_safe end - redirect_to_repository_settings(@project, anchor: 'js-deploy-keys-settings') + redirect_to_repository_settings(@project, anchor: "js-deploy-keys-settings") end def edit @@ -38,10 +38,10 @@ class Projects::DeployKeysController < Projects::ApplicationController def update if deploy_key.update(update_params) - flash[:notice] = 'Deploy key was successfully updated.' - redirect_to_repository_settings(@project, anchor: 'js-deploy-keys-settings') + flash[:notice] = "Deploy key was successfully updated." + redirect_to_repository_settings(@project, anchor: "js-deploy-keys-settings") else - render 'edit' + render "edit" end end @@ -51,7 +51,7 @@ class Projects::DeployKeysController < Projects::ApplicationController return render_404 unless key respond_to do |format| - format.html { redirect_to_repository_settings(@project, anchor: 'js-deploy-keys-settings') } + format.html { redirect_to_repository_settings(@project, anchor: "js-deploy-keys-settings") } format.json { head :ok } end end @@ -62,7 +62,7 @@ class Projects::DeployKeysController < Projects::ApplicationController return render_404 unless deploy_key_project respond_to do |format| - format.html { redirect_to_repository_settings(@project, anchor: 'js-deploy-keys-settings') } + format.html { redirect_to_repository_settings(@project, anchor: "js-deploy-keys-settings") } format.json { head :ok } end end @@ -75,8 +75,8 @@ class Projects::DeployKeysController < Projects::ApplicationController def create_params create_params = params.require(:deploy_key) - .permit(:key, :title, deploy_keys_projects_attributes: [:can_push]) - create_params.dig(:deploy_keys_projects_attributes, '0')&.merge!(project_id: @project.id) + .permit(:key, :title, deploy_keys_projects_attributes: [:can_push]) + create_params.dig(:deploy_keys_projects_attributes, "0")&.merge!(project_id: @project.id) create_params end diff --git a/app/controllers/projects/deploy_tokens_controller.rb b/app/controllers/projects/deploy_tokens_controller.rb index 830b1f4fe4a..eed3fe216a9 100644 --- a/app/controllers/projects/deploy_tokens_controller.rb +++ b/app/controllers/projects/deploy_tokens_controller.rb @@ -7,6 +7,6 @@ class Projects::DeployTokensController < Projects::ApplicationController @token = @project.deploy_tokens.find(params[:id]) @token.revoke! - redirect_to project_settings_repository_path(project, anchor: 'js-deploy-tokens') + redirect_to project_settings_repository_path(project, anchor: "js-deploy-tokens") end end diff --git a/app/controllers/projects/deployments_controller.rb b/app/controllers/projects/deployments_controller.rb index 0a009477d61..9854212ddf5 100644 --- a/app/controllers/projects/deployments_controller.rb +++ b/app/controllers/projects/deployments_controller.rb @@ -7,10 +7,10 @@ class Projects::DeploymentsController < Projects::ApplicationController # rubocop: disable CodeReuse/ActiveRecord def index deployments = environment.deployments.reorder(created_at: :desc) - deployments = deployments.where('created_at > ?', params[:after].to_time) if params[:after]&.to_time + deployments = deployments.where("created_at > ?", params[:after].to_time) if params[:after]&.to_time - render json: { deployments: DeploymentSerializer.new(project: project) - .represent_concise(deployments) } + render json: {deployments: DeploymentSerializer.new(project: project) + .represent_concise(deployments)} end # rubocop: enable CodeReuse/ActiveRecord diff --git a/app/controllers/projects/discussions_controller.rb b/app/controllers/projects/discussions_controller.rb index 028390c7e2a..eae96f4d9d7 100644 --- a/app/controllers/projects/discussions_controller.rb +++ b/app/controllers/projects/discussions_controller.rb @@ -23,7 +23,7 @@ class Projects::DiscussionsController < Projects::ApplicationController def show render json: { - truncated_diff_lines: discussion.try(:truncated_diff_lines) + truncated_diff_lines: discussion.try(:truncated_diff_lines), } end @@ -41,14 +41,14 @@ class Projects::DiscussionsController < Projects::ApplicationController def render_json_with_discussions_serializer render json: DiscussionSerializer.new(project: project, noteable: discussion.noteable, current_user: current_user, note_entity: ProjectNoteEntity) - .represent(discussion, context: self, render_truncated_diff_lines: true) + .represent(discussion, context: self, render_truncated_diff_lines: true) end # Legacy method used to render discussions notes when not using Vue on views. def render_json_with_html render json: { resolved_by: discussion.resolved_by.try(:name), - discussion_headline_html: view_to_html_string('discussions/_headline', discussion: discussion) + discussion_headline_html: view_to_html_string("discussions/_headline", discussion: discussion), } end diff --git a/app/controllers/projects/environments_controller.rb b/app/controllers/projects/environments_controller.rb index e9cd475a199..9263fc6789c 100644 --- a/app/controllers/projects/environments_controller.rb +++ b/app/controllers/projects/environments_controller.rb @@ -1,7 +1,7 @@ # frozen_string_literal: true class Projects::EnvironmentsController < Projects::ApplicationController - layout 'project' + layout "project" before_action :authorize_read_environment! before_action :authorize_create_environment!, only: [:new, :create] before_action :authorize_stop_environment!, only: [:stop] @@ -23,7 +23,7 @@ class Projects::EnvironmentsController < Projects::ApplicationController render json: { environments: serialize_environments(request, response, params[:nested]), available_count: project.environments.available.count, - stopped_count: project.environments.stopped.count + stopped_count: project.environments.stopped.count, } end end @@ -43,7 +43,7 @@ class Projects::EnvironmentsController < Projects::ApplicationController render json: { environments: serialize_environments(request, response), available_count: folder_environments.available.count, - stopped_count: folder_environments.stopped.count + stopped_count: folder_environments.stopped.count, } end end @@ -95,7 +95,7 @@ class Projects::EnvironmentsController < Projects::ApplicationController respond_to do |format| format.html { redirect_to action_or_env_url } - format.json { render json: { redirect_url: action_or_env_url } } + format.json { render json: {redirect_url: action_or_env_url} } end end @@ -116,7 +116,7 @@ class Projects::EnvironmentsController < Projects::ApplicationController set_workhorse_internal_api_content_type render json: Gitlab::Workhorse.terminal_websocket(terminal) else - render html: 'Not found', status: :not_found + render html: "Not found", status: :not_found end end diff --git a/app/controllers/projects/error_tracking_controller.rb b/app/controllers/projects/error_tracking_controller.rb index 88d0755f41f..b84bf09518b 100644 --- a/app/controllers/projects/error_tracking_controller.rb +++ b/app/controllers/projects/error_tracking_controller.rb @@ -30,13 +30,13 @@ class Projects::ErrorTrackingController < Projects::ApplicationController result = service.execute unless result[:status] == :success - return render json: { message: result[:message] }, + return render json: {message: result[:message]}, status: result[:http_status] || :bad_request end render json: { errors: serialize_errors(result[:issues]), - external_url: service.external_url + external_url: service.external_url, } end @@ -50,13 +50,13 @@ class Projects::ErrorTrackingController < Projects::ApplicationController if result[:status] == :success render json: { - projects: serialize_projects(result[:projects]) + projects: serialize_projects(result[:projects]), } else return render( status: result[:http_status] || :bad_request, json: { - message: result[:message] + message: result[:message], } ) end diff --git a/app/controllers/projects/forks_controller.rb b/app/controllers/projects/forks_controller.rb index 7a1700a206a..f40baa0d7c5 100644 --- a/app/controllers/projects/forks_controller.rb +++ b/app/controllers/projects/forks_controller.rb @@ -25,7 +25,7 @@ class Projects::ForksController < Projects::ApplicationController format.json do render json: { - html: view_to_html_string("projects/forks/_projects", projects: @forks) + html: view_to_html_string("projects/forks/_projects", projects: @forks), } end end @@ -63,6 +63,6 @@ class Projects::ForksController < Projects::ApplicationController # rubocop: enable CodeReuse/ActiveRecord def whitelist_query_limiting - Gitlab::QueryLimiting.whitelist('https://gitlab.com/gitlab-org/gitlab-ce/issues/42335') + Gitlab::QueryLimiting.whitelist("https://gitlab.com/gitlab-org/gitlab-ce/issues/42335") end end diff --git a/app/controllers/projects/git_http_client_controller.rb b/app/controllers/projects/git_http_client_controller.rb index d439db97252..82de4de4db0 100644 --- a/app/controllers/projects/git_http_client_controller.rb +++ b/app/controllers/projects/git_http_client_controller.rb @@ -11,8 +11,8 @@ class Projects::GitHttpClientController < Projects::ApplicationController delegate :actor, :authentication_abilities, to: :authentication_result, allow_nil: true delegate :type, to: :authentication_result, allow_nil: true, prefix: :auth_result - alias_method :user, :actor - alias_method :authenticated_user, :actor + alias user actor + alias authenticated_user actor # Git clients will not know what authenticity token to send along skip_before_action :verify_authenticity_token @@ -43,7 +43,8 @@ class Projects::GitHttpClientController < Projects::ApplicationController if kerberos_user @authentication_result = Gitlab::Auth::Result.new( - kerberos_user, nil, :kerberos, Gitlab::Auth.full_authentication_abilities) + kerberos_user, nil, :kerberos, Gitlab::Auth.full_authentication_abilities + ) send_final_spnego_response return # Allow access @@ -68,7 +69,7 @@ class Projects::GitHttpClientController < Projects::ApplicationController challenges = [] challenges << 'Basic realm="GitLab"' if allow_basic_auth? challenges << spnego_challenge if allow_kerberos_spnego_auth? - headers['Www-Authenticate'] = challenges.join("\n") if challenges.any? + headers["Www-Authenticate"] = challenges.join("\n") if challenges.any? end def project @@ -100,7 +101,8 @@ class Projects::GitHttpClientController < Projects::ApplicationController def handle_basic_authentication(login, password) @authentication_result = Gitlab::Auth.find_for_git_client( - login, password, project: project, ip: request.ip) + login, password, project: project, ip: request.ip + ) @authentication_result.success? end diff --git a/app/controllers/projects/git_http_controller.rb b/app/controllers/projects/git_http_controller.rb index 0c5328fc941..2342d3deee4 100644 --- a/app/controllers/projects/git_http_controller.rb +++ b/app/controllers/projects/git_http_controller.rb @@ -37,11 +37,11 @@ class Projects::GitHttpController < Projects::GitHttpClientController end def upload_pack? - git_command == 'git-upload-pack' + git_command == "git-upload-pack" end def git_command - if action_name == 'info_refs' + if action_name == "info_refs" params[:service] else action_name.dasherize @@ -78,7 +78,7 @@ class Projects::GitHttpController < Projects::GitHttpClientController def access @access ||= access_klass.new(access_actor, project, - 'http', authentication_abilities: authentication_abilities, + "http", authentication_abilities: authentication_abilities, namespace_path: params[:namespace_id], project_path: project_path, redirected_path: redirected_path, auth_result_type: auth_result_type) end @@ -98,10 +98,10 @@ class Projects::GitHttpController < Projects::GitHttpClientController end def project_path - @project_path ||= params[:project_id].sub(/\.git$/, '') + @project_path ||= params[:project_id].sub(/\.git$/, "") end def log_user_activity - Users::ActivityService.new(user, 'pull').execute + Users::ActivityService.new(user, "pull").execute end end diff --git a/app/controllers/projects/graphs_controller.rb b/app/controllers/projects/graphs_controller.rb index c80fce513f6..e25e1c10958 100644 --- a/app/controllers/projects/graphs_controller.rb +++ b/app/controllers/projects/graphs_controller.rb @@ -18,11 +18,11 @@ class Projects::GraphsController < Projects::ApplicationController end def commits - redirect_to action: 'charts' + redirect_to action: "charts" end def languages - redirect_to action: 'charts' + redirect_to action: "charts" end def charts @@ -48,7 +48,7 @@ class Projects::GraphsController < Projects::ApplicationController @languages = if @project.repository_languages.present? @project.repository_languages.map do |lang| - { value: lang.share, label: lang.name, color: lang.color, highlight: lang.color } + {value: lang.share, label: lang.name, color: lang.color, highlight: lang.color} end else @project.repository.languages @@ -63,7 +63,7 @@ class Projects::GraphsController < Projects::ApplicationController @log << { author_name: commit.author_name, author_email: commit.author_email, - date: commit.committed_date.strftime("%Y-%m-%d") + date: commit.committed_date.strftime("%Y-%m-%d"), } end diff --git a/app/controllers/projects/group_links_controller.rb b/app/controllers/projects/group_links_controller.rb index 7c713c19762..3bfb5636241 100644 --- a/app/controllers/projects/group_links_controller.rb +++ b/app/controllers/projects/group_links_controller.rb @@ -1,7 +1,7 @@ # frozen_string_literal: true class Projects::GroupLinksController < Projects::ApplicationController - layout 'project_settings' + layout "project_settings" before_action :authorize_admin_project! before_action :authorize_admin_project_member!, only: [:update] @@ -17,7 +17,7 @@ class Projects::GroupLinksController < Projects::ApplicationController Projects::GroupLinks::CreateService.new(project, current_user, group_link_create_params).execute(group) else - flash[:alert] = 'Please select a group.' + flash[:alert] = "Please select a group." end redirect_to project_project_members_path(project) diff --git a/app/controllers/projects/hook_logs_controller.rb b/app/controllers/projects/hook_logs_controller.rb index a7afc3d77a5..1b251e87d5e 100644 --- a/app/controllers/projects/hook_logs_controller.rb +++ b/app/controllers/projects/hook_logs_controller.rb @@ -10,7 +10,7 @@ class Projects::HookLogsController < Projects::ApplicationController respond_to :html - layout 'project_settings' + layout "project_settings" def show end diff --git a/app/controllers/projects/hooks_controller.rb b/app/controllers/projects/hooks_controller.rb index bc84418b79f..4c768cb641d 100644 --- a/app/controllers/projects/hooks_controller.rb +++ b/app/controllers/projects/hooks_controller.rb @@ -32,10 +32,10 @@ class Projects::HooksController < Projects::ApplicationController def update if hook.update(hook_params) - flash[:notice] = 'Hook was successfully updated.' + flash[:notice] = "Hook was successfully updated." redirect_to project_settings_integrations_path(@project) else - render 'edit' + render "edit" end end @@ -44,7 +44,7 @@ class Projects::HooksController < Projects::ApplicationController set_hook_execution_notice(result) - redirect_back_or_default(default: { action: 'index' }) + redirect_back_or_default(default: {action: "index"}) end def destroy diff --git a/app/controllers/projects/imports_controller.rb b/app/controllers/projects/imports_controller.rb index 8b33fa85c1e..9d689402282 100644 --- a/app/controllers/projects/imports_controller.rb +++ b/app/controllers/projects/imports_controller.rb @@ -42,9 +42,9 @@ class Projects::ImportsController < Projects::ApplicationController def finished_notice if @project.forked? - 'The project was successfully forked.' + "The project was successfully forked." else - 'The project was successfully imported.' + "The project was successfully imported." end end diff --git a/app/controllers/projects/issues_controller.rb b/app/controllers/projects/issues_controller.rb index b9d02a62fc3..6d25ec310f7 100644 --- a/app/controllers/projects/issues_controller.rb +++ b/app/controllers/projects/issues_controller.rb @@ -49,11 +49,11 @@ class Projects::IssuesController < Projects::ApplicationController respond_to do |format| format.html - format.atom { render layout: 'xml.atom' } + format.atom { render layout: "xml.atom" } format.json do render json: { html: view_to_html_string("projects/issues/_issues"), - labels: @labels.as_json(methods: :text_color) + labels: @labels.as_json(methods: :text_color), } end end @@ -95,10 +95,10 @@ class Projects::IssuesController < Projects::ApplicationController if service.discussions_to_resolve.count(&:resolved?) > 0 flash[:notice] = if service.discussion_to_resolve_id - "Resolved 1 discussion." - else - "Resolved all discussions." - end + "Resolved 1 discussion." + else + "Resolved all discussions." + end end respond_to do |format| @@ -126,7 +126,6 @@ class Projects::IssuesController < Projects::ApplicationController render_issue_json end end - rescue ActiveRecord::StaleObjectError render_conflict_response end @@ -137,7 +136,7 @@ class Projects::IssuesController < Projects::ApplicationController respond_to do |format| format.json do render json: { - html: view_to_html_string('projects/issues/_merge_requests') + html: view_to_html_string("projects/issues/_merge_requests"), } end end @@ -149,7 +148,7 @@ class Projects::IssuesController < Projects::ApplicationController respond_to do |format| format.json do render json: { - html: view_to_html_string('projects/issues/_related_branches') + html: view_to_html_string("projects/issues/_related_branches"), } end end @@ -162,7 +161,7 @@ class Projects::IssuesController < Projects::ApplicationController respond_to do |format| format.json do - render json: { can_create_branch: can_create, suggested_branch_name: @issue.suggested_branch_name } + render json: {can_create_branch: can_create, suggested_branch_name: @issue.suggested_branch_name} end end end @@ -209,10 +208,10 @@ class Projects::IssuesController < Projects::ApplicationController @issue end # rubocop: enable CodeReuse/ActiveRecord - alias_method :subscribable_resource, :issue - alias_method :issuable, :issue - alias_method :awardable, :issue - alias_method :spammable, :issue + alias subscribable_resource issue + alias issuable issue + alias awardable issue + alias spammable issue def spammable_path project_issue_path(@project, @issue) @@ -226,7 +225,7 @@ class Projects::IssuesController < Projects::ApplicationController if @issue.valid? render json: serializer.represent(@issue) else - render json: { errors: @issue.errors.full_messages }, status: :unprocessable_entity + render json: {errors: @issue.errors.full_messages}, status: :unprocessable_entity end end @@ -247,7 +246,7 @@ class Projects::IssuesController < Projects::ApplicationController task_num lock_version discussion_locked - ] + [{ label_ids: [], assignee_ids: [], update_task: [:index, :checked, :line_number, :line_source] }] + ] + [{label_ids: [], assignee_ids: [], update_task: [:index, :checked, :line_number, :line_source]}] end def store_uri @@ -275,7 +274,7 @@ class Projects::IssuesController < Projects::ApplicationController # 1. https://gitlab.com/gitlab-org/gitlab-ce/issues/42423 # 2. https://gitlab.com/gitlab-org/gitlab-ce/issues/42424 # 3. https://gitlab.com/gitlab-org/gitlab-ce/issues/42426 - Gitlab::QueryLimiting.whitelist('https://gitlab.com/gitlab-org/gitlab-ce/issues/42422') + Gitlab::QueryLimiting.whitelist("https://gitlab.com/gitlab-org/gitlab-ce/issues/42422") end def set_suggested_issues_feature_flags diff --git a/app/controllers/projects/jobs_controller.rb b/app/controllers/projects/jobs_controller.rb index d5ce790e2d9..b8435620feb 100644 --- a/app/controllers/projects/jobs_controller.rb +++ b/app/controllers/projects/jobs_controller.rb @@ -12,28 +12,28 @@ class Projects::JobsController < Projects::ApplicationController before_action :authorize_use_build_terminal!, only: [:terminal, :terminal_websocket_authorize] before_action :verify_api_request!, only: :terminal_websocket_authorize - layout 'project' + layout "project" # rubocop: disable CodeReuse/ActiveRecord def index @scope = params[:scope] @all_builds = project.builds.relevant - @builds = @all_builds.order('ci_builds.id DESC') + @builds = @all_builds.order("ci_builds.id DESC") @builds = case @scope - when 'pending' + when "pending" @builds.pending.reverse_order - when 'running' + when "running" @builds.running.reverse_order - when 'finished' + when "finished" @builds.finished else @builds end @builds = @builds.includes([ - { pipeline: :project }, + {pipeline: :project}, :project, - :tags + :tags, ]) @builds = @builds.page(params[:page]).per(30).without_count end @@ -43,7 +43,7 @@ class Projects::JobsController < Projects::ApplicationController def show @pipeline = @build.pipeline @builds = @pipeline.builds - .order('id DESC') + .order("id DESC") .present(current_user: current_user) respond_to do |format| @@ -64,7 +64,7 @@ class Projects::JobsController < Projects::ApplicationController respond_to do |format| format.json do result = { - id: @build.id, status: @build.status, complete: @build.complete? + id: @build.id, status: @build.status, complete: @build.complete?, } if stream.valid? @@ -122,7 +122,7 @@ class Projects::JobsController < Projects::ApplicationController def erase if @build.erase(erased_by: current_user) redirect_to project_job_path(project, @build), - notice: "Job has been successfully erased!" + notice: "Job has been successfully erased!" else respond_422 end @@ -132,20 +132,20 @@ class Projects::JobsController < Projects::ApplicationController if trace_artifact_file workhorse_set_content_type! send_upload(trace_artifact_file, - send_params: raw_send_params, - redirect_params: raw_redirect_params) + send_params: raw_send_params, + redirect_params: raw_redirect_params) else build.trace.read do |stream| if stream.file? workhorse_set_content_type! - send_file stream.path, type: 'text/plain; charset=utf-8', disposition: 'inline' + send_file stream.path, type: "text/plain; charset=utf-8", disposition: "inline" else # In this case we can't use workhorse_set_content_type! and let # Workhorse handle the response because the data is streamed directly # to the user but, because we have the trace content, we can calculate # the proper content type and disposition here. raw_data = stream.raw - send_data raw_data, type: 'text/plain; charset=utf-8', disposition: raw_trace_content_disposition(raw_data), filename: 'job.log' + send_data raw_data, type: "text/plain; charset=utf-8", disposition: raw_trace_content_disposition(raw_data), filename: "job.log" end end end @@ -179,11 +179,11 @@ class Projects::JobsController < Projects::ApplicationController end def raw_send_params - { type: 'text/plain; charset=utf-8', disposition: 'inline' } + {type: "text/plain; charset=utf-8", disposition: "inline"} end def raw_redirect_params - { query: { 'response-content-type' => 'text/plain; charset=utf-8', 'response-content-disposition' => 'inline' } } + {query: {"response-content-type" => "text/plain; charset=utf-8", "response-content-disposition" => "inline"}} end def trace_artifact_file @@ -203,8 +203,8 @@ class Projects::JobsController < Projects::ApplicationController mime_type = MimeMagic.by_magic(raw_data) # if mime_type is nil can also represent 'text/plain' - return 'inline' if mime_type.nil? || mime_type.type == 'text/plain' + return "inline" if mime_type.nil? || mime_type.type == "text/plain" - 'attachment' + "attachment" end end diff --git a/app/controllers/projects/labels_controller.rb b/app/controllers/projects/labels_controller.rb index 640038818f2..4d79f0a1f5d 100644 --- a/app/controllers/projects/labels_controller.rb +++ b/app/controllers/projects/labels_controller.rb @@ -9,7 +9,7 @@ class Projects::LabelsController < Projects::ApplicationController before_action :authorize_read_label! before_action :authorize_admin_labels!, only: [:new, :create, :edit, :update, :generate, :destroy, :remove_priority, - :set_priorities] + :set_priorities,] before_action :authorize_admin_group_labels!, only: [:promote] respond_to :js, :html @@ -41,7 +41,7 @@ class Projects::LabelsController < Projects::ApplicationController else respond_to do |format| format.html { render :new } - format.json { render json: { message: @label.errors.messages }, status: :bad_request } + format.json { render json: {message: @label.errors.messages}, status: :bad_request } end end end @@ -62,9 +62,9 @@ class Projects::LabelsController < Projects::ApplicationController def generate Gitlab::IssuesLabels.generate(@project) - if params[:redirect] == 'issues' + if params[:redirect] == "issues" redirect_to project_issues_path(@project) - elsif params[:redirect] == 'merge_requests' + elsif params[:redirect] == "merge_requests" redirect_to project_merge_requests_path(@project) else redirect_to project_labels_path(@project) @@ -76,8 +76,8 @@ class Projects::LabelsController < Projects::ApplicationController @labels = find_labels redirect_to project_labels_path(@project), - status: 302, - notice: 'Label was removed' + status: 302, + notice: "Label was removed" end def remove_priority @@ -105,7 +105,7 @@ class Projects::LabelsController < Projects::ApplicationController end respond_to do |format| - format.json { render json: { message: 'success' } } + format.json { render json: {message: "success"} } end end # rubocop: enable CodeReuse/ActiveRecord @@ -122,7 +122,7 @@ class Projects::LabelsController < Projects::ApplicationController redirect_to(project_labels_path(@project), status: :see_other) end format.json do - render json: { url: project_labels_path(@project) } + render json: {url: project_labels_path(@project)} end end rescue ActiveRecord::RecordInvalid => e @@ -132,7 +132,7 @@ class Projects::LabelsController < Projects::ApplicationController respond_to do |format| format.html do redirect_to(project_labels_path(@project), - notice: 'Failed to promote label due to internal error. Please contact administrators.') + notice: "Failed to promote label due to internal error. Please contact administrators.") end format.js end @@ -140,7 +140,7 @@ class Projects::LabelsController < Projects::ApplicationController end def flash_notice_for(label, group) - ''.html_safe + "#{label.title} promoted to " + view_context.link_to('<u>group label</u>'.html_safe, group_labels_path(group)) + '.' + "".html_safe + "#{label.title} promoted to " + view_context.link_to("<u>group label</u>".html_safe, group_labels_path(group)) + "." end protected @@ -160,15 +160,15 @@ class Projects::LabelsController < Projects::ApplicationController def find_labels @available_labels ||= LabelsFinder.new(current_user, - project_id: @project.id, - include_ancestor_groups: params[:include_ancestor_groups], - search: params[:search], - subscribed: params[:subscribed], - sort: sort).execute + project_id: @project.id, + include_ancestor_groups: params[:include_ancestor_groups], + search: params[:search], + subscribed: params[:subscribed], + sort: sort).execute end def sort - @sort ||= params[:sort] || 'name_asc' + @sort ||= params[:sort] || "name_asc" end def authorize_admin_labels! diff --git a/app/controllers/projects/lfs_api_controller.rb b/app/controllers/projects/lfs_api_controller.rb index be40077d389..e4947ea9d3e 100644 --- a/app/controllers/projects/lfs_api_controller.rb +++ b/app/controllers/projects/lfs_api_controller.rb @@ -3,7 +3,7 @@ class Projects::LfsApiController < Projects::GitHttpClientController include LfsRequest - LFS_TRANSFER_CONTENT_TYPE = 'application/octet-stream'.freeze + LFS_TRANSFER_CONTENT_TYPE = "application/octet-stream" skip_before_action :lfs_check_access!, only: [:deprecated] before_action :lfs_check_batch_operation!, only: [:batch] @@ -15,9 +15,9 @@ class Projects::LfsApiController < Projects::GitHttpClientController end if download_request? - render json: { objects: download_objects! } + render json: {objects: download_objects!} elsif upload_request? - render json: { objects: upload_objects! } + render json: {objects: upload_objects!} else raise "Never reached" end @@ -26,8 +26,8 @@ class Projects::LfsApiController < Projects::GitHttpClientController def deprecated render( json: { - message: 'Server supports batch API only, please update your Git LFS client to version 1.0.1 and up.', - documentation_url: "#{Gitlab.config.gitlab.url}/help" + message: "Server supports batch API only, please update your Git LFS client to version 1.0.1 and up.", + documentation_url: "#{Gitlab.config.gitlab.url}/help", }, status: :not_implemented ) @@ -36,17 +36,17 @@ class Projects::LfsApiController < Projects::GitHttpClientController private def download_request? - params[:operation] == 'download' + params[:operation] == "download" end def upload_request? - params[:operation] == 'upload' + params[:operation] == "upload" end # rubocop: disable CodeReuse/ActiveRecord def existing_oids @existing_oids ||= begin - project.all_lfs_objects.where(oid: objects.map { |o| o['oid'].to_s }).pluck(:oid) + project.all_lfs_objects.where(oid: objects.map { |o| o["oid"].to_s }).pluck(:oid) end end # rubocop: enable CodeReuse/ActiveRecord @@ -62,7 +62,7 @@ class Projects::LfsApiController < Projects::GitHttpClientController else object[:error] = { code: 404, - message: "Object does not exist on the server or you don't have permissions to access it" + message: "Object does not exist on the server or you don't have permissions to access it", } end end @@ -81,9 +81,9 @@ class Projects::LfsApiController < Projects::GitHttpClientController download: { href: "#{project.http_url_to_repo}/gitlab-lfs/objects/#{object[:oid]}", header: { - Authorization: request.headers['Authorization'] - }.compact - } + Authorization: request.headers["Authorization"], + }.compact, + }, } end @@ -92,12 +92,12 @@ class Projects::LfsApiController < Projects::GitHttpClientController upload: { href: "#{project.http_url_to_repo}/gitlab-lfs/objects/#{object[:oid]}/#{object[:size]}", header: { - Authorization: request.headers['Authorization'], + Authorization: request.headers["Authorization"], # git-lfs v2.5.0 sets the Content-Type based on the uploaded file. This # ensures that Workhorse can intercept the request. - 'Content-Type': LFS_TRANSFER_CONTENT_TYPE - }.compact - } + 'Content-Type': LFS_TRANSFER_CONTENT_TYPE, + }.compact, + }, } end @@ -105,7 +105,7 @@ class Projects::LfsApiController < Projects::GitHttpClientController if batch_operation_disallowed? render( json: { - message: lfs_read_only_message + message: lfs_read_only_message, }, content_type: LfsRequest::CONTENT_TYPE, status: 403 @@ -120,6 +120,6 @@ class Projects::LfsApiController < Projects::GitHttpClientController # Overridden in EE def lfs_read_only_message - _('You cannot write to this read-only GitLab instance.') + _("You cannot write to this read-only GitLab instance.") end end diff --git a/app/controllers/projects/lfs_locks_api_controller.rb b/app/controllers/projects/lfs_locks_api_controller.rb index 6aacb9d9a56..9b61be1224e 100644 --- a/app/controllers/projects/lfs_locks_api_controller.rb +++ b/app/controllers/projects/lfs_locks_api_controller.rb @@ -26,7 +26,7 @@ class Projects::LfsLocksApiController < Projects::GitHttpClientController ours, theirs = split_by_owner(@result[:locks]) - render_json({ ours: ours, theirs: theirs }, false) + render_json({ours: ours, theirs: theirs}, false) end private @@ -50,7 +50,7 @@ class Projects::LfsLocksApiController < Projects::GitHttpClientController def error_payload(message, custom_attrs = {}) custom_attrs.merge({ message: message, - documentation_url: help_url + documentation_url: help_url, }) end @@ -63,11 +63,11 @@ class Projects::LfsLocksApiController < Projects::GitHttpClientController end def download_request? - params[:action] == 'index' + params[:action] == "index" end def upload_request? - %w(create unlock verify).include?(params[:action]) + %w[create unlock verify].include?(params[:action]) end def lfs_params diff --git a/app/controllers/projects/lfs_storage_controller.rb b/app/controllers/projects/lfs_storage_controller.rb index 013e01b82aa..8faee9161d5 100644 --- a/app/controllers/projects/lfs_storage_controller.rb +++ b/app/controllers/projects/lfs_storage_controller.rb @@ -9,19 +9,20 @@ class Projects::LfsStorageController < Projects::GitHttpClientController def download lfs_object = LfsObject.find_by_oid(oid) - unless lfs_object && lfs_object.file.exists? + unless lfs_object&.file&.exists? render_lfs_not_found return end - send_upload(lfs_object.file, send_params: { content_type: "application/octet-stream" }) + send_upload(lfs_object.file, send_params: {content_type: "application/octet-stream"}) end def upload_authorize set_workhorse_internal_api_content_type authorized = LfsObjectUploader.workhorse_authorize(has_length: true) - authorized.merge!(LfsOid: oid, LfsSize: size) + authorized[:LfsOid] = oid + authorized[:LfsSize] = size render json: authorized end @@ -30,7 +31,7 @@ class Projects::LfsStorageController < Projects::GitHttpClientController if store_file!(oid, size) head 200 else - render plain: 'Unprocessable entity', status: :unprocessable_entity + render plain: "Unprocessable entity", status: :unprocessable_entity end rescue ActiveRecord::RecordInvalid render_lfs_forbidden @@ -43,7 +44,7 @@ class Projects::LfsStorageController < Projects::GitHttpClientController private def download_request? - action_name == 'download' + action_name == "download" end def upload_request? @@ -73,7 +74,8 @@ class Projects::LfsStorageController < Projects::GitHttpClientController def create_file!(oid, size) uploaded_file = UploadedFile.from_params( - params, :file, LfsObjectUploader.workhorse_local_upload_path) + params, :file, LfsObjectUploader.workhorse_local_upload_path + ) return unless uploaded_file LfsObject.create!(oid: oid, size: size, file: uploaded_file) diff --git a/app/controllers/projects/mattermosts_controller.rb b/app/controllers/projects/mattermosts_controller.rb index 085b1bc1498..1c12982b699 100644 --- a/app/controllers/projects/mattermosts_controller.rb +++ b/app/controllers/projects/mattermosts_controller.rb @@ -4,7 +4,7 @@ class Projects::MattermostsController < Projects::ApplicationController include TriggersHelper include ActionView::Helpers::AssetUrlHelper - layout 'project_settings' + layout "project_settings" before_action :authorize_admin_project! before_action :service @@ -17,10 +17,10 @@ class Projects::MattermostsController < Projects::ApplicationController result, message = @service.configure(current_user, configure_params) if result - flash[:notice] = 'This service is now configured' + flash[:notice] = "This service is now configured" redirect_to edit_project_service_path(@project, service) else - flash[:alert] = message || 'Failed to configure service' + flash[:alert] = message || "Failed to configure service" redirect_to new_project_mattermost_path(@project) end end @@ -30,7 +30,8 @@ class Projects::MattermostsController < Projects::ApplicationController def configure_params params.require(:mattermost).permit(:trigger, :team_id).merge( url: service_trigger_url(@service), - icon_url: asset_url('slash-command-logo.png')) + icon_url: asset_url("slash-command-logo.png") + ) end def teams @@ -38,6 +39,6 @@ class Projects::MattermostsController < Projects::ApplicationController end def service - @service ||= @project.find_or_initialize_service('mattermost_slash_commands') + @service ||= @project.find_or_initialize_service("mattermost_slash_commands") end end diff --git a/app/controllers/projects/merge_requests/application_controller.rb b/app/controllers/projects/merge_requests/application_controller.rb index 6045ee4e171..aa34eeb1c37 100644 --- a/app/controllers/projects/merge_requests/application_controller.rb +++ b/app/controllers/projects/merge_requests/application_controller.rb @@ -35,7 +35,7 @@ class Projects::MergeRequests::ApplicationController < Projects::ApplicationCont :title, :discussion_locked, label_ids: [], - update_task: [:index, :checked, :line_number, :line_source] + update_task: [:index, :checked, :line_number, :line_source], ] end diff --git a/app/controllers/projects/merge_requests/conflicts_controller.rb b/app/controllers/projects/merge_requests/conflicts_controller.rb index 045a4e974fe..91a1232f1b5 100644 --- a/app/controllers/projects/merge_requests/conflicts_controller.rb +++ b/app/controllers/projects/merge_requests/conflicts_controller.rb @@ -8,7 +8,7 @@ class Projects::MergeRequests::ConflictsController < Projects::MergeRequests::Ap def show respond_to do |format| format.html do - @issuable_sidebar = serializer.represent(@merge_request, serializer: 'sidebar') + @issuable_sidebar = serializer.represent(@merge_request, serializer: "sidebar") end format.json do @@ -16,13 +16,13 @@ class Projects::MergeRequests::ConflictsController < Projects::MergeRequests::Ap render json: @conflicts_list elsif @merge_request.can_be_merged? render json: { - message: 'The merge conflicts for this merge request have already been resolved. Please return to the merge request.', - type: 'error' + message: "The merge conflicts for this merge request have already been resolved. Please return to the merge request.", + type: "error", } else render json: { - message: 'The merge conflicts for this merge request cannot be resolved through GitLab. Please try to resolve them locally.', - type: 'error' + message: "The merge conflicts for this merge request cannot be resolved through GitLab. Please try to resolve them locally.", + type: "error", } end end @@ -43,7 +43,7 @@ class Projects::MergeRequests::ConflictsController < Projects::MergeRequests::Ap return render_404 unless @conflicts_list.can_be_resolved_in_ui? if @merge_request.can_be_merged? - render status: :bad_request, json: { message: 'The merge conflicts for this merge request have already been resolved.' } + render status: :bad_request, json: {message: "The merge conflicts for this merge request have already been resolved."} return end @@ -52,11 +52,11 @@ class Projects::MergeRequests::ConflictsController < Projects::MergeRequests::Ap .new(merge_request) .execute(current_user, params) - flash[:notice] = 'All merge conflicts were resolved. The merge request can now be merged.' + flash[:notice] = "All merge conflicts were resolved. The merge request can now be merged." - render json: { redirect_to: project_merge_request_url(@project, @merge_request, resolved_conflicts: true) } + render json: {redirect_to: project_merge_request_url(@project, @merge_request, resolved_conflicts: true)} rescue Gitlab::Git::Conflict::Resolver::ResolutionError => e - render status: :bad_request, json: { message: e.message } + render status: :bad_request, json: {message: e.message} end end diff --git a/app/controllers/projects/merge_requests/creations_controller.rb b/app/controllers/projects/merge_requests/creations_controller.rb index 32cefe54613..ca3bff85c56 100644 --- a/app/controllers/projects/merge_requests/creations_controller.rb +++ b/app/controllers/projects/merge_requests/creations_controller.rb @@ -40,8 +40,8 @@ class Projects::MergeRequests::CreationsController < Projects::MergeRequests::Ap render json: { pipelines: PipelineSerializer - .new(project: @project, current_user: @current_user) - .represent(@pipelines) + .new(project: @project, current_user: @current_user) + .represent(@pipelines), } end @@ -52,7 +52,7 @@ class Projects::MergeRequests::CreationsController < Projects::MergeRequests::Ap @environment = @merge_request.environments_for(current_user).last - render json: { html: view_to_html_string('projects/merge_requests/creations/_diffs', diffs: @diffs, environment: @environment) } + render json: {html: view_to_html_string("projects/merge_requests/creations/_diffs", diffs: @diffs, environment: @environment)} end def diff_for_path @@ -100,10 +100,10 @@ class Projects::MergeRequests::CreationsController < Projects::MergeRequests::Ap @noteable = @merge_request @target_branches = if @merge_request.target_project - @merge_request.target_project.repository.branch_names - else - [] - end + @merge_request.target_project.repository.branch_names + else + [] + end @target_project = @merge_request.target_project @source_project = @merge_request.source_project @@ -133,6 +133,6 @@ class Projects::MergeRequests::CreationsController < Projects::MergeRequests::Ap # rubocop: enable CodeReuse/ActiveRecord def whitelist_query_limiting - Gitlab::QueryLimiting.whitelist('https://gitlab.com/gitlab-org/gitlab-ce/issues/42384') + Gitlab::QueryLimiting.whitelist("https://gitlab.com/gitlab-org/gitlab-ce/issues/42384") end end diff --git a/app/controllers/projects/merge_requests/diffs_controller.rb b/app/controllers/projects/merge_requests/diffs_controller.rb index 518d41bd3fb..7e67c79f78d 100644 --- a/app/controllers/projects/merge_requests/diffs_controller.rb +++ b/app/controllers/projects/merge_requests/diffs_controller.rb @@ -30,7 +30,7 @@ class Projects::MergeRequests::DiffsController < Projects::MergeRequests::Applic request = { current_user: current_user, project: @merge_request.project, - render: ->(partial, locals) { view_to_html_string(partial, locals) } + render: ->(partial, locals) { view_to_html_string(partial, locals) }, } render json: DiffsSerializer.new(request).represent(@diffs, additional_attributes) @@ -92,15 +92,15 @@ class Projects::MergeRequests::DiffsController < Projects::MergeRequests::Applic start_version: @start_version, start_sha: @start_sha, commit: @commit, - latest_diff: @merge_request_diff&.latest? + latest_diff: @merge_request_diff&.latest?, } end def define_diff_comment_vars @new_diff_note_attrs = { - noteable_type: 'MergeRequest', + noteable_type: "MergeRequest", noteable_id: @merge_request.id, - commit_id: @commit&.id + commit_id: @commit&.id, } @diff_notes_disabled = false diff --git a/app/controllers/projects/merge_requests_controller.rb b/app/controllers/projects/merge_requests_controller.rb index 46a44841c31..fb746c0e197 100644 --- a/app/controllers/projects/merge_requests_controller.rb +++ b/app/controllers/projects/merge_requests_controller.rb @@ -27,7 +27,7 @@ class Projects::MergeRequestsController < Projects::MergeRequests::ApplicationCo format.html format.json do render json: { - html: view_to_html_string("projects/merge_requests/_merge_requests") + html: view_to_html_string("projects/merge_requests/_merge_requests"), } end end @@ -40,14 +40,14 @@ class Projects::MergeRequestsController < Projects::MergeRequests::ApplicationCo respond_to do |format| format.html do # use next to appease Rubocop - next render('invalid') if target_branch_missing? + next render("invalid") if target_branch_missing? # Build a note object for comment form @note = @project.notes.new(noteable: @merge_request) @noteable = @merge_request @commits_count = @merge_request.commits_count - @issuable_sidebar = serializer.represent(@merge_request, serializer: 'sidebar') + @issuable_sidebar = serializer.represent(@merge_request, serializer: "sidebar") set_pipeline_variables @@ -80,7 +80,7 @@ class Projects::MergeRequestsController < Projects::MergeRequests::ApplicationCo @commits = set_commits_for_rendering(@merge_request.commits.with_pipeline_status) - render json: { html: view_to_html_string('projects/merge_requests/_commits') } + render json: {html: view_to_html_string("projects/merge_requests/_commits")} end def pipelines @@ -94,8 +94,8 @@ class Projects::MergeRequestsController < Projects::MergeRequests::ApplicationCo .with_pagination(request, response) .represent(@pipelines), count: { - all: @pipelines.count - } + all: @pipelines.count, + }, } end @@ -106,13 +106,13 @@ class Projects::MergeRequestsController < Projects::MergeRequests::ApplicationCo when :parsing Gitlab::PollingInterval.set_header(response, interval: 3000) - render json: '', status: :no_content + render json: "", status: :no_content when :parsed render json: result[:data].to_json, status: :ok when :error - render json: { status_reason: result[:status_reason] }, status: :bad_request + render json: {status_reason: result[:status_reason]}, status: :bad_request else - render json: { status_reason: 'Unknown error' }, status: :internal_server_error + render json: {status_reason: "Unknown error"}, status: :internal_server_error end end @@ -138,7 +138,7 @@ class Projects::MergeRequestsController < Projects::MergeRequests::ApplicationCo if merge_request.errors.present? render json: @merge_request.errors, status: :bad_request else - render json: serializer.represent(@merge_request, serializer: 'basic') + render json: serializer.represent(@merge_request, serializer: "basic") end end end @@ -150,14 +150,14 @@ class Projects::MergeRequestsController < Projects::MergeRequests::ApplicationCo def remove_wip @merge_request = ::MergeRequests::UpdateService - .new(project, current_user, wip_event: 'unwip') + .new(project, current_user, wip_event: "unwip") .execute(@merge_request) render json: serialize_widget(@merge_request) end def commit_change_content - render partial: 'projects/merge_requests/widget/commit_change_content', layout: false + render partial: "projects/merge_requests/widget/commit_change_content", layout: false end def cancel_merge_when_pipeline_succeeds @@ -180,9 +180,9 @@ class Projects::MergeRequestsController < Projects::MergeRequests::ApplicationCo status = merge! if @merge_request.merge_error - render json: { status: status, merge_error: @merge_request.merge_error } + render json: {status: status, merge_error: @merge_request.merge_error} else - render json: { status: status } + render json: {status: status} end end @@ -209,10 +209,10 @@ class Projects::MergeRequestsController < Projects::MergeRequests::ApplicationCo def ci_environments_status environments = if ci_environments_status_on_merge_result? - EnvironmentStatus.after_merge_request(@merge_request, current_user) - else - EnvironmentStatus.for_merge_request(@merge_request, current_user) - end + EnvironmentStatus.after_merge_request(@merge_request, current_user) + else + EnvironmentStatus.for_merge_request(@merge_request, current_user) + end render json: EnvironmentStatusSerializer.new(current_user: current_user).represent(environments) end @@ -231,9 +231,9 @@ class Projects::MergeRequestsController < Projects::MergeRequests::ApplicationCo protected - alias_method :subscribable_resource, :merge_request - alias_method :issuable, :merge_request - alias_method :awardable, :merge_request + alias subscribable_resource merge_request + alias issuable merge_request + alias awardable merge_request def issuable_sorting_field MergeRequest::SORTING_PREFERENCE_FIELD @@ -261,7 +261,7 @@ class Projects::MergeRequestsController < Projects::MergeRequests::ApplicationCo private def ci_environments_status_on_merge_result? - params[:environment_target] == 'merge_commit' + params[:environment_target] == "merge_commit" end def target_branch_missing? @@ -315,7 +315,7 @@ class Projects::MergeRequestsController < Projects::MergeRequests::ApplicationCo end def serialize_widget(merge_request) - serializer.represent(merge_request, serializer: 'widget') + serializer.represent(merge_request, serializer: "widget") end def serializer @@ -353,6 +353,6 @@ class Projects::MergeRequestsController < Projects::MergeRequests::ApplicationCo def whitelist_query_limiting # Also see https://gitlab.com/gitlab-org/gitlab-ce/issues/42441 - Gitlab::QueryLimiting.whitelist('https://gitlab.com/gitlab-org/gitlab-ce/issues/42438') + Gitlab::QueryLimiting.whitelist("https://gitlab.com/gitlab-org/gitlab-ce/issues/42438") end end diff --git a/app/controllers/projects/milestones_controller.rb b/app/controllers/projects/milestones_controller.rb index f6f61b6e5fb..ef8f6bd4219 100644 --- a/app/controllers/projects/milestones_controller.rb +++ b/app/controllers/projects/milestones_controller.rb @@ -19,7 +19,7 @@ class Projects::MilestonesController < Projects::ApplicationController respond_to :html def index - @sort = params[:sort] || 'due_date_asc' + @sort = params[:sort] || "due_date_asc" @milestones = milestones.sort_by_attribute(@sort) respond_to do |format| @@ -88,7 +88,7 @@ class Projects::MilestonesController < Projects::ApplicationController redirect_to project_milestones_path(project) end format.json do - render json: { url: project_milestones_path(project) } + render json: {url: project_milestones_path(project)} end end rescue Milestones::PromoteService::PromoteMilestoneError => error @@ -96,7 +96,7 @@ class Projects::MilestonesController < Projects::ApplicationController end def flash_notice_for(milestone, group) - ''.html_safe + "#{milestone.title} promoted to " + view_context.link_to('<u>group milestone</u>'.html_safe, group_milestone_path(group, milestone.iid)) + '.' + "".html_safe + "#{milestone.title} promoted to " + view_context.link_to("<u>group milestone</u>".html_safe, group_milestone_path(group, milestone.iid)) + "." end def destroy diff --git a/app/controllers/projects/mirrors_controller.rb b/app/controllers/projects/mirrors_controller.rb index ab7ab13657a..720e96852a5 100644 --- a/app/controllers/projects/mirrors_controller.rb +++ b/app/controllers/projects/mirrors_controller.rb @@ -11,20 +11,20 @@ class Projects::MirrorsController < Projects::ApplicationController layout "project_settings" def show - redirect_to_repository_settings(project, anchor: 'js-push-remote-settings') + redirect_to_repository_settings(project, anchor: "js-push-remote-settings") end def update result = ::Projects::UpdateService.new(project, current_user, mirror_params).execute if result[:status] == :success - flash[:notice] = 'Mirroring settings were successfully updated.' + flash[:notice] = "Mirroring settings were successfully updated." else - flash[:alert] = project.errors.full_messages.join(', ').html_safe + flash[:alert] = project.errors.full_messages.join(", ").html_safe end respond_to do |format| - format.html { redirect_to_repository_settings(project, anchor: 'js-push-remote-settings') } + format.html { redirect_to_repository_settings(project, anchor: "js-push-remote-settings") } format.json do if project.errors.present? render json: project.errors, status: :unprocessable_entity @@ -41,7 +41,7 @@ class Projects::MirrorsController < Projects::ApplicationController flash[:notice] = "The remote repository is being updated..." end - redirect_to_repository_settings(project, anchor: 'js-push-remote-settings') + redirect_to_repository_settings(project, anchor: "js-push-remote-settings") end def ssh_host_keys @@ -49,7 +49,7 @@ class Projects::MirrorsController < Projects::ApplicationController if lookup.error.present? # Failed to read keys - render json: { message: lookup.error }, status: :bad_request + render json: {message: lookup.error}, status: :bad_request elsif lookup.known_hosts.nil? # Still working, come back later render body: nil, status: :no_content @@ -57,7 +57,7 @@ class Projects::MirrorsController < Projects::ApplicationController render json: lookup end rescue ArgumentError => err - render json: { message: err.message }, status: :bad_request + render json: {message: err.message}, status: :bad_request end private @@ -81,7 +81,7 @@ class Projects::MirrorsController < Projects::ApplicationController password ssh_known_hosts regenerate_ssh_private_key - ] + ], ] end diff --git a/app/controllers/projects/network_controller.rb b/app/controllers/projects/network_controller.rb index 6543711ecfa..e1a819ad84c 100644 --- a/app/controllers/projects/network_controller.rb +++ b/app/controllers/projects/network_controller.rb @@ -13,7 +13,7 @@ class Projects::NetworkController < Projects::ApplicationController def show @url = project_network_path(@project, @ref, @options.merge(format: :json)) - @commit_url = project_commit_path(@project, 'ae45ca32').gsub("ae45ca32", "%s") + @commit_url = project_commit_path(@project, "ae45ca32").gsub("ae45ca32", "%s") respond_to do |format| format.html do @@ -41,6 +41,6 @@ class Projects::NetworkController < Projects::ApplicationController end def whitelist_query_limiting - Gitlab::QueryLimiting.whitelist('https://gitlab.com/gitlab-org/gitlab-ce/issues/42333') + Gitlab::QueryLimiting.whitelist("https://gitlab.com/gitlab-org/gitlab-ce/issues/42333") end end diff --git a/app/controllers/projects/notes_controller.rb b/app/controllers/projects/notes_controller.rb index 3152a38fd8e..015de870b16 100644 --- a/app/controllers/projects/notes_controller.rb +++ b/app/controllers/projects/notes_controller.rb @@ -32,7 +32,7 @@ class Projects::NotesController < Projects::ApplicationController else render json: { resolved_by: note.resolved_by.try(:name), - discussion_headline_html: (view_to_html_string('discussions/_headline', discussion: discussion) if discussion) + discussion_headline_html: (view_to_html_string("discussions/_headline", discussion: discussion) if discussion), } end end @@ -48,7 +48,7 @@ class Projects::NotesController < Projects::ApplicationController render_json_with_notes_serializer else render json: { - discussion_headline_html: (view_to_html_string('discussions/_headline', discussion: discussion) if discussion) + discussion_headline_html: (view_to_html_string("discussions/_headline", discussion: discussion) if discussion), } end end @@ -65,7 +65,7 @@ class Projects::NotesController < Projects::ApplicationController @note ||= @project.notes.find(params[:id]) end - alias_method :awardable, :note + alias awardable note def finder_params params.merge(last_fetched_at: last_fetched_at, notes_filter: notes_filter) @@ -86,6 +86,6 @@ class Projects::NotesController < Projects::ApplicationController end def whitelist_query_limiting - Gitlab::QueryLimiting.whitelist('https://gitlab.com/gitlab-org/gitlab-ce/issues/42383') + Gitlab::QueryLimiting.whitelist("https://gitlab.com/gitlab-org/gitlab-ce/issues/42383") end end diff --git a/app/controllers/projects/pages_controller.rb b/app/controllers/projects/pages_controller.rb index 73e629ab7c3..3ad934cd487 100644 --- a/app/controllers/projects/pages_controller.rb +++ b/app/controllers/projects/pages_controller.rb @@ -1,7 +1,7 @@ # frozen_string_literal: true class Projects::PagesController < Projects::ApplicationController - layout 'project_settings' + layout "project_settings" before_action :require_pages_enabled! before_action :authorize_read_pages!, only: [:show] @@ -21,8 +21,8 @@ class Projects::PagesController < Projects::ApplicationController respond_to do |format| format.html do redirect_to project_pages_path(@project), - status: 302, - notice: 'Pages were removed' + status: 302, + notice: "Pages were removed" end end end @@ -33,9 +33,9 @@ class Projects::PagesController < Projects::ApplicationController respond_to do |format| format.html do if result[:status] == :success - flash[:notice] = 'Your changes have been saved' + flash[:notice] = "Your changes have been saved" else - flash[:alert] = 'Something went wrong on our end' + flash[:alert] = "Something went wrong on our end" end redirect_to project_pages_path(@project) diff --git a/app/controllers/projects/pages_domains_controller.rb b/app/controllers/projects/pages_domains_controller.rb index 58b1bc54181..424b31aac56 100644 --- a/app/controllers/projects/pages_domains_controller.rb +++ b/app/controllers/projects/pages_domains_controller.rb @@ -1,7 +1,7 @@ # frozen_string_literal: true class Projects::PagesDomainsController < Projects::ApplicationController - layout 'project_settings' + layout "project_settings" before_action :require_pages_enabled! before_action :authorize_update_pages! @@ -18,9 +18,9 @@ class Projects::PagesDomainsController < Projects::ApplicationController result = VerifyPagesDomainService.new(@domain).execute if result[:status] == :success - flash[:notice] = 'Successfully verified domain ownership' + flash[:notice] = "Successfully verified domain ownership" else - flash[:alert] = 'Failed to verify domain ownership' + flash[:alert] = "Failed to verify domain ownership" end redirect_to project_pages_domain_path(@project, @domain) @@ -35,7 +35,7 @@ class Projects::PagesDomainsController < Projects::ApplicationController if @domain.valid? redirect_to project_pages_domain_path(@project, @domain) else - render 'new' + render "new" end end @@ -43,9 +43,9 @@ class Projects::PagesDomainsController < Projects::ApplicationController if @domain.update(update_params) redirect_to project_pages_path(@project), status: 302, - notice: 'Domain was updated' + notice: "Domain was updated" else - render 'edit' + render "edit" end end @@ -55,8 +55,8 @@ class Projects::PagesDomainsController < Projects::ApplicationController respond_to do |format| format.html do redirect_to project_pages_path(@project), - status: 302, - notice: 'Domain was removed' + status: 302, + notice: "Domain was removed" end format.js end diff --git a/app/controllers/projects/pipeline_schedules_controller.rb b/app/controllers/projects/pipeline_schedules_controller.rb index acf56f0eb6a..6a627f55f96 100644 --- a/app/controllers/projects/pipeline_schedules_controller.rb +++ b/app/controllers/projects/pipeline_schedules_controller.rb @@ -52,7 +52,7 @@ class Projects::PipelineSchedulesController < Projects::ApplicationController if job_id flash[:notice] = "Successfully scheduled a pipeline to run. Go to the <a href=\"#{project_pipelines_path(@project)}\">Pipelines page</a> for details.".html_safe else - flash[:alert] = 'Unable to schedule a pipeline to run immediately' + flash[:alert] = "Unable to schedule a pipeline to run immediately" end redirect_to pipeline_schedules_path(@project) @@ -71,8 +71,8 @@ class Projects::PipelineSchedulesController < Projects::ApplicationController redirect_to pipeline_schedules_path(@project), status: :found else redirect_to pipeline_schedules_path(@project), - status: :forbidden, - alert: _("Failed to remove the pipeline schedule") + status: :forbidden, + alert: _("Failed to remove the pipeline schedule") end end @@ -85,7 +85,7 @@ class Projects::PipelineSchedulesController < Projects::ApplicationController return unless limiter.throttled?([current_user, schedule], 1) - flash[:alert] = 'You cannot play this scheduled pipeline at the moment. Please wait a minute.' + flash[:alert] = "You cannot play this scheduled pipeline at the moment. Please wait a minute." redirect_to pipeline_schedules_path(@project) end @@ -96,7 +96,7 @@ class Projects::PipelineSchedulesController < Projects::ApplicationController def schedule_params params.require(:schedule) .permit(:description, :cron, :cron_timezone, :ref, :active, - variables_attributes: [:id, :key, :secret_value, :_destroy] ) + variables_attributes: [:id, :key, :secret_value, :_destroy]) end def authorize_play_pipeline_schedule! diff --git a/app/controllers/projects/pipelines_controller.rb b/app/controllers/projects/pipelines_controller.rb index 6a86f8ca729..b00f1826d50 100644 --- a/app/controllers/projects/pipelines_controller.rb +++ b/app/controllers/projects/pipelines_controller.rb @@ -20,9 +20,9 @@ class Projects::PipelinesController < Projects::ApplicationController .page(params[:page]) .per(30) - @running_count = limited_pipelines_count(project, 'running') - @pending_count = limited_pipelines_count(project, 'pending') - @finished_count = limited_pipelines_count(project, 'finished') + @running_count = limited_pipelines_count(project, "running") + @pending_count = limited_pipelines_count(project, "pending") + @finished_count = limited_pipelines_count(project, "finished") @pipelines_count = limited_pipelines_count(project) respond_to do |format| @@ -39,8 +39,8 @@ class Projects::PipelinesController < Projects::ApplicationController all: @pipelines_count, running: @running_count, pending: @pending_count, - finished: @finished_count - } + finished: @finished_count, + }, } end end @@ -58,7 +58,7 @@ class Projects::PipelinesController < Projects::ApplicationController if @pipeline.persisted? redirect_to project_pipeline_path(project, @pipeline) else - render 'new' + render "new" end end @@ -108,7 +108,7 @@ class Projects::PipelinesController < Projects::ApplicationController @stage = pipeline.legacy_stage(params[:stage]) return not_found unless @stage - render json: { html: view_to_html_string('projects/pipelines/_stage') } + render json: {html: view_to_html_string("projects/pipelines/_stage")} end def retry @@ -153,13 +153,13 @@ class Projects::PipelinesController < Projects::ApplicationController def render_show respond_to do |format| format.html do - render 'show' + render "show" end end end def show_represent_params - { grouped: true } + {grouped: true} end def create_params @@ -169,16 +169,16 @@ class Projects::PipelinesController < Projects::ApplicationController # rubocop: disable CodeReuse/ActiveRecord def pipeline @pipeline ||= project - .all_pipelines - .includes(user: :status) - .find_by!(id: params[:id]) - .present(current_user: current_user) + .all_pipelines + .includes(user: :status) + .find_by!(id: params[:id]) + .present(current_user: current_user) end # rubocop: enable CodeReuse/ActiveRecord def whitelist_query_limiting # Also see https://gitlab.com/gitlab-org/gitlab-ce/issues/42343 - Gitlab::QueryLimiting.whitelist('https://gitlab.com/gitlab-org/gitlab-ce/issues/42339') + Gitlab::QueryLimiting.whitelist("https://gitlab.com/gitlab-org/gitlab-ce/issues/42339") end def authorize_update_pipeline! diff --git a/app/controllers/projects/project_members_controller.rb b/app/controllers/projects/project_members_controller.rb index 8938cfbad54..84fdbee678b 100644 --- a/app/controllers/projects/project_members_controller.rb +++ b/app/controllers/projects/project_members_controller.rb @@ -45,9 +45,9 @@ class Projects::ProjectMembersController < Projects::ApplicationController end redirect_to(project_project_members_path(project), - notice: notice) + notice: notice) end # MembershipActions concern - alias_method :membershipable, :project + alias membershipable project end diff --git a/app/controllers/projects/protected_branches_controller.rb b/app/controllers/projects/protected_branches_controller.rb index c5454883060..ea2c0a798e6 100644 --- a/app/controllers/projects/protected_branches_controller.rb +++ b/app/controllers/projects/protected_branches_controller.rb @@ -21,7 +21,7 @@ class Projects::ProtectedBranchesController < Projects::ProtectedRefsController def protected_ref_params params.require(:protected_branch).permit(:name, - merge_access_levels_attributes: access_level_attributes, - push_access_levels_attributes: access_level_attributes) + merge_access_levels_attributes: access_level_attributes, + push_access_levels_attributes: access_level_attributes) end end diff --git a/app/controllers/projects/protected_refs_controller.rb b/app/controllers/projects/protected_refs_controller.rb index 4e2a9df5576..1c7af305ba0 100644 --- a/app/controllers/projects/protected_refs_controller.rb +++ b/app/controllers/projects/protected_refs_controller.rb @@ -18,7 +18,7 @@ class Projects::ProtectedRefsController < Projects::ApplicationController protected_ref = create_service_class.new(@project, current_user, protected_ref_params).execute unless protected_ref.persisted? - flash[:alert] = protected_ref.errors.full_messages.join(', ').html_safe + flash[:alert] = protected_ref.errors.full_messages.join(", ").html_safe end redirect_to_repository_settings(@project, anchor: params[:update_section]) diff --git a/app/controllers/projects/raw_controller.rb b/app/controllers/projects/raw_controller.rb index 42ae5b0ef3c..8a36757f480 100644 --- a/app/controllers/projects/raw_controller.rb +++ b/app/controllers/projects/raw_controller.rb @@ -12,6 +12,6 @@ class Projects::RawController < Projects::ApplicationController def show @blob = @repository.blob_at(@commit.id, @path) - send_blob(@repository, @blob, inline: (params[:inline] != 'false')) + send_blob(@repository, @blob, inline: (params[:inline] != "false")) end end diff --git a/app/controllers/projects/registry/application_controller.rb b/app/controllers/projects/registry/application_controller.rb index 2f891d78c91..2ebfe2e6e56 100644 --- a/app/controllers/projects/registry/application_controller.rb +++ b/app/controllers/projects/registry/application_controller.rb @@ -3,7 +3,7 @@ module Projects module Registry class ApplicationController < Projects::ApplicationController - layout 'project' + layout "project" before_action :verify_registry_enabled! before_action :authorize_read_container_image! diff --git a/app/controllers/projects/repositories_controller.rb b/app/controllers/projects/repositories_controller.rb index 4eeaeb860ee..66fff5ec9f8 100644 --- a/app/controllers/projects/repositories_controller.rb +++ b/app/controllers/projects/repositories_controller.rb @@ -19,7 +19,7 @@ class Projects::RepositoriesController < Projects::ApplicationController append_sha = params[:append_sha] if @ref - shortname = "#{@project.path}-#{@ref.tr('/', '-')}" + shortname = "#{@project.path}-#{@ref.tr("/", "-")}" append_sha = false if @filename == shortname end diff --git a/app/controllers/projects/runner_projects_controller.rb b/app/controllers/projects/runner_projects_controller.rb index cbeb32fd610..3093cf72ef9 100644 --- a/app/controllers/projects/runner_projects_controller.rb +++ b/app/controllers/projects/runner_projects_controller.rb @@ -3,7 +3,7 @@ class Projects::RunnerProjectsController < Projects::ApplicationController before_action :authorize_admin_build! - layout 'project_settings' + layout "project_settings" def create @runner = Ci::Runner.find(params[:runner_project][:runner_id]) @@ -15,7 +15,7 @@ class Projects::RunnerProjectsController < Projects::ApplicationController if @runner.assign_to(project, current_user) redirect_to path else - redirect_to path, alert: 'Failed adding runner to project' + redirect_to path, alert: "Failed adding runner to project" end end diff --git a/app/controllers/projects/runners_controller.rb b/app/controllers/projects/runners_controller.rb index 91f40b90aa8..b4a1dd378dc 100644 --- a/app/controllers/projects/runners_controller.rb +++ b/app/controllers/projects/runners_controller.rb @@ -4,10 +4,10 @@ class Projects::RunnersController < Projects::ApplicationController before_action :authorize_admin_build! before_action :runner, only: [:edit, :update, :destroy, :pause, :resume, :show] - layout 'project_settings' + layout "project_settings" def index - redirect_to project_settings_ci_cd_path(@project, anchor: 'js-runners-settings') + redirect_to project_settings_ci_cd_path(@project, anchor: "js-runners-settings") end def edit @@ -15,9 +15,9 @@ class Projects::RunnersController < Projects::ApplicationController def update if Ci::UpdateRunnerService.new(@runner).update(runner_params) - redirect_to project_runner_path(@project, @runner), notice: 'Runner was successfully updated.' + redirect_to project_runner_path(@project, @runner), notice: "Runner was successfully updated." else - render 'edit' + render "edit" end end @@ -31,34 +31,34 @@ class Projects::RunnersController < Projects::ApplicationController def resume if Ci::UpdateRunnerService.new(@runner).update(active: true) - redirect_to project_runners_path(@project), notice: 'Runner was successfully updated.' + redirect_to project_runners_path(@project), notice: "Runner was successfully updated." else - redirect_to project_runners_path(@project), alert: 'Runner was not updated.' + redirect_to project_runners_path(@project), alert: "Runner was not updated." end end def pause if Ci::UpdateRunnerService.new(@runner).update(active: false) - redirect_to project_runners_path(@project), notice: 'Runner was successfully updated.' + redirect_to project_runners_path(@project), notice: "Runner was successfully updated." else - redirect_to project_runners_path(@project), alert: 'Runner was not updated.' + redirect_to project_runners_path(@project), alert: "Runner was not updated." end end def show - render 'shared/runners/show' + render "shared/runners/show" end def toggle_shared_runners project.toggle!(:shared_runners_enabled) - redirect_to project_settings_ci_cd_path(@project, anchor: 'js-runners-settings') + redirect_to project_settings_ci_cd_path(@project, anchor: "js-runners-settings") end def toggle_group_runners project.toggle_ci_cd_settings!(:group_runners_enabled) - redirect_to project_settings_ci_cd_path(@project, anchor: 'js-runners-settings') + redirect_to project_settings_ci_cd_path(@project, anchor: "js-runners-settings") end protected diff --git a/app/controllers/projects/services_controller.rb b/app/controllers/projects/services_controller.rb index f1c9d0d0f77..9ae486fca73 100644 --- a/app/controllers/projects/services_controller.rb +++ b/app/controllers/projects/services_controller.rb @@ -21,7 +21,7 @@ class Projects::ServicesController < Projects::ApplicationController if @service.save(context: :manual_change) redirect_to(project_settings_integrations_path(@project), notice: success_message) else - render 'edit' + render "edit" end end @@ -43,13 +43,13 @@ class Projects::ServicesController < Projects::ApplicationController if outcome[:success] {} else - { error: true, message: 'Test failed.', service_response: outcome[:result].to_s, test_failed: true } + {error: true, message: "Test failed.", service_response: outcome[:result].to_s, test_failed: true} end else - { error: true, message: 'Validations failed.', service_response: @service.errors.full_messages.join(','), test_failed: false } + {error: true, message: "Validations failed.", service_response: @service.errors.full_messages.join(","), test_failed: false} end rescue Gitlab::HTTP::BlockedUrlError => e - { error: true, message: 'Test failed.', service_response: e.message, test_failed: true } + {error: true, message: "Test failed.", service_response: e.message, test_failed: true} end def success_message diff --git a/app/controllers/projects/settings/ci_cd_controller.rb b/app/controllers/projects/settings/ci_cd_controller.rb index f2f63e986bb..b9a4b3fe63a 100644 --- a/app/controllers/projects/settings/ci_cd_controller.rb +++ b/app/controllers/projects/settings/ci_cd_controller.rb @@ -19,7 +19,7 @@ module Projects redirect_to project_settings_ci_cd_path(@project) else - render 'show' + render "show" end end end @@ -39,7 +39,7 @@ module Projects def reset_registration_token @project.reset_runners_token! - flash[:notice] = 'New runners registration token has been generated!' + flash[:notice] = "New runners registration token has been generated!" redirect_to namespace_project_settings_ci_cd_path end @@ -105,10 +105,10 @@ module Projects end def define_badges_variables - @ref = params[:ref] || @project.default_branch || 'master' + @ref = params[:ref] || @project.default_branch || "master" @badges = [Gitlab::Badge::Pipeline::Status, - Gitlab::Badge::Coverage::Report] + Gitlab::Badge::Coverage::Report,] @badges.map! do |badge| badge.new(@project, @ref).metadata diff --git a/app/controllers/projects/settings/operations_controller.rb b/app/controllers/projects/settings/operations_controller.rb index 521ec2acebb..840f17134f2 100644 --- a/app/controllers/projects/settings/operations_controller.rb +++ b/app/controllers/projects/settings/operations_controller.rb @@ -15,10 +15,10 @@ module Projects result = ::Projects::Operations::UpdateService.new(project, current_user, update_params).execute if result[:status] == :success - flash[:notice] = _('Your changes have been saved') + flash[:notice] = _("Your changes have been saved") redirect_to project_settings_operations_path(@project) else - render 'show' + render "show" end end @@ -35,7 +35,7 @@ module Projects # overridden in EE def permitted_project_params - { error_tracking_setting_attributes: [:enabled, :api_url, :token] } + {error_tracking_setting_attributes: [:enabled, :api_url, :token]} end def check_license diff --git a/app/controllers/projects/settings/repository_controller.rb b/app/controllers/projects/settings/repository_controller.rb index ac3004d069f..7cf504eccf3 100644 --- a/app/controllers/projects/settings/repository_controller.rb +++ b/app/controllers/projects/settings/repository_controller.rb @@ -14,7 +14,7 @@ module Projects @new_deploy_token = DeployTokens::CreateService.new(@project, current_user, deploy_token_params).execute if @new_deploy_token.persisted? - flash.now[:notice] = s_('DeployTokens|Your new project deploy token has been created.') + flash.now[:notice] = s_("DeployTokens|Your new project deploy token has been created.") end render_show @@ -26,9 +26,9 @@ module Projects if result[:status] == :success RepositoryCleanupWorker.perform_async(project.id, current_user.id) - flash[:notice] = _('Repository cleanup has started. You will receive an email once the cleanup operation is complete.') + flash[:notice] = _("Repository cleanup has started. You will receive an email once the cleanup operation is complete.") else - flash[:alert] = _('Failed to upload object map file') + flash[:alert] = _("Failed to upload object map file") end redirect_to project_settings_repository_path(project) @@ -44,7 +44,7 @@ module Projects define_protected_refs remote_mirror - render 'show' + render "show" end # rubocop: disable CodeReuse/ActiveRecord @@ -69,23 +69,23 @@ module Projects { create_access_levels: levels_for_dropdown, push_access_levels: levels_for_dropdown, - merge_access_levels: levels_for_dropdown + merge_access_levels: levels_for_dropdown, } end def levels_for_dropdown - roles = ProtectedRefAccess::HUMAN_ACCESS_LEVELS.map do |id, text| - { id: id, text: text, before_divider: true } - end - { roles: roles } + roles = ProtectedRefAccess::HUMAN_ACCESS_LEVELS.map { |id, text| + {id: id, text: text, before_divider: true} + } + {roles: roles} end def protectable_tags_for_dropdown - { open_tags: ProtectableDropdown.new(@project, :tags).hash } + {open_tags: ProtectableDropdown.new(@project, :tags).hash} end def protectable_branches_for_dropdown - { open_branches: ProtectableDropdown.new(@project, :branches).hash } + {open_branches: ProtectableDropdown.new(@project, :branches).hash} end def load_gon_index diff --git a/app/controllers/projects/snippets_controller.rb b/app/controllers/projects/snippets_controller.rb index 255f1f3569a..89f6c3e8613 100644 --- a/app/controllers/projects/snippets_controller.rb +++ b/app/controllers/projects/snippets_controller.rb @@ -69,7 +69,7 @@ class Projects::SnippetsController < Projects::ApplicationController @discussions = @snippet.discussions @notes = prepare_notes_for_rendering(@discussions.flat_map(&:notes), @noteable) - render 'show' + render "show" end format.json do @@ -78,7 +78,7 @@ class Projects::SnippetsController < Projects::ApplicationController format.js do if @snippet.embeddable? - render 'shared/snippets/show' + render "shared/snippets/show" else head :not_found end @@ -99,8 +99,8 @@ class Projects::SnippetsController < Projects::ApplicationController def snippet @snippet ||= @project.snippets.inc_relations_for_view.find(params[:id]) end - alias_method :awardable, :snippet - alias_method :spammable, :snippet + alias awardable snippet + alias spammable snippet def spammable_path project_snippet_path(@project, @snippet) diff --git a/app/controllers/projects/tags_controller.rb b/app/controllers/projects/tags_controller.rb index a17c050b696..9d07932bf32 100644 --- a/app/controllers/projects/tags_controller.rb +++ b/app/controllers/projects/tags_controller.rb @@ -25,7 +25,7 @@ class Projects::TagsController < Projects::ApplicationController respond_to do |format| format.html - format.atom { render layout: 'xml.atom' } + format.atom { render layout: "xml.atom" } end end # rubocop: enable CodeReuse/ActiveRecord @@ -51,7 +51,7 @@ class Projects::TagsController < Projects::ApplicationController release_params = { tag: params[:tag_name], name: params[:tag_name], - description: params[:release_description] + description: params[:release_description], } Releases::CreateService @@ -66,7 +66,7 @@ class Projects::TagsController < Projects::ApplicationController @error = result[:message] @message = params[:message] @release_description = params[:release_description] - render action: 'new' + render action: "new" end end diff --git a/app/controllers/projects/templates_controller.rb b/app/controllers/projects/templates_controller.rb index 7ceea4e5b96..5edaf4726d4 100644 --- a/app/controllers/projects/templates_controller.rb +++ b/app/controllers/projects/templates_controller.rb @@ -14,7 +14,7 @@ class Projects::TemplatesController < Projects::ApplicationController private def get_template_class - template_types = { issue: Gitlab::Template::IssueTemplate, merge_request: Gitlab::Template::MergeRequestTemplate }.with_indifferent_access + template_types = {issue: Gitlab::Template::IssueTemplate, merge_request: Gitlab::Template::MergeRequestTemplate}.with_indifferent_access @template_type = template_types[params[:template_type]] render json: [], status: :not_found unless @template_type end diff --git a/app/controllers/projects/tree_controller.rb b/app/controllers/projects/tree_controller.rb index edebfc55c17..b3723f8c6d2 100644 --- a/app/controllers/projects/tree_controller.rb +++ b/app/controllers/projects/tree_controller.rb @@ -19,7 +19,7 @@ class Projects::TreeController < Projects::ApplicationController if @repository.blob_at(@commit.id, @path) return redirect_to( project_blob_path(@project, - File.join(@ref, @path)) + File.join(@ref, @path)) ) elsif @path.present? return render_404 @@ -50,7 +50,7 @@ class Projects::TreeController < Projects::ApplicationController @dir_name = File.join(@path, params[:dir_name]) @commit_params = { file_path: @dir_name, - commit_message: params[:commit_message] + commit_message: params[:commit_message], } end end diff --git a/app/controllers/projects/triggers_controller.rb b/app/controllers/projects/triggers_controller.rb index c7b4ebb2b24..e57dbe9c37c 100644 --- a/app/controllers/projects/triggers_controller.rb +++ b/app/controllers/projects/triggers_controller.rb @@ -6,32 +6,32 @@ class Projects::TriggersController < Projects::ApplicationController before_action :authorize_admin_trigger!, only: [:edit, :update] before_action :trigger, only: [:take_ownership, :edit, :update, :destroy] - layout 'project_settings' + layout "project_settings" def index - redirect_to project_settings_ci_cd_path(@project, anchor: 'js-pipeline-triggers') + redirect_to project_settings_ci_cd_path(@project, anchor: "js-pipeline-triggers") end def create @trigger = project.triggers.create(trigger_params.merge(owner: current_user)) if @trigger.valid? - flash[:notice] = 'Trigger was created successfully.' + flash[:notice] = "Trigger was created successfully." else - flash[:alert] = 'You could not create a new trigger.' + flash[:alert] = "You could not create a new trigger." end - redirect_to project_settings_ci_cd_path(@project, anchor: 'js-pipeline-triggers') + redirect_to project_settings_ci_cd_path(@project, anchor: "js-pipeline-triggers") end def take_ownership if trigger.update(owner: current_user) - flash[:notice] = 'Trigger was re-assigned.' + flash[:notice] = "Trigger was re-assigned." else - flash[:alert] = 'You could not take ownership of trigger.' + flash[:alert] = "You could not take ownership of trigger." end - redirect_to project_settings_ci_cd_path(@project, anchor: 'js-pipeline-triggers') + redirect_to project_settings_ci_cd_path(@project, anchor: "js-pipeline-triggers") end def edit @@ -39,7 +39,7 @@ class Projects::TriggersController < Projects::ApplicationController def update if trigger.update(trigger_params) - redirect_to project_settings_ci_cd_path(@project, anchor: 'js-pipeline-triggers'), notice: 'Trigger was successfully updated.' + redirect_to project_settings_ci_cd_path(@project, anchor: "js-pipeline-triggers"), notice: "Trigger was successfully updated." else render action: "edit" end @@ -52,7 +52,7 @@ class Projects::TriggersController < Projects::ApplicationController flash[:alert] = "Could not remove the trigger." end - redirect_to project_settings_ci_cd_path(@project, anchor: 'js-pipeline-triggers'), status: :found + redirect_to project_settings_ci_cd_path(@project, anchor: "js-pipeline-triggers"), status: :found end private diff --git a/app/controllers/projects/uploads_controller.rb b/app/controllers/projects/uploads_controller.rb index 4ffcc2ac805..ee2ca2eb3fd 100644 --- a/app/controllers/projects/uploads_controller.rb +++ b/app/controllers/projects/uploads_controller.rb @@ -6,7 +6,7 @@ class Projects::UploadsController < Projects::ApplicationController # These will kick you out if you don't have access. skip_before_action :project, :repository, - if: -> { action_name == 'show' && image_or_video? } + if: -> { action_name == "show" && image_or_video? } before_action :authorize_upload_file!, only: [:create, :authorize] before_action :verify_workhorse_api!, only: [:authorize] diff --git a/app/controllers/projects/variables_controller.rb b/app/controllers/projects/variables_controller.rb index bb658bfcc19..1dedae56013 100644 --- a/app/controllers/projects/variables_controller.rb +++ b/app/controllers/projects/variables_controller.rb @@ -6,7 +6,7 @@ class Projects::VariablesController < Projects::ApplicationController def show respond_to do |format| format.json do - render status: :ok, json: { variables: VariableSerializer.new.represent(@project.variables) } + render status: :ok, json: {variables: VariableSerializer.new.represent(@project.variables)} end end end @@ -26,7 +26,7 @@ class Projects::VariablesController < Projects::ApplicationController private def render_variables - render status: :ok, json: { variables: VariableSerializer.new.represent(@project.variables) } + render status: :ok, json: {variables: VariableSerializer.new.represent(@project.variables)} end def render_error diff --git a/app/controllers/projects/wikis_controller.rb b/app/controllers/projects/wikis_controller.rb index 88dd111132b..e0b7ac2db23 100644 --- a/app/controllers/projects/wikis_controller.rb +++ b/app/controllers/projects/wikis_controller.rb @@ -21,20 +21,20 @@ class Projects::WikisController < Projects::ApplicationController end def show - view_param = @project_wiki.empty? ? params[:view] : 'create' + view_param = @project_wiki.empty? ? params[:view] : "create" if @page set_encoding_error unless valid_encoding? - render 'show' + render "show" elsif file_blob send_blob(@project_wiki.repository, file_blob) - elsif can?(current_user, :create_wiki, @project) && view_param == 'create' + elsif can?(current_user, :create_wiki, @project) && view_param == "create" @page = build_page(title: params[:id]) - render 'edit' + render "edit" else - render 'empty' + render "empty" end end @@ -42,21 +42,21 @@ class Projects::WikisController < Projects::ApplicationController end def update - return render('empty') unless can?(current_user, :create_wiki, @project) + return render("empty") unless can?(current_user, :create_wiki, @project) @page = WikiPages::UpdateService.new(@project, current_user, wiki_params).execute(@page) if @page.valid? redirect_to( project_wiki_path(@project, @page), - notice: 'Wiki was successfully updated.' + notice: "Wiki was successfully updated." ) else - render 'edit' + render "edit" end rescue WikiPage::PageChangedError, WikiPage::PageRenameError, Gitlab::Git::Wiki::OperationError => e @error = e - render 'edit' + render "edit" end def create @@ -65,7 +65,7 @@ class Projects::WikisController < Projects::ApplicationController if @page.persisted? redirect_to( project_wiki_path(@project, @page), - notice: 'Wiki was successfully updated.' + notice: "Wiki was successfully updated." ) else render action: "edit" @@ -74,13 +74,13 @@ class Projects::WikisController < Projects::ApplicationController @page = build_page(wiki_params) @error = e - render 'edit' + render "edit" end def history if @page @page_versions = Kaminari.paginate_array(@page.versions(page: params[:page].to_i), - total_count: @page.count_versions) + total_count: @page.count_versions) .page(params[:page]) else redirect_to( @@ -94,11 +94,11 @@ class Projects::WikisController < Projects::ApplicationController WikiPages::DestroyService.new(@project, current_user).execute(@page) redirect_to project_wiki_path(@project, :home), - status: 302, - notice: "Page was successfully deleted" + status: 302, + notice: "Page was successfully deleted" rescue Gitlab::Git::Wiki::OperationError => e @error = e - render 'edit' + render "edit" end def git_access @@ -143,7 +143,7 @@ class Projects::WikisController < Projects::ApplicationController def page_params keys = [:id] - keys << :version_id if params[:action] == 'show' + keys << :version_id if params[:action] == "show" params.values_at(*keys) end diff --git a/app/controllers/projects_controller.rb b/app/controllers/projects_controller.rb index 33c6608d321..0f346146e1d 100644 --- a/app/controllers/projects_controller.rb +++ b/app/controllers/projects_controller.rb @@ -43,21 +43,21 @@ class ProjectsController < Projects::ApplicationController def edit @badge_api_endpoint = expose_url(api_v4_projects_badges_path(id: @project.id)) - render 'edit' + render "edit" end def create @project = ::Projects::CreateService.new(current_user, project_params).execute if @project.saved? - cookies[:issue_board_welcome_hidden] = { path: project_path(@project), value: nil, expires: Time.at(0) } + cookies[:issue_board_welcome_hidden] = {path: project_path(@project), value: nil, expires: Time.at(0)} redirect_to( project_path(@project, custom_import_params), - notice: _("Project '%{project_name}' was successfully created.") % { project_name: @project.name } + notice: _("Project '%{project_name}' was successfully created.") % {project_name: @project.name} ) else - render 'new', locals: { active_tab: active_new_project_tab } + render "new", locals: {active_tab: active_new_project_tab} end end @@ -69,15 +69,15 @@ class ProjectsController < Projects::ApplicationController respond_to do |format| if result[:status] == :success - flash[:notice] = _("Project '%{project_name}' was successfully updated.") % { project_name: @project.name } + flash[:notice] = _("Project '%{project_name}' was successfully updated.") % {project_name: @project.name} format.html do - redirect_to(edit_project_path(@project, anchor: 'js-general-project-settings')) + redirect_to(edit_project_path(@project, anchor: "js-general-project-settings")) end else flash.now[:alert] = result[:message] - format.html { render 'edit' } + format.html { render "edit" } end format.js @@ -101,7 +101,7 @@ class ProjectsController < Projects::ApplicationController return access_denied! unless can?(current_user, :remove_fork_project, @project) if ::Projects::UnlinkForkService.new(@project, current_user).execute - flash[:notice] = _('The fork relationship has been removed.') + flash[:notice] = _("The fork relationship has been removed.") end end @@ -110,7 +110,7 @@ class ProjectsController < Projects::ApplicationController format.html format.json do load_events - pager_json('events/_events', @events.count) + pager_json("events/_events", @events.count) end end end @@ -122,7 +122,7 @@ class ProjectsController < Projects::ApplicationController end if @project.pending_delete? - flash.now[:alert] = _("Project '%{project_name}' queued for deletion.") % { project_name: @project.name } + flash.now[:alert] = _("Project '%{project_name}' queued for deletion.") % {project_name: @project.name} end respond_to do |format| @@ -135,7 +135,7 @@ class ProjectsController < Projects::ApplicationController format.atom do load_events - render layout: 'xml.atom' + render layout: "xml.atom" end end end @@ -144,7 +144,7 @@ class ProjectsController < Projects::ApplicationController return access_denied! unless can?(current_user, :remove_project, @project) ::Projects::DestroyService.new(@project, current_user, {}).async_execute - flash[:notice] = _("Project '%{project_name}' is in the process of being deleted.") % { project_name: @project.full_name } + flash[:notice] = _("Project '%{project_name}' is in the process of being deleted.") % {project_name: @project.full_name} redirect_to dashboard_projects_path, status: :found rescue Projects::DestroyService::DestroyError => ex @@ -155,7 +155,7 @@ class ProjectsController < Projects::ApplicationController return render_404 unless Gitlab::IncomingEmail.supports_issue_creation? current_user.reset_incoming_email_token! - render json: { new_address: @project.new_issuable_address(current_user, params[:issuable_type]) } + render json: {new_address: @project.new_issuable_address(current_user, params[:issuable_type])} end def archive @@ -187,7 +187,7 @@ class ProjectsController < Projects::ApplicationController ) rescue ::Projects::HousekeepingService::LeaseTaken => ex redirect_to( - edit_project_path(@project, anchor: 'js-project-advanced-settings'), + edit_project_path(@project, anchor: "js-project-advanced-settings"), alert: ex.to_s ) end @@ -196,7 +196,7 @@ class ProjectsController < Projects::ApplicationController @project.add_export_job(current_user: current_user) redirect_to( - edit_project_path(@project, anchor: 'js-export-project'), + edit_project_path(@project, anchor: "js-export-project"), notice: _("Project export started. A download link will be sent by email.") ) end @@ -206,7 +206,7 @@ class ProjectsController < Projects::ApplicationController send_upload(@project.export_file, attachment: @project.export_file.filename) else redirect_to( - edit_project_path(@project, anchor: 'js-export-project'), + edit_project_path(@project, anchor: "js-export-project"), alert: _("Project export link has expired. Please generate a new export from your project settings.") ) end @@ -219,7 +219,7 @@ class ProjectsController < Projects::ApplicationController flash[:alert] = _("Project export could not be deleted.") end - redirect_to(edit_project_path(@project, anchor: 'js-export-project')) + redirect_to(edit_project_path(@project, anchor: "js-export-project")) end def generate_new_export @@ -227,7 +227,7 @@ class ProjectsController < Projects::ApplicationController export else redirect_to( - edit_project_path(@project, anchor: 'js-export-project'), + edit_project_path(@project, anchor: "js-export-project"), alert: _("Project export could not be deleted.") ) end @@ -238,41 +238,41 @@ class ProjectsController < Projects::ApplicationController @project.reload render json: { - star_count: @project.star_count + star_count: @project.star_count, } end # rubocop: disable CodeReuse/ActiveRecord def refs - find_refs = params['find'] + find_refs = params["find"] find_branches = true find_tags = true find_commits = true unless find_refs.nil? - find_branches = find_refs.include?('branches') - find_tags = find_refs.include?('tags') - find_commits = find_refs.include?('commits') + find_branches = find_refs.include?("branches") + find_tags = find_refs.include?("tags") + find_commits = find_refs.include?("commits") end options = {} if find_branches branches = BranchesFinder.new(@repository, params).execute.take(100).map(&:name) - options['Branches'] = branches + options["Branches"] = branches end if find_tags && @repository.tag_count.nonzero? tags = TagsFinder.new(@repository, params).execute.take(100).map(&:name) - options['Tags'] = tags + options["Tags"] = tags end # If reference is commit id - we should add it to branch/tag selectbox ref = Addressable::URI.unescape(params[:ref]) if find_commits && ref && options.flatten(2).exclude?(ref) && ref =~ /\A[0-9a-zA-Z]{6,52}\z/ - options['Commits'] = [ref] + options["Commits"] = [ref] end render json: options.to_json @@ -285,16 +285,16 @@ class ProjectsController < Projects::ApplicationController # pages list order: repository readme, wiki home, issues list, customize workflow def render_landing_page if can?(current_user, :download_code, @project) - return render 'projects/no_repo' unless @project.repository_exists? + return render "projects/no_repo" unless @project.repository_exists? - render 'projects/empty' if @project.empty_repo? + render "projects/empty" if @project.empty_repo? else if can?(current_user, :read_wiki, @project) @project_wiki = @project.wiki - @wiki_home = @project_wiki.find_page('home', params[:version_id]) + @wiki_home = @project_wiki.find_page("home", params[:version_id]) elsif @project.feature_available?(:issues, current_user) @issues = issuables_collection.page(params[:page]) - @collection_type = 'Issue' + @collection_type = "Issue" @issuable_meta_data = issuable_meta_data(@issues, @collection_type) end @@ -308,11 +308,11 @@ class ProjectsController < Projects::ApplicationController def determine_layout if [:new, :create].include?(action_name.to_sym) - 'application' + "application" elsif [:edit, :update].include?(action_name.to_sym) - 'project_settings' + "project_settings" else - 'project' + "project" end end @@ -371,7 +371,7 @@ class ProjectsController < Projects::ApplicationController snippets_access_level wiki_access_level pages_access_level - ] + ], ] end @@ -380,12 +380,11 @@ class ProjectsController < Projects::ApplicationController end def active_new_project_tab - project_params[:import_url].present? ? 'import' : 'blank' + project_params[:import_url].present? ? "import" : "blank" end def repo_exists? project.repository_exists? && !project.empty_repo? - rescue Gitlab::Git::Repository::NoRepository project.repository.expire_exists_cache @@ -394,7 +393,7 @@ class ProjectsController < Projects::ApplicationController def project_view_files? if current_user - current_user.project_view == 'files' + current_user.project_view == "files" else project_view_files_allowed? end @@ -404,7 +403,7 @@ class ProjectsController < Projects::ApplicationController # for the blob/tree, which in this case is just the root of the default branch. # This way we avoid to access the repository.ref_names. def extract_ref(_id) - [get_id, ''] + [get_id, ""] end # Override get_id from ExtractsPath in this case is just the root of the default branch. @@ -433,11 +432,11 @@ class ProjectsController < Projects::ApplicationController # to # localhost/group/project # - redirect_to request.original_url.sub(%r{\.git/?\Z}, '') if params[:format] == 'git' + redirect_to request.original_url.sub(%r{\.git/?\Z}, "") if params[:format] == "git" end def whitelist_query_limiting - Gitlab::QueryLimiting.whitelist('https://gitlab.com/gitlab-org/gitlab-ce/issues/42440') + Gitlab::QueryLimiting.whitelist("https://gitlab.com/gitlab-org/gitlab-ce/issues/42440") end def present_project diff --git a/app/controllers/registrations_controller.rb b/app/controllers/registrations_controller.rb index 8b8d87524a8..1a034f2400c 100644 --- a/app/controllers/registrations_controller.rb +++ b/app/controllers/registrations_controller.rb @@ -6,8 +6,8 @@ class RegistrationsController < Devise::RegistrationsController before_action :whitelist_query_limiting, only: [:destroy] before_action :ensure_terms_accepted, - if: -> { Gitlab::CurrentSettings.current_application_settings.enforce_terms? }, - only: [:create] + if: -> { Gitlab::CurrentSettings.current_application_settings.enforce_terms? }, + only: [:create] def new redirect_to(new_user_session_path) @@ -27,9 +27,9 @@ class RegistrationsController < Devise::RegistrationsController persist_accepted_terms_if_required(new_user) end else - flash[:alert] = 'There was an error with the reCAPTCHA. Please solve the reCAPTCHA again.' + flash[:alert] = "There was an error with the reCAPTCHA. Please solve the reCAPTCHA again." flash.delete :recaptcha_error - render action: 'new' + render action: "new" end rescue Gitlab::Access::AccessDeniedError redirect_to(new_user_session_path) @@ -39,7 +39,7 @@ class RegistrationsController < Devise::RegistrationsController if destroy_confirmation_valid? current_user.delete_async(deleted_by: current_user) session.try(:destroy) - redirect_to new_user_session_path, status: 303, notice: s_('Profiles|Account scheduled for removal.') + redirect_to new_user_session_path, status: 303, notice: s_("Profiles|Account scheduled for removal.") else redirect_to profile_account_path, status: 303, alert: destroy_confirmation_failure_message end @@ -67,9 +67,9 @@ class RegistrationsController < Devise::RegistrationsController def destroy_confirmation_failure_message if current_user.confirm_deletion_with_password? - s_('Profiles|Invalid password') + s_("Profiles|Invalid password") else - s_('Profiles|Invalid username') + s_("Profiles|Invalid username") end end @@ -106,13 +106,13 @@ class RegistrationsController < Devise::RegistrationsController end def whitelist_query_limiting - Gitlab::QueryLimiting.whitelist('https://gitlab.com/gitlab-org/gitlab-ce/issues/42380') + Gitlab::QueryLimiting.whitelist("https://gitlab.com/gitlab-org/gitlab-ce/issues/42380") end def ensure_terms_accepted return if terms_accepted? - redirect_to new_user_session_path, alert: _('You must accept our Terms of Service and privacy policy in order to register an account') + redirect_to new_user_session_path, alert: _("You must accept our Terms of Service and privacy policy in order to register an account") end def terms_accepted? diff --git a/app/controllers/root_controller.rb b/app/controllers/root_controller.rb index 7b6657e1196..304dacfcc98 100644 --- a/app/controllers/root_controller.rb +++ b/app/controllers/root_controller.rb @@ -33,20 +33,20 @@ class RootController < Dashboard::ProjectsController def redirect_logged_user case current_user.dashboard - when 'stars' + when "stars" flash.keep redirect_to(starred_dashboard_projects_path) - when 'project_activity' + when "project_activity" redirect_to(activity_dashboard_path) - when 'starred_project_activity' - redirect_to(activity_dashboard_path(filter: 'starred')) - when 'groups' + when "starred_project_activity" + redirect_to(activity_dashboard_path(filter: "starred")) + when "groups" redirect_to(dashboard_groups_path) - when 'todos' + when "todos" redirect_to(dashboard_todos_path) - when 'issues' + when "issues" redirect_to(issues_dashboard_path(assignee_username: current_user.username)) - when 'merge_requests' + when "merge_requests" redirect_to(merge_requests_dashboard_path(assignee_username: current_user.username)) end end @@ -56,8 +56,8 @@ class RootController < Dashboard::ProjectsController # Don't redirect to the default URL to prevent endless redirections return false unless Gitlab::CurrentSettings.home_page_url.present? - home_page_url = Gitlab::CurrentSettings.home_page_url.chomp('/') - root_urls = [Gitlab.config.gitlab['url'].chomp('/'), root_url.chomp('/')] + home_page_url = Gitlab::CurrentSettings.home_page_url.chomp("/") + root_urls = [Gitlab.config.gitlab["url"].chomp("/"), root_url.chomp("/")] root_urls.exclude?(home_page_url) end diff --git a/app/controllers/search_controller.rb b/app/controllers/search_controller.rb index 1b22907c10f..3e84b5b121a 100644 --- a/app/controllers/search_controller.rb +++ b/app/controllers/search_controller.rb @@ -11,7 +11,7 @@ class SearchController < ApplicationController search_term_present && !params[:project_id].present? end - layout 'search' + layout "search" def show search_service = SearchService.new(current_user, params) @@ -28,7 +28,7 @@ class SearchController < ApplicationController @search_results = search_service.search_results @search_objects = search_service.search_objects - render_commits if @scope == 'commits' + render_commits if @scope == "commits" check_single_commit_result end @@ -56,7 +56,7 @@ class SearchController < ApplicationController def check_single_commit_result if @search_results.single_commit_result? - only_commit = @search_results.objects('commits').first + only_commit = @search_results.objects("commits").first query = params[:search].strip.downcase found_by_commit_sha = Commit.valid_hash?(query) && only_commit.sha.start_with?(query) diff --git a/app/controllers/sent_notifications_controller.rb b/app/controllers/sent_notifications_controller.rb index 2b76921ebd8..baaf8636f5a 100644 --- a/app/controllers/sent_notifications_controller.rb +++ b/app/controllers/sent_notifications_controller.rb @@ -6,7 +6,7 @@ class SentNotificationsController < ApplicationController def unsubscribe @sent_notification = SentNotification.for(params[:id]) - return render_404 unless @sent_notification && @sent_notification.unsubscribable? + return render_404 unless @sent_notification&.unsubscribable? return unsubscribe_and_redirect if current_user || params[:force] end diff --git a/app/controllers/sessions_controller.rb b/app/controllers/sessions_controller.rb index 4bd7d71e264..fff5e72f96f 100644 --- a/app/controllers/sessions_controller.rb +++ b/app/controllers/sessions_controller.rb @@ -22,7 +22,7 @@ class SessionsController < Devise::SessionsController helper_method :captcha_enabled? - CAPTCHA_HEADER = 'X-GitLab-Show-Login-Captcha'.freeze + CAPTCHA_HEADER = "X-GitLab-Show-Login-Captcha" def new set_minimum_password_length @@ -70,7 +70,7 @@ class SessionsController < Devise::SessionsController increment_failed_login_captcha_counter self.resource = resource_class.new - flash[:alert] = 'There was an error with the reCAPTCHA. Please solve the reCAPTCHA again.' + flash[:alert] = "There was an error with the reCAPTCHA. Please solve the reCAPTCHA again." flash.delete :recaptcha_error respond_with_navigational(resource) { render :new } @@ -80,14 +80,14 @@ class SessionsController < Devise::SessionsController def increment_failed_login_captcha_counter Gitlab::Metrics.counter( :failed_login_captcha_total, - 'Number of failed CAPTCHA attempts for logins'.freeze + "Number of failed CAPTCHA attempts for logins" ).increment end def increment_successful_login_captcha_counter Gitlab::Metrics.counter( :successful_login_captcha_total, - 'Number of successful CAPTCHA attempts for logins'.freeze + "Number of successful CAPTCHA attempts for logins" ).increment end @@ -96,7 +96,7 @@ class SessionsController < Devise::SessionsController # leaving this method here because of backwards compatibility. # def login_counter - @login_counter ||= Gitlab::Metrics.counter(:user_session_logins_total, 'User sign in count') + @login_counter ||= Gitlab::Metrics.counter(:user_session_logins_total, "User sign in count") end def log_failed_login @@ -115,7 +115,7 @@ class SessionsController < Devise::SessionsController user = User.admins.last - return unless user && user.require_password_creation_for_web? + return unless user&.require_password_creation_for_web? Users::UpdateService.new(current_user, user: user).execute do |user| @token = user.generate_reset_token @@ -144,7 +144,7 @@ class SessionsController < Devise::SessionsController def store_redirect_uri redirect_uri = - if request.referer.present? && (params['redirect_to_referer'] == 'yes') + if request.referer.present? && (params["redirect_to_referer"] == "yes") URI(request.referer) else URI(request.url) @@ -177,7 +177,7 @@ class SessionsController < Devise::SessionsController # Auto sign in with an Omniauth provider only if the standard "you need to sign-in" alert is # registered or no alert at all. In case of another alert (such as a blocked user), it is safer # to do nothing to prevent redirection loops with certain Omniauth providers. - return unless flash[:alert].blank? || flash[:alert] == I18n.t('devise.failure.unauthenticated') + return unless flash[:alert].blank? || flash[:alert] == I18n.t("devise.failure.unauthenticated") # Prevent alert from popping up on the first page shown after authentication. flash[:alert] = nil @@ -198,7 +198,7 @@ class SessionsController < Devise::SessionsController def log_user_activity(user) login_counter.increment - Users::ActivityService.new(user, 'login').execute + Users::ActivityService.new(user, "login").execute end def load_recaptcha diff --git a/app/controllers/sherlock/transactions_controller.rb b/app/controllers/sherlock/transactions_controller.rb index 8d1847507cc..a6289af198b 100644 --- a/app/controllers/sherlock/transactions_controller.rb +++ b/app/controllers/sherlock/transactions_controller.rb @@ -15,7 +15,7 @@ module Sherlock def destroy_all Gitlab::Sherlock.collection.clear - redirect_back_or_default(options: { status: :found }) + redirect_back_or_default(options: {status: :found}) end end end diff --git a/app/controllers/snippets/notes_controller.rb b/app/controllers/snippets/notes_controller.rb index eee14b0faf4..ae1018f06c5 100644 --- a/app/controllers/snippets/notes_controller.rb +++ b/app/controllers/snippets/notes_controller.rb @@ -13,7 +13,7 @@ class Snippets::NotesController < ApplicationController def note @note ||= snippet.notes.inc_relations_for_view.find(params[:id]) end - alias_method :awardable, :note + alias awardable note def project nil @@ -24,10 +24,10 @@ class Snippets::NotesController < ApplicationController PersonalSnippet.find_by(id: params[:snippet_id]) end # rubocop: enable CodeReuse/ActiveRecord - alias_method :noteable, :snippet + alias noteable snippet def finder_params - params.merge(last_fetched_at: last_fetched_at, target_id: snippet.id, target_type: 'personal_snippet') + params.merge(last_fetched_at: last_fetched_at, target_id: snippet.id, target_type: "personal_snippet") end def authorize_read_snippet! diff --git a/app/controllers/snippets_controller.rb b/app/controllers/snippets_controller.rb index 8ea5450b4e8..bc8923703d2 100644 --- a/app/controllers/snippets_controller.rb +++ b/app/controllers/snippets_controller.rb @@ -23,7 +23,7 @@ class SnippetsController < ApplicationController skip_before_action :authenticate_user!, only: [:index, :show, :raw] - layout 'snippets' + layout "snippets" respond_to :html def index @@ -33,7 +33,7 @@ class SnippetsController < ApplicationController @snippets = SnippetsFinder.new(current_user, author: @user, scope: params[:scope]) .execute.page(params[:page]) - render 'index' + render "index" else redirect_to(current_user ? dashboard_snippets_path : explore_snippets_path) end @@ -73,7 +73,7 @@ class SnippetsController < ApplicationController respond_to do |format| format.html do - render 'show' + render "show" end format.json do @@ -82,7 +82,7 @@ class SnippetsController < ApplicationController format.js do if @snippet.embeddable? - render 'shared/snippets/show' + render "shared/snippets/show" else head :not_found end @@ -106,8 +106,8 @@ class SnippetsController < ApplicationController end # rubocop: enable CodeReuse/ActiveRecord - alias_method :awardable, :snippet - alias_method :spammable, :snippet + alias awardable snippet + alias spammable snippet def spammable_path snippet_path(@snippet) diff --git a/app/controllers/uploads_controller.rb b/app/controllers/uploads_controller.rb index 519e7439205..bc9c229ce00 100644 --- a/app/controllers/uploads_controller.rb +++ b/app/controllers/uploads_controller.rb @@ -6,13 +6,13 @@ class UploadsController < ApplicationController UnknownUploadModelError = Class.new(StandardError) MODEL_CLASSES = { - "user" => User, - "project" => Project, - "note" => Note, - "group" => Group, - "appearance" => Appearance, + "user" => User, + "project" => Project, + "note" => Note, + "group" => Group, + "appearance" => Appearance, "personal_snippet" => PersonalSnippet, - nil => PersonalSnippet + nil => PersonalSnippet, }.freeze rescue_from UnknownUploadModelError, with: :render_404 @@ -85,6 +85,6 @@ class UploadsController < ApplicationController def upload_mount_satisfied? return true unless upload_model_class_has_mounts? - upload_model_class.uploader_options.has_key?(upload_mount) + upload_model_class.uploader_options.key?(upload_mount) end end diff --git a/app/controllers/users/terms_controller.rb b/app/controllers/users/terms_controller.rb index 3c16d934b4d..8ff5bcb8b8a 100644 --- a/app/controllers/users/terms_controller.rb +++ b/app/controllers/users/terms_controller.rb @@ -12,7 +12,7 @@ module Users before_action :terms - layout 'terms' + layout "terms" def index @redirect = redirect_path @@ -24,25 +24,25 @@ module Users def accept agreement = Users::RespondToTermsService.new(current_user, viewed_term) - .execute(accepted: true) + .execute(accepted: true) if agreement.persisted? redirect_to redirect_path else - flash[:alert] = agreement.errors.full_messages.join(', ') + flash[:alert] = agreement.errors.full_messages.join(", ") redirect_to terms_path, redirect: redirect_path end end def decline agreement = Users::RespondToTermsService.new(current_user, viewed_term) - .execute(accepted: false) + .execute(accepted: false) if agreement.persisted? sign_out(current_user) redirect_to root_path else - flash[:alert] = agreement.errors.full_messages.join(', ') + flash[:alert] = agreement.errors.full_messages.join(", ") redirect_to terms_path, redirect: redirect_path end end diff --git a/app/controllers/users_controller.rb b/app/controllers/users_controller.rb index 072d62ddf38..2e3dcb63f46 100644 --- a/app/controllers/users_controller.rb +++ b/app/controllers/users_controller.rb @@ -17,7 +17,7 @@ class UsersController < ApplicationController prepend_before_action(only: [:show]) { authenticate_sessionless_user!(:rss) } before_action :user, except: [:exists] before_action :authorize_read_user_profile!, - only: [:calendar, :calendar_activities, :groups, :projects, :contributed_projects, :snippets] + only: [:calendar, :calendar_activities, :groups, :projects, :contributed_projects, :snippets] def show respond_to do |format| @@ -25,7 +25,7 @@ class UsersController < ApplicationController format.atom do load_events - render layout: 'xml.atom' + render layout: "xml.atom" end format.json do @@ -37,7 +37,7 @@ class UsersController < ApplicationController def activity respond_to do |format| - format.html { render 'show' } + format.html { render "show" } end end @@ -45,10 +45,10 @@ class UsersController < ApplicationController load_groups respond_to do |format| - format.html { render 'show' } + format.html { render "show" } format.json do render json: { - html: view_to_html_string("shared/groups/_list", groups: @groups) + html: view_to_html_string("shared/groups/_list", groups: @groups), } end end @@ -62,7 +62,7 @@ class UsersController < ApplicationController compact_mode = Gitlab::Utils.to_boolean(params[:compact_mode]) respond_to do |format| - format.html { render 'show' } + format.html { render "show" } format.json do pager_json("shared/projects/_list", @projects.count, projects: @projects, skip_pagination: skip_pagination, skip_namespace: skip_namespace, compact_mode: compact_mode) end @@ -73,10 +73,10 @@ class UsersController < ApplicationController load_contributed_projects respond_to do |format| - format.html { render 'show' } + format.html { render "show" } format.json do render json: { - html: view_to_html_string("shared/projects/_list", projects: @contributed_projects) + html: view_to_html_string("shared/projects/_list", projects: @contributed_projects), } end end @@ -86,10 +86,10 @@ class UsersController < ApplicationController load_snippets respond_to do |format| - format.html { render 'show' } + format.html { render "show" } format.json do render json: { - html: view_to_html_string("snippets/_snippets", collection: @snippets) + html: view_to_html_string("snippets/_snippets", collection: @snippets), } end end @@ -100,14 +100,18 @@ class UsersController < ApplicationController end def calendar_activities - @calendar_date = Date.parse(params[:date]) rescue Date.today + @calendar_date = begin + Date.parse(params[:date]) + rescue + Date.today + end @events = contributions_calendar.events_by_date(@calendar_date) - render 'calendar_activities', layout: false + render "calendar_activities", layout: false end def exists - render json: { exists: !!Namespace.find_by_path_or_name(params[:username]) } + render json: {exists: !!Namespace.find_by_path_or_name(params[:username])} end private @@ -133,8 +137,8 @@ class UsersController < ApplicationController def load_projects @projects = PersonalProjectsFinder.new(user).execute(current_user) - .page(params[:page]) - .per(params[:limit]) + .page(params[:page]) + .per(params[:limit]) prepare_projects_for_rendering(@projects) end diff --git a/app/finders/admin/projects_finder.rb b/app/finders/admin/projects_finder.rb index e2b9b0b44c1..c4764671204 100644 --- a/app/finders/admin/projects_finder.rb +++ b/app/finders/admin/projects_finder.rb @@ -51,7 +51,7 @@ class Admin::ProjectsFinder # rubocop: enable CodeReuse/ActiveRecord def by_archived(items) - if params[:archived] == 'only' + if params[:archived] == "only" items.archived elsif params[:archived].blank? items.non_archived @@ -69,7 +69,7 @@ class Admin::ProjectsFinder end def sort(items) - sort = params.fetch(:sort) { 'latest_activity_desc' } + sort = params.fetch(:sort) { "latest_activity_desc" } items.sort_by_attribute(sort) end end diff --git a/app/finders/admin/runners_finder.rb b/app/finders/admin/runners_finder.rb index b2799565f57..b8533436dcf 100644 --- a/app/finders/admin/runners_finder.rb +++ b/app/finders/admin/runners_finder.rb @@ -19,10 +19,10 @@ class Admin::RunnersFinder < UnionFinder end def sort_key - if @params[:sort] == 'contacted_asc' - 'contacted_asc' + if @params[:sort] == "contacted_asc" + "contacted_asc" else - 'created_date' + "created_date" end end diff --git a/app/finders/autocomplete/users_finder.rb b/app/finders/autocomplete/users_finder.rb index 45955783be9..47af42ddc11 100644 --- a/app/finders/autocomplete/users_finder.rb +++ b/app/finders/autocomplete/users_finder.rb @@ -9,8 +9,8 @@ module Autocomplete LIMIT = 20 attr_reader :current_user, :project, :group, :search, :skip_users, - :author_id, :todo_filter, :todo_state_filter, - :filter_by_current_user + :author_id, :todo_filter, :todo_state_filter, + :filter_by_current_user def initialize(params:, current_user:, project:, group:) @current_user = current_user diff --git a/app/finders/awarded_emoji_finder.rb b/app/finders/awarded_emoji_finder.rb index f0cc17f3b26..57e1ad0d305 100644 --- a/app/finders/awarded_emoji_finder.rb +++ b/app/finders/awarded_emoji_finder.rb @@ -16,6 +16,6 @@ class AwardedEmojiFinder # in descending order, based on how often they were awarded. AwardEmoji .award_counts_for_user(current_user) - .map { |name, _| { name: name } } + .map { |name, _| {name: name} } end end diff --git a/app/finders/branches_finder.rb b/app/finders/branches_finder.rb index 45d5591e81b..4beed0691ed 100644 --- a/app/finders/branches_finder.rb +++ b/app/finders/branches_finder.rb @@ -21,16 +21,16 @@ class BranchesFinder end def sort - @params[:sort].presence || 'name' + @params[:sort].presence || "name" end def by_search(branches) return branches unless search case search - when ->(v) { v.starts_with?('^') } + when ->(v) { v.starts_with?("^") } filter_branches_with_prefix(branches, search.slice(1..-1).upcase) - when ->(v) { v.ends_with?('$') } + when ->(v) { v.ends_with?("$") } filter_branches_with_suffix(branches, search.chop.upcase) else matches = filter_branches_by_name(branches, search.upcase) diff --git a/app/finders/concerns/custom_attributes_filter.rb b/app/finders/concerns/custom_attributes_filter.rb index 825c3a6b5b7..261a8de1634 100644 --- a/app/finders/concerns/custom_attributes_filter.rb +++ b/app/finders/concerns/custom_attributes_filter.rb @@ -10,14 +10,14 @@ module CustomAttributesFilter attributes_table = association.klass.arel_table attributable_table = items.model.arel_table - custom_attributes = association.klass.select('true').where( + custom_attributes = association.klass.select("true").where( attributes_table[association.foreign_key] .eq(attributable_table[association.association_primary_key]) ) # perform a subquery for each attribute to be filtered params[:custom_attributes].inject(items) do |scope, (key, value)| - scope.where('EXISTS (?)', custom_attributes.where(key: key, value: value)) + scope.where("EXISTS (?)", custom_attributes.where(key: key, value: value)) end end # rubocop: enable CodeReuse/ActiveRecord diff --git a/app/finders/concerns/finder_methods.rb b/app/finders/concerns/finder_methods.rb index 8de3276184d..78ee8fbf573 100644 --- a/app/finders/concerns/finder_methods.rb +++ b/app/finders/concerns/finder_methods.rb @@ -34,8 +34,6 @@ module FinderMethods if can_read_object?(result) result - else - nil end end diff --git a/app/finders/environments_finder.rb b/app/finders/environments_finder.rb index 419be46fafe..262cfcdabcc 100644 --- a/app/finders/environments_finder.rb +++ b/app/finders/environments_finder.rb @@ -12,7 +12,7 @@ class EnvironmentsFinder deployments = project.deployments deployments = if ref - deployments_query = params[:with_tags] ? 'ref = :ref OR tag IS TRUE' : 'ref = :ref' + deployments_query = params[:with_tags] ? "ref = :ref OR tag IS TRUE" : "ref = :ref" deployments.where(deployments_query, ref: ref.to_s) elsif commit deployments.where(sha: commit.sha) diff --git a/app/finders/events_finder.rb b/app/finders/events_finder.rb index 234b7090fd9..9be9431f9ca 100644 --- a/app/finders/events_finder.rb +++ b/app/finders/events_finder.rb @@ -74,7 +74,7 @@ class EventsFinder def by_created_at_before(events) return events unless params[:before] - events.where('events.created_at < ?', params[:before].beginning_of_day) + events.where("events.created_at < ?", params[:before].beginning_of_day) end # rubocop: enable CodeReuse/ActiveRecord @@ -82,14 +82,14 @@ class EventsFinder def by_created_at_after(events) return events unless params[:after] - events.where('events.created_at > ?', params[:after].end_of_day) + events.where("events.created_at > ?", params[:after].end_of_day) end # rubocop: enable CodeReuse/ActiveRecord def sort(events) return events unless params[:sort] - if params[:sort] == 'asc' + if params[:sort] == "asc" events.order_id_asc else events.order_id_desc diff --git a/app/finders/group_descendants_finder.rb b/app/finders/group_descendants_finder.rb index ec340f38450..a82805ff0af 100644 --- a/app/finders/group_descendants_finder.rb +++ b/app/finders/group_descendants_finder.rb @@ -65,8 +65,8 @@ class GroupDescendantsFinder def direct_child_groups # rubocop: disable CodeReuse/Finder GroupsFinder.new(current_user, - parent: parent_group, - all_available: true).execute + parent: parent_group, + all_available: true).execute # rubocop: enable CodeReuse/Finder end @@ -75,15 +75,15 @@ class GroupDescendantsFinder # rubocop: disable CodeReuse/Finder groups_table = Group.arel_table visible_to_user = groups_table[:visibility_level] - .in(Gitlab::VisibilityLevel.levels_for_user(current_user)) + .in(Gitlab::VisibilityLevel.levels_for_user(current_user)) if current_user authorized_groups = GroupsFinder.new(current_user, - all_available: false) - .execute.as('authorized') + all_available: false) + .execute.as("authorized") authorized_to_user = groups_table.project(1).from(authorized_groups) - .where(authorized_groups[:id].eq(groups_table[:id])) - .exists + .where(authorized_groups[:id].eq(groups_table[:id])) + .exists visible_to_user = visible_to_user.or(authorized_to_user) end @@ -137,17 +137,17 @@ class GroupDescendantsFinder # When filtering subgroups, we want to find all matches within the tree of # descendants to show to the user groups = if params[:filter] - subgroups_matching_filter - else - direct_child_groups - end + subgroups_matching_filter + else + direct_child_groups + end groups.with_selects_for_list(archived: params[:archived]).order_by(sort) end # rubocop: disable CodeReuse/Finder def direct_child_projects - GroupProjectsFinder.new(group: parent_group, current_user: current_user, params: params, options: { only_owned: true }) + GroupProjectsFinder.new(group: parent_group, current_user: current_user, params: params, options: {only_owned: true}) .execute end # rubocop: enable CodeReuse/Finder @@ -169,16 +169,16 @@ class GroupDescendantsFinder def projects projects = if params[:filter] - projects_matching_filter - else - direct_child_projects - end + projects_matching_filter + else + direct_child_projects + end projects.with_route.order_by(sort) end def sort - params.fetch(:sort, 'created_desc') + params.fetch(:sort, "created_desc") end # rubocop: disable CodeReuse/ActiveRecord diff --git a/app/finders/group_finder.rb b/app/finders/group_finder.rb index d2ad8a372b1..dcb2fb1e041 100644 --- a/app/finders/group_finder.rb +++ b/app/finders/group_finder.rb @@ -13,8 +13,6 @@ class GroupFinder if can?(@current_user, :read_group, group) group - else - nil end end # rubocop: enable CodeReuse/ActiveRecord diff --git a/app/finders/group_labels_finder.rb b/app/finders/group_labels_finder.rb index a668a0f0fae..e1a6ee0688b 100644 --- a/app/finders/group_labels_finder.rb +++ b/app/finders/group_labels_finder.rb @@ -24,6 +24,6 @@ class GroupLabelsFinder end def subscribed? - params[:subscribed] == 'true' + params[:subscribed] == "true" end end diff --git a/app/finders/group_members_finder.rb b/app/finders/group_members_finder.rb index eebc67cfa9e..4557e93bc35 100644 --- a/app/finders/group_members_finder.rb +++ b/app/finders/group_members_finder.rb @@ -30,7 +30,7 @@ class GroupMembersFinder wheres << "members.id IN (#{descendant_members.select(:id).to_sql})" end - GroupMember.where(wheres.join(' OR ')) + GroupMember.where(wheres.join(" OR ")) end # rubocop: enable CodeReuse/ActiveRecord end diff --git a/app/finders/group_projects_finder.rb b/app/finders/group_projects_finder.rb index 4155b6af8da..f5572ab8b5f 100644 --- a/app/finders/group_projects_finder.rb +++ b/app/finders/group_projects_finder.rb @@ -32,10 +32,10 @@ class GroupProjectsFinder < ProjectsFinder def init_collection projects = if current_user - collection_with_user - else - collection_without_user - end + collection_with_user + else + collection_without_user + end union(projects) end @@ -48,7 +48,7 @@ class GroupProjectsFinder < ProjectsFinder else [ owned_projects.public_or_visible_to_user(current_user), - shared_projects.public_or_visible_to_user(current_user) + shared_projects.public_or_visible_to_user(current_user), ] end end diff --git a/app/finders/groups_finder.rb b/app/finders/groups_finder.rb index 0080123407d..9867e6bb401 100644 --- a/app/finders/groups_finder.rb +++ b/app/finders/groups_finder.rb @@ -26,12 +26,12 @@ class GroupsFinder < UnionFinder end def execute - items = all_groups.map do |item| + items = all_groups.map { |item| item = by_parent(item) item = by_custom_attributes(item) item - end + } find_union(items, Group).with_route.order_id_desc end @@ -64,7 +64,7 @@ class GroupsFinder < UnionFinder def groups_with_min_access_level groups = current_user .groups - .where('members.access_level >= ?', params[:min_access_level]) + .where("members.access_level >= ?", params[:min_access_level]) Gitlab::ObjectHierarchy .new(groups) diff --git a/app/finders/issuable_finder.rb b/app/finders/issuable_finder.rb index 5870f158690..2d194c98675 100644 --- a/app/finders/issuable_finder.rb +++ b/app/finders/issuable_finder.rb @@ -39,11 +39,11 @@ class IssuableFinder requires_cross_project_access unless: -> { project? } # This is used as a common filter for None / Any - FILTER_NONE = 'none'.freeze - FILTER_ANY = 'any'.freeze + FILTER_NONE = "none" + FILTER_ANY = "any" # This is accepted as a deprecated filter and is also used in unassigning users - NONE = '0'.freeze + NONE = "0" attr_accessor :current_user, :params @@ -62,7 +62,7 @@ class IssuableFinder end def self.array_params - @array_params ||= { label_name: [], assignee_username: [] } + @array_params ||= {label_name: [], assignee_username: []} end def self.valid_params @@ -147,8 +147,6 @@ class IssuableFinder @group = if params[:group_id].present? Group.find(params[:group_id]) - else - nil end end @@ -187,7 +185,7 @@ class IssuableFinder if current_user && params[:authorized_only].presence && !current_user_related? current_user.authorized_projects elsif group - finder_options = { include_subgroups: params[:include_subgroups], only_owned: true } + finder_options = {include_subgroups: params[:include_subgroups], only_owned: true} GroupProjectsFinder.new(group: group, current_user: current_user, options: finder_options).execute # rubocop: disable CodeReuse/Finder else ProjectsFinder.new(current_user: current_user).execute # rubocop: disable CodeReuse/Finder @@ -218,7 +216,7 @@ class IssuableFinder group_id = group.id if group search_params = - { title: params[:milestone_title], project_ids: project_id, group_ids: group_id } + {title: params[:milestone_title], project_ids: project_id, group_ids: group_id} MilestonesFinder.new(search_params).execute # rubocop: disable CodeReuse/Finder else @@ -269,8 +267,6 @@ class IssuableFinder User.find_by(id: params[:assignee_id]) elsif assignee_username? User.find_by_username(params[:assignee_username]) - else - nil end end # rubocop: enable CodeReuse/ActiveRecord @@ -297,8 +293,6 @@ class IssuableFinder User.find_by(id: params[:author_id]) elsif author_username? User.find_by_username(params[:author_username]) - else - nil end end # rubocop: enable CodeReuse/ActiveRecord @@ -337,9 +331,9 @@ class IssuableFinder return items.none if current_user_related? && !current_user case params[:scope] - when 'created_by_me', 'authored' + when "created_by_me", "authored" items.where(author_id: current_user.id) - when 'assigned_to_me' + when "assigned_to_me" items.assigned_to(current_user) else items @@ -364,14 +358,14 @@ class IssuableFinder # rubocop: disable CodeReuse/ActiveRecord def by_state(items) case params[:state].to_s - when 'closed' + when "closed" items.closed - when 'merged' + when "merged" items.respond_to?(:merged) ? items.merged : items.closed - when 'opened' + when "opened" items.opened - when 'locked' - items.where(state: 'locked') + when "locked" + items.where(state: "locked") else items end @@ -441,7 +435,7 @@ class IssuableFinder if filter_by_no_assignee? items.where(assignee_id: nil) elsif filter_by_any_assignee? - items.where('assignee_id IS NOT NULL') + items.where("assignee_id IS NOT NULL") elsif assignee items.where(assignee_id: assignee.id) elsif assignee_id? || assignee_username? # assignee not found @@ -486,7 +480,7 @@ class IssuableFinder upcoming_ids = Milestone.upcoming_ids(projects, related_groups) items = items.left_joins_milestones.where(milestone_id: upcoming_ids) elsif filter_by_started_milestone? - items = items.left_joins_milestones.where('milestones.start_date <= NOW()') + items = items.left_joins_milestones.where("milestones.start_date <= NOW()") else items = items.with_milestone(params[:milestone_title]) end @@ -554,7 +548,7 @@ class IssuableFinder def label_names if labels? - params[:label_name].is_a?(String) ? params[:label_name].split(',') : params[:label_name] + params[:label_name].is_a?(String) ? params[:label_name].split(",") : params[:label_name] else [] end @@ -566,6 +560,6 @@ class IssuableFinder def current_user_related? scope = params[:scope] - scope == 'created_by_me' || scope == 'authored' || scope == 'assigned_to_me' + scope == "created_by_me" || scope == "authored" || scope == "assigned_to_me" end end diff --git a/app/finders/issues_finder.rb b/app/finders/issues_finder.rb index cb44575d6f1..590df04afc4 100644 --- a/app/finders/issues_finder.rb +++ b/app/finders/issues_finder.rb @@ -41,7 +41,7 @@ class IssuesFinder < IssuableFinder # rubocop: disable CodeReuse/ActiveRecord def with_confidentiality_access_check return Issue.all if user_can_see_all_confidential_issues? - return Issue.where('issues.confidential IS NOT TRUE') if user_cannot_see_confidential_issues? + return Issue.where("issues.confidential IS NOT TRUE") if user_cannot_see_confidential_issues? Issue.where(' issues.confidential IS NOT TRUE diff --git a/app/finders/labels_finder.rb b/app/finders/labels_finder.rb index e523942ea4c..52e2fa715b6 100644 --- a/app/finders/labels_finder.rb +++ b/app/finders/labels_finder.rb @@ -36,8 +36,8 @@ class LabelsFinder < UnionFinder group_ids = group_ids_for(project.group) label_ids << Label.where( - labels_table[:type].eq('GroupLabel').and(labels_table[:group_id].in(group_ids)).or( - labels_table[:type].eq('ProjectLabel').and(labels_table[:project_id].eq(project.id)) + labels_table[:type].eq("GroupLabel").and(labels_table[:group_id].in(group_ids)).or( + labels_table[:type].eq("ProjectLabel").and(labels_table[:project_id].eq(project.id)) ) ) else @@ -92,7 +92,7 @@ class LabelsFinder < UnionFinder end def subscribed? - params[:subscribed] == 'true' + params[:subscribed] == "true" end # Gets redacted array of group ids @@ -164,10 +164,10 @@ class LabelsFinder < UnionFinder return @projects if defined?(@projects) @projects = if skip_authorization - Project.all - else - ProjectsFinder.new(params: { non_archived: true }, current_user: current_user).execute # rubocop: disable CodeReuse/Finder - end + Project.all + else + ProjectsFinder.new(params: {non_archived: true}, current_user: current_user).execute # rubocop: disable CodeReuse/Finder + end @projects = @projects.in_namespace(params[:group_id]) if group? @projects = @projects.where(id: params[:project_ids]) if projects? diff --git a/app/finders/members_finder.rb b/app/finders/members_finder.rb index f90a7868102..665744fa117 100644 --- a/app/finders/members_finder.rb +++ b/app/finders/members_finder.rb @@ -40,32 +40,32 @@ class MembersFinder # We prefer project members over group members, project members should go first. if Gitlab::Database.postgresql? <<~SQL - SELECT DISTINCT ON (user_id, invite_email) member_union.* - FROM (#{union.to_sql}) AS member_union - ORDER BY user_id, - invite_email, - CASE - WHEN type = 'ProjectMember' THEN 1 - WHEN type = 'GroupMember' THEN 2 - ELSE 3 - END + SELECT DISTINCT ON (user_id, invite_email) member_union.* + FROM (#{union.to_sql}) AS member_union + ORDER BY user_id, + invite_email, + CASE + WHEN type = 'ProjectMember' THEN 1 + WHEN type = 'GroupMember' THEN 2 + ELSE 3 + END SQL else # Older versions of MySQL do not support window functions (and DISTINCT ON is postgres-specific). <<~SQL - SELECT t1.* - FROM (#{union.to_sql}) AS t1 - JOIN ( - SELECT - COALESCE(user_id, -1) AS user_id, - COALESCE(invite_email, 'NULL') AS invite_email, - MIN(CASE WHEN type = 'ProjectMember' THEN 1 WHEN type = 'GroupMember' THEN 2 ELSE 3 END) AS type_number - FROM - (#{union.to_sql}) AS t3 - GROUP BY COALESCE(user_id, -1), COALESCE(invite_email, 'NULL') - ) AS t2 ON COALESCE(t1.user_id, -1) = t2.user_id - AND COALESCE(t1.invite_email, 'NULL') = t2.invite_email - AND CASE WHEN t1.type = 'ProjectMember' THEN 1 WHEN t1.type = 'GroupMember' THEN 2 ELSE 3 END = t2.type_number + SELECT t1.* + FROM (#{union.to_sql}) AS t1 + JOIN ( + SELECT + COALESCE(user_id, -1) AS user_id, + COALESCE(invite_email, 'NULL') AS invite_email, + MIN(CASE WHEN type = 'ProjectMember' THEN 1 WHEN type = 'GroupMember' THEN 2 ELSE 3 END) AS type_number + FROM + (#{union.to_sql}) AS t3 + GROUP BY COALESCE(user_id, -1), COALESCE(invite_email, 'NULL') + ) AS t2 ON COALESCE(t1.user_id, -1) = t2.user_id + AND COALESCE(t1.invite_email, 'NULL') = t2.invite_email + AND CASE WHEN t1.type = 'ProjectMember' THEN 1 WHEN t1.type = 'GroupMember' THEN 2 ELSE 3 END = t2.type_number SQL end end diff --git a/app/finders/merge_requests_finder.rb b/app/finders/merge_requests_finder.rb index b645011a3c5..d20fd7c1f3a 100644 --- a/app/finders/merge_requests_finder.rb +++ b/app/finders/merge_requests_finder.rb @@ -68,9 +68,9 @@ class MergeRequestsFinder < IssuableFinder end def by_wip(items) - if params[:wip] == 'yes' + if params[:wip] == "yes" items.where(wip_match(items.arel_table)) - elsif params[:wip] == 'no' + elsif params[:wip] == "no" items.where.not(wip_match(items.arel_table)) else items @@ -78,8 +78,8 @@ class MergeRequestsFinder < IssuableFinder end def wip_match(table) - table[:title].matches('WIP:%') - .or(table[:title].matches('WIP %')) - .or(table[:title].matches('[WIP]%')) + table[:title].matches("WIP:%") + .or(table[:title].matches("WIP %")) + .or(table[:title].matches("[WIP]%")) end end diff --git a/app/finders/milestones_finder.rb b/app/finders/milestones_finder.rb index 77b55cbb838..209d68fec7c 100644 --- a/app/finders/milestones_finder.rb +++ b/app/finders/milestones_finder.rb @@ -58,8 +58,8 @@ class MilestonesFinder # rubocop: disable CodeReuse/ActiveRecord def order(items) - order_statement = Gitlab::Database.nulls_last_order('due_date', 'ASC') - items.reorder(order_statement).order('title ASC') + order_statement = Gitlab::Database.nulls_last_order("due_date", "ASC") + items.reorder(order_statement).order("title ASC") end # rubocop: enable CodeReuse/ActiveRecord end diff --git a/app/finders/notes_finder.rb b/app/finders/notes_finder.rb index 817aac8b5d5..6bb0108e24e 100644 --- a/app/finders/notes_finder.rb +++ b/app/finders/notes_finder.rb @@ -71,7 +71,7 @@ class NotesFinder # rubocop: disable CodeReuse/ActiveRecord def notes_of_any_type - types = %w(commit issue merge_request snippet) + types = %w[commit issue merge_request snippet] note_relations = types.map { |t| notes_for_type(t) } note_relations.map! { |notes| search(notes) } UnionFinder.new.find_union(note_relations, Note.includes(:author)) # rubocop: disable CodeReuse/Finder @@ -97,7 +97,7 @@ class NotesFinder def notes_for_type(noteable_type) if noteable_type == "commit" if Ability.allowed?(@current_user, :download_code, @project) - @project.notes.where(noteable_type: 'Commit') + @project.notes.where(noteable_type: "Commit") else Note.none end diff --git a/app/finders/personal_access_tokens_finder.rb b/app/finders/personal_access_tokens_finder.rb index bd95dcd323f..1ede7058030 100644 --- a/app/finders/personal_access_tokens_finder.rb +++ b/app/finders/personal_access_tokens_finder.rb @@ -39,9 +39,9 @@ class PersonalAccessTokensFinder def by_state(tokens) case @params[:state] - when 'active' + when "active" tokens.active - when 'inactive' + when "inactive" tokens.inactive else tokens diff --git a/app/finders/pipeline_schedules_finder.rb b/app/finders/pipeline_schedules_finder.rb index 3beee608268..b64b9013425 100644 --- a/app/finders/pipeline_schedules_finder.rb +++ b/app/finders/pipeline_schedules_finder.rb @@ -12,9 +12,9 @@ class PipelineSchedulesFinder def execute(scope: nil) scoped_schedules = case scope - when 'active' + when "active" pipeline_schedules.active - when 'inactive' + when "inactive" pipeline_schedules.inactive else pipeline_schedules diff --git a/app/finders/pipelines_finder.rb b/app/finders/pipelines_finder.rb index f5aadc42ff0..c9fa7dc6bfc 100644 --- a/app/finders/pipelines_finder.rb +++ b/app/finders/pipelines_finder.rb @@ -32,7 +32,7 @@ class PipelinesFinder # rubocop: disable CodeReuse/ActiveRecord def ids_for_ref(refs) - pipelines.where(ref: refs).group(:ref).select('max(id)') + pipelines.where(ref: refs).group(:ref).select("max(id)") end # rubocop: enable CodeReuse/ActiveRecord @@ -52,15 +52,15 @@ class PipelinesFinder def by_scope(items) case params[:scope] - when 'running' + when "running" items.running - when 'pending' + when "pending" items.pending - when 'finished' + when "finished" items.finished - when 'branches' + when "branches" from_ids(ids_for_ref(branches)) - when 'tags' + when "tags" from_ids(ids_for_ref(tags)) else items @@ -98,7 +98,7 @@ class PipelinesFinder # rubocop: disable CodeReuse/ActiveRecord def by_name(items) if params[:name].present? - items.joins(:user).where(users: { name: params[:name] }) + items.joins(:user).where(users: {name: params[:name]}) else items end @@ -108,7 +108,7 @@ class PipelinesFinder # rubocop: disable CodeReuse/ActiveRecord def by_username(items) if params[:username].present? - items.joins(:user).where(users: { username: params[:username] }) + items.joins(:user).where(users: {username: params[:username]}) else items end @@ -131,16 +131,16 @@ class PipelinesFinder # rubocop: disable CodeReuse/ActiveRecord def sort_items(items) order_by = if ALLOWED_INDEXED_COLUMNS.include?(params[:order_by]) - params[:order_by] - else - :id - end - - sort = if params[:sort] =~ /\A(ASC|DESC)\z/i - params[:sort] - else - :desc - end + params[:order_by] + else + :id + end + + sort = if /\A(ASC|DESC)\z/i.match?(params[:sort]) + params[:sort] + else + :desc + end items.order(order_by => sort) end diff --git a/app/finders/projects/serverless/functions_finder.rb b/app/finders/projects/serverless/functions_finder.rb index 2f2816a4a08..e5fa402401f 100644 --- a/app/finders/projects/serverless/functions_finder.rb +++ b/app/finders/projects/serverless/functions_finder.rb @@ -47,7 +47,8 @@ module Projects if services.length == 1 s["podcount"] = cluster.application_knative.service_pod_details( cluster.platform_kubernetes&.actual_namespace, - s["metadata"]["name"]).length + s["metadata"]["name"] + ).length end end end diff --git a/app/finders/projects_finder.rb b/app/finders/projects_finder.rb index 93d3c991846..4654ec4ed0d 100644 --- a/app/finders/projects_finder.rb +++ b/app/finders/projects_finder.rb @@ -76,7 +76,7 @@ class ProjectsFinder < UnionFinder if owned_projects? current_user.owned_projects elsif min_access_level? - current_user.authorized_projects.where('project_authorizations.access_level >= ?', params[:min_access_level]) + current_user.authorized_projects.where("project_authorizations.access_level >= ?", params[:min_access_level]) else if private_only? current_user.authorized_projects @@ -119,11 +119,11 @@ class ProjectsFinder < UnionFinder end def by_personal(items) - (params[:personal].present? && current_user) ? items.personal(current_user) : items + params[:personal].present? && current_user ? items.personal(current_user) : items end def by_starred(items) - (params[:starred].present? && current_user) ? items.starred_by(current_user) : items + params[:starred].present? && current_user ? items.starred_by(current_user) : items end def by_trending(items) @@ -157,7 +157,7 @@ class ProjectsFinder < UnionFinder if params[:non_archived] projects.non_archived elsif params.key?(:archived) - if params[:archived] == 'only' + if params[:archived] == "only" projects.archived elsif Gitlab::Utils.to_boolean(params[:archived]) projects @@ -172,6 +172,6 @@ class ProjectsFinder < UnionFinder def finder_params return {} unless min_access_level? - { min_access_level: params[:min_access_level] } + {min_access_level: params[:min_access_level]} end end diff --git a/app/finders/snippets_finder.rb b/app/finders/snippets_finder.rb index d3774746cb8..3497a04a314 100644 --- a/app/finders/snippets_finder.rb +++ b/app/finders/snippets_finder.rb @@ -52,8 +52,8 @@ class SnippetsFinder < UnionFinder if project && author raise( ArgumentError, - 'Filtering by both an author and a project is not supported, ' \ - 'as this finder is not optimised for this use case' + "Filtering by both an author and a project is not supported, " \ + "as this finder is not optimised for this use case" ) end end @@ -144,14 +144,12 @@ class SnippetsFinder < UnionFinder def visibility_from_scope case scope - when 'are_private' + when "are_private" Snippet::PRIVATE - when 'are_internal' + when "are_internal" Snippet::INTERNAL - when 'are_public' + when "are_public" Snippet::PUBLIC - else - nil end end end diff --git a/app/finders/template_finder.rb b/app/finders/template_finder.rb index 3e483716064..16071f5d236 100644 --- a/app/finders/template_finder.rb +++ b/app/finders/template_finder.rb @@ -11,7 +11,7 @@ class TemplateFinder class << self def build(type, project, params = {}) - if type.to_s == 'licenses' + if type.to_s == "licenses" LicenseTemplateFinder.new(project, params) # rubocop: disable CodeReuse/Finder else new(type, project, params) diff --git a/app/finders/todos_finder.rb b/app/finders/todos_finder.rb index d001e18fea9..e2dcc5f88fa 100644 --- a/app/finders/todos_finder.rb +++ b/app/finders/todos_finder.rb @@ -21,9 +21,9 @@ class TodosFinder requires_cross_project_access unless: -> { project? } - NONE = '0'.freeze + NONE = "0" - TODO_TYPES = Set.new(%w(Issue MergeRequest Epic)).freeze + TODO_TYPES = Set.new(%w[Issue MergeRequest Epic]).freeze attr_accessor :current_user, :params @@ -165,7 +165,7 @@ class TodosFinder end def by_state(items) - if params[:state].to_s == 'done' + if params[:state].to_s == "done" items.done else items.pending diff --git a/app/finders/users_finder.rb b/app/finders/users_finder.rb index 81ae50c0bd1..e323419386e 100644 --- a/app/finders/users_finder.rb +++ b/app/finders/users_finder.rb @@ -86,9 +86,9 @@ class UsersFinder def by_2fa(users) case params[:two_factor] - when 'enabled' + when "enabled" users.with_two_factor - when 'disabled' + when "disabled" users.without_two_factor else users diff --git a/app/graphql/mutations/base_mutation.rb b/app/graphql/mutations/base_mutation.rb index eb03dfe1624..56c9c1abe71 100644 --- a/app/graphql/mutations/base_mutation.rb +++ b/app/graphql/mutations/base_mutation.rb @@ -3,8 +3,8 @@ module Mutations class BaseMutation < GraphQL::Schema::RelayClassicMutation field :errors, [GraphQL::STRING_TYPE], - null: false, - description: "Reasons why the mutation failed." + null: false, + description: "Reasons why the mutation failed." def current_user context[:current_user] diff --git a/app/graphql/mutations/merge_requests/base.rb b/app/graphql/mutations/merge_requests/base.rb index 7d0cb777ad1..b31a24d8d16 100644 --- a/app/graphql/mutations/merge_requests/base.rb +++ b/app/graphql/mutations/merge_requests/base.rb @@ -7,17 +7,17 @@ module Mutations include Mutations::ResolvesProject argument :project_path, GraphQL::ID_TYPE, - required: true, - description: "The project the merge request to mutate is in" + required: true, + description: "The project the merge request to mutate is in" argument :iid, GraphQL::ID_TYPE, - required: true, - description: "The iid of the merge request to mutate" + required: true, + description: "The iid of the merge request to mutate" field :merge_request, - Types::MergeRequestType, - null: true, - description: "The merge request after mutation" + Types::MergeRequestType, + null: true, + description: "The merge request after mutation" authorize :update_merge_request diff --git a/app/graphql/mutations/merge_requests/set_wip.rb b/app/graphql/mutations/merge_requests/set_wip.rb index a2aa0c84ee4..0e2c512e2f8 100644 --- a/app/graphql/mutations/merge_requests/set_wip.rb +++ b/app/graphql/mutations/merge_requests/set_wip.rb @@ -3,14 +3,14 @@ module Mutations module MergeRequests class SetWip < Base - graphql_name 'MergeRequestSetWip' + graphql_name "MergeRequestSetWip" argument :wip, - GraphQL::BOOLEAN_TYPE, - required: true, - description: <<~DESC - Whether or not to set the merge request as a WIP. - DESC + GraphQL::BOOLEAN_TYPE, + required: true, + description: <<~DESC + Whether or not to set the merge request as a WIP. + DESC def resolve(project_path:, iid:, wip: nil) merge_request = authorized_find!(project_path: project_path, iid: iid) @@ -21,14 +21,14 @@ module Mutations { merge_request: merge_request, - errors: merge_request.errors.full_messages + errors: merge_request.errors.full_messages, } end private def wip_event(merge_request, wip) - wip ? 'wip' : 'unwip' + wip ? "wip" : "unwip" end end end diff --git a/app/graphql/resolvers/base_resolver.rb b/app/graphql/resolvers/base_resolver.rb index 063def75d38..09247fd8249 100644 --- a/app/graphql/resolvers/base_resolver.rb +++ b/app/graphql/resolvers/base_resolver.rb @@ -3,11 +3,11 @@ module Resolvers class BaseResolver < GraphQL::Schema::Resolver def self.single - @single ||= Class.new(self) do + @single ||= Class.new(self) { def resolve(**args) super.first end - end + } end end end diff --git a/app/graphql/resolvers/concerns/resolves_pipelines.rb b/app/graphql/resolvers/concerns/resolves_pipelines.rb index 8fd26d85994..122de4f831b 100644 --- a/app/graphql/resolvers/concerns/resolves_pipelines.rb +++ b/app/graphql/resolvers/concerns/resolves_pipelines.rb @@ -6,17 +6,17 @@ module ResolvesPipelines included do type [Types::Ci::PipelineType], null: false argument :status, - Types::Ci::PipelineStatusEnum, - required: false, - description: "Filter pipelines by their status" + Types::Ci::PipelineStatusEnum, + required: false, + description: "Filter pipelines by their status" argument :ref, - GraphQL::STRING_TYPE, - required: false, - description: "Filter pipelines by the ref they are run for" + GraphQL::STRING_TYPE, + required: false, + description: "Filter pipelines by the ref they are run for" argument :sha, - GraphQL::STRING_TYPE, - required: false, - description: "Filter pipelines by the sha of the commit they are run for" + GraphQL::STRING_TYPE, + required: false, + description: "Filter pipelines by the sha of the commit they are run for" end def resolve_pipelines(project, params = {}) diff --git a/app/graphql/resolvers/full_path_resolver.rb b/app/graphql/resolvers/full_path_resolver.rb index 0f1a64b6c58..168565c513f 100644 --- a/app/graphql/resolvers/full_path_resolver.rb +++ b/app/graphql/resolvers/full_path_resolver.rb @@ -6,8 +6,8 @@ module Resolvers prepended do argument :full_path, GraphQL::ID_TYPE, - required: true, - description: 'The full path of the project or namespace, e.g., "gitlab-org/gitlab-ce"' + required: true, + description: 'The full path of the project or namespace, e.g., "gitlab-org/gitlab-ce"' end def model_by_full_path(model, full_path) diff --git a/app/graphql/resolvers/issues_resolver.rb b/app/graphql/resolvers/issues_resolver.rb index b98d8bd1fff..6ce40d4a168 100644 --- a/app/graphql/resolvers/issues_resolver.rb +++ b/app/graphql/resolvers/issues_resolver.rb @@ -3,45 +3,45 @@ module Resolvers class IssuesResolver < BaseResolver argument :iid, GraphQL::ID_TYPE, - required: false, - description: 'The IID of the issue, e.g., "1"' + required: false, + description: 'The IID of the issue, e.g., "1"' argument :iids, [GraphQL::ID_TYPE], - required: false, - description: 'The list of IIDs of issues, e.g., [1, 2]' + required: false, + description: "The list of IIDs of issues, e.g., [1, 2]" argument :state, Types::IssuableStateEnum, - required: false, - description: "Current state of Issue" + required: false, + description: "Current state of Issue" argument :label_name, GraphQL::STRING_TYPE.to_list_type, - required: false, - description: "Labels applied to the Issue" + required: false, + description: "Labels applied to the Issue" argument :created_before, Types::TimeType, - required: false, - description: "Issues created before this date" + required: false, + description: "Issues created before this date" argument :created_after, Types::TimeType, - required: false, - description: "Issues created after this date" + required: false, + description: "Issues created after this date" argument :updated_before, Types::TimeType, - required: false, - description: "Issues updated before this date" + required: false, + description: "Issues updated before this date" argument :updated_after, Types::TimeType, - required: false, - description: "Issues updated after this date" + required: false, + description: "Issues updated after this date" argument :closed_before, Types::TimeType, - required: false, - description: "Issues closed before this date" + required: false, + description: "Issues closed before this date" argument :closed_after, Types::TimeType, - required: false, - description: "Issues closed after this date" + required: false, + description: "Issues closed after this date" argument :search, GraphQL::STRING_TYPE, - required: false + required: false argument :sort, Types::Sort, - required: false, - default_value: 'created_desc' + required: false, + default_value: "created_desc" type Types::IssueType, null: true - alias_method :project, :object + alias project object def resolve(**args) # Will need to be be made group & namespace aware with diff --git a/app/graphql/resolvers/merge_request_pipelines_resolver.rb b/app/graphql/resolvers/merge_request_pipelines_resolver.rb index b371f1335f8..79fef122141 100644 --- a/app/graphql/resolvers/merge_request_pipelines_resolver.rb +++ b/app/graphql/resolvers/merge_request_pipelines_resolver.rb @@ -4,7 +4,7 @@ module Resolvers class MergeRequestPipelinesResolver < BaseResolver include ::ResolvesPipelines - alias_method :merge_request, :object + alias merge_request object def resolve(**args) resolve_pipelines(project, args) diff --git a/app/graphql/resolvers/merge_requests_resolver.rb b/app/graphql/resolvers/merge_requests_resolver.rb index 90795c797ac..4a1c2d1740b 100644 --- a/app/graphql/resolvers/merge_requests_resolver.rb +++ b/app/graphql/resolvers/merge_requests_resolver.rb @@ -3,16 +3,16 @@ module Resolvers class MergeRequestsResolver < BaseResolver argument :iid, GraphQL::ID_TYPE, - required: false, - description: 'The IID of the merge request, e.g., "1"' + required: false, + description: 'The IID of the merge request, e.g., "1"' argument :iids, [GraphQL::ID_TYPE], - required: false, - description: 'The list of IIDs of issues, e.g., [1, 2]' + required: false, + description: "The list of IIDs of issues, e.g., [1, 2]" type Types::MergeRequestType, null: true - alias_method :project, :object + alias project object def resolve(**args) return unless project.present? diff --git a/app/graphql/resolvers/project_pipelines_resolver.rb b/app/graphql/resolvers/project_pipelines_resolver.rb index 86094c46c2a..d0dbcf240c6 100644 --- a/app/graphql/resolvers/project_pipelines_resolver.rb +++ b/app/graphql/resolvers/project_pipelines_resolver.rb @@ -4,7 +4,7 @@ module Resolvers class ProjectPipelinesResolver < BaseResolver include ResolvesPipelines - alias_method :project, :object + alias project object def resolve(**args) resolve_pipelines(project, args) diff --git a/app/graphql/types/ci/pipeline_type.rb b/app/graphql/types/ci/pipeline_type.rb index 2bbffad4563..fba8fd48d72 100644 --- a/app/graphql/types/ci/pipeline_type.rb +++ b/app/graphql/types/ci/pipeline_type.rb @@ -5,7 +5,7 @@ module Types class PipelineType < BaseObject expose_permissions Types::PermissionTypes::Ci::Pipeline - graphql_name 'Pipeline' + graphql_name "Pipeline" field :id, GraphQL::ID_TYPE, null: false field :iid, GraphQL::ID_TYPE, null: false @@ -14,13 +14,13 @@ module Types field :before_sha, GraphQL::STRING_TYPE, null: true field :status, PipelineStatusEnum, null: false field :duration, - GraphQL::INT_TYPE, - null: true, - description: "Duration of the pipeline in seconds" + GraphQL::INT_TYPE, + null: true, + description: "Duration of the pipeline in seconds" field :coverage, - GraphQL::FLOAT_TYPE, - null: true, - description: "Coverage percentage" + GraphQL::FLOAT_TYPE, + null: true, + description: "Coverage percentage" field :created_at, Types::TimeType, null: false field :updated_at, Types::TimeType, null: false field :started_at, Types::TimeType, null: true diff --git a/app/graphql/types/issuable_state_enum.rb b/app/graphql/types/issuable_state_enum.rb index f2f6d6c6cab..f460a41e83b 100644 --- a/app/graphql/types/issuable_state_enum.rb +++ b/app/graphql/types/issuable_state_enum.rb @@ -2,11 +2,11 @@ module Types class IssuableStateEnum < BaseEnum - graphql_name 'IssuableState' - description 'State of a GitLab issue or merge request' + graphql_name "IssuableState" + description "State of a GitLab issue or merge request" - value 'opened' - value 'closed' - value 'locked' + value "opened" + value "closed" + value "locked" end end diff --git a/app/graphql/types/issue_state_enum.rb b/app/graphql/types/issue_state_enum.rb index 6521407fc9d..116b2937df3 100644 --- a/app/graphql/types/issue_state_enum.rb +++ b/app/graphql/types/issue_state_enum.rb @@ -2,7 +2,7 @@ module Types class IssueStateEnum < IssuableStateEnum - graphql_name 'IssueState' - description 'State of a GitLab issue' + graphql_name "IssueState" + description "State of a GitLab issue" end end diff --git a/app/graphql/types/issue_type.rb b/app/graphql/types/issue_type.rb index 5ad3ea52930..b336b821dc5 100644 --- a/app/graphql/types/issue_type.rb +++ b/app/graphql/types/issue_type.rb @@ -4,7 +4,7 @@ module Types class IssueType < BaseObject expose_permissions Types::PermissionTypes::Issue - graphql_name 'Issue' + graphql_name "Issue" present_using IssuePresenter @@ -14,23 +14,23 @@ module Types field :state, IssueStateEnum, null: false field :author, Types::UserType, - null: false, - resolve: -> (obj, _args, _ctx) { Gitlab::Graphql::Loaders::BatchModelLoader.new(User, obj.author_id).find }, - authorize: :read_user + null: false, + resolve: ->(obj, _args, _ctx) { Gitlab::Graphql::Loaders::BatchModelLoader.new(User, obj.author_id).find }, + authorize: :read_user field :assignees, Types::UserType.connection_type, null: true field :labels, Types::LabelType.connection_type, null: true field :milestone, Types::MilestoneType, - null: true, - resolve: -> (obj, _args, _ctx) { Gitlab::Graphql::Loaders::BatchModelLoader.new(Milestone, obj.milestone_id).find }, - authorize: :read_milestone + null: true, + resolve: ->(obj, _args, _ctx) { Gitlab::Graphql::Loaders::BatchModelLoader.new(Milestone, obj.milestone_id).find }, + authorize: :read_milestone field :due_date, Types::TimeType, null: true field :confidential, GraphQL::BOOLEAN_TYPE, null: false field :discussion_locked, GraphQL::BOOLEAN_TYPE, - null: false, - resolve: -> (obj, _args, _ctx) { !!obj.discussion_locked } + null: false, + resolve: ->(obj, _args, _ctx) { !!obj.discussion_locked } field :upvotes, GraphQL::INT_TYPE, null: false field :downvotes, GraphQL::INT_TYPE, null: false diff --git a/app/graphql/types/label_type.rb b/app/graphql/types/label_type.rb index ccd466edc1a..9b155bffcfb 100644 --- a/app/graphql/types/label_type.rb +++ b/app/graphql/types/label_type.rb @@ -2,7 +2,7 @@ module Types class LabelType < BaseObject - graphql_name 'Label' + graphql_name "Label" field :description, GraphQL::STRING_TYPE, null: true field :title, GraphQL::STRING_TYPE, null: false diff --git a/app/graphql/types/merge_request_state_enum.rb b/app/graphql/types/merge_request_state_enum.rb index 92f52726ab3..2dee256459e 100644 --- a/app/graphql/types/merge_request_state_enum.rb +++ b/app/graphql/types/merge_request_state_enum.rb @@ -2,9 +2,9 @@ module Types class MergeRequestStateEnum < IssuableStateEnum - graphql_name 'MergeRequestState' - description 'State of a GitLab merge request' + graphql_name "MergeRequestState" + description "State of a GitLab merge request" - value 'merged' + value "merged" end end diff --git a/app/graphql/types/merge_request_type.rb b/app/graphql/types/merge_request_type.rb index 1ed27a14e33..470e041bd62 100644 --- a/app/graphql/types/merge_request_type.rb +++ b/app/graphql/types/merge_request_type.rb @@ -6,7 +6,7 @@ module Types present_using MergeRequestPresenter - graphql_name 'MergeRequest' + graphql_name "MergeRequest" field :id, GraphQL::ID_TYPE, null: false field :iid, GraphQL::ID_TYPE, null: false @@ -50,6 +50,6 @@ module Types field :head_pipeline, Types::Ci::PipelineType, null: true, method: :actual_head_pipeline, authorize: :read_pipeline field :pipelines, Types::Ci::PipelineType.connection_type, - resolver: Resolvers::MergeRequestPipelinesResolver + resolver: Resolvers::MergeRequestPipelinesResolver end end diff --git a/app/graphql/types/milestone_type.rb b/app/graphql/types/milestone_type.rb index af31b572c9a..0478675013f 100644 --- a/app/graphql/types/milestone_type.rb +++ b/app/graphql/types/milestone_type.rb @@ -2,7 +2,7 @@ module Types class MilestoneType < BaseObject - graphql_name 'Milestone' + graphql_name "Milestone" field :description, GraphQL::STRING_TYPE, null: true field :title, GraphQL::STRING_TYPE, null: false diff --git a/app/graphql/types/permission_types/base_permission_type.rb b/app/graphql/types/permission_types/base_permission_type.rb index 26a71e2bfbb..da1afc6808e 100644 --- a/app/graphql/types/permission_types/base_permission_type.rb +++ b/app/graphql/types/permission_types/base_permission_type.rb @@ -13,7 +13,7 @@ module Types def self.ability_field(ability, **kword_args) unless resolving_keywords?(kword_args) - kword_args[:resolve] ||= -> (object, args, context) do + kword_args[:resolve] ||= ->(object, args, context) do can?(context[:current_user], ability, object, args.to_h) end end @@ -26,7 +26,8 @@ module Types name: name, type: GraphQL::BOOLEAN_TYPE, description: "Whether or not a user can perform `#{name}` on this resource", - null: false) + null: false + ) field(**kword_args) end diff --git a/app/graphql/types/permission_types/ci/pipeline.rb b/app/graphql/types/permission_types/ci/pipeline.rb index 73e44a33eba..67449671c6a 100644 --- a/app/graphql/types/permission_types/ci/pipeline.rb +++ b/app/graphql/types/permission_types/ci/pipeline.rb @@ -4,7 +4,7 @@ module Types module PermissionTypes module Ci class Pipeline < BasePermissionType - graphql_name 'PipelinePermissions' + graphql_name "PipelinePermissions" abilities :update_pipeline, :admin_pipeline, :destroy_pipeline end diff --git a/app/graphql/types/permission_types/issue.rb b/app/graphql/types/permission_types/issue.rb index 199540c7d6d..1e6ecc3602c 100644 --- a/app/graphql/types/permission_types/issue.rb +++ b/app/graphql/types/permission_types/issue.rb @@ -3,12 +3,12 @@ module Types module PermissionTypes class Issue < BasePermissionType - description 'Check permissions for the current user on a issue' - graphql_name 'IssuePermissions' + description "Check permissions for the current user on a issue" + graphql_name "IssuePermissions" abilities :read_issue, :admin_issue, - :update_issue, :create_note, - :reopen_issue + :update_issue, :create_note, + :reopen_issue end end end diff --git a/app/graphql/types/permission_types/merge_request.rb b/app/graphql/types/permission_types/merge_request.rb index 13995d3ea8f..6a120b573c3 100644 --- a/app/graphql/types/permission_types/merge_request.rb +++ b/app/graphql/types/permission_types/merge_request.rb @@ -4,11 +4,11 @@ module Types module PermissionTypes class MergeRequest < BasePermissionType present_using MergeRequestPresenter - description 'Check permissions for the current user on a merge request' - graphql_name 'MergeRequestPermissions' + description "Check permissions for the current user on a merge request" + graphql_name "MergeRequestPermissions" abilities :read_merge_request, :admin_merge_request, - :update_merge_request, :create_note + :update_merge_request, :create_note permission_field :push_to_source_branch, method: :can_push_to_source_branch? permission_field :remove_source_branch, method: :can_remove_source_branch? diff --git a/app/graphql/types/permission_types/project.rb b/app/graphql/types/permission_types/project.rb index e9a4ea9157b..93f8a282655 100644 --- a/app/graphql/types/permission_types/project.rb +++ b/app/graphql/types/permission_types/project.rb @@ -3,20 +3,20 @@ module Types module PermissionTypes class Project < BasePermissionType - graphql_name 'ProjectPermissions' + graphql_name "ProjectPermissions" abilities :change_namespace, :change_visibility_level, :rename_project, - :remove_project, :archive_project, :remove_fork_project, - :remove_pages, :read_project, :create_merge_request_in, - :read_wiki, :read_project_member, :create_issue, :upload_file, - :read_cycle_analytics, :download_code, :download_wiki_code, - :fork_project, :create_project_snippet, :read_commit_status, - :request_access, :create_pipeline, :create_pipeline_schedule, - :create_merge_request_from, :create_wiki, :push_code, - :create_deployment, :push_to_delete_protected_branch, - :admin_wiki, :admin_project, :update_pages, - :admin_remote_mirror, :create_label, :update_wiki, :destroy_wiki, - :create_pages, :destroy_pages, :read_pages_content + :remove_project, :archive_project, :remove_fork_project, + :remove_pages, :read_project, :create_merge_request_in, + :read_wiki, :read_project_member, :create_issue, :upload_file, + :read_cycle_analytics, :download_code, :download_wiki_code, + :fork_project, :create_project_snippet, :read_commit_status, + :request_access, :create_pipeline, :create_pipeline_schedule, + :create_merge_request_from, :create_wiki, :push_code, + :create_deployment, :push_to_delete_protected_branch, + :admin_wiki, :admin_project, :update_pages, + :admin_remote_mirror, :create_label, :update_wiki, :destroy_wiki, + :create_pages, :destroy_pages, :read_pages_content end end end diff --git a/app/graphql/types/project_type.rb b/app/graphql/types/project_type.rb index 3ef0cc5020c..5d493137077 100644 --- a/app/graphql/types/project_type.rb +++ b/app/graphql/types/project_type.rb @@ -4,7 +4,7 @@ module Types class ProjectType < BaseObject expose_permissions Types::PermissionTypes::Project - graphql_name 'Project' + graphql_name "Project" field :id, GraphQL::ID_TYPE, null: false @@ -38,23 +38,23 @@ module Types field :lfs_enabled, GraphQL::BOOLEAN_TYPE, null: true field :merge_requests_ff_only_enabled, GraphQL::BOOLEAN_TYPE, null: true - field :avatar_url, GraphQL::STRING_TYPE, null: true, resolve: -> (project, args, ctx) do + field :avatar_url, GraphQL::STRING_TYPE, null: true, resolve: ->(project, args, ctx) do project.avatar_url(only_path: false) end %i[issues merge_requests wiki snippets].each do |feature| - field "#{feature}_enabled", GraphQL::BOOLEAN_TYPE, null: true, resolve: -> (project, args, ctx) do + field "#{feature}_enabled", GraphQL::BOOLEAN_TYPE, null: true, resolve: ->(project, args, ctx) do project.feature_available?(feature, ctx[:current_user]) end end - field :jobs_enabled, GraphQL::BOOLEAN_TYPE, null: true, resolve: -> (project, args, ctx) do + field :jobs_enabled, GraphQL::BOOLEAN_TYPE, null: true, resolve: ->(project, args, ctx) do project.feature_available?(:builds, ctx[:current_user]) end field :public_jobs, GraphQL::BOOLEAN_TYPE, method: :public_builds, null: true - field :open_issues_count, GraphQL::INT_TYPE, null: true, resolve: -> (project, args, ctx) do + field :open_issues_count, GraphQL::INT_TYPE, null: true, resolve: ->(project, args, ctx) do project.open_issues_count if project.feature_available?(:issues, ctx[:current_user]) end @@ -67,30 +67,30 @@ module Types field :printing_merge_request_link_enabled, GraphQL::BOOLEAN_TYPE, null: true field :merge_requests, - Types::MergeRequestType.connection_type, - null: true, - resolver: Resolvers::MergeRequestsResolver, - authorize: :read_merge_request + Types::MergeRequestType.connection_type, + null: true, + resolver: Resolvers::MergeRequestsResolver, + authorize: :read_merge_request field :merge_request, - Types::MergeRequestType, - null: true, - resolver: Resolvers::MergeRequestsResolver.single, - authorize: :read_merge_request + Types::MergeRequestType, + null: true, + resolver: Resolvers::MergeRequestsResolver.single, + authorize: :read_merge_request field :issues, - Types::IssueType.connection_type, - null: true, - resolver: Resolvers::IssuesResolver + Types::IssueType.connection_type, + null: true, + resolver: Resolvers::IssuesResolver field :issue, - Types::IssueType, - null: true, - resolver: Resolvers::IssuesResolver.single + Types::IssueType, + null: true, + resolver: Resolvers::IssuesResolver.single field :pipelines, - Types::Ci::PipelineType.connection_type, - null: false, - resolver: Resolvers::ProjectPipelinesResolver + Types::Ci::PipelineType.connection_type, + null: false, + resolver: Resolvers::ProjectPipelinesResolver end end diff --git a/app/graphql/types/query_type.rb b/app/graphql/types/query_type.rb index 954bcc0a5a3..a8ee4069c3c 100644 --- a/app/graphql/types/query_type.rb +++ b/app/graphql/types/query_type.rb @@ -2,13 +2,13 @@ module Types class QueryType < BaseObject - graphql_name 'Query' + graphql_name "Query" field :project, Types::ProjectType, - null: true, - resolver: Resolvers::ProjectResolver, - description: "Find a project", - authorize: :read_project + null: true, + resolver: Resolvers::ProjectResolver, + description: "Find a project", + authorize: :read_project field :echo, GraphQL::STRING_TYPE, null: false, function: Functions::Echo.new end diff --git a/app/graphql/types/time_type.rb b/app/graphql/types/time_type.rb index f045a50e672..cbe9c95c779 100644 --- a/app/graphql/types/time_type.rb +++ b/app/graphql/types/time_type.rb @@ -2,8 +2,8 @@ module Types class TimeType < BaseScalar - graphql_name 'Time' - description 'Time represented in ISO 8601' + graphql_name "Time" + description "Time represented in ISO 8601" def self.coerce_input(value, ctx) Time.parse(value) diff --git a/app/graphql/types/user_type.rb b/app/graphql/types/user_type.rb index a13e65207df..c01c9ccaee9 100644 --- a/app/graphql/types/user_type.rb +++ b/app/graphql/types/user_type.rb @@ -2,7 +2,7 @@ module Types class UserType < BaseObject - graphql_name 'User' + graphql_name "User" present_using UserPresenter diff --git a/app/helpers/active_sessions_helper.rb b/app/helpers/active_sessions_helper.rb index 84aa1160f12..35e139b7f60 100644 --- a/app/helpers/active_sessions_helper.rb +++ b/app/helpers/active_sessions_helper.rb @@ -8,18 +8,18 @@ module ActiveSessionsHelper def active_session_device_type_icon(active_session) icon_name = case active_session.device_type - when 'smartphone', 'feature phone', 'phablet' - 'mobile' - when 'tablet' - 'tablet' - when 'tv', 'smart display', 'camera', 'portable media player', 'console' - 'media' - when 'car browser' - 'car' + when "smartphone", "feature phone", "phablet" + "mobile" + when "tablet" + "tablet" + when "tv", "smart display", "camera", "portable media player", "console" + "media" + when "car browser" + "car" else - 'monitor-o' + "monitor-o" end - sprite_icon(icon_name, size: 16, css_class: 'prepend-top-2') + sprite_icon(icon_name, size: 16, css_class: "prepend-top-2") end end diff --git a/app/helpers/appearances_helper.rb b/app/helpers/appearances_helper.rb index c0db9910143..a51551ac46d 100644 --- a/app/helpers/appearances_helper.rb +++ b/app/helpers/appearances_helper.rb @@ -9,7 +9,7 @@ module AppearancesHelper def default_brand_title # This resides in a separate method so that EE can easily redefine it. - 'GitLab Community Edition' + "GitLab Community Edition" end def brand_image @@ -30,16 +30,16 @@ module AppearancesHelper def brand_header_logo if current_appearance&.header_logo? - image_tag current_appearance.header_logo_path, class: 'brand-header-logo' + image_tag current_appearance.header_logo_path, class: "brand-header-logo" else - render 'shared/logo.svg' + render "shared/logo.svg" end end # Skip the 'GitLab' type logo when custom brand logo is set def brand_header_logo_type unless current_appearance&.header_logo? - render 'shared/logo_type.svg' + render "shared/logo_type.svg" end end @@ -47,7 +47,7 @@ module AppearancesHelper return unless current_appearance&.show_header? class_names = [] - class_names << 'with-performance-bar' if performance_bar_enabled? + class_names << "with-performance-bar" if performance_bar_enabled? render_message(:header_message, class_names: class_names) end diff --git a/app/helpers/application_helper.rb b/app/helpers/application_helper.rb index ffa5719fefb..a51f9f79fae 100644 --- a/app/helpers/application_helper.rb +++ b/app/helpers/application_helper.rb @@ -1,7 +1,7 @@ # frozen_string_literal: true -require 'digest/md5' -require 'uri' +require "digest/md5" +require "uri" module ApplicationHelper # See https://docs.gitlab.com/ee/development/ee_features.html#code-in-app-views @@ -58,10 +58,10 @@ module ApplicationHelper if project.repo_exists? time_ago_with_tooltip(project.repository.commit.committed_date) else - 'Never' + "Never" end rescue - 'Never' + "Never" end # Define whenever show last push event @@ -69,7 +69,7 @@ module ApplicationHelper # rubocop: disable CodeReuse/ActiveRecord def show_last_push_widget?(event) # Skip if event is not about added or modified non-master branch - return false unless event && event.last_push_to_non_root? && !event.rm_ref? + return false unless event&.last_push_to_non_root? && !event.rm_ref? project = event.project @@ -91,11 +91,11 @@ module ApplicationHelper end def simple_sanitize(str) - sanitize(str, tags: %w(a span)) + sanitize(str, tags: %w[a span]) end def body_data_page - [*controller.controller_path.split('/'), controller.action_name].compact.join(':') + [*controller.controller_path.split("/"), controller.action_name].compact.join(":") end # shortcut for gitlab config @@ -124,32 +124,32 @@ module ApplicationHelper # `html_class` argument is provided. # # Returns an HTML-safe String - def time_ago_with_tooltip(time, placement: 'top', html_class: '', short_format: false) - css_classes = [short_format ? 'js-short-timeago' : 'js-timeago'] + def time_ago_with_tooltip(time, placement: "top", html_class: "", short_format: false) + css_classes = [short_format ? "js-short-timeago" : "js-timeago"] css_classes << html_class unless html_class.blank? element = content_tag :time, l(time, format: "%b %d, %Y"), - class: css_classes.join(' '), + class: css_classes.join(" "), title: l(time.to_time.in_time_zone, format: :timeago_tooltip), datetime: time.to_time.getutc.iso8601, data: { - toggle: 'tooltip', + toggle: "tooltip", placement: placement, - container: 'body' + container: "body", } element end - def edited_time_ago_with_tooltip(object, placement: 'top', html_class: 'time_ago', exclude_author: false) + def edited_time_ago_with_tooltip(object, placement: "top", html_class: "time_ago", exclude_author: false) return unless object.edited? - content_tag :small, class: 'edited-text' do - output = content_tag(:span, 'Edited ') + content_tag :small, class: "edited-text" do + output = content_tag(:span, "Edited ") output << time_ago_with_tooltip(object.last_edited_at, placement: placement, html_class: html_class) if !exclude_author && object.last_edited_by - output << content_tag(:span, ' by ') + output << content_tag(:span, " by ") output << link_to_member(object.project, object.last_edited_by, avatar: false, author_class: nil) end @@ -158,15 +158,15 @@ module ApplicationHelper end def promo_host - 'about.gitlab.com' + "about.gitlab.com" end def promo_url - 'https://' + promo_host + "https://" + promo_host end def support_url - Gitlab::CurrentSettings.current_application_settings.help_page_support_url.presence || promo_url + '/getting-help/' + Gitlab::CurrentSettings.current_application_settings.help_page_support_url.presence || promo_url + "/getting-help/" end def page_filter_path(options = {}) @@ -212,8 +212,8 @@ module ApplicationHelper def page_class class_names = [] - class_names << 'issue-boards-page' if current_controller?(:boards) - class_names << 'with-performance-bar' if performance_bar_enabled? + class_names << "issue-boards-page" if current_controller?(:boards) + class_names << "with-performance-bar" if performance_bar_enabled? class_names << system_message_class class_names end @@ -223,8 +223,8 @@ module ApplicationHelper return class_names unless appearance - class_names << 'with-system-header' if appearance.show_header? - class_names << 'with-system-footer' if appearance.show_footer? + class_names << "with-system-header" if appearance.show_header? + class_names << "with-system-footer" if appearance.show_footer? class_names end @@ -235,16 +235,16 @@ module ApplicationHelper # Example: # %li{ class: active_when(params[:filter] == '1') } def active_when(condition) - 'active' if condition + "active" if condition end def show_callout?(name) - cookies[name] != 'true' + cookies[name] != "true" end def linkedin_url(user) name = user.linkedin - if name =~ %r{\Ahttps?://(www\.)?linkedin\.com/in/} + if %r{\Ahttps?://(www\.)?linkedin\.com/in/}.match?(name) name else "https://www.linkedin.com/in/#{name}" @@ -253,7 +253,7 @@ module ApplicationHelper def twitter_url(user) name = user.twitter - if name =~ %r{\Ahttps?://(www\.)?twitter\.com/} + if %r{\Ahttps?://(www\.)?twitter\.com/}.match?(name) name else "https://twitter.com/#{name}" @@ -272,7 +272,7 @@ module ApplicationHelper def read_only_message return unless Gitlab::Database.read_only? - _('You are on a read-only GitLab instance.') + _("You are on a read-only GitLab instance.") end def client_class_list @@ -281,8 +281,8 @@ module ApplicationHelper def client_js_flags { - "is#{browser.id.to_s.titlecase}": true, - "is#{browser.platform.id.to_s.titlecase}": true + :"is#{browser.id.to_s.titlecase}" => true, + :"is#{browser.platform.id.to_s.titlecase}" => true, } end @@ -296,7 +296,7 @@ module ApplicationHelper labels: labels_project_autocomplete_sources_path(object, type: noteable_type, type_id: params[:id]), milestones: milestones_project_autocomplete_sources_path(object), commands: commands_project_autocomplete_sources_path(object, type: noteable_type, type_id: params[:id]), - snippets: snippets_project_autocomplete_sources_path(object) + snippets: snippets_project_autocomplete_sources_path(object), } end diff --git a/app/helpers/application_settings_helper.rb b/app/helpers/application_settings_helper.rb index e635f608237..4b2fdb69f18 100644 --- a/app/helpers/application_settings_helper.rb +++ b/app/helpers/application_settings_helper.rb @@ -3,11 +3,11 @@ module ApplicationSettingsHelper extend self - delegate :allow_signup?, - :gravatar_enabled?, - :password_authentication_enabled_for_web?, - :akismet_enabled?, - to: :'Gitlab::CurrentSettings.current_application_settings' + delegate :allow_signup?, + :gravatar_enabled?, + :password_authentication_enabled_for_web?, + :akismet_enabled?, + to: :'Gitlab::CurrentSettings.current_application_settings' def user_oauth_applications? Gitlab::CurrentSettings.user_oauth_applications @@ -19,10 +19,10 @@ module ApplicationSettingsHelper def enabled_protocol case Gitlab::CurrentSettings.enabled_git_access_protocol - when 'http' + when "http" Gitlab.config.gitlab.protocol - when 'ssh' - 'ssh' + when "ssh" + "ssh" end end @@ -31,16 +31,16 @@ module ApplicationSettingsHelper end def ssh_enabled? - all_protocols_enabled? || enabled_protocol == 'ssh' + all_protocols_enabled? || enabled_protocol == "ssh" end def http_enabled? - all_protocols_enabled? || Gitlab::CurrentSettings.enabled_git_access_protocol == 'http' + all_protocols_enabled? || Gitlab::CurrentSettings.enabled_git_access_protocol == "http" end def enabled_project_button(project, protocol) case protocol - when 'ssh' + when "ssh" ssh_clone_button(project, append_link: false) else http_clone_button(project, append_link: false) @@ -52,15 +52,15 @@ module ApplicationSettingsHelper def restricted_level_checkboxes(help_block_id, checkbox_name, options = {}) Gitlab::VisibilityLevel.values.map do |level| checked = restricted_visibility_levels(true).include?(level) - css_class = checked ? 'active' : '' + css_class = checked ? "active" : "" tag_name = "application_setting_visibility_level_#{level}" label_tag(tag_name, class: css_class) do check_box_tag(checkbox_name, level, checked, - autocomplete: 'off', - 'aria-describedby' => help_block_id, - 'class' => options[:class], - id: tag_name) + visibility_level_icon(level) + visibility_level_label(level) + :autocomplete => "off", + "aria-describedby" => help_block_id, + "class" => options[:class], + :id => tag_name) + visibility_level_icon(level) + visibility_level_label(level) end end end @@ -70,15 +70,15 @@ module ApplicationSettingsHelper def import_sources_checkboxes(help_block_id, options = {}) Gitlab::ImportSources.options.map do |name, source| checked = Gitlab::CurrentSettings.import_sources.include?(source) - css_class = checked ? 'active' : '' - checkbox_name = 'application_setting[import_sources][]' + css_class = checked ? "active" : "" + checkbox_name = "application_setting[import_sources][]" label_tag(name, class: css_class) do check_box_tag(checkbox_name, source, checked, - autocomplete: 'off', - 'aria-describedby' => help_block_id, - 'class' => options[:class], - id: name.tr(' ', '_')) + name + :autocomplete => "off", + "aria-describedby" => help_block_id, + "class" => options[:class], + :id => name.tr(" ", "_")) + name end end end @@ -86,35 +86,35 @@ module ApplicationSettingsHelper def oauth_providers_checkboxes button_based_providers.map do |source| disabled = Gitlab::CurrentSettings.disabled_oauth_sign_in_sources.include?(source.to_s) - css_class = ['btn'] - css_class << 'active' unless disabled - checkbox_name = 'application_setting[enabled_oauth_sign_in_sources][]' + css_class = ["btn"] + css_class << "active" unless disabled + checkbox_name = "application_setting[enabled_oauth_sign_in_sources][]" name = Gitlab::Auth::OAuth::Provider.label_for(source) - label_tag(checkbox_name, class: css_class.join(' ')) do + label_tag(checkbox_name, class: css_class.join(" ")) do check_box_tag(checkbox_name, source, !disabled, - autocomplete: 'off', - id: name.tr(' ', '_')) + name + autocomplete: "off", + id: name.tr(" ", "_")) + name end end end def key_restriction_options_for_select(type) - bit_size_options = Gitlab::SSHPublicKey.supported_sizes(type).map do |bits| + bit_size_options = Gitlab::SSHPublicKey.supported_sizes(type).map { |bits| ["Must be at least #{bits} bits", bits] - end + } [ - ['Are allowed', 0], + ["Are allowed", 0], *bit_size_options, - ['Are forbidden', ApplicationSetting::FORBIDDEN_KEY_VALUE] + ["Are forbidden", ApplicationSetting::FORBIDDEN_KEY_VALUE], ] end def repository_storages_options_for_select(selected) - options = Gitlab.config.repositories.storages.map do |name, storage| - ["#{name} - #{storage['gitaly_address']}", name] - end + options = Gitlab.config.repositories.storages.map { |name, storage| + ["#{name} - #{storage["gitaly_address"]}", name] + } options_for_select(options, selected) end @@ -233,7 +233,7 @@ module ApplicationSettingsHelper :diff_max_patch_bytes, :commit_email_hostname, :protected_ci_variables, - :local_markdown_version + :local_markdown_version, ] end diff --git a/app/helpers/auth_helper.rb b/app/helpers/auth_helper.rb index 2b1d6f49878..410c6041c7a 100644 --- a/app/helpers/auth_helper.rb +++ b/app/helpers/auth_helper.rb @@ -1,7 +1,7 @@ # frozen_string_literal: true module AuthHelper - PROVIDERS_WITH_ICONS = %w(twitter github gitlab bitbucket google_oauth2 facebook azure_oauth2 authentiq).freeze + PROVIDERS_WITH_ICONS = %w[twitter github gitlab bitbucket google_oauth2 facebook azure_oauth2 authentiq].freeze LDAP_PROVIDER = /\Aldap/ def ldap_enabled? @@ -18,8 +18,8 @@ module AuthHelper def qa_class_for_provider(provider) { - saml: 'qa-saml-login-button', - github: 'qa-github-login-button' + saml: "qa-saml-login-button", + github: "qa-github-login-button", }[provider.to_sym] end @@ -32,7 +32,7 @@ module AuthHelper end def form_based_provider_priority - ['crowd', /^ldap/, 'kerberos'] + ["crowd", /^ldap/, "kerberos"] end def form_based_provider_with_highest_priority @@ -49,7 +49,7 @@ module AuthHelper end def form_based_provider?(name) - [LDAP_PROVIDER, 'crowd'].any? { |pattern| pattern === name.to_s } + [LDAP_PROVIDER, "crowd"].any? { |pattern| pattern === name.to_s } end def form_based_providers @@ -86,7 +86,7 @@ module AuthHelper label = label_for_provider(provider) if provider_has_icon?(provider) - file_name = "#{provider.to_s.split('_').first}_#{size}.png" + file_name = "#{provider.to_s.split("_").first}_#{size}.png" image_tag("auth_buttons/#{file_name}", alt: label, title: "Sign in with #{label}") else @@ -101,7 +101,7 @@ module AuthHelper # rubocop: enable CodeReuse/ActiveRecord def unlink_allowed?(provider) - %w(saml cas3).exclude?(provider.to_s) + %w[saml cas3].exclude?(provider.to_s) end extend self diff --git a/app/helpers/auto_devops_helper.rb b/app/helpers/auto_devops_helper.rb index 67e7e475920..e792bf4bbb4 100644 --- a/app/helpers/auto_devops_helper.rb +++ b/app/helpers/auto_devops_helper.rb @@ -3,7 +3,7 @@ module AutoDevopsHelper def show_auto_devops_callout?(project) Feature.get(:auto_devops_banner_disabled).off? && - show_callout?('auto_devops_settings_dismissed') && + show_callout?("auto_devops_settings_dismissed") && can?(current_user, :admin_pipeline, project) && project.has_auto_devops_implicitly_disabled? && !project.repository.gitlab_ci_yml && diff --git a/app/helpers/avatars_helper.rb b/app/helpers/avatars_helper.rb index 5906ddabee4..bf099890f6e 100644 --- a/app/helpers/avatars_helper.rb +++ b/app/helpers/avatars_helper.rb @@ -38,13 +38,13 @@ module AvatarsHelper end end - def gravatar_icon(user_email = '', size = nil, scale = 2) + def gravatar_icon(user_email = "", size = nil, scale = 2) GravatarService.new.execute(user_email, size, scale) || default_avatar end def default_avatar - ActionController::Base.helpers.image_path('no_avatar.png') + ActionController::Base.helpers.image_path("no_avatar.png") end def author_avatar(commit_or_event, options = {}) @@ -52,7 +52,7 @@ module AvatarsHelper user: commit_or_event.author, user_name: commit_or_event.author_name, user_email: commit_or_event.author_email, - css_class: 'd-none d-sm-inline' + css_class: "d-none d-sm-inline", })) end @@ -77,22 +77,22 @@ module AvatarsHelper css_class = %W[avatar s#{avatar_size}].push(*options[:css_class]) if has_tooltip - css_class.push('has-tooltip') - data_attributes[:container] = 'body' + css_class.push("has-tooltip") + data_attributes[:container] = "body" end if options[:lazy] - css_class << 'lazy' + css_class << "lazy" data_attributes[:src] = avatar_url avatar_url = LazyImageTagHelper.placeholder_image end image_options = { - alt: "#{user_name}'s avatar", - src: avatar_url, - data: data_attributes, + alt: "#{user_name}'s avatar", + src: avatar_url, + data: data_attributes, class: css_class, - title: user_name + title: user_name, } tag(:img, image_options) @@ -124,7 +124,7 @@ module AvatarsHelper bg_key = (source.id % 7) + 1 options[:class] = - [*options[:class], "identicon bg#{bg_key}"].join(' ') + [*options[:class], "identicon bg#{bg_key}"].join(" ") content_tag(:div, class: options[:class].strip) do source.name[0, 1].upcase diff --git a/app/helpers/blame_helper.rb b/app/helpers/blame_helper.rb index 82c74e2416d..ace4bf539b1 100644 --- a/app/helpers/blame_helper.rb +++ b/app/helpers/blame_helper.rb @@ -8,7 +8,7 @@ module BlameHelper { now: now, - started_days_ago: (now - start_date).to_i / 1.day + started_days_ago: (now - start_date).to_i / 1.day, } end diff --git a/app/helpers/blob_helper.rb b/app/helpers/blob_helper.rb index 3e1bb9af5cc..62da4a47afd 100644 --- a/app/helpers/blob_helper.rb +++ b/app/helpers/blob_helper.rb @@ -8,18 +8,18 @@ module BlobHelper end def no_highlight_files - %w(credits changelog news copying copyright license authors) + %w[credits changelog news copying copyright license authors] end def edit_blob_path(project = @project, ref = @ref, path = @path, options = {}) project_edit_blob_path(project, - tree_join(ref, path), - options[:link_opts]) + tree_join(ref, path), + options[:link_opts]) end def ide_edit_path(project = @project, ref = @ref, path = @path, options = {}) - segments = [ide_path, 'project', project.full_path, 'edit', ref] - segments.concat(['-', path]) if path.present? + segments = [ide_path, "project", project.full_path, "edit", ref] + segments.concat(["-", path]) if path.present? File.join(segments) end @@ -29,11 +29,11 @@ module BlobHelper common_classes = "btn js-edit-blob #{options[:extra_class]}" edit_button_tag(blob, - common_classes, - _('Edit'), - Feature.enabled?(:web_ide_default) ? ide_edit_path(project, ref, path, options) : edit_blob_path(project, ref, path, options), - project, - ref) + common_classes, + _("Edit"), + Feature.enabled?(:web_ide_default) ? ide_edit_path(project, ref, path, options) : edit_blob_path(project, ref, path, options), + project, + ref) end def ide_edit_button(project = @project, ref = @ref, path = @path, options = {}) @@ -41,28 +41,32 @@ module BlobHelper return unless blob = readable_blob(options, path, project, ref) edit_button_tag(blob, - 'btn btn-default', - _('Web IDE'), - ide_edit_path(project, ref, path, options), - project, - ref) + "btn btn-default", + _("Web IDE"), + ide_edit_path(project, ref, path, options), + project, + ref) end def modify_file_button(project = @project, ref = @ref, path = @path, label:, action:, btn_class:, modal_type:) return unless current_user - blob = project.repository.blob_at(ref, path) rescue nil + blob = begin + project.repository.blob_at(ref, path) + rescue + nil + end return unless blob common_classes = "btn btn-#{btn_class}" if !on_top_of_branch?(project, ref) - button_tag label, class: "#{common_classes} disabled has-tooltip", title: "You can only #{action} files when you are on a branch", data: { container: 'body' } + button_tag label, class: "#{common_classes} disabled has-tooltip", title: "You can only #{action} files when you are on a branch", data: {container: "body"} elsif blob.stored_externally? - button_tag label, class: "#{common_classes} disabled has-tooltip", title: "It is not possible to #{action} files that are stored in LFS using the web interface", data: { container: 'body' } + button_tag label, class: "#{common_classes} disabled has-tooltip", title: "It is not possible to #{action} files that are stored in LFS using the web interface", data: {container: "body"} elsif can_modify_blob?(blob, project, ref) - button_tag label, class: "#{common_classes}", 'data-target' => "#modal-#{modal_type}-blob", 'data-toggle' => 'modal' + button_tag label, :class => common_classes.to_s, "data-target" => "#modal-#{modal_type}-blob", "data-toggle" => "modal" elsif can?(current_user, :fork_project, project) && can?(current_user, :create_merge_request_in, project) edit_fork_button_tag(common_classes, project, label, edit_modify_file_fork_params(action), action) end @@ -73,9 +77,9 @@ module BlobHelper project, ref, path, - label: "Replace", - action: "replace", - btn_class: "default", + label: "Replace", + action: "replace", + btn_class: "default", modal_type: "upload" ) end @@ -85,9 +89,9 @@ module BlobHelper project, ref, path, - label: "Delete", - action: "delete", - btn_class: "remove", + label: "Delete", + action: "delete", + btn_class: "remove", modal_type: "remove" ) end @@ -102,9 +106,9 @@ module BlobHelper def editing_preview_title(filename) if Gitlab::MarkupHelper.previewable?(filename) - 'Preview' + "Preview" else - 'Preview changes' + "Preview changes" end end @@ -113,7 +117,7 @@ module BlobHelper # mode - File unix mode # mode - File name def blob_icon(mode, name) - icon("#{file_type_icon_class('file', mode, name)} fw") + icon("#{file_type_icon_class("file", mode, name)} fw") end def blob_raw_url(**kwargs) @@ -150,9 +154,9 @@ module BlobHelper categories = grouped.keys categories.each_with_object({}) do |category, hash| - hash[category] = grouped[category].map do |item| - { name: item.name, id: item.key } - end + hash[category] = grouped[category].map { |item| + {name: item.name, id: item.key} + } end end private :template_dropdown_names @@ -175,16 +179,16 @@ module BlobHelper def blob_editor_paths(project) { - 'relative-url-root' => Rails.application.config.relative_url_root, - 'assets-prefix' => Gitlab::Application.config.assets.prefix, - 'blob-filename' => @blob && @blob.path, - 'project-id' => project.id, - 'is-markdown' => @blob && @blob.path && Gitlab::MarkupHelper.gitlab_markdown?(@blob.path) + "relative-url-root" => Rails.application.config.relative_url_root, + "assets-prefix" => Gitlab::Application.config.assets.prefix, + "blob-filename" => @blob&.path, + "project-id" => project.id, + "is-markdown" => @blob&.path && Gitlab::MarkupHelper.gitlab_markdown?(@blob.path), } end def copy_file_path_button(file_path) - clipboard_button(text: file_path, gfm: "`#{file_path}`", class: 'btn-clipboard btn-transparent prepend-left-5', title: 'Copy file path to clipboard') + clipboard_button(text: file_path, gfm: "`#{file_path}`", class: "btn-clipboard btn-transparent prepend-left-5", title: "Copy file path to clipboard") end def copy_blob_source_button(blob) @@ -197,15 +201,15 @@ module BlobHelper return if blob.empty? return if blob.binary? || blob.stored_externally? - title = 'Open raw' - link_to icon('file-code-o'), blob_raw_path, class: 'btn btn-sm has-tooltip', target: '_blank', rel: 'noopener noreferrer', title: title, data: { container: 'body' } + title = "Open raw" + link_to icon("file-code-o"), blob_raw_path, class: "btn btn-sm has-tooltip", target: "_blank", rel: "noopener noreferrer", title: title, data: {container: "body"} end def download_blob_button(blob) return if blob.empty? - title = 'Download' - link_to sprite_icon('download'), blob_raw_path(inline: false), download: @path, class: 'btn btn-sm has-tooltip', target: '_blank', rel: 'noopener noreferrer', title: title, data: { container: 'body' } + title = "Download" + link_to sprite_icon("download"), blob_raw_path(inline: false), download: @path, class: "btn btn-sm has-tooltip", target: "_blank", rel: "noopener noreferrer", title: title, data: {container: "body"} end def blob_render_error_reason(viewer) @@ -217,11 +221,11 @@ module BlobHelper when :server_side_but_stored_externally case viewer.blob.external_storage when :lfs - 'it is stored in LFS' + "it is stored in LFS" when :build_artifact - 'it is stored as a job artifact' + "it is stored as a job artifact" else - 'it is stored externally' + "it is stored externally" end end end @@ -231,16 +235,16 @@ module BlobHelper options = [] if error == :collapsed - options << link_to('load it anyway', url_for(safe_params.merge(viewer: viewer.type, expanded: true, format: nil))) + options << link_to("load it anyway", url_for(safe_params.merge(viewer: viewer.type, expanded: true, format: nil))) end # If the error is `:server_side_but_stored_externally`, the simple viewer will show the same error, # so don't bother switching. if viewer.rich? && viewer.blob.rendered_as_text? && error != :server_side_but_stored_externally - options << link_to('view the source', '#', class: 'js-blob-viewer-switch-btn', data: { viewer: 'simple' }) + options << link_to("view the source", "#", class: "js-blob-viewer-switch-btn", data: {viewer: "simple"}) end - options << link_to('download it', blob_raw_path, target: '_blank', rel: 'noopener noreferrer') + options << link_to("download it", blob_raw_path, target: "_blank", rel: "noopener noreferrer") options end @@ -262,7 +266,11 @@ module BlobHelper def readable_blob(options, path, project, ref) blob = options.delete(:blob) - blob ||= project.repository.blob_at(ref, path) rescue nil + blob ||= begin + project.repository.blob_at(ref, path) + rescue + nil + end blob if blob&.readable_text? end @@ -271,7 +279,7 @@ module BlobHelper { to: path, notice: edit_in_new_fork_notice, - notice_now: edit_in_new_fork_notice_now + notice_now: edit_in_new_fork_notice_now, } end @@ -279,20 +287,20 @@ module BlobHelper { to: request.fullpath, notice: edit_in_new_fork_notice_action(action), - notice_now: edit_in_new_fork_notice_now + notice_now: edit_in_new_fork_notice_now, } end - def edit_fork_button_tag(common_classes, project, label, params, action = 'edit') + def edit_fork_button_tag(common_classes, project, label, params, action = "edit") fork_path = project_forks_path(project, namespace_key: current_user.namespace.id, continue: params) button_tag label, - class: "#{common_classes} js-edit-blob-link-fork-toggler", - data: { action: action, fork_path: fork_path } + class: "#{common_classes} js-edit-blob-link-fork-toggler", + data: {action: action, fork_path: fork_path} end def edit_disabled_button_tag(button_text, common_classes) - button_tag(button_text, class: "#{common_classes} disabled has-tooltip", title: _('You can only edit files when you are on a branch'), data: { container: 'body' }) + button_tag(button_text, class: "#{common_classes} disabled has-tooltip", title: _("You can only edit files when you are on a branch"), data: {container: "body"}) end def edit_link_tag(link_text, edit_path, common_classes) diff --git a/app/helpers/boards_helper.rb b/app/helpers/boards_helper.rb index be1e7016a1e..d869897db07 100644 --- a/app/helpers/boards_helper.rb +++ b/app/helpers/boards_helper.rb @@ -10,11 +10,11 @@ module BoardsHelper boards_endpoint: @boards_endpoint, lists_endpoint: board_lists_path(board), board_id: board.id, - disabled: "#{!can?(current_user, :admin_list, current_board_parent)}", + disabled: (!can?(current_user, :admin_list, current_board_parent)).to_s, issue_link_base: build_issue_link_base, root_path: root_path, bulk_update_path: @bulk_issues_path, - default_avatar: image_path(default_avatar) + default_avatar: image_path(default_avatar), } end @@ -40,10 +40,10 @@ module BoardsHelper def current_board_path(board) @current_board_path ||= if board.group_board? - group_board_path(current_board_parent, board) - else - project_board_path(current_board_parent, board) - end + group_board_path(current_board_parent, board) + else + project_board_path(current_board_parent, board) + end end def current_board_parent @@ -64,7 +64,7 @@ module BoardsHelper labels_endpoint: @labels_endpoint, namespace_path: @namespace_path, project_path: @project&.path, - group_path: @group&.path + group_path: @group&.path, } end @@ -72,16 +72,16 @@ module BoardsHelper dropdown_options = issue_assignees_dropdown_options { - toggle: 'dropdown', - field_name: 'issue[assignee_ids][]', + toggle: "dropdown", + field_name: "issue[assignee_ids][]", first_user: current_user&.username, - current_user: 'true', + current_user: "true", project_id: @project&.id, group_id: @group&.id, - null_user: 'true', - multi_select: 'true', + null_user: "true", + multi_select: "true", 'dropdown-header': dropdown_options[:data][:'dropdown-header'], - 'max-select': dropdown_options[:data][:'max-select'] + 'max-select': dropdown_options[:data][:'max-select'], } end diff --git a/app/helpers/breadcrumbs_helper.rb b/app/helpers/breadcrumbs_helper.rb index b067376cea0..377d5099ec0 100644 --- a/app/helpers/breadcrumbs_helper.rb +++ b/app/helpers/breadcrumbs_helper.rb @@ -5,7 +5,7 @@ module BreadcrumbsHelper @breadcrumbs_extra_links ||= [] @breadcrumbs_extra_links.push({ text: text, - link: link + link: link, }) end diff --git a/app/helpers/broadcast_messages_helper.rb b/app/helpers/broadcast_messages_helper.rb index 289cb44f1e8..394d5d54cba 100644 --- a/app/helpers/broadcast_messages_helper.rb +++ b/app/helpers/broadcast_messages_helper.rb @@ -4,8 +4,8 @@ module BroadcastMessagesHelper def broadcast_message(message) return unless message.present? - content_tag :div, class: 'broadcast-message', style: broadcast_message_style(message) do - icon('bullhorn') << ' ' << render_broadcast_message(message) + content_tag :div, class: "broadcast-message", style: broadcast_message_style(message) do + icon("bullhorn") << " " << render_broadcast_message(message) end end @@ -20,16 +20,16 @@ module BroadcastMessagesHelper style << "color: #{broadcast_message.font}" end - style.join('; ') + style.join("; ") end def broadcast_message_status(broadcast_message) if broadcast_message.active? - 'Active' + "Active" elsif broadcast_message.ended? - 'Expired' + "Expired" else - 'Pending' + "Pending" end end diff --git a/app/helpers/builds_helper.rb b/app/helpers/builds_helper.rb index 3c8caec3fe5..c1df49473b2 100644 --- a/app/helpers/builds_helper.rb +++ b/app/helpers/builds_helper.rb @@ -15,9 +15,9 @@ module BuildsHelper def sidebar_build_class(build, current_build) build_class = [] - build_class << 'active' if build.id === current_build.id - build_class << 'retried' if build.retried? - build_class.join(' ') + build_class << "active" if build.id === current_build.id + build_class << "retried" if build.retried? + build_class.join(" ") end def javascript_build_options @@ -25,14 +25,14 @@ module BuildsHelper page_path: project_job_path(@project, @build), build_status: @build.status, build_stage: @build.stage, - log_state: '' + log_state: "", } end def build_failed_issue_options { title: "Job Failed ##{@build.id}", - description: project_job_url(@project, @build) + description: project_job_url(@project, @build), } end end diff --git a/app/helpers/button_helper.rb b/app/helpers/button_helper.rb index 494c754e7d5..b13bbbf518b 100644 --- a/app/helpers/button_helper.rb +++ b/app/helpers/button_helper.rb @@ -20,9 +20,9 @@ module ButtonHelper # # See http://clipboardjs.com/#usage def clipboard_button(data = {}) - css_class = data[:class] || 'btn-clipboard btn-transparent' - title = data[:title] || 'Copy to clipboard' - button_text = data[:button_text] || '' + css_class = data[:class] || "btn-clipboard btn-transparent" + title = data[:title] || "Copy to clipboard" + button_text = data[:button_text] || "" hide_tooltip = data[:hide_tooltip] || false hide_button_icon = data[:hide_button_icon] || false @@ -31,7 +31,7 @@ module ButtonHelper if text = data.delete(:text) data[:clipboard_text] = if gfm = data.delete(:gfm) - { text: text, gfm: gfm } + {text: text, gfm: gfm} else text end @@ -41,7 +41,7 @@ module ButtonHelper data[:clipboard_target] = target if target unless hide_tooltip - data = { toggle: 'tooltip', placement: 'bottom', container: 'body' }.merge(data) + data = {toggle: "tooltip", placement: "bottom", container: "body"}.merge(data) end button_attributes = { @@ -49,11 +49,11 @@ module ButtonHelper data: data, type: :button, title: title, - aria: { label: title } + aria: {label: title}, } content_tag :button, button_attributes do - concat(sprite_icon('duplicate')) unless hide_button_icon + concat(sprite_icon("duplicate")) unless hide_button_icon concat(button_text) end end @@ -63,14 +63,14 @@ module ButtonHelper dropdown_description = http_dropdown_description(protocol) append_url = project.http_url_to_repo if append_link - dropdown_item_with_description(protocol, dropdown_description, href: append_url, data: { clone_type: 'http' }) + dropdown_item_with_description(protocol, dropdown_description, href: append_url, data: {clone_type: "http"}) end def http_dropdown_description(protocol) if current_user.try(:require_password_creation_for_git?) - _("Set a password on your account to pull or push via %{protocol}.") % { protocol: protocol } + _("Set a password on your account to pull or push via %{protocol}.") % {protocol: protocol} elsif current_user.try(:require_personal_access_token_creation_for_git_auth?) - _("Create a personal access token on your account to pull or push via %{protocol}.") % { protocol: protocol } + _("Create a personal access token on your account to pull or push via %{protocol}.") % {protocol: protocol} end end @@ -82,18 +82,18 @@ module ButtonHelper append_url = project.ssh_url_to_repo if append_link - dropdown_item_with_description('SSH', dropdown_description, href: append_url, data: { clone_type: 'ssh' }) + dropdown_item_with_description("SSH", dropdown_description, href: append_url, data: {clone_type: "ssh"}) end def dropdown_item_with_description(title, description, href: nil, data: nil, default: false) active_class = "is-active" if default - button_content = content_tag(:strong, title, class: 'dropdown-menu-inner-title') - button_content << content_tag(:span, description, class: 'dropdown-menu-inner-content') if description + button_content = content_tag(:strong, title, class: "dropdown-menu-inner-title") + button_content << content_tag(:span, description, class: "dropdown-menu-inner-content") if description content_tag (href ? :a : :span), (href ? button_content : title), class: "#{title.downcase}-selector #{active_class}", - href: (href if href), - data: (data if data) + href: href, + data: data end end diff --git a/app/helpers/calendar_helper.rb b/app/helpers/calendar_helper.rb index ad4116fc3da..c36d74ff80a 100644 --- a/app/helpers/calendar_helper.rb +++ b/app/helpers/calendar_helper.rb @@ -2,9 +2,9 @@ module CalendarHelper def calendar_url_options - { format: :ics, - feed_token: current_user.try(:feed_token), - due_date: Issue::DueNextMonthAndPreviousTwoWeeks.name, - sort: 'closest_future_date' } + {format: :ics, + feed_token: current_user.try(:feed_token), + due_date: Issue::DueNextMonthAndPreviousTwoWeeks.name, + sort: "closest_future_date",} end end diff --git a/app/helpers/ci_status_helper.rb b/app/helpers/ci_status_helper.rb index 923a06a0512..9accced1237 100644 --- a/app/helpers/ci_status_helper.rb +++ b/app/helpers/ci_status_helper.rb @@ -14,17 +14,17 @@ module CiStatusHelper end label = case status - when 'success' - 'passed' - when 'success_with_warnings' - 'passed with warnings' - when 'manual' - 'waiting for manual action' - when 'scheduled' - 'waiting for delayed job' + when "success" + "passed" + when "success_with_warnings" + "passed with warnings" + when "manual" + "waiting for manual action" + when "scheduled" + "waiting for delayed job" else status - end + end translation = "CiStatusLabel|#{label}" s_(translation) end @@ -35,14 +35,14 @@ module CiStatusHelper end case status - when 'success' - s_('CiStatusText|passed') - when 'success_with_warnings' - s_('CiStatusText|passed') - when 'manual' - s_('CiStatusText|blocked') - when 'scheduled' - s_('CiStatusText|delayed') + when "success" + s_("CiStatusText|passed") + when "success_with_warnings" + s_("CiStatusText|passed") + when "manual" + s_("CiStatusText|blocked") + when "scheduled" + s_("CiStatusText|delayed") else # All states are already being translated inside the detailed statuses: # :running => Gitlab::Ci::Status::Running @@ -58,7 +58,7 @@ module CiStatusHelper end def ci_status_for_statuseable(subject) - status = subject.try(:status) || 'not found' + status = subject.try(:status) || "not found" status.humanize end @@ -69,28 +69,28 @@ module CiStatusHelper icon_name = case status - when 'success' - 'status_success' - when 'success_with_warnings' - 'status_warning' - when 'failed' - 'status_failed' - when 'pending' - 'status_pending' - when 'running' - 'status_running' - when 'play' - 'play' - when 'created' - 'status_created' - when 'skipped' - 'status_skipped' - when 'manual' - 'status_manual' - when 'scheduled' - 'status_scheduled' + when "success" + "status_success" + when "success_with_warnings" + "status_warning" + when "failed" + "status_failed" + when "pending" + "status_pending" + when "running" + "status_running" + when "play" + "play" + when "created" + "status_created" + when "skipped" + "status_skipped" + when "manual" + "status_manual" + when "scheduled" + "status_scheduled" else - 'status_canceled' + "status_canceled" end sprite_icon(icon_name, size: size) @@ -100,46 +100,48 @@ module CiStatusHelper "pipeline-status/#{pipeline_status.sha}-#{pipeline_status.status}" end - def render_project_pipeline_status(pipeline_status, tooltip_placement: 'left') + def render_project_pipeline_status(pipeline_status, tooltip_placement: "left") project = pipeline_status.project path = pipelines_project_commit_path(project, pipeline_status.sha, ref: pipeline_status.ref) render_status_with_link( - 'commit', + "commit", pipeline_status.status, path, - tooltip_placement: tooltip_placement) + tooltip_placement: tooltip_placement + ) end - def render_commit_status(commit, ref: nil, tooltip_placement: 'left') + def render_commit_status(commit, ref: nil, tooltip_placement: "left") project = commit.project path = pipelines_project_commit_path(project, commit, ref: ref) render_status_with_link( - 'commit', + "commit", commit.status(ref), path, tooltip_placement: tooltip_placement, - icon_size: 24) + icon_size: 24 + ) end - def render_pipeline_status(pipeline, tooltip_placement: 'left') + def render_pipeline_status(pipeline, tooltip_placement: "left") project = pipeline.project path = project_pipeline_path(project, pipeline) - render_status_with_link('pipeline', pipeline.status, path, tooltip_placement: tooltip_placement) + render_status_with_link("pipeline", pipeline.status, path, tooltip_placement: tooltip_placement) end - def render_status_with_link(type, status, path = nil, tooltip_placement: 'left', cssclass: '', container: 'body', icon_size: 16) + def render_status_with_link(type, status, path = nil, tooltip_placement: "left", cssclass: "", container: "body", icon_size: 16) klass = "ci-status-link ci-status-icon-#{status.dasherize} #{cssclass}" title = "#{type.titleize}: #{ci_label_for_status(status)}" - data = { toggle: 'tooltip', placement: tooltip_placement, container: container } + data = {toggle: "tooltip", placement: tooltip_placement, container: container} if path link_to ci_icon_for_status(status, size: icon_size), path, - class: klass, title: title, data: data + class: klass, title: title, data: data else content_tag :span, ci_icon_for_status(status, size: icon_size), - class: klass, title: title, data: data + class: klass, title: title, data: data end end diff --git a/app/helpers/clusters_helper.rb b/app/helpers/clusters_helper.rb index 916dcb1a308..e7e3093cee3 100644 --- a/app/helpers/clusters_helper.rb +++ b/app/helpers/clusters_helper.rb @@ -10,8 +10,8 @@ module ClustersHelper return if Gitlab::CurrentSettings.current_application_settings.hide_third_party_offers? return unless show_gcp_signup_offer? - content_tag :section, class: 'no-animate expanded' do - render 'clusters/clusters/gcp_signup_offer_banner' + content_tag :section, class: "no-animate expanded" do + render "clusters/clusters/gcp_signup_offer_banner" end end end diff --git a/app/helpers/commits_helper.rb b/app/helpers/commits_helper.rb index d58f634425b..f1e4531c21d 100644 --- a/app/helpers/commits_helper.rb +++ b/app/helpers/commits_helper.rb @@ -18,7 +18,7 @@ module CommitsHelper end def commit_to_html(commit, ref, project) - render 'projects/commits/commit', + render "projects/commits/commit", commit: commit, ref: ref, project: project @@ -29,27 +29,27 @@ module CommitsHelper return unless @project && @ref # Add the root project link and the arrow icon - crumbs = content_tag(:li, class: 'breadcrumb-item') do + crumbs = content_tag(:li, class: "breadcrumb-item") { link_to( @project.path, project_commits_path(@project, @ref) ) - end + } if @path - parts = @path.split('/') + parts = @path.split("/") parts.each_with_index do |part, i| - crumbs << content_tag(:li, class: 'breadcrumb-item') do + crumbs << content_tag(:li, class: "breadcrumb-item") { # The text is just the individual part, but the link needs all the parts before it link_to( part, project_commits_path( @project, - tree_join(@ref, parts[0..i].join('/')) + tree_join(@ref, parts[0..i].join("/")) ) ) - end + } end end @@ -64,31 +64,31 @@ module CommitsHelper # Returns a link formatted as a commit branch link def commit_branch_link(url, text) - link_to(url, class: 'badge badge-gray ref-name branch-link') do - sprite_icon('branch', size: 12, css_class: 'fork-svg') + "#{text}" + link_to(url, class: "badge badge-gray ref-name branch-link") do + sprite_icon("branch", size: 12, css_class: "fork-svg") + text.to_s end end # Returns the sorted alphabetically links to branches, separated by a comma def commit_branches_links(project, branches) - branches.sort.map do |branch| + branches.sort.map { |branch| commit_branch_link(project_ref_path(project, branch), branch) - end.join(' ').html_safe + }.join(" ").html_safe end # Returns a link formatted as a commit tag link def commit_tag_link(url, text) - link_to(url, class: 'badge badge-gray ref-name') do - sprite_icon('tag', size: 12, css_class: 'append-right-5 vertical-align-middle') + "#{text}" + link_to(url, class: "badge badge-gray ref-name") do + sprite_icon("tag", size: 12, css_class: "append-right-5 vertical-align-middle") + text.to_s end end # Returns the sorted links to tags, separated by a comma def commit_tags_links(project, tags) sorted = VersionSorter.rsort(tags) - sorted.map do |tag| + sorted.map { |tag| commit_tag_link(project_ref_path(project, tag), tag) - end.join(' ').html_safe + }.join(" ").html_safe end def link_to_browse_code(project, commit) @@ -105,21 +105,21 @@ module CommitsHelper tooltip = _("Browse Directory") end - link_to url, class: "btn btn-default has-tooltip", title: tooltip, data: { container: "body" } do - sprite_icon('folder-open') + link_to url, class: "btn btn-default has-tooltip", title: tooltip, data: {container: "body"} do + sprite_icon("folder-open") end end def revert_commit_link(commit, continue_to_path, btn_class: nil, has_tooltip: true) - commit_action_link('revert', commit, continue_to_path, btn_class: btn_class, has_tooltip: has_tooltip) + commit_action_link("revert", commit, continue_to_path, btn_class: btn_class, has_tooltip: has_tooltip) end def cherry_pick_commit_link(commit, continue_to_path, btn_class: nil, has_tooltip: true) - commit_action_link('cherry-pick', commit, continue_to_path, btn_class: btn_class, has_tooltip: has_tooltip) + commit_action_link("cherry-pick", commit, continue_to_path, btn_class: btn_class, has_tooltip: has_tooltip) end def commit_signature_badge_classes(additional_classes) - %w(btn gpg-status-box) + Array(additional_classes) + %w[btn gpg-status-box] + Array(additional_classes) end protected @@ -148,13 +148,13 @@ module CommitsHelper end link_options = { - class: "commit-#{options[:source]}-link" + class: "commit-#{options[:source]}-link", } if user.nil? mail_to(source_email, text, link_options) else - link_to(text, user_path(user), { class: "commit-#{options[:source]}-link js-user-link", data: { user_id: user.id } }) + link_to(text, user_path(user), {class: "commit-#{options[:source]}-link js-user-link", data: {user_id: user.id}}) end end @@ -165,31 +165,31 @@ module CommitsHelper btn_class = "btn btn-#{btn_class}" unless btn_class.nil? if can_collaborate_with_project?(@project) - link_to action.capitalize, "#modal-#{action}-commit", 'data-toggle' => 'modal', 'data-container' => 'body', title: (tooltip if has_tooltip), class: "#{btn_class} #{'has-tooltip' if has_tooltip}" + link_to action.capitalize, "#modal-#{action}-commit", "data-toggle" => "modal", "data-container" => "body", :title => (tooltip if has_tooltip), :class => "#{btn_class} #{"has-tooltip" if has_tooltip}" elsif can?(current_user, :fork_project, @project) continue_params = { to: continue_to_path, notice: "#{edit_in_new_fork_notice} Try to #{action} this commit again.", - notice_now: edit_in_new_fork_notice_now + notice_now: edit_in_new_fork_notice_now, } fork_path = project_forks_path(@project, namespace_key: current_user.namespace.id, continue: continue_params) - link_to action.capitalize, fork_path, class: btn_class, method: :post, 'data-toggle' => 'tooltip', 'data-container' => 'body', title: (tooltip if has_tooltip) + link_to action.capitalize, fork_path, :class => btn_class, :method => :post, "data-toggle" => "tooltip", "data-container" => "body", :title => (tooltip if has_tooltip) end end def view_file_button(commit_sha, diff_new_path, project, replaced: false) - title = replaced ? _('View replaced file @ ') : _('View file @ ') + title = replaced ? _("View replaced file @ ") : _("View file @ ") link_to( project_blob_path(project, - tree_join(commit_sha, diff_new_path)), - class: 'btn view-file js-view-file' + tree_join(commit_sha, diff_new_path)), + class: "btn view-file js-view-file" ) do raw(title) + content_tag(:span, Commit.truncate_sha(commit_sha), - class: 'commit-sha') + class: "commit-sha") end end @@ -199,8 +199,8 @@ module CommitsHelper external_url = environment.external_url_for(diff_new_path, commit_sha) return unless external_url - link_to(external_url, class: 'btn btn-file-option has-tooltip', target: '_blank', rel: 'noopener noreferrer', title: "View on #{environment.formatted_external_url}", data: { container: 'body' }) do - icon('external-link') + link_to(external_url, class: "btn btn-file-option has-tooltip", target: "_blank", rel: "noopener noreferrer", title: "View on #{environment.formatted_external_url}", data: {container: "body"}) do + icon("external-link") end end diff --git a/app/helpers/compare_helper.rb b/app/helpers/compare_helper.rb index 9ece8b0bc5b..f2d2e42eb96 100644 --- a/app/helpers/compare_helper.rb +++ b/app/helpers/compare_helper.rb @@ -15,7 +15,7 @@ module CompareHelper project, merge_request: { source_branch: to, - target_branch: from + target_branch: from, } ) end diff --git a/app/helpers/components_helper.rb b/app/helpers/components_helper.rb index d0ef86851ad..ea1474fbb9d 100644 --- a/app/helpers/components_helper.rb +++ b/app/helpers/components_helper.rb @@ -2,8 +2,8 @@ module ComponentsHelper def gitlab_workhorse_version - if request.headers['Gitlab-Workhorse'].present? - request.headers['Gitlab-Workhorse'].split('-').first + if request.headers["Gitlab-Workhorse"].present? + request.headers["Gitlab-Workhorse"].split("-").first else Gitlab::Workhorse.version end diff --git a/app/helpers/conversational_development_index_helper.rb b/app/helpers/conversational_development_index_helper.rb index 37e5bb325fb..60c8a0457c8 100644 --- a/app/helpers/conversational_development_index_helper.rb +++ b/app/helpers/conversational_development_index_helper.rb @@ -3,11 +3,11 @@ module ConversationalDevelopmentIndexHelper def score_level(score) if score < 33.33 - 'low' + "low" elsif score < 66.66 - 'average' + "average" else - 'high' + "high" end end diff --git a/app/helpers/cookies_helper.rb b/app/helpers/cookies_helper.rb index 3a7e9987190..1670f2b59cc 100644 --- a/app/helpers/cookies_helper.rb +++ b/app/helpers/cookies_helper.rb @@ -4,6 +4,6 @@ module CookiesHelper def set_secure_cookie(key, value, httponly: false, permanent: false) cookie_jar = permanent ? cookies.permanent : cookies - cookie_jar[key] = { value: value, secure: Gitlab.config.gitlab.https, httponly: httponly } + cookie_jar[key] = {value: value, secure: Gitlab.config.gitlab.https, httponly: httponly} end end diff --git a/app/helpers/diff_helper.rb b/app/helpers/diff_helper.rb index 32431959851..7b733c496eb 100644 --- a/app/helpers/diff_helper.rb +++ b/app/helpers/diff_helper.rb @@ -16,7 +16,7 @@ module DiffHelper def diff_view @diff_view ||= begin - diff_views = %w(inline parallel) + diff_views = %w[inline parallel] diff_view = params[:view] || cookies[:diff_view] diff_view = diff_views.first unless diff_views.include?(diff_view) diff_view.to_sym @@ -24,9 +24,9 @@ module DiffHelper end def diff_options - options = { ignore_whitespace_change: hide_whitespace?, expanded: diffs_expanded? } + options = {ignore_whitespace_change: hide_whitespace?, expanded: diffs_expanded?} - if action_name == 'diff_for_path' + if action_name == "diff_for_path" options[:expanded] = true options[:paths] = params.values_at(:old_path, :new_path) end @@ -34,23 +34,23 @@ module DiffHelper options end - def diff_match_line(old_pos, new_pos, text: '', view: :inline, bottom: false) + def diff_match_line(old_pos, new_pos, text: "", view: :inline, bottom: false) content_line_class = %w[line_content match] - content_line_class << 'parallel' if view == :parallel + content_line_class << "parallel" if view == :parallel line_num_class = %w[diff-line-num unfold js-unfold] - line_num_class << 'js-unfold-bottom' if bottom + line_num_class << "js-unfold-bottom" if bottom html = [] if old_pos - html << content_tag(:td, '...', class: [*line_num_class, 'old_line'], data: { linenumber: old_pos }) - html << content_tag(:td, text, class: [*content_line_class, 'left-side']) if view == :parallel + html << content_tag(:td, "...", class: [*line_num_class, "old_line"], data: {linenumber: old_pos}) + html << content_tag(:td, text, class: [*content_line_class, "left-side"]) if view == :parallel end if new_pos - html << content_tag(:td, '...', class: [*line_num_class, 'new_line'], data: { linenumber: new_pos }) - html << content_tag(:td, text, class: [*content_line_class, ('right-side' if view == :parallel)]) + html << content_tag(:td, "...", class: [*line_num_class, "new_line"], data: {linenumber: new_pos}) + html << content_tag(:td, text, class: [*content_line_class, ("right-side" if view == :parallel)]) end html.join.html_safe @@ -61,7 +61,7 @@ module DiffHelper " ".html_safe else # We can't use `sub` because the HTML-safeness of `line` will not survive. - line[0] = '' if line.start_with?('+', '-', ' ') + line[0] = "" if line.start_with?("+", "-", " ") line end end @@ -71,12 +71,12 @@ module DiffHelper discussions_left = discussions_right = nil - if left && left.discussable? && (left.unchanged? || left.removed?) + if left&.discussable? && (left&.unchanged? || left&.removed?) line_code = diff_file.line_code(left) discussions_left = @grouped_diff_discussions[line_code] end - if right && right.discussable? && right.added? + if right&.discussable? && right&.added? line_code = diff_file.line_code(right) discussions_right = @grouped_diff_discussions[line_code] end @@ -85,26 +85,26 @@ module DiffHelper end def inline_diff_btn - diff_btn('Inline', 'inline', diff_view == :inline) + diff_btn("Inline", "inline", diff_view == :inline) end def parallel_diff_btn - diff_btn('Side-by-side', 'parallel', diff_view == :parallel) + diff_btn("Side-by-side", "parallel", diff_view == :parallel) end def submodule_link(blob, ref, repository = @repository) project_url, tree_url = submodule_links(blob, ref, repository) commit_id = if tree_url.nil? - Commit.truncate_sha(blob.id) - else - link_to Commit.truncate_sha(blob.id), tree_url - end + Commit.truncate_sha(blob.id) + else + link_to Commit.truncate_sha(blob.id), tree_url + end [ content_tag(:span, link_to(truncate(blob.name, length: 40), project_url)), - '@', - content_tag(:span, commit_id, class: 'commit-sha') - ].join(' ').html_safe + "@", + content_tag(:span, commit_id, class: "commit-sha"), + ].join(" ").html_safe end def diff_file_blob_raw_url(diff_file, only_path: false) @@ -129,8 +129,8 @@ module DiffHelper def diff_file_html_data(project, diff_file_path, diff_commit_id) { blob_diff_path: project_blob_diff_path(project, - tree_join(diff_commit_id, diff_file_path)), - view: diff_view + tree_join(diff_commit_id, diff_file_path)), + view: diff_view, } end @@ -165,7 +165,7 @@ module DiffHelper # Always use HTML to handle case where JSON diff rendered this button params_copy.delete(:format) - link_to url_for(params_copy), id: "#{name}-diff-btn", class: (selected ? 'btn active' : 'btn'), data: { view_type: name } do + link_to url_for(params_copy), id: "#{name}-diff-btn", class: (selected ? "btn active" : "btn"), data: {view_type: name} do title end end @@ -186,7 +186,7 @@ module DiffHelper end def hide_whitespace? - params[:w] == '1' + params[:w] == "1" end # rubocop: disable CodeReuse/ActiveRecord @@ -196,8 +196,8 @@ module DiffHelper # rubocop: enable CodeReuse/ActiveRecord def toggle_whitespace_link(url, options) - options[:class] = [*options[:class], 'btn btn-default'].join(' ') - link_to "#{hide_whitespace? ? 'Show' : 'Hide'} whitespace changes", url, class: options[:class] + options[:class] = [*options[:class], "btn btn-default"].join(" ") + link_to "#{hide_whitespace? ? "Show" : "Hide"} whitespace changes", url, class: options[:class] end def render_overflow_warning?(diff_files) diff --git a/app/helpers/dropdowns_helper.rb b/app/helpers/dropdowns_helper.rb index 8d8c62f1291..890d506d6c5 100644 --- a/app/helpers/dropdowns_helper.rb +++ b/app/helpers/dropdowns_helper.rb @@ -3,7 +3,7 @@ module DropdownsHelper def dropdown_tag(toggle_text, options: {}, &block) content_tag :div, class: "dropdown #{options[:wrapper_class] if options.key?(:wrapper_class)}" do - data_attr = { toggle: "dropdown" } + data_attr = {toggle: "dropdown"} if options.key?(:data) data_attr = options[:data].merge(data_attr) @@ -15,7 +15,7 @@ module DropdownsHelper dropdown_output = dropdown_toggle_link(toggle_text, data_attr, options) end - dropdown_output << content_tag(:div, class: "dropdown-menu dropdown-select #{options[:dropdown_class] if options.key?(:dropdown_class)}") do + dropdown_output << content_tag(:div, class: "dropdown-menu dropdown-select #{options[:dropdown_class] if options.key?(:dropdown_class)}") { output = [] if options.key?(:title) @@ -26,19 +26,19 @@ module DropdownsHelper output << dropdown_filter(options[:placeholder]) end - output << content_tag(:div, class: "dropdown-content #{options[:content_class] if options.key?(:content_class)}") do + output << content_tag(:div, class: "dropdown-content #{options[:content_class] if options.key?(:content_class)}") { capture(&block) if block && !options.key?(:footer_content) - end + } if block && options[:footer_content] - output << content_tag(:div, class: "dropdown-footer") do + output << content_tag(:div, class: "dropdown-footer") { capture(&block) - end + } end output << dropdown_loading output.join.html_safe - end + } dropdown_output.html_safe end @@ -47,8 +47,8 @@ module DropdownsHelper def dropdown_toggle(toggle_text, data_attr, options = {}) default_label = data_attr[:default_label] content_tag(:button, disabled: options[:disabled], class: "dropdown-menu-toggle #{options[:toggle_class] if options.key?(:toggle_class)}", id: (options[:id] if options.key?(:id)), type: "button", data: data_attr) do - output = content_tag(:span, toggle_text, class: "dropdown-toggle-text #{'is-default' if toggle_text == default_label}") - output << icon('chevron-down') + output = content_tag(:span, toggle_text, class: "dropdown-toggle-text #{"is-default" if toggle_text == default_label}") + output << icon("chevron-down") output.html_safe end end @@ -63,17 +63,17 @@ module DropdownsHelper title_output = [] if options.fetch(:back, false) - title_output << content_tag(:button, class: "dropdown-title-button dropdown-menu-back", aria: { label: "Go back" }, type: "button") do - icon('arrow-left') - end + title_output << content_tag(:button, class: "dropdown-title-button dropdown-menu-back", aria: {label: "Go back"}, type: "button") { + icon("arrow-left") + } end title_output << content_tag(:span, title) if options.fetch(:close, true) - title_output << content_tag(:button, class: "dropdown-title-button dropdown-menu-close", aria: { label: "Close" }, type: "button") do - icon('times', class: 'dropdown-menu-close-icon') - end + title_output << content_tag(:button, class: "dropdown-title-button dropdown-menu-close", aria: {label: "Close"}, type: "button") { + icon("times", class: "dropdown-menu-close-icon") + } end title_output.join.html_safe @@ -82,8 +82,8 @@ module DropdownsHelper def dropdown_input(placeholder, input_id: nil) content_tag :div, class: "dropdown-input" do - filter_output = text_field_tag input_id, nil, class: "dropdown-input-field dropdown-no-filter", placeholder: placeholder, autocomplete: 'off' - filter_output << icon('times', class: "dropdown-input-clear js-dropdown-input-clear", role: "button") + filter_output = text_field_tag input_id, nil, class: "dropdown-input-field dropdown-no-filter", placeholder: placeholder, autocomplete: "off" + filter_output << icon("times", class: "dropdown-input-clear js-dropdown-input-clear", role: "button") filter_output.html_safe end @@ -91,9 +91,9 @@ module DropdownsHelper def dropdown_filter(placeholder, search_id: nil) content_tag :div, class: "dropdown-input" do - filter_output = search_field_tag search_id, nil, class: "dropdown-input-field", placeholder: placeholder, autocomplete: 'off' - filter_output << icon('search', class: "dropdown-input-search") - filter_output << icon('times', class: "dropdown-input-clear js-dropdown-input-clear", role: "button") + filter_output = search_field_tag search_id, nil, class: "dropdown-input-field", placeholder: placeholder, autocomplete: "off" + filter_output << icon("search", class: "dropdown-input-search") + filter_output << icon("times", class: "dropdown-input-clear js-dropdown-input-clear", role: "button") filter_output.html_safe end @@ -119,7 +119,7 @@ module DropdownsHelper def dropdown_loading content_tag :div, class: "dropdown-loading" do - icon('spinner spin') + icon("spinner spin") end end end diff --git a/app/helpers/emails_helper.rb b/app/helpers/emails_helper.rb index 96471d15aac..ed5f011644e 100644 --- a/app/helpers/emails_helper.rb +++ b/app/helpers/emails_helper.rb @@ -14,11 +14,11 @@ module EmailsHelper "action" => { "@type" => "ViewAction", "name" => name, - "url" => url - } - } + "url" => url, + }, + } - content_tag :script, type: 'application/ld+json' do + content_tag :script, type: "application/ld+json" do data.to_json.html_safe end end @@ -27,7 +27,7 @@ module EmailsHelper def action_title(url) return unless url - %w(merge_requests issues commit).each do |action| + %w[merge_requests issues commit].each do |action| if url.split("/").include?(action) return "View #{action.humanize.singularize}" end @@ -37,8 +37,8 @@ module EmailsHelper end def sanitize_name(name) - if name =~ URI::DEFAULT_PARSER.regexp[:URI_REF] - name.tr('.', '_') + if name&.match?(URI::DEFAULT_PARSER.regexp[:URI_REF]) + name.tr(".", "_") else name end @@ -47,10 +47,10 @@ module EmailsHelper def password_reset_token_valid_time valid_hours = Devise.reset_password_within / 60 / 60 if valid_hours >= 24 - unit = 'day' + unit = "day" valid_length = (valid_hours / 24).floor else - unit = 'hour' + unit = "hour" valid_length = valid_hours.floor end @@ -58,7 +58,7 @@ module EmailsHelper end def reset_token_expire_message - link_tag = link_to('request a new one', new_user_password_url(user_email: @user.email)) + link_tag = link_to("request a new one", new_user_password_url(user_email: @user.email)) "This link is valid for #{password_reset_token_valid_time}. " \ "After it expires, you can #{link_tag}." end @@ -67,13 +67,13 @@ module EmailsHelper if current_appearance&.header_logo? image_tag( current_appearance.header_logo_path, - style: 'height: 50px' + style: "height: 50px" ) else image_tag( - image_url('mailers/gitlab_header_logo.gif'), - size: '55x50', - alt: 'GitLab' + image_url("mailers/gitlab_header_logo.gif"), + size: "55x50", + alt: "GitLab" ) end end @@ -81,38 +81,38 @@ module EmailsHelper def email_default_heading(text) content_tag :h1, text, style: [ "font-family:'Helvetica Neue',Helvetica,Arial,sans-serif", - 'color:#333333', - 'font-size:18px', - 'font-weight:400', - 'line-height:1.4', - 'padding:0', - 'margin:0', - 'text-align:center' - ].join(';') + "color:#333333", + "font-size:18px", + "font-weight:400", + "line-height:1.4", + "padding:0", + "margin:0", + "text-align:center", + ].join(";") end # "You are receiving this email because #{reason}" def notification_reason_text(reason) string = case reason when NotificationReason::OWN_ACTIVITY - 'of your activity' + "of your activity" when NotificationReason::ASSIGNED - 'you have been assigned an item' + "you have been assigned an item" when NotificationReason::MENTIONED - 'you have been mentioned' + "you have been mentioned" else - 'of your account' - end + "of your account" + end "#{string} on #{Gitlab.config.gitlab.host}" end def create_list_id_string(project, list_id_max_length = 255) project_path_as_domain = project.full_path.downcase - .split('/').reverse.join('/') - .gsub(%r{[^a-z0-9\/]}, '-') - .gsub(%r{\/+}, '.') - .gsub(/(\A\.+|\.+\z)/, '') + .split("/").reverse.join("/") + .gsub(%r{[^a-z0-9\/]}, "-") + .gsub(%r{\/+}, ".") + .gsub(/(\A\.+|\.+\z)/, "") max_domain_length = list_id_max_length - Gitlab.config.gitlab.host.length - project.id.to_s.length - 2 @@ -135,25 +135,25 @@ module EmailsHelper def html_header_message return unless show_header? - render_message(:header_message, style: '') + render_message(:header_message, style: "") end def html_footer_message return unless show_footer? - render_message(:footer_message, style: '') + render_message(:footer_message, style: "") end def text_header_message return unless show_header? - strip_tags(render_message(:header_message, style: '')) + strip_tags(render_message(:header_message, style: "")) end def text_footer_message return unless show_footer? - strip_tags(render_message(:footer_message, style: '')) + strip_tags(render_message(:footer_message, style: "")) end private diff --git a/app/helpers/environment_helper.rb b/app/helpers/environment_helper.rb index 2b7320817ed..1b45ec53a2c 100644 --- a/app/helpers/environment_helper.rb +++ b/app/helpers/environment_helper.rb @@ -21,7 +21,7 @@ module EnvironmentHelper def deployment_link(deployment, text: nil) return unless deployment - link_label = text ? text : "##{deployment.iid}" + link_label = text || "##{deployment.iid}" link_to link_label, [deployment.project.namespace.becomes(Namespace), deployment.project, deployment.deployable] end diff --git a/app/helpers/environments_helper.rb b/app/helpers/environments_helper.rb index 365b94f5a3e..39a7c473f58 100644 --- a/app/helpers/environments_helper.rb +++ b/app/helpers/environments_helper.rb @@ -3,7 +3,7 @@ module EnvironmentsHelper def environments_list_data { - endpoint: project_environments_path(@project, format: :json) + endpoint: project_environments_path(@project, format: :json), } end @@ -11,26 +11,26 @@ module EnvironmentsHelper { "endpoint" => folder_project_environments_path(@project, @folder, format: :json), "folder-name" => @folder, - "can-read-environment" => can?(current_user, :read_environment, @project).to_s + "can-read-environment" => can?(current_user, :read_environment, @project).to_s, } end def metrics_data(project, environment) { - "settings-path" => edit_project_service_path(project, 'prometheus'), + "settings-path" => edit_project_service_path(project, "prometheus"), "clusters-path" => project_clusters_path(project), - "current-environment-name": environment.name, - "documentation-path" => help_page_path('administration/monitoring/prometheus/index.md'), - "empty-getting-started-svg-path" => image_path('illustrations/monitoring/getting_started.svg'), - "empty-loading-svg-path" => image_path('illustrations/monitoring/loading.svg'), - "empty-no-data-svg-path" => image_path('illustrations/monitoring/no_data.svg'), - "empty-unable-to-connect-svg-path" => image_path('illustrations/monitoring/unable_to_connect.svg'), + :"current-environment-name" => environment.name, + "documentation-path" => help_page_path("administration/monitoring/prometheus/index.md"), + "empty-getting-started-svg-path" => image_path("illustrations/monitoring/getting_started.svg"), + "empty-loading-svg-path" => image_path("illustrations/monitoring/loading.svg"), + "empty-no-data-svg-path" => image_path("illustrations/monitoring/no_data.svg"), + "empty-unable-to-connect-svg-path" => image_path("illustrations/monitoring/unable_to_connect.svg"), "metrics-endpoint" => additional_metrics_project_environment_path(project, environment, format: :json), "deployment-endpoint" => project_environment_deployments_path(project, environment, format: :json), - "environments-endpoint": project_environments_path(project, format: :json), + :"environments-endpoint" => project_environments_path(project, format: :json), "project-path" => project_path(project), "tags-path" => project_tags_path(project), - "has-metrics" => "#{environment.has_metrics?}" + "has-metrics" => environment.has_metrics?.to_s, } end end diff --git a/app/helpers/events_helper.rb b/app/helpers/events_helper.rb index 1371e9993b4..42739862aa1 100644 --- a/app/helpers/events_helper.rb +++ b/app/helpers/events_helper.rb @@ -2,23 +2,23 @@ module EventsHelper ICON_NAMES_BY_EVENT_TYPE = { - 'pushed to' => 'commit', - 'pushed new' => 'commit', - 'created' => 'status_open', - 'opened' => 'status_open', - 'closed' => 'status_closed', - 'accepted' => 'fork', - 'commented on' => 'comment', - 'deleted' => 'remove', - 'imported' => 'import', - 'joined' => 'users' + "pushed to" => "commit", + "pushed new" => "commit", + "created" => "status_open", + "opened" => "status_open", + "closed" => "status_closed", + "accepted" => "fork", + "commented on" => "comment", + "deleted" => "remove", + "imported" => "import", + "joined" => "users", }.freeze def link_to_author(event, self_added: false) author = event.author if author - name = self_added ? 'You' : author.name + name = self_added ? "You" : author.name link_to name, user_path(author.username), title: name else escape_once(event.author_name) @@ -26,31 +26,31 @@ module EventsHelper end def event_action_name(event) - target = if event.target_type - if event.note? - event.note_target_type - else - event.target_type.titleize.downcase - end - else - 'project' - end + target = if event.target_type + if event.note? + event.note_target_type + else + event.target_type.titleize.downcase + end + else + "project" + end [event.action_name, target].join(" ") end def event_filter_link(key, text, tooltip) key = key.to_s - active = 'active' if @event_filter.active?(key) + active = "active" if @event_filter.active?(key) link_opts = { class: "event-filter-link", - id: "#{key}_event_filter", - title: tooltip + id: "#{key}_event_filter", + title: tooltip, } content_tag :li, class: active do link_to request.path, link_opts do - content_tag(:span, ' ' + text) + content_tag(:span, " " + text) end end end @@ -111,12 +111,12 @@ module EventsHelper def event_feed_url(event) if event.issue? project_issue_url(event.project, - event.issue) + event.issue) elsif event.merge_request? project_merge_request_url(event.project, event.merge_request) elsif event.commit_note? project_commit_url(event.project, - event.note_target) + event.note_target) elsif event.note? if event.note_target event_note_target_url(event) @@ -132,15 +132,15 @@ module EventsHelper if event.push_with_commits? && event.md_ref? if event.commits_count > 1 project_compare_url(event.project, - from: event.commit_from, to: - event.commit_to) + from: event.commit_from, to: + event.commit_to) else project_commit_url(event.project, - id: event.commit_to) + id: event.commit_to) end else project_commits_url(event.project, - event.ref_name) + event.ref_name) end end @@ -167,8 +167,8 @@ module EventsHelper project_merge_request_url(event.project, id: event.note_target, anchor: dom_id(event.target)) else polymorphic_url([event.project.namespace.becomes(Namespace), - event.project, event.note_target], - anchor: dom_id(event.target)) + event.project, event.note_target,], + anchor: dom_id(event.target)) end end @@ -176,15 +176,15 @@ module EventsHelper if event.note_target capture do concat content_tag(:span, event.note_target_type, class: "event-target-type append-right-4") - concat link_to(event.note_target_reference, event_note_target_url(event), title: event.target_title, class: 'has-tooltip event-target-link append-right-4') + concat link_to(event.note_target_reference, event_note_target_url(event), title: event.target_title, class: "has-tooltip event-target-link append-right-4") end else - content_tag(:strong, '(deleted)') + content_tag(:strong, "(deleted)") end end def event_commit_title(message) - message ||= '' + message ||= "" (message.split("\n").first || "").truncate(70) rescue "--broken encoding" @@ -196,19 +196,19 @@ module EventsHelper end def icon_for_profile_event(event) - if current_path?('users#show') + if current_path?("users#show") content_tag :div, class: "system-note-image #{event.action_name.parameterize}-icon" do icon_for_event(event.action_name) end else - content_tag :div, class: 'system-note-image user-avatar' do + content_tag :div, class: "system-note-image user-avatar" do author_avatar(event, size: 40) end end end def inline_event_icon(event) - unless current_path?('users#show') + unless current_path?("users#show") content_tag :span, class: "system-note-image-inline d-none d-sm-flex append-right-4 #{event.action_name.parameterize}-icon align-self-center" do icon_for_event(event.action_name, size: 14) end diff --git a/app/helpers/explore_helper.rb b/app/helpers/explore_helper.rb index 62be591ec47..1282aa32eee 100644 --- a/app/helpers/explore_helper.rb +++ b/app/helpers/explore_helper.rb @@ -12,7 +12,7 @@ module ExploreHelper personal: params[:personal], archived: params[:archived], shared: params[:shared], - namespace_id: params[:namespace_id] + namespace_id: params[:namespace_id], } options = exist_opts.merge(options).delete_if { |key, value| value.blank? } diff --git a/app/helpers/form_helper.rb b/app/helpers/form_helper.rb index 5705ee54cee..ff4f8a91f85 100644 --- a/app/helpers/form_helper.rb +++ b/app/helpers/form_helper.rb @@ -1,44 +1,44 @@ # frozen_string_literal: true module FormHelper - def form_errors(model, type: 'form') + def form_errors(model, type: "form") return unless model.errors.any? - pluralized = 'error'.pluralize(model.errors.count) + pluralized = "error".pluralize(model.errors.count) headline = "The #{type} contains the following #{pluralized}:" - content_tag(:div, class: 'alert alert-danger', id: 'error_explanation') do + content_tag(:div, class: "alert alert-danger", id: "error_explanation") do content_tag(:h4, headline) << - content_tag(:ul) do + content_tag(:ul) { model.errors.full_messages .map { |msg| content_tag(:li, msg) } .join .html_safe - end + } end end def issue_assignees_dropdown_options { - toggle_class: 'js-user-search js-assignee-search js-multiselect js-save-user-data', - title: 'Select assignee', + toggle_class: "js-user-search js-assignee-search js-multiselect js-save-user-data", + title: "Select assignee", filter: true, - dropdown_class: 'dropdown-menu-user dropdown-menu-selectable dropdown-menu-assignee', - placeholder: 'Search users', + dropdown_class: "dropdown-menu-user dropdown-menu-selectable dropdown-menu-assignee", + placeholder: "Search users", data: { first_user: current_user&.username, null_user: true, current_user: true, project_id: @project&.id, - field_name: 'issue[assignee_ids][]', - default_label: 'Unassigned', + field_name: "issue[assignee_ids][]", + default_label: "Unassigned", 'max-select': 1, - 'dropdown-header': 'Assignee', + 'dropdown-header': "Assignee", multi_select: true, - 'input-meta': 'name', + 'input-meta': "name", 'always-show-selectbox': true, - current_user_info: UserSerializer.new.represent(current_user) - } + current_user_info: UserSerializer.new.represent(current_user), + }, } end end diff --git a/app/helpers/gitlab_routing_helper.rb b/app/helpers/gitlab_routing_helper.rb index 04cf43be452..0ac4d0b08a0 100644 --- a/app/helpers/gitlab_routing_helper.rb +++ b/app/helpers/gitlab_routing_helper.rb @@ -154,17 +154,17 @@ module GitlabRoutingHelper # Artifacts def artifacts_action_path(path, project, build) - action, path_params = path.split('/', 2) + action, path_params = path.split("/", 2) args = [project, build, path_params] case action - when 'download' + when "download" download_project_job_artifacts_path(*args) - when 'browse' + when "browse" browse_project_job_artifacts_path(*args) - when 'file' + when "file" file_project_job_artifacts_path(*args) - when 'raw' + when "raw" raw_project_job_artifacts_path(*args) end end diff --git a/app/helpers/graph_helper.rb b/app/helpers/graph_helper.rb index 49b15cde009..30093bf23f2 100644 --- a/app/helpers/graph_helper.rb +++ b/app/helpers/graph_helper.rb @@ -2,11 +2,11 @@ module GraphHelper def refs(repo, commit) - refs = [commit.ref_names(repo).join(' ')] + refs = [commit.ref_names(repo).join(" ")] # append note count notes_count = @graph.notes[commit.id] - refs << "[#{pluralize(notes_count, 'note')}]" if notes_count > 0 + refs << "[#{pluralize(notes_count, "note")}]" if notes_count > 0 refs.join end diff --git a/app/helpers/groups_helper.rb b/app/helpers/groups_helper.rb index 4a9ed123161..bc16822987a 100644 --- a/app/helpers/groups_helper.rb +++ b/app/helpers/groups_helper.rb @@ -49,7 +49,7 @@ module GroupsHelper group = Group.find_by_full_path(group) end - group.try(:avatar_url) || ActionController::Base.helpers.image_path('no_group_avatar.png') + group.try(:avatar_url) || ActionController::Base.helpers.image_path("no_group_avatar.png") end def group_title(group, name = nil, url = nil) @@ -67,7 +67,7 @@ module GroupsHelper full_title << render("layouts/nav/breadcrumbs/collapsed_dropdown", location: :before, title: _("Show parent subgroups")) full_title << breadcrumb_list_item(group_title_link(group)) - full_title << ' · '.html_safe + link_to(simple_sanitize(name), url, class: 'group-path breadcrumb-item-text js-breadcrumb-item-text') if name + full_title << " · ".html_safe + link_to(simple_sanitize(name), url, class: "group-path breadcrumb-item-text js-breadcrumb-item-text") if name full_title.join.html_safe end @@ -83,14 +83,14 @@ module GroupsHelper size = group.projects.size if lfs_status == size - 'for all projects' + "for all projects" else - "for #{lfs_status} out of #{pluralize(size, 'project')}" + "for #{lfs_status} out of #{pluralize(size, "project")}" end end def group_lfs_status(group) - status = group.lfs_enabled? ? 'enabled' : 'disabled' + status = group.lfs_enabled? ? "enabled" : "disabled" content_tag(:span, class: "lfs-#{status}") do "#{status.humanize} #{projects_lfs_status(group)}" @@ -99,7 +99,7 @@ module GroupsHelper def remove_group_message(group) _("You are going to remove %{group_name}. Removed groups CANNOT be restored! Are you ABSOLUTELY sure?") % - { group_name: group.name } + {group_name: group.name} end def share_with_group_lock_help_text(group) @@ -117,9 +117,9 @@ module GroupsHelper end def parent_group_options(current_group) - groups = current_user.owned_groups.sort_by(&:human_name).map do |group| - { id: group.id, text: group.human_name } - end + groups = current_user.owned_groups.sort_by(&:human_name).map { |group| + {id: group.id, text: group.human_name} + } groups.delete_if { |group| group[:id] == current_group.id } groups.to_json @@ -135,10 +135,10 @@ module GroupsHelper links = [:overview, :group_members] resources = [:activity, :issues, :boards, :labels, :milestones, - :merge_requests] - links += resources.select do |resource| + :merge_requests,] + links += resources.select { |resource| can?(current_user, "read_group_#{resource}".to_sym, @group) - end + } if can?(current_user, :read_cluster, @group) && @group.group_clusters_enabled? links << :kubernetes @@ -152,7 +152,7 @@ module GroupsHelper end def group_title_link(group, hidable: false, show_avatar: false, for_dropdown: false) - link_to(group_path(group), class: "group-path #{'breadcrumb-item-text' unless for_dropdown} js-breadcrumb-item-text #{'hidable' if hidable}") do + link_to(group_path(group), class: "group-path #{"breadcrumb-item-text" unless for_dropdown} js-breadcrumb-item-text #{"hidable" if hidable}") do icon = group_icon(group, class: "avatar-tile", width: 15, height: 15) if (group.try(:avatar_url) || show_avatar) && !Rails.env.test? [icon, simple_sanitize(group.name)].join.html_safe end @@ -169,7 +169,7 @@ module GroupsHelper def remove_the_share_with_group_lock_from_ancestor(group) ancestor = oldest_consecutively_locked_ancestor(group) - text = s_("GroupSettings|remove the share with group lock from %{ancestor_group_name}") % { ancestor_group_name: ancestor.name } + text = s_("GroupSettings|remove the share with group lock from %{ancestor_group_name}") % {ancestor_group_name: ancestor.name} if can?(current_user, :admin_group, ancestor) link_to text, edit_group_path(ancestor) else @@ -188,14 +188,14 @@ module GroupsHelper end def ancestor_locked_but_you_can_override(group) - s_("GroupSettings|This setting is applied on %{ancestor_group}. You can override the setting or %{remove_ancestor_share_with_group_lock}.").html_safe % { ancestor_group: ancestor_group(group), remove_ancestor_share_with_group_lock: remove_the_share_with_group_lock_from_ancestor(group) } + s_("GroupSettings|This setting is applied on %{ancestor_group}. You can override the setting or %{remove_ancestor_share_with_group_lock}.").html_safe % {ancestor_group: ancestor_group(group), remove_ancestor_share_with_group_lock: remove_the_share_with_group_lock_from_ancestor(group)} end def ancestor_locked_so_ask_the_owner(group) - s_("GroupSettings|This setting is applied on %{ancestor_group}. To share projects in this group with another group, ask the owner to override the setting or %{remove_ancestor_share_with_group_lock}.").html_safe % { ancestor_group: ancestor_group(group), remove_ancestor_share_with_group_lock: remove_the_share_with_group_lock_from_ancestor(group) } + s_("GroupSettings|This setting is applied on %{ancestor_group}. To share projects in this group with another group, ask the owner to override the setting or %{remove_ancestor_share_with_group_lock}.").html_safe % {ancestor_group: ancestor_group(group), remove_ancestor_share_with_group_lock: remove_the_share_with_group_lock_from_ancestor(group)} end def ancestor_locked_and_has_been_overridden(group) - s_("GroupSettings|This setting is applied on %{ancestor_group} and has been overridden on this subgroup.").html_safe % { ancestor_group: ancestor_group(group) } + s_("GroupSettings|This setting is applied on %{ancestor_group} and has been overridden on this subgroup.").html_safe % {ancestor_group: ancestor_group(group)} end end diff --git a/app/helpers/hooks_helper.rb b/app/helpers/hooks_helper.rb index c4b39939192..ca3e5097d5b 100644 --- a/app/helpers/hooks_helper.rb +++ b/app/helpers/hooks_helper.rb @@ -8,11 +8,11 @@ module HooksHelper test_project_hook_path(project, hook, trigger: trigger) when SystemHook test_admin_hook_path(hook, trigger: trigger) - end + end - trigger_human_name = trigger.to_s.tr('_', ' ').camelize + trigger_human_name = trigger.to_s.tr("_", " ").camelize - link_to path, rel: 'nofollow', method: :post do + link_to path, rel: "nofollow", method: :post do content_tag(:span, trigger_human_name) end end diff --git a/app/helpers/icons_helper.rb b/app/helpers/icons_helper.rb index 4e11772b252..2726c8a0f0f 100644 --- a/app/helpers/icons_helper.rb +++ b/app/helpers/icons_helper.rb @@ -1,6 +1,6 @@ # frozen_string_literal: true -require 'json' +require "json" module IconsHelper extend self @@ -14,8 +14,8 @@ module IconsHelper def icon(names, options = {}) if (options.keys & %w[aria-hidden aria-label data-hidden]).empty? # Add 'aria-hidden' and 'data-hidden' if they are not set in options. - options['aria-hidden'] = true - options['data-hidden'] = true + options["aria-hidden"] = true + options["data-hidden"] = true end options.include?(:base) ? fa_stacked_icon(names, options) : fa_icon(names, options) @@ -31,14 +31,14 @@ module IconsHelper # SVG Sprites currently don't work across domains, so in the case of a CDN # we have to set the current path deliberately to prevent addition of asset_host sprite_base_url = Gitlab.config.gitlab.url if ActionController::Base.asset_host - ActionController::Base.helpers.image_path('icons.svg', host: sprite_base_url) + ActionController::Base.helpers.image_path("icons.svg", host: sprite_base_url) end def sprite_file_icons_path # SVG Sprites currently don't work across domains, so in the case of a CDN # we have to set the current path deliberately to prevent addition of asset_host sprite_base_url = Gitlab.config.gitlab.url if ActionController::Base.asset_host - ActionController::Base.helpers.image_path('file_icons.svg', host: sprite_base_url) + ActionController::Base.helpers.image_path("file_icons.svg", host: sprite_base_url) end def sprite_icon(icon_name, size: nil, css_class: nil) @@ -51,8 +51,8 @@ module IconsHelper css_classes = [] css_classes << "s#{size}" if size - css_classes << "#{css_class}" unless css_class.blank? - content_tag(:svg, content_tag(:use, "", { "xlink:href" => "#{sprite_icon_path}##{icon_name}" } ), class: css_classes.empty? ? nil : css_classes.join(' ')) + css_classes << css_class.to_s unless css_class.blank? + content_tag(:svg, content_tag(:use, "", {"xlink:href" => "#{sprite_icon_path}##{icon_name}"}), class: css_classes.empty? ? nil : css_classes.join(" ")) end def external_snippet_icon(name) @@ -73,19 +73,19 @@ module IconsHelper end def spinner(text = nil, visible = false) - css_class = ['loading'] - css_class << 'hide' unless visible + css_class = ["loading"] + css_class << "hide" unless visible - content_tag :div, class: css_class.join(' ') do - icon('spinner spin') + text + content_tag :div, class: css_class.join(" ") do + icon("spinner spin") + text end end def boolean_to_icon(value) if value - icon('circle', class: 'cgreen') + icon("circle", class: "cgreen") else - icon('power-off', class: 'clgray') + icon("power-off", class: "clgray") end end @@ -93,59 +93,59 @@ module IconsHelper name = case level when Gitlab::VisibilityLevel::PRIVATE - 'lock' + "lock" when Gitlab::VisibilityLevel::INTERNAL - 'shield' + "shield" else # Gitlab::VisibilityLevel::PUBLIC - 'globe' + "globe" end name = [name] name << "fw" if fw - icon(name.join(' '), options) + icon(name.join(" "), options) end def file_type_icon_class(type, mode, name) - if type == 'folder' - icon_class = 'folder' - elsif type == 'archive' - icon_class = 'archive' - elsif mode == '120000' - icon_class = 'share' + if type == "folder" + icon_class = "folder" + elsif type == "archive" + icon_class = "archive" + elsif mode == "120000" + icon_class = "share" else # Guess which icon to choose based on file extension. # If you think a file extension is missing, feel free to add it on PR case File.extname(name).downcase - when '.pdf' - icon_class = 'file-pdf-o' - when '.jpg', '.jpeg', '.jif', '.jfif', - '.jp2', '.jpx', '.j2k', '.j2c', - '.png', '.gif', '.tif', '.tiff', - '.svg', '.ico', '.bmp' - icon_class = 'file-image-o' - when '.zip', '.zipx', '.tar', '.gz', '.bz', '.bzip', - '.xz', '.rar', '.7z' - icon_class = 'file-archive-o' - when '.mp3', '.wma', '.ogg', '.oga', '.wav', '.flac', '.aac' - icon_class = 'file-audio-o' - when '.mp4', '.m4p', '.m4v', - '.mpg', '.mp2', '.mpeg', '.mpe', '.mpv', - '.mpg', '.mpeg', '.m2v', - '.avi', '.mkv', '.flv', '.ogv', '.mov', - '.3gp', '.3g2' - icon_class = 'file-video-o' - when '.doc', '.dot', '.docx', '.docm', '.dotx', '.dotm', '.docb' - icon_class = 'file-word-o' - when '.xls', '.xlt', '.xlm', '.xlsx', '.xlsm', '.xltx', '.xltm', - '.xlsb', '.xla', '.xlam', '.xll', '.xlw' - icon_class = 'file-excel-o' - when '.ppt', '.pot', '.pps', '.pptx', '.pptm', '.potx', '.potm', - '.ppam', '.ppsx', '.ppsm', '.sldx', '.sldm' - icon_class = 'file-powerpoint-o' + when ".pdf" + icon_class = "file-pdf-o" + when ".jpg", ".jpeg", ".jif", ".jfif", + ".jp2", ".jpx", ".j2k", ".j2c", + ".png", ".gif", ".tif", ".tiff", + ".svg", ".ico", ".bmp" + icon_class = "file-image-o" + when ".zip", ".zipx", ".tar", ".gz", ".bz", ".bzip", + ".xz", ".rar", ".7z" + icon_class = "file-archive-o" + when ".mp3", ".wma", ".ogg", ".oga", ".wav", ".flac", ".aac" + icon_class = "file-audio-o" + when ".mp4", ".m4p", ".m4v", + ".mpg", ".mp2", ".mpeg", ".mpe", ".mpv", + ".mpg", ".mpeg", ".m2v", + ".avi", ".mkv", ".flv", ".ogv", ".mov", + ".3gp", ".3g2" + icon_class = "file-video-o" + when ".doc", ".dot", ".docx", ".docm", ".dotx", ".dotm", ".docb" + icon_class = "file-word-o" + when ".xls", ".xlt", ".xlm", ".xlsx", ".xlsm", ".xltx", ".xltm", + ".xlsb", ".xla", ".xlam", ".xll", ".xlw" + icon_class = "file-excel-o" + when ".ppt", ".pot", ".pps", ".pptx", ".pptm", ".potx", ".potm", + ".ppam", ".ppsx", ".ppsm", ".sldx", ".sldm" + icon_class = "file-powerpoint-o" else - icon_class = 'file-text-o' + icon_class = "file-text-o" end end @@ -155,6 +155,6 @@ module IconsHelper private def known_sprites - @known_sprites ||= JSON.parse(File.read(Rails.root.join('node_modules/@gitlab/svgs/dist/icons.json')))['icons'] + @known_sprites ||= JSON.parse(File.read(Rails.root.join("node_modules/@gitlab/svgs/dist/icons.json")))["icons"] end end diff --git a/app/helpers/ide_helper.rb b/app/helpers/ide_helper.rb index 8e50bbc6c04..4c6c449c2c8 100644 --- a/app/helpers/ide_helper.rb +++ b/app/helpers/ide_helper.rb @@ -3,14 +3,14 @@ module IdeHelper def ide_data { - "empty-state-svg-path" => image_path('illustrations/multi_file_editor_empty.svg'), - "no-changes-state-svg-path" => image_path('illustrations/multi-editor_no_changes_empty.svg'), - "committed-state-svg-path" => image_path('illustrations/multi-editor_all_changes_committed_empty.svg'), - "pipelines-empty-state-svg-path": image_path('illustrations/pipelines_empty.svg'), - "promotion-svg-path": image_path('illustrations/web-ide_promotion.svg'), - "ci-help-page-path" => help_page_path('ci/quick_start/README'), - "web-ide-help-page-path" => help_page_path('user/project/web_ide/index.html'), - "clientside-preview-enabled": Gitlab::CurrentSettings.current_application_settings.web_ide_clientside_preview_enabled.to_s + "empty-state-svg-path" => image_path("illustrations/multi_file_editor_empty.svg"), + "no-changes-state-svg-path" => image_path("illustrations/multi-editor_no_changes_empty.svg"), + "committed-state-svg-path" => image_path("illustrations/multi-editor_all_changes_committed_empty.svg"), + :"pipelines-empty-state-svg-path" => image_path("illustrations/pipelines_empty.svg"), + :"promotion-svg-path" => image_path("illustrations/web-ide_promotion.svg"), + "ci-help-page-path" => help_page_path("ci/quick_start/README"), + "web-ide-help-page-path" => help_page_path("user/project/web_ide/index.html"), + :"clientside-preview-enabled" => Gitlab::CurrentSettings.current_application_settings.web_ide_clientside_preview_enabled.to_s, } end end diff --git a/app/helpers/import_helper.rb b/app/helpers/import_helper.rb index 3d494c3de6a..8469a091d31 100644 --- a/app/helpers/import_helper.rb +++ b/app/helpers/import_helper.rb @@ -10,7 +10,7 @@ module ImportHelper def sanitize_project_name(name) # For personal projects in Bitbucket in the form ~username, we can # just drop that leading tilde. - name.gsub(/\A~+/, '').gsub(/[^\w\-]/, '-') + name.gsub(/\A~+/, "").gsub(/[^\w\-]/, "-") end def import_project_target(owner, name) @@ -24,47 +24,47 @@ module ImportHelper def import_will_timeout_message(_ci_cd_only) timeout = time_interval_in_words(Gitlab.config.gitlab_shell.git_timeout) - _('The import will time out after %{timeout}. For repositories that take longer, use a clone/push combination.') % { timeout: timeout } + _("The import will time out after %{timeout}. For repositories that take longer, use a clone/push combination.") % {timeout: timeout} end def import_svn_message(_ci_cd_only) - svn_link = link_to _('this document'), help_page_path('user/project/import/svn') - _('To import an SVN repository, check out %{svn_link}.').html_safe % { svn_link: svn_link } + svn_link = link_to _("this document"), help_page_path("user/project/import/svn") + _("To import an SVN repository, check out %{svn_link}.").html_safe % {svn_link: svn_link} end def import_in_progress_title if @project.forked? - _('Forking in progress') + _("Forking in progress") else - _('Import in progress') + _("Import in progress") end end def import_wait_and_refresh_message - _('Please wait while we import the repository for you. Refresh at will.') + _("Please wait while we import the repository for you. Refresh at will.") end def import_github_authorize_message - _('To import GitHub repositories, you first need to authorize GitLab to access the list of your GitHub repositories:') + _("To import GitHub repositories, you first need to authorize GitLab to access the list of your GitHub repositories:") end def import_github_personal_access_token_message - personal_access_token_link = link_to _('Personal Access Token'), 'https://github.com/settings/tokens' + personal_access_token_link = link_to _("Personal Access Token"), "https://github.com/settings/tokens" if github_import_configured? - _('Alternatively, you can use a %{personal_access_token_link}. When you create your Personal Access Token, you will need to select the <code>repo</code> scope, so we can display a list of your public and private repositories which are available to import.').html_safe % { personal_access_token_link: personal_access_token_link } + _("Alternatively, you can use a %{personal_access_token_link}. When you create your Personal Access Token, you will need to select the <code>repo</code> scope, so we can display a list of your public and private repositories which are available to import.").html_safe % {personal_access_token_link: personal_access_token_link} else - _('To import GitHub repositories, you can use a %{personal_access_token_link}. When you create your Personal Access Token, you will need to select the <code>repo</code> scope, so we can display a list of your public and private repositories which are available to import.').html_safe % { personal_access_token_link: personal_access_token_link } + _("To import GitHub repositories, you can use a %{personal_access_token_link}. When you create your Personal Access Token, you will need to select the <code>repo</code> scope, so we can display a list of your public and private repositories which are available to import.").html_safe % {personal_access_token_link: personal_access_token_link} end end def import_configure_github_admin_message - github_integration_link = link_to 'GitHub integration', help_page_path('integration/github') + github_integration_link = link_to "GitHub integration", help_page_path("integration/github") if current_user.admin? - _('Note: As an administrator you may like to configure %{github_integration_link}, which will allow login via GitHub and allow importing repositories without generating a Personal Access Token.').html_safe % { github_integration_link: github_integration_link } + _("Note: As an administrator you may like to configure %{github_integration_link}, which will allow login via GitHub and allow importing repositories without generating a Personal Access Token.").html_safe % {github_integration_link: github_integration_link} else - _('Note: Consider asking your GitLab administrator to configure %{github_integration_link}, which will allow login via GitHub and allow importing repositories without generating a Personal Access Token.').html_safe % { github_integration_link: github_integration_link } + _("Note: Consider asking your GitLab administrator to configure %{github_integration_link}, which will allow login via GitHub and allow importing repositories without generating a Personal Access Token.").html_safe % {github_integration_link: github_integration_link} end end end diff --git a/app/helpers/instance_configuration_helper.rb b/app/helpers/instance_configuration_helper.rb index f695be32743..6aeddb82090 100644 --- a/app/helpers/instance_configuration_helper.rb +++ b/app/helpers/instance_configuration_helper.rb @@ -2,7 +2,7 @@ module InstanceConfigurationHelper def instance_configuration_cell_html(value, &block) - return '-' unless value.to_s.presence + return "-" unless value.to_s.presence block_given? ? yield(value) : value end diff --git a/app/helpers/issuables_helper.rb b/app/helpers/issuables_helper.rb index af28e6fcb93..72a726001a5 100644 --- a/app/helpers/issuables_helper.rb +++ b/app/helpers/issuables_helper.rb @@ -4,29 +4,29 @@ module IssuablesHelper include GitlabRoutingHelper def sidebar_gutter_toggle_icon - sidebar_gutter_collapsed? ? icon('angle-double-left', { 'aria-hidden': 'true' }) : icon('angle-double-right', { 'aria-hidden': 'true' }) + sidebar_gutter_collapsed? ? icon("angle-double-left", {'aria-hidden': "true"}) : icon("angle-double-right", {'aria-hidden': "true"}) end def sidebar_gutter_collapsed_class - "right-sidebar-#{sidebar_gutter_collapsed? ? 'collapsed' : 'expanded'}" + "right-sidebar-#{sidebar_gutter_collapsed? ? "collapsed" : "expanded"}" end def sidebar_gutter_tooltip_text - sidebar_gutter_collapsed? ? _('Expand sidebar') : _('Collapse sidebar') + sidebar_gutter_collapsed? ? _("Expand sidebar") : _("Collapse sidebar") end def sidebar_assignee_tooltip_label(issuable) if issuable.assignee issuable.assignee.name else - issuable.allows_multiple_assignees? ? _('Assignee(s)') : _('Assignee') + issuable.allows_multiple_assignees? ? _("Assignee(s)") : _("Assignee") end end def sidebar_milestone_tooltip_label(milestone) - return _('Milestone') unless milestone.present? + return _("Milestone") unless milestone.present? - [milestone[:title], sidebar_milestone_remaining_days(milestone) || _('Milestone')].join('<br/>') + [milestone[:title], sidebar_milestone_remaining_days(milestone) || _("Milestone")].join("<br/>") end def sidebar_milestone_remaining_days(milestone) @@ -34,7 +34,7 @@ module IssuablesHelper end def sidebar_due_date_tooltip_label(due_date) - [_('Due date'), due_date_with_remaining_days(due_date)].compact.join('<br/>') + [_("Due date"), due_date_with_remaining_days(due_date)].compact.join("<br/>") end def due_date_with_remaining_days(due_date, start_date = nil) @@ -44,7 +44,7 @@ module IssuablesHelper end def sidebar_label_filter_path(base_path, label_name) - query_params = { label_name: [label_name] }.to_query + query_params = {label_name: [label_name]}.to_query "#{base_path}?#{query_params}" end @@ -77,7 +77,7 @@ module IssuablesHelper IssueSerializer when MergeRequest MergeRequestSerializer - end + end serializer_klass .new(current_user: current_user, project: issuable.project) @@ -88,18 +88,18 @@ module IssuablesHelper def template_dropdown_tag(issuable, &block) title = selected_template(issuable) || "Choose a template" options = { - toggle_class: 'js-issuable-selector', + toggle_class: "js-issuable-selector", title: title, filter: true, - placeholder: 'Filter', + placeholder: "Filter", footer_content: true, data: { data: issuable_templates(issuable), - field_name: 'issuable_template', + field_name: "issuable_template", selected: selected_template(issuable), project_path: ref_project.path, - namespace_path: ref_project.namespace.full_path - } + namespace_path: ref_project.namespace.full_path, + }, } dropdown_tag(title, options: options) do @@ -189,18 +189,18 @@ module IssuablesHelper output = [] output << "Opened #{time_ago_with_tooltip(issuable.created_at)} by ".html_safe - output << content_tag(:strong) do + output << content_tag(:strong) { author_output = link_to_member(project, issuable.author, size: 24, mobile_classes: "d-none d-sm-inline") author_output << link_to_member(project, issuable.author, size: 24, by_username: true, avatar: false, mobile_classes: "d-block d-sm-none") if status = user_status(issuable.author) - author_output << "#{status}".html_safe + author_output << status.to_s.html_safe end author_output - end + } - output << content_tag(:span, (issuable_first_contribution_icon if issuable.first_contribution?), class: 'has-tooltip prepend-left-4', title: _('1st contribution!')) + output << content_tag(:span, (issuable_first_contribution_icon if issuable.first_contribution?), class: "has-tooltip prepend-left-4", title: _("1st contribution!")) output << content_tag(:span, (issuable.task_status if issuable.tasks?), id: "task_status", class: "d-none d-sm-none d-md-inline-block prepend-left-8") output << content_tag(:span, (issuable.task_status_short if issuable.tasks?), id: "task_status_short", class: "d-md-none") @@ -211,11 +211,11 @@ module IssuablesHelper def issuable_labels_tooltip(labels, limit: 5) first, last = labels.partition.with_index { |_, i| i < limit } - if labels && labels.any? + if labels&.any? label_names = first.collect { |label| label.fetch(:title) } label_names << "and #{last.size} more" unless last.empty? - label_names.join(', ') + label_names.join(", ") else _("Labels") end @@ -223,7 +223,7 @@ module IssuablesHelper def issuables_state_counter_text(issuable_type, state, display_count) titles = { - opened: "Open" + opened: "Open", } state_title = titles[state] || state.to_s.humanize @@ -231,16 +231,16 @@ module IssuablesHelper if display_count count = issuables_count_for_state(issuable_type, state) - html << " " << content_tag(:span, number_with_delimiter(count), class: 'badge badge-pill') + html << " " << content_tag(:span, number_with_delimiter(count), class: "badge badge-pill") end html.html_safe end def issuable_first_contribution_icon - content_tag(:span, class: 'fa-stack') do - concat(icon('certificate', class: "fa-stack-2x")) - concat(content_tag(:strong, '1', class: 'fa-inverse fa-stack-1x')) + content_tag(:span, class: "fa-stack") do + concat(icon("certificate", class: "fa-stack-2x")) + concat(content_tag(:strong, "1", class: "fa-inverse fa-stack-1x")) end end @@ -267,20 +267,21 @@ module IssuablesHelper canDestroy: can?(current_user, :"destroy_#{issuable.to_ability_name}", issuable), issuableRef: issuable.to_reference, markdownPreviewPath: preview_markdown_path(parent), - markdownDocsPath: help_page_path('user/markdown'), + markdownDocsPath: help_page_path("user/markdown"), lockVersion: issuable.lock_version, issuableTemplates: issuable_templates(issuable), initialTitleHtml: markdown_field(issuable, :title), initialTitleText: issuable.title, initialDescriptionHtml: markdown_field(issuable, :description), initialDescriptionText: issuable.description, - initialTaskStatus: issuable.task_status + initialTaskStatus: issuable.task_status, } if parent.is_a?(Group) data[:groupPath] = parent.path else - data.merge!(projectPath: ref_project.path, projectNamespace: ref_project.namespace.full_path) + data[:projectPath] = ref_project.path + data[:projectNamespace] = ref_project.namespace.full_path end data.merge!(updated_at_by(issuable)) @@ -295,8 +296,8 @@ module IssuablesHelper updatedAt: issuable.last_edited_at.to_time.iso8601, updatedBy: { name: issuable.last_edited_by.name, - path: user_path(issuable.last_edited_by) - } + path: user_path(issuable.last_edited_by), + }, } end @@ -330,7 +331,7 @@ module IssuablesHelper end def issuable_button_visibility(issuable, closed) - return 'hidden' if issuable_button_hidden?(issuable, closed) + return "hidden" if issuable_button_hidden?(issuable, closed) end def issuable_button_hidden?(issuable, closed) @@ -345,9 +346,9 @@ module IssuablesHelper def issuable_close_reopen_button_method(issuable) case issuable when Issue - '' + "" when MergeRequest - 'put' + "put" end end @@ -366,7 +367,7 @@ module IssuablesHelper private def sidebar_gutter_collapsed? - cookies[:collapsed_gutter] == 'true' + cookies[:collapsed_gutter] == "true" end def issuable_templates(issuable) @@ -385,24 +386,24 @@ module IssuablesHelper def issuable_todo_button_data(issuable, is_collapsed) { - todo_text: _('Add todo'), - mark_text: _('Mark todo as done'), - todo_icon: sprite_icon('todo-add'), - mark_icon: sprite_icon('todo-done', css_class: 'todo-undone'), + todo_text: _("Add todo"), + mark_text: _("Mark todo as done"), + todo_icon: sprite_icon("todo-add"), + mark_icon: sprite_icon("todo-done", css_class: "todo-undone"), issuable_id: issuable[:id], issuable_type: issuable[:type], create_path: issuable[:create_todo_path], delete_path: issuable.dig(:current_user, :todo, :delete_path), - placement: is_collapsed ? 'left' : nil, - container: is_collapsed ? 'body' : nil, - boundary: 'viewport', - is_collapsed: is_collapsed + placement: is_collapsed ? "left" : nil, + container: is_collapsed ? "body" : nil, + boundary: "viewport", + is_collapsed: is_collapsed, } end def close_reopen_params(issuable, action) { - issuable.model_name.to_s.underscore => { state_event: action } + issuable.model_name.to_s.underscore => {state_event: action}, }.tap do |params| params[:format] = :json if issuable.is_a?(Issue) end @@ -425,7 +426,7 @@ module IssuablesHelper editable: issuable.dig(:current_user, :can_edit), currentUser: issuable[:current_user], rootPath: root_path, - fullPath: issuable[:project_full_path] + fullPath: issuable[:project_full_path], } end diff --git a/app/helpers/issues_helper.rb b/app/helpers/issues_helper.rb index 957ab06b0ca..b2e90612b9a 100644 --- a/app/helpers/issues_helper.rb +++ b/app/helpers/issues_helper.rb @@ -5,18 +5,18 @@ module IssuesHelper classes = ["issue"] classes << "closed" if issue.closed? classes << "today" if issue.today? - classes.join(' ') + classes.join(" ") end # Returns an OpenStruct object suitable for use by <tt>options_from_collection_for_select</tt> # to allow filtering issues by an unassigned User or Milestone def unassigned_filter # Milestone uses :title, Issue uses :name - OpenStruct.new(id: 0, title: 'None (backlog)', name: 'Unassigned') + OpenStruct.new(id: 0, title: "None (backlog)", name: "Unassigned") end def url_for_issue(issue_iid, project = @project, options = {}) - return '' if project.nil? + return "" if project.nil? url = if options[:internal] @@ -28,7 +28,7 @@ module IssuesHelper # Ensure we return a valid URL to prevent possible XSS. URI.parse(url).to_s rescue URI::InvalidURIError - '' + "" end def url_for_tracker_issue(issue_iid, project, options) @@ -51,20 +51,20 @@ module IssuesHelper def status_box_class(item) if item.try(:expired?) - 'status-box-expired' + "status-box-expired" elsif item.try(:merged?) - 'status-box-mr-merged' + "status-box-mr-merged" elsif item.closed? - 'status-box-mr-closed' + "status-box-mr-closed" elsif item.try(:upcoming?) - 'status-box-upcoming' + "status-box-upcoming" else - 'status-box-open' + "status-box-open" end end def issue_button_visibility(issue, closed) - return 'hidden' if issue_button_hidden?(issue, closed) + return "hidden" if issue_button_hidden?(issue, closed) end def issue_button_hidden?(issue, closed) @@ -72,15 +72,15 @@ module IssuesHelper end def confidential_icon(issue) - icon('eye-slash') if issue.confidential? + icon("eye-slash") if issue.confidential? end def award_user_list(awards, current_user, limit: 10) - names = awards.map do |award| - award.user == current_user ? 'You' : award.user.name - end + names = awards.map { |award| + award.user == current_user ? "You" : award.user.name + } - current_user_name = names.delete('You') + current_user_name = names.delete("You") names = names.insert(0, current_user_name).compact.first(limit) names << "#{awards.size - names.size} more." if awards.size > names.size @@ -99,7 +99,7 @@ module IssuesHelper end def awards_sort(awards) - awards.sort_by do |award, award_emojis| + awards.sort_by { |award, award_emojis| if award == "thumbsup" 0 elsif award == "thumbsdown" @@ -107,7 +107,7 @@ module IssuesHelper else 2 end - end.to_h + }.to_h end def link_to_discussions_to_resolve(merge_request, single_discussion = nil) @@ -115,13 +115,13 @@ module IssuesHelper link_text << "(discussion #{single_discussion.first_note.id})" if single_discussion path = if single_discussion - Gitlab::UrlBuilder.build(single_discussion.first_note) - else - project = merge_request.project - project_merge_request_path(project, merge_request) - end + Gitlab::UrlBuilder.build(single_discussion.first_note) + else + project = merge_request.project + project_merge_request_path(project, merge_request) + end - link_to link_text.join(' '), path + link_to link_text.join(" "), path end def show_new_issue_link?(project) diff --git a/app/helpers/labels_helper.rb b/app/helpers/labels_helper.rb index bd53add80ca..1b9ff1bd095 100644 --- a/app/helpers/labels_helper.rb +++ b/app/helpers/labels_helper.rb @@ -54,13 +54,13 @@ module LabelsHelper case subject when Group send("#{type.to_s.pluralize}_group_path", # rubocop:disable GitlabSecurity/PublicSend - subject, - label_name: [label.name]) + subject, + label_name: [label.name]) when Project send("namespace_project_#{type.to_s.pluralize}_path", # rubocop:disable GitlabSecurity/PublicSend - subject.namespace, - subject, - label_name: [label.name]) + subject.namespace, + subject, + label_name: [label.name]) end end @@ -78,7 +78,7 @@ module LabelsHelper end end - def render_colored_label(label, label_suffix = '', tooltip: true) + def render_colored_label(label, label_suffix = "", tooltip: true) text_color = text_color_for_bg(label.color) # Intentionally not using content_tag here so that this method can be called @@ -93,27 +93,27 @@ module LabelsHelper def suggested_colors [ - '#0033CC', - '#428BCA', - '#44AD8E', - '#A8D695', - '#5CB85C', - '#69D100', - '#004E00', - '#34495E', - '#7F8C8D', - '#A295D6', - '#5843AD', - '#8E44AD', - '#FFECDB', - '#AD4363', - '#D10069', - '#CC0033', - '#FF0000', - '#D9534F', - '#D1D100', - '#F0AD4E', - '#AD8D43' + "#0033CC", + "#428BCA", + "#44AD8E", + "#A8D695", + "#5CB85C", + "#69D100", + "#004E00", + "#34495E", + "#7F8C8D", + "#A295D6", + "#5843AD", + "#8E44AD", + "#FFECDB", + "#AD4363", + "#D10069", + "#CC0033", + "#FF0000", + "#D9534F", + "#D1D100", + "#F0AD4E", + "#AD8D43", ] end @@ -125,9 +125,9 @@ module LabelsHelper end if (r + g + b) > 500 - '#333333' + "#333333" else - '#FFFFFF' + "#FFFFFF" end end @@ -159,70 +159,70 @@ module LabelsHelper end def label_subscription_status(label, project) - return 'group-level' if label.subscribed?(current_user) - return 'project-level' if label.subscribed?(current_user, project) + return "group-level" if label.subscribed?(current_user) + return "project-level" if label.subscribed?(current_user, project) - 'unsubscribed' + "unsubscribed" end def toggle_subscription_label_path(label, project) return toggle_subscription_group_label_path(label.group, label) unless project case label_subscription_status(label, project) - when 'group-level' then toggle_subscription_group_label_path(label.group, label) - when 'project-level' then toggle_subscription_project_label_path(project, label) - when 'unsubscribed' then toggle_subscription_project_label_path(project, label) + when "group-level" then toggle_subscription_group_label_path(label.group, label) + when "project-level" then toggle_subscription_project_label_path(project, label) + when "unsubscribed" then toggle_subscription_project_label_path(project, label) end end def label_subscription_toggle_button_text(label, project = nil) - label.subscribed?(current_user, project) ? 'Unsubscribe' : 'Subscribe' + label.subscribed?(current_user, project) ? "Unsubscribe" : "Subscribe" end def label_deletion_confirm_text(label) case label - when GroupLabel then 'Remove this label? This will affect all projects within the group. Are you sure?' - when ProjectLabel then 'Remove this label? Are you sure?' + when GroupLabel then "Remove this label? This will affect all projects within the group. Are you sure?" + when ProjectLabel then "Remove this label? Are you sure?" end end def create_label_title(subject) case subject when Group - _('Create group label') + _("Create group label") when Project - _('Create project label') + _("Create project label") else - _('Create new label') + _("Create new label") end end def manage_labels_title(subject) case subject when Group - _('Manage group labels') + _("Manage group labels") when Project - _('Manage project labels') + _("Manage project labels") else - _('Manage labels') + _("Manage labels") end end def view_labels_title(subject) case subject when Group - _('View group labels') + _("View group labels") when Project - _('View project labels') + _("View project labels") else - _('View labels') + _("View labels") end end def label_status_tooltip(label, status) - type = label.is_a?(ProjectLabel) ? 'project' : 'group' - level = status.unsubscribed? ? type : status.sub('-level', '') - action = status.unsubscribed? ? 'Subscribe' : 'Unsubscribe' + type = label.is_a?(ProjectLabel) ? "project" : "group" + level = status.unsubscribed? ? type : status.sub("-level", "") + action = status.unsubscribed? ? "Subscribe" : "Unsubscribe" "#{action} at #{level} level" end diff --git a/app/helpers/lazy_image_tag_helper.rb b/app/helpers/lazy_image_tag_helper.rb index ac987a04895..30b9e7d7b2a 100644 --- a/app/helpers/lazy_image_tag_helper.rb +++ b/app/helpers/lazy_image_tag_helper.rb @@ -17,7 +17,7 @@ module LazyImageTagHelper klass_opts = Array.wrap(options[:class]) klass_opts << "lazy" - options[:class] = klass_opts.join(' ') + options[:class] = klass_opts.join(" ") source = placeholder_image end diff --git a/app/helpers/markup_helper.rb b/app/helpers/markup_helper.rb index 66f4b7b3f30..7eb193bd087 100644 --- a/app/helpers/markup_helper.rb +++ b/app/helpers/markup_helper.rb @@ -1,6 +1,6 @@ # frozen_string_literal: true -require 'nokogiri' +require "nokogiri" module MarkupHelper include ActionView::Helpers::TagHelper @@ -24,7 +24,7 @@ module MarkupHelper # Use this in places where you would normally use link_to(gfm(...), ...). def link_to_markdown(body, url, html_options = {}) - return '' if body.blank? + return "" if body.blank? link_to_html(markdown(body, pipeline: :single_line), url, html_options) end @@ -45,7 +45,7 @@ module MarkupHelper def link_to_html(redacted, url, html_options = {}) fragment = Nokogiri::HTML::DocumentFragment.parse(redacted) - if fragment.children.size == 1 && fragment.children[0].name == 'a' + if fragment.children.size == 1 && fragment.children[0].name == "a" # Fragment has only one node, and it's a link generated by `gfm`. # Replace it with our requested link. text = fragment.children[0].text @@ -62,7 +62,7 @@ module MarkupHelper # Add any custom CSS classes to the GFM-generated reference links if html_options[:class] - fragment.css('a.gfm').add_class(html_options[:class]) + fragment.css("a.gfm").add_class(html_options[:class]) end fragment.to_html.html_safe @@ -76,14 +76,14 @@ module MarkupHelper md = markdown_field(object, attribute, options) return nil unless md.present? - tags = %w(a gl-emoji b pre code p span) - tags << 'img' if options[:allow_images] + tags = %w[a gl-emoji b pre code p span] + tags << "img" if options[:allow_images] text = truncate_visible(md, max_chars || md.length) text = sanitize( text, tags: tags, - attributes: Rails::Html::WhiteListSanitizer.allowed_attributes + ['style', 'data-src', 'data-name', 'data-unicode-version'] + attributes: Rails::Html::WhiteListSanitizer.allowed_attributes + ["style", "data-src", "data-name", "data-unicode-version"] ) # since <img> tags are stripped, this can leave empty <a> tags hanging around @@ -92,7 +92,7 @@ module MarkupHelper end def markdown(text, context = {}) - return '' unless text.present? + return "" unless text.present? context[:project] ||= @project context[:group] ||= @group @@ -105,7 +105,7 @@ module MarkupHelper object = object.for_display if object.respond_to?(:for_display) redacted_field_html = object.try(:"redacted_#{field}_html") - return '' unless object.present? + return "" unless object.present? return redacted_field_html if redacted_field_html html = Banzai.render_field(object, field, context) @@ -122,7 +122,7 @@ module MarkupHelper def render_wiki_content(wiki_page, context = {}) text = wiki_page.content - return '' unless text.present? + return "" unless text.present? context.merge!( pipeline: :wiki, @@ -146,14 +146,14 @@ module MarkupHelper end def markup_unsafe(file_name, text, context = {}) - return '' unless text.present? + return "" unless text.present? if gitlab_markdown?(file_name) markdown_unsafe(text, context) elsif asciidoc?(file_name) asciidoc_unsafe(text, context) elsif plain?(file_name) - content_tag :pre, class: 'plain-readme' do + content_tag :pre, class: "plain-readme" do text end else @@ -181,7 +181,7 @@ module MarkupHelper if entity.respond_to?(:to_reference) entity.to_reference(project, full: true) else - '' + "" end end @@ -228,7 +228,7 @@ module MarkupHelper def truncate_if_block(node, truncated) return true if truncated - if node.element? && (node.description&.block? || node.matches?('pre > code > .line')) + if node.element? && (node.description&.block? || node.matches?("pre > code > .line")) node.inner_html = "#{node.inner_html}..." if node.next_sibling true else @@ -237,9 +237,9 @@ module MarkupHelper end def strip_empty_link_tags(text) - scrubber = Loofah::Scrubber.new do |node| - node.remove if node.name == 'a' && node.content.blank? - end + scrubber = Loofah::Scrubber.new { |node| + node.remove if node.name == "a" && node.content.blank? + } # Use `Loofah` directly instead of `sanitize` # as we still use the `rails-deprecated_sanitizer` gem @@ -247,14 +247,14 @@ module MarkupHelper end def markdown_toolbar_button(options = {}) - data = options[:data].merge({ container: 'body' }) + data = options[:data].merge({container: "body"}) content_tag :button, - type: 'button', - class: 'toolbar-btn js-md has-tooltip', + type: "button", + class: "toolbar-btn js-md has-tooltip", tabindex: -1, data: data, title: options[:title], - aria: { label: options[:title] } do + aria: {label: options[:title]} do sprite_icon(options[:icon]) end end @@ -272,15 +272,15 @@ module MarkupHelper end def prepare_for_rendering(html, context = {}) - return '' unless html.present? + return "" unless html.present? context.merge!( current_user: (current_user if defined?(current_user)), # RelativeLinkFilter - commit: @commit, - project_wiki: @project_wiki, - ref: @ref, + commit: @commit, + project_wiki: @project_wiki, + ref: @ref, requested_path: @path ) diff --git a/app/helpers/mattermost_helper.rb b/app/helpers/mattermost_helper.rb index b211fe5076a..6d400971ae1 100644 --- a/app/helpers/mattermost_helper.rb +++ b/app/helpers/mattermost_helper.rb @@ -3,7 +3,7 @@ module MattermostHelper def mattermost_teams_options(teams) teams.map do |team| - [team['display_name'] || team['name'], team['id']] + [team["display_name"] || team["name"], team["id"]] end end end diff --git a/app/helpers/members_helper.rb b/app/helpers/members_helper.rb index 11d5591d509..90ae44f4205 100644 --- a/app/helpers/members_helper.rb +++ b/app/helpers/members_helper.rb @@ -3,12 +3,12 @@ module MembersHelper def remove_member_message(member, user: nil) user = current_user if defined?(current_user) - text = 'Are you sure you want to' + text = "Are you sure you want to" action = if member.request? if member.user == user - 'withdraw your access request for' + "withdraw your access request for" else "deny #{member.user.name}'s request to join" end @@ -22,7 +22,7 @@ module MembersHelper end def remove_member_title(member) - action = member.request? ? 'Deny access request' : 'Remove user' + action = member.request? ? "Deny access request" : "Remove user" "#{action} from #{source_text(member)}" end @@ -42,8 +42,8 @@ module MembersHelper def source_text(member) type = member.real_source_type.humanize(capitalize: false) - return type if member.request? || member.invite? || type != 'group' + return type if member.request? || member.invite? || type != "group" - 'group and any subresources' + "group and any subresources" end end diff --git a/app/helpers/merge_requests_helper.rb b/app/helpers/merge_requests_helper.rb index 23d7aa427bb..a921ed566d5 100644 --- a/app/helpers/merge_requests_helper.rb +++ b/app/helpers/merge_requests_helper.rb @@ -15,8 +15,8 @@ module MergeRequestsHelper source_project_id: event.project.id, target_project_id: target_project.id, source_branch: event.branch_name, - target_branch: target_project.repository.root_ref - } + target_branch: target_project.repository.root_ref, + }, } end @@ -24,7 +24,7 @@ module MergeRequestsHelper classes = ["merge-request"] classes << "closed" if mr.closed? classes << "merged" if mr.merged? - classes.join(' ') + classes.join(" ") end def ci_build_details_path(merge_request) @@ -34,7 +34,7 @@ module MergeRequestsHelper parsed_url = URI.parse(build_url) unless parsed_url.userinfo.blank? - parsed_url.userinfo = '' + parsed_url.userinfo = "" end parsed_url.to_s @@ -55,7 +55,7 @@ module MergeRequestsHelper source_project_id: merge_request.source_project_id, target_project_id: merge_request.target_project_id, source_branch: merge_request.source_branch, - target_branch: merge_request.target_branch + target_branch: merge_request.target_branch, }, change_branches: true ) @@ -80,7 +80,7 @@ module MergeRequestsHelper end def merge_request_button_visibility(merge_request, closed) - return 'hidden' if merge_request_button_hidden?(merge_request, closed) + return "hidden" if merge_request_button_hidden?(merge_request, closed) end def merge_request_button_hidden?(merge_request, closed) @@ -106,7 +106,7 @@ module MergeRequestsHelper merge_when_pipeline_succeeds: true, should_remove_source_branch: true, sha: merge_request.diff_head_sha, - squash: merge_request.squash + squash: merge_request.squash, } end @@ -114,12 +114,12 @@ module MergeRequestsHelper data_attrs = { action: tab.to_s, target: "##{tab}", - toggle: options.fetch(:force_link, false) ? '' : 'tabvue' + toggle: options.fetch(:force_link, false) ? "" : "tabvue", } url = case tab when :show - data_attrs[:target] = '#notes' + data_attrs[:target] = "#notes" method(:project_merge_request_path) when :commits method(:commits_project_merge_request_path) @@ -129,7 +129,7 @@ module MergeRequestsHelper method(:diffs_project_merge_request_path) else raise "Cannot create tab #{tab}." - end + end link_to(url[merge_request.project, merge_request], data: data_attrs, &block) end @@ -138,12 +138,12 @@ module MergeRequestsHelper return if merge_request.can_allow_collaboration?(current_user) minimum_visibility = [merge_request.target_project.visibility_level, - merge_request.source_project.visibility_level].min + merge_request.source_project.visibility_level,].min if minimum_visibility < Gitlab::VisibilityLevel::INTERNAL - _('Not available for private projects') + _("Not available for private projects") elsif ProtectedBranch.protected?(merge_request.source_project, merge_request.source_branch) - _('Not available for protected branches') + _("Not available for protected branches") end end diff --git a/app/helpers/milestones_helper.rb b/app/helpers/milestones_helper.rb index 50aec83b867..7ce0f65478a 100644 --- a/app/helpers/milestones_helper.rb +++ b/app/helpers/milestones_helper.rb @@ -25,7 +25,7 @@ module MilestonesHelper end def milestones_browse_issuables_path(milestone, state: nil, type:) - opts = { milestone_title: milestone.title, state: state } + opts = {milestone_title: milestone.title, state: state} if @project polymorphic_path([@project.namespace.becomes(Namespace), @project, type], opts) @@ -59,9 +59,9 @@ module MilestonesHelper counts = milestones.reorder(nil).group(:state).count { - opened: counts['active'] || 0, - closed: counts['closed'] || 0, - all: counts.values.sum || 0 + opened: counts["active"] || 0, + closed: counts["closed"] || 0, + all: counts.values.sum || 0, } end # rubocop: enable CodeReuse/ActiveRecord @@ -71,9 +71,9 @@ module MilestonesHelper # Could be refactored to be simpler but that may make it harder to read def milestone_class_for_state(param, check, match_blank_param = false) if match_blank_param - 'active' if param.blank? || param == check + "active" if param.blank? || param == check elsif param == check - 'active' + "active" else check end @@ -84,21 +84,21 @@ module MilestonesHelper if has_issues [ - _('Progress'), - _("%{percent}%% complete") % { percent: milestone.percent_complete(current_user) } - ].join('<br />') + _("Progress"), + _("%{percent}%% complete") % {percent: milestone.percent_complete(current_user)}, + ].join("<br />") else - _('Progress') + _("Progress") end end def milestone_progress_bar(milestone) options = { - class: 'progress-bar bg-success', - style: "width: #{milestone.percent_complete(current_user)}%;" + class: "progress-bar bg-success", + style: "width: #{milestone.percent_complete(current_user)}%;", } - content_tag :div, class: 'progress' do + content_tag :div, class: "progress" do content_tag :div, nil, options end end @@ -120,16 +120,16 @@ module MilestonesHelper if date time_ago = time_ago_in_words(date).sub("about ", "") state = if date.past? - "ago" - else - "remaining" - end + "ago" + else + "remaining" + end content = [ title, "<br />", date.to_s(:medium), - "(#{time_ago} #{state})" + "(#{time_ago} #{state})", ].join(" ") content.html_safe @@ -148,7 +148,7 @@ module MilestonesHelper content << n_("1 open issue", "%d open issues", issues["opened"]) % issues["opened"] if issues["opened"] content << n_("1 closed issue", "%d closed issues", issues["closed"]) % issues["closed"] if issues["closed"] - content.join('<br />').html_safe + content.join("<br />").html_safe end def milestone_merge_requests_tooltip_text(milestone) @@ -162,14 +162,14 @@ module MilestonesHelper content << n_("1 closed merge request", "%d closed merge requests", merge_requests.closed.count) % merge_requests.closed.count if merge_requests.closed.any? content << n_("1 merged merge request", "%d merged merge requests", merge_requests.merged.count) % merge_requests.merged.count if merge_requests.merged.any? - content.join('<br />').html_safe + content.join("<br />").html_safe end def milestone_tooltip_due_date(milestone) if milestone.due_date "#{milestone.due_date.to_s(:medium)} (#{remaining_days_in_words(milestone.due_date, milestone.start_date)})" else - _('Milestone') + _("Milestone") end end @@ -234,9 +234,9 @@ module MilestonesHelper def group_or_project_milestone_path(milestone) params = if milestone.group_milestone? - { milestone: { title: milestone.title } } + {milestone: {title: milestone.title}} else - { title: milestone.title } + {title: milestone.title} end milestone_path(milestone.milestone, params) diff --git a/app/helpers/mirror_helper.rb b/app/helpers/mirror_helper.rb index 65c7cd82832..4e26b9a5e5f 100644 --- a/app/helpers/mirror_helper.rb +++ b/app/helpers/mirror_helper.rb @@ -4,7 +4,7 @@ module MirrorHelper def mirrors_form_data_attributes { project_mirror_ssh_endpoint: ssh_host_keys_project_mirror_path(@project, :json), - project_mirror_endpoint: project_mirror_path(@project, :json) + project_mirror_endpoint: project_mirror_path(@project, :json), } end end diff --git a/app/helpers/namespaces_helper.rb b/app/helpers/namespaces_helper.rb index ea3bcfc791a..44b58b702d9 100644 --- a/app/helpers/namespaces_helper.rb +++ b/app/helpers/namespaces_helper.rb @@ -11,10 +11,10 @@ module NamespacesHelper selected_id = selected unless extra_group.nil? || extra_group.is_a?(Group) - extra_group = Group.find(extra_group) if Namespace.find(extra_group).kind == 'group' + extra_group = Group.find(extra_group) if Namespace.find(extra_group).kind == "group" end - if extra_group && extra_group.is_a?(Group) + if extra_group&.is_a?(Group) extra_group = dedup_extra_group(extra_group) if Ability.allowed?(current_user, :read_group, extra_group) @@ -28,10 +28,10 @@ module NamespacesHelper end options = [] - options << options_for_group(groups, display_path: display_path, type: 'group') + options << options_for_group(groups, display_path: display_path, type: "group") unless groups_only - options << options_for_group(users, display_path: display_path, type: 'user') + options << options_for_group(users, display_path: display_path, type: "user") if selected == :current_user && current_user.namespace selected_id = current_user.namespace.id @@ -66,17 +66,17 @@ module NamespacesHelper def options_for_group(namespaces, display_path:, type:) group_label = type.pluralize - elements = namespaces.sort_by(&:human_name).map! do |n| + elements = namespaces.sort_by(&:human_name).map! { |n| [display_path ? n.full_path : n.human_name, n.id, data: { options_parent: group_label, visibility_level: n.visibility_level_value, visibility: n.visibility, name: n.name, - show_path: (type == 'group') ? group_path(n) : user_path(n), - edit_path: (type == 'group') ? edit_group_path(n) : nil - }] - end + show_path: type == "group" ? group_path(n) : user_path(n), + edit_path: type == "group" ? edit_group_path(n) : nil, + },] + } [group_label.camelize, elements] end diff --git a/app/helpers/nav_helper.rb b/app/helpers/nav_helper.rb index 05da5ebdb22..f30e8c8c2c0 100644 --- a/app/helpers/nav_helper.rb +++ b/app/helpers/nav_helper.rb @@ -11,9 +11,9 @@ module NavHelper def page_with_sidebar_class class_name = page_gutter_class - class_name << 'page-with-contextual-sidebar' if defined?(@left_sidebar) && @left_sidebar - class_name << 'page-with-icon-sidebar' if collapsed_sidebar? && @left_sidebar - class_name -= ['right-sidebar-expanded'] if defined?(@right_sidebar) && !@right_sidebar + class_name << "page-with-contextual-sidebar" if defined?(@left_sidebar) && @left_sidebar + class_name << "page-with-icon-sidebar" if collapsed_sidebar? && @left_sidebar + class_name -= ["right-sidebar-expanded"] if defined?(@right_sidebar) && !@right_sidebar class_name end @@ -21,14 +21,14 @@ module NavHelper def page_gutter_class if page_has_markdown? - if cookies[:collapsed_gutter] == 'true' + if cookies[:collapsed_gutter] == "true" %w[page-gutter right-sidebar-collapsed] else %w[page-gutter right-sidebar-expanded] end - elsif current_path?('jobs#show') + elsif current_path?("jobs#show") %w[page-gutter build-sidebar right-sidebar-expanded] - elsif current_controller?('wikis') && current_action?('show', 'create', 'edit', 'update', 'history', 'git_access', 'destroy') + elsif current_controller?("wikis") && current_action?("show", "create", "edit", "update", "history", "git_access", "destroy") %w[page-gutter wiki-sidebar right-sidebar-expanded] else [] @@ -41,8 +41,8 @@ module NavHelper def user_dropdown_class class_names = [] - class_names << 'header-user-dropdown-toggle' - class_names << 'impersonated-user' if session[:impersonator_id] + class_names << "header-user-dropdown-toggle" + class_names << "impersonated-user" if session[:impersonator_id] class_names end @@ -52,20 +52,20 @@ module NavHelper end def page_has_markdown? - current_path?('merge_requests#show') || - current_path?('projects/merge_requests/conflicts#show') || - current_path?('issues#show') || - current_path?('milestones#show') + current_path?("merge_requests#show") || + current_path?("projects/merge_requests/conflicts#show") || + current_path?("issues#show") || + current_path?("milestones#show") end private def get_header_links links = if current_user - [:user_dropdown] - else - [:sign_in] - end + [:user_dropdown] + else + [:sign_in] + end if can?(current_user, :read_cross_project) links += [:issues, :merge_requests, :todos] if current_user.present? diff --git a/app/helpers/notes_helper.rb b/app/helpers/notes_helper.rb index aaf38cbfe70..7efeb19ddb0 100644 --- a/app/helpers/notes_helper.rb +++ b/app/helpers/notes_helper.rb @@ -17,7 +17,7 @@ module NotesHelper id: noteable.id, class: noteable.class.name, resources: noteable.class.table_name, - project_id: noteable.project.id + project_id: noteable.project.id, }.to_json end @@ -32,7 +32,7 @@ module NotesHelper data = { line_code: line_code, - line_type: line_type + line_type: line_type, } if @use_legacy_diff_notes @@ -48,12 +48,12 @@ module NotesHelper def add_diff_note_button(line_code, position, line_type) return if @diff_notes_disabled - button_tag '', - class: 'add-diff-note js-add-diff-note-button', - type: 'submit', name: 'button', + button_tag "", + class: "add-diff-note js-add-diff-note-button", + type: "submit", name: "button", data: diff_view_line_data(line_code, position, line_type), - title: 'Add a comment to this line' do - icon('comment-o') + title: "Add a comment to this line" do + icon("comment-o") end end @@ -63,11 +63,11 @@ module NotesHelper data = { discussion_id: discussion.reply_id, discussion_project_id: discussion.project&.id, - line_type: line_type + line_type: line_type, } - button_tag 'Reply...', class: 'btn btn-text-field js-discussion-reply-button', - data: data, title: 'Add a reply' + button_tag "Reply...", class: "btn btn-text-field js-discussion-reply-button", + data: data, title: "Add a reply" end def note_max_access_for_user(note) @@ -95,7 +95,8 @@ module NotesHelper if @snippet.is_a?(PersonalSnippet) snippet_notes_path(@snippet, params) else - params.merge!(target_id: @noteable.id, target_type: @noteable.class.name.underscore) + params[:target_id] = @noteable.id + params[:target_type] = @noteable.class.name.underscore project_noteable_notes_path(@project, params) end @@ -152,8 +153,8 @@ module NotesHelper mergeRequests: autocomplete, epics: autocomplete, milestones: autocomplete, - labels: autocomplete - } + labels: autocomplete, + }, } end @@ -168,20 +169,20 @@ module NotesHelper def notes_data(issuable) { discussionsPath: discussions_path(issuable), - registerPath: new_session_path(:user, redirect_to_referer: 'yes', anchor: 'register-pane'), - newSessionPath: new_session_path(:user, redirect_to_referer: 'yes'), - markdownDocsPath: help_page_path('user/markdown'), - quickActionsDocsPath: help_page_path('user/project/quick_actions'), + registerPath: new_session_path(:user, redirect_to_referer: "yes", anchor: "register-pane"), + newSessionPath: new_session_path(:user, redirect_to_referer: "yes"), + markdownDocsPath: help_page_path("user/markdown"), + quickActionsDocsPath: help_page_path("user/project/quick_actions"), closePath: close_issuable_path(issuable), reopenPath: reopen_issuable_path(issuable), notesPath: notes_url, totalNotes: issuable.discussions.length, - lastFetchedAt: Time.now.to_i + lastFetchedAt: Time.now.to_i, } end def discussion_resolved_intro(discussion) - discussion.resolved_by_push? ? 'Automatically resolved' : 'Resolved' + discussion.resolved_by_push? ? "Automatically resolved" : "Resolved" end def rendered_for_merge_request? @@ -189,6 +190,6 @@ module NotesHelper end def serialize_notes? - rendered_for_merge_request? || params['html'].nil? + rendered_for_merge_request? || params["html"].nil? end end diff --git a/app/helpers/notifications_helper.rb b/app/helpers/notifications_helper.rb index 5318ab4ddef..400d83c8790 100644 --- a/app/helpers/notifications_helper.rb +++ b/app/helpers/notifications_helper.rb @@ -6,15 +6,15 @@ module NotificationsHelper def notification_icon_class(level) case level.to_sym when :disabled - 'microphone-slash' + "microphone-slash" when :participating - 'volume-up' + "volume-up" when :watch - 'eye' + "eye" when :mention - 'at' + "at" when :global - 'globe' + "globe" end end @@ -26,14 +26,14 @@ module NotificationsHelper # Can be anything in `NotificationSetting.level: case level.to_sym when :participating - s_('NotificationLevel|Participate') + s_("NotificationLevel|Participate") when :mention - s_('NotificationLevel|On mention') + s_("NotificationLevel|On mention") else - N_('NotificationLevel|Global') - N_('NotificationLevel|Watch') - N_('NotificationLevel|Disabled') - N_('NotificationLevel|Custom') + N_("NotificationLevel|Global") + N_("NotificationLevel|Watch") + N_("NotificationLevel|Disabled") + N_("NotificationLevel|Custom") level = "NotificationLevel|#{level.to_s.humanize}" s_(level) end @@ -42,17 +42,17 @@ module NotificationsHelper def notification_description(level) case level.to_sym when :participating - _('You will only receive notifications for threads you have participated in') + _("You will only receive notifications for threads you have participated in") when :mention - _('You will receive notifications only for comments in which you were @mentioned') + _("You will receive notifications only for comments in which you were @mentioned") when :watch - _('You will receive notifications for any activity') + _("You will receive notifications for any activity") when :disabled - _('You will not get any notifications via email') + _("You will not get any notifications via email") when :global - _('Use your global notification setting') + _("Use your global notification setting") when :custom - _('You will only receive notifications for the events you choose') + _("You will only receive notifications for the events you choose") end end @@ -61,13 +61,13 @@ module NotificationsHelper data = { notification_level: level, - notification_title: title + notification_title: title, } content_tag(:li, role: "menuitem") do - link_to '#', class: "update-notification #{('is-active' if setting.level == level)}", data: data do - link_output = content_tag(:strong, title, class: 'dropdown-menu-inner-title') - link_output << content_tag(:span, notification_description(level), class: 'dropdown-menu-inner-content') + link_to "#", class: "update-notification #{("is-active" if setting.level == level)}", data: data do + link_output = content_tag(:strong, title, class: "dropdown-menu-inner-title") + link_output << content_tag(:span, notification_description(level), class: "dropdown-menu-inner-content") end end end @@ -88,7 +88,7 @@ module NotificationsHelper # All values from NotificationSetting.email_events case event when :success_pipeline - s_('NotificationEvent|Successful pipeline') + s_("NotificationEvent|Successful pipeline") else s_(event.to_s.humanize) end diff --git a/app/helpers/numbers_helper.rb b/app/helpers/numbers_helper.rb index 3c0b11c4d32..862cc032e5a 100644 --- a/app/helpers/numbers_helper.rb +++ b/app/helpers/numbers_helper.rb @@ -6,7 +6,7 @@ module NumbersHelper limit = options.fetch(:limit, 1000).to_i count = resource.limit(limit + 1).count(:all) if count > limit - number_with_delimiter(count - 1, options) + '+' + number_with_delimiter(count - 1, options) + "+" else number_with_delimiter(count, options) end diff --git a/app/helpers/page_layout_helper.rb b/app/helpers/page_layout_helper.rb index 5038dcf9746..bb57ad65050 100644 --- a/app/helpers/page_layout_helper.rb +++ b/app/helpers/page_layout_helper.rb @@ -45,7 +45,7 @@ module PageLayoutHelper end def page_image - default = image_url('gitlab_logo.png') + default = image_url("gitlab_logo.png") subject = @project || @user || @group @@ -59,7 +59,7 @@ module PageLayoutHelper # # Raises ArgumentError if given more than two attributes def page_card_attributes(map = {}) - raise ArgumentError, 'cannot provide more than two attributes' if map.length > 2 + raise ArgumentError, "cannot provide more than two attributes" if map.length > 2 @page_card_attributes ||= {} @page_card_attributes = map.reject { |_, v| v.blank? } if map.present? @@ -127,6 +127,6 @@ module PageLayoutHelper css_class << "container-blank" end - css_class.join(' ') + css_class.join(" ") end end diff --git a/app/helpers/pagination_helper.rb b/app/helpers/pagination_helper.rb index d05153c9d4b..8586bfdb700 100644 --- a/app/helpers/pagination_helper.rb +++ b/app/helpers/pagination_helper.rb @@ -11,13 +11,13 @@ module PaginationHelper def paginate_without_count(collection) render( - 'kaminari/gitlab/without_count', + "kaminari/gitlab/without_count", previous_path: path_to_prev_page(collection), next_path: path_to_next_page(collection) ) end def paginate_with_count(collection, remote: nil) - paginate(collection, remote: remote, theme: 'gitlab') + paginate(collection, remote: remote, theme: "gitlab") end end diff --git a/app/helpers/pipeline_schedules_helper.rb b/app/helpers/pipeline_schedules_helper.rb index 0e166106b32..6d2dccfd38a 100644 --- a/app/helpers/pipeline_schedules_helper.rb +++ b/app/helpers/pipeline_schedules_helper.rb @@ -6,7 +6,7 @@ module PipelineSchedulesHelper { name: timezone.name, offset: timezone.now.utc_offset, - identifier: timezone.tzinfo.identifier + identifier: timezone.tzinfo.identifier, } end end diff --git a/app/helpers/preferences_helper.rb b/app/helpers/preferences_helper.rb index eed529f93db..7890cd0ab64 100644 --- a/app/helpers/preferences_helper.rb +++ b/app/helpers/preferences_helper.rb @@ -4,22 +4,22 @@ module PreferencesHelper def layout_choices [ - ['Fixed', :fixed], - ['Fluid', :fluid] + ["Fixed", :fixed], + ["Fluid", :fluid], ] end # Maps `dashboard` values to more user-friendly option text DASHBOARD_CHOICES = { projects: _("Your Projects (default)"), - stars: _("Starred Projects"), + stars: _("Starred Projects"), project_activity: _("Your Projects' Activity"), starred_project_activity: _("Starred Projects' Activity"), groups: _("Your Groups"), todos: _("Your Todos"), issues: _("Assigned Issues"), merge_requests: _("Assigned Merge Requests"), - operations: _("Operations Dashboard") + operations: _("Operations Dashboard"), }.with_indifferent_access.freeze # Returns an Array usable by a select field for more user-friendly option text @@ -37,21 +37,21 @@ module PreferencesHelper def project_view_choices [ - ['Files and Readme (default)', :files], - ['Activity', :activity], - ['Readme', :readme] + ["Files and Readme (default)", :files], + ["Activity", :activity], + ["Readme", :readme], ] end def first_day_of_week_choices [ - [_('Sunday'), 0], - [_('Monday'), 1] + [_("Sunday"), 0], + [_("Monday"), 1], ] end def first_day_of_week_choices_with_default - first_day_of_week_choices.unshift([_('System default (%{default})') % { default: default_first_day_of_week }, nil]) + first_day_of_week_choices.unshift([_("System default (%{default})") % {default: default_first_day_of_week}, nil]) end def user_application_theme @@ -79,7 +79,7 @@ module PreferencesHelper # List of dashboard choice to be excluded from CE. # EE would override this. def excluded_dashboard_choices - ['operations'] + ["operations"] end def default_first_day_of_week diff --git a/app/helpers/profiles_helper.rb b/app/helpers/profiles_helper.rb index 5a42e581867..6451c29cffc 100644 --- a/app/helpers/profiles_helper.rb +++ b/app/helpers/profiles_helper.rb @@ -6,8 +6,8 @@ module ProfilesHelper verified_emails = user.verified_emails - [private_email] [ - [s_("Profiles|Use a private email - %{email}").html_safe % { email: private_email }, Gitlab::PrivateCommitEmail::TOKEN], - *verified_emails + [s_("Profiles|Use a private email - %{email}").html_safe % {email: private_email}, Gitlab::PrivateCommitEmail::TOKEN], + *verified_emails, ] end @@ -21,12 +21,12 @@ module ProfilesHelper if user_synced_attributes_metadata.provider Gitlab::Auth::OAuth::Provider.label_for(user_synced_attributes_metadata.provider) else - 'LDAP' + "LDAP" end end end def user_profile? - params[:controller] == 'users' + params[:controller] == "users" end end diff --git a/app/helpers/projects/error_tracking_helper.rb b/app/helpers/projects/error_tracking_helper.rb index 6daf2e21ca2..20f0a3930c8 100644 --- a/app/helpers/projects/error_tracking_helper.rb +++ b/app/helpers/projects/error_tracking_helper.rb @@ -5,11 +5,11 @@ module Projects::ErrorTrackingHelper error_tracking_enabled = !!project.error_tracking_setting&.enabled? { - 'index-path' => project_error_tracking_index_path(project, - format: :json), - 'enable-error-tracking-link' => project_settings_operations_path(project), - 'error-tracking-enabled' => error_tracking_enabled.to_s, - 'illustration-path' => image_path('illustrations/cluster_popover.svg') + "index-path" => project_error_tracking_index_path(project, + format: :json), + "enable-error-tracking-link" => project_settings_operations_path(project), + "error-tracking-enabled" => error_tracking_enabled.to_s, + "illustration-path" => image_path("illustrations/cluster_popover.svg"), } end end diff --git a/app/helpers/projects_helper.rb b/app/helpers/projects_helper.rb index c400302cda3..0fc31cab03a 100644 --- a/app/helpers/projects_helper.rb +++ b/app/helpers/projects_helper.rb @@ -3,10 +3,10 @@ module ProjectsHelper def link_to_project(project) link_to namespace_project_path(namespace_id: project.namespace, id: project), title: h(project.name) do - title = content_tag(:span, project.name, class: 'project-name') + title = content_tag(:span, project.name, class: "project-name") if project.namespace - namespace = content_tag(:span, "#{project.namespace.human_name} / ", class: 'namespace-name') + namespace = content_tag(:span, "#{project.namespace.human_name} / ", class: "namespace-name") title = namespace + title end @@ -15,7 +15,7 @@ module ProjectsHelper end def link_to_member_avatar(author, opts = {}) - default_opts = { size: 16, lazy_load: false } + default_opts = {size: 16, lazy_load: false} opts = default_opts.merge(opts) classes = %W[avatar avatar-inline s#{opts[:size]}] @@ -24,22 +24,22 @@ module ProjectsHelper avatar = avatar_icon_for_user(author, opts[:size]) src = opts[:lazy_load] ? nil : avatar - image_tag(src, width: opts[:size], class: classes, alt: '', "data-src" => avatar) + image_tag(src, :width => opts[:size], :class => classes, :alt => "", "data-src" => avatar) end def author_content_tag(author, opts = {}) - default_opts = { author_class: 'author', tooltip: false, by_username: false } + default_opts = {author_class: "author", tooltip: false, by_username: false} opts = default_opts.merge(opts) has_tooltip = !opts[:by_username] && opts[:tooltip] username = opts[:by_username] ? author.to_reference : author.name - name_tag_options = { class: [opts[:author_class]] } + name_tag_options = {class: [opts[:author_class]]} if has_tooltip name_tag_options[:title] = author.to_reference - name_tag_options[:data] = { placement: 'top' } - name_tag_options[:class] << 'has-tooltip' + name_tag_options[:data] = {placement: "top"} + name_tag_options[:class] << "has-tooltip" end # NOTE: ActionView::Helpers::TagHelper#content_tag HTML escapes username @@ -47,13 +47,13 @@ module ProjectsHelper end def link_to_member(project, author, opts = {}, &block) - default_opts = { avatar: true, name: true, title: ":name" } + default_opts = {avatar: true, name: true, title: ":name"} opts = default_opts.merge(opts) data_attrs = { user_id: author.id, username: author.username, - name: author.name + name: author.name, } return "(deleted)" unless author @@ -71,10 +71,10 @@ module ProjectsHelper author_html = author_html.join.html_safe if opts[:name] - link_to(author_html, user_path(author), class: "author-link js-user-link #{"#{opts[:extra_class]}" if opts[:extra_class]} #{"#{opts[:mobile_classes]}" if opts[:mobile_classes]}", data: data_attrs).html_safe + link_to(author_html, user_path(author), class: "author-link js-user-link #{(opts[:extra_class]).to_s if opts[:extra_class]} #{(opts[:mobile_classes]).to_s if opts[:mobile_classes]}", data: data_attrs).html_safe else title = opts[:title].sub(":name", sanitize(author.name)) - link_to(author_html, user_path(author), class: "author-link has-tooltip", title: title, data: { container: 'body' }).html_safe + link_to(author_html, user_path(author), class: "author-link has-tooltip", title: title, data: {container: "body"}).html_safe end end @@ -88,7 +88,7 @@ module ProjectsHelper end project_link = link_to project_path(project) do - icon = project_icon(project, alt: project.name, class: 'avatar-tile', width: 15, height: 15) if project.avatar_url && !Rails.env.test? + icon = project_icon(project, alt: project.name, class: "avatar-tile", width: 15, height: 15) if project.avatar_url && !Rails.env.test? [icon, content_tag("span", simple_sanitize(project.name), class: "breadcrumb-item-text js-breadcrumb-item-text")].join.html_safe end @@ -100,17 +100,17 @@ module ProjectsHelper def remove_project_message(project) _("You are going to remove %{project_full_name}. Removed project CANNOT be restored! Are you ABSOLUTELY sure?") % - { project_full_name: project.full_name } + {project_full_name: project.full_name} end def transfer_project_message(project) _("You are going to transfer %{project_full_name} to another owner. Are you ABSOLUTELY sure?") % - { project_full_name: project.full_name } + {project_full_name: project.full_name} end def remove_fork_project_message(project) _("You are going to remove the fork relationship to source project %{forked_from_project}. Are you ABSOLUTELY sure?") % - { forked_from_project: fork_source_name(project) } + {forked_from_project: fork_source_name(project)} end def fork_source_name(project) @@ -160,12 +160,12 @@ module ProjectsHelper end def link_to_autodeploy_doc - link_to _('About auto deploy'), help_page_path('ci/autodeploy/index'), target: '_blank' + link_to _("About auto deploy"), help_page_path("ci/autodeploy/index"), target: "_blank" end def autodeploy_flash_notice(branch_name) translation = _("Branch <strong>%{branch_name}</strong> was created. To set up auto deploy, choose a GitLab CI Yaml template and commit your changes. %{link_to_autodeploy_doc}") % - { branch_name: truncate(sanitize(branch_name)), link_to_autodeploy_doc: link_to_autodeploy_doc } + {branch_name: truncate(sanitize(branch_name)), link_to_autodeploy_doc: link_to_autodeploy_doc} translation.html_safe end @@ -179,7 +179,7 @@ module ProjectsHelper Gitlab::CurrentSettings.cache_key, "cross-project:#{can?(current_user, :read_cross_project)}", max_project_member_access_cache_key(project), - 'v2.6' + "v2.6", ] key << pipeline_status_cache_key(project.pipeline_status) if project.pipeline_status.has_status? @@ -212,9 +212,9 @@ module ProjectsHelper def link_to_set_password if current_user.require_password_creation_for_git? - link_to s_('SetPasswordToCloneLink|set a password'), edit_profile_password_path + link_to s_("SetPasswordToCloneLink|set a password"), edit_profile_password_path else - link_to s_('CreateTokenToCloneLink|create a personal access token'), profile_personal_access_tokens_path + link_to s_("CreateTokenToCloneLink|create a personal access token"), profile_personal_access_tokens_path end end @@ -244,7 +244,7 @@ module ProjectsHelper def push_to_create_project_command(user = current_user) repository_url = - if Gitlab::CurrentSettings.current_application_settings.enabled_git_access_protocol == 'http' + if Gitlab::CurrentSettings.current_application_settings.enabled_git_access_protocol == "http" user_url(user) else Gitlab.config.gitlab_shell.ssh_path_prefix + user.username @@ -262,7 +262,7 @@ module ProjectsHelper end def link_to_bfg - link_to 'BFG', 'https://rtyley.github.io/bfg-repo-cleaner/', target: '_blank', rel: 'noopener noreferrer' + link_to "BFG", "https://rtyley.github.io/bfg-repo-cleaner/", target: "_blank", rel: "noopener noreferrer" end def explore_projects_tab? @@ -330,38 +330,38 @@ module ProjectsHelper def tab_ability_map { - environments: :read_environment, - milestones: :read_milestone, - snippets: :read_project_snippet, - settings: :admin_project, - builds: :read_build, - clusters: :read_cluster, - serverless: :read_cluster, - error_tracking: :read_sentry_issue, - labels: :read_label, - issues: :read_issue, - project_members: :read_project_member, - wiki: :read_wiki + environments: :read_environment, + milestones: :read_milestone, + snippets: :read_project_snippet, + settings: :admin_project, + builds: :read_build, + clusters: :read_cluster, + serverless: :read_cluster, + error_tracking: :read_sentry_issue, + labels: :read_label, + issues: :read_issue, + project_members: :read_project_member, + wiki: :read_wiki, } end def search_tab_ability_map @search_tab_ability_map ||= tab_ability_map.merge( - blobs: :download_code, - commits: :download_code, + blobs: :download_code, + commits: :download_code, merge_requests: :read_merge_request, - notes: [:read_merge_request, :download_code, :read_issue, :read_project_snippet] + notes: [:read_merge_request, :download_code, :read_issue, :read_project_snippet] ) end def project_lfs_status(project) if project.lfs_enabled? - content_tag(:span, class: 'lfs-enabled') do - s_('LFSStatus|Enabled') + content_tag(:span, class: "lfs-enabled") do + s_("LFSStatus|Enabled") end else - content_tag(:span, class: 'lfs-disabled') do - s_('LFSStatus|Disabled') + content_tag(:span, class: "lfs-disabled") do + s_("LFSStatus|Disabled") end end end @@ -384,7 +384,7 @@ module ProjectsHelper def default_url_to_repo(project = @project) case default_clone_protocol - when 'ssh' + when "ssh" project.ssh_url_to_repo else project.http_url_to_repo @@ -392,7 +392,7 @@ module ProjectsHelper end def default_clone_label - _("Copy %{protocol} clone URL") % { protocol: default_clone_protocol.upcase } + _("Copy %{protocol} clone URL") % {protocol: default_clone_protocol.upcase} end def default_clone_protocol @@ -407,7 +407,7 @@ module ProjectsHelper if !current_user || current_user.require_ssh_key? gitlab_config.protocol else - 'ssh' + "ssh" end end @@ -417,14 +417,14 @@ module ProjectsHelper def project_last_activity(project) if project.last_activity_at - time_ago_with_tooltip(project.last_activity_at, placement: 'bottom', html_class: 'last_activity_time_ago') + time_ago_with_tooltip(project.last_activity_at, placement: "bottom", html_class: "last_activity_time_ago") else s_("ProjectLastActivity|Never") end end def project_wiki_path_with_version(proj, page, version, is_newest) - url_params = is_newest ? {} : { version_id: version } + url_params = is_newest ? {} : {version_id: version} project_wiki_path(proj, page, url_params) end @@ -440,8 +440,8 @@ module ProjectsHelper end def readme_cache_key - sha = @project.commit.try(:sha) || 'nil' - [@project.full_path, sha, "readme"].join('-') + sha = @project.commit.try(:sha) || "nil" + [@project.full_path, sha, "readme"].join("-") end def current_ref @@ -475,7 +475,7 @@ module ProjectsHelper snippetsAccessLevel: feature.snippets_access_level, pagesAccessLevel: feature.pages_access_level, containerRegistryEnabled: !!project.container_registry_enabled, - lfsEnabled: !!project.lfs_enabled + lfsEnabled: !!project.lfs_enabled, } end @@ -484,14 +484,14 @@ module ProjectsHelper currentSettings: project_permissions_settings(project), canChangeVisibilityLevel: can_change_visibility_level?(project, current_user), allowedVisibilityOptions: project_allowed_visibility_levels(project), - visibilityHelpPath: help_page_path('public_access/public_access'), + visibilityHelpPath: help_page_path("public_access/public_access"), registryAvailable: Gitlab.config.registry.enabled, - registryHelpPath: help_page_path('user/project/container_registry'), + registryHelpPath: help_page_path("user/project/container_registry"), lfsAvailable: Gitlab.config.lfs.enabled, - lfsHelpPath: help_page_path('workflow/lfs/manage_large_binaries_with_git_lfs'), + lfsHelpPath: help_page_path("workflow/lfs/manage_large_binaries_with_git_lfs"), pagesAvailable: Gitlab.config.pages.enabled, pagesAccessControlEnabled: Gitlab.config.pages.access_control, - pagesHelpPath: help_page_path('user/project/pages/introduction', anchor: 'gitlab-pages-access-control-core-only') + pagesHelpPath: help_page_path("user/project/pages/introduction", anchor: "gitlab-pages-access-control-core-only"), } end diff --git a/app/helpers/repository_languages_helper.rb b/app/helpers/repository_languages_helper.rb index cf7eee7fff3..b64ce165aea 100644 --- a/app/helpers/repository_languages_helper.rb +++ b/app/helpers/repository_languages_helper.rb @@ -4,7 +4,7 @@ module RepositoryLanguagesHelper def repository_languages_bar(languages) return if languages.none? - content_tag :div, class: 'progress repository-languages-bar' do + content_tag :div, class: "progress repository-languages-bar" do safe_join(languages.map { |lang| language_progress(lang) }) end end @@ -13,7 +13,7 @@ module RepositoryLanguagesHelper content_tag :div, nil, class: "progress-bar has-tooltip", style: "width: #{lang.share}%; background-color:#{lang.color}", - data: { html: true }, + data: {html: true}, title: "<span class=\"repository-language-bar-tooltip-language\">#{escape_javascript(lang.name)}</span> <span class=\"repository-language-bar-tooltip-share\">#{lang.share.round(1)}%</span>" end end diff --git a/app/helpers/rss_helper.rb b/app/helpers/rss_helper.rb index 67c7d244f11..e50db812e33 100644 --- a/app/helpers/rss_helper.rb +++ b/app/helpers/rss_helper.rb @@ -2,6 +2,6 @@ module RssHelper def rss_url_options - { format: :atom, feed_token: current_user.try(:feed_token) } + {format: :atom, feed_token: current_user.try(:feed_token)} end end diff --git a/app/helpers/runners_helper.rb b/app/helpers/runners_helper.rb index 0d880c38a7b..2ebbd9ba86c 100644 --- a/app/helpers/runners_helper.rb +++ b/app/helpers/runners_helper.rb @@ -6,13 +6,13 @@ module RunnersHelper case status when :not_connected content_tag :i, nil, - class: "fa fa-warning", - title: "New runner. Has not connected yet" + class: "fa fa-warning", + title: "New runner. Has not connected yet" when :online, :offline, :paused content_tag :i, nil, - class: "fa fa-circle runner-status-#{status}", - title: "Runner is #{status}, last contact was #{time_ago_in_words(runner.contacted_at)} ago" + class: "fa fa-circle runner-status-#{status}", + title: "Runner is #{status}, last contact was #{time_ago_in_words(runner.contacted_at)} ago" end end @@ -20,7 +20,7 @@ module RunnersHelper display_name = truncate(runner.display_name, length: 15) id = "\##{runner.id}" - if current_user && current_user.admin + if current_user&.admin link_to admin_runner_path(runner) do display_name + id end @@ -32,7 +32,7 @@ module RunnersHelper # Due to inability of performing sorting of runners by cached "contacted_at" values we have to show uncached values if sorting by "contacted_asc" is requested. # Please refer to the following issue for more details: https://gitlab.com/gitlab-org/gitlab-ce/issues/55920 def runner_contacted_at(runner) - if params[:sort] == 'contacted_asc' + if params[:sort] == "contacted_asc" runner.uncached_contacted_at else runner.contacted_at diff --git a/app/helpers/search_helper.rb b/app/helpers/search_helper.rb index 0ee76a51f7d..6cd8bded0f4 100644 --- a/app/helpers/search_helper.rb +++ b/app/helpers/search_helper.rb @@ -6,7 +6,7 @@ module SearchHelper resources_results = [ groups_autocomplete(term), - projects_autocomplete(term) + projects_autocomplete(term), ].flatten search_pattern = Regexp.new(Regexp.escape(term), "i") @@ -17,7 +17,7 @@ module SearchHelper [ resources_results, - generic_results + generic_results, ].flatten.uniq do |item| item[:label] end @@ -50,50 +50,50 @@ module SearchHelper # Autocomplete results for various settings pages def default_autocomplete [ - { category: "Settings", label: "User settings", url: profile_path }, - { category: "Settings", label: "SSH Keys", url: profile_keys_path }, - { category: "Settings", label: "Dashboard", url: root_path } + {category: "Settings", label: "User settings", url: profile_path}, + {category: "Settings", label: "SSH Keys", url: profile_keys_path}, + {category: "Settings", label: "Dashboard", url: root_path}, ] end # Autocomplete results for settings pages, for admins def default_autocomplete_admin [ - { category: "Settings", label: "Admin Section", url: admin_root_path } + {category: "Settings", label: "Admin Section", url: admin_root_path}, ] end # Autocomplete results for internal help pages def help_autocomplete [ - { category: "Help", label: "API Help", url: help_page_path("api/README") }, - { category: "Help", label: "Markdown Help", url: help_page_path("user/markdown") }, - { category: "Help", label: "Permissions Help", url: help_page_path("user/permissions") }, - { category: "Help", label: "Public Access Help", url: help_page_path("public_access/public_access") }, - { category: "Help", label: "Rake Tasks Help", url: help_page_path("raketasks/README") }, - { category: "Help", label: "SSH Keys Help", url: help_page_path("ssh/README") }, - { category: "Help", label: "System Hooks Help", url: help_page_path("system_hooks/system_hooks") }, - { category: "Help", label: "Webhooks Help", url: help_page_path("user/project/integrations/webhooks") }, - { category: "Help", label: "Workflow Help", url: help_page_path("workflow/README") } + {category: "Help", label: "API Help", url: help_page_path("api/README")}, + {category: "Help", label: "Markdown Help", url: help_page_path("user/markdown")}, + {category: "Help", label: "Permissions Help", url: help_page_path("user/permissions")}, + {category: "Help", label: "Public Access Help", url: help_page_path("public_access/public_access")}, + {category: "Help", label: "Rake Tasks Help", url: help_page_path("raketasks/README")}, + {category: "Help", label: "SSH Keys Help", url: help_page_path("ssh/README")}, + {category: "Help", label: "System Hooks Help", url: help_page_path("system_hooks/system_hooks")}, + {category: "Help", label: "Webhooks Help", url: help_page_path("user/project/integrations/webhooks")}, + {category: "Help", label: "Workflow Help", url: help_page_path("workflow/README")}, ] end # Autocomplete results for the current project, if it's defined def project_autocomplete - if @project && @project.repository.exists? && @project.repository.root_ref + if @project&.repository&.exists? && @project.repository.root_ref ref = @ref || @project.repository.root_ref [ - { category: "In this project", label: "Files", url: project_tree_path(@project, ref) }, - { category: "In this project", label: "Commits", url: project_commits_path(@project, ref) }, - { category: "In this project", label: "Network", url: project_network_path(@project, ref) }, - { category: "In this project", label: "Graph", url: project_graph_path(@project, ref) }, - { category: "In this project", label: "Issues", url: project_issues_path(@project) }, - { category: "In this project", label: "Merge Requests", url: project_merge_requests_path(@project) }, - { category: "In this project", label: "Milestones", url: project_milestones_path(@project) }, - { category: "In this project", label: "Snippets", url: project_snippets_path(@project) }, - { category: "In this project", label: "Members", url: project_project_members_path(@project) }, - { category: "In this project", label: "Wiki", url: project_wikis_path(@project) } + {category: "In this project", label: "Files", url: project_tree_path(@project, ref)}, + {category: "In this project", label: "Commits", url: project_commits_path(@project, ref)}, + {category: "In this project", label: "Network", url: project_network_path(@project, ref)}, + {category: "In this project", label: "Graph", url: project_graph_path(@project, ref)}, + {category: "In this project", label: "Issues", url: project_issues_path(@project)}, + {category: "In this project", label: "Merge Requests", url: project_merge_requests_path(@project)}, + {category: "In this project", label: "Milestones", url: project_milestones_path(@project)}, + {category: "In this project", label: "Snippets", url: project_snippets_path(@project)}, + {category: "In this project", label: "Members", url: project_project_members_path(@project)}, + {category: "In this project", label: "Wiki", url: project_wikis_path(@project)}, ] else [] @@ -107,9 +107,9 @@ module SearchHelper { category: "Groups", id: group.id, - label: "#{search_result_sanitize(group.full_name)}", + label: search_result_sanitize(group.full_name).to_s, url: group_path(group), - avatar_url: group.avatar_url || '' + avatar_url: group.avatar_url || "", } end end @@ -123,10 +123,10 @@ module SearchHelper { category: "Projects", id: p.id, - value: "#{search_result_sanitize(p.name)}", - label: "#{search_result_sanitize(p.full_name)}", + value: search_result_sanitize(p.name).to_s, + label: search_result_sanitize(p.full_name).to_s, url: project_path(p), - avatar_url: p.avatar_url || '' + avatar_url: p.avatar_url || "", } end end @@ -142,7 +142,7 @@ module SearchHelper project_id: params[:project_id], group_id: params[:group_id], scope: params[:scope], - repository_ref: params[:repository_ref] + repository_ref: params[:repository_ref], } options = exist_opts.merge(options) @@ -153,21 +153,21 @@ module SearchHelper opts = { id: "filtered-search-#{type}", - placeholder: 'Search or filter results...', + placeholder: "Search or filter results...", data: { - 'username-params' => UserSerializer.new.represent(@users) + "username-params" => UserSerializer.new.represent(@users), }, - autocomplete: 'off' + autocomplete: "off", } if @project.present? - opts[:data]['project-id'] = @project.id - opts[:data]['base-endpoint'] = project_path(@project) + opts[:data]["project-id"] = @project.id + opts[:data]["base-endpoint"] = project_path(@project) elsif @group.present? - opts[:data]['group-id'] = @group.id - opts[:data]['base-endpoint'] = group_canonical_path(@group) + opts[:data]["group-id"] = @group.id + opts[:data]["base-endpoint"] = group_canonical_path(@group) else - opts[:data]['base-endpoint'] = root_dashboard_path + opts[:data]["base-endpoint"] = root_dashboard_path end opts @@ -179,7 +179,7 @@ module SearchHelper elsif @group.present? @group.full_path else - 'dashboard' + "dashboard" end end @@ -195,7 +195,7 @@ module SearchHelper ) # Truncato's filtered_tags and filtered_attributes are not quite the same - sanitize(html, tags: %w(a p ol ul li pre code)) + sanitize(html, tags: %w[a p ol ul li pre code]) end def limited_count(count, limit = 1000) diff --git a/app/helpers/selects_helper.rb b/app/helpers/selects_helper.rb index 2f802e4eab8..f433ee56ab3 100644 --- a/app/helpers/selects_helper.rb +++ b/app/helpers/selects_helper.rb @@ -5,20 +5,20 @@ module SelectsHelper css_class = ["ajax-users-select"] css_class << "multiselect" if opts[:multiple] css_class << "skip_ldap" if opts[:skip_ldap] - css_class << (opts[:class] || '') - value = opts[:selected] || '' + css_class << (opts[:class] || "") + value = opts[:selected] || "" html = { - class: css_class.join(' '), - data: users_select_data_attributes(opts) + class: css_class.join(" "), + data: users_select_data_attributes(opts), } unless opts[:scope] == :all project = opts[:project] || @project if project - html['data-project-id'] = project.id + html["data-project-id"] = project.id elsif @group - html['data-group-id'] = @group.id + html["data-group-id"] = @group.id end end @@ -27,36 +27,36 @@ module SelectsHelper def groups_select_tag(id, opts = {}) classes = Array.wrap(opts[:class]) - classes << 'ajax-groups-select' + classes << "ajax-groups-select" # EE requires this line to be present, but there is no easy way of injecting # this into EE without causing merge conflicts. Given this line is very # simple and not really EE specific on its own, we just include it in CE. - classes << 'multiselect' if opts[:multiple] + classes << "multiselect" if opts[:multiple] - opts[:class] = classes.join(' ') + opts[:class] = classes.join(" ") select2_tag(id, opts) end def namespace_select_tag(id, opts = {}) - opts[:class] = [*opts[:class], 'ajax-namespace-select'].join(' ') + opts[:class] = [*opts[:class], "ajax-namespace-select"].join(" ") select2_tag(id, opts) end def project_select_tag(id, opts = {}) - opts[:class] = [*opts[:class], 'ajax-project-select'].join(' ') + opts[:class] = [*opts[:class], "ajax-project-select"].join(" ") unless opts.delete(:scope) == :all if @group - opts['data-group-id'] = @group.id + opts["data-group-id"] = @group.id end end with_feature_enabled_data_attribute = case opts.delete(:with_feature_enabled) - when 'issues' then 'data-with-issues-enabled' - when 'merge_requests' then 'data-with-merge-requests-enabled' + when "issues" then "data-with-issues-enabled" + when "merge_requests" then "data-with-merge-requests-enabled" end opts[with_feature_enabled_data_attribute] = true @@ -66,10 +66,10 @@ module SelectsHelper def select2_tag(id, opts = {}) klass_opts = [opts[:class]] - klass_opts << 'multiselect' if opts[:multiple] + klass_opts << "multiselect" if opts[:multiple] - opts[:class] = klass_opts.join(' ') - value = opts[:selected] || '' + opts[:class] = klass_opts.join(" ") + value = opts[:selected] || "" hidden_field_tag(id, value, opts) end @@ -78,14 +78,14 @@ module SelectsHelper def users_select_data_attributes(opts) { - placeholder: opts[:placeholder] || 'Search for a user', + placeholder: opts[:placeholder] || "Search for a user", null_user: opts[:null_user] || false, any_user: opts[:any_user] || false, email_user: opts[:email_user] || false, first_user: opts[:first_user] && current_user ? current_user.username : false, current_user: opts[:current_user] || false, - author_id: opts[:author_id] || '', - skip_users: opts[:skip_users] ? opts[:skip_users].map(&:id) : nil + author_id: opts[:author_id] || "", + skip_users: opts[:skip_users] ? opts[:skip_users].map(&:id) : nil, } end end diff --git a/app/helpers/services_helper.rb b/app/helpers/services_helper.rb index d4b50b7ecfb..4fe2b7e4c0e 100644 --- a/app/helpers/services_helper.rb +++ b/app/helpers/services_helper.rb @@ -32,9 +32,9 @@ module ServicesHelper end def service_save_button(service) - button_tag(class: 'btn btn-success', type: 'submit', disabled: service.deprecated?) do - icon('spinner spin', class: 'hidden js-btn-spinner') + - content_tag(:span, 'Save changes', class: 'js-btn-label') + button_tag(class: "btn btn-success", type: "submit", disabled: service.deprecated?) do + icon("spinner spin", class: "hidden js-btn-spinner") + + content_tag(:span, "Save changes", class: "js-btn-label") end end diff --git a/app/helpers/sidekiq_helper.rb b/app/helpers/sidekiq_helper.rb index 32bf3526571..156d69c5420 100644 --- a/app/helpers/sidekiq_helper.rb +++ b/app/helpers/sidekiq_helper.rb @@ -12,6 +12,6 @@ module SidekiqHelper def parse_sidekiq_ps(line) match = line.strip.match(SIDEKIQ_PS_REGEXP) - match ? match[1..6] : Array.new(6, '?') + match ? match[1..6] : Array.new(6, "?") end end diff --git a/app/helpers/snippets_helper.rb b/app/helpers/snippets_helper.rb index ecb2b2d707b..37870e88086 100644 --- a/app/helpers/snippets_helper.rb +++ b/app/helpers/snippets_helper.rb @@ -46,12 +46,14 @@ module SnippetsHelper def matching_lines(lined_content, surrounding_lines, query) used_lines = [] lined_content.each_with_index do |line, line_number| - used_lines.concat bounded_line_numbers( - line_number, - 0, - lined_content.size, - surrounding_lines - ) if line.downcase.include?(query.downcase) + if line.downcase.include?(query.downcase) + used_lines.concat bounded_line_numbers( + line_number, + 0, + lined_content.size, + surrounding_lines + ) + end end used_lines.uniq.sort @@ -84,7 +86,7 @@ module SnippetsHelper # Non-consecutive line, add chunk to chunk array. snippet_chunks << { data: snippet_chunk.join("\n"), - start_line: snippet_start_line + 1 + start_line: snippet_start_line + 1, } # Start a new chunk. @@ -97,11 +99,11 @@ module SnippetsHelper # Add final chunk to chunk array snippet_chunks << { data: snippet_chunk.join("\n"), - start_line: snippet_start_line + 1 + start_line: snippet_start_line + 1, } # Return snippet with chunk array - { snippet_object: snippet, snippet_chunks: snippet_chunks } + {snippet_object: snippet, snippet_chunks: snippet_chunks} end def snippet_embed @@ -113,21 +115,21 @@ module SnippetsHelper return if blob.empty? || blob.binary? || blob.stored_externally? snippet_raw_url = if @snippet.is_a?(PersonalSnippet) - raw_snippet_url(@snippet) - else - raw_project_snippet_url(@snippet.project, @snippet) - end + raw_snippet_url(@snippet) + else + raw_project_snippet_url(@snippet.project, @snippet) + end - link_to external_snippet_icon('doc-code'), snippet_raw_url, class: 'btn', target: '_blank', rel: 'noopener noreferrer', title: 'Open raw' + link_to external_snippet_icon("doc-code"), snippet_raw_url, class: "btn", target: "_blank", rel: "noopener noreferrer", title: "Open raw" end def embedded_snippet_download_button download_url = if @snippet.is_a?(PersonalSnippet) - raw_snippet_url(@snippet, inline: false) - else - raw_project_snippet_url(@snippet.project, @snippet, inline: false) - end + raw_snippet_url(@snippet, inline: false) + else + raw_project_snippet_url(@snippet.project, @snippet, inline: false) + end - link_to external_snippet_icon('download'), download_url, class: 'btn', target: '_blank', title: 'Download', rel: 'noopener noreferrer' + link_to external_snippet_icon("download"), download_url, class: "btn", target: "_blank", title: "Download", rel: "noopener noreferrer" end end diff --git a/app/helpers/sorting_helper.rb b/app/helpers/sorting_helper.rb index 07ec129dea3..3322e0e5dd8 100644 --- a/app/helpers/sorting_helper.rb +++ b/app/helpers/sorting_helper.rb @@ -3,43 +3,43 @@ module SortingHelper def sort_options_hash { - sort_value_created_date => sort_title_created_date, - sort_value_downvotes => sort_title_downvotes, - sort_value_due_date => sort_title_due_date, - sort_value_due_date_later => sort_title_due_date_later, - sort_value_due_date_soon => sort_title_due_date_soon, - sort_value_label_priority => sort_title_label_priority, - sort_value_largest_group => sort_title_largest_group, - sort_value_largest_repo => sort_title_largest_repo, - sort_value_milestone => sort_title_milestone, - sort_value_milestone_later => sort_title_milestone_later, - sort_value_milestone_soon => sort_title_milestone_soon, - sort_value_name => sort_title_name, - sort_value_name_desc => sort_title_name_desc, - sort_value_oldest_created => sort_title_oldest_created, - sort_value_oldest_signin => sort_title_oldest_signin, - sort_value_oldest_updated => sort_title_oldest_updated, + sort_value_created_date => sort_title_created_date, + sort_value_downvotes => sort_title_downvotes, + sort_value_due_date => sort_title_due_date, + sort_value_due_date_later => sort_title_due_date_later, + sort_value_due_date_soon => sort_title_due_date_soon, + sort_value_label_priority => sort_title_label_priority, + sort_value_largest_group => sort_title_largest_group, + sort_value_largest_repo => sort_title_largest_repo, + sort_value_milestone => sort_title_milestone, + sort_value_milestone_later => sort_title_milestone_later, + sort_value_milestone_soon => sort_title_milestone_soon, + sort_value_name => sort_title_name, + sort_value_name_desc => sort_title_name_desc, + sort_value_oldest_created => sort_title_oldest_created, + sort_value_oldest_signin => sort_title_oldest_signin, + sort_value_oldest_updated => sort_title_oldest_updated, sort_value_recently_created => sort_title_recently_created, - sort_value_recently_signin => sort_title_recently_signin, + sort_value_recently_signin => sort_title_recently_signin, sort_value_recently_updated => sort_title_recently_updated, - sort_value_popularity => sort_title_popularity, - sort_value_priority => sort_title_priority, - sort_value_upvotes => sort_title_upvotes, - sort_value_contacted_date => sort_title_contacted_date + sort_value_popularity => sort_title_popularity, + sort_value_priority => sort_title_priority, + sort_value_upvotes => sort_title_upvotes, + sort_value_contacted_date => sort_title_contacted_date, } end def projects_sort_options_hash options = { - sort_value_latest_activity => sort_title_latest_activity, - sort_value_name => sort_title_name, - sort_value_oldest_activity => sort_title_oldest_activity, - sort_value_oldest_created => sort_title_oldest_created, + sort_value_latest_activity => sort_title_latest_activity, + sort_value_name => sort_title_name, + sort_value_oldest_activity => sort_title_oldest_activity, + sort_value_oldest_created => sort_title_oldest_created, sort_value_recently_created => sort_title_recently_created, - sort_value_most_stars => sort_title_most_stars + sort_value_most_stars => sort_title_most_stars, } - if current_controller?('admin/projects') + if current_controller?("admin/projects") options[sort_value_largest_repo] = sort_title_largest_repo end @@ -48,12 +48,12 @@ module SortingHelper def groups_sort_options_hash { - sort_value_name => sort_title_name, - sort_value_name_desc => sort_title_name_desc, + sort_value_name => sort_title_name, + sort_value_name_desc => sort_title_name_desc, sort_value_recently_created => sort_title_recently_created, - sort_value_oldest_created => sort_title_oldest_created, + sort_value_oldest_created => sort_title_oldest_created, sort_value_recently_updated => sort_title_recently_updated, - sort_value_oldest_updated => sort_title_oldest_updated + sort_value_oldest_updated => sort_title_oldest_updated, } end @@ -71,41 +71,41 @@ module SortingHelper def member_sort_options_hash { - sort_value_access_level_asc => sort_title_access_level_asc, + sort_value_access_level_asc => sort_title_access_level_asc, sort_value_access_level_desc => sort_title_access_level_desc, - sort_value_last_joined => sort_title_last_joined, - sort_value_name => sort_title_name_asc, - sort_value_name_desc => sort_title_name_desc, - sort_value_oldest_joined => sort_title_oldest_joined, - sort_value_oldest_signin => sort_title_oldest_signin, - sort_value_recently_signin => sort_title_recently_signin + sort_value_last_joined => sort_title_last_joined, + sort_value_name => sort_title_name_asc, + sort_value_name_desc => sort_title_name_desc, + sort_value_oldest_joined => sort_title_oldest_joined, + sort_value_oldest_signin => sort_title_oldest_signin, + sort_value_recently_signin => sort_title_recently_signin, } end def milestone_sort_options_hash { - sort_value_name => sort_title_name_asc, - sort_value_name_desc => sort_title_name_desc, - sort_value_due_date_later => sort_title_due_date_later, - sort_value_due_date_soon => sort_title_due_date_soon, + sort_value_name => sort_title_name_asc, + sort_value_name_desc => sort_title_name_desc, + sort_value_due_date_later => sort_title_due_date_later, + sort_value_due_date_soon => sort_title_due_date_soon, sort_value_start_date_later => sort_title_start_date_later, - sort_value_start_date_soon => sort_title_start_date_soon + sort_value_start_date_soon => sort_title_start_date_soon, } end def branches_sort_options_hash { - sort_value_name => sort_title_name, - sort_value_oldest_updated => sort_title_oldest_updated, - sort_value_recently_updated => sort_title_recently_updated + sort_value_name => sort_title_name, + sort_value_oldest_updated => sort_title_oldest_updated, + sort_value_recently_updated => sort_title_recently_updated, } end def tags_sort_options_hash { - sort_value_name => sort_title_name, - sort_value_oldest_updated => sort_title_oldest_updated, - sort_value_recently_updated => sort_title_recently_updated + sort_value_name => sort_title_name, + sort_value_oldest_updated => sort_title_oldest_updated, + sort_value_recently_updated => sort_title_recently_updated, } end @@ -116,7 +116,7 @@ module SortingHelper sort_value_recently_created => sort_title_recently_created, sort_value_oldest_created => sort_title_oldest_created, sort_value_recently_updated => sort_title_recently_updated, - sort_value_oldest_updated => sort_title_oldest_updated + sort_value_oldest_updated => sort_title_oldest_updated, } end @@ -130,19 +130,19 @@ module SortingHelper sort_value_recently_updated => sort_title_recently_updated, sort_value_oldest_updated => sort_title_oldest_updated, sort_value_recently_last_activity => sort_title_recently_last_activity, - sort_value_oldest_last_activity => sort_title_oldest_last_activity + sort_value_oldest_last_activity => sort_title_oldest_last_activity, } end def sortable_item(item, path, sorted_by) - link_to item, path, class: sorted_by == item ? 'is-active' : '' + link_to item, path, class: sorted_by == item ? "is-active" : "" end def issuable_sort_option_overrides { sort_value_oldest_created => sort_value_created_date, sort_value_oldest_updated => sort_value_recently_updated, - sort_value_milestone_later => sort_value_milestone + sort_value_milestone_later => sort_value_milestone, } end @@ -151,7 +151,7 @@ module SortingHelper sort_value_created_date => sort_value_oldest_created, sort_value_recently_created => sort_value_oldest_created, sort_value_recently_updated => sort_value_oldest_updated, - sort_value_milestone => sort_value_milestone_later + sort_value_milestone => sort_value_milestone_later, }.merge(issuable_sort_option_overrides) end @@ -164,303 +164,303 @@ module SortingHelper def issuable_sort_icon_suffix(sort_value) case sort_value when sort_value_milestone, sort_value_due_date, /_asc\z/ - 'lowest' + "lowest" else - 'highest' + "highest" end end def issuable_sort_direction_button(sort_value) - link_class = 'btn btn-default has-tooltip reverse-sort-btn qa-reverse-sort' + link_class = "btn btn-default has-tooltip reverse-sort-btn qa-reverse-sort" reverse_sort = issuable_reverse_sort_order_hash[sort_value] if reverse_sort reverse_url = page_filter_path(sort: reverse_sort) else - reverse_url = '#' - link_class += ' disabled' + reverse_url = "#" + link_class += " disabled" end - link_to(reverse_url, type: 'button', class: link_class, title: 'Sort direction') do + link_to(reverse_url, type: "button", class: link_class, title: "Sort direction") do sprite_icon("sort-#{issuable_sort_icon_suffix(sort_value)}", size: 16) end end # Titles. def sort_title_access_level_asc - s_('SortOptions|Access level, ascending') + s_("SortOptions|Access level, ascending") end def sort_title_access_level_desc - s_('SortOptions|Access level, descending') + s_("SortOptions|Access level, descending") end def sort_title_created_date - s_('SortOptions|Created date') + s_("SortOptions|Created date") end def sort_title_downvotes - s_('SortOptions|Least popular') + s_("SortOptions|Least popular") end def sort_title_due_date - s_('SortOptions|Due date') + s_("SortOptions|Due date") end def sort_title_due_date_later - s_('SortOptions|Due later') + s_("SortOptions|Due later") end def sort_title_due_date_soon - s_('SortOptions|Due soon') + s_("SortOptions|Due soon") end def sort_title_label_priority - s_('SortOptions|Label priority') + s_("SortOptions|Label priority") end def sort_title_largest_group - s_('SortOptions|Largest group') + s_("SortOptions|Largest group") end def sort_title_largest_repo - s_('SortOptions|Largest repository') + s_("SortOptions|Largest repository") end def sort_title_last_joined - s_('SortOptions|Last joined') + s_("SortOptions|Last joined") end def sort_title_latest_activity - s_('SortOptions|Last updated') + s_("SortOptions|Last updated") end def sort_title_milestone - s_('SortOptions|Milestone due date') + s_("SortOptions|Milestone due date") end def sort_title_milestone_later - s_('SortOptions|Milestone due later') + s_("SortOptions|Milestone due later") end def sort_title_milestone_soon - s_('SortOptions|Milestone due soon') + s_("SortOptions|Milestone due soon") end def sort_title_name - s_('SortOptions|Name') + s_("SortOptions|Name") end def sort_title_name_asc - s_('SortOptions|Name, ascending') + s_("SortOptions|Name, ascending") end def sort_title_name_desc - s_('SortOptions|Name, descending') + s_("SortOptions|Name, descending") end def sort_title_oldest_activity - s_('SortOptions|Oldest updated') + s_("SortOptions|Oldest updated") end def sort_title_oldest_created - s_('SortOptions|Oldest created') + s_("SortOptions|Oldest created") end def sort_title_oldest_joined - s_('SortOptions|Oldest joined') + s_("SortOptions|Oldest joined") end def sort_title_oldest_signin - s_('SortOptions|Oldest sign in') + s_("SortOptions|Oldest sign in") end def sort_title_oldest_updated - s_('SortOptions|Oldest updated') + s_("SortOptions|Oldest updated") end def sort_title_popularity - s_('SortOptions|Popularity') + s_("SortOptions|Popularity") end def sort_title_priority - s_('SortOptions|Priority') + s_("SortOptions|Priority") end def sort_title_recently_created - s_('SortOptions|Last created') + s_("SortOptions|Last created") end def sort_title_recently_signin - s_('SortOptions|Recent sign in') + s_("SortOptions|Recent sign in") end def sort_title_recently_updated - s_('SortOptions|Last updated') + s_("SortOptions|Last updated") end def sort_title_start_date_later - s_('SortOptions|Start later') + s_("SortOptions|Start later") end def sort_title_start_date_soon - s_('SortOptions|Start soon') + s_("SortOptions|Start soon") end def sort_title_upvotes - s_('SortOptions|Most popular') + s_("SortOptions|Most popular") end def sort_title_contacted_date - s_('SortOptions|Last Contact') + s_("SortOptions|Last Contact") end def sort_title_most_stars - s_('SortOptions|Most stars') + s_("SortOptions|Most stars") end def sort_title_oldest_last_activity - s_('SortOptions|Oldest last activity') + s_("SortOptions|Oldest last activity") end def sort_title_recently_last_activity - s_('SortOptions|Recent last activity') + s_("SortOptions|Recent last activity") end # Values. def sort_value_access_level_asc - 'access_level_asc' + "access_level_asc" end def sort_value_access_level_desc - 'access_level_desc' + "access_level_desc" end def sort_value_created_date - 'created_date' + "created_date" end def sort_value_downvotes - 'downvotes_desc' + "downvotes_desc" end def sort_value_due_date - 'due_date' + "due_date" end def sort_value_due_date_later - 'due_date_desc' + "due_date_desc" end def sort_value_due_date_soon - 'due_date_asc' + "due_date_asc" end def sort_value_label_priority - 'label_priority' + "label_priority" end def sort_value_largest_group - 'storage_size_desc' + "storage_size_desc" end def sort_value_largest_repo - 'storage_size_desc' + "storage_size_desc" end def sort_value_last_joined - 'last_joined' + "last_joined" end def sort_value_latest_activity - 'latest_activity_desc' + "latest_activity_desc" end def sort_value_milestone - 'milestone' + "milestone" end def sort_value_milestone_later - 'milestone_due_desc' + "milestone_due_desc" end def sort_value_milestone_soon - 'milestone_due_asc' + "milestone_due_asc" end def sort_value_name - 'name_asc' + "name_asc" end def sort_value_name_desc - 'name_desc' + "name_desc" end def sort_value_oldest_activity - 'latest_activity_asc' + "latest_activity_asc" end def sort_value_oldest_created - 'created_asc' + "created_asc" end def sort_value_oldest_signin - 'oldest_sign_in' + "oldest_sign_in" end def sort_value_oldest_joined - 'oldest_joined' + "oldest_joined" end def sort_value_oldest_updated - 'updated_asc' + "updated_asc" end def sort_value_popularity - 'popularity' + "popularity" end def sort_value_priority - 'priority' + "priority" end def sort_value_recently_created - 'created_desc' + "created_desc" end def sort_value_recently_signin - 'recent_sign_in' + "recent_sign_in" end def sort_value_recently_updated - 'updated_desc' + "updated_desc" end def sort_value_start_date_later - 'start_date_desc' + "start_date_desc" end def sort_value_start_date_soon - 'start_date_asc' + "start_date_asc" end def sort_value_upvotes - 'upvotes_desc' + "upvotes_desc" end def sort_value_contacted_date - 'contacted_asc' + "contacted_asc" end def sort_value_most_stars - 'stars_desc' + "stars_desc" end def sort_value_oldest_last_activity - 'last_activity_on_asc' + "last_activity_on_asc" end def sort_value_recently_last_activity - 'last_activity_on_desc' + "last_activity_on_desc" end end diff --git a/app/helpers/storage_helper.rb b/app/helpers/storage_helper.rb index be8761db562..0f8df476299 100644 --- a/app/helpers/storage_helper.rb +++ b/app/helpers/storage_helper.rb @@ -4,6 +4,6 @@ module StorageHelper def storage_counter(size_in_bytes) precision = size_in_bytes < 1.megabyte ? 0 : 1 - number_to_human_size(size_in_bytes, delimiter: ',', precision: precision, significant: false) + number_to_human_size(size_in_bytes, delimiter: ",", precision: precision, significant: false) end end diff --git a/app/helpers/submodule_helper.rb b/app/helpers/submodule_helper.rb index 164c69ca50b..3251f4e0444 100644 --- a/app/helpers/submodule_helper.rb +++ b/app/helpers/submodule_helper.rb @@ -9,35 +9,35 @@ module SubmoduleHelper def submodule_links(submodule_item, ref = nil, repository = @repository) url = repository.submodule_url_for(ref, submodule_item.path) - if url == '.' || url == './' + if url == "." || url == "./" url = File.join(Gitlab.config.gitlab.url, repository.project.full_path) end if url =~ %r{([^/:]+)/([^/]+(?:\.git)?)\Z} namespace, project = $1, $2 gitlab_hosts = [Gitlab.config.gitlab.url, - Gitlab.config.gitlab_shell.ssh_path_prefix] + Gitlab.config.gitlab_shell.ssh_path_prefix,] gitlab_hosts.each do |host| if url.start_with?(host) - namespace, _, project = url.sub(host, '').rpartition('/') + namespace, _, project = url.sub(host, "").rpartition("/") break end end - namespace.sub!(%r{\A/}, '') + namespace.sub!(%r{\A/}, "") project.rstrip! - project.sub!(/\.git\z/, '') + project.sub!(/\.git\z/, "") if self_url?(url, namespace, project) [namespace_project_path(namespace, project), - namespace_project_tree_path(namespace, project, submodule_item.id)] + namespace_project_tree_path(namespace, project, submodule_item.id),] elsif relative_self_url?(url) relative_self_links(url, submodule_item.id, repository.project) elsif github_dot_com_url?(url) - standard_links('github.com', namespace, project, submodule_item.id) + standard_links("github.com", namespace, project, submodule_item.id) elsif gitlab_dot_com_url?(url) - standard_links('gitlab.com', namespace, project, submodule_item.id) + standard_links("gitlab.com", namespace, project, submodule_item.id) else [sanitize_submodule_url(url), nil] end @@ -57,21 +57,21 @@ module SubmoduleHelper end def self_url?(url, namespace, project) - url_no_dotgit = url.chomp('.git') - return true if url_no_dotgit == [Gitlab.config.gitlab.url, '/', namespace, '/', - project].join('') + url_no_dotgit = url.chomp(".git") + return true if url_no_dotgit == [Gitlab.config.gitlab.url, "/", namespace, "/", + project,].join("") - url_with_dotgit = url_no_dotgit + '.git' - url_with_dotgit == Gitlab::Shell.new.url_to_repo([namespace, '/', project].join('')) + url_with_dotgit = url_no_dotgit + ".git" + url_with_dotgit == Gitlab::Shell.new.url_to_repo([namespace, "/", project].join("")) end def relative_self_url?(url) - url.start_with?('../', './') + url.start_with?("../", "./") end def standard_links(host, namespace, project, commit) - base = ['https://', host, '/', namespace, '/', project].join('') - [base, [base, '/tree/', commit].join('')] + base = ["https://", host, "/", namespace, "/", project].join("") + [base, [base, "/tree/", commit].join("")] end def relative_self_links(relative_path, commit, project) @@ -86,17 +86,17 @@ module SubmoduleHelper submodule_project_path = File.absolute_path(relative_path, absolute_project_path) target_namespace_path = File.dirname(submodule_project_path) - if target_namespace_path == '/' || target_namespace_path.start_with?(absolute_project_path) + if target_namespace_path == "/" || target_namespace_path.start_with?(absolute_project_path) return [nil, nil] end - target_namespace_path.sub!(%r{^/}, '') - submodule_base = File.basename(submodule_project_path, '.git') + target_namespace_path.sub!(%r{^/}, "") + submodule_base = File.basename(submodule_project_path, ".git") begin [ namespace_project_path(target_namespace_path, submodule_base), - namespace_project_tree_path(target_namespace_path, submodule_base, commit) + namespace_project_tree_path(target_namespace_path, submodule_base, commit), ] rescue ActionController::UrlGenerationError [nil, nil] @@ -108,8 +108,6 @@ module SubmoduleHelper if uri.scheme.in?(VALID_SUBMODULE_PROTOCOLS) uri.to_s - else - nil end rescue URI::InvalidURIError nil diff --git a/app/helpers/system_note_helper.rb b/app/helpers/system_note_helper.rb index ac4e8f54260..d886712b522 100644 --- a/app/helpers/system_note_helper.rb +++ b/app/helpers/system_note_helper.rb @@ -2,29 +2,29 @@ module SystemNoteHelper ICON_NAMES_BY_ACTION = { - 'commit' => 'commit', - 'description' => 'pencil-square', - 'merge' => 'git-merge', - 'merged' => 'git-merge', - 'opened' => 'issue-open', - 'closed' => 'issue-close', - 'time_tracking' => 'timer', - 'assignee' => 'user', - 'title' => 'pencil-square', - 'task' => 'task-done', - 'label' => 'label', - 'cross_reference' => 'comment-dots', - 'branch' => 'fork', - 'confidential' => 'eye-slash', - 'visible' => 'eye', - 'milestone' => 'clock', - 'discussion' => 'comment', - 'moved' => 'arrow-right', - 'outdated' => 'pencil-square', - 'duplicate' => 'issue-duplicate', - 'locked' => 'lock', - 'unlocked' => 'lock-open', - 'due_date' => 'calendar' + "commit" => "commit", + "description" => "pencil-square", + "merge" => "git-merge", + "merged" => "git-merge", + "opened" => "issue-open", + "closed" => "issue-close", + "time_tracking" => "timer", + "assignee" => "user", + "title" => "pencil-square", + "task" => "task-done", + "label" => "label", + "cross_reference" => "comment-dots", + "branch" => "fork", + "confidential" => "eye-slash", + "visible" => "eye", + "milestone" => "clock", + "discussion" => "comment", + "moved" => "arrow-right", + "outdated" => "pencil-square", + "duplicate" => "issue-duplicate", + "locked" => "lock", + "unlocked" => "lock-open", + "due_date" => "calendar", }.freeze def system_note_icon_name(note) diff --git a/app/helpers/tab_helper.rb b/app/helpers/tab_helper.rb index d91f0f78db7..c1d823cb151 100644 --- a/app/helpers/tab_helper.rb +++ b/app/helpers/tab_helper.rb @@ -58,12 +58,12 @@ module TabHelper # # Returns a list item element String def nav_link(options = {}, &block) - klass = active_nav_link?(options) ? 'active' : '' + klass = active_nav_link?(options) ? "active" : "" # Add our custom class into the html_options, which may or may not exist # and which may or may not already have a :class key o = options.delete(:html_options) || {} - o[:class] = [*o[:class], klass].join(' ').strip + o[:class] = [*o[:class], klass].join(" ").strip if block_given? content_tag(:li, capture(&block), o) @@ -104,16 +104,16 @@ module TabHelper end def current_path?(path) - c, a, _ = path.split('#') + c, a, _ = path.split("#") current_controller?(c) && current_action?(a) end def project_tab_class - if controller.controller_path.start_with?('projects') - return 'active' + if controller.controller_path.start_with?("projects") + return "active" end - if %w(services hooks deploy_keys protected_branches).include? controller.controller_name + if %w[services hooks deploy_keys protected_branches].include? controller.controller_name "active" end end @@ -122,15 +122,15 @@ module TabHelper if current_controller?(:protected_branches) || current_controller?(:branches) || current_page?(project_repository_path(@project)) - 'active' + "active" end end def profile_tab_class - if controller.controller_path.start_with?('profiles') - return 'active' + if controller.controller_path.start_with?("profiles") + return "active" end - 'active' if current_controller?('oauth/applications') + "active" if current_controller?("oauth/applications") end end diff --git a/app/helpers/tags_helper.rb b/app/helpers/tags_helper.rb index de0b92b6fd7..e065f152a7f 100644 --- a/app/helpers/tags_helper.rb +++ b/app/helpers/tags_helper.rb @@ -8,7 +8,7 @@ module TagsHelper def filter_tags_path(options = {}) exist_opts = { search: params[:search], - sort: params[:sort] + sort: params[:sort], } options = exist_opts.merge(options) diff --git a/app/helpers/todos_helper.rb b/app/helpers/todos_helper.rb index 6bd78336ed3..39178b77ac6 100644 --- a/app/helpers/todos_helper.rb +++ b/app/helpers/todos_helper.rb @@ -6,7 +6,7 @@ module TodosHelper end def todos_count_format(count) - count > 99 ? '99+' : count.to_s + count > 99 ? "99+" : count.to_s end def todos_done_count @@ -15,12 +15,12 @@ module TodosHelper def todo_action_name(todo) case todo.action - when Todo::ASSIGNED then todo.self_added? ? 'assigned' : 'assigned you' + when Todo::ASSIGNED then todo.self_added? ? "assigned" : "assigned you" when Todo::MENTIONED then "mentioned #{todo_action_subject(todo)} on" - when Todo::BUILD_FAILED then 'The build failed for' - when Todo::MARKED then 'added a todo for' + when Todo::BUILD_FAILED then "The build failed for" + when Todo::MARKED then "added a todo for" when Todo::APPROVAL_REQUIRED then "set #{todo_action_subject(todo)} as an approver for" - when Todo::UNMERGEABLE then 'Could not merge' + when Todo::UNMERGEABLE then "Could not merge" when Todo::DIRECTLY_ADDRESSED then "directly addressed #{todo_action_subject(todo)} on" end end @@ -28,12 +28,12 @@ module TodosHelper def todo_target_link(todo) text = raw("#{todo.target_type.titleize.downcase} ") + if todo.for_commit? - content_tag(:span, todo.target_reference, class: 'commit-sha') + content_tag(:span, todo.target_reference, class: "commit-sha") else todo.target_reference end - link_to text, todo_target_path(todo), class: 'has-tooltip', title: todo.target.title + link_to text, todo_target_path(todo), class: "has-tooltip", title: todo.target.title end def todo_target_path(todo) @@ -43,7 +43,7 @@ module TodosHelper if todo.for_commit? project_commit_path(todo.project, - todo.target, anchor: anchor) + todo.target, anchor: anchor) else path = [todo.parent, todo.target] @@ -59,12 +59,12 @@ module TodosHelper type = case todo.target when MergeRequest - 'mr' + "mr" when Issue - 'issue' + "issue" end - content_tag(:span, nil, class: 'target-status') do + content_tag(:span, nil, class: "target-status") do content_tag(:span, nil, class: "status-box status-box-#{type}-#{todo.target.state.dasherize}") do todo.target.state.capitalize end @@ -73,11 +73,11 @@ module TodosHelper def todos_filter_params { - state: params[:state], + state: params[:state], project_id: params[:project_id], - author_id: params[:author_id], - type: params[:type], - action_id: params[:action_id] + author_id: params[:author_id], + type: params[:type], + action_id: params[:action_id], } end @@ -101,30 +101,30 @@ module TodosHelper def todo_actions_options [ - { id: '', text: 'Any Action' }, - { id: Todo::ASSIGNED, text: 'Assigned' }, - { id: Todo::MENTIONED, text: 'Mentioned' }, - { id: Todo::MARKED, text: 'Added' }, - { id: Todo::BUILD_FAILED, text: 'Pipelines' }, - { id: Todo::DIRECTLY_ADDRESSED, text: 'Directly addressed' } + {id: "", text: "Any Action"}, + {id: Todo::ASSIGNED, text: "Assigned"}, + {id: Todo::MENTIONED, text: "Mentioned"}, + {id: Todo::MARKED, text: "Added"}, + {id: Todo::BUILD_FAILED, text: "Pipelines"}, + {id: Todo::DIRECTLY_ADDRESSED, text: "Directly addressed"}, ] end def todo_projects_options projects = current_user.authorized_projects.sorted_by_activity.non_archived.with_route - projects = projects.map do |project| - { id: project.id, text: project.full_name } - end + projects = projects.map { |project| + {id: project.id, text: project.full_name} + } - projects.unshift({ id: '', text: 'Any Project' }).to_json + projects.unshift({id: "", text: "Any Project"}).to_json end def todo_types_options [ - { id: '', text: 'Any Type' }, - { id: 'Issue', text: 'Issue' }, - { id: 'MergeRequest', text: 'Merge Request' } + {id: "", text: "Any Type"}, + {id: "Issue", text: "Issue"}, + {id: "MergeRequest", text: "Merge Request"}, ] end @@ -134,7 +134,7 @@ module TodosHelper end def todo_types_dropdown_label(selected_type, default_type) - selected_type = todo_types_options.find { |type| type[:id] == selected_type && type[:id] != '' } + selected_type = todo_types_options.find { |type| type[:id] == selected_type && type[:id] != "" } selected_type ? selected_type[:text] : default_type end @@ -145,16 +145,16 @@ module TodosHelper is_overdue = todo.target.overdue? css_class = if is_due_today - 'text-warning' + "text-warning" elsif is_overdue - 'text-danger' + "text-danger" else - '' + "" end - content = content_tag(:span, class: css_class) do + content = content_tag(:span, class: css_class) { "Due #{is_due_today ? "today" : todo.target.due_date.to_s(:medium)}" - end + } "· #{content}".html_safe end @@ -162,18 +162,18 @@ module TodosHelper private def todo_action_subject(todo) - todo.self_added? ? 'yourself' : 'you' + todo.self_added? ? "yourself" : "you" end def show_todo_state?(todo) - (todo.target.is_a?(MergeRequest) || todo.target.is_a?(Issue)) && %w(closed merged).include?(todo.target.state) + (todo.target.is_a?(MergeRequest) || todo.target.is_a?(Issue)) && %w[closed merged].include?(todo.target.state) end def todo_group_options - groups = current_user.authorized_groups.map do |group| - { id: group.id, text: group.full_name } - end + groups = current_user.authorized_groups.map { |group| + {id: group.id, text: group.full_name} + } - groups.unshift({ id: '', text: 'Any Group' }).to_json + groups.unshift({id: "", text: "Any Group"}).to_json end end diff --git a/app/helpers/tree_helper.rb b/app/helpers/tree_helper.rb index e2879bfdcf1..8eed6664e38 100644 --- a/app/helpers/tree_helper.rb +++ b/app/helpers/tree_helper.rb @@ -15,12 +15,12 @@ module TreeHelper items = (folders + submodules).sort_by(&:name) + files if items.size > FILE_LIMIT - tree << render(partial: 'projects/tree/truncated_notice_tree_row', - locals: { limit: FILE_LIMIT, total: items.size }) + tree << render(partial: "projects/tree/truncated_notice_tree_row", + locals: {limit: FILE_LIMIT, total: items.size}) items = items.take(FILE_LIMIT) end - tree << render(partial: 'projects/tree/tree_row', collection: items) if items.present? + tree << render(partial: "projects/tree/tree_row", collection: items) if items.present? tree.join.html_safe end # rubocop: enable CodeReuse/ActiveRecord @@ -31,20 +31,20 @@ module TreeHelper # mode - File unix mode # name - File name def tree_icon(type, mode, name) - icon([file_type_icon_class(type, mode, name), 'fw']) + icon([file_type_icon_class(type, mode, name), "fw"]) end # Using Rails `*_path` methods can be slow, especially when generating # many paths, as with a repository tree that has thousands of items. def fast_project_blob_path(project, blob_path) ActionDispatch::Journey::Router::Utils.escape_path( - File.join(relative_url_root, project.path_with_namespace, 'blob', blob_path) + File.join(relative_url_root, project.path_with_namespace, "blob", blob_path) ) end def fast_project_tree_path(project, tree_path) ActionDispatch::Journey::Router::Utils.escape_path( - File.join(relative_url_root, project.path_with_namespace, 'tree', tree_path) + File.join(relative_url_root, project.path_with_namespace, "tree", tree_path) ) end @@ -73,14 +73,14 @@ module TreeHelper ref else project = tree_edit_project(project) - project.repository.next_branch('patch') + project.repository.next_branch("patch") end end def tree_edit_project(project = @project) if can?(current_user, :push_code, project) project - elsif current_user && current_user.already_forked?(project) + elsif current_user&.already_forked?(project) current_user.fork_of(project) end end @@ -107,7 +107,7 @@ module TreeHelper branch_name = ERB::Util.html_escape(selected_branch) message = _("Your changes can be committed to %{branch_name} because a merge "\ - "request is open.") % { branch_name: "<strong>#{branch_name}</strong>" } + "request is open.") % {branch_name: "<strong>#{branch_name}</strong>"} message.html_safe end @@ -115,9 +115,9 @@ module TreeHelper def path_breadcrumbs(max_links = 6) if @path.present? part_path = "" - parts = @path.split('/') + parts = @path.split("/") - yield('..', File.join(*parts.first(parts.count - 2))) if parts.count > max_links + yield("..", File.join(*parts.first(parts.count - 2))) if parts.count > max_links parts.each do |part| part_path = File.join(part_path, part) unless part_path.empty? @@ -138,7 +138,7 @@ module TreeHelper # returns the relative path of the first subdir that doesn't have only one directory descendant # rubocop: disable CodeReuse/ActiveRecord def flatten_tree(root_path, tree) - return tree.flat_path.sub(%r{\A#{Regexp.escape(root_path)}/}, '') if tree.flat_path.present? + return tree.flat_path.sub(%r{\A#{Regexp.escape(root_path)}/}, "") if tree.flat_path.present? subtree = Gitlab::Git::Tree.where(@repository, @commit.id, tree.path) if subtree.count == 1 && subtree.first.dir? @@ -154,6 +154,6 @@ module TreeHelper end def relative_url_root - Gitlab.config.gitlab.relative_url_root.presence || '/' + Gitlab.config.gitlab.relative_url_root.presence || "/" end end diff --git a/app/helpers/user_callouts_helper.rb b/app/helpers/user_callouts_helper.rb index 1ad7bb81784..667ad4ba825 100644 --- a/app/helpers/user_callouts_helper.rb +++ b/app/helpers/user_callouts_helper.rb @@ -1,8 +1,8 @@ # frozen_string_literal: true module UserCalloutsHelper - GKE_CLUSTER_INTEGRATION = 'gke_cluster_integration'.freeze - GCP_SIGNUP_OFFER = 'gcp_signup_offer'.freeze + GKE_CLUSTER_INTEGRATION = "gke_cluster_integration" + GCP_SIGNUP_OFFER = "gcp_signup_offer" def show_gke_cluster_integration_callout?(project) can?(current_user, :create_cluster, project) && @@ -14,7 +14,7 @@ module UserCalloutsHelper end def render_flash_user_callout(flash_type, message, feature_name) - render 'shared/flash_user_callout', flash_type: flash_type, message: message, feature_name: feature_name + render "shared/flash_user_callout", flash_type: flash_type, message: message, feature_name: feature_name end private diff --git a/app/helpers/users_helper.rb b/app/helpers/users_helper.rb index 73ca17c6605..79ecc45bb2e 100644 --- a/app/helpers/users_helper.rb +++ b/app/helpers/users_helper.rb @@ -3,17 +3,17 @@ module UsersHelper def user_link(user) link_to(user.name, user_path(user), - title: user.email, - class: 'has-tooltip commit-committer-link') + title: user.email, + class: "has-tooltip commit-committer-link") end def user_email_help_text(user) - return 'We also use email for avatar detection if no avatar is uploaded' unless user.unconfirmed_email.present? + return "We also use email for avatar detection if no avatar is uploaded" unless user.unconfirmed_email.present? - confirmation_link = link_to 'Resend confirmation e-mail', user_confirmation_path(user: { email: @user.unconfirmed_email }), method: :post + confirmation_link = link_to "Resend confirmation e-mail", user_confirmation_path(user: {email: @user.unconfirmed_email}), method: :post - h('Please click the link in the confirmation email before continuing. It was sent to ') + - content_tag(:strong) { user.unconfirmed_email } + h('.') + + h("Please click the link in the confirmation email before continuing. It was sent to ") + + content_tag(:strong) { user.unconfirmed_email } + h(".") + content_tag(:p) { confirmation_link } end @@ -29,11 +29,11 @@ module UsersHelper settings = Gitlab::CurrentSettings.current_application_settings pattern, options = if settings.user_default_internal_regex_enabled? - regex = settings.user_default_internal_regex_instance - JsRegex.new(regex).to_h.slice(:source, :options).values - end + regex = settings.user_default_internal_regex_instance + JsRegex.new(regex).to_h.slice(:source, :options).values + end - { user_internal_regex_pattern: pattern, user_internal_regex_options: options } + {user_internal_regex_pattern: pattern, user_internal_regex_options: options} end def current_user_menu_items @@ -57,15 +57,15 @@ module UsersHelper unless user.association(:status).loaded? exception = RuntimeError.new("Status was not preloaded") - Gitlab::Sentry.track_exception(exception, extra: { user: user.inspect }) + Gitlab::Sentry.track_exception(exception, extra: {user: user.inspect}) end return unless user.status content_tag :span, - class: 'user-status-emoji has-tooltip', - title: user.status.message_html, - data: { html: true, placement: 'top' } do + class: "user-status-emoji has-tooltip", + title: user.status.message_html, + data: {html: true, placement: "top"} do emoji_icon user.status.emoji end end @@ -76,10 +76,10 @@ module UsersHelper def user_badges_in_admin_section(user) [].tap do |badges| - badges << { text: s_('AdminUsers|Blocked'), variant: 'danger' } if user.blocked? - badges << { text: s_('AdminUsers|Admin'), variant: 'success' } if user.admin? - badges << { text: s_('AdminUsers|External'), variant: 'secondary' } if user.external? - badges << { text: s_("AdminUsers|It's you!"), variant: nil } if current_user == user + badges << {text: s_("AdminUsers|Blocked"), variant: "danger"} if user.blocked? + badges << {text: s_("AdminUsers|Admin"), variant: "success"} if user.admin? + badges << {text: s_("AdminUsers|External"), variant: "secondary"} if user.external? + badges << {text: s_("AdminUsers|It's you!"), variant: nil} if current_user == user end end diff --git a/app/helpers/version_check_helper.rb b/app/helpers/version_check_helper.rb index 5e519cf5c19..a947dfa2c7d 100644 --- a/app/helpers/version_check_helper.rb +++ b/app/helpers/version_check_helper.rb @@ -6,19 +6,19 @@ module VersionCheckHelper return unless Gitlab::CurrentSettings.version_check_enabled return if User.single_user&.requires_usage_stats_consent? - image_tag VersionCheck.url, class: 'js-version-status-badge' + image_tag VersionCheck.url, class: "js-version-status-badge" end def link_to_version if Gitlab.pre_release? - commit_link = link_to(Gitlab.revision, Gitlab::COM_URL + namespace_project_commits_path('gitlab-org', source_code_project, Gitlab.revision)) - [Gitlab::VERSION, content_tag(:small, commit_link)].join(' ').html_safe + commit_link = link_to(Gitlab.revision, Gitlab::COM_URL + namespace_project_commits_path("gitlab-org", source_code_project, Gitlab.revision)) + [Gitlab::VERSION, content_tag(:small, commit_link)].join(" ").html_safe else - link_to Gitlab::VERSION, Gitlab::COM_URL + namespace_project_tag_path('gitlab-org', source_code_project, "v#{Gitlab::VERSION}") + link_to Gitlab::VERSION, Gitlab::COM_URL + namespace_project_tag_path("gitlab-org", source_code_project, "v#{Gitlab::VERSION}") end end def source_code_project - 'gitlab-ce' + "gitlab-ce" end end diff --git a/app/helpers/visibility_level_helper.rb b/app/helpers/visibility_level_helper.rb index 712f0f808dd..0a00beca8d5 100644 --- a/app/helpers/visibility_level_helper.rb +++ b/app/helpers/visibility_level_helper.rb @@ -4,11 +4,11 @@ module VisibilityLevelHelper def visibility_level_color(level) case level when Gitlab::VisibilityLevel::PRIVATE - 'vs-private' + "vs-private" when Gitlab::VisibilityLevel::INTERNAL - 'vs-internal' + "vs-internal" when Gitlab::VisibilityLevel::PUBLIC - 'vs-public' + "vs-public" end end @@ -97,7 +97,7 @@ module VisibilityLevelHelper instructions << errors[:instruction] end - reasons = reasons.any? ? ' because ' + reasons.to_sentence : '' + reasons = reasons.any? ? " because " + reasons.to_sentence : "" "This project cannot be #{level_name}#{reasons}.#{instructions.join}".html_safe end @@ -123,7 +123,7 @@ module VisibilityLevelHelper instructions << errors[:instruction] end - reasons = reasons.any? ? ' because ' + reasons.to_sentence : '' + reasons = reasons.any? ? " because " + reasons.to_sentence : "" "This group cannot be #{level_name}#{reasons}.#{instructions.join}".html_safe end @@ -155,9 +155,9 @@ module VisibilityLevelHelper Gitlab::CurrentSettings.restricted_visibility_levels || [] end - delegate :default_project_visibility, - :default_group_visibility, - to: :'Gitlab::CurrentSettings.current_application_settings' + delegate :default_project_visibility, + :default_group_visibility, + to: :'Gitlab::CurrentSettings.current_application_settings' def disallowed_visibility_level?(form_model, level) return false unless form_model.respond_to?(:visibility_level_allowed?) @@ -169,9 +169,9 @@ module VisibilityLevelHelper def visibility_level_errors_for_group(group, level_name) group_name = link_to group.name, group_path(group) - change_visiblity = link_to 'change the visibility', edit_group_path(group) + change_visiblity = link_to "change the visibility", edit_group_path(group) - { reason: "the visibility of #{group_name} is #{group.visibility}", - instruction: " To make this group #{level_name}, you must first #{change_visiblity} of the parent group." } + {reason: "the visibility of #{group_name} is #{group.visibility}", + instruction: " To make this group #{level_name}, you must first #{change_visiblity} of the parent group.",} end end diff --git a/app/helpers/webpack_helper.rb b/app/helpers/webpack_helper.rb index 345ddcf023a..7f6a3f775cd 100644 --- a/app/helpers/webpack_helper.rb +++ b/app/helpers/webpack_helper.rb @@ -9,17 +9,17 @@ module WebpackHelper chunks = [] action = case controller.action_name - when 'create' then 'new' - when 'update' then 'edit' + when "create" then "new" + when "update" then "edit" else controller.action_name - end + end - route = [*controller.controller_path.split('/'), action].compact + route = [*controller.controller_path.split("/"), action].compact until chunks.any? || route.empty? - entrypoint = "pages.#{route.join('.')}" + entrypoint = "pages.#{route.join(".")}" begin - chunks = webpack_entrypoint_paths(entrypoint, extension: 'js') + chunks = webpack_entrypoint_paths(entrypoint, extension: "js") rescue Gitlab::Webpack::Manifest::AssetMissingError # no bundle exists for this path end @@ -27,7 +27,7 @@ module WebpackHelper end if chunks.empty? - chunks = webpack_entrypoint_paths("default", extension: 'js') + chunks = webpack_entrypoint_paths("default", extension: "js") end javascript_include_tag(*chunks) @@ -60,16 +60,16 @@ module WebpackHelper if Rails.env.test? && Rails.configuration.webpack.dev_server.enabled host = Rails.configuration.webpack.dev_server.host port = Rails.configuration.webpack.dev_server.port - protocol = Rails.configuration.webpack.dev_server.https ? 'https' : 'http' + protocol = Rails.configuration.webpack.dev_server.https ? "https" : "http" "#{protocol}://#{host}:#{port}" else - ActionController::Base.asset_host.try(:chomp, '/') + ActionController::Base.asset_host.try(:chomp, "/") end end def webpack_public_path relative_path = Rails.application.config.relative_url_root webpack_path = Rails.application.config.webpack.public_path - File.join(webpack_public_host.to_s, relative_path.to_s, webpack_path.to_s, '') + File.join(webpack_public_host.to_s, relative_path.to_s, webpack_path.to_s, "") end end diff --git a/app/helpers/wiki_helper.rb b/app/helpers/wiki_helper.rb index 647f34e57ed..9f346f1c818 100644 --- a/app/helpers/wiki_helper.rb +++ b/app/helpers/wiki_helper.rb @@ -10,13 +10,13 @@ module WikiHelper # Returns a String composed of the capitalized name of each directory and the # capitalized name of the page itself. def breadcrumb(page_slug) - page_slug.split('/') + page_slug.split("/") .map { |dir_or_page| WikiPage.unhyphenize(dir_or_page).capitalize } - .join(' / ') + .join(" / ") end def wiki_breadcrumb_dropdown_links(page_slug) - page_slug_split = page_slug.split('/') + page_slug_split = page_slug.split("/") page_slug_split.pop(1) current_slug = "" page_slug_split @@ -29,12 +29,12 @@ module WikiHelper def wiki_page_errors(error) return unless error - content_tag(:div, class: 'alert alert-danger') do + content_tag(:div, class: "alert alert-danger") do case error when WikiPage::PageChangedError page_link = link_to s_("WikiPageConflictMessage|the page"), project_wiki_path(@project, @page), target: "_blank" concat( - (s_("WikiPageConflictMessage|Someone edited the page the same time you did. Please check out %{page_link} and make sure your changes will not unintentionally remove theirs.") % { page_link: page_link }).html_safe + (s_("WikiPageConflictMessage|Someone edited the page the same time you did. Please check out %{page_link} and make sure your changes will not unintentionally remove theirs.") % {page_link: page_link}).html_safe ) when WikiPage::PageRenameError s_("WikiEdit|There is already a page with the same title in that path.") diff --git a/app/helpers/workhorse_helper.rb b/app/helpers/workhorse_helper.rb index bb5b1555dc4..6259946168f 100644 --- a/app/helpers/workhorse_helper.rb +++ b/app/helpers/workhorse_helper.rb @@ -7,7 +7,7 @@ module WorkhorseHelper def send_git_blob(repository, blob, inline: true) headers.store(*Gitlab::Workhorse.send_git_blob(repository, blob)) - headers['Content-Disposition'] = inline ? 'inline' : 'attachment' + headers["Content-Disposition"] = inline ? "inline" : "attachment" # If enabled, this will override the values set above workhorse_set_content_type! @@ -18,14 +18,14 @@ module WorkhorseHelper # Send a Git diff through Workhorse def send_git_diff(repository, diff_refs) headers.store(*Gitlab::Workhorse.send_git_diff(repository, diff_refs)) - headers['Content-Disposition'] = 'inline' + headers["Content-Disposition"] = "inline" head :ok end # Send a Git patch through Workhorse def send_git_patch(repository, diff_refs) headers.store(*Gitlab::Workhorse.send_git_patch(repository, diff_refs)) - headers['Content-Disposition'] = 'inline' + headers["Content-Disposition"] = "inline" head :ok end @@ -42,7 +42,7 @@ module WorkhorseHelper end def set_workhorse_internal_api_content_type - headers['Content-Type'] = Gitlab::Workhorse::INTERNAL_API_CONTENT_TYPE + headers["Content-Type"] = Gitlab::Workhorse::INTERNAL_API_CONTENT_TYPE end def workhorse_set_content_type! diff --git a/app/mailers/abuse_report_mailer.rb b/app/mailers/abuse_report_mailer.rb index e0aa66e6de3..41aa27ed8de 100644 --- a/app/mailers/abuse_report_mailer.rb +++ b/app/mailers/abuse_report_mailer.rb @@ -1,7 +1,7 @@ # frozen_string_literal: true class AbuseReportMailer < BaseMailer - layout 'empty_mailer' + layout "empty_mailer" helper EmailsHelper @@ -11,8 +11,8 @@ class AbuseReportMailer < BaseMailer @abuse_report = AbuseReport.find(abuse_report_id) mail( - to: Gitlab::CurrentSettings.admin_notification_email, - subject: "#{@abuse_report.user.name} (#{@abuse_report.user.username}) was reported for abuse" + to: Gitlab::CurrentSettings.admin_notification_email, + subject: "#{@abuse_report.user.name} (#{@abuse_report.user.username}) was reported for abuse" ) end diff --git a/app/mailers/devise_mailer.rb b/app/mailers/devise_mailer.rb index 7aa75ee30e6..f018364a1a9 100644 --- a/app/mailers/devise_mailer.rb +++ b/app/mailers/devise_mailer.rb @@ -4,7 +4,7 @@ class DeviseMailer < Devise::Mailer default from: "#{Gitlab.config.gitlab.email_display_name} <#{Gitlab.config.gitlab.email_from}>" default reply_to: Gitlab.config.gitlab.email_reply_to - layout 'mailer/devise' + layout "mailer/devise" helper EmailsHelper @@ -14,6 +14,6 @@ class DeviseMailer < Devise::Mailer subject = [super] subject << Gitlab.config.gitlab.email_subject_suffix if Gitlab.config.gitlab.email_subject_suffix.present? - subject.join(' | ') + subject.join(" | ") end end diff --git a/app/mailers/email_rejection_mailer.rb b/app/mailers/email_rejection_mailer.rb index d743533b1bc..781517c360f 100644 --- a/app/mailers/email_rejection_mailer.rb +++ b/app/mailers/email_rejection_mailer.rb @@ -1,7 +1,7 @@ # frozen_string_literal: true class EmailRejectionMailer < BaseMailer - layout 'empty_mailer' + layout "empty_mailer" helper EmailsHelper @@ -13,14 +13,14 @@ class EmailRejectionMailer < BaseMailer headers = { to: @original_message.from, - subject: "[Rejected] #{@original_message.subject}" + subject: "[Rejected] #{@original_message.subject}", } - headers['Message-ID'] = "<#{SecureRandom.hex}@#{Gitlab.config.gitlab.host}>" - headers['In-Reply-To'] = @original_message.message_id - headers['References'] = @original_message.message_id + headers["Message-ID"] = "<#{SecureRandom.hex}@#{Gitlab.config.gitlab.host}>" + headers["In-Reply-To"] = @original_message.message_id + headers["References"] = @original_message.message_id - headers['Reply-To'] = @original_message.to.first if can_retry + headers["Reply-To"] = @original_message.to.first if can_retry mail(headers) end diff --git a/app/mailers/emails/auto_devops.rb b/app/mailers/emails/auto_devops.rb index 9705a3052d4..7cd33cd9dcc 100644 --- a/app/mailers/emails/auto_devops.rb +++ b/app/mailers/emails/auto_devops.rb @@ -10,8 +10,8 @@ module Emails mail(to: recipient, subject: auto_devops_disabled_subject(@project.name)) do |format| - format.html { render layout: 'mailer' } - format.text { render layout: 'mailer' } + format.html { render layout: "mailer" } + format.text { render layout: "mailer" } end end diff --git a/app/mailers/emails/issues.rb b/app/mailers/emails/issues.rb index 654ae211310..0f91449ba50 100644 --- a/app/mailers/emails/issues.rb +++ b/app/mailers/emails/issues.rb @@ -57,7 +57,7 @@ module Emails @milestone = milestone @milestone_url = milestone_url(@milestone) mail_answer_thread(@issue, issue_thread_options(updated_by_user_id, recipient_id, reason).merge({ - template_name: 'changed_milestone_email' + template_name: "changed_milestone_email", })) end @@ -82,9 +82,9 @@ module Emails @project = Project.find(project_id) @results = results - mail(to: @user.notification_email, subject: subject('Imported issues')) do |format| - format.html { render layout: 'mailer' } - format.text { render layout: 'mailer' } + mail(to: @user.notification_email, subject: subject("Imported issues")) do |format| + format.html { render layout: "mailer" } + format.text { render layout: "mailer" } end end @@ -100,10 +100,10 @@ module Emails def issue_thread_options(sender_id, recipient_id, reason) { - from: sender(sender_id), - to: recipient(recipient_id), - subject: subject("#{@issue.title} (##{@issue.iid})"), - 'X-GitLab-NotificationReason' => reason + :from => sender(sender_id), + :to => recipient(recipient_id), + :subject => subject("#{@issue.title} (##{@issue.iid})"), + "X-GitLab-NotificationReason" => reason, } end end diff --git a/app/mailers/emails/members.rb b/app/mailers/emails/members.rb index 91dfdf58982..e77a9b01961 100644 --- a/app/mailers/emails/members.rb +++ b/app/mailers/emails/members.rb @@ -49,7 +49,7 @@ module Emails return unless member.created_by mail(to: member.created_by.notification_email, - subject: subject('Invitation accepted')) + subject: subject("Invitation accepted")) end def member_invite_declined_email(member_source_type, source_id, invite_email, created_by_id) @@ -61,7 +61,7 @@ module Emails inviter = User.find(created_by_id) mail(to: inviter.notification_email, - subject: subject('Invitation declined')) + subject: subject("Invitation declined")) end def member diff --git a/app/mailers/emails/merge_requests.rb b/app/mailers/emails/merge_requests.rb index 9ba8f92fcbf..e7568c8d319 100644 --- a/app/mailers/emails/merge_requests.rb +++ b/app/mailers/emails/merge_requests.rb @@ -52,7 +52,7 @@ module Emails @milestone = milestone @milestone_url = milestone_url(@milestone) mail_answer_thread(@merge_request, merge_request_thread_options(updated_by_user_id, recipient_id, reason).merge({ - template_name: 'changed_milestone_email' + template_name: "changed_milestone_email", })) end @@ -107,10 +107,10 @@ module Emails def merge_request_thread_options(sender_id, recipient_id, reason = nil) { - from: sender(sender_id), - to: recipient(recipient_id), - subject: subject("#{@merge_request.title} (#{@merge_request.to_reference})"), - 'X-GitLab-NotificationReason' => reason + :from => sender(sender_id), + :to => recipient(recipient_id), + :subject => subject("#{@merge_request.title} (#{@merge_request.to_reference})"), + "X-GitLab-NotificationReason" => reason, } end end diff --git a/app/mailers/emails/notes.rb b/app/mailers/emails/notes.rb index 1b3c1f9a8a9..342fa2755aa 100644 --- a/app/mailers/emails/notes.rb +++ b/app/mailers/emails/notes.rb @@ -52,7 +52,7 @@ module Emails { from: sender(@note.author_id), to: recipient(recipient_id), - subject: subject("#{@note.noteable.title} (#{@note.noteable.reference_link_text})") + subject: subject("#{@note.noteable.title} (#{@note.noteable.reference_link_text})"), } end diff --git a/app/mailers/emails/pipelines.rb b/app/mailers/emails/pipelines.rb index 31e183640ad..9f0315d9bd4 100644 --- a/app/mailers/emails/pipelines.rb +++ b/app/mailers/emails/pipelines.rb @@ -3,11 +3,11 @@ module Emails module Pipelines def pipeline_success_email(pipeline, recipients) - pipeline_mail(pipeline, recipients, 'succeeded') + pipeline_mail(pipeline, recipients, "succeeded") end def pipeline_failed_email(pipeline, recipients) - pipeline_mail(pipeline, recipients, 'failed') + pipeline_mail(pipeline, recipients, "failed") end private @@ -24,8 +24,8 @@ module Emails mail(bcc: recipients, subject: pipeline_subject(status), skip_premailer: true) do |format| - format.html { render layout: 'mailer' } - format.text { render layout: 'mailer' } + format.html { render layout: "mailer" } + format.text { render layout: "mailer" } end end @@ -35,16 +35,16 @@ module Emails end def add_pipeline_headers - headers['X-GitLab-Pipeline-Id'] = @pipeline.id - headers['X-GitLab-Pipeline-Ref'] = @pipeline.ref - headers['X-GitLab-Pipeline-Status'] = @pipeline.status + headers["X-GitLab-Pipeline-Id"] = @pipeline.id + headers["X-GitLab-Pipeline-Ref"] = @pipeline.ref + headers["X-GitLab-Pipeline-Status"] = @pipeline.status end def pipeline_subject(status) commit = [@pipeline.short_sha] commit << "in #{@merge_request.to_reference}" if @merge_request - subject("Pipeline ##{@pipeline.id} has #{status} for #{@pipeline.ref}", commit.join(' ')) + subject("Pipeline ##{@pipeline.id} has #{status} for #{@pipeline.ref}", commit.join(" ")) end end end diff --git a/app/mailers/emails/projects.rb b/app/mailers/emails/projects.rb index 2500622caa7..15f58f810c0 100644 --- a/app/mailers/emails/projects.rb +++ b/app/mailers/emails/projects.rb @@ -49,11 +49,11 @@ module Emails @diff_notes_disabled = true add_project_headers - headers['X-GitLab-Author'] = @message.author_username + headers["X-GitLab-Author"] = @message.author_username - mail(from: sender(@message.author_id, @message.send_from_committer_email?), - reply_to: @message.reply_to, - subject: @message.subject) + mail(from: sender(@message.author_id, @message.send_from_committer_email?), + reply_to: @message.reply_to, + subject: @message.subject) end end end diff --git a/app/mailers/emails/remote_mirrors.rb b/app/mailers/emails/remote_mirrors.rb index 2018eb7260b..4396ea82c13 100644 --- a/app/mailers/emails/remote_mirrors.rb +++ b/app/mailers/emails/remote_mirrors.rb @@ -6,7 +6,7 @@ module Emails @remote_mirror = RemoteMirrorFinder.new(id: remote_mirror_id).execute @project = @remote_mirror.project - mail(to: recipient(recipient_id), subject: subject('Remote mirror update failed')) + mail(to: recipient(recipient_id), subject: subject("Remote mirror update failed")) end end end diff --git a/app/mailers/notify.rb b/app/mailers/notify.rb index efa1233b434..7f3098e09a6 100644 --- a/app/mailers/notify.rb +++ b/app/mailers/notify.rb @@ -29,8 +29,7 @@ class Notify < BaseMailer mail(to: recipient_email, subject: subject, body: body.html_safe, - content_type: 'text/html' - ) + content_type: "text/html") end # Splits "gitlab.corp.company.com" up into "gitlab.corp.company.com", @@ -105,7 +104,7 @@ class Notify < BaseMailer subject.concat(extra) if extra.present? subject << Gitlab.config.gitlab.email_subject_suffix if Gitlab.config.gitlab.email_subject_suffix.present? - subject.join(' | ') + subject.join(" | ") end # Return a string suitable for inclusion in the 'Message-Id' mail header. @@ -122,18 +121,18 @@ class Notify < BaseMailer headers["X-GitLab-#{model.class.name}-ID"] = model.id headers["X-GitLab-#{model.class.name}-IID"] = model.iid if model.respond_to?(:iid) - headers['X-GitLab-Reply-Key'] = reply_key + headers["X-GitLab-Reply-Key"] = reply_key - @reason = headers['X-GitLab-NotificationReason'] + @reason = headers["X-GitLab-NotificationReason"] if Gitlab::IncomingEmail.enabled? && @sent_notification - headers['Reply-To'] = Mail::Address.new(Gitlab::IncomingEmail.reply_address(reply_key)).tap do |address| + headers["Reply-To"] = Mail::Address.new(Gitlab::IncomingEmail.reply_address(reply_key)).tap do |address| address.display_name = reply_display_name(model) end fallback_reply_message_id = "<reply-#{reply_key}@#{Gitlab.config.gitlab.host}>" - headers['References'] ||= [] - headers['References'].unshift(fallback_reply_message_id) + headers["References"] ||= [] + headers["References"].unshift(fallback_reply_message_id) @reply_by_email = true end @@ -151,7 +150,7 @@ class Notify < BaseMailer # # See: mail_answer_thread def mail_new_thread(model, headers = {}) - headers['Message-ID'] = message_id(model) + headers["Message-ID"] = message_id(model) mail_thread(model, headers) end @@ -165,9 +164,9 @@ class Notify < BaseMailer # * have a 'In-Reply-To' or 'References' header that references the original 'Message-ID' # def mail_answer_thread(model, headers = {}) - headers['Message-ID'] = "<#{SecureRandom.hex}@#{Gitlab.config.gitlab.host}>" - headers['In-Reply-To'] = message_id(model) - headers['References'] = [message_id(model)] + headers["Message-ID"] = "<#{SecureRandom.hex}@#{Gitlab.config.gitlab.host}>" + headers["In-Reply-To"] = message_id(model) + headers["References"] = [message_id(model)] headers[:subject] = "Re: #{headers[:subject]}" if headers[:subject] @@ -175,11 +174,11 @@ class Notify < BaseMailer end def mail_answer_note_thread(model, note, headers = {}) - headers['Message-ID'] = message_id(note) - headers['In-Reply-To'] = message_id(note.references.last) - headers['References'] = note.references.map { |ref| message_id(ref) } + headers["Message-ID"] = message_id(note) + headers["In-Reply-To"] = message_id(note.references.last) + headers["References"] = note.references.map { |ref| message_id(ref) } - headers['X-GitLab-Discussion-ID'] = note.discussion.id if note.part_of_discussion? + headers["X-GitLab-Discussion-ID"] = note.discussion.id if note.part_of_discussion? headers[:subject] = "Re: #{headers[:subject]}" if headers[:subject] @@ -193,10 +192,10 @@ class Notify < BaseMailer def add_project_headers return unless @project - headers['X-GitLab-Project'] = @project.name - headers['X-GitLab-Project-Id'] = @project.id - headers['X-GitLab-Project-Path'] = @project.full_path - headers['List-Id'] = "#{@project.full_path} <#{create_list_id_string(@project)}>" + headers["X-GitLab-Project"] = @project.name + headers["X-GitLab-Project-Id"] = @project.id + headers["X-GitLab-Project-Path"] = @project.full_path + headers["List-Id"] = "#{@project.full_path} <#{create_list_id_string(@project)}>" end def add_unsubscription_headers_and_links @@ -207,7 +206,7 @@ class Notify < BaseMailer list_unsubscribe_methods << "mailto:#{Gitlab::IncomingEmail.unsubscribe_address(reply_key)}" end - headers['List-Unsubscribe'] = list_unsubscribe_methods.map { |e| "<#{e}>" }.join(',') + headers["List-Unsubscribe"] = list_unsubscribe_methods.map { |e| "<#{e}>" }.join(",") @unsubscribe_url = unsubscribe_sent_notification_url(@sent_notification) end end diff --git a/app/mailers/previews/devise_mailer_preview.rb b/app/mailers/previews/devise_mailer_preview.rb index 3b9ef0d3ac0..963d13c946d 100644 --- a/app/mailers/previews/devise_mailer_preview.rb +++ b/app/mailers/previews/devise_mailer_preview.rb @@ -2,22 +2,22 @@ class DeviseMailerPreview < ActionMailer::Preview def confirmation_instructions_for_signup - DeviseMailer.confirmation_instructions(unsaved_user, 'faketoken', {}) + DeviseMailer.confirmation_instructions(unsaved_user, "faketoken", {}) end def confirmation_instructions_for_new_email user = User.last - user.unconfirmed_email = 'unconfirmed@example.com' + user.unconfirmed_email = "unconfirmed@example.com" - DeviseMailer.confirmation_instructions(user, 'faketoken', {}) + DeviseMailer.confirmation_instructions(user, "faketoken", {}) end def reset_password_instructions - DeviseMailer.reset_password_instructions(unsaved_user, 'faketoken', {}) + DeviseMailer.reset_password_instructions(unsaved_user, "faketoken", {}) end def unlock_instructions - DeviseMailer.unlock_instructions(unsaved_user, 'faketoken', {}) + DeviseMailer.unlock_instructions(unsaved_user, "faketoken", {}) end def password_change @@ -27,6 +27,6 @@ class DeviseMailerPreview < ActionMailer::Preview private def unsaved_user - User.new(name: 'Jane Doe', email: 'jdoe@example.com') + User.new(name: "Jane Doe", email: "jdoe@example.com") end end diff --git a/app/mailers/previews/notify_preview.rb b/app/mailers/previews/notify_preview.rb index 80e0a17c312..8d7a3bc8d81 100644 --- a/app/mailers/previews/notify_preview.rb +++ b/app/mailers/previews/notify_preview.rb @@ -13,7 +13,7 @@ class NotifyPreview < ActionMailer::Preview - An explanation for why the user is receiving this notification MD - create_note(noteable_type: 'merge_request', noteable_id: merge_request.id, note: note) + create_note(noteable_type: "merge_request", noteable_id: merge_request.id, note: note) end end @@ -30,7 +30,7 @@ class NotifyPreview < ActionMailer::Preview - An explanation for why the user is receiving this notification MD - create_note(noteable_type: 'merge_request', noteable_id: merge_request.id, type: 'DiscussionNote', note: note) + create_note(noteable_type: "merge_request", noteable_id: merge_request.id, type: "DiscussionNote", note: note) end end @@ -56,7 +56,7 @@ class NotifyPreview < ActionMailer::Preview diff_refs: merge_request.diff_refs ) - create_note(noteable_type: 'merge_request', noteable_id: merge_request.id, type: 'DiffNote', position: position, note: note) + create_note(noteable_type: "merge_request", noteable_id: merge_request.id, type: "DiffNote", position: position, note: note) end end @@ -65,7 +65,7 @@ class NotifyPreview < ActionMailer::Preview end def issue_status_changed_email - Notify.issue_status_changed_email(user.id, issue.id, 'closed', user.id).message + Notify.issue_status_changed_email(user.id, issue.id, "closed", user.id).message end def removed_milestone_issue_email @@ -77,7 +77,7 @@ class NotifyPreview < ActionMailer::Preview end def import_issues_csv_email - Notify.import_issues_csv_email(user, project, { success: 3, errors: [5, 6, 7], valid_file: true }) + Notify.import_issues_csv_email(user, project, {success: 3, errors: [5, 6, 7], valid_file: true}) end def closed_merge_request_email @@ -85,7 +85,7 @@ class NotifyPreview < ActionMailer::Preview end def merge_request_status_email - Notify.merge_request_status_email(user.id, merge_request.id, 'closed', user.id).message + Notify.merge_request_status_email(user.id, merge_request.id, "closed", user.id).message end def merged_merge_request_email @@ -101,37 +101,37 @@ class NotifyPreview < ActionMailer::Preview end def member_access_denied_email - Notify.member_access_denied_email('project', project.id, user.id).message + Notify.member_access_denied_email("project", project.id, user.id).message end def member_access_granted_email - Notify.member_access_granted_email('project', user.id).message + Notify.member_access_granted_email("project", user.id).message end def member_access_requested_email - Notify.member_access_requested_email('group', user.id, 'some@example.com').message + Notify.member_access_requested_email("group", user.id, "some@example.com").message end def member_invite_accepted_email - Notify.member_invite_accepted_email('project', user.id).message + Notify.member_invite_accepted_email("project", user.id).message end def member_invite_declined_email Notify.member_invite_declined_email( - 'project', + "project", project.id, - 'invite@example.com', + "invite@example.com", user.id ).message end def member_invited_email - Notify.member_invited_email('project', user.id, '1234').message + Notify.member_invited_email("project", user.id, "1234").message end def pages_domain_enabled_email cleanup do - pages_domain = PagesDomain.new(domain: 'my.example.com', project: project, verified_at: Time.now, enabled_until: 1.week.from_now) + pages_domain = PagesDomain.new(domain: "my.example.com", project: project, verified_at: Time.now, enabled_until: 1.week.from_now) Notify.pages_domain_enabled_email(pages_domain, user).message end @@ -156,7 +156,7 @@ class NotifyPreview < ActionMailer::Preview private def project - @project ||= Project.find_by_full_path('gitlab-org/gitlab-test') + @project ||= Project.find_by_full_path("gitlab-org/gitlab-test") end def issue diff --git a/app/mailers/repository_check_mailer.rb b/app/mailers/repository_check_mailer.rb index a24d3476d0e..448b52af777 100644 --- a/app/mailers/repository_check_mailer.rb +++ b/app/mailers/repository_check_mailer.rb @@ -2,7 +2,7 @@ class RepositoryCheckMailer < BaseMailer # rubocop: disable CodeReuse/ActiveRecord - layout 'empty_mailer' + layout "empty_mailer" helper EmailsHelper 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 - '&' + "&" 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 - '>' + ">" 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 diff --git a/app/policies/base_policy.rb b/app/policies/base_policy.rb index 72de04203a6..269d92e2259 100644 --- a/app/policies/base_policy.rb +++ b/app/policies/base_policy.rb @@ -1,6 +1,6 @@ # frozen_string_literal: true -require_dependency 'declarative_policy' +require_dependency "declarative_policy" class BasePolicy < DeclarativePolicy::Base desc "User is an instance admin" diff --git a/app/policies/ci/pipeline_schedule_policy.rb b/app/policies/ci/pipeline_schedule_policy.rb index cf3f784f851..60911c29920 100644 --- a/app/policies/ci/pipeline_schedule_policy.rb +++ b/app/policies/ci/pipeline_schedule_policy.rb @@ -2,7 +2,7 @@ module Ci class PipelineSchedulePolicy < PipelinePolicy - alias_method :pipeline_schedule, :subject + alias pipeline_schedule subject condition(:protected_ref) do ref_protected?(@user, @subject.project, @subject.project.repository.tag_exists?(@subject.ref), @subject.ref) diff --git a/app/policies/clusters/cluster_policy.rb b/app/policies/clusters/cluster_policy.rb index d6d590687e2..b2490153a8b 100644 --- a/app/policies/clusters/cluster_policy.rb +++ b/app/policies/clusters/cluster_policy.rb @@ -2,7 +2,7 @@ module Clusters class ClusterPolicy < BasePolicy - alias_method :cluster, :subject + alias cluster subject delegate { cluster.group } delegate { cluster.project } diff --git a/app/policies/global_policy.rb b/app/policies/global_policy.rb index 16c58730878..069b8de8401 100644 --- a/app/policies/global_policy.rb +++ b/app/policies/global_policy.rb @@ -13,7 +13,7 @@ class GlobalPolicy < BasePolicy with_options scope: :user, score: 0 condition(:access_locked) { @user&.access_locked? } - condition(:can_create_fork, scope: :user) { @user && @user.manageable_namespaces.any? { |namespace| @user.can?(:create_projects, namespace) } } + condition(:can_create_fork, scope: :user) { @user&.manageable_namespaces&.any? { |namespace| @user.can?(:create_projects, namespace) } } condition(:required_terms_not_accepted, scope: :user, score: 0) do @user&.required_terms_not_accepted? diff --git a/app/policies/group_policy.rb b/app/policies/group_policy.rb index 298769c0eb8..1ea85d09124 100644 --- a/app/policies/group_policy.rb +++ b/app/policies/group_policy.rb @@ -26,7 +26,7 @@ class GroupPolicy < BasePolicy condition(:can_change_parent_share_with_group_lock) { can?(:change_share_with_group_lock, @subject.parent) } condition(:has_projects) do - GroupProjectsFinder.new(group: @subject, current_user: @user, options: { include_subgroups: true }).execute.any? + GroupProjectsFinder.new(group: @subject, current_user: @user, options: {include_subgroups: true}).execute.any? end condition(:has_clusters, scope: :subject) { clusterable_has_clusters? } diff --git a/app/policies/namespace_policy.rb b/app/policies/namespace_policy.rb index 2babcb0a2d9..9df10bc229f 100644 --- a/app/policies/namespace_policy.rb +++ b/app/policies/namespace_policy.rb @@ -3,7 +3,7 @@ class NamespacePolicy < BasePolicy rule { anonymous }.prevent_all - condition(:personal_project, scope: :subject) { @subject.kind == 'user' } + condition(:personal_project, scope: :subject) { @subject.kind == "user" } condition(:can_create_personal_project, scope: :user) { @user.can_create_project? } condition(:owner) { @subject.owner == @user } diff --git a/app/policies/project_policy.rb b/app/policies/project_policy.rb index 533782104ac..1f28761eb36 100644 --- a/app/policies/project_policy.rb +++ b/app/policies/project_policy.rb @@ -401,13 +401,13 @@ class ProjectPolicy < BasePolicy enable :create_pipeline end - rule do + rule { (can?(:read_project_for_iids) & issues_visible_to_user) | can?(:read_issue) - end.enable :read_issue_iid + }.enable :read_issue_iid - rule do + rule { (~guest & can?(:read_project_for_iids) & merge_requests_visible_to_user) | can?(:read_merge_request) - end.enable :read_merge_request_iid + }.enable :read_merge_request_iid rule { ~can_have_multiple_clusters & has_clusters }.prevent :add_cluster diff --git a/app/policies/project_policy/class_methods.rb b/app/policies/project_policy/class_methods.rb index 42d993406a9..0c8fac7c71f 100644 --- a/app/policies/project_policy/class_methods.rb +++ b/app/policies/project_policy/class_methods.rb @@ -5,7 +5,7 @@ class ProjectPolicy def create_read_update_admin_destroy(name) [ :"read_#{name}", - *create_update_admin_destroy(name) + *create_update_admin_destroy(name), ] end @@ -14,7 +14,7 @@ class ProjectPolicy :"create_#{name}", :"update_#{name}", :"admin_#{name}", - :"destroy_#{name}" + :"destroy_#{name}", ] end end diff --git a/app/policies/project_snippet_policy.rb b/app/policies/project_snippet_policy.rb index e5e005cee6d..e2b101238dd 100644 --- a/app/policies/project_snippet_policy.rb +++ b/app/policies/project_snippet_policy.rb @@ -24,12 +24,12 @@ class ProjectSnippetPolicy < BasePolicy # information about the snippet. However, :read_project_snippet on the *project* # is used to hide/show various snippet-related controls, so we can't just move # all of the handling here. - rule do + rule { all?(private_snippet | (internal_snippet & external_user), - ~project.guest, - ~is_author, - ~full_private_access) - end.prevent :read_project_snippet + ~project.guest, + ~is_author, + ~full_private_access) + }.prevent :read_project_snippet rule { internal_snippet & ~is_author & ~admin }.policy do prevent :update_project_snippet diff --git a/app/presenters/ci/build_metadata_presenter.rb b/app/presenters/ci/build_metadata_presenter.rb index 015b1f67db7..96469043093 100644 --- a/app/presenters/ci/build_metadata_presenter.rb +++ b/app/presenters/ci/build_metadata_presenter.rb @@ -3,9 +3,9 @@ module Ci class BuildMetadataPresenter < Gitlab::View::Presenter::Delegated TIMEOUT_SOURCES = { - unknown_timeout_source: nil, - project_timeout_source: 'project', - runner_timeout_source: 'runner' + unknown_timeout_source: nil, + project_timeout_source: "project", + runner_timeout_source: "runner", }.freeze presents :metadata diff --git a/app/presenters/ci/build_runner_presenter.rb b/app/presenters/ci/build_runner_presenter.rb index d60281c8a0b..22341eed948 100644 --- a/app/presenters/ci/build_runner_presenter.rb +++ b/app/presenters/ci/build_runner_presenter.rb @@ -4,8 +4,8 @@ module Ci class BuildRunnerPresenter < SimpleDelegator include Gitlab::Utils::StrongMemoize - RUNNER_REMOTE_TAG_PREFIX = 'refs/tags/'.freeze - RUNNER_REMOTE_BRANCH_PREFIX = 'refs/remotes/origin/'.freeze + RUNNER_REMOTE_TAG_PREFIX = "refs/tags/" + RUNNER_REMOTE_BRANCH_PREFIX = "refs/remotes/origin/" def artifacts return unless options[:artifacts] @@ -18,15 +18,15 @@ module Ci def ref_type if tag - 'tag' + "tag" else - 'branch' + "branch" end end def git_depth strong_memoize(:git_depth) do - git_depth = variables&.find { |variable| variable[:key] == 'GIT_DEPTH' }&.dig(:value) + git_depth = variables&.find { |variable| variable[:key] == "GIT_DEPTH" }&.dig(:value) git_depth.to_i end end @@ -57,7 +57,7 @@ module Ci untracked: artifacts[:untracked], paths: artifacts[:paths], when: artifacts[:when], - expire_in: artifacts[:expire_in] + expire_in: artifacts[:expire_in], } end @@ -70,17 +70,17 @@ module Ci artifact_format: ::Ci::JobArtifact::TYPE_AND_FORMAT_PAIRS.fetch(report_type.to_sym), name: ::Ci::JobArtifact::DEFAULT_FILE_NAMES.fetch(report_type.to_sym), paths: report_paths, - when: 'always', - expire_in: expire_in + when: "always", + expire_in: expire_in, } end end - def refspec_for_branch(ref = '*') + def refspec_for_branch(ref = "*") "+#{Gitlab::Git::BRANCH_REF_PREFIX}#{ref}:#{RUNNER_REMOTE_BRANCH_PREFIX}#{ref}" end - def refspec_for_tag(ref = '*') + def refspec_for_tag(ref = "*") "+#{Gitlab::Git::TAG_REF_PREFIX}#{ref}:#{RUNNER_REMOTE_TAG_PREFIX}#{ref}" end end diff --git a/app/presenters/ci/group_variable_presenter.rb b/app/presenters/ci/group_variable_presenter.rb index 99011150c84..8c2a7cae028 100644 --- a/app/presenters/ci/group_variable_presenter.rb +++ b/app/presenters/ci/group_variable_presenter.rb @@ -5,7 +5,7 @@ module Ci presents :variable def placeholder - 'GROUP_VARIABLE' + "GROUP_VARIABLE" end def form_path diff --git a/app/presenters/ci/pipeline_presenter.rb b/app/presenters/ci/pipeline_presenter.rb index 57daf04efc6..829a8ac0b9d 100644 --- a/app/presenters/ci/pipeline_presenter.rb +++ b/app/presenters/ci/pipeline_presenter.rb @@ -7,7 +7,7 @@ module Ci # We use a class method here instead of a constant, allowing EE to redefine # the returned `Hash` more easily. def self.failure_reasons - { config_error: 'CI/CD YAML configuration error!' } + {config_error: "CI/CD YAML configuration error!"} end presents :pipeline diff --git a/app/presenters/ci/variable_presenter.rb b/app/presenters/ci/variable_presenter.rb index f027f3aa560..c0214c6fafa 100644 --- a/app/presenters/ci/variable_presenter.rb +++ b/app/presenters/ci/variable_presenter.rb @@ -5,7 +5,7 @@ module Ci presents :variable def placeholder - 'PROJECT_VARIABLE' + "PROJECT_VARIABLE" end def form_path diff --git a/app/presenters/clusters/cluster_presenter.rb b/app/presenters/clusters/cluster_presenter.rb index 7a5b68f9a4b..760c44dfd66 100644 --- a/app/presenters/clusters/cluster_presenter.rb +++ b/app/presenters/clusters/cluster_presenter.rb @@ -12,7 +12,7 @@ module Clusters # clusterable, only for the ancestor clusters. def item_link(clusterable_presenter) if cluster.group_type? && clusterable != clusterable_presenter.subject - contracted_group_name(cluster.group) + ' / ' + link_to_cluster + contracted_group_name(cluster.group) + " / " + link_to_cluster else link_to_cluster end @@ -65,7 +65,7 @@ module Clusters end def contracted_icon - sprite_icon('ellipsis_h', size: 12, css_class: 'vertical-align-middle') + sprite_icon("ellipsis_h", size: 12, css_class: "vertical-align-middle") end def link_to_cluster diff --git a/app/presenters/commit_status_presenter.rb b/app/presenters/commit_status_presenter.rb index 0cd77da6303..c7e8f75f298 100644 --- a/app/presenters/commit_status_presenter.rb +++ b/app/presenters/commit_status_presenter.rb @@ -2,16 +2,16 @@ class CommitStatusPresenter < Gitlab::View::Presenter::Delegated CALLOUT_FAILURE_MESSAGES = { - unknown_failure: 'There is an unknown failure, please try again', + unknown_failure: "There is an unknown failure, please try again", script_failure: nil, - api_failure: 'There has been an API failure, please try again', - stuck_or_timeout_failure: 'There has been a timeout failure or the job got stuck. Check your timeout limits or try again', - runner_system_failure: 'There has been a runner system failure, please try again', - missing_dependency_failure: 'There has been a missing dependency failure', - runner_unsupported: 'Your runner is outdated, please upgrade your runner', - stale_schedule: 'Delayed job could not be executed by some reason, please try again', - job_execution_timeout: 'The script exceeded the maximum execution time set for the job', - archived_failure: 'The job is archived and cannot be run' + api_failure: "There has been an API failure, please try again", + stuck_or_timeout_failure: "There has been a timeout failure or the job got stuck. Check your timeout limits or try again", + runner_system_failure: "There has been a runner system failure, please try again", + missing_dependency_failure: "There has been a missing dependency failure", + runner_unsupported: "Your runner is outdated, please upgrade your runner", + stale_schedule: "Delayed job could not be executed by some reason, please try again", + job_execution_timeout: "The script exceeded the maximum execution time set for the job", + archived_failure: "The job is archived and cannot be run", }.freeze private_constant :CALLOUT_FAILURE_MESSAGES diff --git a/app/presenters/conversational_development_index/metric_presenter.rb b/app/presenters/conversational_development_index/metric_presenter.rb index 9639b84cf56..5f6b0f1ce6c 100644 --- a/app/presenters/conversational_development_index/metric_presenter.rb +++ b/app/presenters/conversational_development_index/metric_presenter.rb @@ -6,81 +6,81 @@ module ConversationalDevelopmentIndex [ Card.new( metric: subject, - title: 'Issues', - description: 'created per active user', - feature: 'issues', - blog: 'https://www2.deloitte.com/content/dam/Deloitte/se/Documents/technology-media-telecommunications/deloitte-digital-collaboration.pdf' + title: "Issues", + description: "created per active user", + feature: "issues", + blog: "https://www2.deloitte.com/content/dam/Deloitte/se/Documents/technology-media-telecommunications/deloitte-digital-collaboration.pdf" ), Card.new( metric: subject, - title: 'Comments', - description: 'created per active user', - feature: 'notes', - blog: 'http://conversationaldevelopment.com/why/' + title: "Comments", + description: "created per active user", + feature: "notes", + blog: "http://conversationaldevelopment.com/why/" ), Card.new( metric: subject, - title: 'Milestones', - description: 'created per active user', - feature: 'milestones', - blog: 'http://conversationaldevelopment.com/shorten-cycle/', - docs: help_page_path('user/project/milestones/index') + title: "Milestones", + description: "created per active user", + feature: "milestones", + blog: "http://conversationaldevelopment.com/shorten-cycle/", + docs: help_page_path("user/project/milestones/index") ), Card.new( metric: subject, - title: 'Boards', - description: 'created per active user', - feature: 'boards', - blog: 'http://jpattonassociates.com/user-story-mapping/', - docs: help_page_path('user/project/issue_board') + title: "Boards", + description: "created per active user", + feature: "boards", + blog: "http://jpattonassociates.com/user-story-mapping/", + docs: help_page_path("user/project/issue_board") ), Card.new( metric: subject, - title: 'Merge Requests', - description: 'per active user', - feature: 'merge_requests', - blog: 'https://8thlight.com/blog/uncle-bob/2013/02/01/The-Humble-Craftsman.html', - docs: help_page_path('user/project/merge_requests/index') + title: "Merge Requests", + description: "per active user", + feature: "merge_requests", + blog: "https://8thlight.com/blog/uncle-bob/2013/02/01/The-Humble-Craftsman.html", + docs: help_page_path("user/project/merge_requests/index") ), Card.new( metric: subject, - title: 'Pipelines', - description: 'created per active user', - feature: 'ci_pipelines', - blog: 'https://martinfowler.com/bliki/ContinuousDelivery.html', - docs: help_page_path('ci/README') + title: "Pipelines", + description: "created per active user", + feature: "ci_pipelines", + blog: "https://martinfowler.com/bliki/ContinuousDelivery.html", + docs: help_page_path("ci/README") ), Card.new( metric: subject, - title: 'Environments', - description: 'created per active user', - feature: 'environments', - blog: 'https://about.gitlab.com/2016/08/26/ci-deployment-and-environments/', - docs: help_page_path('ci/environments') + title: "Environments", + description: "created per active user", + feature: "environments", + blog: "https://about.gitlab.com/2016/08/26/ci-deployment-and-environments/", + docs: help_page_path("ci/environments") ), Card.new( metric: subject, - title: 'Deployments', - description: 'created per active user', - feature: 'deployments', - blog: 'https://puppet.com/blog/continuous-delivery-vs-continuous-deployment-what-s-diff' + title: "Deployments", + description: "created per active user", + feature: "deployments", + blog: "https://puppet.com/blog/continuous-delivery-vs-continuous-deployment-what-s-diff" ), Card.new( metric: subject, - title: 'Monitoring', - description: 'fraction of all projects', - feature: 'projects_prometheus_active', - blog: 'https://prometheus.io/docs/introduction/overview/', - docs: help_page_path('user/project/integrations/prometheus') + title: "Monitoring", + description: "fraction of all projects", + feature: "projects_prometheus_active", + blog: "https://prometheus.io/docs/introduction/overview/", + docs: help_page_path("user/project/integrations/prometheus") ), Card.new( metric: subject, - title: 'Service Desk', - description: 'issues created per active user', - feature: 'service_desk_issues', - blog: 'http://blogs.forrester.com/kate_leggett/17-01-30-top_trends_for_customer_service_in_2017_operations_become_smarter_and_more_strategic', - docs: 'https://docs.gitlab.com/ee/user/project/service_desk.html' - ) + title: "Service Desk", + description: "issues created per active user", + feature: "service_desk_issues", + blog: "http://blogs.forrester.com/kate_leggett/17-01-30-top_trends_for_customer_service_in_2017_operations_become_smarter_and_more_strategic", + docs: "https://docs.gitlab.com/ee/user/project/service_desk.html" + ), ] end @@ -88,54 +88,54 @@ module ConversationalDevelopmentIndex [ IdeaToProductionStep.new( metric: subject, - title: 'Idea', - features: %w(issues) + title: "Idea", + features: %w[issues] ), IdeaToProductionStep.new( metric: subject, - title: 'Issue', - features: %w(issues notes) + title: "Issue", + features: %w[issues notes] ), IdeaToProductionStep.new( metric: subject, - title: 'Plan', - features: %w(milestones boards) + title: "Plan", + features: %w[milestones boards] ), IdeaToProductionStep.new( metric: subject, - title: 'Code', - features: %w(merge_requests) + title: "Code", + features: %w[merge_requests] ), IdeaToProductionStep.new( metric: subject, - title: 'Commit', - features: %w(merge_requests) + title: "Commit", + features: %w[merge_requests] ), IdeaToProductionStep.new( metric: subject, - title: 'Test', - features: %w(ci_pipelines) + title: "Test", + features: %w[ci_pipelines] ), IdeaToProductionStep.new( metric: subject, - title: 'Review', - features: %w(ci_pipelines environments) + title: "Review", + features: %w[ci_pipelines environments] ), IdeaToProductionStep.new( metric: subject, - title: 'Staging', - features: %w(environments deployments) + title: "Staging", + features: %w[environments deployments] ), IdeaToProductionStep.new( metric: subject, - title: 'Production', - features: %w(deployments) + title: "Production", + features: %w[deployments] ), IdeaToProductionStep.new( metric: subject, - title: 'Feedback', - features: %w(projects_prometheus_active service_desk_issues) - ) + title: "Feedback", + features: %w[projects_prometheus_active service_desk_issues] + ), ] end diff --git a/app/presenters/group_clusterable_presenter.rb b/app/presenters/group_clusterable_presenter.rb index ef6bbc0d109..73bfe9a58b8 100644 --- a/app/presenters/group_clusterable_presenter.rb +++ b/app/presenters/group_clusterable_presenter.rb @@ -21,16 +21,16 @@ class GroupClusterablePresenter < ClusterablePresenter override :empty_state_help_text def empty_state_help_text - s_('ClusterIntegration|Adding an integration to your group will share the cluster across all your projects.') + s_("ClusterIntegration|Adding an integration to your group will share the cluster across all your projects.") end override :sidebar_text def sidebar_text - s_('ClusterIntegration|Adding a Kubernetes cluster to your group will automatically share the cluster across all your projects. Use review apps, deploy your applications, and easily run your pipelines for all projects using the same cluster.') + s_("ClusterIntegration|Adding a Kubernetes cluster to your group will automatically share the cluster across all your projects. Use review apps, deploy your applications, and easily run your pipelines for all projects using the same cluster.") end override :learn_more_link def learn_more_link - link_to(s_('ClusterIntegration|Learn more about group Kubernetes clusters'), help_page_path('user/group/clusters/index'), target: '_blank', rel: 'noopener noreferrer') + link_to(s_("ClusterIntegration|Learn more about group Kubernetes clusters"), help_page_path("user/group/clusters/index"), target: "_blank", rel: "noopener noreferrer") end end diff --git a/app/presenters/merge_request_presenter.rb b/app/presenters/merge_request_presenter.rb index c59e73f824c..a708ae33969 100644 --- a/app/presenters/merge_request_presenter.rb +++ b/app/presenters/merge_request_presenter.rb @@ -51,12 +51,12 @@ class MergeRequestPresenter < Gitlab::View::Presenter::Delegated continue_params = { to: merge_request_path(merge_request), notice: "#{edit_in_new_fork_notice} Try to cherry-pick this commit again.", - notice_now: edit_in_new_fork_notice_now + notice_now: edit_in_new_fork_notice_now, } project_forks_path(merge_request.project, - namespace_key: current_user.namespace.id, - continue: continue_params) + namespace_key: current_user.namespace.id, + continue: continue_params) end end @@ -65,12 +65,12 @@ class MergeRequestPresenter < Gitlab::View::Presenter::Delegated continue_params = { to: merge_request_path(merge_request), notice: "#{edit_in_new_fork_notice} Try to revert this commit again.", - notice_now: edit_in_new_fork_notice_now + notice_now: edit_in_new_fork_notice_now, } project_forks_path(project, - namespace_key: current_user.namespace.id, - continue: continue_params) + namespace_key: current_user.namespace.id, + continue: continue_params) end end @@ -138,10 +138,9 @@ class MergeRequestPresenter < Gitlab::View::Presenter::Delegated def assign_to_closing_issues_link # rubocop: disable CodeReuse/ServiceClass issues = MergeRequests::AssignIssuesService.new(project, - current_user, - merge_request: merge_request, - closes_issues: closing_issues - ).assignable_issues + current_user, + merge_request: merge_request, + closes_issues: closing_issues).assignable_issues path = assign_related_issues_project_merge_request_path(project, merge_request) if issues.present? pluralize_this_issue = issues.count > 1 ? "these issues" : "this issue" @@ -194,7 +193,7 @@ class MergeRequestPresenter < Gitlab::View::Presenter::Delegated end def conflicts_docs_path - help_page_path('user/project/merge_requests/resolve_conflicts.md') + help_page_path("user/project/merge_requests/resolve_conflicts.md") end private @@ -222,9 +221,9 @@ class MergeRequestPresenter < Gitlab::View::Presenter::Delegated def issues_sentence(project, issues) # Sorting based on the `#123` or `group/project#123` reference will sort # local issues first. - issues.map do |issue| + issues.map { |issue| issue.to_reference(project) - end.sort.to_sentence + }.sort.to_sentence end def user_can_fork_project? diff --git a/app/presenters/project_clusterable_presenter.rb b/app/presenters/project_clusterable_presenter.rb index 63e69b91b11..7912af95d80 100644 --- a/app/presenters/project_clusterable_presenter.rb +++ b/app/presenters/project_clusterable_presenter.rb @@ -21,11 +21,11 @@ class ProjectClusterablePresenter < ClusterablePresenter override :sidebar_text def sidebar_text - s_('ClusterIntegration|With a Kubernetes cluster associated to this project, you can use review apps, deploy your applications, run your pipelines, and much more in an easy way.') + s_("ClusterIntegration|With a Kubernetes cluster associated to this project, you can use review apps, deploy your applications, run your pipelines, and much more in an easy way.") end override :learn_more_link def learn_more_link - link_to(s_('ClusterIntegration|Learn more about Kubernetes'), help_page_path('user/project/clusters/index'), target: '_blank', rel: 'noopener noreferrer') + link_to(s_("ClusterIntegration|Learn more about Kubernetes"), help_page_path("user/project/clusters/index"), target: "_blank", rel: "noopener noreferrer") end end diff --git a/app/presenters/project_presenter.rb b/app/presenters/project_presenter.rb index 000b7c433a2..3f52bacb86a 100644 --- a/app/presenters/project_presenter.rb +++ b/app/presenters/project_presenter.rb @@ -15,8 +15,8 @@ class ProjectPresenter < Gitlab::View::Presenter::Delegated AnchorData = Struct.new(:is_link, :label, :link, :class_modifier, :icon) MAX_TOPICS_TO_SHOW = 3 - def statistic_icon(icon_name = 'plus-square-o') - sprite_icon(icon_name, size: 16, css_class: 'icon append-right-4') + def statistic_icon(icon_name = "plus-square-o") + sprite_icon(icon_name, size: 16, css_class: "icon append-right-4") end def statistics_anchors(show_auto_devops_callout:) @@ -25,7 +25,7 @@ class ProjectPresenter < Gitlab::View::Presenter::Delegated commits_anchor_data, branches_anchor_data, tags_anchor_data, - files_anchor_data + files_anchor_data, ].compact.select(&:is_link) end @@ -36,7 +36,7 @@ class ProjectPresenter < Gitlab::View::Presenter::Delegated contribution_guide_anchor_data, autodevops_anchor_data(show_auto_devops_callout: show_auto_devops_callout), kubernetes_cluster_anchor_data, - gitlab_ci_anchor_data + gitlab_ci_anchor_data, ].compact.reject(&:is_link) end @@ -46,7 +46,7 @@ class ProjectPresenter < Gitlab::View::Presenter::Delegated commits_anchor_data, branches_anchor_data, tags_anchor_data, - files_anchor_data + files_anchor_data, ].compact.select { |item| item.is_link } end @@ -57,7 +57,7 @@ class ProjectPresenter < Gitlab::View::Presenter::Delegated changelog_anchor_data, contribution_guide_anchor_data, autodevops_anchor_data, - kubernetes_cluster_anchor_data + kubernetes_cluster_anchor_data, ].compact.reject { |item| item.is_link } end @@ -100,34 +100,34 @@ class ProjectPresenter < Gitlab::View::Presenter::Delegated project_blob_path( project, tree_join(project.default_branch, - contribution_guide.name) + contribution_guide.name) ) end end def add_license_path - add_special_file_path(file_name: 'LICENSE') + add_special_file_path(file_name: "LICENSE") end def add_changelog_path - add_special_file_path(file_name: 'CHANGELOG') + add_special_file_path(file_name: "CHANGELOG") end def add_contribution_guide_path - add_special_file_path(file_name: 'CONTRIBUTING.md', commit_message: 'Add CONTRIBUTING') + add_special_file_path(file_name: "CONTRIBUTING.md", commit_message: "Add CONTRIBUTING") end def add_ci_yml_path - add_special_file_path(file_name: '.gitlab-ci.yml') + add_special_file_path(file_name: ".gitlab-ci.yml") end def add_readme_path - add_special_file_path(file_name: 'README.md') + add_special_file_path(file_name: "README.md") end def license_short_name license = repository.license - license&.nickname || license&.name || 'LICENSE' + license&.nickname || license&.name || "LICENSE" end def can_current_user_push_code? @@ -150,100 +150,100 @@ class ProjectPresenter < Gitlab::View::Presenter::Delegated def files_anchor_data AnchorData.new(true, - statistic_icon('doc-code') + - _('%{strong_start}%{human_size}%{strong_end} Files').html_safe % { - human_size: storage_counter(statistics.total_repository_size), - strong_start: '<strong class="project-stat-value">'.html_safe, - strong_end: '</strong>'.html_safe - }, - empty_repo? ? nil : project_tree_path(project)) + statistic_icon("doc-code") + + _("%{strong_start}%{human_size}%{strong_end} Files").html_safe % { + human_size: storage_counter(statistics.total_repository_size), + strong_start: '<strong class="project-stat-value">'.html_safe, + strong_end: "</strong>".html_safe, + }, + empty_repo? ? nil : project_tree_path(project)) end def commits_anchor_data AnchorData.new(true, - statistic_icon('commit') + - n_('%{strong_start}%{commit_count}%{strong_end} Commit', '%{strong_start}%{commit_count}%{strong_end} Commits', statistics.commit_count).html_safe % { - commit_count: number_with_delimiter(statistics.commit_count), - strong_start: '<strong class="project-stat-value">'.html_safe, - strong_end: '</strong>'.html_safe - }, - empty_repo? ? nil : project_commits_path(project, repository.root_ref)) + statistic_icon("commit") + + n_("%{strong_start}%{commit_count}%{strong_end} Commit", "%{strong_start}%{commit_count}%{strong_end} Commits", statistics.commit_count).html_safe % { + commit_count: number_with_delimiter(statistics.commit_count), + strong_start: '<strong class="project-stat-value">'.html_safe, + strong_end: "</strong>".html_safe, + }, + empty_repo? ? nil : project_commits_path(project, repository.root_ref)) end def branches_anchor_data AnchorData.new(true, - statistic_icon('branch') + - n_('%{strong_start}%{branch_count}%{strong_end} Branch', '%{strong_start}%{branch_count}%{strong_end} Branches', repository.branch_count).html_safe % { - branch_count: number_with_delimiter(repository.branch_count), - strong_start: '<strong class="project-stat-value">'.html_safe, - strong_end: '</strong>'.html_safe - }, - empty_repo? ? nil : project_branches_path(project)) + statistic_icon("branch") + + n_("%{strong_start}%{branch_count}%{strong_end} Branch", "%{strong_start}%{branch_count}%{strong_end} Branches", repository.branch_count).html_safe % { + branch_count: number_with_delimiter(repository.branch_count), + strong_start: '<strong class="project-stat-value">'.html_safe, + strong_end: "</strong>".html_safe, + }, + empty_repo? ? nil : project_branches_path(project)) end def tags_anchor_data AnchorData.new(true, - statistic_icon('label') + - n_('%{strong_start}%{tag_count}%{strong_end} Tag', '%{strong_start}%{tag_count}%{strong_end} Tags', repository.tag_count).html_safe % { - tag_count: number_with_delimiter(repository.tag_count), - strong_start: '<strong class="project-stat-value">'.html_safe, - strong_end: '</strong>'.html_safe - }, - empty_repo? ? nil : project_tags_path(project)) + statistic_icon("label") + + n_("%{strong_start}%{tag_count}%{strong_end} Tag", "%{strong_start}%{tag_count}%{strong_end} Tags", repository.tag_count).html_safe % { + tag_count: number_with_delimiter(repository.tag_count), + strong_start: '<strong class="project-stat-value">'.html_safe, + strong_end: "</strong>".html_safe, + }, + empty_repo? ? nil : project_tags_path(project)) end def new_file_anchor_data if current_user && can_current_user_push_to_default_branch? AnchorData.new(false, - statistic_icon + _('New file'), - project_new_blob_path(project, default_branch || 'master'), - 'success') + statistic_icon + _("New file"), + project_new_blob_path(project, default_branch || "master"), + "success") end end def readme_anchor_data if current_user && can_current_user_push_to_default_branch? && repository.readme.nil? AnchorData.new(false, - statistic_icon + _('Add README'), - add_readme_path) + statistic_icon + _("Add README"), + add_readme_path) elsif repository.readme AnchorData.new(false, - statistic_icon('doc-text') + _('README'), - default_view != 'readme' ? readme_path : '#readme', - 'default', - 'doc-text') + statistic_icon("doc-text") + _("README"), + default_view != "readme" ? readme_path : "#readme", + "default", + "doc-text") end end def changelog_anchor_data if current_user && can_current_user_push_to_default_branch? && repository.changelog.blank? AnchorData.new(false, - statistic_icon + _('Add CHANGELOG'), - add_changelog_path) + statistic_icon + _("Add CHANGELOG"), + add_changelog_path) elsif repository.changelog.present? AnchorData.new(false, - statistic_icon('doc-text') + _('CHANGELOG'), - changelog_path, - 'default') + statistic_icon("doc-text") + _("CHANGELOG"), + changelog_path, + "default") end end def license_anchor_data - icon = statistic_icon('scale') + icon = statistic_icon("scale") if repository.license_blob.present? AnchorData.new(true, - icon + content_tag(:strong, license_short_name, class: 'project-stat-value'), - license_path) + icon + content_tag(:strong, license_short_name, class: "project-stat-value"), + license_path) else if current_user && can_current_user_push_to_default_branch? AnchorData.new(true, - content_tag(:span, icon + _('Add license'), class: 'add-license-link d-flex'), - add_license_path) + content_tag(:span, icon + _("Add license"), class: "add-license-link d-flex"), + add_license_path) else AnchorData.new(true, - icon + content_tag(:strong, _('No license. All rights reserved'), class: 'project-stat-value'), - nil) + icon + content_tag(:strong, _("No license. All rights reserved"), class: "project-stat-value"), + nil) end end end @@ -251,13 +251,13 @@ class ProjectPresenter < Gitlab::View::Presenter::Delegated def contribution_guide_anchor_data if current_user && can_current_user_push_to_default_branch? && repository.contribution_guide.blank? AnchorData.new(false, - statistic_icon + _('Add CONTRIBUTING'), - add_contribution_guide_path) + statistic_icon + _("Add CONTRIBUTING"), + add_contribution_guide_path) elsif repository.contribution_guide.present? AnchorData.new(false, - statistic_icon('doc-text') + _('CONTRIBUTING'), - contribution_guide_path, - 'default') + statistic_icon("doc-text") + _("CONTRIBUTING"), + contribution_guide_path, + "default") end end @@ -265,18 +265,18 @@ class ProjectPresenter < Gitlab::View::Presenter::Delegated if current_user && can?(current_user, :admin_pipeline, project) && repository.gitlab_ci_yml.blank? && !show_auto_devops_callout if auto_devops_enabled? AnchorData.new(false, - statistic_icon('doc-text') + _('Auto DevOps enabled'), - project_settings_ci_cd_path(project, anchor: 'autodevops-settings'), - 'default') + statistic_icon("doc-text") + _("Auto DevOps enabled"), + project_settings_ci_cd_path(project, anchor: "autodevops-settings"), + "default") else AnchorData.new(false, - statistic_icon + _('Enable Auto DevOps'), - project_settings_ci_cd_path(project, anchor: 'autodevops-settings')) + statistic_icon + _("Enable Auto DevOps"), + project_settings_ci_cd_path(project, anchor: "autodevops-settings")) end elsif auto_devops_enabled? AnchorData.new(false, - _('Auto DevOps enabled'), - nil) + _("Auto DevOps enabled"), + nil) end end @@ -285,15 +285,15 @@ class ProjectPresenter < Gitlab::View::Presenter::Delegated if clusters.empty? AnchorData.new(false, - statistic_icon + _('Add Kubernetes cluster'), - new_project_cluster_path(project)) + statistic_icon + _("Add Kubernetes cluster"), + new_project_cluster_path(project)) else cluster_link = clusters.count == 1 ? project_cluster_path(project, clusters.first) : project_clusters_path(project) AnchorData.new(false, - _('Kubernetes configured'), - cluster_link, - 'default') + _("Kubernetes configured"), + cluster_link, + "default") end end end @@ -301,13 +301,13 @@ class ProjectPresenter < Gitlab::View::Presenter::Delegated def gitlab_ci_anchor_data if current_user && can_current_user_push_code? && repository.gitlab_ci_yml.blank? && !auto_devops_enabled? AnchorData.new(false, - statistic_icon + _('Set up CI/CD'), - add_ci_yml_path) + statistic_icon + _("Set up CI/CD"), + add_ci_yml_path) elsif repository.gitlab_ci_yml.present? AnchorData.new(false, - statistic_icon('doc-text') + _('CI/CD configuration'), - ci_configuration_path, - 'default') + statistic_icon("doc-text") + _("CI/CD configuration"), + ci_configuration_path, + "default") end end @@ -344,20 +344,20 @@ class ProjectPresenter < Gitlab::View::Presenter::Delegated def anonymous_project_view if !project.empty_repo? && can?(current_user, :download_code, project) - 'files' + "files" else - 'activity' + "activity" end end def add_special_file_path(file_name:, commit_message: nil, branch_name: nil) - commit_message ||= s_("CommitMessage|Add %{file_name}") % { file_name: file_name } + commit_message ||= s_("CommitMessage|Add %{file_name}") % {file_name: file_name} project_new_blob_path( project, - project.default_branch || 'master', - file_name: file_name, + project.default_branch || "master", + file_name: file_name, commit_message: commit_message, - branch_name: branch_name + branch_name: branch_name ) end end diff --git a/app/presenters/projects/settings/deploy_keys_presenter.rb b/app/presenters/projects/settings/deploy_keys_presenter.rb index 85518c9a3a4..ed125cc752d 100644 --- a/app/presenters/projects/settings/deploy_keys_presenter.rb +++ b/app/presenters/projects/settings/deploy_keys_presenter.rb @@ -50,21 +50,21 @@ module Projects def as_json serializer = DeployKeySerializer.new # rubocop: disable CodeReuse/Serializer - opts = { user: current_user } + opts = {user: current_user} { enabled_keys: serializer.represent(enabled_keys, opts), available_project_keys: serializer.represent(available_project_keys, opts), - public_keys: serializer.represent(available_public_keys, opts) + public_keys: serializer.represent(available_public_keys, opts), } end def to_partial_path - 'projects/deploy_keys/index' + "projects/deploy_keys/index" end def form_partial_path - 'projects/deploy_keys/form' + "projects/deploy_keys/form" end end end diff --git a/app/serializers/base_serializer.rb b/app/serializers/base_serializer.rb index 4744a7c1cc8..90bd4730f1e 100644 --- a/app/serializers/base_serializer.rb +++ b/app/serializers/base_serializer.rb @@ -9,7 +9,7 @@ class BaseSerializer end def represent(resource, opts = {}, entity_class = nil) - entity_class = entity_class || self.class.entity_class + entity_class ||= self.class.entity_class entity_class .represent(resource, opts.merge(request: @request)) diff --git a/app/serializers/blob_entity.rb b/app/serializers/blob_entity.rb index 3ac61481dea..0f7d1810ee0 100644 --- a/app/serializers/blob_entity.rb +++ b/app/serializers/blob_entity.rb @@ -8,10 +8,10 @@ class BlobEntity < Grape::Entity expose :readable_text?, as: :readable_text expose :icon do |blob| - IconsHelper.file_type_icon_class('file', blob.mode, blob.name) + IconsHelper.file_type_icon_class("file", blob.mode, blob.name) end - expose :url, if: -> (*) { request.respond_to?(:ref) } do |blob| + expose :url, if: ->(*) { request.respond_to?(:ref) } do |blob| project_blob_path(request.project, File.join(request.ref, blob.path)) end end diff --git a/app/serializers/build_action_entity.rb b/app/serializers/build_action_entity.rb index 95833c3528f..a40cb02634f 100644 --- a/app/serializers/build_action_entity.rb +++ b/app/serializers/build_action_entity.rb @@ -13,15 +13,15 @@ class BuildActionEntity < Grape::Entity expose :playable?, as: :playable expose :scheduled?, as: :scheduled - expose :scheduled_at, if: -> (*) { scheduled? } + expose :scheduled_at, if: ->(*) { scheduled? } - expose :unschedule_path, if: -> (build) { build.scheduled? } do |build| + expose :unschedule_path, if: ->(build) { build.scheduled? } do |build| unschedule_project_job_path(build.project, build) end private - alias_method :build, :object + alias build object def playable? build.playable? && can?(request.current_user, :update_build, build) diff --git a/app/serializers/build_artifact_entity.rb b/app/serializers/build_artifact_entity.rb index 414f436e76e..af638f05e63 100644 --- a/app/serializers/build_artifact_entity.rb +++ b/app/serializers/build_artifact_entity.rb @@ -14,7 +14,7 @@ class BuildArtifactEntity < Grape::Entity download_project_job_artifacts_path(project, job) end - expose :keep_path, if: -> (*) { job.has_expiring_artifacts? } do |job| + expose :keep_path, if: ->(*) { job.has_expiring_artifacts? } do |job| keep_project_job_artifacts_path(project, job) end @@ -24,7 +24,7 @@ class BuildArtifactEntity < Grape::Entity private - alias_method :job, :object + alias job object def project job.project diff --git a/app/serializers/build_details_entity.rb b/app/serializers/build_details_entity.rb index 9ddce0d2c80..770e7f6975c 100644 --- a/app/serializers/build_details_entity.rb +++ b/app/serializers/build_details_entity.rb @@ -10,7 +10,7 @@ class BuildDetailsEntity < JobEntity expose :runner, using: RunnerEntity expose :pipeline, using: PipelineEntity - expose :deployment_status, if: -> (*) { build.starts_environment? } do + expose :deployment_status, if: ->(*) { build.starts_environment? } do expose :deployment_status, as: :status expose :persisted_environment, as: :environment, with: EnvironmentEntity @@ -18,49 +18,49 @@ class BuildDetailsEntity < JobEntity expose :metadata, using: BuildMetadataEntity - expose :artifact, if: -> (*) { can?(current_user, :read_build, build) } do - expose :download_path, if: -> (*) { build.artifacts? } do |build| + expose :artifact, if: ->(*) { can?(current_user, :read_build, build) } do + expose :download_path, if: ->(*) { build.artifacts? } do |build| download_project_job_artifacts_path(project, build) end - expose :browse_path, if: -> (*) { build.browsable_artifacts? } do |build| + expose :browse_path, if: ->(*) { build.browsable_artifacts? } do |build| browse_project_job_artifacts_path(project, build) end - expose :keep_path, if: -> (*) { build.has_expiring_artifacts? && can?(current_user, :update_build, build) } do |build| + expose :keep_path, if: ->(*) { build.has_expiring_artifacts? && can?(current_user, :update_build, build) } do |build| keep_project_job_artifacts_path(project, build) end - expose :expire_at, if: -> (*) { build.artifacts_expire_at.present? } do |build| + expose :expire_at, if: ->(*) { build.artifacts_expire_at.present? } do |build| build.artifacts_expire_at end - expose :expired, if: -> (*) { build.artifacts_expire_at.present? } do |build| + expose :expired, if: ->(*) { build.artifacts_expire_at.present? } do |build| build.artifacts_expired? end end - expose :erased_by, if: -> (*) { build.erased? }, using: UserEntity - expose :erase_path, if: -> (*) { build.erasable? && can?(current_user, :erase_build, build) } do |build| + expose :erased_by, if: ->(*) { build.erased? }, using: UserEntity + expose :erase_path, if: ->(*) { build.erasable? && can?(current_user, :erase_build, build) } do |build| erase_project_job_path(project, build) end - expose :terminal_path, if: -> (*) { can_create_build_terminal? } do |build| + expose :terminal_path, if: ->(*) { can_create_build_terminal? } do |build| terminal_project_job_path(project, build) end - expose :merge_request, if: -> (*) { can?(current_user, :read_merge_request, build.merge_request) } do + expose :merge_request, if: ->(*) { can?(current_user, :read_merge_request, build.merge_request) } do expose :iid do |build| build.merge_request.iid end expose :path do |build| project_merge_request_path(build.merge_request.project, - build.merge_request) + build.merge_request) end end - expose :new_issue_path, if: -> (*) { can?(request.current_user, :create_issue, project) && build.failed? } do |build| + expose :new_issue_path, if: ->(*) { can?(request.current_user, :create_issue, project) && build.failed? } do |build| new_project_issue_path(project, issue: build_failed_issue_options) end @@ -68,7 +68,7 @@ class BuildDetailsEntity < JobEntity raw_project_job_path(project, build) end - expose :trigger, if: -> (*) { build.trigger_request } do + expose :trigger, if: ->(*) { build.trigger_request } do expose :trigger_short_token, as: :short_token expose :trigger_variables, as: :variables, using: TriggerVariableEntity @@ -83,7 +83,7 @@ class BuildDetailsEntity < JobEntity project.any_runners? end - expose :settings_path, if: -> (*) { can_admin_build? } do |build| + expose :settings_path, if: ->(*) { can_admin_build? } do |build| project_runners_path(project) end end @@ -91,8 +91,8 @@ class BuildDetailsEntity < JobEntity private def build_failed_issue_options - { title: "Job Failed ##{build.id}", - description: "Job [##{build.id}](#{project_job_url(project, build)}) failed for #{build.sha}:\n" } + {title: "Job Failed ##{build.id}", + description: "Job [##{build.id}](#{project_job_url(project, build)}) failed for #{build.sha}:\n",} end def current_user diff --git a/app/serializers/build_serializer.rb b/app/serializers/build_serializer.rb index 0649fdad6a8..8a403fc5901 100644 --- a/app/serializers/build_serializer.rb +++ b/app/serializers/build_serializer.rb @@ -4,7 +4,7 @@ class BuildSerializer < BaseSerializer entity JobEntity def represent_status(resource) - data = represent(resource, { only: [:status] }) + data = represent(resource, {only: [:status]}) data.fetch(:status, {}) end end diff --git a/app/serializers/cluster_application_entity.rb b/app/serializers/cluster_application_entity.rb index 02df1480828..d79a607a98a 100644 --- a/app/serializers/cluster_application_entity.rb +++ b/app/serializers/cluster_application_entity.rb @@ -5,8 +5,8 @@ class ClusterApplicationEntity < Grape::Entity expose :status_name, as: :status expose :status_reason expose :version - expose :external_ip, if: -> (e, _) { e.respond_to?(:external_ip) } - expose :hostname, if: -> (e, _) { e.respond_to?(:hostname) } - expose :email, if: -> (e, _) { e.respond_to?(:email) } - expose :update_available?, as: :update_available, if: -> (e, _) { e.respond_to?(:update_available?) } + expose :external_ip, if: ->(e, _) { e.respond_to?(:external_ip) } + expose :hostname, if: ->(e, _) { e.respond_to?(:hostname) } + expose :email, if: ->(e, _) { e.respond_to?(:email) } + expose :update_available?, as: :update_available, if: ->(e, _) { e.respond_to?(:update_available?) } end diff --git a/app/serializers/cluster_serializer.rb b/app/serializers/cluster_serializer.rb index 4bb4d4880d4..8d7de5869f4 100644 --- a/app/serializers/cluster_serializer.rb +++ b/app/serializers/cluster_serializer.rb @@ -4,6 +4,6 @@ class ClusterSerializer < BaseSerializer entity ClusterEntity def represent_status(resource) - represent(resource, { only: [:status, :status_reason, :applications] }) + represent(resource, {only: [:status, :status_reason, :applications]}) end end diff --git a/app/serializers/cohort_entity.rb b/app/serializers/cohort_entity.rb index 3d0213e1038..f3bc4b0f9b7 100644 --- a/app/serializers/cohort_entity.rb +++ b/app/serializers/cohort_entity.rb @@ -4,7 +4,7 @@ class CohortEntity < Grape::Entity include ActionView::Helpers::NumberHelper expose :registration_month do |cohort| - cohort[:registration_month].strftime('%b %Y') + cohort[:registration_month].strftime("%b %Y") end expose :total do |cohort| diff --git a/app/serializers/commit_entity.rb b/app/serializers/commit_entity.rb index a94e32478ce..37da95ac8d5 100644 --- a/app/serializers/commit_entity.rb +++ b/app/serializers/commit_entity.rb @@ -18,19 +18,19 @@ class CommitEntity < API::Entities::Commit project_commit_path(request.project, commit, params: options.fetch(:commit_url_params, {})) end - expose :description_html, if: { type: :full } do |commit| + expose :description_html, if: {type: :full} do |commit| markdown_field(commit, :description) end - expose :title_html, if: { type: :full } do |commit| + expose :title_html, if: {type: :full} do |commit| markdown_field(commit, :title) end - expose :signature_html, if: { type: :full } do |commit| - render('projects/commit/_signature', signature: commit.signature) if commit.has_signature? + expose :signature_html, if: {type: :full} do |commit| + render("projects/commit/_signature", signature: commit.signature) if commit.has_signature? end - expose :pipeline_status_path, if: { type: :full } do |commit, options| + expose :pipeline_status_path, if: {type: :full} do |commit, options| pipeline_ref = options[:pipeline_ref] pipeline_project = options[:pipeline_project] || commit.project next unless pipeline_ref && pipeline_project diff --git a/app/serializers/container_repository_entity.rb b/app/serializers/container_repository_entity.rb index cc746698a05..460e77f48f1 100644 --- a/app/serializers/container_repository_entity.rb +++ b/app/serializers/container_repository_entity.rb @@ -9,13 +9,13 @@ class ContainerRepositoryEntity < Grape::Entity project_registry_repository_tags_path(project, repository, format: :json) end - expose :destroy_path, if: -> (*) { can_destroy? } do |repository| + expose :destroy_path, if: ->(*) { can_destroy? } do |repository| project_container_registry_path(project, repository, format: :json) end private - alias_method :repository, :object + alias repository object def project request.project diff --git a/app/serializers/container_tag_entity.rb b/app/serializers/container_tag_entity.rb index 361c073e22e..ac2a0eb7067 100644 --- a/app/serializers/container_tag_entity.rb +++ b/app/serializers/container_tag_entity.rb @@ -5,13 +5,13 @@ class ContainerTagEntity < Grape::Entity expose :name, :path, :location, :digest, :revision, :short_revision, :total_size, :created_at - expose :destroy_path, if: -> (*) { can_destroy? } do |tag| + expose :destroy_path, if: ->(*) { can_destroy? } do |tag| project_registry_repository_tag_path(project, tag.repository, tag.name) end private - alias_method :tag, :object + alias tag object def project request.project diff --git a/app/serializers/deploy_key_entity.rb b/app/serializers/deploy_key_entity.rb index 54bf030aba1..e26ed8002c6 100644 --- a/app/serializers/deploy_key_entity.rb +++ b/app/serializers/deploy_key_entity.rb @@ -11,8 +11,8 @@ class DeployKeyEntity < Grape::Entity expose :updated_at expose :deploy_keys_projects, using: DeployKeysProjectEntity do |deploy_key| deploy_key.deploy_keys_projects - .without_project_deleted - .select { |deploy_key_project| Ability.allowed?(options[:user], :read_project, deploy_key_project.project) } + .without_project_deleted + .select { |deploy_key_project| Ability.allowed?(options[:user], :read_project, deploy_key_project.project) } end expose :can_edit diff --git a/app/serializers/deployment_entity.rb b/app/serializers/deployment_entity.rb index 34ae06278c8..206e70e241d 100644 --- a/app/serializers/deployment_entity.rb +++ b/app/serializers/deployment_entity.rb @@ -24,8 +24,8 @@ class DeploymentEntity < Grape::Entity expose :user, using: UserEntity expose :commit, using: CommitEntity expose :deployable, using: JobEntity - expose :manual_actions, using: JobEntity, if: -> (*) { can_create_deployment? } - expose :scheduled_actions, using: JobEntity, if: -> (*) { can_create_deployment? } + expose :manual_actions, using: JobEntity, if: ->(*) { can_create_deployment? } + expose :scheduled_actions, using: JobEntity, if: ->(*) { can_create_deployment? } private diff --git a/app/serializers/detailed_status_entity.rb b/app/serializers/detailed_status_entity.rb index da994d78286..5fc46623d2c 100644 --- a/app/serializers/detailed_status_entity.rb +++ b/app/serializers/detailed_status_entity.rb @@ -9,23 +9,21 @@ class DetailedStatusEntity < Grape::Entity expose :details_path expose :illustration do |status| - begin - illustration = { - image: ActionController::Base.helpers.image_path(status.illustration[:image]) - } - illustration = status.illustration.merge(illustration) + illustration = { + image: ActionController::Base.helpers.image_path(status.illustration[:image]), + } + illustration = status.illustration.merge(illustration) - illustration - rescue NotImplementedError - # ignored - end + illustration + rescue NotImplementedError + # ignored end expose :favicon do |status| Gitlab::Favicon.status_overlay(status.favicon) end - expose :action, if: -> (status, _) { status.has_action? } do + expose :action, if: ->(status, _) { status.has_action? } do expose :action_icon, as: :icon expose :action_title, as: :title expose :action_path, as: :path diff --git a/app/serializers/diff_file_base_entity.rb b/app/serializers/diff_file_base_entity.rb index d8630165e49..a5147c1a860 100644 --- a/app/serializers/diff_file_base_entity.rb +++ b/app/serializers/diff_file_base_entity.rb @@ -20,10 +20,10 @@ class DiffFileBaseEntity < Grape::Entity memoized_submodule_links(diff_file).last end - expose :edit_path, if: -> (_, options) { options[:merge_request] } do |diff_file| + expose :edit_path, if: ->(_, options) { options[:merge_request] } do |diff_file| merge_request = options[:merge_request] - options = merge_request.persisted? ? { from_merge_request_iid: merge_request.iid } : {} + options = merge_request.persisted? ? {from_merge_request_iid: merge_request.iid} : {} next unless merge_request.source_project @@ -46,11 +46,11 @@ class DiffFileBaseEntity < Grape::Entity new_path end - expose :formatted_external_url, if: -> (_, options) { options[:environment] } do |diff_file| + expose :formatted_external_url, if: ->(_, options) { options[:environment] } do |diff_file| options[:environment].formatted_external_url end - expose :external_url, if: -> (_, options) { options[:environment] } do |diff_file| + expose :external_url, if: ->(_, options) { options[:environment] } do |diff_file| options[:environment].external_url_for(diff_file.new_path, diff_file.content_sha) end diff --git a/app/serializers/diff_file_entity.rb b/app/serializers/diff_file_entity.rb index 01ee7af37ed..6db66fef022 100644 --- a/app/serializers/diff_file_entity.rb +++ b/app/serializers/diff_file_entity.rb @@ -7,7 +7,7 @@ class DiffFileEntity < DiffFileBaseEntity expose :added_lines expose :removed_lines - expose :load_collapsed_diff_url, if: -> (diff_file, options) { diff_file.viewer.collapsed? && options[:merge_request] } do |diff_file| + expose :load_collapsed_diff_url, if: ->(diff_file, options) { diff_file.viewer.collapsed? && options[:merge_request] } do |diff_file| merge_request = options[:merge_request] project = merge_request.target_project @@ -23,7 +23,7 @@ class DiffFileEntity < DiffFileBaseEntity ) end - expose :view_path, if: -> (_, options) { options[:merge_request] } do |diff_file| + expose :view_path, if: ->(_, options) { options[:merge_request] } do |diff_file| merge_request = options[:merge_request] project = merge_request.target_project @@ -34,8 +34,8 @@ class DiffFileEntity < DiffFileBaseEntity project_blob_path(project, tree_join(diff_file.content_sha, diff_file.new_path)) end - expose :replaced_view_path, if: -> (_, options) { options[:merge_request] } do |diff_file| - image_diff = diff_file.rich_viewer && diff_file.rich_viewer.partial_name == 'image' + expose :replaced_view_path, if: ->(_, options) { options[:merge_request] } do |diff_file| + image_diff = diff_file.rich_viewer && diff_file.rich_viewer.partial_name == "image" image_replaced = diff_file.old_content_sha && diff_file.old_content_sha != diff_file.content_sha merge_request = options[:merge_request] @@ -46,17 +46,17 @@ class DiffFileEntity < DiffFileBaseEntity project_blob_path(project, tree_join(diff_file.old_content_sha, diff_file.old_path)) if image_diff && image_replaced end - expose :context_lines_path, if: -> (diff_file, _) { diff_file.text? } do |diff_file| + expose :context_lines_path, if: ->(diff_file, _) { diff_file.text? } do |diff_file| next unless diff_file.content_sha project_blob_diff_path(diff_file.repository.project, tree_join(diff_file.content_sha, diff_file.file_path)) end # Used for inline diffs - expose :highlighted_diff_lines, using: DiffLineEntity, if: -> (diff_file, _) { diff_file.text? } do |diff_file| + expose :highlighted_diff_lines, using: DiffLineEntity, if: ->(diff_file, _) { diff_file.text? } do |diff_file| diff_file.diff_lines_for_serializer end # Used for parallel diffs - expose :parallel_diff_lines, using: DiffLineParallelEntity, if: -> (diff_file, _) { diff_file.text? } + expose :parallel_diff_lines, using: DiffLineParallelEntity, if: ->(diff_file, _) { diff_file.text? } end diff --git a/app/serializers/diffs_entity.rb b/app/serializers/diffs_entity.rb index b51e4a7e6d0..8249615c633 100644 --- a/app/serializers/diffs_entity.rb +++ b/app/serializers/diffs_entity.rb @@ -18,7 +18,7 @@ class DiffsEntity < Grape::Entity expose :commit do |diffs, options| CommitEntity.represent options[:commit], options.merge( type: :full, - commit_url_params: { merge_request_iid: merge_request&.iid }, + commit_url_params: {merge_request_iid: merge_request&.iid}, pipeline_ref: merge_request&.source_branch, pipeline_project: merge_request&.source_project ) @@ -36,7 +36,7 @@ class DiffsEntity < Grape::Entity options[:latest_diff] end - expose :latest_version_path, if: -> (*) { merge_request } do |diffs| + expose :latest_version_path, if: ->(*) { merge_request } do |diffs| diffs_project_merge_request_path(merge_request&.project, merge_request) end @@ -56,17 +56,17 @@ class DiffsEntity < Grape::Entity render_overflow_warning?(diffs.diff_files) end - expose :email_patch_path, if: -> (*) { merge_request } do |diffs| + expose :email_patch_path, if: ->(*) { merge_request } do |diffs| merge_request_path(merge_request, format: :patch) end - expose :plain_diff_path, if: -> (*) { merge_request } do |diffs| + expose :plain_diff_path, if: ->(*) { merge_request } do |diffs| merge_request_path(merge_request, format: :diff) end expose :diff_files, using: DiffFileEntity - expose :merge_request_diffs, using: MergeRequestDiffEntity, if: -> (_, options) { options[:merge_request_diffs]&.any? } do |diffs| + expose :merge_request_diffs, using: MergeRequestDiffEntity, if: ->(_, options) { options[:merge_request_diffs]&.any? } do |diffs| options[:merge_request_diffs] end diff --git a/app/serializers/discussion_entity.rb b/app/serializers/discussion_entity.rb index b2d9d52bd22..384dab7f080 100644 --- a/app/serializers/discussion_entity.rb +++ b/app/serializers/discussion_entity.rb @@ -5,11 +5,11 @@ class DiscussionEntity < Grape::Entity include NotesHelper expose :id, :reply_id - expose :position, if: -> (d, _) { d.diff_discussion? && !d.legacy_diff_discussion? } - expose :original_position, if: -> (d, _) { d.diff_discussion? && !d.legacy_diff_discussion? } - expose :line_code, if: -> (d, _) { d.diff_discussion? } + expose :position, if: ->(d, _) { d.diff_discussion? && !d.legacy_diff_discussion? } + expose :original_position, if: ->(d, _) { d.diff_discussion? && !d.legacy_diff_discussion? } + expose :line_code, if: ->(d, _) { d.diff_discussion? } expose :expanded?, as: :expanded - expose :active?, as: :active, if: -> (d, _) { d.diff_discussion? } + expose :active?, as: :active, if: ->(d, _) { d.diff_discussion? } expose :project_id expose :notes do |discussion, opts| @@ -29,22 +29,22 @@ class DiscussionEntity < Grape::Entity expose :resolved_by_push?, as: :resolved_by_push expose :resolved_by, using: NoteUserEntity expose :resolved_at - expose :resolve_path, if: -> (d, _) { d.resolvable? } do |discussion| + expose :resolve_path, if: ->(d, _) { d.resolvable? } do |discussion| resolve_project_merge_request_discussion_path(discussion.project, discussion.noteable, discussion.id) end - expose :resolve_with_issue_path, if: -> (d, _) { d.resolvable? } do |discussion| + expose :resolve_with_issue_path, if: ->(d, _) { d.resolvable? } do |discussion| new_project_issue_path(discussion.project, merge_request_to_resolve_discussions_of: discussion.noteable.iid, discussion_to_resolve: discussion.id) end - expose :diff_file, using: DiscussionDiffFileEntity, if: -> (d, _) { d.diff_discussion? } + expose :diff_file, using: DiscussionDiffFileEntity, if: ->(d, _) { d.diff_discussion? } expose :diff_discussion?, as: :diff_discussion - expose :truncated_diff_lines_path, if: -> (d, _) { !d.expanded? && !render_truncated_diff_lines? } do |discussion| + expose :truncated_diff_lines_path, if: ->(d, _) { !d.expanded? && !render_truncated_diff_lines? } do |discussion| project_merge_request_discussion_path(discussion.project, discussion.noteable, discussion) end - expose :truncated_diff_lines, using: DiffLineEntity, if: -> (d, _) { d.diff_discussion? && d.on_text? && (d.expanded? || render_truncated_diff_lines?) } + expose :truncated_diff_lines, using: DiffLineEntity, if: ->(d, _) { d.diff_discussion? && d.on_text? && (d.expanded? || render_truncated_diff_lines?) } expose :for_commit?, as: :for_commit expose :commit_id diff --git a/app/serializers/entity_date_helper.rb b/app/serializers/entity_date_helper.rb index f515abe5917..547df5e00d9 100644 --- a/app/serializers/entity_date_helper.rb +++ b/app/serializers/entity_date_helper.rb @@ -5,9 +5,9 @@ module EntityDateHelper include ActionView::Helpers::TagHelper def interval_in_words(diff) - return 'Not started' unless diff + return "Not started" unless diff - distance_of_time_in_words(Time.now, diff, scope: 'datetime.time_ago_in_words') + distance_of_time_in_words(Time.now, diff, scope: "datetime.time_ago_in_words") end # Converts seconds into a hash such as: @@ -19,7 +19,7 @@ module EntityDateHelper def distance_of_time_as_hash(diff) diff = diff.abs.floor - return { seconds: 0 } if diff == 0 + return {seconds: 0} if diff == 0 mins = (diff / 60).floor seconds = diff % 60 @@ -46,9 +46,9 @@ module EntityDateHelper # If start date is provided and elapsed, with no due date, it returns "# days elapsed" def remaining_days_in_words(due_date, start_date = nil) if due_date&.past? - content_tag(:strong, 'Past due') + content_tag(:strong, "Past due") elsif start_date&.future? - content_tag(:strong, 'Upcoming') + content_tag(:strong, "Upcoming") elsif due_date is_upcoming = (due_date - Date.today).to_i > 0 time_ago = time_ago_in_words(due_date) @@ -65,7 +65,7 @@ module EntityDateHelper "#{content} #{remaining_or_ago}".html_safe elsif start_date&.past? days = (Date.today - start_date).to_i - "#{content_tag(:strong, days)} #{'day'.pluralize(days)} elapsed".html_safe + "#{content_tag(:strong, days)} #{"day".pluralize(days)} elapsed".html_safe end end end diff --git a/app/serializers/environment_entity.rb b/app/serializers/environment_entity.rb index 76248e6470e..469e2c9fe82 100644 --- a/app/serializers/environment_entity.rb +++ b/app/serializers/environment_entity.rb @@ -12,7 +12,7 @@ class EnvironmentEntity < Grape::Entity expose :last_deployment, using: DeploymentEntity expose :stop_action_available?, as: :has_stop_action - expose :metrics_path, if: -> (environment, _) { environment.has_metrics? } do |environment| + expose :metrics_path, if: ->(environment, _) { environment.has_metrics? } do |environment| metrics_project_environment_path(environment.project, environment) end @@ -44,7 +44,7 @@ class EnvironmentEntity < Grape::Entity private - alias_method :environment, :object + alias environment object def current_user request.current_user @@ -55,7 +55,7 @@ class EnvironmentEntity < Grape::Entity end def cluster_platform_kubernetes? - deployment_platform && deployment_platform.is_a?(Clusters::Platforms::Kubernetes) + deployment_platform&.is_a?(Clusters::Platforms::Kubernetes) end def deployment_platform diff --git a/app/serializers/environment_serializer.rb b/app/serializers/environment_serializer.rb index 598ce5f9e4f..216baed6737 100644 --- a/app/serializers/environment_serializer.rb +++ b/app/serializers/environment_serializer.rb @@ -18,9 +18,9 @@ class EnvironmentSerializer < BaseSerializer def represent(resource, opts = {}) if itemized? itemize(resource).map do |item| - { name: item.name, - size: item.size, - latest: super(item.latest, opts) } + {name: item.name, + size: item.size, + latest: super(item.latest, opts),} end else super(resource, opts) @@ -31,10 +31,10 @@ class EnvironmentSerializer < BaseSerializer # rubocop: disable CodeReuse/ActiveRecord def itemize(resource) - items = resource.order('folder ASC') - .group('COALESCE(environment_type, name)') - .select('COALESCE(environment_type, name) AS folder', - 'COUNT(*) AS size', 'MAX(id) AS last_id') + items = resource.order("folder ASC") + .group("COALESCE(environment_type, name)") + .select("COALESCE(environment_type, name) AS folder", + "COUNT(*) AS size", "MAX(id) AS last_id") # It makes a difference when you call `paginate` method, because # although `page` is effective at the end, it calls counting methods diff --git a/app/serializers/group_child_entity.rb b/app/serializers/group_child_entity.rb index 20d7032c970..ae44a8a77a8 100644 --- a/app/serializers/group_child_entity.rb +++ b/app/serializers/group_child_entity.rb @@ -6,7 +6,7 @@ class GroupChildEntity < Grape::Entity include MarkupHelper expose :id, :name, :description, :visibility, :full_name, - :created_at, :updated_at, :avatar_url + :created_at, :updated_at, :avatar_url expose :type do |instance| type @@ -34,11 +34,11 @@ class GroupChildEntity < Grape::Entity # Project only attributes expose :star_count, :archived, - if: lambda { |_instance, _options| project? } + if: lambda { |_instance, _options| project? } # Group only attributes expose :children_count, :parent_id, :project_count, :subgroup_count, - unless: lambda { |_instance, _options| project? } + unless: lambda { |_instance, _options| project? } expose :leave_path, unless: lambda { |_instance, _options| project? } do |instance| leave_group_members_path(instance) diff --git a/app/serializers/issue_board_entity.rb b/app/serializers/issue_board_entity.rb index f7719447b92..d00d71a6e98 100644 --- a/app/serializers/issue_board_entity.rb +++ b/app/serializers/issue_board_entity.rb @@ -28,23 +28,23 @@ class IssueBoardEntity < Grape::Entity LabelEntity.represent issue.labels, project: issue.project, only: [:id, :title, :description, :color, :priority, :text_color] end - expose :reference_path, if: -> (issue) { issue.project } do |issue, options| + expose :reference_path, if: ->(issue) { issue.project } do |issue, options| options[:include_full_project_path] ? issue.to_reference(full: true) : issue.to_reference end - expose :real_path, if: -> (issue) { issue.project } do |issue| + expose :real_path, if: ->(issue) { issue.project } do |issue| project_issue_path(issue.project, issue) end - expose :issue_sidebar_endpoint, if: -> (issue) { issue.project } do |issue| - project_issue_path(issue.project, issue, format: :json, serializer: 'sidebar_extras') + expose :issue_sidebar_endpoint, if: ->(issue) { issue.project } do |issue| + project_issue_path(issue.project, issue, format: :json, serializer: "sidebar_extras") end - expose :toggle_subscription_endpoint, if: -> (issue) { issue.project } do |issue| + expose :toggle_subscription_endpoint, if: ->(issue) { issue.project } do |issue| toggle_subscription_project_issue_path(issue.project, issue) end - expose :assignable_labels_endpoint, if: -> (issue) { issue.project } do |issue| + expose :assignable_labels_endpoint, if: ->(issue) { issue.project } do |issue| project_labels_path(issue.project, format: :json, include_ancestor_groups: true) end end diff --git a/app/serializers/issue_entity.rb b/app/serializers/issue_entity.rb index c3f7d4651fb..7825398b575 100644 --- a/app/serializers/issue_entity.rb +++ b/app/serializers/issue_entity.rb @@ -38,10 +38,10 @@ class IssueEntity < IssuableEntity end expose :create_note_path do |issue| - project_notes_path(issue.project, target_type: 'issue', target_id: issue.id) + project_notes_path(issue.project, target_type: "issue", target_id: issue.id) end expose :preview_note_path do |issue| - preview_markdown_path(issue.project, quick_actions_target_type: 'Issue', quick_actions_target_id: issue.iid) + preview_markdown_path(issue.project, quick_actions_target_type: "Issue", quick_actions_target_id: issue.iid) end end diff --git a/app/serializers/issue_serializer.rb b/app/serializers/issue_serializer.rb index 0fa76f098cd..a57599f895d 100644 --- a/app/serializers/issue_serializer.rb +++ b/app/serializers/issue_serializer.rb @@ -7,11 +7,11 @@ class IssueSerializer < BaseSerializer def represent(issue, opts = {}) entity = case opts[:serializer] - when 'sidebar' + when "sidebar" IssueSidebarBasicEntity - when 'sidebar_extras' + when "sidebar_extras" IssueSidebarExtrasEntity - when 'board' + when "board" IssueBoardEntity else IssueEntity diff --git a/app/serializers/job_entity.rb b/app/serializers/job_entity.rb index d0099ae77f2..7ea04167a4c 100644 --- a/app/serializers/job_entity.rb +++ b/app/serializers/job_entity.rb @@ -13,38 +13,38 @@ class JobEntity < Grape::Entity build_path(build) end - expose :retry_path, if: -> (*) { retryable? } do |build| + expose :retry_path, if: ->(*) { retryable? } do |build| path_to(:retry_namespace_project_job, build) end - expose :cancel_path, if: -> (*) { cancelable? } do |build| + expose :cancel_path, if: ->(*) { cancelable? } do |build| path_to( :cancel_namespace_project_job, build, - { continue: { to: build_path(build) } } + {continue: {to: build_path(build)}} ) end - expose :play_path, if: -> (*) { playable? } do |build| + expose :play_path, if: ->(*) { playable? } do |build| path_to(:play_namespace_project_job, build) end - expose :unschedule_path, if: -> (*) { scheduled? } do |build| + expose :unschedule_path, if: ->(*) { scheduled? } do |build| path_to(:unschedule_namespace_project_job, build) end expose :playable?, as: :playable expose :scheduled?, as: :scheduled - expose :scheduled_at, if: -> (*) { scheduled? } + expose :scheduled_at, if: ->(*) { scheduled? } expose :created_at expose :updated_at expose :detailed_status, as: :status, with: DetailedStatusEntity - expose :callout_message, if: -> (*) { failed? && !build.script_failure? } - expose :recoverable, if: -> (*) { failed? } + expose :callout_message, if: ->(*) { failed? && !build.script_failure? } + expose :recoverable, if: ->(*) { failed? } private - alias_method :build, :object + alias build object def cancelable? build.cancelable? && can?(request.current_user, :update_build, build) diff --git a/app/serializers/job_group_entity.rb b/app/serializers/job_group_entity.rb index 0db7624b3f7..90a488b5d5d 100644 --- a/app/serializers/job_group_entity.rb +++ b/app/serializers/job_group_entity.rb @@ -10,7 +10,7 @@ class JobGroupEntity < Grape::Entity private - alias_method :group, :object + alias group object def detailed_status group.detailed_status(request.current_user) diff --git a/app/serializers/label_entity.rb b/app/serializers/label_entity.rb index 5082245dda9..5905a785e57 100644 --- a/app/serializers/label_entity.rb +++ b/app/serializers/label_entity.rb @@ -13,7 +13,7 @@ class LabelEntity < Grape::Entity expose :created_at expose :updated_at - expose :priority, if: -> (*) { options.key?(:project) } do |label| + expose :priority, if: ->(*) { options.key?(:project) } do |label| label.priority(options[:project]) end end diff --git a/app/serializers/label_serializer.rb b/app/serializers/label_serializer.rb index 25b9f7de243..ac2b52433e8 100644 --- a/app/serializers/label_serializer.rb +++ b/app/serializers/label_serializer.rb @@ -4,6 +4,6 @@ class LabelSerializer < BaseSerializer entity LabelEntity def represent_appearance(resource) - represent(resource, { only: [:id, :title, :color, :text_color] }) + represent(resource, {only: [:id, :title, :color, :text_color]}) end end diff --git a/app/serializers/lfs_file_lock_entity.rb b/app/serializers/lfs_file_lock_entity.rb index 7961c4e666b..3aa6c120b86 100644 --- a/app/serializers/lfs_file_lock_entity.rb +++ b/app/serializers/lfs_file_lock_entity.rb @@ -1,7 +1,7 @@ # frozen_string_literal: true class LfsFileLockEntity < Grape::Entity - root 'locks', 'lock' + root "locks", "lock" expose :path expose(:id) { |entity| entity.id.to_s } diff --git a/app/serializers/merge_request_serializer.rb b/app/serializers/merge_request_serializer.rb index 4cf84336aa4..a8dbf69ceb4 100644 --- a/app/serializers/merge_request_serializer.rb +++ b/app/serializers/merge_request_serializer.rb @@ -7,11 +7,11 @@ class MergeRequestSerializer < BaseSerializer def represent(merge_request, opts = {}) entity = case opts[:serializer] - when 'sidebar' + when "sidebar" MergeRequestSidebarBasicEntity - when 'sidebar_extras' + when "sidebar_extras" IssuableSidebarExtrasEntity - when 'basic' + when "basic" MergeRequestBasicEntity else # fallback to widget for old poll requests without `serializer` set diff --git a/app/serializers/merge_request_user_entity.rb b/app/serializers/merge_request_user_entity.rb index 53257b0602c..95168f53998 100644 --- a/app/serializers/merge_request_user_entity.rb +++ b/app/serializers/merge_request_user_entity.rb @@ -13,7 +13,7 @@ class MergeRequestUserEntity < CurrentUserEntity project && can?(user, :create_merge_request_in, project) end - expose :fork_path, if: -> (*) { project } do |user| + expose :fork_path, if: ->(*) { project } do |user| params = edit_blob_fork_params("Edit") project_forks_path(project, namespace_key: user.namespace.id, continue: params) end diff --git a/app/serializers/merge_request_widget_entity.rb b/app/serializers/merge_request_widget_entity.rb index 2142ceb6122..7f7365dc1a9 100644 --- a/app/serializers/merge_request_widget_entity.rb +++ b/app/serializers/merge_request_widget_entity.rb @@ -56,7 +56,7 @@ class MergeRequestWidgetEntity < IssuableEntity merge_request.diff_head_sha.presence end - expose :actual_head_pipeline, with: PipelineDetailsEntity, as: :pipeline, if: -> (mr, _) { presenter(mr).can_read_pipeline? } + expose :actual_head_pipeline, with: PipelineDetailsEntity, as: :pipeline, if: ->(mr, _) { presenter(mr).can_read_pipeline? } expose :merge_pipeline, with: PipelineDetailsEntity, if: ->(mr, _) { mr.merged? && can?(request.current_user, :read_pipeline, mr.target_project)} @@ -226,7 +226,7 @@ class MergeRequestWidgetEntity < IssuableEntity end expose :create_note_path do |merge_request| - project_notes_path(merge_request.project, target_type: 'merge_request', target_id: merge_request.id) + project_notes_path(merge_request.project, target_type: "merge_request", target_id: merge_request.id) end expose :commit_change_content_path do |merge_request| @@ -234,7 +234,7 @@ class MergeRequestWidgetEntity < IssuableEntity end expose :preview_note_path do |merge_request| - preview_markdown_path(merge_request.project, quick_actions_target_type: 'MergeRequest', quick_actions_target_id: merge_request.iid) + preview_markdown_path(merge_request.project, quick_actions_target_type: "MergeRequest", quick_actions_target_id: merge_request.iid) end expose :merge_commit_path do |merge_request| diff --git a/app/serializers/note_entity.rb b/app/serializers/note_entity.rb index 1d3b59eb1b7..b8ea9b86f4a 100644 --- a/app/serializers/note_entity.rb +++ b/app/serializers/note_entity.rb @@ -19,8 +19,8 @@ class NoteEntity < API::Entities::Note expose :redacted_note_html, as: :note_html - expose :last_edited_at, if: -> (note, _) { note.edited? } - expose :last_edited_by, using: NoteUserEntity, if: -> (note, _) { note.edited? } + expose :last_edited_at, if: ->(note, _) { note.edited? } + expose :last_edited_by, using: NoteUserEntity, if: ->(note, _) { note.edited? } expose :current_user do expose :can_edit do |note| @@ -42,7 +42,7 @@ class NoteEntity < API::Entities::Note expose :resolved_by, using: NoteUserEntity - expose :system_note_icon_name, if: -> (note, _) { note.system? } do |note| + expose :system_note_icon_name, if: ->(note, _) { note.system? } do |note| SystemNoteHelper.system_note_icon_name(note) end @@ -51,9 +51,9 @@ class NoteEntity < API::Entities::Note end expose :emoji_awardable?, as: :emoji_awardable - expose :award_emoji, if: -> (note, _) { note.emoji_awardable? }, using: AwardEmojiEntity + expose :award_emoji, if: ->(note, _) { note.emoji_awardable? }, using: AwardEmojiEntity - expose :report_abuse_path, if: -> (note, _) { note.author_id } do |note| + expose :report_abuse_path, if: ->(note, _) { note.author_id } do |note| new_abuse_report_path(user_id: note.author_id, ref_url: Gitlab::UrlBuilder.build(note)) end @@ -61,15 +61,15 @@ class NoteEntity < API::Entities::Note noteable_note_url(note) end - expose :resolve_path, if: -> (note, _) { note.part_of_discussion? && note.resolvable? } do |note| + expose :resolve_path, if: ->(note, _) { note.part_of_discussion? && note.resolvable? } do |note| resolve_project_merge_request_discussion_path(note.project, note.noteable, note.discussion_id) end - expose :resolve_with_issue_path, if: -> (note, _) { note.part_of_discussion? && note.resolvable? } do |note| + expose :resolve_with_issue_path, if: ->(note, _) { note.part_of_discussion? && note.resolvable? } do |note| new_project_issue_path(note.project, merge_request_to_resolve_discussions_of: note.noteable.iid, discussion_to_resolve: note.discussion_id) end - expose :attachment, using: NoteAttachmentEntity, if: -> (note, _) { note.attachment? } + expose :attachment, using: NoteAttachmentEntity, if: ->(note, _) { note.attachment? } expose :cached_markdown_version diff --git a/app/serializers/pipeline_entity.rb b/app/serializers/pipeline_entity.rb index 29b1a6c244b..366bf2abeb5 100644 --- a/app/serializers/pipeline_entity.rb +++ b/app/serializers/pipeline_entity.rb @@ -53,23 +53,23 @@ class PipelineEntity < Grape::Entity end expose :commit, using: CommitEntity - expose :yaml_errors, if: -> (pipeline, _) { pipeline.has_yaml_errors? } + expose :yaml_errors, if: ->(pipeline, _) { pipeline.has_yaml_errors? } - expose :failure_reason, if: -> (pipeline, _) { pipeline.failure_reason? } do |pipeline| + expose :failure_reason, if: ->(pipeline, _) { pipeline.failure_reason? } do |pipeline| pipeline.present.failure_reason end - expose :retry_path, if: -> (*) { can_retry? } do |pipeline| + expose :retry_path, if: ->(*) { can_retry? } do |pipeline| retry_project_pipeline_path(pipeline.project, pipeline) end - expose :cancel_path, if: -> (*) { can_cancel? } do |pipeline| + expose :cancel_path, if: ->(*) { can_cancel? } do |pipeline| cancel_project_pipeline_path(pipeline.project, pipeline) end private - alias_method :pipeline, :object + alias pipeline object def can_retry? can?(request.current_user, :update_pipeline, pipeline) && diff --git a/app/serializers/pipeline_serializer.rb b/app/serializers/pipeline_serializer.rb index 7451433a841..95c6216f278 100644 --- a/app/serializers/pipeline_serializer.rb +++ b/app/serializers/pipeline_serializer.rb @@ -17,11 +17,11 @@ class PipelineSerializer < BaseSerializer :artifacts, { pending_builds: :project, - project: [:route, { namespace: :route }], + project: [:route, {namespace: :route}], artifacts: { - project: [:route, { namespace: :route }] - } - } + project: [:route, {namespace: :route}], + }, + }, ]) end @@ -40,14 +40,14 @@ class PipelineSerializer < BaseSerializer def represent_status(resource) return {} unless resource.present? - data = represent(resource, { only: [{ details: [:status] }] }) + data = represent(resource, {only: [{details: [:status]}]}) data.dig(:details, :status) || {} end def represent_stages(resource) return {} unless resource.present? - data = represent(resource, { only: [{ details: [:stages] }], preload: true }) + data = represent(resource, {only: [{details: [:stages]}], preload: true}) data.dig(:details, :stages) || [] end end diff --git a/app/serializers/project_note_entity.rb b/app/serializers/project_note_entity.rb index f6cdea1d8b5..e40ee02b550 100644 --- a/app/serializers/project_note_entity.rb +++ b/app/serializers/project_note_entity.rb @@ -1,27 +1,27 @@ # frozen_string_literal: true class ProjectNoteEntity < NoteEntity - expose :human_access, if: -> (note, _) { note.project.present? } do |note| + expose :human_access, if: ->(note, _) { note.project.present? } do |note| note.project.team.human_max_access(note.author_id) end - expose :toggle_award_path, if: -> (note, _) { note.emoji_awardable? } do |note| + expose :toggle_award_path, if: ->(note, _) { note.emoji_awardable? } do |note| toggle_award_emoji_project_note_path(note.project, note.id) end - expose :path, if: -> (note, _) { note.id } do |note| + expose :path, if: ->(note, _) { note.id } do |note| project_note_path(note.project, note) end - expose :resolve_path, if: -> (note, _) { note.part_of_discussion? && note.resolvable? } do |note| + expose :resolve_path, if: ->(note, _) { note.part_of_discussion? && note.resolvable? } do |note| resolve_project_merge_request_discussion_path(note.project, note.noteable, note.discussion_id) end - expose :resolve_with_issue_path, if: -> (note, _) { note.part_of_discussion? && note.resolvable? } do |note| + expose :resolve_with_issue_path, if: ->(note, _) { note.part_of_discussion? && note.resolvable? } do |note| new_project_issue_path(note.project, merge_request_to_resolve_discussions_of: note.noteable.iid, discussion_to_resolve: note.discussion_id) end - expose :delete_attachment_path, if: -> (note, _) { note.attachment? } do |note| + expose :delete_attachment_path, if: ->(note, _) { note.attachment? } do |note| delete_attachment_project_note_path(note.project, note) end end diff --git a/app/serializers/projects/serverless/service_entity.rb b/app/serializers/projects/serverless/service_entity.rb index c98dc1a1c4a..6ec03e5a22b 100644 --- a/app/serializers/projects/serverless/service_entity.rb +++ b/app/serializers/projects/serverless/service_entity.rb @@ -6,59 +6,62 @@ module Projects include RequestAwareEntity expose :name do |service| - service.dig('metadata', 'name') + service.dig("metadata", "name") end expose :namespace do |service| - service.dig('metadata', 'namespace') + service.dig("metadata", "namespace") end expose :environment_scope do |service| - service.dig('environment_scope') + service.dig("environment_scope") end expose :cluster_id do |service| - service.dig('cluster_id') + service.dig("cluster_id") end expose :detail_url do |service| project_serverless_path( request.project, - service.dig('environment_scope'), - service.dig('metadata', 'name')) + service.dig("environment_scope"), + service.dig("metadata", "name") + ) end expose :podcount do |service| - service.dig('podcount') + service.dig("podcount") end expose :created_at do |service| - service.dig('metadata', 'creationTimestamp') + service.dig("metadata", "creationTimestamp") end expose :url do |service| - "http://#{service.dig('status', 'domain')}" + "http://#{service.dig("status", "domain")}" end expose :description do |service| service.dig( - 'spec', - 'runLatest', - 'configuration', - 'revisionTemplate', - 'metadata', - 'annotations', - 'Description') + "spec", + "runLatest", + "configuration", + "revisionTemplate", + "metadata", + "annotations", + "Description" + ) end expose :image do |service| service.dig( - 'spec', - 'runLatest', - 'configuration', - 'build', - 'template', - 'name') + "spec", + "runLatest", + "configuration", + "build", + "template", + "name" + ) end end end diff --git a/app/serializers/runner_entity.rb b/app/serializers/runner_entity.rb index 97e5b336a35..71f520c5494 100644 --- a/app/serializers/runner_entity.rb +++ b/app/serializers/runner_entity.rb @@ -5,13 +5,13 @@ class RunnerEntity < Grape::Entity expose :id, :description - expose :edit_path, if: -> (*) { can_edit_runner? } do |runner| + expose :edit_path, if: ->(*) { can_edit_runner? } do |runner| edit_project_runner_path(project, runner) end private - alias_method :runner, :object + alias runner object def project request.project diff --git a/app/serializers/stage_entity.rb b/app/serializers/stage_entity.rb index 029dd3d0684..116a179578c 100644 --- a/app/serializers/stage_entity.rb +++ b/app/serializers/stage_entity.rb @@ -10,18 +10,18 @@ class StageEntity < Grape::Entity end expose :groups, - if: -> (_, opts) { opts[:grouped] }, + if: ->(_, opts) { opts[:grouped] }, with: JobGroupEntity expose :latest_statuses, - if: -> (_, opts) { opts[:details] }, + if: ->(_, opts) { opts[:details] }, with: JobEntity do |stage| latest_statuses end expose :retried, - if: -> (_, opts) { opts[:retried] }, - with: JobEntity do |stage| + if: ->(_, opts) { opts[:retried] }, + with: JobEntity do |stage| retried_statuses end @@ -31,7 +31,8 @@ class StageEntity < Grape::Entity project_pipeline_path( stage.pipeline.project, stage.pipeline, - anchor: stage.name) + anchor: stage.name + ) end expose :dropdown_path do |stage| @@ -39,12 +40,13 @@ class StageEntity < Grape::Entity stage.pipeline.project, stage.pipeline, stage: stage.name, - format: :json) + format: :json + ) end private - alias_method :stage, :object + alias stage object def detailed_status stage.detailed_status(request.current_user) @@ -59,14 +61,14 @@ class StageEntity < Grape::Entity end def latest_statuses - HasStatus::ORDERED_STATUSES.map do |ordered_status| + HasStatus::ORDERED_STATUSES.map { |ordered_status| grouped_statuses.fetch(ordered_status, []) - end.flatten + }.flatten end def retried_statuses - HasStatus::ORDERED_STATUSES.map do |ordered_status| + HasStatus::ORDERED_STATUSES.map { |ordered_status| grouped_retried_statuses.fetch(ordered_status, []) - end.flatten + }.flatten end end diff --git a/app/serializers/submodule_entity.rb b/app/serializers/submodule_entity.rb index e475a4f301f..6d0ca697772 100644 --- a/app/serializers/submodule_entity.rb +++ b/app/serializers/submodule_entity.rb @@ -6,7 +6,7 @@ class SubmoduleEntity < Grape::Entity expose :id, :path, :name, :mode expose :icon do |blob| - 'archive' + "archive" end expose :url do |blob| diff --git a/app/services/access_token_validation_service.rb b/app/services/access_token_validation_service.rb index 40aa9250885..c16b82ef444 100644 --- a/app/services/access_token_validation_service.rb +++ b/app/services/access_token_validation_service.rb @@ -17,21 +17,21 @@ class AccessTokenValidationService def validate(scopes: []) if token.expired? - return EXPIRED + EXPIRED elsif token.revoked? - return REVOKED + REVOKED - elsif !self.include_any_scope?(scopes) - return INSUFFICIENT_SCOPE + elsif !include_any_scope?(scopes) + INSUFFICIENT_SCOPE elsif token.respond_to?(:impersonation) && token.impersonation && !Gitlab.config.gitlab.impersonation_enabled - return IMPERSONATION_DISABLED + IMPERSONATION_DISABLED else - return VALID + VALID end end diff --git a/app/services/akismet_service.rb b/app/services/akismet_service.rb index 82ae66ab0f5..1672be9a3b2 100644 --- a/app/services/akismet_service.rb +++ b/app/services/akismet_service.rb @@ -13,12 +13,12 @@ class AkismetService return false unless akismet_enabled? params = { - type: 'comment', + type: "comment", text: text, created_at: DateTime.now, author: owner.name, author_email: owner.email, - referrer: options[:referrer] + referrer: options[:referrer], } begin @@ -42,7 +42,7 @@ class AkismetService def akismet_client @akismet_client ||= ::Akismet::Client.new(Gitlab::CurrentSettings.akismet_api_key, - Gitlab.config.gitlab.url) + Gitlab.config.gitlab.url) end def akismet_enabled? @@ -53,10 +53,10 @@ class AkismetService return false unless akismet_enabled? params = { - type: 'comment', + type: "comment", text: text, author: owner.name, - author_email: owner.email + author_email: owner.email, } begin diff --git a/app/services/audit_event_service.rb b/app/services/audit_event_service.rb index 201048aaba5..72529cd2ba1 100644 --- a/app/services/audit_event_service.rb +++ b/app/services/audit_event_service.rb @@ -9,8 +9,8 @@ class AuditEventService @details = { with: @details[:with], target_id: @author.id, - target_type: 'User', - target_details: @author.name + target_type: "User", + target_details: @author.name, } self @@ -27,7 +27,7 @@ class AuditEventService { author_id: @author.id, entity_id: @entity.id, - entity_type: @entity.class.name + entity_type: @entity.class.name, } end diff --git a/app/services/auth/container_registry_authentication_service.rb b/app/services/auth/container_registry_authentication_service.rb index e95ba09c006..4a6da870958 100644 --- a/app/services/auth/container_registry_authentication_service.rb +++ b/app/services/auth/container_registry_authentication_service.rb @@ -2,18 +2,18 @@ module Auth class ContainerRegistryAuthenticationService < BaseService - AUDIENCE = 'container_registry'.freeze + AUDIENCE = "container_registry" def execute(authentication_abilities:) @authentication_abilities = authentication_abilities - return error('UNAVAILABLE', status: 404, message: 'registry not enabled') unless registry.enabled + return error("UNAVAILABLE", status: 404, message: "registry not enabled") unless registry.enabled unless scopes.any? || current_user || project - return error('DENIED', status: 403, message: 'access forbidden') + return error("DENIED", status: 403, message: "access forbidden") end - { token: authorized_token(*scopes).encoded } + {token: authorized_token(*scopes).encoded} end def self.full_access_token(*names) @@ -24,9 +24,9 @@ module Auth token.audience = AUDIENCE token.expire_time = token_expire_at - token[:access] = names.map do |name| - { type: 'repository', name: name, actions: %w(*) } - end + token[:access] = names.map { |name| + {type: "repository", name: name, actions: %w[*]} + } token.encoded end @@ -50,19 +50,19 @@ module Auth def scopes return [] unless params[:scopes] - @scopes ||= params[:scopes].map do |scope| + @scopes ||= params[:scopes].map { |scope| process_scope(scope) - end.compact + }.compact end def process_scope(scope) - type, name, actions = scope.split(':', 3) - actions = actions.split(',') + type, name, actions = scope.split(":", 3) + actions = actions.split(",") case type - when 'registry' + when "registry" process_registry_access(type, name, actions) - when 'repository' + when "repository" path = ContainerRegistry::Path.new(name) process_repository_access(type, path, actions) end @@ -70,10 +70,10 @@ module Auth def process_registry_access(type, name, actions) return unless current_user&.admin? - return unless name == 'catalog' - return unless actions == ['*'] + return unless name == "catalog" + return unless actions == ["*"] - { type: type, name: name, actions: ['*'] } + {type: type, name: name, actions: ["*"]} end def process_repository_access(type, path, actions) @@ -83,9 +83,9 @@ module Auth return unless requested_project - actions = actions.select do |action| + actions = actions.select { |action| can_access?(requested_project, action) - end + } return unless actions.present? @@ -93,7 +93,7 @@ module Auth # ensure_container_repository!(path, actions) - { type: type, name: path.to_s, actions: actions } + {type: type, name: path.to_s, actions: actions} end ## @@ -103,7 +103,7 @@ module Auth # def ensure_container_repository!(path, actions) return if path.has_repository? - return unless actions.include?('push') + return unless actions.include?("push") ContainerRepository.create_from_path!(path) end @@ -112,11 +112,11 @@ module Auth return false unless requested_project.container_registry_enabled? case requested_action - when 'pull' + when "pull" build_can_pull?(requested_project) || user_can_pull?(requested_project) || deploy_token_can_pull?(requested_project) - when 'push' + when "push" build_can_push?(requested_project) || user_can_push?(requested_project) - when '*' + when "*" user_can_admin?(requested_project) else false @@ -174,8 +174,8 @@ module Auth can_user?(:create_container_image, requested_project) end - def error(code, status:, message: '') - { errors: [{ code: code, message: message }], http_status: status } + def error(code, status:, message: "") + {errors: [{code: code, message: message}], http_status: status} end def has_authentication_ability?(capability) diff --git a/app/services/base_count_service.rb b/app/services/base_count_service.rb index ad1647842b8..d3ba3686df1 100644 --- a/app/services/base_count_service.rb +++ b/app/services/base_count_service.rb @@ -35,13 +35,13 @@ class BaseCountService end def cache_key - raise NotImplementedError, 'cache_key must be implemented and return a String' + raise NotImplementedError, "cache_key must be implemented and return a String" end # subclasses can override to add any specific options, such as # super.merge({ expires_in: 5.minutes }) def cache_options - { raw: raw? } + {raw: raw?} end def update_cache_for_key(key, &block) diff --git a/app/services/base_service.rb b/app/services/base_service.rb index 3e968c8f707..5fdee88136f 100644 --- a/app/services/base_service.rb +++ b/app/services/base_service.rb @@ -49,7 +49,7 @@ class BaseService def error(message, http_status = nil) result = { message: message, - status: :error + status: :error, } result[:http_status] = http_status if http_status diff --git a/app/services/boards/issues/create_service.rb b/app/services/boards/issues/create_service.rb index bd045e18b8d..c8b3908decc 100644 --- a/app/services/boards/issues/create_service.rb +++ b/app/services/boards/issues/create_service.rb @@ -18,7 +18,7 @@ module Boards private def issue_params - { label_ids: [list.label_id] } + {label_ids: [list.label_id]} end def board diff --git a/app/services/boards/issues/list_service.rb b/app/services/boards/issues/list_service.rb index 0b69661bbd0..87bf3f2f5a8 100644 --- a/app/services/boards/issues/list_service.rb +++ b/app/services/boards/issues/list_service.rb @@ -12,8 +12,8 @@ module Boards # rubocop: disable CodeReuse/ActiveRecord def metadata keys = metadata_fields.keys - columns = metadata_fields.values_at(*keys).join(', ') - results = Issue.where(id: fetch_issues.select('issues.id')).pluck(columns) + columns = metadata_fields.values_at(*keys).join(", ") + results = Issue.where(id: fetch_issues.select("issues.id")).pluck(columns) Hash[keys.zip(results.flatten)] end @@ -22,7 +22,7 @@ module Boards private def metadata_fields - { size: 'COUNT(*)' } + {size: "COUNT(*)"} end # We memoize the query here since the finder methods we use are quite complex. This does not memoize the result of the query. @@ -70,7 +70,7 @@ module Boards end def set_state - params[:state] = list && list.closed? ? 'closed' : 'opened' + params[:state] = list && list.closed? ? "closed" : "opened" end def set_scope @@ -91,7 +91,7 @@ module Boards def without_board_labels(issues) return issues unless board_label_ids.any? - issues.where.not('EXISTS (?)', issues_label_links.limit(1)) + issues.where.not("EXISTS (?)", issues_label_links.limit(1)) end # rubocop: enable CodeReuse/ActiveRecord @@ -103,7 +103,7 @@ module Boards # rubocop: disable CodeReuse/ActiveRecord def with_list_label(issues) - issues.where('EXISTS (?)', LabelLink.where("label_links.target_type = 'Issue' AND label_links.target_id = issues.id") + issues.where("EXISTS (?)", LabelLink.where("label_links.target_type = 'Issue' AND label_links.target_id = issues.id") .where("label_links.label_id = ?", list.label_id).limit(1)) end # rubocop: enable CodeReuse/ActiveRecord diff --git a/app/services/boards/issues/move_service.rb b/app/services/boards/issues/move_service.rb index 834baeb9643..9e8413c1ae0 100644 --- a/app/services/boards/issues/move_service.rb +++ b/app/services/boards/issues/move_service.rb @@ -57,8 +57,8 @@ module Boards end def issue_state - return 'reopen' if moving_from_list.closed? - return 'close' if moving_to_list.closed? + return "reopen" if moving_from_list.closed? + return "close" if moving_to_list.closed? end def add_label_ids diff --git a/app/services/boards/lists/create_service.rb b/app/services/boards/lists/create_service.rb index 48d2d5abaec..154807a64a8 100644 --- a/app/services/boards/lists/create_service.rb +++ b/app/services/boards/lists/create_service.rb @@ -26,10 +26,11 @@ module Boards end def available_labels_for(board) - options = { include_ancestor_groups: true } + options = {include_ancestor_groups: true} if board.group_board? - options.merge!(group_id: parent.id, only_group_labels: true) + options[:group_id] = parent.id + options[:only_group_labels] = true else options[:project_id] = parent.id end @@ -43,7 +44,7 @@ module Boards end def create_list(board, type, target, position) - board.lists.create(type => target, list_type: type, position: position) + board.lists.create(type => target, :list_type => type, :position => position) end end end diff --git a/app/services/boards/lists/destroy_service.rb b/app/services/boards/lists/destroy_service.rb index e20805d0405..89e02eee2f9 100644 --- a/app/services/boards/lists/destroy_service.rb +++ b/app/services/boards/lists/destroy_service.rb @@ -20,8 +20,8 @@ module Boards # rubocop: disable CodeReuse/ActiveRecord def decrement_higher_lists(list) - board.lists.movable.where('position > ?', list.position) - .update_all('position = position - 1') + board.lists.movable.where("position > ?", list.position) + .update_all("position = position - 1") end # rubocop: enable CodeReuse/ActiveRecord diff --git a/app/services/boards/lists/generate_service.rb b/app/services/boards/lists/generate_service.rb index 4fbf1026019..8f7cdb384dc 100644 --- a/app/services/boards/lists/generate_service.rb +++ b/app/services/boards/lists/generate_service.rb @@ -26,8 +26,8 @@ module Boards def label_params [ - { name: 'To Do', color: '#F0AD4E' }, - { name: 'Doing', color: '#5CB85C' } + {name: "To Do", color: "#F0AD4E"}, + {name: "Doing", color: "#5CB85C"}, ] end end diff --git a/app/services/boards/lists/move_service.rb b/app/services/boards/lists/move_service.rb index 93f81837d1a..da3a46d658d 100644 --- a/app/services/boards/lists/move_service.rb +++ b/app/services/boards/lists/move_service.rb @@ -36,17 +36,17 @@ module Boards # rubocop: disable CodeReuse/ActiveRecord def decrement_intermediate_lists - board.lists.movable.where('position > ?', old_position) - .where('position <= ?', new_position) - .update_all('position = position - 1') + board.lists.movable.where("position > ?", old_position) + .where("position <= ?", new_position) + .update_all("position = position - 1") end # rubocop: enable CodeReuse/ActiveRecord # rubocop: disable CodeReuse/ActiveRecord def increment_intermediate_lists - board.lists.movable.where('position >= ?', new_position) - .where('position < ?', old_position) - .update_all('position = position + 1') + board.lists.movable.where("position >= ?", new_position) + .where("position < ?", old_position) + .update_all("position = position + 1") end # rubocop: enable CodeReuse/ActiveRecord diff --git a/app/services/chat_names/authorize_user_service.rb b/app/services/chat_names/authorize_user_service.rb index 78b53cb3637..c30d3b07630 100644 --- a/app/services/chat_names/authorize_user_service.rb +++ b/app/services/chat_names/authorize_user_service.rb @@ -33,7 +33,7 @@ module ChatNames team_id: @params[:team_id], team_domain: @params[:team_domain], chat_id: @params[:user_id], - chat_name: @params[:user_name] + chat_name: @params[:user_name], } end end diff --git a/app/services/ci/archive_trace_service.rb b/app/services/ci/archive_trace_service.rb index a1dd00721b5..5bb68ae55b2 100644 --- a/app/services/ci/archive_trace_service.rb +++ b/app/services/ci/archive_trace_service.rb @@ -19,7 +19,7 @@ module Ci def failed_archive_counter @failed_archive_counter ||= Gitlab::Metrics.counter(:job_trace_archive_failed_total, - "Counter of failed attempts of trace archiving") + "Counter of failed attempts of trace archiving") end def archive_error(error, job) @@ -28,8 +28,8 @@ module Ci Gitlab::Sentry .track_exception(error, - issue_url: 'https://gitlab.com/gitlab-org/gitlab-ce/issues/51502', - extra: { job_id: job.id }) + issue_url: "https://gitlab.com/gitlab-org/gitlab-ce/issues/51502", + extra: {job_id: job.id}) end end end diff --git a/app/services/ci/compare_reports_base_service.rb b/app/services/ci/compare_reports_base_service.rb index d5625857599..7d42f1c0d5a 100644 --- a/app/services/ci/compare_reports_base_service.rb +++ b/app/services/ci/compare_reports_base_service.rb @@ -9,13 +9,13 @@ module Ci key: key(base_pipeline, head_pipeline), data: serializer_class .new(project: project) - .represent(comparer).as_json + .represent(comparer).as_json, } rescue Gitlab::Ci::Parsers::ParserError => e { status: :error, key: key(base_pipeline, head_pipeline), - status_reason: e.message + status_reason: e.message, } end @@ -28,7 +28,7 @@ module Ci def key(base_pipeline, head_pipeline) [ base_pipeline&.id, base_pipeline&.updated_at, - head_pipeline&.id, head_pipeline&.updated_at + head_pipeline&.id, head_pipeline&.updated_at, ] end diff --git a/app/services/ci/create_pipeline_service.rb b/app/services/ci/create_pipeline_service.rb index 8973c5ffc9e..d3d48c45987 100644 --- a/app/services/ci/create_pipeline_service.rb +++ b/app/services/ci/create_pipeline_service.rb @@ -15,7 +15,7 @@ module Ci Gitlab::Ci::Pipeline::Chain::Limit::Size, Gitlab::Ci::Pipeline::Chain::Populate, Gitlab::Ci::Pipeline::Chain::Create, - Gitlab::Ci::Pipeline::Chain::Limit::Activity].freeze + Gitlab::Ci::Pipeline::Chain::Limit::Activity,].freeze def execute(source, ignore_skip_ci: false, save_on_errors: true, trigger_request: nil, schedule: nil, merge_request: nil, **options, &block) @pipeline = Ci::Pipeline.new @@ -39,7 +39,8 @@ module Ci current_user: current_user, push_options: params[:push_options], chat_data: params[:chat_data], - **extra_options(options)) + **extra_options(options) + ) sequence = Gitlab::Ci::Pipeline::Chain::Sequence .new(pipeline, command, SEQUENCE) @@ -61,7 +62,7 @@ module Ci def execute!(*args, &block) execute(*args, &block).tap do |pipeline| unless pipeline.persisted? - raise CreateError, pipeline.errors.full_messages.join(',') + raise CreateError, pipeline.errors.full_messages.join(",") end end end diff --git a/app/services/ci/destroy_expired_job_artifacts_service.rb b/app/services/ci/destroy_expired_job_artifacts_service.rb index 7d2f5d33fed..1050a4a89dd 100644 --- a/app/services/ci/destroy_expired_job_artifacts_service.rb +++ b/app/services/ci/destroy_expired_job_artifacts_service.rb @@ -8,7 +8,7 @@ module Ci BATCH_SIZE = 100 LOOP_TIMEOUT = 45.minutes LOOP_LIMIT = 1000 - EXCLUSIVE_LOCK_KEY = 'expired_job_artifacts:destroy:lock' + EXCLUSIVE_LOCK_KEY = "expired_job_artifacts:destroy:lock" LOCK_TIMEOUT = 50.minutes ## diff --git a/app/services/ci/extract_sections_from_build_trace_service.rb b/app/services/ci/extract_sections_from_build_trace_service.rb index 97f9918fdb7..b8cefe1df04 100644 --- a/app/services/ci/extract_sections_from_build_trace_service.rb +++ b/app/services/ci/extract_sections_from_build_trace_service.rb @@ -27,7 +27,8 @@ module Ci attr.merge( build_id: build.id, project_id: project.id, - section_name_id: name_record.id) + section_name_id: name_record.id + ) end end end diff --git a/app/services/ci/pipeline_trigger_service.rb b/app/services/ci/pipeline_trigger_service.rb index 2dbb7c3917d..114fa3f84b2 100644 --- a/app/services/ci/pipeline_trigger_service.rb +++ b/app/services/ci/pipeline_trigger_service.rb @@ -19,10 +19,10 @@ module Ci return unless trigger.project == project pipeline = Ci::CreatePipelineService.new(project, trigger.owner, ref: params[:ref]) - .execute(:trigger, ignore_skip_ci: true) do |pipeline| + .execute(:trigger, ignore_skip_ci: true) { |pipeline| pipeline.trigger_requests.build(trigger: trigger) pipeline.variables.build(variables) - end + } if pipeline.persisted? success(pipeline: pipeline) @@ -47,7 +47,7 @@ module Ci def variables params[:variables].to_h.map do |key, value| - { key: key, value: value } + {key: key, value: value} end end end diff --git a/app/services/ci/process_build_service.rb b/app/services/ci/process_build_service.rb index d9f8e7cb452..6a437c3a6c2 100644 --- a/app/services/ci/process_build_service.rb +++ b/app/services/ci/process_build_service.rb @@ -27,15 +27,15 @@ module Ci def valid_statuses_for_when(value) case value - when 'on_success' + when "on_success" %w[success skipped] - when 'on_failure' + when "on_failure" %w[failed] - when 'always' + when "always" %w[success failed skipped] - when 'manual' + when "manual" %w[success skipped] - when 'delayed' + when "delayed" %w[success skipped] else [] diff --git a/app/services/ci/process_pipeline_service.rb b/app/services/ci/process_pipeline_service.rb index 4a7ce00b8e2..f17a8fa974c 100644 --- a/app/services/ci/process_pipeline_service.rb +++ b/app/services/ci/process_pipeline_service.rb @@ -10,9 +10,9 @@ module Ci update_retried new_builds = - stage_indexes_of_created_processables.map do |index| + stage_indexes_of_created_processables.map { |index| process_stage(index) - end + } @pipeline.update_status @@ -38,13 +38,13 @@ module Ci # rubocop: disable CodeReuse/ActiveRecord def status_for_prior_stages(index) - pipeline.builds.where('stage_idx < ?', index).latest.status || 'success' + pipeline.builds.where("stage_idx < ?", index).latest.status || "success" end # rubocop: enable CodeReuse/ActiveRecord # rubocop: disable CodeReuse/ActiveRecord def stage_indexes_of_created_processables - created_processables.order(:stage_idx).pluck('distinct stage_idx') + created_processables.order(:stage_idx).pluck("distinct stage_idx") end # rubocop: enable CodeReuse/ActiveRecord @@ -67,14 +67,16 @@ module Ci # find the latest builds for each name latest_statuses = pipeline.statuses.latest .group(:name) - .having('count(*) > 1') - .pluck('max(id)', 'name') + .having("count(*) > 1") + .pluck("max(id)", "name") # mark builds that are retried - pipeline.statuses.latest - .where(name: latest_statuses.map(&:second)) - .where.not(id: latest_statuses.map(&:first)) - .update_all(retried: true) if latest_statuses.any? + if latest_statuses.any? + pipeline.statuses.latest + .where(name: latest_statuses.map(&:second)) + .where.not(id: latest_statuses.map(&:first)) + .update_all(retried: true) + end end # rubocop: enable CodeReuse/ActiveRecord end diff --git a/app/services/ci/register_job_service.rb b/app/services/ci/register_job_service.rb index 6707a1363d0..09a6e9cf7ee 100644 --- a/app/services/ci/register_job_service.rb +++ b/app/services/ci/register_job_service.rb @@ -7,7 +7,7 @@ module Ci attr_reader :runner JOB_QUEUE_DURATION_SECONDS_BUCKETS = [1, 3, 10, 30].freeze - JOBS_RUNNING_FOR_PROJECT_MAX_BUCKET = 5.freeze + JOBS_RUNNING_FOR_PROJECT_MAX_BUCKET = 5 Result = Struct.new(:build, :valid?) @@ -95,21 +95,21 @@ module Ci def builds_for_shared_runner new_builds. # don't run projects which have not enabled shared runners and builds - joins(:project).where(projects: { shared_runners_enabled: true, pending_delete: false }) - .joins('LEFT JOIN project_features ON ci_builds.project_id = project_features.project_id') - .where('project_features.builds_access_level IS NULL or project_features.builds_access_level > 0'). - - # Implement fair scheduling - # this returns builds that are ordered by number of running builds - # we prefer projects that don't use shared runners at all - joins("LEFT JOIN (#{running_builds_for_shared_runners.to_sql}) AS project_builds ON ci_builds.project_id=project_builds.project_id") - .order('COALESCE(project_builds.running_builds, 0) ASC', 'ci_builds.id ASC') + joins(:project).where(projects: {shared_runners_enabled: true, pending_delete: false}) + .joins("LEFT JOIN project_features ON ci_builds.project_id = project_features.project_id") + .where("project_features.builds_access_level IS NULL or project_features.builds_access_level > 0"). + + # Implement fair scheduling + # this returns builds that are ordered by number of running builds + # we prefer projects that don't use shared runners at all + joins("LEFT JOIN (#{running_builds_for_shared_runners.to_sql}) AS project_builds ON ci_builds.project_id=project_builds.project_id") + .order("COALESCE(project_builds.running_builds, 0) ASC", "ci_builds.id ASC") end # rubocop: enable CodeReuse/ActiveRecord # rubocop: disable CodeReuse/ActiveRecord def builds_for_project_runner - new_builds.where(project: runner.projects.without_deleted.with_builds_enabled).order('id ASC') + new_builds.where(project: runner.projects.without_deleted.with_builds_enabled).order("id ASC") end # rubocop: enable CodeReuse/ActiveRecord @@ -123,14 +123,14 @@ module Ci .with_group_runners_enabled .with_builds_enabled .without_deleted - new_builds.where(project: projects).order('id ASC') + new_builds.where(project: projects).order("id ASC") end # rubocop: enable CodeReuse/ActiveRecord # rubocop: disable CodeReuse/ActiveRecord def running_builds_for_shared_runners Ci::Build.running.where(runner: Ci::Runner.instance_type) - .group(:project_id).select(:project_id, 'count(*) AS running_builds') + .group(:project_id).select(:project_id, "count(*) AS running_builds") end # rubocop: enable CodeReuse/ActiveRecord @@ -146,8 +146,8 @@ module Ci end def register_success(job) - labels = { shared_runner: runner.instance_type?, - jobs_running_for_project: jobs_running_for_project(job) } + labels = {shared_runner: runner.instance_type?, + jobs_running_for_project: jobs_running_for_project(job),} job_queue_duration_seconds.observe(labels, Time.now - job.queued_at) unless job.queued_at.nil? attempt_counter.increment @@ -155,11 +155,11 @@ module Ci # rubocop: disable CodeReuse/ActiveRecord def jobs_running_for_project(job) - return '+Inf' unless runner.instance_type? + return "+Inf" unless runner.instance_type? # excluding currently started job running_jobs_count = job.project.builds.running.where(runner: Ci::Runner.instance_type) - .limit(JOBS_RUNNING_FOR_PROJECT_MAX_BUCKET + 1).count - 1 + .limit(JOBS_RUNNING_FOR_PROJECT_MAX_BUCKET + 1).count - 1 running_jobs_count < JOBS_RUNNING_FOR_PROJECT_MAX_BUCKET ? running_jobs_count : "#{JOBS_RUNNING_FOR_PROJECT_MAX_BUCKET}+" end # rubocop: enable CodeReuse/ActiveRecord @@ -173,7 +173,7 @@ module Ci end def job_queue_duration_seconds - @job_queue_duration_seconds ||= Gitlab::Metrics.histogram(:job_queue_duration_seconds, 'Request handling execution time', {}, JOB_QUEUE_DURATION_SECONDS_BUCKETS) + @job_queue_duration_seconds ||= Gitlab::Metrics.histogram(:job_queue_duration_seconds, "Request handling execution time", {}, JOB_QUEUE_DURATION_SECONDS_BUCKETS) end end end diff --git a/app/services/ci/retry_build_service.rb b/app/services/ci/retry_build_service.rb index fab8a179843..cfb9def4b22 100644 --- a/app/services/ci/retry_build_service.rb +++ b/app/services/ci/retry_build_service.rb @@ -25,9 +25,9 @@ module Ci raise Gitlab::Access::AccessDeniedError end - attributes = CLONE_ACCESSORS.map do |attribute| + attributes = CLONE_ACCESSORS.map { |attribute| [attribute, build.public_send(attribute)] # rubocop:disable GitlabSecurity/PublicSend - end + } attributes.push([:user, current_user]) diff --git a/app/services/clusters/applications/base_helm_service.rb b/app/services/clusters/applications/base_helm_service.rb index 8a71730d5ec..f80d95567e2 100644 --- a/app/services/clusters/applications/base_helm_service.rb +++ b/app/services/clusters/applications/base_helm_service.rb @@ -19,7 +19,7 @@ module Clusters app_id: app.id, project_ids: app.cluster.project_ids, group_ids: app.cluster.group_ids, - message: error.message + message: error.message, } logger.error(meta) diff --git a/app/services/clusters/applications/check_installation_progress_service.rb b/app/services/clusters/applications/check_installation_progress_service.rb index c592d608b89..e2d0d28b145 100644 --- a/app/services/clusters/applications/check_installation_progress_service.rb +++ b/app/services/clusters/applications/check_installation_progress_service.rb @@ -43,7 +43,8 @@ module Clusters end else ClusterWaitForAppInstallationWorker.perform_in( - ClusterWaitForAppInstallationWorker::INTERVAL, app.name, app.id) + ClusterWaitForAppInstallationWorker::INTERVAL, app.name, app.id + ) end end diff --git a/app/services/clusters/applications/create_service.rb b/app/services/clusters/applications/create_service.rb index 12f8c849d41..1a08942288b 100644 --- a/app/services/clusters/applications/create_service.rb +++ b/app/services/clusters/applications/create_service.rb @@ -47,9 +47,9 @@ module Clusters def builders { - "helm" => -> (cluster) { cluster.application_helm || cluster.build_application_helm }, - "ingress" => -> (cluster) { cluster.application_ingress || cluster.build_application_ingress }, - "cert_manager" => -> (cluster) { cluster.application_cert_manager || cluster.build_application_cert_manager } + "helm" => ->(cluster) { cluster.application_helm || cluster.build_application_helm }, + "ingress" => ->(cluster) { cluster.application_ingress || cluster.build_application_ingress }, + "cert_manager" => ->(cluster) { cluster.application_cert_manager || cluster.build_application_cert_manager }, }.tap do |hash| hash.merge!(project_builders) if cluster.project_type? end @@ -59,10 +59,10 @@ module Clusters # with groups of projects def project_builders { - "prometheus" => -> (cluster) { cluster.application_prometheus || cluster.build_application_prometheus }, - "runner" => -> (cluster) { cluster.application_runner || cluster.build_application_runner }, - "jupyter" => -> (cluster) { cluster.application_jupyter || cluster.build_application_jupyter }, - "knative" => -> (cluster) { cluster.application_knative || cluster.build_application_knative } + "prometheus" => ->(cluster) { cluster.application_prometheus || cluster.build_application_prometheus }, + "runner" => ->(cluster) { cluster.application_runner || cluster.build_application_runner }, + "jupyter" => ->(cluster) { cluster.application_jupyter || cluster.build_application_jupyter }, + "knative" => ->(cluster) { cluster.application_knative || cluster.build_application_knative }, } end @@ -74,8 +74,8 @@ module Clusters oauth_application_params = { name: params[:application], redirect_uri: application.callback_url, - scopes: 'api read_user openid', - owner: current_user + scopes: "api read_user openid", + owner: current_user, } ::Applications::CreateService.new(current_user, oauth_application_params).execute(request) diff --git a/app/services/clusters/applications/install_service.rb b/app/services/clusters/applications/install_service.rb index 5a65dc4ef59..4d555a2e785 100644 --- a/app/services/clusters/applications/install_service.rb +++ b/app/services/clusters/applications/install_service.rb @@ -11,11 +11,12 @@ module Clusters helm_api.install(install_command) ClusterWaitForAppInstallationWorker.perform_in( - ClusterWaitForAppInstallationWorker::INTERVAL, app.name, app.id) + ClusterWaitForAppInstallationWorker::INTERVAL, app.name, app.id + ) rescue Kubeclient::HttpError => e log_error(e) app.make_errored!("Kubernetes error: #{e.error_code}") - rescue StandardError => e + rescue => e log_error(e) app.make_errored!("Can't start installation process.") end diff --git a/app/services/clusters/applications/upgrade_service.rb b/app/services/clusters/applications/upgrade_service.rb index a0ece1d2635..bdfe86f1451 100644 --- a/app/services/clusters/applications/upgrade_service.rb +++ b/app/services/clusters/applications/upgrade_service.rb @@ -14,11 +14,12 @@ module Clusters helm_api.update(install_command) ClusterWaitForAppInstallationWorker.perform_in( - ClusterWaitForAppInstallationWorker::INTERVAL, app.name, app.id) + ClusterWaitForAppInstallationWorker::INTERVAL, app.name, app.id + ) rescue Kubeclient::HttpError => e log_error(e) app.make_update_errored!("Kubernetes error: #{e.error_code}") - rescue StandardError => e + rescue => e log_error(e) app.make_update_errored!("Can't start upgrade process.") end diff --git a/app/services/clusters/build_service.rb b/app/services/clusters/build_service.rb index 8de73831164..94a5a368202 100644 --- a/app/services/clusters/build_service.rb +++ b/app/services/clusters/build_service.rb @@ -1,4 +1,5 @@ # frozen_string_literal: true + module Clusters class BuildService def initialize(subject) diff --git a/app/services/clusters/create_service.rb b/app/services/clusters/create_service.rb index 5a9da053780..c1142517a9c 100644 --- a/app/services/clusters/create_service.rb +++ b/app/services/clusters/create_service.rb @@ -9,8 +9,8 @@ module Clusters end def execute(access_token: nil) - raise ArgumentError, 'Unknown clusterable provided' unless clusterable - raise ArgumentError, _('Instance does not support multiple Kubernetes clusters') unless can_create_cluster? + raise ArgumentError, "Unknown clusterable provided" unless clusterable + raise ArgumentError, _("Instance does not support multiple Kubernetes clusters") unless can_create_cluster? cluster_params = params.merge(user: current_user).merge(clusterable_params) cluster_params[:provider_gcp_attributes].try do |provider| @@ -35,9 +35,9 @@ module Clusters def clusterable_params case clusterable when ::Project - { cluster_type: :project_type, projects: [clusterable] } + {cluster_type: :project_type, projects: [clusterable]} when ::Group - { cluster_type: :group_type, groups: [clusterable] } + {cluster_type: :group_type, groups: [clusterable]} else raise NotImplementedError end diff --git a/app/services/clusters/gcp/fetch_operation_service.rb b/app/services/clusters/gcp/fetch_operation_service.rb index 6c648b443a0..29f4d03dd5d 100644 --- a/app/services/clusters/gcp/fetch_operation_service.rb +++ b/app/services/clusters/gcp/fetch_operation_service.rb @@ -7,7 +7,8 @@ module Clusters operation = provider.api_client.projects_zones_operations( provider.gcp_project_id, provider.zone, - provider.operation_id) + provider.operation_id + ) yield(operation) if block_given? rescue Google::Apis::ServerError, Google::Apis::ClientError, Google::Apis::AuthorizationError => e diff --git a/app/services/clusters/gcp/finalize_creation_service.rb b/app/services/clusters/gcp/finalize_creation_service.rb index 5525c1b9b7f..f977b543218 100644 --- a/app/services/clusters/gcp/finalize_creation_service.rb +++ b/app/services/clusters/gcp/finalize_creation_service.rb @@ -14,16 +14,15 @@ module Clusters cluster.save! ClusterConfigureWorker.perform_async(cluster.id) - rescue Google::Apis::ServerError, Google::Apis::ClientError, Google::Apis::AuthorizationError => e log_service_error(e.class.name, provider.id, e.message) - provider.make_errored!(s_('ClusterIntegration|Failed to request to Google Cloud Platform: %{message}') % { message: e.message }) + provider.make_errored!(s_("ClusterIntegration|Failed to request to Google Cloud Platform: %{message}") % {message: e.message}) rescue Kubeclient::HttpError => e log_service_error(e.class.name, provider.id, e.message) - provider.make_errored!(s_('ClusterIntegration|Failed to run Kubeclient: %{message}') % { message: e.message }) + provider.make_errored!(s_("ClusterIntegration|Failed to run Kubeclient: %{message}") % {message: e.message}) rescue ActiveRecord::RecordInvalid => e log_service_error(e.class.name, provider.id, e.message) - provider.make_errored!(s_('ClusterIntegration|Failed to configure Google Kubernetes Engine Cluster: %{message}') % { message: e.message }) + provider.make_errored!(s_("ClusterIntegration|Failed to configure Google Kubernetes Engine Cluster: %{message}") % {message: e.message}) end private @@ -43,12 +42,13 @@ module Clusters def configure_kubernetes cluster.platform_type = :kubernetes cluster.build_platform_kubernetes( - api_url: 'https://' + gke_cluster.endpoint, + api_url: "https://" + gke_cluster.endpoint, ca_cert: Base64.decode64(gke_cluster.master_auth.cluster_ca_certificate), username: gke_cluster.master_auth.username, password: gke_cluster.master_auth.password, authorization_type: authorization_type, - token: request_kubernetes_token) + token: request_kubernetes_token + ) end def request_kubernetes_token @@ -60,7 +60,7 @@ module Clusters end def authorization_type - create_rbac_cluster? ? 'rbac' : 'abac' + create_rbac_cluster? ? "rbac" : "abac" end def create_rbac_cluster? @@ -69,7 +69,7 @@ module Clusters def kube_client @kube_client ||= build_kube_client!( - 'https://' + gke_cluster.endpoint, + "https://" + gke_cluster.endpoint, Base64.decode64(gke_cluster.master_auth.cluster_ca_certificate), gke_cluster.master_auth.username, gke_cluster.master_auth.password @@ -81,14 +81,14 @@ module Clusters Gitlab::Kubernetes::KubeClient.new( api_url, - auth_options: { username: username, password: password }, + auth_options: {username: username, password: password}, ssl_options: kubeclient_ssl_options(ca_pem), - http_proxy_uri: ENV['http_proxy'] + http_proxy_uri: ENV["http_proxy"] ) end def kubeclient_ssl_options(ca_pem) - 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 @@ -102,7 +102,8 @@ module Clusters @gke_cluster ||= provider.api_client.projects_zones_clusters_get( provider.gcp_project_id, provider.zone, - cluster.name) + cluster.name + ) end def cluster diff --git a/app/services/clusters/gcp/kubernetes.rb b/app/services/clusters/gcp/kubernetes.rb index 90ed529670c..40840c95788 100644 --- a/app/services/clusters/gcp/kubernetes.rb +++ b/app/services/clusters/gcp/kubernetes.rb @@ -3,12 +3,12 @@ module Clusters module Gcp module Kubernetes - GITLAB_SERVICE_ACCOUNT_NAME = 'gitlab' - GITLAB_SERVICE_ACCOUNT_NAMESPACE = 'default' - GITLAB_ADMIN_TOKEN_NAME = 'gitlab-token' - GITLAB_CLUSTER_ROLE_BINDING_NAME = 'gitlab-admin' - GITLAB_CLUSTER_ROLE_NAME = 'cluster-admin' - PROJECT_CLUSTER_ROLE_NAME = 'edit' + GITLAB_SERVICE_ACCOUNT_NAME = "gitlab" + GITLAB_SERVICE_ACCOUNT_NAMESPACE = "default" + GITLAB_ADMIN_TOKEN_NAME = "gitlab-token" + GITLAB_CLUSTER_ROLE_BINDING_NAME = "gitlab-admin" + GITLAB_CLUSTER_ROLE_NAME = "cluster-admin" + PROJECT_CLUSTER_ROLE_NAME = "edit" end end end diff --git a/app/services/clusters/gcp/kubernetes/create_or_update_service_account_service.rb b/app/services/clusters/gcp/kubernetes/create_or_update_service_account_service.rb index 49e766cbf13..1031c338b74 100644 --- a/app/services/clusters/gcp/kubernetes/create_or_update_service_account_service.rb +++ b/app/services/clusters/gcp/kubernetes/create_or_update_service_account_service.rb @@ -15,7 +15,7 @@ module Clusters end def self.gitlab_creator(kubeclient, rbac:) - self.new( + new( kubeclient, service_account_name: Clusters::Gcp::Kubernetes::GITLAB_SERVICE_ACCOUNT_NAME, service_account_namespace: Clusters::Gcp::Kubernetes::GITLAB_SERVICE_ACCOUNT_NAMESPACE, @@ -25,7 +25,7 @@ module Clusters end def self.namespace_creator(kubeclient, service_account_name:, service_account_namespace:, rbac:) - self.new( + new( kubeclient, service_account_name: service_account_name, service_account_namespace: service_account_namespace, @@ -79,7 +79,7 @@ module Clusters end def cluster_role_binding_resource - subjects = [{ kind: 'ServiceAccount', name: service_account_name, namespace: service_account_namespace }] + subjects = [{kind: "ServiceAccount", name: service_account_name, namespace: service_account_namespace}] Gitlab::Kubernetes::ClusterRoleBinding.new( Clusters::Gcp::Kubernetes::GITLAB_CLUSTER_ROLE_BINDING_NAME, diff --git a/app/services/clusters/gcp/kubernetes/fetch_kubernetes_token_service.rb b/app/services/clusters/gcp/kubernetes/fetch_kubernetes_token_service.rb index 4ad04ab801e..767e6abc594 100644 --- a/app/services/clusters/gcp/kubernetes/fetch_kubernetes_token_service.rb +++ b/app/services/clusters/gcp/kubernetes/fetch_kubernetes_token_service.rb @@ -13,7 +13,7 @@ module Clusters end def execute - token_base64 = get_secret&.dig('data', 'token') + token_base64 = get_secret&.dig("data", "token") Base64.decode64(token_base64) if token_base64 end diff --git a/app/services/clusters/gcp/provision_service.rb b/app/services/clusters/gcp/provision_service.rb index 80040511ec2..e907fa2f036 100644 --- a/app/services/clusters/gcp/provision_service.rb +++ b/app/services/clusters/gcp/provision_service.rb @@ -12,7 +12,8 @@ module Clusters if provider.make_creating(operation_id) WaitForClusterCreationWorker.perform_in( Clusters::Gcp::VerifyProvisionStatusService::INITIAL_INTERVAL, - provider.cluster_id) + provider.cluster_id + ) else provider.make_errored!("Failed to update provider record; #{provider.errors}") end @@ -31,18 +32,17 @@ module Clusters legacy_abac: provider.legacy_abac ) - unless operation.status == 'PENDING' || operation.status == 'RUNNING' + unless operation.status == "PENDING" || operation.status == "RUNNING" return provider.make_errored!("Operation status is unexpected; #{operation.status_message}") end operation_id = provider.api_client.parse_operation_id(operation.self_link) unless operation_id - return provider.make_errored!('Can not find operation_id from self_link') + return provider.make_errored!("Can not find operation_id from self_link") end yield(operation_id) - rescue Google::Apis::ServerError, Google::Apis::ClientError, Google::Apis::AuthorizationError => e provider.make_errored!("Failed to request to CloudPlatform; #{e.message}") end diff --git a/app/services/clusters/gcp/verify_provision_status_service.rb b/app/services/clusters/gcp/verify_provision_status_service.rb index b24246f5c4b..edb478e3de2 100644 --- a/app/services/clusters/gcp/verify_provision_status_service.rb +++ b/app/services/clusters/gcp/verify_provision_status_service.rb @@ -14,9 +14,9 @@ module Clusters request_operation do |operation| case operation.status - when 'PENDING', 'RUNNING' + when "PENDING", "RUNNING" continue_creation(operation) - when 'DONE' + when "DONE" finalize_creation else provider.make_errored!("Unexpected operation status; #{operation.status} #{operation.status_message}") @@ -30,7 +30,7 @@ module Clusters if elapsed_time_from_creation(operation) < TIMEOUT WaitForClusterCreationWorker.perform_in(EAGER_INTERVAL, provider.cluster_id) else - provider.make_errored!(_('Kubernetes cluster creation time exceeds timeout; %{timeout}') % { timeout: TIMEOUT }) + provider.make_errored!(_("Kubernetes cluster creation time exceeds timeout; %{timeout}") % {timeout: TIMEOUT}) end end diff --git a/app/services/cohorts_service.rb b/app/services/cohorts_service.rb index 6d466c2fc9c..08970fc9fe9 100644 --- a/app/services/cohorts_service.rb +++ b/app/services/cohorts_service.rb @@ -6,7 +6,7 @@ class CohortsService def execute { months_included: MONTHS_INCLUDED, - cohorts: cohorts + cohorts: cohorts, } end @@ -40,7 +40,7 @@ class CohortsService registration_month: registration_month, activity_months: activity_months, total: activity_months.first[:total], - inactive: inactive + inactive: inactive, } end end @@ -63,7 +63,7 @@ class CohortsService overall_total = month_totals.first month_totals.map do |total| - { total: total, percentage: total.zero? ? 0 : 100 * total / overall_total } + {total: total, percentage: total.zero? ? 0 : 100 * total / overall_total} end end @@ -82,11 +82,11 @@ class CohortsService def counts_by_month @counts_by_month ||= begin - created_at_month = column_to_date('created_at') - last_activity_on_month = column_to_date('last_activity_on') + created_at_month = column_to_date("created_at") + last_activity_on_month = column_to_date("last_activity_on") User - .where('created_at > ?', MONTHS_INCLUDED.months.ago.end_of_month) + .where("created_at > ?", MONTHS_INCLUDED.months.ago.end_of_month) .group(created_at_month, last_activity_on_month) .reorder("#{created_at_month} ASC", "#{last_activity_on_month} ASC") .count diff --git a/app/services/commits/change_service.rb b/app/services/commits/change_service.rb index fbf71f02837..92b36ff871b 100644 --- a/app/services/commits/change_service.rb +++ b/app/services/commits/change_service.rb @@ -22,7 +22,8 @@ module Commits @branch_name, message, start_project: @start_project, - start_branch_name: @start_branch) + start_branch_name: @start_branch + ) rescue Gitlab::Git::Repository::CreateTreeError act = action.to_s.dasherize type = @commit.change_type_title(current_user) diff --git a/app/services/commits/commit_patch_service.rb b/app/services/commits/commit_patch_service.rb index 49113c3c691..f3348068131 100644 --- a/app/services/commits/commit_patch_service.rb +++ b/app/services/commits/commit_patch_service.rb @@ -33,7 +33,7 @@ module Commits def prepare_branch! branch_result = CreateBranchService.new(project, current_user) - .execute(@branch_name, @start_branch) + .execute(@branch_name, @start_branch) if branch_result[:status] != :success raise ChangeError, branch_result[:message] diff --git a/app/services/commits/create_service.rb b/app/services/commits/create_service.rb index a3b87c20761..bc9ca8b38f8 100644 --- a/app/services/commits/create_service.rb +++ b/app/services/commits/create_service.rb @@ -60,7 +60,7 @@ module Commits def validate_on_branch! if !@start_project.empty_repo? && !@start_project.repository.branch_exists?(@start_branch) - raise_error('You can only create or edit files when you are on a branch') + raise_error("You can only create or edit files when you are on a branch") end end diff --git a/app/services/commits/tag_service.rb b/app/services/commits/tag_service.rb index bb8cfb63f98..99eda486d53 100644 --- a/app/services/commits/tag_service.rb +++ b/app/services/commits/tag_service.rb @@ -4,7 +4,7 @@ module Commits class TagService < BaseService def execute(commit) unless params[:tag_name] - return error('Missing parameter tag_name') + return error("Missing parameter tag_name") end tag_name = params[:tag_name] diff --git a/app/services/compare_service.rb b/app/services/compare_service.rb index 3adf8a0c1a1..ef782e248c4 100644 --- a/app/services/compare_service.rb +++ b/app/services/compare_service.rb @@ -1,6 +1,6 @@ # frozen_string_literal: true -require 'securerandom' +require "securerandom" # Compare 2 refs for one repo or between repositories # and return Gitlab::Git::Compare object that responds to commits and diffs @@ -18,8 +18,8 @@ class CompareService return unless raw_compare Compare.new(raw_compare, - target_project, - base_sha: base_sha, - straight: straight) + target_project, + base_sha: base_sha, + straight: straight) end end diff --git a/app/services/concerns/exclusive_lease_guard.rb b/app/services/concerns/exclusive_lease_guard.rb index 2cb73555d85..03a5186741d 100644 --- a/app/services/concerns/exclusive_lease_guard.rb +++ b/app/services/concerns/exclusive_lease_guard.rb @@ -21,7 +21,7 @@ module ExclusiveLeaseGuard lease = exclusive_lease.try_obtain unless lease - log_error('Cannot obtain an exclusive lease. There must be another instance already in execution.') + log_error("Cannot obtain an exclusive lease. There must be another instance already in execution.") return end diff --git a/app/services/concerns/issues/resolve_discussions.rb b/app/services/concerns/issues/resolve_discussions.rb index f0e9862ca30..2aaf52a8a0d 100644 --- a/app/services/concerns/issues/resolve_discussions.rb +++ b/app/services/concerns/issues/resolve_discussions.rb @@ -28,7 +28,7 @@ module Issues @discussions_to_resolve ||= # rubocop:disable Gitlab/ModuleWithInstanceVariables if discussion_to_resolve_id discussion_or_nil = merge_request_to_resolve_discussions_of - .find_discussion(discussion_to_resolve_id) + .find_discussion(discussion_to_resolve_id) Array(discussion_or_nil) else merge_request_to_resolve_discussions_of diff --git a/app/services/concerns/users/participable_service.rb b/app/services/concerns/users/participable_service.rb index 6713b6617ae..2565bdc8097 100644 --- a/app/services/concerns/users/participable_service.rb +++ b/app/services/concerns/users/participable_service.rb @@ -36,11 +36,11 @@ module Users private def user_as_hash(user) - { type: user.class.name, username: user.username, name: user.name, avatar_url: user.avatar_url } + {type: user.class.name, username: user.username, name: user.name, avatar_url: user.avatar_url} end def group_as_hash(group) - { type: group.class.name, username: group.full_path, name: group.full_name, avatar_url: group.avatar_url, count: group.users.count } + {type: group.class.name, username: group.full_path, name: group.full_name, avatar_url: group.avatar_url, count: group.users.count} end end end diff --git a/app/services/create_branch_service.rb b/app/services/create_branch_service.rb index 110e589e30d..196c38ad9b6 100644 --- a/app/services/create_branch_service.rb +++ b/app/services/create_branch_service.rb @@ -14,7 +14,7 @@ class CreateBranchService < BaseService if new_branch success(new_branch) else - error('Invalid reference name') + error("Invalid reference name") end rescue Gitlab::Git::PreReceiveError => ex error(ex.message) @@ -29,10 +29,10 @@ class CreateBranchService < BaseService def create_master_branch project.repository.create_file( current_user, - '/README.md', - '', - message: 'Add README.md', - branch_name: 'master' + "/README.md", + "", + message: "Add README.md", + branch_name: "master" ) end end diff --git a/app/services/create_snippet_service.rb b/app/services/create_snippet_service.rb index 6f1fce4989e..bc1164de096 100644 --- a/app/services/create_snippet_service.rb +++ b/app/services/create_snippet_service.rb @@ -7,10 +7,10 @@ class CreateSnippetService < BaseService filter_spam_check_params snippet = if project - project.snippets.build(params) - else - PersonalSnippet.new(params) - end + project.snippets.build(params) + else + PersonalSnippet.new(params) + end unless Gitlab::VisibilityLevel.allowed_for?(current_user, params[:visibility_level]) deny_visibility_level(snippet) diff --git a/app/services/delete_branch_service.rb b/app/services/delete_branch_service.rb index 8322a3d74f4..427cc6be72e 100644 --- a/app/services/delete_branch_service.rb +++ b/app/services/delete_branch_service.rb @@ -6,17 +6,17 @@ class DeleteBranchService < BaseService branch = repository.find_branch(branch_name) unless current_user.can?(:push_code, project) - return error('You dont have push access to repo', 405) + return error("You dont have push access to repo", 405) end unless branch - return error('No such branch', 404) + return error("No such branch", 404) end if repository.rm_branch(current_user, branch_name) - success('Branch was deleted') + success("Branch was deleted") else - error('Failed to remove branch') + error("Failed to remove branch") end rescue Gitlab::Git::PreReceiveError => ex error(ex.message) @@ -37,6 +37,7 @@ class DeleteBranchService < BaseService branch.dereferenced_target.sha, Gitlab::Git::BLANK_SHA, "#{Gitlab::Git::BRANCH_REF_PREFIX}#{branch.name}", - []) + [] + ) end end diff --git a/app/services/emails/destroy_service.rb b/app/services/emails/destroy_service.rb index 9ca1a03e172..a7828a94fd8 100644 --- a/app/services/emails/destroy_service.rb +++ b/app/services/emails/destroy_service.rb @@ -9,11 +9,11 @@ module Emails private def update_secondary_emails! - result = ::Users::UpdateService.new(@current_user, user: @user).execute do |user| + result = ::Users::UpdateService.new(@current_user, user: @user).execute { |user| user.update_secondary_emails! - end + } - result[:status] == 'success' + result[:status] == "success" end end end diff --git a/app/services/error_tracking/list_issues_service.rb b/app/services/error_tracking/list_issues_service.rb index a6c6bec9598..2f8e456b546 100644 --- a/app/services/error_tracking/list_issues_service.rb +++ b/app/services/error_tracking/list_issues_service.rb @@ -2,19 +2,19 @@ module ErrorTracking class ListIssuesService < ::BaseService - DEFAULT_ISSUE_STATUS = 'unresolved' + DEFAULT_ISSUE_STATUS = "unresolved" DEFAULT_LIMIT = 20 def execute - return error('Error Tracking is not enabled') unless enabled? - return error('Access denied', :unauthorized) unless can_read? + return error("Error Tracking is not enabled") unless enabled? + return error("Access denied", :unauthorized) unless can_read? result = project_error_tracking_setting .list_sentry_issues(issue_status: issue_status, limit: limit) # our results are not yet ready unless result - return error('Not ready. Try again later', :no_content) + return error("Not ready. Try again later", :no_content) end if result[:error].present? diff --git a/app/services/error_tracking/list_projects_service.rb b/app/services/error_tracking/list_projects_service.rb index c6e8be0f2be..2cdc74bf8f2 100644 --- a/app/services/error_tracking/list_projects_service.rb +++ b/app/services/error_tracking/list_projects_service.rb @@ -3,12 +3,12 @@ module ErrorTracking class ListProjectsService < ::BaseService def execute - return error('access denied') unless can_read? + return error("access denied") unless can_read? setting = project_error_tracking_setting unless setting.valid? - return error(setting.errors.full_messages.join(', '), :bad_request) + return error(setting.errors.full_messages.join(", "), :bad_request) end begin diff --git a/app/services/event_create_service.rb b/app/services/event_create_service.rb index e7464fd9d5f..4815887b55c 100644 --- a/app/services/event_create_service.rb +++ b/app/services/event_create_service.rb @@ -89,7 +89,7 @@ class EventCreateService Users::LastPushEventService.new(current_user) .cache_last_push_event(event) - Users::ActivityService.new(current_user, 'push').execute + Users::ActivityService.new(current_user, "push").execute end private diff --git a/app/services/events/render_service.rb b/app/services/events/render_service.rb index 50429683902..8adbdc7913c 100644 --- a/app/services/events/render_service.rb +++ b/app/services/events/render_service.rb @@ -19,7 +19,7 @@ module Events def render_options(atom_request) return {} unless atom_request - { only_path: false, xhtml: true } + {only_path: false, xhtml: true} end end end diff --git a/app/services/files/base_service.rb b/app/services/files/base_service.rb index 39e614d6569..a129617cc68 100644 --- a/app/services/files/base_service.rb +++ b/app/services/files/base_service.rb @@ -18,7 +18,7 @@ module Files @previous_path = params[:previous_path] @file_content = params[:file_content] - @file_content = Base64.decode64(@file_content) if params[:file_content_encoding] == 'base64' + @file_content = Base64.decode64(@file_content) if params[:file_content_encoding] == "base64" end def file_has_changed?(path, commit_id) diff --git a/app/services/files/create_dir_service.rb b/app/services/files/create_dir_service.rb index 362b80071ba..a32d9af3a2d 100644 --- a/app/services/files/create_dir_service.rb +++ b/app/services/files/create_dir_service.rb @@ -11,7 +11,8 @@ module Files author_email: @author_email, author_name: @author_name, start_project: @start_project, - start_branch_name: @start_branch) + start_branch_name: @start_branch + ) end end end diff --git a/app/services/files/create_service.rb b/app/services/files/create_service.rb index fd5442a6c28..a5d61c94731 100644 --- a/app/services/files/create_service.rb +++ b/app/services/files/create_service.rb @@ -22,7 +22,8 @@ module Files author_email: @author_email, author_name: @author_name, start_project: @start_project, - start_branch_name: @start_branch) + start_branch_name: @start_branch + ) end end end diff --git a/app/services/files/delete_service.rb b/app/services/files/delete_service.rb index 0ec1f79d396..416e206bab8 100644 --- a/app/services/files/delete_service.rb +++ b/app/services/files/delete_service.rb @@ -11,7 +11,8 @@ module Files author_email: @author_email, author_name: @author_name, start_project: @start_project, - start_branch_name: @start_branch) + start_branch_name: @start_branch + ) end private diff --git a/app/services/files/multi_service.rb b/app/services/files/multi_service.rb index 927634c2159..6fcf0fe2d4a 100644 --- a/app/services/files/multi_service.rb +++ b/app/services/files/multi_service.rb @@ -2,7 +2,7 @@ module Files class MultiService < Files::BaseService - UPDATE_FILE_ACTIONS = %w(update move delete chmod).freeze + UPDATE_FILE_ACTIONS = %w[update move delete chmod].freeze def create_commit! transformer = Lfs::FileTransformer.new(project, @branch_name) @@ -17,7 +17,7 @@ module Files def actions_after_lfs_transformation(transformer, actions) actions.map do |action| - if action[:action] == 'create' + if action[:action] == "create" result = transformer.new_file(action[:file_path], action[:content], encoding: action[:encoding]) action[:content] = result.content action[:encoding] = result.encoding diff --git a/app/services/files/update_service.rb b/app/services/files/update_service.rb index 2b3e96e6c53..a4bec851b0a 100644 --- a/app/services/files/update_service.rb +++ b/app/services/files/update_service.rb @@ -4,13 +4,13 @@ module Files class UpdateService < Files::BaseService def create_commit! repository.update_file(current_user, @file_path, @file_content, - message: @commit_message, - branch_name: @branch_name, - previous_path: @previous_path, - author_email: @author_email, - author_name: @author_name, - start_project: @start_project, - start_branch_name: @start_branch) + message: @commit_message, + branch_name: @branch_name, + previous_path: @previous_path, + author_email: @author_email, + author_name: @author_name, + start_project: @start_project, + start_branch_name: @start_branch) end private diff --git a/app/services/git_push_service.rb b/app/services/git_push_service.rb index f387c749a21..ca5ff51debc 100644 --- a/app/services/git_push_service.rb +++ b/app/services/git_push_service.rb @@ -175,7 +175,8 @@ class GitPushService < BaseService params[:ref], @push_commits, commits_count: commits_count, - push_options: params[:push_options] || []) + push_options: params[:push_options] || [] + ) end def push_to_existing_branch? diff --git a/app/services/git_tag_push_service.rb b/app/services/git_tag_push_service.rb index e39b3603c6c..8816f6a2e7c 100644 --- a/app/services/git_tag_push_service.rb +++ b/app/services/git_tag_push_service.rb @@ -46,7 +46,8 @@ class GitTagPushService < BaseService params[:ref], commits, message, - push_options: params[:push_options] || []) + push_options: params[:push_options] || [] + ) end def build_system_push_data @@ -57,7 +58,8 @@ class GitTagPushService < BaseService params[:newrev], params[:ref], [], - '') + "" + ) end def pipeline_options diff --git a/app/services/gravatar_service.rb b/app/services/gravatar_service.rb index 2a7a5dae291..69aec82e202 100644 --- a/app/services/gravatar_service.rb +++ b/app/services/gravatar_service.rb @@ -13,8 +13,8 @@ class GravatarService sprintf gravatar_url, hash: hash, size: size * scale, - email: ERB::Util.url_encode(email&.strip || ''), - username: ERB::Util.url_encode(username&.strip || '') + email: ERB::Util.url_encode(email&.strip || ""), + username: ERB::Util.url_encode(username&.strip || "") end def gitlab_config diff --git a/app/services/groups/create_service.rb b/app/services/groups/create_service.rb index 99ead467f74..a3106979586 100644 --- a/app/services/groups/create_service.rb +++ b/app/services/groups/create_service.rb @@ -22,7 +22,7 @@ module Groups response = Mattermost::CreateTeamService.new(@group, current_user).execute return @group if @group.errors.any? - @group.build_chat_team(name: response['name'], team_id: response['id']) + @group.build_chat_team(name: response["name"], team_id: response["id"]) end @group.save @@ -44,13 +44,13 @@ module Groups if @group.subgroup? unless can?(current_user, :create_subgroup, @group.parent) @group.parent = nil - @group.errors.add(:parent_id, 'You don’t have permission to create a subgroup in this group.') + @group.errors.add(:parent_id, "You don’t have permission to create a subgroup in this group.") return false end else unless can?(current_user, :create_group) - @group.errors.add(:base, 'You don’t have permission to create groups.') + @group.errors.add(:base, "You don’t have permission to create groups.") return false end diff --git a/app/services/groups/nested_create_service.rb b/app/services/groups/nested_create_service.rb index f01f5656296..8432029c6ce 100644 --- a/app/services/groups/nested_create_service.rb +++ b/app/services/groups/nested_create_service.rb @@ -18,8 +18,8 @@ module Groups return namespace end - if group_path.include?('/') && !Group.supports_nested_objects? - raise 'Nested groups are not supported on MySQL' + if group_path.include?("/") && !Group.supports_nested_objects? + raise "Nested groups are not supported on MySQL" end create_group_path @@ -28,13 +28,13 @@ module Groups private def create_group_path - group_path_segments = group_path.split('/') + group_path_segments = group_path.split("/") last_group = nil partial_path_segments = [] while subgroup_name = group_path_segments.shift partial_path_segments << subgroup_name - partial_path = partial_path_segments.join('/') + partial_path = partial_path_segments.join("/") new_params = params.reverse_merge( path: subgroup_name, diff --git a/app/services/groups/transfer_service.rb b/app/services/groups/transfer_service.rb index f64e327416a..520cacb44be 100644 --- a/app/services/groups/transfer_service.rb +++ b/app/services/groups/transfer_service.rb @@ -3,11 +3,11 @@ module Groups class TransferService < Groups::BaseService ERROR_MESSAGES = { - database_not_supported: 'Database is not supported.', - namespace_with_same_path: 'The parent group already has a subgroup with the same path.', - group_is_already_root: 'Group is already a root group.', - same_parent_as_current: 'Group is already associated to the parent group.', - invalid_policies: "You don't have enough permissions." + database_not_supported: "Database is not supported.", + namespace_with_same_path: "The parent group already has a subgroup with the same path.", + group_is_already_root: "Group is already a root group.", + same_parent_as_current: "Group is already associated to the parent group.", + invalid_policies: "You don't have enough permissions.", }.freeze TransferError = Class.new(StandardError) @@ -23,7 +23,6 @@ module Groups @new_parent_group = new_parent_group ensure_allowed_transfer proceed_to_transfer - rescue TransferError, ActiveRecord::RecordInvalid, Gitlab::UpdatePathError => e @group.errors.clear @error = "Transfer failed: " + e.message diff --git a/app/services/import/base_service.rb b/app/services/import/base_service.rb index 2683c75e41f..1052f005c6a 100644 --- a/app/services/import/base_service.rb +++ b/app/services/import/base_service.rb @@ -25,7 +25,7 @@ module Import end def project_save_error(project) - project.errors.full_messages.join(', ') + project.errors.full_messages.join(", ") end def success(project) diff --git a/app/services/import/github_service.rb b/app/services/import/github_service.rb index a2533683da9..6ac490b4390 100644 --- a/app/services/import/github_service.rb +++ b/app/services/import/github_service.rb @@ -7,12 +7,12 @@ module Import def execute(access_params, provider) unless authorized? - return error('This namespace has already been taken! Please choose another one.', :unprocessable_entity) + return error("This namespace has already been taken! Please choose another one.", :unprocessable_entity) end project = Gitlab::LegacyGithubImport::ProjectCreator - .new(repo, project_name, target_namespace, current_user, access_params, type: provider) - .execute(extra_project_attrs) + .new(repo, project_name, target_namespace, current_user, access_params, type: provider) + .execute(extra_project_attrs) if project.persisted? success(project) diff --git a/app/services/import_export_clean_up_service.rb b/app/services/import_export_clean_up_service.rb index 3ecb51b60d0..3b33bf4ad47 100644 --- a/app/services/import_export_clean_up_service.rb +++ b/app/services/import_export_clean_up_service.rb @@ -23,12 +23,12 @@ class ImportExportCleanUpService private def clean_up_export_files - Gitlab::Popen.popen(%W(find #{path} -not -path #{path} -mmin +#{mmin} -delete)) + Gitlab::Popen.popen(%W[find #{path} -not -path #{path} -mmin +#{mmin} -delete]) end # rubocop: disable CodeReuse/ActiveRecord def clean_up_export_object_files - ImportExportUpload.where('updated_at < ?', mmin.minutes.ago).each do |upload| + ImportExportUpload.where("updated_at < ?", mmin.minutes.ago).each do |upload| upload.remove_export_file! upload.save! end diff --git a/app/services/issuable/bulk_update_service.rb b/app/services/issuable/bulk_update_service.rb index c4beddf2294..618aa12c688 100644 --- a/app/services/issuable/bulk_update_service.rb +++ b/app/services/issuable/bulk_update_service.rb @@ -25,8 +25,8 @@ module Issuable end { - count: items.count, - success: !items.count.zero? + count: items.count, + success: !items.count.zero?, } end # rubocop: enable CodeReuse/ActiveRecord @@ -34,9 +34,9 @@ module Issuable private def permitted_attrs(type) - attrs = %i(state_event milestone_id assignee_id assignee_ids add_label_ids remove_label_ids subscription_event) + attrs = %i[state_event milestone_id assignee_id assignee_ids add_label_ids remove_label_ids subscription_event] - if type == 'issue' + if type == "issue" attrs.push(:assignee_ids) else attrs.push(:assignee_id) diff --git a/app/services/issuable/clone/attributes_rewriter.rb b/app/services/issuable/clone/attributes_rewriter.rb index 0300cc0d8d3..4dfd118b843 100644 --- a/app/services/issuable/clone/attributes_rewriter.rb +++ b/app/services/issuable/clone/attributes_rewriter.rb @@ -20,7 +20,7 @@ module Issuable title = original_entity.milestone&.title return unless title - params = { title: title, project_ids: new_entity.project&.id, group_ids: group&.id } + params = {title: title, project_ids: new_entity.project&.id, group_ids: group&.id} milestones = MilestonesFinder.new(params).execute milestones.first @@ -31,7 +31,7 @@ module Issuable project_id: new_entity.project&.id, group_id: group&.id, title: original_entity.labels.select(:title), - include_ancestor_groups: true + include_ancestor_groups: true, } params[:only_group_labels] = true if new_parent.is_a?(Group) @@ -41,21 +41,21 @@ module Issuable def copy_resource_label_events original_entity.resource_label_events.find_in_batches do |batch| - events = batch.map do |event| - entity_key = new_entity.is_a?(Issue) ? 'issue_id' : 'epic_id' + events = batch.map { |event| + entity_key = new_entity.is_a?(Issue) ? "issue_id" : "epic_id" # rubocop: disable CodeReuse/ActiveRecord event.attributes - .except('id', 'reference', 'reference_html') - .merge(entity_key => new_entity.id, 'action' => ResourceLabelEvent.actions[event.action]) + .except("id", "reference", "reference_html") + .merge(entity_key => new_entity.id, "action" => ResourceLabelEvent.actions[event.action]) # rubocop: enable CodeReuse/ActiveRecord - end + } Gitlab::Database.bulk_insert(ResourceLabelEvent.table_name, events) end end def entity_key - new_entity.class.name.parameterize('_').foreign_key + new_entity.class.name.parameterize("_").foreign_key end end end diff --git a/app/services/issuable/clone/base_service.rb b/app/services/issuable/clone/base_service.rb index 42dd9c666f5..76550e014cc 100644 --- a/app/services/issuable/clone/base_service.rb +++ b/app/services/issuable/clone/base_service.rb @@ -5,7 +5,7 @@ module Issuable class BaseService < IssuableBaseService attr_reader :original_entity, :new_entity - alias_method :old_project, :project + alias old_project project def execute(original_entity, new_project = nil) @original_entity = original_entity @@ -47,7 +47,7 @@ module Issuable end def new_parent - new_entity.project ? new_entity.project : new_entity.group + new_entity.project || new_entity.group end def group diff --git a/app/services/issuable/clone/content_rewriter.rb b/app/services/issuable/clone/content_rewriter.rb index e1e0b75085d..46fdd3ba680 100644 --- a/app/services/issuable/clone/content_rewriter.rb +++ b/app/services/issuable/clone/content_rewriter.rb @@ -29,7 +29,7 @@ module Issuable project: new_entity.project, noteable: new_entity, note: rewrite_content(new_note.note), created_at: note.created_at, - updated_at: note.updated_at + updated_at: note.updated_at, } if note.system_note_metadata diff --git a/app/services/issuable/common_system_notes_service.rb b/app/services/issuable/common_system_notes_service.rb index 77f38f8882e..5feed68b3dd 100644 --- a/app/services/issuable/common_system_notes_service.rb +++ b/app/services/issuable/common_system_notes_service.rb @@ -8,25 +8,25 @@ module Issuable @issuable = issuable if is_update - if issuable.previous_changes.include?('title') - create_title_change_note(issuable.previous_changes['title'].first) + if issuable.previous_changes.include?("title") + create_title_change_note(issuable.previous_changes["title"].first) end handle_description_change_note handle_time_tracking_note if issuable.is_a?(TimeTrackable) - create_discussion_lock_note if issuable.previous_changes.include?('discussion_locked') + create_discussion_lock_note if issuable.previous_changes.include?("discussion_locked") end - create_due_date_note if issuable.previous_changes.include?('due_date') - create_milestone_note if issuable.previous_changes.include?('milestone_id') + create_due_date_note if issuable.previous_changes.include?("due_date") + create_milestone_note if issuable.previous_changes.include?("milestone_id") create_labels_note(old_labels) if old_labels && issuable.labels != old_labels end private def handle_time_tracking_note - if issuable.previous_changes.include?('time_estimate') + if issuable.previous_changes.include?("time_estimate") create_time_estimate_note end @@ -36,7 +36,7 @@ module Issuable end def handle_description_change_note - if issuable.previous_changes.include?('description') + if issuable.previous_changes.include?("description") if issuable.tasks? && issuable.updated_tasks.any? create_task_status_note else diff --git a/app/services/issuable_base_service.rb b/app/services/issuable_base_service.rb index ef991eaf234..2e29f449553 100644 --- a/app/services/issuable_base_service.rb +++ b/app/services/issuable_base_service.rb @@ -60,13 +60,13 @@ class IssuableBaseService < BaseService milestone_id = params[:milestone_id] return unless milestone_id - params[:milestone_id] = '' if milestone_id == IssuableFinder::NONE + params[:milestone_id] = "" if milestone_id == IssuableFinder::NONE groups = project.group&.self_and_ancestors&.select(:id) milestone = Milestone.for_projects_and_groups([project.id], groups).find_by_id(milestone_id) - params[:milestone_id] = '' unless milestone + params[:milestone_id] = "" unless milestone end def filter_labels @@ -89,7 +89,7 @@ class IssuableBaseService < BaseService return unless labels - params[:label_ids] = labels.split(",").map do |label_name| + params[:label_ids] = labels.split(",").map { |label_name| label = Labels::FindOrCreateService.new( current_user, parent, @@ -98,7 +98,7 @@ class IssuableBaseService < BaseService ).execute label.try(:id) - end.compact + }.compact end def process_label_ids(attributes, existing_label_ids: nil) @@ -224,7 +224,7 @@ class IssuableBaseService < BaseService issuable.create_new_cross_references!(current_user) execute_hooks( issuable, - 'update', + "update", old_associations: old_associations ) @@ -254,7 +254,7 @@ class IssuableBaseService < BaseService handle_task_changes(issuable) invalidate_cache_counts(issuable, users: issuable.assignees.to_a) after_update(issuable) - execute_hooks(issuable, 'update', old_associations: nil) + execute_hooks(issuable, "update", old_associations: nil) end end @@ -268,9 +268,9 @@ class IssuableBaseService < BaseService return unless update_task_params tasklist_toggler = TaskListToggleService.new(issuable.description, issuable.description_html, - line_source: update_task_params[:line_source], - line_number: update_task_params[:line_number].to_i, - toggle_as_checked: update_task_params[:checked]) + line_source: update_task_params[:line_source], + line_number: update_task_params[:line_number].to_i, + toggle_as_checked: update_task_params[:checked]) unless tasklist_toggler.execute # if we make it here, the data is much newer than we thought it was - fail fast @@ -300,18 +300,18 @@ class IssuableBaseService < BaseService def change_state(issuable) case params.delete(:state_event) - when 'reopen' + when "reopen" reopen_service.new(project, current_user, {}).execute(issuable) - when 'close' + when "close" close_service.new(project, current_user, {}).execute(issuable) end end def change_subscription(issuable) case params.delete(:subscription_event) - when 'subscribe' + when "subscribe" issuable.subscribe(current_user, project) - when 'unsubscribe' + when "unsubscribe" issuable.unsubscribe(current_user, project) end end @@ -319,9 +319,9 @@ class IssuableBaseService < BaseService # rubocop: disable CodeReuse/ActiveRecord def change_todo(issuable) case params.delete(:todo_event) - when 'add' + when "add" todo_service.mark_todo(issuable, current_user) - when 'done' + when "done" todo = TodosFinder.new(current_user).find_by(target: issuable) todo_service.mark_todos_as_done_by_ids(todo, current_user) if todo end @@ -341,7 +341,7 @@ class IssuableBaseService < BaseService { labels: issuable.labels.to_a, mentioned_users: issuable.mentioned_users.to_a, - assignees: issuable.assignees.to_a + assignees: issuable.assignees.to_a, } associations[:total_time_spent] = issuable.total_time_spent if issuable.respond_to?(:total_time_spent) @@ -351,9 +351,9 @@ class IssuableBaseService < BaseService def has_changes?(issuable, old_labels: [], old_assignees: []) valid_attrs = [:title, :description, :assignee_id, :milestone_id, :target_branch] - attrs_changed = valid_attrs.any? do |attr| + attrs_changed = valid_attrs.any? { |attr| issuable.previous_changes.include?(attr.to_s) - end + } labels_changed = issuable.labels != old_labels @@ -377,7 +377,7 @@ class IssuableBaseService < BaseService end # override if needed - def execute_hooks(issuable, action = 'open', params = {}) + def execute_hooks(issuable, action = "open", params = {}) end def update_project_counter_caches?(issuable) diff --git a/app/services/issues/base_service.rb b/app/services/issues/base_service.rb index ef08adf4f92..54db0d08b74 100644 --- a/app/services/issues/base_service.rb +++ b/app/services/issues/base_service.rb @@ -21,10 +21,11 @@ module Issues def create_assignee_note(issue, old_assignees) SystemNoteService.change_issue_assignees( - issue, issue.project, current_user, old_assignees) + issue, issue.project, current_user, old_assignees + ) end - def execute_hooks(issue, action = 'open', old_associations: {}) + def execute_hooks(issue, action = "open", old_associations: {}) issue_data = hook_data(issue, action, old_associations: old_associations) hooks_scope = issue.confidential? ? :confidential_issue_hooks : :issue_hooks issue.project.execute_hooks(issue_data, hooks_scope) diff --git a/app/services/issues/build_service.rb b/app/services/issues/build_service.rb index 3fb2c2b3007..9deeee23b92 100644 --- a/app/services/issues/build_service.rb +++ b/app/services/issues/build_service.rb @@ -12,7 +12,7 @@ module Issues def issue_params_with_info_from_discussions return {} unless merge_request_to_resolve_discussions_of - { title: title_from_merge_request, description: description_for_discussions } + {title: title_from_merge_request, description: description_for_discussions} end def title_from_merge_request @@ -25,7 +25,7 @@ module Issues "Review the conversation in #{merge_request_to_resolve_discussions_of.to_reference}" end - description = "The following #{'discussion'.pluralize(discussions_to_resolve.size)} "\ + description = "The following #{"discussion".pluralize(discussions_to_resolve.size)} "\ "from #{merge_request_to_resolve_discussions_of.to_reference} "\ "should be addressed:" @@ -47,13 +47,13 @@ module Issues other_note_count = discussion.notes.size - 1 discussion_info = ["- [ ] #{first_note_to_resolve.author.to_reference} #{action} a [discussion](#{note_url}): "] - discussion_info << "(+#{other_note_count} #{'comment'.pluralize(other_note_count)})" if other_note_count > 0 + discussion_info << "(+#{other_note_count} #{"comment".pluralize(other_note_count)})" if other_note_count > 0 note_without_block_quotes = Banzai::Filter::BlockquoteFenceFilter.new(first_note_to_resolve.note).call - spaces = ' ' * 4 + spaces = " " * 4 quote = note_without_block_quotes.lines.map { |line| "#{spaces}> #{line}" }.join - [discussion_info.join(' '), quote].join("\n\n") + [discussion_info.join(" "), quote].join("\n\n") end def issue_params diff --git a/app/services/issues/close_service.rb b/app/services/issues/close_service.rb index e5cc12e6082..c674669c8fc 100644 --- a/app/services/issues/close_service.rb +++ b/app/services/issues/close_service.rb @@ -7,9 +7,9 @@ module Issues return issue unless can?(current_user, :update_issue, issue) close_issue(issue, - commit: commit, - notifications: notifications, - system_note: system_note) + commit: commit, + notifications: notifications, + system_note: system_note) end # Closes the supplied issue without checking if the user is authorized to @@ -30,7 +30,7 @@ module Issues create_note(issue, commit) if system_note notification_service.async.close_issue(issue, current_user) if notifications todo_service.close_issue(issue, current_user) - execute_hooks(issue, 'close') + execute_hooks(issue, "close") invalidate_cache_counts(issue, users: issue.assignees) issue.update_project_counter_caches end diff --git a/app/services/issues/create_service.rb b/app/services/issues/create_service.rb index 5793a15e1bc..6366614d036 100644 --- a/app/services/issues/create_service.rb +++ b/app/services/issues/create_service.rb @@ -37,8 +37,8 @@ module Issues return if discussions_to_resolve.empty? Discussions::ResolveService.new(project, current_user, - merge_request: merge_request_to_resolve_discussions_of, - follow_up_issue: issue) + merge_request: merge_request_to_resolve_discussions_of, + follow_up_issue: issue) .execute(discussions_to_resolve) end diff --git a/app/services/issues/import_csv_service.rb b/app/services/issues/import_csv_service.rb index ef08fafa7cc..a48c6cc91a1 100644 --- a/app/services/issues/import_csv_service.rb +++ b/app/services/issues/import_csv_service.rb @@ -6,7 +6,7 @@ module Issues @user = user @project = project @csv_io = csv_io - @results = { success: 0, error_lines: [], parse_error: false } + @results = {success: 0, error_lines: [], parse_error: false} end def execute diff --git a/app/services/issues/move_service.rb b/app/services/issues/move_service.rb index 41b6a96b005..30478f1b366 100644 --- a/app/services/issues/move_service.rb +++ b/app/services/issues/move_service.rb @@ -8,11 +8,11 @@ module Issues @target_project = target_project unless issue.can_move?(current_user, @target_project) - raise MoveError, 'Cannot move issue due to insufficient permissions!' + raise MoveError, "Cannot move issue due to insufficient permissions!" end if @project == @target_project - raise MoveError, 'Cannot move issue to project it originates from!' + raise MoveError, "Cannot move issue to project it originates from!" end super @@ -32,12 +32,12 @@ module Issues def create_new_entity new_params = { - id: nil, - iid: nil, - project: @target_project, - author: original_entity.author, - assignee_ids: original_entity.assignee_ids - } + id: nil, + iid: nil, + project: @target_project, + author: original_entity.author, + assignee_ids: original_entity.assignee_ids, + } new_params = original_entity.serializable_hash.symbolize_keys.merge(new_params) CreateService.new(@target_project, @current_user, new_params).execute @@ -53,14 +53,14 @@ module Issues def add_note_from SystemNoteService.noteable_moved(new_entity, @target_project, - original_entity, current_user, - direction: :from) + original_entity, current_user, + direction: :from) end def add_note_to SystemNoteService.noteable_moved(original_entity, old_project, - new_entity, current_user, - direction: :to) + new_entity, current_user, + direction: :to) end end end diff --git a/app/services/issues/referenced_merge_requests_service.rb b/app/services/issues/referenced_merge_requests_service.rb index a69cd324b1e..0a5cf2dff5e 100644 --- a/app/services/issues/referenced_merge_requests_service.rb +++ b/app/services/issues/referenced_merge_requests_service.rb @@ -9,7 +9,7 @@ module Issues preloader = ActiveRecord::Associations::Preloader.new preloader.preload(referenced + closed_by, - head_pipeline: { project: [:route, { namespace: :route }] }) + head_pipeline: {project: [:route, {namespace: :route}]}) [sort_by_iid(referenced), sort_by_iid(closed_by)] end @@ -18,7 +18,7 @@ module Issues def referenced_merge_requests(issue) merge_requests = extract_merge_requests(issue) - cross_project_filter = -> (merge_requests) do + cross_project_filter = ->(merge_requests) do merge_requests.select { |mr| mr.target_project == project } end @@ -26,7 +26,7 @@ module Issues merge_requests, current_user, filters: { - read_cross_project: cross_project_filter + read_cross_project: cross_project_filter, } ) end diff --git a/app/services/issues/reopen_service.rb b/app/services/issues/reopen_service.rb index 56d59b235a7..cb68b3bfb82 100644 --- a/app/services/issues/reopen_service.rb +++ b/app/services/issues/reopen_service.rb @@ -7,9 +7,9 @@ module Issues if issue.reopen event_service.reopen_issue(issue, current_user) - create_note(issue, 'reopened') + create_note(issue, "reopened") notification_service.async.reopen_issue(issue, current_user) - execute_hooks(issue, 'reopen') + execute_hooks(issue, "reopen") invalidate_cache_counts(issue, users: issue.assignees) issue.update_project_counter_caches end diff --git a/app/services/issues/update_service.rb b/app/services/issues/update_service.rb index cec5b5734c0..d23abcf99f4 100644 --- a/app/services/issues/update_service.rb +++ b/app/services/issues/update_service.rb @@ -31,8 +31,8 @@ module Issues todo_service.mark_pending_todos_as_done(issue, current_user) end - if issue.previous_changes.include?('title') || - issue.previous_changes.include?('description') + if issue.previous_changes.include?("title") || + issue.previous_changes.include?("description") todo_service.update_issue(issue, current_user, old_mentioned_users) end @@ -42,7 +42,7 @@ module Issues todo_service.reassigned_issue(issue, current_user, old_assignees) end - if issue.previous_changes.include?('confidential') + if issue.previous_changes.include?("confidential") # don't enqueue immediately to prevent todos removal in case of a mistake TodosDestroyer::ConfidentialIssueWorker.perform_in(Todo::WAIT_FOR_DELETE, issue.id) if issue.confidential? create_confidentiality_note(issue) @@ -97,8 +97,8 @@ module Issues target_project = params.delete(:target_project) return unless target_project && - issue.can_move?(current_user, target_project) && - target_project != issue.project + issue.can_move?(current_user, target_project) && + target_project != issue.project update(issue) Issues::MoveService.new(project, current_user).execute(issue, target_project) @@ -116,7 +116,7 @@ module Issues def handle_milestone_change(issue) return if skip_milestone_email - return unless issue.previous_changes.include?('milestone_id') + return unless issue.previous_changes.include?("milestone_id") if issue.milestone.nil? notification_service.async.removed_milestone_issue(issue, current_user) diff --git a/app/services/labels/base_service.rb b/app/services/labels/base_service.rb index ead7f2ea607..b63fc16fc4c 100644 --- a/app/services/labels/base_service.rb +++ b/app/services/labels/base_service.rb @@ -3,159 +3,159 @@ module Labels class BaseService < ::BaseService COLOR_NAME_TO_HEX = { - black: '#000000', - silver: '#C0C0C0', - gray: '#808080', - white: '#FFFFFF', - maroon: '#800000', - red: '#FF0000', - purple: '#800080', - fuchsia: '#FF00FF', - green: '#008000', - lime: '#00FF00', - olive: '#808000', - yellow: '#FFFF00', - navy: '#000080', - blue: '#0000FF', - teal: '#008080', - aqua: '#00FFFF', - orange: '#FFA500', - aliceblue: '#F0F8FF', - antiquewhite: '#FAEBD7', - aquamarine: '#7FFFD4', - azure: '#F0FFFF', - beige: '#F5F5DC', - bisque: '#FFE4C4', - blanchedalmond: '#FFEBCD', - blueviolet: '#8A2BE2', - brown: '#A52A2A', - burlywood: '#DEB887', - cadetblue: '#5F9EA0', - chartreuse: '#7FFF00', - chocolate: '#D2691E', - coral: '#FF7F50', - cornflowerblue: '#6495ED', - cornsilk: '#FFF8DC', - crimson: '#DC143C', - darkblue: '#00008B', - darkcyan: '#008B8B', - darkgoldenrod: '#B8860B', - darkgray: '#A9A9A9', - darkgreen: '#006400', - darkgrey: '#A9A9A9', - darkkhaki: '#BDB76B', - darkmagenta: '#8B008B', - darkolivegreen: '#556B2F', - darkorange: '#FF8C00', - darkorchid: '#9932CC', - darkred: '#8B0000', - darksalmon: '#E9967A', - darkseagreen: '#8FBC8F', - darkslateblue: '#483D8B', - darkslategray: '#2F4F4F', - darkslategrey: '#2F4F4F', - darkturquoise: '#00CED1', - darkviolet: '#9400D3', - deeppink: '#FF1493', - deepskyblue: '#00BFFF', - dimgray: '#696969', - dimgrey: '#696969', - dodgerblue: '#1E90FF', - firebrick: '#B22222', - floralwhite: '#FFFAF0', - forestgreen: '#228B22', - gainsboro: '#DCDCDC', - ghostwhite: '#F8F8FF', - gold: '#FFD700', - goldenrod: '#DAA520', - greenyellow: '#ADFF2F', - grey: '#808080', - honeydew: '#F0FFF0', - hotpink: '#FF69B4', - indianred: '#CD5C5C', - indigo: '#4B0082', - ivory: '#FFFFF0', - khaki: '#F0E68C', - lavender: '#E6E6FA', - lavenderblush: '#FFF0F5', - lawngreen: '#7CFC00', - lemonchiffon: '#FFFACD', - lightblue: '#ADD8E6', - lightcoral: '#F08080', - lightcyan: '#E0FFFF', - lightgoldenrodyellow: '#FAFAD2', - lightgray: '#D3D3D3', - lightgreen: '#90EE90', - lightgrey: '#D3D3D3', - lightpink: '#FFB6C1', - lightsalmon: '#FFA07A', - lightseagreen: '#20B2AA', - lightskyblue: '#87CEFA', - lightslategray: '#778899', - lightslategrey: '#778899', - lightsteelblue: '#B0C4DE', - lightyellow: '#FFFFE0', - limegreen: '#32CD32', - linen: '#FAF0E6', - mediumaquamarine: '#66CDAA', - mediumblue: '#0000CD', - mediumorchid: '#BA55D3', - mediumpurple: '#9370DB', - mediumseagreen: '#3CB371', - mediumslateblue: '#7B68EE', - mediumspringgreen: '#00FA9A', - mediumturquoise: '#48D1CC', - mediumvioletred: '#C71585', - midnightblue: '#191970', - mintcream: '#F5FFFA', - mistyrose: '#FFE4E1', - moccasin: '#FFE4B5', - navajowhite: '#FFDEAD', - oldlace: '#FDF5E6', - olivedrab: '#6B8E23', - orangered: '#FF4500', - orchid: '#DA70D6', - palegoldenrod: '#EEE8AA', - palegreen: '#98FB98', - paleturquoise: '#AFEEEE', - palevioletred: '#DB7093', - papayawhip: '#FFEFD5', - peachpuff: '#FFDAB9', - peru: '#CD853F', - pink: '#FFC0CB', - plum: '#DDA0DD', - powderblue: '#B0E0E6', - rosybrown: '#BC8F8F', - royalblue: '#4169E1', - saddlebrown: '#8B4513', - salmon: '#FA8072', - sandybrown: '#F4A460', - seagreen: '#2E8B57', - seashell: '#FFF5EE', - sienna: '#A0522D', - skyblue: '#87CEEB', - slateblue: '#6A5ACD', - slategray: '#708090', - slategrey: '#708090', - snow: '#FFFAFA', - springgreen: '#00FF7F', - steelblue: '#4682B4', - tan: '#D2B48C', - thistle: '#D8BFD8', - tomato: '#FF6347', - turquoise: '#40E0D0', - violet: '#EE82EE', - wheat: '#F5DEB3', - whitesmoke: '#F5F5F5', - yellowgreen: '#9ACD32', - rebeccapurple: '#663399' + black: "#000000", + silver: "#C0C0C0", + gray: "#808080", + white: "#FFFFFF", + maroon: "#800000", + red: "#FF0000", + purple: "#800080", + fuchsia: "#FF00FF", + green: "#008000", + lime: "#00FF00", + olive: "#808000", + yellow: "#FFFF00", + navy: "#000080", + blue: "#0000FF", + teal: "#008080", + aqua: "#00FFFF", + orange: "#FFA500", + aliceblue: "#F0F8FF", + antiquewhite: "#FAEBD7", + aquamarine: "#7FFFD4", + azure: "#F0FFFF", + beige: "#F5F5DC", + bisque: "#FFE4C4", + blanchedalmond: "#FFEBCD", + blueviolet: "#8A2BE2", + brown: "#A52A2A", + burlywood: "#DEB887", + cadetblue: "#5F9EA0", + chartreuse: "#7FFF00", + chocolate: "#D2691E", + coral: "#FF7F50", + cornflowerblue: "#6495ED", + cornsilk: "#FFF8DC", + crimson: "#DC143C", + darkblue: "#00008B", + darkcyan: "#008B8B", + darkgoldenrod: "#B8860B", + darkgray: "#A9A9A9", + darkgreen: "#006400", + darkgrey: "#A9A9A9", + darkkhaki: "#BDB76B", + darkmagenta: "#8B008B", + darkolivegreen: "#556B2F", + darkorange: "#FF8C00", + darkorchid: "#9932CC", + darkred: "#8B0000", + darksalmon: "#E9967A", + darkseagreen: "#8FBC8F", + darkslateblue: "#483D8B", + darkslategray: "#2F4F4F", + darkslategrey: "#2F4F4F", + darkturquoise: "#00CED1", + darkviolet: "#9400D3", + deeppink: "#FF1493", + deepskyblue: "#00BFFF", + dimgray: "#696969", + dimgrey: "#696969", + dodgerblue: "#1E90FF", + firebrick: "#B22222", + floralwhite: "#FFFAF0", + forestgreen: "#228B22", + gainsboro: "#DCDCDC", + ghostwhite: "#F8F8FF", + gold: "#FFD700", + goldenrod: "#DAA520", + greenyellow: "#ADFF2F", + grey: "#808080", + honeydew: "#F0FFF0", + hotpink: "#FF69B4", + indianred: "#CD5C5C", + indigo: "#4B0082", + ivory: "#FFFFF0", + khaki: "#F0E68C", + lavender: "#E6E6FA", + lavenderblush: "#FFF0F5", + lawngreen: "#7CFC00", + lemonchiffon: "#FFFACD", + lightblue: "#ADD8E6", + lightcoral: "#F08080", + lightcyan: "#E0FFFF", + lightgoldenrodyellow: "#FAFAD2", + lightgray: "#D3D3D3", + lightgreen: "#90EE90", + lightgrey: "#D3D3D3", + lightpink: "#FFB6C1", + lightsalmon: "#FFA07A", + lightseagreen: "#20B2AA", + lightskyblue: "#87CEFA", + lightslategray: "#778899", + lightslategrey: "#778899", + lightsteelblue: "#B0C4DE", + lightyellow: "#FFFFE0", + limegreen: "#32CD32", + linen: "#FAF0E6", + mediumaquamarine: "#66CDAA", + mediumblue: "#0000CD", + mediumorchid: "#BA55D3", + mediumpurple: "#9370DB", + mediumseagreen: "#3CB371", + mediumslateblue: "#7B68EE", + mediumspringgreen: "#00FA9A", + mediumturquoise: "#48D1CC", + mediumvioletred: "#C71585", + midnightblue: "#191970", + mintcream: "#F5FFFA", + mistyrose: "#FFE4E1", + moccasin: "#FFE4B5", + navajowhite: "#FFDEAD", + oldlace: "#FDF5E6", + olivedrab: "#6B8E23", + orangered: "#FF4500", + orchid: "#DA70D6", + palegoldenrod: "#EEE8AA", + palegreen: "#98FB98", + paleturquoise: "#AFEEEE", + palevioletred: "#DB7093", + papayawhip: "#FFEFD5", + peachpuff: "#FFDAB9", + peru: "#CD853F", + pink: "#FFC0CB", + plum: "#DDA0DD", + powderblue: "#B0E0E6", + rosybrown: "#BC8F8F", + royalblue: "#4169E1", + saddlebrown: "#8B4513", + salmon: "#FA8072", + sandybrown: "#F4A460", + seagreen: "#2E8B57", + seashell: "#FFF5EE", + sienna: "#A0522D", + skyblue: "#87CEEB", + slateblue: "#6A5ACD", + slategray: "#708090", + slategrey: "#708090", + snow: "#FFFAFA", + springgreen: "#00FF7F", + steelblue: "#4682B4", + tan: "#D2B48C", + thistle: "#D8BFD8", + tomato: "#FF6347", + turquoise: "#40E0D0", + violet: "#EE82EE", + wheat: "#F5DEB3", + whitesmoke: "#F5F5F5", + yellowgreen: "#9ACD32", + rebeccapurple: "#663399", }.freeze def convert_color_name_to_hex color = params[:color] color_name = color.strip.downcase - return color if color_name.start_with?('#') + return color if color_name.start_with?("#") COLOR_NAME_TO_HEX[color_name.to_sym] || color end diff --git a/app/services/labels/find_or_create_service.rb b/app/services/labels/find_or_create_service.rb index 628873519d7..4bd3969d48e 100644 --- a/app/services/labels/find_or_create_service.rb +++ b/app/services/labels/find_or_create_service.rb @@ -22,8 +22,8 @@ module Labels @available_labels ||= LabelsFinder.new( current_user, "#{parent_type}_id".to_sym => parent.id, - include_ancestor_groups: include_ancestor_groups?, - only_group_labels: parent_is_group? + :include_ancestor_groups => include_ancestor_groups?, + :only_group_labels => parent_is_group? ).execute(skip_authorization: skip_authorization) end diff --git a/app/services/labels/promote_service.rb b/app/services/labels/promote_service.rb index e73e6476c12..a04676312c0 100644 --- a/app/services/labels/promote_service.rb +++ b/app/services/labels/promote_service.rb @@ -7,7 +7,7 @@ module Labels # rubocop: disable CodeReuse/ActiveRecord def execute(label) return unless project.group && - label.is_a?(ProjectLabel) + label.is_a?(ProjectLabel) Label.transaction do new_label = clone_label_to_group_label(label) @@ -36,9 +36,9 @@ module Labels def subscribe_users(new_label, label_ids) # users can be subscribed to multiple labels that will be merged into the group one # we want to keep only one subscription / user - ids_to_update = Subscription.where(subscribable_id: label_ids, subscribable_type: 'Label') + ids_to_update = Subscription.where(subscribable_id: label_ids, subscribable_type: "Label") .group(:user_id) - .pluck('MAX(id)') + .pluck("MAX(id)") Subscription.where(id: ids_to_update).update_all(subscribable_id: new_label.id) end # rubocop: enable CodeReuse/ActiveRecord @@ -92,7 +92,7 @@ module Labels # rubocop: enable CodeReuse/ActiveRecord def clone_label_to_group_label(label) - params = label.attributes.slice('title', 'description', 'color') + params = label.attributes.slice("title", "description", "color") # Since the title of the new label has to be the same as the previous labels # and we're merging old labels in batches we'll skip validation to omit 2-step # merge process and do it in one batch diff --git a/app/services/labels/transfer_service.rb b/app/services/labels/transfer_service.rb index 9cbc9fef529..a340e15e2ac 100644 --- a/app/services/labels/transfer_service.rb +++ b/app/services/labels/transfer_service.rb @@ -37,7 +37,7 @@ module Labels Label .from_union([ group_labels_applied_to_issues, - group_labels_applied_to_merge_requests + group_labels_applied_to_merge_requests, ]) .reorder(nil) .distinct @@ -48,8 +48,8 @@ module Labels def group_labels_applied_to_issues Label.joins(:issues) .where( - issues: { project_id: project.id }, - labels: { type: 'GroupLabel', group_id: old_group.id } + issues: {project_id: project.id}, + labels: {type: "GroupLabel", group_id: old_group.id} ) end # rubocop: enable CodeReuse/ActiveRecord @@ -58,14 +58,14 @@ module Labels def group_labels_applied_to_merge_requests Label.joins(:merge_requests) .where( - merge_requests: { target_project_id: project.id }, - labels: { type: 'GroupLabel', group_id: old_group.id } + merge_requests: {target_project_id: project.id}, + labels: {type: "GroupLabel", group_id: old_group.id} ) end # rubocop: enable CodeReuse/ActiveRecord def find_or_create_label!(label) - params = label.attributes.slice('title', 'description', 'color') + params = label.attributes.slice("title", "description", "color") new_label = FindOrCreateService.new(current_user, project, params).execute new_label.id @@ -78,7 +78,7 @@ module Labels # IDs are fetched in a separate query because MySQL doesn't # allow referring of 'label_links' table in UPDATE query: # https://gitlab.com/gitlab-org/gitlab-ce/-/jobs/62435068 - link_ids = labels.pluck('label_links.id') + link_ids = labels.pluck("label_links.id") LabelLink.where(id: link_ids, label_id: old_label_id) .update_all(label_id: new_label_id) diff --git a/app/services/lfs/file_transformer.rb b/app/services/lfs/file_transformer.rb index 6ecf583cb6a..279f0b3010c 100644 --- a/app/services/lfs/file_transformer.rb +++ b/app/services/lfs/file_transformer.rb @@ -24,13 +24,13 @@ module Lfs def new_file(file_path, file_content, encoding: nil) if project.lfs_enabled? && lfs_file?(file_path) - file_content = Base64.decode64(file_content) if encoding == 'base64' + file_content = Base64.decode64(file_content) if encoding == "base64" lfs_pointer_file = Gitlab::Git::LfsPointerFile.new(file_content) lfs_object = create_lfs_object!(lfs_pointer_file, file_content) link_lfs_object!(lfs_object) - Result.new(content: lfs_pointer_file.pointer, encoding: 'text') + Result.new(content: lfs_pointer_file.pointer, encoding: "text") else Result.new(content: file_content, encoding: encoding) end @@ -48,7 +48,7 @@ module Lfs private def lfs_file?(file_path) - cached_attributes.attributes(file_path)['filter'] == 'lfs' + cached_attributes.attributes(file_path)["filter"] == "lfs" end def cached_attributes diff --git a/app/services/lfs/lock_file_service.rb b/app/services/lfs/lock_file_service.rb index c7730d24bdc..124e99eae29 100644 --- a/app/services/lfs/lock_file_service.rb +++ b/app/services/lfs/lock_file_service.rb @@ -4,12 +4,12 @@ module Lfs class LockFileService < BaseService def execute unless can?(current_user, :push_code, project) - raise Gitlab::GitAccess::UnauthorizedError, 'You have no permissions' + raise Gitlab::GitAccess::UnauthorizedError, "You have no permissions" end create_lock! rescue ActiveRecord::RecordNotUnique - error('already locked', 409, current_lock) + error("already locked", 409, current_lock) rescue Gitlab::GitAccess::UnauthorizedError => ex error(ex.message, 403) rescue => ex @@ -36,7 +36,7 @@ module Lfs status: :error, message: message, http_status: http_status, - lock: lock + lock: lock, } end end diff --git a/app/services/lfs/unlock_file_service.rb b/app/services/lfs/unlock_file_service.rb index a42916d86bb..9306d53d14f 100644 --- a/app/services/lfs/unlock_file_service.rb +++ b/app/services/lfs/unlock_file_service.rb @@ -4,14 +4,14 @@ module Lfs class UnlockFileService < BaseService def execute unless can?(current_user, :push_code, project) - raise Gitlab::GitAccess::UnauthorizedError, _('You have no permissions') + raise Gitlab::GitAccess::UnauthorizedError, _("You have no permissions") end unlock_file rescue Gitlab::GitAccess::UnauthorizedError => ex error(ex.message, 403) rescue ActiveRecord::RecordNotFound - error(_('Lock not found'), 404) + error(_("Lock not found"), 404) rescue => ex error(ex.message, 500) end @@ -26,9 +26,9 @@ module Lfs success(lock: lock, http_status: :ok) elsif forced - error(_('You must have maintainer access to force delete a lock'), 403) + error(_("You must have maintainer access to force delete a lock"), 403) else - error(_("%{lock_path} is locked by GitLab User %{lock_user_id}") % { lock_path: lock.path, lock_user_id: lock.user_id }, 403) + error(_("%{lock_path} is locked by GitLab User %{lock_user_id}") % {lock_path: lock.path, lock_user_id: lock.user_id}, 403) end end @@ -37,10 +37,10 @@ module Lfs return @lock if defined?(@lock) @lock = if params[:id].present? - project.lfs_file_locks.find(params[:id]) - elsif params[:path].present? - project.lfs_file_locks.find_by!(path: params[:path]) - end + project.lfs_file_locks.find(params[:id]) + elsif params[:path].present? + project.lfs_file_locks.find_by!(path: params[:path]) + end end # rubocop: enable CodeReuse/ActiveRecord end diff --git a/app/services/members/base_service.rb b/app/services/members/base_service.rb index e78affff797..1f26378862f 100644 --- a/app/services/members/base_service.rb +++ b/app/services/members/base_service.rb @@ -49,7 +49,7 @@ module Members end def enqueue_delete_todos(member) - type = member.is_a?(GroupMember) ? 'Group' : 'Project' + type = member.is_a?(GroupMember) ? "Group" : "Project" # don't enqueue immediately to prevent todos removal in case of a mistake TodosDestroyer::EntityLeaveWorker.perform_in(Todo::WAIT_FOR_DELETE, member.user_id, member.source_id, type) end diff --git a/app/services/members/create_service.rb b/app/services/members/create_service.rb index cf710fef52b..f6a857af7ec 100644 --- a/app/services/members/create_service.rb +++ b/app/services/members/create_service.rb @@ -5,9 +5,9 @@ module Members DEFAULT_LIMIT = 100 def execute(source) - return error('No users specified.') if params[:user_ids].blank? + return error("No users specified.") if params[:user_ids].blank? - user_ids = params[:user_ids].split(',').uniq + user_ids = params[:user_ids].split(",").uniq return error("Too many users specified (limit is #{user_limit})") if user_limit && user_ids.size > user_limit diff --git a/app/services/members/request_access_service.rb b/app/services/members/request_access_service.rb index b9b0550e290..280561e159d 100644 --- a/app/services/members/request_access_service.rb +++ b/app/services/members/request_access_service.rb @@ -8,7 +8,8 @@ module Members source.members.create( access_level: Gitlab::Access::DEVELOPER, user: current_user, - requested_at: Time.now.utc) + requested_at: Time.now.utc + ) end private diff --git a/app/services/merge_requests/assign_issues_service.rb b/app/services/merge_requests/assign_issues_service.rb index e9107b9998e..0622094474d 100644 --- a/app/services/merge_requests/assign_issues_service.rb +++ b/app/services/merge_requests/assign_issues_service.rb @@ -20,7 +20,7 @@ module MergeRequests end { - count: assignable_issues.count + count: assignable_issues.count, } end diff --git a/app/services/merge_requests/base_service.rb b/app/services/merge_requests/base_service.rb index ac51fee0b3f..72a2d352248 100644 --- a/app/services/merge_requests/base_service.rb +++ b/app/services/merge_requests/base_service.rb @@ -16,7 +16,7 @@ module MergeRequests hook_data end - def execute_hooks(merge_request, action = 'open', old_rev: nil, old_associations: {}) + def execute_hooks(merge_request, action = "open", old_rev: nil, old_associations: {}) if merge_request.project merge_data = hook_data(merge_request, action, old_rev: old_rev, old_associations: old_associations) merge_request.project.execute_hooks(merge_data, :merge_request_hooks) @@ -31,9 +31,9 @@ module MergeRequests # We update the title that is provided in the params or we use the mr title title = params[:title] || merge_request.title params[:title] = case wip_event - when 'wip' then MergeRequest.wip_title(title) - when 'unwip' then MergeRequest.wipless_title(title) - end + when "wip" then MergeRequest.wip_title(title) + when "unwip" then MergeRequest.wipless_title(title) + end end end @@ -51,13 +51,14 @@ module MergeRequests def create_assignee_note(merge_request) SystemNoteService.change_assignee( - merge_request, merge_request.project, current_user, merge_request.assignee) + merge_request, merge_request.project, current_user, merge_request.assignee + ) end def create_merge_request_pipeline(merge_request, user) return unless Feature.enabled?(:ci_merge_request_pipeline, - merge_request.source_project, - default_enabled: true) + merge_request.source_project, + default_enabled: true) ## # UpdateMergeRequestsWorker could be retried by an exception. @@ -68,9 +69,9 @@ module MergeRequests Ci::CreatePipelineService .new(merge_request.source_project, user, ref: merge_request.source_branch) .execute(:merge_request, - ignore_skip_ci: true, - save_on_errors: false, - merge_request: merge_request) + ignore_skip_ci: true, + save_on_errors: false, + merge_request: merge_request) end # Returns all origin and fork merge requests from `@project` satisfying passed arguments. diff --git a/app/services/merge_requests/build_service.rb b/app/services/merge_requests/build_service.rb index 48419da98ad..8a63c7e66c5 100644 --- a/app/services/merge_requests/build_service.rb +++ b/app/services/merge_requests/build_service.rb @@ -10,7 +10,7 @@ module MergeRequests # TODO: this should handle all quick actions that don't have side effects # https://gitlab.com/gitlab-org/gitlab-ce/issues/53658 merge_quick_actions_into_params!(merge_request, only: [:target_branch]) - merge_request.merge_params['force_remove_source_branch'] = params.delete(:force_remove_source_branch) if params.has_key?(:force_remove_source_branch) + merge_request.merge_params["force_remove_source_branch"] = params.delete(:force_remove_source_branch) if params.key?(:force_remove_source_branch) merge_request.assign_attributes(params) merge_request.author = current_user @@ -37,16 +37,16 @@ module MergeRequests attr_accessor :merge_request delegate :target_branch, - :target_branch_ref, - :target_project, - :source_branch, - :source_branch_ref, - :source_project, - :compare_commits, - :wip_title, - :description, - :errors, - to: :merge_request + :target_branch_ref, + :target_project, + :source_branch, + :source_branch_ref, + :source_project, + :compare_commits, + :wip_title, + :description, + :errors, + to: :merge_request def find_source_project return source_project if source_project.present? && can?(current_user, :create_merge_request_from, source_project) @@ -105,8 +105,8 @@ module MergeRequests return if errors.any? - add_error('You must select source and target branch') unless branches_present? - add_error('You must select different branches') if same_source_and_target? + add_error("You must select source and target branch") unless branches_present? + add_error("You must select different branches") if same_source_and_target? add_error("Source branch \"#{source_branch}\" does not exist") unless source_branch_exists? add_error("Target branch \"#{target_branch}\" does not exist") unless target_branch_exists? end @@ -200,15 +200,15 @@ module MergeRequests branch_title = source_branch.downcase.remove(issue_iid.downcase).titleize.humanize title_parts << "\"#{branch_title}\"" if branch_title.present? - title_parts.join(' ') + title_parts.join(" ") end def issue_iid strong_memoize(:issue_iid) do @params_issue_iid || begin id = if target_project.external_issue_tracker - source_branch.match(target_project.external_issue_reference_pattern).try(:[], 0) - end + source_branch.match(target_project.external_issue_reference_pattern).try(:[], 0) + end id || source_branch.match(/\A(\d+)-/).try(:[], 1) end diff --git a/app/services/merge_requests/close_service.rb b/app/services/merge_requests/close_service.rb index 04527bb9713..e5449f015ce 100644 --- a/app/services/merge_requests/close_service.rb +++ b/app/services/merge_requests/close_service.rb @@ -14,7 +14,7 @@ module MergeRequests create_note(merge_request) notification_service.async.close_mr(merge_request, current_user) todo_service.close_merge_request(merge_request, current_user) - execute_hooks(merge_request, 'close') + execute_hooks(merge_request, "close") invalidate_cache_counts(merge_request, users: merge_request.assignees) merge_request.update_project_counter_caches end diff --git a/app/services/merge_requests/create_from_issue_service.rb b/app/services/merge_requests/create_from_issue_service.rb index e69791872cc..cef57be8082 100644 --- a/app/services/merge_requests/create_from_issue_service.rb +++ b/app/services/merge_requests/create_from_issue_service.rb @@ -14,7 +14,7 @@ module MergeRequests end def execute - return error('Invalid issue iid') unless @issue_iid.present? && issue.present? + return error("Invalid issue iid") unless @issue_iid.present? && issue.present? result = CreateBranchService.new(project, current_user).execute(branch_name, ref) return result if result[:status] == :error @@ -47,7 +47,7 @@ module MergeRequests def ref return @ref if project.repository.branch_exists?(@ref) - project.default_branch || 'master' + project.default_branch || "master" end def merge_request @@ -60,7 +60,7 @@ module MergeRequests source_project_id: project.id, source_branch: branch_name, target_project_id: project.id, - target_branch: ref + target_branch: ref, } end diff --git a/app/services/merge_requests/create_service.rb b/app/services/merge_requests/create_service.rb index 02c2388c05c..c5a9aae7af3 100644 --- a/app/services/merge_requests/create_service.rb +++ b/app/services/merge_requests/create_service.rb @@ -9,7 +9,7 @@ module MergeRequests merge_request.target_project = @project merge_request.source_project = @source_project merge_request.source_branch = params[:source_branch] - merge_request.merge_params['force_remove_source_branch'] = params.delete(:force_remove_source_branch) + merge_request.merge_params["force_remove_source_branch"] = params.delete(:force_remove_source_branch) create(merge_request) end diff --git a/app/services/merge_requests/ff_merge_service.rb b/app/services/merge_requests/ff_merge_service.rb index 479e0fe6699..b04a7fcacb8 100644 --- a/app/services/merge_requests/ff_merge_service.rb +++ b/app/services/merge_requests/ff_merge_service.rb @@ -12,12 +12,12 @@ module MergeRequests def commit repository.ff_merge(current_user, - source, - merge_request.target_branch, - merge_request: merge_request) + source, + merge_request.target_branch, + merge_request: merge_request) rescue Gitlab::Git::PreReceiveError => e raise MergeError, e.message - rescue StandardError => e + rescue => e raise MergeError, "Something went wrong during merge: #{e.message}" ensure merge_request.update(in_progress_merge_commit_sha: nil) diff --git a/app/services/merge_requests/get_urls_service.rb b/app/services/merge_requests/get_urls_service.rb index 7c88c9abb41..1cb4b991968 100644 --- a/app/services/merge_requests/get_urls_service.rb +++ b/app/services/merge_requests/get_urls_service.rb @@ -35,7 +35,7 @@ module MergeRequests return [] unless project.merge_requests_enabled? changes_list = Gitlab::ChangesList.new(changes) - changes_list.map do |change| + changes_list.map { |change| next unless Gitlab::Git.branch_ref?(change[:ref]) # Deleted branch @@ -46,19 +46,19 @@ module MergeRequests next if branch_name == project.default_branch branch_name - end.compact + }.compact end def url_for_new_merge_request(branch_name) - merge_request_params = { source_branch: branch_name } + merge_request_params = {source_branch: branch_name} url = Gitlab::Routing.url_helpers.project_new_merge_request_url(project, merge_request: merge_request_params) - { branch_name: branch_name, url: url, new_merge_request: true } + {branch_name: branch_name, url: url, new_merge_request: true} end def url_for_existing_merge_request(merge_request) target_project = merge_request.target_project url = Gitlab::Routing.url_helpers.project_merge_request_url(target_project, merge_request) - { branch_name: merge_request.source_branch, url: url, new_merge_request: false } + {branch_name: merge_request.source_branch, url: url, new_merge_request: false} end end end diff --git a/app/services/merge_requests/merge_service.rb b/app/services/merge_requests/merge_service.rb index 8241e408ce5..4b1dc239488 100644 --- a/app/services/merge_requests/merge_service.rb +++ b/app/services/merge_requests/merge_service.rb @@ -11,7 +11,7 @@ module MergeRequests delegate :merge_jid, :state, to: :@merge_request def execute(merge_request) - if project.merge_requests_ff_only_enabled && !self.is_a?(FfMergeService) + if project.merge_requests_ff_only_enabled && !is_a?(FfMergeService) FfMergeService.new(project, current_user, params).execute(merge_request) return end @@ -41,7 +41,7 @@ module MergeRequests def authorization_check! unless @merge_request.can_be_merged_by?(current_user) - raise_error('You are not allowed to merge this merge request') + raise_error("You are not allowed to merge this merge request") end end @@ -50,11 +50,11 @@ module MergeRequests error = if @merge_request.should_be_rebased? - 'Only fast-forward merge is allowed for your project. Please update your source branch' + "Only fast-forward merge is allowed for your project. Please update your source branch" elsif !@merge_request.mergeable? - 'Merge request is not mergeable' + "Merge request is not mergeable" elsif !source - 'No source for merge' + "No source for merge" end raise_error(error) if error @@ -67,7 +67,7 @@ module MergeRequests if commit_id log_info("Git merge finished on JID #{merge_jid} commit #{commit_id}") else - raise_error('Conflicts detected during merge') + raise_error("Conflicts detected during merge") end merge_request.update!(merge_commit_sha: commit_id) @@ -77,10 +77,10 @@ module MergeRequests repository.merge(current_user, source, merge_request, commit_message) rescue Gitlab::Git::PreReceiveError => e handle_merge_error(log_message: e.message) - raise_error('Something went wrong during merge pre-receive hook') + raise_error("Something went wrong during merge pre-receive hook") rescue => e handle_merge_error(log_message: e.message) - raise_error('Something went wrong during merge') + raise_error("Something went wrong during merge") ensure merge_request.update!(in_progress_merge_commit_sha: nil) end @@ -108,7 +108,7 @@ module MergeRequests # or the source branch may have been updated, or the user may not have permission # def delete_source_branch? - params.fetch('should_remove_source_branch', @merge_request.force_remove_source_branch?) && + params.fetch("should_remove_source_branch", @merge_request.force_remove_source_branch?) && @merge_request.can_remove_source_branch?(branch_deletion_user) end diff --git a/app/services/merge_requests/merge_to_ref_service.rb b/app/services/merge_requests/merge_to_ref_service.rb index 586652ae44e..9770af0dffe 100644 --- a/app/services/merge_requests/merge_to_ref_service.rb +++ b/app/services/merge_requests/merge_to_ref_service.rb @@ -18,7 +18,7 @@ module MergeRequests commit_id = commit - raise_error('Conflicts detected during merge') unless commit_id + raise_error("Conflicts detected during merge") unless commit_id success(commit_id: commit_id) rescue MergeError => error @@ -37,17 +37,17 @@ module MergeRequests error = if Feature.disabled?(:merge_to_tmp_merge_ref_path, project) - 'Feature is not enabled' + "Feature is not enabled" elsif !merge_method_supported? "#{project.human_merge_method} to #{target_ref} is currently not supported." elsif !hooks_validation_pass?(merge_request) hooks_validation_error(merge_request) elsif @merge_request.should_be_rebased? - 'Fast-forward merge is not possible. Please update your source branch.' + "Fast-forward merge is not possible. Please update your source branch." elsif !@merge_request.mergeable_to_ref? "Merge request is not mergeable to #{target_ref}" elsif !source - 'No source for merge' + "No source for merge" end raise_error(error) if error diff --git a/app/services/merge_requests/post_merge_service.rb b/app/services/merge_requests/post_merge_service.rb index f26e3bee06f..467fc4b05ca 100644 --- a/app/services/merge_requests/post_merge_service.rb +++ b/app/services/merge_requests/post_merge_service.rb @@ -14,7 +14,7 @@ module MergeRequests create_event(merge_request) create_note(merge_request) notification_service.merge_mr(merge_request, current_user) - execute_hooks(merge_request, 'merge') + execute_hooks(merge_request, "merge") invalidate_cache_counts(merge_request, users: merge_request.assignees) merge_request.update_project_counter_caches delete_non_latest_diffs(merge_request) diff --git a/app/services/merge_requests/rebase_service.rb b/app/services/merge_requests/rebase_service.rb index 31b3ebf311e..9e5842906a3 100644 --- a/app/services/merge_requests/rebase_service.rb +++ b/app/services/merge_requests/rebase_service.rb @@ -2,7 +2,7 @@ module MergeRequests class RebaseService < MergeRequests::WorkingCopyBaseService - REBASE_ERROR = 'Rebase failed. Please rebase locally'.freeze + REBASE_ERROR = "Rebase failed. Please rebase locally" def execute(merge_request) @merge_request = merge_request @@ -16,7 +16,7 @@ module MergeRequests def rebase if merge_request.rebase_in_progress? - log_error('Rebase task canceled: Another rebase is already in progress', save_message_on_model: true) + log_error("Rebase task canceled: Another rebase is already in progress", save_message_on_model: true) return false end diff --git a/app/services/merge_requests/refresh_service.rb b/app/services/merge_requests/refresh_service.rb index f712b8863cd..f131bf76fab 100644 --- a/app/services/merge_requests/refresh_service.rb +++ b/app/services/merge_requests/refresh_service.rb @@ -58,10 +58,10 @@ module MergeRequests .preload(:latest_merge_request_diff) .where(target_branch: @push.branch_name).to_a .select(&:diff_head_commit) - .select do |merge_request| + .select { |merge_request| commit_ids.include?(merge_request.diff_head_sha) && - merge_request.merge_request_diff.state != 'empty' - end + merge_request.merge_request_diff.state != "empty" + } merge_requests = filter_merge_requests(merge_requests) return if merge_requests.empty? @@ -166,7 +166,8 @@ module MergeRequests merge_requests_for_source_branch.each do |merge_request| SystemNoteService.change_branch_presence( merge_request, merge_request.project, @current_user, - :source, @push.branch_name, presence) + :source, @push.branch_name, presence + ) end end @@ -177,13 +178,13 @@ module MergeRequests merge_requests_for_source_branch.each do |merge_request| mr_commit_ids = Set.new(merge_request.commit_shas) - new_commits, existing_commits = @commits.partition do |commit| + new_commits, existing_commits = @commits.partition { |commit| mr_commit_ids.include?(commit.id) - end + } SystemNoteService.add_commits(merge_request, merge_request.project, - @current_user, new_commits, - existing_commits, @push.oldrev) + @current_user, new_commits, + existing_commits, @push.oldrev) notification_service.push_to_merge_request(merge_request, @current_user, new_commits: new_commits, existing_commits: existing_commits) end @@ -195,9 +196,9 @@ module MergeRequests merge_requests_for_source_branch.each do |merge_request| commit_shas = merge_request.commit_shas - wip_commit = @commits.detect do |commit| + wip_commit = @commits.detect { |commit| commit.work_in_progress? && commit_shas.include?(commit.sha) - end + } if wip_commit && !merge_request.work_in_progress? merge_request.update(title: merge_request.wip_title) @@ -214,7 +215,7 @@ module MergeRequests # Call merge request webhook with update branches def execute_mr_web_hooks merge_requests_for_source_branch.each do |merge_request| - execute_hooks(merge_request, 'update', old_rev: @push.oldrev) + execute_hooks(merge_request, "update", old_rev: @push.oldrev) end end diff --git a/app/services/merge_requests/reopen_service.rb b/app/services/merge_requests/reopen_service.rb index f6cbe769ef4..2df19aba42b 100644 --- a/app/services/merge_requests/reopen_service.rb +++ b/app/services/merge_requests/reopen_service.rb @@ -7,9 +7,9 @@ module MergeRequests if merge_request.reopen create_event(merge_request) - create_note(merge_request, 'reopened') + create_note(merge_request, "reopened") notification_service.async.reopen_mr(merge_request, current_user) - execute_hooks(merge_request, 'reopen') + execute_hooks(merge_request, "reopen") merge_request.reload_diff(current_user) merge_request.mark_as_unchecked invalidate_cache_counts(merge_request, users: merge_request.assignees) diff --git a/app/services/merge_requests/squash_service.rb b/app/services/merge_requests/squash_service.rb index 9d1a5d5e6d4..423de0baf38 100644 --- a/app/services/merge_requests/squash_service.rb +++ b/app/services/merge_requests/squash_service.rb @@ -10,10 +10,10 @@ module MergeRequests end if merge_request.squash_in_progress? - return error('Squash task canceled: another squash is already in progress.') + return error("Squash task canceled: another squash is already in progress.") end - squash! || error('Failed to squash. Should be done manually.') + squash! || error("Failed to squash. Should be done manually.") end private diff --git a/app/services/merge_requests/update_service.rb b/app/services/merge_requests/update_service.rb index 8112c2a4299..7ea2f2de9c7 100644 --- a/app/services/merge_requests/update_service.rb +++ b/app/services/merge_requests/update_service.rb @@ -17,7 +17,7 @@ module MergeRequests end if params[:force_remove_source_branch].present? - merge_request.merge_params['force_remove_source_branch'] = params.delete(:force_remove_source_branch) + merge_request.merge_params["force_remove_source_branch"] = params.delete(:force_remove_source_branch) end handle_wip_event(merge_request) @@ -34,21 +34,21 @@ module MergeRequests todo_service.mark_pending_todos_as_done(merge_request, current_user) end - if merge_request.previous_changes.include?('title') || - merge_request.previous_changes.include?('description') + if merge_request.previous_changes.include?("title") || + merge_request.previous_changes.include?("description") todo_service.update_merge_request(merge_request, current_user, old_mentioned_users) end - if merge_request.previous_changes.include?('target_branch') - create_branch_change_note(merge_request, 'target', - merge_request.previous_changes['target_branch'].first, - merge_request.target_branch) + if merge_request.previous_changes.include?("target_branch") + create_branch_change_note(merge_request, "target", + merge_request.previous_changes["target_branch"].first, + merge_request.target_branch) end - if merge_request.previous_changes.include?('assignee_id') + if merge_request.previous_changes.include?("assignee_id") reassigned_merge_request_args = [merge_request, current_user] - old_assignee_id = merge_request.previous_changes['assignee_id'].first + old_assignee_id = merge_request.previous_changes["assignee_id"].first reassigned_merge_request_args << User.find(old_assignee_id) if old_assignee_id create_assignee_note(merge_request) @@ -56,8 +56,8 @@ module MergeRequests todo_service.reassigned_merge_request(merge_request, current_user) end - if merge_request.previous_changes.include?('target_branch') || - merge_request.previous_changes.include?('source_branch') + if merge_request.previous_changes.include?("target_branch") || + merge_request.previous_changes.include?("source_branch") merge_request.mark_as_unchecked end @@ -94,7 +94,7 @@ module MergeRequests merge_request.update(merge_error: nil) - if merge_request.head_pipeline && merge_request.head_pipeline.active? + if merge_request.head_pipeline&.active? MergeRequests::MergeWhenPipelineSucceedsService.new(project, current_user).execute(merge_request) else merge_request.merge_async(current_user.id, {}) @@ -118,7 +118,7 @@ module MergeRequests def handle_milestone_change(merge_request) return if skip_milestone_email - return unless merge_request.previous_changes.include?('milestone_id') + return unless merge_request.previous_changes.include?("milestone_id") if merge_request.milestone.nil? notification_service.async.removed_milestone_merge_request(merge_request, current_user) @@ -130,7 +130,8 @@ module MergeRequests def create_branch_change_note(issuable, branch_type, old_branch, new_branch) SystemNoteService.change_branch( issuable, issuable.project, current_user, branch_type, - old_branch, new_branch) + old_branch, new_branch + ) end end end diff --git a/app/services/metrics_service.rb b/app/services/metrics_service.rb index 222a5c8c79c..d076f8032b2 100644 --- a/app/services/metrics_service.rb +++ b/app/services/metrics_service.rb @@ -1,6 +1,6 @@ # frozen_string_literal: true -require 'prometheus/client/formats/text' +require "prometheus/client/formats/text" class MetricsService def prometheus_metrics_text diff --git a/app/services/milestones/destroy_service.rb b/app/services/milestones/destroy_service.rb index 87c7a282081..20a3d526a1d 100644 --- a/app/services/milestones/destroy_service.rb +++ b/app/services/milestones/destroy_service.rb @@ -4,7 +4,7 @@ module Milestones class DestroyService < Milestones::BaseService def execute(milestone) Milestone.transaction do - update_params = { milestone: nil, skip_milestone_email: true } + update_params = {milestone: nil, skip_milestone_email: true} milestone.issues.each do |issue| Issues::UpdateService.new(parent, current_user, update_params).execute(issue) diff --git a/app/services/milestones/promote_service.rb b/app/services/milestones/promote_service.rb index cbe5996e8ca..c249d25679e 100644 --- a/app/services/milestones/promote_service.rb +++ b/app/services/milestones/promote_service.rb @@ -31,7 +31,7 @@ module Milestones # Pluck need to be used here instead of select so the array of ids # is persistent after old milestones gets deleted. @milestone_ids_for_merge ||= begin - search_params = { title: group_milestone.title, project_ids: group_project_ids, state: 'all' } + search_params = {title: group_milestone.title, project_ids: group_project_ids, state: "all"} milestones = MilestonesFinder.new(search_params).execute milestones.pluck(:id) end @@ -45,7 +45,7 @@ module Milestones end def check_project_milestone!(milestone) - raise_error('Only project milestones can be promoted.') unless milestone.project_milestone? + raise_error("Only project milestones can be promoted.") unless milestone.project_milestone? end def clone_project_milestone(milestone) @@ -73,7 +73,7 @@ module Milestones # rubocop: enable CodeReuse/ActiveRecord def group - @group ||= parent.group || raise_error('Project does not belong to a group.') + @group ||= parent.group || raise_error("Project does not belong to a group.") end # rubocop: disable CodeReuse/ActiveRecord diff --git a/app/services/milestones/update_service.rb b/app/services/milestones/update_service.rb index 01ab8b37bac..2e40326b324 100644 --- a/app/services/milestones/update_service.rb +++ b/app/services/milestones/update_service.rb @@ -7,9 +7,9 @@ module Milestones state = params[:state_event] case state - when 'activate' + when "activate" Milestones::ReopenService.new(parent, current_user, {}).execute(milestone) - when 'close' + when "close" Milestones::CloseService.new(parent, current_user, {}).execute(milestone) end diff --git a/app/services/note_summary.rb b/app/services/note_summary.rb index 81f6f92f75c..fbcdd6190e0 100644 --- a/app/services/note_summary.rb +++ b/app/services/note_summary.rb @@ -5,8 +5,8 @@ class NoteSummary attr_reader :metadata def initialize(noteable, project, author, body, action: nil, commit_count: nil) - @note = { noteable: noteable, project: project, author: author, note: body } - @metadata = { action: action, commit_count: commit_count }.compact + @note = {noteable: noteable, project: project, author: author, note: body} + @metadata = {action: action, commit_count: commit_count}.compact set_commit_params if note[:noteable].is_a?(Commit) end @@ -16,7 +16,7 @@ class NoteSummary end def set_commit_params - note.merge!(noteable_type: 'Commit', commit_id: note[:noteable].id) + note.merge!(noteable_type: "Commit", commit_id: note[:noteable].id) note[:noteable] = nil end end diff --git a/app/services/notes/build_service.rb b/app/services/notes/build_service.rb index 541f3e0d23c..f527419cd6b 100644 --- a/app/services/notes/build_service.rb +++ b/app/services/notes/build_service.rb @@ -11,7 +11,7 @@ module Notes unless discussion && can?(current_user, :create_note, discussion.noteable) note = Note.new - note.errors.add(:base, 'Discussion to reply to cannot be found') + note.errors.add(:base, "Discussion to reply to cannot be found") return note end diff --git a/app/services/notes/create_service.rb b/app/services/notes/create_service.rb index 5a6e7338b42..a1aa1f694bf 100644 --- a/app/services/notes/create_service.rb +++ b/app/services/notes/create_service.rb @@ -8,9 +8,9 @@ module Notes note = Notes::BuildService.new(project, current_user, params).execute # n+1: https://gitlab.com/gitlab-org/gitlab-ce/issues/37440 - note_valid = Gitlab::GitalyClient.allow_n_plus_1_calls do + note_valid = Gitlab::GitalyClient.allow_n_plus_1_calls { note.valid? - end + } return note unless note_valid @@ -20,7 +20,7 @@ module Notes quick_actions_service = QuickActionsService.new(project, current_user) if quick_actions_service.supported?(note) - options = { merge_request_diff_head_sha: merge_request_diff_head_sha } + options = {merge_request_diff_head_sha: merge_request_diff_head_sha} content, command_params = quick_actions_service.extract_commands(note, options) only_commands = content.empty? @@ -49,7 +49,7 @@ module Notes # We must add the error after we call #save because errors are reset # when #save is called if only_commands - note.errors.add(:commands_only, 'Commands applied') + note.errors.add(:commands_only, "Commands applied") end note.commands_changes = command_params diff --git a/app/services/notes/quick_actions_service.rb b/app/services/notes/quick_actions_service.rb index 985a03060bd..e9a2e1b34e0 100644 --- a/app/services/notes/quick_actions_service.rb +++ b/app/services/notes/quick_actions_service.rb @@ -3,9 +3,9 @@ module Notes class QuickActionsService < BaseService UPDATE_SERVICES = { - 'Issue' => Issues::UpdateService, - 'MergeRequest' => MergeRequests::UpdateService, - 'Commit' => Commits::TagService + "Issue" => Issues::UpdateService, + "MergeRequest" => MergeRequests::UpdateService, + "Commit" => Commits::TagService, }.freeze private_constant :UPDATE_SERVICES diff --git a/app/services/notes/update_service.rb b/app/services/notes/update_service.rb index d2052bed646..1090794aeb8 100644 --- a/app/services/notes/update_service.rb +++ b/app/services/notes/update_service.rb @@ -10,7 +10,7 @@ module Notes note.update(params.merge(updated_by: current_user)) note.create_new_cross_references!(current_user) - if note.previous_changes.include?('note') + if note.previous_changes.include?("note") TodoService.new.update_note(note, current_user, old_mentioned_users) end diff --git a/app/services/notification_recipient_service.rb b/app/services/notification_recipient_service.rb index 56f11b31110..940feded269 100644 --- a/app/services/notification_recipient_service.rb +++ b/app/services/notification_recipient_service.rb @@ -31,11 +31,11 @@ module NotificationRecipientService module Builder class Base def initialize(*) - raise 'abstract' + raise "abstract" end def build! - raise 'abstract' + raise "abstract" end def filter! @@ -47,7 +47,7 @@ module NotificationRecipientService end def target - raise 'abstract' + raise "abstract" end def project @@ -293,7 +293,7 @@ module NotificationRecipientService target.assignees else target.assignee - end + end # We use the `:participating` notification level in order to match existing legacy behavior as captured # in existing specs (notification_service_spec.rb ~ line 507) diff --git a/app/services/notification_service.rb b/app/services/notification_service.rb index 1a65561dd70..1fa1d66c51b 100644 --- a/app/services/notification_service.rb +++ b/app/services/notification_service.rb @@ -151,8 +151,8 @@ class NotificationService end def push_to_merge_request(merge_request, current_user, new_commits: [], existing_commits: []) - new_commits = new_commits.map { |c| { short_id: c.short_id, title: c.title } } - existing_commits = existing_commits.map { |c| { short_id: c.short_id, title: c.title } } + new_commits = new_commits.map { |c| {short_id: c.short_id, title: c.title} } + existing_commits = existing_commits.map { |c| {short_id: c.short_id, title: c.title} } recipients = NotificationRecipientService.build_recipients(merge_request, current_user, action: "push_to") recipients.each do |recipient| @@ -228,7 +228,7 @@ class NotificationService end def reopen_issue(issue, current_user) - reopen_resource_email(issue, current_user, :issue_status_changed_email, 'reopened') + reopen_resource_email(issue, current_user, :issue_status_changed_email, "reopened") end def merge_mr(merge_request, current_user) @@ -245,7 +245,7 @@ class NotificationService merge_request, current_user, :merge_request_status_email, - 'reopened' + "reopened" ) end @@ -253,7 +253,8 @@ class NotificationService recipients = NotificationRecipientService.build_recipients( merge_request, current_user, - action: "resolve_all_discussions") + action: "resolve_all_discussions" + ) recipients.each do |recipient| mailer.resolved_all_discussions_email(recipient.user.id, merge_request.id, current_user.id, recipient.reason).deliver_later @@ -386,7 +387,7 @@ class NotificationService end def issue_moved(issue, new_issue, current_user) - recipients = NotificationRecipientService.build_recipients(issue, current_user, action: 'moved') + recipients = NotificationRecipientService.build_recipients(issue, current_user, action: "moved") recipients.map do |recipient| email = mailer.issue_moved_email(recipient.user, issue, new_issue, current_user, recipient.reason) @@ -430,25 +431,25 @@ class NotificationService end def pages_domain_verification_succeeded(domain) - project_maintainers_recipients(domain, action: 'succeeded').each do |recipient| + project_maintainers_recipients(domain, action: "succeeded").each do |recipient| mailer.pages_domain_verification_succeeded_email(domain, recipient.user).deliver_later end end def pages_domain_verification_failed(domain) - project_maintainers_recipients(domain, action: 'failed').each do |recipient| + project_maintainers_recipients(domain, action: "failed").each do |recipient| mailer.pages_domain_verification_failed_email(domain, recipient.user).deliver_later end end def pages_domain_enabled(domain) - project_maintainers_recipients(domain, action: 'enabled').each do |recipient| + project_maintainers_recipients(domain, action: "enabled").each do |recipient| mailer.pages_domain_enabled_email(domain, recipient.user).deliver_later end end def pages_domain_disabled(domain) - project_maintainers_recipients(domain, action: 'disabled').each do |recipient| + project_maintainers_recipients(domain, action: "disabled").each do |recipient| mailer.pages_domain_disabled_email(domain, recipient.user).deliver_later end end @@ -457,7 +458,7 @@ class NotificationService recipients = NotificationRecipientService.build_recipients( issue, issue.author, - action: 'due', + action: "due", custom_action: :issue_due, skip_current_user: false ) @@ -476,7 +477,7 @@ class NotificationService end def remote_mirror_update_failed(remote_mirror) - recipients = project_maintainers_recipients(remote_mirror, action: 'update_failed') + recipients = project_maintainers_recipients(remote_mirror, action: "update_failed") recipients.each do |recipient| mailer.remote_mirror_update_failed_email(remote_mirror.id, recipient.user.id).deliver_later @@ -536,7 +537,7 @@ class NotificationService recipients = NotificationRecipientService.build_recipients( target, current_user, - action: 'removed_milestone' + action: "removed_milestone" ) recipients.each do |recipient| @@ -548,7 +549,7 @@ class NotificationService recipients = NotificationRecipientService.build_recipients( target, current_user, - action: 'changed_milestone' + action: "changed_milestone" ) recipients.each do |recipient| diff --git a/app/services/preview_markdown_service.rb b/app/services/preview_markdown_service.rb index c1655c38095..1e4e2a2c002 100644 --- a/app/services/preview_markdown_service.rb +++ b/app/services/preview_markdown_service.rb @@ -10,14 +10,14 @@ class PreviewMarkdownService < BaseService text: text, users: users, suggestions: suggestions, - commands: commands.join(' ') + commands: commands.join(" ") ) end private def explain_quick_actions(text) - return text, [] unless %w(Issue MergeRequest Commit).include?(commands_target_type) + return text, [] unless %w[Issue MergeRequest Commit].include?(commands_target_type) quick_actions_service = QuickActions::InterpretService.new(project, current_user) quick_actions_service.explain(text, find_commands_target) diff --git a/app/services/projects/after_import_service.rb b/app/services/projects/after_import_service.rb index bbdde4408d2..3d4849bebff 100644 --- a/app/services/projects/after_import_service.rb +++ b/app/services/projects/after_import_service.rb @@ -2,7 +2,7 @@ module Projects class AfterImportService - RESERVED_REF_PREFIXES = Repository::RESERVED_REFS_NAMES.map { |n| File.join('refs', n, '/') } + RESERVED_REF_PREFIXES = Repository::RESERVED_REFS_NAMES.map { |n| File.join("refs", n, "/") } def initialize(project) @project = project @@ -14,7 +14,8 @@ module Projects end rescue Projects::HousekeepingService::LeaseTaken => e Rails.logger.info( - "Could not perform housekeeping for project #{@project.full_path} (#{@project.id}): #{e}") + "Could not perform housekeeping for project #{@project.full_path} (#{@project.id}): #{e}" + ) end private diff --git a/app/services/projects/auto_devops/disable_service.rb b/app/services/projects/auto_devops/disable_service.rb index 6608b3da1a8..a2090023892 100644 --- a/app/services/projects/auto_devops/disable_service.rb +++ b/app/services/projects/auto_devops/disable_service.rb @@ -29,7 +29,7 @@ module Projects # rubocop: enable CodeReuse/ActiveRecord def disable_auto_devops - project.auto_devops_attributes = { enabled: false } + project.auto_devops_attributes = {enabled: false} project.save! end diff --git a/app/services/projects/autocomplete_service.rb b/app/services/projects/autocomplete_service.rb index 3dad90188cf..0dce88302d1 100644 --- a/app/services/projects/autocomplete_service.rb +++ b/app/services/projects/autocomplete_service.rb @@ -4,14 +4,14 @@ module Projects class AutocompleteService < BaseService include LabelsAsHash def issues - IssuesFinder.new(current_user, project_id: project.id, state: 'opened').execute.select([:iid, :title]) + IssuesFinder.new(current_user, project_id: project.id, state: "opened").execute.select([:iid, :title]) end def milestones finder_params = { project_ids: [@project.id], state: :active, - order: { due_date: :asc, title: :asc } + order: {due_date: :asc, title: :asc}, } finder_params[:group_ids] = @project.group.self_and_ancestors.select(:id) if @project.group @@ -20,7 +20,7 @@ module Projects end def merge_requests - MergeRequestsFinder.new(current_user, project_id: project.id, state: 'opened').execute.select([:iid, :title]) + MergeRequestsFinder.new(current_user, project_id: project.id, state: "opened").execute.select([:iid, :title]) end def commands(noteable, type) diff --git a/app/services/projects/base_move_relations_service.rb b/app/services/projects/base_move_relations_service.rb index 24dec1f3a45..27913105e8d 100644 --- a/app/services/projects/base_move_relations_service.rb +++ b/app/services/projects/base_move_relations_service.rb @@ -18,7 +18,7 @@ module Projects if Gitlab::Database.postgresql? relation else - relation.model.where("#{id_param}": relation.pluck(id_param)) + relation.model.where(:"#{id_param}" => relation.pluck(id_param)) end end # rubocop: enable CodeReuse/ActiveRecord diff --git a/app/services/projects/batch_count_service.rb b/app/services/projects/batch_count_service.rb index aec3b32da89..228d2208a82 100644 --- a/app/services/projects/batch_count_service.rb +++ b/app/services/projects/batch_count_service.rb @@ -23,11 +23,11 @@ module Projects end def global_count(project) - raise NotImplementedError, 'global_count must be implemented and return an hash indexed by the project id' + raise NotImplementedError, "global_count must be implemented and return an hash indexed by the project id" end def count_service - raise NotImplementedError, 'count_service must be implemented and return a Projects::CountService object' + raise NotImplementedError, "count_service must be implemented and return a Projects::CountService object" end end end diff --git a/app/services/projects/batch_forks_count_service.rb b/app/services/projects/batch_forks_count_service.rb index 6467744a435..33f6fb67059 100644 --- a/app/services/projects/batch_forks_count_service.rb +++ b/app/services/projects/batch_forks_count_service.rb @@ -9,8 +9,8 @@ module Projects def global_count @global_count ||= begin count_service.query(project_ids) - .group(:forked_from_project_id) - .count + .group(:forked_from_project_id) + .count end end # rubocop: enable CodeReuse/ActiveRecord diff --git a/app/services/projects/container_repository/cleanup_tags_service.rb b/app/services/projects/container_repository/cleanup_tags_service.rb index 488290db824..638d9ebde57 100644 --- a/app/services/projects/container_repository/cleanup_tags_service.rb +++ b/app/services/projects/container_repository/cleanup_tags_service.rb @@ -4,8 +4,8 @@ module Projects module ContainerRepository class CleanupTagsService < BaseService def execute(container_repository) - return error('feature disabled') unless can_use? - return error('access denied') unless can_admin? + return error("feature disabled") unless can_use? + return error("access denied") unless can_admin? tags = container_repository.tags tags_by_digest = group_by_digest(tags) @@ -25,9 +25,9 @@ module Projects private def delete_tags(tags_to_delete, tags_by_digest) - deleted_digests = group_by_digest(tags_to_delete).select do |digest, tags| + deleted_digests = group_by_digest(tags_to_delete).select { |digest, tags| delete_tag_digest(digest, tags, tags_by_digest[digest]) - end + } deleted_digests.values.flatten end @@ -61,7 +61,7 @@ module Projects end def filter_by_name(tags) - regex = Gitlab::UntrustedRegexp.new("\\A#{params['name_regex']}\\z") + regex = Gitlab::UntrustedRegexp.new("\\A#{params["name_regex"]}\\z") tags.select do |tag| regex.scan(tag.name).any? @@ -69,13 +69,13 @@ module Projects end def filter_keep_n(tags) - tags.drop(params['keep_n'].to_i) + tags.drop(params["keep_n"].to_i) end def filter_by_older_than(tags) - return tags unless params['older_than'] + return tags unless params["older_than"] - older_than = ChronicDuration.parse(params['older_than']).seconds.ago + older_than = ChronicDuration.parse(params["older_than"]).seconds.ago tags.select do |tag| tag.created_at && tag.created_at < older_than diff --git a/app/services/projects/count_service.rb b/app/services/projects/count_service.rb index 3cee80c7bbc..28072bc9ce0 100644 --- a/app/services/projects/count_service.rb +++ b/app/services/projects/count_service.rb @@ -27,7 +27,7 @@ module Projects def cache_key(key = nil) cache_key = key || cache_key_name - ['projects', 'count_service', VERSION, @project.id, cache_key] + ["projects", "count_service", VERSION, @project.id, cache_key] end def self.query(project_ids) diff --git a/app/services/projects/create_service.rb b/app/services/projects/create_service.rb index d03137b63b2..8ea65d00a06 100644 --- a/app/services/projects/create_service.rb +++ b/app/services/projects/create_service.rb @@ -61,7 +61,7 @@ module Projects message = "Unable to save #{e.record.type}: #{e.record.errors.full_messages.join(", ")} " fail(error: message) rescue => e - @project.errors.add(:base, e.message) if @project + @project&.errors&.add(:base, e.message) fail(error: e.message) end @@ -114,10 +114,10 @@ module Projects def create_readme commit_attrs = { - branch_name: 'master', - commit_message: 'Initial commit', - file_path: 'README.md', - file_content: "# #{@project.name}\n\n#{@project.description}" + branch_name: "master", + commit_message: "Initial commit", + file_path: "README.md", + file_content: "# #{@project.name}\n\n#{@project.description}", } Files::CreateService.new(@project, current_user, commit_attrs).execute @@ -142,7 +142,7 @@ module Projects end unless @project.import? - raise 'Failed to create repository' unless @project.create_repository + raise "Failed to create repository" unless @project.create_repository end end end @@ -191,7 +191,7 @@ module Projects if @project.errors.empty? @project.import_state.schedule if @project.import? && !@project.bare_repository_import? else - fail(error: @project.errors.full_messages.join(', ')) + fail(error: @project.errors.full_messages.join(", ")) end end end diff --git a/app/services/projects/destroy_service.rb b/app/services/projects/destroy_service.rb index b14b31302f5..fd787993fc9 100644 --- a/app/services/projects/destroy_service.rb +++ b/app/services/projects/destroy_service.rb @@ -6,7 +6,7 @@ module Projects DestroyError = Class.new(StandardError) - DELETED_FLAG = '+deleted'.freeze + DELETED_FLAG = "+deleted" REPO_REMOVAL_DELAY = 5.minutes.to_i def async_execute @@ -61,11 +61,11 @@ module Projects flush_caches(@project) unless rollback_repository(removal_path(repo_path), repo_path) - raise_error('Failed to restore project repository. Please contact the administrator.') + raise_error("Failed to restore project repository. Please contact the administrator.") end unless rollback_repository(removal_path(wiki_path), wiki_path) - raise_error('Failed to restore wiki repository. Please contact the administrator.') + raise_error("Failed to restore wiki repository. Please contact the administrator.") end end @@ -81,11 +81,11 @@ module Projects def trash_repositories! unless remove_repository(repo_path) - raise_error('Failed to remove project repository. Please try again or contact administrator.') + raise_error("Failed to remove project repository. Please try again or contact administrator.") end unless remove_repository(wiki_path) - raise_error('Failed to remove wiki repository. Please try again or contact administrator.') + raise_error("Failed to remove wiki repository. Please try again or contact administrator.") end end @@ -96,10 +96,10 @@ module Projects new_path = removal_path(path) if mv_repository(path, new_path) - log_info(%Q{Repository "#{path}" moved to "#{new_path}" for project "#{project.full_path}"}) + log_info(%(Repository "#{path}" moved to "#{new_path}" for project "#{project.full_path}")) project.run_after_commit do - GitlabShellWorker.perform_in(REPO_REMOVAL_DELAY, :remove_repository, self.repository_storage, new_path) + GitlabShellWorker.perform_in(REPO_REMOVAL_DELAY, :remove_repository, repository_storage, new_path) end else false @@ -125,7 +125,7 @@ module Projects # rubocop: disable CodeReuse/ActiveRecord def repo_exists?(path) - gitlab_shell.exists?(project.repository_storage, path + '.git') + gitlab_shell.exists?(project.repository_storage, path + ".git") end # rubocop: enable CodeReuse/ActiveRecord @@ -148,7 +148,7 @@ module Projects def attempt_destroy_transaction(project) unless remove_registry_tags - raise_error('Failed to remove some tags in project container registry. Please try again or contact administrator.') + raise_error("Failed to remove some tags in project container registry. Please try again or contact administrator.") end project.leave_pool_repository diff --git a/app/services/projects/detect_repository_languages_service.rb b/app/services/projects/detect_repository_languages_service.rb index 4a837a4fb6a..ff469f001e4 100644 --- a/app/services/projects/detect_repository_languages_service.rb +++ b/app/services/projects/detect_repository_languages_service.rb @@ -39,9 +39,9 @@ module Projects return existing_languages if detection.languages.size == existing_languages.size missing_languages = detection.languages - existing_languages.map(&:name) - created_languages = missing_languages.map do |name| + created_languages = missing_languages.map { |name| create_language(name, detection.language_color(name)) - end + } existing_languages + created_languages end diff --git a/app/services/projects/download_service.rb b/app/services/projects/download_service.rb index dd297c9ba43..060007b4bf2 100644 --- a/app/services/projects/download_service.rb +++ b/app/services/projects/download_service.rb @@ -3,7 +3,7 @@ module Projects class DownloadService < BaseService WHITELIST = [ - /^[^.]+\.fogbugz.com$/ + /^[^.]+\.fogbugz.com$/, ].freeze def initialize(project, url) @@ -27,7 +27,7 @@ module Projects end def http?(url) - url =~ /\A#{URI.regexp(%w(http https))}\z/ + url =~ /\A#{URI.regexp(%w[http https])}\z/ end def valid_domain?(url) diff --git a/app/services/projects/fetch_statistics_increment_service.rb b/app/services/projects/fetch_statistics_increment_service.rb index 8644e6bf313..e2525d55361 100644 --- a/app/services/projects/fetch_statistics_increment_service.rb +++ b/app/services/projects/fetch_statistics_increment_service.rb @@ -15,10 +15,10 @@ module Projects SQL increment_fetch_count_sql += if Gitlab::Database.postgresql? - "ON CONFLICT (project_id, date) DO UPDATE SET fetch_count = #{table_name}.fetch_count + 1" - else - "ON DUPLICATE KEY UPDATE fetch_count = #{table_name}.fetch_count + 1" - end + "ON CONFLICT (project_id, date) DO UPDATE SET fetch_count = #{table_name}.fetch_count + 1" + else + "ON DUPLICATE KEY UPDATE fetch_count = #{table_name}.fetch_count + 1" + end ActiveRecord::Base.connection.execute(increment_fetch_count_sql) end diff --git a/app/services/projects/fork_service.rb b/app/services/projects/fork_service.rb index fc234bafc57..16982cafa8a 100644 --- a/app/services/projects/fork_service.rb +++ b/app/services/projects/fork_service.rb @@ -36,18 +36,18 @@ module Projects def fork_new_project new_params = { - visibility_level: allowed_visibility_level, - description: @project.description, - name: target_name, - path: target_path, + visibility_level: allowed_visibility_level, + description: @project.description, + name: target_name, + path: target_path, shared_runners_enabled: @project.shared_runners_enabled, - namespace_id: target_namespace.id, - fork_network: fork_network, + namespace_id: target_namespace.id, + fork_network: fork_network, # We need to assign the fork network membership after the project has # been instantiated to avoid ActiveRecord trying to create it when # initializing the project, as that would cause a foreign key constraint # exception. - relations_block: -> (project) { build_fork_network_member(project) } + relations_block: ->(project) { build_fork_network_member(project) }, } if @project.avatar.present? && @project.avatar.image? @@ -79,7 +79,7 @@ module Projects fork_to_project.build_fork_network_member(forked_from_project: @project, fork_network: fork_network) else - fork_to_project.errors.add(:forked_from_project_id, 'is forbidden') + fork_to_project.errors.add(:forked_from_project_id, "is forbidden") end end diff --git a/app/services/projects/forks_count_service.rb b/app/services/projects/forks_count_service.rb index ca85e2dc281..2807ee1555e 100644 --- a/app/services/projects/forks_count_service.rb +++ b/app/services/projects/forks_count_service.rb @@ -4,7 +4,7 @@ module Projects # Service class for getting and caching the number of forks of a project. class ForksCountService < Projects::CountService def cache_key_name - 'forks_count' + "forks_count" end # rubocop: disable CodeReuse/ActiveRecord diff --git a/app/services/projects/gitlab_projects_import_service.rb b/app/services/projects/gitlab_projects_import_service.rb index a315adf42f0..5141e298e06 100644 --- a/app/services/projects/gitlab_projects_import_service.rb +++ b/app/services/projects/gitlab_projects_import_service.rb @@ -62,10 +62,10 @@ module Projects end if template_file - params[:import_type] = 'gitlab_project' + params[:import_type] = "gitlab_project" end - params[:import_data] = { data: data } if data.present? + params[:import_data] = {data: data} if data.present? end end end diff --git a/app/services/projects/hashed_storage/migrate_repository_service.rb b/app/services/projects/hashed_storage/migrate_repository_service.rb index 9c672283c7e..f1d48d140dc 100644 --- a/app/services/projects/hashed_storage/migrate_repository_service.rb +++ b/app/services/projects/hashed_storage/migrate_repository_service.rb @@ -15,7 +15,7 @@ module Projects result = move_repository(old_disk_path, new_disk_path) if move_wiki - result &&= move_repository("#{old_wiki_disk_path}", "#{new_disk_path}.wiki") + result &&= move_repository(old_wiki_disk_path.to_s, "#{new_disk_path}.wiki") end if result diff --git a/app/services/projects/import_error_filter.rb b/app/services/projects/import_error_filter.rb index a0fc5149bb4..1b04468777e 100644 --- a/app/services/projects/import_error_filter.rb +++ b/app/services/projects/import_error_filter.rb @@ -5,7 +5,7 @@ module Projects # included in an error message that could be stored in the DB class ImportErrorFilter ERROR_MESSAGE_FILTER = /[^\s]*#{File::SEPARATOR}[^\s]*(?=(\s|\z))/ - FILTER_MESSAGE = '[FILTERED]' + FILTER_MESSAGE = "[FILTERED]" def self.filter_message(message) message.gsub(ERROR_MESSAGE_FILTER, FILTER_MESSAGE) diff --git a/app/services/projects/import_export/export_service.rb b/app/services/projects/import_export/export_service.rb index e3491282a8a..b471fd9ed6b 100644 --- a/app/services/projects/import_export/export_service.rb +++ b/app/services/projects/import_export/export_service.rb @@ -62,7 +62,7 @@ module Projects end def cleanup_and_notify_error - Rails.logger.error("Import/Export - Project #{project.name} with ID: #{project.id} export error - #{@shared.errors.join(', ')}") + Rails.logger.error("Import/Export - Project #{project.name} with ID: #{project.id} export error - #{@shared.errors.join(", ")}") FileUtils.rm_rf(@shared.export_path) @@ -72,7 +72,7 @@ module Projects def cleanup_and_notify_error! cleanup_and_notify_error - raise Gitlab::ImportExport::Error.new(@shared.errors.join(', ')) + raise Gitlab::ImportExport::Error.new(@shared.errors.join(", ")) end def notify_success diff --git a/app/services/projects/import_service.rb b/app/services/projects/import_service.rb index 7214e9efaf6..d720e80f1ad 100644 --- a/app/services/projects/import_service.rb +++ b/app/services/projects/import_service.rb @@ -25,13 +25,13 @@ module Projects success rescue Gitlab::UrlBlocker::BlockedUrlError => e - Gitlab::Sentry.track_acceptable_exception(e, extra: { project_path: project.full_path, importer: project.import_type }) + Gitlab::Sentry.track_acceptable_exception(e, extra: {project_path: project.full_path, importer: project.import_type}) error("Error importing repository #{project.safe_import_url} into #{project.full_path} - #{e.message}") rescue => e message = Projects::ImportErrorFilter.filter_message(e.message) - Gitlab::Sentry.track_acceptable_exception(e, extra: { project_path: project.full_path, importer: project.import_type }) + Gitlab::Sentry.track_acceptable_exception(e, extra: {project_path: project.full_path, importer: project.import_type}) error("Error importing repository #{project.safe_import_url} into #{project.full_path} - #{message}") end @@ -61,28 +61,26 @@ module Projects def create_repository unless project.create_repository - raise Error, 'The repository could not be created.' + raise Error, "The repository could not be created." end end def import_repository - begin - refmap = importer_class.try(:refmap) if has_importer? - - if refmap - project.ensure_repository - project.repository.fetch_as_mirror(project.import_url, refmap: refmap) - else - gitlab_shell.import_project_repository(project) - end - rescue Gitlab::Shell::Error => e - # Expire cache to prevent scenarios such as: - # 1. First import failed, but the repo was imported successfully, so +exists?+ returns true - # 2. Retried import, repo is broken or not imported but +exists?+ still returns true - project.repository.expire_content_cache if project.repository_exists? + refmap = importer_class.try(:refmap) if has_importer? - raise Error, e.message + if refmap + project.ensure_repository + project.repository.fetch_as_mirror(project.import_url, refmap: refmap) + else + gitlab_shell.import_project_repository(project) end + rescue Gitlab::Shell::Error => e + # Expire cache to prevent scenarios such as: + # 1. First import failed, but the repo was imported successfully, so +exists?+ returns true + # 2. Retried import, repo is broken or not imported but +exists?+ still returns true + project.repository.expire_content_cache if project.repository_exists? + + raise Error, e.message end def download_lfs_objects @@ -98,7 +96,7 @@ module Projects lfs_objects_to_download.each do |lfs_download_object| Projects::LfsPointers::LfsDownloadService.new(project, lfs_download_object) - .execute + .execute end rescue => e # Right now, to avoid aborting the importing process, we silently fail @@ -112,7 +110,7 @@ module Projects project.repository.expire_content_cache unless project.gitlab_project_import? unless importer.execute - raise Error, 'The remote data could not be imported.' + raise Error, "The remote data could not be imported." end end diff --git a/app/services/projects/lfs_pointers/lfs_download_link_list_service.rb b/app/services/projects/lfs_pointers/lfs_download_link_list_service.rb index 7998976b00a..2ec7385f190 100644 --- a/app/services/projects/lfs_pointers/lfs_download_link_list_service.rb +++ b/app/services/projects/lfs_pointers/lfs_download_link_list_service.rb @@ -5,7 +5,7 @@ module Projects module LfsPointers class LfsDownloadLinkListService < BaseService - DOWNLOAD_ACTION = 'download'.freeze + DOWNLOAD_ACTION = "download" DownloadLinksError = Class.new(StandardError) DownloadLinkNotFound = Class.new(StandardError) @@ -32,41 +32,39 @@ module Projects def get_download_links(oids) response = Gitlab::HTTP.post(remote_uri, - body: request_body(oids), - headers: headers) + body: request_body(oids), + headers: headers) raise DownloadLinksError, response.message unless response.success? - parse_response_links(response['objects']) + parse_response_links(response["objects"]) end def parse_response_links(objects_response) objects_response.each_with_object([]) do |entry, link_list| - begin - link = entry.dig('actions', DOWNLOAD_ACTION, 'href') + link = entry.dig("actions", DOWNLOAD_ACTION, "href") - raise DownloadLinkNotFound unless link + raise DownloadLinkNotFound unless link - link_list << LfsDownloadObject.new(oid: entry['oid'], - size: entry['size'], - link: add_credentials(link)) - rescue DownloadLinkNotFound, Addressable::URI::InvalidURIError - log_error("Link for Lfs Object with oid #{entry['oid']} not found or invalid.") - end + link_list << LfsDownloadObject.new(oid: entry["oid"], + size: entry["size"], + link: add_credentials(link)) + rescue DownloadLinkNotFound, Addressable::URI::InvalidURIError + log_error("Link for Lfs Object with oid #{entry["oid"]} not found or invalid.") end end def request_body(oids) { operation: DOWNLOAD_ACTION, - objects: oids.map { |oid, size| { oid: oid, size: size } } + objects: oids.map { |oid, size| {oid: oid, size: size} }, }.to_json end def headers { - 'Accept' => LfsRequest::CONTENT_TYPE, - 'Content-Type' => LfsRequest::CONTENT_TYPE + "Accept" => LfsRequest::CONTENT_TYPE, + "Content-Type" => LfsRequest::CONTENT_TYPE, }.freeze end diff --git a/app/services/projects/lfs_pointers/lfs_download_service.rb b/app/services/projects/lfs_pointers/lfs_download_service.rb index 398f00a598d..997ecc7f7ef 100644 --- a/app/services/projects/lfs_pointers/lfs_download_service.rb +++ b/app/services/projects/lfs_pointers/lfs_download_service.rb @@ -49,12 +49,12 @@ module Projects def download_and_save_file!(file) digester = Digest::SHA256.new - response = Gitlab::HTTP.get(lfs_sanitized_url, download_headers) do |fragment| + response = Gitlab::HTTP.get(lfs_sanitized_url, download_headers) { |fragment| digester << fragment file.write(fragment) raise_size_error! if file.size > lfs_size - end + } raise StandardError, "Received error code #{response.code}" unless response.success? @@ -63,10 +63,10 @@ module Projects end def download_headers - { stream_body: true }.tap do |headers| + {stream_body: true}.tap do |headers| if lfs_credentials[:user].present? || lfs_credentials[:password].present? # Using authentication headers in the request - headers[:basic_auth] = { username: lfs_credentials[:user], password: lfs_credentials[:password] } + headers[:basic_auth] = {username: lfs_credentials[:user], password: lfs_credentials[:password]} end end end @@ -74,18 +74,16 @@ module Projects def with_tmp_file create_tmp_storage_dir - File.open(tmp_filename, 'wb') do |file| - begin - yield file - rescue StandardError => e - # If the lfs file is successfully downloaded it will be removed - # when it is added to the project's lfs files. - # Nevertheless if any excetion raises the file would remain - # in the file system. Here we ensure to remove it - File.unlink(file) if File.exist?(file) - - raise e - end + File.open(tmp_filename, "wb") do |file| + yield file + rescue => e + # If the lfs file is successfully downloaded it will be removed + # when it is added to the project's lfs files. + # Nevertheless if any excetion raises the file would remain + # in the file system. Here we ensure to remove it + File.unlink(file) if File.exist?(file) + + raise e end end @@ -98,7 +96,7 @@ module Projects end def tmp_storage_dir - @tmp_storage_dir ||= File.join(storage_dir, 'tmp', 'download') + @tmp_storage_dir ||= File.join(storage_dir, "tmp", "download") end def storage_dir @@ -106,11 +104,11 @@ module Projects end def raise_size_error! - raise SizeError, 'Size mistmatch' + raise SizeError, "Size mistmatch" end def raise_oid_error! - raise OidError, 'Oid mismatch' + raise OidError, "Oid mismatch" end def error(message, http_status = nil) diff --git a/app/services/projects/lfs_pointers/lfs_import_service.rb b/app/services/projects/lfs_pointers/lfs_import_service.rb index 9215fa0a7bf..1e5bda516ea 100644 --- a/app/services/projects/lfs_pointers/lfs_import_service.rb +++ b/app/services/projects/lfs_pointers/lfs_import_service.rb @@ -8,9 +8,9 @@ module Projects class LfsImportService < BaseService include Gitlab::Utils::StrongMemoize - HEAD_REV = 'HEAD'.freeze + HEAD_REV = "HEAD" LFS_ENDPOINT_PATTERN = /^\t?url\s*=\s*(.+)$/.freeze - LFS_BATCH_API_ENDPOINT = '/info/lfs/objects/batch'.freeze + LFS_BATCH_API_ENDPOINT = "/info/lfs/objects/batch" LfsImportError = Class.new(StandardError) @@ -68,13 +68,13 @@ module Projects end end rescue URI::InvalidURIError - raise LfsImportError, 'Invalid URL in .lfsconfig file' + raise LfsImportError, "Invalid URL in .lfsconfig file" end def import_uri @import_uri ||= URI.parse(project.import_url) rescue URI::InvalidURIError - raise LfsImportError, 'Invalid project import URL' + raise LfsImportError, "Invalid project import URL" end def current_endpoint_uri @@ -85,8 +85,8 @@ module Projects def default_endpoint_uri @default_endpoint_uri ||= begin import_uri.dup.tap do |uri| - path = uri.path.gsub(%r(/$), '') - path += '.git' unless path.ends_with?('.git') + path = uri.path.gsub(%r{/$}, "") + path += ".git" unless path.ends_with?(".git") uri.path = path + LFS_BATCH_API_ENDPOINT end end diff --git a/app/services/projects/lfs_pointers/lfs_list_service.rb b/app/services/projects/lfs_pointers/lfs_list_service.rb index 22160017f4f..cbf7d8377ac 100644 --- a/app/services/projects/lfs_pointers/lfs_list_service.rb +++ b/app/services/projects/lfs_pointers/lfs_list_service.rb @@ -4,7 +4,7 @@ module Projects module LfsPointers class LfsListService < BaseService - REV = 'HEAD'.freeze + REV = "HEAD" # Retrieve all lfs blob pointers and returns a hash # with the structure { lfs_file_oid => lfs_file_size } @@ -12,9 +12,9 @@ module Projects return {} unless project&.lfs_enabled? Gitlab::Git::LfsChanges.new(project.repository, REV) - .all_pointers - .map! { |blob| [blob.lfs_oid, blob.lfs_size] } - .to_h + .all_pointers + .map! { |blob| [blob.lfs_oid, blob.lfs_size] } + .to_h end end end diff --git a/app/services/projects/move_access_service.rb b/app/services/projects/move_access_service.rb index 8e2c3ad2f69..78538fb11cc 100644 --- a/app/services/projects/move_access_service.rb +++ b/app/services/projects/move_access_service.rb @@ -9,7 +9,7 @@ module Projects if @project.namespace != source_project.namespace @project.run_after_commit do source_project.namespace.refresh_project_authorizations - self.namespace.refresh_project_authorizations + namespace.refresh_project_authorizations end end diff --git a/app/services/projects/move_deploy_keys_projects_service.rb b/app/services/projects/move_deploy_keys_projects_service.rb index b6a3af8c7b8..7a56e191fb4 100644 --- a/app/services/projects/move_deploy_keys_projects_service.rb +++ b/app/services/projects/move_deploy_keys_projects_service.rb @@ -23,8 +23,8 @@ module Projects # rubocop: disable CodeReuse/ActiveRecord def non_existent_deploy_keys_projects source_project.deploy_keys_projects - .joins(:deploy_key) - .where.not(keys: { fingerprint: @project.deploy_keys.select(:fingerprint) }) + .joins(:deploy_key) + .where.not(keys: {fingerprint: @project.deploy_keys.select(:fingerprint)}) end # rubocop: enable CodeReuse/ActiveRecord diff --git a/app/services/projects/move_project_authorizations_service.rb b/app/services/projects/move_project_authorizations_service.rb index 2985ba89014..c02576fa2b6 100644 --- a/app/services/projects/move_project_authorizations_service.rb +++ b/app/services/projects/move_project_authorizations_service.rb @@ -36,8 +36,8 @@ module Projects # rubocop: disable CodeReuse/ActiveRecord def non_existent_authorization source_project.project_authorizations - .select(:user_id) - .where.not(user: @project.authorized_users) + .select(:user_id) + .where.not(user: @project.authorized_users) end # rubocop: enable CodeReuse/ActiveRecord end diff --git a/app/services/projects/move_project_group_links_service.rb b/app/services/projects/move_project_group_links_service.rb index 36afcd0c503..707c1171e16 100644 --- a/app/services/projects/move_project_group_links_service.rb +++ b/app/services/projects/move_project_group_links_service.rb @@ -37,7 +37,7 @@ module Projects # rubocop: disable CodeReuse/ActiveRecord def non_existent_group_links source_project.project_group_links - .where.not(group_id: group_links_in_target_project) + .where.not(group_id: group_links_in_target_project) end # rubocop: enable CodeReuse/ActiveRecord end diff --git a/app/services/projects/move_project_members_service.rb b/app/services/projects/move_project_members_service.rb index faf389241d2..10991e2f42e 100644 --- a/app/services/projects/move_project_members_service.rb +++ b/app/services/projects/move_project_members_service.rb @@ -36,8 +36,8 @@ module Projects # rubocop: disable CodeReuse/ActiveRecord def non_existent_members source_project.members - .select(:id) - .where.not(user_id: @project.project_members.select(:user_id)) + .select(:id) + .where.not(user_id: @project.project_members.select(:user_id)) end # rubocop: enable CodeReuse/ActiveRecord end diff --git a/app/services/projects/open_issues_count_service.rb b/app/services/projects/open_issues_count_service.rb index ee9884e9042..a9629fac6eb 100644 --- a/app/services/projects/open_issues_count_service.rb +++ b/app/services/projects/open_issues_count_service.rb @@ -7,8 +7,8 @@ module Projects include Gitlab::Utils::StrongMemoize # Cache keys used to store issues count - PUBLIC_COUNT_KEY = 'public_open_issues_count'.freeze - TOTAL_COUNT_KEY = 'total_open_issues_count'.freeze + PUBLIC_COUNT_KEY = "public_open_issues_count" + TOTAL_COUNT_KEY = "total_open_issues_count" def initialize(project, user = nil) @user = user diff --git a/app/services/projects/open_merge_requests_count_service.rb b/app/services/projects/open_merge_requests_count_service.rb index 76ec13952ab..875c5529aa8 100644 --- a/app/services/projects/open_merge_requests_count_service.rb +++ b/app/services/projects/open_merge_requests_count_service.rb @@ -9,7 +9,7 @@ module Projects end def cache_key_name - 'open_merge_requests_count' + "open_merge_requests_count" end end end diff --git a/app/services/projects/overwrite_project_service.rb b/app/services/projects/overwrite_project_service.rb index 696e1b665b2..53f82a8c632 100644 --- a/app/services/projects/overwrite_project_service.rb +++ b/app/services/projects/overwrite_project_service.rb @@ -28,7 +28,7 @@ module Projects private def move_before_destroy_relationships(source_project) - options = { remove_remaining_elements: false } + options = {remove_remaining_elements: false} ::Projects::MoveUsersStarProjectsService.new(@project, @current_user).execute(source_project, options) ::Projects::MoveAccessService.new(@project, @current_user).execute(source_project, options) @@ -47,9 +47,9 @@ module Projects def rename_project(name, path) # Update de project's name and path to the original name/path ::Projects::UpdateService.new(@project, - @current_user, - { name: name, path: path }) - .execute + @current_user, + {name: name, path: path}) + .execute end def attempt_restore_repositories(project) diff --git a/app/services/projects/participants_service.rb b/app/services/projects/participants_service.rb index 7080f388e53..3e0201ae555 100644 --- a/app/services/projects/participants_service.rb +++ b/app/services/projects/participants_service.rb @@ -16,7 +16,7 @@ module Projects end def all_members - [{ username: "all", name: "All Project and Group Members", count: project_members.count }] + [{username: "all", name: "All Project and Group Members", count: project_members.count}] end end end diff --git a/app/services/projects/propagate_service_template.rb b/app/services/projects/propagate_service_template.rb index 633a263af7b..93c696e3923 100644 --- a/app/services/projects/propagate_service_template.rb +++ b/app/services/projects/propagate_service_template.rb @@ -33,12 +33,12 @@ module Projects end def bulk_create_from_template(batch) - service_list = batch.map do |project_id| + service_list = batch.map { |project_id| service_hash.values << project_id - end + } Project.transaction do - bulk_insert_services(service_hash.keys << 'project_id', service_list) + bulk_insert_services(service_hash.keys << "project_id", service_list) run_callbacks(batch) end end @@ -64,8 +64,8 @@ module Projects def bulk_insert_services(columns, values_array) ActiveRecord::Base.connection.execute( <<-SQL.strip_heredoc - INSERT INTO services (#{columns.join(', ')}) - VALUES #{values_array.map { |tuple| "(#{tuple.join(', ')})" }.join(', ')} + INSERT INTO services (#{columns.join(", ")}) + VALUES #{values_array.map { |tuple| "(#{tuple.join(", ")})" }.join(", ")} SQL ) end @@ -74,7 +74,7 @@ module Projects def service_hash @service_hash ||= begin - template_hash = @template.as_json(methods: :type).except('id', 'template', 'project_id') + template_hash = @template.as_json(methods: :type).except("id", "template", "project_id") template_hash.each_with_object({}) do |(key, value), service_hash| value = value.is_a?(Hash) ? value.to_json : value @@ -103,7 +103,7 @@ module Projects end def active_external_wiki? - @template.type == 'ExternalWikiService' + @template.type == "ExternalWikiService" end end end diff --git a/app/services/projects/protect_default_branch_service.rb b/app/services/projects/protect_default_branch_service.rb index 245490791bf..2f5795b9289 100644 --- a/app/services/projects/protect_default_branch_service.rb +++ b/app/services/projects/protect_default_branch_service.rb @@ -28,8 +28,8 @@ module Projects def create_protected_branch params = { name: default_branch, - push_access_levels_attributes: [{ access_level: push_access_level }], - merge_access_levels_attributes: [{ access_level: merge_access_level }] + push_access_levels_attributes: [{access_level: push_access_level}], + merge_access_levels_attributes: [{access_level: merge_access_level}], } # The creator of the project is always allowed to create protected diff --git a/app/services/projects/transfer_service.rb b/app/services/projects/transfer_service.rb index 5da1e39a1fb..e108b846010 100644 --- a/app/services/projects/transfer_service.rb +++ b/app/services/projects/transfer_service.rb @@ -17,11 +17,11 @@ module Projects @new_namespace = new_namespace if @new_namespace.blank? - raise TransferError, 'Please select a new namespace for your project.' + raise TransferError, "Please select a new namespace for your project." end unless allowed_transfer?(current_user, project) - raise TransferError, 'Transfer failed, please contact an admin.' + raise TransferError, "Transfer failed, please contact an admin." end transfer(project) @@ -41,16 +41,16 @@ module Projects def transfer(project) @old_path = project.full_path @old_group = project.group - @new_path = File.join(@new_namespace.try(:full_path) || '', project.path) + @new_path = File.join(@new_namespace.try(:full_path) || "", project.path) @old_namespace = project.namespace - if Project.where(namespace_id: @new_namespace.try(:id)).where('path = ? or name = ?', project.path, project.name).exists? + if Project.where(namespace_id: @new_namespace.try(:id)).where("path = ? or name = ?", project.path, project.name).exists? raise TransferError.new("Project with same name or path in target namespace already exists") end if project.has_container_registry_tags? # We currently don't support renaming repository if it contains tags in container registry - raise TransferError.new('Project cannot be transferred, because tags are present in its container registry') + raise TransferError.new("Project cannot be transferred, because tags are present in its container registry") end attempt_transfer_transaction diff --git a/app/services/projects/unlink_fork_service.rb b/app/services/projects/unlink_fork_service.rb index 1b8a920268f..a41aabcf99d 100644 --- a/app/services/projects/unlink_fork_service.rb +++ b/app/services/projects/unlink_fork_service.rb @@ -15,10 +15,10 @@ module Projects end merge_requests = @project.fork_network - .merge_requests - .opened - .where.not(target_project: @project) - .from_project(@project) + .merge_requests + .opened + .where.not(target_project: @project) + .from_project(@project) merge_requests.each do |mr| ::MergeRequests::CloseService.new(@project, @current_user).execute(mr) diff --git a/app/services/projects/update_pages_configuration_service.rb b/app/services/projects/update_pages_configuration_service.rb index 674071ad92a..66969701c06 100644 --- a/app/services/projects/update_pages_configuration_service.rb +++ b/app/services/projects/update_pages_configuration_service.rb @@ -35,7 +35,7 @@ module Projects domains: pages_domains_config, https_only: project.pages_https_only?, id: project.project_id, - access_control: !project.public_pages? + access_control: !project.public_pages?, } end @@ -47,7 +47,7 @@ module Projects key: domain.key, https_only: project.pages_https_only? && domain.https?, id: project.project_id, - access_control: !project.public_pages? + access_control: !project.public_pages?, } end end @@ -71,16 +71,16 @@ module Projects end def pages_config_file - File.join(pages_path, 'config.json') + File.join(pages_path, "config.json") end def pages_update_file - File.join(::Settings.pages.path, '.update') + File.join(::Settings.pages.path, ".update") end def update_file(file, data) temp_file = "#{file}.#{SecureRandom.hex(16)}" - File.open(temp_file, 'w') do |f| + File.open(temp_file, "w") do |f| f.write(data) end FileUtils.move(temp_file, file, force: true) @@ -95,7 +95,7 @@ module Projects end def read_file(file) - File.open(file, 'r') do |f| + File.open(file, "r") do |f| f.read end rescue diff --git a/app/services/projects/update_pages_service.rb b/app/services/projects/update_pages_service.rb index 5caeb4cfa5f..01f0dd48762 100644 --- a/app/services/projects/update_pages_service.rb +++ b/app/services/projects/update_pages_service.rb @@ -7,11 +7,11 @@ module Projects BLOCK_SIZE = 32.kilobytes MAX_SIZE = 1.terabyte - PUBLIC_DIR = 'public'.freeze + PUBLIC_DIR = "public" # this has to be invalid group name, # as it shares the namespace with groups - TMP_EXTRACT_PATH = '@pages.tmp'.freeze + TMP_EXTRACT_PATH = "@pages.tmp" attr_reader :build @@ -27,8 +27,8 @@ module Projects @status.enqueue! @status.run! - raise InvalidStateError, 'missing pages artifacts' unless build.artifacts? - raise InvalidStateError, 'pages are outdated' unless latest? + raise InvalidStateError, "missing pages artifacts" unless build.artifacts? + raise InvalidStateError, "pages are outdated" unless latest? # Create temporary directory in which we will extract the artifacts make_secure_tmp_dir(tmp_path) do |archive_path| @@ -36,8 +36,8 @@ module Projects # Check if we did extract public directory archive_public_path = File.join(archive_path, PUBLIC_DIR) - raise InvalidStateError, 'pages miss the public folder' unless Dir.exist?(archive_public_path) - raise InvalidStateError, 'pages are outdated' unless latest? + raise InvalidStateError, "pages miss the public folder" unless Dir.exist?(archive_public_path) + raise InvalidStateError, "pages are outdated" unless latest? deploy_page!(archive_public_path) success @@ -71,24 +71,24 @@ module Projects pipeline: build.pipeline, user: build.user, ref: build.ref, - stage: 'deploy', - name: 'pages:deploy' + stage: "deploy", + name: "pages:deploy" ) end def extract_archive!(temp_path) - if artifacts.ends_with?('.zip') + if artifacts.ends_with?(".zip") extract_zip_archive!(temp_path) else - raise InvalidStateError, 'unsupported artifacts format' + raise InvalidStateError, "unsupported artifacts format" end end def extract_zip_archive!(temp_path) - raise InvalidStateError, 'missing artifacts metadata' unless build.artifacts_metadata? + raise InvalidStateError, "missing artifacts metadata" unless build.artifacts_metadata? # Calculate page size after extract - public_entry = build.artifacts_metadata_entry(PUBLIC_DIR + '/', recursive: true) + public_entry = build.artifacts_metadata_entry(PUBLIC_DIR + "/", recursive: true) if public_entry.total_size > max_size raise InvalidStateError, "artifacts for pages are too large: #{public_entry.total_size}" diff --git a/app/services/projects/update_service.rb b/app/services/projects/update_service.rb index 6856009b395..17858dbd1dc 100644 --- a/app/services/projects/update_service.rb +++ b/app/services/projects/update_service.rb @@ -30,7 +30,7 @@ module Projects # rubocop: enable CodeReuse/ActiveRecord def run_auto_devops_pipeline? - return false if project.repository.gitlab_ci_yml || !project.auto_devops&.previous_changes&.include?('enabled') + return false if project.repository.gitlab_ci_yml || !project.auto_devops&.previous_changes&.include?("enabled") project.auto_devops_enabled? end @@ -39,11 +39,11 @@ module Projects def validate! unless valid_visibility_level_change?(project, params[:visibility_level]) - raise ValidationError.new('New visibility level not allowed!') + raise ValidationError.new("New visibility level not allowed!") end if renaming_project_with_container_registry_tags? - raise ValidationError.new('Cannot rename project because it contains container registry tags!') + raise ValidationError.new("Cannot rename project because it contains container registry tags!") end if changing_default_branch? @@ -52,11 +52,11 @@ module Projects end def after_update - todos_features_changes = %w( + todos_features_changes = %w[ issues_access_level merge_requests_access_level repository_access_level - ) + ] project_changed_feature_keys = project.project_feature.previous_changes.keys if project.previous_changes.include?(:visibility_level) && project.private? @@ -66,7 +66,7 @@ module Projects TodosDestroyer::PrivateFeaturesWorker.perform_in(Todo::WAIT_FOR_DELETE, project.id) end - if project.previous_changes.include?('path') + if project.previous_changes.include?("path") after_rename_service(project).execute else system_hook_service.execute_hooks_for(project, :update) @@ -77,7 +77,7 @@ module Projects def after_rename_service(project) # The path slug the project was using, before the rename took place. - path_before = project.previous_changes['path'].first + path_before = project.previous_changes["path"].first AfterRenameService.new(project, path_before: path_before, full_path_before: project.full_path_was) end @@ -88,7 +88,7 @@ module Projects def update_failed! model_errors = project.errors.full_messages.to_sentence - error_message = model_errors.presence || 'Project could not be updated!' + error_message = model_errors.presence || "Project could not be updated!" error(error_message) end @@ -121,7 +121,7 @@ module Projects ProjectWiki.new(project, project.owner).wiki rescue ProjectWiki::CouldNotCreateWikiError log_error("Could not create wiki for #{project.full_name}") - Gitlab::Metrics.counter(:wiki_can_not_be_created_total, 'Counts the times we failed to create a wiki') + Gitlab::Metrics.counter(:wiki_can_not_be_created_total, "Counts the times we failed to create a wiki") end def update_pages_config diff --git a/app/services/prometheus/adapter_service.rb b/app/services/prometheus/adapter_service.rb index 3be958e1613..673799e5f38 100644 --- a/app/services/prometheus/adapter_service.rb +++ b/app/services/prometheus/adapter_service.rb @@ -5,25 +5,21 @@ module Prometheus def initialize(project, deployment_platform = nil) @project = project - @deployment_platform = if deployment_platform - deployment_platform - else - project.deployment_platform - end + @deployment_platform = deployment_platform || project.deployment_platform end attr_reader :deployment_platform, :project def prometheus_adapter @prometheus_adapter ||= if service_prometheus_adapter.can_query? - service_prometheus_adapter - else - cluster_prometheus_adapter - end + service_prometheus_adapter + else + cluster_prometheus_adapter + end end def service_prometheus_adapter - project.find_or_initialize_service('prometheus') + project.find_or_initialize_service("prometheus") end def cluster_prometheus_adapter diff --git a/app/services/protected_branches/access_level_params.rb b/app/services/protected_branches/access_level_params.rb index a7ef573ff0b..06b10fd98c1 100644 --- a/app/services/protected_branches/access_level_params.rb +++ b/app/services/protected_branches/access_level_params.rb @@ -29,7 +29,7 @@ module ProtectedBranches return [] unless access_level - [{ access_level: access_level }] + [{access_level: access_level}] end end end diff --git a/app/services/protected_branches/api_service.rb b/app/services/protected_branches/api_service.rb index 1b13dace5f2..b432728dc75 100644 --- a/app/services/protected_branches/api_service.rb +++ b/app/services/protected_branches/api_service.rb @@ -10,7 +10,7 @@ module ProtectedBranches { name: params[:name], push_access_levels_attributes: AccessLevelParams.new(:push, params).access_levels, - merge_access_levels_attributes: AccessLevelParams.new(:merge, params).access_levels + merge_access_levels_attributes: AccessLevelParams.new(:merge, params).access_levels, } end end diff --git a/app/services/protected_branches/legacy_api_create_service.rb b/app/services/protected_branches/legacy_api_create_service.rb index aef99a860a0..493fd127320 100644 --- a/app/services/protected_branches/legacy_api_create_service.rb +++ b/app/services/protected_branches/legacy_api_create_service.rb @@ -21,8 +21,8 @@ module ProtectedBranches Gitlab::Access::MAINTAINER end - @params.merge!(push_access_levels_attributes: [{ access_level: push_access_level }], - merge_access_levels_attributes: [{ access_level: merge_access_level }]) + @params[:push_access_levels_attributes] = [{access_level: push_access_level}] + @params[:merge_access_levels_attributes] = [{access_level: merge_access_level}] service = ProtectedBranches::CreateService.new(@project, @current_user, @params) service.execute diff --git a/app/services/protected_branches/legacy_api_update_service.rb b/app/services/protected_branches/legacy_api_update_service.rb index 7cb8d41818f..c8f0138f490 100644 --- a/app/services/protected_branches/legacy_api_update_service.rb +++ b/app/services/protected_branches/legacy_api_update_service.rb @@ -18,16 +18,16 @@ module ProtectedBranches case developers_can_push when true - params[:push_access_levels_attributes] = [{ access_level: Gitlab::Access::DEVELOPER }] + params[:push_access_levels_attributes] = [{access_level: Gitlab::Access::DEVELOPER}] when false - params[:push_access_levels_attributes] = [{ access_level: Gitlab::Access::MAINTAINER }] + params[:push_access_levels_attributes] = [{access_level: Gitlab::Access::MAINTAINER}] end case developers_can_merge when true - params[:merge_access_levels_attributes] = [{ access_level: Gitlab::Access::DEVELOPER }] + params[:merge_access_levels_attributes] = [{access_level: Gitlab::Access::DEVELOPER}] when false - params[:merge_access_levels_attributes] = [{ access_level: Gitlab::Access::MAINTAINER }] + params[:merge_access_levels_attributes] = [{access_level: Gitlab::Access::MAINTAINER}] end service = ProtectedBranches::UpdateService.new(project, current_user, params) diff --git a/app/services/quick_actions/interpret_service.rb b/app/services/quick_actions/interpret_service.rb index 5c58caee8cd..9b1e8bd921a 100644 --- a/app/services/quick_actions/interpret_service.rb +++ b/app/services/quick_actions/interpret_service.rb @@ -7,19 +7,19 @@ module QuickActions attr_reader :issuable - SHRUG = '¯\\_(ツ)_/¯'.freeze - TABLEFLIP = '(╯°□°)╯︵ ┻━┻'.freeze + SHRUG = '¯\\_(ツ)_/¯' + TABLEFLIP = "(╯°□°)╯︵ ┻━┻" # Takes an issuable and returns an array of all the available commands # represented with .to_h def available_commands(issuable) @issuable = issuable - self.class.command_definitions.map do |definition| + self.class.command_definitions.map { |definition| next unless definition.available?(self) definition.to_h(self) - end.compact + }.compact end # Takes a text and interprets the commands that are extracted from it. @@ -67,7 +67,7 @@ module QuickActions current_user.can?(:"update_#{issuable.to_ability_name}", issuable) end command :close do - @updates[:state_event] = 'close' + @updates[:state_event] = "close" end desc do @@ -83,11 +83,11 @@ module QuickActions current_user.can?(:"update_#{issuable.to_ability_name}", issuable) end command :reopen do - @updates[:state_event] = 'reopen' + @updates[:state_event] = "reopen" end - desc 'Merge (when the pipeline succeeds)' - explanation 'Merges this merge request when the pipeline succeeds.' + desc "Merge (when the pipeline succeeds)" + explanation "Merges this merge request when the pipeline succeeds." condition do last_diff_sha = params && params[:merge_request_diff_head_sha] issuable.is_a?(MergeRequest) && @@ -98,11 +98,11 @@ module QuickActions @updates[:merge] = params[:merge_request_diff_head_sha] end - desc 'Change title' + desc "Change title" explanation do |title_param| "Changes the title to \"#{title_param}\"." end - params '<New title>' + params "<New title>" condition do issuable.persisted? && current_user.can?(:"update_#{issuable.to_ability_name}", issuable) @@ -111,7 +111,7 @@ module QuickActions @updates[:title] = title_param end - desc 'Assign' + desc "Assign" # rubocop: disable CodeReuse/ActiveRecord explanation do |users| users = issuable.allows_multiple_assignees? ? users : users.take(1) @@ -119,7 +119,7 @@ module QuickActions end # rubocop: enable CodeReuse/ActiveRecord params do - issuable.allows_multiple_assignees? ? '@user1 @user2' : '@user' + issuable.allows_multiple_assignees? ? "@user1 @user2" : "@user" end condition do current_user.can?(:"admin_#{issuable.to_ability_name}", project) @@ -140,18 +140,18 @@ module QuickActions desc do if issuable.allows_multiple_assignees? - 'Remove all or specific assignee(s)' + "Remove all or specific assignee(s)" else - 'Remove assignee' + "Remove assignee" end end explanation do |users = nil| assignees = issuable.assignees assignees &= users if users.present? && issuable.allows_multiple_assignees? - "Removes #{'assignee'.pluralize(assignees.size)} #{assignees.map(&:to_reference).to_sentence}." + "Removes #{"assignee".pluralize(assignees.size)} #{assignees.map(&:to_reference).to_sentence}." end params do - issuable.allows_multiple_assignees? ? '@user1 @user2' : '' + issuable.allows_multiple_assignees? ? "@user1 @user2" : "" end condition do issuable.is_a?(Issuable) && @@ -172,14 +172,14 @@ module QuickActions end end - desc 'Set milestone' + desc "Set milestone" explanation do |milestone| "Sets the milestone to #{milestone.to_reference}." if milestone end params '%"milestone"' condition do current_user.can?(:"admin_#{issuable.to_ability_name}", project) && - find_milestones(project, state: 'active').any? + find_milestones(project, state: "active").any? end parse_params do |milestone_param| extract_references(milestone_param, :milestone).first || @@ -189,7 +189,7 @@ module QuickActions @updates[:milestone_id] = milestone.id if milestone end - desc 'Remove milestone' + desc "Remove milestone" explanation do "Removes #{issuable.milestone.to_reference(format: :name)} milestone." end @@ -203,11 +203,11 @@ module QuickActions @updates[:milestone_id] = nil end - desc 'Add label(s)' + desc "Add label(s)" explanation do |labels_param| labels = find_label_references(labels_param) - "Adds #{labels.join(' ')} #{'label'.pluralize(labels.count)}." if labels.any? + "Adds #{labels.join(" ")} #{"label".pluralize(labels.count)}." if labels.any? end params '~label1 ~"label 2"' condition do @@ -226,13 +226,13 @@ module QuickActions end end - desc 'Remove all or specific label(s)' + desc "Remove all or specific label(s)" explanation do |labels_param = nil| if labels_param.present? labels = find_label_references(labels_param) - "Removes #{labels.join(' ')} #{'label'.pluralize(labels.count)}." if labels.any? + "Removes #{labels.join(" ")} #{"label".pluralize(labels.count)}." if labels.any? else - 'Removes all labels.' + "Removes all labels." end end params '~label1 ~"label 2"' @@ -257,10 +257,10 @@ module QuickActions end end - desc 'Replace all label(s)' + desc "Replace all label(s)" explanation do |labels_param| labels = find_label_references(labels_param) - "Replaces all labels with #{labels.join(' ')} #{'label'.pluralize(labels.count)}." if labels.any? + "Replaces all labels with #{labels.join(" ")} #{"label".pluralize(labels.count)}." if labels.any? end params '~label1 ~"label 2"' condition do @@ -280,11 +280,11 @@ module QuickActions end end - desc 'Copy labels and milestone from other issue or merge request' + desc "Copy labels and milestone from other issue or merge request" explanation do |source_issuable| "Copy labels and milestone from #{source_issuable.to_reference}." end - params '#issue | !merge_request' + params "#issue | !merge_request" condition do [MergeRequest, Issue].include?(issuable.class) && current_user.can?(:"update_#{issuable.to_ability_name}", issuable) @@ -300,28 +300,28 @@ module QuickActions end end - desc 'Add a todo' - explanation 'Adds a todo.' + desc "Add a todo" + explanation "Adds a todo." condition do issuable.is_a?(Issuable) && issuable.persisted? && !TodoService.new.todo_exist?(issuable, current_user) end command :todo do - @updates[:todo_event] = 'add' + @updates[:todo_event] = "add" end - desc 'Mark todo as done' - explanation 'Marks todo as done.' + desc "Mark todo as done" + explanation "Marks todo as done." condition do issuable.persisted? && TodoService.new.todo_exist?(issuable, current_user) end command :done do - @updates[:todo_event] = 'done' + @updates[:todo_event] = "done" end - desc 'Subscribe' + desc "Subscribe" explanation do "Subscribes to this #{issuable.to_ability_name.humanize(capitalize: false)}." end @@ -331,10 +331,10 @@ module QuickActions !issuable.subscribed?(current_user, project) end command :subscribe do - @updates[:subscription_event] = 'subscribe' + @updates[:subscription_event] = "subscribe" end - desc 'Unsubscribe' + desc "Unsubscribe" explanation do "Unsubscribes from this #{issuable.to_ability_name.humanize(capitalize: false)}." end @@ -344,14 +344,14 @@ module QuickActions issuable.subscribed?(current_user, project) end command :unsubscribe do - @updates[:subscription_event] = 'unsubscribe' + @updates[:subscription_event] = "unsubscribe" end - desc 'Set due date' + desc "Set due date" explanation do |due_date| "Sets the due date to #{due_date.to_s(:medium)}." if due_date end - params '<in 2 days | this Friday | December 31st>' + params "<in 2 days | this Friday | December 31st>" condition do issuable.respond_to?(:due_date) && current_user.can?(:"admin_#{issuable.to_ability_name}", project) @@ -363,8 +363,8 @@ module QuickActions @updates[:due_date] = due_date if due_date end - desc 'Remove due date' - explanation 'Removes the due date.' + desc "Remove due date" + explanation "Removes the due date." condition do issuable.persisted? && issuable.respond_to?(:due_date) && @@ -375,9 +375,9 @@ module QuickActions @updates[:due_date] = nil end - desc 'Toggle the Work In Progress status' + desc "Toggle the Work In Progress status" explanation do - verb = issuable.work_in_progress? ? 'Unmarks' : 'Marks' + verb = issuable.work_in_progress? ? "Unmarks" : "Marks" noun = issuable.to_ability_name.humanize(capitalize: false) "#{verb} this #{noun} as Work In Progress." end @@ -387,14 +387,14 @@ module QuickActions (issuable.new_record? || current_user.can?(:"update_#{issuable.to_ability_name}", issuable)) end command :wip do - @updates[:wip_event] = issuable.work_in_progress? ? 'unwip' : 'wip' + @updates[:wip_event] = issuable.work_in_progress? ? "unwip" : "wip" end - desc 'Toggle emoji award' + desc "Toggle emoji award" explanation do |name| "Toggles :#{name}: emoji award." if name end - params ':emoji:' + params ":emoji:" condition do issuable.is_a?(Issuable) && issuable.persisted? @@ -409,13 +409,13 @@ module QuickActions end end - desc 'Set time estimate' + desc "Set time estimate" explanation do |time_estimate| time_estimate = Gitlab::TimeTrackingFormatter.output(time_estimate) "Sets time estimate to #{time_estimate}." if time_estimate end - params '<1w 3d 2h 14m>' + params "<1w 3d 2h 14m>" condition do current_user.can?(:"admin_#{issuable.to_ability_name}", project) end @@ -428,21 +428,21 @@ module QuickActions end end - desc 'Add or subtract spent time' + desc "Add or subtract spent time" explanation do |time_spent, time_spent_date| if time_spent if time_spent > 0 - verb = 'Adds' + verb = "Adds" value = time_spent else - verb = 'Subtracts' + verb = "Subtracts" value = -time_spent end "#{verb} #{Gitlab::TimeTrackingFormatter.output(value)} spent time." end end - params '<time(1h30m | -1h30m)> <date(YYYY-MM-DD)>' + params "<time(1h30m | -1h30m)> <date(YYYY-MM-DD)>" condition do issuable.is_a?(TimeTrackable) && current_user.can?(:"admin_#{issuable.to_ability_name}", issuable) @@ -455,13 +455,13 @@ module QuickActions @updates[:spend_time] = { duration: time_spent, user_id: current_user.id, - spent_at: time_spent_date + spent_at: time_spent_date, } end end - desc 'Remove time estimate' - explanation 'Removes time estimate.' + desc "Remove time estimate" + explanation "Removes time estimate." condition do issuable.persisted? && current_user.can?(:"admin_#{issuable.to_ability_name}", project) @@ -470,24 +470,24 @@ module QuickActions @updates[:time_estimate] = 0 end - desc 'Remove spent time' - explanation 'Removes spent time.' + desc "Remove spent time" + explanation "Removes spent time." condition do issuable.persisted? && current_user.can?(:"admin_#{issuable.to_ability_name}", project) end command :remove_time_spent do - @updates[:spend_time] = { duration: :reset, user_id: current_user.id } + @updates[:spend_time] = {duration: :reset, user_id: current_user.id} end desc "Append the comment with #{SHRUG}" - params '<Comment>' + params "<Comment>" substitution :shrug do |comment| "#{comment} #{SHRUG}" end desc "Append the comment with #{TABLEFLIP}" - params '<Comment>' + params "<Comment>" substitution :tableflip do |comment| "#{comment} #{TABLEFLIP}" end @@ -517,15 +517,15 @@ module QuickActions end # This is a dummy command, so that it appears in the autocomplete commands - desc 'CC' - params '@user' + desc "CC" + params "@user" command :cc - desc 'Set target branch' + desc "Set target branch" explanation do |branch_name| "Sets target branch to #{branch_name}." end - params '<Local branch name>' + params "<Local branch name>" condition do issuable.respond_to?(:target_branch) && (current_user.can?(:"update_#{issuable.to_ability_name}", issuable) || @@ -538,7 +538,7 @@ module QuickActions @updates[:target_branch] = branch_name if project.repository.branch_exists?(branch_name) end - desc 'Move issue from one column of the board to another' + desc "Move issue from one column of the board to another" explanation do |target_list_name| label = find_label_references(target_list_name).first "Moves issue to #{label} column in the board." if label @@ -566,11 +566,11 @@ module QuickActions end # rubocop: enable CodeReuse/ActiveRecord - desc 'Mark this issue as a duplicate of another issue' + desc "Mark this issue as a duplicate of another issue" explanation do |duplicate_reference| "Marks this issue as a duplicate of #{duplicate_reference}." end - params '#issue' + params "#issue" condition do issuable.is_a?(Issue) && issuable.persisted? && @@ -584,11 +584,11 @@ module QuickActions end end - desc 'Move this issue to another project.' + desc "Move this issue to another project." explanation do |path_to_project| "Moves this issue to #{path_to_project}." end - params 'path/to/project' + params "path/to/project" condition do issuable.is_a?(Issue) && issuable.persisted? && @@ -602,9 +602,9 @@ module QuickActions end end - desc 'Make issue confidential.' + desc "Make issue confidential." explanation do - 'Makes this issue confidential' + "Makes this issue confidential" end condition do issuable.is_a?(Issue) && current_user.can?(:"admin_#{issuable.to_ability_name}", issuable) @@ -613,14 +613,14 @@ module QuickActions @updates[:confidential] = true end - desc 'Tag this commit.' + desc "Tag this commit." explanation do |tag_name, message| - with_message = %{ with "#{message}"} if message.present? + with_message = %( with "#{message}") if message.present? "Tags this commit to #{tag_name}#{with_message}." end - params 'v1.2.3 <message>' + params "v1.2.3 <message>" parse_params do |tag_name_and_message| - tag_name_and_message.split(' ', 2) + tag_name_and_message.split(" ", 2) end condition do issuable.is_a?(Commit) && current_user.can?(:push_code, project) @@ -630,9 +630,9 @@ module QuickActions @updates[:tag_message] = message end - desc 'Create a merge request.' + desc "Create a merge request." explanation do |branch_name = nil| - branch_text = branch_name ? "branch '#{branch_name}'" : 'a branch' + branch_text = branch_name ? "branch '#{branch_name}'" : "a branch" "Creates #{branch_text} and a merge request to resolve this issue" end params "<branch name>" @@ -642,7 +642,7 @@ module QuickActions command :create_merge_request do |branch_name = nil| @updates[:create_merge_request] = { branch_name: branch_name, - issue_iid: issuable.iid + issue_iid: issuable.iid, } end @@ -654,10 +654,10 @@ module QuickActions if users.empty? users = - if params.strip == 'me' + if params.strip == "me" [current_user] else - User.where(username: params.split(' ').map(&:strip)) + User.where(username: params.split(" ").map(&:strip)) end end @@ -680,7 +680,7 @@ module QuickActions end def find_labels(labels_params = nil) - finder_params = { include_ancestor_groups: true } + finder_params = {include_ancestor_groups: true} finder_params[:project_id] = project.id if project finder_params[:group_id] = group.id if group finder_params[:name] = labels_params.split if labels_params @@ -699,12 +699,12 @@ module QuickActions end def explain_commands(commands) - commands.map do |name, arg| + commands.map { |name, arg| definition = self.class.definition_by_name(name) next unless definition definition.explain(self, arg) - end.compact + }.compact end def extract_updates(commands) diff --git a/app/services/quick_actions/target_service.rb b/app/services/quick_actions/target_service.rb index 69464c3c1ae..798ce95df92 100644 --- a/app/services/quick_actions/target_service.rb +++ b/app/services/quick_actions/target_service.rb @@ -4,11 +4,11 @@ module QuickActions class TargetService < BaseService def execute(type, type_id) case type&.downcase - when 'issue' + when "issue" issue(type_id) - when 'mergerequest' + when "mergerequest" merge_request(type_id) - when 'commit' + when "commit" commit(type_id) end end diff --git a/app/services/releases/create_service.rb b/app/services/releases/create_service.rb index c6e143d440d..0e042ae2756 100644 --- a/app/services/releases/create_service.rb +++ b/app/services/releases/create_service.rb @@ -5,8 +5,8 @@ module Releases include Releases::Concerns def execute - return error('Access Denied', 403) unless allowed? - return error('Release already exists', 409) if release + return error("Access Denied", 403) unless allowed? + return error("Release already exists", 409) if release tag = ensure_tag @@ -22,7 +22,7 @@ module Releases end def create_tag - return error('Ref is not specified', 422) unless ref + return error("Ref is not specified", 422) unless ref result = Tags::CreateService .new(project, current_user) @@ -44,7 +44,7 @@ module Releases author: current_user, tag: tag.name, sha: tag.dereferenced_target.sha, - links_attributes: params.dig(:assets, 'links') || [] + links_attributes: params.dig(:assets, "links") || [] ) success(tag: tag, release: release) diff --git a/app/services/releases/destroy_service.rb b/app/services/releases/destroy_service.rb index 8c2bc3b4e6e..85b0c4801a2 100644 --- a/app/services/releases/destroy_service.rb +++ b/app/services/releases/destroy_service.rb @@ -5,14 +5,14 @@ module Releases include Releases::Concerns def execute - return error('Tag does not exist', 404) unless existing_tag - return error('Release does not exist', 404) unless release - return error('Access Denied', 403) unless allowed? + return error("Tag does not exist", 404) unless existing_tag + return error("Release does not exist", 404) unless release + return error("Access Denied", 403) unless allowed? if release.destroy success(tag: existing_tag, release: release) else - error(release.errors.messages || '400 Bad request', 400) + error(release.errors.messages || "400 Bad request", 400) end end diff --git a/app/services/releases/update_service.rb b/app/services/releases/update_service.rb index fabfa398c59..f90e94667c4 100644 --- a/app/services/releases/update_service.rb +++ b/app/services/releases/update_service.rb @@ -5,15 +5,15 @@ module Releases include Releases::Concerns def execute - return error('Tag does not exist', 404) unless existing_tag - return error('Release does not exist', 404) unless release - return error('Access Denied', 403) unless allowed? - return error('params is empty', 400) if empty_params? + return error("Tag does not exist", 404) unless existing_tag + return error("Release does not exist", 404) unless release + return error("Access Denied", 403) unless allowed? + return error("params is empty", 400) if empty_params? if release.update(params) success(tag: existing_tag, release: release) else - error(release.errors.messages || '400 Bad request', 400) + error(release.errors.messages || "400 Bad request", 400) end end diff --git a/app/services/repository_archive_clean_up_service.rb b/app/services/repository_archive_clean_up_service.rb index 99a9c834352..b099bb1237e 100644 --- a/app/services/repository_archive_clean_up_service.rb +++ b/app/services/repository_archive_clean_up_service.rb @@ -22,12 +22,12 @@ class RepositoryArchiveCleanUpService private def clean_up_old_archives - run(%W(find #{path} -mindepth 1 -maxdepth 3 -type f \( -name \*.tar -o -name \*.bz2 -o -name \*.tar.gz -o -name \*.zip \) -mmin +#{mmin} -delete)) + run(%W[find #{path} -mindepth 1 -maxdepth 3 -type f \( -name \*.tar -o -name \*.bz2 -o -name \*.tar.gz -o -name \*.zip \) -mmin +#{mmin} -delete]) end def clean_up_empty_directories - run(%W(find #{path} -mindepth 2 -maxdepth 2 -type d -empty -delete)) - run(%W(find #{path} -mindepth 1 -maxdepth 1 -type d -empty -delete)) + run(%W[find #{path} -mindepth 2 -maxdepth 2 -type d -empty -delete]) + run(%W[find #{path} -mindepth 1 -maxdepth 1 -type d -empty -delete]) end def run(cmd) diff --git a/app/services/resource_events/change_labels_service.rb b/app/services/resource_events/change_labels_service.rb index 039d6e2ebad..ccef073f84f 100644 --- a/app/services/resource_events/change_labels_service.rb +++ b/app/services/resource_events/change_labels_service.rb @@ -11,16 +11,16 @@ module ResourceEvents def execute(added_labels: [], removed_labels: []) label_hash = { resource_column(resource) => resource.id, - user_id: user.id, - created_at: Time.now + :user_id => user.id, + :created_at => Time.now, } - labels = added_labels.map do |label| - label_hash.merge(label_id: label.id, action: ResourceLabelEvent.actions['add']) - end - labels += removed_labels.map do |label| - label_hash.merge(label_id: label.id, action: ResourceLabelEvent.actions['remove']) - end + labels = added_labels.map { |label| + label_hash.merge(label_id: label.id, action: ResourceLabelEvent.actions["add"]) + } + labels += removed_labels.map { |label| + label_hash.merge(label_id: label.id, action: ResourceLabelEvent.actions["remove"]) + } Gitlab::Database.bulk_insert(ResourceLabelEvent.table_name, labels) resource.expire_note_etag_cache diff --git a/app/services/search/global_service.rb b/app/services/search/global_service.rb index d6af26d949d..fe8d6e57f6d 100644 --- a/app/services/search/global_service.rb +++ b/app/services/search/global_service.rb @@ -14,7 +14,7 @@ module Search def execute Gitlab::SearchResults.new(current_user, projects, params[:search], - default_project_filter: default_project_filter) + default_project_filter: default_project_filter) end def projects @@ -29,7 +29,7 @@ module Search def scope strong_memoize(:scope) do - allowed_scopes.include?(params[:scope]) ? params[:scope] : 'projects' + allowed_scopes.include?(params[:scope]) ? params[:scope] : "projects" end end end diff --git a/app/services/search/project_service.rb b/app/services/search/project_service.rb index f223c8be103..2ec99c290ef 100644 --- a/app/services/search/project_service.rb +++ b/app/services/search/project_service.rb @@ -10,13 +10,13 @@ module Search def execute Gitlab::ProjectSearchResults.new(current_user, - project, - params[:search], - params[:repository_ref]) + project, + params[:search], + params[:repository_ref]) end def scope - @scope ||= %w[notes issues merge_requests milestones wiki_blobs commits].delete(params[:scope]) { 'blobs' } + @scope ||= %w[notes issues merge_requests milestones wiki_blobs commits].delete(params[:scope]) { "blobs" } end end end diff --git a/app/services/search/snippet_service.rb b/app/services/search/snippet_service.rb index e899a36f468..3e9b54b595f 100644 --- a/app/services/search/snippet_service.rb +++ b/app/services/search/snippet_service.rb @@ -15,7 +15,7 @@ module Search end def scope - @scope ||= %w[snippet_titles].delete(params[:scope]) { 'snippet_blobs' } + @scope ||= %w[snippet_titles].delete(params[:scope]) { "snippet_blobs" } end end end diff --git a/app/services/search_service.rb b/app/services/search_service.rb index e0cbfac2420..f5852628d8f 100644 --- a/app/services/search_service.rb +++ b/app/services/search_service.rb @@ -16,8 +16,6 @@ class SearchService if params[:project_id].present? the_project = Project.find_by(id: params[:project_id]) can?(current_user, :read_project, the_project) ? the_project : nil - else - nil end end # rubocop: enable CodeReuse/ActiveRecord @@ -30,8 +28,6 @@ class SearchService if params[:group_id].present? the_group = Group.find_by(id: params[:group_id]) can?(current_user, :read_group, the_group) ? the_group : nil - else - nil end end # rubocop: enable CodeReuse/ActiveRecord @@ -39,7 +35,7 @@ class SearchService def show_snippets? return @show_snippets if defined?(@show_snippets) - @show_snippets = params[:snippets] == 'true' + @show_snippets = params[:snippets] == "true" end delegate :scope, to: :search_service diff --git a/app/services/spam_service.rb b/app/services/spam_service.rb index f2f133dae28..41d82dc116c 100644 --- a/app/services/spam_service.rb +++ b/app/services/spam_service.rb @@ -10,9 +10,9 @@ class SpamService @options = {} if @request - @options[:ip_address] = @request.env['action_dispatch.remote_ip'].to_s - @options[:user_agent] = @request.env['HTTP_USER_AGENT'] - @options[:referrer] = @request.env['HTTP_REFERRER'] + @options[:ip_address] = @request.env["action_dispatch.remote_ip"].to_s + @options[:user_agent] = @request.env["HTTP_USER_AGENT"] + @options[:referrer] = @request.env["HTTP_REFERRER"] else @options[:ip_address] = @spammable.ip_address @options[:user_agent] = @spammable.user_agent @@ -87,7 +87,7 @@ class SpamService source_ip: options[:ip_address], user_agent: options[:user_agent], noteable_type: spammable.class.to_s, - via_api: api + via_api: api, } ) end diff --git a/app/services/submit_usage_ping_service.rb b/app/services/submit_usage_ping_service.rb index 62222d3fd2a..c98ee9c0989 100644 --- a/app/services/submit_usage_ping_service.rb +++ b/app/services/submit_usage_ping_service.rb @@ -1,7 +1,7 @@ # frozen_string_literal: true class SubmitUsagePingService - URL = 'https://version.gitlab.com/usage_data'.freeze + URL = "https://version.gitlab.com/usage_data" METRICS = %w[leader_issues instance_issues percentage_issues leader_notes instance_notes percentage_notes leader_milestones instance_milestones percentage_milestones @@ -21,7 +21,7 @@ class SubmitUsagePingService URL, body: Gitlab::UsageData.to_json(force_refresh: true), allow_local_requests: true, - headers: { 'Content-type' => 'application/json' } + headers: {"Content-type" => "application/json"} ) store_metrics(response) @@ -36,10 +36,10 @@ class SubmitUsagePingService private def store_metrics(response) - return unless response['conv_index'].present? + return unless response["conv_index"].present? ConversationalDevelopmentIndex::Metric.create!( - response['conv_index'].slice(*METRICS) + response["conv_index"].slice(*METRICS) ) end end diff --git a/app/services/submodules/update_service.rb b/app/services/submodules/update_service.rb index a6011a920bd..803cc5f4744 100644 --- a/app/services/submodules/update_service.rb +++ b/app/services/submodules/update_service.rb @@ -16,23 +16,23 @@ module Submodules def validate! super - raise ValidationError, 'The repository is empty' if repository.empty? + raise ValidationError, "The repository is empty" if repository.empty? end def execute super - rescue StandardError => e + rescue => e error(e.message) end def create_commit! repository.update_submodule(current_user, - @submodule, - @commit_sha, - message: @commit_message, - branch: @branch_name) + @submodule, + @commit_sha, + message: @commit_message, + branch: @branch_name) rescue ArgumentError, TypeError - raise ValidationError, 'Invalid parameters' + raise ValidationError, "Invalid parameters" end end end diff --git a/app/services/suggestions/apply_service.rb b/app/services/suggestions/apply_service.rb index f778c5aa5f5..3b7ea5bc87d 100644 --- a/app/services/suggestions/apply_service.rb +++ b/app/services/suggestions/apply_service.rb @@ -8,17 +8,17 @@ module Suggestions def execute(suggestion) unless suggestion.appliable? - return error('Suggestion is not appliable') + return error("Suggestion is not appliable") end unless latest_source_head?(suggestion) - return error('The file has been changed') + return error("The file has been changed") end diff_file = suggestion.note.latest_diff_file unless diff_file - return error('The file was not found') + return error("The file was not found") end params = file_update_params(suggestion, diff_file) @@ -30,7 +30,7 @@ module Suggestions result rescue Files::UpdateService::FileChangedError - error('The file has been changed') + error("The file has been changed") end private @@ -53,8 +53,8 @@ module Suggestions file_last_commit = Gitlab::Git::Commit.last_for_path(suggestion.project.repository, - blob.commit_id, - blob.path) + blob.commit_id, + blob.path) { file_path: file_path, @@ -62,7 +62,7 @@ module Suggestions start_branch: branch_name, commit_message: commit_message, file_content: file_content, - last_commit_sha: file_last_commit&.id + last_commit_sha: file_last_commit&.id, } end diff --git a/app/services/suggestions/create_service.rb b/app/services/suggestions/create_service.rb index c7ac2452c53..5ba6b83164f 100644 --- a/app/services/suggestions/create_service.rb +++ b/app/services/suggestions/create_service.rb @@ -23,7 +23,7 @@ module Suggestions comment_line = @note.position.new_line rows = - suggestions.map.with_index do |suggestion, index| + suggestions.map.with_index { |suggestion, index| from_content = changing_lines(diff_file, comment_line, comment_line) # The parsed suggestion doesn't have information about the correct @@ -37,12 +37,12 @@ module Suggestions note_id: @note.id, from_content: from_content, to_content: to_content, - relative_order: index + relative_order: index, } - end + } rows.in_groups_of(100, false) do |rows| - Gitlab::Database.bulk_insert('suggestions', rows) + Gitlab::Database.bulk_insert("suggestions", rows) end end diff --git a/app/services/system_hooks_service.rb b/app/services/system_hooks_service.rb index bd3907cdf8e..5e24ee7541a 100644 --- a/app/services/system_hooks_service.rb +++ b/app/services/system_hooks_service.rb @@ -11,7 +11,7 @@ class SystemHooksService def execute_hooks(data, hooks_scope = :all) SystemHook.hooks_for(hooks_scope).find_each do |hook| - hook.async_execute(data, 'system_hooks') + hook.async_execute(data, "system_hooks") end Gitlab::Plugin.execute_all_async(data) @@ -23,15 +23,13 @@ class SystemHooksService data = { event_name: build_event_name(model, event), created_at: model.created_at&.xmlschema, - updated_at: model.updated_at&.xmlschema + updated_at: model.updated_at&.xmlschema, } case model when Key - data.merge!( - key: model.key, - id: model.id - ) + data[:key] = model.key + data[:id] = model.id if model.user data[:username] = model.user.username @@ -57,10 +55,8 @@ class SystemHooksService data.merge!(group_data(model)) if event == :rename - data.merge!( - old_path: model.path_was, - old_full_path: model.full_path_was - ) + data[:old_path] = model.path_was + data[:old_full_path] = model.full_path_was end when GroupMember data.merge!(group_member_data(model)) @@ -75,8 +71,8 @@ class SystemHooksService return "user_add_to_team" if event == :create return "user_remove_from_team" if event == :destroy when GroupMember - return 'user_add_to_group' if event == :create - return 'user_remove_from_group' if event == :destroy + return "user_add_to_group" if event == :create + return "user_remove_from_group" if event == :destroy else "#{model.class.name.downcase}_#{event}" end @@ -92,7 +88,7 @@ class SystemHooksService project_id: model.id, owner_name: owner.name, owner_email: owner.respond_to?(:email) ? owner.email : "", - project_visibility: model.visibility.downcase + project_visibility: model.visibility.downcase, } end @@ -100,16 +96,16 @@ class SystemHooksService project = model.project || Project.unscoped.find(model.source_id) { - project_name: project.name, - project_path: project.path, - project_path_with_namespace: project.full_path, - project_id: project.id, - user_username: model.user.username, - user_name: model.user.name, - user_email: model.user.email, - user_id: model.user.id, - access_level: model.human_access, - project_visibility: Project.visibility_levels.key(project.visibility_level_value).downcase + project_name: project.name, + project_path: project.path, + project_path_with_namespace: project.full_path, + project_id: project.id, + user_username: model.user.username, + user_name: model.user.name, + user_email: model.user.email, + user_id: model.user.id, + access_level: model.human_access, + project_visibility: Project.visibility_levels.key(project.visibility_level_value).downcase, } end @@ -122,7 +118,7 @@ class SystemHooksService full_path: model.full_path, group_id: model.id, owner_name: owner.try(:name), - owner_email: owner.try(:email) + owner_email: owner.try(:email), } end @@ -135,7 +131,7 @@ class SystemHooksService user_name: model.user.name, user_email: model.user.email, user_id: model.user.id, - group_access: model.human_access + group_access: model.human_access, } end @@ -144,7 +140,7 @@ class SystemHooksService name: model.name, email: model.email, user_id: model.id, - username: model.username + username: model.username, } end end diff --git a/app/services/system_note_service.rb b/app/services/system_note_service.rb index ea8ac7e4656..c77bce01f09 100644 --- a/app/services/system_note_service.rb +++ b/app/services/system_note_service.rb @@ -29,7 +29,7 @@ module SystemNoteService body = text_parts.join("\n\n") - create_note(NoteSummary.new(noteable, project, author, body, action: 'commit', commit_count: total_count)) + create_note(NoteSummary.new(noteable, project, author, body, action: "commit", commit_count: total_count)) end # Called when a commit was tagged @@ -44,7 +44,7 @@ module SystemNoteService link = url_helpers.project_tag_url(project, id: tag_name) body = "tagged commit #{noteable.sha} to [`#{tag_name}`](#{link})" - create_note(NoteSummary.new(noteable, project, author, body, action: 'tag')) + create_note(NoteSummary.new(noteable, project, author, body, action: "tag")) end # Called when the assignee of a Noteable is changed or removed @@ -62,9 +62,9 @@ module SystemNoteService # # Returns the created Note object def change_assignee(noteable, project, author, assignee) - body = assignee.nil? ? 'removed assignee' : "assigned to #{assignee.to_reference}" + body = assignee.nil? ? "removed assignee" : "assigned to #{assignee.to_reference}" - create_note(NoteSummary.new(noteable, project, author, body, action: 'assignee')) + create_note(NoteSummary.new(noteable, project, author, body, action: "assignee")) end # Called when the assignees of an Issue is changed or removed @@ -93,9 +93,9 @@ module SystemNoteService text_parts << "assigned to #{added_users.map(&:to_reference).to_sentence}" if added_users.any? text_parts << "unassigned #{unassigned_users.map(&:to_reference).to_sentence}" if unassigned_users.any? - body = text_parts.join(' and ') + body = text_parts.join(" and ") - create_note(NoteSummary.new(issue, project, author, body, action: 'assignee')) + create_note(NoteSummary.new(issue, project, author, body, action: "assignee")) end # Called when the milestone of a Noteable is changed @@ -114,9 +114,9 @@ module SystemNoteService # Returns the created Note object def change_milestone(noteable, project, author, milestone) format = milestone&.group_milestone? ? :name : :iid - body = milestone.nil? ? 'removed milestone' : "changed milestone to #{milestone.to_reference(project, format: format)}" + body = milestone.nil? ? "removed milestone" : "changed milestone to #{milestone.to_reference(project, format: format)}" - create_note(NoteSummary.new(noteable, project, author, body, action: 'milestone')) + create_note(NoteSummary.new(noteable, project, author, body, action: "milestone")) end # Called when the due_date of a Noteable is changed @@ -134,9 +134,9 @@ module SystemNoteService # # Returns the created Note object def change_due_date(noteable, project, author, due_date) - body = due_date ? "changed due date to #{due_date.to_s(:long)}" : 'removed due date' + body = due_date ? "changed due date to #{due_date.to_s(:long)}" : "removed due date" - create_note(NoteSummary.new(noteable, project, author, body, action: 'due_date')) + create_note(NoteSummary.new(noteable, project, author, body, action: "due_date")) end # Called when the estimated time of a Noteable is changed @@ -156,12 +156,12 @@ module SystemNoteService def change_time_estimate(noteable, project, author) parsed_time = Gitlab::TimeTrackingFormatter.output(noteable.time_estimate) body = if noteable.time_estimate == 0 - "removed time estimate" - else - "changed time estimate to #{parsed_time}" - end + "removed time estimate" + else + "changed time estimate to #{parsed_time}" + end - create_note(NoteSummary.new(noteable, project, author, body, action: 'time_tracking')) + create_note(NoteSummary.new(noteable, project, author, body, action: "time_tracking")) end # Called when the spent time of a Noteable is changed @@ -186,14 +186,14 @@ module SystemNoteService else spent_at = noteable.spent_at parsed_time = Gitlab::TimeTrackingFormatter.output(time_spent.abs) - action = time_spent > 0 ? 'added' : 'subtracted' + action = time_spent > 0 ? "added" : "subtracted" text_parts = ["#{action} #{parsed_time} of time spent"] text_parts << "at #{spent_at}" if spent_at - body = text_parts.join(' ') + body = text_parts.join(" ") end - create_note(NoteSummary.new(noteable, project, author, body, action: 'time_tracking')) + create_note(NoteSummary.new(noteable, project, author, body, action: "time_tracking")) end # Called when the status of a Noteable is changed @@ -215,7 +215,7 @@ module SystemNoteService body = status.dup body << " via #{source.gfm_reference(project)}" if source - action = status == 'reopened' ? 'opened' : status + action = status == "reopened" ? "opened" : status create_note(NoteSummary.new(noteable, project, author, body, action: action)) end @@ -224,14 +224,14 @@ module SystemNoteService def merge_when_pipeline_succeeds(noteable, project, author, last_commit) body = "enabled an automatic merge when the pipeline for #{last_commit.to_reference(project)} succeeds" - create_note(NoteSummary.new(noteable, project, author, body, action: 'merge')) + create_note(NoteSummary.new(noteable, project, author, body, action: "merge")) end # Called when 'merge when pipeline succeeds' is canceled def cancel_merge_when_pipeline_succeeds(noteable, project, author) - body = 'canceled the automatic merge' + body = "canceled the automatic merge" - create_note(NoteSummary.new(noteable, project, author, body, action: 'merge')) + create_note(NoteSummary.new(noteable, project, author, body, action: "merge")) end def handle_merge_request_wip(noteable, project, author) @@ -239,19 +239,19 @@ module SystemNoteService body = "#{prefix} as a **Work In Progress**" - create_note(NoteSummary.new(noteable, project, author, body, action: 'title')) + create_note(NoteSummary.new(noteable, project, author, body, action: "title")) end def add_merge_request_wip_from_commit(noteable, project, author, commit) body = "marked as a **Work In Progress** from #{commit.to_reference(project)}" - create_note(NoteSummary.new(noteable, project, author, body, action: 'title')) + create_note(NoteSummary.new(noteable, project, author, body, action: "title")) end def resolve_all_discussions(merge_request, project, author) body = "resolved all discussions" - create_note(NoteSummary.new(merge_request, project, author, body, action: 'discussion')) + create_note(NoteSummary.new(merge_request, project, author, body, action: "discussion")) end def discussion_continued_in_issue(discussion, project, author, issue) @@ -259,7 +259,7 @@ module SystemNoteService note_attributes = discussion.reply_attributes.merge(project: project, author: author, note: body) note = Note.create(note_attributes.merge(system: true)) - note.system_note_metadata = SystemNoteMetadata.new(action: 'discussion') + note.system_note_metadata = SystemNoteMetadata.new(action: "discussion") note end @@ -279,11 +279,11 @@ module SystemNoteService text_parts << "version #{version_index} of the diff" end - body = text_parts.join(' ') + body = text_parts.join(" ") note_attributes = discussion.reply_attributes.merge(project: project, author: author, note: body) note = Note.create(note_attributes.merge(system: true)) - note.system_note_metadata = SystemNoteMetadata.new(action: 'outdated') + note.system_note_metadata = SystemNoteMetadata.new(action: "outdated") note end @@ -310,7 +310,7 @@ module SystemNoteService body = "changed title from **#{marked_old_title}** to **#{marked_new_title}**" - create_note(NoteSummary.new(noteable, project, author, body, action: 'title')) + create_note(NoteSummary.new(noteable, project, author, body, action: "title")) end # Called when the description of a Noteable is changed @@ -325,9 +325,9 @@ module SystemNoteService # # Returns the created Note object def change_description(noteable, project, author) - body = 'changed the description' + body = "changed the description" - create_note(NoteSummary.new(noteable, project, author, body, action: 'description')) + create_note(NoteSummary.new(noteable, project, author, body, action: "description")) end # Called when the confidentiality changes @@ -343,11 +343,11 @@ module SystemNoteService # Returns the created Note object def change_issue_confidentiality(issue, project, author) if issue.confidential - body = 'made the issue confidential' - action = 'confidential' + body = "made the issue confidential" + action = "confidential" else - body = 'made the issue visible to everyone' - action = 'visible' + body = "made the issue visible to everyone" + action = "visible" end create_note(NoteSummary.new(issue, project, author, body, action: action)) @@ -370,7 +370,7 @@ module SystemNoteService def change_branch(noteable, project, author, branch_type, old_branch, new_branch) body = "changed #{branch_type} branch from `#{old_branch}` to `#{new_branch}`" - create_note(NoteSummary.new(noteable, project, author, body, action: 'branch')) + create_note(NoteSummary.new(noteable, project, author, body, action: "branch")) end # Called when a branch in Noteable is added or deleted @@ -390,14 +390,14 @@ module SystemNoteService def change_branch_presence(noteable, project, author, branch_type, branch, presence) verb = if presence == :add - 'restored' + "restored" else - 'deleted' + "deleted" end body = "#{verb} #{branch_type} branch `#{branch}`" - create_note(NoteSummary.new(noteable, project, author, body, action: 'branch')) + create_note(NoteSummary.new(noteable, project, author, body, action: "branch")) end # Called when a branch is created from the 'new branch' button on a issue @@ -409,13 +409,13 @@ module SystemNoteService body = "created branch [`#{branch}`](#{link}) to address this issue" - create_note(NoteSummary.new(issue, project, author, body, action: 'branch')) + create_note(NoteSummary.new(issue, project, author, body, action: "branch")) end def new_merge_request(issue, project, author, merge_request) body = "created merge request #{merge_request.to_reference} to address this issue" - create_note(NoteSummary.new(issue, project, author, body, action: 'merge')) + create_note(NoteSummary.new(issue, project, author, body, action: "merge")) end # Called when a Mentionable references a Noteable @@ -444,7 +444,7 @@ module SystemNoteService if noteable.is_a?(ExternalIssue) noteable.project.issues_tracker.create_cross_reference_note(noteable, mentioner, author) else - create_note(NoteSummary.new(noteable, noteable.project, author, body, action: 'cross_reference')) + create_note(NoteSummary.new(noteable, noteable.project, author, body, action: "cross_reference")) end end @@ -489,7 +489,7 @@ module SystemNoteService # Returns an Array of Strings def new_commit_summary(new_commits) new_commits.collect do |commit| - content_tag('li', "#{commit.short_id} - #{commit.title}") + content_tag("li", "#{commit.short_id} - #{commit.title}") end end @@ -509,7 +509,7 @@ module SystemNoteService status_label = new_task.complete? ? Taskable::COMPLETED : Taskable::INCOMPLETE body = "marked the task **#{new_task.source}** as #{status_label}" - create_note(NoteSummary.new(noteable, project, author, body, action: 'task')) + create_note(NoteSummary.new(noteable, project, author, body, action: "task")) end # Called when noteable has been moved to another project @@ -532,7 +532,7 @@ module SystemNoteService cross_reference = noteable_ref.to_reference(project) body = "moved #{direction} #{cross_reference}" - create_note(NoteSummary.new(noteable, project, author, body, action: 'moved')) + create_note(NoteSummary.new(noteable, project, author, body, action: "moved")) end # Called when a Noteable has been marked as a duplicate of another Issue @@ -551,7 +551,7 @@ module SystemNoteService # Returns the created Note object def mark_duplicate_issue(noteable, project, author, canonical_issue) body = "marked this issue as a duplicate of #{canonical_issue.to_reference(project)}" - create_note(NoteSummary.new(noteable, project, author, body, action: 'duplicate')) + create_note(NoteSummary.new(noteable, project, author, body, action: "duplicate")) end # Called when a Noteable has been marked as the canonical Issue of a duplicate @@ -570,11 +570,11 @@ module SystemNoteService # Returns the created Note object def mark_canonical_issue_of_duplicate(noteable, project, author, duplicate_issue) body = "marked #{duplicate_issue.to_reference(project)} as a duplicate of this issue" - create_note(NoteSummary.new(noteable, project, author, body, action: 'duplicate')) + create_note(NoteSummary.new(noteable, project, author, body, action: "duplicate")) end def discussion_lock(issuable, author) - action = issuable.discussion_locked? ? 'locked' : 'unlocked' + action = issuable.discussion_locked? ? "locked" : "unlocked" body = "#{action} this #{issuable.class.to_s.titleize.downcase}" create_note(NoteSummary.new(issuable, issuable.project, author, body, action: action)) @@ -590,7 +590,7 @@ module SystemNoteService def notes_for_mentioner(mentioner, noteable, notes) if mentioner.is_a?(Commit) text = "#{cross_reference_note_prefix}%#{mentioner.to_reference(nil)}" - notes.where('(note LIKE ? OR note LIKE ?)', text, text.capitalize) + notes.where("(note LIKE ? OR note LIKE ?)", text, text.capitalize) else gfm_reference = mentioner.gfm_reference(noteable.project || noteable.group) text = cross_reference_note_content(gfm_reference) @@ -607,7 +607,7 @@ module SystemNoteService end def cross_reference_note_prefix - 'mentioned in ' + "mentioned in " end def cross_reference_note_content(gfm_reference) @@ -621,7 +621,7 @@ module SystemNoteService existing_commit_summary = existing_commit_summary(noteable, existing_commits, oldrev) new_commit_summary = new_commit_summary(new_commits).join - content_tag('ul', "#{existing_commit_summary}#{new_commit_summary}".html_safe) + content_tag("ul", "#{existing_commit_summary}#{new_commit_summary}".html_safe) end # Build a single line summarizing existing commits being added in a merge @@ -641,27 +641,27 @@ module SystemNoteService # # Returns a newline-terminated String def existing_commit_summary(noteable, existing_commits, oldrev = nil) - return '' if existing_commits.empty? + return "" if existing_commits.empty? count = existing_commits.size commit_ids = if count == 1 - existing_commits.first.short_id - else - if oldrev && !Gitlab::Git.blank_ref?(oldrev) - "#{Commit.truncate_sha(oldrev)}...#{existing_commits.last.short_id}" - else - "#{existing_commits.first.short_id}..#{existing_commits.last.short_id}" - end - end + existing_commits.first.short_id + else + if oldrev && !Gitlab::Git.blank_ref?(oldrev) + "#{Commit.truncate_sha(oldrev)}...#{existing_commits.last.short_id}" + else + "#{existing_commits.first.short_id}..#{existing_commits.last.short_id}" + end + end commits_text = "#{count} commit".pluralize(count) branch = noteable.target_branch branch = "#{noteable.target_project_namespace}:#{branch}" if noteable.for_fork? - branch_name = content_tag('code', branch) - content_tag('li', "#{commit_ids} - #{commits_text} from branch #{branch_name}".html_safe) + branch_name = content_tag("code", branch) + content_tag("li", "#{commit_ids} - #{commits_text} from branch #{branch_name}".html_safe) end def url_helpers diff --git a/app/services/tags/create_service.rb b/app/services/tags/create_service.rb index 4de6b2d2774..4d836ba763e 100644 --- a/app/services/tags/create_service.rb +++ b/app/services/tags/create_service.rb @@ -4,7 +4,7 @@ module Tags class CreateService < BaseService def execute(tag_name, target, message) valid_tag = Gitlab::GitRefValidator.validate(tag_name) - return error('Tag name invalid') unless valid_tag + return error("Tag name invalid") unless valid_tag repository = project.repository message = message&.strip diff --git a/app/services/tags/destroy_service.rb b/app/services/tags/destroy_service.rb index cab507946b4..48d419c2cf7 100644 --- a/app/services/tags/destroy_service.rb +++ b/app/services/tags/destroy_service.rb @@ -7,7 +7,7 @@ module Tags tag = repository.find_tag(tag_name) unless tag - return error('No such tag', 404) + return error("No such tag", 404) end if repository.rm_tag(current_user, tag_name) @@ -23,9 +23,9 @@ module Tags project.execute_hooks(push_data.dup, :tag_push_hooks) project.execute_services(push_data.dup, :tag_push_hooks) - success('Tag was removed') + success("Tag was removed") else - error('Failed to remove tag') + error("Failed to remove tag") end rescue Gitlab::Git::PreReceiveError => ex error(ex.message) @@ -46,7 +46,8 @@ module Tags tag.dereferenced_target.sha, Gitlab::Git::BLANK_SHA, "#{Gitlab::Git::TAG_REF_PREFIX}#{tag.name}", - []) + [] + ) end end end diff --git a/app/services/task_list_toggle_service.rb b/app/services/task_list_toggle_service.rb index f6602a35033..47eb805d461 100644 --- a/app/services/task_list_toggle_service.rb +++ b/app/services/task_list_toggle_service.rb @@ -41,9 +41,9 @@ class TaskListToggleService # Check `toggle_as_checked` to make sure we don't accidentally replace # any `[ ]` or `[x]` in the middle of the text if currently_checked - markdown_task.sub!(Taskable::COMPLETE_PATTERN, '[ ]') unless toggle_as_checked + markdown_task.sub!(Taskable::COMPLETE_PATTERN, "[ ]") unless toggle_as_checked else - markdown_task.sub!(Taskable::INCOMPLETE_PATTERN, '[x]') if toggle_as_checked + markdown_task.sub!(Taskable::INCOMPLETE_PATTERN, "[x]") if toggle_as_checked end source_lines[source_line_index] = markdown_task @@ -56,9 +56,9 @@ class TaskListToggleService return unless html_checkbox if toggle_as_checked - html_checkbox[:checked] = 'checked' + html_checkbox[:checked] = "checked" else - html_checkbox.remove_attribute('checked') + html_checkbox.remove_attribute("checked") end @updated_markdown_html = html.to_html diff --git a/app/services/test_hooks/base_service.rb b/app/services/test_hooks/base_service.rb index 8b5439c00bf..422dfc096ef 100644 --- a/app/services/test_hooks/base_service.rb +++ b/app/services/test_hooks/base_service.rb @@ -14,15 +14,15 @@ module TestHooks trigger_key = hook.class.triggers.key(trigger.to_sym) trigger_data_method = "#{trigger}_data" - if trigger_key.nil? || !self.respond_to?(trigger_data_method, true) - return error('Testing not available for this hook') + if trigger_key.nil? || !respond_to?(trigger_data_method, true) + return error("Testing not available for this hook") end - error_message = catch(:validation_error) do - sample_data = self.__send__(trigger_data_method) # rubocop:disable GitlabSecurity/PublicSend + error_message = catch(:validation_error) { + sample_data = __send__(trigger_data_method) # rubocop:disable GitlabSecurity/PublicSend return hook.execute(sample_data, trigger_key) # rubocop:disable Cop/AvoidReturnFromBlocks - end + } error(error_message) end @@ -32,7 +32,7 @@ module TestHooks def error(message, http_status = nil) result = { message: message, - status: :error + status: :error, } result[:http_status] = http_status if http_status diff --git a/app/services/test_hooks/project_service.rb b/app/services/test_hooks/project_service.rb index 7e14ddcd017..99c3d541490 100644 --- a/app/services/test_hooks/project_service.rb +++ b/app/services/test_hooks/project_service.rb @@ -11,46 +11,46 @@ module TestHooks private def push_events_data - throw(:validation_error, 'Ensure the project has at least one commit.') if project.empty_repo? + throw(:validation_error, "Ensure the project has at least one commit.") if project.empty_repo? Gitlab::DataBuilder::Push.build_sample(project, current_user) end - alias_method :tag_push_events_data, :push_events_data + alias tag_push_events_data push_events_data def note_events_data note = project.notes.first - throw(:validation_error, 'Ensure the project has notes.') unless note.present? + throw(:validation_error, "Ensure the project has notes.") unless note.present? Gitlab::DataBuilder::Note.build(note, current_user) end def issues_events_data issue = project.issues.first - throw(:validation_error, 'Ensure the project has issues.') unless issue.present? + throw(:validation_error, "Ensure the project has issues.") unless issue.present? issue.to_hook_data(current_user) end - alias_method :confidential_issues_events_data, :issues_events_data + alias confidential_issues_events_data issues_events_data def merge_requests_events_data merge_request = project.merge_requests.first - throw(:validation_error, 'Ensure the project has merge requests.') unless merge_request.present? + throw(:validation_error, "Ensure the project has merge requests.") unless merge_request.present? merge_request.to_hook_data(current_user) end def job_events_data build = project.builds.first - throw(:validation_error, 'Ensure the project has CI jobs.') unless build.present? + throw(:validation_error, "Ensure the project has CI jobs.") unless build.present? Gitlab::DataBuilder::Build.build(build) end def pipeline_events_data pipeline = project.ci_pipelines.first - throw(:validation_error, 'Ensure the project has CI pipelines.') unless pipeline.present? + throw(:validation_error, "Ensure the project has CI pipelines.") unless pipeline.present? Gitlab::DataBuilder::Pipeline.build(pipeline) end @@ -58,10 +58,10 @@ module TestHooks def wiki_page_events_data page = project.wiki.pages.first if !project.wiki_enabled? || page.blank? - throw(:validation_error, 'Ensure the wiki is enabled and has pages.') + throw(:validation_error, "Ensure the wiki is enabled and has pages.") end - Gitlab::DataBuilder::WikiPage.build(page, current_user, 'create') + Gitlab::DataBuilder::WikiPage.build(page, current_user, "create") end end end diff --git a/app/services/test_hooks/system_service.rb b/app/services/test_hooks/system_service.rb index 082830c5538..55a9c794d1a 100644 --- a/app/services/test_hooks/system_service.rb +++ b/app/services/test_hooks/system_service.rb @@ -18,7 +18,7 @@ module TestHooks def merge_requests_events_data merge_request = MergeRequest.of_projects(current_user.projects.select(:id)).first - throw(:validation_error, 'Ensure one of your projects has merge requests.') unless merge_request.present? + throw(:validation_error, "Ensure one of your projects has merge requests.") unless merge_request.present? merge_request.to_hook_data(current_user) end diff --git a/app/services/todo_service.rb b/app/services/todo_service.rb index f357dc37fe7..65ca9e0b4f4 100644 --- a/app/services/todo_service.rb +++ b/app/services/todo_service.rb @@ -239,7 +239,7 @@ class TodoService end def toggling_tasks?(issuable) - issuable.previous_changes.include?('description') && + issuable.previous_changes.include?("description") && issuable.tasks? && issuable.updated_tasks.any? end @@ -288,11 +288,12 @@ class TodoService project_id: target&.project&.id, target_id: target.id, target_type: target.class.name, - commit_id: nil + commit_id: nil, } if target.is_a?(Commit) - attributes.merge!(target_id: nil, commit_id: target.id) + attributes[:target_id] = nil + attributes[:commit_id] = target.id end attributes diff --git a/app/services/todos/destroy/base_service.rb b/app/services/todos/destroy/base_service.rb index f3f1dbb5698..f718fcfbf46 100644 --- a/app/services/todos/destroy/base_service.rb +++ b/app/services/todos/destroy/base_service.rb @@ -13,7 +13,7 @@ module Todos # rubocop: disable CodeReuse/ActiveRecord def without_authorized(items) - items.where('user_id NOT IN (?)', authorized_users) + items.where("user_id NOT IN (?)", authorized_users) end # rubocop: enable CodeReuse/ActiveRecord diff --git a/app/services/todos/destroy/confidential_issue_service.rb b/app/services/todos/destroy/confidential_issue_service.rb index 6276e332448..a231f19b04b 100644 --- a/app/services/todos/destroy/confidential_issue_service.rb +++ b/app/services/todos/destroy/confidential_issue_service.rb @@ -19,8 +19,8 @@ module Todos # rubocop: disable CodeReuse/ActiveRecord def todos Todo.where(target: issue) - .where('user_id != ?', issue.author_id) - .where('user_id NOT IN (?)', issue.assignees.select(:id)) + .where("user_id != ?", issue.author_id) + .where("user_id NOT IN (?)", issue.assignees.select(:id)) end # rubocop: enable CodeReuse/ActiveRecord @@ -39,7 +39,7 @@ module Todos def authorized_users ProjectAuthorization.select(:user_id) .where(project_id: project_ids) - .where('access_level >= ?', Gitlab::Access::REPORTER) + .where("access_level >= ?", Gitlab::Access::REPORTER) end # rubocop: enable CodeReuse/ActiveRecord end diff --git a/app/services/todos/destroy/entity_leave_service.rb b/app/services/todos/destroy/entity_leave_service.rb index ebfb20132d0..86f1f368b11 100644 --- a/app/services/todos/destroy/entity_leave_service.rb +++ b/app/services/todos/destroy/entity_leave_service.rb @@ -9,7 +9,7 @@ module Todos # rubocop: disable CodeReuse/ActiveRecord def initialize(user_id, entity_id, entity_type) - unless %w(Group Project).include?(entity_type) + unless %w[Group Project].include?(entity_type) raise ArgumentError.new("#{entity_type} is not an entity user can leave") end @@ -67,10 +67,10 @@ module Todos def project_ids condition = case entity when Project - { id: entity.id } + {id: entity.id} when Namespace - { namespace_id: non_member_groups } - end + {namespace_id: non_member_groups} + end Project.where(condition).select(:id) end @@ -78,7 +78,7 @@ module Todos # rubocop: disable CodeReuse/ActiveRecord def non_authorized_projects - project_ids.where('id NOT IN (?)', user.authorized_projects.select(:id)) + project_ids.where("id NOT IN (?)", user.authorized_projects.select(:id)) end # rubocop: enable CodeReuse/ActiveRecord @@ -87,14 +87,14 @@ module Todos return [] unless entity.is_a?(Namespace) entity.self_and_descendants.select(:id) - .where('id NOT IN (?)', GroupsFinder.new(user).execute.select(:id)) + .where("id NOT IN (?)", GroupsFinder.new(user).execute.select(:id)) end # rubocop: enable CodeReuse/ActiveRecord # rubocop: disable CodeReuse/ActiveRecord def non_member_groups entity.self_and_descendants.select(:id) - .where('id NOT IN (?)', user.membership_groups.select(:id)) + .where("id NOT IN (?)", user.membership_groups.select(:id)) end # rubocop: enable CodeReuse/ActiveRecord @@ -111,9 +111,9 @@ module Todos .authorized_projects(Gitlab::Access::REPORTER).select(:id) Issue.where(project_id: project_ids, confidential: true) - .where('project_id NOT IN(?)', authorized_reporter_projects) - .where('author_id != ?', user.id) - .where('id NOT IN (?)', assigned_ids) + .where("project_id NOT IN(?)", authorized_reporter_projects) + .where("author_id != ?", user.id) + .where("id NOT IN (?)", assigned_ids) end # rubocop: enable CodeReuse/ActiveRecord end diff --git a/app/services/todos/destroy/private_features_service.rb b/app/services/todos/destroy/private_features_service.rb index bd49519d694..cfb7cc5dec9 100644 --- a/app/services/todos/destroy/private_features_service.rb +++ b/app/services/todos/destroy/private_features_service.rb @@ -36,7 +36,7 @@ module Todos items = Todo.where(project_id: project_id) items = items.where(user_id: user_id) if user_id - items.where('user_id NOT IN (?)', authorized_users) + items.where("user_id NOT IN (?)", authorized_users) .where(target_type: target_types) .delete_all end diff --git a/app/services/update_deployment_service.rb b/app/services/update_deployment_service.rb index aa7fcca1e2a..6d08d1521c6 100644 --- a/app/services/update_deployment_service.rb +++ b/app/services/update_deployment_service.rb @@ -48,6 +48,6 @@ class UpdateDeploymentService end def action - environment_options[:action] || 'start' + environment_options[:action] || "start" end end diff --git a/app/services/user_agent_detail_service.rb b/app/services/user_agent_detail_service.rb index 5cb42e879a0..0419b039b84 100644 --- a/app/services/user_agent_detail_service.rb +++ b/app/services/user_agent_detail_service.rb @@ -10,6 +10,6 @@ class UserAgentDetailService def create return unless request - spammable.create_user_agent_detail(user_agent: request.env['HTTP_USER_AGENT'], ip_address: request.env['action_dispatch.remote_ip'].to_s) + spammable.create_user_agent_detail(user_agent: request.env["HTTP_USER_AGENT"], ip_address: request.env["action_dispatch.remote_ip"].to_s) end end diff --git a/app/services/users/activity_service.rb b/app/services/users/activity_service.rb index e50840a9158..a51bb5e015d 100644 --- a/app/services/users/activity_service.rb +++ b/app/services/users/activity_service.rb @@ -6,10 +6,10 @@ module Users def initialize(author, activity) @user = if author.respond_to?(:username) - author - elsif author.respond_to?(:user) - author.user - end + author + elsif author.respond_to?(:user) + author.user + end @user = nil unless @user.is_a?(User) @activity = activity @@ -31,7 +31,7 @@ module Users return if @user.last_activity_on == today lease = Gitlab::ExclusiveLease.new("acitvity_service:#{@user.id}", - timeout: LEASE_TIMEOUT) + timeout: LEASE_TIMEOUT) return unless lease.try_obtain @user.update_attribute(:last_activity_on, today) diff --git a/app/services/users/build_service.rb b/app/services/users/build_service.rb index 3f503f3da28..382be61185a 100644 --- a/app/services/users/build_service.rb +++ b/app/services/users/build_service.rb @@ -3,8 +3,8 @@ module Users class BuildService < BaseService delegate :user_default_internal_regex_enabled?, - :user_default_internal_regex_instance, - to: :'Gitlab::CurrentSettings.current_application_settings' + :user_default_internal_regex_instance, + to: :'Gitlab::CurrentSettings.current_application_settings' def initialize(current_user, params = {}) @current_user = current_user @@ -71,7 +71,7 @@ module Users :private_profile, :organization, :location, - :public_email + :public_email, ] end @@ -83,7 +83,7 @@ module Users :password_automatically_set, :name, :password, - :username + :username, ] end @@ -93,7 +93,8 @@ module Users user_params[:created_by_id] = current_user&.id if params[:reset_password] - user_params.merge!(force_random_password: true, password_expires_at: nil) + user_params[:force_random_password] = true + user_params[:password_expires_at] = nil end else allowed_signup_params = signup_params diff --git a/app/services/users/destroy_service.rb b/app/services/users/destroy_service.rb index 73fa6089945..141dee49b45 100644 --- a/app/services/users/destroy_service.rb +++ b/app/services/users/destroy_service.rb @@ -31,7 +31,7 @@ module Users end if !delete_solo_owned_groups && user.solo_owned_groups.present? - user.errors[:base] << 'You must transfer ownership or delete groups before you can remove user' + user.errors[:base] << "You must transfer ownership or delete groups before you can remove user" return user end diff --git a/app/services/users/last_push_event_service.rb b/app/services/users/last_push_event_service.rb index b3980b8e32c..6e9c3b7c658 100644 --- a/app/services/users/last_push_event_service.rb +++ b/app/services/users/last_push_event_service.rb @@ -15,7 +15,7 @@ module Users def cache_last_push_event(event) keys = [ project_cache_key(event.project), - user_cache_key + user_cache_key, ] if forked_from = event.project.forked_from_project diff --git a/app/services/users/refresh_authorized_projects_service.rb b/app/services/users/refresh_authorized_projects_service.rb index fe5a82e23fa..e26df34a6e1 100644 --- a/app/services/users/refresh_authorized_projects_service.rb +++ b/app/services/users/refresh_authorized_projects_service.rb @@ -51,21 +51,21 @@ module Users current = current_authorizations_per_project fresh = fresh_access_levels_per_project - remove = current.each_with_object([]) do |(project_id, row), array| + remove = current.each_with_object([]) { |(project_id, row), array| # rows not in the new list or with a different access level should be # removed. if !fresh[project_id] || fresh[project_id] != row.access_level array << row.project_id end - end + } - add = fresh.each_with_object([]) do |(project_id, level), array| + add = fresh.each_with_object([]) { |(project_id, level), array| # rows not in the old list or with a different access level should be # added. if !current[project_id] || current[project_id].access_level != level array << [user.id, project_id, level] end - end + } update_authorizations(remove, add) end @@ -103,10 +103,10 @@ module Users def fresh_authorizations klass = if Group.supports_nested_objects? - Gitlab::ProjectAuthorizations::WithNestedGroups - else - Gitlab::ProjectAuthorizations::WithoutNestedGroups - end + Gitlab::ProjectAuthorizations::WithNestedGroups + else + Gitlab::ProjectAuthorizations::WithoutNestedGroups + end klass.new(user).calculate end diff --git a/app/services/users/update_service.rb b/app/services/users/update_service.rb index 0b00bd135eb..ac2d7643e25 100644 --- a/app/services/users/update_service.rb +++ b/app/services/users/update_service.rb @@ -22,7 +22,7 @@ module Users notify_success(user_exists) else messages = @user.errors.full_messages + Array(@user.status&.errors&.full_messages) - error(messages.uniq.join('. ')) + error(messages.uniq.join(". ")) end end diff --git a/app/services/validate_new_branch_service.rb b/app/services/validate_new_branch_service.rb index c19e2ec2043..8f6973a2d4d 100644 --- a/app/services/validate_new_branch_service.rb +++ b/app/services/validate_new_branch_service.rb @@ -1,17 +1,17 @@ # frozen_string_literal: true -require_relative 'base_service' +require_relative "base_service" class ValidateNewBranchService < BaseService def execute(branch_name) valid_branch = Gitlab::GitRefValidator.validate(branch_name) unless valid_branch - return error('Branch name is invalid') + return error("Branch name is invalid") end if project.repository.branch_exists?(branch_name) - return error('Branch already exists') + return error("Branch already exists") end success diff --git a/app/services/verify_pages_domain_service.rb b/app/services/verify_pages_domain_service.rb index 07f7391f877..4524facbceb 100644 --- a/app/services/verify_pages_domain_service.rb +++ b/app/services/verify_pages_domain_service.rb @@ -1,6 +1,6 @@ # frozen_string_literal: true -require 'resolv' +require "resolv" class VerifyPagesDomainService < BaseService # The maximum number of seconds to be spent on each DNS lookup diff --git a/app/services/web_hook_service.rb b/app/services/web_hook_service.rb index 1fee8bfcd31..ef85272829e 100644 --- a/app/services/web_hook_service.rb +++ b/app/services/web_hook_service.rb @@ -6,8 +6,8 @@ class WebHookService def initialize @headers = Gitlab::HTTP::Response::Headers.new({}) - @body = '' - @code = 'internal error' + @body = "" + @code = "internal error" end end @@ -17,7 +17,7 @@ class WebHookService @hook = hook @data = data @hook_name = hook_name.to_s - @request_options = { timeout: Gitlab.config.gitlab.webhook_timeout } + @request_options = {timeout: Gitlab.config.gitlab.webhook_timeout} @request_options.merge!(allow_local_requests: true) if @hook.is_a?(SystemHook) end @@ -25,10 +25,10 @@ class WebHookService start_time = Gitlab::Metrics::System.monotonic_time response = if parsed_url.userinfo.blank? - make_request(hook.url) - else - make_request_with_auth - end + make_request(hook.url) + else + make_request_with_auth + end log_execution( trigger: hook_name, @@ -41,7 +41,7 @@ class WebHookService { status: :success, http_status: response.code, - message: response.to_s + message: response.to_s, } rescue SocketError, OpenSSL::SSL::SSLError, Errno::ECONNRESET, Errno::ECONNREFUSED, Errno::EHOSTUNREACH, Net::OpenTimeout, Net::ReadTimeout, Gitlab::HTTP::BlockedUrlError, Gitlab::HTTP::RedirectionTooDeep => e log_execution( @@ -57,7 +57,7 @@ class WebHookService { status: :error, - message: e.to_s + message: e.to_s, } end @@ -81,10 +81,10 @@ class WebHookService end def make_request_with_auth - post_url = hook.url.gsub("#{parsed_url.userinfo}@", '') + post_url = hook.url.gsub("#{parsed_url.userinfo}@", "") basic_auth = { username: CGI.unescape(parsed_url.user), - password: CGI.unescape(parsed_url.password.presence || '') + password: CGI.unescape(parsed_url.password.presence || ""), } make_request(post_url, basic_auth) end @@ -110,10 +110,10 @@ class WebHookService def build_headers(hook_name) @headers ||= begin { - 'Content-Type' => 'application/json', - 'X-Gitlab-Event' => hook_name.singularize.titleize + "Content-Type" => "application/json", + "X-Gitlab-Event" => hook_name.singularize.titleize, }.tap do |hash| - hash['X-Gitlab-Token'] = Gitlab::Utils.remove_line_breaks(hook.token) if hook.token.present? + hash["X-Gitlab-Token"] = Gitlab::Utils.remove_line_breaks(hook.token) if hook.token.present? end end end @@ -126,8 +126,8 @@ class WebHookService end def safe_response_body(response) - return '' unless response.body + return "" unless response.body - response.body.encode('UTF-8', invalid: :replace, undef: :replace, replace: '') + response.body.encode("UTF-8", invalid: :replace, undef: :replace, replace: "") end end diff --git a/app/services/wiki_pages/base_service.rb b/app/services/wiki_pages/base_service.rb index e259f5bd1bc..ed2e2a917f2 100644 --- a/app/services/wiki_pages/base_service.rb +++ b/app/services/wiki_pages/base_service.rb @@ -4,7 +4,7 @@ module WikiPages class BaseService < ::BaseService private - def execute_hooks(page, action = 'create') + def execute_hooks(page, action = "create") page_data = Gitlab::DataBuilder::WikiPage.build(page, current_user, action) @project.execute_hooks(page_data, :wiki_page_hooks) @project.execute_services(page_data, :wiki_page_hooks) diff --git a/app/services/wiki_pages/create_service.rb b/app/services/wiki_pages/create_service.rb index 2e2e0fd9033..85ddf35bffa 100644 --- a/app/services/wiki_pages/create_service.rb +++ b/app/services/wiki_pages/create_service.rb @@ -7,7 +7,7 @@ module WikiPages page = WikiPage.new(project_wiki) if page.create(@params) - execute_hooks(page, 'create') + execute_hooks(page, "create") end page diff --git a/app/services/wiki_pages/destroy_service.rb b/app/services/wiki_pages/destroy_service.rb index 3f9343339cd..8860544a8cd 100644 --- a/app/services/wiki_pages/destroy_service.rb +++ b/app/services/wiki_pages/destroy_service.rb @@ -4,7 +4,7 @@ module WikiPages class DestroyService < WikiPages::BaseService def execute(page) if page&.delete - execute_hooks(page, 'delete') + execute_hooks(page, "delete") end page diff --git a/app/services/wiki_pages/update_service.rb b/app/services/wiki_pages/update_service.rb index 2159dd91e9c..b283ccb74a7 100644 --- a/app/services/wiki_pages/update_service.rb +++ b/app/services/wiki_pages/update_service.rb @@ -4,7 +4,7 @@ module WikiPages class UpdateService < WikiPages::BaseService def execute(page) if page.update(@params) - execute_hooks(page, 'update') + execute_hooks(page, "update") end page diff --git a/app/services/wikis/create_attachment_service.rb b/app/services/wikis/create_attachment_service.rb index df31ad7c8ea..00276e40eb2 100644 --- a/app/services/wikis/create_attachment_service.rb +++ b/app/services/wikis/create_attachment_service.rb @@ -2,7 +2,7 @@ module Wikis class CreateAttachmentService < Files::CreateService - ATTACHMENT_PATH = 'uploads'.freeze + ATTACHMENT_PATH = "uploads" MAX_FILENAME_LENGTH = 255 delegate :wiki, to: :project @@ -29,7 +29,7 @@ module Wikis file_name = truncate_file_name(file_name) # CommonMark does not allow Urls with whitespaces, so we have to replace them # Using the same regex Carrierwave use to replace invalid characters - file_name.gsub(CarrierWave::SanitizedFile.sanitize_regexp, '_') + file_name.gsub(CarrierWave::SanitizedFile.sanitize_regexp, "_") end def truncate_file_name(file_name) @@ -47,12 +47,12 @@ module Wikis end def validate_file_name! - raise_error('The file name cannot be empty') unless @file_name + raise_error("The file name cannot be empty") unless @file_name end def validate_permissions! unless can?(current_user, :create_wiki, project) - raise_error('You are not allowed to push to the wiki') + raise_error("You are not allowed to push to the wiki") end end @@ -64,7 +64,8 @@ module Wikis message: @commit_message, branch_name: @branch_name, author_email: @author_email, - author_name: @author_name) + author_name: @author_name + ) end def commit_result(commit_id) @@ -72,7 +73,7 @@ module Wikis file_name: @file_name, file_path: @file_path, branch: @branch_name, - commit: commit_id + commit: commit_id, } end end diff --git a/app/uploaders/avatar_uploader.rb b/app/uploaders/avatar_uploader.rb index c0165759203..6c1b715ed01 100644 --- a/app/uploaders/avatar_uploader.rb +++ b/app/uploaders/avatar_uploader.rb @@ -7,7 +7,7 @@ class AvatarUploader < GitlabUploader prepend ObjectStorage::Extension::RecordsUploads def exists? - model.avatar.file && model.avatar.file.present? + model.avatar.file&.present? end def move_to_store diff --git a/app/uploaders/external_diff_uploader.rb b/app/uploaders/external_diff_uploader.rb index d2707cd0777..af114c10372 100644 --- a/app/uploaders/external_diff_uploader.rb +++ b/app/uploaders/external_diff_uploader.rb @@ -5,7 +5,7 @@ class ExternalDiffUploader < GitlabUploader storage_options Gitlab.config.external_diffs - alias_method :upload, :model + alias upload model def filename "diff-#{model.id}" diff --git a/app/uploaders/file_mover.rb b/app/uploaders/file_mover.rb index a7f8615e9ba..7b3b50b662b 100644 --- a/app/uploaders/file_mover.rb +++ b/app/uploaders/file_mover.rb @@ -28,7 +28,7 @@ class FileMover def update_markdown updated_text = model.read_attribute(update_field) - .gsub(temp_file_uploader.markdown_link, uploader.markdown_link) + .gsub(temp_file_uploader.markdown_link, uploader.markdown_link) model.update_attribute(update_field, updated_text) rescue revert diff --git a/app/uploaders/file_uploader.rb b/app/uploaders/file_uploader.rb index e90599f2505..f78b85fae4b 100644 --- a/app/uploaders/file_uploader.rb +++ b/app/uploaders/file_uploader.rb @@ -24,7 +24,7 @@ class FileUploader < GitlabUploader after :store, :schedule_background_upload def self.root - File.join(options.storage_path, 'uploads') + File.join(options.storage_path, "uploads") end def self.absolute_path(upload) @@ -74,7 +74,7 @@ class FileUploader < GitlabUploader def upload_paths(identifier) [ File.join(secret, identifier), - File.join(base_dir(Store::REMOTE), secret, identifier) + File.join(base_dir(Store::REMOTE), secret, identifier), ] end @@ -118,15 +118,15 @@ class FileUploader < GitlabUploader def store_dirs { Store::LOCAL => File.join(base_dir, dynamic_segment), - Store::REMOTE => File.join(base_dir(ObjectStorage::Store::REMOTE), dynamic_segment) + Store::REMOTE => File.join(base_dir(ObjectStorage::Store::REMOTE), dynamic_segment), } end def to_h { - alt: markdown_name, - url: secure_url, - markdown: markdown_link + alt: markdown_name, + url: secure_url, + markdown: markdown_link, } end @@ -149,7 +149,7 @@ class FileUploader < GitlabUploader # return a new uploader with a file copy on another project def self.copy_to(uploader, to_project) - moved = self.new(to_project) + moved = new(to_project) moved.object_store = uploader.object_store moved.filename = uploader.filename @@ -159,10 +159,10 @@ class FileUploader < GitlabUploader def copy_file(file) to_path = if file_storage? - File.join(self.class.root, store_path) - else - store_path - end + File.join(self.class.root, store_path) + else + store_path + end self.file = file.copy_to(to_path) record_upload # after_store is not triggered @@ -195,6 +195,6 @@ class FileUploader < GitlabUploader end def secure_url - File.join('/uploads', @secret, file.filename) + File.join("/uploads", @secret, file.filename) end end diff --git a/app/uploaders/gitlab_uploader.rb b/app/uploaders/gitlab_uploader.rb index cefcd3d3f5a..fe41054072f 100644 --- a/app/uploaders/gitlab_uploader.rb +++ b/app/uploaders/gitlab_uploader.rb @@ -15,7 +15,7 @@ class GitlabUploader < CarrierWave::Uploader::Base # represent the directory namespacing at the class level def base_dir - options.fetch('base_dir', '') + options.fetch("base_dir", "") end def file_storage? @@ -52,11 +52,11 @@ class GitlabUploader < CarrierWave::Uploader::Base end def cache_dir - File.join(root, base_dir, 'tmp/cache') + File.join(root, base_dir, "tmp/cache") end def work_dir - File.join(root, base_dir, 'tmp/work') + File.join(root, base_dir, "tmp/work") end def filename @@ -74,7 +74,7 @@ class GitlabUploader < CarrierWave::Uploader::Base end def local_url - File.join('/', self.class.base_dir, dynamic_segment, filename) + File.join("/", self.class.base_dir, dynamic_segment, filename) end def cached_size diff --git a/app/uploaders/job_artifact_uploader.rb b/app/uploaders/job_artifact_uploader.rb index 400f0b3dcc6..b7849b1b0bc 100644 --- a/app/uploaders/job_artifact_uploader.rb +++ b/app/uploaders/job_artifact_uploader.rb @@ -9,7 +9,7 @@ class JobArtifactUploader < GitlabUploader storage_options Gitlab.config.artifacts - alias_method :upload, :model + alias upload model def cached_size return model.size if model.size.present? && !model.file_changed? @@ -24,7 +24,7 @@ class JobArtifactUploader < GitlabUploader private def dynamic_segment - raise ObjectNotReadyError, 'JobArtifact is not ready' unless model.id + raise ObjectNotReadyError, "JobArtifact is not ready" unless model.id if model.hashed_path? hashed_path @@ -37,11 +37,11 @@ class JobArtifactUploader < GitlabUploader def hashed_path File.join(disk_hash[0..1], disk_hash[2..3], disk_hash, - model.created_at.utc.strftime('%Y_%m_%d'), model.job_id.to_s, model.id.to_s) + model.created_at.utc.strftime("%Y_%m_%d"), model.job_id.to_s, model.id.to_s) end def legacy_path - File.join(model.created_at.utc.strftime('%Y_%m'), model.project_id.to_s, model.job_id.to_s) + File.join(model.created_at.utc.strftime("%Y_%m"), model.project_id.to_s, model.job_id.to_s) end def disk_hash diff --git a/app/uploaders/legacy_artifact_uploader.rb b/app/uploaders/legacy_artifact_uploader.rb index a9afc104ed1..9caa787d789 100644 --- a/app/uploaders/legacy_artifact_uploader.rb +++ b/app/uploaders/legacy_artifact_uploader.rb @@ -8,7 +8,7 @@ class LegacyArtifactUploader < GitlabUploader storage_options Gitlab.config.artifacts - alias_method :upload, :model + alias upload model def store_dir dynamic_segment @@ -17,8 +17,8 @@ class LegacyArtifactUploader < GitlabUploader private def dynamic_segment - raise ObjectNotReadyError, 'Build is not ready' unless model.id + raise ObjectNotReadyError, "Build is not ready" unless model.id - File.join(model.created_at.utc.strftime('%Y_%m'), model.project_id.to_s, model.id.to_s) + File.join(model.created_at.utc.strftime("%Y_%m"), model.project_id.to_s, model.id.to_s) end end diff --git a/app/uploaders/lfs_object_uploader.rb b/app/uploaders/lfs_object_uploader.rb index 0a966f3d44f..eed47cd3b53 100644 --- a/app/uploaders/lfs_object_uploader.rb +++ b/app/uploaders/lfs_object_uploader.rb @@ -6,7 +6,7 @@ class LfsObjectUploader < GitlabUploader storage_options Gitlab.config.lfs - alias_method :upload, :model + alias upload model def filename model.oid[4..-1] diff --git a/app/uploaders/namespace_file_uploader.rb b/app/uploaders/namespace_file_uploader.rb index 4965bd7f057..c41e12dc3ac 100644 --- a/app/uploaders/namespace_file_uploader.rb +++ b/app/uploaders/namespace_file_uploader.rb @@ -12,8 +12,8 @@ class NamespaceFileUploader < FileUploader def self.base_dirs(model) { - Store::LOCAL => File.join(options.base_dir, 'namespace', model_path_segment(model)), - Store::REMOTE => File.join('namespace', model_path_segment(model)) + Store::LOCAL => File.join(options.base_dir, "namespace", model_path_segment(model)), + Store::REMOTE => File.join("namespace", model_path_segment(model)), } end @@ -22,7 +22,7 @@ class NamespaceFileUploader < FileUploader end def self.workhorse_local_upload_path - File.join(options.storage_path, 'uploads', TMP_UPLOAD_PATH) + File.join(options.storage_path, "uploads", TMP_UPLOAD_PATH) end # Re-Override diff --git a/app/uploaders/object_storage.rb b/app/uploaders/object_storage.rb index dad6e85fb56..8a450b73cb0 100644 --- a/app/uploaders/object_storage.rb +++ b/app/uploaders/object_storage.rb @@ -1,7 +1,7 @@ # frozen_string_literal: true -require 'fog/aws' -require 'carrierwave/storage/fog' +require "fog/aws" +require "carrierwave/storage/fog" # # This concern should add object storage support @@ -19,11 +19,11 @@ module ObjectStorage def message *lease_key_group, _ = *@lease_key.split(":") - "Exclusive lease for #{lease_key_group.join(':')} is already taken." + "Exclusive lease for #{lease_key_group.join(":")} is already taken." end end - TMP_UPLOAD_PATH = 'tmp/uploads'.freeze + TMP_UPLOAD_PATH = "tmp/uploads" module Store LOCAL = 1 @@ -70,9 +70,9 @@ module ObjectStorage return unless upload ObjectStorage::BackgroundMoveWorker.perform_async(self.class.name, - upload.class.to_s, - mounted_as, - upload.id) + upload.class.to_s, + mounted_as, + upload.id) end def exclusive_lease_key @@ -111,7 +111,7 @@ module ObjectStorage end def changed_mounts - self.class.uploaders.select do |mount, uploader_class| + self.class.uploaders.select { |mount, uploader_class| mounted_as = uploader_class.serialization_column(self.class, mount) uploader = send(:"#{mounted_as}") # rubocop:disable GitlabSecurity/PublicSend @@ -120,7 +120,7 @@ module ObjectStorage next unless send(:"#{mounted_as}_changed?") # rubocop:disable GitlabSecurity/PublicSend mount - end.keys + }.keys end included do @@ -180,21 +180,21 @@ module ObjectStorage def workhorse_authorize(has_length:, maximum_size: nil) { RemoteObject: workhorse_remote_upload_options(has_length: has_length, maximum_size: maximum_size), - TempPath: workhorse_local_upload_path + TempPath: workhorse_local_upload_path, }.compact end def workhorse_local_upload_path - File.join(self.root, TMP_UPLOAD_PATH) + File.join(root, TMP_UPLOAD_PATH) end def workhorse_remote_upload_options(has_length:, maximum_size: nil) - return unless self.object_store_enabled? - return unless self.direct_upload_enabled? + return unless object_store_enabled? + return unless direct_upload_enabled? - id = [CarrierWave.generate_cache_id, SecureRandom.hex].join('-') + id = [CarrierWave.generate_cache_id, SecureRandom.hex].join("-") upload_path = File.join(TMP_UPLOAD_PATH, id) - direct_upload = ObjectStorage::DirectUpload.new(self.object_store_credentials, remote_store_path, upload_path, + direct_upload = ObjectStorage::DirectUpload.new(object_store_credentials, remote_store_path, upload_path, has_length: has_length, maximum_size: maximum_size) direct_upload.to_hash.merge(ID: id) @@ -241,7 +241,7 @@ module ObjectStorage return unless persist_object_store? updated = model.update_column(store_serialization_column, object_store) - raise 'Failed to update object store' unless updated + raise "Failed to update object store" unless updated end def use_file(&blk) @@ -265,9 +265,9 @@ module ObjectStorage return unless schedule_background_upload? ObjectStorage::BackgroundMoveWorker.perform_async(self.class.name, - model.class.name, - mounted_as, - model.id) + model.class.name, + mounted_as, + model.id) end def fog_directory @@ -297,7 +297,7 @@ module ObjectStorage def store_dirs { Store::LOCAL => File.join(base_dir, dynamic_segment), - Store::REMOTE => File.join(dynamic_segment) + Store::REMOTE => File.join(dynamic_segment), } end @@ -336,20 +336,20 @@ module ObjectStorage def schedule_background_upload? self.class.object_store_enabled? && self.class.background_upload_enabled? && - self.file_storage? + file_storage? end def cache_remote_file!(remote_object_id, original_filename) file_path = File.join(TMP_UPLOAD_PATH, remote_object_id) file_path = Pathname.new(file_path).cleanpath.to_s - raise RemoteStoreError, 'Bad file path' unless file_path.start_with?(TMP_UPLOAD_PATH + '/') + raise RemoteStoreError, "Bad file path" unless file_path.start_with?(TMP_UPLOAD_PATH + "/") # TODO: # This should be changed to make use of `tmp/cache` mechanism # instead of using custom upload directory, # using tmp/cache makes this implementation way easier than it is today CarrierWave::Storage::Fog::File.new(self, storage_for(Store::REMOTE), file_path).tap do |file| - raise RemoteStoreError, 'Missing file' unless file.exists? + raise RemoteStoreError, "Missing file" unless file.exists? # Remote stored file, we force to store on remote storage self.object_store = Store::REMOTE @@ -377,7 +377,7 @@ module ObjectStorage # Returns the column where the 'store' is saved # defaults to 'store' def store_serialization_column - [serialization_column, 'store'].compact.join('_').to_sym + [serialization_column, "store"].compact.join("_").to_sym end def storage @@ -387,7 +387,7 @@ module ObjectStorage def storage_for(store) case store when Store::REMOTE - raise 'Object Storage is not enabled' unless self.class.object_store_enabled? + raise "Object Storage is not enabled" unless self.class.object_store_enabled? CarrierWave::Storage::Fog.new(self) when Store::LOCAL @@ -434,7 +434,7 @@ module ObjectStorage file rescue => e # in case of failure delete new file - new_file.delete unless new_file.nil? + new_file&.delete # revert back to the old file self.object_store = from_object_store self.file = file_to_delete diff --git a/app/uploaders/personal_file_uploader.rb b/app/uploaders/personal_file_uploader.rb index 272837aa6ce..5a16794bce6 100644 --- a/app/uploaders/personal_file_uploader.rb +++ b/app/uploaders/personal_file_uploader.rb @@ -13,12 +13,12 @@ class PersonalFileUploader < FileUploader def self.base_dirs(model) { Store::LOCAL => File.join(options.base_dir, model_path_segment(model)), - Store::REMOTE => model_path_segment(model) + Store::REMOTE => model_path_segment(model), } end def self.model_path_segment(model) - return 'temp/' unless model + return "temp/" unless model File.join(model.class.to_s.underscore, model.id.to_s) end @@ -43,6 +43,6 @@ class PersonalFileUploader < FileUploader private def secure_url - File.join('/', base_dir, secret, file.filename) + File.join("/", base_dir, secret, file.filename) end end diff --git a/app/uploaders/records_uploads.rb b/app/uploaders/records_uploads.rb index 9a243e07936..90a51436c1a 100644 --- a/app/uploaders/records_uploads.rb +++ b/app/uploaders/records_uploads.rb @@ -21,7 +21,7 @@ module RecordsUploads # rubocop: disable CodeReuse/ActiveRecord def record_upload(_tempfile = nil) return unless model - return unless file && file.exists? + return unless file&.exists? # MySQL InnoDB may encounter a deadlock if a deletion and an # insert is in the same transaction due to its next-key locking @@ -36,7 +36,7 @@ module RecordsUploads def readd_upload uploads.where(path: upload_path).delete_all - upload.delete if upload + upload&.delete self.upload = build_upload.tap(&:save!) end @@ -69,7 +69,7 @@ module RecordsUploads # Called `before :remove` # rubocop: disable CodeReuse/ActiveRecord def destroy_upload(*args) - return unless file && file.exists? + return unless file&.exists? self.upload = nil uploads.where(path: upload_path).delete_all diff --git a/app/uploaders/uploader_helper.rb b/app/uploaders/uploader_helper.rb index e8a2dce7755..c4f4e29da4e 100644 --- a/app/uploaders/uploader_helper.rb +++ b/app/uploaders/uploader_helper.rb @@ -9,7 +9,7 @@ module UploaderHelper def extension_match?(extensions) return false unless file - extension = file.try(:extension) || File.extname(file.path).delete('.') + extension = file.try(:extension) || File.extname(file.path).delete(".") extensions.include?(extension.downcase) end end diff --git a/app/uploaders/workhorse.rb b/app/uploaders/workhorse.rb index 84dc2791b9c..db821f811a6 100644 --- a/app/uploaders/workhorse.rb +++ b/app/uploaders/workhorse.rb @@ -3,7 +3,7 @@ module Workhorse module UploadPath def workhorse_upload_path - File.join(root, base_dir, 'tmp/uploads') + File.join(root, base_dir, "tmp/uploads") end end end diff --git a/app/validators/abstract_path_validator.rb b/app/validators/abstract_path_validator.rb index 45ac695c5ec..b96ea5b7766 100644 --- a/app/validators/abstract_path_validator.rb +++ b/app/validators/abstract_path_validator.rb @@ -21,7 +21,7 @@ class AbstractPathValidator < ActiveModel::EachValidator end def validate_each(record, attribute, value) - unless value =~ self.class.format_regex + unless value&.match?(self.class.format_regex) record.errors.add(attribute, self.class.format_error_message) return end diff --git a/app/validators/branch_filter_validator.rb b/app/validators/branch_filter_validator.rb index 6a0899be850..db44d75c503 100644 --- a/app/validators/branch_filter_validator.rb +++ b/app/validators/branch_filter_validator.rb @@ -14,10 +14,10 @@ # class BranchFilterValidator < ActiveModel::EachValidator def validate_each(record, attribute, value) - value.squish! unless value.nil? + value&.squish! if value.present? - value_without_wildcards = value.tr('*', 'x') + value_without_wildcards = value.tr("*", "x") unless Gitlab::GitRefValidator.validate(value_without_wildcards) record.errors[attribute] << "is not a valid branch name" @@ -32,6 +32,6 @@ class BranchFilterValidator < ActiveModel::EachValidator private def contains_wildcard?(value) - value.include?('*') + value.include?("*") end end diff --git a/app/validators/cluster_name_validator.rb b/app/validators/cluster_name_validator.rb index 85fd63f08e5..db45ebd21ea 100644 --- a/app/validators/cluster_name_validator.rb +++ b/app/validators/cluster_name_validator.rb @@ -14,7 +14,7 @@ class ClusterNameValidator < ActiveModel::EachValidator record.errors.add(attribute, " is invalid syntax") end - unless value =~ Gitlab::Regex.kubernetes_namespace_regex + unless value&.match?(Gitlab::Regex.kubernetes_namespace_regex) record.errors.add(attribute, Gitlab::Regex.kubernetes_namespace_regex_message) end else diff --git a/app/validators/color_validator.rb b/app/validators/color_validator.rb index 1932d042e83..3e1231f5a89 100644 --- a/app/validators/color_validator.rb +++ b/app/validators/color_validator.rb @@ -15,7 +15,7 @@ class ColorValidator < ActiveModel::EachValidator PATTERN = /\A\#[0-9A-Fa-f]{3}{1,2}+\Z/.freeze def validate_each(record, attribute, value) - unless value =~ PATTERN + unless PATTERN.match?(value) record.errors.add(attribute, "must be a valid color code") end end diff --git a/app/validators/key_restriction_validator.rb b/app/validators/key_restriction_validator.rb index 891d13b1596..580987e7ad3 100644 --- a/app/validators/key_restriction_validator.rb +++ b/app/validators/key_restriction_validator.rb @@ -21,7 +21,7 @@ class KeyRestrictionValidator < ActiveModel::EachValidator def supported_sizes_message sizes = self.class.supported_sizes(options[:type]) - sizes.to_sentence(last_word_connector: ', or ', two_words_connector: ' or ') + sizes.to_sentence(last_word_connector: ", or ", two_words_connector: " or ") end def valid_restriction?(value) diff --git a/app/validators/line_code_validator.rb b/app/validators/line_code_validator.rb index a351180790e..e1abccc1dff 100644 --- a/app/validators/line_code_validator.rb +++ b/app/validators/line_code_validator.rb @@ -7,7 +7,7 @@ class LineCodeValidator < ActiveModel::EachValidator PATTERN = /\A[a-z0-9]+_\d+_\d+\z/.freeze def validate_each(record, attribute, value) - unless value =~ PATTERN + unless PATTERN.match?(value) record.errors.add(attribute, "must be a valid line code") end end diff --git a/app/validators/namespace_name_validator.rb b/app/validators/namespace_name_validator.rb index fb1c241037c..b3a486013f0 100644 --- a/app/validators/namespace_name_validator.rb +++ b/app/validators/namespace_name_validator.rb @@ -5,7 +5,7 @@ # Custom validator for GitLab namespace name strings. class NamespaceNameValidator < ActiveModel::EachValidator def validate_each(record, attribute, value) - unless value =~ Gitlab::Regex.namespace_name_regex + unless value&.match?(Gitlab::Regex.namespace_name_regex) record.errors.add(attribute, Gitlab::Regex.namespace_name_regex_message) end end diff --git a/app/validators/url_validator.rb b/app/validators/url_validator.rb index 3fd015c3cf5..a35e857db9a 100644 --- a/app/validators/url_validator.rb +++ b/app/validators/url_validator.rb @@ -35,7 +35,7 @@ # validates :web_url, url: { ports: [80, 443] } # end class UrlValidator < ActiveModel::EachValidator - DEFAULT_PROTOCOLS = %w(http https).freeze + DEFAULT_PROTOCOLS = %w[http https].freeze attr_reader :record @@ -43,7 +43,7 @@ class UrlValidator < ActiveModel::EachValidator @record = record unless value.present? - record.errors.add(attribute, 'must be a valid URL') + record.errors.add(attribute, "must be a valid URL") return end @@ -72,14 +72,14 @@ class UrlValidator < ActiveModel::EachValidator allow_local_network: true, ascii_only: false, enforce_user: false, - enforce_sanitization: false + enforce_sanitization: false, } end def current_options - options = self.options.map do |option, value| + options = self.options.map { |option, value| [option, value.is_a?(Proc) ? value.call(record) : value] - end.to_h + }.to_h default_options.merge(options) end diff --git a/app/validators/variable_duplicates_validator.rb b/app/validators/variable_duplicates_validator.rb index d36a56e81b9..8b13b8e7bf0 100644 --- a/app/validators/variable_duplicates_validator.rb +++ b/app/validators/variable_duplicates_validator.rb @@ -10,9 +10,9 @@ class VariableDuplicatesValidator < ActiveModel::EachValidator return if record.errors.include?(:"#{attribute}.key") if options[:scope] - scoped = value.group_by do |variable| + scoped = value.group_by { |variable| Array(options[:scope]).map { |attr| variable.send(attr) } # rubocop:disable GitlabSecurity/PublicSend - end + } scoped.each_value { |scope| validate_duplicates(record, attribute, scope) } else validate_duplicates(record, attribute, value) diff --git a/app/views/dashboard/issues.atom.builder b/app/views/dashboard/issues.atom.builder index 6034389b897..0a2c02e7158 100644 --- a/app/views/dashboard/issues.atom.builder +++ b/app/views/dashboard/issues.atom.builder @@ -5,5 +5,5 @@ xml.link href: issues_dashboard_url, rel: "alternate", type: "text/html" xml.id issues_dashboard_url xml.updated @issues.first.updated_at.xmlschema if @issues.reorder(nil).any? -xml << render(partial: 'issues/issue', collection: @issues) if @issues.reorder(nil).any? +xml << render(partial: "issues/issue", collection: @issues) if @issues.reorder(nil).any? # rubocop: enable CodeReuse/ActiveRecord diff --git a/app/views/dashboard/projects/index.atom.builder b/app/views/dashboard/projects/index.atom.builder index 747c53b440e..4d13cebab26 100644 --- a/app/views/dashboard/projects/index.atom.builder +++ b/app/views/dashboard/projects/index.atom.builder @@ -4,4 +4,4 @@ xml.link href: dashboard_projects_url, rel: "alternate", type: "text/html" xml.id dashboard_projects_url xml.updated @events[0].updated_at.xmlschema if @events[0] -xml << render(partial: 'events/event', collection: @events) if @events.any? +xml << render(partial: "events/event", collection: @events) if @events.any? diff --git a/app/views/groups/issues.atom.builder b/app/views/groups/issues.atom.builder index 2fd96c9d158..8ac77d66ecc 100644 --- a/app/views/groups/issues.atom.builder +++ b/app/views/groups/issues.atom.builder @@ -5,5 +5,5 @@ xml.link href: issues_group_url, rel: "alternate", type: "text/html" xml.id issues_group_url xml.updated @issues.first.updated_at.xmlschema if @issues.reorder(nil).any? -xml << render(partial: 'issues/issue', collection: @issues) if @issues.reorder(nil).any? +xml << render(partial: "issues/issue", collection: @issues) if @issues.reorder(nil).any? # rubocop: enable CodeReuse/ActiveRecord diff --git a/app/views/issues/_issues_calendar.ics.ruby b/app/views/issues/_issues_calendar.ics.ruby index 94c3099ace2..965ca78e77f 100644 --- a/app/views/issues/_issues_calendar.ics.ruby +++ b/app/views/issues/_issues_calendar.ics.ruby @@ -1,6 +1,6 @@ cal = Icalendar::Calendar.new -cal.prodid = '-//GitLab//NONSGML GitLab//EN' -cal.x_wr_calname = 'GitLab Issues' +cal.prodid = "-//GitLab//NONSGML GitLab//EN" +cal.x_wr_calname = "GitLab Issues" # rubocop: disable CodeReuse/ActiveRecord @issues.preload(project: :namespace).each do |issue| @@ -9,7 +9,7 @@ cal.x_wr_calname = 'GitLab Issues' event.summary = "#{issue.title} (in #{issue.project.full_path})" event.description = "Find out more at #{issue_url(issue)}" event.url = issue_url(issue) - event.transp = 'TRANSPARENT' + event.transp = "TRANSPARENT" end end # rubocop: enable CodeReuse/ActiveRecord diff --git a/app/views/layouts/xml.atom.builder b/app/views/layouts/xml.atom.builder index 4ee09cb87a1..ae506b7c3bf 100644 --- a/app/views/layouts/xml.atom.builder +++ b/app/views/layouts/xml.atom.builder @@ -1,4 +1,4 @@ xml.instruct! -xml.feed 'xmlns' => 'http://www.w3.org/2005/Atom', 'xmlns:media' => 'http://search.yahoo.com/mrss/' do +xml.feed "xmlns" => "http://www.w3.org/2005/Atom", "xmlns:media" => "http://search.yahoo.com/mrss/" do xml << yield end diff --git a/app/views/projects/commits/_commit.atom.builder b/app/views/projects/commits/_commit.atom.builder index 640b5ecf99e..98ff8ac914d 100644 --- a/app/views/projects/commits/_commit.atom.builder +++ b/app/views/projects/commits/_commit.atom.builder @@ -10,5 +10,5 @@ xml.entry do xml.email commit.author_email end - xml.summary markdown_field(commit, :description), type: 'html' + xml.summary markdown_field(commit, :description), type: "html" end diff --git a/app/views/projects/issues/index.atom.builder b/app/views/projects/issues/index.atom.builder index 6566866be82..54b46de4a8a 100644 --- a/app/views/projects/issues/index.atom.builder +++ b/app/views/projects/issues/index.atom.builder @@ -5,5 +5,5 @@ xml.link href: project_issues_url(@project), rel: "alternate", type: "text/ht xml.id project_issues_url(@project) xml.updated @issues.first.updated_at.xmlschema if @issues.reorder(nil).any? -xml << render(partial: 'issues/issue', collection: @issues) if @issues.reorder(nil).any? +xml << render(partial: "issues/issue", collection: @issues) if @issues.reorder(nil).any? # rubocop: enable CodeReuse/ActiveRecord diff --git a/app/views/projects/tags/_tag.atom.builder b/app/views/projects/tags/_tag.atom.builder index 60d4b21b9d1..08c17cd6b1a 100644 --- a/app/views/projects/tags/_tag.atom.builder +++ b/app/views/projects/tags/_tag.atom.builder @@ -8,9 +8,9 @@ if commit xml.link href: tag_url xml.title truncate(tag.name, length: 80) xml.summary strip_gpg_signature(tag.message) - xml.content markdown_field(release, :description), type: 'html' + xml.content markdown_field(release, :description), type: "html" xml.updated release.updated_at.xmlschema if release - xml.media :thumbnail, width: '40', height: '40', url: image_url(avatar_icon_for_email(commit.author_email)) + xml.media :thumbnail, width: "40", height: "40", url: image_url(avatar_icon_for_email(commit.author_email)) xml.author do |author| xml.name commit.author_name xml.email commit.author_email diff --git a/app/views/projects/tags/index.atom.builder b/app/views/projects/tags/index.atom.builder index b9b58b7beaa..268405821e2 100644 --- a/app/views/projects/tags/index.atom.builder +++ b/app/views/projects/tags/index.atom.builder @@ -1,7 +1,7 @@ xml.title "#{@project.name} tags" -xml.link href: project_tags_url(@project, @ref, rss_url_options), rel: 'self', type: 'application/atom+xml' -xml.link href: project_tags_url(@project, @ref), rel: 'alternate', type: 'text/html' +xml.link href: project_tags_url(@project, @ref, rss_url_options), rel: "self", type: "application/atom+xml" +xml.link href: project_tags_url(@project, @ref), rel: "alternate", type: "text/html" xml.id project_tags_url(@project, @ref) xml.updated @releases.first.updated_at.xmlschema if @releases.any? -xml << render(partial: 'tag', collection: @tags) if @tags.any? +xml << render(partial: "tag", collection: @tags) if @tags.any? diff --git a/app/workers/background_migration_worker.rb b/app/workers/background_migration_worker.rb index 688b600649a..da796b5fce5 100644 --- a/app/workers/background_migration_worker.rb +++ b/app/workers/background_migration_worker.rb @@ -84,7 +84,7 @@ class BackgroundMigrationWorker def database_unhealthy_counter Gitlab::Metrics.counter( :background_migration_database_health_reschedules, - 'The number of times a background migration is rescheduled because the database is unhealthy.' + "The number of times a background migration is rescheduled because the database is unhealthy." ) end end diff --git a/app/workers/concerns/application_worker.rb b/app/workers/concerns/application_worker.rb index d64c2f82a09..e6f5db7cf80 100644 --- a/app/workers/concerns/application_worker.rb +++ b/app/workers/concerns/application_worker.rb @@ -17,17 +17,17 @@ module ApplicationWorker end def set_queue - queue_name = [queue_namespace, base_queue_name].compact.join(':') + queue_name = [queue_namespace, base_queue_name].compact.join(":") sidekiq_options queue: queue_name # rubocop:disable Cop/SidekiqOptionsQueue end def base_queue_name name - .sub(/\AGitlab::/, '') - .sub(/Worker\z/, '') + .sub(/\AGitlab::/, "") + .sub(/Worker\z/, "") .underscore - .tr('/', '_') + .tr("/", "_") end def queue_namespace(new_namespace = nil) @@ -36,16 +36,16 @@ module ApplicationWorker set_queue else - get_sidekiq_options['queue_namespace']&.to_s + get_sidekiq_options["queue_namespace"]&.to_s end end def queue - get_sidekiq_options['queue'].to_s + get_sidekiq_options["queue"].to_s end def bulk_perform_async(args_list) - Sidekiq::Client.push_bulk('class' => self, 'args' => args_list) + Sidekiq::Client.push_bulk("class" => self, "args" => args_list) end def bulk_perform_in(delay, args_list) @@ -53,10 +53,10 @@ module ApplicationWorker schedule = now + delay.to_i if schedule <= now - raise ArgumentError, 'The schedule time must be in the future!' + raise ArgumentError, "The schedule time must be in the future!" end - Sidekiq::Client.push_bulk('class' => self, 'args' => args_list, 'at' => schedule) + Sidekiq::Client.push_bulk("class" => self, "args" => args_list, "at" => schedule) end end end diff --git a/app/workers/concerns/auto_devops_queue.rb b/app/workers/concerns/auto_devops_queue.rb index aba928ccaab..77f45ff7e43 100644 --- a/app/workers/concerns/auto_devops_queue.rb +++ b/app/workers/concerns/auto_devops_queue.rb @@ -1,5 +1,5 @@ # frozen_string_literal: true -# + module AutoDevopsQueue extend ActiveSupport::Concern diff --git a/app/workers/concerns/gitlab/github_import/notify_upon_death.rb b/app/workers/concerns/gitlab/github_import/notify_upon_death.rb index 3d7120665b6..d5b2da22c8c 100644 --- a/app/workers/concerns/gitlab/github_import/notify_upon_death.rb +++ b/app/workers/concerns/gitlab/github_import/notify_upon_death.rb @@ -18,8 +18,8 @@ module Gitlab # AdvanceStageWorker. This prevents the entire import from getting stuck # just because 1 job threw too many errors. sidekiq_retries_exhausted do |job| - args = job['args'] - jid = job['jid'] + args = job["args"] + jid = job["jid"] if args.length == 3 && (key = args.last) && key.is_a?(String) JobWaiter.notify(key, jid) diff --git a/app/workers/concerns/gitlab/github_import/stage_methods.rb b/app/workers/concerns/gitlab/github_import/stage_methods.rb index e2dee315cde..07bcdc121f8 100644 --- a/app/workers/concerns/gitlab/github_import/stage_methods.rb +++ b/app/workers/concerns/gitlab/github_import/stage_methods.rb @@ -24,7 +24,7 @@ module Gitlab def find_project(id) # If the project has been marked as failed we want to bail out # automatically. - Project.joins_import_state.where(import_state: { status: :started }).find_by(id: id) + Project.joins_import_state.where(import_state: {status: :started}).find_by(id: id) end # rubocop: enable CodeReuse/ActiveRecord end diff --git a/app/workers/concerns/project_import_options.rb b/app/workers/concerns/project_import_options.rb index 2baf768bfd1..7b1c5277355 100644 --- a/app/workers/concerns/project_import_options.rb +++ b/app/workers/concerns/project_import_options.rb @@ -10,16 +10,16 @@ module ProjectImportOptions # We only want to mark the project as failed once we exhausted all retries sidekiq_retries_exhausted do |job| - project = Project.find(job['args'].first) + project = Project.find(job["args"].first) action = if project.forked? - "fork" - else - "import" - end + "fork" + else + "import" + end - project.import_state.mark_as_failed(_("Every %{action} attempt has failed: %{job_error_message}. Please try again.") % { action: action, job_error_message: job['error_message'] }) - Sidekiq.logger.warn "Failed #{job['class']} with #{job['args']}: #{job['error_message']}" + project.import_state.mark_as_failed(_("Every %{action} attempt has failed: %{job_error_message}. Please try again.") % {action: action, job_error_message: job["error_message"]}) + Sidekiq.logger.warn "Failed #{job["class"]} with #{job["args"]}: #{job["error_message"]}" end end end diff --git a/app/workers/concerns/project_start_import.rb b/app/workers/concerns/project_start_import.rb index 4462bc51a24..7679c467443 100644 --- a/app/workers/concerns/project_start_import.rb +++ b/app/workers/concerns/project_start_import.rb @@ -3,7 +3,7 @@ # Used in EE by mirroring module ProjectStartImport def start(import_state) - if import_state.started? && import_state.jid == self.jid + if import_state.started? && import_state.jid == jid return true end diff --git a/app/workers/concerns/waitable_worker.rb b/app/workers/concerns/waitable_worker.rb index 27b94a82444..17946bbc5ca 100644 --- a/app/workers/concerns/waitable_worker.rb +++ b/app/workers/concerns/waitable_worker.rb @@ -25,11 +25,9 @@ module WaitableWorker failed = [] args_list.each do |args| - begin - new.perform(*args) - rescue - failed << args - end + new.perform(*args) + rescue + failed << args end bulk_perform_async(failed) if failed.present? diff --git a/app/workers/create_gpg_signature_worker.rb b/app/workers/create_gpg_signature_worker.rb index 49c7a403838..2827529cc1c 100644 --- a/app/workers/create_gpg_signature_worker.rb +++ b/app/workers/create_gpg_signature_worker.rb @@ -20,11 +20,9 @@ class CreateGpgSignatureWorker # This calculates and caches the signature in the database commits.each do |commit| - begin - Gitlab::Gpg::Commit.new(commit).signature - rescue => e - Rails.logger.error("Failed to create signature for commit #{commit.id}. Error: #{e.message}") - end + Gitlab::Gpg::Commit.new(commit).signature + rescue => e + Rails.logger.error("Failed to create signature for commit #{commit.id}. Error: #{e.message}") end end # rubocop: enable CodeReuse/ActiveRecord diff --git a/app/workers/delete_stored_files_worker.rb b/app/workers/delete_stored_files_worker.rb index ff7931849d8..6341d70386e 100644 --- a/app/workers/delete_stored_files_worker.rb +++ b/app/workers/delete_stored_files_worker.rb @@ -6,8 +6,8 @@ class DeleteStoredFilesWorker def perform(class_name, keys) klass = begin class_name.constantize - rescue NameError - nil + rescue NameError + nil end unless klass diff --git a/app/workers/emails_on_push_worker.rb b/app/workers/emails_on_push_worker.rb index 17ad1d5ab88..ab254d8968e 100644 --- a/app/workers/emails_on_push_worker.rb +++ b/app/workers/emails_on_push_worker.rb @@ -8,8 +8,8 @@ class EmailsOnPushWorker def perform(project_id, recipients, push_data, options = {}) options.symbolize_keys! options.reverse_merge!( - send_from_committer_email: false, - disable_diffs: false + send_from_committer_email: false, + disable_diffs: false ) send_from_committer_email = options[:send_from_committer_email] disable_diffs = options[:disable_diffs] @@ -52,24 +52,22 @@ class EmailsOnPushWorker end valid_recipients(recipients).each do |recipient| - begin - send_email( - recipient, - project_id, - author_id: author_id, - ref: ref, - action: action, - compare: compare, - reverse_compare: reverse_compare, - diff_refs: diff_refs, - send_from_committer_email: send_from_committer_email, - disable_diffs: disable_diffs - ) - - # These are input errors and won't be corrected even if Sidekiq retries - rescue Net::SMTPFatalError, Net::SMTPSyntaxError => e - logger.info("Failed to send e-mail for project '#{project.full_name}' to #{recipient}: #{e}") - end + send_email( + recipient, + project_id, + author_id: author_id, + ref: ref, + action: action, + compare: compare, + reverse_compare: reverse_compare, + diff_refs: diff_refs, + send_from_committer_email: send_from_committer_email, + disable_diffs: disable_diffs + ) + + # These are input errors and won't be corrected even if Sidekiq retries + rescue Net::SMTPFatalError, Net::SMTPSyntaxError => e + logger.info("Failed to send e-mail for project '#{project.full_name}' to #{recipient}: #{e}") end ensure @email = nil @@ -92,7 +90,7 @@ class EmailsOnPushWorker def valid_recipients(recipients) recipients.split.select do |recipient| - recipient.include?('@') + recipient.include?("@") end end end diff --git a/app/workers/expire_build_artifacts_worker.rb b/app/workers/expire_build_artifacts_worker.rb index 251e95c68d5..5b38dd23eea 100644 --- a/app/workers/expire_build_artifacts_worker.rb +++ b/app/workers/expire_build_artifacts_worker.rb @@ -18,7 +18,7 @@ class ExpireBuildArtifactsWorker # rubocop: disable CodeReuse/ActiveRecord def perform_legacy_artifacts_removal - Rails.logger.info 'Scheduling removal of build artifacts' + Rails.logger.info "Scheduling removal of build artifacts" build_ids = Ci::Build.with_expired_artifacts.pluck(:id) build_ids = build_ids.map { |build_id| [build_id] } diff --git a/app/workers/gitlab/github_import/advance_stage_worker.rb b/app/workers/gitlab/github_import/advance_stage_worker.rb index 0b3437a8a33..97d1cbab541 100644 --- a/app/workers/gitlab/github_import/advance_stage_worker.rb +++ b/app/workers/gitlab/github_import/advance_stage_worker.rb @@ -22,7 +22,7 @@ module Gitlab issues_and_diff_notes: Stage::ImportIssuesAndDiffNotesWorker, notes: Stage::ImportNotesWorker, lfs_objects: Stage::ImportLfsObjectsWorker, - finish: Stage::FinishImportWorker + finish: Stage::FinishImportWorker, }.freeze # project_id - The ID of the project being imported. diff --git a/app/workers/gitlab/github_import/import_diff_note_worker.rb b/app/workers/gitlab/github_import/import_diff_note_worker.rb index ef2a74c51c5..3e076812ab3 100644 --- a/app/workers/gitlab/github_import/import_diff_note_worker.rb +++ b/app/workers/gitlab/github_import/import_diff_note_worker.rb @@ -18,7 +18,7 @@ module Gitlab end def counter_description - 'The number of imported GitHub pull request review comments' + "The number of imported GitHub pull request review comments" end end end diff --git a/app/workers/gitlab/github_import/import_issue_worker.rb b/app/workers/gitlab/github_import/import_issue_worker.rb index 1b081ae5966..aa8a7649a5f 100644 --- a/app/workers/gitlab/github_import/import_issue_worker.rb +++ b/app/workers/gitlab/github_import/import_issue_worker.rb @@ -18,7 +18,7 @@ module Gitlab end def counter_description - 'The number of imported GitHub issues' + "The number of imported GitHub issues" end end end diff --git a/app/workers/gitlab/github_import/import_lfs_object_worker.rb b/app/workers/gitlab/github_import/import_lfs_object_worker.rb index 520c5cb091a..264e939f183 100644 --- a/app/workers/gitlab/github_import/import_lfs_object_worker.rb +++ b/app/workers/gitlab/github_import/import_lfs_object_worker.rb @@ -18,7 +18,7 @@ module Gitlab end def counter_description - 'The number of imported GitHub Lfs Objects' + "The number of imported GitHub Lfs Objects" end end end diff --git a/app/workers/gitlab/github_import/import_note_worker.rb b/app/workers/gitlab/github_import/import_note_worker.rb index d2b4c36a5b9..a7a839168ab 100644 --- a/app/workers/gitlab/github_import/import_note_worker.rb +++ b/app/workers/gitlab/github_import/import_note_worker.rb @@ -18,7 +18,7 @@ module Gitlab end def counter_description - 'The number of imported GitHub comments' + "The number of imported GitHub comments" end end end diff --git a/app/workers/gitlab/github_import/import_pull_request_worker.rb b/app/workers/gitlab/github_import/import_pull_request_worker.rb index 62a6da152a3..ca78c6e0e12 100644 --- a/app/workers/gitlab/github_import/import_pull_request_worker.rb +++ b/app/workers/gitlab/github_import/import_pull_request_worker.rb @@ -18,7 +18,7 @@ module Gitlab end def counter_description - 'The number of imported GitHub pull requests' + "The number of imported GitHub pull requests" end end end diff --git a/app/workers/gitlab/github_import/stage/finish_import_worker.rb b/app/workers/gitlab/github_import/stage/finish_import_worker.rb index a779e631516..d8699b9b7f5 100644 --- a/app/workers/gitlab/github_import/stage/finish_import_worker.rb +++ b/app/workers/gitlab/github_import/stage/finish_import_worker.rb @@ -18,7 +18,7 @@ module Gitlab duration = Time.zone.now - project.created_at path = project.full_path - histogram.observe({ project: path }, duration) + histogram.observe({project: path}, duration) counter.increment logger.info("GitHub importer finished for #{path} in #{duration.round(2)} seconds") @@ -27,14 +27,14 @@ module Gitlab def histogram @histogram ||= Gitlab::Metrics.histogram( :github_importer_total_duration_seconds, - 'Total time spent importing GitHub projects, in seconds' + "Total time spent importing GitHub projects, in seconds" ) end def counter @counter ||= Gitlab::Metrics.counter( :github_importer_imported_projects, - 'The number of imported GitHub projects' + "The number of imported GitHub projects" ) end end diff --git a/app/workers/gitlab/github_import/stage/import_base_data_worker.rb b/app/workers/gitlab/github_import/stage/import_base_data_worker.rb index ccfed2ae187..fb81071ccaf 100644 --- a/app/workers/gitlab/github_import/stage/import_base_data_worker.rb +++ b/app/workers/gitlab/github_import/stage/import_base_data_worker.rb @@ -13,7 +13,7 @@ module Gitlab IMPORTERS = [ Importer::LabelsImporter, Importer::MilestonesImporter, - Importer::ReleasesImporter + Importer::ReleasesImporter, ].freeze # client - An instance of Gitlab::GithubImport::Client. diff --git a/app/workers/gitlab/github_import/stage/import_issues_and_diff_notes_worker.rb b/app/workers/gitlab/github_import/stage/import_issues_and_diff_notes_worker.rb index 7007754ff2e..5c114aa8cd5 100644 --- a/app/workers/gitlab/github_import/stage/import_issues_and_diff_notes_worker.rb +++ b/app/workers/gitlab/github_import/stage/import_issues_and_diff_notes_worker.rb @@ -12,16 +12,16 @@ module Gitlab # on as we also use these to enrich pull requests with assigned labels. IMPORTERS = [ Importer::IssuesImporter, - Importer::DiffNotesImporter + Importer::DiffNotesImporter, ].freeze # client - An instance of Gitlab::GithubImport::Client. # project - An instance of Project. def import(client, project) - waiters = IMPORTERS.each_with_object({}) do |klass, hash| + waiters = IMPORTERS.each_with_object({}) { |klass, hash| waiter = klass.new(project, client).execute hash[waiter.key] = waiter.jobs_remaining - end + } AdvanceStageWorker.perform_async(project.id, waiters, :notes) end diff --git a/app/workers/gitlab/github_import/stage/import_lfs_objects_worker.rb b/app/workers/gitlab/github_import/stage/import_lfs_objects_worker.rb index 29257603a9d..016eda1bb3f 100644 --- a/app/workers/gitlab/github_import/stage/import_lfs_objects_worker.rb +++ b/app/workers/gitlab/github_import/stage/import_lfs_objects_worker.rb @@ -22,7 +22,7 @@ module Gitlab AdvanceStageWorker.perform_async( project.id, - { waiter.key => waiter.jobs_remaining }, + {waiter.key => waiter.jobs_remaining}, :finish ) end diff --git a/app/workers/gitlab/github_import/stage/import_notes_worker.rb b/app/workers/gitlab/github_import/stage/import_notes_worker.rb index ccf0013180d..1dd08acaff0 100644 --- a/app/workers/gitlab/github_import/stage/import_notes_worker.rb +++ b/app/workers/gitlab/github_import/stage/import_notes_worker.rb @@ -17,7 +17,7 @@ module Gitlab AdvanceStageWorker.perform_async( project.id, - { waiter.key => waiter.jobs_remaining }, + {waiter.key => waiter.jobs_remaining}, :lfs_objects ) end diff --git a/app/workers/gitlab/github_import/stage/import_pull_requests_worker.rb b/app/workers/gitlab/github_import/stage/import_pull_requests_worker.rb index 37a7a7f4ba0..f4c4d955f1b 100644 --- a/app/workers/gitlab/github_import/stage/import_pull_requests_worker.rb +++ b/app/workers/gitlab/github_import/stage/import_pull_requests_worker.rb @@ -19,7 +19,7 @@ module Gitlab AdvanceStageWorker.perform_async( project.id, - { waiter.key => waiter.jobs_remaining }, + {waiter.key => waiter.jobs_remaining}, :issues_and_diff_notes ) end diff --git a/app/workers/gitlab/github_import/stage/import_repository_worker.rb b/app/workers/gitlab/github_import/stage/import_repository_worker.rb index 4d16cef1130..d2bd7de1cab 100644 --- a/app/workers/gitlab/github_import/stage/import_repository_worker.rb +++ b/app/workers/gitlab/github_import/stage/import_repository_worker.rb @@ -29,7 +29,7 @@ module Gitlab def counter Gitlab::Metrics.counter( :github_importer_imported_repositories, - 'The number of imported GitHub repositories' + "The number of imported GitHub repositories" ) end end diff --git a/app/workers/gitlab_usage_ping_worker.rb b/app/workers/gitlab_usage_ping_worker.rb index b75e724ca98..eb1c7d1991e 100644 --- a/app/workers/gitlab_usage_ping_worker.rb +++ b/app/workers/gitlab_usage_ping_worker.rb @@ -16,6 +16,6 @@ class GitlabUsagePingWorker private def try_obtain_lease - Gitlab::ExclusiveLease.new('gitlab_usage_ping_worker:ping', timeout: LEASE_TIMEOUT).try_obtain + Gitlab::ExclusiveLease.new("gitlab_usage_ping_worker:ping", timeout: LEASE_TIMEOUT).try_obtain end end diff --git a/app/workers/import_issues_csv_worker.rb b/app/workers/import_issues_csv_worker.rb index d44fdfec8ae..42b70cb60e5 100644 --- a/app/workers/import_issues_csv_worker.rb +++ b/app/workers/import_issues_csv_worker.rb @@ -4,7 +4,7 @@ class ImportIssuesCsvWorker include ApplicationWorker sidekiq_retries_exhausted do |job| - Upload.find(job['args'][2]).destroy + Upload.find(job["args"][2]).destroy end def perform(current_user_id, project_id, upload_id) diff --git a/app/workers/irker_worker.rb b/app/workers/irker_worker.rb index 29631c6b7ac..c44c263706e 100644 --- a/app/workers/irker_worker.rb +++ b/app/workers/irker_worker.rb @@ -1,7 +1,7 @@ # frozen_string_literal: true -require 'json' -require 'socket' +require "json" +require "socket" class IrkerWorker include ApplicationWorker @@ -12,9 +12,9 @@ class IrkerWorker # Get config parameters return false unless init_perform settings, chans, colors - repo_name = push_data['repository']['name'] - committer = push_data['user_name'] - branch = push_data['ref'].gsub(%r'refs/[^/]*/', '') + repo_name = push_data["repository"]["name"] + committer = push_data["user_name"] + branch = push_data["ref"].gsub(%r{refs/[^/]*/}, "") if @colors repo_name = "\x0304#{repo_name}\x0f" @@ -36,7 +36,7 @@ class IrkerWorker def init_perform(set, chans, colors) @colors = colors @channels = chans - start_connection set['server_host'], set['server_port'] + start_connection set["server_host"], set["server_port"] end def start_connection(irker_server, irker_port) @@ -50,7 +50,7 @@ class IrkerWorker end def sendtoirker(privmsg) - to_send = { to: @channels, privmsg: privmsg } + to_send = {to: @channels, privmsg: privmsg} @socket.puts JSON.dump(to_send) end @@ -59,9 +59,9 @@ class IrkerWorker end def send_branch_updates(push_data, project, repo_name, committer, branch) - if Gitlab::Git.blank_ref?(push_data['before']) + if Gitlab::Git.blank_ref?(push_data["before"]) send_new_branch project, repo_name, committer, branch - elsif Gitlab::Git.blank_ref?(push_data['after']) + elsif Gitlab::Git.blank_ref?(push_data["after"]) send_del_branch repo_name, committer, branch end end @@ -82,29 +82,29 @@ class IrkerWorker end def send_commits(push_data, project, repo_name, committer, branch) - return if push_data['total_commits_count'] == 0 + return if push_data["total_commits_count"] == 0 # Next message is for number of commit pushed, if any - if Gitlab::Git.blank_ref?(push_data['before']) + if Gitlab::Git.blank_ref?(push_data["before"]) # Tweak on push_data["before"] in order to have a nice compare URL - push_data['before'] = before_on_new_branch push_data, project + push_data["before"] = before_on_new_branch push_data, project end send_commits_count(push_data, project, repo_name, committer, branch) # One message per commit, limited by 3 messages (same limit as the # github irc hook) - commits = push_data['commits'].first(3) + commits = push_data["commits"].first(3) commits.each do |hook_attrs| send_one_commit project, hook_attrs, repo_name, branch end end def before_on_new_branch(push_data, project) - commit = commit_from_id project, push_data['commits'][0]['id'] + commit = commit_from_id project, push_data["commits"][0]["id"] parents = commit.parents # Return old value if there's no new one - return push_data['before'] if parents.empty? + return push_data["before"] if parents.empty? # Or return the first parent-commit parents[0].id @@ -112,26 +112,26 @@ class IrkerWorker def send_commits_count(data, project, repo, committer, branch) url = compare_url data, project.full_path - commits = colorize_commits data['total_commits_count'] + commits = colorize_commits data["total_commits_count"] - new_commits = 'new commit'.pluralize(data['total_commits_count']) + new_commits = "new commit".pluralize(data["total_commits_count"]) sendtoirker "[#{repo}] #{committer} pushed #{commits} #{new_commits} " \ "to #{branch}: #{url}" end def compare_url(data, repo_path) - sha1 = Commit.truncate_sha(data['before']) - sha2 = Commit.truncate_sha(data['after']) + sha1 = Commit.truncate_sha(data["before"]) + sha2 = Commit.truncate_sha(data["after"]) compare_url = "#{Gitlab.config.gitlab.url}/#{repo_path}/compare" \ "/#{sha1}...#{sha2}" colorize_url compare_url end def send_one_commit(project, hook_attrs, repo_name, branch) - commit = commit_from_id project, hook_attrs['id'] - sha = colorize_sha Commit.truncate_sha(hook_attrs['id']) - author = hook_attrs['author']['name'] - files = colorize_nb_files(files_count commit) + commit = commit_from_id project, hook_attrs["id"] + sha = colorize_sha Commit.truncate_sha(hook_attrs["id"]) + author = hook_attrs["author"]["name"] + files = colorize_nb_files(files_count(commit)) title = commit.title sendtoirker "#{repo_name}/#{branch} #{sha} #{author} (#{files}): #{title}" diff --git a/app/workers/mail_scheduler/notification_service_worker.rb b/app/workers/mail_scheduler/notification_service_worker.rb index 421fbf04e28..7b455e0439f 100644 --- a/app/workers/mail_scheduler/notification_service_worker.rb +++ b/app/workers/mail_scheduler/notification_service_worker.rb @@ -1,6 +1,6 @@ # frozen_string_literal: true -require 'active_job/arguments' +require "active_job/arguments" module MailScheduler class NotificationServiceWorker @@ -51,7 +51,7 @@ module MailScheduler def serialize_argument(argument) case argument - when -> (arg) { arg.respond_to?(:permitted?) } + when ->(arg) { arg.respond_to?(:permitted?) } serialize_hash(argument.to_h).tap do |result| result[WITH_INDIFFERENT_ACCESS_KEY] = serialize_argument(true) end @@ -62,7 +62,7 @@ module MailScheduler end # Make sure we remove this patch starting with Rails 6.0. - if Rails.version.start_with?('6.0') + if Rails.version.start_with?("6.0") raise <<~MSG Please remove the patch `Arguments` module and use `ActiveJob::Arguments` again. MSG diff --git a/app/workers/namespaceless_project_destroy_worker.rb b/app/workers/namespaceless_project_destroy_worker.rb index f6e98746055..1f694308830 100644 --- a/app/workers/namespaceless_project_destroy_worker.rb +++ b/app/workers/namespaceless_project_destroy_worker.rb @@ -31,6 +31,6 @@ class NamespacelessProjectDestroyWorker def unlink_fork(project) merge_requests = project.forked_from_project.merge_requests.opened.from_project(project) - merge_requests.update_all(state: 'closed') + merge_requests.update_all(state: "closed") end end diff --git a/app/workers/object_storage/migrate_uploads_worker.rb b/app/workers/object_storage/migrate_uploads_worker.rb index fe5d27b087d..206eb71b898 100644 --- a/app/workers/object_storage/migrate_uploads_worker.rb +++ b/app/workers/object_storage/migrate_uploads_worker.rb @@ -126,11 +126,9 @@ module ObjectStorage def process_uploader(uploader) MigrationResult.new(uploader.upload).tap do |result| - begin - uploader.migrate!(@to_store) - rescue => e - result.error = e - end + uploader.migrate!(@to_store) + rescue => e + result.error = e end end end diff --git a/app/workers/pipeline_schedule_worker.rb b/app/workers/pipeline_schedule_worker.rb index ac4e9710f33..15703f059a0 100644 --- a/app/workers/pipeline_schedule_worker.rb +++ b/app/workers/pipeline_schedule_worker.rb @@ -8,16 +8,15 @@ class PipelineScheduleWorker def perform Ci::PipelineSchedule.active.where("next_run_at < ?", Time.now) .preload(:owner, :project).find_each do |schedule| - begin - Ci::CreatePipelineService.new(schedule.project, - schedule.owner, - ref: schedule.ref) - .execute!(:schedule, ignore_skip_ci: true, save_on_errors: true, schedule: schedule) - rescue => e - error(schedule, e) - ensure - schedule.schedule_next_run! - end + + Ci::CreatePipelineService.new(schedule.project, + schedule.owner, + ref: schedule.ref) + .execute!(:schedule, ignore_skip_ci: true, save_on_errors: true, schedule: schedule) + rescue => e + error(schedule, e) + ensure + schedule.schedule_next_run! end end # rubocop: enable CodeReuse/ActiveRecord @@ -32,13 +31,13 @@ class PipelineScheduleWorker Gitlab::Sentry .track_exception(error, - issue_url: 'https://gitlab.com/gitlab-org/gitlab-ce/issues/41231', - extra: { schedule_id: schedule.id }) + issue_url: "https://gitlab.com/gitlab-org/gitlab-ce/issues/41231", + extra: {schedule_id: schedule.id}) end def failed_creation_counter @failed_creation_counter ||= Gitlab::Metrics.counter(:pipeline_schedule_creation_failed_total, - "Counter of failed attempts of pipeline schedule creation") + "Counter of failed attempts of pipeline schedule creation") end end diff --git a/app/workers/post_receive.rb b/app/workers/post_receive.rb index bbd4ab159e4..dc8b73d8b41 100644 --- a/app/workers/post_receive.rb +++ b/app/workers/post_receive.rb @@ -11,10 +11,10 @@ class PostReceive return false end - changes = Base64.decode64(changes) unless changes.include?(' ') + changes = Base64.decode64(changes) unless changes.include?(" ") # Use Sidekiq.logger so arguments can be correlated with execution # time and thread ID's. - Sidekiq.logger.info "changes: #{changes.inspect}" if ENV['SIDEKIQ_LOG_ARGUMENTS'] + Sidekiq.logger.info "changes: #{changes.inspect}" if ENV["SIDEKIQ_LOG_ARGUMENTS"] post_received = Gitlab::GitPostReceive.new(project, identifier, changes, push_options) if is_wiki @@ -44,7 +44,8 @@ class PostReceive oldrev: oldrev, newrev: newrev, ref: ref, - push_options: post_received.push_options).execute + push_options: post_received.push_options + ).execute elsif Gitlab::Git.branch_ref?(ref) GitPushService.new( post_received.project, @@ -52,7 +53,8 @@ class PostReceive oldrev: oldrev, newrev: newrev, ref: ref, - push_options: post_received.push_options).execute + push_options: post_received.push_options + ).execute end changes << Gitlab::DataBuilder::Repository.single_change(oldrev, newrev, ref) diff --git a/app/workers/process_commit_worker.rb b/app/workers/process_commit_worker.rb index 29a7f8e691a..13837c4025a 100644 --- a/app/workers/process_commit_worker.rb +++ b/app/workers/process_commit_worker.rb @@ -64,7 +64,7 @@ class ProcessCommitWorker # rubocop: enable CodeReuse/ActiveRecord def build_commit(project, hash) - date_suffix = '_date' + date_suffix = "_date" # When processing Sidekiq payloads various timestamps are stored as Strings. # Commit in turn expects Time-like instances upon input, so we have to diff --git a/app/workers/project_cache_worker.rb b/app/workers/project_cache_worker.rb index d27b5e62574..e1489f2fd41 100644 --- a/app/workers/project_cache_worker.rb +++ b/app/workers/project_cache_worker.rb @@ -16,7 +16,7 @@ class ProjectCacheWorker def perform(project_id, files = [], statistics = []) project = Project.find_by(id: project_id) - return unless project && project.repository.exists? + return unless project&.repository&.exists? update_statistics(project, statistics.map(&:to_sym)) diff --git a/app/workers/project_export_worker.rb b/app/workers/project_export_worker.rb index ed9da39c7c3..bc9d4c17c49 100644 --- a/app/workers/project_export_worker.rb +++ b/app/workers/project_export_worker.rb @@ -17,7 +17,7 @@ class ProjectExportWorker private def build!(after_export_strategy) - strategy_klass = after_export_strategy&.delete('klass') + strategy_klass = after_export_strategy&.delete("klass") Gitlab::ImportExport::AfterExportStrategyBuilder.build!(strategy_klass, after_export_strategy) end diff --git a/app/workers/project_migrate_hashed_storage_worker.rb b/app/workers/project_migrate_hashed_storage_worker.rb index 1c8f313e6e9..267be29eb8e 100644 --- a/app/workers/project_migrate_hashed_storage_worker.rb +++ b/app/workers/project_migrate_hashed_storage_worker.rb @@ -4,7 +4,7 @@ class ProjectMigrateHashedStorageWorker include ApplicationWorker LEASE_TIMEOUT = 30.seconds.to_i - LEASE_KEY_SEGMENT = 'project_migrate_hashed_storage_worker'.freeze + LEASE_KEY_SEGMENT = "project_migrate_hashed_storage_worker" # rubocop: disable CodeReuse/ActiveRecord def perform(project_id, old_disk_path = nil) @@ -20,7 +20,6 @@ class ProjectMigrateHashedStorageWorker else return false end - ensure cancel_lease_for(project_id, uuid) if uuid end diff --git a/app/workers/prune_old_events_worker.rb b/app/workers/prune_old_events_worker.rb index dc4b7670131..694e8997c72 100644 --- a/app/workers/prune_old_events_worker.rb +++ b/app/workers/prune_old_events_worker.rb @@ -9,13 +9,15 @@ class PruneOldEventsWorker # Contribution calendar shows maximum 12 months of events, we retain 2 years for data integrity. # Double nested query is used because MySQL doesn't allow DELETE subqueries on the same table. Event.unscoped.where( - '(id IN (SELECT id FROM (?) ids_to_remove))', + "(id IN (SELECT id FROM (?) ids_to_remove))", Event.unscoped.where( - 'created_at < ?', - (2.years + 1.day).ago) + "created_at < ?", + (2.years + 1.day).ago + ) .select(:id) - .limit(10_000)) - .delete_all + .limit(10_000) + ) + .delete_all end # rubocop: enable CodeReuse/ActiveRecord end diff --git a/app/workers/prune_web_hook_logs_worker.rb b/app/workers/prune_web_hook_logs_worker.rb index 38054069f4e..f5b38b9520e 100644 --- a/app/workers/prune_web_hook_logs_worker.rb +++ b/app/workers/prune_web_hook_logs_worker.rb @@ -16,10 +16,10 @@ class PruneWebHookLogsWorker # another sub query. WebHookLog .where( - 'id IN (SELECT id FROM (?) ids_to_remove)', + "id IN (SELECT id FROM (?) ids_to_remove)", WebHookLog .select(:id) - .where('created_at < ?', 90.days.ago.beginning_of_day) + .where("created_at < ?", 90.days.ago.beginning_of_day) .limit(DELETE_LIMIT) ) .delete_all diff --git a/app/workers/reactive_caching_worker.rb b/app/workers/reactive_caching_worker.rb index 9ec8bcca4f3..a357443bcbf 100644 --- a/app/workers/reactive_caching_worker.rb +++ b/app/workers/reactive_caching_worker.rb @@ -7,8 +7,8 @@ class ReactiveCachingWorker def perform(class_name, id, *args) klass = begin class_name.constantize - rescue NameError - nil + rescue NameError + nil end return unless klass diff --git a/app/workers/remove_expired_members_worker.rb b/app/workers/remove_expired_members_worker.rb index 41913900571..3497a1f9280 100644 --- a/app/workers/remove_expired_members_worker.rb +++ b/app/workers/remove_expired_members_worker.rb @@ -6,11 +6,9 @@ class RemoveExpiredMembersWorker def perform Member.expired.find_each do |member| - begin - Members::DestroyService.new.execute(member, skip_authorization: true) - rescue => ex - logger.error("Expired Member ID=#{member.id} cannot be removed - #{ex}") - end + Members::DestroyService.new.execute(member, skip_authorization: true) + rescue => ex + logger.error("Expired Member ID=#{member.id} cannot be removed - #{ex}") end end end diff --git a/app/workers/repository_check/batch_worker.rb b/app/workers/repository_check/batch_worker.rb index c1bb1adc9cc..2fbe0be6e0e 100644 --- a/app/workers/repository_check/batch_worker.rb +++ b/app/workers/repository_check/batch_worker.rb @@ -62,7 +62,7 @@ module RepositoryCheck # rubocop: disable CodeReuse/ActiveRecord def never_checked_project_ids(batch_size) projects_on_shard.where(last_repository_check_at: nil) - .where('created_at < ?', 24.hours.ago) + .where("created_at < ?", 24.hours.ago) .limit(batch_size).pluck(:id) end # rubocop: enable CodeReuse/ActiveRecord @@ -70,7 +70,7 @@ module RepositoryCheck # rubocop: disable CodeReuse/ActiveRecord def old_checked_project_ids(batch_size) projects_on_shard.where.not(last_repository_check_at: nil) - .where('last_repository_check_at < ?', 1.month.ago) + .where("last_repository_check_at < ?", 1.month.ago) .reorder(last_repository_check_at: :asc) .limit(batch_size).pluck(:id) end diff --git a/app/workers/repository_cleanup_worker.rb b/app/workers/repository_cleanup_worker.rb index aa26c173a72..bf9f85d4009 100644 --- a/app/workers/repository_cleanup_worker.rb +++ b/app/workers/repository_cleanup_worker.rb @@ -8,7 +8,7 @@ class RepositoryCleanupWorker sidekiq_retries_exhausted do |msg, err| next if err.is_a?(ActiveRecord::RecordNotFound) - args = msg['args'] + [msg['error_message']] + args = msg["args"] + [msg["error_message"]] new.perform_failure(*args) end diff --git a/app/workers/repository_fork_worker.rb b/app/workers/repository_fork_worker.rb index a9b88a133be..bbdac6620d0 100644 --- a/app/workers/repository_fork_worker.rb +++ b/app/workers/repository_fork_worker.rb @@ -12,7 +12,7 @@ class RepositoryForkWorker source_project = target_project.forked_from_project unless source_project - return target_project.import_state.mark_as_failed(_('Source project cannot be found.')) + return target_project.import_state.mark_as_failed(_("Source project cannot be found.")) end fork_repository(target_project, source_project) diff --git a/app/workers/repository_update_remote_mirror_worker.rb b/app/workers/repository_update_remote_mirror_worker.rb index c0bae08ba85..c18ae6bec37 100644 --- a/app/workers/repository_update_remote_mirror_worker.rb +++ b/app/workers/repository_update_remote_mirror_worker.rb @@ -11,7 +11,7 @@ class RepositoryUpdateRemoteMirrorWorker sidekiq_retry_in { |count| 30 * count } sidekiq_retries_exhausted do |msg, _| - Sidekiq.logger.warn "Failed #{msg['class']} with #{msg['args']}: #{msg['error_message']}" + Sidekiq.logger.warn "Failed #{msg["class"]} with #{msg["args"]}: #{msg["error_message"]}" end def perform(remote_mirror_id, scheduled_time) diff --git a/app/workers/run_pipeline_schedule_worker.rb b/app/workers/run_pipeline_schedule_worker.rb index f72331c003a..8651acaed47 100644 --- a/app/workers/run_pipeline_schedule_worker.rb +++ b/app/workers/run_pipeline_schedule_worker.rb @@ -19,8 +19,8 @@ class RunPipelineScheduleWorker def run_pipeline_schedule(schedule, user) Ci::CreatePipelineService.new(schedule.project, - user, - ref: schedule.ref) + user, + ref: schedule.ref) .execute(:schedule, ignore_skip_ci: true, save_on_errors: false, schedule: schedule) end end diff --git a/app/workers/stuck_ci_jobs_worker.rb b/app/workers/stuck_ci_jobs_worker.rb index 25809f68080..f2b00f0f5ed 100644 --- a/app/workers/stuck_ci_jobs_worker.rb +++ b/app/workers/stuck_ci_jobs_worker.rb @@ -4,7 +4,7 @@ class StuckCiJobsWorker include ApplicationWorker include CronjobQueue - EXCLUSIVE_LEASE_KEY = 'stuck_ci_builds_worker_lease'.freeze + EXCLUSIVE_LEASE_KEY = "stuck_ci_builds_worker_lease" BUILD_RUNNING_OUTDATED_TIMEOUT = 1.hour BUILD_PENDING_OUTDATED_TIMEOUT = 1.day @@ -16,10 +16,10 @@ class StuckCiJobsWorker Rails.logger.info "#{self.class}: Cleaning stuck builds" - drop :running, BUILD_RUNNING_OUTDATED_TIMEOUT, 'ci_builds.updated_at < ?', :stuck_or_timeout_failure - drop :pending, BUILD_PENDING_OUTDATED_TIMEOUT, 'ci_builds.updated_at < ?', :stuck_or_timeout_failure - drop :scheduled, BUILD_SCHEDULED_OUTDATED_TIMEOUT, 'scheduled_at IS NOT NULL AND scheduled_at < ?', :stale_schedule - drop_stuck :pending, BUILD_PENDING_STUCK_TIMEOUT, 'ci_builds.updated_at < ?', :stuck_or_timeout_failure + drop :running, BUILD_RUNNING_OUTDATED_TIMEOUT, "ci_builds.updated_at < ?", :stuck_or_timeout_failure + drop :pending, BUILD_PENDING_OUTDATED_TIMEOUT, "ci_builds.updated_at < ?", :stuck_or_timeout_failure + drop :scheduled, BUILD_SCHEDULED_OUTDATED_TIMEOUT, "scheduled_at IS NOT NULL AND scheduled_at < ?", :stale_schedule + drop_stuck :pending, BUILD_PENDING_STUCK_TIMEOUT, "ci_builds.updated_at < ?", :stuck_or_timeout_failure remove_lease end diff --git a/app/workers/stuck_import_jobs_worker.rb b/app/workers/stuck_import_jobs_worker.rb index c8a186ba4ce..626fc30a3df 100644 --- a/app/workers/stuck_import_jobs_worker.rb +++ b/app/workers/stuck_import_jobs_worker.rb @@ -11,8 +11,8 @@ class StuckImportJobsWorker import_state_with_jid_count = mark_import_states_with_jid_as_failed! Gitlab::Metrics.add_event(:stuck_import_jobs, - projects_without_jid_count: import_state_without_jid_count, - projects_with_jid_count: import_state_with_jid_count) + projects_without_jid_count: import_state_without_jid_count, + projects_with_jid_count: import_state_with_jid_count) end private @@ -37,7 +37,7 @@ class StuckImportJobsWorker # scheduled/started to finished/failed while we were looking up their Sidekiq status. completed_import_states = enqueued_import_states_with_jid.where(id: completed_import_state_ids) - completed_import_state_jids = completed_import_states.map { |import_state| import_state.jid }.join(', ') + completed_import_state_jids = completed_import_states.map { |import_state| import_state.jid }.join(", ") Rails.logger.info("Marked stuck import jobs as failed. JIDs: #{completed_import_state_jids}") completed_import_states.each do |import_state| @@ -63,6 +63,6 @@ class StuckImportJobsWorker # rubocop: enable CodeReuse/ActiveRecord def error_message - _("Import timed out. Import took longer than %{import_jobs_expiration} seconds") % { import_jobs_expiration: IMPORT_JOBS_EXPIRATION } + _("Import timed out. Import took longer than %{import_jobs_expiration} seconds") % {import_jobs_expiration: IMPORT_JOBS_EXPIRATION} end end diff --git a/app/workers/stuck_merge_jobs_worker.rb b/app/workers/stuck_merge_jobs_worker.rb index f34ed6c4844..73144947475 100644 --- a/app/workers/stuck_merge_jobs_worker.rb +++ b/app/workers/stuck_merge_jobs_worker.rb @@ -39,13 +39,13 @@ class StuckMergeJobsWorker # We rely on state machine callbacks to update head_pipeline_id merge_requests_to_reopen.each(&:unlock_mr) - self.class.logger.info("Updated state of locked merge jobs. JIDs: #{completed_jids.join(', ')}") + self.class.logger.info("Updated state of locked merge jobs. JIDs: #{completed_jids.join(", ")}") end # rubocop: enable CodeReuse/ActiveRecord # rubocop: disable CodeReuse/ActiveRecord def stuck_merge_requests - MergeRequest.select('id, merge_jid').with_state(:locked).where.not(merge_jid: nil).reorder(nil) + MergeRequest.select("id, merge_jid").with_state(:locked).where.not(merge_jid: nil).reorder(nil) end # rubocop: enable CodeReuse/ActiveRecord end diff --git a/app/workers/trending_projects_worker.rb b/app/workers/trending_projects_worker.rb index 3297a1fe3d0..def43b860a7 100644 --- a/app/workers/trending_projects_worker.rb +++ b/app/workers/trending_projects_worker.rb @@ -5,7 +5,7 @@ class TrendingProjectsWorker include CronjobQueue def perform - Rails.logger.info('Refreshing trending projects') + Rails.logger.info("Refreshing trending projects") TrendingProject.refresh! end diff --git a/app/workers/update_merge_requests_worker.rb b/app/workers/update_merge_requests_worker.rb index c7213df652a..ebba1610986 100644 --- a/app/workers/update_merge_requests_worker.rb +++ b/app/workers/update_merge_requests_worker.rb @@ -14,9 +14,9 @@ class UpdateMergeRequestsWorker return unless user # TODO: remove this benchmarking when we have rich logging - time = Benchmark.measure do + time = Benchmark.measure { MergeRequests::RefreshService.new(project, user).execute(oldrev, newrev, ref) - end + } args_log = [ "elapsed=#{time.real}", @@ -24,8 +24,8 @@ class UpdateMergeRequestsWorker "user_id=#{user_id}", "oldrev=#{oldrev}", "newrev=#{newrev}", - "ref=#{ref}" - ].join(',') + "ref=#{ref}", + ].join(",") Rails.logger.info("UpdateMergeRequestsWorker#perform #{args_log}") if time.real > LOG_TIME_THRESHOLD end |