Class: Snippet

Direct Known Subclasses

PersonalSnippet, ProjectSnippet

Constant Summary collapse

MAX_FILE_COUNT =
10
MAX_SINGLE_FILE_COUNT =
1

Constants included from Gitlab::SQL::Pattern

Gitlab::SQL::Pattern::MIN_CHARS_FOR_PARTIAL_MATCHING, Gitlab::SQL::Pattern::REGEX_QUOTED_WORD

Constants included from Noteable

Noteable::MAX_NOTES_LIMIT

Constants included from CacheMarkdownField

CacheMarkdownField::INVALIDATED_BY

Constants included from Redactable

Redactable::UNSUBSCRIBE_PATTERN

Constants included from Gitlab::VisibilityLevel

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

Instance Attribute Summary

Attributes included from Noteable

#system_note_timestamp

Class Method Summary collapse

Instance Method Summary collapse

Methods included from Gitlab::Utils::Override

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

Methods included from AfterCommitQueue

#run_after_commit, #run_after_commit_or_now

Methods included from HasRepository

#commit, #commit_by, #commits_by, #default_branch, #default_branch_from_preferences, #empty_repo?, #http_url_to_repo, #reload_default_branch, #repo_exists?, #repository_exists?, #root_ref?, #ssh_url_to_repo, #url_to_repo, #valid_repo?, #web_url

Methods included from Gitlab::Utils::StrongMemoize

#clear_memoization, #strong_memoize, #strong_memoized?

Methods included from Gitlab::ShellAdapter

#gitlab_shell

Methods included from Referable

#referable_inspect, #reference_link_text, #to_reference_base

Methods included from Editable

#edited?, #last_edited_by

Methods included from Spammable

#clear_spam_flags!, #invalidate_if_spam, #needs_recaptcha!, #recaptcha_error!, #spam!, #spam_description, #spam_title, #spammable_text, #submittable_as_spam?, #submittable_as_spam_by?, #unrecoverable_spam_error!

Methods included from Mentionable

#all_references, #create_cross_references!, #create_new_cross_references!, #directly_addressed_users, #extractors, #gfm_reference, #local_reference, #matches_cross_reference_regex?, #mentioned_users, #referenced_group_users, #referenced_groups, #referenced_mentionables, #referenced_project_users, #referenced_projects, #referenced_users, #store_mentions!

Methods included from Awardable

#awarded_emoji?, #downvotes, #emoji_awardable?, #grouped_awards, #upvotes, #user_authored?, #user_can_award?

Methods included from Participable

#participants

Methods included from Noteable

#after_note_created, #after_note_destroyed, #base_class_name, #capped_notes_count, #discussion_ids_relation, #discussion_notes, #discussions, #discussions_can_be_resolved_by?, #discussions_rendered_on_frontend?, #discussions_resolvable?, #discussions_resolved?, #discussions_to_be_resolved, #etag_caching_enabled?, #expire_note_etag_cache, #grouped_diff_discussions, #has_any_diff_note_positions?, #human_class_name, #lockable?, #note_etag_key, #preloads_discussion_diff_highlighting?, #resolvable_discussions, #supports_discussions?, #supports_replying_to_individual_notes?, #supports_resolvable_notes?, #supports_suggestion?

Methods included from CacheMarkdownField

#attribute_invalidated?, #banzai_render_context, #cached_html_for, #cached_html_up_to_date?, #invalidated_markdown_cache?, #latest_cached_markdown_version, #local_version, #parent_user, #refresh_markdown_cache, #refresh_markdown_cache!, #rendered_field_content, #skip_project_check?, #updated_cached_html_for

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_level_attributes, #visibility_level_decreased?, #visibility_level_previous_changes, #visibility_level_value

Methods inherited from ApplicationRecord

at_most, id_in, id_not_in, iid_in, pluck_primary_key, primary_key_in, safe_ensure_unique, safe_find_or_create_by, safe_find_or_create_by!, underscore, without_order

Constructor Details

#initialize(attributes = {}) ⇒ Snippet

Returns a new instance of Snippet.


182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
# File 'app/models/snippet.rb', line 182

def initialize(attributes = {})
  # We can't use default_value_for because the database has a default
  # value of 0 for visibility_level. If someone attempts to create a
  # private snippet, default_value_for will assume that the
  # visibility_level hasn't changed and will use the application
  # setting default, which could be internal or public.
  #
  # To fix the problem, 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_snippet_visibility
  end

  super
end

Class Method Details

.find_by_id_and_project(id:, project:) ⇒ Object


174
175
176
# File 'app/models/snippet.rb', line 174

def self.find_by_id_and_project(id:, project:)
  Snippet.find_by(id: id, project: project)
end

.for_project_with_user(project, user = nil) ⇒ Object


141
142
143
144
145
146
147
148
149
# File 'app/models/snippet.rb', line 141

def self.for_project_with_user(project, user = nil)
  return none unless project.snippets_visible?(user)

  if user && project.team.member?(user)
    project.snippets
  else
    project.snippets.public_to_user(user)
  end
end

170
171
172
# File 'app/models/snippet.rb', line 170

def self.link_reference_pattern
  @link_reference_pattern ||= super("snippets", /(?<snippet>\d+)/)
end

.max_file_limit(user) ⇒ Object


178
179
180
# File 'app/models/snippet.rb', line 178

def self.max_file_limit(user)
  Feature.enabled?(:snippet_multiple_files, user) ? MAX_FILE_COUNT : MAX_SINGLE_FILE_COUNT
end

.only_include_authorized_projects(current_user) ⇒ Object


131
132
133
134
135
136
137
138
139
# File 'app/models/snippet.rb', line 131

def self.only_include_authorized_projects(current_user)
  where(
    'EXISTS (?)',
    ProjectAuthorization
      .select(1)
      .where('project_id = snippets.project_id')
      .where(user_id: current_user.id)
  )
end

.only_include_projects_visible_to(current_user = nil) ⇒ Object


115
116
117
118
119
# File 'app/models/snippet.rb', line 115

def self.only_include_projects_visible_to(current_user = nil)
  levels = Gitlab::VisibilityLevel.levels_for_user(current_user)

  joins(:project).where('projects.visibility_level IN (?)', levels)
end

.only_include_projects_with_snippets_enabled(include_private: false) ⇒ Object


121
122
123
124
125
126
127
128
129
# File 'app/models/snippet.rb', line 121

def self.only_include_projects_with_snippets_enabled(include_private: false)
  column = ProjectFeature.access_level_attribute(:snippets)
  levels = [ProjectFeature::ENABLED, ProjectFeature::PUBLIC]

  levels << ProjectFeature::PRIVATE if include_private

  joins(project: :project_feature)
    .where(project_features: { column => levels })
end

.only_personal_snippetsObject


107
108
109
# File 'app/models/snippet.rb', line 107

def self.only_personal_snippets
  where(project_id: nil)
end

.only_project_snippetsObject


111
112
113
# File 'app/models/snippet.rb', line 111

def self.only_project_snippets
  where.not(project_id: nil)
end

.parent_classObject


364
365
366
# File 'app/models/snippet.rb', line 364

def parent_class
  ::Project
end

.reference_patternObject

Pattern used to extract `$123` snippet references from text

This pattern supports cross-project references.


163
164
165
166
167
168
# File 'app/models/snippet.rb', line 163

def self.reference_pattern
  @reference_pattern ||= %r{
    (#{Project.reference_pattern})?
    #{Regexp.escape(reference_prefix)}(?<snippet>\d+)
  }x
end

.reference_prefixObject


156
157
158
# File 'app/models/snippet.rb', line 156

def self.reference_prefix
  '$'
end

.sanitized_file_name(file_name) ⇒ Object


228
229
230
# File 'app/models/snippet.rb', line 228

def self.sanitized_file_name(file_name)
  file_name.gsub(/[^a-zA-Z0-9_\-\.]+/, '')
end

.search(query) ⇒ Object

Searches for snippets with a matching title, description or file name.

This method uses ILIKE on PostgreSQL.

query - The search query as a String.

Returns an ActiveRecord::Relation.


360
361
362
# File 'app/models/snippet.rb', line 360

def search(query)
  fuzzy_search(query, [:title, :description, :file_name])
end

.visible_to_or_authored_by(user) ⇒ Object


151
152
153
154
# File 'app/models/snippet.rb', line 151

def self.visible_to_or_authored_by(user)
  query = where(visibility_level: Gitlab::VisibilityLevel.levels_for_user(user))
  query.or(where(author_id: user.id))
end

.with_optional_visibility(value = nil) ⇒ Object


99
100
101
102
103
104
105
# File 'app/models/snippet.rb', line 99

def self.with_optional_visibility(value = nil)
  if value
    where(visibility_level: value)
  else
    all
  end
end

Instance Method Details

#allow_possible_spam?Boolean

Returns:

  • (Boolean)

251
252
253
# File 'app/models/snippet.rb', line 251

def allow_possible_spam?
  false
end

#as_json(options = {}) ⇒ Object


269
270
271
272
273
274
# File 'app/models/snippet.rb', line 269

def as_json(options = {})
  options[:except] = Array.wrap(options[:except])
  options[:except] << :secret_token

  super
end

#blobObject


210
211
212
# File 'app/models/snippet.rb', line 210

def blob
  @blob ||= Blob.decorate(SnippetBlob.new(self), self)
end

#blobsObject


214
215
216
217
218
# File 'app/models/snippet.rb', line 214

def blobs
  return [] unless repository_exists?

  repository.ls_files(repository.root_ref).map { |file| Blob.lazy(repository, repository.root_ref, file) }
end

#can_cache_field?(field) ⇒ Boolean

Returns:

  • (Boolean)

328
329
330
# File 'app/models/snippet.rb', line 328

def can_cache_field?(field)
  field != :content || MarkupHelper.gitlab_markdown?(file_name)
end

#check_for_spam?Boolean

Returns:

  • (Boolean)

244
245
246
247
# File 'app/models/snippet.rb', line 244

def check_for_spam?
  visibility_level_changed?(to: Snippet::PUBLIC) ||
    (public? && (title_changed? || content_changed?))
end

#content_html_invalidated?Boolean

Returns:

  • (Boolean)

37
38
39
# File 'app/models/snippet.rb', line 37

def content_html_invalidated?
  default_content_html_invalidator || file_name_changed?
end

#create_repositoryObject


316
317
318
319
320
321
# File 'app/models/snippet.rb', line 316

def create_repository
  return if repository_exists? && snippet_repository

  repository.create_if_not_exists
  track_snippet_repository(repository.storage)
end

#default_content_html_invalidatorObject

If file_name changes, it invalidates content


36
# File 'app/models/snippet.rb', line 36

alias_method :default_content_html_invalidator, :content_html_invalidated?

#embeddable?Boolean

Returns:

  • (Boolean)

236
237
238
# File 'app/models/snippet.rb', line 236

def embeddable?
  Ability.allowed?(nil, :read_snippet, self)
end

#file_nameObject


224
225
226
# File 'app/models/snippet.rb', line 224

def file_name
  super.to_s
end

#file_name_on_repoObject


336
337
338
339
340
# File 'app/models/snippet.rb', line 336

def file_name_on_repo
  return if repository.empty?

  list_files(repository.root_ref).first
end

#full_pathObject


300
301
302
303
304
305
306
307
308
309
310
# File 'app/models/snippet.rb', line 300

def full_path
  return unless persisted?

  @full_path ||= begin
    components = []
    components << project.full_path if project_id?
    components << '@snippets'
    components << self.id
    components.join('/')
  end
end

#hexdigestObject


332
333
334
# File 'app/models/snippet.rb', line 332

def hexdigest
  Digest::SHA256.hexdigest("#{title}#{description}#{created_at}#{updated_at}")
end

#hook_attrsObject


220
221
222
# File 'app/models/snippet.rb', line 220

def hook_attrs
  attributes
end

#list_files(ref = nil) ⇒ Object


342
343
344
345
346
# File 'app/models/snippet.rb', line 342

def list_files(ref = nil)
  return [] if repository.empty?

  repository.ls_files(ref)
end

#multiple_files?Boolean

Returns:

  • (Boolean)

348
349
350
# File 'app/models/snippet.rb', line 348

def multiple_files?
  list_files(repository.root_ref).size > 1
end

#notes_with_associationsObject


240
241
242
# File 'app/models/snippet.rb', line 240

def notes_with_associations
  notes.includes(:author)
end

#repositoryObject


277
278
279
# File 'app/models/snippet.rb', line 277

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

#repository_size_checkerObject


282
283
284
285
286
287
288
289
# File 'app/models/snippet.rb', line 282

def repository_size_checker
  strong_memoize(:repository_size_checker) do
    ::Gitlab::RepositorySizeChecker.new(
      current_size_proc: -> { repository.size.megabytes },
      limit: Gitlab::CurrentSettings.snippet_size_limit
    )
  end
end

#repository_storageObject


312
313
314
# File 'app/models/snippet.rb', line 312

def repository_storage
  snippet_repository&.shard_name || self.class.pick_repository_storage
end

#spammable_entity_typeObject


255
256
257
# File 'app/models/snippet.rb', line 255

def spammable_entity_type
  'snippet'
end

#storageObject


292
293
294
# File 'app/models/snippet.rb', line 292

def storage
  @storage ||= Storage::Hashed.new(self, prefix: Storage::Hashed::SNIPPET_REPOSITORY_PATH_PREFIX)
end

#to_ability_nameObject


259
260
261
# File 'app/models/snippet.rb', line 259

def to_ability_name
  'snippet'
end

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


200
201
202
203
204
205
206
207
208
# File 'app/models/snippet.rb', line 200

def to_reference(from = nil, full: false)
  reference = "#{self.class.reference_prefix}#{id}"

  if project.present?
    "#{project.to_reference_base(from, full: full)}#{reference}"
  else
    reference
  end
end

#track_snippet_repository(shard) ⇒ Object


323
324
325
326
# File 'app/models/snippet.rb', line 323

def track_snippet_repository(shard)
  snippet_repo = snippet_repository || build_snippet_repository
  snippet_repo.update!(shard_name: shard, disk_path: disk_path)
end

#valid_secret_token?(token) ⇒ Boolean

Returns:

  • (Boolean)

263
264
265
266
267
# File 'app/models/snippet.rb', line 263

def valid_secret_token?(token)
  return false unless token && secret_token

  ActiveSupport::SecurityUtils.secure_compare(token.to_s, secret_token.to_s)
end

#visibility_level_fieldObject


232
233
234
# File 'app/models/snippet.rb', line 232

def visibility_level_field
  :visibility_level
end