Class: Project

Constant Summary collapse

BoardLimitExceeded =
Class.new(StandardError)
ExportLimitExceeded =
Class.new(StandardError)
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
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

Constants included from BlocksUnsafeSerialization

BlocksUnsafeSerialization::UnsafeSerializationError

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::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::PRIVATE, Gitlab::VisibilityLevel::PUBLIC

Constants inherited from ApplicationRecord

ApplicationRecord::MAX_PLUCK

Constants included from ResetOnUnionError

ResetOnUnionError::MAX_RESET_PERIOD

Instance Attribute Summary collapse

Attributes included from Gitlab::Cache::RequestCache

#request_cache_key_block

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 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

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

#wiki_page_path, #wiki_path

Methods included from Routing::SnippetsHelper

#gitlab_dashboard_snippets_path, #gitlab_raw_snippet_blob_path, #gitlab_raw_snippet_blob_url, #gitlab_raw_snippet_path, #gitlab_raw_snippet_url, #gitlab_snippet_note_path, #gitlab_snippet_note_url, #gitlab_snippet_notes_path, #gitlab_snippet_notes_url, #gitlab_snippet_path, #gitlab_snippet_url, #gitlab_toggle_award_emoji_snippet_note_path, #gitlab_toggle_award_emoji_snippet_note_url, #gitlab_toggle_award_emoji_snippet_path, #gitlab_toggle_award_emoji_snippet_url, #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, #issue_url, #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?, #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, #http_enabled?, #import_sources_checkboxes, #instance_clusters_enabled?, #integration_expanded?, #key_restriction_options_for_select, #kroki_available_formats, #oauth_providers_checkboxes, #omnibus_protected_paths_throttle?, #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

Methods included from ProjectsHelper

#able_to_see_forks_count?, #able_to_see_issues?, #able_to_see_merge_requests?, #any_projects?, #author_content_tag, #autodeploy_flash_notice, #badge_count, #branch_rules_path, #can_admin_associated_clusters?, #can_admin_project_member?, #can_change_visibility_level?, #can_disable_emails?, #can_push_code?, #can_view_branch_rules?, #clusters_deprecation_alert_message, #delete_confirm_phrase, #directory?, #error_tracking_setting_project_json, #explore_projects_tab?, #external_classification_label_help_message, #fork_button_data_attributes, #grafana_integration_enabled?, #grafana_integration_masked_token, #grafana_integration_url, #http_clone_url_to_repo, #import_from_bitbucket_message, #import_from_gitlab_message, #inactive_project_deletion_date, #last_pipeline_from_status_cache, #last_push_event, #link_to_autodeploy_doc, #link_to_member, #link_to_member_avatar, #link_to_project, #load_pipeline_status, #localized_project_human_access, #no_password_message, #project_can_be_shared?, #project_classes, #project_coverage_chart_data_attributes, #project_incident_management_setting, #project_license_name, #project_list_cache_key, #project_permissions_panel_data, #project_title, #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_auto_devops_implicitly_enabled_banner?, #show_clusters_alert?, #show_count?, #show_inactive_project_deletion_banner?, #show_mobile_devops_project_promo?, #show_no_password_message?, #show_no_ssh_key_message?, #show_projects?, #show_terraform_banner?, #show_xcode_link?, #ssh_clone_url_to_repo, #transfer_project_message, #visibility_level_content, #visible_fork_source, #vue_fork_divergence_data, #xcode_uri_to_repo

Methods included from Gitlab::Allowable

#can?

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, optimize_routable_enabled?, #owned_by?, #route_loaded?

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, #web_hook_failure_redis_key

Methods included from HasWiki

#create_wiki, #wiki, #wiki_repository_exists?

Methods included from HasRepository

#commit, #commit_by, #commits_by, #default_branch, #default_branch_from_group_preferences, #default_branch_from_preferences, #empty_repo?, #full_path, #http_url_to_repo, #lfs_http_url_to_repo, #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=, #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, #local_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!, #updated_cached_html_for

Methods included from Avatarable

#avatar_path, #avatar_type, #uncached_avatar_path, #upload_paths

Methods included from AccessRequestable

#request_access

Methods included from Gitlab::VisibilityLevel

allowed_for?, allowed_level?, allowed_levels, 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, declarative_enum, default_select_columns, id_in, id_not_in, iid_in, pluck_primary_key, 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 SensitiveSerializableHash

#serializable_hash

Constructor Details

#initialize(attributes = nil) ⇒ Project

Returns a new instance of Project.



1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
# File 'app/models/project.rb', line 1080

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.



160
161
162
# File 'app/models/project.rb', line 160

def old_path_with_namespace
  @old_path_with_namespace
end

#pipeline_statusObject

Lazy loading of the ‘pipeline_status` attribute



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

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.



163
164
165
# File 'app/models/project.rb', line 163

def skip_disk_validation
  @skip_disk_validation
end

#template_nameObject

Returns the value of attribute template_name.



161
162
163
# File 'app/models/project.rb', line 161

def template_name
  @template_name
end

#topic_listObject



3132
3133
3134
# File 'app/models/project.rb', line 3132

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

Class Method Details

.by_pages_enabled_unique_domain(domain) ⇒ Object



1070
1071
1072
1073
1074
1075
1076
1077
# File 'app/models/project.rb', line 1070

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



1018
1019
1020
1021
1022
# File 'app/models/project.rb', line 1018

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



870
871
872
873
874
875
876
877
878
# File 'app/models/project.rb', line 870

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

.eager_load_namespace_and_ownerObject



842
843
844
# File 'app/models/project.rb', line 842

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.



897
898
899
900
901
902
903
# File 'app/models/project.rb', line 897

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

.find_by_url(url) ⇒ Object



1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
# File 'app/models/project.rb', line 1039

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_idsObject



1024
1025
1026
# File 'app/models/project.rb', line 1024

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



1032
1033
1034
1035
1036
1037
# File 'app/models/project.rb', line 1032

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

.inactiveObject



910
911
912
913
914
915
916
917
918
# File 'app/models/project.rb', line 910

def self.inactive
  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

.integration_association_name(name) ⇒ Object



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

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.



1005
1006
1007
1008
1009
1010
1011
# File 'app/models/project.rb', line 1005

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

.project_features_defaultsObject



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

def project_features_defaults
  PROJECT_FEATURES_DEFAULTS
end

.projects_user_can(projects, user, action) ⇒ Object



888
889
890
891
892
893
894
# File 'app/models/project.rb', line 888

def self.projects_user_can(projects, user, action)
  projects = where(id: projects)

  DeclarativePolicy.user_scope do
    projects.select { |project| Ability.allowed?(user, action, project) }
  end
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.



848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
# File 'app/models/project.rb', line 848

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),
      Gitlab::VisibilityLevel.levels_for_user(user)
    )
  end
end

.reference_patternObject



986
987
988
989
990
991
992
# File 'app/models/project.rb', line 986

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

.reference_postfixObject



994
995
996
# File 'app/models/project.rb', line 994

def reference_postfix
  '>'
end

.reference_postfix_escapedObject



998
999
1000
# File 'app/models/project.rb', line 998

def reference_postfix_escaped
  '&gt;'
end

.search(query, include_namespace: 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.



949
950
951
952
953
954
955
956
957
# File 'app/models/project.rb', line 949

def search(query, include_namespace: 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
    fuzzy_search(query, [:path, :name, :description], use_minimum_char_limit: use_minimum_char_limit)
  end
end

.search_by_title(query) ⇒ Object



959
960
961
# File 'app/models/project.rb', line 959

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

.sort_by_attribute(method) ⇒ Object



967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
# File 'app/models/project.rb', line 967

def sort_by_attribute(method)
  case method.to_s
  when 'storage_size_desc'
    # storage_size is a joined column so we need to
    # pass a string to avoid AR adding the table name
    reorder('project_statistics.storage_size DESC, projects.id DESC')
  when 'latest_activity_desc'
    sorted_by_updated_desc
  when 'latest_activity_asc'
    sorted_by_updated_asc
  when 'stars_desc'
    sorted_by_stars_desc
  when 'stars_asc'
    sorted_by_stars_asc
  else
    order_by(method)
  end
end


1013
1014
1015
1016
# File 'app/models/project.rb', line 1013

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

.visibility_levelsObject



963
964
965
# File 'app/models/project.rb', line 963

def visibility_levels
  Gitlab::VisibilityLevel.options
end

.with_api_entity_associationsObject



820
821
822
# File 'app/models/project.rb', line 820

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

.with_feature_available_for_user(feature, user) ⇒ Object



884
885
886
# File 'app/models/project.rb', line 884

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



828
829
830
831
832
833
834
835
836
837
838
839
840
# File 'app/models/project.rb', line 828

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



824
825
826
# File 'app/models/project.rb', line 824

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

.without_integration(integration) ⇒ Object



1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
# File 'app/models/project.rb', line 1054

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)
    .where(archived: false)
end

.wrap_with_cte(collection) ⇒ Object



905
906
907
908
# File 'app/models/project.rb', line 905

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



2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
# File 'app/models/project.rb', line 2866

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



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

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

#active_webide_pipelines(user:) ⇒ Object



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

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

#activity_pathObject



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

def activity_path
  Gitlab::Routing.url_helpers.activity_project_path(self)
end

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



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

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

  job_id = ProjectExportWorker.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



1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
# File 'app/models/project.rb', line 1399

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



3137
3138
3139
# File 'app/models/project.rb', line 3137

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



2339
2340
2341
# File 'app/models/project.rb', line 2339

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

#after_importObject



2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
# File 'app/models/project.rb', line 2302

def after_import
  repository.expire_content_cache
  repository.remove_prohibited_branches
  wiki.repository.expire_content_cache

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

  enqueue_record_project_target_platforms

  # 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)

  import_state&.finish
  update_project_counter_caches
  after_create_default_branch
  join_pool_repository
  refresh_markdown_cache!
  set_full_path
end

#after_repository_change_headObject



2048
2049
2050
2051
2052
# File 'app/models/project.rb', line 2048

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

  super
end

#all_available_runnersObject



2170
2171
2172
# File 'app/models/project.rb', line 2170

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

#all_clustersObject



1804
1805
1806
1807
1808
1809
# File 'app/models/project.rb', line 1804

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



1174
1175
1176
1177
1178
1179
1180
# File 'app/models/project.rb', line 1174

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

#all_protected_branchesObject



2915
2916
2917
2918
2919
2920
2921
# File 'app/models/project.rb', line 2915

def all_protected_branches
  if allow_protected_branches_for_group?
    @all_protected_branches ||= ProtectedBranch.from_union([protected_branches, group_protected_branches])
  else
    protected_branches
  end
end

#all_runnersObject



2166
2167
2168
# File 'app/models/project.rb', line 2166

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

#allow_protected_branches_for_group?Boolean

Returns:

  • (Boolean)


2923
2924
2925
# File 'app/models/project.rb', line 2923

def allow_protected_branches_for_group?
  Feature.enabled?(:group_protected_branches, group) || Feature.enabled?(:allow_protected_branches_for_group, group)
end

#allowed_to_share_with_group?Boolean

Returns:

  • (Boolean)


2072
2073
2074
# File 'app/models/project.rb', line 2072

def allowed_to_share_with_group?
  !namespace.share_with_group_lock
end

#analytics_enabled?Boolean

Returns:

  • (Boolean)


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

def analytics_enabled?
  !!project_feature&.analytics_enabled?
end

#ancestors(hierarchy_order: nil) ⇒ Object



1222
1223
1224
# File 'app/models/project.rb', line 1222

def ancestors(hierarchy_order: nil)
  group&.self_and_ancestors(hierarchy_order: hierarchy_order) || Group.none
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



1217
1218
1219
1220
# File 'app/models/project.rb', line 1217

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



1226
1227
1228
# File 'app/models/project.rb', line 1226

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

#any_branch_allows_collaboration?(user) ⇒ Boolean

Returns:

  • (Boolean)


2746
2747
2748
# File 'app/models/project.rb', line 2746

def any_branch_allows_collaboration?(user)
  fetch_branch_allows_collaboration(user)
end

#any_lfs_file_locks?Boolean

Returns:

  • (Boolean)


2778
2779
2780
# File 'app/models/project.rb', line 2778

def any_lfs_file_locks?
  lfs_file_locks.any?
end

#any_online_runners?(&block) ⇒ Boolean

Returns:

  • (Boolean)


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

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

#api_variablesObject



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

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

#auto_cancel_pending_pipelines?Boolean

Returns:

  • (Boolean)


2783
2784
2785
# File 'app/models/project.rb', line 2783

def auto_cancel_pending_pipelines?
  auto_cancel_pending_pipelines == 'enabled'
end

#auto_devops_enabled?Boolean

Returns:

  • (Boolean)


1244
1245
1246
1247
1248
1249
1250
# File 'app/models/project.rb', line 1244

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

#auto_devops_variablesObject



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

def auto_devops_variables
  return [] unless auto_devops_enabled?

  (auto_devops || build_auto_devops)&.predefined_variables
end

#autoclose_referenced_issuesObject



1202
1203
1204
1205
1206
# File 'app/models/project.rb', line 1202

def autoclose_referenced_issues
  return true if super.nil?

  super
end

#available_shared_runnersObject



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

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

#avatar_in_gitObject



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

def avatar_in_git
  repository.avatar
end

#avatar_url(**args) ⇒ Object



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

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

#badgesObject



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

def badges
  return project_badges unless group

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

#beautified_import_status_nameObject



1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
# File 'app/models/project.rb', line 1387

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

#botsObject



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

def bots
  users.project_bot
end

#branch_allows_collaboration?(user, branch_name) ⇒ Boolean

Returns:

  • (Boolean)


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

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

#build_commit_note(commit) ⇒ Object



1687
1688
1689
# File 'app/models/project.rb', line 1687

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

#builds_enabled?Boolean

Returns:

  • (Boolean)


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

def builds_enabled?
  !!project_feature&.builds_enabled?
end

#can_create_custom_domains?Boolean

Returns:

  • (Boolean)


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

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_suggest_reviewers?Boolean

overridden in EE

Returns:

  • (Boolean)


3256
3257
3258
# File 'app/models/project.rb', line 3256

def can_suggest_reviewers?
  false
end

#certificate_based_clusters_enabled?Boolean

Returns:

  • (Boolean)


1107
1108
1109
# File 'app/models/project.rb', line 1107

def certificate_based_clusters_enabled?
  !!namespace&.certificate_based_clusters_enabled?
end

#changing_shared_runners_enabled_is_allowedObject



1611
1612
1613
1614
1615
1616
1617
# File 'app/models/project.rb', line 1611

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



1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
# File 'app/models/project.rb', line 1554

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
      _('Personal project creation is not allowed. Please contact your administrator with questions')
    else
      _('Your project limit is %{limit} projects! Please contact your administrator to increase it')
    end

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

#check_repository_path_availabilityObject

Check if repository already exists on disk



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

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:

  • (Boolean)


3090
3091
3092
3093
3094
# File 'app/models/project.rb', line 3090

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



3054
3055
3056
# File 'app/models/project.rb', line 3054

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

#ci_config_path=(value) ⇒ Object



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

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

#ci_config_path_or_defaultObject



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

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

#ci_forward_deployment_enabled?Boolean

Returns:

  • (Boolean)


3078
3079
3080
3081
3082
# File 'app/models/project.rb', line 3078

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:

  • (Boolean)


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

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:

  • (Boolean)


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

def ci_inbound_job_token_scope_enabled?
  return true unless ci_cd_settings

  ci_cd_settings.inbound_job_token_scope_enabled?
end

#ci_integrationObject



1787
1788
1789
# File 'app/models/project.rb', line 1787

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

#ci_integrationsObject

rubocop: enable CodeReuse/ServiceClass



1783
1784
1785
# File 'app/models/project.rb', line 1783

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

#ci_outbound_job_token_scope_enabled?Boolean

Returns:

  • (Boolean)


3096
3097
3098
3099
3100
# File 'app/models/project.rb', line 3096

def ci_outbound_job_token_scope_enabled?
  return false unless ci_cd_settings

  ci_cd_settings.job_token_scope_enabled?
end

#ci_pipelinesObject



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

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

#ci_template_variablesObject



2496
2497
2498
2499
2500
# File 'app/models/project.rb', line 2496

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!



1297
1298
1299
# File 'app/models/project.rb', line 1297

def cleanup
  @repository = nil
end

#closest_setting(name) ⇒ Object



2878
2879
2880
2881
2882
2883
# File 'app/models/project.rb', line 2878

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



1800
1801
1802
# File 'app/models/project.rb', line 1800

def code
  path
end

#commit_notesObject

Used by Import/Export to export commit notes



1442
1443
1444
# File 'app/models/project.rb', line 1442

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

#container_registry_enabled?Boolean Also known as: container_registry_enabled

Returns:

  • (Boolean)


2141
2142
2143
# File 'app/models/project.rb', line 2141

def container_registry_enabled?
  !!project_feature&.container_registry_enabled?
end

#container_registry_urlObject



1303
1304
1305
1306
1307
# File 'app/models/project.rb', line 1303

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

#container_registry_variablesObject



2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
# File 'app/models/project.rb', line 2520

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



1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
# File 'app/models/project.rb', line 1309

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

    ContainerRegistry::GitlabApiClient.deduplicated_size(full_path)
  end
end

#content_editor_on_issues_feature_flag_enabled?Boolean

Returns:

  • (Boolean)


3198
3199
3200
# File 'app/models/project.rb', line 3198

def content_editor_on_issues_feature_flag_enabled?
  group&.content_editor_on_issues_feature_flag_enabled? || Feature.enabled?(:content_editor_on_issues, self)
end

#create_labelsObject

rubocop: disable CodeReuse/ServiceClass



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

def create_labels
  Label.templates.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')
    Labels::FindOrCreateService.new(nil, self, params).execute(skip_authorization: true)
  end
end

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

TODO: rename to build_or_assign_import_data as it doesn’t save record gitlab.com/gitlab-org/gitlab/-/issues/377319



1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
# File 'app/models/project.rb', line 1475

def create_or_update_import_data(data: nil, credentials: nil)
  return if data.nil? && credentials.nil?

  project_import_data = import_data || build_import_data

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

  project_import_data
end

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



1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
# File 'app/models/project.rb', line 1972

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

  repository.create_repository(default_branch)
  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

#created_and_owned_by_banned_user?Boolean

Returns:

  • (Boolean)


3192
3193
3194
3195
3196
# File 'app/models/project.rb', line 3192

def created_and_owned_by_banned_user?
  return false unless creator

  creator.banned? && team.max_member_access(creator.id) == Gitlab::Access::OWNER
end

#crm_enabled?Boolean

Returns:

  • (Boolean)


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

def crm_enabled?
  return false unless group

  group.crm_enabled?
end

#default_branch_or_mainObject



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

def default_branch_or_main
  return default_branch if default_branch

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

#default_branch_protected?Boolean

Returns:

  • (Boolean)


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

def default_branch_protected?
  branch_protection = Gitlab::Access::BranchProtection.new(self.namespace.default_branch_protection)

  branch_protection.fully_protected? || branch_protection.developer_can_merge? || branch_protection.developer_can_initial_push?
end

#default_environmentObject



2532
2533
2534
2535
2536
2537
2538
2539
# File 'app/models/project.rb', line 2532

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:

  • (Boolean)


1721
1722
1723
# File 'app/models/project.rb', line 1721

def default_issues_tracker?
  !external_issue_tracker
end

#default_merge_request_targetObject



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

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



1194
1195
1196
1197
1198
1199
1200
# File 'app/models/project.rb', line 1194

def default_pipeline_lock
  if keep_latest_artifacts_available?
    return :artifacts_locked
  end

  :unlocked
end

#default_service_desk_suffixObject



2995
2996
2997
# File 'app/models/project.rb', line 2995

def default_service_desk_suffix
  "#{id}-issue-"
end

#dependency_proxy_variablesObject



2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
# File 'app/models/project.rb', line 2502

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



2927
2928
2929
# File 'app/models/project.rb', line 2927

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



2931
2932
2933
# File 'app/models/project.rb', line 2931

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



2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
# File 'app/models/project.rb', line 2560

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



1837
1838
1839
1840
1841
# File 'app/models/project.rb', line 1837

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:

  • (Boolean)


1275
1276
1277
# File 'app/models/project.rb', line 1275

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

#design_repositoryObject



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

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

#destroy_deployment_by_id(deployment_id) ⇒ Object



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

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

#disabled_integrationsObject



1757
1758
1759
1760
1761
1762
1763
1764
1765
# File 'app/models/project.rb', line 1757

def disabled_integrations
  return [] if Rails.env.development?

  names = %w[shimo zentao]

  # The Slack Slash Commands integration is only available for customers who cannot use the GitLab for Slack app.
  # The GitLab for Slack app integration is only available when enabled through settings.
  names << (Gitlab::CurrentSettings.slack_app_enabled ? 'slack_slash_commands' : 'gitlab_slack_application')
end

#drop_visibility_level!Object



2885
2886
2887
2888
2889
2890
2891
2892
2893
# File 'app/models/project.rb', line 2885

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:

  • (Boolean)


1230
1231
1232
1233
# File 'app/models/project.rb', line 1230

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

#enable_ciObject



2146
2147
2148
# File 'app/models/project.rb', line 2146

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

#enabled_group_deploy_keysObject



3058
3059
3060
3061
3062
# File 'app/models/project.rb', line 3058

def enabled_group_deploy_keys
  return GroupDeployKey.none unless group

  GroupDeployKey.for_groups(group.self_and_ancestors_ids)
end

#enforce_auth_checks_on_uploads?Boolean

Returns:

  • (Boolean)


1142
1143
1144
# File 'app/models/project.rb', line 1142

def enforce_auth_checks_on_uploads?
  !!project_setting&.enforce_auth_checks_on_uploads?
end

#enforced_runner_token_expiration_intervalObject



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

def enforced_runner_token_expiration_interval
  all_parent_groups = Gitlab::ObjectHierarchy.new(Group.where(id: group)).base_and_ancestors
  all_group_settings = NamespaceSetting.where(namespace_id: all_parent_groups)
  group_interval = all_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



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

def enqueue_record_project_target_platforms
  return unless Gitlab.com?

  Projects::RecordTargetPlatformsWorker.perform_async(id)
end

#ensure_repositoryObject



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

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

#environments_for_scope(scope) ⇒ Object



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

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



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

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



1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
# File 'app/models/project.rb', line 1874

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.



1938
1939
1940
1941
1942
1943
1944
1945
1946
# File 'app/models/project.rb', line 1938

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?Boolean

Returns:

  • (Boolean)


2412
2413
2414
# File 'app/models/project.rb', line 2412

def export_archive_exists?
  import_export_upload&.export_archive_exists?
end

#export_enqueued?Boolean

Returns:

  • (Boolean)


2391
2392
2393
2394
2395
# File 'app/models/project.rb', line 2391

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

#export_fileObject



2416
2417
2418
# File 'app/models/project.rb', line 2416

def export_file
  import_export_upload&.export_file
end

#export_file_exists?Boolean

Returns:

  • (Boolean)


2408
2409
2410
# File 'app/models/project.rb', line 2408

def export_file_exists?
  import_export_upload&.export_file_exists?
end

#export_in_progress?Boolean

Returns:

  • (Boolean)


2385
2386
2387
2388
2389
# File 'app/models/project.rb', line 2385

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

#export_pathObject



2365
2366
2367
2368
2369
# File 'app/models/project.rb', line 2365

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

  import_export_shared.archive_path
end

#export_statusObject



2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
# File 'app/models/project.rb', line 2371

def export_status
  if regeneration_in_progress?
    :regeneration_in_progress
  elsif export_enqueued?
    :queued
  elsif export_in_progress?
    :started
  elsif export_file_exists?
    :finished
  else
    :none
  end
end

#external_authorization_classification_labelObject



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

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

#external_import?Boolean

Returns:

  • (Boolean)


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

def external_import?
  import_url.present?
end

#external_issue_reference_patternObject



1717
1718
1719
# File 'app/models/project.rb', line 1717

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

#external_issue_trackerObject



1725
1726
1727
1728
1729
1730
1731
# File 'app/models/project.rb', line 1725

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:

  • (Boolean)


1733
1734
1735
# File 'app/models/project.rb', line 1733

def external_references_supported?
  external_issue_tracker&.support_cross_reference?
end

#external_wikiObject



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

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:

  • (Boolean)


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

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

#feature_flags_client_tokenObject



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

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

#feature_usageObject



1903
1904
1905
# File 'app/models/project.rb', line 1903

def feature_usage
  super.presence || build_feature_usage
end

#ff_merge_must_be_possible?Boolean

Returns:

  • (Boolean)


2692
2693
2694
# File 'app/models/project.rb', line 2692

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

#find_or_create_design_management_repositoryObject



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

def find_or_create_design_management_repository
  design_management_repository || create_design_management_repository
end

#find_or_initialize_integration(name) ⇒ Object



1767
1768
1769
1770
1771
# File 'app/models/project.rb', line 1767

def find_or_initialize_integration(name)
  return if disabled_integrations.include?(name) || Integration.available_integration_names.exclude?(name)

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

#find_or_initialize_integrationsObject



1749
1750
1751
1752
1753
1754
1755
# File 'app/models/project.rb', line 1749

def find_or_initialize_integrations
  Integration
    .available_integration_names
    .difference(disabled_integrations)
    .map { find_or_initialize_integration(_1) }
    .sort_by(&:title)
end

#first_auto_devops_configObject



1268
1269
1270
1271
1272
# File 'app/models/project.rb', line 1268

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



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

def first_owner
  obj = owner

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

#fork_sourceObject



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

def fork_source
  return unless forked?

  forked_from_project || fork_network&.root_project
end

#forked?Boolean

Returns:

  • (Boolean)


1907
1908
1909
# File 'app/models/project.rb', line 1907

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

#forked_from?(other_project) ⇒ Boolean

Returns:

  • (Boolean)


2054
2055
2056
# File 'app/models/project.rb', line 2054

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

#forking_enabled?Boolean

Returns:

  • (Boolean)


2109
2110
2111
# File 'app/models/project.rb', line 2109

def forking_enabled?
  !!project_feature&.forking_enabled?
end

#forks_countObject

rubocop: disable CodeReuse/ServiceClass



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

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



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

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

#full_path_slugObject



2420
2421
2422
# File 'app/models/project.rb', line 2420

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

#get_issue(issue_id, current_user) ⇒ Object



1703
1704
1705
1706
1707
1708
1709
1710
1711
# File 'app/models/project.rb', line 1703

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



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

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:

  • (Boolean)


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

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:

  • (Boolean)


2717
2718
2719
2720
2721
# File 'app/models/project.rb', line 2717

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

#gitea_import?Boolean

Returns:

  • (Boolean)


1510
1511
1512
# File 'app/models/project.rb', line 1510

def gitea_import?
  import_type == 'gitea'
end

#github_enterprise_import?Boolean

Returns:

  • (Boolean)


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

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

#github_import?Boolean

Returns:

  • (Boolean)


1514
1515
1516
# File 'app/models/project.rb', line 1514

def github_import?
  import_type == 'github'
end

#gitlab_deploy_tokenObject



2772
2773
2774
2775
2776
# File 'app/models/project.rb', line 2772

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:

  • (Boolean)


1502
1503
1504
# File 'app/models/project.rb', line 1502

def gitlab_project_import?
  import_type == 'gitlab_project'
end

#gitlab_project_migration?Boolean

Returns:

  • (Boolean)


1506
1507
1508
# File 'app/models/project.rb', line 1506

def gitlab_project_migration?
  import_type == 'gitlab_project_migration'
end


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

def group_group_links
  group&.shared_with_group_links&.of_ancestors_and_self || GroupGroupLink.none
end

#group_protected_branchesObject



2911
2912
2913
# File 'app/models/project.rb', line 2911

def group_protected_branches
  root_namespace.is_a?(Group) ? root_namespace.protected_branches : ProtectedBranch.none
end

#group_runnersObject



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

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:

  • (Boolean)


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

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:

  • (Boolean)


1885
1886
1887
1888
1889
1890
1891
1892
1893
# File 'app/models/project.rb', line 1885

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:

  • (Boolean)


1895
1896
1897
1898
1899
1900
1901
# File 'app/models/project.rb', line 1895

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:

  • (Boolean)


1258
1259
1260
1261
1262
# File 'app/models/project.rb', line 1258

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:

  • (Boolean)


1252
1253
1254
1255
1256
# File 'app/models/project.rb', line 1252

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:

  • (Boolean)


2424
2425
2426
# File 'app/models/project.rb', line 2424

def has_ci?
  repository.gitlab_ci_yml || auto_devops_enabled?
end

#has_container_registry_tags?Boolean

Returns:

  • (Boolean)


1320
1321
1322
1323
1324
1325
# File 'app/models/project.rb', line 1320

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_namespaced_npm_packages?Boolean

Returns:

  • (Boolean)


3038
3039
3040
3041
3042
# File 'app/models/project.rb', line 3038

def has_namespaced_npm_packages?
  packages.with_npm_scope(root_namespace.path)
          .not_pending_destruction
          .exists?
end

#has_pool_repository?Boolean

Returns:

  • (Boolean)


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

def has_pool_repository?
  pool_repository.present?
end

#has_remote_mirror?Boolean

Returns:

  • (Boolean)


1523
1524
1525
# File 'app/models/project.rb', line 1523

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

#has_wiki?Boolean

Returns:

  • (Boolean)


1737
1738
1739
# File 'app/models/project.rb', line 1737

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:

  • feature (Symbol)

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

Returns:

  • (Boolean)

Raises:

  • (ArgumentError)


2650
2651
2652
2653
2654
# File 'app/models/project.rb', line 2650

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



1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
# File 'app/models/project.rb', line 1986

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



1383
1384
1385
# File 'app/models/project.rb', line 1383

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

#human_merge_methodObject



2660
2661
2662
2663
2664
2665
2666
# File 'app/models/project.rb', line 2660

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

#import?Boolean

Returns:

  • (Boolean)


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

def import?
  external_import? || forked? || gitlab_project_import? || jira_import? || gitlab_project_migration?
end

#import_checksumsObject



1375
1376
1377
# File 'app/models/project.rb', line 1375

def import_checksums
  import_state&.checksums || {}
end

#import_export_sharedObject



2361
2362
2363
# File 'app/models/project.rb', line 2361

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

#import_failed?Boolean

Returns:

  • (Boolean)


1166
1167
1168
# File 'app/models/project.rb', line 1166

def import_failed?
  !!import_state&.failed?
end

#import_finished?Boolean

Returns:

  • (Boolean)


1170
1171
1172
# File 'app/models/project.rb', line 1170

def import_finished?
  !!import_state&.finished?
end

#import_in_progress?Boolean

Returns:

  • (Boolean)


1162
1163
1164
# File 'app/models/project.rb', line 1162

def import_in_progress?
  !!import_state&.in_progress?
end

#import_scheduled?Boolean

Returns:

  • (Boolean)


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

def import_scheduled?
  !!import_state&.scheduled?
end

#import_started?Boolean

Returns:

  • (Boolean)


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

def import_started?
  !!import_state&.started?
end

#import_statusObject



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

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

#import_urlObject



1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
# File 'app/models/project.rb', line 1458

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

#import_url=(value) ⇒ Object



1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
# File 'app/models/project.rb', line 1446

def import_url=(value)
  if Gitlab::UrlSanitizer.valid?(value)
    import_url = Gitlab::UrlSanitizer.new(value)
    super(import_url.sanitized_url)

    credentials = import_url.credentials.to_h.transform_values { |value| CGI.unescape(value.to_s) }
    create_or_update_import_data(credentials: credentials)
  else
    super(value)
  end
end

#in_fork_network_of?(other_project) ⇒ Boolean

Returns:

  • (Boolean)


2058
2059
2060
2061
2062
# File 'app/models/project.rb', line 2058

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

#inactive?Boolean

Returns:

  • (Boolean)


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

def inactive?
  (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

#initial_push_to_default_branch_allowed_for_developer?Boolean

Returns:

  • (Boolean)


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

def initial_push_to_default_branch_allowed_for_developer?
  branch_protection = Gitlab::Access::BranchProtection.new(self.namespace.default_branch_protection)

  !branch_protection.any? || branch_protection.developer_can_push? || branch_protection.developer_can_initial_push?
end

#instance_runner_running_jobs_countObject



3284
3285
3286
3287
3288
# File 'app/models/project.rb', line 3284

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



1127
1128
1129
1130
1131
1132
# File 'app/models/project.rb', line 1127

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:

  • (Boolean)


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

def issue_exists?(issue_id)
  get_issue(issue_id)
end

#issues_enabled?Boolean

Returns:

  • (Boolean)


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

def issues_enabled?
  !!project_feature&.issues_enabled?
end

#items_for(entity) ⇒ Object



1811
1812
1813
1814
1815
1816
1817
1818
# File 'app/models/project.rb', line 1811

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

#jira_import?Boolean

Returns:

  • (Boolean)


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

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

#jira_import_statusObject



1379
1380
1381
# File 'app/models/project.rb', line 1379

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

#jira_subscription_exists?Boolean

Returns:

  • (Boolean)


2899
2900
2901
# File 'app/models/project.rb', line 2899

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

#keep_latest_artifact?Boolean

Returns:

  • (Boolean)


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

def keep_latest_artifact?
  return false unless ci_cd_settings

  ci_cd_settings.keep_latest_artifact?
end

#keep_latest_artifacts_available?Boolean

Returns:

  • (Boolean)


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

def keep_latest_artifacts_available?
  return false unless ci_cd_settings

  ci_cd_settings.keep_latest_artifacts_available?
end

#last_activityObject



1691
1692
1693
# File 'app/models/project.rb', line 1691

def last_activity
  last_event
end

#last_activity_dateObject



1695
1696
1697
# File 'app/models/project.rb', line 1695

def last_activity_date
  updated_at
end

#latest_jira_importObject



2953
2954
2955
# File 'app/models/project.rb', line 2953

def latest_jira_import
  jira_imports.last
end

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



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

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

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



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

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

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

#latest_successful_build_for_ref(job_name, ref = default_branch) ⇒ Object

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



1328
1329
1330
1331
1332
1333
1334
1335
# File 'app/models/project.rb', line 1328

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



1346
1347
1348
# File 'app/models/project.rb', line 1346

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



1337
1338
1339
1340
1341
1342
1343
1344
# File 'app/models/project.rb', line 1337

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



2085
2086
2087
2088
2089
2090
2091
# File 'app/models/project.rb', line 2085

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



2076
2077
2078
2079
2080
2081
2082
2083
# File 'app/models/project.rb', line 2076

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

#leave_pool_repositoryObject



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

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:

  • (Boolean)


2643
2644
2645
# File 'app/models/project.rb', line 2643

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

#lfs_enabled?Boolean Also known as: lfs_enabled

Returns:

  • (Boolean)


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

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

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

#lfs_objects_for_repository_types(*types) ⇒ Object



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

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



1923
1924
1925
# File 'app/models/project.rb', line 1923

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

#lfs_objects_oids_from_fork_source(oids: []) ⇒ Object



1927
1928
1929
1930
1931
# File 'app/models/project.rb', line 1927

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

  oids(fork_source.lfs_objects, oids: oids)
end

#licensed_feature_available?(_feature) ⇒ Boolean

Overridden in EE::Project

Returns:

  • (Boolean)


2760
2761
2762
# File 'app/models/project.rb', line 2760

def licensed_feature_available?(_feature)
  false
end

#licensed_featuresObject



2764
2765
2766
# File 'app/models/project.rb', line 2764

def licensed_features
  []
end

#limited_protected_branches(limit) ⇒ Object



2907
2908
2909
# File 'app/models/project.rb', line 2907

def limited_protected_branches(limit)
  protected_branches.limit(limit)
end


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

def link_pool_repository
  return unless pool_repository
  return if (pool_repository.shard_name != repository.shard) && replicate_object_pool_on_move_ff_enabled?

  pool_repository.link_repository(repository)
end

#linked_work_items_feature_flag_enabled?Boolean

Returns:

  • (Boolean)


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

def linked_work_items_feature_flag_enabled?
  group&.linked_work_items_feature_flag_enabled? || Feature.enabled?(:linked_work_items, self)
end

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



1412
1413
1414
1415
1416
1417
1418
1419
1420
# File 'app/models/project.rb', line 1412

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

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

#mark_pages_as_deployedObject



2271
2272
2273
# File 'app/models/project.rb', line 2271

def mark_pages_as_deployed
  ensure_pages_metadatum.update!(deployed: true)
end

#mark_pages_as_not_deployedObject



2275
2276
2277
# File 'app/models/project.rb', line 2275

def mark_pages_as_not_deployed
  ensure_pages_metadatum.update!(deployed: false)
end

#mark_pages_onboarding_completeObject



2267
2268
2269
# File 'app/models/project.rb', line 2267

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

#mark_remote_mirrors_for_removalObject



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

def mark_remote_mirrors_for_removal
  remote_mirrors.each(&:mark_for_delete_if_blank_url)
end

#mark_stuck_remote_mirrors_as_failed!Object



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

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

#max_attachment_sizeObject



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

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

#member(user) ⇒ Object



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

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



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

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

Returns:

  • (Boolean)


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

def membership_locked?
  false
end

#merge_base_commit(first_commit_id, second_commit_id) ⇒ Object



1362
1363
1364
1365
# File 'app/models/project.rb', line 1362

def merge_base_commit(first_commit_id, second_commit_id)
  sha = repository.merge_base(first_commit_id, second_commit_id)
  commit_by(oid: sha) if sha
end

#merge_commit_template_or_defaultObject



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

def merge_commit_template_or_default
  merge_commit_template.presence || DEFAULT_MERGE_COMMIT_TEMPLATE
end

#merge_commit_template_or_default=(value) ⇒ Object



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

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



2668
2669
2670
2671
2672
2673
2674
2675
2676
# File 'app/models/project.rb', line 2668

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



2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
# File 'app/models/project.rb', line 2678

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



2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
# File 'app/models/project.rb', line 2735

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:

  • (Boolean)


2105
2106
2107
# File 'app/models/project.rb', line 2105

def merge_requests_enabled?
  !!project_feature&.merge_requests_enabled?
end

#migrate_to_hashed_storage!Object



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

def migrate_to_hashed_storage!
  return unless storage_upgradable?

  if git_transfer_in_progress?
    HashedStorage::ProjectMigrateWorker.perform_in(Gitlab::ReferenceCounter::REFERENCE_EXPIRE_TIME, id)
  else
    HashedStorage::ProjectMigrateWorker.perform_async(id)
  end
end

#mr_can_target_upstream?Boolean

Returns:

  • (Boolean)


2610
2611
2612
2613
2614
2615
2616
# File 'app/models/project.rb', line 2610

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:

  • (Boolean)


2618
2619
2620
# File 'app/models/project.rb', line 2618

def multiple_issue_boards_available?
  true
end

#new_issuable_address(author, address_type) ⇒ Object



1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
# File 'app/models/project.rb', line 1672

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:

  • (Boolean)


1150
1151
1152
# File 'app/models/project.rb', line 1150

def no_import?
  !!import_state&.no_import?
end

#object_pool_paramsObject



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

def object_pool_params
  return {} unless !forked? && git_objects_poolable?

  {
    repository_storage: repository_storage,
    pool_repository: pool_repository || create_new_pool_repository
  }
end

#open_issues_count(current_user = nil) ⇒ Object

rubocop: disable CodeReuse/ServiceClass



2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
# File 'app/models/project.rb', line 2189

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



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

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:

  • (Boolean)


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

def operations_enabled?
  !!project_feature&.operations_enabled?
end

#origin_merge_requestsObject



2064
2065
2066
# File 'app/models/project.rb', line 2064

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

#ownerObject

rubocop: enable CodeReuse/ServiceClass



1830
1831
1832
1833
1834
1835
# File 'app/models/project.rb', line 1830

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

#ownersObject



1843
1844
1845
1846
1847
1848
# File 'app/models/project.rb', line 1843

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

#package_already_taken?(package_name, package_version, package_type:) ⇒ Boolean

Returns:

  • (Boolean)


3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
# File 'app/models/project.rb', line 3026

def package_already_taken?(package_name, package_version, package_type:)
  Packages::Package.with_name(package_name)
    .with_version(package_version)
    .with_package_type(package_type)
    .not_pending_destruction
    .for_projects(
      root_ancestor.all_projects
        .id_not_in(id)
        .select(:id)
    ).exists?
end

#packages_cleanup_policyObject



1264
1265
1266
# File 'app/models/project.rb', line 1264

def packages_cleanup_policy
  super || build_packages_cleanup_policy
end

#packages_policy_subjectObject



3241
3242
3243
# File 'app/models/project.rb', line 3241

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

#pages_available?Boolean

Returns:

  • (Boolean)


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

def pages_available?
  Gitlab.config.pages.enabled
end

#pages_deployed?Boolean

Returns:

  • (Boolean)


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

def pages_deployed?
  pages_metadatum&.deployed?
end

#pages_enabled?Boolean

Returns:

  • (Boolean)


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

def pages_enabled?
  !!project_feature&.pages_enabled?
end

#pages_https_onlyObject



1591
1592
1593
1594
1595
# File 'app/models/project.rb', line 1591

def pages_https_only
  return false unless Gitlab.config.pages.external_https

  super
end

#pages_https_only?Boolean

Returns:

  • (Boolean)


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

def pages_https_only?
  return false unless Gitlab.config.pages.external_https

  super
end

#pages_pathObject



2239
2240
2241
2242
# File 'app/models/project.rb', line 2239

def pages_path
  # TODO: when we migrate Pages to work with new storage types, change here to use disk_path
  File.join(Settings.pages.path, full_path)
end

#pages_show_onboarding?Boolean

Returns:

  • (Boolean)


2248
2249
2250
# File 'app/models/project.rb', line 2248

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

#pages_variablesObject



2480
2481
2482
2483
2484
2485
2486
2487
# File 'app/models/project.rb', line 2480

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)
    variables.append(key: 'CI_PAGES_URL', value: Gitlab::Pages::UrlBuilder.new(self).pages_url(with_unique_domain: true))
  end
end

#parent_changed?Boolean

Returns:

  • (Boolean)


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

def parent_changed?
  namespace_id_changed?
end

#parent_loaded?Boolean

Returns:

  • (Boolean)


1103
1104
1105
# File 'app/models/project.rb', line 1103

def parent_loaded?
  association(:namespace).loaded?
end

#path_availabilityObject



3275
3276
3277
3278
3279
3280
3281
3282
# File 'app/models/project.rb', line 3275

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

#pending_delete_or_hidden?Boolean

Returns:

  • (Boolean)


3188
3189
3190
# File 'app/models/project.rb', line 3188

def pending_delete_or_hidden?
  pending_delete? || hidden?
end

#personal?Boolean

Returns:

  • (Boolean)


1933
1934
1935
# File 'app/models/project.rb', line 1933

def personal?
  !group
end

#personal_namespace_holder?(user) ⇒ Boolean

Returns:

  • (Boolean)


1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
# File 'app/models/project.rb', line 1115

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

#predefined_ci_server_variablesObject



2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
# File 'app/models/project.rb', line 2462

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_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



2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
# File 'app/models/project.rb', line 2442

def predefined_project_variables
  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_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_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_CONFIG_PATH', value: ci_config_path_or_default)
end

#predefined_variablesObject



2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
# File 'app/models/project.rb', line 2428

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



1208
1209
1210
1211
1212
1213
# File 'app/models/project.rb', line 1208

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

#private_pages?Boolean

Returns:

  • (Boolean)


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

def private_pages?
  !!project_feature&.private_pages?
end

#project_idObject



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

def project_id
  self.id
end

#project_settingObject



1134
1135
1136
# File 'app/models/project.rb', line 1134

def project_setting
  super.presence || build_project_setting
end

#prometheus_integration_active?Boolean

Returns:

  • (Boolean)


1111
1112
1113
# File 'app/models/project.rb', line 1111

def prometheus_integration_active?
  !!prometheus_integration&.active?
end

#protected_for?(ref) ⇒ Boolean

Returns:

  • (Boolean)

Raises:



2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
# File 'app/models/project.rb', line 2541

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:

  • (Boolean)


2129
2130
2131
# File 'app/models/project.rb', line 2129

def public_pages?
  !!project_feature&.public_pages?
end

#public_path_for_source_path(path, commit_sha) ⇒ Object



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

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



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

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



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

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

#refreshing_build_artifacts_size?Boolean

Returns:

  • (Boolean)


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

def refreshing_build_artifacts_size?
  build_artifacts_size_refresh&.started?
end

#regeneration_in_progress?Boolean

Returns:

  • (Boolean)


2397
2398
2399
# File 'app/models/project.rb', line 2397

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


3018
3019
3020
3021
3022
3023
3024
# File 'app/models/project.rb', line 3018

def related_group_ids
  ids = invited_group_ids

  ids += group.self_and_ancestors_ids if group

  ids
end

#remote_mirror_available?Boolean

Returns:

  • (Boolean)


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

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

#remove_exportsObject



2401
2402
2403
2404
2405
2406
# File 'app/models/project.rb', line 2401

def remove_exports
  return unless export_file_exists?

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

#remove_import_dataObject

This method is overridden in EE::Project model



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

def remove_import_data
  import_data&.destroy
end

#remove_private_deploy_keysObject



2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
# File 'app/models/project.rb', line 2252

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:

  • (Boolean)


2656
2657
2658
# File 'app/models/project.rb', line 2656

def renamed?
  persisted? && path_changed?
end

#repositoryObject



1283
1284
1285
# File 'app/models/project.rb', line 1283

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

#reset_cache_and_import_attrsObject



1422
1423
1424
1425
1426
1427
1428
1429
# File 'app/models/project.rb', line 1422

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

#restrict_user_defined_variables?Boolean

Returns:

  • (Boolean)


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

def restrict_user_defined_variables?
  return false unless ci_cd_settings

  ci_cd_settings.restrict_user_defined_variables?
end

#rollback_to_legacy_storage!Object



2706
2707
2708
2709
2710
2711
2712
2713
2714
# File 'app/models/project.rb', line 2706

def rollback_to_legacy_storage!
  return if legacy_storage?

  if git_transfer_in_progress?
    HashedStorage::ProjectRollbackWorker.perform_in(Gitlab::ReferenceCounter::REFERENCE_EXPIRE_TIME, id)
  else
    HashedStorage::ProjectRollbackWorker.perform_async(id)
  end
end

#root_namespaceObject



2999
3000
3001
3002
3003
3004
3005
# File 'app/models/project.rb', line 2999

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

#route_map_for(commit_sha) ⇒ Object



2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
# File 'app/models/project.rb', line 2578

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



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

def runners_token
  ensure_runners_token!
end

#safe_import_urlObject



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

def safe_import_url
  Gitlab::UrlSanitizer.new(import_url).masked_url
end

#saved?Boolean

Returns:

  • (Boolean)


1367
1368
1369
# File 'app/models/project.rb', line 1367

def saved?
  id && persisted?
end

#security_training_available?Boolean

Returns:

  • (Boolean)


3237
3238
3239
# File 'app/models/project.rb', line 3237

def security_training_available?
  licensed_feature_available?(:security_training)
end

#self_or_root_group_idsObject

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



3008
3009
3010
3011
3012
3013
3014
3015
3016
# File 'app/models/project.rb', line 3008

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



1821
1822
1823
1824
1825
1826
1827
# File 'app/models/project.rb', line 1821

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

#service_desk_addressObject



2963
2964
2965
# File 'app/models/project.rb', line 2963

def service_desk_address
  service_desk_custom_address || service_desk_system_address
end

#service_desk_alias_addressObject



2980
2981
2982
2983
2984
2985
2986
# File 'app/models/project.rb', line 2980

def service_desk_alias_address
  return unless Gitlab::Email::ServiceDeskEmail.enabled?

  key = service_desk_setting&.project_key || default_service_desk_suffix

  Gitlab::Email::ServiceDeskEmail.address_for_key("#{full_path_slug}-#{key}")
end

#service_desk_custom_addressObject



2988
2989
2990
2991
2992
2993
# File 'app/models/project.rb', line 2988

def service_desk_custom_address
  return unless Feature.enabled?(:service_desk_custom_email, self)
  return unless service_desk_setting&.custom_email_enabled?

  service_desk_setting.custom_email
end

#service_desk_enabledObject Also known as: service_desk_enabled?



2957
2958
2959
# File 'app/models/project.rb', line 2957

def service_desk_enabled
  Gitlab::ServiceDesk.enabled?(project: self)
end

#service_desk_incoming_addressObject



2971
2972
2973
2974
2975
2976
2977
2978
# File 'app/models/project.rb', line 2971

def service_desk_incoming_address
  return unless service_desk_enabled?

  config = Gitlab.config.incoming_email
  wildcard = Gitlab::Email::Common::WILDCARD_PLACEHOLDER

  config.address&.gsub(wildcard, "#{full_path_slug}-#{default_service_desk_suffix}")
end

#service_desk_system_addressObject



2967
2968
2969
# File 'app/models/project.rb', line 2967

def service_desk_system_address
  service_desk_alias_address || service_desk_incoming_address
end

#set_first_pages_deployment!(deployment) ⇒ Object



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

def set_first_pages_deployment!(deployment)
  ensure_pages_metadatum

  # where().update_all to perform update in the single transaction with check for null
  ProjectPagesMetadatum
    .where(project_id: id, pages_deployment_id: nil)
    .update_all(deployed: deployment.present?, pages_deployment_id: deployment&.id)
end

#set_full_path(gl_full_path: full_path) ⇒ Object



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

def set_full_path(gl_full_path: full_path)
  # We'd need to keep track of project full path otherwise directory tree
  # created with hashed storage enabled cannot be usefully imported using
  # the import rake task.
  repository.raw_repository.set_full_path(full_path: gl_full_path)
rescue Gitlab::Git::Repository::NoRepository => e
  Gitlab::AppLogger.error("Error writing to .git/config for project #{full_path} (#{id}): #{e.message}.")
  nil
end

#set_project_feature_defaultsObject

Remove along with ProjectFeaturesCompatibility module



1094
1095
1096
1097
1098
1099
1100
1101
# File 'app/models/project.rb', line 1094

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

#shared_runnersObject



2154
2155
2156
# File 'app/models/project.rb', line 2154

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

#shared_runners_available?Boolean

Returns:

  • (Boolean)


2150
2151
2152
# File 'app/models/project.rb', line 2150

def shared_runners_available?
  shared_runners_enabled?
end

#shared_runners_setting_conflicting_with_group?Boolean

Returns:

  • (Boolean)


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

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:

  • (Boolean)


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

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

#show_default_award_emojis?Boolean

Returns:

  • (Boolean)


1138
1139
1140
# File 'app/models/project.rb', line 1138

def show_default_award_emojis?
  !!project_setting&.show_default_award_emojis?
end

#snippets_enabled?Boolean

Returns:

  • (Boolean)


2125
2126
2127
# File 'app/models/project.rb', line 2125

def snippets_enabled?
  !!project_feature&.snippets_enabled?
end

#snippets_visible?(user = nil) ⇒ Boolean

Returns:

  • (Boolean)


2800
2801
2802
# File 'app/models/project.rb', line 2800

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

#squash_commit_template_or_defaultObject



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

def squash_commit_template_or_default
  squash_commit_template.presence || DEFAULT_SQUASH_COMMIT_TEMPLATE
end

#squash_commit_template_or_default=(value) ⇒ Object



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

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



2787
2788
2789
2790
2791
2792
2793
2794
# File 'app/models/project.rb', line 2787

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

#storage_upgradable?Boolean

Returns:

  • (Boolean)


2796
2797
2798
# File 'app/models/project.rb', line 2796

def storage_upgradable?
  storage_version != LATEST_STORAGE_VERSION
end

#storage_version=(value) ⇒ Object



2723
2724
2725
2726
2727
# File 'app/models/project.rb', line 2723

def storage_version=(value)
  super

  @storage = nil if storage_version_changed?
end

#suggested_reviewers_available?Boolean

overridden in EE

Returns:

  • (Boolean)


3261
3262
3263
# File 'app/models/project.rb', line 3261

def suggested_reviewers_available?
  false
end

#supports_lock_on_merge?Boolean

Returns:

  • (Boolean)


3271
3272
3273
# File 'app/models/project.rb', line 3271

def supports_lock_on_merge?
  group&.supports_lock_on_merge? || ::Feature.enabled?(:enforce_locked_labels_on_merge, self, type: :ops)
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



2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
# File 'app/models/project.rb', line 2841

def swap_pool_repository!
  return unless replicate_object_pool_on_move_ff_enabled?
  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



1279
1280
1281
# File 'app/models/project.rb', line 1279

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

#template_source?Boolean

Returns:

  • (Boolean)


2895
2896
2897
# File 'app/models/project.rb', line 2895

def template_source?
  false
end

#to_human_reference(from = nil) ⇒ Object



1657
1658
1659
1660
1661
1662
1663
# File 'app/models/project.rb', line 1657

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

#to_paramObject



1629
1630
1631
1632
1633
1634
1635
# File 'app/models/project.rb', line 1629

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.



1643
1644
1645
1646
# File 'app/models/project.rb', line 1643

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) ⇒ Object

‘from` argument can be a Namespace or Project.



1649
1650
1651
1652
1653
1654
1655
# File 'app/models/project.rb', line 1649

def to_reference_base(from = nil, full: false)
  if full || cross_namespace_reference?(from)
    full_path
  elsif cross_project_reference?(from)
    path
  end
end

#toggle_ci_cd_settings!(settings_attribute) ⇒ Object



2768
2769
2770
# File 'app/models/project.rb', line 2768

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

#track_project_repositoryObject



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

def track_project_repository
  repository = project_repository || build_project_repository
  repository.update!(shard_name: repository_storage, disk_path: disk_path)

  cleanup if replicate_object_pool_on_move_ff_enabled?
end

#triggered_hooks(hooks_scope, data) ⇒ Object

rubocop: enable CodeReuse/ServiceClass



1869
1870
1871
1872
# File 'app/models/project.rb', line 1869

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

#update_pages_deployment!(deployment) ⇒ Object



2279
2280
2281
# File 'app/models/project.rb', line 2279

def update_pages_deployment!(deployment)
  ensure_pages_metadatum.update!(pages_deployment: deployment)
end

#update_project_counter_cachesObject



2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
# File 'app/models/project.rb', line 2327

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

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

#update_remote_mirrorsObject



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

def update_remote_mirrors
  return unless remote_mirror_available?

  remote_mirrors.enabled.each(&:sync)
end

#updating_remote_mirror?Boolean

Returns:

  • (Boolean)


1527
1528
1529
# File 'app/models/project.rb', line 1527

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

#uses_default_ci_config?Boolean

Returns:

  • (Boolean)


2903
2904
2905
# File 'app/models/project.rb', line 2903

def uses_default_ci_config?
  ci_config_path.blank? || ci_config_path == Gitlab::FileDetector::PATTERNS[:gitlab_ci]
end

#valid_import_url?Boolean

Returns:

  • (Boolean)


1469
1470
1471
# File 'app/models/project.rb', line 1469

def valid_import_url?
  valid?(:import_url) || errors.messages[:import_url].nil?
end

#valid_runners_token?(token) ⇒ Boolean

Returns:

  • (Boolean)


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

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

#validate_pages_https_onlyObject



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

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:

  • (Boolean)


2227
2228
2229
# File 'app/models/project.rb', line 2227

def visibility_level_allowed?(level = self.visibility_level)
  visibility_level_allowed_as_fork?(level) && visibility_level_allowed_by_group?(level)
end

#visibility_level_allowed_as_forkObject



1584
1585
1586
1587
1588
1589
# File 'app/models/project.rb', line 1584

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:

  • (Boolean)


2212
2213
2214
2215
2216
2217
2218
2219
# File 'app/models/project.rb', line 2212

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_groupObject



1576
1577
1578
1579
1580
1581
1582
# File 'app/models/project.rb', line 1576

def visibility_level_allowed_by_group
  return if visibility_level_allowed_by_group?

  level_name = Gitlab::VisibilityLevel.level_name(self.visibility_level).downcase
  group_level_name = Gitlab::VisibilityLevel.level_name(self.group.visibility_level).downcase
  self.errors.add(:visibility_level, _("%{level_name} is not allowed in a %{group_level_name} group.") % { level_name: level_name, group_level_name: group_level_name })
end

#visibility_level_allowed_by_group?(level = self.visibility_level) ⇒ Boolean

Returns:

  • (Boolean)


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

def visibility_level_allowed_by_group?(level = self.visibility_level)
  return true unless group

  level <= group.visibility_level
end

#visibility_level_fieldObject



2043
2044
2045
# File 'app/models/project.rb', line 2043

def visibility_level_field
  :visibility_level
end


3141
3142
3143
3144
3145
3146
3147
3148
3149
# File 'app/models/project.rb', line 3141

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:

  • (Boolean)


1146
1147
1148
# File 'app/models/project.rb', line 1146

def warn_about_potentially_unwanted_characters?
  !!project_setting&.warn_about_potentially_unwanted_characters?
end

#wiki_enabled?Boolean

Returns:

  • (Boolean)


2101
2102
2103
# File 'app/models/project.rb', line 2101

def wiki_enabled?
  !!project_feature&.wiki_enabled?
end

#work_items_feature_flag_enabled?Boolean

Returns:

  • (Boolean)


3202
3203
3204
# File 'app/models/project.rb', line 3202

def work_items_feature_flag_enabled?
  group&.work_items_feature_flag_enabled? || Feature.enabled?(:work_items, self)
end

#work_items_mvc_2_feature_flag_enabled?Boolean

Returns:

  • (Boolean)


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

def work_items_mvc_2_feature_flag_enabled?
  group&.work_items_mvc_2_feature_flag_enabled? || Feature.enabled?(:work_items_mvc_2)
end

#work_items_mvc_feature_flag_enabled?Boolean

Returns:

  • (Boolean)


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

def work_items_mvc_feature_flag_enabled?
  group&.work_items_mvc_feature_flag_enabled? || Feature.enabled?(:work_items_mvc)
end