entities.rb 39.4 KB
Newer Older
1
module API
N
Nihad Abbasov 已提交
2
  module Entities
B
blackst0ne 已提交
3 4 5 6 7 8 9 10 11 12
    class WikiPageBasic < Grape::Entity
      expose :format
      expose :slug
      expose :title
    end

    class WikiPage < WikiPageBasic
      expose :content
    end

13
    class UserSafe < Grape::Entity
14
      expose :id, :name, :username
15
    end
16

17
    class UserBasic < UserSafe
18
      expose :state
19

20 21 22
      expose :avatar_url do |user, options|
        user.avatar_url(only_path: false)
      end
D
Douwe Maan 已提交
23

24
      expose :avatar_path, if: ->(user, options) { options.fetch(:only_path, false) && user.avatar_path }
25
      expose :custom_attributes, using: 'API::Entities::CustomAttribute', if: :with_custom_attributes
26

D
Douwe Maan 已提交
27
      expose :web_url do |user, options|
28
        Gitlab::Routing.url_helpers.user_url(user)
D
Douwe Maan 已提交
29
      end
N
Nihad Abbasov 已提交
30
    end
N
Nihad Abbasov 已提交
31

32 33
    class User < UserBasic
      expose :created_at
34
      expose :bio, :location, :skype, :linkedin, :twitter, :website_url, :organization
35 36
    end

37 38
    class UserActivity < Grape::Entity
      expose :username
39 40
      expose :last_activity_on
      expose :last_activity_on, as: :last_activity_at # Back-compat
41 42
    end

43 44 45 46
    class Identity < Grape::Entity
      expose :provider, :extern_uid
    end

47
    class UserPublic < User
48 49
      expose :last_sign_in_at
      expose :confirmed_at
50
      expose :last_activity_on
51
      expose :email
52
      expose :theme_id, :color_scheme_id, :projects_limit, :current_sign_in_at
53
      expose :identities, using: Entities::Identity
54 55
      expose :can_create_group?, as: :can_create_group
      expose :can_create_project?, as: :can_create_project
56
      expose :two_factor_enabled?, as: :two_factor_enabled
57
      expose :external
58 59
    end

60
    class UserWithAdmin < UserPublic
61
      expose :admin?, as: :is_admin
62 63
    end

64 65 66 67
    class Email < Grape::Entity
      expose :id, :email
    end

M
miks 已提交
68
    class Hook < Grape::Entity
69
      expose :id, :url, :created_at, :push_events, :tag_push_events, :merge_requests_events, :repository_update_events
70
      expose :enable_ssl_verification
M
miks 已提交
71 72
    end

73
    class ProjectHook < Hook
74
      expose :project_id, :issues_events, :confidential_issues_events
75
      expose :note_events, :pipeline_events, :wiki_page_events
76
      expose :job_events
77 78
    end

79 80 81 82 83 84 85 86
    class SharedGroup < Grape::Entity
      expose :group_id
      expose :group_name do |group_link, options|
        group_link.group.name
      end
      expose :group_access, as: :group_access_level
    end

T
Tomasz Maczukin 已提交
87 88
    class ProjectIdentity < Grape::Entity
      expose :id, :description
89 90
      expose :name, :name_with_namespace
      expose :path, :path_with_namespace
T
Tomasz Maczukin 已提交
91 92 93
      expose :created_at
    end

T
Travis Miller 已提交
94 95 96 97
    class ProjectExportStatus < ProjectIdentity
      include ::API::Helpers::RelatedResourcesHelpers

      expose :export_status
98
      expose :_links, if: lambda { |project, _options| project.export_status == :finished } do
T
Travis Miller 已提交
99 100 101 102 103 104 105 106 107 108
        expose :api_url do |project|
          expose_url(api_v4_projects_export_download_path(id: project.id))
        end

        expose :web_url do |project|
          Gitlab::Routing.url_helpers.download_export_project_url(project)
        end
      end
    end

J
James Lopez 已提交
109 110
    class ProjectImportStatus < ProjectIdentity
      expose :import_status
J
James Lopez 已提交
111 112 113

      # TODO: Use `expose_nil` once we upgrade the grape-entity gem
      expose :import_error, if: lambda { |status, _ops| status.import_error }
J
James Lopez 已提交
114 115
    end

F
Francisco Lopez 已提交
116
    class BasicProjectDetails < ProjectIdentity
F
Francisco Lopez 已提交
117 118 119 120 121 122 123 124 125 126 127
      include ::API::ProjectsRelationBuilder

      expose :default_branch
      # Avoids an N+1 query: https://github.com/mbleigh/acts-as-taggable-on/issues/91#issuecomment-168273770
      expose :tag_list do |project|
        # project.tags.order(:name).pluck(:name) is the most suitable option
        # to avoid loading all the ActiveRecord objects but, if we use it here
        # it override the preloaded associations and makes a query
        # (fixed in https://github.com/rails/rails/pull/25976).
        project.tags.map(&:name).sort
      end
T
Tomasz Maczukin 已提交
128
      expose :ssh_url_to_repo, :http_url_to_repo, :web_url
129 130 131
      expose :avatar_url do |project, options|
        project.avatar_url(only_path: false)
      end
132
      expose :star_count, :forks_count
F
Francisco Lopez 已提交
133
      expose :last_activity_at
134

135 136
      expose :custom_attributes, using: 'API::Entities::CustomAttribute', if: :with_custom_attributes

137
      def self.preload_relation(projects_relation, options =  {})
138 139 140 141
        projects_relation.preload(:project_feature, :route)
                         .preload(namespace: [:route, :owner],
                                  tags: :taggings)
      end
142 143
    end

144
    class Project < BasicProjectDetails
145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176
      include ::API::Helpers::RelatedResourcesHelpers

      expose :_links do
        expose :self do |project|
          expose_url(api_v4_projects_path(id: project.id))
        end

        expose :issues, if: -> (*args) { issues_available?(*args) } do |project|
          expose_url(api_v4_projects_issues_path(id: project.id))
        end

        expose :merge_requests, if: -> (*args) { mrs_available?(*args) } do |project|
          expose_url(api_v4_projects_merge_requests_path(id: project.id))
        end

        expose :repo_branches do |project|
          expose_url(api_v4_projects_repository_branches_path(id: project.id))
        end

        expose :labels do |project|
          expose_url(api_v4_projects_labels_path(id: project.id))
        end

        expose :events do |project|
          expose_url(api_v4_projects_events_path(id: project.id))
        end

        expose :members do |project|
          expose_url(api_v4_projects_members_path(id: project.id))
        end
      end

177
      expose :archived?, as: :archived
178
      expose :visibility
179
      expose :owner, using: Entities::UserBasic, unless: ->(project, options) { project.group }
180
      expose :resolve_outdated_diff_discussions
F
Felipe Artur 已提交
181 182 183
      expose :container_registry_enabled

      # Expose old field names with the new permissions methods to keep API compatible
184 185 186
      expose(:issues_enabled) { |project, options| project.feature_available?(:issues, options[:current_user]) }
      expose(:merge_requests_enabled) { |project, options| project.feature_available?(:merge_requests, options[:current_user]) }
      expose(:wiki_enabled) { |project, options| project.feature_available?(:wiki, options[:current_user]) }
187
      expose(:jobs_enabled) { |project, options| project.feature_available?(:builds, options[:current_user]) }
188
      expose(:snippets_enabled) { |project, options| project.feature_available?(:snippets, options[:current_user]) }
F
Felipe Artur 已提交
189

190 191
      expose :shared_runners_enabled
      expose :lfs_enabled?, as: :lfs_enabled
192
      expose :creator_id
193
      expose :namespace, using: 'API::Entities::NamespaceBasic'
194
      expose :forked_from_project, using: Entities::BasicProjectDetails, if: lambda { |project, options| project.forked? }
195 196
      expose :import_status
      expose :import_error, if: lambda { |_project, options| options[:user_can_admin_project] }
197

198
      expose :open_issues_count, if: lambda { |project, options| project.feature_available?(:issues, options[:current_user]) }
199
      expose :runners_token, if: lambda { |_project, options| options[:user_can_admin_project] }
200
      expose :public_builds, as: :public_jobs
201
      expose :ci_config_path
202
      expose :shared_with_groups do |project, options|
203
        SharedGroup.represent(project.project_group_links, options)
204
      end
J
James Lopez 已提交
205
      expose :only_allow_merge_if_pipeline_succeeds
206
      expose :request_access_enabled
207
      expose :only_allow_merge_if_all_discussions_are_resolved
208
      expose :printing_merge_request_link_enabled
M
Markus Koller 已提交
209 210

      expose :statistics, using: 'API::Entities::ProjectStatistics', if: :statistics
211 212

      def self.preload_relation(projects_relation, options =  {})
213 214 215 216 217
        super(projects_relation).preload(:group)
                                .preload(project_group_links: :group,
                                         fork_network: :root_project,
                                         forked_project_link: :forked_from_project,
                                         forked_from_project: [:route, :forks, namespace: :route, tags: :taggings])
218 219 220
      end

      def self.forks_counting_projects(projects_relation)
221
        projects_relation + projects_relation.map(&:forked_from_project).compact
222
      end
M
Markus Koller 已提交
223 224 225 226 227 228 229
    end

    class ProjectStatistics < Grape::Entity
      expose :commit_count
      expose :storage_size
      expose :repository_size
      expose :lfs_objects_size
230
      expose :build_artifacts_size, as: :job_artifacts_size
N
Nihad Abbasov 已提交
231 232
    end

233 234 235 236
    class Member < Grape::Entity
      expose :user, merge: true, using: UserBasic
      expose :access_level
      expose :expires_at
237 238
    end

239 240 241
    class AccessRequester < Grape::Entity
      expose :user, merge: true, using: UserBasic
      expose :requested_at
M
miks 已提交
242 243
    end

244
    class Group < Grape::Entity
245
      expose :id, :name, :path, :description, :visibility
246
      expose :lfs_enabled?, as: :lfs_enabled
247 248
      expose :avatar_url do |group, options|
        group.avatar_url(only_path: false)
249
      end
R
Rémy Coutable 已提交
250
      expose :web_url
251
      expose :request_access_enabled
252
      expose :full_name, :full_path
253 254 255 256

      if ::Group.supports_nested_groups?
        expose :parent_id
      end
M
Markus Koller 已提交
257

258 259
      expose :custom_attributes, using: 'API::Entities::CustomAttribute', if: :with_custom_attributes

M
Markus Koller 已提交
260 261 262 263 264
      expose :statistics, if: :statistics do
        with_options format_with: -> (value) { value.to_i } do
          expose :storage_size
          expose :repository_size
          expose :lfs_objects_size
265
          expose :build_artifacts_size, as: :job_artifacts_size
M
Markus Koller 已提交
266 267
        end
      end
268
    end
A
Andrew8xx8 已提交
269

270
    class GroupDetail < Group
271 272 273 274 275 276 277 278 279 280 281 282 283 284 285
      expose :projects, using: Entities::Project do |group, options|
        GroupProjectsFinder.new(
          group: group,
          current_user: options[:current_user],
          options: { only_owned: true }
        ).execute
      end

      expose :shared_projects, using: Entities::Project do |group, options|
        GroupProjectsFinder.new(
          group: group,
          current_user: options[:current_user],
          options: { only_shared: true }
        ).execute
      end
286 287
    end

288
    class Commit < Grape::Entity
289 290 291 292 293 294 295
      expose :id, :short_id, :title, :created_at
      expose :parent_ids
      expose :safe_message, as: :message
      expose :author_name, :author_email, :authored_date
      expose :committer_name, :committer_email, :committed_date
    end

296
    class CommitStats < Grape::Entity
297 298 299
      expose :additions, :deletions, :total
    end

300
    class CommitDetail < Commit
301
      expose :stats, using: Entities::CommitStats, if: :stats
302
      expose :status
303
      expose :last_pipeline, using: 'API::Entities::PipelineBasic'
304
      expose :project_id
305 306
    end

307
    class BasicRef < Grape::Entity
308
      expose :type, :name
309 310
    end

R
Robert Schilling 已提交
311
    class Branch < Grape::Entity
312 313
      expose :name

314
      expose :commit, using: Entities::Commit do |repo_branch, options|
315
        options[:project].repository.commit(repo_branch.dereferenced_target)
316 317
      end

R
Robert Schilling 已提交
318
      expose :merged do |repo_branch, options|
319 320 321 322 323
        if options[:merged_branch_names]
          options[:merged_branch_names].include?(repo_branch.name)
        else
          options[:project].repository.merged_to_root_ref?(repo_branch)
        end
R
Robert Schilling 已提交
324 325
      end

326
      expose :protected do |repo_branch, options|
E
Eric 已提交
327
        ::ProtectedBranch.protected?(options[:project], repo_branch.name)
328 329
      end

330
      expose :developers_can_push do |repo_branch, options|
331
        options[:project].protected_branches.developers_can?(:push, repo_branch.name)
332
      end
333

334
      expose :developers_can_merge do |repo_branch, options|
335
        options[:project].protected_branches.developers_can?(:merge, repo_branch.name)
336
      end
N
Nihad Abbasov 已提交
337
    end
N
Nihad Abbasov 已提交
338

339
    class TreeObject < Grape::Entity
340
      expose :id, :name, :type, :path
341 342

      expose :mode do |obj, options|
M
mhasbini 已提交
343
        filemode = obj.mode
344 345 346 347 348
        filemode = "0" + filemode if filemode.length < 6
        filemode
      end
    end

J
Jarka Kadlecová 已提交
349
    class Snippet < Grape::Entity
350
      expose :id, :title, :file_name, :description
351
      expose :author, using: Entities::UserBasic
R
Robert Speicher 已提交
352
      expose :updated_at, :created_at
J
Jarka Kadlecová 已提交
353 354
      expose :project_id
      expose :web_url do |snippet|
355 356
        Gitlab::UrlBuilder.build(snippet)
      end
N
Nihad Abbasov 已提交
357
    end
N
Nihad Abbasov 已提交
358

J
Jarka Kadlecová 已提交
359 360
    class ProjectSnippet < Snippet
    end
361

J
Jarka Kadlecová 已提交
362
    class PersonalSnippet < Snippet
363 364 365 366 367
      expose :raw_url do |snippet|
        Gitlab::UrlBuilder.build(snippet) + "/raw"
      end
    end

368 369
    class ProjectEntity < Grape::Entity
      expose :id, :iid
F
Felipe Artur 已提交
370
      expose(:project_id) { |entity| entity&.project.try(:id) }
371 372
      expose :title, :description
      expose :state, :created_at, :updated_at
373 374
    end

375
    class Diff < Grape::Entity
M
micael.bergeron 已提交
376
      expose :old_path, :new_path, :a_mode, :b_mode
377 378 379
      expose :new_file?, as: :new_file
      expose :renamed_file?, as: :renamed_file
      expose :deleted_file?, as: :deleted_file
380
      expose :json_safe_diff, as: :diff
381 382
    end

E
Eric 已提交
383 384 385 386 387 388 389 390 391 392 393 394 395
    class ProtectedRefAccess < Grape::Entity
      expose :access_level
      expose :access_level_description do |protected_ref_access|
        protected_ref_access.humanize
      end
    end

    class ProtectedBranch < Grape::Entity
      expose :name
      expose :push_access_levels, using: Entities::ProtectedRefAccess
      expose :merge_access_levels, using: Entities::ProtectedRefAccess
    end

F
Felipe Artur 已提交
396 397
    class Milestone < Grape::Entity
      expose :id, :iid
F
Felipe Artur 已提交
398 399
      expose :project_id, if: -> (entity, options) { entity&.project_id }
      expose :group_id, if: -> (entity, options) { entity&.group_id }
F
Felipe Artur 已提交
400 401
      expose :title, :description
      expose :state, :created_at, :updated_at
402
      expose :due_date
V
Valery Sizov 已提交
403
      expose :start_date
N
Nihad Abbasov 已提交
404 405
    end

406
    class IssueBasic < ProjectEntity
407
      expose :closed_at
408 409 410 411
      expose :labels do |issue, options|
        # Avoids an N+1 query since labels are preloaded
        issue.labels.map(&:title).sort
      end
412
      expose :milestone, using: Entities::Milestone
413 414 415 416 417
      expose :assignees, :author, using: Entities::UserBasic

      expose :assignee, using: ::API::Entities::UserBasic do |issue, options|
        issue.assignees.first
      end
418

Z
Z.J. van de Weg 已提交
419
      expose :user_notes_count
420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435
      expose :upvotes do |issue, options|
        if options[:issuable_metadata]
          # Avoids an N+1 query when metadata is included
          options[:issuable_metadata][issue.id].upvotes
        else
          issue.upvotes
        end
      end
      expose :downvotes do |issue, options|
        if options[:issuable_metadata]
          # Avoids an N+1 query when metadata is included
          options[:issuable_metadata][issue.id].downvotes
        else
          issue.downvotes
        end
      end
436
      expose :due_date
437
      expose :confidential
438
      expose :discussion_locked
439 440 441 442

      expose :web_url do |issue, options|
        Gitlab::UrlBuilder.build(issue)
      end
443 444 445 446

      expose :time_stats, using: 'API::Entities::IssuableTimeStats' do |issue|
        issue
      end
N
Nihad Abbasov 已提交
447
    end
A
Alex Denisov 已提交
448

449
    class Issue < IssueBasic
450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469
      include ::API::Helpers::RelatedResourcesHelpers

      expose :_links do
        expose :self do |issue|
          expose_url(api_v4_project_issue_path(id: issue.project_id, issue_iid: issue.iid))
        end

        expose :notes do |issue|
          expose_url(api_v4_projects_issues_notes_path(id: issue.project_id, noteable_id: issue.iid))
        end

        expose :award_emoji do |issue|
          expose_url(api_v4_projects_issues_award_emoji_path(id: issue.project_id, issue_iid: issue.iid))
        end

        expose :project do |issue|
          expose_url(api_v4_projects_path(id: issue.project_id))
        end
      end

470 471 472 473 474
      expose :subscribed do |issue, options|
        issue.subscribed?(options[:current_user], options[:project] || issue.project)
      end
    end

475
    class IssuableTimeStats < Grape::Entity
476 477 478 479
      format_with(:time_tracking_formatter) do |time_spent|
        Gitlab::TimeTrackingFormatter.output(time_spent)
      end

480 481 482
      expose :time_estimate
      expose :total_time_spent
      expose :human_time_estimate
483 484 485 486 487 488 489 490 491

      with_options(format_with: :time_tracking_formatter) do
        expose :total_time_spent, as: :human_total_time_spent
      end

      def total_time_spent
        # Avoids an N+1 query since timelogs are preloaded
        object.timelogs.map(&:time_spent).sum
      end
492 493
    end

494 495 496 497 498
    class ExternalIssue < Grape::Entity
      expose :title
      expose :id
    end

H
haseeb 已提交
499 500 501 502
    class PipelineBasic < Grape::Entity
      expose :id, :sha, :ref, :status
    end

S
Stan Hu 已提交
503 504 505 506 507 508 509
    class MergeRequestSimple < ProjectEntity
      expose :title
      expose :web_url do |merge_request, options|
        Gitlab::UrlBuilder.build(merge_request)
      end
    end

510
    class MergeRequestBasic < ProjectEntity
V
Valery Sizov 已提交
511
      expose :target_branch, :source_branch
512 513 514 515 516 517 518 519 520 521 522 523 524 525
      expose :upvotes do |merge_request, options|
        if options[:issuable_metadata]
          options[:issuable_metadata][merge_request.id].upvotes
        else
          merge_request.upvotes
        end
      end
      expose :downvotes do |merge_request, options|
        if options[:issuable_metadata]
          options[:issuable_metadata][merge_request.id].downvotes
        else
          merge_request.downvotes
        end
      end
526 527
      expose :author, :assignee, using: Entities::UserBasic
      expose :source_project_id, :target_project_id
528 529 530 531
      expose :labels do |merge_request, options|
        # Avoids an N+1 query since labels are preloaded
        merge_request.labels.map(&:title).sort
      end
B
Ben Boeckel 已提交
532
      expose :work_in_progress?, as: :work_in_progress
533
      expose :milestone, using: Entities::Milestone
J
James Lopez 已提交
534
      expose :merge_when_pipeline_succeeds
535 536 537 538 539 540

      # Ideally we should deprecate `MergeRequest#merge_status` exposure and
      # use `MergeRequest#mergeable?` instead (boolean).
      # See https://gitlab.com/gitlab-org/gitlab-ce/issues/42344 for more
      # information.
      expose :merge_status do |merge_request|
541 542
        merge_request.check_if_can_be_merged
        merge_request.merge_status
543
      end
544 545
      expose :diff_head_sha, as: :sha
      expose :merge_commit_sha
Z
Z.J. van de Weg 已提交
546
      expose :user_notes_count
547
      expose :discussion_locked
548 549
      expose :should_remove_source_branch?, as: :should_remove_source_branch
      expose :force_remove_source_branch?, as: :force_remove_source_branch
550
      expose :allow_maintainer_to_push, if: -> (merge_request, _) { merge_request.for_fork? }
551 552 553 554

      expose :web_url do |merge_request, options|
        Gitlab::UrlBuilder.build(merge_request)
      end
555 556 557 558

      expose :time_stats, using: 'API::Entities::IssuableTimeStats' do |merge_request|
        merge_request
      end
A
Alex Denisov 已提交
559
    end
V
Valeriy Sizov 已提交
560

561 562 563 564
    class MergeRequest < MergeRequestBasic
      expose :subscribed do |merge_request, options|
        merge_request.subscribed?(options[:current_user], options[:project])
      end
565 566 567 568

      expose :changes_count do |merge_request, _options|
        merge_request.merge_request_diff.real_size
      end
H
haseeb 已提交
569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604

      expose :merged_by, using: Entities::UserBasic do |merge_request, _options|
        merge_request.metrics&.merged_by
      end

      expose :merged_at do |merge_request, _options|
        merge_request.metrics&.merged_at
      end

      expose :closed_by, using: Entities::UserBasic do |merge_request, _options|
        merge_request.metrics&.latest_closed_by
      end

      expose :closed_at do |merge_request, _options|
        merge_request.metrics&.latest_closed_at
      end

      expose :latest_build_started_at, if: -> (_, options) { build_available?(options) } do |merge_request, _options|
        merge_request.metrics&.latest_build_started_at
      end

      expose :latest_build_finished_at, if: -> (_, options) { build_available?(options) } do |merge_request, _options|
        merge_request.metrics&.latest_build_finished_at
      end

      expose :first_deployed_to_production_at, if: -> (_, options) { build_available?(options) } do |merge_request, _options|
        merge_request.metrics&.first_deployed_to_production_at
      end

      expose :pipeline, using: Entities::PipelineBasic, if: -> (_, options) { build_available?(options) } do |merge_request, _options|
        merge_request.metrics&.pipeline
      end

      def build_available?(options)
        options[:project]&.feature_available?(:builds, options[:current_user])
      end
605 606
    end

607
    class MergeRequestChanges < MergeRequest
608
      expose :diffs, as: :changes, using: Entities::Diff do |compare, _|
D
Douwe Maan 已提交
609
        compare.raw_diffs(limits: false).to_a
610 611 612
      end
    end

613 614 615
    class MergeRequestDiff < Grape::Entity
      expose :id, :head_commit_sha, :base_commit_sha, :start_commit_sha,
        :created_at, :merge_request_id, :state, :real_size
616
    end
617

618
    class MergeRequestDiffFull < MergeRequestDiff
619
      expose :commits, using: Entities::Commit
620

621
      expose :diffs, using: Entities::Diff do |compare, _|
D
Douwe Maan 已提交
622
        compare.raw_diffs(limits: false).to_a
623 624 625
      end
    end

626
    class SSHKey < Grape::Entity
627
      expose :id, :title, :key, :created_at
V
Valeriy Sizov 已提交
628
    end
629

630
    class SSHKeyWithUser < SSHKey
631
      expose :user, using: Entities::UserPublic
632 633
    end

634 635 636 637 638
    class DeployKeysProject < Grape::Entity
      expose :deploy_key, merge: true, using: Entities::SSHKey
      expose :can_push
    end

R
Robert Schilling 已提交
639 640 641 642
    class GPGKey < Grape::Entity
      expose :id, :key, :created_at
    end

643
    class Note < Grape::Entity
S
sue445 已提交
644 645 646
      # Only Issue and MergeRequest have iid
      NOTEABLE_TYPES_WITH_IID = %w(Issue MergeRequest).freeze

647
      expose :id
J
Jan Provaznik 已提交
648
      expose :type
649
      expose :note, as: :body
650
      expose :attachment_identifier, as: :attachment
651
      expose :author, using: Entities::UserBasic
652
      expose :created_at, :updated_at
653
      expose :system?, as: :system
D
Dmitriy Zaporozhets 已提交
654
      expose :noteable_id, :noteable_type
S
sue445 已提交
655 656 657

      # Avoid N+1 queries as much as possible
      expose(:noteable_iid) { |note| note.noteable.iid if NOTEABLE_TYPES_WITH_IID.include?(note.noteable_type) }
658
    end
659

J
Jan Provaznik 已提交
660 661 662 663 664 665
    class Discussion < Grape::Entity
      expose :id
      expose :individual_note?, as: :individual_note
      expose :notes, using: Entities::Note
    end

Z
Z.J. van de Weg 已提交
666 667 668 669 670 671 672 673
    class AwardEmoji < Grape::Entity
      expose :id
      expose :name
      expose :user, using: Entities::UserBasic
      expose :created_at, :updated_at
      expose :awardable_id, :awardable_type
    end

674 675 676 677
    class MRNote < Grape::Entity
      expose :note
      expose :author, using: Entities::UserBasic
    end
D
Dmitriy Zaporozhets 已提交
678

679 680
    class CommitNote < Grape::Entity
      expose :note
681 682 683
      expose(:path) { |note| note.diff_file.try(:file_path) if note.diff_note? }
      expose(:line) { |note| note.diff_line.try(:new_line) if note.diff_note? }
      expose(:line_type) { |note| note.diff_line.try(:type) if note.diff_note? }
684
      expose :author, using: Entities::UserBasic
685
      expose :created_at
686 687
    end

K
Kamil Trzcinski 已提交
688 689
    class CommitStatus < Grape::Entity
      expose :id, :sha, :ref, :status, :name, :target_url, :description,
690
             :created_at, :started_at, :finished_at, :allow_failure, :coverage
K
Kamil Trzcinski 已提交
691
      expose :author, using: Entities::UserBasic
K
Kamil Trzcinski 已提交
692 693
    end

694 695 696 697 698
    class PushEventPayload < Grape::Entity
      expose :commit_count, :action, :ref_type, :commit_from, :commit_to
      expose :ref, :commit_title
    end

D
Dmitriy Zaporozhets 已提交
699
    class Event < Grape::Entity
700
      expose :project_id, :action_name
S
sue445 已提交
701
      expose :target_id, :target_iid, :target_type, :author_id
702
      expose :target_title
703
      expose :created_at
D
Dmitriy Zaporozhets 已提交
704 705
      expose :note, using: Entities::Note, if: ->(event, options) { event.note? }
      expose :author, using: Entities::UserBasic, if: ->(event, options) { event.author }
706

707 708 709 710 711
      expose :push_event_payload,
        as: :push_data,
        using: PushEventPayload,
        if: -> (event, _) { event.push? }

712
      expose :author_username do |event, options|
Z
Z.J. van de Weg 已提交
713
        event.author&.username
714
      end
D
Dmitriy Zaporozhets 已提交
715
    end
716

717
    class ProjectGroupLink < Grape::Entity
718
      expose :id, :project_id, :group_id, :group_access, :expires_at
719 720
    end

D
Douglas Barbosa Alexandre 已提交
721 722 723 724
    class Todo < Grape::Entity
      expose :id
      expose :project, using: Entities::BasicProjectDetails
      expose :author, using: Entities::UserBasic
R
Robert Schilling 已提交
725
      expose :action_name
D
Douglas Barbosa Alexandre 已提交
726
      expose :target_type
727 728

      expose :target do |todo, options|
729
        Entities.const_get(todo.target_type).represent(todo.target, options)
D
Douglas Barbosa Alexandre 已提交
730 731 732 733 734
      end

      expose :target_url do |todo, options|
        target_type   = todo.target_type.underscore
        target_url    = "namespace_project_#{target_type}_url"
735
        target_anchor = "note_#{todo.note_id}" if todo.note_id?
D
Douglas Barbosa Alexandre 已提交
736

737 738 739
        Gitlab::Routing
          .url_helpers
          .public_send(target_url, todo.project.namespace, todo.project, todo.target, anchor: target_anchor) # rubocop:disable GitlabSecurity/PublicSend
D
Douglas Barbosa Alexandre 已提交
740 741 742 743 744 745 746
      end

      expose :body
      expose :state
      expose :created_at
    end

747
    class NamespaceBasic < Grape::Entity
748
      expose :id, :name, :path, :kind, :full_path, :parent_id
749
    end
750

751
    class Namespace < NamespaceBasic
752 753 754 755 756 757
      expose :members_count_with_descendants, if: -> (namespace, opts) { expose_members_count_with_descendants?(namespace, opts) } do |namespace, _|
        namespace.users_with_descendants.count
      end

      def expose_members_count_with_descendants?(namespace, opts)
        namespace.kind == 'group' && Ability.allowed?(opts[:current_user], :admin_group, namespace)
758
      end
759
    end
760

761
    class MemberAccess < Grape::Entity
D
Dmitriy Zaporozhets 已提交
762
      expose :access_level
763
      expose :notification_level do |member, options|
764 765 766
        if member.notification_setting
          ::NotificationSetting.levels[member.notification_setting.level]
        end
767
      end
768 769
    end

770
    class ProjectAccess < MemberAccess
771 772
    end

773
    class GroupAccess < MemberAccess
774 775
    end

776 777 778 779 780 781 782 783 784 785 786 787 788 789 790
    class NotificationSetting < Grape::Entity
      expose :level
      expose :events, if: ->(notification_setting, _) { notification_setting.custom? } do
        ::NotificationSetting::EMAIL_EVENTS.each do |event|
          expose event
        end
      end
    end

    class GlobalNotificationSetting < NotificationSetting
      expose :notification_email do |notification_setting, options|
        notification_setting.user.notification_email
      end
    end

791 792
    class ProjectService < Grape::Entity
      expose :id, :title, :created_at, :updated_at, :active
793 794 795
      expose :push_events, :issues_events, :confidential_issues_events
      expose :merge_requests_events, :tag_push_events, :note_events
      expose :pipeline_events, :wiki_page_events
796
      expose :job_events
797 798
      # Expose serialized properties
      expose :properties do |service, options|
S
Stan Hu 已提交
799
        service.properties.slice(*service.api_field_names)
800 801 802
      end
    end

803 804 805
    class ProjectWithAccess < Project
      expose :permissions do
        expose :project_access, using: Entities::ProjectAccess do |project, options|
806
          if options.key?(:project_members)
807 808 809
            (options[:project_members] || []).find { |member| member.source_id == project.id }
          else
            project.project_member(options[:current_user])
810
          end
811 812 813
        end

        expose :group_access, using: Entities::GroupAccess do |project, options|
814
          if project.group
815
            if options.key?(:group_members)
816 817 818
              (options[:group_members] || []).find { |member| member.source_id == project.namespace_id }
            else
              project.group.group_member(options[:current_user])
819
            end
820
          end
821 822
        end
      end
823 824 825 826 827 828 829 830 831 832 833 834 835 836

      def self.preload_relation(projects_relation, options = {})
        relation = super(projects_relation, options)

        unless options.key?(:group_members)
          relation = relation.preload(group: [group_members: [:source, user: [notification_settings: :source]]])
        end

        unless options.key?(:project_members)
          relation = relation.preload(project_members: [:source, user: [notification_settings: :source]])
        end

        relation
      end
837
    end
838

A
Andre Guedes 已提交
839
    class LabelBasic < Grape::Entity
R
Rares Sfirlogea 已提交
840
      expose :id, :name, :color, :description
A
Andre Guedes 已提交
841 842 843
    end

    class Label < LabelBasic
844
      expose :open_issues_count do |label, options|
F
Francesco Coda Zabetta 已提交
845 846
        label.open_issues_count(options[:current_user])
      end
847

F
Francesco Coda Zabetta 已提交
848 849 850
      expose :closed_issues_count do |label, options|
        label.closed_issues_count(options[:current_user])
      end
851

F
Francesco Coda Zabetta 已提交
852 853
      expose :open_merge_requests_count do |label, options|
        label.open_merge_requests_count(options[:current_user])
854 855
      end

856 857 858
      expose :priority do |label, options|
        label.priority(options[:project])
      end
859 860

      expose :subscribed do |label, options|
861
        label.subscribed?(options[:current_user], options[:project])
862
      end
863
    end
864

A
Andre Guedes 已提交
865 866 867 868 869 870 871 872
    class List < Grape::Entity
      expose :id
      expose :label, using: Entities::LabelBasic
      expose :position
    end

    class Board < Grape::Entity
      expose :id
F
Felipe Artur 已提交
873 874
      expose :project, using: Entities::BasicProjectDetails

A
Andre Guedes 已提交
875 876 877 878 879
      expose :lists, using: Entities::List do |board|
        board.lists.destroyable
      end
    end

880
    class Compare < Grape::Entity
881 882
      expose :commit, using: Entities::Commit do |compare, options|
        ::Commit.decorate(compare.commits, nil).last
883
      end
884

885 886
      expose :commits, using: Entities::Commit do |compare, options|
        ::Commit.decorate(compare.commits, nil)
887
      end
888

889
      expose :diffs, using: Entities::Diff do |compare, options|
D
Douwe Maan 已提交
890
        compare.diffs(limits: false).to_a
891
      end
892 893

      expose :compare_timeout do |compare, options|
J
Jacob Vosmaer 已提交
894
        compare.diffs.overflow?
895 896 897
      end

      expose :same, as: :compare_same_ref
898
    end
899 900 901 902

    class Contributor < Grape::Entity
      expose :name, :email, :commits, :additions, :deletions
    end
D
Douwe Maan 已提交
903 904 905 906

    class BroadcastMessage < Grape::Entity
      expose :message, :starts_at, :ends_at, :color, :font
    end
907 908 909

    class ApplicationSetting < Grape::Entity
      expose :id
910
      expose(*::ApplicationSettingsHelper.visible_attributes)
911 912 913 914 915 916
      expose(:restricted_visibility_levels) do |setting, _options|
        setting.restricted_visibility_levels.map { |level| Gitlab::VisibilityLevel.string_level(level) }
      end
      expose(:default_project_visibility) { |setting, _options| Gitlab::VisibilityLevel.string_level(setting.default_project_visibility) }
      expose(:default_snippet_visibility) { |setting, _options| Gitlab::VisibilityLevel.string_level(setting.default_snippet_visibility) }
      expose(:default_group_visibility) { |setting, _options| Gitlab::VisibilityLevel.string_level(setting.default_group_visibility) }
917 918 919 920

      # support legacy names, can be removed in v5
      expose :password_authentication_enabled_for_web, as: :password_authentication_enabled
      expose :password_authentication_enabled_for_web, as: :signin_enabled
921
    end
D
Dmitriy Zaporozhets 已提交
922 923

    class Release < Grape::Entity
924 925
      expose :tag, as: :tag_name
      expose :description
D
Dmitriy Zaporozhets 已提交
926
    end
927

R
Robert Schilling 已提交
928 929
    class Tag < Grape::Entity
      expose :name, :message
930

931
      expose :commit, using: Entities::Commit do |repo_tag, options|
932
        options[:project].repository.commit(repo_tag.dereferenced_target)
933 934
      end

935 936
      expose :release, using: Entities::Release do |repo_tag, options|
        options[:project].releases.find_by(tag: repo_tag.name)
937 938
      end
    end
K
Kamil Trzcinski 已提交
939

T
Tomasz Maczukin 已提交
940
    class Runner < Grape::Entity
T
Tomasz Maczukin 已提交
941 942 943 944 945
      expose :id
      expose :description
      expose :active
      expose :is_shared
      expose :name
946
      expose :online?, as: :online
947
      expose :status
T
Tomasz Maczukin 已提交
948 949
    end

950 951
    class RunnerDetails < Runner
      expose :tag_list
952
      expose :run_untagged
953
      expose :locked
954
      expose :maximum_timeout
S
Shinya Maeda 已提交
955
      expose :access_level
956
      expose :version, :revision, :platform, :architecture
957
      expose :contacted_at
B
blackst0ne 已提交
958
      expose :token, if: lambda { |runner, options| options[:current_user].admin? || !runner.is_shared? }
959
      expose :projects, with: Entities::BasicProjectDetails do |runner, options|
B
blackst0ne 已提交
960
        if options[:current_user].admin?
961 962
          runner.projects
        else
963
          options[:current_user].authorized_projects.where(id: runner.projects)
964 965
        end
      end
966 967
    end

968 969 970 971
    class RunnerRegistrationDetails < Grape::Entity
      expose :id, :token
    end

972
    class JobArtifactFile < Grape::Entity
973 974 975
      expose :filename, :size
    end

T
Tomasz Maczukin 已提交
976
    class JobBasic < Grape::Entity
T
Tomasz Maczukin 已提交
977
      expose :id, :status, :stage, :name, :ref, :tag, :coverage
T
Tomasz Maczukin 已提交
978
      expose :created_at, :started_at, :finished_at
M
Mehdi Lahmam 已提交
979
      expose :duration
T
Tomasz Maczukin 已提交
980
      expose :user, with: User
981
      expose :commit, with: Commit
982
      expose :pipeline, with: PipelineBasic
983
    end
984

T
Tomasz Maczukin 已提交
985 986 987 988 989 990
    class Job < JobBasic
      expose :artifacts_file, using: JobArtifactFile, if: -> (job, opts) { job.artifacts? }
      expose :runner, with: Runner
    end

    class JobBasicWithProject < JobBasic
T
Tomasz Maczukin 已提交
991 992 993
      expose :project, with: ProjectIdentity
    end

T
Tomasz Maczukin 已提交
994
    class Trigger < Grape::Entity
995
      expose :id
996
      expose :token, :description
997
      expose :created_at, :updated_at, :last_used
998
      expose :owner, using: Entities::UserBasic
T
Tomasz Maczukin 已提交
999
    end
1000

1001
    class Variable < Grape::Entity
T
Tomasz Maczukin 已提交
1002
      expose :key, :value
S
Shinya Maeda 已提交
1003
      expose :protected?, as: :protected, if: -> (entity, _) { entity.respond_to?(:protected?) }
1004
    end
1005

1006 1007
    class Pipeline < PipelineBasic
      expose :before_sha, :tag, :yaml_errors
Z
Z.J. van de Weg 已提交
1008 1009 1010 1011

      expose :user, with: Entities::UserBasic
      expose :created_at, :updated_at, :started_at, :finished_at, :committed_at
      expose :duration
1012
      expose :coverage
Z
Z.J. van de Weg 已提交
1013 1014
    end

1015 1016 1017
    class PipelineSchedule < Grape::Entity
      expose :id
      expose :description, :ref, :cron, :cron_timezone, :next_run_at, :active
1018
      expose :created_at, :updated_at
1019 1020 1021
      expose :owner, using: Entities::UserBasic
    end

S
Shinya Maeda 已提交
1022 1023
    class PipelineScheduleDetails < PipelineSchedule
      expose :last_pipeline, using: Entities::PipelineBasic
1024
      expose :variables, using: Entities::Variable
S
Shinya Maeda 已提交
1025 1026
    end

1027
    class EnvironmentBasic < Grape::Entity
N
Nick Thomas 已提交
1028
      expose :id, :name, :slug, :external_url
1029 1030
    end

1031
    class Environment < EnvironmentBasic
1032
      expose :project, using: Entities::BasicProjectDetails
Z
Z.J. van de Weg 已提交
1033 1034 1035 1036
    end

    class Deployment < Grape::Entity
      expose :id, :iid, :ref, :sha, :created_at
1037 1038
      expose :user,        using: Entities::UserBasic
      expose :environment, using: Entities::EnvironmentBasic
1039
      expose :deployable,  using: Entities::Job
1040 1041
    end

1042
    class License < Grape::Entity
1043 1044
      expose :key, :name, :nickname
      expose :featured, as: :popular
1045 1046 1047
      expose :url, as: :html_url
      expose(:source_url) { |license| license.meta['source'] }
      expose(:description) { |license| license.meta['description'] }
1048 1049 1050
      expose(:conditions) { |license| license.meta['conditions'] }
      expose(:permissions) { |license| license.meta['permissions'] }
      expose(:limitations) { |license| license.meta['limitations'] }
1051 1052
      expose :content
    end
1053

Z
ZJ van de Weg 已提交
1054
    class TemplatesList < Grape::Entity
1055 1056 1057
      expose :name
    end

Z
ZJ van de Weg 已提交
1058
    class Template < Grape::Entity
1059 1060
      expose :name, :content
    end
1061 1062 1063 1064 1065

    class BroadcastMessage < Grape::Entity
      expose :id, :message, :starts_at, :ends_at, :color, :font
      expose :active?, as: :active
    end
T
Tomasz Maczukin 已提交
1066

1067
    class PersonalAccessToken < Grape::Entity
1068 1069 1070 1071 1072 1073 1074
      expose :id, :name, :revoked, :created_at, :scopes
      expose :active?, as: :active
      expose :expires_at do |personal_access_token|
        personal_access_token.expires_at ? personal_access_token.expires_at.strftime("%Y-%m-%d") : nil
      end
    end

1075
    class PersonalAccessTokenWithToken < PersonalAccessToken
1076 1077
      expose :token
    end
1078 1079 1080 1081

    class ImpersonationToken < PersonalAccessTokenWithToken
      expose :impersonation
    end
1082

1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104
    class FeatureGate < Grape::Entity
      expose :key
      expose :value
    end

    class Feature < Grape::Entity
      expose :name
      expose :state
      expose :gates, using: FeatureGate do |model|
        model.gates.map do |gate|
          value = model.gate_values[gate.key]

          # By default all gate values are populated. Only show relevant ones.
          if (value.is_a?(Integer) && value.zero?) || (value.is_a?(Set) && value.empty?)
            next
          end

          { key: gate.key, value: value }
        end.compact
      end
    end

1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120
    module JobRequest
      class JobInfo < Grape::Entity
        expose :name, :stage
        expose :project_id, :project_name
      end

      class GitInfo < Grape::Entity
        expose :repo_url, :ref, :sha, :before_sha
        expose :ref_type do |model|
          if model.tag
            'tag'
          else
            'branch'
          end
        end
      end
T
Tomasz Maczukin 已提交
1121

1122 1123 1124
      class RunnerInfo < Grape::Entity
        expose :timeout
      end
T
Tomasz Maczukin 已提交
1125

1126
      class Step < Grape::Entity
T
Tomasz Maczukin 已提交
1127
        expose :name, :script, :timeout, :when, :allow_failure
1128
      end
T
Tomasz Maczukin 已提交
1129

1130
      class Image < Grape::Entity
1131 1132 1133
        expose :name, :entrypoint
      end

1134
      class Service < Image
1135
        expose :alias, :command
1136
      end
T
Tomasz Maczukin 已提交
1137

1138 1139
      class Artifacts < Grape::Entity
        expose :name, :untracked, :paths, :when, :expire_in
T
Tomasz Maczukin 已提交
1140 1141
      end

1142
      class Cache < Grape::Entity
1143
        expose :key, :untracked, :paths, :policy
T
Tomasz Maczukin 已提交
1144 1145
      end

1146 1147 1148
      class Credentials < Grape::Entity
        expose :type, :url, :username, :password
      end
T
Tomasz Maczukin 已提交
1149

1150
      class Dependency < Grape::Entity
T
Tomasz Maczukin 已提交
1151
        expose :id, :name, :token
1152
        expose :artifacts_file, using: JobArtifactFile, if: ->(job, _) { job.artifacts? }
1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174
      end

      class Response < Grape::Entity
        expose :id
        expose :token
        expose :allow_git_fetch

        expose :job_info, using: JobInfo do |model|
          model
        end

        expose :git_info, using: GitInfo do |model|
          model
        end

        expose :runner_info, using: RunnerInfo do |model|
          model
        end

        expose :variables
        expose :steps, using: Step
        expose :image, using: Image
1175
        expose :services, using: Service
1176 1177 1178
        expose :artifacts, using: Artifacts
        expose :cache, using: Cache
        expose :credentials, using: Credentials
T
Tomasz Maczukin 已提交
1179
        expose :dependencies, using: Dependency
1180
        expose :features
1181
      end
T
Tomasz Maczukin 已提交
1182
    end
1183 1184 1185 1186

    class UserAgentDetail < Grape::Entity
      expose :user_agent
      expose :ip_address
J
James Lopez 已提交
1187
      expose :submitted, as: :akismet_submitted
1188
    end
1189 1190 1191 1192 1193 1194

    class RepositoryStorageHealth < Grape::Entity
      expose :storage_name
      expose :failing_on_hosts
      expose :total_failures
    end
1195 1196 1197 1198 1199

    class CustomAttribute < Grape::Entity
      expose :key
      expose :value
    end
T
Travis Miller 已提交
1200

1201 1202 1203 1204 1205
    class PagesDomainCertificateExpiration < Grape::Entity
      expose :expired?, as: :expired
      expose :expiration
    end

T
Travis Miller 已提交
1206 1207 1208 1209 1210 1211 1212
    class PagesDomainCertificate < Grape::Entity
      expose :subject
      expose :expired?, as: :expired
      expose :certificate
      expose :certificate_text
    end

1213 1214 1215
    class PagesDomainBasic < Grape::Entity
      expose :domain
      expose :url
1216
      expose :project_id
1217 1218 1219 1220
      expose :verified?, as: :verified
      expose :verification_code, as: :verification_code
      expose :enabled_until

1221 1222 1223 1224 1225 1226 1227 1228
      expose :certificate,
        as: :certificate_expiration,
        if: ->(pages_domain, _) { pages_domain.certificate? },
        using: PagesDomainCertificateExpiration do |pages_domain|
        pages_domain
      end
    end

T
Travis Miller 已提交
1229 1230 1231
    class PagesDomain < Grape::Entity
      expose :domain
      expose :url
1232 1233 1234 1235
      expose :verified?, as: :verified
      expose :verification_code, as: :verification_code
      expose :enabled_until

T
Travis Miller 已提交
1236
      expose :certificate,
1237 1238
        if: ->(pages_domain, _) { pages_domain.certificate? },
        using: PagesDomainCertificate do |pages_domain|
T
Travis Miller 已提交
1239 1240 1241
        pages_domain
      end
    end
N
Nicolas MERELLI 已提交
1242 1243 1244 1245 1246

    class Application < Grape::Entity
      expose :uid, as: :application_id
      expose :redirect_uri, as: :callback_url
    end
1247 1248 1249 1250 1251

    # Use with care, this exposes the secret
    class ApplicationWithSecret < Application
      expose :secret
    end
J
Jarka Kadlecová 已提交
1252 1253 1254 1255 1256 1257 1258 1259

    class Blob < Grape::Entity
      expose :basename
      expose :data
      expose :filename
      expose :id
      expose :ref
      expose :startline
1260
      expose :project_id
J
Jarka Kadlecová 已提交
1261
    end
1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279

    class BasicBadgeDetails < Grape::Entity
      expose :link_url
      expose :image_url
      expose :rendered_link_url do |badge, options|
        badge.rendered_link_url(options.fetch(:project, nil))
      end
      expose :rendered_image_url do |badge, options|
        badge.rendered_image_url(options.fetch(:project, nil))
      end
    end

    class Badge < BasicBadgeDetails
      expose :id
      expose :kind do |badge|
        badge.type == 'ProjectBadge' ? 'project' : 'group'
      end
    end
N
Nihad Abbasov 已提交
1280 1281
  end
end