Class: Project

Constant Summary collapse

BoardLimitExceeded =
Class.new(StandardError)
ExportLimitExceeded =
Class.new(StandardError)
ExportAlreadyInProgress =
Class.new(StandardError)
EPOCH_CACHE_EXPIRATION =
30.days
STATISTICS_ATTRIBUTE =
'repositories_count'
UNKNOWN_IMPORT_URL =
'http://unknown.git'
LATEST_STORAGE_VERSION =

Hashed Storage versions handle rolling out new storage to project and dependents models: nil: legacy 1: repository 2: attachments

2
HASHED_STORAGE_FEATURES =
{
  repository: 1,
  attachments: 2
}.freeze
VALID_IMPORT_PORTS =
[80, 443].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
SORTING_PREFERENCE_FIELD =
:projects_sort
MAX_BUILD_TIMEOUT =
1.month
GL_REPOSITORY_TYPES =
[Gitlab::GlRepository::PROJECT, Gitlab::GlRepository::WIKI, Gitlab::GlRepository::DESIGN].freeze
MAX_SUGGESTIONS_TEMPLATE_LENGTH =
255
MAX_COMMIT_TEMPLATE_LENGTH =
500
MAX_MERGE_REQUEST_TITLE_REGEX =
255
MAX_MERGE_REQUEST_TITLE_REGEX_DESCRIPTION =
255
INSTANCE_RUNNER_RUNNING_JOBS_MAX_BUCKET =
5
DEFAULT_MERGE_COMMIT_TEMPLATE =
<<~MSG.rstrip.freeze
  Merge branch '%{source_branch}' into '%{target_branch}'

  %{title}

  %{issues}

  See merge request %{reference}
MSG
DEFAULT_SQUASH_COMMIT_TEMPLATE =
'%{title}'
PROJECT_FEATURES_DEFAULTS =
{
  issues: gitlab_config_features.issues,
  merge_requests: gitlab_config_features.merge_requests,
  builds: gitlab_config_features.builds,
  wiki: gitlab_config_features.wiki,
  snippets: gitlab_config_features.snippets
}.freeze
PROJECT_ACTIVITY_ATTRIBUTES =

List of attributes that, when updated, should be considered as Project Activity

%w[description name].freeze

Constants included from Cells::Claimable

Cells::Claimable::CLAIMS_BUCKET_TYPE, Cells::Claimable::CLAIMS_SOURCE_TYPE, Cells::Claimable::CLAIMS_SUBJECT_TYPE, Cells::Claimable::MissingPrimaryKeyError

Constants included from BlocksUnsafeSerialization

BlocksUnsafeSerialization::UnsafeSerializationError

Constants included from Routing::PseudonymizationHelper

Routing::PseudonymizationHelper::PSEUDONOMIZED_GROUP, Routing::PseudonymizationHelper::PSEUDONOMIZED_ID, Routing::PseudonymizationHelper::PSEUDONOMIZED_NAMESPACE, Routing::PseudonymizationHelper::PSEUDONOMIZED_PROJECT, Routing::PseudonymizationHelper::PSEUDONOMIZED_USERNAME

Constants included from BatchDestroyDependentAssociations

BatchDestroyDependentAssociations::DEPENDENT_ASSOCIATIONS_BATCH_SIZE

Constants included from WithUploads

WithUploads::FILE_UPLOADERS

Constants included from Gitlab::SQL::Pattern

Gitlab::SQL::Pattern::MIN_CHARS_FOR_PARTIAL_MATCHING, Gitlab::SQL::Pattern::REGEX_QUOTED_TERM

Constants included from CanMoveRepositoryStorage

CanMoveRepositoryStorage::RepositoryReadOnlyError

Constants included from WebHooks::HasWebHooks

WebHooks::HasWebHooks::WEB_HOOK_CACHE_EXPIRY

Constants included from CacheMarkdownField

CacheMarkdownField::INVALIDATED_BY

Constants included from Avatarable

Avatarable::ALLOWED_IMAGE_SCALER_WIDTHS, Avatarable::COMBINED_AVATAR_SIZES, Avatarable::COMBINED_AVATAR_SIZES_RETINA, Avatarable::GROUP_AVATAR_SIZES, Avatarable::MAXIMUM_FILE_SIZE, Avatarable::PROJECT_AVATAR_SIZES, Avatarable::USER_AVATAR_SIZES

Constants included from Gitlab::VisibilityLevel

Gitlab::VisibilityLevel::INTERNAL, Gitlab::VisibilityLevel::LEVELS_FOR_ADMINS, Gitlab::VisibilityLevel::PRIVATE, Gitlab::VisibilityLevel::PUBLIC

Constants inherited from ApplicationRecord

ApplicationRecord::MAX_PLUCK

Constants included from HasCheckConstraints

HasCheckConstraints::NOT_NULL_CHECK_PATTERN

Constants included from ResetOnColumnErrors

ResetOnColumnErrors::MAX_RESET_PERIOD

Instance Attribute Summary collapse

Attributes included from Gitlab::Cache::RequestCache

#request_cache_key_block

Attributes included from Importable

#importing, #user_contributions

Attributes included from CacheMarkdownField

#skip_markdown_cache_validation

Class Method Summary collapse

Instance Method Summary collapse

Methods included from Gitlab::Cache::RequestCache

extended, request_cache, request_cache_key

Methods included from Gitlab::Utils::Override

extended, extensions, included, method_added, override, prepended, queue_verification, verify!

Methods included from Gitlab::ConfigHelper

gitlab_config, gitlab_config_features

Methods included from Cells::Claimable

#handle_grpc_error

Methods included from Namespaces::AdjournedDeletable

#ancestor_scheduled_for_deletion?, #deletion_adjourned_period, #deletion_in_progress_or_scheduled_in_hierarchy_chain?, #first_scheduled_for_deletion_in_hierarchy_chain, #scheduled_for_deletion_in_hierarchy_chain?, #self_deletion_scheduled?, #self_deletion_scheduled_deletion_created_on

Methods included from BlocksUnsafeSerialization

#serializable_hash

Methods included from RunnerTokenExpirationInterval

#effective_runner_token_expiration_interval, #effective_runner_token_expiration_interval_human_readable, #enforced_runner_token_expiration_interval_human_readable

Methods included from Routing::PackagesHelper

#package_path

Methods included from Routing::PseudonymizationHelper

#masked_page_url, #masked_query_params, #masked_referrer_url, #referrer_params

Methods included from Routing::GraphqlHelper

#graphql_etag_pipeline_path, #graphql_etag_pipeline_sha_path, #graphql_etag_project_on_demand_scan_counts_path

Methods included from Routing::WikiHelper

#group_wiki_page_url, #project_wiki_page_url, #wiki_page_path, #wiki_path

Methods included from Routing::SnippetsHelper

#gitlab_raw_snippet_blob_url, #gitlab_raw_snippet_url, #gitlab_snippet_note_path, #gitlab_snippet_notes_path, #gitlab_snippet_path, #gitlab_snippet_url, #gitlab_toggle_award_emoji_snippet_note_path, #preview_markdown_path, #toggle_award_emoji_personal_snippet_path, #toggle_award_emoji_project_project_snippet_path, #toggle_award_emoji_project_project_snippet_url

Methods included from Routing::PipelineSchedulesHelper

#edit_pipeline_schedule_path, #pipeline_schedule_path, #pipeline_schedules_path, #play_pipeline_schedule_path, #take_ownership_pipeline_schedule_path

Methods included from Routing::ArtifactsHelper

#artifacts_action_path, #expose_fast_artifacts_path, #fast_browse_project_job_artifacts_path, #fast_download_project_job_artifacts_path, #fast_keep_project_job_artifacts_path

Methods included from Routing::MembersHelper

#source_members_url

Methods included from Routing::Groups::MembersHelper

#approve_access_request_group_member_path, #group_member_path, #group_members_url, #leave_group_members_path, #request_access_group_members_path, #resend_invite_group_member_path

Methods included from Routing::Projects::MembersHelper

#approve_access_request_project_member_path, #leave_project_members_path, #project_member_path, #project_members_url, #request_access_project_members_path, #resend_invite_project_member_path

Methods included from Routing::ProjectsHelper

#commit_url, #commits_url, #edit_milestone_path, #environment_delete_path, #environment_path, #issue_path, #merge_request_path, #merge_request_url, #pipeline_job_url, #pipeline_path, #pipeline_url, #project_commits_path, #project_ref_path, #project_tree_path, #release_url, #toggle_subscription_path, #work_item_url

Methods included from API::Helpers::RelatedResourcesHelpers

#expose_path, #expose_url, #issues_available?, #mrs_available?, #project_feature_string_access_level

Methods included from ApplicationSettingsHelper

#all_protocols_enabled?, #allowed_protocols_present?, #anti_spam_service_enabled?, #custom_admin_roles_available?, #default_search_scope_options_for_select, #deletion_protection_data, #deprecated_attributes, #enabled_protocol, #enabled_protocol_button, #expanded_by_default?, #external_authorization_allow_token_help_text, #external_authorization_client_certificate_help_text, #external_authorization_client_key_help_text, #external_authorization_client_pass_help_text, #external_authorization_client_url_help_text, #external_authorization_description, #external_authorization_service_attributes, #external_authorization_timeout_help_text, #external_authorization_url_help_text, #global_search_settings_checkboxes, #http_enabled?, #import_sources_checkboxes, #instance_clusters_enabled?, #integration_expanded?, #key_restriction_options_for_select, #kroki_available_formats, #oauth_providers_checkboxes, #pending_user_count, #registration_features_can_be_prompted?, #repository_storages_options_json, #restricted_level_checkboxes, #runner_token_expiration_interval_attributes, #sidekiq_job_limiter_mode_help_text, #sidekiq_job_limiter_modes_for_select, #signup_enabled?, #signup_form_data, #ssh_enabled?, #storage_weights, #user_oauth_applications?, #valid_runner_registrars, #visible_attributes, #vscode_extension_marketplace_settings_description, #vscode_extension_marketplace_settings_view

Methods included from ProjectsHelper

#able_to_see_forks_count?, #able_to_see_issues?, #able_to_see_merge_requests?, #any_projects?, #archiving_available?, #author_content_tag, #autodeploy_flash_notice, #badge_count, #branch_rules_path, #can_admin_associated_clusters?, #can_change_visibility_level?, #can_disable_emails?, #can_push_code?, #can_set_diff_preview_in_email?, #can_view_branch_rules?, #clusters_deprecation_alert_message, #dashboard_projects_app_data, #delete_confirm_phrase, #directory?, #error_tracking_setting_project_json, #explore_projects_tab?, #external_classification_label_help_message, #fork_button_data_attributes, #hidden_issue_icon, #home_panel_data_attributes, #http_clone_url_to_repo, #import_from_bitbucket_message, #inactive_project_deletion_date, #issue_css_classes, #issue_manual_ordering_class, #last_pipeline_from_status_cache, #last_push_event, #link_to_autodeploy_doc, #link_to_data_loss_doc, #link_to_member, #link_to_member_avatar, #link_to_namespace_change_doc, #link_to_project, #load_catalog_resources, #load_pipeline_status, #localized_project_human_access, #no_password_message, #notification_data_attributes, #project_archive_settings_app_data, #project_can_be_shared?, #project_classes, #project_coverage_chart_data_attributes, #project_incident_management_setting, #project_license_name, #project_pages_domain_choices, #project_permissions_panel_data, #project_unarchive_settings_app_data, #projects_filtered_search_and_sort_app_data, #push_project_breadcrumbs, #push_to_create_project_command, #remote_mirror_setting_enabled?, #remove_fork_project_confirm_json, #remove_fork_project_description_message, #remove_fork_project_warning_message, #remove_project_message, #show_archived_badge?, #show_auto_devops_implicitly_enabled_banner?, #show_clusters_alert?, #show_count?, #show_dashboard_projects_welcome_page?, #show_inactive_project_deletion_banner?, #show_invalid_gpg_key_message?, #show_lfs_misconfiguration_banner?, #show_mobile_devops_project_promo?, #show_no_password_message?, #show_no_ssh_key_message?, #show_terraform_banner?, #show_xcode_link?, #ssh_clone_url_to_repo, #star_count_data_attributes, #transfer_project_confirm_button, #transfer_project_message, #visibility_level_content, #visible_fork_source, #vue_fork_divergence_data, #xcode_uri_to_repo

Methods included from Gitlab::Allowable

#can?, #can_all?, #can_any?

Methods included from CompareHelper

#create_mr_button?, #create_mr_path, #project_compare_selector_data, #target_projects

Methods included from Repositories::CanHousekeepRepository

#increment_pushes_since_gc, #pushes_since_gc, #reset_pushes_since_gc

Methods included from FeatureGate

#flipper_id

Methods included from BatchDestroyDependentAssociations

#dependent_associations_to_destroy, #destroy_dependent_associations_in_batches

Methods included from WithUploads

#retrieve_upload

Methods included from FastDestroyAll::Helpers

#perform_fast_destroy

Methods included from AfterCommitQueue

#run_after_commit, #run_after_commit_or_now

Methods included from ChronicDurationAttribute

#chronic_duration_attributes, #output_chronic_duration_attribute

Methods included from DeploymentPlatform

#deployment_platform

Methods included from Gitlab::SQL::Pattern

split_query_to_search_terms

Methods included from GroupDescendant

build_hierarchy, #hierarchy

Methods included from Routable

#build_full_path, find_by_full_path, #full_name, #full_path, #full_path_components, #owned_by?

Methods included from CanMoveRepositoryStorage

#reference_counter, #set_repository_read_only!, #set_repository_writable!

Methods included from WebHooks::HasWebHooks

#any_hook_failed?, #cache_web_hook_failure, #fetch_web_hook_failure, #get_web_hook_failure, #last_failure_redis_key, #last_webhook_failure, #update_last_webhook_failure, #web_hook_failure_redis_key

Methods included from HasWiki

#create_wiki, #wiki, #wiki_repository_exists?

Methods included from HasRepository

#after_create_repository, #apply_desired_default_branch, #branch_exists?, #commit, #commit_by, #commits_by, #default_branch, #default_branch=, #default_branch_from_group_preferences, #default_branch_from_preferences, #empty_repo?, #full_path, #http_url_to_repo, #lfs_http_url_to_repo, #ref_exists?, #reload_default_branch, #repo_exists?, #repository_exists?, #repository_size_checker, #root_ref?, #ssh_url_to_repo, #url_to_repo, #valid_repo?, #web_url

Methods included from Gitlab::ShellAdapter

#gitlab_shell

Methods included from Referable

#referable_inspect, #reference_link_text

Methods included from Presentable

#present

Methods included from ProjectFeaturesCompatibility

#analytics_access_level=, #builds_access_level=, #builds_enabled=, #container_registry_access_level=, #container_registry_enabled=, #environments_access_level=, #feature_flags_access_level=, #forking_access_level=, #infrastructure_access_level=, #issues_access_level=, #issues_enabled=, #merge_requests_access_level=, #merge_requests_enabled=, #metrics_dashboard_access_level=, #model_experiments_access_level=, #model_registry_access_level=, #monitor_access_level=, #operations_access_level=, #package_registry_access_level=, #pages_access_level=, #releases_access_level=, #repository_access_level=, #security_and_compliance_access_level=, #security_and_compliance_enabled=, #snippets_access_level=, #snippets_enabled=, #wiki_access_level=, #wiki_enabled=

Methods included from ProjectAPICompatibility

#auto_devops_deploy_strategy=, #auto_devops_enabled=, #build_git_strategy=

Methods included from ValidAttribute

#valid_attribute?

Methods included from CacheMarkdownField

#attribute_invalidated?, #banzai_render_context, #cached_html_for, #cached_html_up_to_date?, #can_cache_field?, #invalidated_markdown_cache?, #latest_cached_markdown_version, #mentionable_attributes_changed?, #mentioned_filtered_user_ids_for, #parent_user, #refresh_markdown_cache, #refresh_markdown_cache!, #rendered_field_content, #skip_project_check?, #store_mentions!, #store_mentions?, #store_mentions_after_commit?, #updated_cached_html_for

Methods included from Avatarable

#avatar_path, #avatar_type, #uncached_avatar_path, #upload_paths

Methods included from Authz::HasRoles

#can_assign_role?, #roles_user_can_assign

Methods included from AccessRequestable

#request_access

Methods included from Gitlab::VisibilityLevel

allowed_for?, allowed_level?, allowed_levels, allowed_levels_for_user, closest_allowed_level, #internal?, level_name, level_value, levels_for_user, non_restricted_level?, options, #private?, #public?, public_visibility_restricted?, restricted_level?, string_level, string_options, string_values, valid_level?, #visibility, #visibility=, #visibility_attribute_present?, #visibility_attribute_value, #visibility_level_attributes, #visibility_level_previous_changes, #visibility_level_value

Methods inherited from ApplicationRecord

===, cached_column_list, #create_or_load_association, current_transaction, declarative_enum, default_select_columns, delete_all_returning, #deleted_from_database?, id_in, id_not_in, iid_in, nullable_column?, primary_key_in, #readable_by?, safe_ensure_unique, safe_find_or_create_by, safe_find_or_create_by!, #to_ability_name, underscore, where_exists, where_not_exists, with_fast_read_statement_timeout, without_order

Methods included from Organizations::Sharding

#sharding_organization

Methods included from ResetOnColumnErrors

#reset_on_union_error, #reset_on_unknown_attribute_error

Methods included from Gitlab::SensitiveSerializableHash

#serializable_hash

Constructor Details

#initialize(attributes = nil) ⇒ Project

Returns a new instance of Project.



1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
# File 'app/models/project.rb', line 1396

def initialize(attributes = nil)
  # We assign the actual snippet default if no explicit visibility has been initialized.
  attributes ||= {}

  unless visibility_attribute_present?(attributes)
    attributes[:visibility_level] = Gitlab::CurrentSettings.default_project_visibility
  end

  @init_attributes = attributes

  super
end

Instance Attribute Details

#old_path_with_namespaceObject

Returns the value of attribute old_path_with_namespace.



186
187
188
# File 'app/models/project.rb', line 186

def old_path_with_namespace
  @old_path_with_namespace
end

#pipeline_statusObject

Lazy loading of the pipeline_status attribute



2756
2757
2758
# File 'app/models/project.rb', line 2756

def pipeline_status
  @pipeline_status ||= Gitlab::Cache::Ci::ProjectPipelineStatus.load_for_project(self)
end

#skip_disk_validationObject

Returns the value of attribute skip_disk_validation.



189
190
191
# File 'app/models/project.rb', line 189

def skip_disk_validation
  @skip_disk_validation
end

#template_nameObject

Returns the value of attribute template_name.



187
188
189
# File 'app/models/project.rb', line 187

def template_name
  @template_name
end

#topic_listObject



3521
3522
3523
# File 'app/models/project.rb', line 3521

def topic_list
  self.topics.map(&:name)
end

Class Method Details

.by_pages_enabled_unique_domain(domain) ⇒ Object



1363
1364
1365
1366
1367
1368
1369
1370
# File 'app/models/project.rb', line 1363

def by_pages_enabled_unique_domain(domain)
  without_deleted
    .joins(:project_setting)
    .find_by(project_setting: {
      pages_unique_domain_enabled: true,
      pages_unique_domain: domain
    })
end

.cached_countObject



1311
1312
1313
1314
1315
# File 'app/models/project.rb', line 1311

def cached_count
  Rails.cache.fetch('total_project_count', expires_in: 5.minutes) do
    Project.count
  end
end

.cascading_with_parent_namespace(attribute) ⇒ Object

Define two instance methods:

  • [attribute]?(inherit_group_setting) Returns the final value after inheriting the parent group

  • [attribute]_locked? Returns true if the value is inherited from the parent group

These functions will be overridden in EE to make sense afterwards



1138
1139
1140
1141
1142
1143
1144
1145
1146
# File 'app/models/project.rb', line 1138

def self.cascading_with_parent_namespace(attribute)
  define_method("#{attribute}?") do |inherit_group_setting: false|
    self.public_send(attribute) # rubocop:disable GitlabSecurity/PublicSend
  end

  define_method("#{attribute}_locked?") do
    false
  end
end

.dormantObject



1196
1197
1198
1199
1200
1201
1202
1203
1204
# File 'app/models/project.rb', line 1196

def self.dormant
  project_statistics = ::ProjectStatistics.arel_table
  minimum_size_mb = ::Gitlab::CurrentSettings.inactive_projects_min_size_mb.megabytes
  last_activity_cutoff = ::Gitlab::CurrentSettings.inactive_projects_send_warning_email_after_months.months.ago

  joins(:statistics)
    .where((project_statistics[:storage_size]).gt(minimum_size_mb))
    .where('last_activity_at < ?', last_activity_cutoff)
end

.eager_load_namespace_and_ownerObject



1084
1085
1086
# File 'app/models/project.rb', line 1084

def self.eager_load_namespace_and_owner
  includes(namespace: :owner)
end

.filter_by_feature_visibility(feature, user) ⇒ Object

This scope returns projects where user has access to both the project and the feature.



1183
1184
1185
1186
1187
1188
1189
# File 'app/models/project.rb', line 1183

def self.filter_by_feature_visibility(feature, user)
  with_feature_available_for_user(feature, user)
    .public_or_visible_to_user(
      user,
      ProjectFeature.required_minimum_access_level_for_private_project(feature)
    )
end

.filter_out_public_projects_with_unauthorized_private_repos(projects, user) ⇒ Object



1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
# File 'app/models/project.rb', line 1163

def self.filter_out_public_projects_with_unauthorized_private_repos(projects, user)
  public_projects_with_private_repos = projects.with_project_feature.where(
    visibility_level: Gitlab::VisibilityLevel::PUBLIC,
    project_features: { repository_access_level: ProjectFeature::PRIVATE }
  ).pluck(:id)

  return projects unless public_projects_with_private_repos.present?

  authorized_public_projects_with_private_repos = projects.filter_by_feature_visibility(
    :repository, user
  )

  rejected_projects_with_private_repos = (
    public_projects_with_private_repos - authorized_public_projects_with_private_repos.pluck(:id)
  )

  projects.where.not(id: rejected_projects_with_private_repos)
end

.find_by_url(url) ⇒ Object



1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
# File 'app/models/project.rb', line 1332

def find_by_url(url)
  uri = URI(url)

  return unless uri.host == Gitlab.config.gitlab.host

  match = Rails.application.routes.recognize_path(url)

  return if match[:unmatched_route].present?
  return if match[:namespace_id].blank? || match[:id].blank?

  find_by_full_path(match.values_at(:namespace_id, :id).join("/"))
rescue ActionController::RoutingError, URI::InvalidURIError
  nil
end

.group_by_namespace_traversal_ids(project_batch) ⇒ Object



1376
1377
1378
1379
1380
1381
1382
# File 'app/models/project.rb', line 1376

def group_by_namespace_traversal_ids(project_batch)
  by_ids(project_batch)
    .with_namespace
    .pluck(:id, 'namespaces.traversal_ids')
    .group_by(&:last)
    .transform_values { |projects| projects.map(&:first) }
end

.group_idsObject



1317
1318
1319
# File 'app/models/project.rb', line 1317

def group_ids
  joins(:namespace).where(namespaces: { type: Group.sti_name }).select(:namespace_id)
end

.ids_with_issuables_available_for(user) ⇒ Object

Returns ids of projects with issuables available for given user

Used on queries to find milestones or labels which user can see For example: Milestone.where(project_id: ids_with_issuables_available_for(user))



1325
1326
1327
1328
1329
1330
# File 'app/models/project.rb', line 1325

def ids_with_issuables_available_for(user)
  with_issues_enabled = with_issues_available_for_user(user).select(:id)
  with_merge_requests_enabled = with_merge_requests_available_for_user(user).select(:id)

  from_union([with_issues_enabled, with_merge_requests_enabled]).select(:id)
end

.integration_association_name(name) ⇒ Object



221
222
223
# File 'app/models/project.rb', line 221

def self.integration_association_name(name)
  "#{name}_integration"
end

.markdown_reference_patternObject

Pattern used to extract namespace/project> project references from text. ‘>’ or its escaped form (‘&gt;’) are checked for because ‘>’ is sometimes escaped when the reference comes from an external source.



1298
1299
1300
1301
1302
1303
1304
# File 'app/models/project.rb', line 1298

def markdown_reference_pattern
  @markdown_reference_pattern ||=
    %r{
      #{reference_pattern}
      (#{reference_postfix}|#{reference_postfix_escaped})
    }x
end

.project_features_defaultsObject



1359
1360
1361
# File 'app/models/project.rb', line 1359

def project_features_defaults
  PROJECT_FEATURES_DEFAULTS
end

.project_namespace_for(id:) ⇒ Object



1372
1373
1374
# File 'app/models/project.rb', line 1372

def project_namespace_for(id:)
  find_by(id: id)&.project_namespace
end

.projects_user_can(projects, user, action) ⇒ Object



1157
1158
1159
1160
1161
# File 'app/models/project.rb', line 1157

def self.projects_user_can(projects, user, action)
  DeclarativePolicy.user_scope do
    projects.select { |project| Ability.allowed?(user, action, project) }
  end
end

.public_non_forked_or_visible_to_user(user, min_access_level = nil) ⇒ Object

Returns a collection of projects that is either:

  • public and not forked

  • or visible to the logged in user



1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
# File 'app/models/project.rb', line 1109

def self.public_non_forked_or_visible_to_user(user, min_access_level = nil)
  min_access_level = nil if user.can_read_all_resources?

  left_outer_joins(:fork_network_member)
    .where(
      'EXISTS (?) OR (projects.visibility_level IN (?) AND ?)',
      user.authorizations_for_projects(min_access_level: min_access_level),
      visibility_levels_for_user(user),
      ForkNetworkMember.arel_table[:forked_from_project_id].eq(nil)
    )
end

.public_or_visible_to_user(user = nil, min_access_level = nil) ⇒ Object

Returns a collection of projects that is either public or visible to the logged in user.



1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
# File 'app/models/project.rb', line 1090

def self.public_or_visible_to_user(user = nil, min_access_level = nil)
  min_access_level = nil if user&.can_read_all_resources?

  return public_to_user unless user

  if user.is_a?(DeployToken)
    where(id: user.accessible_projects)
  else
    where(
      'EXISTS (?) OR projects.visibility_level IN (?)',
      user.authorizations_for_projects(min_access_level: min_access_level),
      self.visibility_levels_for_user(user)
    )
  end
end

.reference_patternObject

rubocop:enable Metrics/CyclomaticComplexity



1278
1279
1280
1281
1282
1283
1284
1285
# File 'app/models/project.rb', line 1278

def reference_pattern
  %r{
    (?<!#{Gitlab::PathRegex::PATH_START_CHAR})
    (?<absolute_path>/)?
    ((?<namespace>#{Gitlab::PathRegex::FULL_NAMESPACE_FORMAT_REGEX})/)?
    (?<project>#{Gitlab::PathRegex::PROJECT_PATH_FORMAT_REGEX})
  }xo
end

.reference_postfixObject



1287
1288
1289
# File 'app/models/project.rb', line 1287

def reference_postfix
  '>'
end

.reference_postfix_escapedObject



1291
1292
1293
# File 'app/models/project.rb', line 1291

def reference_postfix_escaped
  '&gt;'
end

.root_ids_for(project_ids) ⇒ Object



1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
# File 'app/models/project.rb', line 1384

def root_ids_for(project_ids)
  namespace_ids = id_in(project_ids)
    .limit(Project::MAX_PLUCK)
    .distinct
    .pluck(:namespace_id)

  return [] if namespace_ids.empty?

  Namespace.root_ids_for(namespace_ids)
end

.search(query, include_namespace: false, exclude_description: false, use_minimum_char_limit: true) ⇒ Object

Searches for a list of projects based on the query given in query.

On PostgreSQL this method uses “ILIKE” to perform a case-insensitive search.

query - The search query as a String.



1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
# File 'app/models/project.rb', line 1225

def search(query, include_namespace: false, exclude_description: false, use_minimum_char_limit: true)
  if include_namespace
    joins(:route).fuzzy_search(query, [Route.arel_table[:path], Route.arel_table[:name], :description],
      use_minimum_char_limit: use_minimum_char_limit)
    .allow_cross_joins_across_databases(url: 'https://gitlab.com/gitlab-org/gitlab/-/issues/421843')
  else
    search_columns = [:path, :name]
    search_columns << :description unless exclude_description
    fuzzy_search(query, search_columns, use_minimum_char_limit: use_minimum_char_limit)
  end
end

.search_by_title(query) ⇒ Object



1237
1238
1239
# File 'app/models/project.rb', line 1237

def search_by_title(query)
  non_archived.fuzzy_search(query, [:name])
end

.sort_by_attribute(method) ⇒ Object

rubocop:disable Metrics/CyclomaticComplexity – stick to existing implementation for sort params:



1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
# File 'app/models/project.rb', line 1246

def sort_by_attribute(method)
  case method.to_s
  when 'storage_size_desc' then sorted_by_storage_size_desc
  when 'storage_size_asc' then sorted_by_storage_size_asc
  when 'repository_size_desc' then sorted_by_repository_size_desc
  when 'repository_size_asc' then sorted_by_repository_size_asc
  when 'snippets_size_desc'then sorted_by_snippets_size_desc
  when 'snippets_size_asc'then sorted_by_snippets_size_asc
  when 'build_artifacts_size_desc' then sorted_by_build_artifacts_size_desc
  when 'build_artifacts_size_asc'then sorted_by_build_artifacts_size_asc
  when 'lfs_objects_size_desc'then sorted_by_lfs_objects_size_desc
  when 'lfs_objects_size_asc' then sorted_by_lfs_objects_size_asc
  when 'packages_size_desc' then sorted_by_packages_size_desc
  when 'packages_size_asc' then sorted_by_packages_size_asc
  when 'wiki_size_desc' then sorted_by_wiki_size_desc
  when 'wiki_size_asc'then sorted_by_wiki_size_asc
  when 'container_registry_size_desc' then sorted_by_container_registry_size_desc
  when 'container_registry_size_asc' then sorted_by_container_registry_size_asc
  when 'latest_activity_desc' then sorted_by_updated_desc
  when 'latest_activity_asc' then sorted_by_updated_asc
  when 'path_desc'then sorted_by_path_desc
  when 'path_asc' then sorted_by_path_asc
  when 'full_path_desc'then sorted_by_full_path_desc
  when 'full_path_asc' then sorted_by_full_path_asc
  when 'stars_desc' then sorted_by_stars_desc
  when 'stars_asc' then sorted_by_stars_asc
  else
    order_by(method)
  end
end


1306
1307
1308
1309
# File 'app/models/project.rb', line 1306

def trending
  joins('INNER JOIN trending_projects ON projects.id = trending_projects.project_id')
    .reorder('trending_projects.id ASC')
end

.visibility_levelsObject



1241
1242
1243
# File 'app/models/project.rb', line 1241

def visibility_levels
  Gitlab::VisibilityLevel.options
end

.visibility_levels_for_user(user) ⇒ Object

Auditors can :read_all_resources while admins can :read_all_resources and read_admin_projects. In EE, a regular user can read_admin_projects through custom admin roles.



1124
1125
1126
1127
1128
1129
1130
# File 'app/models/project.rb', line 1124

def self.visibility_levels_for_user(user)
  can_read_all_projects = user&.can_read_all_resources? || user&.can?(:read_admin_projects)

  return ::Gitlab::VisibilityLevel::LEVELS_FOR_ADMINS if can_read_all_projects

  Gitlab::VisibilityLevel.levels_for_user(user)
end

.with_api_blob_entity_associationsObject



1066
1067
1068
# File 'app/models/project.rb', line 1066

def self.with_api_blob_entity_associations
  preload(:project_feature, :route, namespace: [:route, :owner])
end

.with_api_commit_entity_associationsObject



1062
1063
1064
# File 'app/models/project.rb', line 1062

def self.with_api_commit_entity_associations
  preload(:project_feature, :route, namespace: [:route, :owner])
end

.with_api_entity_associationsObject



1053
1054
1055
1056
# File 'app/models/project.rb', line 1053

def self.with_api_entity_associations
  with_fork_network_associations
    .preload(:project_feature, :route, :topics, :group, :timelogs, namespace: [:route, :owner])
end

.with_feature_available_for_user(feature, user) ⇒ Object



1153
1154
1155
# File 'app/models/project.rb', line 1153

def self.with_feature_available_for_user(feature, user)
  with_project_feature.merge(ProjectFeature.with_feature_available_for_user(feature, user))
end

.with_slack_application_disabledObject



1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
# File 'app/models/project.rb', line 1070

def self.with_slack_application_disabled
  # Using Arel to avoid exposing what the column backing the type: attribute is
  # rubocop: disable GitlabSecurity/PublicSend
  with_active_slack = Integration.active.by_name(:gitlab_slack_application)
  join_contraint = arel_table[:id].eq(Integration.arel_table[:project_id])
  constraint = with_active_slack.where_clause.send(:predicates).reduce(join_contraint) { |a, b| a.and(b) }
  join = arel_table.join(Integration.arel_table, Arel::Nodes::OuterJoin).on(constraint).join_sources
  # rubocop: enable GitlabSecurity/PublicSend

  joins(join).where(integrations: { id: nil })
rescue Integration::UnknownType
  all
end

.with_web_entity_associationsObject



1058
1059
1060
# File 'app/models/project.rb', line 1058

def self.with_web_entity_associations
  preload(:project_feature, :route, :creator, group: :parent, namespace: [:route, :owner, :namespace_settings, :namespace_settings_with_ancestors_inherited_settings])
end

.without_integration(integration) ⇒ Object



1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
# File 'app/models/project.rb', line 1347

def without_integration(integration)
  integrations = Integration
    .select('1')
    .where("#{Integration.table_name}.project_id = projects.id")
    .where(type: integration.type)

  Project
    .where('NOT EXISTS (?)', integrations)
    .where(pending_delete: false)
    .non_archived
end

.wrap_with_cte(collection) ⇒ Object



1191
1192
1193
1194
# File 'app/models/project.rb', line 1191

def self.wrap_with_cte(collection)
  cte = Gitlab::SQL::CTE.new(:projects_cte, collection)
  Project.with(cte.to_arel).from(cte.alias_to(Project.arel_table))
end

Instance Method Details

#access_request_approvers_to_be_notifiedObject



3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
# File 'app/models/project.rb', line 3306

def access_request_approvers_to_be_notified
  access_request_approvers = members.owners_and_maintainers

  recipients = access_request_approvers.connected_to_user..limit(Member::ACCESS_REQUEST_APPROVERS_TO_BE_NOTIFIED_LIMIT)

  if recipients.blank?
    recipients = group.access_request_approvers_to_be_notified
  end

  recipients
end

#active_runnersObject



2615
2616
2617
2618
2619
# File 'app/models/project.rb', line 2615

def active_runners
  strong_memoize(:active_runners) do
    all_available_runners.active
  end
end

#active_webide_pipelines(user:) ⇒ Object



1518
1519
1520
# File 'app/models/project.rb', line 1518

def active_webide_pipelines(user:)
  webide_pipelines.running_or_pending.for_user(user)
end

#add_export_job(current_user:, after_export_strategy: nil, params: {}) ⇒ Object



2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
# File 'app/models/project.rb', line 2760

def add_export_job(current_user:, after_export_strategy: nil, params: {})
  check_project_export_limit!
  check_duplicate_export!(current_user)

  params[:exported_by_admin] = current_user.can_admin_all_resources?

  job_id = Projects::ImportExport::CreateRelationExportsWorker
               .perform_async(current_user.id, self.id, after_export_strategy, params)

  if job_id
    Gitlab::AppLogger.info "Export job started for project ID #{self.id} with job ID #{job_id}"
  else
    Gitlab::AppLogger.error "Export job failed to start for project ID #{self.id}"
  end
end

#add_import_jobObject



1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
# File 'app/models/project.rb', line 1751

def add_import_job
  job_id =
    if forked?
      RepositoryForkWorker.perform_async(id)
    else
      RepositoryImportWorker.perform_async(self.id)
    end

  log_import_activity(job_id)

  job_id
end

#after_change_head_branch_does_not_exist(branch) ⇒ Object



3526
3527
3528
# File 'app/models/project.rb', line 3526

def after_change_head_branch_does_not_exist(branch)
  self.errors.add(:base, _("Could not change HEAD: branch '%{branch}' does not exist") % { branch: branch })
end

#after_create_default_branchObject

rubocop: disable CodeReuse/ServiceClass



2750
2751
2752
# File 'app/models/project.rb', line 2750

def after_create_default_branch
  Projects::ProtectDefaultBranchService.new(self).execute
end

#after_importObject



2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
# File 'app/models/project.rb', line 2710

def after_import
  repository.expire_content_cache
  repository.remove_prohibited_refs
  wiki.repository.expire_content_cache

  DetectRepositoryLanguagesWorker.perform_async(id)
  ProjectCacheWorker.perform_async(self.id, [], %w[repository_size wiki_size])
  AuthorizedProjectUpdate::ProjectRecalculateWorker.perform_async(id)

  enqueue_record_project_target_platforms

  reset_counters_and_iids

  import_state&.finish
  after_create_default_branch
  join_pool_repository
  refresh_markdown_cache!
end

#after_repository_change_headObject



2475
2476
2477
2478
2479
# File 'app/models/project.rb', line 2475

def after_repository_change_head
  ProjectCacheWorker.perform_async(self.id, [], %w[commit_count])

  super
end

#all_available_runnersObject



2611
2612
2613
# File 'app/models/project.rb', line 2611

def all_available_runners
  Ci::Runner.from_union([runners, group_runners, available_shared_runners])
end

#all_clustersObject



2202
2203
2204
2205
2206
2207
# File 'app/models/project.rb', line 2202

def all_clusters
  group_clusters = Clusters::Cluster.joins(:groups).where(cluster_groups: { group_id: ancestors_upto })
  instance_clusters = Clusters::Cluster.instance_type

  Clusters::Cluster.from_union([clusters, group_clusters, instance_clusters])
end

#all_pipelinesObject



1502
1503
1504
1505
1506
1507
1508
# File 'app/models/project.rb', line 1502

def all_pipelines
  if builds_enabled?
    super
  else
    super.external
  end
end

#all_runnersObject



2607
2608
2609
# File 'app/models/project.rb', line 2607

def all_runners
  Ci::Runner.from_union([runners, group_runners, shared_runners])
end

#allow_iframes_in_markdown_feature_flag_enabled?Boolean

Returns:



3602
3603
3604
# File 'app/models/project.rb', line 3602

def allow_iframes_in_markdown_feature_flag_enabled?
  group&.allow_iframes_in_markdown_feature_flag_enabled? || Feature.enabled?(:allow_iframes_in_markdown, self, type: :wip)
end

#allowed_to_share_with_group?Boolean

Overridden in EE

Returns:



2500
2501
2502
# File 'app/models/project.rb', line 2500

def allowed_to_share_with_group?
  share_with_group_enabled?
end

#allows_multiple_merge_request_assignees?Boolean

Overridden in EE

Returns:



3716
3717
3718
# File 'app/models/project.rb', line 3716

def allows_multiple_merge_request_assignees?
  false
end

#allows_multiple_merge_request_reviewers?Boolean

Overridden in EE

Returns:



3721
3722
3723
# File 'app/models/project.rb', line 3721

def allows_multiple_merge_request_reviewers?
  false
end

#analytics_enabled?Boolean

Returns:



2553
2554
2555
# File 'app/models/project.rb', line 2553

def analytics_enabled?
  !!project_feature&.analytics_enabled?
end

#ancestors(hierarchy_order: nil) ⇒ Object Also known as: group_and_ancestors



1550
1551
1552
# File 'app/models/project.rb', line 1550

def ancestors(hierarchy_order: nil)
  group&.self_and_ancestors(hierarchy_order: hierarchy_order) || Group.none
end

#ancestors_archived?Boolean

Returns:



3118
3119
3120
# File 'app/models/project.rb', line 3118

def ancestors_archived?
  ancestors.archived.exists?
end

#ancestors_upto(top = nil, hierarchy_order: nil) ⇒ Object

returns all ancestor-groups upto but excluding the given namespace when no namespace is given, all ancestors upto the top are returned



1545
1546
1547
1548
# File 'app/models/project.rb', line 1545

def ancestors_upto(top = nil, hierarchy_order: nil)
  Gitlab::ObjectHierarchy.new(Group.where(id: namespace_id))
    .base_and_ancestors(upto: top, hierarchy_order: hierarchy_order)
end

#ancestors_upto_idsObject



1561
1562
1563
# File 'app/models/project.rb', line 1561

def ancestors_upto_ids(...)
  ancestors_upto(...).pluck(:id)
end

#any_branch_allows_collaboration?(user) ⇒ Boolean

Returns:



3196
3197
3198
# File 'app/models/project.rb', line 3196

def any_branch_allows_collaboration?(user)
  fetch_branch_allows_collaboration(user)
end

#any_import_in_progress?Boolean

Determine whether any kind of import is in progress.

  • Full file import

  • Relation import

  • Direct Transfer

Returns:



1909
1910
1911
1912
1913
1914
1915
# File 'app/models/project.rb', line 1909

def any_import_in_progress?
  last_relation_import_tracker = relation_import_trackers.last

  (last_relation_import_tracker&.started? && !last_relation_import_tracker.stale?) ||
    import_started? ||
    BulkImports::Entity.with_status(:started).where(project_id: id).any?
end

#any_lfs_file_locks?Boolean

Returns:



3228
3229
3230
# File 'app/models/project.rb', line 3228

def any_lfs_file_locks?
  lfs_file_locks.any?
end

#any_online_runners?(&block) ⇒ Boolean

Returns:



2621
2622
2623
# File 'app/models/project.rb', line 2621

def any_online_runners?(&block)
  online_runners_with_tags.any?(&block)
end

#api_variablesObject



2941
2942
2943
2944
2945
2946
# File 'app/models/project.rb', line 2941

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_GRAPHQL_URL', value: Gitlab::Routing.url_helpers.api_graphql_url)
  end
end

#archivedObject Also known as: self_archived?



3108
3109
3110
# File 'app/models/project.rb', line 3108

def archived
  super && !self_deletion_scheduled?
end

#auto_cancel_pending_pipelines?Boolean

Returns:



3233
3234
3235
# File 'app/models/project.rb', line 3233

def auto_cancel_pending_pipelines?
  auto_cancel_pending_pipelines == 'enabled'
end

#auto_devops_enabled?Boolean

Returns:



1579
1580
1581
1582
1583
1584
1585
# File 'app/models/project.rb', line 1579

def auto_devops_enabled?
  if auto_devops&.enabled.nil?
    has_auto_devops_implicitly_enabled?
  else
    auto_devops.enabled?
  end
end

#auto_devops_variablesObject



3024
3025
3026
3027
3028
# File 'app/models/project.rb', line 3024

def auto_devops_variables
  return [] unless auto_devops_enabled?

  (auto_devops || build_auto_devops)&.predefined_variables
end

#autoclose_referenced_issuesObject



1530
1531
1532
1533
1534
# File 'app/models/project.rb', line 1530

def autoclose_referenced_issues
  return true if super.nil?

  super
end

#available_shared_runnersObject



2599
2600
2601
# File 'app/models/project.rb', line 2599

def available_shared_runners
  @available_shared_runners ||= shared_runners_available? ? shared_runners : Ci::Runner.none
end

#avatar_in_gitObject



2189
2190
2191
# File 'app/models/project.rb', line 2189

def avatar_in_git
  repository.avatar
end

#avatar_url(**args) ⇒ Object



2193
2194
2195
# File 'app/models/project.rb', line 2193

def avatar_url(**args)
  Gitlab::Routing.url_helpers.project_avatar_url(self) if avatar_in_git
end

#badgesObject



3179
3180
3181
3182
3183
# File 'app/models/project.rb', line 3179

def badges
  return project_badges unless group

  Badge.from_union([project_badges, GroupBadge.where(group: group.self_and_ancestors)])
end

#batch_loaded_environment_by_name(name) ⇒ Object



3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
# File 'app/models/project.rb', line 3375

def batch_loaded_environment_by_name(name)
  # This code path has caused N+1s in the past, since environments are only indirectly
  # associated to builds and pipelines; see https://gitlab.com/gitlab-org/gitlab/-/issues/326445
  # We therefore batch-load them to prevent dormant N+1s until we found a proper solution.
  BatchLoader.for(name).batch(key: id) do |names, loader, args|
    Environment.where(name: names, project: args[:key]).find_each do |environment|
      loader.call(environment.name, environment)
    end
  end
end

#beautified_import_status_nameObject



1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
# File 'app/models/project.rb', line 1739

def beautified_import_status_name
  if import_finished?
    return 'completed' unless import_checksums.present?

    fetched = import_checksums['fetched']
    imported = import_checksums['imported']
    fetched.keys.any? { |key| fetched[key] != imported[key] } ? 'partially completed' : 'completed'
  else
    import_status
  end
end

#bitbucket_import?Boolean

Returns:



1892
1893
1894
# File 'app/models/project.rb', line 1892

def bitbucket_import?
  import_type == 'bitbucket'
end

#bitbucket_server_import?Boolean

Returns:



1896
1897
1898
# File 'app/models/project.rb', line 1896

def bitbucket_server_import?
  import_type == 'bitbucket_server'
end

#botsObject



2454
2455
2456
# File 'app/models/project.rb', line 2454

def bots
  users.project_bot
end

#branch_allows_collaboration?(user, branch_name) ⇒ Boolean

Returns:



3200
3201
3202
# File 'app/models/project.rb', line 3200

def branch_allows_collaboration?(user, branch_name)
  fetch_branch_allows_collaboration(user, branch_name)
end

#build_commit_note(commit) ⇒ Object



2090
2091
2092
# File 'app/models/project.rb', line 2090

def build_commit_note(commit)
  notes.new(commit_id: commit.id, noteable_type: 'Commit')
end

#build_or_assign_import_data(data: nil, credentials: nil) ⇒ Object



1849
1850
1851
1852
1853
1854
1855
1856
# File 'app/models/project.rb', line 1849

def build_or_assign_import_data(data: nil, credentials: nil)
  project_import_data = import_data || build_import_data

  project_import_data.merge_data(data.to_h) if data
  project_import_data.merge_credentials(credentials.to_h) if credentials

  project_import_data
end

#builds_enabled?Boolean

Returns:



2529
2530
2531
# File 'app/models/project.rb', line 2529

def builds_enabled?
  !!project_feature&.builds_enabled?
end

#can_create_custom_domains?Boolean

Returns:



3659
3660
3661
3662
3663
# File 'app/models/project.rb', line 3659

def can_create_custom_domains?
  return true if Gitlab::CurrentSettings.max_pages_custom_domains_per_project == 0

  pages_domains.count < Gitlab::CurrentSettings.max_pages_custom_domains_per_project
end

#can_create_new_ref_commits?Boolean

Returns:



3144
3145
3146
# File 'app/models/project.rb', line 3144

def can_create_new_ref_commits?
  merge_method != :merge
end

#can_suggest_reviewers?Boolean

overridden in EE

Returns:



3670
3671
3672
# File 'app/models/project.rb', line 3670

def can_suggest_reviewers?
  false
end

#certificate_based_clusters_enabled?Boolean

Returns:



1431
1432
1433
# File 'app/models/project.rb', line 1431

def certificate_based_clusters_enabled?
  !!namespace&.certificate_based_clusters_enabled?
end

#changing_shared_runners_enabled_is_allowedObject



2007
2008
2009
2010
2011
2012
2013
# File 'app/models/project.rb', line 2007

def changing_shared_runners_enabled_is_allowed
  return unless new_record? || changes.has_key?(:shared_runners_enabled)

  if shared_runners_setting_conflicting_with_group?
    errors.add(:shared_runners_enabled, _('cannot be enabled because parent group does not allow it'))
  end
end

#check_personal_projects_limitObject



1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
# File 'app/models/project.rb', line 1948

def check_personal_projects_limit
  # Since this method is called as validation hook, `creator` might not be
  # present. Since the validation for that will fail, we can just return
  # early.
  return if !creator || creator.can_create_project? ||
    namespace.kind == 'group'

  limit = creator.projects_limit
  error =
    if limit == 0
      _('You cannot create projects in your personal namespace. Contact your GitLab administrator.')
    else
      _("You've reached your limit of %{limit} projects created. Contact your GitLab administrator.")
    end

  self.errors.add(:limit_reached, error % { limit: limit })
end

#check_repository_path_availabilityObject

Check if repository already exists on disk



2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
# File 'app/models/project.rb', line 2362

def check_repository_path_availability
  return true if skip_disk_validation
  return false unless repository_storage

  # 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'))
    return false
  end

  true
rescue GRPC::Internal # if the path is too long
  false
end

#ci_allow_fork_pipelines_to_run_in_parent_project?Boolean

Returns:



3465
3466
3467
3468
3469
# File 'app/models/project.rb', line 3465

def ci_allow_fork_pipelines_to_run_in_parent_project?
  return false unless ci_cd_settings

  ci_cd_settings.allow_fork_pipelines_to_run_in_parent_project?
end

#ci_config_for(sha) ⇒ Object



3433
3434
3435
# File 'app/models/project.rb', line 3433

def ci_config_for(sha)
  repository.blob_data_at(sha, ci_config_path_or_default)
end

#ci_config_path=(value) ⇒ Object



1789
1790
1791
1792
# File 'app/models/project.rb', line 1789

def ci_config_path=(value)
  # Strip all leading slashes so that //foo -> foo
  super(value&.delete("\0"))
end

#ci_config_path_or_defaultObject



3429
3430
3431
# File 'app/models/project.rb', line 3429

def ci_config_path_or_default
  ci_config_path.presence || Ci::Pipeline::DEFAULT_CONFIG_PATH
end

#ci_display_pipeline_variables?Boolean

Returns:



3447
3448
3449
3450
3451
# File 'app/models/project.rb', line 3447

def ci_display_pipeline_variables?
  return false unless ci_cd_settings

  ci_cd_settings.display_pipeline_variables?
end

#ci_forward_deployment_enabled?Boolean

Returns:



3453
3454
3455
3456
3457
# File 'app/models/project.rb', line 3453

def ci_forward_deployment_enabled?
  return false unless ci_cd_settings

  ci_cd_settings.forward_deployment_enabled?
end

#ci_forward_deployment_rollback_allowed?Boolean

Returns:



3459
3460
3461
3462
3463
# File 'app/models/project.rb', line 3459

def ci_forward_deployment_rollback_allowed?
  return false unless ci_cd_settings

  ci_cd_settings.forward_deployment_rollback_allowed?
end

#ci_inbound_job_token_scope_enabled?Boolean

Returns:



3477
3478
3479
3480
3481
3482
3483
# File 'app/models/project.rb', line 3477

def ci_inbound_job_token_scope_enabled?
  return true unless ci_cd_settings

  return true if ::Gitlab::CurrentSettings.enforce_ci_inbound_job_token_scope_enabled?

  ci_cd_settings.inbound_job_token_scope_enabled?
end

#ci_integrationObject



2185
2186
2187
# File 'app/models/project.rb', line 2185

def ci_integration
  @ci_integration ||= ci_integrations.reorder(nil).find_by(active: true)
end

#ci_integrationsObject

rubocop: enable CodeReuse/ServiceClass



2181
2182
2183
# File 'app/models/project.rb', line 2181

def ci_integrations
  integrations.where(category: :ci)
end

#ci_outbound_job_token_scope_enabled?Boolean

Returns:



3471
3472
3473
3474
3475
# File 'app/models/project.rb', line 3471

def ci_outbound_job_token_scope_enabled?
  return false unless ci_cd_settings

  ci_cd_settings.job_token_scope_enabled?
end

#ci_pipelinesObject



1510
1511
1512
1513
1514
1515
1516
# File 'app/models/project.rb', line 1510

def ci_pipelines
  if builds_enabled?
    super
  else
    super.external
  end
end

#ci_push_repository_for_job_token_allowed?Boolean

Returns:



3497
3498
3499
3500
3501
# File 'app/models/project.rb', line 3497

def ci_push_repository_for_job_token_allowed?
  return false unless ci_cd_settings

  ci_cd_settings.push_repository_for_job_token_allowed?
end

#ci_template_variablesObject



2948
2949
2950
2951
2952
# File 'app/models/project.rb', line 2948

def ci_template_variables
  Gitlab::Ci::Variables::Collection.new.tap do |variables|
    variables.append(key: 'CI_TEMPLATE_REGISTRY_HOST', value: 'registry.gitlab.com')
  end
end

#cleanupObject Also known as: reload_repository!



1633
1634
1635
# File 'app/models/project.rb', line 1633

def cleanup
  @repository = nil
end

#closest_setting(name) ⇒ Object



3318
3319
3320
3321
3322
3323
# File 'app/models/project.rb', line 3318

def closest_setting(name)
  setting = read_attribute(name)
  setting = closest_namespace_setting(name) if setting.nil?
  setting = app_settings_for(name) if setting.nil?
  setting
end

#codeObject

For compatibility with old code



2198
2199
2200
# File 'app/models/project.rb', line 2198

def code
  path
end

#commit_notesObject

Used by Import/Export to export commit notes



1795
1796
1797
# File 'app/models/project.rb', line 1795

def commit_notes
  notes.where(noteable_type: "Commit")
end

#container_registry_enabled?Boolean Also known as: container_registry_enabled

Returns:



2582
2583
2584
# File 'app/models/project.rb', line 2582

def container_registry_enabled?
  !!project_feature&.container_registry_enabled?
end

#container_registry_urlObject



1639
1640
1641
1642
1643
# File 'app/models/project.rb', line 1639

def container_registry_url
  if Gitlab.config.registry.enabled
    "#{Gitlab.config.registry.host_port}/#{full_path.downcase}"
  end
end

#container_registry_variablesObject



2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
# File 'app/models/project.rb', line 2972

def container_registry_variables
  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)

    if container_registry_enabled?
      variables.append(key: 'CI_REGISTRY_IMAGE', value: container_registry_url)
    end
  end
end

#container_repositories_sizeObject



1645
1646
1647
1648
1649
1650
1651
1652
# File 'app/models/project.rb', line 1645

def container_repositories_size
  strong_memoize(:container_repositories_size) do
    next 0 if container_repositories.empty?
    next unless ContainerRegistry::GitlabApiClient.supports_gitlab_api?

    ContainerRegistry::GitlabApiClient.deduplicated_size(full_path)
  end
end

#create_labelsObject

rubocop: disable CodeReuse/ServiceClass



2170
2171
2172
2173
2174
2175
2176
2177
2178
# File 'app/models/project.rb', line 2170

def create_labels
  Label.templates.in_organization(organization).each do |label|
    # slice on column_names to ensure an added DB column will not break a mixed deployment
    params = label.attributes
                  .slice(*Label.column_names)
                  .except('id', 'template', 'created_at', 'updated_at', 'type', 'organization_id')
    Labels::FindOrCreateService.new(nil, self, params).execute(skip_authorization: true)
  end
end

#create_repository(force: false, default_branch: nil, object_format: nil) ⇒ Object



2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
# File 'app/models/project.rb', line 2398

def create_repository(force: false, default_branch: nil, object_format: nil)
  # Forked import is handled asynchronously
  return if forked? && !force

  repository.create_repository(default_branch, object_format: object_format)
  repository.after_create

  true
rescue StandardError => e
  Gitlab::ErrorTracking.track_exception(e, project: { id: id, full_path: full_path, disk_path: disk_path })
  errors.add(:base, _('Failed to create repository'))
  false
end

#crm_enabled?Boolean

Returns:



3679
3680
3681
3682
3683
# File 'app/models/project.rb', line 3679

def crm_enabled?
  return false unless group

  group.crm_enabled?
end

#crm_groupObject



3685
3686
3687
3688
3689
# File 'app/models/project.rb', line 3685

def crm_group
  return unless group

  group.crm_group
end

#default_branch_or_mainObject



3423
3424
3425
3426
3427
# File 'app/models/project.rb', line 3423

def default_branch_or_main
  return default_branch if default_branch

  Gitlab::DefaultBranch.value(object: self)
end

#default_branch_protected?Boolean

Returns:



3357
3358
3359
3360
3361
# File 'app/models/project.rb', line 3357

def default_branch_protected?
  branch_protection = Gitlab::Access::DefaultBranchProtection.new(self.namespace.default_branch_protection_settings)

  !branch_protection.developer_can_push?
end

#default_environmentObject



2984
2985
2986
2987
2988
2989
2990
2991
# File 'app/models/project.rb', line 2984

def default_environment
  production_first = Arel.sql("(CASE WHEN name = 'production' THEN 0 ELSE 1 END), id ASC")

  environments
    .with_state(:available)
    .reorder(production_first)
    .first
end

#default_issues_tracker?Boolean

Returns:



2120
2121
2122
# File 'app/models/project.rb', line 2120

def default_issues_tracker?
  !external_issue_tracker
end

#default_merge_request_targetObject



3055
3056
3057
3058
3059
3060
# File 'app/models/project.rb', line 3055

def default_merge_request_target
  return self if project_setting.mr_default_target_self
  return self unless mr_can_target_upstream?

  forked_from_project
end

#default_pipeline_lockObject



1522
1523
1524
1525
1526
1527
1528
# File 'app/models/project.rb', line 1522

def default_pipeline_lock
  if keep_latest_artifacts_available?
    return :artifacts_locked
  end

  :unlocked
end

#dependency_proxy_variablesObject



2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
# File 'app/models/project.rb', line 2954

def dependency_proxy_variables
  Gitlab::Ci::Variables::Collection.new.tap do |variables|
    break variables unless Gitlab.config.dependency_proxy.enabled

    variables.append(key: 'CI_DEPENDENCY_PROXY_SERVER', value: Gitlab.host_with_port)
    variables.append(
      key: 'CI_DEPENDENCY_PROXY_GROUP_IMAGE_PREFIX',
      # The namespace path can include uppercase letters, which
      # Docker doesn't allow. The proxy expects it to be downcased.
      value: "#{Gitlab.host_with_port}/#{namespace.root_ancestor.path.downcase}#{DependencyProxy::URL_SUFFIX}"
    )
    variables.append(
      key: 'CI_DEPENDENCY_PROXY_DIRECT_GROUP_IMAGE_PREFIX',
      value: "#{Gitlab.host_with_port}/#{namespace.full_path.downcase}#{DependencyProxy::URL_SUFFIX}"
    )
  end
end

#deploy_token_create_url(opts = {}) ⇒ Object



3349
3350
3351
# File 'app/models/project.rb', line 3349

def deploy_token_create_url(opts = {})
  Gitlab::Routing.url_helpers.create_deploy_token_project_settings_repository_path(self, opts)
end

#deploy_token_revoke_url_for(token) ⇒ Object



3353
3354
3355
# File 'app/models/project.rb', line 3353

def deploy_token_revoke_url_for(token)
  Gitlab::Routing.url_helpers.revoke_project_deploy_token_path(self, token)
end

#deployment_variables(environment:, kubernetes_namespace: nil) ⇒ Object



3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
# File 'app/models/project.rb', line 3012

def deployment_variables(environment:, kubernetes_namespace: nil)
  platform = deployment_platform(environment: environment)

  return [] unless platform.present?

  platform.predefined_variables(
    project: self,
    environment_name: environment,
    kubernetes_namespace: kubernetes_namespace
  )
end

#deprecated_ownerObject



2235
2236
2237
2238
2239
# File 'app/models/project.rb', line 2235

def deprecated_owner
  # Kept in order to maintain webhook structures until we remove owner_name and owner_email
  # See https://gitlab.com/gitlab-org/gitlab/-/issues/350603
  group || namespace.try(:owner)
end

#design_management_enabled?Boolean

LFS and hashed repository storage are required for using Design Management.

Returns:



1610
1611
1612
# File 'app/models/project.rb', line 1610

def design_management_enabled?
  lfs_enabled? && hashed_storage?(:repository)
end

#design_repositoryObject



1627
1628
1629
1630
1631
# File 'app/models/project.rb', line 1627

def design_repository
  strong_memoize(:design_repository) do
    find_or_create_design_management_repository.repository
  end
end

#destroy_deployment_by_id(deployment_id) ⇒ Object



3655
3656
3657
# File 'app/models/project.rb', line 3655

def destroy_deployment_by_id(deployment_id)
  deployments.where(id: deployment_id).fast_destroy_all
end

#disabled_integrationsObject

Returns a list of integration names that should be disabled at the project-level. Globally disabled integrations should go in Integration.disabled_integration_names.



2158
2159
2160
# File 'app/models/project.rb', line 2158

def disabled_integrations
  %w[zentao]
end

#dormant?Boolean

Returns:



3634
3635
3636
3637
# File 'app/models/project.rb', line 3634

def dormant?
  (statistics || build_statistics).storage_size > ::Gitlab::CurrentSettings.inactive_projects_min_size_mb.megabytes &&
    last_activity_at < ::Gitlab::CurrentSettings.inactive_projects_send_warning_email_after_months.months.ago
end

#drop_visibility_level!Object



3325
3326
3327
3328
3329
3330
3331
3332
3333
# File 'app/models/project.rb', line 3325

def drop_visibility_level!
  if group && group.visibility_level < visibility_level
    self.visibility_level = group.visibility_level
  end

  if Gitlab::CurrentSettings.restricted_visibility_levels.include?(visibility_level)
    self.visibility_level = Gitlab::VisibilityLevel::PRIVATE
  end
end

#emails_disabled?Boolean

Returns:



1565
1566
1567
1568
# File 'app/models/project.rb', line 1565

def emails_disabled?
  # disabling in the namespace overrides the project setting
  !emails_enabled?
end

#enable_ciObject



2587
2588
2589
# File 'app/models/project.rb', line 2587

def enable_ci
  project_feature.update_attribute(:builds_access_level, ProjectFeature::ENABLED)
end

#enforce_auth_checks_on_uploads?Boolean

Returns:



1466
1467
1468
# File 'app/models/project.rb', line 1466

def enforce_auth_checks_on_uploads?
  !!project_setting&.enforce_auth_checks_on_uploads?
end

#enforced_runner_token_expiration_intervalObject



3544
3545
3546
3547
3548
3549
3550
3551
3552
# File 'app/models/project.rb', line 3544

def enforced_runner_token_expiration_interval
  group_settings = NamespaceSetting.where(namespace_id: parent_groups)
  group_interval = group_settings.where.not(project_runner_token_expiration_interval: nil).minimum(:project_runner_token_expiration_interval)&.seconds

  [
    Gitlab::CurrentSettings.project_runner_token_expiration_interval&.seconds,
    group_interval
  ].compact.min
end

#enqueue_record_project_target_platformsObject



3628
3629
3630
3631
3632
# File 'app/models/project.rb', line 3628

def enqueue_record_project_target_platforms
  return unless Gitlab.com?

  Projects::RecordTargetPlatformsWorker.perform_async(id)
end

#ensure_pool_repositoryObject

Ensures project has a pool repository without exposing private creation logic



3787
3788
3789
# File 'app/models/project.rb', line 3787

def ensure_pool_repository
  pool_repository || create_new_pool_repository
end

#ensure_repositoryObject



2495
2496
2497
# File 'app/models/project.rb', line 2495

def ensure_repository
  create_repository(force: true) unless repository_exists?
end

#environments_for_scope(scope) ⇒ Object



3369
3370
3371
3372
3373
# File 'app/models/project.rb', line 3369

def environments_for_scope(scope)
  quoted_scope = ::Gitlab::SQL::Glob.q(scope)

  environments.where("name LIKE (#{::Gitlab::SQL::Glob.to_like(quoted_scope)})") # rubocop:disable GitlabSecurity/SqlInjection
end

#execute_hooks(data, hooks_scope = :push_hooks) ⇒ Object

rubocop: disable CodeReuse/ServiceClass



2259
2260
2261
2262
2263
2264
# File 'app/models/project.rb', line 2259

def execute_hooks(data, hooks_scope = :push_hooks)
  run_after_commit_or_now do
    triggered_hooks(hooks_scope, data).execute
    SystemHooksService.new.execute_hooks(data, hooks_scope)
  end
end

#execute_integrations(data, hooks_scope = :push_hooks, skip_ci: false) ⇒ Object



2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
# File 'app/models/project.rb', line 2283

def execute_integrations(data, hooks_scope = :push_hooks, skip_ci: false)
  # Call only service hooks that are active for this scope
  run_after_commit_or_now do
    association("#{hooks_scope}_integrations").reader.each do |integration|
      next if skip_ci && integration.ci?

      integration.async_execute(data)
    end
  end
end

#expire_caches_before_rename(old_path) ⇒ Object

Expires various caches before a project is renamed.



2351
2352
2353
2354
2355
2356
2357
2358
2359
# File 'app/models/project.rb', line 2351

def expire_caches_before_rename(old_path)
  project_repo = Repository.new(old_path, self, shard: repository_storage)
  wiki_repo = Repository.new("#{old_path}#{Gitlab::GlRepository::WIKI.path_suffix}", self, shard: repository_storage, repo_type: Gitlab::GlRepository::WIKI)
  design_repo = Repository.new("#{old_path}#{Gitlab::GlRepository::DESIGN.path_suffix}", self, shard: repository_storage, repo_type: Gitlab::GlRepository::DESIGN)

  [project_repo, wiki_repo, design_repo].each do |repo|
    repo.before_delete if repo.exists?
  end
end

#export_archive_exists?(user) ⇒ Boolean

Returns:



2849
2850
2851
# File 'app/models/project.rb', line 2849

def export_archive_exists?(user)
  import_export_upload_by_user(user)&.export_archive_exists?
end

#export_enqueued?(user) ⇒ Boolean

Returns:



2808
2809
2810
2811
2812
# File 'app/models/project.rb', line 2808

def export_enqueued?(user)
  strong_memoize(:export_enqueued) do
    ::Projects::ExportJobFinder.new(self, user, { status: :queued }).execute.present?
  end
end

#export_failed?(user) ⇒ Boolean

Returns:



2814
2815
2816
2817
2818
# File 'app/models/project.rb', line 2814

def export_failed?(user)
  strong_memoize(:export_failed) do
    ::Projects::ExportJobFinder.new(self, user, { status: :failed }).execute.present?
  end
end

#export_file(user) ⇒ Object



2853
2854
2855
# File 'app/models/project.rb', line 2853

def export_file(user)
  import_export_upload_by_user(user)&.export_file
end

#export_file_exists?(user) ⇒ Boolean

Returns:



2845
2846
2847
# File 'app/models/project.rb', line 2845

def export_file_exists?(user)
  import_export_upload_by_user(user)&.export_file_exists?
end

#export_in_progress?(user) ⇒ Boolean

Returns:



2802
2803
2804
2805
2806
# File 'app/models/project.rb', line 2802

def export_in_progress?(user)
  strong_memoize(:export_in_progress) do
    ::Projects::ExportJobFinder.new(self, user, { status: :started }).execute.present?
  end
end

#export_pathObject



2780
2781
2782
2783
2784
# File 'app/models/project.rb', line 2780

def export_path
  return unless namespace.present? || hashed_storage?(:repository)

  import_export_shared.archive_path
end

#export_status(user) ⇒ Object



2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
# File 'app/models/project.rb', line 2786

def export_status(user)
  if regeneration_in_progress?(user)
    :regeneration_in_progress
  elsif export_enqueued?(user)
    :queued
  elsif export_in_progress?(user)
    :started
  elsif export_file_exists?(user)
    :finished
  elsif export_failed?(user)
    :failed
  else
    :none
  end
end

#extended_prat_expiry_webhooks_execute?Boolean

Returns:



1474
1475
1476
# File 'app/models/project.rb', line 1474

def extended_prat_expiry_webhooks_execute?
  !!project_setting&.extended_prat_expiry_webhooks_execute?
end

#external_authorization_classification_labelObject



3204
3205
3206
3207
# File 'app/models/project.rb', line 3204

def external_authorization_classification_label
  super || ::Gitlab::CurrentSettings.current_application_settings
             .external_authorization_service_default_label
end

#external_import?Boolean

Returns:



1862
1863
1864
# File 'app/models/project.rb', line 1862

def external_import?
  safe_import_url.present?
end

#external_issue_reference_patternObject



2116
2117
2118
# File 'app/models/project.rb', line 2116

def external_issue_reference_pattern
  external_issue_tracker.reference_pattern(only_long: issues_enabled?)
end

#external_issue_trackerObject



2124
2125
2126
2127
2128
2129
2130
# File 'app/models/project.rb', line 2124

def external_issue_tracker
  cache_has_external_issue_tracker if has_external_issue_tracker.nil?

  return unless has_external_issue_tracker?

  @external_issue_tracker ||= integrations.external_issue_trackers.first
end

#external_references_supported?Boolean

Returns:



2132
2133
2134
# File 'app/models/project.rb', line 2132

def external_references_supported?
  external_issue_tracker&.support_cross_reference?
end

#external_wikiObject



2140
2141
2142
2143
2144
2145
2146
# File 'app/models/project.rb', line 2140

def external_wiki
  cache_has_external_wiki if has_external_wiki.nil?

  return unless has_external_wiki?

  @external_wiki ||= integrations.external_wikis.first
end

#feature_available?(feature, user = nil) ⇒ Boolean

Returns:



2525
2526
2527
# File 'app/models/project.rb', line 2525

def feature_available?(feature, user = nil)
  !!project_feature&.feature_available?(feature, user)
end

#feature_flags_client_tokenObject



3437
3438
3439
3440
# File 'app/models/project.rb', line 3437

def feature_flags_client_token
  instance = operations_feature_flags_client || create_operations_feature_flags_client!
  instance.token
end

#feature_usageObject



2312
2313
2314
# File 'app/models/project.rb', line 2312

def feature_usage
  super.presence || build_feature_usage
end

#ff_merge_must_be_possible?Boolean

Returns:



3162
3163
3164
# File 'app/models/project.rb', line 3162

def ff_merge_must_be_possible?
  self.merge_requests_ff_only_enabled || self.merge_requests_rebase_enabled
end

#find_or_create_design_management_repositoryObject



1623
1624
1625
# File 'app/models/project.rb', line 1623

def find_or_create_design_management_repository
  design_management_repository || create_design_management_repository
end

#find_or_initialize_integration(name) ⇒ Object



2162
2163
2164
2165
2166
2167
# File 'app/models/project.rb', line 2162

def find_or_initialize_integration(name)
  return if disabled_integrations.include?(name)
  return if Integration.available_integration_names(include_instance_specific: false).exclude?(name)

  find_integration(integrations, name) || build_from_instance(name) || build_integration(name)
end

#find_or_initialize_integrationsObject



2148
2149
2150
2151
2152
2153
2154
# File 'app/models/project.rb', line 2148

def find_or_initialize_integrations
  Integration
    .available_integration_names(include_instance_specific: false)
    .difference(disabled_integrations)
    .map { find_or_initialize_integration(_1) }
    .sort_by { |int| int.title.downcase }
end

#first_auto_devops_configObject



1603
1604
1605
1606
1607
# File 'app/models/project.rb', line 1603

def first_auto_devops_config
  return namespace.first_auto_devops_config if auto_devops&.enabled.nil?

  { scope: :project, status: auto_devops&.enabled || Feature.enabled?(:force_autodevops_on_by_default, self) }
end

#first_ownerObject



2248
2249
2250
2251
2252
2253
2254
2255
2256
# File 'app/models/project.rb', line 2248

def first_owner
  obj = owner

  if obj.respond_to?(:first_owner)
    obj.first_owner
  else
    obj
  end
end

#fork_sourceObject



2320
2321
2322
2323
2324
# File 'app/models/project.rb', line 2320

def fork_source
  return unless forked?

  forked_from_project || fork_network&.root_project
end

#forked?Boolean

Returns:



2316
2317
2318
# File 'app/models/project.rb', line 2316

def forked?
  fork_network && fork_network.root_project != self
end

#forked_from?(other_project) ⇒ Boolean

Returns:



2481
2482
2483
# File 'app/models/project.rb', line 2481

def forked_from?(other_project)
  forked? && forked_from_project == other_project
end

#forking_enabled?Boolean

Returns:



2541
2542
2543
# File 'app/models/project.rb', line 2541

def forking_enabled?
  !!project_feature&.forking_enabled?
end

#forks_countObject

rubocop: disable CodeReuse/ServiceClass



3084
3085
3086
3087
3088
3089
3090
3091
3092
# File 'app/models/project.rb', line 3084

def forks_count
  BatchLoader.for(self).batch do |projects, loader|
    fork_count_per_project = ::Projects::BatchForksCountService.new(projects).refresh_cache_and_retrieve_data

    fork_count_per_project.each do |project, count|
      loader.call(project, count)
    end
  end
end

#full_path_before_last_saveObject



3074
3075
3076
# File 'app/models/project.rb', line 3074

def full_path_before_last_save
  File.join(namespace.full_path, path_before_last_save)
end

#full_path_slugObject



2857
2858
2859
# File 'app/models/project.rb', line 2857

def full_path_slug
  Gitlab::Utils.slugify(full_path.to_s)
end

#get_issue(issue_id, current_user) ⇒ Object



2102
2103
2104
2105
2106
2107
2108
2109
2110
# File 'app/models/project.rb', line 2102

def get_issue(issue_id, current_user)
  issue = IssuesFinder.new(current_user, project_id: id).find_by(iid: issue_id) if issues_enabled?

  if issue
    issue
  elsif external_issue_tracker
    ExternalIssue.new(issue_id, self)
  end
end

#git_garbage_collect_worker_klassObject



3443
3444
3445
# File 'app/models/project.rb', line 3443

def git_garbage_collect_worker_klass
  Projects::GitGarbageCollectWorker
end

#git_objects_poolable?Boolean

Git objects are only poolable when the project is or has:

  • Hashed storage -> The object pool will have a remote to its members, using relative paths.

    If the repository path changes we would have to update the remote.
    
  • not private -> The visibility level or repository access level has to be greater than private

    to prevent fetching objects that might not exist
    
  • Repository -> Else the disk path will be empty, and there’s nothing to pool

Returns:



3264
3265
3266
3267
3268
3269
3270
# File 'app/models/project.rb', line 3264

def git_objects_poolable?
  hashed_storage?(:repository) &&
    visibility_level > Gitlab::VisibilityLevel::PRIVATE &&
    repository_access_level > ProjectFeature::PRIVATE &&
    repository_exists? &&
    Gitlab::CurrentSettings.hashed_storage_enabled
end

#git_transfer_in_progress?Boolean

Returns:



3167
3168
3169
3170
3171
# File 'app/models/project.rb', line 3167

def git_transfer_in_progress?
  GL_REPOSITORY_TYPES.any? do |type|
    reference_counter(type: type).value > 0
  end
end

#gitea_import?Boolean

Returns:



1884
1885
1886
# File 'app/models/project.rb', line 1884

def gitea_import?
  import_type == 'gitea'
end

#github_enterprise_import?Boolean

Returns:



1900
1901
1902
1903
# File 'app/models/project.rb', line 1900

def github_enterprise_import?
  github_import? &&
    URI.parse(safe_import_url).host != URI.parse(Octokit::Default::API_ENDPOINT).host
end

#github_import?Boolean

Returns:



1888
1889
1890
# File 'app/models/project.rb', line 1888

def github_import?
  import_type == 'github'
end

#gitlab_deploy_tokenObject



3222
3223
3224
3225
3226
# File 'app/models/project.rb', line 3222

def gitlab_deploy_token
  strong_memoize(:gitlab_deploy_token) do
    deploy_tokens.gitlab_deploy_token || group&.gitlab_deploy_token
  end
end

#gitlab_project_import?Boolean

Returns:



1876
1877
1878
# File 'app/models/project.rb', line 1876

def gitlab_project_import?
  import_type == 'gitlab_project'
end

#gitlab_project_migration?Boolean

Returns:



1880
1881
1882
# File 'app/models/project.rb', line 1880

def gitlab_project_migration?
  import_type == 'gitlab_project_migration'
end

#glql_load_on_click_feature_flag_enabled?Boolean

Returns:



3594
3595
3596
# File 'app/models/project.rb', line 3594

def glql_load_on_click_feature_flag_enabled?
  group&.glql_load_on_click_feature_flag_enabled? || Feature.enabled?(:glql_load_on_click, self, type: :ops)
end


3643
3644
3645
# File 'app/models/project.rb', line 3643

def group_group_links
  group&.shared_with_group_links_of_ancestors_and_self || GroupGroupLink.none
end

#group_protected_branchesObject



3343
3344
3345
3346
3347
# File 'app/models/project.rb', line 3343

def group_protected_branches
  return root_namespace.protected_branches if root_namespace.is_a?(Group)

  ProtectedBranch.none
end

#group_runnersObject



2603
2604
2605
# File 'app/models/project.rb', line 2603

def group_runners
  @group_runners ||= group_runners_enabled? ? Ci::Runner.belonging_to_parent_groups_of_project(self.id) : Ci::Runner.none
end

#group_runners_enabled?Boolean

Returns:



3515
3516
3517
3518
3519
# File 'app/models/project.rb', line 3515

def group_runners_enabled?
  return false unless ci_cd_settings

  ci_cd_settings.group_runners_enabled?
end

#has_active_hooks?(hooks_scope = :push_hooks) ⇒ Boolean

Returns:



2294
2295
2296
2297
2298
2299
2300
2301
2302
# File 'app/models/project.rb', line 2294

def has_active_hooks?(hooks_scope = :push_hooks)
  @has_active_hooks ||= {} # rubocop: disable Gitlab/PredicateMemoization

  return @has_active_hooks[hooks_scope] if @has_active_hooks.key?(hooks_scope)

  @has_active_hooks[hooks_scope] = hooks.hooks_for(hooks_scope).any? ||
    SystemHook.hooks_for(hooks_scope).any? ||
    Gitlab::FileHook.any?
end

#has_active_integrations?(hooks_scope = :push_hooks) ⇒ Boolean

Returns:



2304
2305
2306
2307
2308
2309
2310
# File 'app/models/project.rb', line 2304

def has_active_integrations?(hooks_scope = :push_hooks)
  @has_active_integrations ||= {} # rubocop: disable Gitlab/PredicateMemoization

  return @has_active_integrations[hooks_scope] if @has_active_integrations.key?(hooks_scope)

  @has_active_integrations[hooks_scope] = integrations.public_send(hooks_scope).any? # rubocop:disable GitlabSecurity/PublicSend
end

#has_auto_devops_implicitly_disabled?Boolean

Returns:



1593
1594
1595
1596
1597
# File 'app/models/project.rb', line 1593

def has_auto_devops_implicitly_disabled?
  auto_devops_config = first_auto_devops_config

  auto_devops_config[:scope] != :project && !auto_devops_config[:status]
end

#has_auto_devops_implicitly_enabled?Boolean

Returns:



1587
1588
1589
1590
1591
# File 'app/models/project.rb', line 1587

def has_auto_devops_implicitly_enabled?
  auto_devops_config = first_auto_devops_config

  auto_devops_config[:scope] != :project && auto_devops_config[:status]
end

#has_ci?Boolean

Returns:



2861
2862
2863
# File 'app/models/project.rb', line 2861

def has_ci?
  has_ci_config_file? || auto_devops_enabled?
end

#has_ci_config_file?Boolean

Returns:



2865
2866
2867
2868
2869
# File 'app/models/project.rb', line 2865

def has_ci_config_file?
  strong_memoize(:has_ci_config_file) do
    ci_config_for('HEAD').present?
  end
end

#has_container_registry_protected_tag_rules?(action:, access_level:) ⇒ Boolean

Returns:



3775
3776
3777
3778
3779
# File 'app/models/project.rb', line 3775

def has_container_registry_protected_tag_rules?(action:, access_level:)
  strong_memoize_with(:has_container_registry_protected_tag_rules, action, access_level) do
    container_registry_protection_tag_rules.for_actions_and_access([action], access_level).exists?
  end
end

#has_container_registry_tags?Boolean

Returns:



1654
1655
1656
1657
1658
1659
# File 'app/models/project.rb', line 1654

def has_container_registry_tags?
  return @images if defined?(@images)

  @images = container_repositories.to_a.any?(&:has_tags?) ||
    has_root_container_repository_tags?
end

#has_pool_repository?Boolean

Returns:



3302
3303
3304
# File 'app/models/project.rb', line 3302

def has_pool_repository?
  pool_repository.present?
end

#has_remote_mirror?Boolean

Returns:



1917
1918
1919
# File 'app/models/project.rb', line 1917

def has_remote_mirror?
  remote_mirror_available? && remote_mirrors.enabled.exists?
end

#has_wiki?Boolean

Returns:



2136
2137
2138
# File 'app/models/project.rb', line 2136

def has_wiki?
  wiki_enabled? || has_external_wiki?
end

#hashed_storage?(feature) ⇒ Boolean

Check if Hashed Storage is enabled for the project with at least informed feature rolled out

Parameters:

  • that needs to be rolled out for the project (:repository, :attachments)

Returns:

Raises:



3102
3103
3104
3105
3106
# File 'app/models/project.rb', line 3102

def hashed_storage?(feature)
  raise ArgumentError, _("Invalid feature") unless HASHED_STORAGE_FEATURES.include?(feature)

  self.storage_version && self.storage_version >= HASHED_STORAGE_FEATURES[feature]
end

#hook_attrs(backward: true) ⇒ Object



2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
# File 'app/models/project.rb', line 2412

def hook_attrs(backward: true)
  attrs = {
    id: id,
    name: name,
    description: description,
    web_url: web_url,
    avatar_url: avatar_url(only_path: false),
    git_ssh_url: ssh_url_to_repo,
    git_http_url: http_url_to_repo,
    namespace: namespace.name,
    visibility_level: visibility_level,
    path_with_namespace: full_path,
    default_branch: default_branch,
    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
    })
  end

  attrs
end

#human_import_status_nameObject



1735
1736
1737
# File 'app/models/project.rb', line 1735

def human_import_status_name
  import_state&.human_status_name || 'none'
end

#human_merge_methodObject



3126
3127
3128
3129
3130
3131
3132
# File 'app/models/project.rb', line 3126

def human_merge_method
  if merge_method == :ff
    'Fast-forward'
  else
    merge_method.to_s.humanize
  end
end

#import?Boolean

Returns:



1858
1859
1860
# File 'app/models/project.rb', line 1858

def import?
  external_import? || forked? || gitlab_project_import? || jira_import? || gitlab_project_migration? || Gitlab::ImportSources.template?(import_type)
end

#import_checksumsObject



1727
1728
1729
# File 'app/models/project.rb', line 1727

def import_checksums
  import_state&.checksums || {}
end

#import_export_sharedObject



2776
2777
2778
# File 'app/models/project.rb', line 2776

def import_export_shared
  @import_export_shared ||= Gitlab::ImportExport::Shared.new(self)
end

#import_export_upload_by_user(user) ⇒ Object



2841
2842
2843
# File 'app/models/project.rb', line 2841

def import_export_upload_by_user(user)
  import_export_uploads.find_by(user_id: user.id)
end

#import_failed?Boolean

Returns:



1494
1495
1496
# File 'app/models/project.rb', line 1494

def import_failed?
  !!import_state&.failed?
end

#import_finished?Boolean

Returns:



1498
1499
1500
# File 'app/models/project.rb', line 1498

def import_finished?
  !!import_state&.finished?
end

#import_in_progress?Boolean

Returns:



1490
1491
1492
# File 'app/models/project.rb', line 1490

def import_in_progress?
  !!import_state&.in_progress?
end

#import_scheduled?Boolean

Returns:



1482
1483
1484
# File 'app/models/project.rb', line 1482

def import_scheduled?
  !!import_state&.scheduled?
end

#import_started?Boolean

Returns:



1486
1487
1488
# File 'app/models/project.rb', line 1486

def import_started?
  !!import_state&.started?
end

#import_statusObject



1723
1724
1725
# File 'app/models/project.rb', line 1723

def import_status
  import_state&.status || 'none'
end

#import_url=(value) ⇒ Object



1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
# File 'app/models/project.rb', line 1814

def import_url=(value)
  if Gitlab::UrlSanitizer.valid?(value)
    # Assign sanitized URL, stripped of userinfo credentials, to `Project#import_url` attribute.
    import_url = Gitlab::UrlSanitizer.new(value)
    super(import_url.sanitized_url)

    # Assign any userinfo credentials to the `ProjectImportData#credentials` attribute.
    credentials = import_url.credentials.to_h.transform_values { |value| CGI.unescape(value.to_s) }
    build_or_assign_import_data(credentials: credentials)
  else
    super(value)
  end
end

#in_fork_network_of?(other_project) ⇒ Boolean

Returns:



2485
2486
2487
2488
2489
# File 'app/models/project.rb', line 2485

def in_fork_network_of?(other_project)
  return false if fork_network.nil? || other_project.fork_network.nil?

  fork_network == other_project.fork_network
end

#initial_push_to_default_branch_allowed_for_developer?Boolean

Returns:



3363
3364
3365
3366
3367
# File 'app/models/project.rb', line 3363

def initial_push_to_default_branch_allowed_for_developer?
  branch_protection = Gitlab::Access::DefaultBranchProtection.new(self.namespace.default_branch_protection_settings)

  branch_protection.developer_can_push? || branch_protection.developer_can_initial_push?
end

#instance_runner_running_jobs_countObject



3708
3709
3710
3711
3712
# File 'app/models/project.rb', line 3708

def instance_runner_running_jobs_count
  # excluding currently started job
  ::Ci::RunningBuild.instance_type.where(project_id: self.id)
                    .limit(INSTANCE_RUNNER_RUNNING_JOBS_MAX_BUCKET + 1).count - 1
end

#invalidate_personal_projects_count_of_ownerObject



1451
1452
1453
1454
1455
1456
# File 'app/models/project.rb', line 1451

def invalidate_personal_projects_count_of_owner
  return unless personal?
  return unless namespace.owner

  namespace.owner.invalidate_personal_projects_count
end

#issue_exists?(issue_id) ⇒ Boolean

Returns:



2112
2113
2114
# File 'app/models/project.rb', line 2112

def issue_exists?(issue_id)
  get_issue(issue_id)
end

#issues_enabled?Boolean

Returns:



2545
2546
2547
# File 'app/models/project.rb', line 2545

def issues_enabled?
  !!project_feature&.issues_enabled?
end

#items_for(entity) ⇒ Object



2209
2210
2211
2212
2213
2214
2215
2216
# File 'app/models/project.rb', line 2209

def items_for(entity)
  case entity
  when 'issue' then
    issues
  when 'merge_request' then
    merge_requests
  end
end

#jenkins_integration_active?Boolean

Returns:



1435
1436
1437
# File 'app/models/project.rb', line 1435

def jenkins_integration_active?
  !!jenkins_integration&.active?
end

#jira_import?Boolean

Returns:



1872
1873
1874
# File 'app/models/project.rb', line 1872

def jira_import?
  import_type == 'jira' && latest_jira_import.present?
end

#jira_import_statusObject



1731
1732
1733
# File 'app/models/project.rb', line 1731

def jira_import_status
  latest_jira_import&.status || 'initial'
end

#jira_subscription_exists?Boolean

Returns:



3339
3340
3341
# File 'app/models/project.rb', line 3339

def jira_subscription_exists?
  JiraConnectSubscription.for_project(self).exists?
end

#keep_latest_artifact?Boolean

Returns:



3509
3510
3511
3512
3513
# File 'app/models/project.rb', line 3509

def keep_latest_artifact?
  return false unless ci_cd_settings

  ci_cd_settings.keep_latest_artifact?
end

#keep_latest_artifacts_available?Boolean

Returns:



3503
3504
3505
3506
3507
# File 'app/models/project.rb', line 3503

def keep_latest_artifacts_available?
  return false unless ci_cd_settings

  ci_cd_settings.keep_latest_artifacts_available?
end

#last_activityObject



2094
2095
2096
# File 'app/models/project.rb', line 2094

def last_activity
  last_event
end

#latest_jira_importObject



3386
3387
3388
# File 'app/models/project.rb', line 3386

def latest_jira_import
  jira_imports.last
end

#latest_pipeline(ref = default_branch, sha = nil, source = nil) ⇒ Object



1704
1705
1706
# File 'app/models/project.rb', line 1704

def latest_pipeline(ref = default_branch, sha = nil, source = nil)
  latest_pipelines(ref: ref, sha: sha, source: source).take
end

#latest_pipeline_for_ci_and_security_orchestration(ref = default_branch) ⇒ Object



1708
1709
1710
# File 'app/models/project.rb', line 1708

def latest_pipeline_for_ci_and_security_orchestration(ref = default_branch)
  all_pipelines.ci_and_security_orchestration_sources.newest_first(ref: ref).take
end

#latest_pipelines(ref: default_branch, sha: nil, limit: nil, source: nil) ⇒ Object



1684
1685
1686
1687
1688
1689
1690
# File 'app/models/project.rb', line 1684

def latest_pipelines(ref: default_branch, sha: nil, limit: nil, source: nil)
  ref = ref.presence || default_branch
  sha ||= commit(ref)&.sha
  return ci_pipelines.none unless sha

  ci_pipelines.newest_first(ref: ref, sha: sha, limit: limit, source: source)
end

#latest_successful_build_for_ref(job_name, ref = default_branch) ⇒ Object

ref can’t be HEAD, can only be branch/tag name



1662
1663
1664
1665
1666
1667
1668
1669
# File 'app/models/project.rb', line 1662

def latest_successful_build_for_ref(job_name, ref = default_branch)
  return unless ref

  latest_pipeline = ci_pipelines.latest_successful_for_ref(ref)
  return unless latest_pipeline

  latest_pipeline.build_with_artifacts_in_self_and_project_descendants(job_name)
end

#latest_successful_build_for_ref!(job_name, ref = default_branch) ⇒ Object



1680
1681
1682
# File 'app/models/project.rb', line 1680

def latest_successful_build_for_ref!(job_name, ref = default_branch)
  latest_successful_build_for_ref(job_name, ref) || raise(ActiveRecord::RecordNotFound, "Couldn't find job #{job_name}")
end

#latest_successful_build_for_sha(job_name, sha) ⇒ Object



1671
1672
1673
1674
1675
1676
1677
1678
# File 'app/models/project.rb', line 1671

def latest_successful_build_for_sha(job_name, sha)
  return unless sha

  latest_pipeline = ci_pipelines.latest_successful_for_sha(sha)
  return unless latest_pipeline

  latest_pipeline.build_with_artifacts_in_self_and_project_descendants(job_name)
end

#latest_successful_pipeline_for(ref = nil) ⇒ Object



2517
2518
2519
2520
2521
2522
2523
# File 'app/models/project.rb', line 2517

def latest_successful_pipeline_for(ref = nil)
  if ref && ref != default_branch
    ci_pipelines.latest_successful_for_ref(ref)
  else
    latest_successful_pipeline_for_default_branch
  end
end

#latest_successful_pipeline_for_default_branchObject



2508
2509
2510
2511
2512
2513
2514
2515
# File 'app/models/project.rb', line 2508

def latest_successful_pipeline_for_default_branch
  if defined?(@latest_successful_pipeline_for_default_branch)
    return @latest_successful_pipeline_for_default_branch
  end

  @latest_successful_pipeline_for_default_branch =
    ci_pipelines.latest_successful_for_ref(default_branch)
end

#latest_unscheduled_pipeline(ref = default_branch, sha = nil) ⇒ Object



1700
1701
1702
# File 'app/models/project.rb', line 1700

def latest_unscheduled_pipeline(ref = default_branch, sha = nil)
  latest_unscheduled_pipelines(ref: ref, sha: sha).take
end

#latest_unscheduled_pipelines(ref: default_branch, sha: nil) ⇒ Object



1692
1693
1694
1695
1696
1697
1698
# File 'app/models/project.rb', line 1692

def latest_unscheduled_pipelines(ref: default_branch, sha: nil)
  ref = ref.presence || default_branch
  sha ||= commit(ref)&.sha
  return ci_pipelines.none unless sha

  ci_pipelines.newest_without_schedules(ref: ref, sha: sha)
end

#leave_pool_repositoryObject



3272
3273
3274
3275
3276
3277
3278
3279
# File 'app/models/project.rb', line 3272

def leave_pool_repository
  return if pool_repository.blank?

  # Disconnecting the repository can be expensive, so let's skip it if
  # this repository is being deleted anyway.
  pool_repository.unlink_repository(repository, disconnect: !pending_delete?)
  update_column(:pool_repository_id, nil)
end

#legacy_storage?Boolean

rubocop: enable CodeReuse/ServiceClass

Returns:



3095
3096
3097
# File 'app/models/project.rb', line 3095

def legacy_storage?
  [nil, 0].include?(self.storage_version)
end

#lfs_enabled?Boolean Also known as: lfs_enabled

Returns:



1571
1572
1573
1574
1575
# File 'app/models/project.rb', line 1571

def lfs_enabled?
  return namespace.lfs_enabled? if self[:lfs_enabled].nil?

  self[:lfs_enabled] && Gitlab.config.lfs.enabled
end

#lfs_file_locks_changed_epochObject



3740
3741
3742
# File 'app/models/project.rb', line 3740

def lfs_file_locks_changed_epoch
  get_epoch_from(lfs_file_locks_changed_epoch_cache_key)
end

#lfs_objects_for_repository_types(*types) ⇒ Object



2330
2331
2332
2333
2334
# File 'app/models/project.rb', line 2330

def lfs_objects_for_repository_types(*types)
  LfsObject
    .joins(:lfs_objects_projects)
    .where(lfs_objects_projects: { project: self, repository_type: types })
end

#lfs_objects_oids(oids: []) ⇒ Object



2336
2337
2338
# File 'app/models/project.rb', line 2336

def lfs_objects_oids(oids: [])
  oids(lfs_objects, oids: oids)
end

#lfs_objects_oids_from_fork_source(oids: []) ⇒ Object



2340
2341
2342
2343
2344
# File 'app/models/project.rb', line 2340

def lfs_objects_oids_from_fork_source(oids: [])
  return [] unless forked?

  oids(fork_source.lfs_objects, oids: oids)
end

#licensed_ai_features_available?Boolean

Overridden for EE

Returns:



3782
3783
3784
# File 'app/models/project.rb', line 3782

def licensed_ai_features_available?
  false
end

#licensed_feature_available?(_feature) ⇒ Boolean

Overridden in EE::Project

Returns:



3210
3211
3212
# File 'app/models/project.rb', line 3210

def licensed_feature_available?(_feature)
  false
end

#licensed_featuresObject



3214
3215
3216
# File 'app/models/project.rb', line 3214

def licensed_features
  []
end


3295
3296
3297
3298
3299
3300
# File 'app/models/project.rb', line 3295

def link_pool_repository
  return unless pool_repository
  return if pool_repository.shard_name != repository.shard

  pool_repository.link_repository(repository)
end

#log_import_activity(job_id, type: :import) ⇒ Object



1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
# File 'app/models/project.rb', line 1764

def log_import_activity(job_id, type: :import)
  job_type = type.to_s.capitalize

  if job_id
    use_primary = ::Gitlab::Database::LoadBalancing::SessionMap.current(load_balancer).use_primary?
    Gitlab::AppLogger.info("#{job_type} job scheduled for #{full_path} with job ID #{job_id} (primary: #{use_primary}).")
  else
    Gitlab::AppLogger.error("#{job_type} job failed to create for #{full_path}.")
  end
end

#mark_pages_onboarding_completeObject



2706
2707
2708
# File 'app/models/project.rb', line 2706

def mark_pages_onboarding_complete
  ensure_pages_metadatum.update!(onboarding_complete: true)
end

#mark_remote_mirrors_for_removalObject



1939
1940
1941
# File 'app/models/project.rb', line 1939

def mark_remote_mirrors_for_removal
  remote_mirrors.each(&:mark_for_delete_if_blank_url)
end

#mark_stuck_remote_mirrors_as_failed!Object



1931
1932
1933
1934
1935
1936
1937
# File 'app/models/project.rb', line 1931

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_update_at: Time.current
  )
end

#markdown_placeholders_feature_flag_enabled?Boolean

Returns:



3598
3599
3600
# File 'app/models/project.rb', line 3598

def markdown_placeholders_feature_flag_enabled?
  group&.markdown_placeholders_feature_flag_enabled? || Feature.enabled?(:markdown_placeholders, self, type: :gitlab_com_derisk)
end

#marked_for_deletion_onObject

marked_for_deletion_at is deprecated in our v5 REST API in favor of marked_for_deletion_on docs.gitlab.com/ee/api/projects.html#removals-in-api-v5



196
# File 'app/models/project.rb', line 196

alias_attribute :marked_for_deletion_on, :marked_for_deletion_at

#max_attachment_sizeObject



3254
3255
3256
# File 'app/models/project.rb', line 3254

def max_attachment_size
  Gitlab::CurrentSettings.max_attachment_size.megabytes.to_i
end

#member(user) ⇒ Object



2441
2442
2443
2444
2445
2446
2447
# File 'app/models/project.rb', line 2441

def member(user)
  if project_members.loaded?
    project_members.find { |member| member.user_id == user.id }
  else
    project_members.find_by(user_id: user)
  end
end

#members_among(users) ⇒ Object

Filters users to return only authorized users of the project



2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
# File 'app/models/project.rb', line 2459

def members_among(users)
  if users.is_a?(ActiveRecord::Relation) && !users.loaded?
    authorized_users.merge(users)
  else
    return [] if users.empty?

    user_ids = authorized_users.where(users: { id: users.map(&:id) }).pluck(:id)
    users.select { |user| user_ids.include?(user.id) }
  end
end

#membership_locked?Boolean

Overridden in EE

Returns:



2450
2451
2452
# File 'app/models/project.rb', line 2450

def membership_locked?
  false
end

#merge_base_commit(first_commit_id, second_commit_id) ⇒ Object



1712
1713
1714
1715
1716
1717
# File 'app/models/project.rb', line 1712

def merge_base_commit(first_commit_id, second_commit_id)
  strong_memoize(:"merge_base_commit_#{first_commit_id}_#{second_commit_id}") do
    sha = repository.merge_base(first_commit_id, second_commit_id)
    commit_by(oid: sha) if sha
  end
end

#merge_commit_template_or_defaultObject



3554
3555
3556
# File 'app/models/project.rb', line 3554

def merge_commit_template_or_default
  merge_commit_template.presence || DEFAULT_MERGE_COMMIT_TEMPLATE
end

#merge_commit_template_or_default=(value) ⇒ Object



3558
3559
3560
3561
3562
3563
3564
3565
# File 'app/models/project.rb', line 3558

def merge_commit_template_or_default=(value)
  project_setting.merge_commit_template =
    if value.blank? || value.delete("\r") == DEFAULT_MERGE_COMMIT_TEMPLATE
      nil
    else
      value
    end
end

#merge_methodObject



3134
3135
3136
3137
3138
3139
3140
3141
3142
# File 'app/models/project.rb', line 3134

def merge_method
  if self.merge_requests_ff_only_enabled
    :ff
  elsif self.merge_requests_rebase_enabled
    :rebase_merge
  else
    :merge
  end
end

#merge_method=(method) ⇒ Object



3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
# File 'app/models/project.rb', line 3148

def merge_method=(method)
  case method.to_s
  when "ff"
    self.merge_requests_ff_only_enabled = true
    self.merge_requests_rebase_enabled = true
  when "rebase_merge"
    self.merge_requests_ff_only_enabled = false
    self.merge_requests_rebase_enabled = true
  when "merge"
    self.merge_requests_ff_only_enabled = false
    self.merge_requests_rebase_enabled = false
  end
end

#merge_requests_allowing_push_to_user(user) ⇒ Object



3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
# File 'app/models/project.rb', line 3185

def merge_requests_allowing_push_to_user(user)
  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)
end

#merge_requests_enabled?Boolean

Returns:



2537
2538
2539
# File 'app/models/project.rb', line 2537

def merge_requests_enabled?
  !!project_feature&.merge_requests_enabled?
end

#merge_trains_enabled?Boolean

Overridden in EE

Returns:



3736
3737
3738
# File 'app/models/project.rb', line 3736

def merge_trains_enabled?
  false
end

#mr_can_target_upstream?Boolean

Returns:



3062
3063
3064
3065
3066
3067
3068
# File 'app/models/project.rb', line 3062

def mr_can_target_upstream?
  # When our current visibility is more restrictive than the upstream project,
  # (e.g., the fork is `private` but the parent is `public`), don't allow target upstream
  forked_from_project &&
    forked_from_project.merge_requests_enabled? &&
    forked_from_project.visibility_level_value <= visibility_level_value
end

#multiple_issue_boards_available?Boolean

Returns:



3070
3071
3072
# File 'app/models/project.rb', line 3070

def multiple_issue_boards_available?
  true
end

#new_issuable_address(author, address_type) ⇒ Object



2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
# File 'app/models/project.rb', line 2075

def new_issuable_address(author, address_type)
  return unless Gitlab::Email::IncomingEmail.supports_issue_creation? && author

  # check since this can come from a request parameter
  return unless %w[issue merge_request].include?(address_type)

  author.ensure_incoming_email_token!

  suffix = address_type.dasherize

  # example: incoming+h5bp-html5-boilerplate-8-1234567890abcdef123456789-issue@localhost.com
  # example: incoming+h5bp-html5-boilerplate-8-1234567890abcdef123456789-merge-request@localhost.com
  Gitlab::Email::IncomingEmail.reply_address("#{full_path_slug}-#{project_id}-#{author.incoming_email_token}-#{suffix}")
end

#no_import?Boolean

Returns:



1478
1479
1480
# File 'app/models/project.rb', line 1478

def no_import?
  !!import_state&.no_import?
end

#notify_project_import_complete?Boolean

Returns:



1866
1867
1868
1869
1870
# File 'app/models/project.rb', line 1866

def notify_project_import_complete?
  return false if import_type.nil? || mirror? || forked?

  gitea_import? || github_import? || bitbucket_import? || bitbucket_server_import?
end

#on_demand_dast_available?Boolean

Overridden in EE

Returns:



3726
3727
3728
# File 'app/models/project.rb', line 3726

def on_demand_dast_available?
  false
end

#open_issues_count(current_user = nil) ⇒ Object

rubocop: disable CodeReuse/ServiceClass



2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
# File 'app/models/project.rb', line 2630

def open_issues_count(current_user = nil)
  return Projects::OpenIssuesCountService.new(self, current_user).count unless current_user.nil?

  BatchLoader.for(self).batch do |projects, loader|
    issues_count_per_project = ::Projects::BatchOpenIssuesCountService.new(projects).refresh_cache_and_retrieve_data

    issues_count_per_project.each do |project, count|
      loader.call(project, count)
    end
  end
end

#open_merge_requests_count(_current_user = nil) ⇒ Object

rubocop: disable CodeReuse/ServiceClass



2644
2645
2646
2647
2648
2649
2650
# File 'app/models/project.rb', line 2644

def open_merge_requests_count(_current_user = nil)
  BatchLoader.for(self).batch do |projects, loader|
    ::Projects::BatchOpenMergeRequestsCountService.new(projects)
      .refresh_cache_and_retrieve_data
      .each { |project, count| loader.call(project, count) }
  end
end

#operations_enabled?Boolean

Returns:



2578
2579
2580
# File 'app/models/project.rb', line 2578

def operations_enabled?
  !!project_feature&.operations_enabled?
end

#origin_merge_requestsObject



2491
2492
2493
# File 'app/models/project.rb', line 2491

def origin_merge_requests
  merge_requests.where(source_project_id: self.id)
end

#override_pipeline_variables_allowed?(access_level, user) ⇒ Boolean

Returns:



3491
3492
3493
3494
3495
# File 'app/models/project.rb', line 3491

def override_pipeline_variables_allowed?(access_level, user)
  return false unless ci_cd_settings

  ci_cd_settings.override_pipeline_variables_allowed?(access_level, user)
end

#ownerObject

rubocop: enable CodeReuse/ServiceClass



2228
2229
2230
2231
2232
2233
# File 'app/models/project.rb', line 2228

def owner
  # This will be phased out and replaced with `owners` relationship
  # backed by memberships with direct/inherited Owner access roles
  # See https://gitlab.com/groups/gitlab-org/-/epics/7405
  group || namespace.try(:owner)
end

#owner_entityObject



1409
1410
1411
# File 'app/models/project.rb', line 1409

def owner_entity
  self
end

#owner_entity_nameObject



1413
1414
1415
# File 'app/models/project.rb', line 1413

def owner_entity_name
  :project
end

#ownersObject



2241
2242
2243
2244
2245
2246
# File 'app/models/project.rb', line 2241

def owners
  # This will be phased out and replaced with `owners` relationship
  # backed by memberships with direct/inherited Owner access roles
  # See https://gitlab.com/groups/gitlab-org/-/epics/7405
  team.owners
end

#packages_cleanup_policyObject



1599
1600
1601
# File 'app/models/project.rb', line 1599

def packages_cleanup_policy
  super || build_packages_cleanup_policy
end

#packages_policy_subjectObject



3651
3652
3653
# File 'app/models/project.rb', line 3651

def packages_policy_subject
  ::Packages::Policies::Project.new(self)
end

#pages_access_control_forced_by_ancestor?Boolean

Returns:



2572
2573
2574
2575
2576
# File 'app/models/project.rb', line 2572

def pages_access_control_forced_by_ancestor?
  return true if ::Gitlab::Pages.access_control_is_forced?

  namespace.pages_access_control_forced_by_self_or_ancestor?
end

#pages_deployed?Boolean

Returns:



2679
2680
2681
# File 'app/models/project.rb', line 2679

def pages_deployed?
  active_pages_deployments.exists?
end

#pages_domain_present?(domain_url) ⇒ Boolean

Returns:



3665
3666
3667
# File 'app/models/project.rb', line 3665

def pages_domain_present?(domain_url)
  pages_url == domain_url || pages_domains.any? { |domain| domain.url == domain_url }
end

#pages_enabled?Boolean

Returns:



2549
2550
2551
# File 'app/models/project.rb', line 2549

def pages_enabled?
  !!project_feature&.pages_enabled?
end

#pages_hostname(options = nil) ⇒ Object



3761
3762
3763
# File 'app/models/project.rb', line 3761

def pages_hostname(options = nil)
  pages_url_builder(options).hostname
end

#pages_https_onlyObject



1987
1988
1989
1990
1991
# File 'app/models/project.rb', line 1987

def pages_https_only
  return false unless Gitlab.config.pages.external_https || Gitlab.config.pages.custom_domain_mode == 'https'

  super
end

#pages_https_only?Boolean

Returns:



1993
1994
1995
1996
1997
# File 'app/models/project.rb', line 1993

def pages_https_only?
  return false unless Gitlab.config.pages.external_https || Gitlab.config.pages.custom_domain_mode == 'https'

  super
end

#pages_show_onboarding?Boolean

Returns:



2683
2684
2685
# File 'app/models/project.rb', line 2683

def pages_show_onboarding?
  !(pages_metadatum&.onboarding_complete || pages_deployed?)
end

#pages_unique_domain_enabled?Boolean

Returns:



2687
2688
2689
# File 'app/models/project.rb', line 2687

def pages_unique_domain_enabled?
  project_setting.pages_unique_domain_enabled
end

#pages_url(options = nil) ⇒ Object



3757
3758
3759
# File 'app/models/project.rb', line 3757

def pages_url(options = nil)
  pages_url_builder(options).pages_url
end

#pages_url_builder(options = nil) ⇒ Object



3769
3770
3771
3772
3773
# File 'app/models/project.rb', line 3769

def pages_url_builder(options = nil)
  strong_memoize_with(:pages_url_builder, options) do
    Gitlab::Pages::UrlBuilder.new(self, options)
  end
end

#pages_variablesObject



2931
2932
2933
2934
2935
2936
2937
2938
2939
# File 'app/models/project.rb', line 2931

def pages_variables
  Gitlab::Ci::Variables::Collection.new.tap do |variables|
    break unless pages_enabled?

    variables
      .append(key: 'CI_PAGES_DOMAIN', value: Gitlab.config.pages.host)
      .append(key: 'CI_PAGES_HOSTNAME', value: pages_hostname)
  end
end

#parent_changed?Boolean

Returns:



3051
3052
3053
# File 'app/models/project.rb', line 3051

def parent_changed?
  namespace_id_changed?
end

#parent_groupsObject



3540
3541
3542
# File 'app/models/project.rb', line 3540

def parent_groups
  Gitlab::ObjectHierarchy.new(Group.where(id: group)).base_and_ancestors
end

#parent_organization_matchObject



2015
2016
2017
2018
2019
2020
# File 'app/models/project.rb', line 2015

def parent_organization_match
  return unless parent
  return if parent.organization_id == organization_id

  errors.add(:organization_id, _("must match the parent organization's ID"))
end

#path_availabilityObject



3695
3696
3697
3698
3699
3700
3701
3702
# File 'app/models/project.rb', line 3695

def path_availability
  base, _, host = path.partition('.')

  return unless host == Gitlab.config.pages&.dig('host')
  return unless ProjectSetting.where(pages_unique_domain: base).exists?

  errors.add(:path, s_('Project|already in use'))
end

#personal?Boolean

Returns:



2346
2347
2348
# File 'app/models/project.rb', line 2346

def personal?
  !group
end

#personal_namespace_holder?(user) ⇒ Boolean

Returns:



1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
# File 'app/models/project.rb', line 1439

def personal_namespace_holder?(user)
  return false unless personal?
  return false unless user

  # We do not want to use a check like `project.team.owner?(user)`
  # here because that would depend upon the state of the `project_authorizations` cache,
  # and also perform the check across multiple `owners` of the project, but our intention
  # is to check if the user is the "holder" of the personal namespace, so need to make this
  # check against only a single user (ie, namespace.owner).
  namespace.owner == user
end

#placeholder_reference_storeObject



3748
3749
3750
3751
3752
3753
3754
3755
# File 'app/models/project.rb', line 3748

def placeholder_reference_store
  return unless import_state

  ::Import::PlaceholderReferences::Store.new(
    import_source: import_type,
    import_uid: import_state.id
  )
end

#predefined_ci_server_variablesObject

rubocop: enable Metrics/AbcSize



2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
# File 'app/models/project.rb', line 2912

def predefined_ci_server_variables
  Gitlab::Ci::Variables::Collection.new
    .append(key: 'CI', value: 'true')
    .append(key: 'GITLAB_CI', value: 'true')
    .append(key: 'CI_SERVER_FQDN', value: Gitlab.config.gitlab.server_fqdn)
    .append(key: 'CI_SERVER_URL', value: Gitlab.config.gitlab.url)
    .append(key: 'CI_SERVER_HOST', value: Gitlab.config.gitlab.host)
    .append(key: 'CI_SERVER_PORT', value: Gitlab.config.gitlab.port.to_s)
    .append(key: 'CI_SERVER_PROTOCOL', value: Gitlab.config.gitlab.protocol)
    .append(key: 'CI_SERVER_SHELL_SSH_HOST', value: Gitlab.config.gitlab_shell.ssh_host.to_s)
    .append(key: 'CI_SERVER_SHELL_SSH_PORT', value: Gitlab.config.gitlab_shell.ssh_port.to_s)
    .append(key: 'CI_SERVER_NAME', value: 'GitLab')
    .append(key: 'CI_SERVER_VERSION', value: Gitlab::VERSION)
    .append(key: 'CI_SERVER_VERSION_MAJOR', value: Gitlab.version_info.major.to_s)
    .append(key: 'CI_SERVER_VERSION_MINOR', value: Gitlab.version_info.minor.to_s)
    .append(key: 'CI_SERVER_VERSION_PATCH', value: Gitlab.version_info.patch.to_s)
    .append(key: 'CI_SERVER_REVISION', value: Gitlab.revision)
end

#predefined_project_variablesObject

rubocop: disable Metrics/AbcSize – TODO: Method size will be reduced in follow-up MR, see gitlab.com/gitlab-org/gitlab/-/merge_requests/199182#note_2655958320



2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
# File 'app/models/project.rb', line 2886

def predefined_project_variables
  strong_memoize(:predefined_project_variables) do
    Gitlab::Ci::Variables::Collection.new
      .append(key: 'GITLAB_FEATURES', value: licensed_features.join(','))
      .append(key: 'CI_PROJECT_ID', value: id.to_s)
      .append(key: 'CI_PROJECT_NAME', value: path)
      .append(key: 'CI_PROJECT_TITLE', value: title)
      .append(key: 'CI_PROJECT_DESCRIPTION', value: description)
      .append(key: 'CI_PROJECT_TOPICS', value: topic_list.first(20).join(',').downcase)
      .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_NAMESPACE_SLUG', value: Gitlab::Utils.slugify(namespace.full_path))
      .append(key: 'CI_PROJECT_NAMESPACE_ID', value: namespace.id.to_s)
      .append(key: 'CI_PROJECT_ROOT_NAMESPACE', value: namespace.root_ancestor.path)
      .append(key: 'CI_PROJECT_URL', value: web_url)
      .append(key: 'CI_PROJECT_VISIBILITY', value: Gitlab::VisibilityLevel.string_level(visibility_level))
      .append(key: 'CI_PROJECT_REPOSITORY_LANGUAGES', value: repository_languages.map(&:name).join(',').downcase)
      .append(key: 'CI_PROJECT_CLASSIFICATION_LABEL', value: external_authorization_classification_label)
      .append(key: 'CI_DEFAULT_BRANCH', value: default_branch)
      .append(key: 'CI_DEFAULT_BRANCH_SLUG', value: Gitlab::Utils.slugify(default_branch.to_s))
      .append(key: 'CI_CONFIG_PATH', value: ci_config_path_or_default)
  end
end

#predefined_variablesObject



2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
# File 'app/models/project.rb', line 2871

def predefined_variables
  strong_memoize(:predefined_variables) do
    Gitlab::Ci::Variables::Collection.new
      .concat(predefined_ci_server_variables)
      .concat(predefined_project_variables)
      .concat(pages_variables)
      .concat(container_registry_variables)
      .concat(dependency_proxy_variables)
      .concat(auto_devops_variables)
      .concat(api_variables)
      .concat(ci_template_variables)
  end
end

#preload_protected_branchesObject



1536
1537
1538
1539
1540
1541
# File 'app/models/project.rb', line 1536

def preload_protected_branches
  ActiveRecord::Associations::Preloader.new(
    records: [all_protected_branches, protected_branches].flatten,
    associations: [:push_access_levels, :merge_access_levels]
  ).call
end

#private_pages?Boolean

Returns:



2565
2566
2567
2568
2569
2570
# File 'app/models/project.rb', line 2565

def private_pages?
  return false unless Gitlab.config.pages.access_control

  pages_access_control_forced_by_ancestor? ||
    !!project_feature&.private_pages?
end

#project_idObject



2098
2099
2100
# File 'app/models/project.rb', line 2098

def project_id
  self.id
end

#project_settingObject



1458
1459
1460
# File 'app/models/project.rb', line 1458

def project_setting
  super.presence || build_project_setting
end

#protected_for?(ref) ⇒ Boolean

Returns:

Raises:



2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
# File 'app/models/project.rb', line 2993

def protected_for?(ref)
  raise Repository::AmbiguousRefError if repository.ambiguous_ref?(ref)

  resolved_ref = repository.expand_ref(ref) || ref
  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

  if Gitlab::Git.branch_ref?(resolved_ref)
    ProtectedBranch.protected?(self, ref_name)
  elsif Gitlab::Git.tag_ref?(resolved_ref)
    ProtectedTag.protected?(self, ref_name)
  end
end

#public_pages?Boolean

Returns:



2561
2562
2563
# File 'app/models/project.rb', line 2561

def public_pages?
  !private_pages?
end

#public_path_for_source_path(path, commit_sha) ⇒ Object



3044
3045
3046
3047
3048
3049
# File 'app/models/project.rb', line 3044

def public_path_for_source_path(path, commit_sha)
  map = route_map_for(commit_sha)
  return unless map

  map.public_path_for_source_path(path)
end

#readme_urlObject



2068
2069
2070
2071
2072
2073
# File 'app/models/project.rb', line 2068

def readme_url
  readme_path = repository.readme_path
  if readme_path
    Gitlab::Routing.url_helpers.project_blob_url(self, File.join(default_branch, readme_path))
  end
end

#reconcile_shared_runners_setting!Object



2026
2027
2028
2029
2030
# File 'app/models/project.rb', line 2026

def reconcile_shared_runners_setting!
  if shared_runners_setting_conflicting_with_group?
    self.shared_runners_enabled = false
  end
end

#refresh_lfs_file_locks_changed_epochObject



3744
3745
3746
# File 'app/models/project.rb', line 3744

def refresh_lfs_file_locks_changed_epoch
  refresh_epoch_cache(lfs_file_locks_changed_epoch_cache_key)
end

#refreshing_build_artifacts_size?Boolean

Returns:



3639
3640
3641
# File 'app/models/project.rb', line 3639

def refreshing_build_artifacts_size?
  build_artifacts_size_refresh&.started?
end

#regeneration_in_progress?(user) ⇒ Boolean

Returns:



2820
2821
2822
# File 'app/models/project.rb', line 2820

def regeneration_in_progress?(user)
  (export_enqueued?(user) || export_in_progress?(user)) && export_file_exists?(user)
end


3415
3416
3417
3418
3419
3420
3421
# File 'app/models/project.rb', line 3415

def related_group_ids
  ids = invited_group_ids

  ids += group.self_and_ancestors_ids if group

  ids
end

#remote_mirror_available?Boolean

Returns:



1943
1944
1945
1946
# File 'app/models/project.rb', line 1943

def remote_mirror_available?
  remote_mirror_available_overridden ||
    ::Gitlab::CurrentSettings.mirror_available
end

#remove_export_for_user(user) ⇒ Object



2833
2834
2835
2836
2837
2838
2839
# File 'app/models/project.rb', line 2833

def remove_export_for_user(user)
  import_export_upload = import_export_upload_by_user(user)
  return unless import_export_upload&.export_file_exists?

  import_export_upload.remove_export_file!
  import_export_upload.save unless import_export_upload.destroyed?
end

#remove_exportsObject



2824
2825
2826
2827
2828
2829
2830
2831
# File 'app/models/project.rb', line 2824

def remove_exports
  import_export_uploads.each do |import_export_upload|
    next unless import_export_upload.export_file_exists?

    import_export_upload.remove_export_file!
    import_export_upload.save unless import_export_upload.destroyed?
  end
end

#remove_import_dataObject

This method is overridden in EE::Project model



1785
1786
1787
# File 'app/models/project.rb', line 1785

def remove_import_data
  import_data&.destroy
end

#remove_private_deploy_keysObject



2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
# File 'app/models/project.rb', line 2691

def remove_private_deploy_keys
  exclude_keys_linked_to_other_projects = <<-SQL
    NOT EXISTS (
      SELECT 1
      FROM deploy_keys_projects dkp2
      WHERE dkp2.deploy_key_id = deploy_keys_projects.deploy_key_id
      AND dkp2.project_id != deploy_keys_projects.project_id
    )
  SQL

  deploy_keys.where(public: false)
             .where(exclude_keys_linked_to_other_projects)
             .delete_all
end

#renamed?Boolean

Returns:



3122
3123
3124
# File 'app/models/project.rb', line 3122

def renamed?
  persisted? && path_changed?
end

#repositoryRepository

Returns:



1619
1620
1621
# File 'app/models/project.rb', line 1619

def repository
  @repository ||= Gitlab::GlRepository::PROJECT.repository_for(self)
end

#repository_object_formatObject



3704
3705
3706
# File 'app/models/project.rb', line 3704

def repository_object_format
  project_repository&.object_format
end

#reset_cache_and_import_attrsObject



1775
1776
1777
1778
1779
1780
1781
1782
# File 'app/models/project.rb', line 1775

def reset_cache_and_import_attrs
  run_after_commit do
    ProjectCacheWorker.perform_async(self.id)
  end

  import_state.update(last_error: nil)
  remove_import_data
end

#reset_counters_and_iidsObject



2729
2730
2731
2732
2733
2734
2735
2736
# File 'app/models/project.rb', line 2729

def reset_counters_and_iids
  # The import assigns iid values on its own, e.g. by re-using GitHub ids.
  # Flush existing InternalId records for this project for consistency reasons.
  # Those records are going to be recreated with the next normal creation
  # of a model instance (e.g. an Issue).
  InternalId.flush_records!(project: self)
  update_project_counter_caches
end

#resource_parentObject



1427
1428
1429
# File 'app/models/project.rb', line 1427

def resource_parent
  self
end

#restrict_user_defined_variables?Boolean

Returns:



3485
3486
3487
3488
3489
# File 'app/models/project.rb', line 3485

def restrict_user_defined_variables?
  return false unless ci_cd_settings

  ci_cd_settings.restrict_user_defined_variables?
end

#root_groupObject



3398
3399
3400
3401
3402
# File 'app/models/project.rb', line 3398

def root_group
  return if personal?

  root_namespace
end

#root_namespaceObject



3390
3391
3392
3393
3394
3395
3396
# File 'app/models/project.rb', line 3390

def root_namespace
  if namespace.has_parent?
    namespace.root_ancestor
  else
    namespace
  end
end

#route_map_for(commit_sha) ⇒ Object



3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
# File 'app/models/project.rb', line 3030

def route_map_for(commit_sha)
  @route_maps_by_commit ||= Hash.new do |h, sha|
    h[sha] = begin
      data = repository.route_map_for(sha)

      Gitlab::RouteMap.new(data) if data
    rescue Gitlab::RouteMap::FormatError
      nil
    end
  end

  @route_maps_by_commit[commit_sha]
end

#runners_tokenObject



2673
2674
2675
2676
2677
# File 'app/models/project.rb', line 2673

def runners_token
  return unless namespace.allow_runner_registration_token?

  ensure_runners_token!
end

#safe_import_url(masked: true) ⇒ String

Returns sanitized import URL.

Examples:

project.safe_import_url #=> “https://****:****@example.com”

project.safe_import_url(masked: false) # => “example.com

Parameters:

  • Toggles how URL will be sanitized. Defaults to true. when true the userinfo credentials will be masked, when false the userinfo credentials will be stripped.

Returns:

  • Sanitized import URL.



1809
1810
1811
1812
# File 'app/models/project.rb', line 1809

def safe_import_url(masked: true)
  url = Gitlab::UrlSanitizer.new(unsafe_import_url)
  masked ? url.masked_url : url.sanitized_url
end

#saved?Boolean

Returns:



1719
1720
1721
# File 'app/models/project.rb', line 1719

def saved?
  id && persisted?
end

#security_training_available?Boolean

Returns:



3647
3648
3649
# File 'app/models/project.rb', line 3647

def security_training_available?
  licensed_feature_available?(:security_training)
end

#self_and_ancestors_idsObject



1555
1556
1557
1558
1559
# File 'app/models/project.rb', line 1555

def self_and_ancestors_ids
  strong_memoize(:self_and_ancestors_ids) do
    ancestors.pluck(:id) + [id]
  end
end

#self_deletion_in_progress?Boolean

Returns:



3582
3583
3584
# File 'app/models/project.rb', line 3582

def self_deletion_in_progress?
  pending_delete?
end

#self_deletion_in_progress_or_hidden?Boolean

Returns:



3586
3587
3588
# File 'app/models/project.rb', line 3586

def self_deletion_in_progress_or_hidden?
  self_deletion_in_progress? || hidden?
end

#self_or_ancestors_archived?Boolean

Returns:



3114
3115
3116
# File 'app/models/project.rb', line 3114

def self_or_ancestors_archived?
  self_archived? || namespace.self_or_ancestors_archived?
end

#self_or_root_group_idsObject

for projects that are part of user namespace, return project.



3405
3406
3407
3408
3409
3410
3411
3412
3413
# File 'app/models/project.rb', line 3405

def self_or_root_group_ids
  if group
    root_group = root_namespace
  else
    project = self
  end

  [project&.id, root_group&.id]
end

#send_move_instructions(old_path_with_namespace) ⇒ Object

rubocop: disable CodeReuse/ServiceClass



2219
2220
2221
2222
2223
2224
2225
# File 'app/models/project.rb', line 2219

def send_move_instructions(old_path_with_namespace)
  # New project path needs to be committed to the DB or notification will
  # retrieve stale information
  run_after_commit do
    NotificationService.new.project_was_moved(self, old_path_with_namespace)
  end
end

#set_project_feature_defaultsObject

Remove along with ProjectFeaturesCompatibility module



1418
1419
1420
1421
1422
1423
1424
1425
# File 'app/models/project.rb', line 1418

def set_project_feature_defaults
  self.class.project_features_defaults.each do |attr, value|
    # If the deprecated _enabled or the accepted _access_level attribute is specified, we don't need to set the default
    next unless @init_attributes[:"#{attr}_enabled"].nil? && @init_attributes[:"#{attr}_access_level"].nil?

    public_send("#{attr}_enabled=", value) # rubocop:disable GitlabSecurity/PublicSend
  end
end

#share_with_group_enabled?Boolean

Returns:



2504
2505
2506
# File 'app/models/project.rb', line 2504

def share_with_group_enabled?
  !parent.share_with_group_lock?
end

#shared_runnersObject



2595
2596
2597
# File 'app/models/project.rb', line 2595

def shared_runners
  @shared_runners ||= shared_runners_enabled? ? Ci::Runner.instance_type : Ci::Runner.none
end

#shared_runners_available?Boolean

Returns:



2591
2592
2593
# File 'app/models/project.rb', line 2591

def shared_runners_available?
  shared_runners_enabled?
end

#shared_runners_setting_conflicting_with_group?Boolean

Returns:



2022
2023
2024
# File 'app/models/project.rb', line 2022

def shared_runners_setting_conflicting_with_group?
  shared_runners_enabled && group&.shared_runners_setting == Namespace::SR_DISABLED_AND_UNOVERRIDABLE
end

#should_validate_visibility_level?Boolean

Returns:



1966
1967
1968
# File 'app/models/project.rb', line 1966

def should_validate_visibility_level?
  new_record? || changes.has_key?(:visibility_level)
end

#show_default_award_emojis?Boolean

Returns:



1462
1463
1464
# File 'app/models/project.rb', line 1462

def show_default_award_emojis?
  !!project_setting&.show_default_award_emojis?
end

#snippets_enabled?Boolean

Returns:



2557
2558
2559
# File 'app/models/project.rb', line 2557

def snippets_enabled?
  !!project_feature&.snippets_enabled?
end

#snippets_visible?(user = nil) ⇒ Boolean

Returns:



3250
3251
3252
# File 'app/models/project.rb', line 3250

def snippets_visible?(user = nil)
  Ability.allowed?(user, :read_snippet, self)
end

#squash_commit_template_or_defaultObject



3567
3568
3569
# File 'app/models/project.rb', line 3567

def squash_commit_template_or_default
  squash_commit_template.presence || DEFAULT_SQUASH_COMMIT_TEMPLATE
end

#squash_commit_template_or_default=(value) ⇒ Object



3571
3572
3573
3574
3575
3576
3577
3578
# File 'app/models/project.rb', line 3571

def squash_commit_template_or_default=(value)
  project_setting.squash_commit_template =
    if value.blank? || value.delete("\r") == DEFAULT_SQUASH_COMMIT_TEMPLATE
      nil
    else
      value
    end
end

#storageObject



3237
3238
3239
3240
3241
3242
3243
3244
# File 'app/models/project.rb', line 3237

def storage
  @storage ||=
    if hashed_storage?(:repository)
      Storage::Hashed.new(self)
    else
      Storage::LegacyProject.new(self)
    end
end

#storage_upgradable?Boolean

Returns:



3246
3247
3248
# File 'app/models/project.rb', line 3246

def storage_upgradable?
  storage_version != LATEST_STORAGE_VERSION
end

#storage_version=(value) ⇒ Object



3173
3174
3175
3176
3177
# File 'app/models/project.rb', line 3173

def storage_version=(value)
  super

  @storage = nil if storage_version_changed?
end

#suggested_reviewers_available?Boolean

overridden in EE

Returns:



3675
3676
3677
# File 'app/models/project.rb', line 3675

def suggested_reviewers_available?
  false
end

#supports_lock_on_merge?Boolean

Returns:



3691
3692
3693
# File 'app/models/project.rb', line 3691

def supports_lock_on_merge?
  group&.supports_lock_on_merge? || ::Feature.enabled?(:enforce_locked_labels_on_merge, self, type: :ops)
end

#supports_saved_replies?Boolean

Overridden in EE

Returns:



3731
3732
3733
# File 'app/models/project.rb', line 3731

def supports_saved_replies?
  false
end

#swap_pool_repository!Object

After repository is moved from shard to shard, disconnect it from the previous object pool and connect to the new pool



3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
# File 'app/models/project.rb', line 3282

def swap_pool_repository!
  return unless repository_exists?

  old_pool_repository = pool_repository
  return if old_pool_repository.blank?
  return if pool_repository_shard_matches_repository?(old_pool_repository)

  new_pool_repository = PoolRepository.by_disk_path_and_shard_name(old_pool_repository.disk_path, repository_storage).take!
  update!(pool_repository: new_pool_repository)

  old_pool_repository.unlink_repository(repository, disconnect: !pending_delete?)
end

#teamObject



1614
1615
1616
# File 'app/models/project.rb', line 1614

def team
  @team ||= ProjectTeam.new(self)
end

#template_source?Boolean

Returns:



3335
3336
3337
# File 'app/models/project.rb', line 3335

def template_source?
  false
end

#to_human_reference(from = nil) ⇒ Object



2060
2061
2062
2063
2064
2065
2066
# File 'app/models/project.rb', line 2060

def to_human_reference(from = nil)
  if cross_namespace_reference?(from)
    name_with_namespace
  elsif cross_project_reference?(from)
    name
  end
end

#to_paramObject



2032
2033
2034
2035
2036
2037
2038
# File 'app/models/project.rb', line 2032

def to_param
  if persisted? && errors.include?(:path)
    path_was
  else
    path
  end
end

#to_reference(from = nil, full: false) ⇒ Object

Produce a valid reference (see Referable#to_reference)

NB: For projects, all references are ‘full’ - i.e. they all include the full_path, rather than just the project name. For this reason, we ignore the value of full: passed to this method, which is part of the Referable interface.



2046
2047
2048
2049
# File 'app/models/project.rb', line 2046

def to_reference(from = nil, full: false)
  base = to_reference_base(from, full: true)
  "#{base}#{self.class.reference_postfix}"
end

#to_reference_base(from = nil, full: false, absolute_path: false) ⇒ Object

from argument can be a Namespace or Project.



2052
2053
2054
2055
2056
2057
2058
# File 'app/models/project.rb', line 2052

def to_reference_base(from = nil, full: false, absolute_path: false)
  if full || cross_namespace_reference?(from)
    absolute_path ? "/#{full_path}" : full_path
  elsif cross_project_reference?(from)
    path
  end
end

#toggle_ci_cd_settings!(settings_attribute) ⇒ Object



3218
3219
3220
# File 'app/models/project.rb', line 3218

def toggle_ci_cd_settings!(settings_attribute)
  ci_cd_settings.toggle!(settings_attribute)
end

#track_project_repositoryObject

When the project has an existing project_repository record, we want to update it. Otherwise, if a corresponding Git repository exists, we create a new record. This method might be called when a project_repository record already exists, during project transfer to another namespace, in Projects::TransferService or when repository storage is being updated in Projects::UpdateRepositoryStorageService



2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
# File 'app/models/project.rb', line 2383

def track_project_repository
  return unless project_repository.presence || repository.raw_repository.exists?

  (project_repository || build_project_repository).tap do |proj_repo|
    attributes = { shard_name: repository_storage, disk_path: disk_path }

    object_format = repository.object_format
    attributes[:object_format] = object_format if object_format.present?

    proj_repo.update!(**attributes)
  end

  cleanup
end

#triggered_hooks(hooks_scope, data) ⇒ Object

rubocop: enable CodeReuse/ServiceClass



2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
# File 'app/models/project.rb', line 2267

def triggered_hooks(hooks_scope, data)
  triggered = ::Projects::TriggeredHooks.new(hooks_scope, data)

  # By default the webhook resource_access_token_hooks will execute for
  # seven_days interval but we have a setting to allow webhook execution
  # for thirty_days and sixty_days interval too.
  if hooks_scope == :resource_access_token_hooks &&
      data[:interval] != :seven_days &&
      !self.extended_prat_expiry_webhooks_execute?

    triggered
  else
    triggered.add_hooks(hooks)
  end
end

#unsafe_import_urlString

WARNING - This method returns sensitive userinfo credentials of the import URL. Use #safe_import_url instead unless it is necessary to include sensitive credentials.

Builds an import URL including userinfo credentials from the import_url attribute and the encrypted ‘ProjectImportData#credentials`.

Examples:

project.unsafe_import_url #=> “user:[email protected]

Returns:

  • Unsanitized import URL.

See Also:



1839
1840
1841
1842
1843
1844
1845
1846
1847
# File 'app/models/project.rb', line 1839

def unsafe_import_url
  if import_data && import_url.present?
    Gitlab::UrlSanitizer.new(import_url, credentials: import_data.credentials).full_url
  else
    import_url
  end
rescue StandardError
  import_url
end

#update_project_counter_cachesObject



2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
# File 'app/models/project.rb', line 2738

def update_project_counter_caches
  classes = [
    Projects::OpenIssuesCountService,
    Projects::OpenMergeRequestsCountService
  ]

  classes.each do |klass|
    klass.new(self).refresh_cache
  end
end

#update_remote_mirrorsObject



1925
1926
1927
1928
1929
# File 'app/models/project.rb', line 1925

def update_remote_mirrors
  return unless remote_mirror_available?

  remote_mirrors.enabled.each(&:sync)
end

#updating_remote_mirror?Boolean

Returns:



1921
1922
1923
# File 'app/models/project.rb', line 1921

def updating_remote_mirror?
  remote_mirrors.enabled.started.exists?
end

#uploads_sharding_keyObject



3765
3766
3767
# File 'app/models/project.rb', line 3765

def uploads_sharding_key
  { project_id: id }
end

#use_work_item_url?Boolean

Returns:



3620
3621
3622
3623
3624
3625
3626
# File 'app/models/project.rb', line 3620

def use_work_item_url?
  return false if Feature.enabled?(:work_item_legacy_url, self, type: :gitlab_com_derisk)
  return work_items_consolidated_list_enabled? if group.blank?

  work_items_consolidated_list_enabled? &&
    group.use_work_item_url?
end

#valid_lfs_oids(oids_to_check) ⇒ Object



2326
2327
2328
# File 'app/models/project.rb', line 2326

def valid_lfs_oids(oids_to_check)
  lfs_objects.where(oid: oids_to_check).pluck(:oid)
end

#valid_runners_token?(token) ⇒ Boolean

Returns:



2625
2626
2627
# File 'app/models/project.rb', line 2625

def valid_runners_token?(token)
  self.runners_token && ActiveSupport::SecurityUtils.secure_compare(token, self.runners_token)
end

#validate_pages_https_onlyObject



1999
2000
2001
2002
2003
2004
2005
# File 'app/models/project.rb', line 1999

def validate_pages_https_only
  return unless pages_https_only?

  unless pages_domains.all?(&:https?)
    errors.add(:pages_https_only, _("cannot be enabled unless all domains have TLS certificates"))
  end
end

#visibility_level_allowed?(level = self.visibility_level) ⇒ Boolean

Returns:



2669
2670
2671
# File 'app/models/project.rb', line 2669

def visibility_level_allowed?(level = self.visibility_level)
  visibility_level_allowed_as_fork?(level) && visibility_level_allowed_by_namespace?(level)
end

#visibility_level_allowed_as_forkObject



1980
1981
1982
1983
1984
1985
# File 'app/models/project.rb', line 1980

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: level_name })
end

#visibility_level_allowed_as_fork?(level = self.visibility_level) ⇒ Boolean

rubocop: enable CodeReuse/ServiceClass

Returns:



2653
2654
2655
2656
2657
2658
2659
2660
# File 'app/models/project.rb', line 2653

def visibility_level_allowed_as_fork?(level = self.visibility_level)
  return true unless forked?

  original_project = fork_source
  return true unless original_project

  level <= original_project.visibility_level
end

#visibility_level_allowed_by_namespaceObject



1970
1971
1972
1973
1974
1975
1976
1977
1978
# File 'app/models/project.rb', line 1970

def visibility_level_allowed_by_namespace
  return if visibility_level_allowed_by_namespace?

  level_name = Gitlab::VisibilityLevel.level_name(self.visibility_level).downcase
  # Use group visibility level directly when available to avoid stale association issues
  namespace_visibility = group ? group.visibility_level : namespace.visibility_level
  namespace_level_name = Gitlab::VisibilityLevel.level_name(namespace_visibility).downcase
  self.errors.add(:visibility_level, _("%{level_name} is not allowed in a %{namespace_level_name} namespace.") % { level_name: level_name, namespace_level_name: namespace_level_name })
end

#visibility_level_allowed_by_namespace?(level = self.visibility_level) ⇒ Boolean

Returns:



2662
2663
2664
2665
2666
2667
# File 'app/models/project.rb', line 2662

def visibility_level_allowed_by_namespace?(level = self.visibility_level)
  return true unless group || namespace
  return level <= group.visibility_level if group

  level <= namespace.visibility_level
end

#visibility_level_fieldObject



2470
2471
2472
# File 'app/models/project.rb', line 2470

def visibility_level_field
  :visibility_level
end


3530
3531
3532
3533
3534
3535
3536
3537
3538
# File 'app/models/project.rb', line 3530

def visible_group_links(for_user:)
  user = for_user
  links = project_group_links_with_preload
  user.max_member_access_for_group_ids(links.map(&:group_id)) if user && links.any?

  DeclarativePolicy.user_scope do
    links.select { Ability.allowed?(user, :read_group, _1.group) }
  end
end

#warn_about_potentially_unwanted_characters?Boolean

Returns:



1470
1471
1472
# File 'app/models/project.rb', line 1470

def warn_about_potentially_unwanted_characters?
  !!project_setting&.warn_about_potentially_unwanted_characters?
end

#wiki_enabled?Boolean

Returns:



2533
2534
2535
# File 'app/models/project.rb', line 2533

def wiki_enabled?
  !!project_feature&.wiki_enabled?
end

#work_item_tasks_on_boards_feature_flag_enabled?Boolean

Returns:



3590
3591
3592
# File 'app/models/project.rb', line 3590

def work_item_tasks_on_boards_feature_flag_enabled?
  group&.work_item_tasks_on_boards_feature_flag_enabled? || Feature.enabled?(:work_item_tasks_on_boards, type: :wip)
end

#work_items_consolidated_list_enabled?(user = nil) ⇒ Boolean

Returns:



3612
3613
3614
3615
3616
3617
3618
# File 'app/models/project.rb', line 3612

def work_items_consolidated_list_enabled?(user = nil)
  # work_item_planning_view is the feature flag used to determine whether the consolidated list is enabled or not
  # The global check is required for projects which do not have an associated group (i.e. from a user namespace)
  return true if group&.work_items_consolidated_list_enabled?(user) || Feature.enabled?(:work_item_planning_view, type: :wip)

  user.present? && Feature.enabled?(:work_items_consolidated_list_user, user)
end

#work_items_saved_views_enabled?(user = nil) ⇒ Boolean

Returns:



3606
3607
3608
3609
3610
# File 'app/models/project.rb', line 3606

def work_items_saved_views_enabled?(user = nil)
  return true if group&.work_items_saved_views_enabled?(user) || Feature.enabled?(:work_items_saved_views, type: :wip)

  user.present? && Feature.enabled?(:work_items_saved_views_user, user)
end