summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorFilipa Lacerda <filipa@gitlab.com>2017-05-07 15:00:58 +0100
committerFilipa Lacerda <filipa@gitlab.com>2017-05-07 15:00:58 +0100
commit842918602dbe622dc20593c0abea5293e304ac62 (patch)
treec748164aab8cfa43fe3332640c60e3308b4e9c29
parent214d7880c3d651b367eb73651a6e0e3046868287 (diff)
parent6ad3814e1b31bfacfae7a2aabb4e4607b12ca66f (diff)
downloadgitlab-ce-remove-old-isobject.tar.gz
Merge branch 'master' into remove-old-isobjectremove-old-isobject
* master: (226 commits) Real time pipeline show action Fix `Routable.find_by_full_path` on MySQL add CHANGELOG.md entry for !11138 add tooltips to user contrib graph key Use an absolute path for locale path in FastGettext config Colorize labels in issue search field Fix Karma failures for jQuery deferreds Reduce risk of deadlocks Fix failing spec and eslint Resolve discussions Resolve discussions Dry up routable lookups. Fixes #30317 Add “project moved” flash message on redirect Resolve discussions Fix Rubocop failures Index redirect_routes path for LIKE Add index for source association and for path Fix or workaround spec failure Refactor Delete conflicting redirects ...
-rw-r--r--GITLAB_PAGES_VERSION2
-rw-r--r--Gemfile1
-rw-r--r--Gemfile.lock1
-rw-r--r--app/assets/javascripts/autosave.js44
-rw-r--r--app/assets/javascripts/behaviors/gl_emoji/unicode_support_map.js17
-rw-r--r--app/assets/javascripts/blob/balsamiq/balsamiq_viewer.js114
-rw-r--r--app/assets/javascripts/blob/balsamiq_viewer.js6
-rw-r--r--app/assets/javascripts/blob/file_template_mediator.js6
-rw-r--r--app/assets/javascripts/blob/file_template_selector.js10
-rw-r--r--app/assets/javascripts/blob/target_branch_dropdown.js4
-rw-r--r--app/assets/javascripts/blob/template_selector.js7
-rw-r--r--app/assets/javascripts/blob/template_selectors/ci_yaml_selector.js2
-rw-r--r--app/assets/javascripts/blob/template_selectors/dockerfile_selector.js2
-rw-r--r--app/assets/javascripts/blob/template_selectors/gitignore_selector.js2
-rw-r--r--app/assets/javascripts/blob/template_selectors/license_selector.js13
-rw-r--r--app/assets/javascripts/blob/template_selectors/type_selector.js2
-rw-r--r--app/assets/javascripts/boards/boards_bundle.js2
-rw-r--r--app/assets/javascripts/boards/components/board_new_issue.js1
-rw-r--r--app/assets/javascripts/boards/components/board_sidebar.js61
-rw-r--r--app/assets/javascripts/boards/components/issue_card_inner.js104
-rw-r--r--app/assets/javascripts/boards/components/new_list_dropdown.js4
-rw-r--r--app/assets/javascripts/boards/models/assignee.js (renamed from app/assets/javascripts/boards/models/user.js)6
-rw-r--r--app/assets/javascripts/boards/models/issue.js32
-rw-r--r--app/assets/javascripts/dispatcher.js1
-rw-r--r--app/assets/javascripts/filtered_search/components/recent_searches_dropdown_content.js12
-rw-r--r--app/assets/javascripts/filtered_search/filtered_search_manager.js11
-rw-r--r--app/assets/javascripts/filtered_search/filtered_search_visual_tokens.js43
-rw-r--r--app/assets/javascripts/filtered_search/recent_searches_root.js7
-rw-r--r--app/assets/javascripts/filtered_search/services/recent_searches_service.js14
-rw-r--r--app/assets/javascripts/filtered_search/services/recent_searches_service_error.js11
-rw-r--r--app/assets/javascripts/gl_dropdown.js56
-rw-r--r--app/assets/javascripts/issuable/issuable_bundle.js1
-rw-r--r--app/assets/javascripts/issuable/time_tracking/components/collapsed_state.js42
-rw-r--r--app/assets/javascripts/issuable/time_tracking/components/comparison_pane.js70
-rw-r--r--app/assets/javascripts/issuable/time_tracking/components/estimate_only_pane.js14
-rw-r--r--app/assets/javascripts/issuable/time_tracking/components/help_state.js25
-rw-r--r--app/assets/javascripts/issuable/time_tracking/components/no_tracking_pane.js12
-rw-r--r--app/assets/javascripts/issuable/time_tracking/components/spent_only_pane.js14
-rw-r--r--app/assets/javascripts/issuable/time_tracking/components/time_tracker.js117
-rw-r--r--app/assets/javascripts/issuable/time_tracking/time_tracking_bundle.js66
-rw-r--r--app/assets/javascripts/issue_show/actions/tasks.js27
-rw-r--r--app/assets/javascripts/issue_show/index.js6
-rw-r--r--app/assets/javascripts/issue_show/issue_title.vue80
-rw-r--r--app/assets/javascripts/issue_show/issue_title_description.vue180
-rw-r--r--app/assets/javascripts/issue_status_select.js4
-rw-r--r--app/assets/javascripts/issues_bulk_assignment.js3
-rw-r--r--app/assets/javascripts/labels_select.js7
-rw-r--r--app/assets/javascripts/lib/utils/accessor.js47
-rw-r--r--app/assets/javascripts/lib/utils/ajax_cache.js32
-rw-r--r--app/assets/javascripts/main.js1
-rw-r--r--app/assets/javascripts/members.js4
-rw-r--r--app/assets/javascripts/milestone_select.js5
-rw-r--r--app/assets/javascripts/namespace_select.js3
-rw-r--r--app/assets/javascripts/notes.js2
-rw-r--r--app/assets/javascripts/project.js3
-rw-r--r--app/assets/javascripts/protected_branches/protected_branch_access_dropdown.js4
-rw-r--r--app/assets/javascripts/protected_branches/protected_branch_dropdown.js3
-rw-r--r--app/assets/javascripts/protected_tags/protected_tag_access_dropdown.js4
-rw-r--r--app/assets/javascripts/protected_tags/protected_tag_dropdown.js4
-rw-r--r--app/assets/javascripts/raven/index.js16
-rw-r--r--app/assets/javascripts/raven/raven_config.js100
-rw-r--r--app/assets/javascripts/sidebar/components/assignees/assignee_title.js41
-rw-r--r--app/assets/javascripts/sidebar/components/assignees/assignees.js224
-rw-r--r--app/assets/javascripts/sidebar/components/assignees/sidebar_assignees.js84
-rw-r--r--app/assets/javascripts/sidebar/components/time_tracking/collapsed_state.js97
-rw-r--r--app/assets/javascripts/sidebar/components/time_tracking/comparison_pane.js98
-rw-r--r--app/assets/javascripts/sidebar/components/time_tracking/estimate_only_pane.js17
-rw-r--r--app/assets/javascripts/sidebar/components/time_tracking/help_state.js44
-rw-r--r--app/assets/javascripts/sidebar/components/time_tracking/no_tracking_pane.js10
-rw-r--r--app/assets/javascripts/sidebar/components/time_tracking/sidebar_time_tracking.js51
-rw-r--r--app/assets/javascripts/sidebar/components/time_tracking/spent_only_pane.js15
-rw-r--r--app/assets/javascripts/sidebar/components/time_tracking/time_tracker.js163
-rw-r--r--app/assets/javascripts/sidebar/event_hub.js3
-rw-r--r--app/assets/javascripts/sidebar/services/sidebar_service.js28
-rw-r--r--app/assets/javascripts/sidebar/sidebar_bundle.js24
-rw-r--r--app/assets/javascripts/sidebar/sidebar_mediator.js38
-rw-r--r--app/assets/javascripts/sidebar/stores/sidebar_store.js52
-rw-r--r--app/assets/javascripts/signin_tabs_memoizer.js12
-rw-r--r--app/assets/javascripts/subbable_resource.js51
-rw-r--r--app/assets/javascripts/subscription_select.js4
-rw-r--r--app/assets/javascripts/users/calendar.js26
-rw-r--r--app/assets/javascripts/users_select.js403
-rw-r--r--app/assets/stylesheets/framework/avatar.scss11
-rw-r--r--app/assets/stylesheets/framework/dropdowns.scss16
-rw-r--r--app/assets/stylesheets/framework/files.scss12
-rw-r--r--app/assets/stylesheets/framework/filters.scss14
-rw-r--r--app/assets/stylesheets/framework/lists.scss1
-rw-r--r--app/assets/stylesheets/framework/variables.scss2
-rw-r--r--app/assets/stylesheets/pages/boards.scss74
-rw-r--r--app/assets/stylesheets/pages/diff.scss9
-rw-r--r--app/assets/stylesheets/pages/issuable.scss117
-rw-r--r--app/assets/stylesheets/pages/issues.scss9
-rw-r--r--app/assets/stylesheets/pages/labels.scss2
-rw-r--r--app/assets/stylesheets/pages/pipelines.scss27
-rw-r--r--app/assets/stylesheets/pages/todos.scss3
-rw-r--r--app/controllers/admin/application_settings_controller.rb2
-rw-r--r--app/controllers/admin/services_controller.rb2
-rw-r--r--app/controllers/application_controller.rb2
-rw-r--r--app/controllers/concerns/issuable_actions.rb1
-rw-r--r--app/controllers/concerns/issuable_collections.rb2
-rw-r--r--app/controllers/concerns/routable_actions.rb38
-rw-r--r--app/controllers/dashboard/labels_controller.rb2
-rw-r--r--app/controllers/groups/application_controller.rb24
-rw-r--r--app/controllers/groups/labels_controller.rb2
-rw-r--r--app/controllers/groups_controller.rb2
-rw-r--r--app/controllers/projects/application_controller.rb57
-rw-r--r--app/controllers/projects/boards/issues_controller.rb2
-rw-r--r--app/controllers/projects/builds_controller.rb22
-rw-r--r--app/controllers/projects/git_http_controller.rb2
-rw-r--r--app/controllers/projects/issues_controller.rb17
-rw-r--r--app/controllers/projects/labels_controller.rb2
-rw-r--r--app/controllers/projects/pipelines_controller.rb44
-rw-r--r--app/controllers/users_controller.rb9
-rw-r--r--app/finders/issuable_finder.rb2
-rw-r--r--app/finders/issues_finder.rb19
-rw-r--r--app/helpers/application_helper.rb16
-rw-r--r--app/helpers/builds_helper.rb12
-rw-r--r--app/helpers/form_helper.rb32
-rw-r--r--app/helpers/issuables_helper.rb10
-rw-r--r--app/helpers/system_note_helper.rb1
-rw-r--r--app/mailers/emails/issues.rb6
-rw-r--r--app/models/application_setting.rb4
-rw-r--r--app/models/blob.rb1
-rw-r--r--app/models/blob_viewer/balsamiq.rb12
-rw-r--r--app/models/ci/build.rb11
-rw-r--r--app/models/ci/group.rb40
-rw-r--r--app/models/ci/stage.rb8
-rw-r--r--app/models/concerns/issuable.rb29
-rw-r--r--app/models/concerns/milestoneish.rb2
-rw-r--r--app/models/concerns/routable.rb24
-rw-r--r--app/models/deployment.rb4
-rw-r--r--app/models/global_milestone.rb6
-rw-r--r--app/models/issue.rb35
-rw-r--r--app/models/issue_assignee.rb13
-rw-r--r--app/models/merge_request.rb32
-rw-r--r--app/models/milestone.rb5
-rw-r--r--app/models/note.rb6
-rw-r--r--app/models/redirect_route.rb12
-rw-r--r--app/models/route.rb55
-rw-r--r--app/models/snippet.rb5
-rw-r--r--app/models/system_note_metadata.rb2
-rw-r--r--app/models/user.rb13
-rw-r--r--app/policies/base_policy.rb4
-rw-r--r--app/policies/ci/build_policy.rb16
-rw-r--r--app/policies/ci/pipeline_policy.rb5
-rw-r--r--app/policies/environment_policy.rb14
-rw-r--r--app/serializers/build_action_entity.rb8
-rw-r--r--app/serializers/build_entity.rb10
-rw-r--r--app/serializers/issuable_entity.rb1
-rw-r--r--app/serializers/issue_entity.rb1
-rw-r--r--app/serializers/job_group_entity.rb16
-rw-r--r--app/serializers/label_entity.rb1
-rw-r--r--app/serializers/label_serializer.rb7
-rw-r--r--app/serializers/merge_request_entity.rb1
-rw-r--r--app/serializers/pipeline_entity.rb6
-rw-r--r--app/serializers/stage_entity.rb8
-rw-r--r--app/serializers/status_entity.rb7
-rw-r--r--app/services/ci/play_build_service.rb17
-rw-r--r--app/services/ci/retry_pipeline_service.rb2
-rw-r--r--app/services/ci/stop_environments_service.rb14
-rw-r--r--app/services/issuable/bulk_update_service.rb6
-rw-r--r--app/services/issuable_base_service.rb39
-rw-r--r--app/services/issues/base_service.rb22
-rw-r--r--app/services/issues/update_service.rb14
-rw-r--r--app/services/members/authorized_destroy_service.rb15
-rw-r--r--app/services/merge_requests/assign_issues_service.rb4
-rw-r--r--app/services/merge_requests/base_service.rb5
-rw-r--r--app/services/merge_requests/update_service.rb5
-rw-r--r--app/services/notification_recipient_service.rb7
-rw-r--r--app/services/notification_service.rb29
-rw-r--r--app/services/projects/propagate_service_template.rb103
-rw-r--r--app/services/slash_commands/interpret_service.rb33
-rw-r--r--app/services/system_note_service.rb55
-rw-r--r--app/services/todo_service.rb4
-rw-r--r--app/views/admin/application_settings/_form.html.haml18
-rw-r--r--app/views/issues/_issue.atom.builder15
-rw-r--r--app/views/layouts/_head.html.haml3
-rw-r--r--app/views/layouts/application.html.haml2
-rw-r--r--app/views/layouts/devise.html.haml1
-rw-r--r--app/views/layouts/devise_empty.html.haml1
-rw-r--r--app/views/notify/_reassigned_issuable_email.text.erb6
-rw-r--r--app/views/notify/new_issue_email.html.haml4
-rw-r--r--app/views/notify/new_issue_email.text.erb2
-rw-r--r--app/views/notify/new_mention_in_issue_email.text.erb2
-rw-r--r--app/views/notify/reassigned_issue_email.html.haml11
-rw-r--r--app/views/notify/reassigned_issue_email.text.erb7
-rw-r--r--app/views/notify/reassigned_merge_request_email.html.haml10
-rw-r--r--app/views/notify/reassigned_merge_request_email.text.erb7
-rw-r--r--app/views/projects/blob/viewers/_balsamiq.html.haml4
-rw-r--r--app/views/projects/boards/components/_board.html.haml4
-rw-r--r--app/views/projects/boards/components/sidebar/_assignee.html.haml44
-rw-r--r--app/views/projects/ci/builds/_build.html.haml2
-rw-r--r--app/views/projects/environments/terminal.html.haml5
-rw-r--r--app/views/projects/issues/_issue.html.haml4
-rw-r--r--app/views/projects/issues/show.html.haml11
-rw-r--r--app/views/projects/pipelines/_with_tabs.html.haml19
-rw-r--r--app/views/projects/protected_branches/_create_protected_branch.html.haml4
-rw-r--r--app/views/projects/protected_branches/_update_protected_branch.html.haml4
-rw-r--r--app/views/projects/protected_tags/_dropdown.html.haml2
-rw-r--r--app/views/projects/protected_tags/_update_protected_tag.haml2
-rw-r--r--app/views/shared/issuable/_assignees.html.haml15
-rw-r--r--app/views/shared/issuable/_participants.html.haml8
-rw-r--r--app/views/shared/issuable/_search_bar.html.haml7
-rw-r--r--app/views/shared/issuable/_sidebar.html.haml95
-rw-r--r--app/views/shared/issuable/form/_issue_assignee.html.haml30
-rw-r--r--app/views/shared/issuable/form/_merge_request_assignee.html.haml31
-rw-r--r--app/views/shared/issuable/form/_metadata.html.haml28
-rw-r--r--app/views/shared/milestones/_issuable.html.haml8
-rw-r--r--app/views/shared/milestones/_labels_tab.html.haml14
-rw-r--r--app/views/shared/notes/_note.html.haml2
-rw-r--r--app/views/shared/snippets/_header.html.haml2
-rw-r--r--app/workers/post_receive.rb38
-rw-r--r--app/workers/propagate_service_template_worker.rb21
-rw-r--r--changelogs/unreleased/17361-redirect-renamed-paths.yml4
-rw-r--r--changelogs/unreleased/23751-add-contribution-graph-key-tooltips.yml4
-rw-r--r--changelogs/unreleased/24883-build-failure-summary-page.yml4
-rw-r--r--changelogs/unreleased/29925-gitlab-shell-hooks-can-no-longer-send-absolute-paths-to-gitlab-ce.yml4
-rw-r--r--changelogs/unreleased/30007-done-todo-hover-state.yml4
-rw-r--r--changelogs/unreleased/30903-vertically-align-mini-pipeline.yml4
-rw-r--r--changelogs/unreleased/add_system_note_for_editing_issuable.yml4
-rw-r--r--changelogs/unreleased/balsalmiq-support.yml4
-rw-r--r--changelogs/unreleased/feature-gb-manual-actions-protected-branches-permissions.yml4
-rw-r--r--changelogs/unreleased/fix-admin-integrations.yml4
-rw-r--r--changelogs/unreleased/fix-gb-hide-environment-external-url-btn-when-not-provided.yml4
-rw-r--r--changelogs/unreleased/issue-title-description-realtime.yml4
-rw-r--r--changelogs/unreleased/winh-visual-token-labels.yml4
-rw-r--r--changelogs/unreleased/zj-real-time-pipelines.yml4
-rw-r--r--config/initializers/fast_gettext.rb2
-rw-r--r--config/routes/project.rb1
-rw-r--r--config/sidekiq_queues.yml1
-rw-r--r--config/webpack.config.js12
-rw-r--r--db/fixtures/development/09_issues.rb2
-rw-r--r--db/migrate/20170320171632_create_issue_assignees_table.rb40
-rw-r--r--db/migrate/20170320173259_migrate_assignees.rb52
-rw-r--r--db/migrate/20170427215854_create_redirect_routes.rb14
-rw-r--r--db/migrate/20170503021915_add_last_edited_at_and_last_edited_by_id_to_issues.rb14
-rw-r--r--db/migrate/20170503022548_add_last_edited_at_and_last_edited_by_id_to_merge_requests.rb14
-rw-r--r--db/migrate/20170503184421_add_index_to_redirect_routes.rb21
-rw-r--r--db/migrate/20170503185032_index_redirect_routes_path_for_like.rb29
-rw-r--r--db/migrate/20170504102911_add_clientside_sentry_to_application_settings.rb33
-rw-r--r--db/schema.rb30
-rw-r--r--doc/api/issues.md84
-rw-r--r--doc/ci/yaml/README.md7
-rw-r--r--doc/development/fe_guide/droplab/droplab.md2
-rw-r--r--doc/user/project/integrations/webhooks.md12
-rw-r--r--features/project/issues/issues.feature1
-rw-r--r--features/steps/dashboard/dashboard.rb2
-rw-r--r--features/steps/dashboard/todos.rb2
-rw-r--r--features/steps/group/milestones.rb4
-rw-r--r--features/steps/groups.rb4
-rw-r--r--lib/api/api.rb2
-rw-r--r--lib/api/entities.rb6
-rw-r--r--lib/api/helpers/common_helpers.rb13
-rw-r--r--lib/api/helpers/internal_helpers.rb52
-rw-r--r--lib/api/internal.rb10
-rw-r--r--lib/api/issues.rb9
-rw-r--r--lib/api/jobs.rb9
-rw-r--r--lib/api/settings.rb5
-rw-r--r--lib/api/v3/builds.rb10
-rw-r--r--lib/api/v3/entities.rb7
-rw-r--r--lib/api/v3/issues.rb31
-rw-r--r--lib/api/v3/merge_requests.rb2
-rw-r--r--lib/api/v3/milestones.rb4
-rw-r--r--lib/banzai/reference_parser/issue_parser.rb2
-rw-r--r--lib/constraints/group_url_constrainer.rb2
-rw-r--r--lib/constraints/project_url_constrainer.rb2
-rw-r--r--lib/constraints/user_url_constrainer.rb2
-rw-r--r--lib/github/import.rb2
-rw-r--r--lib/gitlab/chat_commands/presenters/issue_base.rb2
-rw-r--r--lib/gitlab/ci/status/build/action.rb21
-rw-r--r--lib/gitlab/ci/status/build/cancelable.rb4
-rw-r--r--lib/gitlab/ci/status/build/factory.rb3
-rw-r--r--lib/gitlab/ci/status/build/failed_allowed.rb4
-rw-r--r--lib/gitlab/ci/status/build/play.rb4
-rw-r--r--lib/gitlab/ci/status/build/retryable.rb4
-rw-r--r--lib/gitlab/ci/status/build/stop.rb4
-rw-r--r--lib/gitlab/ci/status/extended.rb12
-rw-r--r--lib/gitlab/ci/status/group/common.rb21
-rw-r--r--lib/gitlab/ci/status/group/factory.rb13
-rw-r--r--lib/gitlab/ci/status/pipeline/blocked.rb4
-rw-r--r--lib/gitlab/ci/status/success_warning.rb4
-rw-r--r--lib/gitlab/etag_caching/router.rb6
-rw-r--r--lib/gitlab/fogbugz_import/importer.rb18
-rw-r--r--lib/gitlab/git_post_receive.rb29
-rw-r--r--lib/gitlab/github_import/issue_formatter.rb2
-rw-r--r--lib/gitlab/gl_repository.rb20
-rw-r--r--lib/gitlab/gon_helper.rb2
-rw-r--r--lib/gitlab/google_code_import/importer.rb14
-rw-r--r--lib/gitlab/import_export/import_export.yml2
-rw-r--r--lib/gitlab/import_export/relation_factory.rb2
-rw-r--r--lib/gitlab/repo_path.rb29
-rw-r--r--lib/gitlab/workhorse.rb6
-rw-r--r--lib/tasks/migrate/setup_postgresql.rake1
-rw-r--r--package.json2
-rw-r--r--spec/controllers/admin/services_controller_spec.rb32
-rw-r--r--spec/controllers/application_controller_spec.rb5
-rw-r--r--spec/controllers/dashboard/todos_controller_spec.rb2
-rw-r--r--spec/controllers/groups_controller_spec.rb96
-rw-r--r--spec/controllers/projects/boards/issues_controller_spec.rb2
-rw-r--r--spec/controllers/projects/builds_controller_spec.rb2
-rw-r--r--spec/controllers/projects/issues_controller_spec.rb8
-rw-r--r--spec/controllers/projects/merge_requests_controller_spec.rb2
-rw-r--r--spec/controllers/projects/pipelines_controller_spec.rb31
-rw-r--r--spec/controllers/projects_controller_spec.rb87
-rw-r--r--spec/controllers/users_controller_spec.rb211
-rw-r--r--spec/factories/environments.rb10
-rw-r--r--spec/features/atom/dashboard_issues_spec.rb8
-rw-r--r--spec/features/atom/issues_spec.rb8
-rw-r--r--spec/features/boards/boards_spec.rb2
-rw-r--r--spec/features/boards/modal_filter_spec.rb2
-rw-r--r--spec/features/boards/sidebar_spec.rb14
-rw-r--r--spec/features/dashboard/issuables_counter_spec.rb6
-rw-r--r--spec/features/dashboard/issues_spec.rb7
-rw-r--r--spec/features/dashboard_issues_spec.rb4
-rw-r--r--spec/features/gitlab_flavored_markdown_spec.rb4
-rw-r--r--spec/features/groups/group_settings_spec.rb80
-rw-r--r--spec/features/issues/award_emoji_spec.rb2
-rw-r--r--spec/features/issues/award_spec.rb6
-rw-r--r--spec/features/issues/filtered_search/filter_issues_spec.rb10
-rw-r--r--spec/features/issues/form_spec.rb57
-rw-r--r--spec/features/issues/issue_sidebar_spec.rb17
-rw-r--r--spec/features/issues/update_issues_spec.rb2
-rw-r--r--spec/features/issues_spec.rb42
-rw-r--r--spec/features/merge_requests/assign_issues_spec.rb2
-rw-r--r--spec/features/milestones/show_spec.rb2
-rw-r--r--spec/features/profiles/account_spec.rb59
-rw-r--r--spec/features/projects/environments/environment_spec.rb4
-rw-r--r--spec/features/projects/features_visibility_spec.rb35
-rw-r--r--spec/features/projects/issuable_templates_spec.rb4
-rw-r--r--spec/features/projects/pipelines/pipeline_spec.rb53
-rw-r--r--spec/features/projects/project_settings_spec.rb152
-rw-r--r--spec/features/raven_js_spec.rb23
-rw-r--r--spec/features/search_spec.rb2
-rw-r--r--spec/features/task_lists_spec.rb35
-rw-r--r--spec/features/unsubscribe_links_spec.rb2
-rw-r--r--spec/finders/issues_finder_spec.rb12
-rw-r--r--spec/fixtures/api/schemas/issue.json18
-rw-r--r--spec/fixtures/api/schemas/pipeline.json354
-rw-r--r--spec/fixtures/api/schemas/public_api/v4/issues.json17
-rw-r--r--spec/helpers/issuables_helper_spec.rb17
-rw-r--r--spec/javascripts/autosave_spec.js134
-rw-r--r--spec/javascripts/behaviors/gl_emoji/unicode_support_map_spec.js47
-rw-r--r--spec/javascripts/blob/balsamiq/balsamiq_viewer_spec.js342
-rw-r--r--spec/javascripts/boards/board_card_spec.js8
-rw-r--r--spec/javascripts/boards/board_list_spec.js1
-rw-r--r--spec/javascripts/boards/boards_store_spec.js19
-rw-r--r--spec/javascripts/boards/issue_card_spec.js114
-rw-r--r--spec/javascripts/boards/issue_spec.js76
-rw-r--r--spec/javascripts/boards/list_spec.js25
-rw-r--r--spec/javascripts/boards/mock_data.js3
-rw-r--r--spec/javascripts/boards/modal_store_spec.js12
-rw-r--r--spec/javascripts/filtered_search/components/recent_searches_dropdown_content_spec.js20
-rw-r--r--spec/javascripts/filtered_search/filtered_search_manager_spec.js34
-rw-r--r--spec/javascripts/filtered_search/filtered_search_visual_tokens_spec.js101
-rw-r--r--spec/javascripts/filtered_search/recent_searches_root_spec.js31
-rw-r--r--spec/javascripts/filtered_search/services/recent_searches_service_error_spec.js18
-rw-r--r--spec/javascripts/filtered_search/services/recent_searches_service_spec.js95
-rw-r--r--spec/javascripts/fixtures/labels.rb56
-rw-r--r--spec/javascripts/helpers/user_mock_data_helper.js16
-rw-r--r--spec/javascripts/issuable_time_tracker_spec.js250
-rw-r--r--spec/javascripts/issue_show/issue_title_description_spec.js60
-rw-r--r--spec/javascripts/issue_show/issue_title_spec.js22
-rw-r--r--spec/javascripts/issue_show/mock_data.js26
-rw-r--r--spec/javascripts/issue_spec.js6
-rw-r--r--spec/javascripts/lib/utils/accessor_spec.js78
-rw-r--r--spec/javascripts/lib/utils/ajax_cache_spec.js129
-rw-r--r--spec/javascripts/notes_spec.js217
-rw-r--r--spec/javascripts/raven/index_spec.js42
-rw-r--r--spec/javascripts/raven/raven_config_spec.js276
-rw-r--r--spec/javascripts/sidebar/assignee_title_spec.js80
-rw-r--r--spec/javascripts/sidebar/assignees_spec.js272
-rw-r--r--spec/javascripts/sidebar/mock_data.js109
-rw-r--r--spec/javascripts/sidebar/sidebar_assignees_spec.js45
-rw-r--r--spec/javascripts/sidebar/sidebar_bundle_spec.js42
-rw-r--r--spec/javascripts/sidebar/sidebar_mediator_spec.js40
-rw-r--r--spec/javascripts/sidebar/sidebar_service_spec.js32
-rw-r--r--spec/javascripts/sidebar/sidebar_store_spec.js80
-rw-r--r--spec/javascripts/signin_tabs_memoizer_spec.js90
-rw-r--r--spec/javascripts/subbable_resource_spec.js63
-rw-r--r--spec/lib/banzai/filter/redactor_filter_spec.rb2
-rw-r--r--spec/lib/constraints/group_url_constrainer_spec.rb32
-rw-r--r--spec/lib/constraints/project_url_constrainer_spec.rb21
-rw-r--r--spec/lib/constraints/user_url_constrainer_spec.rb21
-rw-r--r--spec/lib/gitlab/chat_commands/command_spec.rb14
-rw-r--r--spec/lib/gitlab/chat_commands/deploy_spec.rb16
-rw-r--r--spec/lib/gitlab/ci/status/build/action_spec.rb56
-rw-r--r--spec/lib/gitlab/ci/status/build/factory_spec.rb51
-rw-r--r--spec/lib/gitlab/ci/status/build/play_spec.rb45
-rw-r--r--spec/lib/gitlab/ci/status/extended_spec.rb6
-rw-r--r--spec/lib/gitlab/ci/status/group/common_spec.rb20
-rw-r--r--spec/lib/gitlab/ci/status/group/factory_spec.rb13
-rw-r--r--spec/lib/gitlab/github_import/issue_formatter_spec.rb10
-rw-r--r--spec/lib/gitlab/gl_repository_spec.rb19
-rw-r--r--spec/lib/gitlab/google_code_import/importer_spec.rb2
-rw-r--r--spec/lib/gitlab/import_export/all_models.yml7
-rw-r--r--spec/lib/gitlab/import_export/project_tree_saver_spec.rb2
-rw-r--r--spec/lib/gitlab/import_export/safe_model_attributes.yml4
-rw-r--r--spec/lib/gitlab/project_search_results_spec.rb2
-rw-r--r--spec/lib/gitlab/repo_path_spec.rb24
-rw-r--r--spec/lib/gitlab/search_results_spec.rb4
-rw-r--r--spec/lib/gitlab/workhorse_spec.rb17
-rw-r--r--spec/mailers/notify_spec.rb10
-rw-r--r--spec/models/ci/build_spec.rb42
-rw-r--r--spec/models/ci/group_spec.rb44
-rw-r--r--spec/models/ci/stage_spec.rb33
-rw-r--r--spec/models/concerns/issuable_spec.rb109
-rw-r--r--spec/models/concerns/milestoneish_spec.rb6
-rw-r--r--spec/models/concerns/routable_spec.rb52
-rw-r--r--spec/models/environment_spec.rb53
-rw-r--r--spec/models/event_spec.rb4
-rw-r--r--spec/models/issue_collection_spec.rb2
-rw-r--r--spec/models/issue_spec.rb91
-rw-r--r--spec/models/merge_request_spec.rb91
-rw-r--r--spec/models/redirect_route_spec.rb27
-rw-r--r--spec/models/route_spec.rb114
-rw-r--r--spec/models/user_spec.rb59
-rw-r--r--spec/policies/ci/build_policy_spec.rb53
-rw-r--r--spec/policies/environment_policy_spec.rb57
-rw-r--r--spec/policies/issue_policy_spec.rb8
-rw-r--r--spec/requests/api/helpers/internal_helpers_spec.rb32
-rw-r--r--spec/requests/api/internal_spec.rb77
-rw-r--r--spec/requests/api/issues_spec.rb92
-rw-r--r--spec/requests/api/jobs_spec.rb67
-rw-r--r--spec/requests/api/v3/issues_spec.rb31
-rw-r--r--spec/routing/project_routing_spec.rb6
-rw-r--r--spec/serializers/build_action_entity_spec.rb3
-rw-r--r--spec/serializers/build_entity_spec.rb28
-rw-r--r--spec/serializers/label_serializer_spec.rb46
-rw-r--r--spec/serializers/stage_entity_spec.rb8
-rw-r--r--spec/services/ci/play_build_service_spec.rb105
-rw-r--r--spec/services/ci/process_pipeline_service_spec.rb7
-rw-r--r--spec/services/ci/retry_pipeline_service_spec.rb44
-rw-r--r--spec/services/ci/stop_environments_service_spec.rb16
-rw-r--r--spec/services/issuable/bulk_update_service_spec.rb62
-rw-r--r--spec/services/issues/close_service_spec.rb2
-rw-r--r--spec/services/issues/create_service_spec.rb86
-rw-r--r--spec/services/issues/update_service_spec.rb70
-rw-r--r--spec/services/members/authorized_destroy_service_spec.rb6
-rw-r--r--spec/services/merge_requests/assign_issues_service_spec.rb10
-rw-r--r--spec/services/merge_requests/create_service_spec.rb82
-rw-r--r--spec/services/merge_requests/update_service_spec.rb55
-rw-r--r--spec/services/notes/slash_commands_service_spec.rb31
-rw-r--r--spec/services/notification_service_spec.rb80
-rw-r--r--spec/services/projects/autocomplete_service_spec.rb2
-rw-r--r--spec/services/projects/propagate_service_template_spec.rb103
-rw-r--r--spec/services/slash_commands/interpret_service_spec.rb86
-rw-r--r--spec/services/system_note_service_spec.rb61
-rw-r--r--spec/services/todo_service_spec.rb26
-rw-r--r--spec/services/users/destroy_service_spec.rb4
-rw-r--r--spec/support/features/issuable_slash_commands_shared_examples.rb8
-rw-r--r--spec/support/import_export/export_file_helper.rb2
-rw-r--r--spec/support/matchers/gitlab_git_matchers.rb6
-rw-r--r--spec/support/services/issuable_create_service_shared_examples.rb52
-rw-r--r--spec/support/services/issuable_create_service_slash_commands_shared_examples.rb18
-rw-r--r--spec/support/services/issuable_update_service_shared_examples.rb48
-rw-r--r--spec/support/test_env.rb1
-rw-r--r--spec/support/time_tracking_shared_examples.rb12
-rw-r--r--spec/views/projects/environments/terminal.html.haml_spec.rb32
-rw-r--r--spec/workers/post_receive_spec.rb43
-rw-r--r--spec/workers/propagate_service_template_worker_spec.rb29
-rw-r--r--yarn.lock12
461 files changed, 10781 insertions, 2453 deletions
diff --git a/GITLAB_PAGES_VERSION b/GITLAB_PAGES_VERSION
index 267577d47e4..2b7c5ae0184 100644
--- a/GITLAB_PAGES_VERSION
+++ b/GITLAB_PAGES_VERSION
@@ -1 +1 @@
-0.4.1
+0.4.2
diff --git a/Gemfile b/Gemfile
index 9426a558612..5dbb0bdfddb 100644
--- a/Gemfile
+++ b/Gemfile
@@ -257,6 +257,7 @@ gem 'sentry-raven', '~> 2.4.0'
gem 'premailer-rails', '~> 1.9.0'
# I18n
+gem 'ruby_parser', '~> 3.8.4', require: false
gem 'gettext_i18n_rails', '~> 1.8.0'
gem 'gettext_i18n_rails_js', '~> 1.2.0'
gem 'gettext', '~> 3.2.2', require: false, group: :development
diff --git a/Gemfile.lock b/Gemfile.lock
index c7e3f9935da..01c35a935f2 100644
--- a/Gemfile.lock
+++ b/Gemfile.lock
@@ -1012,6 +1012,7 @@ DEPENDENCIES
rubocop-rspec (~> 1.15.0)
ruby-fogbugz (~> 0.2.1)
ruby-prof (~> 0.16.2)
+ ruby_parser (~> 3.8.4)
rufus-scheduler (~> 3.1.10)
rugged (~> 0.25.1.1)
sanitize (~> 2.0)
diff --git a/app/assets/javascripts/autosave.js b/app/assets/javascripts/autosave.js
index 8630b18a73f..cfab6c40b34 100644
--- a/app/assets/javascripts/autosave.js
+++ b/app/assets/javascripts/autosave.js
@@ -1,8 +1,11 @@
/* eslint-disable func-names, space-before-function-paren, wrap-iife, no-param-reassign, quotes, prefer-template, no-var, one-var, no-unused-vars, one-var-declaration-per-line, no-void, consistent-return, no-empty, max-len */
+import AccessorUtilities from './lib/utils/accessor';
window.Autosave = (function() {
function Autosave(field, key) {
this.field = field;
+ this.isLocalStorageAvailable = AccessorUtilities.isLocalStorageAccessSafe();
+
if (key.join != null) {
key = key.join("/");
}
@@ -17,16 +20,12 @@ window.Autosave = (function() {
}
Autosave.prototype.restore = function() {
- var e, text;
- if (window.localStorage == null) {
- return;
- }
- try {
- text = window.localStorage.getItem(this.key);
- } catch (error) {
- e = error;
- return;
- }
+ var text;
+
+ if (!this.isLocalStorageAvailable) return;
+
+ text = window.localStorage.getItem(this.key);
+
if ((text != null ? text.length : void 0) > 0) {
this.field.val(text);
}
@@ -35,27 +34,22 @@ window.Autosave = (function() {
Autosave.prototype.save = function() {
var text;
- if (window.localStorage == null) {
- return;
- }
text = this.field.val();
- if ((text != null ? text.length : void 0) > 0) {
- try {
- return window.localStorage.setItem(this.key, text);
- } catch (error) {}
- } else {
- return this.reset();
+
+ if (this.isLocalStorageAvailable && (text != null ? text.length : void 0) > 0) {
+ return window.localStorage.setItem(this.key, text);
}
+
+ return this.reset();
};
Autosave.prototype.reset = function() {
- if (window.localStorage == null) {
- return;
- }
- try {
- return window.localStorage.removeItem(this.key);
- } catch (error) {}
+ if (!this.isLocalStorageAvailable) return;
+
+ return window.localStorage.removeItem(this.key);
};
return Autosave;
})();
+
+export default window.Autosave;
diff --git a/app/assets/javascripts/behaviors/gl_emoji/unicode_support_map.js b/app/assets/javascripts/behaviors/gl_emoji/unicode_support_map.js
index aa522e20c36..257df55e54f 100644
--- a/app/assets/javascripts/behaviors/gl_emoji/unicode_support_map.js
+++ b/app/assets/javascripts/behaviors/gl_emoji/unicode_support_map.js
@@ -1,3 +1,5 @@
+import AccessorUtilities from '../../lib/utils/accessor';
+
const unicodeSupportTestMap = {
// man, student (emojione does not have any of these yet), http://emojipedia.org/emoji-zwj-sequences/
// occupationZwj: '\u{1F468}\u{200D}\u{1F393}',
@@ -140,16 +142,25 @@ function generateUnicodeSupportMap(testMap) {
function getUnicodeSupportMap() {
let unicodeSupportMap;
- const userAgentFromCache = window.localStorage.getItem('gl-emoji-user-agent');
+ let userAgentFromCache;
+
+ const isLocalStorageAvailable = AccessorUtilities.isLocalStorageAccessSafe();
+
+ if (isLocalStorageAvailable) userAgentFromCache = window.localStorage.getItem('gl-emoji-user-agent');
+
try {
unicodeSupportMap = JSON.parse(window.localStorage.getItem('gl-emoji-unicode-support-map'));
} catch (err) {
// swallow
}
+
if (!unicodeSupportMap || userAgentFromCache !== navigator.userAgent) {
unicodeSupportMap = generateUnicodeSupportMap(unicodeSupportTestMap);
- window.localStorage.setItem('gl-emoji-user-agent', navigator.userAgent);
- window.localStorage.setItem('gl-emoji-unicode-support-map', JSON.stringify(unicodeSupportMap));
+
+ if (isLocalStorageAvailable) {
+ window.localStorage.setItem('gl-emoji-user-agent', navigator.userAgent);
+ window.localStorage.setItem('gl-emoji-unicode-support-map', JSON.stringify(unicodeSupportMap));
+ }
}
return unicodeSupportMap;
diff --git a/app/assets/javascripts/blob/balsamiq/balsamiq_viewer.js b/app/assets/javascripts/blob/balsamiq/balsamiq_viewer.js
new file mode 100644
index 00000000000..cdbfe36ca1c
--- /dev/null
+++ b/app/assets/javascripts/blob/balsamiq/balsamiq_viewer.js
@@ -0,0 +1,114 @@
+/* global Flash */
+
+import sqljs from 'sql.js';
+import { template as _template } from 'underscore';
+
+const PREVIEW_TEMPLATE = _template(`
+ <div class="panel panel-default">
+ <div class="panel-heading"><%- name %></div>
+ <div class="panel-body">
+ <img class="img-thumbnail" src="data:image/png;base64,<%- image %>"/>
+ </div>
+ </div>
+`);
+
+class BalsamiqViewer {
+ constructor(viewer) {
+ this.viewer = viewer;
+ this.endpoint = this.viewer.dataset.endpoint;
+ }
+
+ loadFile() {
+ const xhr = new XMLHttpRequest();
+
+ xhr.open('GET', this.endpoint, true);
+ xhr.responseType = 'arraybuffer';
+
+ xhr.onload = this.renderFile.bind(this);
+ xhr.onerror = BalsamiqViewer.onError;
+
+ xhr.send();
+ }
+
+ renderFile(loadEvent) {
+ const container = document.createElement('ul');
+
+ this.initDatabase(loadEvent.target.response);
+
+ const previews = this.getPreviews();
+ previews.forEach((preview) => {
+ const renderedPreview = this.renderPreview(preview);
+
+ container.appendChild(renderedPreview);
+ });
+
+ container.classList.add('list-inline');
+ container.classList.add('previews');
+
+ this.viewer.appendChild(container);
+ }
+
+ initDatabase(data) {
+ const previewBinary = new Uint8Array(data);
+
+ this.database = new sqljs.Database(previewBinary);
+ }
+
+ getPreviews() {
+ const thumbnails = this.database.exec('SELECT * FROM thumbnails');
+
+ return thumbnails[0].values.map(BalsamiqViewer.parsePreview);
+ }
+
+ getResource(resourceID) {
+ const resources = this.database.exec(`SELECT * FROM resources WHERE id = '${resourceID}'`);
+
+ return resources[0];
+ }
+
+ renderPreview(preview) {
+ const previewElement = document.createElement('li');
+
+ previewElement.classList.add('preview');
+ previewElement.innerHTML = this.renderTemplate(preview);
+
+ return previewElement;
+ }
+
+ renderTemplate(preview) {
+ const resource = this.getResource(preview.resourceID);
+ const name = BalsamiqViewer.parseTitle(resource);
+ const image = preview.image;
+
+ const template = PREVIEW_TEMPLATE({
+ name,
+ image,
+ });
+
+ return template;
+ }
+
+ static parsePreview(preview) {
+ return JSON.parse(preview[1]);
+ }
+
+ /*
+ * resource = {
+ * columns: ['ID', 'BRANCHID', 'ATTRIBUTES', 'DATA'],
+ * values: [['id', 'branchId', 'attributes', 'data']],
+ * }
+ *
+ * 'attributes' being a JSON string containing the `name` property.
+ */
+ static parseTitle(resource) {
+ return JSON.parse(resource.values[0][2]).name;
+ }
+
+ static onError() {
+ const flash = new Flash('Balsamiq file could not be loaded.');
+
+ return flash;
+ }
+}
+
+export default BalsamiqViewer;
diff --git a/app/assets/javascripts/blob/balsamiq_viewer.js b/app/assets/javascripts/blob/balsamiq_viewer.js
new file mode 100644
index 00000000000..1dacf84470f
--- /dev/null
+++ b/app/assets/javascripts/blob/balsamiq_viewer.js
@@ -0,0 +1,6 @@
+import BalsamiqViewer from './balsamiq/balsamiq_viewer';
+
+document.addEventListener('DOMContentLoaded', () => {
+ const balsamiqViewer = new BalsamiqViewer(document.getElementById('js-balsamiq-viewer'));
+ balsamiqViewer.loadFile();
+});
diff --git a/app/assets/javascripts/blob/file_template_mediator.js b/app/assets/javascripts/blob/file_template_mediator.js
index 3062cd51ee3..a20c6ca7a21 100644
--- a/app/assets/javascripts/blob/file_template_mediator.js
+++ b/app/assets/javascripts/blob/file_template_mediator.js
@@ -99,7 +99,7 @@ export default class FileTemplateMediator {
});
}
- selectTemplateType(item, el, e) {
+ selectTemplateType(item, e) {
if (e) {
e.preventDefault();
}
@@ -117,6 +117,10 @@ export default class FileTemplateMediator {
this.cacheToggleText();
}
+ selectTemplateTypeOptions(options) {
+ this.selectTemplateType(options.selectedObj, options.e);
+ }
+
selectTemplateFile(selector, query, data) {
selector.renderLoading();
// in case undo menu is already already there
diff --git a/app/assets/javascripts/blob/file_template_selector.js b/app/assets/javascripts/blob/file_template_selector.js
index 31dd45fac89..ab5b3751c4e 100644
--- a/app/assets/javascripts/blob/file_template_selector.js
+++ b/app/assets/javascripts/blob/file_template_selector.js
@@ -52,9 +52,17 @@ export default class FileTemplateSelector {
.removeClass('fa-spinner fa-spin');
}
- reportSelection(query, el, e, data) {
+ reportSelection(options) {
+ const { query, e, data } = options;
e.preventDefault();
return this.mediator.selectTemplateFile(this, query, data);
}
+
+ reportSelectionName(options) {
+ const opts = options;
+ opts.query = options.selectedObj.name;
+
+ this.reportSelection(opts);
+ }
}
diff --git a/app/assets/javascripts/blob/target_branch_dropdown.js b/app/assets/javascripts/blob/target_branch_dropdown.js
index 216f069ef71..d52d69b1274 100644
--- a/app/assets/javascripts/blob/target_branch_dropdown.js
+++ b/app/assets/javascripts/blob/target_branch_dropdown.js
@@ -37,8 +37,8 @@ class TargetBranchDropDown {
}
return SELECT_ITEM_MSG;
},
- clicked(item, el, e) {
- e.preventDefault();
+ clicked(options) {
+ options.e.preventDefault();
self.onClick.call(self);
},
fieldName: self.fieldName,
diff --git a/app/assets/javascripts/blob/template_selector.js b/app/assets/javascripts/blob/template_selector.js
index d7c1c32efbd..888883163c5 100644
--- a/app/assets/javascripts/blob/template_selector.js
+++ b/app/assets/javascripts/blob/template_selector.js
@@ -24,7 +24,7 @@ export default class TemplateSelector {
search: {
fields: ['name'],
},
- clicked: (item, el, e) => this.fetchFileTemplate(item, el, e),
+ clicked: options => this.fetchFileTemplate(options),
text: item => item.name,
});
}
@@ -51,7 +51,10 @@ export default class TemplateSelector {
return this.$dropdownContainer.removeClass('hidden');
}
- fetchFileTemplate(item, el, e) {
+ fetchFileTemplate(options) {
+ const { e } = options;
+ const item = options.selectedObj;
+
e.preventDefault();
return this.requestFile(item);
}
diff --git a/app/assets/javascripts/blob/template_selectors/ci_yaml_selector.js b/app/assets/javascripts/blob/template_selectors/ci_yaml_selector.js
index 935df07677c..f2f81af137b 100644
--- a/app/assets/javascripts/blob/template_selectors/ci_yaml_selector.js
+++ b/app/assets/javascripts/blob/template_selectors/ci_yaml_selector.js
@@ -25,7 +25,7 @@ export default class BlobCiYamlSelector extends FileTemplateSelector {
search: {
fields: ['name'],
},
- clicked: (query, el, e) => this.reportSelection(query.name, el, e),
+ clicked: options => this.reportSelectionName(options),
text: item => item.name,
});
}
diff --git a/app/assets/javascripts/blob/template_selectors/dockerfile_selector.js b/app/assets/javascripts/blob/template_selectors/dockerfile_selector.js
index b4b4d09c315..3cb7b960aaa 100644
--- a/app/assets/javascripts/blob/template_selectors/dockerfile_selector.js
+++ b/app/assets/javascripts/blob/template_selectors/dockerfile_selector.js
@@ -25,7 +25,7 @@ export default class DockerfileSelector extends FileTemplateSelector {
search: {
fields: ['name'],
},
- clicked: (query, el, e) => this.reportSelection(query.name, el, e),
+ clicked: options => this.reportSelectionName(options),
text: item => item.name,
});
}
diff --git a/app/assets/javascripts/blob/template_selectors/gitignore_selector.js b/app/assets/javascripts/blob/template_selectors/gitignore_selector.js
index aefae54ae71..7efda8e7f50 100644
--- a/app/assets/javascripts/blob/template_selectors/gitignore_selector.js
+++ b/app/assets/javascripts/blob/template_selectors/gitignore_selector.js
@@ -24,7 +24,7 @@ export default class BlobGitignoreSelector extends FileTemplateSelector {
search: {
fields: ['name'],
},
- clicked: (query, el, e) => this.reportSelection(query.name, el, e),
+ clicked: options => this.reportSelectionName(options),
text: item => item.name,
});
}
diff --git a/app/assets/javascripts/blob/template_selectors/license_selector.js b/app/assets/javascripts/blob/template_selectors/license_selector.js
index c8abd689ab4..1d757332f6c 100644
--- a/app/assets/javascripts/blob/template_selectors/license_selector.js
+++ b/app/assets/javascripts/blob/template_selectors/license_selector.js
@@ -24,13 +24,22 @@ export default class BlobLicenseSelector extends FileTemplateSelector {
search: {
fields: ['name'],
},
- clicked: (query, el, e) => {
+ clicked: (options) => {
+ const { e } = options;
+ const el = options.$el;
+ const query = options.selectedObj;
+
const data = {
project: this.$dropdown.data('project'),
fullname: this.$dropdown.data('fullname'),
};
- this.reportSelection(query.id, el, e, data);
+ this.reportSelection({
+ query: query.id,
+ el,
+ e,
+ data,
+ });
},
text: item => item.name,
});
diff --git a/app/assets/javascripts/blob/template_selectors/type_selector.js b/app/assets/javascripts/blob/template_selectors/type_selector.js
index 56f23ef0568..a09381014a7 100644
--- a/app/assets/javascripts/blob/template_selectors/type_selector.js
+++ b/app/assets/javascripts/blob/template_selectors/type_selector.js
@@ -17,7 +17,7 @@ export default class FileTemplateTypeSelector extends FileTemplateSelector {
filterable: false,
selectable: true,
toggleLabel: item => item.name,
- clicked: (item, el, e) => this.mediator.selectTemplateType(item, el, e),
+ clicked: options => this.mediator.selectTemplateTypeOptions(options),
text: item => item.name,
});
}
diff --git a/app/assets/javascripts/boards/boards_bundle.js b/app/assets/javascripts/boards/boards_bundle.js
index 8c08b2d4db3..88eb4251339 100644
--- a/app/assets/javascripts/boards/boards_bundle.js
+++ b/app/assets/javascripts/boards/boards_bundle.js
@@ -11,7 +11,7 @@ require('./models/issue');
require('./models/label');
require('./models/list');
require('./models/milestone');
-require('./models/user');
+require('./models/assignee');
require('./stores/boards_store');
require('./stores/modal_store');
require('./services/board_service');
diff --git a/app/assets/javascripts/boards/components/board_new_issue.js b/app/assets/javascripts/boards/components/board_new_issue.js
index 0fa85b6fe14..1ce95b62138 100644
--- a/app/assets/javascripts/boards/components/board_new_issue.js
+++ b/app/assets/javascripts/boards/components/board_new_issue.js
@@ -26,6 +26,7 @@ export default {
title: this.title,
labels,
subscribed: true,
+ assignees: [],
});
this.list.newIssue(issue)
diff --git a/app/assets/javascripts/boards/components/board_sidebar.js b/app/assets/javascripts/boards/components/board_sidebar.js
index f0066d4ec5d..317cef9f227 100644
--- a/app/assets/javascripts/boards/components/board_sidebar.js
+++ b/app/assets/javascripts/boards/components/board_sidebar.js
@@ -3,8 +3,13 @@
/* global MilestoneSelect */
/* global LabelsSelect */
/* global Sidebar */
+/* global Flash */
import Vue from 'vue';
+import eventHub from '../../sidebar/event_hub';
+
+import AssigneeTitle from '../../sidebar/components/assignees/assignee_title';
+import Assignees from '../../sidebar/components/assignees/assignees';
require('./sidebar/remove_issue');
@@ -22,6 +27,7 @@ gl.issueBoards.BoardSidebar = Vue.extend({
detail: Store.detail,
issue: {},
list: {},
+ loadingAssignees: false,
};
},
computed: {
@@ -43,6 +49,10 @@ gl.issueBoards.BoardSidebar = Vue.extend({
this.issue = this.detail.issue;
this.list = this.detail.list;
+
+ this.$nextTick(() => {
+ this.endpoint = this.$refs.assigneeDropdown.dataset.issueUpdate;
+ });
},
deep: true
},
@@ -53,12 +63,57 @@ gl.issueBoards.BoardSidebar = Vue.extend({
$('.right-sidebar').getNiceScroll().resize();
});
}
- }
+
+ this.issue = this.detail.issue;
+ this.list = this.detail.list;
+ },
+ deep: true
},
methods: {
closeSidebar () {
this.detail.issue = {};
- }
+ },
+ assignSelf () {
+ // Notify gl dropdown that we are now assigning to current user
+ this.$refs.assigneeBlock.dispatchEvent(new Event('assignYourself'));
+
+ this.addAssignee(this.currentUser);
+ this.saveAssignees();
+ },
+ removeAssignee (a) {
+ gl.issueBoards.BoardsStore.detail.issue.removeAssignee(a);
+ },
+ addAssignee (a) {
+ gl.issueBoards.BoardsStore.detail.issue.addAssignee(a);
+ },
+ removeAllAssignees () {
+ gl.issueBoards.BoardsStore.detail.issue.removeAllAssignees();
+ },
+ saveAssignees () {
+ this.loadingAssignees = true;
+
+ gl.issueBoards.BoardsStore.detail.issue.update(this.endpoint)
+ .then(() => {
+ this.loadingAssignees = false;
+ })
+ .catch(() => {
+ this.loadingAssignees = false;
+ return new Flash('An error occurred while saving assignees');
+ });
+ },
+ },
+ created () {
+ // Get events from glDropdown
+ eventHub.$on('sidebar.removeAssignee', this.removeAssignee);
+ eventHub.$on('sidebar.addAssignee', this.addAssignee);
+ eventHub.$on('sidebar.removeAllAssignees', this.removeAllAssignees);
+ eventHub.$on('sidebar.saveAssignees', this.saveAssignees);
+ },
+ beforeDestroy() {
+ eventHub.$off('sidebar.removeAssignee', this.removeAssignee);
+ eventHub.$off('sidebar.addAssignee', this.addAssignee);
+ eventHub.$off('sidebar.removeAllAssignees', this.removeAllAssignees);
+ eventHub.$off('sidebar.saveAssignees', this.saveAssignees);
},
mounted () {
new IssuableContext(this.currentUser);
@@ -70,5 +125,7 @@ gl.issueBoards.BoardSidebar = Vue.extend({
},
components: {
removeBtn: gl.issueBoards.RemoveIssueBtn,
+ 'assignee-title': AssigneeTitle,
+ assignees: Assignees,
},
});
diff --git a/app/assets/javascripts/boards/components/issue_card_inner.js b/app/assets/javascripts/boards/components/issue_card_inner.js
index fc154ee7b8b..710207db0c7 100644
--- a/app/assets/javascripts/boards/components/issue_card_inner.js
+++ b/app/assets/javascripts/boards/components/issue_card_inner.js
@@ -31,18 +31,36 @@ gl.issueBoards.IssueCardInner = Vue.extend({
default: false,
},
},
+ data() {
+ return {
+ limitBeforeCounter: 3,
+ maxRender: 4,
+ maxCounter: 99,
+ };
+ },
computed: {
- cardUrl() {
- return `${this.issueLinkBase}/${this.issue.id}`;
+ numberOverLimit() {
+ return this.issue.assignees.length - this.limitBeforeCounter;
},
- assigneeUrl() {
- return `${this.rootPath}${this.issue.assignee.username}`;
+ assigneeCounterTooltip() {
+ return `${this.assigneeCounterLabel} more`;
+ },
+ assigneeCounterLabel() {
+ if (this.numberOverLimit > this.maxCounter) {
+ return `${this.maxCounter}+`;
+ }
+
+ return `+${this.numberOverLimit}`;
},
- assigneeUrlTitle() {
- return `Assigned to ${this.issue.assignee.name}`;
+ shouldRenderCounter() {
+ if (this.issue.assignees.length <= this.maxRender) {
+ return false;
+ }
+
+ return this.issue.assignees.length > this.numberOverLimit;
},
- avatarUrlTitle() {
- return `Avatar for ${this.issue.assignee.name}`;
+ cardUrl() {
+ return `${this.issueLinkBase}/${this.issue.id}`;
},
issueId() {
return `#${this.issue.id}`;
@@ -52,6 +70,28 @@ gl.issueBoards.IssueCardInner = Vue.extend({
},
},
methods: {
+ isIndexLessThanlimit(index) {
+ return index < this.limitBeforeCounter;
+ },
+ shouldRenderAssignee(index) {
+ // Eg. maxRender is 4,
+ // Render up to all 4 assignees if there are only 4 assigness
+ // Otherwise render up to the limitBeforeCounter
+ if (this.issue.assignees.length <= this.maxRender) {
+ return index < this.maxRender;
+ }
+
+ return index < this.limitBeforeCounter;
+ },
+ assigneeUrl(assignee) {
+ return `${this.rootPath}${assignee.username}`;
+ },
+ assigneeUrlTitle(assignee) {
+ return `Assigned to ${assignee.name}`;
+ },
+ avatarUrlTitle(assignee) {
+ return `Avatar for ${assignee.name}`;
+ },
showLabel(label) {
if (!this.list) return true;
@@ -105,25 +145,39 @@ gl.issueBoards.IssueCardInner = Vue.extend({
{{ issueId }}
</span>
</h4>
- <a
- class="card-assignee has-tooltip js-no-trigger"
- :href="assigneeUrl"
- :title="assigneeUrlTitle"
- v-if="issue.assignee"
- data-container="body"
- >
- <img
- class="avatar avatar-inline s20 js-no-trigger"
- :src="issue.assignee.avatar"
- width="20"
- height="20"
- :alt="avatarUrlTitle"
- />
- </a>
+ <div class="card-assignee">
+ <a
+ class="has-tooltip js-no-trigger"
+ :href="assigneeUrl(assignee)"
+ :title="assigneeUrlTitle(assignee)"
+ v-for="(assignee, index) in issue.assignees"
+ v-if="shouldRenderAssignee(index)"
+ data-container="body"
+ data-placement="bottom"
+ >
+ <img
+ class="avatar avatar-inline s20"
+ :src="assignee.avatar"
+ width="20"
+ height="20"
+ :alt="avatarUrlTitle(assignee)"
+ />
+ </a>
+ <span
+ class="avatar-counter has-tooltip"
+ :title="assigneeCounterTooltip"
+ v-if="shouldRenderCounter"
+ >
+ {{ assigneeCounterLabel }}
+ </span>
+ </div>
</div>
- <div class="card-footer" v-if="showLabelFooter">
+ <div
+ class="card-footer"
+ v-if="showLabelFooter"
+ >
<button
- class="label color-label has-tooltip js-no-trigger"
+ class="label color-label has-tooltip"
v-for="label in issue.labels"
type="button"
v-if="showLabel(label)"
diff --git a/app/assets/javascripts/boards/components/new_list_dropdown.js b/app/assets/javascripts/boards/components/new_list_dropdown.js
index 7e3bb79af1d..f29b6caa1ac 100644
--- a/app/assets/javascripts/boards/components/new_list_dropdown.js
+++ b/app/assets/javascripts/boards/components/new_list_dropdown.js
@@ -52,7 +52,9 @@ gl.issueBoards.newListDropdownInit = () => {
filterable: true,
selectable: true,
multiSelect: true,
- clicked (label, $el, e) {
+ clicked (options) {
+ const { e } = options;
+ const label = options.selectedObj;
e.preventDefault();
if (!Store.findList('title', label.title)) {
diff --git a/app/assets/javascripts/boards/models/user.js b/app/assets/javascripts/boards/models/assignee.js
index 2af583c3279..05dd449e4fd 100644
--- a/app/assets/javascripts/boards/models/user.js
+++ b/app/assets/javascripts/boards/models/assignee.js
@@ -1,4 +1,6 @@
-class ListUser {
+/* eslint-disable no-unused-vars */
+
+class ListAssignee {
constructor(user, defaultAvatar) {
this.id = user.id;
this.name = user.name;
@@ -7,4 +9,4 @@ class ListUser {
}
}
-window.ListUser = ListUser;
+window.ListAssignee = ListAssignee;
diff --git a/app/assets/javascripts/boards/models/issue.js b/app/assets/javascripts/boards/models/issue.js
index db783467f87..6c2d8a3781b 100644
--- a/app/assets/javascripts/boards/models/issue.js
+++ b/app/assets/javascripts/boards/models/issue.js
@@ -1,7 +1,7 @@
/* eslint-disable no-unused-vars, space-before-function-paren, arrow-body-style, arrow-parens, comma-dangle, max-len */
/* global ListLabel */
/* global ListMilestone */
-/* global ListUser */
+/* global ListAssignee */
import Vue from 'vue';
@@ -14,14 +14,10 @@ class ListIssue {
this.dueDate = obj.due_date;
this.subscribed = obj.subscribed;
this.labels = [];
+ this.assignees = [];
this.selected = false;
- this.assignee = false;
this.position = obj.relative_position || Infinity;
- if (obj.assignee) {
- this.assignee = new ListUser(obj.assignee, defaultAvatar);
- }
-
if (obj.milestone) {
this.milestone = new ListMilestone(obj.milestone);
}
@@ -29,6 +25,8 @@ class ListIssue {
obj.labels.forEach((label) => {
this.labels.push(new ListLabel(label));
});
+
+ this.assignees = obj.assignees.map(a => new ListAssignee(a, defaultAvatar));
}
addLabel (label) {
@@ -51,6 +49,26 @@ class ListIssue {
labels.forEach(this.removeLabel.bind(this));
}
+ addAssignee (assignee) {
+ if (!this.findAssignee(assignee)) {
+ this.assignees.push(new ListAssignee(assignee));
+ }
+ }
+
+ findAssignee (findAssignee) {
+ return this.assignees.filter(assignee => assignee.id === findAssignee.id)[0];
+ }
+
+ removeAssignee (removeAssignee) {
+ if (removeAssignee) {
+ this.assignees = this.assignees.filter(assignee => assignee.id !== removeAssignee.id);
+ }
+ }
+
+ removeAllAssignees () {
+ this.assignees = [];
+ }
+
getLists () {
return gl.issueBoards.BoardsStore.state.lists.filter(list => list.findIssue(this.id));
}
@@ -60,7 +78,7 @@ class ListIssue {
issue: {
milestone_id: this.milestone ? this.milestone.id : null,
due_date: this.dueDate,
- assignee_id: this.assignee ? this.assignee.id : null,
+ assignee_ids: this.assignees.length > 0 ? this.assignees.map((u) => u.id) : [0],
label_ids: this.labels.map((label) => label.id)
}
};
diff --git a/app/assets/javascripts/dispatcher.js b/app/assets/javascripts/dispatcher.js
index b87c57c38fe..b16ff2a0221 100644
--- a/app/assets/javascripts/dispatcher.js
+++ b/app/assets/javascripts/dispatcher.js
@@ -252,6 +252,7 @@ const ShortcutsBlob = require('./shortcuts_blob');
}
break;
case 'projects:pipelines:builds':
+ case 'projects:pipelines:failures':
case 'projects:pipelines:show':
const { controllerAction } = document.querySelector('.js-pipeline-container').dataset;
const pipelineStatusUrl = `${document.querySelector('.js-pipeline-tab-link a').getAttribute('href')}/status.json`;
diff --git a/app/assets/javascripts/filtered_search/components/recent_searches_dropdown_content.js b/app/assets/javascripts/filtered_search/components/recent_searches_dropdown_content.js
index 9126422b335..15052dbd362 100644
--- a/app/assets/javascripts/filtered_search/components/recent_searches_dropdown_content.js
+++ b/app/assets/javascripts/filtered_search/components/recent_searches_dropdown_content.js
@@ -8,6 +8,11 @@ export default {
type: Array,
required: true,
},
+ isLocalStorageAvailable: {
+ type: Boolean,
+ required: false,
+ default: true,
+ },
},
computed: {
@@ -47,7 +52,12 @@ export default {
template: `
<div>
- <ul v-if="hasItems">
+ <div
+ v-if="!isLocalStorageAvailable"
+ class="dropdown-info-note">
+ This feature requires local storage to be enabled
+ </div>
+ <ul v-else-if="hasItems">
<li
v-for="(item, index) in processedItems"
:key="index">
diff --git a/app/assets/javascripts/filtered_search/filtered_search_manager.js b/app/assets/javascripts/filtered_search/filtered_search_manager.js
index 36af0674ac6..9fea563370f 100644
--- a/app/assets/javascripts/filtered_search/filtered_search_manager.js
+++ b/app/assets/javascripts/filtered_search/filtered_search_manager.js
@@ -1,5 +1,3 @@
-/* global Flash */
-
import FilteredSearchContainer from './container';
import RecentSearchesRoot from './recent_searches_root';
import RecentSearchesStore from './stores/recent_searches_store';
@@ -15,7 +13,9 @@ class FilteredSearchManager {
this.tokensContainer = this.container.querySelector('.tokens-container');
this.filteredSearchTokenKeys = gl.FilteredSearchTokenKeys;
- this.recentSearchesStore = new RecentSearchesStore();
+ this.recentSearchesStore = new RecentSearchesStore({
+ isLocalStorageAvailable: RecentSearchesService.isAvailable(),
+ });
let recentSearchesKey = 'issue-recent-searches';
if (page === 'merge_requests') {
recentSearchesKey = 'merge-request-recent-searches';
@@ -24,9 +24,10 @@ class FilteredSearchManager {
// Fetch recent searches from localStorage
this.fetchingRecentSearchesPromise = this.recentSearchesService.fetch()
- .catch(() => {
+ .catch((error) => {
+ if (error.name === 'RecentSearchesServiceError') return undefined;
// eslint-disable-next-line no-new
- new Flash('An error occured while parsing recent searches');
+ new window.Flash('An error occured while parsing recent searches');
// Gracefully fail to empty array
return [];
})
diff --git a/app/assets/javascripts/filtered_search/filtered_search_visual_tokens.js b/app/assets/javascripts/filtered_search/filtered_search_visual_tokens.js
index 453ecccc6fc..f3003b86493 100644
--- a/app/assets/javascripts/filtered_search/filtered_search_visual_tokens.js
+++ b/app/assets/javascripts/filtered_search/filtered_search_visual_tokens.js
@@ -1,3 +1,5 @@
+import AjaxCache from '~/lib/utils/ajax_cache';
+import '~/flash'; /* global Flash */
import FilteredSearchContainer from './container';
class FilteredSearchVisualTokens {
@@ -48,6 +50,40 @@ class FilteredSearchVisualTokens {
`;
}
+ static updateLabelTokenColor(tokenValueContainer, tokenValue) {
+ const filteredSearchInput = FilteredSearchContainer.container.querySelector('.filtered-search');
+ const baseEndpoint = filteredSearchInput.dataset.baseEndpoint;
+ const labelsEndpoint = `${baseEndpoint}/labels.json`;
+
+ return AjaxCache.retrieve(labelsEndpoint)
+ .then((labels) => {
+ const matchingLabel = (labels || []).find(label => `~${gl.DropdownUtils.getEscapedText(label.title)}` === tokenValue);
+
+ if (!matchingLabel) {
+ return;
+ }
+
+ const tokenValueStyle = tokenValueContainer.style;
+ tokenValueStyle.backgroundColor = matchingLabel.color;
+ tokenValueStyle.color = matchingLabel.text_color;
+
+ if (matchingLabel.text_color === '#FFFFFF') {
+ const removeToken = tokenValueContainer.querySelector('.remove-token');
+ removeToken.classList.add('inverted');
+ }
+ })
+ .catch(() => new Flash('An error occurred while fetching label colors.'));
+ }
+
+ static renderVisualTokenValue(parentElement, tokenName, tokenValue) {
+ const tokenValueContainer = parentElement.querySelector('.value-container');
+ tokenValueContainer.querySelector('.value').innerText = tokenValue;
+
+ if (tokenName.toLowerCase() === 'label') {
+ FilteredSearchVisualTokens.updateLabelTokenColor(tokenValueContainer, tokenValue);
+ }
+ }
+
static addVisualTokenElement(name, value, isSearchTerm) {
const li = document.createElement('li');
li.classList.add('js-visual-token');
@@ -55,7 +91,7 @@ class FilteredSearchVisualTokens {
if (value) {
li.innerHTML = FilteredSearchVisualTokens.createVisualTokenElementHTML();
- li.querySelector('.value').innerText = value;
+ FilteredSearchVisualTokens.renderVisualTokenValue(li, name, value);
} else {
li.innerHTML = '<div class="name"></div>';
}
@@ -74,7 +110,7 @@ class FilteredSearchVisualTokens {
const name = FilteredSearchVisualTokens.getLastTokenPartial();
lastVisualToken.innerHTML = FilteredSearchVisualTokens.createVisualTokenElementHTML();
lastVisualToken.querySelector('.name').innerText = name;
- lastVisualToken.querySelector('.value').innerText = value;
+ FilteredSearchVisualTokens.renderVisualTokenValue(lastVisualToken, name, value);
}
}
@@ -183,6 +219,9 @@ class FilteredSearchVisualTokens {
static moveInputToTheRight() {
const input = FilteredSearchContainer.container.querySelector('.filtered-search');
+
+ if (!input) return;
+
const inputLi = input.parentElement;
const tokenContainer = FilteredSearchContainer.container.querySelector('.tokens-container');
diff --git a/app/assets/javascripts/filtered_search/recent_searches_root.js b/app/assets/javascripts/filtered_search/recent_searches_root.js
index 4e38409e12a..b2e6f63aacf 100644
--- a/app/assets/javascripts/filtered_search/recent_searches_root.js
+++ b/app/assets/javascripts/filtered_search/recent_searches_root.js
@@ -29,12 +29,15 @@ class RecentSearchesRoot {
}
render() {
+ const state = this.store.state;
this.vm = new Vue({
el: this.wrapperElement,
- data: this.store.state,
+ data() { return state; },
template: `
<recent-searches-dropdown-content
- :items="recentSearches" />
+ :items="recentSearches"
+ :is-local-storage-available="isLocalStorageAvailable"
+ />
`,
components: {
'recent-searches-dropdown-content': RecentSearchesDropdownContent,
diff --git a/app/assets/javascripts/filtered_search/services/recent_searches_service.js b/app/assets/javascripts/filtered_search/services/recent_searches_service.js
index 3e402d5aed0..a056dea928d 100644
--- a/app/assets/javascripts/filtered_search/services/recent_searches_service.js
+++ b/app/assets/javascripts/filtered_search/services/recent_searches_service.js
@@ -1,9 +1,17 @@
+import RecentSearchesServiceError from './recent_searches_service_error';
+import AccessorUtilities from '../../lib/utils/accessor';
+
class RecentSearchesService {
constructor(localStorageKey = 'issuable-recent-searches') {
this.localStorageKey = localStorageKey;
}
fetch() {
+ if (!RecentSearchesService.isAvailable()) {
+ const error = new RecentSearchesServiceError();
+ return Promise.reject(error);
+ }
+
const input = window.localStorage.getItem(this.localStorageKey);
let searches = [];
@@ -19,8 +27,14 @@ class RecentSearchesService {
}
save(searches = []) {
+ if (!RecentSearchesService.isAvailable()) return;
+
window.localStorage.setItem(this.localStorageKey, JSON.stringify(searches));
}
+
+ static isAvailable() {
+ return AccessorUtilities.isLocalStorageAccessSafe();
+ }
}
export default RecentSearchesService;
diff --git a/app/assets/javascripts/filtered_search/services/recent_searches_service_error.js b/app/assets/javascripts/filtered_search/services/recent_searches_service_error.js
new file mode 100644
index 00000000000..5917b223d63
--- /dev/null
+++ b/app/assets/javascripts/filtered_search/services/recent_searches_service_error.js
@@ -0,0 +1,11 @@
+class RecentSearchesServiceError {
+ constructor(message) {
+ this.name = 'RecentSearchesServiceError';
+ this.message = message || 'Recent Searches Service is unavailable';
+ }
+}
+
+// Can't use `extends` for builtin prototypes and get true inheritance yet
+RecentSearchesServiceError.prototype = Error.prototype;
+
+export default RecentSearchesServiceError;
diff --git a/app/assets/javascripts/gl_dropdown.js b/app/assets/javascripts/gl_dropdown.js
index 689a6b3f856..7d30f9207e9 100644
--- a/app/assets/javascripts/gl_dropdown.js
+++ b/app/assets/javascripts/gl_dropdown.js
@@ -256,7 +256,8 @@ GitLabDropdown = (function() {
}
};
// Remote data
- })(this)
+ })(this),
+ instance: this,
});
}
}
@@ -270,6 +271,7 @@ GitLabDropdown = (function() {
remote: this.options.filterRemote,
query: this.options.data,
keys: searchFields,
+ instance: this,
elements: (function(_this) {
return function() {
selector = '.dropdown-content li:not(' + NON_SELECTABLE_CLASSES + ')';
@@ -344,21 +346,26 @@ GitLabDropdown = (function() {
}
this.dropdown.on("click", selector, function(e) {
var $el, selected, selectedObj, isMarking;
- $el = $(this);
+ $el = $(e.currentTarget);
selected = self.rowClicked($el);
selectedObj = selected ? selected[0] : null;
isMarking = selected ? selected[1] : null;
- if (self.options.clicked) {
- self.options.clicked(selectedObj, $el, e, isMarking);
+ if (this.options.clicked) {
+ this.options.clicked.call(this, {
+ selectedObj,
+ $el,
+ e,
+ isMarking,
+ });
}
// Update label right after all modifications in dropdown has been done
- if (self.options.toggleLabel) {
- self.updateLabel(selectedObj, $el, self);
+ if (this.options.toggleLabel) {
+ this.updateLabel(selectedObj, $el, this);
}
$el.trigger('blur');
- });
+ }.bind(this));
}
}
@@ -440,15 +447,34 @@ GitLabDropdown = (function() {
}
};
+ GitLabDropdown.prototype.filteredFullData = function() {
+ return this.fullData.filter(r => typeof r === 'object'
+ && !Object.prototype.hasOwnProperty.call(r, 'beforeDivider')
+ && !Object.prototype.hasOwnProperty.call(r, 'header')
+ );
+ };
+
GitLabDropdown.prototype.opened = function(e) {
var contentHtml;
this.resetRows();
this.addArrowKeyEvent();
+ const dropdownToggle = this.dropdown.find('.dropdown-menu-toggle');
+ const hasFilterBulkUpdate = dropdownToggle.hasClass('js-filter-bulk-update');
+ const hasMultiSelect = dropdownToggle.hasClass('js-multiselect');
+
// Makes indeterminate items effective
- if (this.fullData && this.dropdown.find('.dropdown-menu-toggle').hasClass('js-filter-bulk-update')) {
+ if (this.fullData && hasFilterBulkUpdate) {
this.parseData(this.fullData);
}
+
+ // Process the data to make sure rendered data
+ // matches the correct layout
+ if (this.fullData && hasMultiSelect && this.options.processData) {
+ const inputValue = this.filterInput.val();
+ this.options.processData.call(this.options, inputValue, this.filteredFullData(), this.parseData.bind(this));
+ }
+
contentHtml = $('.dropdown-content', this.dropdown).html();
if (this.remote && contentHtml === "") {
this.remote.execute();
@@ -710,6 +736,11 @@ GitLabDropdown = (function() {
if (this.options.inputId != null) {
$input.attr('id', this.options.inputId);
}
+
+ if (this.options.inputMeta) {
+ $input.attr('data-meta', selectedObject[this.options.inputMeta]);
+ }
+
return this.dropdown.before($input);
};
@@ -830,7 +861,14 @@ GitLabDropdown = (function() {
if (instance == null) {
instance = null;
}
- return $(this.el).find(".dropdown-toggle-text").text(this.options.toggleLabel(selected, el, instance));
+
+ let toggleText = this.options.toggleLabel(selected, el, instance);
+ if (this.options.updateLabel) {
+ // Option to override the dropdown label text
+ toggleText = this.options.updateLabel;
+ }
+
+ return $(this.el).find(".dropdown-toggle-text").text(toggleText);
};
GitLabDropdown.prototype.clearField = function(field, isInput) {
diff --git a/app/assets/javascripts/issuable/issuable_bundle.js b/app/assets/javascripts/issuable/issuable_bundle.js
deleted file mode 100644
index e927cc0077c..00000000000
--- a/app/assets/javascripts/issuable/issuable_bundle.js
+++ /dev/null
@@ -1 +0,0 @@
-require('./time_tracking/time_tracking_bundle');
diff --git a/app/assets/javascripts/issuable/time_tracking/components/collapsed_state.js b/app/assets/javascripts/issuable/time_tracking/components/collapsed_state.js
deleted file mode 100644
index aec13e78f42..00000000000
--- a/app/assets/javascripts/issuable/time_tracking/components/collapsed_state.js
+++ /dev/null
@@ -1,42 +0,0 @@
-import Vue from 'vue';
-import stopwatchSvg from 'icons/_icon_stopwatch.svg';
-
-require('../../../lib/utils/pretty_time');
-
-(() => {
- Vue.component('time-tracking-collapsed-state', {
- name: 'time-tracking-collapsed-state',
- props: [
- 'showComparisonState',
- 'showSpentOnlyState',
- 'showEstimateOnlyState',
- 'showNoTimeTrackingState',
- 'timeSpentHumanReadable',
- 'timeEstimateHumanReadable',
- ],
- methods: {
- abbreviateTime(timeStr) {
- return gl.utils.prettyTime.abbreviateTime(timeStr);
- },
- },
- template: `
- <div class='sidebar-collapsed-icon'>
- ${stopwatchSvg}
- <div class='time-tracking-collapsed-summary'>
- <div class='compare' v-if='showComparisonState'>
- <span>{{ abbreviateTime(timeSpentHumanReadable) }} / {{ abbreviateTime(timeEstimateHumanReadable) }}</span>
- </div>
- <div class='estimate-only' v-if='showEstimateOnlyState'>
- <span class='bold'>-- / {{ abbreviateTime(timeEstimateHumanReadable) }}</span>
- </div>
- <div class='spend-only' v-if='showSpentOnlyState'>
- <span class='bold'>{{ abbreviateTime(timeSpentHumanReadable) }} / --</span>
- </div>
- <div class='no-tracking' v-if='showNoTimeTrackingState'>
- <span class='no-value'>None</span>
- </div>
- </div>
- </div>
- `,
- });
-})();
diff --git a/app/assets/javascripts/issuable/time_tracking/components/comparison_pane.js b/app/assets/javascripts/issuable/time_tracking/components/comparison_pane.js
deleted file mode 100644
index c55e263f6f4..00000000000
--- a/app/assets/javascripts/issuable/time_tracking/components/comparison_pane.js
+++ /dev/null
@@ -1,70 +0,0 @@
-import Vue from 'vue';
-
-require('../../../lib/utils/pretty_time');
-
-(() => {
- const prettyTime = gl.utils.prettyTime;
-
- Vue.component('time-tracking-comparison-pane', {
- name: 'time-tracking-comparison-pane',
- props: [
- 'timeSpent',
- 'timeEstimate',
- 'timeSpentHumanReadable',
- 'timeEstimateHumanReadable',
- ],
- computed: {
- parsedRemaining() {
- const diffSeconds = this.timeEstimate - this.timeSpent;
- return prettyTime.parseSeconds(diffSeconds);
- },
- timeRemainingHumanReadable() {
- return prettyTime.stringifyTime(this.parsedRemaining);
- },
- timeRemainingTooltip() {
- const prefix = this.timeRemainingMinutes < 0 ? 'Over by' : 'Time remaining:';
- return `${prefix} ${this.timeRemainingHumanReadable}`;
- },
- /* Diff values for comparison meter */
- timeRemainingMinutes() {
- return this.timeEstimate - this.timeSpent;
- },
- timeRemainingPercent() {
- return `${Math.floor((this.timeSpent / this.timeEstimate) * 100)}%`;
- },
- timeRemainingStatusClass() {
- return this.timeEstimate >= this.timeSpent ? 'within_estimate' : 'over_estimate';
- },
- /* Parsed time values */
- parsedEstimate() {
- return prettyTime.parseSeconds(this.timeEstimate);
- },
- parsedSpent() {
- return prettyTime.parseSeconds(this.timeSpent);
- },
- },
- template: `
- <div class='time-tracking-comparison-pane'>
- <div class='compare-meter' data-toggle='tooltip' data-placement='top' role='timeRemainingDisplay'
- :aria-valuenow='timeRemainingTooltip'
- :title='timeRemainingTooltip'
- :data-original-title='timeRemainingTooltip'
- :class='timeRemainingStatusClass'>
- <div class='meter-container' role='timeSpentPercent' :aria-valuenow='timeRemainingPercent'>
- <div :style='{ width: timeRemainingPercent }' class='meter-fill'></div>
- </div>
- <div class='compare-display-container'>
- <div class='compare-display pull-left'>
- <span class='compare-label'>Spent</span>
- <span class='compare-value spent'>{{ timeSpentHumanReadable }}</span>
- </div>
- <div class='compare-display estimated pull-right'>
- <span class='compare-label'>Est</span>
- <span class='compare-value'>{{ timeEstimateHumanReadable }}</span>
- </div>
- </div>
- </div>
- </div>
- `,
- });
-})();
diff --git a/app/assets/javascripts/issuable/time_tracking/components/estimate_only_pane.js b/app/assets/javascripts/issuable/time_tracking/components/estimate_only_pane.js
deleted file mode 100644
index a7fbd704c40..00000000000
--- a/app/assets/javascripts/issuable/time_tracking/components/estimate_only_pane.js
+++ /dev/null
@@ -1,14 +0,0 @@
-import Vue from 'vue';
-
-(() => {
- Vue.component('time-tracking-estimate-only-pane', {
- name: 'time-tracking-estimate-only-pane',
- props: ['timeEstimateHumanReadable'],
- template: `
- <div class='time-tracking-estimate-only-pane'>
- <span class='bold'>Estimated:</span>
- {{ timeEstimateHumanReadable }}
- </div>
- `,
- });
-})();
diff --git a/app/assets/javascripts/issuable/time_tracking/components/help_state.js b/app/assets/javascripts/issuable/time_tracking/components/help_state.js
deleted file mode 100644
index 344b29ebea4..00000000000
--- a/app/assets/javascripts/issuable/time_tracking/components/help_state.js
+++ /dev/null
@@ -1,25 +0,0 @@
-import Vue from 'vue';
-
-(() => {
- Vue.component('time-tracking-help-state', {
- name: 'time-tracking-help-state',
- props: ['docsUrl'],
- template: `
- <div class='time-tracking-help-state'>
- <div class='time-tracking-info'>
- <h4>Track time with slash commands</h4>
- <p>Slash commands can be used in the issues description and comment boxes.</p>
- <p>
- <code>/estimate</code>
- will update the estimated time with the latest command.
- </p>
- <p>
- <code>/spend</code>
- will update the sum of the time spent.
- </p>
- <a class='btn btn-default learn-more-button' :href='docsUrl'>Learn more</a>
- </div>
- </div>
- `,
- });
-})();
diff --git a/app/assets/javascripts/issuable/time_tracking/components/no_tracking_pane.js b/app/assets/javascripts/issuable/time_tracking/components/no_tracking_pane.js
deleted file mode 100644
index b081adf5e64..00000000000
--- a/app/assets/javascripts/issuable/time_tracking/components/no_tracking_pane.js
+++ /dev/null
@@ -1,12 +0,0 @@
-import Vue from 'vue';
-
-(() => {
- Vue.component('time-tracking-no-tracking-pane', {
- name: 'time-tracking-no-tracking-pane',
- template: `
- <div class='time-tracking-no-tracking-pane'>
- <span class='no-value'>No estimate or time spent</span>
- </div>
- `,
- });
-})();
diff --git a/app/assets/javascripts/issuable/time_tracking/components/spent_only_pane.js b/app/assets/javascripts/issuable/time_tracking/components/spent_only_pane.js
deleted file mode 100644
index edb9169112f..00000000000
--- a/app/assets/javascripts/issuable/time_tracking/components/spent_only_pane.js
+++ /dev/null
@@ -1,14 +0,0 @@
-import Vue from 'vue';
-
-(() => {
- Vue.component('time-tracking-spent-only-pane', {
- name: 'time-tracking-spent-only-pane',
- props: ['timeSpentHumanReadable'],
- template: `
- <div class='time-tracking-spend-only-pane'>
- <span class='bold'>Spent:</span>
- {{ timeSpentHumanReadable }}
- </div>
- `,
- });
-})();
diff --git a/app/assets/javascripts/issuable/time_tracking/components/time_tracker.js b/app/assets/javascripts/issuable/time_tracking/components/time_tracker.js
deleted file mode 100644
index 0213522f551..00000000000
--- a/app/assets/javascripts/issuable/time_tracking/components/time_tracker.js
+++ /dev/null
@@ -1,117 +0,0 @@
-import Vue from 'vue';
-
-require('./help_state');
-require('./collapsed_state');
-require('./spent_only_pane');
-require('./no_tracking_pane');
-require('./estimate_only_pane');
-require('./comparison_pane');
-
-(() => {
- Vue.component('issuable-time-tracker', {
- name: 'issuable-time-tracker',
- props: [
- 'time_estimate',
- 'time_spent',
- 'human_time_estimate',
- 'human_time_spent',
- 'docsUrl',
- ],
- data() {
- return {
- showHelp: false,
- };
- },
- computed: {
- timeSpent() {
- return this.time_spent;
- },
- timeEstimate() {
- return this.time_estimate;
- },
- timeEstimateHumanReadable() {
- return this.human_time_estimate;
- },
- timeSpentHumanReadable() {
- return this.human_time_spent;
- },
- hasTimeSpent() {
- return !!this.timeSpent;
- },
- hasTimeEstimate() {
- return !!this.timeEstimate;
- },
- showComparisonState() {
- return this.hasTimeEstimate && this.hasTimeSpent;
- },
- showEstimateOnlyState() {
- return this.hasTimeEstimate && !this.hasTimeSpent;
- },
- showSpentOnlyState() {
- return this.hasTimeSpent && !this.hasTimeEstimate;
- },
- showNoTimeTrackingState() {
- return !this.hasTimeEstimate && !this.hasTimeSpent;
- },
- showHelpState() {
- return !!this.showHelp;
- },
- },
- methods: {
- toggleHelpState(show) {
- this.showHelp = show;
- },
- },
- template: `
- <div class='time_tracker time-tracking-component-wrap' v-cloak>
- <time-tracking-collapsed-state
- :show-comparison-state='showComparisonState'
- :show-help-state='showHelpState'
- :show-spent-only-state='showSpentOnlyState'
- :show-estimate-only-state='showEstimateOnlyState'
- :time-spent-human-readable='timeSpentHumanReadable'
- :time-estimate-human-readable='timeEstimateHumanReadable'>
- </time-tracking-collapsed-state>
- <div class='title hide-collapsed'>
- Time tracking
- <div class='help-button pull-right'
- v-if='!showHelpState'
- @click='toggleHelpState(true)'>
- <i class='fa fa-question-circle' aria-hidden='true'></i>
- </div>
- <div class='close-help-button pull-right'
- v-if='showHelpState'
- @click='toggleHelpState(false)'>
- <i class='fa fa-close' aria-hidden='true'></i>
- </div>
- </div>
- <div class='time-tracking-content hide-collapsed'>
- <time-tracking-estimate-only-pane
- v-if='showEstimateOnlyState'
- :time-estimate-human-readable='timeEstimateHumanReadable'>
- </time-tracking-estimate-only-pane>
- <time-tracking-spent-only-pane
- v-if='showSpentOnlyState'
- :time-spent-human-readable='timeSpentHumanReadable'>
- </time-tracking-spent-only-pane>
- <time-tracking-no-tracking-pane
- v-if='showNoTimeTrackingState'>
- </time-tracking-no-tracking-pane>
- <time-tracking-comparison-pane
- v-if='showComparisonState'
- :time-estimate='timeEstimate'
- :time-spent='timeSpent'
- :time-spent-human-readable='timeSpentHumanReadable'
- :time-estimate-human-readable='timeEstimateHumanReadable'>
- </time-tracking-comparison-pane>
- <transition name='help-state-toggle'>
- <time-tracking-help-state
- v-if='showHelpState'
- :docs-url='docsUrl'>
- </time-tracking-help-state>
- </transition>
- </div>
- </div>
- `,
- });
-})();
diff --git a/app/assets/javascripts/issuable/time_tracking/time_tracking_bundle.js b/app/assets/javascripts/issuable/time_tracking/time_tracking_bundle.js
deleted file mode 100644
index 1689a69e1ed..00000000000
--- a/app/assets/javascripts/issuable/time_tracking/time_tracking_bundle.js
+++ /dev/null
@@ -1,66 +0,0 @@
-import Vue from 'vue';
-import VueResource from 'vue-resource';
-
-require('./components/time_tracker');
-require('../../smart_interval');
-require('../../subbable_resource');
-
-Vue.use(VueResource);
-
-(() => {
- /* This Vue instance represents what will become the parent instance for the
- * sidebar. It will be responsible for managing `issuable` state and propagating
- * changes to sidebar components. We will want to create a separate service to
- * interface with the server at that point.
- */
-
- class IssuableTimeTracking {
- constructor(issuableJSON) {
- const parsedIssuable = JSON.parse(issuableJSON);
- return this.initComponent(parsedIssuable);
- }
-
- initComponent(parsedIssuable) {
- this.parentInstance = new Vue({
- el: '#issuable-time-tracker',
- data: {
- issuable: parsedIssuable,
- },
- methods: {
- fetchIssuable() {
- return gl.IssuableResource.get.call(gl.IssuableResource, {
- type: 'GET',
- url: gl.IssuableResource.endpoint,
- });
- },
- updateState(data) {
- this.issuable = data;
- },
- subscribeToUpdates() {
- gl.IssuableResource.subscribe(data => this.updateState(data));
- },
- listenForSlashCommands() {
- $(document).on('ajax:success', '.gfm-form', (e, data) => {
- const subscribedCommands = ['spend_time', 'time_estimate'];
- const changedCommands = data.commands_changes
- ? Object.keys(data.commands_changes)
- : [];
- if (changedCommands && _.intersection(subscribedCommands, changedCommands).length) {
- this.fetchIssuable();
- }
- });
- },
- },
- created() {
- this.fetchIssuable();
- },
- mounted() {
- this.subscribeToUpdates();
- this.listenForSlashCommands();
- },
- });
- }
- }
-
- gl.IssuableTimeTracking = IssuableTimeTracking;
-})(window.gl || (window.gl = {}));
diff --git a/app/assets/javascripts/issue_show/actions/tasks.js b/app/assets/javascripts/issue_show/actions/tasks.js
new file mode 100644
index 00000000000..0740a9f559c
--- /dev/null
+++ b/app/assets/javascripts/issue_show/actions/tasks.js
@@ -0,0 +1,27 @@
+export default (newStateData, tasks) => {
+ const $tasks = $('#task_status');
+ const $tasksShort = $('#task_status_short');
+ const $issueableHeader = $('.issuable-header');
+ const tasksStates = { newState: null, currentState: null };
+
+ if ($tasks.length === 0) {
+ if (!(newStateData.task_status.indexOf('0 of 0') === 0)) {
+ $issueableHeader.append(`<span id="task_status">${newStateData.task_status}</span>`);
+ } else {
+ $issueableHeader.append('<span id="task_status"></span>');
+ }
+ } else {
+ tasksStates.newState = newStateData.task_status.indexOf('0 of 0') === 0;
+ tasksStates.currentState = tasks.indexOf('0 of 0') === 0;
+ }
+
+ if ($tasks.length !== 0 && !tasksStates.newState) {
+ $tasks.text(newStateData.task_status);
+ $tasksShort.text(newStateData.task_status);
+ } else if (tasksStates.currentState) {
+ $issueableHeader.append(`<span id="task_status">${newStateData.task_status}</span>`);
+ } else if (tasksStates.newState) {
+ $tasks.remove();
+ $tasksShort.remove();
+ }
+};
diff --git a/app/assets/javascripts/issue_show/index.js b/app/assets/javascripts/issue_show/index.js
index 4d491e70d83..eb20a597bb5 100644
--- a/app/assets/javascripts/issue_show/index.js
+++ b/app/assets/javascripts/issue_show/index.js
@@ -1,16 +1,16 @@
import Vue from 'vue';
-import IssueTitle from './issue_title.vue';
+import IssueTitle from './issue_title_description.vue';
import '../vue_shared/vue_resource_interceptor';
(() => {
const issueTitleData = document.querySelector('.issue-title-data').dataset;
- const { initialTitle, endpoint } = issueTitleData;
+ const { canUpdateTasksClass, endpoint } = issueTitleData;
const vm = new Vue({
el: '.issue-title-entrypoint',
render: createElement => createElement(IssueTitle, {
props: {
- initialTitle,
+ canUpdateTasksClass,
endpoint,
},
}),
diff --git a/app/assets/javascripts/issue_show/issue_title.vue b/app/assets/javascripts/issue_show/issue_title.vue
deleted file mode 100644
index 00b0e56030a..00000000000
--- a/app/assets/javascripts/issue_show/issue_title.vue
+++ /dev/null
@@ -1,80 +0,0 @@
-<script>
-import Visibility from 'visibilityjs';
-import Poll from './../lib/utils/poll';
-import Service from './services/index';
-
-export default {
- props: {
- initialTitle: { required: true, type: String },
- endpoint: { required: true, type: String },
- },
- data() {
- const resource = new Service(this.$http, this.endpoint);
-
- const poll = new Poll({
- resource,
- method: 'getTitle',
- successCallback: (res) => {
- this.renderResponse(res);
- },
- errorCallback: (err) => {
- if (process.env.NODE_ENV !== 'production') {
- // eslint-disable-next-line no-console
- console.error('ISSUE SHOW TITLE REALTIME ERROR', err);
- } else {
- throw new Error(err);
- }
- },
- });
-
- return {
- poll,
- timeoutId: null,
- title: this.initialTitle,
- };
- },
- methods: {
- renderResponse(res) {
- const body = JSON.parse(res.body);
- this.triggerAnimation(body);
- },
- triggerAnimation(body) {
- const { title } = body;
-
- /**
- * since opacity is changed, even if there is no diff for Vue to update
- * we must check the title even on a 304 to ensure no visual change
- */
- if (this.title === title) return;
-
- this.$el.style.opacity = 0;
-
- this.timeoutId = setTimeout(() => {
- this.title = title;
-
- this.$el.style.transition = 'opacity 0.2s ease';
- this.$el.style.opacity = 1;
-
- clearTimeout(this.timeoutId);
- }, 100);
- },
- },
- created() {
- if (!Visibility.hidden()) {
- this.poll.makeRequest();
- }
-
- Visibility.change(() => {
- if (!Visibility.hidden()) {
- this.poll.restart();
- } else {
- this.poll.stop();
- }
- });
- },
-};
-</script>
-
-<template>
- <h2 class="title" v-html="title"></h2>
-</template>
diff --git a/app/assets/javascripts/issue_show/issue_title_description.vue b/app/assets/javascripts/issue_show/issue_title_description.vue
new file mode 100644
index 00000000000..dc3ba2550c5
--- /dev/null
+++ b/app/assets/javascripts/issue_show/issue_title_description.vue
@@ -0,0 +1,180 @@
+<script>
+import Visibility from 'visibilityjs';
+import Poll from './../lib/utils/poll';
+import Service from './services/index';
+import tasks from './actions/tasks';
+
+export default {
+ props: {
+ endpoint: {
+ required: true,
+ type: String,
+ },
+ canUpdateTasksClass: {
+ required: true,
+ type: String,
+ },
+ },
+ data() {
+ const resource = new Service(this.$http, this.endpoint);
+
+ const poll = new Poll({
+ resource,
+ method: 'getTitle',
+ successCallback: (res) => {
+ this.renderResponse(res);
+ },
+ errorCallback: (err) => {
+ throw new Error(err);
+ },
+ });
+
+ return {
+ poll,
+ apiData: {},
+ tasks: '0 of 0',
+ title: null,
+ titleText: '',
+ titleFlag: {
+ pre: true,
+ pulse: false,
+ },
+ description: null,
+ descriptionText: '',
+ descriptionChange: false,
+ descriptionFlag: {
+ pre: true,
+ pulse: false,
+ },
+ timeAgoEl: $('.issue_edited_ago'),
+ titleEl: document.querySelector('title'),
+ };
+ },
+ methods: {
+ updateFlag(key, toggle) {
+ this[key].pre = toggle;
+ this[key].pulse = !toggle;
+ },
+ renderResponse(res) {
+ this.apiData = res.json();
+ this.triggerAnimation();
+ },
+ updateTaskHTML() {
+ tasks(this.apiData, this.tasks);
+ },
+ elementsToVisualize(noTitleChange, noDescriptionChange) {
+ if (!noTitleChange) {
+ this.titleText = this.apiData.title_text;
+ this.updateFlag('titleFlag', true);
+ }
+
+ if (!noDescriptionChange) {
+ // only change to true when we need to bind TaskLists the html of description
+ this.descriptionChange = true;
+ this.updateTaskHTML();
+ this.tasks = this.apiData.task_status;
+ this.updateFlag('descriptionFlag', true);
+ }
+ },
+ setTabTitle() {
+ const currentTabTitleScope = this.titleEl.innerText.split('·');
+ currentTabTitleScope[0] = `${this.titleText} (#${this.apiData.issue_number}) `;
+ this.titleEl.innerText = currentTabTitleScope.join('·');
+ },
+ animate(title, description) {
+ this.title = title;
+ this.description = description;
+ this.setTabTitle();
+
+ this.$nextTick(() => {
+ this.updateFlag('titleFlag', false);
+ this.updateFlag('descriptionFlag', false);
+ });
+ },
+ triggerAnimation() {
+ // always reset to false before checking the change
+ this.descriptionChange = false;
+
+ const { title, description } = this.apiData;
+ this.descriptionText = this.apiData.description_text;
+
+ const noTitleChange = this.title === title;
+ const noDescriptionChange = this.description === description;
+
+ /**
+ * since opacity is changed, even if there is no diff for Vue to update
+ * we must check the title/description even on a 304 to ensure no visual change
+ */
+ if (noTitleChange && noDescriptionChange) return;
+
+ this.elementsToVisualize(noTitleChange, noDescriptionChange);
+ this.animate(title, description);
+ },
+ updateEditedTimeAgo() {
+ const toolTipTime = gl.utils.formatDate(this.apiData.updated_at);
+ this.timeAgoEl.attr('datetime', this.apiData.updated_at);
+ this.timeAgoEl.attr('title', toolTipTime).tooltip('fixTitle');
+ },
+ },
+ created() {
+ if (!Visibility.hidden()) {
+ this.poll.makeRequest();
+ }
+
+ Visibility.change(() => {
+ if (!Visibility.hidden()) {
+ this.poll.restart();
+ } else {
+ this.poll.stop();
+ }
+ });
+ },
+ updated() {
+ // if new html is injected (description changed) - bind TaskList and call renderGFM
+ if (this.descriptionChange) {
+ this.updateEditedTimeAgo();
+
+ $(this.$refs['issue-content-container-gfm-entry']).renderGFM();
+
+ const tl = new gl.TaskList({
+ dataType: 'issue',
+ fieldName: 'description',
+ selector: '.detail-page-description',
+ });
+
+ return tl && null;
+ }
+
+ return null;
+ },
+};
+</script>
+
+<template>
+ <div>
+ <h2
+ class="title"
+ :class="{ 'issue-realtime-pre-pulse': titleFlag.pre, 'issue-realtime-trigger-pulse': titleFlag.pulse }"
+ ref="issue-title"
+ v-html="title"
+ >
+ </h2>
+ <div
+ class="description is-task-list-enabled"
+ :class="canUpdateTasksClass"
+ v-if="description"
+ >
+ <div
+ class="wiki"
+ :class="{ 'issue-realtime-pre-pulse': descriptionFlag.pre, 'issue-realtime-trigger-pulse': descriptionFlag.pulse }"
+ v-html="description"
+ ref="issue-content-container-gfm-entry"
+ >
+ </div>
+ <textarea
+ class="hidden js-task-list-field"
+ v-if="descriptionText"
+ >{{descriptionText}}</textarea>
+ </div>
+ </div>
+</template>
diff --git a/app/assets/javascripts/issue_status_select.js b/app/assets/javascripts/issue_status_select.js
index b2cfd3ef2a3..56cb536dcde 100644
--- a/app/assets/javascripts/issue_status_select.js
+++ b/app/assets/javascripts/issue_status_select.js
@@ -19,8 +19,8 @@
return label;
};
})(this),
- clicked: function(item, $el, e) {
- return e.preventDefault();
+ clicked: function(options) {
+ return options.e.preventDefault();
},
id: function(obj, el) {
return $(el).data("id");
diff --git a/app/assets/javascripts/issues_bulk_assignment.js b/app/assets/javascripts/issues_bulk_assignment.js
index e0ebd36a65c..fee3429e2b8 100644
--- a/app/assets/javascripts/issues_bulk_assignment.js
+++ b/app/assets/javascripts/issues_bulk_assignment.js
@@ -88,7 +88,10 @@
const formData = {
update: {
state_event: this.form.find('input[name="update[state_event]"]').val(),
+ // For Merge Requests
assignee_id: this.form.find('input[name="update[assignee_id]"]').val(),
+ // For Issues
+ assignee_ids: [this.form.find('input[name="update[assignee_ids][]"]').val()],
milestone_id: this.form.find('input[name="update[milestone_id]"]').val(),
issuable_ids: this.form.find('input[name="update[issuable_ids]"]').val(),
subscription_event: this.form.find('input[name="update[subscription_event]"]').val(),
diff --git a/app/assets/javascripts/labels_select.js b/app/assets/javascripts/labels_select.js
index 9a60f5464df..ac5ce84e31b 100644
--- a/app/assets/javascripts/labels_select.js
+++ b/app/assets/javascripts/labels_select.js
@@ -330,7 +330,10 @@
},
multiSelect: $dropdown.hasClass('js-multiselect'),
vue: $dropdown.hasClass('js-issue-board-sidebar'),
- clicked: function(label, $el, e, isMarking) {
+ clicked: function(options) {
+ const { $el, e, isMarking } = options;
+ const label = options.selectedObj;
+
var isIssueIndex, isMRIndex, page, boardsModel;
var fadeOutLoader = () => {
$loading.fadeOut();
@@ -352,7 +355,7 @@
if ($dropdown.hasClass('js-filter-bulk-update')) {
_this.enableBulkLabelDropdown();
- _this.setDropdownData($dropdown, isMarking, this.id(label));
+ _this.setDropdownData($dropdown, isMarking, label.id);
return;
}
diff --git a/app/assets/javascripts/lib/utils/accessor.js b/app/assets/javascripts/lib/utils/accessor.js
new file mode 100644
index 00000000000..1d18992af63
--- /dev/null
+++ b/app/assets/javascripts/lib/utils/accessor.js
@@ -0,0 +1,47 @@
+function isPropertyAccessSafe(base, property) {
+ let safe;
+
+ try {
+ safe = !!base[property];
+ } catch (error) {
+ safe = false;
+ }
+
+ return safe;
+}
+
+function isFunctionCallSafe(base, functionName, ...args) {
+ let safe = true;
+
+ try {
+ base[functionName](...args);
+ } catch (error) {
+ safe = false;
+ }
+
+ return safe;
+}
+
+function isLocalStorageAccessSafe() {
+ let safe;
+
+ const TEST_KEY = 'isLocalStorageAccessSafe';
+ const TEST_VALUE = 'true';
+
+ safe = isPropertyAccessSafe(window, 'localStorage');
+ if (!safe) return safe;
+
+ safe = isFunctionCallSafe(window.localStorage, 'setItem', TEST_KEY, TEST_VALUE);
+
+ if (safe) window.localStorage.removeItem(TEST_KEY);
+
+ return safe;
+}
+
+const AccessorUtilities = {
+ isPropertyAccessSafe,
+ isFunctionCallSafe,
+ isLocalStorageAccessSafe,
+};
+
+export default AccessorUtilities;
diff --git a/app/assets/javascripts/lib/utils/ajax_cache.js b/app/assets/javascripts/lib/utils/ajax_cache.js
new file mode 100644
index 00000000000..d99eefb5089
--- /dev/null
+++ b/app/assets/javascripts/lib/utils/ajax_cache.js
@@ -0,0 +1,32 @@
+const AjaxCache = {
+ internalStorage: { },
+ get(endpoint) {
+ return this.internalStorage[endpoint];
+ },
+ hasData(endpoint) {
+ return Object.prototype.hasOwnProperty.call(this.internalStorage, endpoint);
+ },
+ purge(endpoint) {
+ delete this.internalStorage[endpoint];
+ },
+ retrieve(endpoint) {
+ if (AjaxCache.hasData(endpoint)) {
+ return Promise.resolve(AjaxCache.get(endpoint));
+ }
+
+ return new Promise((resolve, reject) => {
+ $.ajax(endpoint) // eslint-disable-line promise/catch-or-return
+ .then(data => resolve(data),
+ (jqXHR, textStatus, errorThrown) => {
+ const error = new Error(`${endpoint}: ${errorThrown}`);
+ error.textStatus = textStatus;
+ reject(error);
+ },
+ );
+ })
+ .then((data) => { this.internalStorage[endpoint] = data; })
+ .then(() => AjaxCache.get(endpoint));
+ },
+};
+
+export default AjaxCache;
diff --git a/app/assets/javascripts/main.js b/app/assets/javascripts/main.js
index 1c60b3b0b3b..c660d6919f6 100644
--- a/app/assets/javascripts/main.js
+++ b/app/assets/javascripts/main.js
@@ -157,7 +157,6 @@ import './single_file_diff';
import './smart_interval';
import './snippets_list';
import './star';
-import './subbable_resource';
import './subscription';
import './subscription_select';
import './syntax_highlight';
diff --git a/app/assets/javascripts/members.js b/app/assets/javascripts/members.js
index e3f367a11eb..8291b8c4a70 100644
--- a/app/assets/javascripts/members.js
+++ b/app/assets/javascripts/members.js
@@ -31,8 +31,8 @@
toggleLabel(selected, $el) {
return $el.text();
},
- clicked: (selected, $link) => {
- this.formSubmit(null, $link);
+ clicked: (options) => {
+ this.formSubmit(null, options.$el);
},
});
});
diff --git a/app/assets/javascripts/milestone_select.js b/app/assets/javascripts/milestone_select.js
index bebd0aa357e..11e68c0a3be 100644
--- a/app/assets/javascripts/milestone_select.js
+++ b/app/assets/javascripts/milestone_select.js
@@ -121,7 +121,10 @@
return $value.css('display', '');
},
vue: $dropdown.hasClass('js-issue-board-sidebar'),
- clicked: function(selected, $el, e) {
+ clicked: function(options) {
+ const { $el, e } = options;
+ let selected = options.selectedObj;
+
var data, isIssueIndex, isMRIndex, page, boardsStore;
page = $('body').data('page');
isIssueIndex = page === 'projects:issues:index';
diff --git a/app/assets/javascripts/namespace_select.js b/app/assets/javascripts/namespace_select.js
index b98e6121967..36bc1257cef 100644
--- a/app/assets/javascripts/namespace_select.js
+++ b/app/assets/javascripts/namespace_select.js
@@ -58,7 +58,8 @@
});
}
- NamespaceSelect.prototype.onSelectItem = function(item, el, e) {
+ NamespaceSelect.prototype.onSelectItem = function(options) {
+ const { e } = options;
return e.preventDefault();
};
diff --git a/app/assets/javascripts/notes.js b/app/assets/javascripts/notes.js
index 72709f68070..55391ebc089 100644
--- a/app/assets/javascripts/notes.js
+++ b/app/assets/javascripts/notes.js
@@ -1356,7 +1356,7 @@ const normalizeNewlines = function(str) {
// Show updated comment content temporarily
$noteBodyText.html(formContent);
- $editingNote.removeClass('is-editing').addClass('being-posted fade-in-half');
+ $editingNote.removeClass('is-editing fade-in-full').addClass('being-posted fade-in-half');
$editingNote.find('.note-headline-meta a').html('<i class="fa fa-spinner fa-spin" aria-label="Comment is being updated" aria-hidden="true"></i>');
/* eslint-disable promise/catch-or-return */
diff --git a/app/assets/javascripts/project.js b/app/assets/javascripts/project.js
index f944fcc5a58..738e710deb9 100644
--- a/app/assets/javascripts/project.js
+++ b/app/assets/javascripts/project.js
@@ -112,7 +112,8 @@ import Cookies from 'js-cookie';
toggleLabel: function(obj, $el) {
return $el.text().trim();
},
- clicked: function(selected, $el, e) {
+ clicked: function(options) {
+ const { e } = options;
e.preventDefault();
if ($('input[name="ref"]').length) {
var $form = $dropdown.closest('form');
diff --git a/app/assets/javascripts/protected_branches/protected_branch_access_dropdown.js b/app/assets/javascripts/protected_branches/protected_branch_access_dropdown.js
index e7fff57ff45..42993a252c3 100644
--- a/app/assets/javascripts/protected_branches/protected_branch_access_dropdown.js
+++ b/app/assets/javascripts/protected_branches/protected_branch_access_dropdown.js
@@ -19,7 +19,9 @@
return 'Select';
}
},
- clicked(item, $el, e) {
+ clicked(opts) {
+ const { e } = opts;
+
e.preventDefault();
onSelect();
}
diff --git a/app/assets/javascripts/protected_branches/protected_branch_dropdown.js b/app/assets/javascripts/protected_branches/protected_branch_dropdown.js
index 1d4bb8a13d6..bc6110fcd4e 100644
--- a/app/assets/javascripts/protected_branches/protected_branch_dropdown.js
+++ b/app/assets/javascripts/protected_branches/protected_branch_dropdown.js
@@ -35,7 +35,8 @@ class ProtectedBranchDropdown {
return _.escape(protectedBranch.id);
},
onFilter: this.toggleCreateNewButton.bind(this),
- clicked: (item, $el, e) => {
+ clicked: (options) => {
+ const { $el, e } = options;
e.preventDefault();
this.onSelect();
}
diff --git a/app/assets/javascripts/protected_tags/protected_tag_access_dropdown.js b/app/assets/javascripts/protected_tags/protected_tag_access_dropdown.js
index fff83f3af3b..d4c9a91a74a 100644
--- a/app/assets/javascripts/protected_tags/protected_tag_access_dropdown.js
+++ b/app/assets/javascripts/protected_tags/protected_tag_access_dropdown.js
@@ -17,8 +17,8 @@ export default class ProtectedTagAccessDropdown {
}
return 'Select';
},
- clicked(item, $el, e) {
- e.preventDefault();
+ clicked(options) {
+ options.e.preventDefault();
onSelect();
},
});
diff --git a/app/assets/javascripts/protected_tags/protected_tag_dropdown.js b/app/assets/javascripts/protected_tags/protected_tag_dropdown.js
index 5ff4e443262..068e9698e1d 100644
--- a/app/assets/javascripts/protected_tags/protected_tag_dropdown.js
+++ b/app/assets/javascripts/protected_tags/protected_tag_dropdown.js
@@ -39,8 +39,8 @@ export default class ProtectedTagDropdown {
return _.escape(protectedTag.id);
},
onFilter: this.toggleCreateNewButton.bind(this),
- clicked: (item, $el, e) => {
- e.preventDefault();
+ clicked: (options) => {
+ options.e.preventDefault();
this.onSelect();
},
});
diff --git a/app/assets/javascripts/raven/index.js b/app/assets/javascripts/raven/index.js
new file mode 100644
index 00000000000..5325e495815
--- /dev/null
+++ b/app/assets/javascripts/raven/index.js
@@ -0,0 +1,16 @@
+import RavenConfig from './raven_config';
+
+const index = function index() {
+ RavenConfig.init({
+ sentryDsn: gon.sentry_dsn,
+ currentUserId: gon.current_user_id,
+ whitelistUrls: [gon.gitlab_url],
+ isProduction: process.env.NODE_ENV,
+ });
+
+ return RavenConfig;
+};
+
+index();
+
+export default index;
diff --git a/app/assets/javascripts/raven/raven_config.js b/app/assets/javascripts/raven/raven_config.js
new file mode 100644
index 00000000000..c7fe1cacf49
--- /dev/null
+++ b/app/assets/javascripts/raven/raven_config.js
@@ -0,0 +1,100 @@
+import Raven from 'raven-js';
+
+const IGNORE_ERRORS = [
+ // Random plugins/extensions
+ 'top.GLOBALS',
+ // See: http://blog.errorception.com/2012/03/tale-of-unfindable-js-error. html
+ 'originalCreateNotification',
+ 'canvas.contentDocument',
+ 'MyApp_RemoveAllHighlights',
+ 'http://tt.epicplay.com',
+ 'Can\'t find variable: ZiteReader',
+ 'jigsaw is not defined',
+ 'ComboSearch is not defined',
+ 'http://loading.retry.widdit.com/',
+ 'atomicFindClose',
+ // Facebook borked
+ 'fb_xd_fragment',
+ // ISP "optimizing" proxy - `Cache-Control: no-transform` seems to
+ // reduce this. (thanks @acdha)
+ // See http://stackoverflow.com/questions/4113268
+ 'bmi_SafeAddOnload',
+ 'EBCallBackMessageReceived',
+ // See http://toolbar.conduit.com/Developer/HtmlAndGadget/Methods/JSInjection.aspx
+ 'conduitPage',
+];
+
+const IGNORE_URLS = [
+ // Facebook flakiness
+ /graph\.facebook\.com/i,
+ // Facebook blocked
+ /connect\.facebook\.net\/en_US\/all\.js/i,
+ // Woopra flakiness
+ /eatdifferent\.com\.woopra-ns\.com/i,
+ /static\.woopra\.com\/js\/woopra\.js/i,
+ // Chrome extensions
+ /extensions\//i,
+ /^chrome:\/\//i,
+ // Other plugins
+ /127\.0\.0\.1:4001\/isrunning/i, // Cacaoweb
+ /webappstoolbarba\.texthelp\.com\//i,
+ /metrics\.itunes\.apple\.com\.edgesuite\.net\//i,
+];
+
+const SAMPLE_RATE = 95;
+
+const RavenConfig = {
+ IGNORE_ERRORS,
+ IGNORE_URLS,
+ SAMPLE_RATE,
+ init(options = {}) {
+ this.options = options;
+
+ this.configure();
+ this.bindRavenErrors();
+ if (this.options.currentUserId) this.setUser();
+ },
+
+ configure() {
+ Raven.config(this.options.sentryDsn, {
+ whitelistUrls: this.options.whitelistUrls,
+ environment: this.options.isProduction ? 'production' : 'development',
+ ignoreErrors: this.IGNORE_ERRORS,
+ ignoreUrls: this.IGNORE_URLS,
+ shouldSendCallback: this.shouldSendSample.bind(this),
+ }).install();
+ },
+
+ setUser() {
+ Raven.setUserContext({
+ id: this.options.currentUserId,
+ });
+ },
+
+ bindRavenErrors() {
+ window.$(document).on('ajaxError.raven', this.handleRavenErrors);
+ },
+
+ handleRavenErrors(event, req, config, err) {
+ const error = err || req.statusText;
+ const responseText = req.responseText || 'Unknown response text';
+
+ Raven.captureMessage(error, {
+ extra: {
+ type: config.type,
+ url: config.url,
+ data: config.data,
+ status: req.status,
+ response: responseText,
+ error,
+ event,
+ },
+ });
+ },
+
+ shouldSendSample() {
+ return Math.random() * 100 <= this.SAMPLE_RATE;
+ },
+};
+
+export default RavenConfig;
diff --git a/app/assets/javascripts/sidebar/components/assignees/assignee_title.js b/app/assets/javascripts/sidebar/components/assignees/assignee_title.js
new file mode 100644
index 00000000000..a9ad3708514
--- /dev/null
+++ b/app/assets/javascripts/sidebar/components/assignees/assignee_title.js
@@ -0,0 +1,41 @@
+export default {
+ name: 'AssigneeTitle',
+ props: {
+ loading: {
+ type: Boolean,
+ required: false,
+ default: false,
+ },
+ numberOfAssignees: {
+ type: Number,
+ required: true,
+ },
+ editable: {
+ type: Boolean,
+ required: true,
+ },
+ },
+ computed: {
+ assigneeTitle() {
+ const assignees = this.numberOfAssignees;
+ return assignees > 1 ? `${assignees} Assignees` : 'Assignee';
+ },
+ },
+ template: `
+ <div class="title hide-collapsed">
+ {{assigneeTitle}}
+ <i
+ v-if="loading"
+ aria-hidden="true"
+ class="fa fa-spinner fa-spin block-loading"
+ />
+ <a
+ v-if="editable"
+ class="edit-link pull-right"
+ href="#"
+ >
+ Edit
+ </a>
+ </div>
+ `,
+};
diff --git a/app/assets/javascripts/sidebar/components/assignees/assignees.js b/app/assets/javascripts/sidebar/components/assignees/assignees.js
new file mode 100644
index 00000000000..7e5feac622c
--- /dev/null
+++ b/app/assets/javascripts/sidebar/components/assignees/assignees.js
@@ -0,0 +1,224 @@
+export default {
+ name: 'Assignees',
+ data() {
+ return {
+ defaultRenderCount: 5,
+ defaultMaxCounter: 99,
+ showLess: true,
+ };
+ },
+ props: {
+ rootPath: {
+ type: String,
+ required: true,
+ },
+ users: {
+ type: Array,
+ required: true,
+ },
+ editable: {
+ type: Boolean,
+ required: true,
+ },
+ },
+ computed: {
+ firstUser() {
+ return this.users[0];
+ },
+ hasMoreThanTwoAssignees() {
+ return this.users.length > 2;
+ },
+ hasMoreThanOneAssignee() {
+ return this.users.length > 1;
+ },
+ hasAssignees() {
+ return this.users.length > 0;
+ },
+ hasNoUsers() {
+ return !this.users.length;
+ },
+ hasOneUser() {
+ return this.users.length === 1;
+ },
+ renderShowMoreSection() {
+ return this.users.length > this.defaultRenderCount;
+ },
+ numberOfHiddenAssignees() {
+ return this.users.length - this.defaultRenderCount;
+ },
+ isHiddenAssignees() {
+ return this.numberOfHiddenAssignees > 0;
+ },
+ hiddenAssigneesLabel() {
+ return `+ ${this.numberOfHiddenAssignees} more`;
+ },
+ collapsedTooltipTitle() {
+ const maxRender = Math.min(this.defaultRenderCount, this.users.length);
+ const renderUsers = this.users.slice(0, maxRender);
+ const names = renderUsers.map(u => u.name);
+
+ if (this.users.length > maxRender) {
+ names.push(`+ ${this.users.length - maxRender} more`);
+ }
+
+ return names.join(', ');
+ },
+ sidebarAvatarCounter() {
+ let counter = `+${this.users.length - 1}`;
+
+ if (this.users.length > this.defaultMaxCounter) {
+ counter = `${this.defaultMaxCounter}+`;
+ }
+
+ return counter;
+ },
+ },
+ methods: {
+ assignSelf() {
+ this.$emit('assign-self');
+ },
+ toggleShowLess() {
+ this.showLess = !this.showLess;
+ },
+ renderAssignee(index) {
+ return !this.showLess || (index < this.defaultRenderCount && this.showLess);
+ },
+ avatarUrl(user) {
+ return user.avatar || user.avatar_url;
+ },
+ assigneeUrl(user) {
+ return `${this.rootPath}${user.username}`;
+ },
+ assigneeAlt(user) {
+ return `${user.name}'s avatar`;
+ },
+ assigneeUsername(user) {
+ return `@${user.username}`;
+ },
+ shouldRenderCollapsedAssignee(index) {
+ const firstTwo = this.users.length <= 2 && index <= 2;
+
+ return index === 0 || firstTwo;
+ },
+ },
+ template: `
+ <div>
+ <div
+ class="sidebar-collapsed-icon sidebar-collapsed-user"
+ :class="{ 'multiple-users': hasMoreThanOneAssignee, 'has-tooltip': hasAssignees }"
+ data-container="body"
+ data-placement="left"
+ :title="collapsedTooltipTitle"
+ >
+ <i
+ v-if="hasNoUsers"
+ aria-label="No Assignee"
+ class="fa fa-user"
+ />
+ <button
+ type="button"
+ class="btn-link"
+ v-for="(user, index) in users"
+ v-if="shouldRenderCollapsedAssignee(index)"
+ >
+ <img
+ width="24"
+ class="avatar avatar-inline s24"
+ :alt="assigneeAlt(user)"
+ :src="avatarUrl(user)"
+ />
+ <span class="author">
+ {{ user.name }}
+ </span>
+ </button>
+ <button
+ v-if="hasMoreThanTwoAssignees"
+ class="btn-link"
+ type="button"
+ >
+ <span
+ class="avatar-counter sidebar-avatar-counter"
+ >
+ {{ sidebarAvatarCounter }}
+ </span>
+ </button>
+ </div>
+ <div class="value hide-collapsed">
+ <template v-if="hasNoUsers">
+ <span class="assign-yourself no-value">
+ No assignee
+ <template v-if="editable">
+ -
+ <button
+ type="button"
+ class="btn-link"
+ @click="assignSelf"
+ >
+ assign yourself
+ </button>
+ </template>
+ </span>
+ </template>
+ <template v-else-if="hasOneUser">
+ <a
+ class="author_link bold"
+ :href="assigneeUrl(firstUser)"
+ >
+ <img
+ width="32"
+ class="avatar avatar-inline s32"
+ :alt="assigneeAlt(firstUser)"
+ :src="avatarUrl(firstUser)"
+ />
+ <span class="author">
+ {{ firstUser.name }}
+ </span>
+ <span class="username">
+ {{ assigneeUsername(firstUser) }}
+ </span>
+ </a>
+ </template>
+ <template v-else>
+ <div class="user-list">
+ <div
+ class="user-item"
+ v-for="(user, index) in users"
+ v-if="renderAssignee(index)"
+ >
+ <a
+ class="user-link has-tooltip"
+ data-placement="bottom"
+ :href="assigneeUrl(user)"
+ :data-title="user.name"
+ >
+ <img
+ width="32"
+ class="avatar avatar-inline s32"
+ :alt="assigneeAlt(user)"
+ :src="avatarUrl(user)"
+ />
+ </a>
+ </div>
+ </div>
+ <div
+ v-if="renderShowMoreSection"
+ class="user-list-more"
+ >
+ <button
+ type="button"
+ class="btn-link"
+ @click="toggleShowLess"
+ >
+ <template v-if="showLess">
+ {{ hiddenAssigneesLabel }}
+ </template>
+ <template v-else>
+ - show less
+ </template>
+ </button>
+ </div>
+ </template>
+ </div>
+ </div>
+ `,
+};
diff --git a/app/assets/javascripts/sidebar/components/assignees/sidebar_assignees.js b/app/assets/javascripts/sidebar/components/assignees/sidebar_assignees.js
new file mode 100644
index 00000000000..1488a66c695
--- /dev/null
+++ b/app/assets/javascripts/sidebar/components/assignees/sidebar_assignees.js
@@ -0,0 +1,84 @@
+/* global Flash */
+
+import AssigneeTitle from './assignee_title';
+import Assignees from './assignees';
+
+import Store from '../../stores/sidebar_store';
+import Mediator from '../../sidebar_mediator';
+
+import eventHub from '../../event_hub';
+
+export default {
+ name: 'SidebarAssignees',
+ data() {
+ return {
+ mediator: new Mediator(),
+ store: new Store(),
+ loading: false,
+ field: '',
+ };
+ },
+ components: {
+ 'assignee-title': AssigneeTitle,
+ assignees: Assignees,
+ },
+ methods: {
+ assignSelf() {
+ // Notify gl dropdown that we are now assigning to current user
+ this.$el.parentElement.dispatchEvent(new Event('assignYourself'));
+
+ this.mediator.assignYourself();
+ this.saveAssignees();
+ },
+ saveAssignees() {
+ this.loading = true;
+
+ function setLoadingFalse() {
+ this.loading = false;
+ }
+
+ this.mediator.saveAssignees(this.field)
+ .then(setLoadingFalse.bind(this))
+ .catch(() => {
+ setLoadingFalse();
+ return new Flash('Error occurred when saving assignees');
+ });
+ },
+ },
+ created() {
+ this.removeAssignee = this.store.removeAssignee.bind(this.store);
+ this.addAssignee = this.store.addAssignee.bind(this.store);
+ this.removeAllAssignees = this.store.removeAllAssignees.bind(this.store);
+
+ // Get events from glDropdown
+ eventHub.$on('sidebar.removeAssignee', this.removeAssignee);
+ eventHub.$on('sidebar.addAssignee', this.addAssignee);
+ eventHub.$on('sidebar.removeAllAssignees', this.removeAllAssignees);
+ eventHub.$on('sidebar.saveAssignees', this.saveAssignees);
+ },
+ beforeDestroy() {
+ eventHub.$off('sidebar.removeAssignee', this.removeAssignee);
+ eventHub.$off('sidebar.addAssignee', this.addAssignee);
+ eventHub.$off('sidebar.removeAllAssignees', this.removeAllAssignees);
+ eventHub.$off('sidebar.saveAssignees', this.saveAssignees);
+ },
+ beforeMount() {
+ this.field = this.$el.dataset.field;
+ },
+ template: `
+ <div>
+ <assignee-title
+ :number-of-assignees="store.assignees.length"
+ :loading="loading"
+ :editable="store.editable"
+ />
+ <assignees
+ class="value"
+ :root-path="store.rootPath"
+ :users="store.assignees"
+ :editable="store.editable"
+ @assign-self="assignSelf"
+ />
+ </div>
+ `,
+};
diff --git a/app/assets/javascripts/sidebar/components/time_tracking/collapsed_state.js b/app/assets/javascripts/sidebar/components/time_tracking/collapsed_state.js
new file mode 100644
index 00000000000..0da265053bd
--- /dev/null
+++ b/app/assets/javascripts/sidebar/components/time_tracking/collapsed_state.js
@@ -0,0 +1,97 @@
+import stopwatchSvg from 'icons/_icon_stopwatch.svg';
+
+import '../../../lib/utils/pretty_time';
+
+export default {
+ name: 'time-tracking-collapsed-state',
+ props: {
+ showComparisonState: {
+ type: Boolean,
+ required: true,
+ },
+ showSpentOnlyState: {
+ type: Boolean,
+ required: true,
+ },
+ showEstimateOnlyState: {
+ type: Boolean,
+ required: true,
+ },
+ showNoTimeTrackingState: {
+ type: Boolean,
+ required: true,
+ },
+ timeSpentHumanReadable: {
+ type: String,
+ required: false,
+ default: '',
+ },
+ timeEstimateHumanReadable: {
+ type: String,
+ required: false,
+ default: '',
+ },
+ },
+ computed: {
+ timeSpent() {
+ return this.abbreviateTime(this.timeSpentHumanReadable);
+ },
+ timeEstimate() {
+ return this.abbreviateTime(this.timeEstimateHumanReadable);
+ },
+ divClass() {
+ if (this.showComparisonState) {
+ return 'compare';
+ } else if (this.showEstimateOnlyState) {
+ return 'estimate-only';
+ } else if (this.showSpentOnlyState) {
+ return 'spend-only';
+ } else if (this.showNoTimeTrackingState) {
+ return 'no-tracking';
+ }
+
+ return '';
+ },
+ spanClass() {
+ if (this.showComparisonState) {
+ return '';
+ } else if (this.showEstimateOnlyState || this.showSpentOnlyState) {
+ return 'bold';
+ } else if (this.showNoTimeTrackingState) {
+ return 'no-value';
+ }
+
+ return '';
+ },
+ text() {
+ if (this.showComparisonState) {
+ return `${this.timeSpent} / ${this.timeEstimate}`;
+ } else if (this.showEstimateOnlyState) {
+ return `-- / ${this.timeEstimate}`;
+ } else if (this.showSpentOnlyState) {
+ return `${this.timeSpent} / --`;
+ } else if (this.showNoTimeTrackingState) {
+ return 'None';
+ }
+
+ return '';
+ },
+ },
+ methods: {
+ abbreviateTime(timeStr) {
+ return gl.utils.prettyTime.abbreviateTime(timeStr);
+ },
+ },
+ template: `
+ <div class="sidebar-collapsed-icon">
+ ${stopwatchSvg}
+ <div class="time-tracking-collapsed-summary">
+ <div :class="divClass">
+ <span :class="spanClass">
+ {{ text }}
+ </span>
+ </div>
+ </div>
+ </div>
+ `,
+};
diff --git a/app/assets/javascripts/sidebar/components/time_tracking/comparison_pane.js b/app/assets/javascripts/sidebar/components/time_tracking/comparison_pane.js
new file mode 100644
index 00000000000..40f5c89c5bb
--- /dev/null
+++ b/app/assets/javascripts/sidebar/components/time_tracking/comparison_pane.js
@@ -0,0 +1,98 @@
+import '../../../lib/utils/pretty_time';
+
+const prettyTime = gl.utils.prettyTime;
+
+export default {
+ name: 'time-tracking-comparison-pane',
+ props: {
+ timeSpent: {
+ type: Number,
+ required: true,
+ },
+ timeEstimate: {
+ type: Number,
+ required: true,
+ },
+ timeSpentHumanReadable: {
+ type: String,
+ required: true,
+ },
+ timeEstimateHumanReadable: {
+ type: String,
+ required: true,
+ },
+ },
+ computed: {
+ parsedRemaining() {
+ const diffSeconds = this.timeEstimate - this.timeSpent;
+ return prettyTime.parseSeconds(diffSeconds);
+ },
+ timeRemainingHumanReadable() {
+ return prettyTime.stringifyTime(this.parsedRemaining);
+ },
+ timeRemainingTooltip() {
+ const prefix = this.timeRemainingMinutes < 0 ? 'Over by' : 'Time remaining:';
+ return `${prefix} ${this.timeRemainingHumanReadable}`;
+ },
+ /* Diff values for comparison meter */
+ timeRemainingMinutes() {
+ return this.timeEstimate - this.timeSpent;
+ },
+ timeRemainingPercent() {
+ return `${Math.floor((this.timeSpent / this.timeEstimate) * 100)}%`;
+ },
+ timeRemainingStatusClass() {
+ return this.timeEstimate >= this.timeSpent ? 'within_estimate' : 'over_estimate';
+ },
+ /* Parsed time values */
+ parsedEstimate() {
+ return prettyTime.parseSeconds(this.timeEstimate);
+ },
+ parsedSpent() {
+ return prettyTime.parseSeconds(this.timeSpent);
+ },
+ },
+ template: `
+ <div class="time-tracking-comparison-pane">
+ <div
+ class="compare-meter"
+ data-toggle="tooltip"
+ data-placement="top"
+ role="timeRemainingDisplay"
+ :aria-valuenow="timeRemainingTooltip"
+ :title="timeRemainingTooltip"
+ :data-original-title="timeRemainingTooltip"
+ :class="timeRemainingStatusClass"
+ >
+ <div
+ class="meter-container"
+ role="timeSpentPercent"
+ :aria-valuenow="timeRemainingPercent"
+ >
+ <div
+ :style="{ width: timeRemainingPercent }"
+ class="meter-fill"
+ />
+ </div>
+ <div class="compare-display-container">
+ <div class="compare-display pull-left">
+ <span class="compare-label">
+ Spent
+ </span>
+ <span class="compare-value spent">
+ {{ timeSpentHumanReadable }}
+ </span>
+ </div>
+ <div class="compare-display estimated pull-right">
+ <span class="compare-label">
+ Est
+ </span>
+ <span class="compare-value">
+ {{ timeEstimateHumanReadable }}
+ </span>
+ </div>
+ </div>
+ </div>
+ </div>
+ `,
+};
diff --git a/app/assets/javascripts/sidebar/components/time_tracking/estimate_only_pane.js b/app/assets/javascripts/sidebar/components/time_tracking/estimate_only_pane.js
new file mode 100644
index 00000000000..ad1b9179db0
--- /dev/null
+++ b/app/assets/javascripts/sidebar/components/time_tracking/estimate_only_pane.js
@@ -0,0 +1,17 @@
+export default {
+ name: 'time-tracking-estimate-only-pane',
+ props: {
+ timeEstimateHumanReadable: {
+ type: String,
+ required: true,
+ },
+ },
+ template: `
+ <div class="time-tracking-estimate-only-pane">
+ <span class="bold">
+ Estimated:
+ </span>
+ {{ timeEstimateHumanReadable }}
+ </div>
+ `,
+};
diff --git a/app/assets/javascripts/sidebar/components/time_tracking/help_state.js b/app/assets/javascripts/sidebar/components/time_tracking/help_state.js
new file mode 100644
index 00000000000..b2a77462fe0
--- /dev/null
+++ b/app/assets/javascripts/sidebar/components/time_tracking/help_state.js
@@ -0,0 +1,44 @@
+export default {
+ name: 'time-tracking-help-state',
+ props: {
+ rootPath: {
+ type: String,
+ required: true,
+ },
+ },
+ computed: {
+ href() {
+ return `${this.rootPath}help/workflow/time_tracking.md`;
+ },
+ },
+ template: `
+ <div class="time-tracking-help-state">
+ <div class="time-tracking-info">
+ <h4>
+ Track time with slash commands
+ </h4>
+ <p>
+ Slash commands can be used in the issues description and comment boxes.
+ </p>
+ <p>
+ <code>
+ /estimate
+ </code>
+ will update the estimated time with the latest command.
+ </p>
+ <p>
+ <code>
+ /spend
+ </code>
+ will update the sum of the time spent.
+ </p>
+ <a
+ class="btn btn-default learn-more-button"
+ :href="href"
+ >
+ Learn more
+ </a>
+ </div>
+ </div>
+ `,
+};
diff --git a/app/assets/javascripts/sidebar/components/time_tracking/no_tracking_pane.js b/app/assets/javascripts/sidebar/components/time_tracking/no_tracking_pane.js
new file mode 100644
index 00000000000..d1dd1dcdd27
--- /dev/null
+++ b/app/assets/javascripts/sidebar/components/time_tracking/no_tracking_pane.js
@@ -0,0 +1,10 @@
+export default {
+ name: 'time-tracking-no-tracking-pane',
+ template: `
+ <div class="time-tracking-no-tracking-pane">
+ <span class="no-value">
+ No estimate or time spent
+ </span>
+ </div>
+ `,
+};
diff --git a/app/assets/javascripts/sidebar/components/time_tracking/sidebar_time_tracking.js b/app/assets/javascripts/sidebar/components/time_tracking/sidebar_time_tracking.js
new file mode 100644
index 00000000000..244b67b3ad9
--- /dev/null
+++ b/app/assets/javascripts/sidebar/components/time_tracking/sidebar_time_tracking.js
@@ -0,0 +1,51 @@
+import '~/smart_interval';
+
+import timeTracker from './time_tracker';
+
+import Store from '../../stores/sidebar_store';
+import Mediator from '../../sidebar_mediator';
+
+export default {
+ data() {
+ return {
+ mediator: new Mediator(),
+ store: new Store(),
+ };
+ },
+ components: {
+ 'issuable-time-tracker': timeTracker,
+ },
+ methods: {
+ listenForSlashCommands() {
+ $(document).on('ajax:success', '.gfm-form', this.slashCommandListened);
+ },
+ slashCommandListened(e, data) {
+ const subscribedCommands = ['spend_time', 'time_estimate'];
+ let changedCommands;
+ if (data !== undefined) {
+ changedCommands = data.commands_changes
+ ? Object.keys(data.commands_changes)
+ : [];
+ } else {
+ changedCommands = [];
+ }
+ if (changedCommands && _.intersection(subscribedCommands, changedCommands).length) {
+ this.mediator.fetch();
+ }
+ },
+ },
+ mounted() {
+ this.listenForSlashCommands();
+ },
+ template: `
+ <div class="block">
+ <issuable-time-tracker
+ :time_estimate="store.timeEstimate"
+ :time_spent="store.totalTimeSpent"
+ :human_time_estimate="store.humanTimeEstimate"
+ :human_time_spent="store.humanTotalTimeSpent"
+ :rootPath="store.rootPath"
+ />
+ </div>
+ `,
+};
diff --git a/app/assets/javascripts/sidebar/components/time_tracking/spent_only_pane.js b/app/assets/javascripts/sidebar/components/time_tracking/spent_only_pane.js
new file mode 100644
index 00000000000..bf987562647
--- /dev/null
+++ b/app/assets/javascripts/sidebar/components/time_tracking/spent_only_pane.js
@@ -0,0 +1,15 @@
+export default {
+ name: 'time-tracking-spent-only-pane',
+ props: {
+ timeSpentHumanReadable: {
+ type: String,
+ required: true,
+ },
+ },
+ template: `
+ <div class="time-tracking-spend-only-pane">
+ <span class="bold">Spent:</span>
+ {{ timeSpentHumanReadable }}
+ </div>
+ `,
+};
diff --git a/app/assets/javascripts/sidebar/components/time_tracking/time_tracker.js b/app/assets/javascripts/sidebar/components/time_tracking/time_tracker.js
new file mode 100644
index 00000000000..ed0d71a4f79
--- /dev/null
+++ b/app/assets/javascripts/sidebar/components/time_tracking/time_tracker.js
@@ -0,0 +1,163 @@
+import timeTrackingHelpState from './help_state';
+import timeTrackingCollapsedState from './collapsed_state';
+import timeTrackingSpentOnlyPane from './spent_only_pane';
+import timeTrackingNoTrackingPane from './no_tracking_pane';
+import timeTrackingEstimateOnlyPane from './estimate_only_pane';
+import timeTrackingComparisonPane from './comparison_pane';
+
+import eventHub from '../../event_hub';
+
+export default {
+ name: 'issuable-time-tracker',
+ props: {
+ time_estimate: {
+ type: Number,
+ required: true,
+ },
+ time_spent: {
+ type: Number,
+ required: true,
+ },
+ human_time_estimate: {
+ type: String,
+ required: false,
+ default: '',
+ },
+ human_time_spent: {
+ type: String,
+ required: false,
+ default: '',
+ },
+ rootPath: {
+ type: String,
+ required: true,
+ },
+ },
+ data() {
+ return {
+ showHelp: false,
+ };
+ },
+ components: {
+ 'time-tracking-collapsed-state': timeTrackingCollapsedState,
+ 'time-tracking-estimate-only-pane': timeTrackingEstimateOnlyPane,
+ 'time-tracking-spent-only-pane': timeTrackingSpentOnlyPane,
+ 'time-tracking-no-tracking-pane': timeTrackingNoTrackingPane,
+ 'time-tracking-comparison-pane': timeTrackingComparisonPane,
+ 'time-tracking-help-state': timeTrackingHelpState,
+ },
+ computed: {
+ timeSpent() {
+ return this.time_spent;
+ },
+ timeEstimate() {
+ return this.time_estimate;
+ },
+ timeEstimateHumanReadable() {
+ return this.human_time_estimate;
+ },
+ timeSpentHumanReadable() {
+ return this.human_time_spent;
+ },
+ hasTimeSpent() {
+ return !!this.timeSpent;
+ },
+ hasTimeEstimate() {
+ return !!this.timeEstimate;
+ },
+ showComparisonState() {
+ return this.hasTimeEstimate && this.hasTimeSpent;
+ },
+ showEstimateOnlyState() {
+ return this.hasTimeEstimate && !this.hasTimeSpent;
+ },
+ showSpentOnlyState() {
+ return this.hasTimeSpent && !this.hasTimeEstimate;
+ },
+ showNoTimeTrackingState() {
+ return !this.hasTimeEstimate && !this.hasTimeSpent;
+ },
+ showHelpState() {
+ return !!this.showHelp;
+ },
+ },
+ methods: {
+ toggleHelpState(show) {
+ this.showHelp = show;
+ },
+ update(data) {
+ this.time_estimate = data.time_estimate;
+ this.time_spent = data.time_spent;
+ this.human_time_estimate = data.human_time_estimate;
+ this.human_time_spent = data.human_time_spent;
+ },
+ },
+ created() {
+ eventHub.$on('timeTracker:updateData', this.update);
+ },
+ template: `
+ <div
+ class="time_tracker time-tracking-component-wrap"
+ v-cloak
+ >
+ <time-tracking-collapsed-state
+ :show-comparison-state="showComparisonState"
+ :show-no-time-tracking-state="showNoTimeTrackingState"
+ :show-help-state="showHelpState"
+ :show-spent-only-state="showSpentOnlyState"
+ :show-estimate-only-state="showEstimateOnlyState"
+ :time-spent-human-readable="timeSpentHumanReadable"
+ :time-estimate-human-readable="timeEstimateHumanReadable"
+ />
+ <div class="title hide-collapsed">
+ Time tracking
+ <div
+ class="help-button pull-right"
+ v-if="!showHelpState"
+ @click="toggleHelpState(true)"
+ >
+ <i
+ class="fa fa-question-circle"
+ aria-hidden="true"
+ />
+ </div>
+ <div
+ class="close-help-button pull-right"
+ v-if="showHelpState"
+ @click="toggleHelpState(false)"
+ >
+ <i
+ class="fa fa-close"
+ aria-hidden="true"
+ />
+ </div>
+ </div>
+ <div class="time-tracking-content hide-collapsed">
+ <time-tracking-estimate-only-pane
+ v-if="showEstimateOnlyState"
+ :time-estimate-human-readable="timeEstimateHumanReadable"
+ />
+ <time-tracking-spent-only-pane
+ v-if="showSpentOnlyState"
+ :time-spent-human-readable="timeSpentHumanReadable"
+ />
+ <time-tracking-no-tracking-pane
+ v-if="showNoTimeTrackingState"
+ />
+ <time-tracking-comparison-pane
+ v-if="showComparisonState"
+ :time-estimate="timeEstimate"
+ :time-spent="timeSpent"
+ :time-spent-human-readable="timeSpentHumanReadable"
+ :time-estimate-human-readable="timeEstimateHumanReadable"
+ />
+ <transition name="help-state-toggle">
+ <time-tracking-help-state
+ v-if="showHelpState"
+ :rootPath="rootPath"
+ />
+ </transition>
+ </div>
+ </div>
+ `,
+};
diff --git a/app/assets/javascripts/sidebar/event_hub.js b/app/assets/javascripts/sidebar/event_hub.js
new file mode 100644
index 00000000000..0948c2e5352
--- /dev/null
+++ b/app/assets/javascripts/sidebar/event_hub.js
@@ -0,0 +1,3 @@
+import Vue from 'vue';
+
+export default new Vue();
diff --git a/app/assets/javascripts/sidebar/services/sidebar_service.js b/app/assets/javascripts/sidebar/services/sidebar_service.js
new file mode 100644
index 00000000000..5a82d01dc41
--- /dev/null
+++ b/app/assets/javascripts/sidebar/services/sidebar_service.js
@@ -0,0 +1,28 @@
+import Vue from 'vue';
+import VueResource from 'vue-resource';
+
+Vue.use(VueResource);
+
+export default class SidebarService {
+ constructor(endpoint) {
+ if (!SidebarService.singleton) {
+ this.endpoint = endpoint;
+
+ SidebarService.singleton = this;
+ }
+
+ return SidebarService.singleton;
+ }
+
+ get() {
+ return Vue.http.get(this.endpoint);
+ }
+
+ update(key, data) {
+ return Vue.http.put(this.endpoint, {
+ [key]: data,
+ }, {
+ emulateJSON: true,
+ });
+ }
+}
diff --git a/app/assets/javascripts/sidebar/sidebar_bundle.js b/app/assets/javascripts/sidebar/sidebar_bundle.js
new file mode 100644
index 00000000000..2b02af87d8a
--- /dev/null
+++ b/app/assets/javascripts/sidebar/sidebar_bundle.js
@@ -0,0 +1,24 @@
+import Vue from 'vue';
+import sidebarTimeTracking from './components/time_tracking/sidebar_time_tracking';
+import sidebarAssignees from './components/assignees/sidebar_assignees';
+
+import Mediator from './sidebar_mediator';
+
+function domContentLoaded() {
+ const mediator = new Mediator(gl.sidebarOptions);
+ mediator.fetch();
+
+ const sidebarAssigneesEl = document.querySelector('#js-vue-sidebar-assignees');
+
+ // Only create the sidebarAssignees vue app if it is found in the DOM
+ // We currently do not use sidebarAssignees for the MR page
+ if (sidebarAssigneesEl) {
+ new Vue(sidebarAssignees).$mount(sidebarAssigneesEl);
+ }
+
+ new Vue(sidebarTimeTracking).$mount('#issuable-time-tracker');
+}
+
+document.addEventListener('DOMContentLoaded', domContentLoaded);
+
+export default domContentLoaded;
diff --git a/app/assets/javascripts/sidebar/sidebar_mediator.js b/app/assets/javascripts/sidebar/sidebar_mediator.js
new file mode 100644
index 00000000000..5ccfb4ee9c1
--- /dev/null
+++ b/app/assets/javascripts/sidebar/sidebar_mediator.js
@@ -0,0 +1,38 @@
+/* global Flash */
+
+import Service from './services/sidebar_service';
+import Store from './stores/sidebar_store';
+
+export default class SidebarMediator {
+ constructor(options) {
+ if (!SidebarMediator.singleton) {
+ this.store = new Store(options);
+ this.service = new Service(options.endpoint);
+ SidebarMediator.singleton = this;
+ }
+
+ return SidebarMediator.singleton;
+ }
+
+ assignYourself() {
+ this.store.addAssignee(this.store.currentUser);
+ }
+
+ saveAssignees(field) {
+ const selected = this.store.assignees.map(u => u.id);
+
+ // If there are no ids, that means we have to unassign (which is id = 0)
+ // And it only accepts an array, hence [0]
+ return this.service.update(field, selected.length === 0 ? [0] : selected);
+ }
+
+ fetch() {
+ this.service.get()
+ .then((response) => {
+ const data = response.json();
+ this.store.setAssigneeData(data);
+ this.store.setTimeTrackingData(data);
+ })
+ .catch(() => new Flash('Error occured when fetching sidebar data'));
+ }
+}
diff --git a/app/assets/javascripts/sidebar/stores/sidebar_store.js b/app/assets/javascripts/sidebar/stores/sidebar_store.js
new file mode 100644
index 00000000000..2d44c05bb8d
--- /dev/null
+++ b/app/assets/javascripts/sidebar/stores/sidebar_store.js
@@ -0,0 +1,52 @@
+export default class SidebarStore {
+ constructor(store) {
+ if (!SidebarStore.singleton) {
+ const { currentUser, rootPath, editable } = store;
+ this.currentUser = currentUser;
+ this.rootPath = rootPath;
+ this.editable = editable;
+ this.timeEstimate = 0;
+ this.totalTimeSpent = 0;
+ this.humanTimeEstimate = '';
+ this.humanTimeSpent = '';
+ this.assignees = [];
+
+ SidebarStore.singleton = this;
+ }
+
+ return SidebarStore.singleton;
+ }
+
+ setAssigneeData(data) {
+ if (data.assignees) {
+ this.assignees = data.assignees;
+ }
+ }
+
+ setTimeTrackingData(data) {
+ this.timeEstimate = data.time_estimate;
+ this.totalTimeSpent = data.total_time_spent;
+ this.humanTimeEstimate = data.human_time_estimate;
+ this.humanTotalTimeSpent = data.human_total_time_spent;
+ }
+
+ addAssignee(assignee) {
+ if (!this.findAssignee(assignee)) {
+ this.assignees.push(assignee);
+ }
+ }
+
+ findAssignee(findAssignee) {
+ return this.assignees.filter(assignee => assignee.id === findAssignee.id)[0];
+ }
+
+ removeAssignee(removeAssignee) {
+ if (removeAssignee) {
+ this.assignees = this.assignees.filter(assignee => assignee.id !== removeAssignee.id);
+ }
+ }
+
+ removeAllAssignees() {
+ this.assignees = [];
+ }
+}
diff --git a/app/assets/javascripts/signin_tabs_memoizer.js b/app/assets/javascripts/signin_tabs_memoizer.js
index d811d1cd53a..2587facc582 100644
--- a/app/assets/javascripts/signin_tabs_memoizer.js
+++ b/app/assets/javascripts/signin_tabs_memoizer.js
@@ -1,5 +1,7 @@
/* eslint no-param-reassign: ["error", { "props": false }]*/
/* eslint no-new: "off" */
+import AccessorUtilities from './lib/utils/accessor';
+
((global) => {
/**
* Memorize the last selected tab after reloading a page.
@@ -9,6 +11,8 @@
constructor({ currentTabKey = 'current_signin_tab', tabSelector = 'ul.nav-tabs' } = {}) {
this.currentTabKey = currentTabKey;
this.tabSelector = tabSelector;
+ this.isLocalStorageAvailable = AccessorUtilities.isLocalStorageAccessSafe();
+
this.bootstrap();
}
@@ -37,11 +41,15 @@
}
saveData(val) {
- localStorage.setItem(this.currentTabKey, val);
+ if (!this.isLocalStorageAvailable) return undefined;
+
+ return window.localStorage.setItem(this.currentTabKey, val);
}
readData() {
- return localStorage.getItem(this.currentTabKey);
+ if (!this.isLocalStorageAvailable) return null;
+
+ return window.localStorage.getItem(this.currentTabKey);
}
}
diff --git a/app/assets/javascripts/subbable_resource.js b/app/assets/javascripts/subbable_resource.js
deleted file mode 100644
index d8191605128..00000000000
--- a/app/assets/javascripts/subbable_resource.js
+++ /dev/null
@@ -1,51 +0,0 @@
-(() => {
-/*
-* SubbableResource can be extended to provide a pubsub-style service for one-off REST
-* calls. Subscribe by passing a callback or render method you will use to handle responses.
- *
-* */
-
- class SubbableResource {
- constructor(resourcePath) {
- this.endpoint = resourcePath;
-
- // TODO: Switch to axios.create
- this.resource = $.ajax;
- this.subscribers = [];
- }
-
- subscribe(callback) {
- this.subscribers.push(callback);
- }
-
- publish(newResponse) {
- const responseCopy = _.extend({}, newResponse);
- this.subscribers.forEach((fn) => {
- fn(responseCopy);
- });
- return newResponse;
- }
-
- get(payload) {
- return this.resource(payload)
- .then(data => this.publish(data));
- }
-
- post(payload) {
- return this.resource(payload)
- .then(data => this.publish(data));
- }
-
- put(payload) {
- return this.resource(payload)
- .then(data => this.publish(data));
- }
-
- delete(payload) {
- return this.resource(payload)
- .then(data => this.publish(data));
- }
- }
-
- gl.SubbableResource = SubbableResource;
-})(window.gl || (window.gl = {}));
diff --git a/app/assets/javascripts/subscription_select.js b/app/assets/javascripts/subscription_select.js
index 8b25f43ffc7..0cd591c7320 100644
--- a/app/assets/javascripts/subscription_select.js
+++ b/app/assets/javascripts/subscription_select.js
@@ -19,8 +19,8 @@
return label;
};
})(this),
- clicked: function(item, $el, e) {
- return e.preventDefault();
+ clicked: function(options) {
+ return options.e.preventDefault();
},
id: function(obj, el) {
return $(el).data("id");
diff --git a/app/assets/javascripts/users/calendar.js b/app/assets/javascripts/users/calendar.js
index 754d448564f..32ffa2f0ac0 100644
--- a/app/assets/javascripts/users/calendar.js
+++ b/app/assets/javascripts/users/calendar.js
@@ -168,15 +168,23 @@ import d3 from 'd3';
};
Calendar.prototype.renderKey = function() {
- var keyColors;
- keyColors = ['#ededed', this.colorKey(0), this.colorKey(1), this.colorKey(2), this.colorKey(3)];
- return this.svg.append('g').attr('transform', "translate(18, " + (this.daySizeWithSpace * 8 + 16) + ")").selectAll('rect').data(keyColors).enter().append('rect').attr('width', this.daySize).attr('height', this.daySize).attr('x', (function(_this) {
- return function(color, i) {
- return _this.daySizeWithSpace * i;
- };
- })(this)).attr('y', 0).attr('fill', function(color) {
- return color;
- });
+ const keyValues = ['no contributions', '1-9 contributions', '10-19 contributions', '20-29 contributions', '30+ contributions'];
+ const keyColors = ['#ededed', this.colorKey(0), this.colorKey(1), this.colorKey(2), this.colorKey(3)];
+
+ this.svg.append('g')
+ .attr('transform', `translate(18, ${this.daySizeWithSpace * 8 + 16})`)
+ .selectAll('rect')
+ .data(keyColors)
+ .enter()
+ .append('rect')
+ .attr('width', this.daySize)
+ .attr('height', this.daySize)
+ .attr('x', (color, i) => this.daySizeWithSpace * i)
+ .attr('y', 0)
+ .attr('fill', color => color)
+ .attr('class', 'js-tooltip')
+ .attr('title', (color, i) => keyValues[i])
+ .attr('data-container', 'body');
};
Calendar.prototype.initColor = function() {
diff --git a/app/assets/javascripts/users_select.js b/app/assets/javascripts/users_select.js
index 68cf9ced3ef..be29b08c343 100644
--- a/app/assets/javascripts/users_select.js
+++ b/app/assets/javascripts/users_select.js
@@ -1,6 +1,7 @@
/* eslint-disable func-names, space-before-function-paren, one-var, no-var, prefer-rest-params, wrap-iife, quotes, max-len, one-var-declaration-per-line, vars-on-top, prefer-arrow-callback, consistent-return, comma-dangle, object-shorthand, no-shadow, no-unused-vars, no-else-return, no-self-compare, prefer-template, no-unused-expressions, no-lonely-if, yoda, prefer-spread, no-void, camelcase, no-param-reassign */
/* global Issuable */
-/* global ListUser */
+
+import eventHub from './sidebar/event_hub';
(function() {
var bind = function(fn, me) { return function() { return fn.apply(me, arguments); }; },
@@ -54,42 +55,115 @@
selectedIdDefault = (defaultNullUser && showNullUser) ? 0 : null;
selectedId = $dropdown.data('selected') || selectedIdDefault;
- var updateIssueBoardsIssue = function () {
- $loading.removeClass('hidden').fadeIn();
- gl.issueBoards.BoardsStore.detail.issue.update($dropdown.attr('data-issue-update'))
- .then(function () {
- $loading.fadeOut();
- })
- .catch(function () {
- $loading.fadeOut();
- });
+ const assignYourself = function () {
+ const unassignedSelected = $dropdown.closest('.selectbox')
+ .find(`input[name='${$dropdown.data('field-name')}'][value=0]`);
+
+ if (unassignedSelected) {
+ unassignedSelected.remove();
+ }
+
+ // Save current selected user to the DOM
+ const input = document.createElement('input');
+ input.type = 'hidden';
+ input.name = $dropdown.data('field-name');
+
+ const currentUserInfo = $dropdown.data('currentUserInfo');
+
+ if (currentUserInfo) {
+ input.value = currentUserInfo.id;
+ input.dataset.meta = currentUserInfo.name;
+ } else if (_this.currentUser) {
+ input.value = _this.currentUser.id;
+ }
+
+ if ($selectbox) {
+ $dropdown.parent().before(input);
+ } else {
+ $dropdown.after(input);
+ }
+ };
+
+ if ($block[0]) {
+ $block[0].addEventListener('assignYourself', assignYourself);
+ }
+
+ const getSelectedUserInputs = function() {
+ return $selectbox
+ .find(`input[name="${$dropdown.data('field-name')}"]`);
+ };
+
+ const getSelected = function() {
+ return getSelectedUserInputs()
+ .map((index, input) => parseInt(input.value, 10))
+ .get();
+ };
+
+ const checkMaxSelect = function() {
+ const maxSelect = $dropdown.data('max-select');
+ if (maxSelect) {
+ const selected = getSelected();
+
+ if (selected.length > maxSelect) {
+ const firstSelectedId = selected[0];
+ const firstSelected = $dropdown.closest('.selectbox')
+ .find(`input[name='${$dropdown.data('field-name')}'][value=${firstSelectedId}]`);
+
+ firstSelected.remove();
+ eventHub.$emit('sidebar.removeAssignee', {
+ id: firstSelectedId,
+ });
+ }
+ }
+ };
+
+ const getMultiSelectDropdownTitle = function(selectedUser, isSelected) {
+ const selectedUsers = getSelected()
+ .filter(u => u !== 0);
+
+ const firstUser = getSelectedUserInputs()
+ .map((index, input) => ({
+ name: input.dataset.meta,
+ value: parseInt(input.value, 10),
+ }))
+ .filter(u => u.id !== 0)
+ .get(0);
+
+ if (selectedUsers.length === 0) {
+ return 'Unassigned';
+ } else if (selectedUsers.length === 1) {
+ return firstUser.name;
+ } else if (isSelected) {
+ const otherSelected = selectedUsers.filter(s => s !== selectedUser.id);
+ return `${selectedUser.name} + ${otherSelected.length} more`;
+ } else {
+ return `${firstUser.name} + ${selectedUsers.length - 1} more`;
+ }
};
$('.assign-to-me-link').on('click', (e) => {
e.preventDefault();
$(e.currentTarget).hide();
- const $input = $(`input[name="${$dropdown.data('field-name')}"]`);
- $input.val(gon.current_user_id);
- selectedId = $input.val();
- $dropdown.find('.dropdown-toggle-text').text(gon.current_user_fullname).removeClass('is-default');
- });
- $block.on('click', '.js-assign-yourself', function(e) {
- e.preventDefault();
-
- if ($dropdown.hasClass('js-issue-board-sidebar')) {
- gl.issueBoards.boardStoreIssueSet('assignee', new ListUser({
- id: _this.currentUser.id,
- username: _this.currentUser.username,
- name: _this.currentUser.name,
- avatar_url: _this.currentUser.avatar_url
- }));
+ if ($dropdown.data('multiSelect')) {
+ assignYourself();
+ checkMaxSelect();
- updateIssueBoardsIssue();
+ const currentUserInfo = $dropdown.data('currentUserInfo');
+ $dropdown.find('.dropdown-toggle-text').text(getMultiSelectDropdownTitle(currentUserInfo)).removeClass('is-default');
} else {
- return assignTo(_this.currentUser.id);
+ const $input = $(`input[name="${$dropdown.data('field-name')}"]`);
+ $input.val(gon.current_user_id);
+ selectedId = $input.val();
+ $dropdown.find('.dropdown-toggle-text').text(gon.current_user_fullname).removeClass('is-default');
}
});
+
+ $block.on('click', '.js-assign-yourself', (e) => {
+ e.preventDefault();
+ return assignTo(_this.currentUser.id);
+ });
+
assignTo = function(selected) {
var data;
data = {};
@@ -97,6 +171,7 @@
data[abilityName].assignee_id = selected != null ? selected : null;
$loading.removeClass('hidden').fadeIn();
$dropdown.trigger('loading.gl.dropdown');
+
return $.ajax({
type: 'PUT',
dataType: 'json',
@@ -106,7 +181,6 @@
var user;
$dropdown.trigger('loaded.gl.dropdown');
$loading.fadeOut();
- $selectbox.hide();
if (data.assignee) {
user = {
name: data.assignee.name,
@@ -133,51 +207,90 @@
var isAuthorFilter;
isAuthorFilter = $('.js-author-search');
return _this.users(term, options, function(users) {
- var anyUser, index, j, len, name, obj, showDivider;
- if (term.length === 0) {
- showDivider = 0;
- if (firstUser) {
- // Move current user to the front of the list
- for (index = j = 0, len = users.length; j < len; index = (j += 1)) {
- obj = users[index];
- if (obj.username === firstUser) {
- users.splice(index, 1);
- users.unshift(obj);
- break;
- }
+ // GitLabDropdownFilter returns this.instance
+ // GitLabDropdownRemote returns this.options.instance
+ const glDropdown = this.instance || this.options.instance;
+ glDropdown.options.processData(term, users, callback);
+ }.bind(this));
+ },
+ processData: function(term, users, callback) {
+ let anyUser;
+ let index;
+ let j;
+ let len;
+ let name;
+ let obj;
+ let showDivider;
+ if (term.length === 0) {
+ showDivider = 0;
+ if (firstUser) {
+ // Move current user to the front of the list
+ for (index = j = 0, len = users.length; j < len; index = (j += 1)) {
+ obj = users[index];
+ if (obj.username === firstUser) {
+ users.splice(index, 1);
+ users.unshift(obj);
+ break;
}
}
- if (showNullUser) {
- showDivider += 1;
- users.unshift({
- beforeDivider: true,
- name: 'Unassigned',
- id: 0
- });
- }
- if (showAnyUser) {
- showDivider += 1;
- name = showAnyUser;
- if (name === true) {
- name = 'Any User';
- }
- anyUser = {
- beforeDivider: true,
- name: name,
- id: null
- };
- users.unshift(anyUser);
+ }
+ if (showNullUser) {
+ showDivider += 1;
+ users.unshift({
+ beforeDivider: true,
+ name: 'Unassigned',
+ id: 0
+ });
+ }
+ if (showAnyUser) {
+ showDivider += 1;
+ name = showAnyUser;
+ if (name === true) {
+ name = 'Any User';
}
+ anyUser = {
+ beforeDivider: true,
+ name: name,
+ id: null
+ };
+ users.unshift(anyUser);
}
+
if (showDivider) {
- users.splice(showDivider, 0, "divider");
+ users.splice(showDivider, 0, 'divider');
}
- callback(users);
- if (showMenuAbove) {
- $dropdown.data('glDropdown').positionMenuAbove();
+ if ($dropdown.hasClass('js-multiselect')) {
+ const selected = getSelected().filter(i => i !== 0);
+
+ if (selected.length > 0) {
+ if ($dropdown.data('dropdown-header')) {
+ showDivider += 1;
+ users.splice(showDivider, 0, {
+ header: $dropdown.data('dropdown-header'),
+ });
+ }
+
+ const selectedUsers = users
+ .filter(u => selected.indexOf(u.id) !== -1)
+ .sort((a, b) => a.name > b.name);
+
+ users = users.filter(u => selected.indexOf(u.id) === -1);
+
+ selectedUsers.forEach((selectedUser) => {
+ showDivider += 1;
+ users.splice(showDivider, 0, selectedUser);
+ });
+
+ users.splice(showDivider + 1, 0, 'divider');
+ }
}
- });
+ }
+
+ callback(users);
+ if (showMenuAbove) {
+ $dropdown.data('glDropdown').positionMenuAbove();
+ }
},
filterable: true,
filterRemote: true,
@@ -186,7 +299,22 @@
},
selectable: true,
fieldName: $dropdown.data('field-name'),
- toggleLabel: function(selected, el) {
+ toggleLabel: function(selected, el, glDropdown) {
+ const inputValue = glDropdown.filterInput.val();
+
+ if (this.multiSelect && inputValue === '') {
+ // Remove non-users from the fullData array
+ const users = glDropdown.filteredFullData();
+ const callback = glDropdown.parseData.bind(glDropdown);
+
+ // Update the data model
+ this.processData(inputValue, users, callback);
+ }
+
+ if (this.multiSelect) {
+ return getMultiSelectDropdownTitle(selected, $(el).hasClass('is-active'));
+ }
+
if (selected && 'id' in selected && $(el).hasClass('is-active')) {
$dropdown.find('.dropdown-toggle-text').removeClass('is-default');
if (selected.text) {
@@ -200,22 +328,81 @@
}
},
defaultLabel: defaultLabel,
- inputId: 'issue_assignee_id',
hidden: function(e) {
- $selectbox.hide();
- // display:block overrides the hide-collapse rule
- return $value.css('display', '');
+ if ($dropdown.hasClass('js-multiselect')) {
+ eventHub.$emit('sidebar.saveAssignees');
+ }
+
+ if (!$dropdown.data('always-show-selectbox')) {
+ $selectbox.hide();
+
+ // Recalculate where .value is because vue might have changed it
+ $block = $selectbox.closest('.block');
+ $value = $block.find('.value');
+ // display:block overrides the hide-collapse rule
+ $value.css('display', '');
+ }
},
- vue: $dropdown.hasClass('js-issue-board-sidebar'),
- clicked: function(user, $el, e) {
- var isIssueIndex, isMRIndex, page, selected, isSelecting;
+ multiSelect: $dropdown.hasClass('js-multiselect'),
+ inputMeta: $dropdown.data('input-meta'),
+ clicked: function(options) {
+ const { $el, e, isMarking } = options;
+ const user = options.selectedObj;
+
+ if ($dropdown.hasClass('js-multiselect')) {
+ const isActive = $el.hasClass('is-active');
+ const previouslySelected = $dropdown.closest('.selectbox')
+ .find("input[name='" + ($dropdown.data('field-name')) + "'][value!=0]");
+
+ // Enables support for limiting the number of users selected
+ // Automatically removes the first on the list if more users are selected
+ checkMaxSelect();
+
+ if (user.beforeDivider && user.name.toLowerCase() === 'unassigned') {
+ // Unassigned selected
+ previouslySelected.each((index, element) => {
+ const id = parseInt(element.value, 10);
+ element.remove();
+ });
+ eventHub.$emit('sidebar.removeAllAssignees');
+ } else if (isActive) {
+ // user selected
+ eventHub.$emit('sidebar.addAssignee', user);
+
+ // Remove unassigned selection (if it was previously selected)
+ const unassignedSelected = $dropdown.closest('.selectbox')
+ .find("input[name='" + ($dropdown.data('field-name')) + "'][value=0]");
+
+ if (unassignedSelected) {
+ unassignedSelected.remove();
+ }
+ } else {
+ if (previouslySelected.length === 0) {
+ // Select unassigned because there is no more selected users
+ this.addInput($dropdown.data('field-name'), 0, {});
+ }
+
+ // User unselected
+ eventHub.$emit('sidebar.removeAssignee', user);
+ }
+
+ if (getSelected().find(u => u === gon.current_user_id)) {
+ $('.assign-to-me-link').hide();
+ } else {
+ $('.assign-to-me-link').show();
+ }
+ }
+
+ var isIssueIndex, isMRIndex, page, selected;
page = $('body').data('page');
isIssueIndex = page === 'projects:issues:index';
isMRIndex = (page === page && page === 'projects:merge_requests:index');
- isSelecting = (user.id !== selectedId);
- selectedId = isSelecting ? user.id : selectedIdDefault;
if ($dropdown.hasClass('js-filter-bulk-update') || $dropdown.hasClass('js-issuable-form-dropdown')) {
e.preventDefault();
+
+ const isSelecting = (user.id !== selectedId);
+ selectedId = isSelecting ? user.id : selectedIdDefault;
+
if (selectedId === gon.current_user_id) {
$('.assign-to-me-link').hide();
} else {
@@ -229,20 +416,7 @@
return Issuable.filterResults($dropdown.closest('form'));
} else if ($dropdown.hasClass('js-filter-submit')) {
return $dropdown.closest('form').submit();
- } else if ($dropdown.hasClass('js-issue-board-sidebar')) {
- if (user.id && isSelecting) {
- gl.issueBoards.boardStoreIssueSet('assignee', new ListUser({
- id: user.id,
- username: user.username,
- name: user.name,
- avatar_url: user.avatar_url
- }));
- } else {
- gl.issueBoards.boardStoreIssueDelete('assignee');
- }
-
- updateIssueBoardsIssue();
- } else {
+ } else if (!$dropdown.hasClass('js-multiselect')) {
selected = $dropdown.closest('.selectbox').find("input[name='" + ($dropdown.data('field-name')) + "']").val();
return assignTo(selected);
}
@@ -256,29 +430,54 @@
selectedId = parseInt($dropdown[0].dataset.selected, 10) || selectedIdDefault;
}
$el.find('.is-active').removeClass('is-active');
- $el.find(`li[data-user-id="${selectedId}"] .dropdown-menu-user-link`).addClass('is-active');
+
+ function highlightSelected(id) {
+ $el.find(`li[data-user-id="${id}"] .dropdown-menu-user-link`).addClass('is-active');
+ }
+
+ if ($selectbox[0]) {
+ getSelected().forEach(selectedId => highlightSelected(selectedId));
+ } else {
+ highlightSelected(selectedId);
+ }
},
+ updateLabel: $dropdown.data('dropdown-title'),
renderRow: function(user) {
- var avatar, img, listClosingTags, listWithName, listWithUserName, selected, username;
+ var avatar, img, listClosingTags, listWithName, listWithUserName, username;
username = user.username ? "@" + user.username : "";
avatar = user.avatar_url ? user.avatar_url : false;
- selected = user.id === parseInt(selectedId, 10) ? "is-active" : "";
+
+ let selected = user.id === parseInt(selectedId, 10);
+
+ if (this.multiSelect) {
+ const fieldName = this.fieldName;
+ const field = $dropdown.closest('.selectbox').find("input[name='" + fieldName + "'][value='" + user.id + "']");
+
+ if (field.length) {
+ selected = true;
+ }
+ }
+
img = "";
if (user.beforeDivider != null) {
- "<li> <a href='#' class='" + selected + "'> " + user.name + " </a> </li>";
+ `<li><a href='#' class='${selected === true ? 'is-active' : ''}'>${user.name}</a></li>`;
} else {
if (avatar) {
- img = "<img src='" + avatar + "' class='avatar avatar-inline' width='30' />";
+ img = "<img src='" + avatar + "' class='avatar avatar-inline' width='32' />";
}
}
- // split into three parts so we can remove the username section if nessesary
- listWithName = "<li data-user-id=" + user.id + "> <a href='#' class='dropdown-menu-user-link " + selected + "'> " + img + " <strong class='dropdown-menu-user-full-name'> " + user.name + " </strong>";
- listWithUserName = "<span class='dropdown-menu-user-username'> " + username + " </span>";
- listClosingTags = "</a> </li>";
- if (username === '') {
- listWithUserName = '';
- }
- return listWithName + listWithUserName + listClosingTags;
+
+ return `
+ <li data-user-id=${user.id}>
+ <a href='#' class='dropdown-menu-user-link ${selected === true ? 'is-active' : ''}'>
+ ${img}
+ <strong class='dropdown-menu-user-full-name'>
+ ${user.name}
+ </strong>
+ ${username ? `<span class='dropdown-menu-user-username'>${username}</span>` : ''}
+ </a>
+ </li>
+ `;
}
});
};
diff --git a/app/assets/stylesheets/framework/avatar.scss b/app/assets/stylesheets/framework/avatar.scss
index 3f5b78ed445..91c1ebd5a7d 100644
--- a/app/assets/stylesheets/framework/avatar.scss
+++ b/app/assets/stylesheets/framework/avatar.scss
@@ -93,3 +93,14 @@
align-self: center;
}
}
+
+.avatar-counter {
+ background-color: $gray-darkest;
+ color: $white-light;
+ border: 1px solid $border-color;
+ border-radius: 1em;
+ font-family: $regular_font;
+ font-size: 9px;
+ line-height: 16px;
+ text-align: center;
+}
diff --git a/app/assets/stylesheets/framework/dropdowns.scss b/app/assets/stylesheets/framework/dropdowns.scss
index 73ded9f30d4..5c9b71a452c 100644
--- a/app/assets/stylesheets/framework/dropdowns.scss
+++ b/app/assets/stylesheets/framework/dropdowns.scss
@@ -251,14 +251,16 @@
}
.dropdown-header {
- color: $gl-text-color;
+ color: $gl-text-color-secondary;
font-size: 13px;
- font-weight: 600;
line-height: 22px;
- text-transform: capitalize;
padding: 0 16px;
}
+ &.capitalize-header .dropdown-header {
+ text-transform: capitalize;
+ }
+
.separator + .dropdown-header {
padding-top: 2px;
}
@@ -337,8 +339,8 @@
.dropdown-menu-user {
.avatar {
float: left;
- width: 30px;
- height: 30px;
+ width: 2 * $gl-padding;
+ height: 2 * $gl-padding;
margin: 0 10px 0 0;
}
}
@@ -381,6 +383,7 @@
.dropdown-menu-selectable {
a {
padding-left: 26px;
+ position: relative;
&.is-indeterminate,
&.is-active {
@@ -406,6 +409,9 @@
&.is-active::before {
content: "\f00c";
+ position: absolute;
+ top: 50%;
+ transform: translateY(-50%);
}
}
}
diff --git a/app/assets/stylesheets/framework/files.scss b/app/assets/stylesheets/framework/files.scss
index c197bf6b9f5..1dd0e5ab581 100644
--- a/app/assets/stylesheets/framework/files.scss
+++ b/app/assets/stylesheets/framework/files.scss
@@ -162,6 +162,18 @@
&.code {
padding: 0;
}
+
+ .list-inline.previews {
+ display: flex;
+ flex-wrap: wrap;
+ justify-content: center;
+ align-content: flex-start;
+ align-items: baseline;
+
+ .preview {
+ padding: $gl-padding;
+ }
+ }
}
}
diff --git a/app/assets/stylesheets/framework/filters.scss b/app/assets/stylesheets/framework/filters.scss
index 0692f65043b..e624d0d951e 100644
--- a/app/assets/stylesheets/framework/filters.scss
+++ b/app/assets/stylesheets/framework/filters.scss
@@ -114,11 +114,21 @@
padding-right: 8px;
.fa-close {
- color: $gl-text-color-disabled;
+ color: $gl-text-color-secondary;
}
&:hover .fa-close {
- color: $gl-text-color-secondary;
+ color: $gl-text-color;
+ }
+
+ &.inverted {
+ .fa-close {
+ color: $gl-text-color-secondary-inverted;
+ }
+
+ &:hover .fa-close {
+ color: $gl-text-color-inverted;
+ }
}
}
diff --git a/app/assets/stylesheets/framework/lists.scss b/app/assets/stylesheets/framework/lists.scss
index 15dc0aa6a52..c9a25946ffd 100644
--- a/app/assets/stylesheets/framework/lists.scss
+++ b/app/assets/stylesheets/framework/lists.scss
@@ -255,6 +255,7 @@ ul.controls {
.avatar-inline {
margin-left: 0;
margin-right: 0;
+ margin-bottom: 0;
}
}
}
diff --git a/app/assets/stylesheets/framework/variables.scss b/app/assets/stylesheets/framework/variables.scss
index 49741c963df..08bcb582613 100644
--- a/app/assets/stylesheets/framework/variables.scss
+++ b/app/assets/stylesheets/framework/variables.scss
@@ -101,6 +101,8 @@ $gl-font-size: 14px;
$gl-text-color: rgba(0, 0, 0, .85);
$gl-text-color-secondary: rgba(0, 0, 0, .55);
$gl-text-color-disabled: rgba(0, 0, 0, .35);
+$gl-text-color-inverted: rgba(255, 255, 255, 1.0);
+$gl-text-color-secondary-inverted: rgba(255, 255, 255, .85);
$gl-text-green: $green-600;
$gl-text-red: $red-500;
$gl-text-orange: $orange-600;
diff --git a/app/assets/stylesheets/pages/boards.scss b/app/assets/stylesheets/pages/boards.scss
index 0be1c215959..68d7ab4bf84 100644
--- a/app/assets/stylesheets/pages/boards.scss
+++ b/app/assets/stylesheets/pages/boards.scss
@@ -207,8 +207,13 @@
margin-bottom: 5px;
}
- &.is-active {
+ &.is-active,
+ &.is-active .card-assignee:hover a {
background-color: $row-hover;
+
+ &:first-child:not(:only-child) {
+ box-shadow: -10px 0 10px 1px $row-hover;
+ }
}
.label {
@@ -224,7 +229,7 @@
}
.card-title {
- margin: 0;
+ margin: 0 30px 0 0;
font-size: 1em;
line-height: inherit;
@@ -240,10 +245,69 @@
min-height: 20px;
.card-assignee {
- margin-left: auto;
- margin-right: 5px;
- padding-left: 10px;
+ display: flex;
+ justify-content: flex-end;
+ position: absolute;
+ right: 15px;
height: 20px;
+ width: 20px;
+
+ .avatar-counter {
+ display: none;
+ vertical-align: middle;
+ min-width: 20px;
+ line-height: 19px;
+ height: 20px;
+ padding-left: 2px;
+ padding-right: 2px;
+ border-radius: 2em;
+ }
+
+ img {
+ vertical-align: top;
+ }
+
+ a {
+ position: relative;
+ margin-left: -15px;
+ }
+
+ a:nth-child(1) {
+ z-index: 3;
+ }
+
+ a:nth-child(2) {
+ z-index: 2;
+ }
+
+ a:nth-child(3) {
+ z-index: 1;
+ }
+
+ a:nth-child(4) {
+ display: none;
+ }
+
+ &:hover {
+ .avatar-counter {
+ display: inline-block;
+ }
+
+ a {
+ position: static;
+ background-color: $white-light;
+ transition: background-color 0s;
+ margin-left: auto;
+
+ &:nth-child(4) {
+ display: block;
+ }
+
+ &:first-child:not(:only-child) {
+ box-shadow: -10px 0 10px 1px $white-light;
+ }
+ }
+ }
}
.avatar {
diff --git a/app/assets/stylesheets/pages/diff.scss b/app/assets/stylesheets/pages/diff.scss
index feefaad8a15..77f2638683a 100644
--- a/app/assets/stylesheets/pages/diff.scss
+++ b/app/assets/stylesheets/pages/diff.scss
@@ -570,14 +570,7 @@
.diff-comments-more-count,
.diff-notes-collapse {
- background-color: $gray-darkest;
- color: $white-light;
- border: 1px solid $white-light;
- border-radius: 1em;
- font-family: $regular_font;
- font-size: 9px;
- line-height: 17px;
- text-align: center;
+ @extend .avatar-counter;
}
.diff-notes-collapse {
diff --git a/app/assets/stylesheets/pages/issuable.scss b/app/assets/stylesheets/pages/issuable.scss
index ad6eb9f6fe0..c4210ffd823 100644
--- a/app/assets/stylesheets/pages/issuable.scss
+++ b/app/assets/stylesheets/pages/issuable.scss
@@ -95,10 +95,15 @@
}
.right-sidebar {
- a {
+ a,
+ .btn-link {
color: inherit;
}
+ .btn-link {
+ outline: none;
+ }
+
.issuable-header-text {
margin-top: 7px;
}
@@ -215,6 +220,10 @@
}
}
+ .assign-yourself .btn-link {
+ padding-left: 0;
+ }
+
.light {
font-weight: normal;
}
@@ -239,6 +248,10 @@
margin-left: 0;
}
+ .assignee .user-list .avatar {
+ margin: 0;
+ }
+
.username {
display: block;
margin-top: 4px;
@@ -301,6 +314,10 @@
margin-top: 0;
}
+ .sidebar-avatar-counter {
+ padding-top: 2px;
+ }
+
.todo-undone {
color: $gl-link-color;
}
@@ -309,10 +326,15 @@
display: none;
}
- .avatar:hover {
+ .avatar:hover,
+ .avatar-counter:hover {
border-color: $issuable-sidebar-color;
}
+ .avatar-counter:hover {
+ color: $issuable-sidebar-color;
+ }
+
.btn-clipboard {
border: none;
color: $issuable-sidebar-color;
@@ -322,6 +344,17 @@
color: $gl-text-color;
}
}
+
+ &.multiple-users {
+ display: flex;
+ justify-content: center;
+ }
+ }
+
+ .sidebar-avatar-counter {
+ width: 24px;
+ height: 24px;
+ border-radius: 12px;
}
.sidebar-collapsed-user {
@@ -332,6 +365,37 @@
.issuable-header-btn {
display: none;
}
+
+ .multiple-users {
+ height: 24px;
+ margin-bottom: 17px;
+ margin-top: 4px;
+ padding-bottom: 4px;
+
+ .btn-link {
+ padding: 0;
+ border: 0;
+
+ .avatar {
+ margin: 0;
+ }
+ }
+
+ .btn-link:first-child {
+ position: absolute;
+ left: 10px;
+ z-index: 1;
+ }
+
+ .btn-link:last-child {
+ position: absolute;
+ right: 10px;
+
+ &:hover {
+ text-decoration: none;
+ }
+ }
+ }
}
a {
@@ -383,6 +447,12 @@
margin: -5px;
}
+
+.user-list {
+ display: flex;
+ flex-wrap: wrap;
+}
+
.participants-author {
display: inline-block;
padding: 5px;
@@ -400,13 +470,39 @@
}
}
-.participants-more {
+.user-item {
+ display: inline-block;
+ padding: 5px;
+ flex-basis: 20%;
+
+ .user-link {
+ display: inline-block;
+ }
+}
+
+.participants-more,
+.user-list-more {
margin-top: 5px;
margin-left: 5px;
- a {
+ a,
+ .btn-link {
color: $gl-text-color-secondary;
}
+
+ .btn-link {
+ outline: none;
+ padding: 0;
+ }
+
+ .btn-link:hover {
+ @extend a:hover;
+ text-decoration: none;
+ }
+
+ .btn-link:focus {
+ text-decoration: none;
+ }
}
.issuable-form-padding-top {
@@ -499,6 +595,19 @@
}
}
+.issuable-list li,
+.issue-info-container .controls {
+ .avatar-counter {
+ display: inline-block;
+ vertical-align: middle;
+ min-width: 16px;
+ line-height: 14px;
+ height: 16px;
+ padding-left: 2px;
+ padding-right: 2px;
+ }
+}
+
.time_tracker {
padding-bottom: 0;
border-bottom: 0;
diff --git a/app/assets/stylesheets/pages/issues.scss b/app/assets/stylesheets/pages/issues.scss
index b18bbc329c3..ad3b6e0344b 100644
--- a/app/assets/stylesheets/pages/issues.scss
+++ b/app/assets/stylesheets/pages/issues.scss
@@ -18,6 +18,15 @@
}
}
+.issue-realtime-pre-pulse {
+ opacity: 0;
+}
+
+.issue-realtime-trigger-pulse {
+ transition: opacity $fade-in-duration linear;
+ opacity: 1;
+}
+
.check-all-holder {
line-height: 36px;
float: left;
diff --git a/app/assets/stylesheets/pages/labels.scss b/app/assets/stylesheets/pages/labels.scss
index e1ef0b029a5..c10588ac58e 100644
--- a/app/assets/stylesheets/pages/labels.scss
+++ b/app/assets/stylesheets/pages/labels.scss
@@ -116,7 +116,7 @@
}
.manage-labels-list {
- > li:not(.empty-message) {
+ > li:not(.empty-message):not(.is-not-draggable) {
background-color: $white-light;
cursor: move;
cursor: -webkit-grab;
diff --git a/app/assets/stylesheets/pages/pipelines.scss b/app/assets/stylesheets/pages/pipelines.scss
index 9115d26c779..530a6f3c6a1 100644
--- a/app/assets/stylesheets/pages/pipelines.scss
+++ b/app/assets/stylesheets/pages/pipelines.scss
@@ -273,6 +273,7 @@
.stage-container {
display: inline-block;
position: relative;
+ vertical-align: middle;
height: 22px;
margin: 3px 6px 3px 0;
@@ -316,6 +317,32 @@
}
}
+.build-failures {
+ .build-state {
+ padding: 20px 2px;
+
+ .build-name {
+ float: right;
+ font-weight: 500;
+ }
+
+ .ci-status-icon-failed svg {
+ vertical-align: middle;
+ }
+
+ .stage {
+ color: $gl-text-color-secondary;
+ font-weight: 500;
+ vertical-align: middle;
+ }
+ }
+
+ .build-log {
+ border: none;
+ line-height: initial;
+ }
+}
+
// Pipeline graph
.pipeline-graph {
width: 100%;
diff --git a/app/assets/stylesheets/pages/todos.scss b/app/assets/stylesheets/pages/todos.scss
index a39815319f3..de652a79369 100644
--- a/app/assets/stylesheets/pages/todos.scss
+++ b/app/assets/stylesheets/pages/todos.scss
@@ -54,8 +54,9 @@
background-color: $white-light;
&:hover {
- border-color: $white-dark;
+ border-color: $white-normal;
background-color: $gray-light;
+ border-top: 1px solid transparent;
.todo-avatar,
.todo-item {
diff --git a/app/controllers/admin/application_settings_controller.rb b/app/controllers/admin/application_settings_controller.rb
index 643993d035e..152d7baad49 100644
--- a/app/controllers/admin/application_settings_controller.rb
+++ b/app/controllers/admin/application_settings_controller.rb
@@ -133,6 +133,8 @@ class Admin::ApplicationSettingsController < Admin::ApplicationController
:signup_enabled,
:sentry_dsn,
:sentry_enabled,
+ :clientside_sentry_dsn,
+ :clientside_sentry_enabled,
:send_user_confirmation_email,
:shared_runners_enabled,
:shared_runners_text,
diff --git a/app/controllers/admin/services_controller.rb b/app/controllers/admin/services_controller.rb
index 37a1a23178e..4c3d336b3af 100644
--- a/app/controllers/admin/services_controller.rb
+++ b/app/controllers/admin/services_controller.rb
@@ -16,6 +16,8 @@ class Admin::ServicesController < Admin::ApplicationController
def update
if service.update_attributes(service_params[:service])
+ PropagateServiceTemplateWorker.perform_async(service.id) if service.active?
+
redirect_to admin_application_settings_services_path,
notice: 'Application settings saved successfully'
else
diff --git a/app/controllers/application_controller.rb b/app/controllers/application_controller.rb
index d2c13da6917..65a1f640a76 100644
--- a/app/controllers/application_controller.rb
+++ b/app/controllers/application_controller.rb
@@ -58,7 +58,7 @@ class ApplicationController < ActionController::Base
if current_user
not_found
else
- redirect_to new_user_session_path
+ authenticate_user!
end
end
diff --git a/app/controllers/concerns/issuable_actions.rb b/app/controllers/concerns/issuable_actions.rb
index 3ccf2a9ce33..b199f18da1e 100644
--- a/app/controllers/concerns/issuable_actions.rb
+++ b/app/controllers/concerns/issuable_actions.rb
@@ -66,6 +66,7 @@ module IssuableActions
:milestone_id,
:state_event,
:subscription_event,
+ assignee_ids: [],
label_ids: [],
add_label_ids: [],
remove_label_ids: []
diff --git a/app/controllers/concerns/issuable_collections.rb b/app/controllers/concerns/issuable_collections.rb
index c8a501d7319..6df2c068745 100644
--- a/app/controllers/concerns/issuable_collections.rb
+++ b/app/controllers/concerns/issuable_collections.rb
@@ -43,7 +43,7 @@ module IssuableCollections
end
def issues_collection
- issues_finder.execute.preload(:project, :author, :assignee, :labels, :milestone, project: :namespace)
+ issues_finder.execute.preload(:project, :author, :assignees, :labels, :milestone, project: :namespace)
end
def merge_requests_collection
diff --git a/app/controllers/concerns/routable_actions.rb b/app/controllers/concerns/routable_actions.rb
new file mode 100644
index 00000000000..d4ab6782444
--- /dev/null
+++ b/app/controllers/concerns/routable_actions.rb
@@ -0,0 +1,38 @@
+module RoutableActions
+ extend ActiveSupport::Concern
+
+ def find_routable!(routable_klass, requested_full_path, extra_authorization_proc: nil)
+ routable = routable_klass.find_by_full_path(requested_full_path, follow_redirects: request.get?)
+
+ if routable_authorized?(routable_klass, routable, extra_authorization_proc)
+ ensure_canonical_path(routable, requested_full_path)
+ routable
+ else
+ route_not_found
+ nil
+ end
+ end
+
+ def routable_authorized?(routable_klass, routable, extra_authorization_proc)
+ action = :"read_#{routable_klass.to_s.underscore}"
+ return false unless can?(current_user, action, routable)
+
+ if extra_authorization_proc
+ extra_authorization_proc.call(routable)
+ else
+ true
+ end
+ end
+
+ def ensure_canonical_path(routable, requested_path)
+ return unless request.get?
+
+ canonical_path = routable.full_path
+ if canonical_path != requested_path
+ if canonical_path.casecmp(requested_path) != 0
+ flash[:notice] = "Project '#{requested_path}' was moved to '#{canonical_path}'. Please update any links and bookmarks that may still have the old path."
+ end
+ redirect_to request.original_url.sub(requested_path, canonical_path)
+ end
+ end
+end
diff --git a/app/controllers/dashboard/labels_controller.rb b/app/controllers/dashboard/labels_controller.rb
index d5031da867a..dd1d46a68c7 100644
--- a/app/controllers/dashboard/labels_controller.rb
+++ b/app/controllers/dashboard/labels_controller.rb
@@ -3,7 +3,7 @@ class Dashboard::LabelsController < Dashboard::ApplicationController
labels = LabelsFinder.new(current_user).execute
respond_to do |format|
- format.json { render json: labels.as_json(only: [:id, :title, :color]) }
+ format.json { render json: LabelSerializer.new.represent_appearance(labels) }
end
end
end
diff --git a/app/controllers/groups/application_controller.rb b/app/controllers/groups/application_controller.rb
index 29ffaeb19c1..afffb813b44 100644
--- a/app/controllers/groups/application_controller.rb
+++ b/app/controllers/groups/application_controller.rb
@@ -1,4 +1,6 @@
class Groups::ApplicationController < ApplicationController
+ include RoutableActions
+
layout 'group'
skip_before_action :authenticate_user!
@@ -7,29 +9,17 @@ class Groups::ApplicationController < ApplicationController
private
def group
- unless @group
- id = params[:group_id] || params[:id]
- @group = Group.find_by_full_path(id)
- @group_merge_requests = MergeRequestsFinder.new(current_user, group_id: @group.id).execute
-
- unless @group && can?(current_user, :read_group, @group)
- @group = nil
-
- if current_user.nil?
- authenticate_user!
- else
- render_404
- end
- end
- end
-
- @group
+ @group ||= find_routable!(Group, params[:group_id] || params[:id])
end
def group_projects
@projects ||= GroupProjectsFinder.new(group: group, current_user: current_user).execute
end
+ def group_merge_requests
+ @group_merge_requests = MergeRequestsFinder.new(current_user, group_id: @group.id).execute
+ end
+
def authorize_admin_group!
unless can?(current_user, :admin_group, group)
return render_404
diff --git a/app/controllers/groups/labels_controller.rb b/app/controllers/groups/labels_controller.rb
index facb25525b5..3fa0516fb0c 100644
--- a/app/controllers/groups/labels_controller.rb
+++ b/app/controllers/groups/labels_controller.rb
@@ -15,7 +15,7 @@ class Groups::LabelsController < Groups::ApplicationController
format.json do
available_labels = LabelsFinder.new(current_user, group_id: @group.id).execute
- render json: available_labels.as_json(only: [:id, :title, :color])
+ render json: LabelSerializer.new.represent_appearance(available_labels)
end
end
end
diff --git a/app/controllers/groups_controller.rb b/app/controllers/groups_controller.rb
index 593001e6396..46c3ff10694 100644
--- a/app/controllers/groups_controller.rb
+++ b/app/controllers/groups_controller.rb
@@ -12,8 +12,8 @@ class GroupsController < Groups::ApplicationController
before_action :authorize_admin_group!, only: [:edit, :update, :destroy, :projects]
before_action :authorize_create_group!, only: [:new, :create]
- # Load group projects
before_action :group_projects, only: [:projects, :activity, :issues, :merge_requests]
+ before_action :group_merge_requests, only: [:merge_requests]
before_action :event_filter, only: [:activity]
before_action :user_actions, only: [:show, :subgroups]
diff --git a/app/controllers/projects/application_controller.rb b/app/controllers/projects/application_controller.rb
index 89f1128ec36..12e4a6999ae 100644
--- a/app/controllers/projects/application_controller.rb
+++ b/app/controllers/projects/application_controller.rb
@@ -1,5 +1,8 @@
class Projects::ApplicationController < ApplicationController
+ include RoutableActions
+
skip_before_action :authenticate_user!
+ before_action :redirect_git_extension
before_action :project
before_action :repository
layout 'project'
@@ -8,40 +11,22 @@ class Projects::ApplicationController < ApplicationController
private
+ def redirect_git_extension
+ # Redirect from
+ # localhost/group/project.git
+ # to
+ # localhost/group/project
+ #
+ redirect_to url_for(params.merge(format: nil)) if params[:format] == 'git'
+ end
+
def project
- unless @project
- namespace = params[:namespace_id]
- id = params[:project_id] || params[:id]
-
- # Redirect from
- # localhost/group/project.git
- # to
- # localhost/group/project
- #
- if params[:format] == 'git'
- redirect_to request.original_url.gsub(/\.git\/?\Z/, '')
- return
- end
-
- project_path = "#{namespace}/#{id}"
- @project = Project.find_by_full_path(project_path)
-
- if can?(current_user, :read_project, @project) && !@project.pending_delete?
- if @project.path_with_namespace != project_path
- redirect_to request.original_url.gsub(project_path, @project.path_with_namespace)
- end
- else
- @project = nil
-
- if current_user.nil?
- authenticate_user!
- else
- render_404
- end
- end
- end
+ return @project if @project
+
+ path = File.join(params[:namespace_id], params[:project_id] || params[:id])
+ auth_proc = ->(project) { !project.pending_delete? }
- @project
+ @project = find_routable!(Project, path, extra_authorization_proc: auth_proc)
end
def repository
@@ -55,13 +40,15 @@ class Projects::ApplicationController < ApplicationController
(current_user && current_user.already_forked?(project))
end
- def authorize_project!(action)
- return access_denied! unless can?(current_user, action, project)
+ def authorize_action!(action)
+ unless can?(current_user, action, project)
+ return access_denied!
+ end
end
def method_missing(method_sym, *arguments, &block)
if method_sym.to_s =~ /\Aauthorize_(.*)!\z/
- authorize_project!($1.to_sym)
+ authorize_action!($1.to_sym)
else
super
end
diff --git a/app/controllers/projects/boards/issues_controller.rb b/app/controllers/projects/boards/issues_controller.rb
index 28c9646910d..da9b789d617 100644
--- a/app/controllers/projects/boards/issues_controller.rb
+++ b/app/controllers/projects/boards/issues_controller.rb
@@ -82,7 +82,7 @@ module Projects
labels: true,
only: [:id, :iid, :title, :confidential, :due_date, :relative_position],
include: {
- assignee: { only: [:id, :name, :username], methods: [:avatar_url] },
+ assignees: { only: [:id, :name, :username], methods: [:avatar_url] },
milestone: { only: [:id, :title] }
},
user: current_user
diff --git a/app/controllers/projects/builds_controller.rb b/app/controllers/projects/builds_controller.rb
index e24fc45d166..0fd35bcb790 100644
--- a/app/controllers/projects/builds_controller.rb
+++ b/app/controllers/projects/builds_controller.rb
@@ -1,7 +1,11 @@
class Projects::BuildsController < Projects::ApplicationController
before_action :build, except: [:index, :cancel_all]
- before_action :authorize_read_build!, only: [:index, :show, :status, :raw, :trace]
- before_action :authorize_update_build!, except: [:index, :show, :status, :raw, :trace]
+
+ before_action :authorize_read_build!,
+ only: [:index, :show, :status, :raw, :trace]
+ before_action :authorize_update_build!,
+ except: [:index, :show, :status, :raw, :trace, :cancel_all]
+
layout 'project'
def index
@@ -28,7 +32,12 @@ class Projects::BuildsController < Projects::ApplicationController
end
def cancel_all
- @project.builds.running_or_pending.each(&:cancel)
+ return access_denied! unless can?(current_user, :update_build, project)
+
+ @project.builds.running_or_pending.each do |build|
+ build.cancel if can?(current_user, :update_build, build)
+ end
+
redirect_to namespace_project_builds_path(project.namespace, project)
end
@@ -107,8 +116,13 @@ class Projects::BuildsController < Projects::ApplicationController
private
+ def authorize_update_build!
+ return access_denied! unless can?(current_user, :update_build, build)
+ end
+
def build
- @build ||= project.builds.find_by!(id: params[:id]).present(current_user: current_user)
+ @build ||= project.builds.find(params[:id])
+ .present(current_user: current_user)
end
def build_path(build)
diff --git a/app/controllers/projects/git_http_controller.rb b/app/controllers/projects/git_http_controller.rb
index 10adddb4636..9e4edcae101 100644
--- a/app/controllers/projects/git_http_controller.rb
+++ b/app/controllers/projects/git_http_controller.rb
@@ -59,7 +59,7 @@ class Projects::GitHttpController < Projects::GitHttpClientController
def render_ok
set_workhorse_internal_api_content_type
- render json: Gitlab::Workhorse.git_http_ok(repository, user, action_name)
+ render json: Gitlab::Workhorse.git_http_ok(repository, wiki?, user, action_name)
end
def render_http_not_allowed
diff --git a/app/controllers/projects/issues_controller.rb b/app/controllers/projects/issues_controller.rb
index af9157bfbb5..bcd23d61519 100644
--- a/app/controllers/projects/issues_controller.rb
+++ b/app/controllers/projects/issues_controller.rb
@@ -67,7 +67,7 @@ class Projects::IssuesController < Projects::ApplicationController
def new
params[:issue] ||= ActionController::Parameters.new(
- assignee_id: ""
+ assignee_ids: ""
)
build_params = issue_params.merge(
merge_request_to_resolve_discussions_of: params[:merge_request_to_resolve_discussions_of],
@@ -150,7 +150,7 @@ class Projects::IssuesController < Projects::ApplicationController
if @issue.valid?
render json: @issue.to_json(methods: [:task_status, :task_status_short],
include: { milestone: {},
- assignee: { only: [:name, :username], methods: [:avatar_url] },
+ assignees: { only: [:id, :name, :username], methods: [:avatar_url] },
labels: { methods: :text_color } })
else
render json: { errors: @issue.errors.full_messages }, status: :unprocessable_entity
@@ -201,7 +201,16 @@ class Projects::IssuesController < Projects::ApplicationController
def rendered_title
Gitlab::PollingInterval.set_header(response, interval: 3_000)
- render json: { title: view_context.markdown_field(@issue, :title) }
+
+ render json: {
+ title: view_context.markdown_field(@issue, :title),
+ title_text: @issue.title,
+ description: view_context.markdown_field(@issue, :description),
+ description_text: @issue.description,
+ task_status: @issue.task_status,
+ issue_number: @issue.iid,
+ updated_at: @issue.updated_at,
+ }
end
def create_merge_request
@@ -275,7 +284,7 @@ class Projects::IssuesController < Projects::ApplicationController
def issue_params
params.require(:issue).permit(
:title, :assignee_id, :position, :description, :confidential,
- :milestone_id, :due_date, :state_event, :task_num, :lock_version, label_ids: []
+ :milestone_id, :due_date, :state_event, :task_num, :lock_version, label_ids: [], assignee_ids: [],
)
end
diff --git a/app/controllers/projects/labels_controller.rb b/app/controllers/projects/labels_controller.rb
index 2f55ba4e700..71bfb7163da 100644
--- a/app/controllers/projects/labels_controller.rb
+++ b/app/controllers/projects/labels_controller.rb
@@ -19,7 +19,7 @@ class Projects::LabelsController < Projects::ApplicationController
respond_to do |format|
format.html
format.json do
- render json: @available_labels.as_json(only: [:id, :title, :color])
+ render json: LabelSerializer.new.represent_appearance(@available_labels)
end
end
end
diff --git a/app/controllers/projects/pipelines_controller.rb b/app/controllers/projects/pipelines_controller.rb
index 2908036607a..5cb2e428201 100644
--- a/app/controllers/projects/pipelines_controller.rb
+++ b/app/controllers/projects/pipelines_controller.rb
@@ -1,6 +1,6 @@
class Projects::PipelinesController < Projects::ApplicationController
before_action :pipeline, except: [:index, :new, :create, :charts]
- before_action :commit, only: [:show, :builds]
+ before_action :commit, only: [:show, :builds, :failures]
before_action :authorize_read_pipeline!
before_action :authorize_create_pipeline!, only: [:new, :create]
before_action :authorize_update_pipeline!, only: [:retry, :cancel]
@@ -8,6 +8,8 @@ class Projects::PipelinesController < Projects::ApplicationController
wrap_parameters Ci::Pipeline
+ POLLING_INTERVAL = 10_000
+
def index
@scope = params[:scope]
@pipelines = PipelinesFinder
@@ -31,7 +33,7 @@ class Projects::PipelinesController < Projects::ApplicationController
respond_to do |format|
format.html
format.json do
- Gitlab::PollingInterval.set_header(response, interval: 10_000)
+ Gitlab::PollingInterval.set_header(response, interval: POLLING_INTERVAL)
render json: {
pipelines: PipelineSerializer
@@ -57,22 +59,36 @@ class Projects::PipelinesController < Projects::ApplicationController
@pipeline = Ci::CreatePipelineService
.new(project, current_user, create_params)
.execute(ignore_skip_ci: true, save_on_errors: false)
- unless @pipeline.persisted?
+
+ if @pipeline.persisted?
+ redirect_to namespace_project_pipeline_path(project.namespace, project, @pipeline)
+ else
render 'new'
- return
end
-
- redirect_to namespace_project_pipeline_path(project.namespace, project, @pipeline)
end
def show
+ respond_to do |format|
+ format.html
+ format.json do
+ Gitlab::PollingInterval.set_header(response, interval: POLLING_INTERVAL)
+
+ render json: PipelineSerializer
+ .new(project: @project, user: @current_user)
+ .represent(@pipeline, grouped: true)
+ end
+ end
end
def builds
- respond_to do |format|
- format.html do
- render 'show'
- end
+ render_show
+ end
+
+ def failures
+ if @pipeline.statuses.latest.failed.present?
+ render_show
+ else
+ redirect_to pipeline_path(@pipeline)
end
end
@@ -125,6 +141,14 @@ class Projects::PipelinesController < Projects::ApplicationController
private
+ def render_show
+ respond_to do |format|
+ format.html do
+ render 'show'
+ end
+ end
+ end
+
def create_params
params.require(:pipeline).permit(:ref)
end
diff --git a/app/controllers/users_controller.rb b/app/controllers/users_controller.rb
index a452bbba422..ca89ed221c6 100644
--- a/app/controllers/users_controller.rb
+++ b/app/controllers/users_controller.rb
@@ -1,7 +1,8 @@
class UsersController < ApplicationController
+ include RoutableActions
+
skip_before_action :authenticate_user!
before_action :user, except: [:exists]
- before_action :authorize_read_user!, only: [:show]
def show
respond_to do |format|
@@ -91,12 +92,8 @@ class UsersController < ApplicationController
private
- def authorize_read_user!
- render_404 unless can?(current_user, :read_user, user)
- end
-
def user
- @user ||= User.find_by_username!(params[:username])
+ @user ||= find_routable!(User, params[:username])
end
def contributed_projects
diff --git a/app/finders/issuable_finder.rb b/app/finders/issuable_finder.rb
index 4cc42b88a2a..957ad875858 100644
--- a/app/finders/issuable_finder.rb
+++ b/app/finders/issuable_finder.rb
@@ -231,7 +231,7 @@ class IssuableFinder
when 'created-by-me', 'authored'
items.where(author_id: current_user.id)
when 'assigned-to-me'
- items.where(assignee_id: current_user.id)
+ items.assigned_to(current_user)
else
items
end
diff --git a/app/finders/issues_finder.rb b/app/finders/issues_finder.rb
index 76715e5970d..b4c074bc69c 100644
--- a/app/finders/issues_finder.rb
+++ b/app/finders/issues_finder.rb
@@ -26,17 +26,28 @@ class IssuesFinder < IssuableFinder
IssuesFinder.not_restricted_by_confidentiality(current_user)
end
+ def by_assignee(items)
+ if assignee
+ items.assigned_to(assignee)
+ elsif no_assignee?
+ items.unassigned
+ elsif assignee_id? || assignee_username? # assignee not found
+ items.none
+ else
+ items
+ end
+ end
+
def self.not_restricted_by_confidentiality(user)
- return Issue.where('issues.confidential IS NULL OR issues.confidential IS FALSE') if user.blank?
+ return Issue.where('issues.confidential IS NOT TRUE') if user.blank?
return Issue.all if user.admin?
Issue.where('
- issues.confidential IS NULL
- OR issues.confidential IS FALSE
+ issues.confidential IS NOT TRUE
OR (issues.confidential = TRUE
AND (issues.author_id = :user_id
- OR issues.assignee_id = :user_id
+ OR EXISTS (SELECT TRUE FROM issue_assignees WHERE user_id = :user_id AND issue_id = issues.id)
OR issues.project_id IN(:project_ids)))',
user_id: user.id,
project_ids: user.authorized_projects(Gitlab::Access::REPORTER).select(:id))
diff --git a/app/helpers/application_helper.rb b/app/helpers/application_helper.rb
index fff57472a4f..6d6bcbaf88a 100644
--- a/app/helpers/application_helper.rb
+++ b/app/helpers/application_helper.rb
@@ -180,16 +180,16 @@ module ApplicationHelper
element
end
- def edited_time_ago_with_tooltip(object, placement: 'top', html_class: 'time_ago', include_author: false)
- return if object.updated_at == object.created_at
+ def edited_time_ago_with_tooltip(object, placement: 'top', html_class: 'time_ago', exclude_author: false)
+ return if object.last_edited_at == object.created_at || object.last_edited_at.blank?
- content_tag :small, class: "edited-text" do
- output = content_tag(:span, "Edited ")
- output << time_ago_with_tooltip(object.updated_at, placement: placement, html_class: html_class)
+ content_tag :small, class: 'edited-text' do
+ output = content_tag(:span, 'Edited ')
+ output << time_ago_with_tooltip(object.last_edited_at, placement: placement, html_class: html_class)
- if include_author && object.updated_by && object.updated_by != object.author
- output << content_tag(:span, " by ")
- output << link_to_member(object.project, object.updated_by, avatar: false, author_class: nil)
+ if !exclude_author && object.last_edited_by
+ output << content_tag(:span, ' by ')
+ output << link_to_member(object.project, object.last_edited_by, avatar: false, author_class: nil)
end
output
diff --git a/app/helpers/builds_helper.rb b/app/helpers/builds_helper.rb
index 2fcb7a59fc3..2eb2c6c7389 100644
--- a/app/helpers/builds_helper.rb
+++ b/app/helpers/builds_helper.rb
@@ -1,4 +1,16 @@
module BuildsHelper
+ def build_summary(build, skip: false)
+ if build.has_trace?
+ if skip
+ link_to "View job trace", pipeline_build_url(build.pipeline, build)
+ else
+ build.trace.html(last_lines: 10).html_safe
+ end
+ else
+ "No job trace"
+ end
+ end
+
def sidebar_build_class(build, current_build)
build_class = ''
build_class += ' active' if build.id === current_build.id
diff --git a/app/helpers/form_helper.rb b/app/helpers/form_helper.rb
index 1182939f656..53962b84618 100644
--- a/app/helpers/form_helper.rb
+++ b/app/helpers/form_helper.rb
@@ -15,4 +15,36 @@ module FormHelper
end
end
end
+
+ def issue_dropdown_options(issuable, has_multiple_assignees = true)
+ options = {
+ toggle_class: 'js-user-search js-assignee-search js-multiselect js-save-user-data',
+ title: 'Select assignee',
+ filter: true,
+ dropdown_class: 'dropdown-menu-user dropdown-menu-selectable dropdown-menu-assignee',
+ placeholder: 'Search users',
+ data: {
+ first_user: current_user&.username,
+ null_user: true,
+ current_user: true,
+ project_id: issuable.project.try(:id),
+ field_name: "#{issuable.class.model_name.param_key}[assignee_ids][]",
+ default_label: 'Assignee',
+ 'max-select': 1,
+ 'dropdown-header': 'Assignee',
+ multi_select: true,
+ 'input-meta': 'name',
+ 'always-show-selectbox': true,
+ current_user_info: current_user.to_json(only: [:id, :name])
+ }
+ }
+
+ if has_multiple_assignees
+ options[:title] = 'Select assignee(s)'
+ options[:data][:'dropdown-header'] = 'Assignee(s)'
+ options[:data].delete(:'max-select')
+ end
+
+ options
+ end
end
diff --git a/app/helpers/issuables_helper.rb b/app/helpers/issuables_helper.rb
index 0b13dbf5f8d..7656929efe7 100644
--- a/app/helpers/issuables_helper.rb
+++ b/app/helpers/issuables_helper.rb
@@ -63,6 +63,16 @@ module IssuablesHelper
end
end
+ def users_dropdown_label(selected_users)
+ if selected_users.length == 0
+ "Unassigned"
+ elsif selected_users.length == 1
+ selected_users[0].name
+ else
+ "#{selected_users[0].name} + #{selected_users.length - 1} more"
+ end
+ end
+
def user_dropdown_label(user_id, default_label)
return default_label if user_id.nil?
return "Unassigned" if user_id == "0"
diff --git a/app/helpers/system_note_helper.rb b/app/helpers/system_note_helper.rb
index 1ea60e39386..d889d141101 100644
--- a/app/helpers/system_note_helper.rb
+++ b/app/helpers/system_note_helper.rb
@@ -1,6 +1,7 @@
module SystemNoteHelper
ICON_NAMES_BY_ACTION = {
'commit' => 'icon_commit',
+ 'description' => 'icon_edit',
'merge' => 'icon_merge',
'merged' => 'icon_merged',
'opened' => 'icon_status_open',
diff --git a/app/mailers/emails/issues.rb b/app/mailers/emails/issues.rb
index d64e48f774b..0f847841295 100644
--- a/app/mailers/emails/issues.rb
+++ b/app/mailers/emails/issues.rb
@@ -11,10 +11,12 @@ module Emails
mail_answer_thread(@issue, issue_thread_options(updated_by_user_id, recipient_id))
end
- def reassigned_issue_email(recipient_id, issue_id, previous_assignee_id, updated_by_user_id)
+ def reassigned_issue_email(recipient_id, issue_id, previous_assignee_ids, updated_by_user_id)
setup_issue_mail(issue_id, recipient_id)
- @previous_assignee = User.find_by(id: previous_assignee_id) if previous_assignee_id
+ @previous_assignees = []
+ @previous_assignees = User.where(id: previous_assignee_ids) if previous_assignee_ids.any?
+
mail_answer_thread(@issue, issue_thread_options(updated_by_user_id, recipient_id))
end
diff --git a/app/models/application_setting.rb b/app/models/application_setting.rb
index cf042717c95..54f01f8637e 100644
--- a/app/models/application_setting.rb
+++ b/app/models/application_setting.rb
@@ -62,6 +62,10 @@ class ApplicationSetting < ActiveRecord::Base
presence: true,
if: :sentry_enabled
+ validates :clientside_sentry_dsn,
+ presence: true,
+ if: :clientside_sentry_enabled
+
validates :akismet_api_key,
presence: true,
if: :akismet_enabled
diff --git a/app/models/blob.rb b/app/models/blob.rb
index a4fae22a0c4..eaf0b713122 100644
--- a/app/models/blob.rb
+++ b/app/models/blob.rb
@@ -26,6 +26,7 @@ class Blob < SimpleDelegator
BlobViewer::Image,
BlobViewer::Sketch,
+ BlobViewer::Balsamiq,
BlobViewer::Video,
diff --git a/app/models/blob_viewer/balsamiq.rb b/app/models/blob_viewer/balsamiq.rb
new file mode 100644
index 00000000000..f982521db99
--- /dev/null
+++ b/app/models/blob_viewer/balsamiq.rb
@@ -0,0 +1,12 @@
+module BlobViewer
+ class Balsamiq < Base
+ include Rich
+ include ClientSide
+
+ self.partial_name = 'balsamiq'
+ self.extensions = %w(bmpr)
+ self.binary = true
+ self.switcher_icon = 'file-image-o'
+ self.switcher_title = 'preview'
+ end
+end
diff --git a/app/models/ci/build.rb b/app/models/ci/build.rb
index b426c27afbb..971ab7cb0ee 100644
--- a/app/models/ci/build.rb
+++ b/app/models/ci/build.rb
@@ -111,14 +111,9 @@ module Ci
end
def play(current_user)
- # Try to queue a current build
- if self.enqueue
- self.update(user: current_user)
- self
- else
- # Otherwise we need to create a duplicate
- Ci::Build.retry(self, current_user)
- end
+ Ci::PlayBuildService
+ .new(project, current_user)
+ .execute(self)
end
def cancelable?
diff --git a/app/models/ci/group.rb b/app/models/ci/group.rb
new file mode 100644
index 00000000000..87898b086c6
--- /dev/null
+++ b/app/models/ci/group.rb
@@ -0,0 +1,40 @@
+module Ci
+ ##
+ # This domain model is a representation of a group of jobs that are related
+ # to each other, like `rspec 0 1`, `rspec 0 2`.
+ #
+ # It is not persisted in the database.
+ #
+ class Group
+ include StaticModel
+
+ attr_reader :stage, :name, :jobs
+
+ delegate :size, to: :jobs
+
+ def initialize(stage, name:, jobs:)
+ @stage = stage
+ @name = name
+ @jobs = jobs
+ end
+
+ def status
+ @status ||= commit_statuses.status
+ end
+
+ def detailed_status(current_user)
+ if jobs.one?
+ jobs.first.detailed_status(current_user)
+ else
+ Gitlab::Ci::Status::Group::Factory
+ .new(self, current_user).fabricate!
+ end
+ end
+
+ private
+
+ def commit_statuses
+ @commit_statuses ||= CommitStatus.where(id: jobs.map(&:id))
+ end
+ end
+end
diff --git a/app/models/ci/stage.rb b/app/models/ci/stage.rb
index e7d6b17d445..9bda3186c30 100644
--- a/app/models/ci/stage.rb
+++ b/app/models/ci/stage.rb
@@ -15,6 +15,14 @@ module Ci
@warnings = warnings
end
+ def groups
+ @groups ||= statuses.ordered.latest
+ .sort_by(&:sortable_name).group_by(&:group_name)
+ .map do |group_name, grouped_statuses|
+ Ci::Group.new(self, name: group_name, jobs: grouped_statuses)
+ end
+ end
+
def to_param
name
end
diff --git a/app/models/concerns/issuable.rb b/app/models/concerns/issuable.rb
index 26dbf4d9570..075ec575f9d 100644
--- a/app/models/concerns/issuable.rb
+++ b/app/models/concerns/issuable.rb
@@ -26,8 +26,8 @@ module Issuable
cache_markdown_field :description, issuable_state_filter_enabled: true
belongs_to :author, class_name: "User"
- belongs_to :assignee, class_name: "User"
belongs_to :updated_by, class_name: "User"
+ belongs_to :last_edited_by, class_name: 'User'
belongs_to :milestone
has_many :notes, as: :noteable, inverse_of: :noteable, dependent: :destroy do
def authors_loaded?
@@ -65,11 +65,8 @@ module Issuable
validates :title, presence: true, length: { maximum: 255 }
scope :authored, ->(user) { where(author_id: user) }
- scope :assigned_to, ->(u) { where(assignee_id: u.id)}
scope :recent, -> { reorder(id: :desc) }
scope :order_position_asc, -> { reorder(position: :asc) }
- scope :assigned, -> { where("assignee_id IS NOT NULL") }
- scope :unassigned, -> { where("assignee_id IS NULL") }
scope :of_projects, ->(ids) { where(project_id: ids) }
scope :of_milestones, ->(ids) { where(milestone_id: ids) }
scope :with_milestone, ->(title) { left_joins_milestones.where(milestones: { title: title }) }
@@ -92,23 +89,14 @@ module Issuable
attr_mentionable :description
participant :author
- participant :assignee
participant :notes_with_associations
strip_attributes :title
acts_as_paranoid
- after_save :update_assignee_cache_counts, if: :assignee_id_changed?
after_save :record_metrics, unless: :imported?
- def update_assignee_cache_counts
- # make sure we flush the cache for both the old *and* new assignees(if they exist)
- previous_assignee = User.find_by_id(assignee_id_was) if assignee_id_was
- previous_assignee&.update_cache_counts
- assignee&.update_cache_counts
- end
-
# We want to use optimistic lock for cases when only title or description are involved
# http://api.rubyonrails.org/classes/ActiveRecord/Locking/Optimistic.html
def locking_enabled?
@@ -237,10 +225,6 @@ module Issuable
today? && created_at == updated_at
end
- def is_being_reassigned?
- assignee_id_changed?
- end
-
def open?
opened? || reopened?
end
@@ -269,7 +253,11 @@ module Issuable
# DEPRECATED
repository: project.hook_attrs.slice(:name, :url, :description, :homepage)
}
- hook_data[:assignee] = assignee.hook_attrs if assignee
+ if self.is_a?(Issue)
+ hook_data[:assignees] = assignees.map(&:hook_attrs) if assignees.any?
+ else
+ hook_data[:assignee] = assignee.hook_attrs if assignee
+ end
hook_data
end
@@ -331,11 +319,6 @@ module Issuable
false
end
- def assignee_or_author?(user)
- # We're comparing IDs here so we don't need to load any associations.
- author_id == user.id || assignee_id == user.id
- end
-
def record_metrics
metrics = self.metrics || create_metrics
metrics.record!
diff --git a/app/models/concerns/milestoneish.rb b/app/models/concerns/milestoneish.rb
index f449229864d..a3472af5c55 100644
--- a/app/models/concerns/milestoneish.rb
+++ b/app/models/concerns/milestoneish.rb
@@ -40,7 +40,7 @@ module Milestoneish
def issues_visible_to_user(user)
memoize_per_user(user, :issues_visible_to_user) do
IssuesFinder.new(user, issues_finder_params)
- .execute.where(milestone_id: milestoneish_ids)
+ .execute.includes(:assignees).where(milestone_id: milestoneish_ids)
end
end
diff --git a/app/models/concerns/routable.rb b/app/models/concerns/routable.rb
index b28e05d0c28..c4463abdfe6 100644
--- a/app/models/concerns/routable.rb
+++ b/app/models/concerns/routable.rb
@@ -5,6 +5,7 @@ module Routable
included do
has_one :route, as: :source, autosave: true, dependent: :destroy
+ has_many :redirect_routes, as: :source, autosave: true, dependent: :destroy
validates_associated :route
validates :route, presence: true
@@ -26,16 +27,31 @@ module Routable
# Klass.find_by_full_path('gitlab-org/gitlab-ce')
#
# Returns a single object, or nil.
- def find_by_full_path(path)
+ def find_by_full_path(path, follow_redirects: false)
# On MySQL we want to ensure the ORDER BY uses a case-sensitive match so
# any literal matches come first, for this we have to use "BINARY".
# Without this there's still no guarantee in what order MySQL will return
# rows.
+ #
+ # Why do we do this?
+ #
+ # Even though we have Rails validation on Route for unique paths
+ # (case-insensitive), there are old projects in our DB (and possibly
+ # clients' DBs) that have the same path with different cases.
+ # See https://gitlab.com/gitlab-org/gitlab-ce/issues/18603. Also note that
+ # our unique index is case-sensitive in Postgres.
binary = Gitlab::Database.mysql? ? 'BINARY' : ''
-
order_sql = "(CASE WHEN #{binary} routes.path = #{connection.quote(path)} THEN 0 ELSE 1 END)"
-
- where_full_path_in([path]).reorder(order_sql).take
+ found = where_full_path_in([path]).reorder(order_sql).take
+ return found if found
+
+ if follow_redirects
+ if Gitlab::Database.postgresql?
+ joins(:redirect_routes).find_by("LOWER(redirect_routes.path) = LOWER(?)", path)
+ else
+ joins(:redirect_routes).find_by(redirect_routes: { path: path })
+ end
+ end
end
# Builds a relation to find multiple objects by their full paths.
diff --git a/app/models/deployment.rb b/app/models/deployment.rb
index afad001d50f..37adfb4de73 100644
--- a/app/models/deployment.rb
+++ b/app/models/deployment.rb
@@ -85,8 +85,8 @@ class Deployment < ActiveRecord::Base
end
def stop_action
- return nil unless on_stop.present?
- return nil unless manual_actions
+ return unless on_stop.present?
+ return unless manual_actions
@stop_action ||= manual_actions.find_by(name: on_stop)
end
diff --git a/app/models/global_milestone.rb b/app/models/global_milestone.rb
index 0afbca2cb32..538615130a7 100644
--- a/app/models/global_milestone.rb
+++ b/app/models/global_milestone.rb
@@ -36,7 +36,7 @@ class GlobalMilestone
closed = count_by_state(milestones_by_state_and_title, 'closed')
all = milestones_by_state_and_title.map { |(_, title), _| title }.uniq.count
- {
+ {
opened: opened,
closed: closed,
all: all
@@ -86,7 +86,7 @@ class GlobalMilestone
end
def issues
- @issues ||= Issue.of_milestones(milestoneish_ids).includes(:project, :assignee, :labels)
+ @issues ||= Issue.of_milestones(milestoneish_ids).includes(:project, :assignees, :labels)
end
def merge_requests
@@ -94,7 +94,7 @@ class GlobalMilestone
end
def participants
- @participants ||= milestones.includes(:participants).map(&:participants).flatten.compact.uniq
+ @participants ||= milestones.map(&:participants).flatten.uniq
end
def labels
diff --git a/app/models/issue.rb b/app/models/issue.rb
index 78bde6820da..27e3ed9bc7f 100644
--- a/app/models/issue.rb
+++ b/app/models/issue.rb
@@ -24,10 +24,17 @@ class Issue < ActiveRecord::Base
has_many :merge_requests_closing_issues, class_name: 'MergeRequestsClosingIssues', dependent: :delete_all
+ has_many :issue_assignees
+ has_many :assignees, class_name: "User", through: :issue_assignees
+
validates :project, presence: true
scope :in_projects, ->(project_ids) { where(project_id: project_ids) }
+ scope :assigned, -> { where('EXISTS (SELECT TRUE FROM issue_assignees WHERE issue_id = issues.id)') }
+ scope :unassigned, -> { where('NOT EXISTS (SELECT TRUE FROM issue_assignees WHERE issue_id = issues.id)') }
+ scope :assigned_to, ->(u) { where('EXISTS (SELECT TRUE FROM issue_assignees WHERE user_id = ? AND issue_id = issues.id)', u.id)}
+
scope :without_due_date, -> { where(due_date: nil) }
scope :due_before, ->(date) { where('issues.due_date < ?', date) }
scope :due_between, ->(from_date, to_date) { where('issues.due_date >= ?', from_date).where('issues.due_date <= ?', to_date) }
@@ -37,13 +44,15 @@ class Issue < ActiveRecord::Base
scope :created_after, -> (datetime) { where("created_at >= ?", datetime) }
- scope :include_associations, -> { includes(:assignee, :labels, project: :namespace) }
+ scope :include_associations, -> { includes(:labels, project: :namespace) }
after_save :expire_etag_cache
attr_spammable :title, spam_title: true
attr_spammable :description, spam_description: true
+ participant :assignees
+
state_machine :state, initial: :opened do
event :close do
transition [:reopened, :opened] => :closed
@@ -63,10 +72,14 @@ class Issue < ActiveRecord::Base
end
def hook_attrs
+ assignee_ids = self.assignee_ids
+
attrs = {
total_time_spent: total_time_spent,
human_total_time_spent: human_total_time_spent,
- human_time_estimate: human_time_estimate
+ human_time_estimate: human_time_estimate,
+ assignee_ids: assignee_ids,
+ assignee_id: assignee_ids.first # This key is deprecated
}
attributes.merge!(attrs)
@@ -114,6 +127,22 @@ class Issue < ActiveRecord::Base
"id DESC")
end
+ # Returns a Hash of attributes to be used for Twitter card metadata
+ def card_attributes
+ {
+ 'Author' => author.try(:name),
+ 'Assignee' => assignee_list
+ }
+ end
+
+ def assignee_or_author?(user)
+ author_id == user.id || assignees.exists?(user.id)
+ end
+
+ def assignee_list
+ assignees.map(&:name).to_sentence
+ end
+
# `from` argument can be a Namespace or Project.
def to_reference(from = nil, full: false)
reference = "#{self.class.reference_prefix}#{iid}"
@@ -248,7 +277,7 @@ class Issue < ActiveRecord::Base
true
elsif confidential?
author == user ||
- assignee == user ||
+ assignees.include?(user) ||
project.team.member?(user, Gitlab::Access::REPORTER)
else
project.public? ||
diff --git a/app/models/issue_assignee.rb b/app/models/issue_assignee.rb
new file mode 100644
index 00000000000..0663d3aaef8
--- /dev/null
+++ b/app/models/issue_assignee.rb
@@ -0,0 +1,13 @@
+class IssueAssignee < ActiveRecord::Base
+ extend Gitlab::CurrentSettings
+
+ belongs_to :issue
+ belongs_to :assignee, class_name: "User", foreign_key: :user_id
+
+ after_create :update_assignee_cache_counts
+ after_destroy :update_assignee_cache_counts
+
+ def update_assignee_cache_counts
+ assignee&.update_cache_counts
+ end
+end
diff --git a/app/models/merge_request.rb b/app/models/merge_request.rb
index 12c5481cd6d..35231bab12e 100644
--- a/app/models/merge_request.rb
+++ b/app/models/merge_request.rb
@@ -17,6 +17,8 @@ class MergeRequest < ActiveRecord::Base
has_many :merge_requests_closing_issues, class_name: 'MergeRequestsClosingIssues', dependent: :delete_all
+ belongs_to :assignee, class_name: "User"
+
serialize :merge_params, Hash
after_create :ensure_merge_request_diff, unless: :importing?
@@ -114,8 +116,14 @@ class MergeRequest < ActiveRecord::Base
scope :join_project, -> { joins(:target_project) }
scope :references_project, -> { references(:target_project) }
+ scope :assigned, -> { where("assignee_id IS NOT NULL") }
+ scope :unassigned, -> { where("assignee_id IS NULL") }
+ scope :assigned_to, ->(u) { where(assignee_id: u.id)}
+
+ participant :assignee
after_save :keep_around_commit
+ after_save :update_assignee_cache_counts, if: :assignee_id_changed?
def self.reference_prefix
'!'
@@ -177,6 +185,30 @@ class MergeRequest < ActiveRecord::Base
work_in_progress?(title) ? title : "WIP: #{title}"
end
+ def update_assignee_cache_counts
+ # make sure we flush the cache for both the old *and* new assignees(if they exist)
+ previous_assignee = User.find_by_id(assignee_id_was) if assignee_id_was
+ previous_assignee&.update_cache_counts
+ assignee&.update_cache_counts
+ end
+
+ # Returns a Hash of attributes to be used for Twitter card metadata
+ def card_attributes
+ {
+ 'Author' => author.try(:name),
+ 'Assignee' => assignee.try(:name)
+ }
+ end
+
+ # This method is needed for compatibility with issues to not mess view and other code
+ def assignees
+ Array(assignee)
+ end
+
+ def assignee_or_author?(user)
+ author_id == user.id || assignee_id == user.id
+ end
+
# `from` argument can be a Namespace or Project.
def to_reference(from = nil, full: false)
reference = "#{self.class.reference_prefix}#{iid}"
diff --git a/app/models/milestone.rb b/app/models/milestone.rb
index 652b1551928..c06bfe0ccdd 100644
--- a/app/models/milestone.rb
+++ b/app/models/milestone.rb
@@ -21,7 +21,6 @@ class Milestone < ActiveRecord::Base
has_many :issues
has_many :labels, -> { distinct.reorder('labels.title') }, through: :issues
has_many :merge_requests
- has_many :participants, -> { distinct.reorder('users.name') }, through: :issues, source: :assignee
has_many :events, as: :target, dependent: :destroy
scope :active, -> { with_state(:active) }
@@ -107,6 +106,10 @@ class Milestone < ActiveRecord::Base
end
end
+ def participants
+ User.joins(assigned_issues: :milestone).where("milestones.id = ?", id)
+ end
+
def self.sort(method)
case method.to_s
when 'due_date_asc'
diff --git a/app/models/note.rb b/app/models/note.rb
index b06985b4a6f..46d0a4f159f 100644
--- a/app/models/note.rb
+++ b/app/models/note.rb
@@ -18,6 +18,11 @@ class Note < ActiveRecord::Base
cache_markdown_field :note, pipeline: :note, issuable_state_filter_enabled: true
+ # Aliases to make application_helper#edited_time_ago_with_tooltip helper work properly with notes.
+ # See https://gitlab.com/gitlab-org/gitlab-ce/merge_requests/10392/diffs#note_28719102
+ alias_attribute :last_edited_at, :updated_at
+ alias_attribute :last_edited_by, :updated_by
+
# Attribute containing rendered and redacted Markdown as generated by
# Banzai::ObjectRenderer.
attr_accessor :redacted_note_html
@@ -38,6 +43,7 @@ class Note < ActiveRecord::Base
belongs_to :noteable, polymorphic: true, touch: true
belongs_to :author, class_name: "User"
belongs_to :updated_by, class_name: "User"
+ belongs_to :last_edited_by, class_name: 'User'
has_many :todos, dependent: :destroy
has_many :events, as: :target, dependent: :destroy
diff --git a/app/models/redirect_route.rb b/app/models/redirect_route.rb
new file mode 100644
index 00000000000..99812bcde53
--- /dev/null
+++ b/app/models/redirect_route.rb
@@ -0,0 +1,12 @@
+class RedirectRoute < ActiveRecord::Base
+ belongs_to :source, polymorphic: true
+
+ validates :source, presence: true
+
+ validates :path,
+ length: { within: 1..255 },
+ presence: true,
+ uniqueness: { case_sensitive: false }
+
+ scope :matching_path_and_descendants, -> (path) { where('redirect_routes.path = ? OR redirect_routes.path LIKE ?', path, "#{sanitize_sql_like(path)}/%") }
+end
diff --git a/app/models/route.rb b/app/models/route.rb
index 4b3efab5c3c..12a7fa3d01b 100644
--- a/app/models/route.rb
+++ b/app/models/route.rb
@@ -8,29 +8,58 @@ class Route < ActiveRecord::Base
presence: true,
uniqueness: { case_sensitive: false }
+ after_create :delete_conflicting_redirects
+ after_update :delete_conflicting_redirects, if: :path_changed?
+ after_update :create_redirect_for_old_path
after_update :rename_descendants
scope :inside_path, -> (path) { where('routes.path LIKE ?', "#{sanitize_sql_like(path)}/%") }
def rename_descendants
- if path_changed? || name_changed?
- descendants = self.class.inside_path(path_was)
+ return unless path_changed? || name_changed?
- descendants.each do |route|
- attributes = {}
+ descendant_routes = self.class.inside_path(path_was)
- if path_changed? && route.path.present?
- attributes[:path] = route.path.sub(path_was, path)
- end
+ descendant_routes.each do |route|
+ attributes = {}
- if name_changed? && name_was.present? && route.name.present?
- attributes[:name] = route.name.sub(name_was, name)
- end
+ if path_changed? && route.path.present?
+ attributes[:path] = route.path.sub(path_was, path)
+ end
- # Note that update_columns skips validation and callbacks.
- # We need this to avoid recursive call of rename_descendants method
- route.update_columns(attributes) unless attributes.empty?
+ if name_changed? && name_was.present? && route.name.present?
+ attributes[:name] = route.name.sub(name_was, name)
+ end
+
+ if attributes.present?
+ old_path = route.path
+
+ # Callbacks must be run manually
+ route.update_columns(attributes)
+
+ # We are not calling route.delete_conflicting_redirects here, in hopes
+ # of avoiding deadlocks. The parent (self, in this method) already
+ # called it, which deletes conflicts for all descendants.
+ route.create_redirect(old_path) if attributes[:path]
end
end
end
+
+ def delete_conflicting_redirects
+ conflicting_redirects.delete_all
+ end
+
+ def conflicting_redirects
+ RedirectRoute.matching_path_and_descendants(path)
+ end
+
+ def create_redirect(path)
+ RedirectRoute.create(source: source, path: path)
+ end
+
+ private
+
+ def create_redirect_for_old_path
+ create_redirect(path_was) if path_changed?
+ end
end
diff --git a/app/models/snippet.rb b/app/models/snippet.rb
index d8860718cb5..abfbefdf9a0 100644
--- a/app/models/snippet.rb
+++ b/app/models/snippet.rb
@@ -12,6 +12,11 @@ class Snippet < ActiveRecord::Base
cache_markdown_field :title, pipeline: :single_line
cache_markdown_field :content
+ # Aliases to make application_helper#edited_time_ago_with_tooltip helper work properly with snippets.
+ # See https://gitlab.com/gitlab-org/gitlab-ce/merge_requests/10392/diffs#note_28719102
+ alias_attribute :last_edited_at, :updated_at
+ alias_attribute :last_edited_by, :updated_by
+
# If file_name changes, it invalidates content
alias_method :default_content_html_invalidator, :content_html_invalidated?
def content_html_invalidated?
diff --git a/app/models/system_note_metadata.rb b/app/models/system_note_metadata.rb
index 1e6fc837a75..b44f4fe000c 100644
--- a/app/models/system_note_metadata.rb
+++ b/app/models/system_note_metadata.rb
@@ -1,6 +1,6 @@
class SystemNoteMetadata < ActiveRecord::Base
ICON_TYPES = %w[
- commit merge confidential visible label assignee cross_reference
+ commit description merge confidential visible label assignee cross_reference
title time_tracking branch milestone discussion task moved opened closed merged
].freeze
diff --git a/app/models/user.rb b/app/models/user.rb
index 43c5fdc038d..accaa91b805 100644
--- a/app/models/user.rb
+++ b/app/models/user.rb
@@ -100,6 +100,10 @@ class User < ActiveRecord::Base
has_many :award_emoji, dependent: :destroy
has_many :triggers, dependent: :destroy, class_name: 'Ci::Trigger', foreign_key: :owner_id
+ has_many :issue_assignees
+ has_many :assigned_issues, class_name: "Issue", through: :issue_assignees, source: :issue
+ has_many :assigned_merge_requests, dependent: :nullify, foreign_key: :assignee_id, class_name: "MergeRequest"
+
# Issues that a user owns are expected to be moved to the "ghost" user before
# the user is destroyed. If the user owns any issues during deletion, this
# should be treated as an exceptional condition.
@@ -333,6 +337,11 @@ class User < ActiveRecord::Base
find_by(id: Key.unscoped.select(:user_id).where(id: key_id))
end
+ def find_by_full_path(path, follow_redirects: false)
+ namespace = Namespace.find_by_full_path(path, follow_redirects: follow_redirects)
+ namespace&.owner
+ end
+
def reference_prefix
'@'
end
@@ -355,6 +364,10 @@ class User < ActiveRecord::Base
end
end
+ def full_path
+ username
+ end
+
def self.internal_attributes
[:ghost]
end
diff --git a/app/policies/base_policy.rb b/app/policies/base_policy.rb
index 8890409d056..623424c63e0 100644
--- a/app/policies/base_policy.rb
+++ b/app/policies/base_policy.rb
@@ -97,6 +97,10 @@ class BasePolicy
rules
end
+ def rules
+ raise NotImplementedError
+ end
+
def delegate!(new_subject)
@rule_set.merge(Ability.allowed(@user, new_subject))
end
diff --git a/app/policies/ci/build_policy.rb b/app/policies/ci/build_policy.rb
index 8b25332b73c..d4af4490608 100644
--- a/app/policies/ci/build_policy.rb
+++ b/app/policies/ci/build_policy.rb
@@ -1,5 +1,7 @@
module Ci
class BuildPolicy < CommitStatusPolicy
+ alias_method :build, :subject
+
def rules
super
@@ -8,6 +10,20 @@ module Ci
%w[read create update admin].each do |rule|
cannot! :"#{rule}_commit_status" unless can? :"#{rule}_build"
end
+
+ if can?(:update_build) && protected_action?
+ cannot! :update_build
+ end
+ end
+
+ private
+
+ def protected_action?
+ return false unless build.action?
+
+ !::Gitlab::UserAccess
+ .new(user, project: build.project)
+ .can_push_to_branch?(build.ref)
end
end
end
diff --git a/app/policies/ci/pipeline_policy.rb b/app/policies/ci/pipeline_policy.rb
index 3d2eef1c50c..10aa2d3e72a 100644
--- a/app/policies/ci/pipeline_policy.rb
+++ b/app/policies/ci/pipeline_policy.rb
@@ -1,4 +1,7 @@
module Ci
- class PipelinePolicy < BuildPolicy
+ class PipelinePolicy < BasePolicy
+ def rules
+ delegate! @subject.project
+ end
end
end
diff --git a/app/policies/environment_policy.rb b/app/policies/environment_policy.rb
index f4219569161..2fa15e64562 100644
--- a/app/policies/environment_policy.rb
+++ b/app/policies/environment_policy.rb
@@ -1,5 +1,17 @@
class EnvironmentPolicy < BasePolicy
+ alias_method :environment, :subject
+
def rules
- delegate! @subject.project
+ delegate! environment.project
+
+ if can?(:create_deployment) && environment.stop_action?
+ can! :stop_environment if can_play_stop_action?
+ end
+ end
+
+ private
+
+ def can_play_stop_action?
+ Ability.allowed?(user, :update_build, environment.stop_action)
end
end
diff --git a/app/serializers/build_action_entity.rb b/app/serializers/build_action_entity.rb
index 184b4b7a681..75dda1af709 100644
--- a/app/serializers/build_action_entity.rb
+++ b/app/serializers/build_action_entity.rb
@@ -13,4 +13,12 @@ class BuildActionEntity < Grape::Entity
end
expose :playable?, as: :playable
+
+ private
+
+ alias_method :build, :object
+
+ def playable?
+ build.playable? && can?(request.user, :update_build, build)
+ end
end
diff --git a/app/serializers/build_entity.rb b/app/serializers/build_entity.rb
index b804d6d0e8a..1380b347d8e 100644
--- a/app/serializers/build_entity.rb
+++ b/app/serializers/build_entity.rb
@@ -12,7 +12,7 @@ class BuildEntity < Grape::Entity
path_to(:retry_namespace_project_build, build)
end
- expose :play_path, if: ->(build, _) { build.playable? } do |build|
+ expose :play_path, if: -> (*) { playable? } do |build|
path_to(:play_namespace_project_build, build)
end
@@ -25,11 +25,15 @@ class BuildEntity < Grape::Entity
alias_method :build, :object
- def path_to(route, build)
- send("#{route}_path", build.project.namespace, build.project, build)
+ def playable?
+ build.playable? && can?(request.user, :update_build, build)
end
def detailed_status
build.detailed_status(request.user)
end
+
+ def path_to(route, build)
+ send("#{route}_path", build.project.namespace, build.project, build)
+ end
end
diff --git a/app/serializers/issuable_entity.rb b/app/serializers/issuable_entity.rb
index 29aecb50849..65b204d4dd2 100644
--- a/app/serializers/issuable_entity.rb
+++ b/app/serializers/issuable_entity.rb
@@ -1,7 +1,6 @@
class IssuableEntity < Grape::Entity
expose :id
expose :iid
- expose :assignee_id
expose :author_id
expose :description
expose :lock_version
diff --git a/app/serializers/issue_entity.rb b/app/serializers/issue_entity.rb
index 6429159ebe1..bc4f68710b2 100644
--- a/app/serializers/issue_entity.rb
+++ b/app/serializers/issue_entity.rb
@@ -1,6 +1,7 @@
class IssueEntity < IssuableEntity
expose :branch_name
expose :confidential
+ expose :assignees, using: API::Entities::UserBasic
expose :due_date
expose :moved_to_id
expose :project_id
diff --git a/app/serializers/job_group_entity.rb b/app/serializers/job_group_entity.rb
new file mode 100644
index 00000000000..a4d3737429c
--- /dev/null
+++ b/app/serializers/job_group_entity.rb
@@ -0,0 +1,16 @@
+class JobGroupEntity < Grape::Entity
+ include RequestAwareEntity
+
+ expose :name
+ expose :size
+ expose :detailed_status, as: :status, with: StatusEntity
+ expose :jobs, with: BuildEntity
+
+ private
+
+ alias_method :group, :object
+
+ def detailed_status
+ group.detailed_status(request.user)
+ end
+end
diff --git a/app/serializers/label_entity.rb b/app/serializers/label_entity.rb
index 304fd9de08f..ad565654342 100644
--- a/app/serializers/label_entity.rb
+++ b/app/serializers/label_entity.rb
@@ -6,6 +6,7 @@ class LabelEntity < Grape::Entity
expose :group_id
expose :project_id
expose :template
+ expose :text_color
expose :created_at
expose :updated_at
end
diff --git a/app/serializers/label_serializer.rb b/app/serializers/label_serializer.rb
new file mode 100644
index 00000000000..ad6ba8c46c9
--- /dev/null
+++ b/app/serializers/label_serializer.rb
@@ -0,0 +1,7 @@
+class LabelSerializer < BaseSerializer
+ entity LabelEntity
+
+ def represent_appearance(resource)
+ represent(resource, { only: [:id, :title, :color, :text_color] })
+ end
+end
diff --git a/app/serializers/merge_request_entity.rb b/app/serializers/merge_request_entity.rb
index 5f80ab397a9..453ba52b892 100644
--- a/app/serializers/merge_request_entity.rb
+++ b/app/serializers/merge_request_entity.rb
@@ -1,4 +1,5 @@
class MergeRequestEntity < IssuableEntity
+ expose :assignee_id
expose :in_progress_merge_commit_sha
expose :locked_at
expose :merge_commit_sha
diff --git a/app/serializers/pipeline_entity.rb b/app/serializers/pipeline_entity.rb
index ad8b4d43e8f..7eb7aac72eb 100644
--- a/app/serializers/pipeline_entity.rb
+++ b/app/serializers/pipeline_entity.rb
@@ -48,15 +48,15 @@ class PipelineEntity < Grape::Entity
end
expose :commit, using: CommitEntity
- expose :yaml_errors, if: ->(pipeline, _) { pipeline.has_yaml_errors? }
+ expose :yaml_errors, if: -> (pipeline, _) { pipeline.has_yaml_errors? }
- expose :retry_path, if: proc { can_retry? } do |pipeline|
+ expose :retry_path, if: -> (*) { can_retry? } do |pipeline|
retry_namespace_project_pipeline_path(pipeline.project.namespace,
pipeline.project,
pipeline.id)
end
- expose :cancel_path, if: proc { can_cancel? } do |pipeline|
+ expose :cancel_path, if: -> (*) { can_cancel? } do |pipeline|
cancel_namespace_project_pipeline_path(pipeline.project.namespace,
pipeline.project,
pipeline.id)
diff --git a/app/serializers/stage_entity.rb b/app/serializers/stage_entity.rb
index 7a047bdc712..97ced8730ed 100644
--- a/app/serializers/stage_entity.rb
+++ b/app/serializers/stage_entity.rb
@@ -7,9 +7,11 @@ class StageEntity < Grape::Entity
"#{stage.name}: #{detailed_status.label}"
end
- expose :detailed_status,
- as: :status,
- with: StatusEntity
+ expose :groups,
+ if: -> (_, opts) { opts[:grouped] },
+ with: JobGroupEntity
+
+ expose :detailed_status, as: :status, with: StatusEntity
expose :path do |stage|
namespace_project_pipeline_path(
diff --git a/app/serializers/status_entity.rb b/app/serializers/status_entity.rb
index 188c3747f18..3e40ecf1c1c 100644
--- a/app/serializers/status_entity.rb
+++ b/app/serializers/status_entity.rb
@@ -12,4 +12,11 @@ class StatusEntity < Grape::Entity
ActionController::Base.helpers.image_path(File.join(dir, "#{status.favicon}.ico"))
end
+
+ expose :action, if: -> (status, _) { status.has_action? } do
+ expose :action_icon, as: :icon
+ expose :action_title, as: :title
+ expose :action_path, as: :path
+ expose :action_method, as: :method
+ end
end
diff --git a/app/services/ci/play_build_service.rb b/app/services/ci/play_build_service.rb
new file mode 100644
index 00000000000..e24f48c2d16
--- /dev/null
+++ b/app/services/ci/play_build_service.rb
@@ -0,0 +1,17 @@
+module Ci
+ class PlayBuildService < ::BaseService
+ def execute(build)
+ unless can?(current_user, :update_build, build)
+ raise Gitlab::Access::AccessDeniedError
+ end
+
+ # Try to enqueue the build, otherwise create a duplicate.
+ #
+ if build.enqueue
+ build.tap { |action| action.update(user: current_user) }
+ else
+ Ci::Build.retry(build, current_user)
+ end
+ end
+ end
+end
diff --git a/app/services/ci/retry_pipeline_service.rb b/app/services/ci/retry_pipeline_service.rb
index ecc6173a96a..5b207157345 100644
--- a/app/services/ci/retry_pipeline_service.rb
+++ b/app/services/ci/retry_pipeline_service.rb
@@ -8,6 +8,8 @@ module Ci
end
pipeline.retryable_builds.find_each do |build|
+ next unless can?(current_user, :update_build, build)
+
Ci::RetryBuildService.new(project, current_user)
.reprocess(build)
end
diff --git a/app/services/ci/stop_environments_service.rb b/app/services/ci/stop_environments_service.rb
index 42c72aba7dd..43c9a065fcf 100644
--- a/app/services/ci/stop_environments_service.rb
+++ b/app/services/ci/stop_environments_service.rb
@@ -5,10 +5,11 @@ module Ci
def execute(branch_name)
@ref = branch_name
- return unless has_ref?
+ return unless @ref.present?
environments.each do |environment|
- next unless can?(current_user, :create_deployment, project)
+ next unless environment.stop_action?
+ next unless can?(current_user, :stop_environment, environment)
environment.stop_with_action!(current_user)
end
@@ -16,13 +17,10 @@ module Ci
private
- def has_ref?
- @ref.present?
- end
-
def environments
- @environments ||=
- EnvironmentsFinder.new(project, current_user, ref: @ref, recently_updated: true).execute
+ @environments ||= EnvironmentsFinder
+ .new(project, current_user, ref: @ref, recently_updated: true)
+ .execute
end
end
end
diff --git a/app/services/issuable/bulk_update_service.rb b/app/services/issuable/bulk_update_service.rb
index 60891cbb255..40ff9b8b867 100644
--- a/app/services/issuable/bulk_update_service.rb
+++ b/app/services/issuable/bulk_update_service.rb
@@ -7,10 +7,14 @@ module Issuable
ids = params.delete(:issuable_ids).split(",")
items = model_class.where(id: ids)
- %i(state_event milestone_id assignee_id add_label_ids remove_label_ids subscription_event).each do |key|
+ %i(state_event milestone_id assignee_id assignee_ids add_label_ids remove_label_ids subscription_event).each do |key|
params.delete(key) unless params[key].present?
end
+ if params[:assignee_ids] == [IssuableFinder::NONE.to_s]
+ params[:assignee_ids] = []
+ end
+
items.each do |issuable|
next unless can?(current_user, :"update_#{type}", issuable)
diff --git a/app/services/issuable_base_service.rb b/app/services/issuable_base_service.rb
index b071a398481..c1e532b504a 100644
--- a/app/services/issuable_base_service.rb
+++ b/app/services/issuable_base_service.rb
@@ -1,11 +1,6 @@
class IssuableBaseService < BaseService
private
- def create_assignee_note(issuable)
- SystemNoteService.change_assignee(
- issuable, issuable.project, current_user, issuable.assignee)
- end
-
def create_milestone_note(issuable)
SystemNoteService.change_milestone(
issuable, issuable.project, current_user, issuable.milestone)
@@ -24,6 +19,10 @@ class IssuableBaseService < BaseService
issuable, issuable.project, current_user, old_title)
end
+ def create_description_change_note(issuable)
+ SystemNoteService.change_description(issuable, issuable.project, current_user)
+ end
+
def create_branch_change_note(issuable, branch_type, old_branch, new_branch)
SystemNoteService.change_branch(
issuable, issuable.project, current_user, branch_type,
@@ -53,6 +52,7 @@ class IssuableBaseService < BaseService
params.delete(:add_label_ids)
params.delete(:remove_label_ids)
params.delete(:label_ids)
+ params.delete(:assignee_ids)
params.delete(:assignee_id)
params.delete(:due_date)
end
@@ -77,7 +77,7 @@ class IssuableBaseService < BaseService
def assignee_can_read?(issuable, assignee_id)
new_assignee = User.find_by_id(assignee_id)
- return false unless new_assignee.present?
+ return false unless new_assignee
ability_name = :"read_#{issuable.to_ability_name}"
resource = issuable.persisted? ? issuable : project
@@ -207,6 +207,7 @@ class IssuableBaseService < BaseService
filter_params(issuable)
old_labels = issuable.labels.to_a
old_mentioned_users = issuable.mentioned_users.to_a
+ old_assignees = issuable.assignees.to_a
label_ids = process_label_ids(params, existing_label_ids: issuable.label_ids)
params[:label_ids] = label_ids if labels_changing?(issuable.label_ids, label_ids)
@@ -214,6 +215,10 @@ class IssuableBaseService < BaseService
if issuable.changed? || params.present?
issuable.assign_attributes(params.merge(updated_by: current_user))
+ if has_title_or_description_changed?(issuable)
+ issuable.assign_attributes(last_edited_at: Time.now, last_edited_by: current_user)
+ end
+
before_update(issuable)
if issuable.with_transaction_returning_status { issuable.save }
@@ -222,7 +227,13 @@ class IssuableBaseService < BaseService
handle_common_system_notes(issuable, old_labels: old_labels)
end
- handle_changes(issuable, old_labels: old_labels, old_mentioned_users: old_mentioned_users)
+ handle_changes(
+ issuable,
+ old_labels: old_labels,
+ old_mentioned_users: old_mentioned_users,
+ old_assignees: old_assignees
+ )
+
after_update(issuable)
issuable.create_new_cross_references!(current_user)
execute_hooks(issuable, 'update')
@@ -236,6 +247,10 @@ class IssuableBaseService < BaseService
old_label_ids.sort != new_label_ids.sort
end
+ def has_title_or_description_changed?(issuable)
+ issuable.title_changed? || issuable.description_changed?
+ end
+
def change_state(issuable)
case params.delete(:state_event)
when 'reopen'
@@ -272,7 +287,7 @@ class IssuableBaseService < BaseService
end
end
- def has_changes?(issuable, old_labels: [])
+ def has_changes?(issuable, old_labels: [], old_assignees: [])
valid_attrs = [:title, :description, :assignee_id, :milestone_id, :target_branch]
attrs_changed = valid_attrs.any? do |attr|
@@ -281,7 +296,9 @@ class IssuableBaseService < BaseService
labels_changed = issuable.labels != old_labels
- attrs_changed || labels_changed
+ assignees_changed = issuable.assignees != old_assignees
+
+ attrs_changed || labels_changed || assignees_changed
end
def handle_common_system_notes(issuable, old_labels: [])
@@ -289,6 +306,10 @@ class IssuableBaseService < BaseService
create_title_change_note(issuable, issuable.previous_changes['title'].first)
end
+ if issuable.previous_changes.include?('description')
+ create_description_change_note(issuable)
+ end
+
if issuable.previous_changes.include?('description') && issuable.tasks?
create_task_status_note(issuable)
end
diff --git a/app/services/issues/base_service.rb b/app/services/issues/base_service.rb
index ee1b40db718..34199eb5d13 100644
--- a/app/services/issues/base_service.rb
+++ b/app/services/issues/base_service.rb
@@ -9,11 +9,33 @@ module Issues
private
+ def create_assignee_note(issue, old_assignees)
+ SystemNoteService.change_issue_assignees(
+ issue, issue.project, current_user, old_assignees)
+ end
+
def execute_hooks(issue, action = 'open')
issue_data = hook_data(issue, action)
hooks_scope = issue.confidential? ? :confidential_issue_hooks : :issue_hooks
issue.project.execute_hooks(issue_data, hooks_scope)
issue.project.execute_services(issue_data, hooks_scope)
end
+
+ def filter_assignee(issuable)
+ return if params[:assignee_ids].blank?
+
+ # The number of assignees is limited by one for GitLab CE
+ params[:assignee_ids] = params[:assignee_ids][0, 1]
+
+ assignee_ids = params[:assignee_ids].select { |assignee_id| assignee_can_read?(issuable, assignee_id) }
+
+ if params[:assignee_ids].map(&:to_s) == [IssuableFinder::NONE]
+ params[:assignee_ids] = []
+ elsif assignee_ids.any?
+ params[:assignee_ids] = assignee_ids
+ else
+ params.delete(:assignee_ids)
+ end
+ end
end
end
diff --git a/app/services/issues/update_service.rb b/app/services/issues/update_service.rb
index b7fe5cb168b..cd9f9a4a16e 100644
--- a/app/services/issues/update_service.rb
+++ b/app/services/issues/update_service.rb
@@ -12,8 +12,12 @@ module Issues
spam_check(issue, current_user)
end
- def handle_changes(issue, old_labels: [], old_mentioned_users: [])
- if has_changes?(issue, old_labels: old_labels)
+ def handle_changes(issue, options)
+ old_labels = options[:old_labels] || []
+ old_mentioned_users = options[:old_mentioned_users] || []
+ old_assignees = options[:old_assignees] || []
+
+ if has_changes?(issue, old_labels: old_labels, old_assignees: old_assignees)
todo_service.mark_pending_todos_as_done(issue, current_user)
end
@@ -26,9 +30,9 @@ module Issues
create_milestone_note(issue)
end
- if issue.previous_changes.include?('assignee_id')
- create_assignee_note(issue)
- notification_service.reassigned_issue(issue, current_user)
+ if issue.assignees != old_assignees
+ create_assignee_note(issue, old_assignees)
+ notification_service.reassigned_issue(issue, current_user, old_assignees)
todo_service.reassigned_issue(issue, current_user)
end
diff --git a/app/services/members/authorized_destroy_service.rb b/app/services/members/authorized_destroy_service.rb
index 1711be7211c..a85b9465c84 100644
--- a/app/services/members/authorized_destroy_service.rb
+++ b/app/services/members/authorized_destroy_service.rb
@@ -26,15 +26,22 @@ module Members
def unassign_issues_and_merge_requests(member)
if member.is_a?(GroupMember)
- IssuesFinder.new(user, group_id: member.source_id, assignee_id: member.user_id).
- execute.
- update_all(assignee_id: nil)
+ issue_ids = IssuesFinder.new(user, group_id: member.source_id, assignee_id: member.user_id).
+ execute.pluck(:id)
+
+ IssueAssignee.destroy_all(issue_id: issue_ids, user_id: member.user_id)
+
MergeRequestsFinder.new(user, group_id: member.source_id, assignee_id: member.user_id).
execute.
update_all(assignee_id: nil)
else
project = member.source
- project.issues.opened.assigned_to(member.user).update_all(assignee_id: nil)
+
+ IssueAssignee.destroy_all(
+ user_id: member.user_id,
+ issue_id: project.issues.opened.assigned_to(member.user).select(:id)
+ )
+
project.merge_requests.opened.assigned_to(member.user).update_all(assignee_id: nil)
member.user.update_cache_counts
end
diff --git a/app/services/merge_requests/assign_issues_service.rb b/app/services/merge_requests/assign_issues_service.rb
index 066efa1acc3..8c6c4841020 100644
--- a/app/services/merge_requests/assign_issues_service.rb
+++ b/app/services/merge_requests/assign_issues_service.rb
@@ -4,7 +4,7 @@ module MergeRequests
@assignable_issues ||= begin
if current_user == merge_request.author
closes_issues.select do |issue|
- !issue.is_a?(ExternalIssue) && !issue.assignee_id? && can?(current_user, :admin_issue, issue)
+ !issue.is_a?(ExternalIssue) && !issue.assignees.present? && can?(current_user, :admin_issue, issue)
end
else
[]
@@ -14,7 +14,7 @@ module MergeRequests
def execute
assignable_issues.each do |issue|
- Issues::UpdateService.new(issue.project, current_user, assignee_id: current_user.id).execute(issue)
+ Issues::UpdateService.new(issue.project, current_user, assignee_ids: [current_user.id]).execute(issue)
end
{
diff --git a/app/services/merge_requests/base_service.rb b/app/services/merge_requests/base_service.rb
index 582d5c47b66..3542a41ac83 100644
--- a/app/services/merge_requests/base_service.rb
+++ b/app/services/merge_requests/base_service.rb
@@ -38,6 +38,11 @@ module MergeRequests
private
+ def create_assignee_note(merge_request)
+ SystemNoteService.change_assignee(
+ merge_request, merge_request.project, current_user, merge_request.assignee)
+ end
+
# Returns all origin and fork merge requests from `@project` satisfying passed arguments.
def merge_requests_for(source_branch, mr_states: [:opened, :reopened])
MergeRequest
diff --git a/app/services/merge_requests/update_service.rb b/app/services/merge_requests/update_service.rb
index ab7fcf3b6e2..5c843a258fb 100644
--- a/app/services/merge_requests/update_service.rb
+++ b/app/services/merge_requests/update_service.rb
@@ -21,7 +21,10 @@ module MergeRequests
update(merge_request)
end
- def handle_changes(merge_request, old_labels: [], old_mentioned_users: [])
+ def handle_changes(merge_request, options)
+ old_labels = options[:old_labels] || []
+ old_mentioned_users = options[:old_mentioned_users] || []
+
if has_changes?(merge_request, old_labels: old_labels)
todo_service.mark_pending_todos_as_done(merge_request, current_user)
end
diff --git a/app/services/notification_recipient_service.rb b/app/services/notification_recipient_service.rb
index 8bb995158de..988bd0a7cdb 100644
--- a/app/services/notification_recipient_service.rb
+++ b/app/services/notification_recipient_service.rb
@@ -19,9 +19,14 @@ class NotificationRecipientService
# Re-assign is considered as a mention of the new assignee so we add the
# new assignee to the list of recipients after we rejected users with
# the "on mention" notification level
- if [:reassign_merge_request, :reassign_issue].include?(custom_action)
+ case custom_action
+ when :reassign_merge_request
recipients << previous_assignee if previous_assignee
recipients << target.assignee
+ when :reassign_issue
+ previous_assignees = Array(previous_assignee)
+ recipients.concat(previous_assignees)
+ recipients.concat(target.assignees)
end
recipients = reject_muted_users(recipients)
diff --git a/app/services/notification_service.rb b/app/services/notification_service.rb
index 6b186263bd1..c65c66d7150 100644
--- a/app/services/notification_service.rb
+++ b/app/services/notification_service.rb
@@ -66,8 +66,25 @@ class NotificationService
# * issue new assignee if their notification level is not Disabled
# * users with custom level checked with "reassign issue"
#
- def reassigned_issue(issue, current_user)
- reassign_resource_email(issue, issue.project, current_user, :reassigned_issue_email)
+ def reassigned_issue(issue, current_user, previous_assignees = [])
+ recipients = NotificationRecipientService.new(issue.project).build_recipients(
+ issue,
+ current_user,
+ action: "reassign",
+ previous_assignee: previous_assignees
+ )
+
+ previous_assignee_ids = previous_assignees.map(&:id)
+
+ recipients.each do |recipient|
+ mailer.send(
+ :reassigned_issue_email,
+ recipient.id,
+ issue.id,
+ previous_assignee_ids,
+ current_user.id
+ ).deliver_later
+ end
end
# When we add labels to an issue we should send an email to:
@@ -367,10 +384,10 @@ class NotificationService
end
def previous_record(object, attribute)
- if object && attribute
- if object.previous_changes.include?(attribute)
- object.previous_changes[attribute].first
- end
+ return unless object && attribute
+
+ if object.previous_changes.include?(attribute)
+ object.previous_changes[attribute].first
end
end
end
diff --git a/app/services/projects/propagate_service_template.rb b/app/services/projects/propagate_service_template.rb
new file mode 100644
index 00000000000..a8ef2108492
--- /dev/null
+++ b/app/services/projects/propagate_service_template.rb
@@ -0,0 +1,103 @@
+module Projects
+ class PropagateServiceTemplate
+ BATCH_SIZE = 100
+
+ def self.propagate(*args)
+ new(*args).propagate
+ end
+
+ def initialize(template)
+ @template = template
+ end
+
+ def propagate
+ return unless @template.active?
+
+ Rails.logger.info("Propagating services for template #{@template.id}")
+
+ propagate_projects_with_template
+ end
+
+ private
+
+ def propagate_projects_with_template
+ loop do
+ batch = project_ids_batch
+
+ bulk_create_from_template(batch) unless batch.empty?
+
+ break if batch.size < BATCH_SIZE
+ end
+ end
+
+ def bulk_create_from_template(batch)
+ service_list = batch.map do |project_id|
+ service_hash.values << project_id
+ end
+
+ Project.transaction do
+ bulk_insert_services(service_hash.keys << 'project_id', service_list)
+ run_callbacks(batch)
+ end
+ end
+
+ def project_ids_batch
+ Project.connection.select_values(
+ <<-SQL
+ SELECT id
+ FROM projects
+ WHERE NOT EXISTS (
+ SELECT true
+ FROM services
+ WHERE services.project_id = projects.id
+ AND services.type = '#{@template.type}'
+ )
+ AND projects.pending_delete = false
+ AND projects.archived = false
+ LIMIT #{BATCH_SIZE}
+ SQL
+ )
+ end
+
+ def bulk_insert_services(columns, values_array)
+ ActiveRecord::Base.connection.execute(
+ <<-SQL.strip_heredoc
+ INSERT INTO services (#{columns.join(', ')})
+ VALUES #{values_array.map { |tuple| "(#{tuple.join(', ')})" }.join(', ')}
+ SQL
+ )
+ end
+
+ def service_hash
+ @service_hash ||=
+ begin
+ template_hash = @template.as_json(methods: :type).except('id', 'template', 'project_id')
+
+ template_hash.each_with_object({}) do |(key, value), service_hash|
+ value = value.is_a?(Hash) ? value.to_json : value
+
+ service_hash[ActiveRecord::Base.connection.quote_column_name(key)] =
+ ActiveRecord::Base.sanitize(value)
+ end
+ end
+ end
+
+ def run_callbacks(batch)
+ if active_external_issue_tracker?
+ Project.where(id: batch).update_all(has_external_issue_tracker: true)
+ end
+
+ if active_external_wiki?
+ Project.where(id: batch).update_all(has_external_wiki: true)
+ end
+ end
+
+ def active_external_issue_tracker?
+ @template.issue_tracker? && !@template.default
+ end
+
+ def active_external_wiki?
+ @template.type == 'ExternalWikiService'
+ end
+ end
+end
diff --git a/app/services/slash_commands/interpret_service.rb b/app/services/slash_commands/interpret_service.rb
index f1bbc7032d5..a7e13648b54 100644
--- a/app/services/slash_commands/interpret_service.rb
+++ b/app/services/slash_commands/interpret_service.rb
@@ -91,32 +91,47 @@ module SlashCommands
end
desc 'Assign'
- explanation do |user|
- "Assigns #{user.to_reference}." if user
+ explanation do |users|
+ "Assigns #{users.map(&:to_reference).to_sentence}." if users.any?
end
params '@user'
condition do
current_user.can?(:"admin_#{issuable.to_ability_name}", project)
end
parse_params do |assignee_param|
- extract_references(assignee_param, :user).first ||
- User.find_by(username: assignee_param)
+ users = extract_references(assignee_param, :user)
+
+ if users.empty?
+ users = User.where(username: assignee_param.split(' ').map(&:strip))
+ end
+
+ users
end
- command :assign do |user|
- @updates[:assignee_id] = user.id if user
+ command :assign do |users|
+ next if users.empty?
+
+ if issuable.is_a?(Issue)
+ @updates[:assignee_ids] = users.map(&:id)
+ else
+ @updates[:assignee_id] = users.last.id
+ end
end
desc 'Remove assignee'
explanation do
- "Removes assignee #{issuable.assignee.to_reference}."
+ "Removes assignee #{issuable.assignees.first.to_reference}."
end
condition do
issuable.persisted? &&
- issuable.assignee_id? &&
+ issuable.assignees.any? &&
current_user.can?(:"admin_#{issuable.to_ability_name}", project)
end
command :unassign do
- @updates[:assignee_id] = nil
+ if issuable.is_a?(Issue)
+ @updates[:assignee_ids] = []
+ else
+ @updates[:assignee_id] = nil
+ end
end
desc 'Set milestone'
diff --git a/app/services/system_note_service.rb b/app/services/system_note_service.rb
index c9e25c7aaa2..174e7c6e95b 100644
--- a/app/services/system_note_service.rb
+++ b/app/services/system_note_service.rb
@@ -49,6 +49,44 @@ module SystemNoteService
create_note(NoteSummary.new(noteable, project, author, body, action: 'assignee'))
end
+ # Called when the assignees of an Issue is changed or removed
+ #
+ # issue - Issue object
+ # project - Project owning noteable
+ # author - User performing the change
+ # assignees - Users being assigned, or nil
+ #
+ # Example Note text:
+ #
+ # "removed all assignees"
+ #
+ # "assigned to @user1 additionally to @user2"
+ #
+ # "assigned to @user1, @user2 and @user3 and unassigned from @user4 and @user5"
+ #
+ # "assigned to @user1 and @user2"
+ #
+ # Returns the created Note object
+ def change_issue_assignees(issue, project, author, old_assignees)
+ body =
+ if issue.assignees.any? && old_assignees.any?
+ unassigned_users = old_assignees - issue.assignees
+ added_users = issue.assignees.to_a - old_assignees
+
+ text_parts = []
+ text_parts << "assigned to #{added_users.map(&:to_reference).to_sentence}" if added_users.any?
+ text_parts << "unassigned #{unassigned_users.map(&:to_reference).to_sentence}" if unassigned_users.any?
+
+ text_parts.join(' and ')
+ elsif old_assignees.any?
+ "removed all assignees"
+ elsif issue.assignees.any?
+ "assigned to #{issue.assignees.map(&:to_reference).to_sentence}"
+ end
+
+ create_note(NoteSummary.new(issue, project, author, body, action: 'assignee'))
+ end
+
# Called when one or more labels on a Noteable are added and/or removed
#
# noteable - Noteable object
@@ -261,6 +299,23 @@ module SystemNoteService
create_note(NoteSummary.new(noteable, project, author, body, action: 'title'))
end
+ # Called when the description of a Noteable is changed
+ #
+ # noteable - Noteable object that responds to `description`
+ # project - Project owning noteable
+ # author - User performing the change
+ #
+ # Example Note text:
+ #
+ # "changed the description"
+ #
+ # Returns the created Note object
+ def change_description(noteable, project, author)
+ body = 'changed the description'
+
+ create_note(NoteSummary.new(noteable, project, author, body, action: 'description'))
+ end
+
# Called when the confidentiality changes
#
# issue - Issue object
diff --git a/app/services/todo_service.rb b/app/services/todo_service.rb
index 8ae61694b50..322c6286365 100644
--- a/app/services/todo_service.rb
+++ b/app/services/todo_service.rb
@@ -251,9 +251,9 @@ class TodoService
end
def create_assignment_todo(issuable, author)
- if issuable.assignee
+ if issuable.assignees.any?
attributes = attributes_for_todo(issuable.project, issuable, author, Todo::ASSIGNED)
- create_todos(issuable.assignee, attributes)
+ create_todos(issuable.assignees, attributes)
end
end
diff --git a/app/views/admin/application_settings/_form.html.haml b/app/views/admin/application_settings/_form.html.haml
index 0dc1103eece..4b6628169ef 100644
--- a/app/views/admin/application_settings/_form.html.haml
+++ b/app/views/admin/application_settings/_form.html.haml
@@ -394,8 +394,6 @@
%fieldset
%legend Error Reporting and Logging
- %p
- These settings require a restart to take effect.
.form-group
.col-sm-offset-2.col-sm-10
.checkbox
@@ -403,6 +401,7 @@
= f.check_box :sentry_enabled
Enable Sentry
.help-block
+ %p This setting requires a restart to take effect.
Sentry is an error reporting and logging tool which is currently not shipped with GitLab, get it here:
%a{ href: 'https://getsentry.com', target: '_blank', rel: 'noopener noreferrer' } https://getsentry.com
@@ -411,6 +410,21 @@
.col-sm-10
= f.text_field :sentry_dsn, class: 'form-control'
+ .form-group
+ .col-sm-offset-2.col-sm-10
+ .checkbox
+ = f.label :clientside_sentry_enabled do
+ = f.check_box :clientside_sentry_enabled
+ Enable Clientside Sentry
+ .help-block
+ Sentry can also be used for reporting and logging clientside exceptions.
+ %a{ href: 'https://sentry.io/for/javascript/', target: '_blank', rel: 'noopener noreferrer' } https://sentry.io/for/javascript/
+
+ .form-group
+ = f.label :clientside_sentry_dsn, 'Clientside Sentry DSN', class: 'control-label col-sm-2'
+ .col-sm-10
+ = f.text_field :clientside_sentry_dsn, class: 'form-control'
+
%fieldset
%legend Repository Storage
.form-group
diff --git a/app/views/issues/_issue.atom.builder b/app/views/issues/_issue.atom.builder
index 23a88448055..2ed78bb3b65 100644
--- a/app/views/issues/_issue.atom.builder
+++ b/app/views/issues/_issue.atom.builder
@@ -23,10 +23,19 @@ xml.entry do
end
end
- if issue.assignee
+ if issue.assignees.any?
+ xml.assignees do
+ issue.assignees.each do |assignee|
+ xml.assignee do
+ xml.name assignee.name
+ xml.email assignee.public_email
+ end
+ end
+ end
+
xml.assignee do
- xml.name issue.assignee.name
- xml.email issue.assignee_public_email
+ xml.name issue.assignees.first.name
+ xml.email issue.assignees.first.public_email
end
end
end
diff --git a/app/views/layouts/_head.html.haml b/app/views/layouts/_head.html.haml
index 19473b6ab27..afcc2b6e4f3 100644
--- a/app/views/layouts/_head.html.haml
+++ b/app/views/layouts/_head.html.haml
@@ -28,9 +28,12 @@
= stylesheet_link_tag "application", media: "all"
= stylesheet_link_tag "print", media: "print"
+ = Gon::Base.render_data
+
= webpack_bundle_tag "runtime"
= webpack_bundle_tag "common"
= webpack_bundle_tag "main"
+ = webpack_bundle_tag "raven" if current_application_settings.clientside_sentry_enabled
- if content_for?(:page_specific_javascripts)
= yield :page_specific_javascripts
diff --git a/app/views/layouts/application.html.haml b/app/views/layouts/application.html.haml
index dc926a615c7..7e011ac3e75 100644
--- a/app/views/layouts/application.html.haml
+++ b/app/views/layouts/application.html.haml
@@ -2,8 +2,6 @@
%html{ lang: I18n.locale, class: "#{page_class}" }
= render "layouts/head"
%body{ class: @body_class, data: { page: body_data_page, project: "#{@project.path if @project}", group: "#{@group.path if @group}" } }
- = Gon::Base.render_data
-
= render "layouts/header/default", title: header_title
= render 'layouts/page', sidebar: sidebar, nav: nav
diff --git a/app/views/layouts/devise.html.haml b/app/views/layouts/devise.html.haml
index 3368a9beb29..52fb46eb8c9 100644
--- a/app/views/layouts/devise.html.haml
+++ b/app/views/layouts/devise.html.haml
@@ -3,7 +3,6 @@
= render "layouts/head"
%body.ui_charcoal.login-page.application.navless{ data: { page: body_data_page } }
.page-wrap
- = Gon::Base.render_data
= render "layouts/header/empty"
= render "layouts/broadcast"
.container.navless-container
diff --git a/app/views/layouts/devise_empty.html.haml b/app/views/layouts/devise_empty.html.haml
index 7466423a934..ed6731bde95 100644
--- a/app/views/layouts/devise_empty.html.haml
+++ b/app/views/layouts/devise_empty.html.haml
@@ -2,7 +2,6 @@
%html{ lang: "en" }
= render "layouts/head"
%body.ui_charcoal.login-page.application.navless
- = Gon::Base.render_data
= render "layouts/header/empty"
= render "layouts/broadcast"
.container.navless-container
diff --git a/app/views/notify/_reassigned_issuable_email.text.erb b/app/views/notify/_reassigned_issuable_email.text.erb
deleted file mode 100644
index daf20a226dd..00000000000
--- a/app/views/notify/_reassigned_issuable_email.text.erb
+++ /dev/null
@@ -1,6 +0,0 @@
-Reassigned <%= issuable.class.model_name.human.titleize %> <%= issuable.iid %>
-
-<%= url_for([issuable.project.namespace.becomes(Namespace), issuable.project, issuable, { only_path: false }]) %>
-
-Assignee changed <%= "from #{@previous_assignee.name}" if @previous_assignee -%>
- to <%= "#{issuable.assignee_id ? issuable.assignee_name : 'Unassigned'}" %>
diff --git a/app/views/notify/new_issue_email.html.haml b/app/views/notify/new_issue_email.html.haml
index c762578971a..eb5157ccac9 100644
--- a/app/views/notify/new_issue_email.html.haml
+++ b/app/views/notify/new_issue_email.html.haml
@@ -2,9 +2,9 @@
%p.details
#{link_to @issue.author_name, user_url(@issue.author)} created an issue:
-- if @issue.assignee_id.present?
+- if @issue.assignees.any?
%p
- Assignee: #{@issue.assignee_name}
+ Assignee: #{@issue.assignee_list}
- if @issue.description
%div
diff --git a/app/views/notify/new_issue_email.text.erb b/app/views/notify/new_issue_email.text.erb
index ca5c2f2688c..13f1ac08e94 100644
--- a/app/views/notify/new_issue_email.text.erb
+++ b/app/views/notify/new_issue_email.text.erb
@@ -2,6 +2,6 @@ New Issue was created.
Issue <%= @issue.iid %>: <%= url_for(namespace_project_issue_url(@issue.project.namespace, @issue.project, @issue)) %>
Author: <%= @issue.author_name %>
-Assignee: <%= @issue.assignee_name %>
+Assignee: <%= @issue.assignee_list %>
<%= @issue.description %>
diff --git a/app/views/notify/new_mention_in_issue_email.text.erb b/app/views/notify/new_mention_in_issue_email.text.erb
index 457e94b4800..f19ac3adfc7 100644
--- a/app/views/notify/new_mention_in_issue_email.text.erb
+++ b/app/views/notify/new_mention_in_issue_email.text.erb
@@ -2,6 +2,6 @@ You have been mentioned in an issue.
Issue <%= @issue.iid %>: <%= url_for(namespace_project_issue_url(@issue.project.namespace, @issue.project, @issue)) %>
Author: <%= @issue.author_name %>
-Assignee: <%= @issue.assignee_name %>
+Assignee: <%= @issue.assignee_list %>
<%= @issue.description %>
diff --git a/app/views/notify/reassigned_issue_email.html.haml b/app/views/notify/reassigned_issue_email.html.haml
index 498ba8b8365..ee2f40e1683 100644
--- a/app/views/notify/reassigned_issue_email.html.haml
+++ b/app/views/notify/reassigned_issue_email.html.haml
@@ -1 +1,10 @@
-= render 'reassigned_issuable_email', issuable: @issue
+%p
+ Assignee changed
+ - if @previous_assignees.any?
+ from
+ %strong= @previous_assignees.map(&:name).to_sentence
+ to
+ - if @issue.assignees.any?
+ %strong= @issue.assignee_list
+ - else
+ %strong Unassigned
diff --git a/app/views/notify/reassigned_issue_email.text.erb b/app/views/notify/reassigned_issue_email.text.erb
index 710253be984..6c357f1074a 100644
--- a/app/views/notify/reassigned_issue_email.text.erb
+++ b/app/views/notify/reassigned_issue_email.text.erb
@@ -1 +1,6 @@
-<%= render 'reassigned_issuable_email', issuable: @issue %>
+Reassigned Issue <%= @issue.iid %>
+
+<%= url_for([@issue.project.namespace.becomes(Namespace), @issue.project, @issue, { only_path: false }]) %>
+
+Assignee changed <%= "from #{@previous_assignees.map(&:name).to_sentence}" if @previous_assignees.any? -%>
+ to <%= "#{@issue.assignees.any? ? @issue.assignee_list : 'Unassigned'}" %>
diff --git a/app/views/notify/reassigned_merge_request_email.html.haml b/app/views/notify/reassigned_merge_request_email.html.haml
index 2a650130f59..841df872857 100644
--- a/app/views/notify/reassigned_merge_request_email.html.haml
+++ b/app/views/notify/reassigned_merge_request_email.html.haml
@@ -1 +1,9 @@
-= render 'reassigned_issuable_email', issuable: @merge_request
+Reassigned Merge Request #{ @merge_request.iid }
+
+= url_for([@merge_request.project.namespace.becomes(Namespace), @merge_request.project, @merge_request, { only_path: false }])
+
+Assignee changed
+- if @previous_assignee
+ from #{@previous_assignee.name}
+to
+= @merge_request.assignee_id ? @merge_request.assignee_name : 'Unassigned'
diff --git a/app/views/notify/reassigned_merge_request_email.text.erb b/app/views/notify/reassigned_merge_request_email.text.erb
index b5b4f1ff99a..998a40fefde 100644
--- a/app/views/notify/reassigned_merge_request_email.text.erb
+++ b/app/views/notify/reassigned_merge_request_email.text.erb
@@ -1 +1,6 @@
-<%= render 'reassigned_issuable_email', issuable: @merge_request %>
+Reassigned Merge Request <%= @merge_request.iid %>
+
+<%= url_for([@merge_request.project.namespace.becomes(Namespace), @merge_request.project, @merge_request, { only_path: false }]) %>
+
+Assignee changed <%= "from #{@previous_assignee.name}" if @previous_assignee -%>
+ to <%= "#{@merge_request.assignee_id ? @merge_request.assignee_name : 'Unassigned'}" %>
diff --git a/app/views/projects/blob/viewers/_balsamiq.html.haml b/app/views/projects/blob/viewers/_balsamiq.html.haml
new file mode 100644
index 00000000000..28670e7de97
--- /dev/null
+++ b/app/views/projects/blob/viewers/_balsamiq.html.haml
@@ -0,0 +1,4 @@
+- content_for :page_specific_javascripts do
+ = page_specific_javascript_bundle_tag('balsamiq_viewer')
+
+.file-content.balsamiq-viewer#js-balsamiq-viewer{ data: { endpoint: blob_raw_url } }
diff --git a/app/views/projects/boards/components/_board.html.haml b/app/views/projects/boards/components/_board.html.haml
index 5a4eaf92b16..bc5c727bf0d 100644
--- a/app/views/projects/boards/components/_board.html.haml
+++ b/app/views/projects/boards/components/_board.html.haml
@@ -13,8 +13,8 @@
%button.btn.btn-small.btn-default.pull-right.has-tooltip{ type: "button",
"@click" => "showNewIssueForm",
"v-if" => 'list.type !== "closed"',
- "aria-label" => "Add an issue",
- "title" => "Add an issue",
+ "aria-label" => "New issue",
+ "title" => "New issue",
data: { placement: "top", container: "body" } }
= icon("plus")
- if can?(current_user, :admin_list, @project)
diff --git a/app/views/projects/boards/components/sidebar/_assignee.html.haml b/app/views/projects/boards/components/sidebar/_assignee.html.haml
index 0f424334521..642da679f97 100644
--- a/app/views/projects/boards/components/sidebar/_assignee.html.haml
+++ b/app/views/projects/boards/components/sidebar/_assignee.html.haml
@@ -1,40 +1,28 @@
-.block.assignee
- .title.hide-collapsed
- Assignee
- - if can?(current_user, :admin_issue, @project)
- = icon("spinner spin", class: "block-loading")
- = link_to "Edit", "#", class: "edit-link pull-right"
- .value.hide-collapsed
- %span.assign-yourself.no-value{ "v-if" => "!issue.assignee" }
- No assignee
- - if can?(current_user, :admin_issue, @project)
- \-
- %a.js-assign-yourself{ href: "#" }
- assign yourself
- %a.author_link.bold{ ":href" => "'#{root_url}' + issue.assignee.username",
- "v-if" => "issue.assignee" }
- %img.avatar.avatar-inline.s32{ ":src" => "issue.assignee.avatar",
- width: "32", alt: "Avatar" }
- %span.author
- {{ issue.assignee.name }}
- %span.username
- = precede "@" do
- {{ issue.assignee.username }}
+.block.assignee{ ref: "assigneeBlock" }
+ %template{ "v-if" => "issue.assignees" }
+ %assignee-title{ ":number-of-assignees" => "issue.assignees.length",
+ ":loading" => "loadingAssignees",
+ ":editable" => can?(current_user, :admin_issue, @project) }
+ %assignees.value{ "root-path" => "#{root_url}",
+ ":users" => "issue.assignees",
+ ":editable" => can?(current_user, :admin_issue, @project),
+ "@assign-self" => "assignSelf" }
+
- if can?(current_user, :admin_issue, @project)
.selectbox.hide-collapsed
%input{ type: "hidden",
- name: "issue[assignee_id]",
- id: "issue_assignee_id",
- ":value" => "issue.assignee.id",
- "v-if" => "issue.assignee" }
+ name: "issue[assignee_ids][]",
+ ":value" => "assignee.id",
+ "v-if" => "issue.assignees",
+ "v-for" => "assignee in issue.assignees" }
.dropdown
- %button.dropdown-menu-toggle.js-user-search.js-author-search.js-issue-board-sidebar{ type: "button", data: { toggle: "dropdown", field_name: "issue[assignee_id]", first_user: (current_user.username if current_user), current_user: "true", project_id: @project.id, null_user: "true", null_user_default: "true" },
+ %button.dropdown-menu-toggle.js-user-search.js-author-search.js-multiselect.js-save-user-data.js-issue-board-sidebar{ type: "button", ref: "assigneeDropdown", data: { toggle: "dropdown", field_name: "issue[assignee_ids][]", first_user: (current_user.username if current_user), current_user: "true", project_id: @project.id, null_user: "true", multi_select: "true", 'max-select' => 1, dropdown: { header: 'Assignee' } },
":data-issuable-id" => "issue.id",
":data-selected" => "assigneeId",
":data-issue-update" => "'#{namespace_project_issues_path(@project.namespace, @project)}/' + issue.id + '.json'" }
Select assignee
= icon("chevron-down")
- .dropdown-menu.dropdown-menu-user.dropdown-menu-selectable.dropdown-menu-author
+ .dropdown-menu.dropdown-select.dropdown-menu-user.dropdown-menu-selectable.dropdown-menu-author
= dropdown_title("Assign to")
= dropdown_filter("Search users")
= dropdown_content
diff --git a/app/views/projects/ci/builds/_build.html.haml b/app/views/projects/ci/builds/_build.html.haml
index 2c3fd1fcd4d..c0019996176 100644
--- a/app/views/projects/ci/builds/_build.html.haml
+++ b/app/views/projects/ci/builds/_build.html.haml
@@ -102,7 +102,7 @@
= link_to cancel_namespace_project_build_path(job.project.namespace, job.project, job, return_to: request.original_url), method: :post, title: 'Cancel', class: 'btn btn-build' do
= icon('remove', class: 'cred')
- elsif allow_retry
- - if job.playable? && !admin
+ - if job.playable? && !admin && can?(current_user, :update_build, job)
= link_to play_namespace_project_build_path(job.project.namespace, job.project, job, return_to: request.original_url), method: :post, title: 'Play', class: 'btn btn-build' do
= custom_icon('icon_play')
- elsif job.retryable?
diff --git a/app/views/projects/environments/terminal.html.haml b/app/views/projects/environments/terminal.html.haml
index c8363087d6a..4c4aa0baff3 100644
--- a/app/views/projects/environments/terminal.html.haml
+++ b/app/views/projects/environments/terminal.html.haml
@@ -16,8 +16,9 @@
.col-sm-6
.nav-controls
- = link_to @environment.external_url, class: 'btn btn-default', target: '_blank', rel: 'noopener noreferrer nofollow' do
- = icon('external-link')
+ - if @environment.external_url.present?
+ = link_to @environment.external_url, class: 'btn btn-default', target: '_blank', rel: 'noopener noreferrer nofollow' do
+ = icon('external-link')
= render 'projects/deployments/actions', deployment: @environment.last_deployment
.terminal-container{ class: container_class }
diff --git a/app/views/projects/issues/_issue.html.haml b/app/views/projects/issues/_issue.html.haml
index 0e3902c066a..c184e0e0022 100644
--- a/app/views/projects/issues/_issue.html.haml
+++ b/app/views/projects/issues/_issue.html.haml
@@ -13,9 +13,9 @@
%li
CLOSED
- - if issue.assignee
+ - if issue.assignees.any?
%li
- = link_to_member(@project, issue.assignee, name: false, title: "Assigned to :name")
+ = render 'shared/issuable/assignees', project: @project, issue: issue
= render 'shared/issuable_meta_data', issuable: issue
diff --git a/app/views/projects/issues/show.html.haml b/app/views/projects/issues/show.html.haml
index 1418ad73553..9084883eb3e 100644
--- a/app/views/projects/issues/show.html.haml
+++ b/app/views/projects/issues/show.html.haml
@@ -51,16 +51,11 @@
.issue-details.issuable-details
.detail-page-description.content-block
- .issue-title-data.hidden{ "data" => { "initial-title" => markdown_field(@issue, :title),
- "endpoint" => rendered_title_namespace_project_issue_path(@project.namespace, @project, @issue),
+ .issue-title-data.hidden{ "data" => { "endpoint" => rendered_title_namespace_project_issue_path(@project.namespace, @project, @issue),
+ "can-update-tasks-class" => can?(current_user, :update_issue, @issue) ? 'js-task-list-container' : '',
} }
.issue-title-entrypoint
- - if @issue.description.present?
- .description{ class: can?(current_user, :update_issue, @issue) ? 'js-task-list-container' : '' }
- .wiki
- = markdown_field(@issue, :description)
- %textarea.hidden.js-task-list-field
- = @issue.description
+
= edited_time_ago_with_tooltip(@issue, placement: 'bottom', html_class: 'issue_edited_ago')
#merge-requests{ data: { url: referenced_merge_requests_namespace_project_issue_url(@project.namespace, @project, @issue) } }
diff --git a/app/views/projects/pipelines/_with_tabs.html.haml b/app/views/projects/pipelines/_with_tabs.html.haml
index d7cefb8613e..1aa48bf9813 100644
--- a/app/views/projects/pipelines/_with_tabs.html.haml
+++ b/app/views/projects/pipelines/_with_tabs.html.haml
@@ -1,3 +1,5 @@
+- failed_builds = @pipeline.statuses.latest.failed
+
.tabs-holder
%ul.pipelines-tabs.nav-links.no-top.no-bottom
%li.js-pipeline-tab-link
@@ -7,8 +9,11 @@
= link_to builds_namespace_project_pipeline_path(@project.namespace, @project, @pipeline), data: {target: 'div#js-tab-builds', action: 'builds', toggle: 'tab' }, class: 'builds-tab' do
Jobs
%span.badge.js-builds-counter= pipeline.statuses.count
-
-
+ - if failed_builds.present?
+ %li.js-failures-tab-link
+ = link_to failures_namespace_project_pipeline_path(@project.namespace, @project, @pipeline), data: {target: 'div#js-tab-failures', action: 'failures', toggle: 'tab' }, class: 'failures-tab' do
+ Failed Jobs
+ %span.badge.js-failures-counter= failed_builds.count
.tab-content
#js-tab-pipeline.tab-pane
@@ -39,3 +44,13 @@
%th Coverage
%th
= render partial: "projects/stage/stage", collection: pipeline.stages, as: :stage
+ - if failed_builds.present?
+ #js-tab-failures.build-failures.tab-pane
+ - failed_builds.each_with_index do |build, index|
+ .build-state
+ %span.ci-status-icon-failed= custom_icon('icon_status_failed')
+ %span.stage
+ = build.stage.titleize
+ %span.build-name
+ = link_to build.name, pipeline_build_url(pipeline, build)
+ %pre.build-log= build_summary(build, skip: index >= 10)
diff --git a/app/views/projects/protected_branches/_create_protected_branch.html.haml b/app/views/projects/protected_branches/_create_protected_branch.html.haml
index b8e885b4d9a..99bc2516366 100644
--- a/app/views/projects/protected_branches/_create_protected_branch.html.haml
+++ b/app/views/projects/protected_branches/_create_protected_branch.html.haml
@@ -25,7 +25,7 @@
.merge_access_levels-container
= dropdown_tag('Select',
options: { toggle_class: 'js-allowed-to-merge wide',
- dropdown_class: 'dropdown-menu-selectable',
+ dropdown_class: 'dropdown-menu-selectable capitalize-header',
data: { field_name: 'protected_branch[merge_access_levels_attributes][0][access_level]', input_id: 'merge_access_levels_attributes' }})
.form-group
%label.col-md-2.text-right{ for: 'push_access_levels_attributes' }
@@ -34,7 +34,7 @@
.push_access_levels-container
= dropdown_tag('Select',
options: { toggle_class: 'js-allowed-to-push wide',
- dropdown_class: 'dropdown-menu-selectable',
+ dropdown_class: 'dropdown-menu-selectable capitalize-header',
data: { field_name: 'protected_branch[push_access_levels_attributes][0][access_level]', input_id: 'push_access_levels_attributes' }})
.panel-footer
diff --git a/app/views/projects/protected_branches/_update_protected_branch.html.haml b/app/views/projects/protected_branches/_update_protected_branch.html.haml
index d6044aacaec..c61b2951e1e 100644
--- a/app/views/projects/protected_branches/_update_protected_branch.html.haml
+++ b/app/views/projects/protected_branches/_update_protected_branch.html.haml
@@ -1,10 +1,10 @@
%td
= hidden_field_tag "allowed_to_merge_#{protected_branch.id}", protected_branch.merge_access_levels.first.access_level
= dropdown_tag( (protected_branch.merge_access_levels.first.humanize || 'Select') ,
- options: { toggle_class: 'js-allowed-to-merge', dropdown_class: 'dropdown-menu-selectable js-allowed-to-merge-container',
+ options: { toggle_class: 'js-allowed-to-merge', dropdown_class: 'dropdown-menu-selectable js-allowed-to-merge-container capitalize-header',
data: { field_name: "allowed_to_merge_#{protected_branch.id}", access_level_id: protected_branch.merge_access_levels.first.id }})
%td
= hidden_field_tag "allowed_to_push_#{protected_branch.id}", protected_branch.push_access_levels.first.access_level
= dropdown_tag( (protected_branch.push_access_levels.first.humanize || 'Select') ,
- options: { toggle_class: 'js-allowed-to-push', dropdown_class: 'dropdown-menu-selectable js-allowed-to-push-container',
+ options: { toggle_class: 'js-allowed-to-push', dropdown_class: 'dropdown-menu-selectable js-allowed-to-push-container capitalize-header',
data: { field_name: "allowed_to_push_#{protected_branch.id}", access_level_id: protected_branch.push_access_levels.first.id }})
diff --git a/app/views/projects/protected_tags/_dropdown.html.haml b/app/views/projects/protected_tags/_dropdown.html.haml
index 74851519077..c50515cfe06 100644
--- a/app/views/projects/protected_tags/_dropdown.html.haml
+++ b/app/views/projects/protected_tags/_dropdown.html.haml
@@ -2,7 +2,7 @@
= dropdown_tag('Select tag or create wildcard',
options: { toggle_class: 'js-protected-tag-select js-filter-submit wide',
- filter: true, dropdown_class: "dropdown-menu-selectable", placeholder: "Search protected tag",
+ filter: true, dropdown_class: "dropdown-menu-selectable capitalize-header", placeholder: "Search protected tag",
footer_content: true,
data: { show_no: true, show_any: true, show_upcoming: true,
selected: params[:protected_tag_name],
diff --git a/app/views/projects/protected_tags/_update_protected_tag.haml b/app/views/projects/protected_tags/_update_protected_tag.haml
index 62823bee46e..cc80bd04dd0 100644
--- a/app/views/projects/protected_tags/_update_protected_tag.haml
+++ b/app/views/projects/protected_tags/_update_protected_tag.haml
@@ -1,5 +1,5 @@
%td
= hidden_field_tag "allowed_to_create_#{protected_tag.id}", protected_tag.create_access_levels.first.access_level
= dropdown_tag( (protected_tag.create_access_levels.first.humanize || 'Select') ,
- options: { toggle_class: 'js-allowed-to-create', dropdown_class: 'dropdown-menu-selectable js-allowed-to-create-container',
+ options: { toggle_class: 'js-allowed-to-create', dropdown_class: 'dropdown-menu-selectable capitalize-header js-allowed-to-create-container',
data: { field_name: "allowed_to_create_#{protected_tag.id}", access_level_id: protected_tag.create_access_levels.first.id }})
diff --git a/app/views/shared/issuable/_assignees.html.haml b/app/views/shared/issuable/_assignees.html.haml
new file mode 100644
index 00000000000..36bbb1148d4
--- /dev/null
+++ b/app/views/shared/issuable/_assignees.html.haml
@@ -0,0 +1,15 @@
+- max_render = 3
+- max = [max_render, issue.assignees.length].min
+
+- issue.assignees.each_with_index do |assignee, index|
+ - if index < max
+ = link_to_member(@project, assignee, name: false, title: "Assigned to :name")
+
+- if issue.assignees.length > max_render
+ - counter = issue.assignees.length - max_render
+
+ %span{ class: 'avatar-counter has-tooltip', data: { container: 'body', placement: 'bottom', 'line-type' => 'old', 'original-title' => "+#{counter} more assignees" } }
+ - if counter < 99
+ = "+#{counter}"
+ - else
+ 99+
diff --git a/app/views/shared/issuable/_participants.html.haml b/app/views/shared/issuable/_participants.html.haml
index 171da899937..db407363a09 100644
--- a/app/views/shared/issuable/_participants.html.haml
+++ b/app/views/shared/issuable/_participants.html.haml
@@ -12,9 +12,9 @@
- participants.each do |participant|
.participants-author.js-participants-author
= link_to_member(@project, participant, name: false, size: 24)
- - if participants_extra > 0
- .participants-more
- %a.js-participants-more{ href: "#", data: { original_text: "+ #{participants_size - 7} more", less_text: "- show less" } }
- + #{participants_extra} more
+ - if participants_extra > 0
+ .hide-collapsed.participants-more
+ %a.js-participants-more{ href: "#", data: { original_text: "+ #{participants_size - 7} more", less_text: "- show less" } }
+ + #{participants_extra} more
:javascript
IssuableContext.prototype.PARTICIPANTS_ROW_COUNT = #{participants_row};
diff --git a/app/views/shared/issuable/_search_bar.html.haml b/app/views/shared/issuable/_search_bar.html.haml
index b6fce5e3cd4..f7b87171573 100644
--- a/app/views/shared/issuable/_search_bar.html.haml
+++ b/app/views/shared/issuable/_search_bar.html.haml
@@ -124,8 +124,13 @@
%li
%a{ href: "#", data: { id: "close" } } Closed
.filter-item.inline
+ - if type == :issues
+ - field_name = "update[assignee_ids][]"
+ - else
+ - field_name = "update[assignee_id]"
+
= dropdown_tag("Assignee", options: { toggle_class: "js-user-search js-update-assignee js-filter-submit js-filter-bulk-update", title: "Assign to", filter: true, dropdown_class: "dropdown-menu-user dropdown-menu-selectable",
- placeholder: "Search authors", data: { first_user: (current_user.username if current_user), null_user: true, current_user: true, project_id: @project.id, field_name: "update[assignee_id]", default_label: "Assignee" } })
+ placeholder: "Search authors", data: { first_user: (current_user.username if current_user), null_user: true, current_user: true, project_id: @project.id, field_name: field_name } })
.filter-item.inline
= dropdown_tag("Milestone", options: { title: "Assign milestone", toggle_class: 'js-milestone-select js-extra-options js-filter-submit js-filter-bulk-update', filter: true, dropdown_class: "dropdown-menu-selectable dropdown-menu-milestone", placeholder: "Search milestones", data: { show_no: true, field_name: "update[milestone_id]", project_id: @project.id, milestones: namespace_project_milestones_path(@project.namespace, @project, :json), use_id: true, default_label: "Milestone" } })
.filter-item.inline.labels-filter
diff --git a/app/views/shared/issuable/_sidebar.html.haml b/app/views/shared/issuable/_sidebar.html.haml
index bc638e994f3..44e624c15a7 100644
--- a/app/views/shared/issuable/_sidebar.html.haml
+++ b/app/views/shared/issuable/_sidebar.html.haml
@@ -1,10 +1,10 @@
- todo = issuable_todo(issuable)
- content_for :page_specific_javascripts do
= page_specific_javascript_bundle_tag('common_vue')
- = page_specific_javascript_bundle_tag('issuable')
+ = page_specific_javascript_bundle_tag('sidebar')
%aside.right-sidebar.js-right-sidebar{ data: { "offset-top" => "102", "spy" => "affix" }, class: sidebar_gutter_collapsed_class, 'aria-live' => 'polite' }
- .issuable-sidebar
+ .issuable-sidebar{ data: { endpoint: "#{issuable_json_path(issuable)}" } }
- can_edit_issuable = can?(current_user, :"admin_#{issuable.to_ability_name}", @project)
.block.issuable-sidebar-header
- if current_user
@@ -20,36 +20,55 @@
.block.todo.hide-expanded
= render "shared/issuable/sidebar_todo", todo: todo, issuable: issuable, is_collapsed: true
.block.assignee
- .sidebar-collapsed-icon.sidebar-collapsed-user{ data: { toggle: "tooltip", placement: "left", container: "body" }, title: (issuable.assignee.name if issuable.assignee) }
- - if issuable.assignee
- = link_to_member(@project, issuable.assignee, size: 24)
- - else
- = icon('user', 'aria-hidden': 'true')
- .title.hide-collapsed
- Assignee
- = icon('spinner spin', class: 'hidden block-loading', 'aria-hidden': 'true')
- - if can_edit_issuable
- = link_to 'Edit', '#', class: 'edit-link pull-right'
- .value.hide-collapsed
- - if issuable.assignee
- = link_to_member(@project, issuable.assignee, size: 32, extra_class: 'bold') do
- - if issuable.instance_of?(MergeRequest) && !issuable.can_be_merged_by?(issuable.assignee)
- %span.pull-right.cannot-be-merged{ data: { toggle: 'tooltip', placement: 'left' }, title: 'Not allowed to merge' }
- = icon('exclamation-triangle', 'aria-hidden': 'true')
- %span.username
- = issuable.assignee.to_reference
- - else
- %span.assign-yourself.no-value
- No assignee
- - if can_edit_issuable
- \-
- %a.js-assign-yourself{ href: '#' }
- assign yourself
+ - if issuable.instance_of?(Issue)
+ #js-vue-sidebar-assignees{ data: { field: "#{issuable.to_ability_name}[assignee_ids]" } }
+ - else
+ .sidebar-collapsed-icon.sidebar-collapsed-user{ data: { toggle: "tooltip", placement: "left", container: "body" }, title: (issuable.assignee.name if issuable.assignee) }
+ - if issuable.assignee
+ = link_to_member(@project, issuable.assignee, size: 24)
+ - else
+ = icon('user', 'aria-hidden': 'true')
+ .title.hide-collapsed
+ Assignee
+ = icon('spinner spin', class: 'hidden block-loading', 'aria-hidden': 'true')
+ - if can_edit_issuable
+ = link_to 'Edit', '#', class: 'edit-link pull-right'
+ .value.hide-collapsed
+ - if issuable.assignee
+ = link_to_member(@project, issuable.assignee, size: 32, extra_class: 'bold') do
+ - if issuable.instance_of?(MergeRequest) && !issuable.can_be_merged_by?(issuable.assignee)
+ %span.pull-right.cannot-be-merged{ data: { toggle: 'tooltip', placement: 'left' }, title: 'Not allowed to merge' }
+ = icon('exclamation-triangle', 'aria-hidden': 'true')
+ %span.username
+ = issuable.assignee.to_reference
+ - else
+ %span.assign-yourself.no-value
+ No assignee
+ - if can_edit_issuable
+ \-
+ %a.js-assign-yourself{ href: '#' }
+ assign yourself
.selectbox.hide-collapsed
- = f.hidden_field 'assignee_id', value: issuable.assignee_id, id: 'issue_assignee_id'
- = dropdown_tag('Select assignee', options: { toggle_class: 'js-user-search js-author-search', title: 'Assign to', filter: true, dropdown_class: 'dropdown-menu-user dropdown-menu-selectable dropdown-menu-author', placeholder: 'Search users', data: { first_user: (current_user.username if current_user), current_user: true, project_id: (@project.id if @project), author_id: issuable.author_id, field_name: "#{issuable.to_ability_name}[assignee_id]", issue_update: issuable_json_path(issuable), ability_name: issuable.to_ability_name, null_user: true, null_user_default: true, selected: issuable.assignee_id } })
+ - issuable.assignees.each do |assignee|
+ = hidden_field_tag "#{issuable.to_ability_name}[assignee_ids][]", assignee.id, id: nil
+ - options = { toggle_class: 'js-user-search js-author-search', title: 'Assign to', filter: true, dropdown_class: 'dropdown-menu-user dropdown-menu-selectable dropdown-menu-author', placeholder: 'Search users', data: { first_user: (current_user.username if current_user), current_user: true, project_id: (@project.id if @project), author_id: issuable.author_id, field_name: "#{issuable.to_ability_name}[assignee_ids][]", issue_update: issuable_json_path(issuable), ability_name: issuable.to_ability_name, null_user: true } }
+
+ - if issuable.instance_of?(Issue)
+ - if issuable.assignees.length == 0
+ = hidden_field_tag "#{issuable.to_ability_name}[assignee_ids][]", 0, id: nil
+ - title = 'Select assignee'
+ - options[:toggle_class] += ' js-multiselect js-save-user-data'
+ - options[:data][:field_name] = "#{issuable.to_ability_name}[assignee_ids][]"
+ - options[:data][:multi_select] = true
+ - options[:data]['dropdown-title'] = title
+ - options[:data]['dropdown-header'] = 'Assignee'
+ - options[:data]['max-select'] = 1
+ - else
+ - title = 'Select assignee'
+
+ = dropdown_tag(title, options: options)
.block.milestone
.sidebar-collapsed-icon
= icon('clock-o', 'aria-hidden': 'true')
@@ -75,11 +94,10 @@
= dropdown_tag('Milestone', options: { title: 'Assign milestone', toggle_class: 'js-milestone-select js-extra-options', filter: true, dropdown_class: 'dropdown-menu-selectable', placeholder: 'Search milestones', data: { show_no: true, field_name: "#{issuable.to_ability_name}[milestone_id]", project_id: @project.id, issuable_id: issuable.id, milestones: namespace_project_milestones_path(@project.namespace, @project, :json), ability_name: issuable.to_ability_name, issue_update: issuable_json_path(issuable), use_id: true }})
- if issuable.has_attribute?(:time_estimate)
#issuable-time-tracker.block
- %issuable-time-tracker{ ':time_estimate' => 'issuable.time_estimate', ':time_spent' => 'issuable.total_time_spent', ':human_time_estimate' => 'issuable.human_time_estimate', ':human_time_spent' => 'issuable.human_total_time_spent', 'docs-url' => help_page_path('workflow/time_tracking.md') }
- // Fallback while content is loading
- .title.hide-collapsed
- Time tracking
- = icon('spinner spin', 'aria-hidden': 'true')
+ // Fallback while content is loading
+ .title.hide-collapsed
+ Time tracking
+ = icon('spinner spin', 'aria-hidden': 'true')
- if issuable.has_attribute?(:due_date)
.block.due_date
.sidebar-collapsed-icon
@@ -169,8 +187,13 @@
= clipboard_button(text: project_ref, title: "Copy reference to clipboard", placement: "left")
:javascript
- gl.IssuableResource = new gl.SubbableResource('#{issuable_json_path(issuable)}');
- new gl.IssuableTimeTracking("#{escape_javascript(serialize_issuable(issuable))}");
+ gl.sidebarOptions = {
+ endpoint: "#{issuable_json_path(issuable)}",
+ editable: #{can_edit_issuable ? true : false},
+ currentUser: #{current_user.to_json(only: [:username, :id, :name], methods: :avatar_url)},
+ rootPath: "#{root_path}"
+ };
+
new MilestoneSelect('{"full_path":"#{@project.full_path}"}');
new LabelsSelect();
new IssuableContext('#{escape_javascript(current_user.to_json(only: [:username, :id, :name]))}');
diff --git a/app/views/shared/issuable/form/_issue_assignee.html.haml b/app/views/shared/issuable/form/_issue_assignee.html.haml
new file mode 100644
index 00000000000..c33474ac3b4
--- /dev/null
+++ b/app/views/shared/issuable/form/_issue_assignee.html.haml
@@ -0,0 +1,30 @@
+- issue = issuable
+.block.assignee
+ .sidebar-collapsed-icon.sidebar-collapsed-user{ data: { toggle: "tooltip", placement: "left", container: "body" }, title: (issuable.assignee_list) }
+ - if issue.assignees.any?
+ - issue.assignees.each do |assignee|
+ = link_to_member(@project, assignee, size: 24)
+ - else
+ = icon('user', 'aria-hidden': 'true')
+ .title.hide-collapsed
+ Assignee
+ = icon('spinner spin', class: 'hidden block-loading', 'aria-hidden': 'true')
+ - if can_edit_issuable
+ = link_to 'Edit', '#', class: 'edit-link pull-right'
+ .value.hide-collapsed
+ - if issue.assignees.any?
+ - issue.assignees.each do |assignee|
+ = link_to_member(@project, assignee, size: 32, extra_class: 'bold') do
+ %span.username
+ = assignee.to_reference
+ - else
+ %span.assign-yourself.no-value
+ No assignee
+ - if can_edit_issuable
+ \-
+ %a.js-assign-yourself{ href: '#' }
+ assign yourself
+
+ .selectbox.hide-collapsed
+ = f.hidden_field 'assignee_ids', value: issuable.assignee_ids, id: 'issue_assignee_ids'
+ = dropdown_tag('Select assignee', options: { toggle_class: 'js-user-search js-author-search', title: 'Assign to', filter: true, dropdown_class: 'dropdown-menu-user dropdown-menu-selectable dropdown-menu-author', placeholder: 'Search users', data: { first_user: (current_user.username if current_user), current_user: true, project_id: (@project.id if @project), author_id: issuable.author_id, field_name: "#{issuable.to_ability_name}[assignee_id]", issue_update: issuable_json_path(issuable), ability_name: issuable.to_ability_name, null_user: true } })
diff --git a/app/views/shared/issuable/form/_merge_request_assignee.html.haml b/app/views/shared/issuable/form/_merge_request_assignee.html.haml
new file mode 100644
index 00000000000..18011d528a0
--- /dev/null
+++ b/app/views/shared/issuable/form/_merge_request_assignee.html.haml
@@ -0,0 +1,31 @@
+- merge_request = issuable
+.block.assignee
+ .sidebar-collapsed-icon.sidebar-collapsed-user{ data: { toggle: "tooltip", placement: "left", container: "body" }, title: (merge_request.assignee.name if merge_request.assignee) }
+ - if merge_request.assignee
+ = link_to_member(@project, merge_request.assignee, size: 24)
+ - else
+ = icon('user', 'aria-hidden': 'true')
+ .title.hide-collapsed
+ Assignee
+ = icon('spinner spin', class: 'hidden block-loading', 'aria-hidden': 'true')
+ - if can_edit_issuable
+ = link_to 'Edit', '#', class: 'edit-link pull-right'
+ .value.hide-collapsed
+ - if merge_request.assignee
+ = link_to_member(@project, merge_request.assignee, size: 32, extra_class: 'bold') do
+ - unless merge_request.can_be_merged_by?(merge_request.assignee)
+ %span.pull-right.cannot-be-merged{ data: { toggle: 'tooltip', placement: 'left' }, title: 'Not allowed to merge' }
+ = icon('exclamation-triangle', 'aria-hidden': 'true')
+ %span.username
+ = merge_request.assignee.to_reference
+ - else
+ %span.assign-yourself.no-value
+ No assignee
+ - if can_edit_issuable
+ \-
+ %a.js-assign-yourself{ href: '#' }
+ assign yourself
+
+ .selectbox.hide-collapsed
+ = f.hidden_field 'assignee_id', value: merge_request.assignee_id, id: 'issue_assignee_id'
+ = dropdown_tag('Select assignee', options: { toggle_class: 'js-user-search js-author-search', title: 'Assign to', filter: true, dropdown_class: 'dropdown-menu-user dropdown-menu-selectable dropdown-menu-author', placeholder: 'Search users', data: { first_user: (current_user.username if current_user), current_user: true, project_id: @project&.id, author_id: merge_request.author_id, field_name: 'merge_request[assignee_id]', issue_update: issuable_json_path(merge_request), ability_name: 'merge_request', null_user: true } })
diff --git a/app/views/shared/issuable/form/_metadata.html.haml b/app/views/shared/issuable/form/_metadata.html.haml
index 9dbfedb84f1..9281a515744 100644
--- a/app/views/shared/issuable/form/_metadata.html.haml
+++ b/app/views/shared/issuable/form/_metadata.html.haml
@@ -10,13 +10,27 @@
.row
%div{ class: (has_due_date ? "col-lg-6" : "col-sm-12") }
.form-group.issue-assignee
- = form.label :assignee_id, "Assignee", class: "control-label #{"col-lg-4" if has_due_date}"
- .col-sm-10{ class: ("col-lg-8" if has_due_date) }
- .issuable-form-select-holder
- = form.hidden_field :assignee_id
- = dropdown_tag(user_dropdown_label(issuable.assignee_id, "Assignee"), options: { toggle_class: "js-dropdown-keep-input js-user-search js-issuable-form-dropdown js-assignee-search", title: "Select assignee", filter: true, dropdown_class: "dropdown-menu-user dropdown-menu-selectable dropdown-menu-assignee js-filter-submit",
- placeholder: "Search assignee", data: { first_user: current_user.try(:username), null_user: true, current_user: true, project_id: issuable.project.try(:id), selected: issuable.assignee_id, field_name: "#{issuable.class.model_name.param_key}[assignee_id]", default_label: "Assignee"} })
- = link_to 'Assign to me', '#', class: "assign-to-me-link #{'hide' if issuable.assignee_id == current_user.id}"
+ - if issuable.is_a?(Issue)
+ = form.label :assignee_ids, "Assignee", class: "control-label #{"col-lg-4" if has_due_date}"
+ .col-sm-10{ class: ("col-lg-8" if has_due_date) }
+ .issuable-form-select-holder.selectbox
+ - issuable.assignees.each do |assignee|
+ = hidden_field_tag "#{issuable.to_ability_name}[assignee_ids][]", assignee.id, id: nil, data: { meta: assignee.name }
+
+ - if issuable.assignees.length === 0
+ = hidden_field_tag "#{issuable.to_ability_name}[assignee_ids][]", 0, id: nil, data: { meta: '' }
+
+ = dropdown_tag(users_dropdown_label(issuable.assignees), options: issue_dropdown_options(issuable,false))
+ = link_to 'Assign to me', '#', class: "assign-to-me-link #{'hide' if issuable.assignees.include?(current_user)}"
+ - else
+ = form.label :assignee_id, "Assignee", class: "control-label #{"col-lg-4" if has_due_date}"
+ .col-sm-10{ class: ("col-lg-8" if has_due_date) }
+ .issuable-form-select-holder
+ = form.hidden_field :assignee_id
+
+ = dropdown_tag(user_dropdown_label(issuable.assignee_id, "Assignee"), options: { toggle_class: "js-dropdown-keep-input js-user-search js-issuable-form-dropdown js-assignee-search", title: "Select assignee", filter: true, dropdown_class: "dropdown-menu-user dropdown-menu-selectable dropdown-menu-assignee js-filter-submit",
+ placeholder: "Search assignee", data: { first_user: current_user.try(:username), null_user: true, current_user: true, project_id: issuable.project.try(:id), selected: issuable.assignee_id, field_name: "#{issuable.class.model_name.param_key}[assignee_id]", default_label: "Assignee"} })
+ = link_to 'Assign to me', '#', class: "assign-to-me-link #{'hide' if issuable.assignee_id == current_user.id}"
.form-group.issue-milestone
= form.label :milestone_id, "Milestone", class: "control-label #{"col-lg-4" if has_due_date}"
.col-sm-10{ class: ("col-lg-8" if has_due_date) }
diff --git a/app/views/shared/milestones/_issuable.html.haml b/app/views/shared/milestones/_issuable.html.haml
index 5247d6a51e6..22547a30cdf 100644
--- a/app/views/shared/milestones/_issuable.html.haml
+++ b/app/views/shared/milestones/_issuable.html.haml
@@ -1,7 +1,7 @@
-# @project is present when viewing Project's milestone
- project = @project || issuable.project
- namespace = @project_namespace || project.namespace.becomes(Namespace)
-- assignee = issuable.assignee
+- assignees = issuable.assignees
- issuable_type = issuable.class.table_name
- base_url_args = [namespace, project]
- issuable_type_args = base_url_args + [issuable_type]
@@ -26,7 +26,7 @@
- render_colored_label(label)
%span.assignee-icon
- - if assignee
- = link_to polymorphic_path(issuable_type_args, { milestone_title: @milestone.title, assignee_id: issuable.assignee_id, state: 'all' }),
+ - assignees.each do |assignee|
+ = link_to polymorphic_path(base_url_args, { milestone_title: @milestone.title, assignee_id: assignee.id, state: 'all' }),
class: 'has-tooltip', title: "Assigned to #{assignee.name}", data: { container: 'body' } do
- - image_tag(avatar_icon(issuable.assignee, 16), class: "avatar s16", alt: '')
+ - image_tag(avatar_icon(assignee, 16), class: "avatar s16", alt: '')
diff --git a/app/views/shared/milestones/_labels_tab.html.haml b/app/views/shared/milestones/_labels_tab.html.haml
index 33f93dccd3c..a26b3b8009e 100644
--- a/app/views/shared/milestones/_labels_tab.html.haml
+++ b/app/views/shared/milestones/_labels_tab.html.haml
@@ -2,7 +2,7 @@
- labels.each do |label|
- options = { milestone_title: @milestone.title, label_name: label.title }
- %li
+ %li.is-not-draggable
%span.label-row
%span.label-name
= link_to milestones_label_path(options) do
@@ -10,10 +10,8 @@
%span.prepend-description-left
= markdown_field(label, :description)
- .pull-info-right
- %span.append-right-20
- = link_to milestones_label_path(options.merge(state: 'opened')) do
- - pluralize milestone_issues_by_label_count(@milestone, label, state: :opened), 'open issue'
- %span.append-right-20
- = link_to milestones_label_path(options.merge(state: 'closed')) do
- - pluralize milestone_issues_by_label_count(@milestone, label, state: :closed), 'closed issue'
+ .pull-right.hidden-xs.hidden-sm.hidden-md
+ = link_to milestones_label_path(options.merge(state: 'opened')), class: 'btn btn-transparent btn-action' do
+ - pluralize milestone_issues_by_label_count(@milestone, label, state: :opened), 'open issue'
+ = link_to milestones_label_path(options.merge(state: 'closed')), class: 'btn btn-transparent btn-action' do
+ - pluralize milestone_issues_by_label_count(@milestone, label, state: :closed), 'closed issue'
diff --git a/app/views/shared/notes/_note.html.haml b/app/views/shared/notes/_note.html.haml
index 071c48fa2e4..5c1156b06fb 100644
--- a/app/views/shared/notes/_note.html.haml
+++ b/app/views/shared/notes/_note.html.haml
@@ -40,7 +40,7 @@
.note-body{ class: note_editable ? 'js-task-list-container' : '' }
.note-text.md
= note.redacted_note_html
- = edited_time_ago_with_tooltip(note, placement: 'bottom', html_class: 'note_edited_ago', include_author: true)
+ = edited_time_ago_with_tooltip(note, placement: 'bottom', html_class: 'note_edited_ago')
- if note_editable
= render 'shared/notes/edit', note: note
.note-awards
diff --git a/app/views/shared/snippets/_header.html.haml b/app/views/shared/snippets/_header.html.haml
index d084f5e9684..501c09d71d5 100644
--- a/app/views/shared/snippets/_header.html.haml
+++ b/app/views/shared/snippets/_header.html.haml
@@ -21,4 +21,4 @@
= markdown_field(@snippet, :title)
- if @snippet.updated_at != @snippet.created_at
- = edited_time_ago_with_tooltip(@snippet, placement: 'bottom', html_class: 'snippet-edited-ago')
+ = edited_time_ago_with_tooltip(@snippet, placement: 'bottom', html_class: 'snippet-edited-ago', exclude_author: true)
diff --git a/app/workers/post_receive.rb b/app/workers/post_receive.rb
index 015a41b6e82..127d8dfbb61 100644
--- a/app/workers/post_receive.rb
+++ b/app/workers/post_receive.rb
@@ -2,27 +2,24 @@ class PostReceive
include Sidekiq::Worker
include DedicatedSidekiqQueue
- def perform(repo_path, identifier, changes)
- repo_relative_path = Gitlab::RepoPath.strip_storage_path(repo_path)
+ def perform(project_identifier, identifier, changes)
+ project, is_wiki = parse_project_identifier(project_identifier)
+
+ if project.nil?
+ log("Triggered hook for non-existing project with identifier \"#{project_identifier}\"")
+ return false
+ end
changes = Base64.decode64(changes) unless changes.include?(' ')
# Use Sidekiq.logger so arguments can be correlated with execution
# time and thread ID's.
Sidekiq.logger.info "changes: #{changes.inspect}" if ENV['SIDEKIQ_LOG_ARGUMENTS']
- post_received = Gitlab::GitPostReceive.new(repo_relative_path, identifier, changes)
-
- if post_received.project.nil?
- log("Triggered hook for non-existing project with full path \"#{repo_relative_path}\"")
- return false
- end
+ post_received = Gitlab::GitPostReceive.new(project, identifier, changes)
- if post_received.wiki?
+ if is_wiki
# Nothing defined here yet.
- elsif post_received.regular_project?
- process_project_changes(post_received)
else
- log("Triggered hook for unidentifiable repository type with full path \"#{repo_relative_path}\"")
- false
+ process_project_changes(post_received)
end
end
@@ -47,6 +44,21 @@ class PostReceive
private
+ # To maintain backwards compatibility, we accept both gl_repository or
+ # repository paths as project identifiers. Our plan is to migrate to
+ # gl_repository only with the following plan:
+ # 9.2: Handle both possible values. Keep Gitlab-Shell sending only repo paths
+ # 9.3 (or patch release): Make GitLab Shell pass gl_repository if present
+ # 9.4 (or patch release): Make GitLab Shell always pass gl_repository
+ # 9.5 (or patch release): Handle only gl_repository as project identifier on this method
+ def parse_project_identifier(project_identifier)
+ if project_identifier.start_with?('/')
+ Gitlab::RepoPath.parse(project_identifier)
+ else
+ Gitlab::GlRepository.parse(project_identifier)
+ end
+ end
+
def log(message)
Gitlab::GitLogger.error("POST-RECEIVE: #{message}")
end
diff --git a/app/workers/propagate_service_template_worker.rb b/app/workers/propagate_service_template_worker.rb
new file mode 100644
index 00000000000..5ce0e0405d0
--- /dev/null
+++ b/app/workers/propagate_service_template_worker.rb
@@ -0,0 +1,21 @@
+# Worker for updating any project specific caches.
+class PropagateServiceTemplateWorker
+ include Sidekiq::Worker
+ include DedicatedSidekiqQueue
+
+ LEASE_TIMEOUT = 4.hours.to_i
+
+ def perform(template_id)
+ return unless try_obtain_lease_for(template_id)
+
+ Projects::PropagateServiceTemplate.propagate(Service.find_by(id: template_id))
+ end
+
+ private
+
+ def try_obtain_lease_for(template_id)
+ Gitlab::ExclusiveLease.
+ new("propagate_service_template_worker:#{template_id}", timeout: LEASE_TIMEOUT).
+ try_obtain
+ end
+end
diff --git a/changelogs/unreleased/17361-redirect-renamed-paths.yml b/changelogs/unreleased/17361-redirect-renamed-paths.yml
new file mode 100644
index 00000000000..7a33c9fb3ec
--- /dev/null
+++ b/changelogs/unreleased/17361-redirect-renamed-paths.yml
@@ -0,0 +1,4 @@
+---
+title: Redirect old links after renaming a user/group/project.
+merge_request: 10370
+author:
diff --git a/changelogs/unreleased/23751-add-contribution-graph-key-tooltips.yml b/changelogs/unreleased/23751-add-contribution-graph-key-tooltips.yml
new file mode 100644
index 00000000000..7c4c6fb46a0
--- /dev/null
+++ b/changelogs/unreleased/23751-add-contribution-graph-key-tooltips.yml
@@ -0,0 +1,4 @@
+---
+title: Add tooltips to user contribution graph key
+merge_request: 11138
+author:
diff --git a/changelogs/unreleased/24883-build-failure-summary-page.yml b/changelogs/unreleased/24883-build-failure-summary-page.yml
new file mode 100644
index 00000000000..214cd3e2bc7
--- /dev/null
+++ b/changelogs/unreleased/24883-build-failure-summary-page.yml
@@ -0,0 +1,4 @@
+---
+title: Added build failures summary page for pipelines
+merge_request: 10719
+author:
diff --git a/changelogs/unreleased/29925-gitlab-shell-hooks-can-no-longer-send-absolute-paths-to-gitlab-ce.yml b/changelogs/unreleased/29925-gitlab-shell-hooks-can-no-longer-send-absolute-paths-to-gitlab-ce.yml
new file mode 100644
index 00000000000..1df8f695ef1
--- /dev/null
+++ b/changelogs/unreleased/29925-gitlab-shell-hooks-can-no-longer-send-absolute-paths-to-gitlab-ce.yml
@@ -0,0 +1,4 @@
+---
+title: Generate and handle a gl_repository param to pass around components
+merge_request: 10992
+author:
diff --git a/changelogs/unreleased/30007-done-todo-hover-state.yml b/changelogs/unreleased/30007-done-todo-hover-state.yml
new file mode 100644
index 00000000000..bfbde7a49c8
--- /dev/null
+++ b/changelogs/unreleased/30007-done-todo-hover-state.yml
@@ -0,0 +1,4 @@
+---
+title: Add transparent top-border to the hover state of done todos
+merge_request:
+author:
diff --git a/changelogs/unreleased/30903-vertically-align-mini-pipeline.yml b/changelogs/unreleased/30903-vertically-align-mini-pipeline.yml
new file mode 100644
index 00000000000..af87e5ce39f
--- /dev/null
+++ b/changelogs/unreleased/30903-vertically-align-mini-pipeline.yml
@@ -0,0 +1,4 @@
+---
+title: Vertically align mini pipeline stage container
+merge_request:
+author:
diff --git a/changelogs/unreleased/add_system_note_for_editing_issuable.yml b/changelogs/unreleased/add_system_note_for_editing_issuable.yml
new file mode 100644
index 00000000000..3cbc7f91bf0
--- /dev/null
+++ b/changelogs/unreleased/add_system_note_for_editing_issuable.yml
@@ -0,0 +1,4 @@
+---
+title: Add system note on description change of issue/merge request
+merge_request: 10392
+author: blackst0ne
diff --git a/changelogs/unreleased/balsalmiq-support.yml b/changelogs/unreleased/balsalmiq-support.yml
new file mode 100644
index 00000000000..56a0b4c83fa
--- /dev/null
+++ b/changelogs/unreleased/balsalmiq-support.yml
@@ -0,0 +1,4 @@
+---
+title: Added balsamiq file viewer
+merge_request: 10564
+author:
diff --git a/changelogs/unreleased/feature-gb-manual-actions-protected-branches-permissions.yml b/changelogs/unreleased/feature-gb-manual-actions-protected-branches-permissions.yml
new file mode 100644
index 00000000000..6f8e80e7d64
--- /dev/null
+++ b/changelogs/unreleased/feature-gb-manual-actions-protected-branches-permissions.yml
@@ -0,0 +1,4 @@
+---
+title: Implement protected manual actions
+merge_request: 10494
+author:
diff --git a/changelogs/unreleased/fix-admin-integrations.yml b/changelogs/unreleased/fix-admin-integrations.yml
new file mode 100644
index 00000000000..7689623501f
--- /dev/null
+++ b/changelogs/unreleased/fix-admin-integrations.yml
@@ -0,0 +1,4 @@
+---
+title: Fix new admin integrations not taking effect on existing projects
+merge_request:
+author:
diff --git a/changelogs/unreleased/fix-gb-hide-environment-external-url-btn-when-not-provided.yml b/changelogs/unreleased/fix-gb-hide-environment-external-url-btn-when-not-provided.yml
new file mode 100644
index 00000000000..66158e337fd
--- /dev/null
+++ b/changelogs/unreleased/fix-gb-hide-environment-external-url-btn-when-not-provided.yml
@@ -0,0 +1,4 @@
+---
+title: Hide external environment URL button on terminal page if URL is not defined
+merge_request: 11029
+author:
diff --git a/changelogs/unreleased/issue-title-description-realtime.yml b/changelogs/unreleased/issue-title-description-realtime.yml
new file mode 100644
index 00000000000..003e1a4ab33
--- /dev/null
+++ b/changelogs/unreleased/issue-title-description-realtime.yml
@@ -0,0 +1,4 @@
+---
+title: Add realtime descriptions to issue show pages
+merge_request:
+author:
diff --git a/changelogs/unreleased/winh-visual-token-labels.yml b/changelogs/unreleased/winh-visual-token-labels.yml
new file mode 100644
index 00000000000..d4952e910b4
--- /dev/null
+++ b/changelogs/unreleased/winh-visual-token-labels.yml
@@ -0,0 +1,4 @@
+---
+title: Colorize labels in search field
+merge_request: 11047
+author:
diff --git a/changelogs/unreleased/zj-real-time-pipelines.yml b/changelogs/unreleased/zj-real-time-pipelines.yml
new file mode 100644
index 00000000000..eec22e67467
--- /dev/null
+++ b/changelogs/unreleased/zj-real-time-pipelines.yml
@@ -0,0 +1,4 @@
+---
+title: Pipeline view updates in near real time
+merge_request: 10777
+author:
diff --git a/config/initializers/fast_gettext.rb b/config/initializers/fast_gettext.rb
index bea85b43b95..a69fe0c902e 100644
--- a/config/initializers/fast_gettext.rb
+++ b/config/initializers/fast_gettext.rb
@@ -1,4 +1,4 @@
-FastGettext.add_text_domain 'gitlab', path: 'locale', type: :po
+FastGettext.add_text_domain 'gitlab', path: File.join(Rails.root, 'locale'), type: :po
FastGettext.default_text_domain = 'gitlab'
FastGettext.default_available_locales = Gitlab::I18n.available_locales
diff --git a/config/routes/project.rb b/config/routes/project.rb
index 085f5a24e2e..68474a44368 100644
--- a/config/routes/project.rb
+++ b/config/routes/project.rb
@@ -123,6 +123,7 @@ constraints(ProjectUrlConstrainer.new) do
post :cancel
post :retry
get :builds
+ get :failures
get :status
end
end
diff --git a/config/sidekiq_queues.yml b/config/sidekiq_queues.yml
index c3bd73533d0..433381e79d3 100644
--- a/config/sidekiq_queues.yml
+++ b/config/sidekiq_queues.yml
@@ -53,3 +53,4 @@
- [pages, 1]
- [system_hook_push, 1]
- [update_user_activity, 1]
+ - [propagate_service_template, 1]
diff --git a/config/webpack.config.js b/config/webpack.config.js
index 3abdb6c2d76..119b1ea9d2e 100644
--- a/config/webpack.config.js
+++ b/config/webpack.config.js
@@ -17,6 +17,10 @@ var DEV_SERVER_LIVERELOAD = process.env.DEV_SERVER_LIVERELOAD !== 'false';
var WEBPACK_REPORT = process.env.WEBPACK_REPORT;
var config = {
+ // because sqljs requires fs.
+ node: {
+ fs: "empty"
+ },
context: path.join(ROOT_PATH, 'app/assets/javascripts'),
entry: {
blob: './blob_edit/blob_bundle.js',
@@ -34,8 +38,6 @@ var config = {
graphs: './graphs/graphs_bundle.js',
group: './group.js',
groups_list: './groups_list.js',
- issuable: './issuable/issuable_bundle.js',
- locale: './locale/index.js',
issue_show: './issue_show/index.js',
locale: './locale/index.js',
main: './main.js',
@@ -46,15 +48,18 @@ var config = {
notebook_viewer: './blob/notebook_viewer.js',
pdf_viewer: './blob/pdf_viewer.js',
pipelines: './pipelines/index.js',
+ balsamiq_viewer: './blob/balsamiq_viewer.js',
profile: './profile/profile_bundle.js',
protected_branches: './protected_branches/protected_branches_bundle.js',
protected_tags: './protected_tags',
+ sidebar: './sidebar/sidebar_bundle.js',
snippet: './snippet/snippet_bundle.js',
sketch_viewer: './blob/sketch_viewer.js',
stl_viewer: './blob/stl_viewer.js',
terminal: './terminal/terminal_bundle.js',
u2f: ['vendor/u2f'],
users: './users/users_bundle.js',
+ raven: './raven/index.js',
},
output: {
@@ -133,12 +138,13 @@ var config = {
'diff_notes',
'environments',
'environments_folder',
- 'issuable',
+ 'sidebar',
'issue_show',
'merge_conflicts',
'notebook_viewer',
'pdf_viewer',
'pipelines',
+ 'balsamiq_viewer',
],
minChunks: function(module, count) {
return module.resource && (/vue_shared/).test(module.resource);
diff --git a/db/fixtures/development/09_issues.rb b/db/fixtures/development/09_issues.rb
index d93d133d157..0b32a461d56 100644
--- a/db/fixtures/development/09_issues.rb
+++ b/db/fixtures/development/09_issues.rb
@@ -8,7 +8,7 @@ Gitlab::Seeder.quiet do
description: FFaker::Lorem.sentence,
state: ['opened', 'closed'].sample,
milestone: project.milestones.sample,
- assignee: project.team.users.sample
+ assignees: [project.team.users.sample]
}
Issues::CreateService.new(project, project.team.users.sample, issue_params).execute
diff --git a/db/migrate/20170320171632_create_issue_assignees_table.rb b/db/migrate/20170320171632_create_issue_assignees_table.rb
new file mode 100644
index 00000000000..23b8da37b6d
--- /dev/null
+++ b/db/migrate/20170320171632_create_issue_assignees_table.rb
@@ -0,0 +1,40 @@
+# See http://doc.gitlab.com/ce/development/migration_style_guide.html
+# for more information on how to write migrations for GitLab.
+
+class CreateIssueAssigneesTable < ActiveRecord::Migration
+ include Gitlab::Database::MigrationHelpers
+
+ INDEX_NAME = 'index_issue_assignees_on_issue_id_and_user_id'
+
+ # Set this constant to true if this migration requires downtime.
+ DOWNTIME = false
+
+ # When a migration requires downtime you **must** uncomment the following
+ # constant and define a short and easy to understand explanation as to why the
+ # migration requires downtime.
+ # DOWNTIME_REASON = ''
+
+ # When using the methods "add_concurrent_index" or "add_column_with_default"
+ # you must disable the use of transactions as these methods can not run in an
+ # existing transaction. When using "add_concurrent_index" make sure that this
+ # method is the _only_ method called in the migration, any other changes
+ # should go in a separate migration. This ensures that upon failure _only_ the
+ # index creation fails and can be retried or reverted easily.
+ #
+ # To disable transactions uncomment the following line and remove these
+ # comments:
+ # disable_ddl_transaction!
+
+ def up
+ create_table :issue_assignees do |t|
+ t.references :user, foreign_key: { on_delete: :cascade }, index: true, null: false
+ t.references :issue, foreign_key: { on_delete: :cascade }, null: false
+ end
+
+ add_index :issue_assignees, [:issue_id, :user_id], unique: true, name: INDEX_NAME
+ end
+
+ def down
+ drop_table :issue_assignees
+ end
+end
diff --git a/db/migrate/20170320173259_migrate_assignees.rb b/db/migrate/20170320173259_migrate_assignees.rb
new file mode 100644
index 00000000000..ba8edbd7d32
--- /dev/null
+++ b/db/migrate/20170320173259_migrate_assignees.rb
@@ -0,0 +1,52 @@
+# See http://doc.gitlab.com/ce/development/migration_style_guide.html
+# for more information on how to write migrations for GitLab.
+
+class MigrateAssignees < ActiveRecord::Migration
+ include Gitlab::Database::MigrationHelpers
+
+ # Set this constant to true if this migration requires downtime.
+ DOWNTIME = false
+
+ # When a migration requires downtime you **must** uncomment the following
+ # constant and define a short and easy to understand explanation as to why the
+ # migration requires downtime.
+ # DOWNTIME_REASON = ''
+
+ # When using the methods "add_concurrent_index" or "add_column_with_default"
+ # you must disable the use of transactions as these methods can not run in an
+ # existing transaction. When using "add_concurrent_index" make sure that this
+ # method is the _only_ method called in the migration, any other changes
+ # should go in a separate migration. This ensures that upon failure _only_ the
+ # index creation fails and can be retried or reverted easily.
+ #
+ # To disable transactions uncomment the following line and remove these
+ # comments:
+ disable_ddl_transaction!
+
+ def up
+ # Optimisation: this accounts for most of the invalid assignee IDs on GitLab.com
+ update_column_in_batches(:issues, :assignee_id, nil) do |table, query|
+ query.where(table[:assignee_id].eq(0))
+ end
+
+ users = Arel::Table.new(:users)
+
+ update_column_in_batches(:issues, :assignee_id, nil) do |table, query|
+ query.where(table[:assignee_id].not_eq(nil)\
+ .and(
+ users.project("true").where(users[:id].eq(table[:assignee_id])).exists.not
+ ))
+ end
+
+ execute <<-EOF
+ INSERT INTO issue_assignees(issue_id, user_id)
+ SELECT id, assignee_id FROM issues WHERE assignee_id IS NOT NULL
+ EOF
+ end
+
+ def down
+ execute <<-EOF
+ DELETE FROM issue_assignees
+ EOF
+ end
+end
diff --git a/db/migrate/20170427215854_create_redirect_routes.rb b/db/migrate/20170427215854_create_redirect_routes.rb
new file mode 100644
index 00000000000..2bf086b3e30
--- /dev/null
+++ b/db/migrate/20170427215854_create_redirect_routes.rb
@@ -0,0 +1,14 @@
+class CreateRedirectRoutes < ActiveRecord::Migration
+ # Set this constant to true if this migration requires downtime.
+ DOWNTIME = false
+
+ def change
+ create_table :redirect_routes do |t|
+ t.integer :source_id, null: false
+ t.string :source_type, null: false
+ t.string :path, null: false
+
+ t.timestamps null: false
+ end
+ end
+end
diff --git a/db/migrate/20170503021915_add_last_edited_at_and_last_edited_by_id_to_issues.rb b/db/migrate/20170503021915_add_last_edited_at_and_last_edited_by_id_to_issues.rb
new file mode 100644
index 00000000000..6ac10723c82
--- /dev/null
+++ b/db/migrate/20170503021915_add_last_edited_at_and_last_edited_by_id_to_issues.rb
@@ -0,0 +1,14 @@
+# See http://doc.gitlab.com/ce/development/migration_style_guide.html
+# for more information on how to write migrations for GitLab.
+
+class AddLastEditedAtAndLastEditedByIdToIssues < ActiveRecord::Migration
+ include Gitlab::Database::MigrationHelpers
+
+ # Set this constant to true if this migration requires downtime.
+ DOWNTIME = false
+
+ def change
+ add_column :issues, :last_edited_at, :timestamp
+ add_column :issues, :last_edited_by_id, :integer
+ end
+end
diff --git a/db/migrate/20170503022548_add_last_edited_at_and_last_edited_by_id_to_merge_requests.rb b/db/migrate/20170503022548_add_last_edited_at_and_last_edited_by_id_to_merge_requests.rb
new file mode 100644
index 00000000000..7a1acdcbf69
--- /dev/null
+++ b/db/migrate/20170503022548_add_last_edited_at_and_last_edited_by_id_to_merge_requests.rb
@@ -0,0 +1,14 @@
+# See http://doc.gitlab.com/ce/development/migration_style_guide.html
+# for more information on how to write migrations for GitLab.
+
+class AddLastEditedAtAndLastEditedByIdToMergeRequests < ActiveRecord::Migration
+ include Gitlab::Database::MigrationHelpers
+
+ # Set this constant to true if this migration requires downtime.
+ DOWNTIME = false
+
+ def change
+ add_column :merge_requests, :last_edited_at, :timestamp
+ add_column :merge_requests, :last_edited_by_id, :integer
+ end
+end
diff --git a/db/migrate/20170503184421_add_index_to_redirect_routes.rb b/db/migrate/20170503184421_add_index_to_redirect_routes.rb
new file mode 100644
index 00000000000..9062cf19a73
--- /dev/null
+++ b/db/migrate/20170503184421_add_index_to_redirect_routes.rb
@@ -0,0 +1,21 @@
+# See http://doc.gitlab.com/ce/development/migration_style_guide.html
+# for more information on how to write migrations for GitLab.
+
+class AddIndexToRedirectRoutes < ActiveRecord::Migration
+ include Gitlab::Database::MigrationHelpers
+
+ # Set this constant to true if this migration requires downtime.
+ DOWNTIME = false
+
+ disable_ddl_transaction!
+
+ def up
+ add_concurrent_index(:redirect_routes, :path, unique: true)
+ add_concurrent_index(:redirect_routes, [:source_type, :source_id])
+ end
+
+ def down
+ remove_concurrent_index(:redirect_routes, :path) if index_exists?(:redirect_routes, :path)
+ remove_concurrent_index(:redirect_routes, [:source_type, :source_id]) if index_exists?(:redirect_routes, [:source_type, :source_id])
+ end
+end
diff --git a/db/migrate/20170503185032_index_redirect_routes_path_for_like.rb b/db/migrate/20170503185032_index_redirect_routes_path_for_like.rb
new file mode 100644
index 00000000000..5b8b6c828be
--- /dev/null
+++ b/db/migrate/20170503185032_index_redirect_routes_path_for_like.rb
@@ -0,0 +1,29 @@
+# See http://doc.gitlab.com/ce/development/migration_style_guide.html
+# for more information on how to write migrations for GitLab.
+
+class IndexRedirectRoutesPathForLike < ActiveRecord::Migration
+ include Gitlab::Database::MigrationHelpers
+
+ # Set this constant to true if this migration requires downtime.
+ DOWNTIME = false
+
+ INDEX_NAME = 'index_redirect_routes_on_path_text_pattern_ops'
+
+ disable_ddl_transaction!
+
+ def up
+ return unless Gitlab::Database.postgresql?
+
+ unless index_exists?(:redirect_routes, :path, name: INDEX_NAME)
+ execute("CREATE INDEX CONCURRENTLY #{INDEX_NAME} ON redirect_routes (path varchar_pattern_ops);")
+ end
+ end
+
+ def down
+ return unless Gitlab::Database.postgresql?
+
+ if index_exists?(:redirect_routes, :path, name: INDEX_NAME)
+ execute("DROP INDEX CONCURRENTLY #{INDEX_NAME};")
+ end
+ end
+end
diff --git a/db/migrate/20170504102911_add_clientside_sentry_to_application_settings.rb b/db/migrate/20170504102911_add_clientside_sentry_to_application_settings.rb
new file mode 100644
index 00000000000..141112f8b50
--- /dev/null
+++ b/db/migrate/20170504102911_add_clientside_sentry_to_application_settings.rb
@@ -0,0 +1,33 @@
+# See http://doc.gitlab.com/ce/development/migration_style_guide.html
+# for more information on how to write migrations for GitLab.
+
+class AddClientsideSentryToApplicationSettings < ActiveRecord::Migration
+ include Gitlab::Database::MigrationHelpers
+
+ # Set this constant to true if this migration requires downtime.
+ DOWNTIME = false
+
+ # When a migration requires downtime you **must** uncomment the following
+ # constant and define a short and easy to understand explanation as to why the
+ # migration requires downtime.
+ # DOWNTIME_REASON = ''
+
+ # When using "add_concurrent_index" or "remove_concurrent_index" methods make sure
+ # that either of them is the _only_ method called in the migration,
+ # any other changes should go in a separate migration.
+ # This ensures that upon failure _only_ the index creation or removing fails
+ # and can be retried or reverted easily.
+ #
+ # To disable transactions uncomment the following line and remove these
+ # comments:
+ disable_ddl_transaction!
+
+ def up
+ add_column_with_default :application_settings, :clientside_sentry_enabled, :boolean, default: false
+ add_column :application_settings, :clientside_sentry_dsn, :string
+ end
+
+ def down
+ remove_columns :application_settings, :clientside_sentry_enabled, :clientside_sentry_dsn
+ end
+end
diff --git a/db/schema.rb b/db/schema.rb
index 132549ab34c..61af066ed3b 100644
--- a/db/schema.rb
+++ b/db/schema.rb
@@ -11,7 +11,7 @@
#
# It's strongly recommended that you check this file into your version control system.
-ActiveRecord::Schema.define(version: 20170503004425) do
+ActiveRecord::Schema.define(version: 20170504102911) do
# These are extensions that must be enabled in order to support this database
enable_extension "plpgsql"
@@ -121,6 +121,8 @@ ActiveRecord::Schema.define(version: 20170503004425) do
t.integer "cached_markdown_version"
t.boolean "usage_ping_enabled", default: true, null: false
t.string "uuid"
+ t.boolean "clientside_sentry_enabled", default: false, null: false
+ t.string "clientside_sentry_dsn"
end
create_table "audit_events", force: :cascade do |t|
@@ -452,6 +454,14 @@ ActiveRecord::Schema.define(version: 20170503004425) do
add_index "identities", ["user_id"], name: "index_identities_on_user_id", using: :btree
+ create_table "issue_assignees", force: :cascade do |t|
+ t.integer "user_id", null: false
+ t.integer "issue_id", null: false
+ end
+
+ add_index "issue_assignees", ["issue_id", "user_id"], name: "index_issue_assignees_on_issue_id_and_user_id", unique: true, using: :btree
+ add_index "issue_assignees", ["user_id"], name: "index_issue_assignees_on_user_id", using: :btree
+
create_table "issue_metrics", force: :cascade do |t|
t.integer "issue_id", null: false
t.datetime "first_mentioned_in_commit_at"
@@ -488,6 +498,8 @@ ActiveRecord::Schema.define(version: 20170503004425) do
t.integer "relative_position"
t.datetime "closed_at"
t.integer "cached_markdown_version"
+ t.datetime "last_edited_at"
+ t.integer "last_edited_by_id"
end
add_index "issues", ["assignee_id"], name: "index_issues_on_assignee_id", using: :btree
@@ -674,6 +686,8 @@ ActiveRecord::Schema.define(version: 20170503004425) do
t.text "description_html"
t.integer "time_estimate"
t.integer "cached_markdown_version"
+ t.datetime "last_edited_at"
+ t.integer "last_edited_by_id"
end
add_index "merge_requests", ["assignee_id"], name: "index_merge_requests_on_assignee_id", using: :btree
@@ -1038,6 +1052,18 @@ ActiveRecord::Schema.define(version: 20170503004425) do
add_index "protected_tags", ["project_id"], name: "index_protected_tags_on_project_id", using: :btree
+ create_table "redirect_routes", force: :cascade do |t|
+ t.integer "source_id", null: false
+ t.string "source_type", null: false
+ t.string "path", null: false
+ t.datetime "created_at", null: false
+ t.datetime "updated_at", null: false
+ end
+
+ add_index "redirect_routes", ["path"], name: "index_redirect_routes_on_path", unique: true, using: :btree
+ add_index "redirect_routes", ["path"], name: "index_redirect_routes_on_path_text_pattern_ops", using: :btree, opclasses: {"path"=>"varchar_pattern_ops"}
+ add_index "redirect_routes", ["source_type", "source_id"], name: "index_redirect_routes_on_source_type_and_source_id", using: :btree
+
create_table "releases", force: :cascade do |t|
t.string "tag"
t.text "description"
@@ -1386,6 +1412,8 @@ ActiveRecord::Schema.define(version: 20170503004425) do
add_foreign_key "ci_trigger_requests", "ci_triggers", column: "trigger_id", name: "fk_b8ec8b7245", on_delete: :cascade
add_foreign_key "ci_trigger_schedules", "ci_triggers", column: "trigger_id", name: "fk_90a406cc94", on_delete: :cascade
add_foreign_key "ci_triggers", "users", column: "owner_id", name: "fk_e8e10d1964", on_delete: :cascade
+ add_foreign_key "issue_assignees", "issues", on_delete: :cascade
+ add_foreign_key "issue_assignees", "users", on_delete: :cascade
add_foreign_key "container_repositories", "projects"
add_foreign_key "issue_metrics", "issues", on_delete: :cascade
add_foreign_key "label_priorities", "labels", on_delete: :cascade
diff --git a/doc/api/issues.md b/doc/api/issues.md
index 6c10b5ab0e7..1d43b1298b9 100644
--- a/doc/api/issues.md
+++ b/doc/api/issues.md
@@ -70,6 +70,14 @@ Example response:
"updated_at" : "2016-01-04T15:31:39.996Z"
},
"project_id" : 1,
+ "assignees" : [{
+ "state" : "active",
+ "id" : 1,
+ "name" : "Administrator",
+ "web_url" : "https://gitlab.example.com/root",
+ "avatar_url" : null,
+ "username" : "root"
+ }],
"assignee" : {
"state" : "active",
"id" : 1,
@@ -92,6 +100,8 @@ Example response:
]
```
+**Note**: `assignee` column is deprecated, it shows the first assignee only.
+
## List group issues
Get a list of a group's issues.
@@ -153,6 +163,14 @@ Example response:
"description" : "Omnis vero earum sunt corporis dolor et placeat.",
"state" : "closed",
"iid" : 1,
+ "assignees" : [{
+ "avatar_url" : null,
+ "web_url" : "https://gitlab.example.com/lennie",
+ "state" : "active",
+ "username" : "lennie",
+ "id" : 9,
+ "name" : "Dr. Luella Kovacek"
+ }],
"assignee" : {
"avatar_url" : null,
"web_url" : "https://gitlab.example.com/lennie",
@@ -174,6 +192,8 @@ Example response:
]
```
+**Note**: `assignee` column is deprecated, it shows the first assignee only.
+
## List project issues
Get a list of a project's issues.
@@ -235,6 +255,14 @@ Example response:
"description" : "Omnis vero earum sunt corporis dolor et placeat.",
"state" : "closed",
"iid" : 1,
+ "assignees" : [{
+ "avatar_url" : null,
+ "web_url" : "https://gitlab.example.com/lennie",
+ "state" : "active",
+ "username" : "lennie",
+ "id" : 9,
+ "name" : "Dr. Luella Kovacek"
+ }],
"assignee" : {
"avatar_url" : null,
"web_url" : "https://gitlab.example.com/lennie",
@@ -256,6 +284,8 @@ Example response:
]
```
+**Note**: `assignee` column is deprecated, it shows the first assignee only.
+
## Single issue
Get a single project issue.
@@ -300,6 +330,14 @@ Example response:
"description" : "Omnis vero earum sunt corporis dolor et placeat.",
"state" : "closed",
"iid" : 1,
+ "assignees" : [{
+ "avatar_url" : null,
+ "web_url" : "https://gitlab.example.com/lennie",
+ "state" : "active",
+ "username" : "lennie",
+ "id" : 9,
+ "name" : "Dr. Luella Kovacek"
+ }],
"assignee" : {
"avatar_url" : null,
"web_url" : "https://gitlab.example.com/lennie",
@@ -321,6 +359,8 @@ Example response:
}
```
+**Note**: `assignee` column is deprecated, it shows the first assignee only.
+
## New issue
Creates a new project issue.
@@ -329,13 +369,13 @@ Creates a new project issue.
POST /projects/:id/issues
```
-| Attribute | Type | Required | Description |
-|-------------------------------------------|---------|----------|--------------|
+| Attribute | Type | Required | Description |
+|-------------------------------------------|----------------|----------|--------------|
| `id` | integer/string | yes | The ID or [URL-encoded path of the project](README.md#namespaced-path-encoding) owned by the authenticated user |
| `title` | string | yes | The title of an issue |
| `description` | string | no | The description of an issue |
| `confidential` | boolean | no | Set an issue to be confidential. Default is `false`. |
-| `assignee_id` | integer | no | The ID of a user to assign issue |
+| `assignee_ids` | Array[integer] | no | The ID of a user to assign issue |
| `milestone_id` | integer | no | The ID of a milestone to assign issue |
| `labels` | string | no | Comma-separated label names for an issue |
| `created_at` | string | no | Date time string, ISO 8601 formatted, e.g. `2016-03-11T03:45:40Z` (requires admin or project owner rights) |
@@ -357,6 +397,7 @@ Example response:
"iid" : 14,
"title" : "Issues with auth",
"state" : "opened",
+ "assignees" : [],
"assignee" : null,
"labels" : [
"bug"
@@ -380,6 +421,8 @@ Example response:
}
```
+**Note**: `assignee` column is deprecated, it shows the first assignee only.
+
## Edit issue
Updates an existing project issue. This call is also used to mark an issue as
@@ -396,7 +439,7 @@ PUT /projects/:id/issues/:issue_iid
| `title` | string | no | The title of an issue |
| `description` | string | no | The description of an issue |
| `confidential` | boolean | no | Updates an issue to be confidential |
-| `assignee_id` | integer | no | The ID of a user to assign the issue to |
+| `assignee_ids` | Array[integer] | no | The ID of a user to assign the issue to |
| `milestone_id` | integer | no | The ID of a milestone to assign the issue to |
| `labels` | string | no | Comma-separated label names for an issue |
| `state_event` | string | no | The state event of an issue. Set `close` to close the issue and `reopen` to reopen it |
@@ -430,6 +473,7 @@ Example response:
"bug"
],
"id" : 85,
+ "assignees" : [],
"assignee" : null,
"milestone" : null,
"subscribed" : true,
@@ -440,6 +484,8 @@ Example response:
}
```
+**Note**: `assignee` column is deprecated, it shows the first assignee only.
+
## Delete an issue
Only for admins and project owners. Soft deletes the issue in question.
@@ -494,6 +540,14 @@ Example response:
"updated_at": "2016-04-07T12:20:17.596Z",
"labels": [],
"milestone": null,
+ "assignees": [{
+ "name": "Miss Monserrate Beier",
+ "username": "axel.block",
+ "id": 12,
+ "state": "active",
+ "avatar_url": "http://www.gravatar.com/avatar/46f6f7dc858ada7be1853f7fb96e81da?s=80&d=identicon",
+ "web_url": "https://gitlab.example.com/axel.block"
+ }],
"assignee": {
"name": "Miss Monserrate Beier",
"username": "axel.block",
@@ -516,6 +570,8 @@ Example response:
}
```
+**Note**: `assignee` column is deprecated, it shows the first assignee only.
+
## Subscribe to an issue
Subscribes the authenticated user to an issue to receive notifications.
@@ -549,6 +605,14 @@ Example response:
"updated_at": "2016-04-07T12:20:17.596Z",
"labels": [],
"milestone": null,
+ "assignees": [{
+ "name": "Miss Monserrate Beier",
+ "username": "axel.block",
+ "id": 12,
+ "state": "active",
+ "avatar_url": "http://www.gravatar.com/avatar/46f6f7dc858ada7be1853f7fb96e81da?s=80&d=identicon",
+ "web_url": "https://gitlab.example.com/axel.block"
+ }],
"assignee": {
"name": "Miss Monserrate Beier",
"username": "axel.block",
@@ -571,6 +635,8 @@ Example response:
}
```
+**Note**: `assignee` column is deprecated, it shows the first assignee only.
+
## Unsubscribe from an issue
Unsubscribes the authenticated user from the issue to not receive notifications
@@ -652,6 +718,14 @@ Example response:
"updated_at": "2016-06-17T07:47:33.832Z",
"due_date": null
},
+ "assignees": [{
+ "name": "Jarret O'Keefe",
+ "username": "francisca",
+ "id": 14,
+ "state": "active",
+ "avatar_url": "http://www.gravatar.com/avatar/a7fa515d53450023c83d62986d0658a8?s=80&d=identicon",
+ "web_url": "https://gitlab.example.com/francisca"
+ }],
"assignee": {
"name": "Jarret O'Keefe",
"username": "francisca",
@@ -683,6 +757,8 @@ Example response:
}
```
+**Note**: `assignee` column is deprecated, it shows the first assignee only.
+
## Set a time estimate for an issue
Sets an estimated time of work for this issue.
diff --git a/doc/ci/yaml/README.md b/doc/ci/yaml/README.md
index ad3ebd144df..16308a957cb 100644
--- a/doc/ci/yaml/README.md
+++ b/doc/ci/yaml/README.md
@@ -553,6 +553,8 @@ The above script will:
#### Manual actions
> Introduced in GitLab 8.10.
+> Blocking manual actions were introduced in GitLab 9.0
+> Protected actions were introduced in GitLab 9.2
Manual actions are a special type of job that are not executed automatically;
they need to be explicitly started by a user. Manual actions can be started
@@ -578,7 +580,10 @@ Optional manual actions have `allow_failure: true` set by default.
**Statuses of optional actions do not contribute to overall pipeline status.**
-> Blocking manual actions were introduced in GitLab 9.0
+**Manual actions are considered to be write actions, so permissions for
+protected branches are used when user wants to trigger an action. In other
+words, in order to trigger a manual action assigned to a branch that the
+pipeline is running for, user needs to have ability to push to this branch.**
### environment
diff --git a/doc/development/fe_guide/droplab/droplab.md b/doc/development/fe_guide/droplab/droplab.md
index 8f0b6b21953..112ff3419d9 100644
--- a/doc/development/fe_guide/droplab/droplab.md
+++ b/doc/development/fe_guide/droplab/droplab.md
@@ -183,6 +183,8 @@ For example,
either by a mouse click or by enter key selection.
* The `droplab-item-active` css class is added to items that have been selected
using arrow key navigation.
+* You can add the `droplab-item-ignore` css class to any item that you do not want to be selectable. For example,
+an `<li class="divider"></li>` list divider element that should not be interactive.
## Internal events
diff --git a/doc/user/project/integrations/webhooks.md b/doc/user/project/integrations/webhooks.md
index dbdc93a77a8..e15daa2feae 100644
--- a/doc/user/project/integrations/webhooks.md
+++ b/doc/user/project/integrations/webhooks.md
@@ -232,6 +232,7 @@ X-Gitlab-Event: Issue Hook
"object_attributes": {
"id": 301,
"title": "New API: create/update/delete file",
+ "assignee_ids": [51],
"assignee_id": 51,
"author_id": 51,
"project_id": 14,
@@ -246,6 +247,11 @@ X-Gitlab-Event: Issue Hook
"url": "http://example.com/diaspora/issues/23",
"action": "open"
},
+ "assignees": [{
+ "name": "User1",
+ "username": "user1",
+ "avatar_url": "http://www.gravatar.com/avatar/e64c7d89f26bd1972efa854d13d7dd61?s=40\u0026d=identicon"
+ }],
"assignee": {
"name": "User1",
"username": "user1",
@@ -265,6 +271,9 @@ X-Gitlab-Event: Issue Hook
}]
}
```
+
+**Note**: `assignee` and `assignee_id` keys are deprecated and now show the first assignee only.
+
### Comment events
Triggered when a new comment is made on commits, merge requests, issues, and code snippets.
@@ -544,6 +553,7 @@ X-Gitlab-Event: Note Hook
"issue": {
"id": 92,
"title": "test",
+ "assignee_ids": [],
"assignee_id": null,
"author_id": 1,
"project_id": 5,
@@ -559,6 +569,8 @@ X-Gitlab-Event: Note Hook
}
```
+**Note**: `assignee_id` field is deprecated and now shows the first assignee only.
+
#### Comment on code snippet
**Request header**:
diff --git a/features/project/issues/issues.feature b/features/project/issues/issues.feature
index 4dee0cd23dc..1b00d8a32a0 100644
--- a/features/project/issues/issues.feature
+++ b/features/project/issues/issues.feature
@@ -82,6 +82,7 @@ Feature: Project Issues
# Markdown
+ @javascript
Scenario: Headers inside the description should have ids generated for them.
Given I visit issue page "Release 0.4"
Then Header "Description header" should have correct id and link
diff --git a/features/steps/dashboard/dashboard.rb b/features/steps/dashboard/dashboard.rb
index c715c85c43c..bf09d7b7114 100644
--- a/features/steps/dashboard/dashboard.rb
+++ b/features/steps/dashboard/dashboard.rb
@@ -77,7 +77,7 @@ class Spinach::Features::Dashboard < Spinach::FeatureSteps
step 'project "Shop" has issue "Bugfix1" with label "feature"' do
project = Project.find_by(name: "Shop")
- issue = create(:issue, title: "Bugfix1", project: project, assignee: current_user)
+ issue = create(:issue, title: "Bugfix1", project: project, assignees: [current_user])
issue.labels << project.labels.find_by(title: 'feature')
end
end
diff --git a/features/steps/dashboard/todos.rb b/features/steps/dashboard/todos.rb
index 3225e19995b..b56558ba0d2 100644
--- a/features/steps/dashboard/todos.rb
+++ b/features/steps/dashboard/todos.rb
@@ -182,7 +182,7 @@ class Spinach::Features::DashboardTodos < Spinach::FeatureSteps
end
def issue
- @issue ||= create(:issue, assignee: current_user, project: project)
+ @issue ||= create(:issue, assignees: [current_user], project: project)
end
def merge_request
diff --git a/features/steps/group/milestones.rb b/features/steps/group/milestones.rb
index 49fcd6f1201..0b0983f0d06 100644
--- a/features/steps/group/milestones.rb
+++ b/features/steps/group/milestones.rb
@@ -113,7 +113,7 @@ class Spinach::Features::GroupMilestones < Spinach::FeatureSteps
create :issue,
project: project,
- assignee: current_user,
+ assignees: [current_user],
author: current_user,
milestone: milestone
@@ -125,7 +125,7 @@ class Spinach::Features::GroupMilestones < Spinach::FeatureSteps
issue = create :issue,
project: project,
- assignee: current_user,
+ assignees: [current_user],
author: current_user,
milestone: milestone
diff --git a/features/steps/groups.rb b/features/steps/groups.rb
index 4dc87dc4d9c..83d8abbab1f 100644
--- a/features/steps/groups.rb
+++ b/features/steps/groups.rb
@@ -61,7 +61,7 @@ class Spinach::Features::Groups < Spinach::FeatureSteps
step 'project from group "Owned" has issues assigned to me' do
create :issue,
project: project,
- assignee: current_user,
+ assignees: [current_user],
author: current_user
end
@@ -123,7 +123,7 @@ class Spinach::Features::Groups < Spinach::FeatureSteps
step 'the archived project have some issues' do
create :issue,
project: @archived_project,
- assignee: current_user,
+ assignees: [current_user],
author: current_user
end
diff --git a/lib/api/api.rb b/lib/api/api.rb
index 302ccd3e532..52cd7cbe3db 100644
--- a/lib/api/api.rb
+++ b/lib/api/api.rb
@@ -6,6 +6,7 @@ module API
version 'v3', using: :path do
helpers ::API::V3::Helpers
+ helpers ::API::Helpers::CommonHelpers
mount ::API::V3::AwardEmoji
mount ::API::V3::Boards
@@ -80,6 +81,7 @@ module API
# Ensure the namespace is right, otherwise we might load Grape::API::Helpers
helpers ::SentryHelper
helpers ::API::Helpers
+ helpers ::API::Helpers::CommonHelpers
# Keep in alphabetical order
mount ::API::AccessRequests
diff --git a/lib/api/entities.rb b/lib/api/entities.rb
index 6d6ccefe877..f8f5548d23d 100644
--- a/lib/api/entities.rb
+++ b/lib/api/entities.rb
@@ -256,7 +256,11 @@ module API
class IssueBasic < ProjectEntity
expose :label_names, as: :labels
expose :milestone, using: Entities::Milestone
- expose :assignee, :author, using: Entities::UserBasic
+ expose :assignees, :author, using: Entities::UserBasic
+
+ expose :assignee, using: ::API::Entities::UserBasic do |issue, options|
+ issue.assignees.first
+ end
expose :user_notes_count
expose :upvotes, :downvotes
diff --git a/lib/api/helpers/common_helpers.rb b/lib/api/helpers/common_helpers.rb
new file mode 100644
index 00000000000..6236fdd43ca
--- /dev/null
+++ b/lib/api/helpers/common_helpers.rb
@@ -0,0 +1,13 @@
+module API
+ module Helpers
+ module CommonHelpers
+ def convert_parameters_from_legacy_format(params)
+ if params[:assignee_id].present?
+ params[:assignee_ids] = [params.delete(:assignee_id)]
+ end
+
+ params
+ end
+ end
+ end
+end
diff --git a/lib/api/helpers/internal_helpers.rb b/lib/api/helpers/internal_helpers.rb
index 718f936a1fc..264df7271a3 100644
--- a/lib/api/helpers/internal_helpers.rb
+++ b/lib/api/helpers/internal_helpers.rb
@@ -1,48 +1,14 @@
module API
module Helpers
module InternalHelpers
- # Project paths may be any of the following:
- # * /repository/storage/path/namespace/project
- # * /namespace/project
- # * namespace/project
- #
- # In addition, they may have a '.git' extension and multiple namespaces
- #
- # Transform all these cases to 'namespace/project'
- def clean_project_path(project_path, storages = Gitlab.config.repositories.storages.values)
- project_path = project_path.sub(/\.git\z/, '')
-
- storages.each do |storage|
- storage_path = File.expand_path(storage['path'])
-
- if project_path.start_with?(storage_path)
- project_path = project_path.sub(storage_path, '')
- break
- end
- end
-
- project_path.sub(/\A\//, '')
- end
-
- def project_path
- @project_path ||= clean_project_path(params[:project])
- end
-
def wiki?
- @wiki ||= project_path.end_with?('.wiki') &&
- !Project.find_by_full_path(project_path)
+ set_project unless defined?(@wiki)
+ @wiki
end
def project
- @project ||= begin
- # Check for *.wiki repositories.
- # Strip out the .wiki from the pathname before finding the
- # project. This applies the correct project permissions to
- # the wiki repository as well.
- project_path.chomp!('.wiki') if wiki?
-
- Project.find_by_full_path(project_path)
- end
+ set_project unless defined?(@project)
+ @project
end
def ssh_authentication_abilities
@@ -66,6 +32,16 @@ module API
::Users::ActivityService.new(actor, 'Git SSH').execute if commands.include?(params[:action])
end
+
+ private
+
+ def set_project
+ if params[:gl_repository]
+ @project, @wiki = Gitlab::GlRepository.parse(params[:gl_repository])
+ else
+ @project, @wiki = Gitlab::RepoPath.parse(params[:project])
+ end
+ end
end
end
end
diff --git a/lib/api/internal.rb b/lib/api/internal.rb
index ebed26dd178..2a11790b215 100644
--- a/lib/api/internal.rb
+++ b/lib/api/internal.rb
@@ -42,6 +42,10 @@ module API
if access_status.status
log_user_activity(actor)
+ # Project id to pass between components that don't share/don't have
+ # access to the same filesystem mounts
+ response[:gl_repository] = Gitlab::GlRepository.gl_repository(project, wiki?)
+
# Return the repository full path so that gitlab-shell has it when
# handling ssh commands
response[:repository_path] =
@@ -134,11 +138,9 @@ module API
return unless Gitlab::GitalyClient.enabled?
- relative_path = Gitlab::RepoPath.strip_storage_path(params[:repo_path])
- project = Project.find_by_full_path(relative_path.sub(/\.(git|wiki)\z/, ''))
-
begin
- Gitlab::GitalyClient::Notifications.new(project.repository).post_receive
+ repository = wiki? ? project.wiki.repository : project.repository
+ Gitlab::GitalyClient::Notifications.new(repository.raw_repository).post_receive
rescue GRPC::Unavailable => e
render_api_error!(e, 500)
end
diff --git a/lib/api/issues.rb b/lib/api/issues.rb
index 522f0f3be92..78db960ae28 100644
--- a/lib/api/issues.rb
+++ b/lib/api/issues.rb
@@ -32,7 +32,8 @@ module API
params :issue_params_ce do
optional :description, type: String, desc: 'The description of an issue'
- optional :assignee_id, type: Integer, desc: 'The ID of a user to assign issue'
+ optional :assignee_ids, type: Array[Integer], desc: 'The array of user IDs to assign issue'
+ optional :assignee_id, type: Integer, desc: '[Deprecated] The ID of a user to assign issue'
optional :milestone_id, type: Integer, desc: 'The ID of a milestone to assign issue'
optional :labels, type: String, desc: 'Comma-separated list of label names'
optional :due_date, type: String, desc: 'Date string in the format YEAR-MONTH-DAY'
@@ -135,6 +136,8 @@ module API
issue_params = declared_params(include_missing: false)
+ issue_params = convert_parameters_from_legacy_format(issue_params)
+
issue = ::Issues::CreateService.new(user_project,
current_user,
issue_params.merge(request: request, api: true)).execute
@@ -159,7 +162,7 @@ module API
desc: 'Date time when the issue was updated. Available only for admins and project owners.'
optional :state_event, type: String, values: %w[reopen close], desc: 'State of the issue'
use :issue_params
- at_least_one_of :title, :description, :assignee_id, :milestone_id,
+ at_least_one_of :title, :description, :assignee_ids, :assignee_id, :milestone_id,
:labels, :created_at, :due_date, :confidential, :state_event
end
put ':id/issues/:issue_iid' do
@@ -173,6 +176,8 @@ module API
update_params = declared_params(include_missing: false).merge(request: request, api: true)
+ update_params = convert_parameters_from_legacy_format(update_params)
+
issue = ::Issues::UpdateService.new(user_project,
current_user,
update_params).execute(issue)
diff --git a/lib/api/jobs.rb b/lib/api/jobs.rb
index 288b03d940c..0223957fde1 100644
--- a/lib/api/jobs.rb
+++ b/lib/api/jobs.rb
@@ -132,6 +132,7 @@ module API
authorize_update_builds!
build = get_build!(params[:job_id])
+ authorize!(:update_build, build)
build.cancel
@@ -148,6 +149,7 @@ module API
authorize_update_builds!
build = get_build!(params[:job_id])
+ authorize!(:update_build, build)
return forbidden!('Job is not retryable') unless build.retryable?
build = Ci::Build.retry(build, current_user)
@@ -165,6 +167,7 @@ module API
authorize_update_builds!
build = get_build!(params[:job_id])
+ authorize!(:update_build, build)
return forbidden!('Job is not erasable!') unless build.erasable?
build.erase(erased_by: current_user)
@@ -181,6 +184,7 @@ module API
authorize_update_builds!
build = get_build!(params[:job_id])
+ authorize!(:update_build, build)
return not_found!(build) unless build.artifacts?
build.keep_artifacts!
@@ -201,6 +205,7 @@ module API
build = get_build!(params[:job_id])
+ authorize!(:update_build, build)
bad_request!("Unplayable Job") unless build.playable?
build.play(current_user)
@@ -211,12 +216,12 @@ module API
end
helpers do
- def get_build(id)
+ def find_build(id)
user_project.builds.find_by(id: id.to_i)
end
def get_build!(id)
- get_build(id) || not_found!
+ find_build(id) || not_found!
end
def present_artifacts!(artifacts_file)
diff --git a/lib/api/settings.rb b/lib/api/settings.rb
index d01c7f2703b..82f513c984e 100644
--- a/lib/api/settings.rb
+++ b/lib/api/settings.rb
@@ -58,6 +58,7 @@ module API
:restricted_visibility_levels,
:send_user_confirmation_email,
:sentry_enabled,
+ :clientside_sentry_enabled,
:session_expire_delay,
:shared_runners_enabled,
:sidekiq_throttling_enabled,
@@ -138,6 +139,10 @@ module API
given sentry_enabled: ->(val) { val } do
requires :sentry_dsn, type: String, desc: 'Sentry Data Source Name'
end
+ optional :clientside_sentry_enabled, type: Boolean, desc: 'Sentry can also be used for reporting and logging clientside exceptions. https://sentry.io/for/javascript/'
+ given clientside_sentry_enabled: ->(val) { val } do
+ requires :clientside_sentry_dsn, type: String, desc: 'Clientside Sentry Data Source Name'
+ end
optional :repository_storage, type: String, desc: 'Storage paths for new projects'
optional :repository_checks_enabled, type: Boolean, desc: "GitLab will periodically run 'git fsck' in all project and wiki repositories to look for silent disk corruption issues."
optional :koding_enabled, type: Boolean, desc: 'Enable Koding'
diff --git a/lib/api/v3/builds.rb b/lib/api/v3/builds.rb
index 4dd03cdf24b..21935922414 100644
--- a/lib/api/v3/builds.rb
+++ b/lib/api/v3/builds.rb
@@ -134,6 +134,7 @@ module API
authorize_update_builds!
build = get_build!(params[:build_id])
+ authorize!(:update_build, build)
build.cancel
@@ -150,6 +151,7 @@ module API
authorize_update_builds!
build = get_build!(params[:build_id])
+ authorize!(:update_build, build)
return forbidden!('Build is not retryable') unless build.retryable?
build = Ci::Build.retry(build, current_user)
@@ -167,6 +169,7 @@ module API
authorize_update_builds!
build = get_build!(params[:build_id])
+ authorize!(:update_build, build)
return forbidden!('Build is not erasable!') unless build.erasable?
build.erase(erased_by: current_user)
@@ -183,6 +186,7 @@ module API
authorize_update_builds!
build = get_build!(params[:build_id])
+ authorize!(:update_build, build)
return not_found!(build) unless build.artifacts?
build.keep_artifacts!
@@ -202,7 +206,7 @@ module API
authorize_read_builds!
build = get_build!(params[:build_id])
-
+ authorize!(:update_build, build)
bad_request!("Unplayable Job") unless build.playable?
build.play(current_user)
@@ -213,12 +217,12 @@ module API
end
helpers do
- def get_build(id)
+ def find_build(id)
user_project.builds.find_by(id: id.to_i)
end
def get_build!(id)
- get_build(id) || not_found!
+ find_build(id) || not_found!
end
def present_artifacts!(artifacts_file)
diff --git a/lib/api/v3/entities.rb b/lib/api/v3/entities.rb
index 832b4bdeb4f..7c8be7e51db 100644
--- a/lib/api/v3/entities.rb
+++ b/lib/api/v3/entities.rb
@@ -248,6 +248,13 @@ module API
expose :project_id, :issues_events, :merge_requests_events
expose :note_events, :build_events, :pipeline_events, :wiki_page_events
end
+
+ class Issue < ::API::Entities::Issue
+ unexpose :assignees
+ expose :assignee do |issue, options|
+ ::API::Entities::UserBasic.represent(issue.assignees.first, options)
+ end
+ end
end
end
end
diff --git a/lib/api/v3/issues.rb b/lib/api/v3/issues.rb
index 715083fc4f8..cb371fdbab8 100644
--- a/lib/api/v3/issues.rb
+++ b/lib/api/v3/issues.rb
@@ -8,6 +8,7 @@ module API
helpers do
def find_issues(args = {})
args = params.merge(args)
+ args = convert_parameters_from_legacy_format(args)
args.delete(:id)
args[:milestone_title] = args.delete(:milestone)
@@ -51,7 +52,7 @@ module API
resource :issues do
desc "Get currently authenticated user's issues" do
- success ::API::Entities::Issue
+ success ::API::V3::Entities::Issue
end
params do
optional :state, type: String, values: %w[opened closed all], default: 'all',
@@ -61,7 +62,7 @@ module API
get do
issues = find_issues(scope: 'authored')
- present paginate(issues), with: ::API::Entities::Issue, current_user: current_user
+ present paginate(issues), with: ::API::V3::Entities::Issue, current_user: current_user
end
end
@@ -70,7 +71,7 @@ module API
end
resource :groups, requirements: { id: %r{[^/]+} } do
desc 'Get a list of group issues' do
- success ::API::Entities::Issue
+ success ::API::V3::Entities::Issue
end
params do
optional :state, type: String, values: %w[opened closed all], default: 'all',
@@ -82,7 +83,7 @@ module API
issues = find_issues(group_id: group.id, match_all_labels: true)
- present paginate(issues), with: ::API::Entities::Issue, current_user: current_user
+ present paginate(issues), with: ::API::V3::Entities::Issue, current_user: current_user
end
end
@@ -94,7 +95,7 @@ module API
desc 'Get a list of project issues' do
detail 'iid filter is deprecated have been removed on V4'
- success ::API::Entities::Issue
+ success ::API::V3::Entities::Issue
end
params do
optional :state, type: String, values: %w[opened closed all], default: 'all',
@@ -107,22 +108,22 @@ module API
issues = find_issues(project_id: project.id)
- present paginate(issues), with: ::API::Entities::Issue, current_user: current_user, project: user_project
+ present paginate(issues), with: ::API::V3::Entities::Issue, current_user: current_user, project: user_project
end
desc 'Get a single project issue' do
- success ::API::Entities::Issue
+ success ::API::V3::Entities::Issue
end
params do
requires :issue_id, type: Integer, desc: 'The ID of a project issue'
end
get ":id/issues/:issue_id" do
issue = find_project_issue(params[:issue_id])
- present issue, with: ::API::Entities::Issue, current_user: current_user, project: user_project
+ present issue, with: ::API::V3::Entities::Issue, current_user: current_user, project: user_project
end
desc 'Create a new project issue' do
- success ::API::Entities::Issue
+ success ::API::V3::Entities::Issue
end
params do
requires :title, type: String, desc: 'The title of an issue'
@@ -140,6 +141,7 @@ module API
issue_params = declared_params(include_missing: false)
issue_params = issue_params.merge(merge_request_to_resolve_discussions_of: issue_params.delete(:merge_request_for_resolving_discussions))
+ issue_params = convert_parameters_from_legacy_format(issue_params)
issue = ::Issues::CreateService.new(user_project,
current_user,
@@ -147,14 +149,14 @@ module API
render_spam_error! if issue.spam?
if issue.valid?
- present issue, with: ::API::Entities::Issue, current_user: current_user, project: user_project
+ present issue, with: ::API::V3::Entities::Issue, current_user: current_user, project: user_project
else
render_validation_error!(issue)
end
end
desc 'Update an existing issue' do
- success ::API::Entities::Issue
+ success ::API::V3::Entities::Issue
end
params do
requires :issue_id, type: Integer, desc: 'The ID of a project issue'
@@ -176,6 +178,7 @@ module API
end
update_params = declared_params(include_missing: false).merge(request: request, api: true)
+ update_params = convert_parameters_from_legacy_format(update_params)
issue = ::Issues::UpdateService.new(user_project,
current_user,
@@ -184,14 +187,14 @@ module API
render_spam_error! if issue.spam?
if issue.valid?
- present issue, with: ::API::Entities::Issue, current_user: current_user, project: user_project
+ present issue, with: ::API::V3::Entities::Issue, current_user: current_user, project: user_project
else
render_validation_error!(issue)
end
end
desc 'Move an existing issue' do
- success ::API::Entities::Issue
+ success ::API::V3::Entities::Issue
end
params do
requires :issue_id, type: Integer, desc: 'The ID of a project issue'
@@ -206,7 +209,7 @@ module API
begin
issue = ::Issues::MoveService.new(user_project, current_user).execute(issue, new_project)
- present issue, with: ::API::Entities::Issue, current_user: current_user, project: user_project
+ present issue, with: ::API::V3::Entities::Issue, current_user: current_user, project: user_project
rescue ::Issues::MoveService::MoveError => error
render_api_error!(error.message, 400)
end
diff --git a/lib/api/v3/merge_requests.rb b/lib/api/v3/merge_requests.rb
index 1616142a619..b6b7254ae29 100644
--- a/lib/api/v3/merge_requests.rb
+++ b/lib/api/v3/merge_requests.rb
@@ -34,7 +34,7 @@ module API
if project.has_external_issue_tracker?
::API::Entities::ExternalIssue
else
- ::API::Entities::Issue
+ ::API::V3::Entities::Issue
end
end
diff --git a/lib/api/v3/milestones.rb b/lib/api/v3/milestones.rb
index be90cec4afc..4c7061d4939 100644
--- a/lib/api/v3/milestones.rb
+++ b/lib/api/v3/milestones.rb
@@ -39,7 +39,7 @@ module API
end
desc 'Get all issues for a single project milestone' do
- success ::API::Entities::Issue
+ success ::API::V3::Entities::Issue
end
params do
requires :milestone_id, type: Integer, desc: 'The ID of a project milestone'
@@ -56,7 +56,7 @@ module API
}
issues = IssuesFinder.new(current_user, finder_params).execute
- present paginate(issues), with: ::API::Entities::Issue, current_user: current_user, project: user_project
+ present paginate(issues), with: ::API::V3::Entities::Issue, current_user: current_user, project: user_project
end
end
end
diff --git a/lib/banzai/reference_parser/issue_parser.rb b/lib/banzai/reference_parser/issue_parser.rb
index e02b360924a..89ec715ddf6 100644
--- a/lib/banzai/reference_parser/issue_parser.rb
+++ b/lib/banzai/reference_parser/issue_parser.rb
@@ -28,7 +28,7 @@ module Banzai
nodes,
Issue.all.includes(
:author,
- :assignee,
+ :assignees,
{
# These associations are primarily used for checking permissions.
# Eager loading these ensures we don't end up running dozens of
diff --git a/lib/constraints/group_url_constrainer.rb b/lib/constraints/group_url_constrainer.rb
index 1501f64d537..5f379756c11 100644
--- a/lib/constraints/group_url_constrainer.rb
+++ b/lib/constraints/group_url_constrainer.rb
@@ -4,6 +4,6 @@ class GroupUrlConstrainer
return false unless DynamicPathValidator.valid?(id)
- Group.find_by_full_path(id).present?
+ Group.find_by_full_path(id, follow_redirects: request.get?).present?
end
end
diff --git a/lib/constraints/project_url_constrainer.rb b/lib/constraints/project_url_constrainer.rb
index d0ce2caffff..6f542f63f98 100644
--- a/lib/constraints/project_url_constrainer.rb
+++ b/lib/constraints/project_url_constrainer.rb
@@ -6,6 +6,6 @@ class ProjectUrlConstrainer
return false unless DynamicPathValidator.valid?(full_path)
- Project.find_by_full_path(full_path).present?
+ Project.find_by_full_path(full_path, follow_redirects: request.get?).present?
end
end
diff --git a/lib/constraints/user_url_constrainer.rb b/lib/constraints/user_url_constrainer.rb
index 9ab5bcb12ff..28159dc0dec 100644
--- a/lib/constraints/user_url_constrainer.rb
+++ b/lib/constraints/user_url_constrainer.rb
@@ -1,5 +1,5 @@
class UserUrlConstrainer
def matches?(request)
- User.find_by_username(request.params[:username]).present?
+ User.find_by_full_path(request.params[:username], follow_redirects: request.get?).present?
end
end
diff --git a/lib/github/import.rb b/lib/github/import.rb
index d49761fd6c6..06beb607a3e 100644
--- a/lib/github/import.rb
+++ b/lib/github/import.rb
@@ -245,7 +245,7 @@ module Github
issue.label_ids = label_ids(representation.labels)
issue.milestone_id = milestone_id(representation.milestone)
issue.author_id = author_id
- issue.assignee_id = user_id(representation.assignee)
+ issue.assignee_ids = [user_id(representation.assignee)]
issue.created_at = representation.created_at
issue.updated_at = representation.updated_at
issue.save!(validate: false)
diff --git a/lib/gitlab/chat_commands/presenters/issue_base.rb b/lib/gitlab/chat_commands/presenters/issue_base.rb
index 054f7f4be0c..25bc82994ba 100644
--- a/lib/gitlab/chat_commands/presenters/issue_base.rb
+++ b/lib/gitlab/chat_commands/presenters/issue_base.rb
@@ -22,7 +22,7 @@ module Gitlab
[
{
title: "Assignee",
- value: @resource.assignee ? @resource.assignee.name : "_None_",
+ value: @resource.assignees.any? ? @resource.assignees.first.name : "_None_",
short: true
},
{
diff --git a/lib/gitlab/ci/status/build/action.rb b/lib/gitlab/ci/status/build/action.rb
new file mode 100644
index 00000000000..45fd0d4aa07
--- /dev/null
+++ b/lib/gitlab/ci/status/build/action.rb
@@ -0,0 +1,21 @@
+module Gitlab
+ module Ci
+ module Status
+ module Build
+ class Action < Status::Extended
+ def label
+ if has_action?
+ @status.label
+ else
+ "#{@status.label} (not allowed)"
+ end
+ end
+
+ def self.matches?(build, user)
+ build.action?
+ end
+ end
+ end
+ end
+ end
+end
diff --git a/lib/gitlab/ci/status/build/cancelable.rb b/lib/gitlab/ci/status/build/cancelable.rb
index 67bbc3c4849..57b533bad99 100644
--- a/lib/gitlab/ci/status/build/cancelable.rb
+++ b/lib/gitlab/ci/status/build/cancelable.rb
@@ -2,9 +2,7 @@ module Gitlab
module Ci
module Status
module Build
- class Cancelable < SimpleDelegator
- include Status::Extended
-
+ class Cancelable < Status::Extended
def has_action?
can?(user, :update_build, subject)
end
diff --git a/lib/gitlab/ci/status/build/factory.rb b/lib/gitlab/ci/status/build/factory.rb
index 38ac6edc9f1..c852d607373 100644
--- a/lib/gitlab/ci/status/build/factory.rb
+++ b/lib/gitlab/ci/status/build/factory.rb
@@ -8,7 +8,8 @@ module Gitlab
Status::Build::Retryable],
[Status::Build::FailedAllowed,
Status::Build::Play,
- Status::Build::Stop]]
+ Status::Build::Stop],
+ [Status::Build::Action]]
end
def self.common_helpers
diff --git a/lib/gitlab/ci/status/build/failed_allowed.rb b/lib/gitlab/ci/status/build/failed_allowed.rb
index 807afe24bd5..e42d3574357 100644
--- a/lib/gitlab/ci/status/build/failed_allowed.rb
+++ b/lib/gitlab/ci/status/build/failed_allowed.rb
@@ -2,9 +2,7 @@ module Gitlab
module Ci
module Status
module Build
- class FailedAllowed < SimpleDelegator
- include Status::Extended
-
+ class FailedAllowed < Status::Extended
def label
'failed (allowed to fail)'
end
diff --git a/lib/gitlab/ci/status/build/play.rb b/lib/gitlab/ci/status/build/play.rb
index 3495b8d0448..c6139f1b716 100644
--- a/lib/gitlab/ci/status/build/play.rb
+++ b/lib/gitlab/ci/status/build/play.rb
@@ -2,9 +2,7 @@ module Gitlab
module Ci
module Status
module Build
- class Play < SimpleDelegator
- include Status::Extended
-
+ class Play < Status::Extended
def label
'manual play action'
end
diff --git a/lib/gitlab/ci/status/build/retryable.rb b/lib/gitlab/ci/status/build/retryable.rb
index 6b362af7634..505f80848b2 100644
--- a/lib/gitlab/ci/status/build/retryable.rb
+++ b/lib/gitlab/ci/status/build/retryable.rb
@@ -2,9 +2,7 @@ module Gitlab
module Ci
module Status
module Build
- class Retryable < SimpleDelegator
- include Status::Extended
-
+ class Retryable < Status::Extended
def has_action?
can?(user, :update_build, subject)
end
diff --git a/lib/gitlab/ci/status/build/stop.rb b/lib/gitlab/ci/status/build/stop.rb
index e8530f2aaae..0b5199e5483 100644
--- a/lib/gitlab/ci/status/build/stop.rb
+++ b/lib/gitlab/ci/status/build/stop.rb
@@ -2,9 +2,7 @@ module Gitlab
module Ci
module Status
module Build
- class Stop < SimpleDelegator
- include Status::Extended
-
+ class Stop < Status::Extended
def label
'manual stop action'
end
diff --git a/lib/gitlab/ci/status/extended.rb b/lib/gitlab/ci/status/extended.rb
index d367c9bda69..1e8101f8949 100644
--- a/lib/gitlab/ci/status/extended.rb
+++ b/lib/gitlab/ci/status/extended.rb
@@ -1,13 +1,13 @@
module Gitlab
module Ci
module Status
- module Extended
- extend ActiveSupport::Concern
+ class Extended < SimpleDelegator
+ def initialize(status)
+ super(@status = status)
+ end
- class_methods do
- def matches?(_subject, _user)
- raise NotImplementedError
- end
+ def self.matches?(_subject, _user)
+ raise NotImplementedError
end
end
end
diff --git a/lib/gitlab/ci/status/group/common.rb b/lib/gitlab/ci/status/group/common.rb
new file mode 100644
index 00000000000..cfd4329a923
--- /dev/null
+++ b/lib/gitlab/ci/status/group/common.rb
@@ -0,0 +1,21 @@
+module Gitlab
+ module Ci
+ module Status
+ module Group
+ module Common
+ def has_details?
+ false
+ end
+
+ def details_path
+ nil
+ end
+
+ def has_action?
+ false
+ end
+ end
+ end
+ end
+ end
+end
diff --git a/lib/gitlab/ci/status/group/factory.rb b/lib/gitlab/ci/status/group/factory.rb
new file mode 100644
index 00000000000..d118116cfc3
--- /dev/null
+++ b/lib/gitlab/ci/status/group/factory.rb
@@ -0,0 +1,13 @@
+module Gitlab
+ module Ci
+ module Status
+ module Group
+ class Factory < Status::Factory
+ def self.common_helpers
+ Status::Group::Common
+ end
+ end
+ end
+ end
+ end
+end
diff --git a/lib/gitlab/ci/status/pipeline/blocked.rb b/lib/gitlab/ci/status/pipeline/blocked.rb
index a250c3fcb41..37dfe43fb62 100644
--- a/lib/gitlab/ci/status/pipeline/blocked.rb
+++ b/lib/gitlab/ci/status/pipeline/blocked.rb
@@ -2,9 +2,7 @@ module Gitlab
module Ci
module Status
module Pipeline
- class Blocked < SimpleDelegator
- include Status::Extended
-
+ class Blocked < Status::Extended
def text
'blocked'
end
diff --git a/lib/gitlab/ci/status/success_warning.rb b/lib/gitlab/ci/status/success_warning.rb
index d4cdab6957a..df6e76b0151 100644
--- a/lib/gitlab/ci/status/success_warning.rb
+++ b/lib/gitlab/ci/status/success_warning.rb
@@ -5,9 +5,7 @@ module Gitlab
# Extended status used when pipeline or stage passed conditionally.
# This means that failed jobs that are allowed to fail were present.
#
- class SuccessWarning < SimpleDelegator
- include Status::Extended
-
+ class SuccessWarning < Status::Extended
def text
'passed'
end
diff --git a/lib/gitlab/etag_caching/router.rb b/lib/gitlab/etag_caching/router.rb
index aac210f19e8..692c909d838 100644
--- a/lib/gitlab/etag_caching/router.rb
+++ b/lib/gitlab/etag_caching/router.rb
@@ -36,7 +36,11 @@ module Gitlab
Gitlab::EtagCaching::Router::Route.new(
%r(^(?!.*(#{RESERVED_WORDS_REGEX})).*/pipelines\.json\z),
'project_pipelines'
- )
+ ),
+ Gitlab::EtagCaching::Router::Route.new(
+ %r(^(?!.*(#{RESERVED_WORDS})).*/pipelines/\d+\.json\z),
+ 'project_pipeline'
+ ),
].freeze
def self.match(env)
diff --git a/lib/gitlab/fogbugz_import/importer.rb b/lib/gitlab/fogbugz_import/importer.rb
index 222bcdcbf9c..3dcee681c72 100644
--- a/lib/gitlab/fogbugz_import/importer.rb
+++ b/lib/gitlab/fogbugz_import/importer.rb
@@ -122,15 +122,15 @@ module Gitlab
author_id = user_info(bug['ixPersonOpenedBy'])[:gitlab_id] || project.creator_id
issue = Issue.create!(
- iid: bug['ixBug'],
- project_id: project.id,
- title: bug['sTitle'],
- description: body,
- author_id: author_id,
- assignee_id: assignee_id,
- state: bug['fOpen'] == 'true' ? 'opened' : 'closed',
- created_at: date,
- updated_at: DateTime.parse(bug['dtLastUpdated'])
+ iid: bug['ixBug'],
+ project_id: project.id,
+ title: bug['sTitle'],
+ description: body,
+ author_id: author_id,
+ assignee_ids: [assignee_id],
+ state: bug['fOpen'] == 'true' ? 'opened' : 'closed',
+ created_at: date,
+ updated_at: DateTime.parse(bug['dtLastUpdated'])
)
issue_labels = ::LabelsFinder.new(nil, project_id: project.id, title: labels).execute(skip_authorization: true)
diff --git a/lib/gitlab/git_post_receive.rb b/lib/gitlab/git_post_receive.rb
index 6babea144c7..0e14253ab4e 100644
--- a/lib/gitlab/git_post_receive.rb
+++ b/lib/gitlab/git_post_receive.rb
@@ -1,25 +1,12 @@
module Gitlab
class GitPostReceive
include Gitlab::Identifier
- attr_reader :repo_path, :identifier, :changes, :project
+ attr_reader :project, :identifier, :changes
- def initialize(repo_path, identifier, changes)
- repo_path.gsub!(/\.git\z/, '')
- repo_path.gsub!(/\A\//, '')
-
- @repo_path = repo_path
+ def initialize(project, identifier, changes)
+ @project = project
@identifier = identifier
@changes = deserialize_changes(changes)
-
- retrieve_project_and_type
- end
-
- def wiki?
- @type == :wiki
- end
-
- def regular_project?
- @type == :project
end
def identify(revision)
@@ -28,16 +15,6 @@ module Gitlab
private
- def retrieve_project_and_type
- @type = :project
- @project = Project.find_by_full_path(@repo_path)
-
- if @repo_path.end_with?('.wiki') && !@project
- @type = :wiki
- @project = Project.find_by_full_path(@repo_path.gsub(/\.wiki\z/, ''))
- end
- end
-
def deserialize_changes(changes)
changes = utf8_encode_changes(changes)
changes.lines
diff --git a/lib/gitlab/github_import/issue_formatter.rb b/lib/gitlab/github_import/issue_formatter.rb
index 6f5ac4dac0d..977cd0423ba 100644
--- a/lib/gitlab/github_import/issue_formatter.rb
+++ b/lib/gitlab/github_import/issue_formatter.rb
@@ -10,7 +10,7 @@ module Gitlab
description: description,
state: state,
author_id: author_id,
- assignee_id: assignee_id,
+ assignee_ids: Array(assignee_id),
created_at: raw_data.created_at,
updated_at: raw_data.updated_at
}
diff --git a/lib/gitlab/gl_repository.rb b/lib/gitlab/gl_repository.rb
new file mode 100644
index 00000000000..07c0abcce23
--- /dev/null
+++ b/lib/gitlab/gl_repository.rb
@@ -0,0 +1,20 @@
+module Gitlab
+ module GlRepository
+ def self.gl_repository(project, is_wiki)
+ "#{is_wiki ? 'wiki' : 'project'}-#{project.id}"
+ end
+
+ def self.parse(gl_repository)
+ match_data = /\A(project|wiki)-([1-9][0-9]*)\z/.match(gl_repository)
+ unless match_data
+ raise ArgumentError, "Invalid GL Repository \"#{gl_repository}\""
+ end
+
+ type, id = match_data.captures
+ project = Project.find_by(id: id)
+ wiki = type == 'wiki'
+
+ [project, wiki]
+ end
+ end
+end
diff --git a/lib/gitlab/gon_helper.rb b/lib/gitlab/gon_helper.rb
index 5ab84266b7d..26473f99bc3 100644
--- a/lib/gitlab/gon_helper.rb
+++ b/lib/gitlab/gon_helper.rb
@@ -10,6 +10,8 @@ module Gitlab
gon.user_color_scheme = Gitlab::ColorSchemes.for_user(current_user).css_class
gon.katex_css_url = ActionController::Base.helpers.asset_path('katex.css')
gon.katex_js_url = ActionController::Base.helpers.asset_path('katex.js')
+ gon.sentry_dsn = current_application_settings.clientside_sentry_dsn if current_application_settings.clientside_sentry_enabled
+ gon.gitlab_url = Gitlab.config.gitlab.url
if current_user
gon.current_user_id = current_user.id
diff --git a/lib/gitlab/google_code_import/importer.rb b/lib/gitlab/google_code_import/importer.rb
index 5ca3e6a95ca..1b43440673c 100644
--- a/lib/gitlab/google_code_import/importer.rb
+++ b/lib/gitlab/google_code_import/importer.rb
@@ -108,13 +108,13 @@ module Gitlab
end
issue = Issue.create!(
- iid: raw_issue['id'],
- project_id: project.id,
- title: raw_issue['title'],
- description: body,
- author_id: project.creator_id,
- assignee_id: assignee_id,
- state: raw_issue['state'] == 'closed' ? 'closed' : 'opened'
+ iid: raw_issue['id'],
+ project_id: project.id,
+ title: raw_issue['title'],
+ description: body,
+ author_id: project.creator_id,
+ assignee_ids: [assignee_id],
+ state: raw_issue['state'] == 'closed' ? 'closed' : 'opened'
)
issue_labels = ::LabelsFinder.new(nil, project_id: project.id, title: labels).execute(skip_authorization: true)
diff --git a/lib/gitlab/import_export/import_export.yml b/lib/gitlab/import_export/import_export.yml
index 3aac731e844..5f757f99fb3 100644
--- a/lib/gitlab/import_export/import_export.yml
+++ b/lib/gitlab/import_export/import_export.yml
@@ -85,6 +85,8 @@ excluded_attributes:
- :id
- :star_count
- :last_activity_at
+ - :last_repository_updated_at
+ - :last_repository_check_at
snippets:
- :expired_at
merge_request_diff:
diff --git a/lib/gitlab/import_export/relation_factory.rb b/lib/gitlab/import_export/relation_factory.rb
index 4a54e7ef2e7..956763fa399 100644
--- a/lib/gitlab/import_export/relation_factory.rb
+++ b/lib/gitlab/import_export/relation_factory.rb
@@ -15,7 +15,7 @@ module Gitlab
priorities: :label_priorities,
label: :project_label }.freeze
- USER_REFERENCES = %w[author_id assignee_id updated_by_id user_id created_by_id merge_user_id resolved_by_id].freeze
+ USER_REFERENCES = %w[author_id assignee_id updated_by_id user_id created_by_id last_edited_by_id merge_user_id resolved_by_id].freeze
PROJECT_REFERENCES = %w[project_id source_project_id target_project_id].freeze
diff --git a/lib/gitlab/repo_path.rb b/lib/gitlab/repo_path.rb
index 4b1d828c45c..878e03f61d7 100644
--- a/lib/gitlab/repo_path.rb
+++ b/lib/gitlab/repo_path.rb
@@ -2,18 +2,29 @@ module Gitlab
module RepoPath
NotFoundError = Class.new(StandardError)
- def self.strip_storage_path(repo_path)
- result = nil
+ def self.parse(repo_path)
+ project_path = strip_storage_path(repo_path.sub(/\.git\z/, ''), fail_on_not_found: false)
+ project = Project.find_by_full_path(project_path)
+ if project_path.end_with?('.wiki') && !project
+ project = Project.find_by_full_path(project_path.chomp('.wiki'))
+ wiki = true
+ else
+ wiki = false
+ end
+
+ [project, wiki]
+ end
+
+ def self.strip_storage_path(repo_path, fail_on_not_found: true)
+ result = repo_path
- Gitlab.config.repositories.storages.values.each do |params|
- storage_path = params['path']
- if repo_path.start_with?(storage_path)
- result = repo_path.sub(storage_path, '')
- break
- end
+ storage = Gitlab.config.repositories.storages.values.find do |params|
+ repo_path.start_with?(params['path'])
end
- if result.nil?
+ if storage
+ result = result.sub(storage['path'], '')
+ elsif fail_on_not_found
raise NotFoundError.new("No known storage path matches #{repo_path.inspect}")
end
diff --git a/lib/gitlab/workhorse.rb b/lib/gitlab/workhorse.rb
index c551f939df1..8c5ad01e8c2 100644
--- a/lib/gitlab/workhorse.rb
+++ b/lib/gitlab/workhorse.rb
@@ -16,15 +16,17 @@ module Gitlab
SECRET_LENGTH = 32
class << self
- def git_http_ok(repository, user, action)
+ def git_http_ok(repository, is_wiki, user, action)
+ project = repository.project
repo_path = repository.path_to_repo
params = {
GL_ID: Gitlab::GlId.gl_id(user),
+ GL_REPOSITORY: Gitlab::GlRepository.gl_repository(project, is_wiki),
RepoPath: repo_path,
}
if Gitlab.config.gitaly.enabled
- address = Gitlab::GitalyClient.get_address(repository.project.repository_storage)
+ address = Gitlab::GitalyClient.get_address(project.repository_storage)
params[:Repository] = repository.gitaly_repository.to_h
feature_enabled = case action.to_s
diff --git a/lib/tasks/migrate/setup_postgresql.rake b/lib/tasks/migrate/setup_postgresql.rake
index 8938bc515f5..1e00b47303d 100644
--- a/lib/tasks/migrate/setup_postgresql.rake
+++ b/lib/tasks/migrate/setup_postgresql.rake
@@ -11,4 +11,5 @@ task setup_postgresql: :environment do
AddUsersLowerUsernameEmailIndexes.new.up
AddLowerPathIndexToRoutes.new.up
IndexRoutesPathForLike.new.up
+ IndexRedirectRoutesPathForLike.new.up
end
diff --git a/package.json b/package.json
index 63b2c190269..800327d8a08 100644
--- a/package.json
+++ b/package.json
@@ -40,9 +40,11 @@
"pikaday": "^1.5.1",
"prismjs": "^1.6.0",
"raphael": "^2.2.7",
+ "raven-js": "^3.14.0",
"raw-loader": "^0.5.1",
"react-dev-utils": "^0.5.2",
"select2": "3.5.2-browserify",
+ "sql.js": "^0.4.0",
"stats-webpack-plugin": "^0.4.3",
"three": "^0.84.0",
"three-orbit-controls": "^82.1.0",
diff --git a/spec/controllers/admin/services_controller_spec.rb b/spec/controllers/admin/services_controller_spec.rb
index e5cdd52307e..c94616d8508 100644
--- a/spec/controllers/admin/services_controller_spec.rb
+++ b/spec/controllers/admin/services_controller_spec.rb
@@ -23,4 +23,36 @@ describe Admin::ServicesController do
end
end
end
+
+ describe "#update" do
+ let(:project) { create(:empty_project) }
+ let!(:service) do
+ RedmineService.create(
+ project: project,
+ active: false,
+ template: true,
+ properties: {
+ project_url: 'http://abc',
+ issues_url: 'http://abc',
+ new_issue_url: 'http://abc'
+ }
+ )
+ end
+
+ it 'calls the propagation worker when service is active' do
+ expect(PropagateServiceTemplateWorker).to receive(:perform_async).with(service.id)
+
+ put :update, id: service.id, service: { active: true }
+
+ expect(response).to have_http_status(302)
+ end
+
+ it 'does not call the propagation worker when service is not active' do
+ expect(PropagateServiceTemplateWorker).not_to receive(:perform_async)
+
+ put :update, id: service.id, service: { properties: {} }
+
+ expect(response).to have_http_status(302)
+ end
+ end
end
diff --git a/spec/controllers/application_controller_spec.rb b/spec/controllers/application_controller_spec.rb
index 1bf0533ca24..d40aae04fc3 100644
--- a/spec/controllers/application_controller_spec.rb
+++ b/spec/controllers/application_controller_spec.rb
@@ -106,10 +106,9 @@ describe ApplicationController do
controller.send(:route_not_found)
end
- it 'does redirect to login page if not authenticated' do
+ it 'does redirect to login page via authenticate_user! if not authenticated' do
allow(controller).to receive(:current_user).and_return(nil)
- expect(controller).to receive(:redirect_to)
- expect(controller).to receive(:new_user_session_path)
+ expect(controller).to receive(:authenticate_user!)
controller.send(:route_not_found)
end
end
diff --git a/spec/controllers/dashboard/todos_controller_spec.rb b/spec/controllers/dashboard/todos_controller_spec.rb
index 762e90f4a16..085f3fd8543 100644
--- a/spec/controllers/dashboard/todos_controller_spec.rb
+++ b/spec/controllers/dashboard/todos_controller_spec.rb
@@ -14,7 +14,7 @@ describe Dashboard::TodosController do
describe 'GET #index' do
context 'when using pagination' do
let(:last_page) { user.todos.page.total_pages }
- let!(:issues) { create_list(:issue, 2, project: project, assignee: user) }
+ let!(:issues) { create_list(:issue, 2, project: project, assignees: [user]) }
before do
issues.each { |issue| todo_service.new_issue(issue, user) }
diff --git a/spec/controllers/groups_controller_spec.rb b/spec/controllers/groups_controller_spec.rb
index cad82a34fb0..073b87a1cb4 100644
--- a/spec/controllers/groups_controller_spec.rb
+++ b/spec/controllers/groups_controller_spec.rb
@@ -49,6 +49,26 @@ describe GroupsController do
expect(assigns(:issues)).to eq [issue_2, issue_1]
end
end
+
+ context 'when requesting the canonical path with different casing' do
+ it 'redirects to the correct casing' do
+ get :issues, id: group.to_param.upcase
+
+ expect(response).to redirect_to(issues_group_path(group.to_param))
+ expect(controller).not_to set_flash[:notice]
+ end
+ end
+
+ context 'when requesting a redirected path' do
+ let(:redirect_route) { group.redirect_routes.create(path: 'old-path') }
+
+ it 'redirects to the canonical path' do
+ get :issues, id: redirect_route.path
+
+ expect(response).to redirect_to(issues_group_path(group.to_param))
+ expect(controller).to set_flash[:notice].to(/moved/)
+ end
+ end
end
describe 'GET #merge_requests' do
@@ -74,6 +94,26 @@ describe GroupsController do
expect(assigns(:merge_requests)).to eq [merge_request_2, merge_request_1]
end
end
+
+ context 'when requesting the canonical path with different casing' do
+ it 'redirects to the correct casing' do
+ get :merge_requests, id: group.to_param.upcase
+
+ expect(response).to redirect_to(merge_requests_group_path(group.to_param))
+ expect(controller).not_to set_flash[:notice]
+ end
+ end
+
+ context 'when requesting a redirected path' do
+ let(:redirect_route) { group.redirect_routes.create(path: 'old-path') }
+
+ it 'redirects to the canonical path' do
+ get :merge_requests, id: redirect_route.path
+
+ expect(response).to redirect_to(merge_requests_group_path(group.to_param))
+ expect(controller).to set_flash[:notice].to(/moved/)
+ end
+ end
end
describe 'DELETE #destroy' do
@@ -81,7 +121,7 @@ describe GroupsController do
it 'returns 404' do
sign_in(create(:user))
- delete :destroy, id: group.path
+ delete :destroy, id: group.to_param
expect(response.status).to eq(404)
end
@@ -94,15 +134,39 @@ describe GroupsController do
it 'schedules a group destroy' do
Sidekiq::Testing.fake! do
- expect { delete :destroy, id: group.path }.to change(GroupDestroyWorker.jobs, :size).by(1)
+ expect { delete :destroy, id: group.to_param }.to change(GroupDestroyWorker.jobs, :size).by(1)
end
end
it 'redirects to the root path' do
- delete :destroy, id: group.path
+ delete :destroy, id: group.to_param
expect(response).to redirect_to(root_path)
end
+
+ context 'when requesting the canonical path with different casing' do
+ it 'does not 404' do
+ delete :destroy, id: group.to_param.upcase
+
+ expect(response).not_to have_http_status(404)
+ end
+
+ it 'does not redirect to the correct casing' do
+ delete :destroy, id: group.to_param.upcase
+
+ expect(response).not_to redirect_to(group_path(group.to_param))
+ end
+ end
+
+ context 'when requesting a redirected path' do
+ let(:redirect_route) { group.redirect_routes.create(path: 'old-path') }
+
+ it 'returns not found' do
+ delete :destroy, id: redirect_route.path
+
+ expect(response).to have_http_status(404)
+ end
+ end
end
end
@@ -111,7 +175,7 @@ describe GroupsController do
sign_in(user)
end
- it 'updates the path succesfully' do
+ it 'updates the path successfully' do
post :update, id: group.to_param, group: { path: 'new_path' }
expect(response).to have_http_status(302)
@@ -125,5 +189,29 @@ describe GroupsController do
expect(assigns(:group).errors).not_to be_empty
expect(assigns(:group).path).not_to eq('new_path')
end
+
+ context 'when requesting the canonical path with different casing' do
+ it 'does not 404' do
+ post :update, id: group.to_param.upcase, group: { path: 'new_path' }
+
+ expect(response).not_to have_http_status(404)
+ end
+
+ it 'does not redirect to the correct casing' do
+ post :update, id: group.to_param.upcase, group: { path: 'new_path' }
+
+ expect(response).not_to redirect_to(group_path(group.to_param))
+ end
+ end
+
+ context 'when requesting a redirected path' do
+ let(:redirect_route) { group.redirect_routes.create(path: 'old-path') }
+
+ it 'returns not found' do
+ post :update, id: redirect_route.path, group: { path: 'new_path' }
+
+ expect(response).to have_http_status(404)
+ end
+ end
end
end
diff --git a/spec/controllers/projects/boards/issues_controller_spec.rb b/spec/controllers/projects/boards/issues_controller_spec.rb
index 15667e8d4b1..dc3b72c6de4 100644
--- a/spec/controllers/projects/boards/issues_controller_spec.rb
+++ b/spec/controllers/projects/boards/issues_controller_spec.rb
@@ -34,7 +34,7 @@ describe Projects::Boards::IssuesController do
issue = create(:labeled_issue, project: project, labels: [planning])
create(:labeled_issue, project: project, labels: [planning])
create(:labeled_issue, project: project, labels: [development], due_date: Date.tomorrow)
- create(:labeled_issue, project: project, labels: [development], assignee: johndoe)
+ create(:labeled_issue, project: project, labels: [development], assignees: [johndoe])
issue.subscribe(johndoe, project)
list_issues user: user, board: board, list: list2
diff --git a/spec/controllers/projects/builds_controller_spec.rb b/spec/controllers/projects/builds_controller_spec.rb
index 22193eac672..3ce23c17cdc 100644
--- a/spec/controllers/projects/builds_controller_spec.rb
+++ b/spec/controllers/projects/builds_controller_spec.rb
@@ -261,7 +261,7 @@ describe Projects::BuildsController do
describe 'POST play' do
before do
- project.add_developer(user)
+ project.add_master(user)
sign_in(user)
post_play
diff --git a/spec/controllers/projects/issues_controller_spec.rb b/spec/controllers/projects/issues_controller_spec.rb
index 5f1f892821a..1f79e72495a 100644
--- a/spec/controllers/projects/issues_controller_spec.rb
+++ b/spec/controllers/projects/issues_controller_spec.rb
@@ -173,12 +173,12 @@ describe Projects::IssuesController do
namespace_id: project.namespace.to_param,
project_id: project,
id: issue.iid,
- issue: { assignee_id: assignee.id },
+ issue: { assignee_ids: [assignee.id] },
format: :json
body = JSON.parse(response.body)
- expect(body['assignee'].keys)
- .to match_array(%w(name username avatar_url))
+ expect(body['assignees'].first.keys)
+ .to match_array(%w(id name username avatar_url))
end
end
@@ -348,7 +348,7 @@ describe Projects::IssuesController do
let(:admin) { create(:admin) }
let!(:issue) { create(:issue, project: project) }
let!(:unescaped_parameter_value) { create(:issue, :confidential, project: project, author: author) }
- let!(:request_forgery_timing_attack) { create(:issue, :confidential, project: project, assignee: assignee) }
+ let!(:request_forgery_timing_attack) { create(:issue, :confidential, project: project, assignees: [assignee]) }
describe 'GET #index' do
it 'does not list confidential issues for guests' do
diff --git a/spec/controllers/projects/merge_requests_controller_spec.rb b/spec/controllers/projects/merge_requests_controller_spec.rb
index a793da4162a..0483c6b7879 100644
--- a/spec/controllers/projects/merge_requests_controller_spec.rb
+++ b/spec/controllers/projects/merge_requests_controller_spec.rb
@@ -1067,7 +1067,7 @@ describe Projects::MergeRequestsController do
end
it 'correctly pluralizes flash message on success' do
- issue2.update!(assignee: user)
+ issue2.assignees = [user]
post_assign_issues
diff --git a/spec/controllers/projects/pipelines_controller_spec.rb b/spec/controllers/projects/pipelines_controller_spec.rb
index 1b47d163c0b..fb4a4721a58 100644
--- a/spec/controllers/projects/pipelines_controller_spec.rb
+++ b/spec/controllers/projects/pipelines_controller_spec.rb
@@ -1,6 +1,8 @@
require 'spec_helper'
describe Projects::PipelinesController do
+ include ApiHelpers
+
let(:user) { create(:user) }
let(:project) { create(:empty_project, :public) }
@@ -24,6 +26,7 @@ describe Projects::PipelinesController do
it 'returns JSON with serialized pipelines' do
expect(response).to have_http_status(:ok)
+ expect(response).to match_response_schema('pipeline')
expect(json_response).to include('pipelines')
expect(json_response['pipelines'].count).to eq 4
@@ -34,6 +37,34 @@ describe Projects::PipelinesController do
end
end
+ describe 'GET show JSON' do
+ let!(:pipeline) { create(:ci_pipeline_with_one_job, project: project) }
+
+ it 'returns the pipeline' do
+ get_pipeline_json
+
+ expect(response).to have_http_status(:ok)
+ expect(json_response).not_to be_an(Array)
+ expect(json_response['id']).to be(pipeline.id)
+ expect(json_response['details']).to have_key 'stages'
+ end
+
+ context 'when the pipeline has multiple jobs' do
+ it 'does not perform N + 1 queries' do
+ control_count = ActiveRecord::QueryRecorder.new { get_pipeline_json }.count
+
+ create(:ci_build, pipeline: pipeline)
+
+ # The plus 2 is needed to group and sort
+ expect { get_pipeline_json }.not_to exceed_query_limit(control_count + 2)
+ end
+ end
+
+ def get_pipeline_json
+ get :show, namespace_id: project.namespace, project_id: project, id: pipeline, format: :json
+ end
+ end
+
describe 'GET stages.json' do
let(:pipeline) { create(:ci_pipeline, project: project) }
diff --git a/spec/controllers/projects_controller_spec.rb b/spec/controllers/projects_controller_spec.rb
index eafc2154568..e46ef447df2 100644
--- a/spec/controllers/projects_controller_spec.rb
+++ b/spec/controllers/projects_controller_spec.rb
@@ -185,6 +185,7 @@ describe ProjectsController do
expect(assigns(:project)).to eq(public_project)
expect(response).to redirect_to("/#{public_project.full_path}")
+ expect(controller).not_to set_flash[:notice]
end
end
end
@@ -218,19 +219,33 @@ describe ProjectsController do
expect(response).to redirect_to(namespace_project_path)
end
end
+
+ context 'when requesting a redirected path' do
+ let!(:redirect_route) { public_project.redirect_routes.create!(path: "foo/bar") }
+
+ it 'redirects to the canonical path' do
+ get :show, namespace_id: 'foo', id: 'bar'
+
+ expect(response).to redirect_to(public_project)
+ expect(controller).to set_flash[:notice].to(/moved/)
+ end
+ end
end
describe "#update" do
render_views
let(:admin) { create(:admin) }
+ let(:project) { create(:project, :repository) }
+ let(:new_path) { 'renamed_path' }
+ let(:project_params) { { path: new_path } }
+
+ before do
+ sign_in(admin)
+ end
it "sets the repository to the right path after a rename" do
- project = create(:project, :repository)
- new_path = 'renamed_path'
- project_params = { path: new_path }
controller.instance_variable_set(:@project, project)
- sign_in(admin)
put :update,
namespace_id: project.namespace,
@@ -241,6 +256,34 @@ describe ProjectsController do
expect(assigns(:repository).path).to eq(project.repository.path)
expect(response).to have_http_status(302)
end
+
+ context 'when requesting the canonical path' do
+ it "is case-insensitive" do
+ controller.instance_variable_set(:@project, project)
+
+ put :update,
+ namespace_id: 'FOo',
+ id: 'baR',
+ project: project_params
+
+ expect(project.repository.path).to include(new_path)
+ expect(assigns(:repository).path).to eq(project.repository.path)
+ expect(response).to have_http_status(302)
+ end
+ end
+
+ context 'when requesting a redirected path' do
+ let!(:redirect_route) { project.redirect_routes.create!(path: "foo/bar") }
+
+ it 'returns not found' do
+ put :update,
+ namespace_id: 'foo',
+ id: 'bar',
+ project: project_params
+
+ expect(response).to have_http_status(404)
+ end
+ end
end
describe "#destroy" do
@@ -276,6 +319,31 @@ describe ProjectsController do
expect(merge_request.reload.state).to eq('closed')
end
end
+
+ context 'when requesting the canonical path' do
+ it "is case-insensitive" do
+ controller.instance_variable_set(:@project, project)
+ sign_in(admin)
+
+ orig_id = project.id
+ delete :destroy, namespace_id: project.namespace, id: project.path.upcase
+
+ expect { Project.find(orig_id) }.to raise_error(ActiveRecord::RecordNotFound)
+ expect(response).to have_http_status(302)
+ expect(response).to redirect_to(dashboard_projects_path)
+ end
+ end
+
+ context 'when requesting a redirected path' do
+ let!(:redirect_route) { project.redirect_routes.create!(path: "foo/bar") }
+
+ it 'returns not found' do
+ sign_in(admin)
+ delete :destroy, namespace_id: 'foo', id: 'bar'
+
+ expect(response).to have_http_status(404)
+ end
+ end
end
describe 'PUT #new_issue_address' do
@@ -397,6 +465,17 @@ describe ProjectsController do
expect(parsed_body["Tags"]).to include("v1.0.0")
expect(parsed_body["Commits"]).to include("123456")
end
+
+ context 'when requesting a redirected path' do
+ let!(:redirect_route) { public_project.redirect_routes.create!(path: "foo/bar") }
+
+ it 'redirects to the canonical path' do
+ get :refs, namespace_id: 'foo', id: 'bar'
+
+ expect(response).to redirect_to(refs_namespace_project_path(namespace_id: public_project.namespace, id: public_project))
+ expect(controller).to set_flash[:notice].to(/moved/)
+ end
+ end
end
describe 'POST #preview_markdown' do
diff --git a/spec/controllers/users_controller_spec.rb b/spec/controllers/users_controller_spec.rb
index bbe9aaf737f..74c5aa44ba9 100644
--- a/spec/controllers/users_controller_spec.rb
+++ b/spec/controllers/users_controller_spec.rb
@@ -4,15 +4,6 @@ describe UsersController do
let(:user) { create(:user) }
describe 'GET #show' do
- it 'is case-insensitive' do
- user = create(:user, username: 'CamelCaseUser')
- sign_in(user)
-
- get :show, username: user.username.downcase
-
- expect(response).to be_success
- end
-
context 'with rendered views' do
render_views
@@ -45,9 +36,9 @@ describe UsersController do
end
context 'when logged out' do
- it 'renders 404' do
+ it 'redirects to login page' do
get :show, username: user.username
- expect(response).to have_http_status(404)
+ expect(response).to redirect_to new_user_session_path
end
end
@@ -61,6 +52,58 @@ describe UsersController do
end
end
end
+
+ context 'when requesting the canonical path' do
+ let(:user) { create(:user, username: 'CamelCaseUser') }
+
+ before { sign_in(user) }
+
+ context 'with exactly matching casing' do
+ it 'responds with success' do
+ get :show, username: user.username
+
+ expect(response).to be_success
+ end
+ end
+
+ context 'with different casing' do
+ it 'redirects to the correct casing' do
+ get :show, username: user.username.downcase
+
+ expect(response).to redirect_to(user)
+ expect(controller).not_to set_flash[:notice]
+ end
+ end
+ end
+
+ context 'when requesting a redirected path' do
+ let(:redirect_route) { user.namespace.redirect_routes.create(path: 'old-username') }
+
+ it 'redirects to the canonical path' do
+ get :show, username: redirect_route.path
+
+ expect(response).to redirect_to(user)
+ expect(controller).to set_flash[:notice].to(/moved/)
+ end
+ end
+
+ context 'when a user by that username does not exist' do
+ context 'when logged out' do
+ it 'redirects to login page' do
+ get :show, username: 'nonexistent'
+ expect(response).to redirect_to new_user_session_path
+ end
+ end
+
+ context 'when logged in' do
+ before { sign_in(user) }
+
+ it 'renders 404' do
+ get :show, username: 'nonexistent'
+ expect(response).to have_http_status(404)
+ end
+ end
+ end
end
describe 'GET #calendar' do
@@ -88,11 +131,45 @@ describe UsersController do
expect(assigns(:contributions_calendar).projects.count).to eq(2)
end
end
+
+ context 'when requesting the canonical path' do
+ let(:user) { create(:user, username: 'CamelCaseUser') }
+
+ before { sign_in(user) }
+
+ context 'with exactly matching casing' do
+ it 'responds with success' do
+ get :calendar, username: user.username
+
+ expect(response).to be_success
+ end
+ end
+
+ context 'with different casing' do
+ it 'redirects to the correct casing' do
+ get :calendar, username: user.username.downcase
+
+ expect(response).to redirect_to(user_calendar_path(user))
+ expect(controller).not_to set_flash[:notice]
+ end
+ end
+ end
+
+ context 'when requesting a redirected path' do
+ let(:redirect_route) { user.namespace.redirect_routes.create(path: 'old-username') }
+
+ it 'redirects to the canonical path' do
+ get :calendar, username: redirect_route.path
+
+ expect(response).to redirect_to(user_calendar_path(user))
+ expect(controller).to set_flash[:notice].to(/moved/)
+ end
+ end
end
describe 'GET #calendar_activities' do
let!(:project) { create(:empty_project) }
- let!(:user) { create(:user) }
+ let(:user) { create(:user) }
before do
allow_any_instance_of(User).to receive(:contributed_projects_ids).and_return([project.id])
@@ -110,6 +187,38 @@ describe UsersController do
get :calendar_activities, username: user.username
expect(response).to render_template('calendar_activities')
end
+
+ context 'when requesting the canonical path' do
+ let(:user) { create(:user, username: 'CamelCaseUser') }
+
+ context 'with exactly matching casing' do
+ it 'responds with success' do
+ get :calendar_activities, username: user.username
+
+ expect(response).to be_success
+ end
+ end
+
+ context 'with different casing' do
+ it 'redirects to the correct casing' do
+ get :calendar_activities, username: user.username.downcase
+
+ expect(response).to redirect_to(user_calendar_activities_path(user))
+ expect(controller).not_to set_flash[:notice]
+ end
+ end
+ end
+
+ context 'when requesting a redirected path' do
+ let(:redirect_route) { user.namespace.redirect_routes.create(path: 'old-username') }
+
+ it 'redirects to the canonical path' do
+ get :calendar_activities, username: redirect_route.path
+
+ expect(response).to redirect_to(user_calendar_activities_path(user))
+ expect(controller).to set_flash[:notice].to(/moved/)
+ end
+ end
end
describe 'GET #snippets' do
@@ -132,5 +241,83 @@ describe UsersController do
expect(JSON.parse(response.body)).to have_key('html')
end
end
+
+ context 'when requesting the canonical path' do
+ let(:user) { create(:user, username: 'CamelCaseUser') }
+
+ context 'with exactly matching casing' do
+ it 'responds with success' do
+ get :snippets, username: user.username
+
+ expect(response).to be_success
+ end
+ end
+
+ context 'with different casing' do
+ it 'redirects to the correct casing' do
+ get :snippets, username: user.username.downcase
+
+ expect(response).to redirect_to(user_snippets_path(user))
+ expect(controller).not_to set_flash[:notice]
+ end
+ end
+ end
+
+ context 'when requesting a redirected path' do
+ let(:redirect_route) { user.namespace.redirect_routes.create(path: 'old-username') }
+
+ it 'redirects to the canonical path' do
+ get :snippets, username: redirect_route.path
+
+ expect(response).to redirect_to(user_snippets_path(user))
+ expect(controller).to set_flash[:notice].to(/moved/)
+ end
+ end
+ end
+
+ describe 'GET #exists' do
+ before do
+ sign_in(user)
+ end
+
+ context 'when user exists' do
+ it 'returns JSON indicating the user exists' do
+ get :exists, username: user.username
+
+ expected_json = { exists: true }.to_json
+ expect(response.body).to eq(expected_json)
+ end
+
+ context 'when the casing is different' do
+ let(:user) { create(:user, username: 'CamelCaseUser') }
+
+ it 'returns JSON indicating the user exists' do
+ get :exists, username: user.username.downcase
+
+ expected_json = { exists: true }.to_json
+ expect(response.body).to eq(expected_json)
+ end
+ end
+ end
+
+ context 'when the user does not exist' do
+ it 'returns JSON indicating the user does not exist' do
+ get :exists, username: 'foo'
+
+ expected_json = { exists: false }.to_json
+ expect(response.body).to eq(expected_json)
+ end
+
+ context 'when a user changed their username' do
+ let(:redirect_route) { user.namespace.redirect_routes.create(path: 'old-username') }
+
+ it 'returns JSON indicating a user by that username does not exist' do
+ get :exists, username: 'old-username'
+
+ expected_json = { exists: false }.to_json
+ expect(response.body).to eq(expected_json)
+ end
+ end
+ end
end
end
diff --git a/spec/factories/environments.rb b/spec/factories/environments.rb
index 3fbf24b5c7d..d8d699fb3aa 100644
--- a/spec/factories/environments.rb
+++ b/spec/factories/environments.rb
@@ -18,15 +18,21 @@ FactoryGirl.define do
# interconnected objects to simulate a review app.
#
after(:create) do |environment, evaluator|
+ pipeline = create(:ci_pipeline, project: environment.project)
+
+ deployable = create(:ci_build, name: "#{environment.name}:deploy",
+ pipeline: pipeline)
+
deployment = create(:deployment,
environment: environment,
project: environment.project,
+ deployable: deployable,
ref: evaluator.ref,
sha: environment.project.commit(evaluator.ref).id)
teardown_build = create(:ci_build, :manual,
- name: "#{deployment.environment.name}:teardown",
- pipeline: deployment.deployable.pipeline)
+ name: "#{environment.name}:teardown",
+ pipeline: pipeline)
deployment.update_column(:on_stop, teardown_build.name)
environment.update_attribute(:deployments, [deployment])
diff --git a/spec/features/atom/dashboard_issues_spec.rb b/spec/features/atom/dashboard_issues_spec.rb
index 58b14e09740..9ea325ab41b 100644
--- a/spec/features/atom/dashboard_issues_spec.rb
+++ b/spec/features/atom/dashboard_issues_spec.rb
@@ -32,7 +32,7 @@ describe "Dashboard Issues Feed", feature: true do
end
context "issue with basic fields" do
- let!(:issue2) { create(:issue, author: user, assignee: assignee, project: project2, description: 'test desc') }
+ let!(:issue2) { create(:issue, author: user, assignees: [assignee], project: project2, description: 'test desc') }
it "renders issue fields" do
visit issues_dashboard_path(:atom, private_token: user.private_token)
@@ -41,7 +41,7 @@ describe "Dashboard Issues Feed", feature: true do
expect(entry).to be_present
expect(entry).to have_selector('author email', text: issue2.author_public_email)
- expect(entry).to have_selector('assignee email', text: issue2.assignee_public_email)
+ expect(entry).to have_selector('assignees email', text: assignee.public_email)
expect(entry).not_to have_selector('labels')
expect(entry).not_to have_selector('milestone')
expect(entry).to have_selector('description', text: issue2.description)
@@ -51,7 +51,7 @@ describe "Dashboard Issues Feed", feature: true do
context "issue with label and milestone" do
let!(:milestone1) { create(:milestone, project: project1, title: 'v1') }
let!(:label1) { create(:label, project: project1, title: 'label1') }
- let!(:issue1) { create(:issue, author: user, assignee: assignee, project: project1, milestone: milestone1) }
+ let!(:issue1) { create(:issue, author: user, assignees: [assignee], project: project1, milestone: milestone1) }
before do
issue1.labels << label1
@@ -64,7 +64,7 @@ describe "Dashboard Issues Feed", feature: true do
expect(entry).to be_present
expect(entry).to have_selector('author email', text: issue1.author_public_email)
- expect(entry).to have_selector('assignee email', text: issue1.assignee_public_email)
+ expect(entry).to have_selector('assignees email', text: assignee.public_email)
expect(entry).to have_selector('labels label', text: label1.title)
expect(entry).to have_selector('milestone', text: milestone1.title)
expect(entry).not_to have_selector('description')
diff --git a/spec/features/atom/issues_spec.rb b/spec/features/atom/issues_spec.rb
index b3903ec2faf..4f6754ad541 100644
--- a/spec/features/atom/issues_spec.rb
+++ b/spec/features/atom/issues_spec.rb
@@ -6,7 +6,7 @@ describe 'Issues Feed', feature: true do
let!(:assignee) { create(:user, email: 'private2@example.com', public_email: 'public2@example.com') }
let!(:group) { create(:group) }
let!(:project) { create(:project) }
- let!(:issue) { create(:issue, author: user, assignee: assignee, project: project) }
+ let!(:issue) { create(:issue, author: user, assignees: [assignee], project: project) }
before do
project.team << [user, :developer]
@@ -22,7 +22,8 @@ describe 'Issues Feed', feature: true do
to have_content('application/atom+xml')
expect(body).to have_selector('title', text: "#{project.name} issues")
expect(body).to have_selector('author email', text: issue.author_public_email)
- expect(body).to have_selector('assignee email', text: issue.author_public_email)
+ expect(body).to have_selector('assignees assignee email', text: issue.assignees.first.public_email)
+ expect(body).to have_selector('assignee email', text: issue.assignees.first.public_email)
expect(body).to have_selector('entry summary', text: issue.title)
end
end
@@ -36,7 +37,8 @@ describe 'Issues Feed', feature: true do
to have_content('application/atom+xml')
expect(body).to have_selector('title', text: "#{project.name} issues")
expect(body).to have_selector('author email', text: issue.author_public_email)
- expect(body).to have_selector('assignee email', text: issue.author_public_email)
+ expect(body).to have_selector('assignees assignee email', text: issue.assignees.first.public_email)
+ expect(body).to have_selector('assignee email', text: issue.assignees.first.public_email)
expect(body).to have_selector('entry summary', text: issue.title)
end
end
diff --git a/spec/features/boards/boards_spec.rb b/spec/features/boards/boards_spec.rb
index a172ce1e8c0..18585488e26 100644
--- a/spec/features/boards/boards_spec.rb
+++ b/spec/features/boards/boards_spec.rb
@@ -71,7 +71,7 @@ describe 'Issue Boards', feature: true, js: true do
let!(:list2) { create(:list, board: board, label: development, position: 1) }
let!(:confidential_issue) { create(:labeled_issue, :confidential, project: project, author: user, labels: [planning], relative_position: 9) }
- let!(:issue1) { create(:labeled_issue, project: project, assignee: user, labels: [planning], relative_position: 8) }
+ let!(:issue1) { create(:labeled_issue, project: project, assignees: [user], labels: [planning], relative_position: 8) }
let!(:issue2) { create(:labeled_issue, project: project, author: user2, labels: [planning], relative_position: 7) }
let!(:issue3) { create(:labeled_issue, project: project, labels: [planning], relative_position: 6) }
let!(:issue4) { create(:labeled_issue, project: project, labels: [planning], relative_position: 5) }
diff --git a/spec/features/boards/modal_filter_spec.rb b/spec/features/boards/modal_filter_spec.rb
index 4a4c13e79c8..e1367c675e5 100644
--- a/spec/features/boards/modal_filter_spec.rb
+++ b/spec/features/boards/modal_filter_spec.rb
@@ -98,7 +98,7 @@ describe 'Issue Boards add issue modal filtering', :feature, :js do
end
context 'assignee' do
- let!(:issue) { create(:issue, project: project, assignee: user2) }
+ let!(:issue) { create(:issue, project: project, assignees: [user2]) }
before do
project.team << [user2, :developer]
diff --git a/spec/features/boards/sidebar_spec.rb b/spec/features/boards/sidebar_spec.rb
index bafa4f05937..7c53d2b47d9 100644
--- a/spec/features/boards/sidebar_spec.rb
+++ b/spec/features/boards/sidebar_spec.rb
@@ -4,13 +4,14 @@ describe 'Issue Boards', feature: true, js: true do
include WaitForVueResource
let(:user) { create(:user) }
+ let(:user2) { create(:user) }
let(:project) { create(:empty_project, :public) }
let!(:milestone) { create(:milestone, project: project) }
let!(:development) { create(:label, project: project, name: 'Development') }
let!(:bug) { create(:label, project: project, name: 'Bug') }
let!(:regression) { create(:label, project: project, name: 'Regression') }
let!(:stretch) { create(:label, project: project, name: 'Stretch') }
- let!(:issue1) { create(:labeled_issue, project: project, assignee: user, milestone: milestone, labels: [development], relative_position: 2) }
+ let!(:issue1) { create(:labeled_issue, project: project, assignees: [user], milestone: milestone, labels: [development], relative_position: 2) }
let!(:issue2) { create(:labeled_issue, project: project, labels: [development, stretch], relative_position: 1) }
let(:board) { create(:board, project: project) }
let!(:list) { create(:list, board: board, label: development, position: 0) }
@@ -112,10 +113,11 @@ describe 'Issue Boards', feature: true, js: true do
page.within('.dropdown-menu-user') do
click_link 'Unassigned'
-
- wait_for_vue_resource
end
+ find('.dropdown-menu-toggle').click
+ wait_for_vue_resource
+
expect(page).to have_content('No assignee')
end
@@ -128,7 +130,7 @@ describe 'Issue Boards', feature: true, js: true do
page.within(find('.assignee')) do
expect(page).to have_content('No assignee')
- click_link 'assign yourself'
+ click_button 'assign yourself'
wait_for_vue_resource
@@ -138,7 +140,7 @@ describe 'Issue Boards', feature: true, js: true do
expect(card).to have_selector('.avatar')
end
- it 'resets assignee dropdown' do
+ it 'updates assignee dropdown' do
click_card(card)
page.within('.assignee') do
@@ -162,7 +164,7 @@ describe 'Issue Boards', feature: true, js: true do
page.within('.assignee') do
click_link 'Edit'
- expect(page).not_to have_selector('.is-active')
+ expect(page).to have_selector('.is-active')
end
end
end
diff --git a/spec/features/dashboard/issuables_counter_spec.rb b/spec/features/dashboard/issuables_counter_spec.rb
index 4fca7577e74..6f7bf0eba6e 100644
--- a/spec/features/dashboard/issuables_counter_spec.rb
+++ b/spec/features/dashboard/issuables_counter_spec.rb
@@ -7,7 +7,7 @@ describe 'Navigation bar counter', feature: true, caching: true do
let(:merge_request) { create(:merge_request, source_project: project) }
before do
- issue.update(assignee: user)
+ issue.assignees = [user]
merge_request.update(assignee: user)
login_as(user)
end
@@ -17,7 +17,9 @@ describe 'Navigation bar counter', feature: true, caching: true do
expect_counters('issues', '1')
- issue.update(assignee: nil)
+ issue.assignees = []
+
+ user.update_cache_counts
Timecop.travel(3.minutes.from_now) do
visit issues_path
diff --git a/spec/features/dashboard/issues_spec.rb b/spec/features/dashboard/issues_spec.rb
index f4420814c3a..86c7954e60c 100644
--- a/spec/features/dashboard/issues_spec.rb
+++ b/spec/features/dashboard/issues_spec.rb
@@ -11,7 +11,7 @@ RSpec.describe 'Dashboard Issues', feature: true do
let!(:authored_issue) { create :issue, author: current_user, project: project }
let!(:authored_issue_on_public_project) { create :issue, author: current_user, project: public_project }
- let!(:assigned_issue) { create :issue, assignee: current_user, project: project }
+ let!(:assigned_issue) { create :issue, assignees: [current_user], project: project }
let!(:other_issue) { create :issue, project: project }
before do
@@ -30,6 +30,11 @@ RSpec.describe 'Dashboard Issues', feature: true do
find('#assignee_id', visible: false).set('')
find('.js-author-search', match: :first).click
find('.dropdown-menu-author li a', match: :first, text: current_user.to_reference).click
+ find('.js-author-search', match: :first).click
+
+ page.within '.dropdown-menu-user' do
+ expect(find('.dropdown-menu-author li a.is-active', match: :first, text: current_user.to_reference)).to be_visible
+ end
expect(page).to have_content(authored_issue.title)
expect(page).to have_content(authored_issue_on_public_project.title)
diff --git a/spec/features/dashboard_issues_spec.rb b/spec/features/dashboard_issues_spec.rb
index b6b87905231..ad60fb2c74f 100644
--- a/spec/features/dashboard_issues_spec.rb
+++ b/spec/features/dashboard_issues_spec.rb
@@ -10,8 +10,8 @@ describe "Dashboard Issues filtering", feature: true, js: true do
project.team << [user, :master]
login_as(user)
- create(:issue, project: project, author: user, assignee: user)
- create(:issue, project: project, author: user, assignee: user, milestone: milestone)
+ create(:issue, project: project, author: user, assignees: [user])
+ create(:issue, project: project, author: user, assignees: [user], milestone: milestone)
visit_issues
end
diff --git a/spec/features/gitlab_flavored_markdown_spec.rb b/spec/features/gitlab_flavored_markdown_spec.rb
index f5b54463df8..005a029a393 100644
--- a/spec/features/gitlab_flavored_markdown_spec.rb
+++ b/spec/features/gitlab_flavored_markdown_spec.rb
@@ -54,11 +54,11 @@ describe "GitLab Flavored Markdown", feature: true do
before do
@other_issue = create(:issue,
author: @user,
- assignee: @user,
+ assignees: [@user],
project: project)
@issue = create(:issue,
author: @user,
- assignee: @user,
+ assignees: [@user],
project: project,
title: "fix #{@other_issue.to_reference}",
description: "ask #{fred.to_reference} for details")
diff --git a/spec/features/groups/group_settings_spec.rb b/spec/features/groups/group_settings_spec.rb
new file mode 100644
index 00000000000..cc25db4ad60
--- /dev/null
+++ b/spec/features/groups/group_settings_spec.rb
@@ -0,0 +1,80 @@
+require 'spec_helper'
+
+feature 'Edit group settings', feature: true do
+ given(:user) { create(:user) }
+ given(:group) { create(:group, path: 'foo') }
+
+ background do
+ group.add_owner(user)
+ login_as(user)
+ end
+
+ describe 'when the group path is changed' do
+ let(:new_group_path) { 'bar' }
+ let(:old_group_full_path) { "/#{group.path}" }
+ let(:new_group_full_path) { "/#{new_group_path}" }
+
+ scenario 'the group is accessible via the new path' do
+ update_path(new_group_path)
+ visit new_group_full_path
+ expect(current_path).to eq(new_group_full_path)
+ expect(find('h1.group-title')).to have_content(new_group_path)
+ end
+
+ scenario 'the old group path redirects to the new path' do
+ update_path(new_group_path)
+ visit old_group_full_path
+ expect(current_path).to eq(new_group_full_path)
+ expect(find('h1.group-title')).to have_content(new_group_path)
+ end
+
+ context 'with a subgroup' do
+ given!(:subgroup) { create(:group, parent: group, path: 'subgroup') }
+ given(:old_subgroup_full_path) { "/#{group.path}/#{subgroup.path}" }
+ given(:new_subgroup_full_path) { "/#{new_group_path}/#{subgroup.path}" }
+
+ scenario 'the subgroup is accessible via the new path' do
+ update_path(new_group_path)
+ visit new_subgroup_full_path
+ expect(current_path).to eq(new_subgroup_full_path)
+ expect(find('h1.group-title')).to have_content(subgroup.path)
+ end
+
+ scenario 'the old subgroup path redirects to the new path' do
+ update_path(new_group_path)
+ visit old_subgroup_full_path
+ expect(current_path).to eq(new_subgroup_full_path)
+ expect(find('h1.group-title')).to have_content(subgroup.path)
+ end
+ end
+
+ context 'with a project' do
+ given!(:project) { create(:project, group: group, path: 'project') }
+ given(:old_project_full_path) { "/#{group.path}/#{project.path}" }
+ given(:new_project_full_path) { "/#{new_group_path}/#{project.path}" }
+
+ before(:context) { TestEnv.clean_test_path }
+ after(:example) { TestEnv.clean_test_path }
+
+ scenario 'the project is accessible via the new path' do
+ update_path(new_group_path)
+ visit new_project_full_path
+ expect(current_path).to eq(new_project_full_path)
+ expect(find('h1.project-title')).to have_content(project.name)
+ end
+
+ scenario 'the old project path redirects to the new path' do
+ update_path(new_group_path)
+ visit old_project_full_path
+ expect(current_path).to eq(new_project_full_path)
+ expect(find('h1.project-title')).to have_content(project.name)
+ end
+ end
+ end
+end
+
+def update_path(new_group_path)
+ visit edit_group_path(group)
+ fill_in 'group_path', with: new_group_path
+ click_button 'Save group'
+end
diff --git a/spec/features/issues/award_emoji_spec.rb b/spec/features/issues/award_emoji_spec.rb
index 71df3c949db..853632614c4 100644
--- a/spec/features/issues/award_emoji_spec.rb
+++ b/spec/features/issues/award_emoji_spec.rb
@@ -7,7 +7,7 @@ describe 'Awards Emoji', feature: true do
let!(:user) { create(:user) }
let(:issue) do
create(:issue,
- assignee: @user,
+ assignees: [user],
project: project)
end
diff --git a/spec/features/issues/award_spec.rb b/spec/features/issues/award_spec.rb
index 401e1ea2b89..08e3f99e29f 100644
--- a/spec/features/issues/award_spec.rb
+++ b/spec/features/issues/award_spec.rb
@@ -6,9 +6,12 @@ feature 'Issue awards', js: true, feature: true do
let(:issue) { create(:issue, project: project) }
describe 'logged in' do
+ include WaitForVueResource
+
before do
login_as(user)
visit namespace_project_issue_path(project.namespace, project, issue)
+ wait_for_vue_resource
end
it 'adds award to issue' do
@@ -38,8 +41,11 @@ feature 'Issue awards', js: true, feature: true do
end
describe 'logged out' do
+ include WaitForVueResource
+
before do
visit namespace_project_issue_path(project.namespace, project, issue)
+ wait_for_vue_resource
end
it 'does not see award menu button' do
diff --git a/spec/features/issues/filtered_search/filter_issues_spec.rb b/spec/features/issues/filtered_search/filter_issues_spec.rb
index c824aa6a414..a8f4e2d7e10 100644
--- a/spec/features/issues/filtered_search/filter_issues_spec.rb
+++ b/spec/features/issues/filtered_search/filter_issues_spec.rb
@@ -51,15 +51,15 @@ describe 'Filter issues', js: true, feature: true do
create(:issue, project: project, title: "issue with 'single quotes'")
create(:issue, project: project, title: "issue with \"double quotes\"")
create(:issue, project: project, title: "issue with !@\#{$%^&*()-+")
- create(:issue, project: project, title: "issue by assignee", milestone: milestone, author: user, assignee: user)
- create(:issue, project: project, title: "issue by assignee with searchTerm", milestone: milestone, author: user, assignee: user)
+ create(:issue, project: project, title: "issue by assignee", milestone: milestone, author: user, assignees: [user])
+ create(:issue, project: project, title: "issue by assignee with searchTerm", milestone: milestone, author: user, assignees: [user])
issue = create(:issue,
title: "Bug 2",
project: project,
milestone: milestone,
author: user,
- assignee: user)
+ assignees: [user])
issue.labels << bug_label
issue_with_caps_label = create(:issue,
@@ -67,7 +67,7 @@ describe 'Filter issues', js: true, feature: true do
project: project,
milestone: milestone,
author: user,
- assignee: user)
+ assignees: [user])
issue_with_caps_label.labels << caps_sensitive_label
issue_with_everything = create(:issue,
@@ -75,7 +75,7 @@ describe 'Filter issues', js: true, feature: true do
project: project,
milestone: milestone,
author: user,
- assignee: user)
+ assignees: [user])
issue_with_everything.labels << bug_label
issue_with_everything.labels << caps_sensitive_label
diff --git a/spec/features/issues/form_spec.rb b/spec/features/issues/form_spec.rb
index 21b8cf3add5..87adce3cddd 100644
--- a/spec/features/issues/form_spec.rb
+++ b/spec/features/issues/form_spec.rb
@@ -10,7 +10,7 @@ describe 'New/edit issue', feature: true, js: true do
let!(:milestone) { create(:milestone, project: project) }
let!(:label) { create(:label, project: project) }
let!(:label2) { create(:label, project: project) }
- let!(:issue) { create(:issue, project: project, assignee: user, milestone: milestone) }
+ let!(:issue) { create(:issue, project: project, assignees: [user], milestone: milestone) }
before do
project.team << [user, :master]
@@ -23,23 +23,62 @@ describe 'New/edit issue', feature: true, js: true do
visit new_namespace_project_issue_path(project.namespace, project)
end
+ describe 'multiple assignees' do
+ before do
+ click_button 'Unassigned'
+ end
+
+ it 'unselects other assignees when unassigned is selected' do
+ page.within '.dropdown-menu-user' do
+ click_link user2.name
+ end
+
+ page.within '.dropdown-menu-user' do
+ click_link 'Unassigned'
+ end
+
+ page.within '.js-assignee-search' do
+ expect(page).to have_content 'Unassigned'
+ end
+
+ expect(find('input[name="issue[assignee_ids][]"]', visible: false).value).to match('0')
+ end
+
+ it 'toggles assign to me when current user is selected and unselected' do
+ page.within '.dropdown-menu-user' do
+ click_link user.name
+ end
+
+ expect(find('a', text: 'Assign to me', visible: false)).not_to be_visible
+
+ page.within '.dropdown-menu-user' do
+ click_link user.name
+ end
+
+ expect(find('a', text: 'Assign to me')).to be_visible
+ end
+ end
+
it 'allows user to create new issue' do
fill_in 'issue_title', with: 'title'
fill_in 'issue_description', with: 'title'
expect(find('a', text: 'Assign to me')).to be_visible
- click_button 'Assignee'
+ click_button 'Unassigned'
page.within '.dropdown-menu-user' do
click_link user2.name
end
- expect(find('input[name="issue[assignee_id]"]', visible: false).value).to match(user2.id.to_s)
+ expect(find('input[name="issue[assignee_ids][]"]', visible: false).value).to match(user2.id.to_s)
page.within '.js-assignee-search' do
expect(page).to have_content user2.name
end
expect(find('a', text: 'Assign to me')).to be_visible
click_link 'Assign to me'
- expect(find('input[name="issue[assignee_id]"]', visible: false).value).to match(user.id.to_s)
+ assignee_ids = page.all('input[name="issue[assignee_ids][]"]', visible: false)
+
+ expect(assignee_ids[0].value).to match(user.id.to_s)
+
page.within '.js-assignee-search' do
expect(page).to have_content user.name
end
@@ -69,7 +108,7 @@ describe 'New/edit issue', feature: true, js: true do
page.within '.issuable-sidebar' do
page.within '.assignee' do
- expect(page).to have_content user.name
+ expect(page).to have_content "Assignee"
end
page.within '.milestone' do
@@ -108,12 +147,12 @@ describe 'New/edit issue', feature: true, js: true do
end
it 'correctly updates the selected user when changing assignee' do
- click_button 'Assignee'
+ click_button 'Unassigned'
page.within '.dropdown-menu-user' do
click_link user.name
end
- expect(find('input[name="issue[assignee_id]"]', visible: false).value).to match(user.id.to_s)
+ expect(find('input[name="issue[assignee_ids][]"]', visible: false).value).to match(user.id.to_s)
click_button user.name
@@ -127,7 +166,7 @@ describe 'New/edit issue', feature: true, js: true do
click_link user2.name
end
- expect(find('input[name="issue[assignee_id]"]', visible: false).value).to match(user2.id.to_s)
+ expect(find('input[name="issue[assignee_ids][]"]', visible: false).value).to match(user2.id.to_s)
click_button user2.name
@@ -141,7 +180,7 @@ describe 'New/edit issue', feature: true, js: true do
end
it 'allows user to update issue' do
- expect(find('input[name="issue[assignee_id]"]', visible: false).value).to match(user.id.to_s)
+ expect(find('input[name="issue[assignee_ids][]"]', visible: false).value).to match(user.id.to_s)
expect(find('input[name="issue[milestone_id]"]', visible: false).value).to match(milestone.id.to_s)
expect(find('a', text: 'Assign to me', visible: false)).not_to be_visible
diff --git a/spec/features/issues/issue_sidebar_spec.rb b/spec/features/issues/issue_sidebar_spec.rb
index 82b80a69bed..0de0f93089a 100644
--- a/spec/features/issues/issue_sidebar_spec.rb
+++ b/spec/features/issues/issue_sidebar_spec.rb
@@ -42,6 +42,21 @@ feature 'Issue Sidebar', feature: true do
expect(page).to have_content(user2.name)
end
end
+
+ it 'assigns yourself' do
+ find('.block.assignee .dropdown-menu-toggle').click
+
+ click_button 'assign yourself'
+
+ wait_for_ajax
+
+ find('.block.assignee .edit-link').click
+
+ page.within '.dropdown-menu-user' do
+ expect(page.find('.dropdown-header')).to be_visible
+ expect(page.find('.dropdown-menu-user-link.is-active')).to have_content(user.name)
+ end
+ end
end
context 'as a allowed user' do
@@ -152,7 +167,7 @@ feature 'Issue Sidebar', feature: true do
end
def open_issue_sidebar
- find('aside.right-sidebar.right-sidebar-collapsed .js-sidebar-toggle').click
+ find('aside.right-sidebar.right-sidebar-collapsed .js-sidebar-toggle').trigger('click')
find('aside.right-sidebar.right-sidebar-expanded')
end
end
diff --git a/spec/features/issues/update_issues_spec.rb b/spec/features/issues/update_issues_spec.rb
index 7fa83c1fcf7..b250fa2ed3c 100644
--- a/spec/features/issues/update_issues_spec.rb
+++ b/spec/features/issues/update_issues_spec.rb
@@ -99,7 +99,7 @@ feature 'Multiple issue updating from issues#index', feature: true do
end
def create_assigned
- create(:issue, project: project, assignee: user)
+ create(:issue, project: project, assignees: [user])
end
def create_with_milestone
diff --git a/spec/features/issues_spec.rb b/spec/features/issues_spec.rb
index 81cc8513454..5285dda361b 100644
--- a/spec/features/issues_spec.rb
+++ b/spec/features/issues_spec.rb
@@ -18,7 +18,7 @@ describe 'Issues', feature: true do
let!(:issue) do
create(:issue,
author: @user,
- assignee: @user,
+ assignees: [@user],
project: project)
end
@@ -43,7 +43,7 @@ describe 'Issues', feature: true do
let!(:issue) do
create(:issue,
author: @user,
- assignee: @user,
+ assignees: [@user],
project: project)
end
@@ -61,7 +61,7 @@ describe 'Issues', feature: true do
expect(page).to have_content 'No assignee - assign yourself'
end
- expect(issue.reload.assignee).to be_nil
+ expect(issue.reload.assignees).to be_empty
end
end
@@ -138,7 +138,7 @@ describe 'Issues', feature: true do
describe 'Issue info' do
it 'excludes award_emoji from comment count' do
- issue = create(:issue, author: @user, assignee: @user, project: project, title: 'foobar')
+ issue = create(:issue, author: @user, assignees: [@user], project: project, title: 'foobar')
create(:award_emoji, awardable: issue)
visit namespace_project_issues_path(project.namespace, project, assignee_id: @user.id)
@@ -153,14 +153,14 @@ describe 'Issues', feature: true do
%w(foobar barbaz gitlab).each do |title|
create(:issue,
author: @user,
- assignee: @user,
+ assignees: [@user],
project: project,
title: title)
end
@issue = Issue.find_by(title: 'foobar')
@issue.milestone = create(:milestone, project: project)
- @issue.assignee = nil
+ @issue.assignees = []
@issue.save
end
@@ -351,9 +351,9 @@ describe 'Issues', feature: true do
let(:user2) { create(:user) }
before do
- foo.assignee = user2
+ foo.assignees << user2
foo.save
- bar.assignee = user2
+ bar.assignees << user2
bar.save
end
@@ -396,7 +396,7 @@ describe 'Issues', feature: true do
end
describe 'update labels from issue#show', js: true do
- let(:issue) { create(:issue, project: project, author: @user, assignee: @user) }
+ let(:issue) { create(:issue, project: project, author: @user, assignees: [@user]) }
let!(:label) { create(:label, project: project) }
before do
@@ -415,7 +415,7 @@ describe 'Issues', feature: true do
end
describe 'update assignee from issue#show' do
- let(:issue) { create(:issue, project: project, author: @user, assignee: @user) }
+ let(:issue) { create(:issue, project: project, author: @user, assignees: [@user]) }
context 'by authorized user' do
it 'allows user to select unassigned', js: true do
@@ -426,10 +426,14 @@ describe 'Issues', feature: true do
click_link 'Edit'
click_link 'Unassigned'
+ first('.title').click
expect(page).to have_content 'No assignee'
end
- expect(issue.reload.assignee).to be_nil
+ # wait_for_ajax does not work with vue-resource at the moment
+ sleep 1
+
+ expect(issue.reload.assignees).to be_empty
end
it 'allows user to select an assignee', js: true do
@@ -461,14 +465,18 @@ describe 'Issues', feature: true do
click_link 'Edit'
click_link @user.name
- page.within '.value' do
+ find('.dropdown-menu-toggle').click
+
+ page.within '.value .author' do
expect(page).to have_content @user.name
end
click_link 'Edit'
click_link @user.name
- page.within '.value' do
+ find('.dropdown-menu-toggle').click
+
+ page.within '.value .assign-yourself' do
expect(page).to have_content "No assignee"
end
end
@@ -487,7 +495,7 @@ describe 'Issues', feature: true do
login_with guest
visit namespace_project_issue_path(project.namespace, project, issue)
- expect(page).to have_content issue.assignee.name
+ expect(page).to have_content issue.assignees.first.name
end
end
end
@@ -558,7 +566,7 @@ describe 'Issues', feature: true do
let(:user2) { create(:user) }
before do
- issue.assignee = user2
+ issue.assignees << user2
issue.save
end
end
@@ -655,7 +663,7 @@ describe 'Issues', feature: true do
describe 'due date' do
context 'update due on issue#show', js: true do
- let(:issue) { create(:issue, project: project, author: @user, assignee: @user) }
+ let(:issue) { create(:issue, project: project, author: @user, assignees: [@user]) }
before do
visit namespace_project_issue_path(project.namespace, project, issue)
@@ -702,7 +710,7 @@ describe 'Issues', feature: true do
include WaitForVueResource
it 'updates the title', js: true do
- issue = create(:issue, author: @user, assignee: @user, project: project, title: 'new title')
+ issue = create(:issue, author: @user, assignees: [@user], project: project, title: 'new title')
visit namespace_project_issue_path(project.namespace, project, issue)
diff --git a/spec/features/merge_requests/assign_issues_spec.rb b/spec/features/merge_requests/assign_issues_spec.rb
index 43cc6f2a2a7..ec49003772b 100644
--- a/spec/features/merge_requests/assign_issues_spec.rb
+++ b/spec/features/merge_requests/assign_issues_spec.rb
@@ -33,7 +33,7 @@ feature 'Merge request issue assignment', js: true, feature: true do
end
it "doesn't display if related issues are already assigned" do
- [issue1, issue2].each { |issue| issue.update!(assignee: user) }
+ [issue1, issue2].each { |issue| issue.update!(assignees: [user]) }
visit_merge_request
diff --git a/spec/features/milestones/show_spec.rb b/spec/features/milestones/show_spec.rb
index 40b4dc63697..227eb04ba72 100644
--- a/spec/features/milestones/show_spec.rb
+++ b/spec/features/milestones/show_spec.rb
@@ -5,7 +5,7 @@ describe 'Milestone show', feature: true do
let(:project) { create(:empty_project) }
let(:milestone) { create(:milestone, project: project) }
let(:labels) { create_list(:label, 2, project: project) }
- let(:issue_params) { { project: project, assignee: user, author: user, milestone: milestone, labels: labels } }
+ let(:issue_params) { { project: project, assignees: [user], author: user, milestone: milestone, labels: labels } }
before do
project.add_user(user, :developer)
diff --git a/spec/features/profiles/account_spec.rb b/spec/features/profiles/account_spec.rb
new file mode 100644
index 00000000000..05a7587f8d4
--- /dev/null
+++ b/spec/features/profiles/account_spec.rb
@@ -0,0 +1,59 @@
+require 'rails_helper'
+
+feature 'Profile > Account', feature: true do
+ given(:user) { create(:user, username: 'foo') }
+
+ before do
+ login_as(user)
+ end
+
+ describe 'Change username' do
+ given(:new_username) { 'bar' }
+ given(:new_user_path) { "/#{new_username}" }
+ given(:old_user_path) { "/#{user.username}" }
+
+ scenario 'the user is accessible via the new path' do
+ update_username(new_username)
+ visit new_user_path
+ expect(current_path).to eq(new_user_path)
+ expect(find('.user-info')).to have_content(new_username)
+ end
+
+ scenario 'the old user path redirects to the new path' do
+ update_username(new_username)
+ visit old_user_path
+ expect(current_path).to eq(new_user_path)
+ expect(find('.user-info')).to have_content(new_username)
+ end
+
+ context 'with a project' do
+ given!(:project) { create(:project, namespace: user.namespace, path: 'project') }
+ given(:new_project_path) { "/#{new_username}/#{project.path}" }
+ given(:old_project_path) { "/#{user.username}/#{project.path}" }
+
+ before(:context) { TestEnv.clean_test_path }
+ after(:example) { TestEnv.clean_test_path }
+
+ scenario 'the project is accessible via the new path' do
+ update_username(new_username)
+ visit new_project_path
+ expect(current_path).to eq(new_project_path)
+ expect(find('h1.project-title')).to have_content(project.name)
+ end
+
+ scenario 'the old project path redirects to the new path' do
+ update_username(new_username)
+ visit old_project_path
+ expect(current_path).to eq(new_project_path)
+ expect(find('h1.project-title')).to have_content(project.name)
+ end
+ end
+ end
+end
+
+def update_username(new_username)
+ allow(user.namespace).to receive(:move_dir)
+ visit profile_account_path
+ fill_in 'user_username', with: new_username
+ click_button 'Update username'
+end
diff --git a/spec/features/projects/environments/environment_spec.rb b/spec/features/projects/environments/environment_spec.rb
index 1e12f8542e2..86ce50c976f 100644
--- a/spec/features/projects/environments/environment_spec.rb
+++ b/spec/features/projects/environments/environment_spec.rb
@@ -62,6 +62,8 @@ feature 'Environment', :feature do
name: 'deploy to production')
end
+ given(:role) { :master }
+
scenario 'does show a play button' do
expect(page).to have_link(action.name.humanize)
end
@@ -132,6 +134,8 @@ feature 'Environment', :feature do
on_stop: 'close_app')
end
+ given(:role) { :master }
+
scenario 'does allow to stop environment' do
click_link('Stop')
diff --git a/spec/features/projects/features_visibility_spec.rb b/spec/features/projects/features_visibility_spec.rb
index b080a8d500e..e1781cf320a 100644
--- a/spec/features/projects/features_visibility_spec.rb
+++ b/spec/features/projects/features_visibility_spec.rb
@@ -68,20 +68,23 @@ describe 'Edit Project Settings', feature: true do
end
describe 'project features visibility pages' do
- before do
- @tools =
- {
- builds: namespace_project_pipelines_path(project.namespace, project),
- issues: namespace_project_issues_path(project.namespace, project),
- wiki: namespace_project_wiki_path(project.namespace, project, :home),
- snippets: namespace_project_snippets_path(project.namespace, project),
- merge_requests: namespace_project_merge_requests_path(project.namespace, project),
- }
+ let(:tools) do
+ {
+ builds: namespace_project_pipelines_path(project.namespace, project),
+ issues: namespace_project_issues_path(project.namespace, project),
+ wiki: namespace_project_wiki_path(project.namespace, project, :home),
+ snippets: namespace_project_snippets_path(project.namespace, project),
+ merge_requests: namespace_project_merge_requests_path(project.namespace, project),
+ }
end
context 'normal user' do
+ before do
+ login_as(member)
+ end
+
it 'renders 200 if tool is enabled' do
- @tools.each do |method_name, url|
+ tools.each do |method_name, url|
project.project_feature.update_attribute("#{method_name}_access_level", ProjectFeature::ENABLED)
visit url
expect(page.status_code).to eq(200)
@@ -89,7 +92,7 @@ describe 'Edit Project Settings', feature: true do
end
it 'renders 404 if feature is disabled' do
- @tools.each do |method_name, url|
+ tools.each do |method_name, url|
project.project_feature.update_attribute("#{method_name}_access_level", ProjectFeature::DISABLED)
visit url
expect(page.status_code).to eq(404)
@@ -99,21 +102,21 @@ describe 'Edit Project Settings', feature: true do
it 'renders 404 if feature is enabled only for team members' do
project.team.truncate
- @tools.each do |method_name, url|
+ tools.each do |method_name, url|
project.project_feature.update_attribute("#{method_name}_access_level", ProjectFeature::PRIVATE)
visit url
expect(page.status_code).to eq(404)
end
end
- it 'renders 200 if users is member of group' do
+ it 'renders 200 if user is member of group' do
group = create(:group)
project.group = group
project.save
group.add_owner(member)
- @tools.each do |method_name, url|
+ tools.each do |method_name, url|
project.project_feature.update_attribute("#{method_name}_access_level", ProjectFeature::PRIVATE)
visit url
expect(page.status_code).to eq(200)
@@ -128,7 +131,7 @@ describe 'Edit Project Settings', feature: true do
end
it 'renders 404 if feature is disabled' do
- @tools.each do |method_name, url|
+ tools.each do |method_name, url|
project.project_feature.update_attribute("#{method_name}_access_level", ProjectFeature::DISABLED)
visit url
expect(page.status_code).to eq(404)
@@ -138,7 +141,7 @@ describe 'Edit Project Settings', feature: true do
it 'renders 200 if feature is enabled only for team members' do
project.team.truncate
- @tools.each do |method_name, url|
+ tools.each do |method_name, url|
project.project_feature.update_attribute("#{method_name}_access_level", ProjectFeature::PRIVATE)
visit url
expect(page.status_code).to eq(200)
diff --git a/spec/features/projects/issuable_templates_spec.rb b/spec/features/projects/issuable_templates_spec.rb
index d28a853bbc2..fa5e30075e3 100644
--- a/spec/features/projects/issuable_templates_spec.rb
+++ b/spec/features/projects/issuable_templates_spec.rb
@@ -12,7 +12,7 @@ feature 'issuable templates', feature: true, js: true do
context 'user creates an issue using templates' do
let(:template_content) { 'this is a test "bug" template' }
let(:longtemplate_content) { %Q(this\n\n\n\n\nis\n\n\n\n\na\n\n\n\n\nbug\n\n\n\n\ntemplate) }
- let(:issue) { create(:issue, author: user, assignee: user, project: project) }
+ let(:issue) { create(:issue, author: user, assignees: [user], project: project) }
let(:description_addition) { ' appending to description' }
background do
@@ -72,7 +72,7 @@ feature 'issuable templates', feature: true, js: true do
context 'user creates an issue using templates, with a prior description' do
let(:prior_description) { 'test issue description' }
let(:template_content) { 'this is a test "bug" template' }
- let(:issue) { create(:issue, author: user, assignee: user, project: project) }
+ let(:issue) { create(:issue, author: user, assignees: [user], project: project) }
background do
project.repository.create_file(
diff --git a/spec/features/projects/pipelines/pipeline_spec.rb b/spec/features/projects/pipelines/pipeline_spec.rb
index 5a53e48f5f8..cfac54ef259 100644
--- a/spec/features/projects/pipelines/pipeline_spec.rb
+++ b/spec/features/projects/pipelines/pipeline_spec.rb
@@ -254,4 +254,57 @@ describe 'Pipeline', :feature, :js do
it { expect(build_manual.reload).to be_pending }
end
end
+
+ describe 'GET /:project/pipelines/:id/failures' do
+ let(:project) { create(:project) }
+ let(:pipeline) { create(:ci_pipeline, project: project, ref: 'master', sha: project.commit.id) }
+ let(:pipeline_failures_page) { failures_namespace_project_pipeline_path(project.namespace, project, pipeline) }
+ let!(:failed_build) { create(:ci_build, :failed, pipeline: pipeline) }
+
+ context 'with failed build' do
+ before do
+ failed_build.trace.set('4 examples, 1 failure')
+
+ visit pipeline_failures_page
+ end
+
+ it 'shows jobs tab pane as active' do
+ expect(page).to have_content('Failed Jobs')
+ expect(page).to have_css('#js-tab-failures.active')
+ end
+
+ it 'lists failed builds' do
+ expect(page).to have_content(failed_build.name)
+ expect(page).to have_content(failed_build.stage)
+ end
+
+ it 'shows build failure logs' do
+ expect(page).to have_content('4 examples, 1 failure')
+ end
+ end
+
+ context 'when missing build logs' do
+ before do
+ visit pipeline_failures_page
+ end
+
+ it 'includes failed jobs' do
+ expect(page).to have_content('No job trace')
+ end
+ end
+
+ context 'without failures' do
+ before do
+ failed_build.update!(status: :success)
+
+ visit pipeline_failures_page
+ end
+
+ it 'displays the pipeline graph' do
+ expect(current_path).to eq(pipeline_path(pipeline))
+ expect(page).not_to have_content('Failed Jobs')
+ expect(page).to have_selector('.pipeline-visualization')
+ end
+ end
+ end
end
diff --git a/spec/features/projects/project_settings_spec.rb b/spec/features/projects/project_settings_spec.rb
index 5d0314d5c09..11dcab4d737 100644
--- a/spec/features/projects/project_settings_spec.rb
+++ b/spec/features/projects/project_settings_spec.rb
@@ -1,64 +1,158 @@
require 'spec_helper'
describe 'Edit Project Settings', feature: true do
+ include Select2Helper
+
let(:user) { create(:user) }
- let(:project) { create(:empty_project, path: 'gitlab', name: 'sample') }
+ let(:project) { create(:empty_project, namespace: user.namespace, path: 'gitlab', name: 'sample') }
before do
login_as(user)
- project.team << [user, :master]
end
- describe 'Project settings', js: true do
+ describe 'Project settings section', js: true do
it 'shows errors for invalid project name' do
visit edit_namespace_project_path(project.namespace, project)
-
fill_in 'project_name_edit', with: 'foo&bar'
-
click_button 'Save changes'
-
expect(page).to have_field 'project_name_edit', with: 'foo&bar'
expect(page).to have_content "Name can contain only letters, digits, emojis, '_', '.', dash, space. It must start with letter, digit, emoji or '_'."
expect(page).to have_button 'Save changes'
end
- scenario 'shows a successful notice when the project is updated' do
+ it 'shows a successful notice when the project is updated' do
visit edit_namespace_project_path(project.namespace, project)
-
fill_in 'project_name_edit', with: 'hello world'
-
click_button 'Save changes'
-
expect(page).to have_content "Project 'hello world' was successfully updated."
end
end
- describe 'Rename repository' do
- it 'shows errors for invalid project path/name' do
- visit edit_namespace_project_path(project.namespace, project)
-
- fill_in 'project_name', with: 'foo&bar'
- fill_in 'Path', with: 'foo&bar'
+ describe 'Rename repository section' do
+ context 'with invalid characters' do
+ it 'shows errors for invalid project path/name' do
+ rename_project(project, name: 'foo&bar', path: 'foo&bar')
+ expect(page).to have_field 'Project name', with: 'foo&bar'
+ expect(page).to have_field 'Path', with: 'foo&bar'
+ expect(page).to have_content "Name can contain only letters, digits, emojis, '_', '.', dash, space. It must start with letter, digit, emoji or '_'."
+ expect(page).to have_content "Path can contain only letters, digits, '_', '-' and '.'. Cannot start with '-', end in '.git' or end in '.atom'"
+ end
+ end
- click_button 'Rename project'
+ context 'when changing project name' do
+ it 'renames the repository' do
+ rename_project(project, name: 'bar')
+ expect(find('h1.title')).to have_content(project.name)
+ end
+
+ context 'with emojis' do
+ it 'shows error for invalid project name' do
+ rename_project(project, name: '🚀 foo bar ☁️')
+ expect(page).to have_field 'Project name', with: '🚀 foo bar ☁️'
+ expect(page).not_to have_content "Name can contain only letters, digits, emojis '_', '.', dash and space. It must start with letter, digit, emoji or '_'."
+ end
+ end
+ end
- expect(page).to have_field 'Project name', with: 'foo&bar'
- expect(page).to have_field 'Path', with: 'foo&bar'
- expect(page).to have_content "Name can contain only letters, digits, emojis, '_', '.', dash, space. It must start with letter, digit, emoji or '_'."
- expect(page).to have_content "Path can contain only letters, digits, '_', '-' and '.'. Cannot start with '-', end in '.git' or end in '.atom'"
+ context 'when changing project path' do
+ # Not using empty project because we need a repo to exist
+ let(:project) { create(:project, namespace: user.namespace, name: 'gitlabhq') }
+
+ before(:context) { TestEnv.clean_test_path }
+ after(:example) { TestEnv.clean_test_path }
+
+ specify 'the project is accessible via the new path' do
+ rename_project(project, path: 'bar')
+ new_path = namespace_project_path(project.namespace, 'bar')
+ visit new_path
+ expect(current_path).to eq(new_path)
+ expect(find('h1.title')).to have_content(project.name)
+ end
+
+ specify 'the project is accessible via a redirect from the old path' do
+ old_path = namespace_project_path(project.namespace, project)
+ rename_project(project, path: 'bar')
+ new_path = namespace_project_path(project.namespace, 'bar')
+ visit old_path
+ expect(current_path).to eq(new_path)
+ expect(find('h1.title')).to have_content(project.name)
+ end
+
+ context 'and a new project is added with the same path' do
+ it 'overrides the redirect' do
+ old_path = namespace_project_path(project.namespace, project)
+ rename_project(project, path: 'bar')
+ new_project = create(:empty_project, namespace: user.namespace, path: 'gitlabhq', name: 'quz')
+ visit old_path
+ expect(current_path).to eq(old_path)
+ expect(find('h1.title')).to have_content(new_project.name)
+ end
+ end
end
end
- describe 'Rename repository name with emojis' do
- it 'shows error for invalid project name' do
- visit edit_namespace_project_path(project.namespace, project)
-
- fill_in 'project_name', with: '🚀 foo bar ☁️'
+ describe 'Transfer project section', js: true do
+ # Not using empty project because we need a repo to exist
+ let!(:project) { create(:project, namespace: user.namespace, name: 'gitlabhq') }
+ let!(:group) { create(:group) }
+
+ before(:context) { TestEnv.clean_test_path }
+ before(:example) { group.add_owner(user) }
+ after(:example) { TestEnv.clean_test_path }
+
+ specify 'the project is accessible via the new path' do
+ transfer_project(project, group)
+ new_path = namespace_project_path(group, project)
+ visit new_path
+ expect(current_path).to eq(new_path)
+ expect(find('h1.title')).to have_content(project.name)
+ end
- click_button 'Rename project'
+ specify 'the project is accessible via a redirect from the old path' do
+ old_path = namespace_project_path(project.namespace, project)
+ transfer_project(project, group)
+ new_path = namespace_project_path(group, project)
+ visit old_path
+ expect(current_path).to eq(new_path)
+ expect(find('h1.title')).to have_content(project.name)
+ end
- expect(page).to have_field 'Project name', with: '🚀 foo bar ☁️'
- expect(page).not_to have_content "Name can contain only letters, digits, emojis '_', '.', dash and space. It must start with letter, digit, emoji or '_'."
+ context 'and a new project is added with the same path' do
+ it 'overrides the redirect' do
+ old_path = namespace_project_path(project.namespace, project)
+ transfer_project(project, group)
+ new_project = create(:empty_project, namespace: user.namespace, path: 'gitlabhq', name: 'quz')
+ visit old_path
+ expect(current_path).to eq(old_path)
+ expect(find('h1.title')).to have_content(new_project.name)
+ end
end
end
end
+
+def rename_project(project, name: nil, path: nil)
+ visit edit_namespace_project_path(project.namespace, project)
+ fill_in('project_name', with: name) if name
+ fill_in('Path', with: path) if path
+ click_button('Rename project')
+ wait_for_edit_project_page_reload
+ project.reload
+end
+
+def transfer_project(project, namespace)
+ visit edit_namespace_project_path(project.namespace, project)
+ select2(namespace.id, from: '#new_namespace_id')
+ click_button('Transfer project')
+ confirm_transfer_modal
+ wait_for_edit_project_page_reload
+ project.reload
+end
+
+def confirm_transfer_modal
+ fill_in('confirm_name_input', with: project.path)
+ click_button 'Confirm'
+end
+
+def wait_for_edit_project_page_reload
+ expect(find('.project-edit-container')).to have_content('Rename repository')
+end
diff --git a/spec/features/raven_js_spec.rb b/spec/features/raven_js_spec.rb
new file mode 100644
index 00000000000..e8fa49c18cb
--- /dev/null
+++ b/spec/features/raven_js_spec.rb
@@ -0,0 +1,23 @@
+require 'spec_helper'
+
+feature 'RavenJS', :feature, :js do
+ let(:raven_path) { '/raven.bundle.js' }
+
+ it 'should not load raven if sentry is disabled' do
+ visit new_user_session_path
+
+ expect(has_requested_raven).to eq(false)
+ end
+
+ it 'should load raven if sentry is enabled' do
+ stub_application_setting(clientside_sentry_dsn: 'https://key@domain.com/id', clientside_sentry_enabled: true)
+
+ visit new_user_session_path
+
+ expect(has_requested_raven).to eq(true)
+ end
+
+ def has_requested_raven
+ page.driver.network_traffic.one? {|request| request.url.end_with?(raven_path)}
+ end
+end
diff --git a/spec/features/search_spec.rb b/spec/features/search_spec.rb
index da6388dcdf2..498a4a5cba0 100644
--- a/spec/features/search_spec.rb
+++ b/spec/features/search_spec.rb
@@ -5,7 +5,7 @@ describe "Search", feature: true do
let(:user) { create(:user) }
let(:project) { create(:empty_project, namespace: user.namespace) }
- let!(:issue) { create(:issue, project: project, assignee: user) }
+ let!(:issue) { create(:issue, project: project, assignees: [user]) }
let!(:issue2) { create(:issue, project: project, author: user) }
before do
diff --git a/spec/features/task_lists_spec.rb b/spec/features/task_lists_spec.rb
index c33692fc4a9..8bd13caf2b0 100644
--- a/spec/features/task_lists_spec.rb
+++ b/spec/features/task_lists_spec.rb
@@ -62,12 +62,15 @@ feature 'Task Lists', feature: true do
visit namespace_project_issue_path(project.namespace, project, issue)
end
- describe 'for Issues' do
- describe 'multiple tasks' do
+ describe 'for Issues', feature: true do
+ describe 'multiple tasks', js: true do
+ include WaitForVueResource
+
let!(:issue) { create(:issue, description: markdown, author: user, project: project) }
it 'renders' do
visit_issue(project, issue)
+ wait_for_vue_resource
expect(page).to have_selector('ul.task-list', count: 1)
expect(page).to have_selector('li.task-list-item', count: 6)
@@ -76,25 +79,24 @@ feature 'Task Lists', feature: true do
it 'contains the required selectors' do
visit_issue(project, issue)
+ wait_for_vue_resource
- container = '.detail-page-description .description.js-task-list-container'
-
- expect(page).to have_selector(container)
- expect(page).to have_selector("#{container} .wiki .task-list .task-list-item .task-list-item-checkbox")
- expect(page).to have_selector("#{container} .js-task-list-field")
- expect(page).to have_selector('form.js-issuable-update')
+ expect(page).to have_selector(".wiki .task-list .task-list-item .task-list-item-checkbox")
expect(page).to have_selector('a.btn-close')
end
it 'is only editable by author' do
visit_issue(project, issue)
- expect(page).to have_selector('.js-task-list-container')
+ wait_for_vue_resource
- logout(:user)
+ expect(page).to have_selector(".wiki .task-list .task-list-item .task-list-item-checkbox")
+ logout(:user)
login_as(user2)
visit current_path
- expect(page).not_to have_selector('.js-task-list-container')
+ wait_for_vue_resource
+
+ expect(page).to have_selector(".wiki .task-list .task-list-item .task-list-item-checkbox")
end
it 'provides a summary on Issues#index' do
@@ -103,11 +105,14 @@ feature 'Task Lists', feature: true do
end
end
- describe 'single incomplete task' do
+ describe 'single incomplete task', js: true do
+ include WaitForVueResource
+
let!(:issue) { create(:issue, description: singleIncompleteMarkdown, author: user, project: project) }
it 'renders' do
visit_issue(project, issue)
+ wait_for_vue_resource
expect(page).to have_selector('ul.task-list', count: 1)
expect(page).to have_selector('li.task-list-item', count: 1)
@@ -116,15 +121,18 @@ feature 'Task Lists', feature: true do
it 'provides a summary on Issues#index' do
visit namespace_project_issues_path(project.namespace, project)
+
expect(page).to have_content("0 of 1 task completed")
end
end
- describe 'single complete task' do
+ describe 'single complete task', js: true do
+ include WaitForVueResource
let!(:issue) { create(:issue, description: singleCompleteMarkdown, author: user, project: project) }
it 'renders' do
visit_issue(project, issue)
+ wait_for_vue_resource
expect(page).to have_selector('ul.task-list', count: 1)
expect(page).to have_selector('li.task-list-item', count: 1)
@@ -133,6 +141,7 @@ feature 'Task Lists', feature: true do
it 'provides a summary on Issues#index' do
visit namespace_project_issues_path(project.namespace, project)
+
expect(page).to have_content("1 of 1 task completed")
end
end
diff --git a/spec/features/unsubscribe_links_spec.rb b/spec/features/unsubscribe_links_spec.rb
index e2d9cfdd0b0..a23c4ca2b92 100644
--- a/spec/features/unsubscribe_links_spec.rb
+++ b/spec/features/unsubscribe_links_spec.rb
@@ -6,7 +6,7 @@ describe 'Unsubscribe links', feature: true do
let(:recipient) { create(:user) }
let(:author) { create(:user) }
let(:project) { create(:empty_project, :public) }
- let(:params) { { title: 'A bug!', description: 'Fix it!', assignee: recipient } }
+ let(:params) { { title: 'A bug!', description: 'Fix it!', assignees: [recipient] } }
let(:issue) { Issues::CreateService.new(project, author, params).execute }
let(:mail) { ActionMailer::Base.deliveries.last }
diff --git a/spec/finders/issues_finder_spec.rb b/spec/finders/issues_finder_spec.rb
index a5f717e6233..96151689359 100644
--- a/spec/finders/issues_finder_spec.rb
+++ b/spec/finders/issues_finder_spec.rb
@@ -7,12 +7,12 @@ describe IssuesFinder do
set(:project2) { create(:empty_project) }
set(:milestone) { create(:milestone, project: project1) }
set(:label) { create(:label, project: project2) }
- set(:issue1) { create(:issue, author: user, assignee: user, project: project1, milestone: milestone, title: 'gitlab') }
- set(:issue2) { create(:issue, author: user, assignee: user, project: project2, description: 'gitlab') }
- set(:issue3) { create(:issue, author: user2, assignee: user2, project: project2, title: 'tanuki', description: 'tanuki') }
+ set(:issue1) { create(:issue, author: user, assignees: [user], project: project1, milestone: milestone, title: 'gitlab') }
+ set(:issue2) { create(:issue, author: user, assignees: [user], project: project2, description: 'gitlab') }
+ set(:issue3) { create(:issue, author: user2, assignees: [user2], project: project2, title: 'tanuki', description: 'tanuki') }
describe '#execute' do
- set(:closed_issue) { create(:issue, author: user2, assignee: user2, project: project2, state: 'closed') }
+ set(:closed_issue) { create(:issue, author: user2, assignees: [user2], project: project2, state: 'closed') }
set(:label_link) { create(:label_link, label: label, target: issue2) }
let(:search_user) { user }
let(:params) { {} }
@@ -91,7 +91,7 @@ describe IssuesFinder do
before do
milestones.each do |milestone|
- create(:issue, project: milestone.project, milestone: milestone, author: user, assignee: user)
+ create(:issue, project: milestone.project, milestone: milestone, author: user, assignees: [user])
end
end
@@ -126,7 +126,7 @@ describe IssuesFinder do
before do
milestones.each do |milestone|
- create(:issue, project: milestone.project, milestone: milestone, author: user, assignee: user)
+ create(:issue, project: milestone.project, milestone: milestone, author: user, assignees: [user])
end
end
diff --git a/spec/fixtures/api/schemas/issue.json b/spec/fixtures/api/schemas/issue.json
index 21c078e0f44..ff86437fdd5 100644
--- a/spec/fixtures/api/schemas/issue.json
+++ b/spec/fixtures/api/schemas/issue.json
@@ -46,6 +46,24 @@
"username": { "type": "string" },
"avatar_url": { "type": "uri" }
},
+ "assignees": {
+ "type": "array",
+ "items": {
+ "type": ["object", "null"],
+ "required": [
+ "id",
+ "name",
+ "username",
+ "avatar_url"
+ ],
+ "properties": {
+ "id": { "type": "integer" },
+ "name": { "type": "string" },
+ "username": { "type": "string" },
+ "avatar_url": { "type": "uri" }
+ }
+ }
+ },
"subscribed": { "type": ["boolean", "null"] }
},
"additionalProperties": false
diff --git a/spec/fixtures/api/schemas/pipeline.json b/spec/fixtures/api/schemas/pipeline.json
new file mode 100644
index 00000000000..55511d17b5e
--- /dev/null
+++ b/spec/fixtures/api/schemas/pipeline.json
@@ -0,0 +1,354 @@
+{
+ "$schema": "http://json-schema.org/draft-04/schema#",
+ "definitions": {},
+ "id": "http://example.com/example.json",
+ "properties": {
+ "commit": {
+ "id": "/properties/commit",
+ "properties": {
+ "author": {
+ "id": "/properties/commit/properties/author",
+ "type": "null"
+ },
+ "author_email": {
+ "id": "/properties/commit/properties/author_email",
+ "type": "string"
+ },
+ "author_gravatar_url": {
+ "id": "/properties/commit/properties/author_gravatar_url",
+ "type": "string"
+ },
+ "author_name": {
+ "id": "/properties/commit/properties/author_name",
+ "type": "string"
+ },
+ "authored_date": {
+ "id": "/properties/commit/properties/authored_date",
+ "type": "string"
+ },
+ "commit_path": {
+ "id": "/properties/commit/properties/commit_path",
+ "type": "string"
+ },
+ "commit_url": {
+ "id": "/properties/commit/properties/commit_url",
+ "type": "string"
+ },
+ "committed_date": {
+ "id": "/properties/commit/properties/committed_date",
+ "type": "string"
+ },
+ "committer_email": {
+ "id": "/properties/commit/properties/committer_email",
+ "type": "string"
+ },
+ "committer_name": {
+ "id": "/properties/commit/properties/committer_name",
+ "type": "string"
+ },
+ "created_at": {
+ "id": "/properties/commit/properties/created_at",
+ "type": "string"
+ },
+ "id": {
+ "id": "/properties/commit/properties/id",
+ "type": "string"
+ },
+ "message": {
+ "id": "/properties/commit/properties/message",
+ "type": "string"
+ },
+ "parent_ids": {
+ "id": "/properties/commit/properties/parent_ids",
+ "items": {
+ "id": "/properties/commit/properties/parent_ids/items",
+ "type": "string"
+ },
+ "type": "array"
+ },
+ "short_id": {
+ "id": "/properties/commit/properties/short_id",
+ "type": "string"
+ },
+ "title": {
+ "id": "/properties/commit/properties/title",
+ "type": "string"
+ }
+ },
+ "type": "object"
+ },
+ "created_at": {
+ "id": "/properties/created_at",
+ "type": "string"
+ },
+ "details": {
+ "id": "/properties/details",
+ "properties": {
+ "artifacts": {
+ "id": "/properties/details/properties/artifacts",
+ "items": {},
+ "type": "array"
+ },
+ "duration": {
+ "id": "/properties/details/properties/duration",
+ "type": "integer"
+ },
+ "finished_at": {
+ "id": "/properties/details/properties/finished_at",
+ "type": "string"
+ },
+ "manual_actions": {
+ "id": "/properties/details/properties/manual_actions",
+ "items": {},
+ "type": "array"
+ },
+ "stages": {
+ "id": "/properties/details/properties/stages",
+ "items": {
+ "id": "/properties/details/properties/stages/items",
+ "properties": {
+ "dropdown_path": {
+ "id": "/properties/details/properties/stages/items/properties/dropdown_path",
+ "type": "string"
+ },
+ "groups": {
+ "id": "/properties/details/properties/stages/items/properties/groups",
+ "items": {
+ "id": "/properties/details/properties/stages/items/properties/groups/items",
+ "properties": {
+ "name": {
+ "id": "/properties/details/properties/stages/items/properties/groups/items/properties/name",
+ "type": "string"
+ },
+ "size": {
+ "id": "/properties/details/properties/stages/items/properties/groups/items/properties/size",
+ "type": "integer"
+ },
+ "status": {
+ "id": "/properties/details/properties/stages/items/properties/groups/items/properties/status",
+ "properties": {
+ "details_path": {
+ "id": "/properties/details/properties/stages/items/properties/groups/items/properties/status/properties/details_path",
+ "type": "null"
+ },
+ "favicon": {
+ "id": "/properties/details/properties/stages/items/properties/groups/items/properties/status/properties/favicon",
+ "type": "string"
+ },
+ "group": {
+ "id": "/properties/details/properties/stages/items/properties/groups/items/properties/status/properties/group",
+ "type": "string"
+ },
+ "has_details": {
+ "id": "/properties/details/properties/stages/items/properties/groups/items/properties/status/properties/has_details",
+ "type": "boolean"
+ },
+ "icon": {
+ "id": "/properties/details/properties/stages/items/properties/groups/items/properties/status/properties/icon",
+ "type": "string"
+ },
+ "label": {
+ "id": "/properties/details/properties/stages/items/properties/groups/items/properties/status/properties/label",
+ "type": "string"
+ },
+ "text": {
+ "id": "/properties/details/properties/stages/items/properties/groups/items/properties/status/properties/text",
+ "type": "string"
+ }
+ },
+ "type": "object"
+ }
+ },
+ "type": "object"
+ },
+ "type": "array"
+ },
+ "name": {
+ "id": "/properties/details/properties/stages/items/properties/name",
+ "type": "string"
+ },
+ "path": {
+ "id": "/properties/details/properties/stages/items/properties/path",
+ "type": "string"
+ },
+ "status": {
+ "id": "/properties/details/properties/stages/items/properties/status",
+ "properties": {
+ "details_path": {
+ "id": "/properties/details/properties/stages/items/properties/status/properties/details_path",
+ "type": "string"
+ },
+ "favicon": {
+ "id": "/properties/details/properties/stages/items/properties/status/properties/favicon",
+ "type": "string"
+ },
+ "group": {
+ "id": "/properties/details/properties/stages/items/properties/status/properties/group",
+ "type": "string"
+ },
+ "has_details": {
+ "id": "/properties/details/properties/stages/items/properties/status/properties/has_details",
+ "type": "boolean"
+ },
+ "icon": {
+ "id": "/properties/details/properties/stages/items/properties/status/properties/icon",
+ "type": "string"
+ },
+ "label": {
+ "id": "/properties/details/properties/stages/items/properties/status/properties/label",
+ "type": "string"
+ },
+ "text": {
+ "id": "/properties/details/properties/stages/items/properties/status/properties/text",
+ "type": "string"
+ }
+ },
+ "type": "object"
+ },
+ "title": {
+ "id": "/properties/details/properties/stages/items/properties/title",
+ "type": "string"
+ }
+ },
+ "type": "object"
+ },
+ "type": "array"
+ },
+ "status": {
+ "id": "/properties/details/properties/status",
+ "properties": {
+ "details_path": {
+ "id": "/properties/details/properties/status/properties/details_path",
+ "type": "string"
+ },
+ "favicon": {
+ "id": "/properties/details/properties/status/properties/favicon",
+ "type": "string"
+ },
+ "group": {
+ "id": "/properties/details/properties/status/properties/group",
+ "type": "string"
+ },
+ "has_details": {
+ "id": "/properties/details/properties/status/properties/has_details",
+ "type": "boolean"
+ },
+ "icon": {
+ "id": "/properties/details/properties/status/properties/icon",
+ "type": "string"
+ },
+ "label": {
+ "id": "/properties/details/properties/status/properties/label",
+ "type": "string"
+ },
+ "text": {
+ "id": "/properties/details/properties/status/properties/text",
+ "type": "string"
+ }
+ },
+ "type": "object"
+ }
+ },
+ "type": "object"
+ },
+ "flags": {
+ "id": "/properties/flags",
+ "properties": {
+ "cancelable": {
+ "id": "/properties/flags/properties/cancelable",
+ "type": "boolean"
+ },
+ "latest": {
+ "id": "/properties/flags/properties/latest",
+ "type": "boolean"
+ },
+ "retryable": {
+ "id": "/properties/flags/properties/retryable",
+ "type": "boolean"
+ },
+ "stuck": {
+ "id": "/properties/flags/properties/stuck",
+ "type": "boolean"
+ },
+ "triggered": {
+ "id": "/properties/flags/properties/triggered",
+ "type": "boolean"
+ },
+ "yaml_errors": {
+ "id": "/properties/flags/properties/yaml_errors",
+ "type": "boolean"
+ }
+ },
+ "type": "object"
+ },
+ "id": {
+ "id": "/properties/id",
+ "type": "integer"
+ },
+ "path": {
+ "id": "/properties/path",
+ "type": "string"
+ },
+ "ref": {
+ "id": "/properties/ref",
+ "properties": {
+ "branch": {
+ "id": "/properties/ref/properties/branch",
+ "type": "boolean"
+ },
+ "name": {
+ "id": "/properties/ref/properties/name",
+ "type": "string"
+ },
+ "path": {
+ "id": "/properties/ref/properties/path",
+ "type": "string"
+ },
+ "tag": {
+ "id": "/properties/ref/properties/tag",
+ "type": "boolean"
+ }
+ },
+ "type": "object"
+ },
+ "retry_path": {
+ "id": "/properties/retry_path",
+ "type": "string"
+ },
+ "updated_at": {
+ "id": "/properties/updated_at",
+ "type": "string"
+ },
+ "user": {
+ "id": "/properties/user",
+ "properties": {
+ "avatar_url": {
+ "id": "/properties/user/properties/avatar_url",
+ "type": "string"
+ },
+ "id": {
+ "id": "/properties/user/properties/id",
+ "type": "integer"
+ },
+ "name": {
+ "id": "/properties/user/properties/name",
+ "type": "string"
+ },
+ "state": {
+ "id": "/properties/user/properties/state",
+ "type": "string"
+ },
+ "username": {
+ "id": "/properties/user/properties/username",
+ "type": "string"
+ },
+ "web_url": {
+ "id": "/properties/user/properties/web_url",
+ "type": "string"
+ }
+ },
+ "type": "object"
+ }
+ },
+ "type": "object"
+}
diff --git a/spec/fixtures/api/schemas/public_api/v4/issues.json b/spec/fixtures/api/schemas/public_api/v4/issues.json
index 52199e75734..2d1c84ee93d 100644
--- a/spec/fixtures/api/schemas/public_api/v4/issues.json
+++ b/spec/fixtures/api/schemas/public_api/v4/issues.json
@@ -33,6 +33,21 @@
},
"additionalProperties": false
},
+ "assignees": {
+ "type": "array",
+ "items": {
+ "type": ["object", "null"],
+ "properties": {
+ "name": { "type": "string" },
+ "username": { "type": "string" },
+ "id": { "type": "integer" },
+ "state": { "type": "string" },
+ "avatar_url": { "type": "uri" },
+ "web_url": { "type": "uri" }
+ },
+ "additionalProperties": false
+ }
+ },
"assignee": {
"type": ["object", "null"],
"properties": {
@@ -67,7 +82,7 @@
"required": [
"id", "iid", "project_id", "title", "description",
"state", "created_at", "updated_at", "labels",
- "milestone", "assignee", "author", "user_notes_count",
+ "milestone", "assignees", "author", "user_notes_count",
"upvotes", "downvotes", "due_date", "confidential",
"web_url"
],
diff --git a/spec/helpers/issuables_helper_spec.rb b/spec/helpers/issuables_helper_spec.rb
index 93bb711f29a..c1ecb46aece 100644
--- a/spec/helpers/issuables_helper_spec.rb
+++ b/spec/helpers/issuables_helper_spec.rb
@@ -4,6 +4,23 @@ describe IssuablesHelper do
let(:label) { build_stubbed(:label) }
let(:label2) { build_stubbed(:label) }
+ describe '#users_dropdown_label' do
+ let(:user) { build_stubbed(:user) }
+ let(:user2) { build_stubbed(:user) }
+
+ it 'returns unassigned' do
+ expect(users_dropdown_label([])).to eq('Unassigned')
+ end
+
+ it 'returns selected user\'s name' do
+ expect(users_dropdown_label([user])).to eq(user.name)
+ end
+
+ it 'returns selected user\'s name and counter' do
+ expect(users_dropdown_label([user, user2])).to eq("#{user.name} + 1 more")
+ end
+ end
+
describe '#issuable_labels_tooltip' do
it 'returns label text' do
expect(issuable_labels_tooltip([label])).to eq(label.title)
diff --git a/spec/javascripts/autosave_spec.js b/spec/javascripts/autosave_spec.js
new file mode 100644
index 00000000000..9f9acc392c2
--- /dev/null
+++ b/spec/javascripts/autosave_spec.js
@@ -0,0 +1,134 @@
+import Autosave from '~/autosave';
+import AccessorUtilities from '~/lib/utils/accessor';
+
+describe('Autosave', () => {
+ let autosave;
+
+ describe('class constructor', () => {
+ const key = 'key';
+ const field = jasmine.createSpyObj('field', ['data', 'on']);
+
+ beforeEach(() => {
+ spyOn(AccessorUtilities, 'isLocalStorageAccessSafe').and.returnValue(true);
+ spyOn(Autosave.prototype, 'restore');
+
+ autosave = new Autosave(field, key);
+ });
+
+ it('should set .isLocalStorageAvailable', () => {
+ expect(AccessorUtilities.isLocalStorageAccessSafe).toHaveBeenCalled();
+ expect(autosave.isLocalStorageAvailable).toBe(true);
+ });
+ });
+
+ describe('restore', () => {
+ const key = 'key';
+ const field = jasmine.createSpyObj('field', ['trigger']);
+
+ beforeEach(() => {
+ autosave = {
+ field,
+ key,
+ };
+
+ spyOn(window.localStorage, 'getItem');
+ });
+
+ describe('if .isLocalStorageAvailable is `false`', () => {
+ beforeEach(() => {
+ autosave.isLocalStorageAvailable = false;
+
+ Autosave.prototype.restore.call(autosave);
+ });
+
+ it('should not call .getItem', () => {
+ expect(window.localStorage.getItem).not.toHaveBeenCalled();
+ });
+ });
+
+ describe('if .isLocalStorageAvailable is `true`', () => {
+ beforeEach(() => {
+ autosave.isLocalStorageAvailable = true;
+
+ Autosave.prototype.restore.call(autosave);
+ });
+
+ it('should call .getItem', () => {
+ expect(window.localStorage.getItem).toHaveBeenCalledWith(key);
+ });
+ });
+ });
+
+ describe('save', () => {
+ const field = jasmine.createSpyObj('field', ['val']);
+
+ beforeEach(() => {
+ autosave = jasmine.createSpyObj('autosave', ['reset']);
+ autosave.field = field;
+
+ field.val.and.returnValue('value');
+
+ spyOn(window.localStorage, 'setItem');
+ });
+
+ describe('if .isLocalStorageAvailable is `false`', () => {
+ beforeEach(() => {
+ autosave.isLocalStorageAvailable = false;
+
+ Autosave.prototype.save.call(autosave);
+ });
+
+ it('should not call .setItem', () => {
+ expect(window.localStorage.setItem).not.toHaveBeenCalled();
+ });
+ });
+
+ describe('if .isLocalStorageAvailable is `true`', () => {
+ beforeEach(() => {
+ autosave.isLocalStorageAvailable = true;
+
+ Autosave.prototype.save.call(autosave);
+ });
+
+ it('should call .setItem', () => {
+ expect(window.localStorage.setItem).toHaveBeenCalled();
+ });
+ });
+ });
+
+ describe('reset', () => {
+ const key = 'key';
+
+ beforeEach(() => {
+ autosave = {
+ key,
+ };
+
+ spyOn(window.localStorage, 'removeItem');
+ });
+
+ describe('if .isLocalStorageAvailable is `false`', () => {
+ beforeEach(() => {
+ autosave.isLocalStorageAvailable = false;
+
+ Autosave.prototype.reset.call(autosave);
+ });
+
+ it('should not call .removeItem', () => {
+ expect(window.localStorage.removeItem).not.toHaveBeenCalled();
+ });
+ });
+
+ describe('if .isLocalStorageAvailable is `true`', () => {
+ beforeEach(() => {
+ autosave.isLocalStorageAvailable = true;
+
+ Autosave.prototype.reset.call(autosave);
+ });
+
+ it('should call .removeItem', () => {
+ expect(window.localStorage.removeItem).toHaveBeenCalledWith(key);
+ });
+ });
+ });
+});
diff --git a/spec/javascripts/behaviors/gl_emoji/unicode_support_map_spec.js b/spec/javascripts/behaviors/gl_emoji/unicode_support_map_spec.js
new file mode 100644
index 00000000000..1ed96a67478
--- /dev/null
+++ b/spec/javascripts/behaviors/gl_emoji/unicode_support_map_spec.js
@@ -0,0 +1,47 @@
+import { getUnicodeSupportMap } from '~/behaviors/gl_emoji/unicode_support_map';
+import AccessorUtilities from '~/lib/utils/accessor';
+
+describe('Unicode Support Map', () => {
+ describe('getUnicodeSupportMap', () => {
+ const stringSupportMap = 'stringSupportMap';
+
+ beforeEach(() => {
+ spyOn(AccessorUtilities, 'isLocalStorageAccessSafe');
+ spyOn(window.localStorage, 'getItem');
+ spyOn(window.localStorage, 'setItem');
+ spyOn(JSON, 'parse');
+ spyOn(JSON, 'stringify').and.returnValue(stringSupportMap);
+ });
+
+ describe('if isLocalStorageAvailable is `true`', function () {
+ beforeEach(() => {
+ AccessorUtilities.isLocalStorageAccessSafe.and.returnValue(true);
+
+ getUnicodeSupportMap();
+ });
+
+ it('should call .getItem and .setItem', () => {
+ const allArgs = window.localStorage.setItem.calls.allArgs();
+
+ expect(window.localStorage.getItem).toHaveBeenCalledWith('gl-emoji-user-agent');
+ expect(allArgs[0][0]).toBe('gl-emoji-user-agent');
+ expect(allArgs[0][1]).toBe(navigator.userAgent);
+ expect(allArgs[1][0]).toBe('gl-emoji-unicode-support-map');
+ expect(allArgs[1][1]).toBe(stringSupportMap);
+ });
+ });
+
+ describe('if isLocalStorageAvailable is `false`', function () {
+ beforeEach(() => {
+ AccessorUtilities.isLocalStorageAccessSafe.and.returnValue(false);
+
+ getUnicodeSupportMap();
+ });
+
+ it('should not call .getItem or .setItem', () => {
+ expect(window.localStorage.getItem.calls.count()).toBe(1);
+ expect(window.localStorage.setItem).not.toHaveBeenCalled();
+ });
+ });
+ });
+});
diff --git a/spec/javascripts/blob/balsamiq/balsamiq_viewer_spec.js b/spec/javascripts/blob/balsamiq/balsamiq_viewer_spec.js
new file mode 100644
index 00000000000..85816ee1f11
--- /dev/null
+++ b/spec/javascripts/blob/balsamiq/balsamiq_viewer_spec.js
@@ -0,0 +1,342 @@
+import sqljs from 'sql.js';
+import BalsamiqViewer from '~/blob/balsamiq/balsamiq_viewer';
+import ClassSpecHelper from '../../helpers/class_spec_helper';
+
+describe('BalsamiqViewer', () => {
+ let balsamiqViewer;
+ let endpoint;
+ let viewer;
+
+ describe('class constructor', () => {
+ beforeEach(() => {
+ endpoint = 'endpoint';
+ viewer = {
+ dataset: {
+ endpoint,
+ },
+ };
+
+ balsamiqViewer = new BalsamiqViewer(viewer);
+ });
+
+ it('should set .viewer', () => {
+ expect(balsamiqViewer.viewer).toBe(viewer);
+ });
+
+ it('should set .endpoint', () => {
+ expect(balsamiqViewer.endpoint).toBe(endpoint);
+ });
+ });
+
+ describe('loadFile', () => {
+ let xhr;
+
+ beforeEach(() => {
+ endpoint = 'endpoint';
+ xhr = jasmine.createSpyObj('xhr', ['open', 'send']);
+
+ balsamiqViewer = jasmine.createSpyObj('balsamiqViewer', ['renderFile']);
+ balsamiqViewer.endpoint = endpoint;
+
+ spyOn(window, 'XMLHttpRequest').and.returnValue(xhr);
+
+ BalsamiqViewer.prototype.loadFile.call(balsamiqViewer);
+ });
+
+ it('should call .open', () => {
+ expect(xhr.open).toHaveBeenCalledWith('GET', endpoint, true);
+ });
+
+ it('should set .responseType', () => {
+ expect(xhr.responseType).toBe('arraybuffer');
+ });
+
+ it('should call .send', () => {
+ expect(xhr.send).toHaveBeenCalled();
+ });
+ });
+
+ describe('renderFile', () => {
+ let container;
+ let loadEvent;
+ let previews;
+
+ beforeEach(() => {
+ loadEvent = { target: { response: {} } };
+ viewer = jasmine.createSpyObj('viewer', ['appendChild']);
+ previews = [document.createElement('ul'), document.createElement('ul')];
+
+ balsamiqViewer = jasmine.createSpyObj('balsamiqViewer', ['initDatabase', 'getPreviews', 'renderPreview']);
+ balsamiqViewer.viewer = viewer;
+
+ balsamiqViewer.getPreviews.and.returnValue(previews);
+ balsamiqViewer.renderPreview.and.callFake(preview => preview);
+ viewer.appendChild.and.callFake((containerElement) => {
+ container = containerElement;
+ });
+
+ BalsamiqViewer.prototype.renderFile.call(balsamiqViewer, loadEvent);
+ });
+
+ it('should call .initDatabase', () => {
+ expect(balsamiqViewer.initDatabase).toHaveBeenCalledWith(loadEvent.target.response);
+ });
+
+ it('should call .getPreviews', () => {
+ expect(balsamiqViewer.getPreviews).toHaveBeenCalled();
+ });
+
+ it('should call .renderPreview for each preview', () => {
+ const allArgs = balsamiqViewer.renderPreview.calls.allArgs();
+
+ expect(allArgs.length).toBe(2);
+
+ previews.forEach((preview, i) => {
+ expect(allArgs[i][0]).toBe(preview);
+ });
+ });
+
+ it('should set the container HTML', () => {
+ expect(container.innerHTML).toBe('<ul></ul><ul></ul>');
+ });
+
+ it('should add inline preview classes', () => {
+ expect(container.classList[0]).toBe('list-inline');
+ expect(container.classList[1]).toBe('previews');
+ });
+
+ it('should call viewer.appendChild', () => {
+ expect(viewer.appendChild).toHaveBeenCalledWith(container);
+ });
+ });
+
+ describe('initDatabase', () => {
+ let database;
+ let uint8Array;
+ let data;
+
+ beforeEach(() => {
+ uint8Array = {};
+ database = {};
+ data = 'data';
+
+ balsamiqViewer = {};
+
+ spyOn(window, 'Uint8Array').and.returnValue(uint8Array);
+ spyOn(sqljs, 'Database').and.returnValue(database);
+
+ BalsamiqViewer.prototype.initDatabase.call(balsamiqViewer, data);
+ });
+
+ it('should instantiate Uint8Array', () => {
+ expect(window.Uint8Array).toHaveBeenCalledWith(data);
+ });
+
+ it('should call sqljs.Database', () => {
+ expect(sqljs.Database).toHaveBeenCalledWith(uint8Array);
+ });
+
+ it('should set .database', () => {
+ expect(balsamiqViewer.database).toBe(database);
+ });
+ });
+
+ describe('getPreviews', () => {
+ let database;
+ let thumbnails;
+ let getPreviews;
+
+ beforeEach(() => {
+ database = jasmine.createSpyObj('database', ['exec']);
+ thumbnails = [{ values: [0, 1, 2] }];
+
+ balsamiqViewer = {
+ database,
+ };
+
+ spyOn(BalsamiqViewer, 'parsePreview').and.callFake(preview => preview.toString());
+ database.exec.and.returnValue(thumbnails);
+
+ getPreviews = BalsamiqViewer.prototype.getPreviews.call(balsamiqViewer);
+ });
+
+ it('should call database.exec', () => {
+ expect(database.exec).toHaveBeenCalledWith('SELECT * FROM thumbnails');
+ });
+
+ it('should call .parsePreview for each value', () => {
+ const allArgs = BalsamiqViewer.parsePreview.calls.allArgs();
+
+ expect(allArgs.length).toBe(3);
+
+ thumbnails[0].values.forEach((value, i) => {
+ expect(allArgs[i][0]).toBe(value);
+ });
+ });
+
+ it('should return an array of parsed values', () => {
+ expect(getPreviews).toEqual(['0', '1', '2']);
+ });
+ });
+
+ describe('getResource', () => {
+ let database;
+ let resourceID;
+ let resource;
+ let getResource;
+
+ beforeEach(() => {
+ database = jasmine.createSpyObj('database', ['exec']);
+ resourceID = 4;
+ resource = ['resource'];
+
+ balsamiqViewer = {
+ database,
+ };
+
+ database.exec.and.returnValue(resource);
+
+ getResource = BalsamiqViewer.prototype.getResource.call(balsamiqViewer, resourceID);
+ });
+
+ it('should call database.exec', () => {
+ expect(database.exec).toHaveBeenCalledWith(`SELECT * FROM resources WHERE id = '${resourceID}'`);
+ });
+
+ it('should return the selected resource', () => {
+ expect(getResource).toBe(resource[0]);
+ });
+ });
+
+ describe('renderPreview', () => {
+ let previewElement;
+ let innerHTML;
+ let preview;
+ let renderPreview;
+
+ beforeEach(() => {
+ innerHTML = '<a>innerHTML</a>';
+ previewElement = {
+ outerHTML: '<p>outerHTML</p>',
+ classList: jasmine.createSpyObj('classList', ['add']),
+ };
+ preview = {};
+
+ balsamiqViewer = jasmine.createSpyObj('balsamiqViewer', ['renderTemplate']);
+
+ spyOn(document, 'createElement').and.returnValue(previewElement);
+ balsamiqViewer.renderTemplate.and.returnValue(innerHTML);
+
+ renderPreview = BalsamiqViewer.prototype.renderPreview.call(balsamiqViewer, preview);
+ });
+
+ it('should call classList.add', () => {
+ expect(previewElement.classList.add).toHaveBeenCalledWith('preview');
+ });
+
+ it('should call .renderTemplate', () => {
+ expect(balsamiqViewer.renderTemplate).toHaveBeenCalledWith(preview);
+ });
+
+ it('should set .innerHTML', () => {
+ expect(previewElement.innerHTML).toBe(innerHTML);
+ });
+
+ it('should return element', () => {
+ expect(renderPreview).toBe(previewElement);
+ });
+ });
+
+ describe('renderTemplate', () => {
+ let preview;
+ let name;
+ let resource;
+ let template;
+ let renderTemplate;
+
+ beforeEach(() => {
+ preview = { resourceID: 1, image: 'image' };
+ name = 'name';
+ resource = 'resource';
+ template = `
+ <div class="panel panel-default">
+ <div class="panel-heading">name</div>
+ <div class="panel-body">
+ <img class="img-thumbnail" src="data:image/png;base64,image"/>
+ </div>
+ </div>
+ `;
+
+ balsamiqViewer = jasmine.createSpyObj('balsamiqViewer', ['getResource']);
+
+ spyOn(BalsamiqViewer, 'parseTitle').and.returnValue(name);
+ balsamiqViewer.getResource.and.returnValue(resource);
+
+ renderTemplate = BalsamiqViewer.prototype.renderTemplate.call(balsamiqViewer, preview);
+ });
+
+ it('should call .getResource', () => {
+ expect(balsamiqViewer.getResource).toHaveBeenCalledWith(preview.resourceID);
+ });
+
+ it('should call .parseTitle', () => {
+ expect(BalsamiqViewer.parseTitle).toHaveBeenCalledWith(resource);
+ });
+
+ it('should return the template string', function () {
+ expect(renderTemplate.replace(/\s/g, '')).toEqual(template.replace(/\s/g, ''));
+ });
+ });
+
+ describe('parsePreview', () => {
+ let preview;
+ let parsePreview;
+
+ beforeEach(() => {
+ preview = ['{}', '{ "id": 1 }'];
+
+ spyOn(JSON, 'parse').and.callThrough();
+
+ parsePreview = BalsamiqViewer.parsePreview(preview);
+ });
+
+ ClassSpecHelper.itShouldBeAStaticMethod(BalsamiqViewer, 'parsePreview');
+
+ it('should return the parsed JSON', () => {
+ expect(parsePreview).toEqual(JSON.parse('{ "id": 1 }'));
+ });
+ });
+
+ describe('parseTitle', () => {
+ let title;
+ let parseTitle;
+
+ beforeEach(() => {
+ title = { values: [['{}', '{}', '{"name":"name"}']] };
+
+ spyOn(JSON, 'parse').and.callThrough();
+
+ parseTitle = BalsamiqViewer.parseTitle(title);
+ });
+
+ ClassSpecHelper.itShouldBeAStaticMethod(BalsamiqViewer, 'parsePreview');
+
+ it('should return the name value', () => {
+ expect(parseTitle).toBe('name');
+ });
+ });
+
+ describe('onError', () => {
+ beforeEach(() => {
+ spyOn(window, 'Flash');
+
+ BalsamiqViewer.onError();
+ });
+
+ ClassSpecHelper.itShouldBeAStaticMethod(BalsamiqViewer, 'onError');
+
+ it('should instantiate Flash', () => {
+ expect(window.Flash).toHaveBeenCalledWith('Balsamiq file could not be loaded.');
+ });
+ });
+});
diff --git a/spec/javascripts/boards/board_card_spec.js b/spec/javascripts/boards/board_card_spec.js
index de072e7e470..376e706d1db 100644
--- a/spec/javascripts/boards/board_card_spec.js
+++ b/spec/javascripts/boards/board_card_spec.js
@@ -1,12 +1,12 @@
/* global List */
-/* global ListUser */
+/* global ListAssignee */
/* global ListLabel */
/* global listObj */
/* global boardsMockInterceptor */
/* global BoardService */
import Vue from 'vue';
-import '~/boards/models/user';
+import '~/boards/models/assignee';
require('~/boards/models/list');
require('~/boards/models/label');
@@ -133,12 +133,12 @@ describe('Issue card', () => {
});
it('does not set detail issue if img is clicked', (done) => {
- vm.issue.assignee = new ListUser({
+ vm.issue.assignees = [new ListAssignee({
id: 1,
name: 'testing 123',
username: 'test',
avatar: 'test_image',
- });
+ })];
Vue.nextTick(() => {
triggerEvent('mouseup', vm.$el.querySelector('img'));
diff --git a/spec/javascripts/boards/board_list_spec.js b/spec/javascripts/boards/board_list_spec.js
index 3f598887603..a89be911667 100644
--- a/spec/javascripts/boards/board_list_spec.js
+++ b/spec/javascripts/boards/board_list_spec.js
@@ -35,6 +35,7 @@ describe('Board list component', () => {
iid: 1,
confidential: false,
labels: [],
+ assignees: [],
});
list.issuesSize = 1;
list.issues.push(issue);
diff --git a/spec/javascripts/boards/boards_store_spec.js b/spec/javascripts/boards/boards_store_spec.js
index b55ff2f473a..5ea160b7790 100644
--- a/spec/javascripts/boards/boards_store_spec.js
+++ b/spec/javascripts/boards/boards_store_spec.js
@@ -8,14 +8,14 @@
import Vue from 'vue';
import Cookies from 'js-cookie';
-require('~/lib/utils/url_utility');
-require('~/boards/models/issue');
-require('~/boards/models/label');
-require('~/boards/models/list');
-require('~/boards/models/user');
-require('~/boards/services/board_service');
-require('~/boards/stores/boards_store');
-require('./mock_data');
+import '~/lib/utils/url_utility';
+import '~/boards/models/issue';
+import '~/boards/models/label';
+import '~/boards/models/list';
+import '~/boards/models/assignee';
+import '~/boards/services/board_service';
+import '~/boards/stores/boards_store';
+import './mock_data';
describe('Store', () => {
beforeEach(() => {
@@ -212,7 +212,8 @@ describe('Store', () => {
title: 'Testing',
iid: 2,
confidential: false,
- labels: []
+ labels: [],
+ assignees: [],
});
const list = gl.issueBoards.BoardsStore.addList(listObj);
diff --git a/spec/javascripts/boards/issue_card_spec.js b/spec/javascripts/boards/issue_card_spec.js
index ef567635d48..fddde799d01 100644
--- a/spec/javascripts/boards/issue_card_spec.js
+++ b/spec/javascripts/boards/issue_card_spec.js
@@ -1,20 +1,20 @@
-/* global ListUser */
+/* global ListAssignee */
/* global ListLabel */
/* global listObj */
/* global ListIssue */
import Vue from 'vue';
-require('~/boards/models/issue');
-require('~/boards/models/label');
-require('~/boards/models/list');
-require('~/boards/models/user');
-require('~/boards/stores/boards_store');
-require('~/boards/components/issue_card_inner');
-require('./mock_data');
+import '~/boards/models/issue';
+import '~/boards/models/label';
+import '~/boards/models/list';
+import '~/boards/models/assignee';
+import '~/boards/stores/boards_store';
+import '~/boards/components/issue_card_inner';
+import './mock_data';
describe('Issue card component', () => {
- const user = new ListUser({
+ const user = new ListAssignee({
id: 1,
name: 'testing 123',
username: 'test',
@@ -40,6 +40,7 @@ describe('Issue card component', () => {
iid: 1,
confidential: false,
labels: [list.label],
+ assignees: [],
});
component = new Vue({
@@ -92,12 +93,12 @@ describe('Issue card component', () => {
it('renders confidential icon', (done) => {
component.issue.confidential = true;
- setTimeout(() => {
+ Vue.nextTick(() => {
expect(
component.$el.querySelector('.confidential-icon'),
).not.toBeNull();
done();
- }, 0);
+ });
});
it('renders issue ID with #', () => {
@@ -109,34 +110,32 @@ describe('Issue card component', () => {
describe('assignee', () => {
it('does not render assignee', () => {
expect(
- component.$el.querySelector('.card-assignee'),
+ component.$el.querySelector('.card-assignee .avatar'),
).toBeNull();
});
describe('exists', () => {
beforeEach((done) => {
- component.issue.assignee = user;
+ component.issue.assignees = [user];
- setTimeout(() => {
- done();
- }, 0);
+ Vue.nextTick(() => done());
});
it('renders assignee', () => {
expect(
- component.$el.querySelector('.card-assignee'),
+ component.$el.querySelector('.card-assignee .avatar'),
).not.toBeNull();
});
it('sets title', () => {
expect(
- component.$el.querySelector('.card-assignee').getAttribute('title'),
+ component.$el.querySelector('.card-assignee a').getAttribute('title'),
).toContain(`Assigned to ${user.name}`);
});
it('sets users path', () => {
expect(
- component.$el.querySelector('.card-assignee').getAttribute('href'),
+ component.$el.querySelector('.card-assignee a').getAttribute('href'),
).toBe('/test');
});
@@ -149,11 +148,11 @@ describe('Issue card component', () => {
describe('assignee default avatar', () => {
beforeEach((done) => {
- component.issue.assignee = new ListUser({
+ component.issue.assignees = [new ListAssignee({
id: 1,
name: 'testing 123',
username: 'test',
- }, 'default_avatar');
+ }, 'default_avatar')];
Vue.nextTick(done);
});
@@ -169,6 +168,75 @@ describe('Issue card component', () => {
});
});
+ describe('multiple assignees', () => {
+ beforeEach((done) => {
+ component.issue.assignees = [
+ user,
+ new ListAssignee({
+ id: 2,
+ name: 'user2',
+ username: 'user2',
+ avatar: 'test_image',
+ }),
+ new ListAssignee({
+ id: 3,
+ name: 'user3',
+ username: 'user3',
+ avatar: 'test_image',
+ }),
+ new ListAssignee({
+ id: 4,
+ name: 'user4',
+ username: 'user4',
+ avatar: 'test_image',
+ })];
+
+ Vue.nextTick(() => done());
+ });
+
+ it('renders all four assignees', () => {
+ expect(component.$el.querySelectorAll('.card-assignee .avatar').length).toEqual(4);
+ });
+
+ describe('more than four assignees', () => {
+ beforeEach((done) => {
+ component.issue.assignees.push(new ListAssignee({
+ id: 5,
+ name: 'user5',
+ username: 'user5',
+ avatar: 'test_image',
+ }));
+
+ Vue.nextTick(() => done());
+ });
+
+ it('renders more avatar counter', () => {
+ expect(component.$el.querySelector('.card-assignee .avatar-counter').innerText).toEqual('+2');
+ });
+
+ it('renders three assignees', () => {
+ expect(component.$el.querySelectorAll('.card-assignee .avatar').length).toEqual(3);
+ });
+
+ it('renders 99+ avatar counter', (done) => {
+ for (let i = 5; i < 104; i += 1) {
+ const u = new ListAssignee({
+ id: i,
+ name: 'name',
+ username: 'username',
+ avatar: 'test_image',
+ });
+ component.issue.assignees.push(u);
+ }
+
+ Vue.nextTick(() => {
+ expect(component.$el.querySelector('.card-assignee .avatar-counter').innerText).toEqual('99+');
+ done();
+ });
+ });
+ });
+ });
+
describe('labels', () => {
it('does not render any', () => {
expect(
@@ -180,9 +248,7 @@ describe('Issue card component', () => {
beforeEach((done) => {
component.issue.addLabel(label1);
- setTimeout(() => {
- done();
- }, 0);
+ Vue.nextTick(() => done());
});
it('does not render list label', () => {
diff --git a/spec/javascripts/boards/issue_spec.js b/spec/javascripts/boards/issue_spec.js
index c96dfe94a4a..cd1497bc5e6 100644
--- a/spec/javascripts/boards/issue_spec.js
+++ b/spec/javascripts/boards/issue_spec.js
@@ -2,14 +2,15 @@
/* global BoardService */
/* global ListIssue */
-require('~/lib/utils/url_utility');
-require('~/boards/models/issue');
-require('~/boards/models/label');
-require('~/boards/models/list');
-require('~/boards/models/user');
-require('~/boards/services/board_service');
-require('~/boards/stores/boards_store');
-require('./mock_data');
+import Vue from 'vue';
+import '~/lib/utils/url_utility';
+import '~/boards/models/issue';
+import '~/boards/models/label';
+import '~/boards/models/list';
+import '~/boards/models/assignee';
+import '~/boards/services/board_service';
+import '~/boards/stores/boards_store';
+import './mock_data';
describe('Issue model', () => {
let issue;
@@ -27,7 +28,13 @@ describe('Issue model', () => {
title: 'test',
color: 'red',
description: 'testing'
- }]
+ }],
+ assignees: [{
+ id: 1,
+ name: 'name',
+ username: 'username',
+ avatar_url: 'http://avatar_url',
+ }],
});
});
@@ -80,6 +87,33 @@ describe('Issue model', () => {
expect(issue.labels.length).toBe(0);
});
+ it('adds assignee', () => {
+ issue.addAssignee({
+ id: 2,
+ name: 'Bruce Wayne',
+ username: 'batman',
+ avatar_url: 'http://batman',
+ });
+
+ expect(issue.assignees.length).toBe(2);
+ });
+
+ it('finds assignee', () => {
+ const assignee = issue.findAssignee(issue.assignees[0]);
+ expect(assignee).toBeDefined();
+ });
+
+ it('removes assignee', () => {
+ const assignee = issue.findAssignee(issue.assignees[0]);
+ issue.removeAssignee(assignee);
+ expect(issue.assignees.length).toBe(0);
+ });
+
+ it('removes all assignees', () => {
+ issue.removeAllAssignees();
+ expect(issue.assignees.length).toBe(0);
+ });
+
it('sets position to infinity if no position is stored', () => {
expect(issue.position).toBe(Infinity);
});
@@ -90,9 +124,31 @@ describe('Issue model', () => {
iid: 1,
confidential: false,
relative_position: 1,
- labels: []
+ labels: [],
+ assignees: [],
});
expect(relativePositionIssue.position).toBe(1);
});
+
+ describe('update', () => {
+ it('passes assignee ids when there are assignees', (done) => {
+ spyOn(Vue.http, 'patch').and.callFake((url, data) => {
+ expect(data.issue.assignee_ids).toEqual([1]);
+ done();
+ });
+
+ issue.update('url');
+ });
+
+ it('passes assignee ids of [0] when there are no assignees', (done) => {
+ spyOn(Vue.http, 'patch').and.callFake((url, data) => {
+ expect(data.issue.assignee_ids).toEqual([0]);
+ done();
+ });
+
+ issue.removeAllAssignees();
+ issue.update('url');
+ });
+ });
});
diff --git a/spec/javascripts/boards/list_spec.js b/spec/javascripts/boards/list_spec.js
index 24a2da9f6b6..8e3d9fd77a0 100644
--- a/spec/javascripts/boards/list_spec.js
+++ b/spec/javascripts/boards/list_spec.js
@@ -8,14 +8,14 @@
import Vue from 'vue';
-require('~/lib/utils/url_utility');
-require('~/boards/models/issue');
-require('~/boards/models/label');
-require('~/boards/models/list');
-require('~/boards/models/user');
-require('~/boards/services/board_service');
-require('~/boards/stores/boards_store');
-require('./mock_data');
+import '~/lib/utils/url_utility';
+import '~/boards/models/issue';
+import '~/boards/models/label';
+import '~/boards/models/list';
+import '~/boards/models/assignee';
+import '~/boards/services/board_service';
+import '~/boards/stores/boards_store';
+import './mock_data';
describe('List model', () => {
let list;
@@ -94,7 +94,8 @@ describe('List model', () => {
title: 'Testing',
iid: _.random(10000),
confidential: false,
- labels: [list.label, listDup.label]
+ labels: [list.label, listDup.label],
+ assignees: [],
});
list.issues.push(issue);
@@ -119,7 +120,8 @@ describe('List model', () => {
title: 'Testing',
iid: _.random(10000) + i,
confidential: false,
- labels: [list.label]
+ labels: [list.label],
+ assignees: [],
}));
}
list.issuesSize = 50;
@@ -137,7 +139,8 @@ describe('List model', () => {
title: 'Testing',
iid: _.random(10000),
confidential: false,
- labels: [list.label]
+ labels: [list.label],
+ assignees: [],
}));
list.issuesSize = 2;
diff --git a/spec/javascripts/boards/mock_data.js b/spec/javascripts/boards/mock_data.js
index a4fa694eebe..a64c3964ee3 100644
--- a/spec/javascripts/boards/mock_data.js
+++ b/spec/javascripts/boards/mock_data.js
@@ -33,7 +33,8 @@ const BoardsMockData = {
title: 'Testing',
iid: 1,
confidential: false,
- labels: []
+ labels: [],
+ assignees: [],
}],
size: 1
}
diff --git a/spec/javascripts/boards/modal_store_spec.js b/spec/javascripts/boards/modal_store_spec.js
index 80db816aff8..32e6d04df9f 100644
--- a/spec/javascripts/boards/modal_store_spec.js
+++ b/spec/javascripts/boards/modal_store_spec.js
@@ -1,10 +1,10 @@
/* global ListIssue */
-require('~/boards/models/issue');
-require('~/boards/models/label');
-require('~/boards/models/list');
-require('~/boards/models/user');
-require('~/boards/stores/modal_store');
+import '~/boards/models/issue';
+import '~/boards/models/label';
+import '~/boards/models/list';
+import '~/boards/models/assignee';
+import '~/boards/stores/modal_store';
describe('Modal store', () => {
let issue;
@@ -21,12 +21,14 @@ describe('Modal store', () => {
iid: 1,
confidential: false,
labels: [],
+ assignees: [],
});
issue2 = new ListIssue({
title: 'Testing',
iid: 2,
confidential: false,
labels: [],
+ assignees: [],
});
Store.store.issues.push(issue);
Store.store.issues.push(issue2);
diff --git a/spec/javascripts/filtered_search/components/recent_searches_dropdown_content_spec.js b/spec/javascripts/filtered_search/components/recent_searches_dropdown_content_spec.js
index 2722882375f..d0f09a561d5 100644
--- a/spec/javascripts/filtered_search/components/recent_searches_dropdown_content_spec.js
+++ b/spec/javascripts/filtered_search/components/recent_searches_dropdown_content_spec.js
@@ -76,6 +76,26 @@ describe('RecentSearchesDropdownContent', () => {
});
});
+ describe('if isLocalStorageAvailable is `false`', () => {
+ let el;
+
+ beforeEach(() => {
+ const props = Object.assign({ isLocalStorageAvailable: false }, propsDataWithItems);
+
+ vm = createComponent(props);
+ el = vm.$el;
+ });
+
+ it('should render an info note', () => {
+ const note = el.querySelector('.dropdown-info-note');
+ const items = el.querySelectorAll('.filtered-search-history-dropdown-item');
+
+ expect(note).toBeDefined();
+ expect(note.innerText.trim()).toBe('This feature requires local storage to be enabled');
+ expect(items.length).toEqual(propsDataWithoutItems.items.length);
+ });
+ });
+
describe('computed', () => {
describe('processedItems', () => {
it('with items', () => {
diff --git a/spec/javascripts/filtered_search/filtered_search_manager_spec.js b/spec/javascripts/filtered_search/filtered_search_manager_spec.js
index e747aa497c2..063d547d00c 100644
--- a/spec/javascripts/filtered_search/filtered_search_manager_spec.js
+++ b/spec/javascripts/filtered_search/filtered_search_manager_spec.js
@@ -1,3 +1,7 @@
+import * as recentSearchesStoreSrc from '~/filtered_search/stores/recent_searches_store';
+import RecentSearchesService from '~/filtered_search/services/recent_searches_service';
+import RecentSearchesServiceError from '~/filtered_search/services/recent_searches_service_error';
+
require('~/lib/utils/url_utility');
require('~/lib/utils/common_utils');
require('~/filtered_search/filtered_search_token_keys');
@@ -60,6 +64,36 @@ describe('Filtered Search Manager', () => {
manager.cleanup();
});
+ describe('class constructor', () => {
+ const isLocalStorageAvailable = 'isLocalStorageAvailable';
+ let filteredSearchManager;
+
+ beforeEach(() => {
+ spyOn(RecentSearchesService, 'isAvailable').and.returnValue(isLocalStorageAvailable);
+ spyOn(recentSearchesStoreSrc, 'default');
+
+ filteredSearchManager = new gl.FilteredSearchManager();
+
+ return filteredSearchManager;
+ });
+
+ it('should instantiate RecentSearchesStore with isLocalStorageAvailable', () => {
+ expect(RecentSearchesService.isAvailable).toHaveBeenCalled();
+ expect(recentSearchesStoreSrc.default).toHaveBeenCalledWith({
+ isLocalStorageAvailable,
+ });
+ });
+
+ it('should not instantiate Flash if an RecentSearchesServiceError is caught', () => {
+ spyOn(RecentSearchesService.prototype, 'fetch').and.callFake(() => Promise.reject(new RecentSearchesServiceError()));
+ spyOn(window, 'Flash');
+
+ filteredSearchManager = new gl.FilteredSearchManager();
+
+ expect(window.Flash).not.toHaveBeenCalled();
+ });
+ });
+
describe('search', () => {
const defaultParams = '?scope=all&utf8=%E2%9C%93&state=opened';
diff --git a/spec/javascripts/filtered_search/filtered_search_visual_tokens_spec.js b/spec/javascripts/filtered_search/filtered_search_visual_tokens_spec.js
index d75b9061281..8b750561eb7 100644
--- a/spec/javascripts/filtered_search/filtered_search_visual_tokens_spec.js
+++ b/spec/javascripts/filtered_search/filtered_search_visual_tokens_spec.js
@@ -1,3 +1,5 @@
+import AjaxCache from '~/lib/utils/ajax_cache';
+
require('~/filtered_search/filtered_search_visual_tokens');
const FilteredSearchSpecHelper = require('../helpers/filtered_search_spec_helper');
@@ -611,4 +613,103 @@ describe('Filtered Search Visual Tokens', () => {
expect(token.querySelector('.value').innerText).toEqual('~bug');
});
});
+
+ describe('renderVisualTokenValue', () => {
+ let searchTokens;
+
+ beforeEach(() => {
+ tokensContainer.innerHTML = FilteredSearchSpecHelper.createTokensContainerHTML(`
+ ${FilteredSearchSpecHelper.createFilterVisualTokenHTML('label', 'none')}
+ ${FilteredSearchSpecHelper.createSearchVisualTokenHTML('search')}
+ ${FilteredSearchSpecHelper.createFilterVisualTokenHTML('milestone', 'upcoming')}
+ `);
+
+ searchTokens = document.querySelectorAll('.filtered-search-token');
+ });
+
+ it('renders a token value element', () => {
+ spyOn(gl.FilteredSearchVisualTokens, 'updateLabelTokenColor');
+ const updateLabelTokenColorSpy = gl.FilteredSearchVisualTokens.updateLabelTokenColor;
+
+ expect(searchTokens.length).toBe(2);
+ Array.prototype.forEach.call(searchTokens, (token) => {
+ updateLabelTokenColorSpy.calls.reset();
+
+ const tokenName = token.querySelector('.name').innerText;
+ const tokenValue = 'new value';
+ gl.FilteredSearchVisualTokens.renderVisualTokenValue(token, tokenName, tokenValue);
+
+ const tokenValueElement = token.querySelector('.value');
+ expect(tokenValueElement.innerText).toBe(tokenValue);
+
+ if (tokenName.toLowerCase() === 'label') {
+ const tokenValueContainer = token.querySelector('.value-container');
+ expect(updateLabelTokenColorSpy.calls.count()).toBe(1);
+ const expectedArgs = [tokenValueContainer, tokenValue];
+ expect(updateLabelTokenColorSpy.calls.argsFor(0)).toEqual(expectedArgs);
+ } else {
+ expect(updateLabelTokenColorSpy.calls.count()).toBe(0);
+ }
+ });
+ });
+ });
+
+ describe('updateLabelTokenColor', () => {
+ const jsonFixtureName = 'labels/project_labels.json';
+ const dummyEndpoint = '/dummy/endpoint';
+
+ preloadFixtures(jsonFixtureName);
+ const labelData = getJSONFixture(jsonFixtureName);
+ const findLabel = tokenValue => labelData.find(
+ label => tokenValue === `~${gl.DropdownUtils.getEscapedText(label.title)}`,
+ );
+
+ const bugLabelToken = FilteredSearchSpecHelper.createFilterVisualToken('label', '~bug');
+ const missingLabelToken = FilteredSearchSpecHelper.createFilterVisualToken('label', '~doesnotexist');
+ const spaceLabelToken = FilteredSearchSpecHelper.createFilterVisualToken('label', '~"some space"');
+
+ const parseColor = (color) => {
+ const dummyElement = document.createElement('div');
+ dummyElement.style.color = color;
+ return dummyElement.style.color;
+ };
+
+ beforeEach(() => {
+ tokensContainer.innerHTML = FilteredSearchSpecHelper.createTokensContainerHTML(`
+ ${bugLabelToken.outerHTML}
+ ${missingLabelToken.outerHTML}
+ ${spaceLabelToken.outerHTML}
+ `);
+
+ const filteredSearchInput = document.querySelector('.filtered-search');
+ filteredSearchInput.dataset.baseEndpoint = dummyEndpoint;
+
+ AjaxCache.internalStorage = { };
+ AjaxCache.internalStorage[`${dummyEndpoint}/labels.json`] = labelData;
+ });
+
+ const testCase = (token, done) => {
+ const tokenValueContainer = token.querySelector('.value-container');
+ const tokenValue = token.querySelector('.value').innerText;
+ const label = findLabel(tokenValue);
+
+ gl.FilteredSearchVisualTokens.updateLabelTokenColor(tokenValueContainer, tokenValue)
+ .then(() => {
+ if (label) {
+ expect(tokenValueContainer.getAttribute('style')).not.toBe(null);
+ expect(tokenValueContainer.style.backgroundColor).toBe(parseColor(label.color));
+ expect(tokenValueContainer.style.color).toBe(parseColor(label.text_color));
+ } else {
+ expect(token).toBe(missingLabelToken);
+ expect(tokenValueContainer.getAttribute('style')).toBe(null);
+ }
+ })
+ .then(done)
+ .catch(fail);
+ };
+
+ it('updates the color of a label token', done => testCase(bugLabelToken, done));
+ it('updates the color of a label token with spaces', done => testCase(spaceLabelToken, done));
+ it('does not change color of a missing label', done => testCase(missingLabelToken, done));
+ });
});
diff --git a/spec/javascripts/filtered_search/recent_searches_root_spec.js b/spec/javascripts/filtered_search/recent_searches_root_spec.js
new file mode 100644
index 00000000000..d8ba6de5f45
--- /dev/null
+++ b/spec/javascripts/filtered_search/recent_searches_root_spec.js
@@ -0,0 +1,31 @@
+import RecentSearchesRoot from '~/filtered_search/recent_searches_root';
+import * as vueSrc from 'vue';
+
+describe('RecentSearchesRoot', () => {
+ describe('render', () => {
+ let recentSearchesRoot;
+ let data;
+ let template;
+
+ beforeEach(() => {
+ recentSearchesRoot = {
+ store: {
+ state: 'state',
+ },
+ };
+
+ spyOn(vueSrc, 'default').and.callFake((options) => {
+ data = options.data;
+ template = options.template;
+ });
+
+ RecentSearchesRoot.prototype.render.call(recentSearchesRoot);
+ });
+
+ it('should instantiate Vue', () => {
+ expect(vueSrc.default).toHaveBeenCalled();
+ expect(data()).toBe(recentSearchesRoot.store.state);
+ expect(template).toContain(':is-local-storage-available="isLocalStorageAvailable"');
+ });
+ });
+});
diff --git a/spec/javascripts/filtered_search/services/recent_searches_service_error_spec.js b/spec/javascripts/filtered_search/services/recent_searches_service_error_spec.js
new file mode 100644
index 00000000000..ea7c146fa4f
--- /dev/null
+++ b/spec/javascripts/filtered_search/services/recent_searches_service_error_spec.js
@@ -0,0 +1,18 @@
+import RecentSearchesServiceError from '~/filtered_search/services/recent_searches_service_error';
+
+describe('RecentSearchesServiceError', () => {
+ let recentSearchesServiceError;
+
+ beforeEach(() => {
+ recentSearchesServiceError = new RecentSearchesServiceError();
+ });
+
+ it('instantiates an instance of RecentSearchesServiceError and not an Error', () => {
+ expect(recentSearchesServiceError).toEqual(jasmine.any(RecentSearchesServiceError));
+ expect(recentSearchesServiceError.name).toBe('RecentSearchesServiceError');
+ });
+
+ it('should set a default message', () => {
+ expect(recentSearchesServiceError.message).toBe('Recent Searches Service is unavailable');
+ });
+});
diff --git a/spec/javascripts/filtered_search/services/recent_searches_service_spec.js b/spec/javascripts/filtered_search/services/recent_searches_service_spec.js
index c255bf7c939..31fa478804a 100644
--- a/spec/javascripts/filtered_search/services/recent_searches_service_spec.js
+++ b/spec/javascripts/filtered_search/services/recent_searches_service_spec.js
@@ -1,6 +1,7 @@
/* eslint-disable promise/catch-or-return */
import RecentSearchesService from '~/filtered_search/services/recent_searches_service';
+import AccessorUtilities from '~/lib/utils/accessor';
describe('RecentSearchesService', () => {
let service;
@@ -11,6 +12,10 @@ describe('RecentSearchesService', () => {
});
describe('fetch', () => {
+ beforeEach(() => {
+ spyOn(RecentSearchesService, 'isAvailable').and.returnValue(true);
+ });
+
it('should default to empty array', (done) => {
const fetchItemsPromise = service.fetch();
@@ -29,11 +34,21 @@ describe('RecentSearchesService', () => {
const fetchItemsPromise = service.fetch();
fetchItemsPromise
- .catch(() => {
+ .catch((error) => {
+ expect(error).toEqual(jasmine.any(SyntaxError));
done();
});
});
+ it('should reject when service is unavailable', (done) => {
+ RecentSearchesService.isAvailable.and.returnValue(false);
+
+ service.fetch().catch((error) => {
+ expect(error).toEqual(jasmine.any(Error));
+ done();
+ });
+ });
+
it('should return items from localStorage', (done) => {
window.localStorage.setItem(service.localStorageKey, '["foo", "bar"]');
const fetchItemsPromise = service.fetch();
@@ -44,15 +59,89 @@ describe('RecentSearchesService', () => {
done();
});
});
+
+ describe('if .isAvailable returns `false`', () => {
+ beforeEach(() => {
+ RecentSearchesService.isAvailable.and.returnValue(false);
+
+ spyOn(window.localStorage, 'getItem');
+
+ RecentSearchesService.prototype.fetch();
+ });
+
+ it('should not call .getItem', () => {
+ expect(window.localStorage.getItem).not.toHaveBeenCalled();
+ });
+ });
});
describe('setRecentSearches', () => {
+ beforeEach(() => {
+ spyOn(RecentSearchesService, 'isAvailable').and.returnValue(true);
+ });
+
it('should save things in localStorage', () => {
const items = ['foo', 'bar'];
service.save(items);
- const newLocalStorageValue =
- window.localStorage.getItem(service.localStorageKey);
+ const newLocalStorageValue = window.localStorage.getItem(service.localStorageKey);
expect(JSON.parse(newLocalStorageValue)).toEqual(items);
});
});
+
+ describe('save', () => {
+ beforeEach(() => {
+ spyOn(window.localStorage, 'setItem');
+ spyOn(RecentSearchesService, 'isAvailable');
+ });
+
+ describe('if .isAvailable returns `true`', () => {
+ const searchesString = 'searchesString';
+ const localStorageKey = 'localStorageKey';
+ const recentSearchesService = {
+ localStorageKey,
+ };
+
+ beforeEach(() => {
+ RecentSearchesService.isAvailable.and.returnValue(true);
+
+ spyOn(JSON, 'stringify').and.returnValue(searchesString);
+
+ RecentSearchesService.prototype.save.call(recentSearchesService);
+ });
+
+ it('should call .setItem', () => {
+ expect(window.localStorage.setItem).toHaveBeenCalledWith(localStorageKey, searchesString);
+ });
+ });
+
+ describe('if .isAvailable returns `false`', () => {
+ beforeEach(() => {
+ RecentSearchesService.isAvailable.and.returnValue(false);
+
+ RecentSearchesService.prototype.save();
+ });
+
+ it('should not call .setItem', () => {
+ expect(window.localStorage.setItem).not.toHaveBeenCalled();
+ });
+ });
+ });
+
+ describe('isAvailable', () => {
+ let isAvailable;
+
+ beforeEach(() => {
+ spyOn(AccessorUtilities, 'isLocalStorageAccessSafe').and.callThrough();
+
+ isAvailable = RecentSearchesService.isAvailable();
+ });
+
+ it('should call .isLocalStorageAccessSafe', () => {
+ expect(AccessorUtilities.isLocalStorageAccessSafe).toHaveBeenCalled();
+ });
+
+ it('should return a boolean', () => {
+ expect(typeof isAvailable).toBe('boolean');
+ });
+ });
});
diff --git a/spec/javascripts/fixtures/labels.rb b/spec/javascripts/fixtures/labels.rb
new file mode 100644
index 00000000000..2e4811b64a4
--- /dev/null
+++ b/spec/javascripts/fixtures/labels.rb
@@ -0,0 +1,56 @@
+require 'spec_helper'
+
+describe 'Labels (JavaScript fixtures)' do
+ include JavaScriptFixturesHelpers
+
+ let(:admin) { create(:admin) }
+ let(:group) { create(:group, name: 'frontend-fixtures-group' )}
+ let(:project) { create(:project_empty_repo, namespace: group, path: 'labels-project') }
+
+ let!(:project_label_bug) { create(:label, project: project, title: 'bug', color: '#FF0000') }
+ let!(:project_label_enhancement) { create(:label, project: project, title: 'enhancement', color: '#00FF00') }
+ let!(:project_label_feature) { create(:label, project: project, title: 'feature', color: '#0000FF') }
+
+ let!(:group_label_roses) { create(:group_label, group: group, title: 'roses', color: '#FF0000') }
+ let!(:groub_label_space) { create(:group_label, group: group, title: 'some space', color: '#FFFFFF') }
+ let!(:groub_label_violets) { create(:group_label, group: group, title: 'violets', color: '#0000FF') }
+
+ before(:all) do
+ clean_frontend_fixtures('labels/')
+ end
+
+ describe Groups::LabelsController, '(JavaScript fixtures)', type: :controller do
+ render_views
+
+ before(:each) do
+ sign_in(admin)
+ end
+
+ it 'labels/group_labels.json' do |example|
+ get :index,
+ group_id: group,
+ format: 'json'
+
+ expect(response).to be_success
+ store_frontend_fixture(response, example.description)
+ end
+ end
+
+ describe Projects::LabelsController, '(JavaScript fixtures)', type: :controller do
+ render_views
+
+ before(:each) do
+ sign_in(admin)
+ end
+
+ it 'labels/project_labels.json' do |example|
+ get :index,
+ namespace_id: group,
+ project_id: project,
+ format: 'json'
+
+ expect(response).to be_success
+ store_frontend_fixture(response, example.description)
+ end
+ end
+end
diff --git a/spec/javascripts/helpers/user_mock_data_helper.js b/spec/javascripts/helpers/user_mock_data_helper.js
new file mode 100644
index 00000000000..a9783ea065c
--- /dev/null
+++ b/spec/javascripts/helpers/user_mock_data_helper.js
@@ -0,0 +1,16 @@
+export default {
+ createNumberRandomUsers(numberUsers) {
+ const users = [];
+ for (let i = 0; i < numberUsers; i = i += 1) {
+ users.push(
+ {
+ avatar: 'http://gravatar.com/avatar/e64c7d89f26bd1972efa854d13d7dd61?s=80&d=identicon',
+ id: (i + 1),
+ name: `GitLab User ${i}`,
+ username: `gitlab${i}`,
+ },
+ );
+ }
+ return users;
+ },
+};
diff --git a/spec/javascripts/issuable_time_tracker_spec.js b/spec/javascripts/issuable_time_tracker_spec.js
index 0a830f25e29..8ff93c4f918 100644
--- a/spec/javascripts/issuable_time_tracker_spec.js
+++ b/spec/javascripts/issuable_time_tracker_spec.js
@@ -2,7 +2,7 @@
import Vue from 'vue';
-require('~/issuable/time_tracking/components/time_tracker');
+import timeTracker from '~/sidebar/components/time_tracking/time_tracker';
function initTimeTrackingComponent(opts) {
setFixtures(`
@@ -16,187 +16,185 @@ function initTimeTrackingComponent(opts) {
time_spent: opts.timeSpent,
human_time_estimate: opts.timeEstimateHumanReadable,
human_time_spent: opts.timeSpentHumanReadable,
- docsUrl: '/help/workflow/time_tracking.md',
+ rootPath: '/',
};
- const TimeTrackingComponent = Vue.component('issuable-time-tracker');
+ const TimeTrackingComponent = Vue.extend(timeTracker);
this.timeTracker = new TimeTrackingComponent({
el: '#mock-container',
propsData: this.initialData,
});
}
-((gl) => {
- describe('Issuable Time Tracker', function() {
- describe('Initialization', function() {
- beforeEach(function() {
- initTimeTrackingComponent.call(this, { timeEstimate: 100000, timeSpent: 5000, timeEstimateHumanReadable: '2h 46m', timeSpentHumanReadable: '1h 23m' });
- });
+describe('Issuable Time Tracker', function() {
+ describe('Initialization', function() {
+ beforeEach(function() {
+ initTimeTrackingComponent.call(this, { timeEstimate: 100000, timeSpent: 5000, timeEstimateHumanReadable: '2h 46m', timeSpentHumanReadable: '1h 23m' });
+ });
- it('should return something defined', function() {
- expect(this.timeTracker).toBeDefined();
- });
+ it('should return something defined', function() {
+ expect(this.timeTracker).toBeDefined();
+ });
- it ('should correctly set timeEstimate', function(done) {
- Vue.nextTick(() => {
- expect(this.timeTracker.timeEstimate).toBe(this.initialData.time_estimate);
- done();
- });
+ it ('should correctly set timeEstimate', function(done) {
+ Vue.nextTick(() => {
+ expect(this.timeTracker.timeEstimate).toBe(this.initialData.time_estimate);
+ done();
});
- it ('should correctly set time_spent', function(done) {
- Vue.nextTick(() => {
- expect(this.timeTracker.timeSpent).toBe(this.initialData.time_spent);
- done();
- });
+ });
+ it ('should correctly set time_spent', function(done) {
+ Vue.nextTick(() => {
+ expect(this.timeTracker.timeSpent).toBe(this.initialData.time_spent);
+ done();
});
});
+ });
- describe('Content Display', function() {
- describe('Panes', function() {
- describe('Comparison pane', function() {
- beforeEach(function() {
- initTimeTrackingComponent.call(this, { timeEstimate: 100000, timeSpent: 5000, timeEstimateHumanReadable: '', timeSpentHumanReadable: '' });
+ describe('Content Display', function() {
+ describe('Panes', function() {
+ describe('Comparison pane', function() {
+ beforeEach(function() {
+ initTimeTrackingComponent.call(this, { timeEstimate: 100000, timeSpent: 5000, timeEstimateHumanReadable: '', timeSpentHumanReadable: '' });
+ });
+
+ it('should show the "Comparison" pane when timeEstimate and time_spent are truthy', function(done) {
+ Vue.nextTick(() => {
+ const $comparisonPane = this.timeTracker.$el.querySelector('.time-tracking-comparison-pane');
+ expect(this.timeTracker.showComparisonState).toBe(true);
+ done();
});
+ });
- it('should show the "Comparison" pane when timeEstimate and time_spent are truthy', function(done) {
+ describe('Remaining meter', function() {
+ it('should display the remaining meter with the correct width', function(done) {
Vue.nextTick(() => {
- const $comparisonPane = this.timeTracker.$el.querySelector('.time-tracking-comparison-pane');
- expect(this.timeTracker.showComparisonState).toBe(true);
+ const meterWidth = this.timeTracker.$el.querySelector('.time-tracking-comparison-pane .meter-fill').style.width;
+ const correctWidth = '5%';
+
+ expect(meterWidth).toBe(correctWidth);
done();
- });
+ })
});
- describe('Remaining meter', function() {
- it('should display the remaining meter with the correct width', function(done) {
- Vue.nextTick(() => {
- const meterWidth = this.timeTracker.$el.querySelector('.time-tracking-comparison-pane .meter-fill').style.width;
- const correctWidth = '5%';
-
- expect(meterWidth).toBe(correctWidth);
- done();
- })
- });
-
- it('should display the remaining meter with the correct background color when within estimate', function(done) {
- Vue.nextTick(() => {
- const styledMeter = $(this.timeTracker.$el).find('.time-tracking-comparison-pane .within_estimate .meter-fill');
- expect(styledMeter.length).toBe(1);
- done()
- });
+ it('should display the remaining meter with the correct background color when within estimate', function(done) {
+ Vue.nextTick(() => {
+ const styledMeter = $(this.timeTracker.$el).find('.time-tracking-comparison-pane .within_estimate .meter-fill');
+ expect(styledMeter.length).toBe(1);
+ done()
});
+ });
- it('should display the remaining meter with the correct background color when over estimate', function(done) {
- this.timeTracker.time_estimate = 100000;
- this.timeTracker.time_spent = 20000000;
- Vue.nextTick(() => {
- const styledMeter = $(this.timeTracker.$el).find('.time-tracking-comparison-pane .over_estimate .meter-fill');
- expect(styledMeter.length).toBe(1);
- done();
- });
+ it('should display the remaining meter with the correct background color when over estimate', function(done) {
+ this.timeTracker.time_estimate = 100000;
+ this.timeTracker.time_spent = 20000000;
+ Vue.nextTick(() => {
+ const styledMeter = $(this.timeTracker.$el).find('.time-tracking-comparison-pane .over_estimate .meter-fill');
+ expect(styledMeter.length).toBe(1);
+ done();
});
});
});
+ });
- describe("Estimate only pane", function() {
- beforeEach(function() {
- initTimeTrackingComponent.call(this, { timeEstimate: 100000, timeSpent: 0, timeEstimateHumanReadable: '2h 46m', timeSpentHumanReadable: '' });
- });
+ describe("Estimate only pane", function() {
+ beforeEach(function() {
+ initTimeTrackingComponent.call(this, { timeEstimate: 100000, timeSpent: 0, timeEstimateHumanReadable: '2h 46m', timeSpentHumanReadable: '' });
+ });
- it('should display the human readable version of time estimated', function(done) {
- Vue.nextTick(() => {
- const estimateText = this.timeTracker.$el.querySelector('.time-tracking-estimate-only-pane').innerText;
- const correctText = 'Estimated: 2h 46m';
+ it('should display the human readable version of time estimated', function(done) {
+ Vue.nextTick(() => {
+ const estimateText = this.timeTracker.$el.querySelector('.time-tracking-estimate-only-pane').innerText;
+ const correctText = 'Estimated: 2h 46m';
- expect(estimateText).toBe(correctText);
- done();
- });
+ expect(estimateText).toBe(correctText);
+ done();
});
});
+ });
- describe('Spent only pane', function() {
- beforeEach(function() {
- initTimeTrackingComponent.call(this, { timeEstimate: 0, timeSpent: 5000, timeEstimateHumanReadable: '2h 46m', timeSpentHumanReadable: '1h 23m' });
- });
+ describe('Spent only pane', function() {
+ beforeEach(function() {
+ initTimeTrackingComponent.call(this, { timeEstimate: 0, timeSpent: 5000, timeEstimateHumanReadable: '2h 46m', timeSpentHumanReadable: '1h 23m' });
+ });
- it('should display the human readable version of time spent', function(done) {
- Vue.nextTick(() => {
- const spentText = this.timeTracker.$el.querySelector('.time-tracking-spend-only-pane').innerText;
- const correctText = 'Spent: 1h 23m';
+ it('should display the human readable version of time spent', function(done) {
+ Vue.nextTick(() => {
+ const spentText = this.timeTracker.$el.querySelector('.time-tracking-spend-only-pane').innerText;
+ const correctText = 'Spent: 1h 23m';
- expect(spentText).toBe(correctText);
- done();
- });
+ expect(spentText).toBe(correctText);
+ done();
});
});
+ });
- describe('No time tracking pane', function() {
- beforeEach(function() {
- initTimeTrackingComponent.call(this, { timeEstimate: 0, timeSpent: 0, timeEstimateHumanReadable: 0, timeSpentHumanReadable: 0 });
- });
+ describe('No time tracking pane', function() {
+ beforeEach(function() {
+ initTimeTrackingComponent.call(this, { timeEstimate: 0, timeSpent: 0, timeEstimateHumanReadable: '', timeSpentHumanReadable: '' });
+ });
- it('should only show the "No time tracking" pane when both timeEstimate and time_spent are falsey', function(done) {
- Vue.nextTick(() => {
- const $noTrackingPane = this.timeTracker.$el.querySelector('.time-tracking-no-tracking-pane');
- const noTrackingText =$noTrackingPane.innerText;
- const correctText = 'No estimate or time spent';
+ it('should only show the "No time tracking" pane when both timeEstimate and time_spent are falsey', function(done) {
+ Vue.nextTick(() => {
+ const $noTrackingPane = this.timeTracker.$el.querySelector('.time-tracking-no-tracking-pane');
+ const noTrackingText =$noTrackingPane.innerText;
+ const correctText = 'No estimate or time spent';
- expect(this.timeTracker.showNoTimeTrackingState).toBe(true);
- expect($noTrackingPane).toBeVisible();
- expect(noTrackingText).toBe(correctText);
- done();
- });
+ expect(this.timeTracker.showNoTimeTrackingState).toBe(true);
+ expect($noTrackingPane).toBeVisible();
+ expect(noTrackingText).toBe(correctText);
+ done();
});
});
+ });
- describe("Help pane", function() {
- beforeEach(function() {
- initTimeTrackingComponent.call(this, { timeEstimate: 0, timeSpent: 0 });
- });
+ describe("Help pane", function() {
+ beforeEach(function() {
+ initTimeTrackingComponent.call(this, { timeEstimate: 0, timeSpent: 0 });
+ });
- it('should not show the "Help" pane by default', function(done) {
- Vue.nextTick(() => {
- const $helpPane = this.timeTracker.$el.querySelector('.time-tracking-help-state');
+ it('should not show the "Help" pane by default', function(done) {
+ Vue.nextTick(() => {
+ const $helpPane = this.timeTracker.$el.querySelector('.time-tracking-help-state');
- expect(this.timeTracker.showHelpState).toBe(false);
- expect($helpPane).toBeNull();
- done();
- });
+ expect(this.timeTracker.showHelpState).toBe(false);
+ expect($helpPane).toBeNull();
+ done();
});
+ });
- it('should show the "Help" pane when help button is clicked', function(done) {
- Vue.nextTick(() => {
- $(this.timeTracker.$el).find('.help-button').click();
+ it('should show the "Help" pane when help button is clicked', function(done) {
+ Vue.nextTick(() => {
+ $(this.timeTracker.$el).find('.help-button').click();
- setTimeout(() => {
- const $helpPane = this.timeTracker.$el.querySelector('.time-tracking-help-state');
- expect(this.timeTracker.showHelpState).toBe(true);
- expect($helpPane).toBeVisible();
- done();
- }, 10);
- });
+ setTimeout(() => {
+ const $helpPane = this.timeTracker.$el.querySelector('.time-tracking-help-state');
+ expect(this.timeTracker.showHelpState).toBe(true);
+ expect($helpPane).toBeVisible();
+ done();
+ }, 10);
});
+ });
- it('should not show the "Help" pane when help button is clicked and then closed', function(done) {
- Vue.nextTick(() => {
- $(this.timeTracker.$el).find('.help-button').click();
+ it('should not show the "Help" pane when help button is clicked and then closed', function(done) {
+ Vue.nextTick(() => {
+ $(this.timeTracker.$el).find('.help-button').click();
- setTimeout(() => {
+ setTimeout(() => {
- $(this.timeTracker.$el).find('.close-help-button').click();
+ $(this.timeTracker.$el).find('.close-help-button').click();
- setTimeout(() => {
- const $helpPane = this.timeTracker.$el.querySelector('.time-tracking-help-state');
+ setTimeout(() => {
+ const $helpPane = this.timeTracker.$el.querySelector('.time-tracking-help-state');
- expect(this.timeTracker.showHelpState).toBe(false);
- expect($helpPane).toBeNull();
+ expect(this.timeTracker.showHelpState).toBe(false);
+ expect($helpPane).toBeNull();
- done();
- }, 1000);
+ done();
}, 1000);
- });
+ }, 1000);
});
});
});
});
});
-})(window.gl || (window.gl = {}));
+});
diff --git a/spec/javascripts/issue_show/issue_title_description_spec.js b/spec/javascripts/issue_show/issue_title_description_spec.js
new file mode 100644
index 00000000000..1ec4fe58b08
--- /dev/null
+++ b/spec/javascripts/issue_show/issue_title_description_spec.js
@@ -0,0 +1,60 @@
+import Vue from 'vue';
+import $ from 'jquery';
+import '~/render_math';
+import '~/render_gfm';
+import issueTitleDescription from '~/issue_show/issue_title_description.vue';
+import issueShowData from './mock_data';
+
+window.$ = $;
+
+const issueShowInterceptor = data => (request, next) => {
+ next(request.respondWith(JSON.stringify(data), {
+ status: 200,
+ headers: {
+ 'POLL-INTERVAL': 1,
+ },
+ }));
+};
+
+describe('Issue Title', () => {
+ document.body.innerHTML = '<span id="task_status"></span>';
+
+ let IssueTitleDescriptionComponent;
+
+ beforeEach(() => {
+ IssueTitleDescriptionComponent = Vue.extend(issueTitleDescription);
+ });
+
+ afterEach(() => {
+ Vue.http.interceptors = _.without(Vue.http.interceptors, issueShowInterceptor);
+ });
+
+ it('should render a title/description and update title/description on update', (done) => {
+ Vue.http.interceptors.push(issueShowInterceptor(issueShowData.initialRequest));
+
+ const issueShowComponent = new IssueTitleDescriptionComponent({
+ propsData: {
+ canUpdateIssue: '.css-stuff',
+ endpoint: '/gitlab-org/gitlab-shell/issues/9/rendered_title',
+ },
+ }).$mount();
+
+ setTimeout(() => {
+ expect(document.querySelector('title').innerText).toContain('this is a title (#1)');
+ expect(issueShowComponent.$el.querySelector('.title').innerHTML).toContain('<p>this is a title</p>');
+ expect(issueShowComponent.$el.querySelector('.wiki').innerHTML).toContain('<p>this is a description!</p>');
+ expect(issueShowComponent.$el.querySelector('.js-task-list-field').innerText).toContain('this is a description');
+
+ Vue.http.interceptors.push(issueShowInterceptor(issueShowData.secondRequest));
+
+ setTimeout(() => {
+ expect(document.querySelector('title').innerText).toContain('2 (#1)');
+ expect(issueShowComponent.$el.querySelector('.title').innerHTML).toContain('<p>2</p>');
+ expect(issueShowComponent.$el.querySelector('.wiki').innerHTML).toContain('<p>42</p>');
+ expect(issueShowComponent.$el.querySelector('.js-task-list-field').innerText).toContain('42');
+
+ done();
+ });
+ });
+ });
+});
diff --git a/spec/javascripts/issue_show/issue_title_spec.js b/spec/javascripts/issue_show/issue_title_spec.js
deleted file mode 100644
index 03edbf9f947..00000000000
--- a/spec/javascripts/issue_show/issue_title_spec.js
+++ /dev/null
@@ -1,22 +0,0 @@
-import Vue from 'vue';
-import issueTitle from '~/issue_show/issue_title.vue';
-
-describe('Issue Title', () => {
- let IssueTitleComponent;
-
- beforeEach(() => {
- IssueTitleComponent = Vue.extend(issueTitle);
- });
-
- it('should render a title', () => {
- const component = new IssueTitleComponent({
- propsData: {
- initialTitle: 'wow',
- endpoint: '/gitlab-org/gitlab-shell/issues/9/rendered_title',
- },
- }).$mount();
-
- expect(component.$el.classList).toContain('title');
- expect(component.$el.innerHTML).toContain('wow');
- });
-});
diff --git a/spec/javascripts/issue_show/mock_data.js b/spec/javascripts/issue_show/mock_data.js
new file mode 100644
index 00000000000..ad5a7b63470
--- /dev/null
+++ b/spec/javascripts/issue_show/mock_data.js
@@ -0,0 +1,26 @@
+export default {
+ initialRequest: {
+ title: '<p>this is a title</p>',
+ title_text: 'this is a title',
+ description: '<p>this is a description!</p>',
+ description_text: 'this is a description',
+ issue_number: 1,
+ task_status: '2 of 4 completed',
+ },
+ secondRequest: {
+ title: '<p>2</p>',
+ title_text: '2',
+ description: '<p>42</p>',
+ description_text: '42',
+ issue_number: 1,
+ task_status: '0 of 0 completed',
+ },
+ issueSpecRequest: {
+ title: '<p>this is a title</p>',
+ title_text: 'this is a title',
+ description: '<li class="task-list-item enabled"><input type="checkbox" class="task-list-item-checkbox">Task List Item</li>',
+ description_text: '- [ ] Task List Item',
+ issue_number: 1,
+ task_status: '0 of 1 completed',
+ },
+};
diff --git a/spec/javascripts/issue_spec.js b/spec/javascripts/issue_spec.js
index 0fd573eae3f..763f5ee9e50 100644
--- a/spec/javascripts/issue_spec.js
+++ b/spec/javascripts/issue_spec.js
@@ -81,12 +81,6 @@ describe('Issue', function() {
this.issue = new Issue();
});
- it('modifies the Markdown field', function() {
- spyOn(jQuery, 'ajax').and.stub();
- $('input[type=checkbox]').attr('checked', true).trigger('change');
- expect($('.js-task-list-field').val()).toBe('- [x] Task List Item');
- });
-
it('submits an ajax request on tasklist:changed', function() {
spyOn(jQuery, 'ajax').and.callFake(function(req) {
expect(req.type).toBe('PATCH');
diff --git a/spec/javascripts/lib/utils/accessor_spec.js b/spec/javascripts/lib/utils/accessor_spec.js
new file mode 100644
index 00000000000..b768d6f2a68
--- /dev/null
+++ b/spec/javascripts/lib/utils/accessor_spec.js
@@ -0,0 +1,78 @@
+import AccessorUtilities from '~/lib/utils/accessor';
+
+describe('AccessorUtilities', () => {
+ const testError = new Error('test error');
+
+ describe('isPropertyAccessSafe', () => {
+ let base;
+
+ it('should return `true` if access is safe', () => {
+ base = { testProp: 'testProp' };
+
+ expect(AccessorUtilities.isPropertyAccessSafe(base, 'testProp')).toBe(true);
+ });
+
+ it('should return `false` if access throws an error', () => {
+ base = { get testProp() { throw testError; } };
+
+ expect(AccessorUtilities.isPropertyAccessSafe(base, 'testProp')).toBe(false);
+ });
+
+ it('should return `false` if property is undefined', () => {
+ base = {};
+
+ expect(AccessorUtilities.isPropertyAccessSafe(base, 'testProp')).toBe(false);
+ });
+ });
+
+ describe('isFunctionCallSafe', () => {
+ const base = {};
+
+ it('should return `true` if calling is safe', () => {
+ base.func = () => {};
+
+ expect(AccessorUtilities.isFunctionCallSafe(base, 'func')).toBe(true);
+ });
+
+ it('should return `false` if calling throws an error', () => {
+ base.func = () => { throw new Error('test error'); };
+
+ expect(AccessorUtilities.isFunctionCallSafe(base, 'func')).toBe(false);
+ });
+
+ it('should return `false` if function is undefined', () => {
+ base.func = undefined;
+
+ expect(AccessorUtilities.isFunctionCallSafe(base, 'func')).toBe(false);
+ });
+ });
+
+ describe('isLocalStorageAccessSafe', () => {
+ beforeEach(() => {
+ spyOn(window.localStorage, 'setItem');
+ spyOn(window.localStorage, 'removeItem');
+ });
+
+ it('should return `true` if access is safe', () => {
+ expect(AccessorUtilities.isLocalStorageAccessSafe()).toBe(true);
+ });
+
+ it('should return `false` if access to .setItem isnt safe', () => {
+ window.localStorage.setItem.and.callFake(() => { throw testError; });
+
+ expect(AccessorUtilities.isLocalStorageAccessSafe()).toBe(false);
+ });
+
+ it('should set a test item if access is safe', () => {
+ AccessorUtilities.isLocalStorageAccessSafe();
+
+ expect(window.localStorage.setItem).toHaveBeenCalledWith('isLocalStorageAccessSafe', 'true');
+ });
+
+ it('should remove the test item if access is safe', () => {
+ AccessorUtilities.isLocalStorageAccessSafe();
+
+ expect(window.localStorage.removeItem).toHaveBeenCalledWith('isLocalStorageAccessSafe');
+ });
+ });
+});
diff --git a/spec/javascripts/lib/utils/ajax_cache_spec.js b/spec/javascripts/lib/utils/ajax_cache_spec.js
new file mode 100644
index 00000000000..7b466a11b92
--- /dev/null
+++ b/spec/javascripts/lib/utils/ajax_cache_spec.js
@@ -0,0 +1,129 @@
+import AjaxCache from '~/lib/utils/ajax_cache';
+
+describe('AjaxCache', () => {
+ const dummyEndpoint = '/AjaxCache/dummyEndpoint';
+ const dummyResponse = {
+ important: 'dummy data',
+ };
+ let ajaxSpy = (url) => {
+ expect(url).toBe(dummyEndpoint);
+ const deferred = $.Deferred();
+ deferred.resolve(dummyResponse);
+ return deferred.promise();
+ };
+
+ beforeEach(() => {
+ AjaxCache.internalStorage = { };
+ spyOn(jQuery, 'ajax').and.callFake(url => ajaxSpy(url));
+ });
+
+ describe('#get', () => {
+ it('returns undefined if cache is empty', () => {
+ const data = AjaxCache.get(dummyEndpoint);
+
+ expect(data).toBe(undefined);
+ });
+
+ it('returns undefined if cache contains no matching data', () => {
+ AjaxCache.internalStorage['not matching'] = dummyResponse;
+
+ const data = AjaxCache.get(dummyEndpoint);
+
+ expect(data).toBe(undefined);
+ });
+
+ it('returns matching data', () => {
+ AjaxCache.internalStorage[dummyEndpoint] = dummyResponse;
+
+ const data = AjaxCache.get(dummyEndpoint);
+
+ expect(data).toBe(dummyResponse);
+ });
+ });
+
+ describe('#hasData', () => {
+ it('returns false if cache is empty', () => {
+ expect(AjaxCache.hasData(dummyEndpoint)).toBe(false);
+ });
+
+ it('returns false if cache contains no matching data', () => {
+ AjaxCache.internalStorage['not matching'] = dummyResponse;
+
+ expect(AjaxCache.hasData(dummyEndpoint)).toBe(false);
+ });
+
+ it('returns true if data is available', () => {
+ AjaxCache.internalStorage[dummyEndpoint] = dummyResponse;
+
+ expect(AjaxCache.hasData(dummyEndpoint)).toBe(true);
+ });
+ });
+
+ describe('#purge', () => {
+ it('does nothing if cache is empty', () => {
+ AjaxCache.purge(dummyEndpoint);
+
+ expect(AjaxCache.internalStorage).toEqual({ });
+ });
+
+ it('does nothing if cache contains no matching data', () => {
+ AjaxCache.internalStorage['not matching'] = dummyResponse;
+
+ AjaxCache.purge(dummyEndpoint);
+
+ expect(AjaxCache.internalStorage['not matching']).toBe(dummyResponse);
+ });
+
+ it('removes matching data', () => {
+ AjaxCache.internalStorage[dummyEndpoint] = dummyResponse;
+
+ AjaxCache.purge(dummyEndpoint);
+
+ expect(AjaxCache.internalStorage).toEqual({ });
+ });
+ });
+
+ describe('#retrieve', () => {
+ it('stores and returns data from Ajax call if cache is empty', (done) => {
+ AjaxCache.retrieve(dummyEndpoint)
+ .then((data) => {
+ expect(data).toBe(dummyResponse);
+ expect(AjaxCache.internalStorage[dummyEndpoint]).toBe(dummyResponse);
+ })
+ .then(done)
+ .catch(fail);
+ });
+
+ it('returns undefined if Ajax call fails and cache is empty', (done) => {
+ const dummyStatusText = 'exploded';
+ const dummyErrorMessage = 'server exploded';
+ ajaxSpy = (url) => {
+ expect(url).toBe(dummyEndpoint);
+ const deferred = $.Deferred();
+ deferred.reject(null, dummyStatusText, dummyErrorMessage);
+ return deferred.promise();
+ };
+
+ AjaxCache.retrieve(dummyEndpoint)
+ .then(data => fail(`Received unexpected data: ${JSON.stringify(data)}`))
+ .catch((error) => {
+ expect(error.message).toBe(`${dummyEndpoint}: ${dummyErrorMessage}`);
+ expect(error.textStatus).toBe(dummyStatusText);
+ done();
+ })
+ .catch(fail);
+ });
+
+ it('makes no Ajax call if matching data exists', (done) => {
+ AjaxCache.internalStorage[dummyEndpoint] = dummyResponse;
+ ajaxSpy = () => fail(new Error('expected no Ajax call!'));
+
+ AjaxCache.retrieve(dummyEndpoint)
+ .then((data) => {
+ expect(data).toBe(dummyResponse);
+ })
+ .then(done)
+ .catch(fail);
+ });
+ });
+});
diff --git a/spec/javascripts/notes_spec.js b/spec/javascripts/notes_spec.js
index 7bffa90ab14..cfd599f793e 100644
--- a/spec/javascripts/notes_spec.js
+++ b/spec/javascripts/notes_spec.js
@@ -29,7 +29,7 @@ import '~/notes';
$('.js-comment-button').on('click', function(e) {
e.preventDefault();
});
- this.notes = new Notes();
+ this.notes = new Notes('', []);
});
it('modifies the Markdown field', function() {
@@ -51,7 +51,7 @@ import '~/notes';
var textarea = '.js-note-text';
beforeEach(function() {
- this.notes = new Notes();
+ this.notes = new Notes('', []);
this.autoSizeSpy = spyOnEvent($(textarea), 'autosize:update');
spyOn(this.notes, 'renderNote').and.stub();
@@ -273,9 +273,92 @@ import '~/notes';
});
});
+ describe('postComment & updateComment', () => {
+ const sampleComment = 'foo';
+ const updatedComment = 'bar';
+ const note = {
+ id: 1234,
+ html: `<li class="note note-row-1234 timeline-entry" id="note_1234">
+ <div class="note-text">${sampleComment}</div>
+ </li>`,
+ note: sampleComment,
+ valid: true
+ };
+ let $form;
+ let $notesContainer;
+
+ beforeEach(() => {
+ this.notes = new Notes('', []);
+ window.gon.current_username = 'root';
+ window.gon.current_user_fullname = 'Administrator';
+ $form = $('form.js-main-target-form');
+ $notesContainer = $('ul.main-notes-list');
+ $form.find('textarea.js-note-text').val(sampleComment);
+ });
+
+ it('should show placeholder note while new comment is being posted', () => {
+ $('.js-comment-button').click();
+ expect($notesContainer.find('.note.being-posted').length > 0).toEqual(true);
+ });
+
+ it('should remove placeholder note when new comment is done posting', () => {
+ const deferred = $.Deferred();
+ spyOn($, 'ajax').and.returnValue(deferred.promise());
+ $('.js-comment-button').click();
+
+ deferred.resolve(note);
+ expect($notesContainer.find('.note.being-posted').length).toEqual(0);
+ });
+
+ it('should show actual note element when new comment is done posting', () => {
+ const deferred = $.Deferred();
+ spyOn($, 'ajax').and.returnValue(deferred.promise());
+ $('.js-comment-button').click();
+
+ deferred.resolve(note);
+ expect($notesContainer.find(`#note_${note.id}`).length > 0).toEqual(true);
+ });
+
+ it('should reset Form when new comment is done posting', () => {
+ const deferred = $.Deferred();
+ spyOn($, 'ajax').and.returnValue(deferred.promise());
+ $('.js-comment-button').click();
+
+ deferred.resolve(note);
+ expect($form.find('textarea.js-note-text').val()).toEqual('');
+ });
+
+ it('should show flash error message when new comment failed to be posted', () => {
+ const deferred = $.Deferred();
+ spyOn($, 'ajax').and.returnValue(deferred.promise());
+ $('.js-comment-button').click();
+
+ deferred.reject();
+ expect($notesContainer.parent().find('.flash-container .flash-text').is(':visible')).toEqual(true);
+ });
+
+ it('should show flash error message when comment failed to be updated', () => {
+ const deferred = $.Deferred();
+ spyOn($, 'ajax').and.returnValue(deferred.promise());
+ $('.js-comment-button').click();
+
+ deferred.resolve(note);
+ const $noteEl = $notesContainer.find(`#note_${note.id}`);
+ $noteEl.find('.js-note-edit').click();
+ $noteEl.find('textarea.js-note-text').val(updatedComment);
+ $noteEl.find('.js-comment-save-button').click();
+
+ deferred.reject();
+ const $updatedNoteEl = $notesContainer.find(`#note_${note.id}`);
+ expect($updatedNoteEl.hasClass('.being-posted')).toEqual(false); // Remove being-posted visuals
+ expect($updatedNoteEl.find('.note-text').text().trim()).toEqual(sampleComment); // See if comment reverted back to original
+ expect($('.flash-container').is(':visible')).toEqual(true); // Flash error message shown
+ });
+ });
+
describe('getFormData', () => {
it('should return form metadata object from form reference', () => {
- this.notes = new Notes();
+ this.notes = new Notes('', []);
const $form = $('form');
const sampleComment = 'foobar';
@@ -290,7 +373,7 @@ import '~/notes';
describe('hasSlashCommands', () => {
beforeEach(() => {
- this.notes = new Notes();
+ this.notes = new Notes('', []);
});
it('should return true when comment has slash commands', () => {
@@ -327,7 +410,7 @@ import '~/notes';
const currentUserFullname = 'Administrator';
beforeEach(() => {
- this.notes = new Notes();
+ this.notes = new Notes('', []);
});
it('should return constructed placeholder element for regular note based on form contents', () => {
@@ -364,129 +447,5 @@ import '~/notes';
expect($tempNote.find('.timeline-content').hasClass('discussion')).toBeTruthy();
});
});
-
- describe('postComment & updateComment', () => {
- const sampleComment = 'foo';
- const updatedComment = 'bar';
- const note = {
- id: 1234,
- html: `<li class="note note-row-1234 timeline-entry" id="note_1234">
- <div class="note-text">${sampleComment}</div>
- </li>`,
- note: sampleComment,
- valid: true
- };
- let $form;
- let $notesContainer;
-
- beforeEach(() => {
- this.notes = new Notes();
- window.gon.current_username = 'root';
- window.gon.current_user_fullname = 'Administrator';
- $form = $('form');
- $notesContainer = $('ul.main-notes-list');
- $form.find('textarea.js-note-text').val(sampleComment);
- $('.js-comment-button').click();
- });
-
- it('should show placeholder note while new comment is being posted', () => {
- expect($notesContainer.find('.note.being-posted').length > 0).toEqual(true);
- });
-
- it('should remove placeholder note when new comment is done posting', () => {
- spyOn($, 'ajax').and.callFake((options) => {
- options.success(note);
- expect($notesContainer.find('.note.being-posted').length).toEqual(0);
- });
- });
-
- it('should show actual note element when new comment is done posting', () => {
- spyOn($, 'ajax').and.callFake((options) => {
- options.success(note);
- expect($notesContainer.find(`#${note.id}`).length > 0).toEqual(true);
- });
- });
-
- it('should reset Form when new comment is done posting', () => {
- spyOn($, 'ajax').and.callFake((options) => {
- options.success(note);
- expect($form.find('textarea.js-note-text')).toEqual('');
- });
- });
-
- it('should trigger ajax:success event on Form when new comment is done posting', () => {
- spyOn($, 'ajax').and.callFake((options) => {
- options.success(note);
- spyOn($form, 'trigger');
- expect($form.trigger).toHaveBeenCalledWith('ajax:success', [note]);
- });
- });
-
- it('should show flash error message when new comment failed to be posted', () => {
- spyOn($, 'ajax').and.callFake((options) => {
- options.error();
- expect($notesContainer.parent().find('.flash-container .flash-text').is(':visible')).toEqual(true);
- });
- });
-
- it('should refill form textarea with original comment content when new comment failed to be posted', () => {
- spyOn($, 'ajax').and.callFake((options) => {
- options.error();
- expect($form.find('textarea.js-note-text')).toEqual(sampleComment);
- });
- });
-
- it('should show updated comment as _actively being posted_ while comment being updated', () => {
- spyOn($, 'ajax').and.callFake((options) => {
- options.success(note);
- const $noteEl = $notesContainer.find(`#note_${note.id}`);
- $noteEl.find('.js-note-edit').click();
- $noteEl.find('textarea.js-note-text').val(updatedComment);
- $noteEl.find('.js-comment-save-button').click();
- expect($noteEl.hasClass('.being-posted')).toEqual(true);
- expect($noteEl.find('.note-text').text()).toEqual(updatedComment);
- });
- });
-
- it('should show updated comment when comment update is done posting', () => {
- spyOn($, 'ajax').and.callFake((options) => {
- options.success(note);
- const $noteEl = $notesContainer.find(`#note_${note.id}`);
- $noteEl.find('.js-note-edit').click();
- $noteEl.find('textarea.js-note-text').val(updatedComment);
- $noteEl.find('.js-comment-save-button').click();
-
- spyOn($, 'ajax').and.callFake((updateOptions) => {
- const updatedNote = Object.assign({}, note);
- updatedNote.note = updatedComment;
- updatedNote.html = `<li class="note note-row-1234 timeline-entry" id="note_1234">
- <div class="note-text">${updatedComment}</div>
- </li>`;
- updateOptions.success(updatedNote);
- const $updatedNoteEl = $notesContainer.find(`#note_${updatedNote.id}`);
- expect($updatedNoteEl.hasClass('.being-posted')).toEqual(false); // Remove being-posted visuals
- expect($updatedNoteEl.find('note-text').text().trim()).toEqual(updatedComment); // Verify if comment text updated
- });
- });
- });
-
- it('should show flash error message when comment failed to be updated', () => {
- spyOn($, 'ajax').and.callFake((options) => {
- options.success(note);
- const $noteEl = $notesContainer.find(`#note_${note.id}`);
- $noteEl.find('.js-note-edit').click();
- $noteEl.find('textarea.js-note-text').val(updatedComment);
- $noteEl.find('.js-comment-save-button').click();
-
- spyOn($, 'ajax').and.callFake((updateOptions) => {
- updateOptions.error();
- const $updatedNoteEl = $notesContainer.find(`#note_${note.id}`);
- expect($updatedNoteEl.hasClass('.being-posted')).toEqual(false); // Remove being-posted visuals
- expect($updatedNoteEl.find('note-text').text().trim()).toEqual(sampleComment); // See if comment reverted back to original
- expect($notesContainer.parent().find('.flash-container .flash-text').is(':visible')).toEqual(true); // Flash error message shown
- });
- });
- });
- });
});
}).call(window);
diff --git a/spec/javascripts/raven/index_spec.js b/spec/javascripts/raven/index_spec.js
new file mode 100644
index 00000000000..b5662cd0331
--- /dev/null
+++ b/spec/javascripts/raven/index_spec.js
@@ -0,0 +1,42 @@
+import RavenConfig from '~/raven/raven_config';
+import index from '~/raven/index';
+
+describe('RavenConfig options', () => {
+ let sentryDsn;
+ let currentUserId;
+ let gitlabUrl;
+ let isProduction;
+ let indexReturnValue;
+
+ beforeEach(() => {
+ sentryDsn = 'sentryDsn';
+ currentUserId = 'currentUserId';
+ gitlabUrl = 'gitlabUrl';
+ isProduction = 'isProduction';
+
+ window.gon = {
+ sentry_dsn: sentryDsn,
+ current_user_id: currentUserId,
+ gitlab_url: gitlabUrl,
+ };
+
+ process.env.NODE_ENV = isProduction;
+
+ spyOn(RavenConfig, 'init');
+
+ indexReturnValue = index();
+ });
+
+ it('should init with .sentryDsn, .currentUserId, .whitelistUrls and .isProduction', () => {
+ expect(RavenConfig.init).toHaveBeenCalledWith({
+ sentryDsn,
+ currentUserId,
+ whitelistUrls: [gitlabUrl],
+ isProduction,
+ });
+ });
+
+ it('should return RavenConfig', () => {
+ expect(indexReturnValue).toBe(RavenConfig);
+ });
+});
diff --git a/spec/javascripts/raven/raven_config_spec.js b/spec/javascripts/raven/raven_config_spec.js
new file mode 100644
index 00000000000..a2d720760fc
--- /dev/null
+++ b/spec/javascripts/raven/raven_config_spec.js
@@ -0,0 +1,276 @@
+import Raven from 'raven-js';
+import RavenConfig from '~/raven/raven_config';
+
+describe('RavenConfig', () => {
+ describe('IGNORE_ERRORS', () => {
+ it('should be an array of strings', () => {
+ const areStrings = RavenConfig.IGNORE_ERRORS.every(error => typeof error === 'string');
+
+ expect(areStrings).toBe(true);
+ });
+ });
+
+ describe('IGNORE_URLS', () => {
+ it('should be an array of regexps', () => {
+ const areRegExps = RavenConfig.IGNORE_URLS.every(url => url instanceof RegExp);
+
+ expect(areRegExps).toBe(true);
+ });
+ });
+
+ describe('SAMPLE_RATE', () => {
+ it('should be a finite number', () => {
+ expect(typeof RavenConfig.SAMPLE_RATE).toEqual('number');
+ });
+ });
+
+ describe('init', () => {
+ let options;
+
+ beforeEach(() => {
+ options = {
+ sentryDsn: '//sentryDsn',
+ ravenAssetUrl: '//ravenAssetUrl',
+ currentUserId: 1,
+ whitelistUrls: ['//gitlabUrl'],
+ isProduction: true,
+ };
+
+ spyOn(RavenConfig, 'configure');
+ spyOn(RavenConfig, 'bindRavenErrors');
+ spyOn(RavenConfig, 'setUser');
+
+ RavenConfig.init(options);
+ });
+
+ it('should set the options property', () => {
+ expect(RavenConfig.options).toEqual(options);
+ });
+
+ it('should call the configure method', () => {
+ expect(RavenConfig.configure).toHaveBeenCalled();
+ });
+
+ it('should call the error bindings method', () => {
+ expect(RavenConfig.bindRavenErrors).toHaveBeenCalled();
+ });
+
+ it('should call setUser', () => {
+ expect(RavenConfig.setUser).toHaveBeenCalled();
+ });
+
+ it('should not call setUser if there is no current user ID', () => {
+ RavenConfig.setUser.calls.reset();
+
+ RavenConfig.init({
+ sentryDsn: '//sentryDsn',
+ ravenAssetUrl: '//ravenAssetUrl',
+ currentUserId: undefined,
+ whitelistUrls: ['//gitlabUrl'],
+ isProduction: true,
+ });
+
+ expect(RavenConfig.setUser).not.toHaveBeenCalled();
+ });
+ });
+
+ describe('configure', () => {
+ let options;
+ let raven;
+ let ravenConfig;
+
+ beforeEach(() => {
+ options = {
+ sentryDsn: '//sentryDsn',
+ whitelistUrls: ['//gitlabUrl'],
+ isProduction: true,
+ };
+
+ ravenConfig = jasmine.createSpyObj('ravenConfig', ['shouldSendSample']);
+ raven = jasmine.createSpyObj('raven', ['install']);
+
+ spyOn(Raven, 'config').and.returnValue(raven);
+
+ ravenConfig.options = options;
+ ravenConfig.IGNORE_ERRORS = 'ignore_errors';
+ ravenConfig.IGNORE_URLS = 'ignore_urls';
+
+ RavenConfig.configure.call(ravenConfig);
+ });
+
+ it('should call Raven.config', () => {
+ expect(Raven.config).toHaveBeenCalledWith(options.sentryDsn, {
+ whitelistUrls: options.whitelistUrls,
+ environment: 'production',
+ ignoreErrors: ravenConfig.IGNORE_ERRORS,
+ ignoreUrls: ravenConfig.IGNORE_URLS,
+ shouldSendCallback: jasmine.any(Function),
+ });
+ });
+
+ it('should call Raven.install', () => {
+ expect(raven.install).toHaveBeenCalled();
+ });
+
+ it('should set .environment to development if isProduction is false', () => {
+ ravenConfig.options.isProduction = false;
+
+ RavenConfig.configure.call(ravenConfig);
+
+ expect(Raven.config).toHaveBeenCalledWith(options.sentryDsn, {
+ whitelistUrls: options.whitelistUrls,
+ environment: 'development',
+ ignoreErrors: ravenConfig.IGNORE_ERRORS,
+ ignoreUrls: ravenConfig.IGNORE_URLS,
+ shouldSendCallback: jasmine.any(Function),
+ });
+ });
+ });
+
+ describe('setUser', () => {
+ let ravenConfig;
+
+ beforeEach(() => {
+ ravenConfig = { options: { currentUserId: 1 } };
+ spyOn(Raven, 'setUserContext');
+
+ RavenConfig.setUser.call(ravenConfig);
+ });
+
+ it('should call .setUserContext', function () {
+ expect(Raven.setUserContext).toHaveBeenCalledWith({
+ id: ravenConfig.options.currentUserId,
+ });
+ });
+ });
+
+ describe('bindRavenErrors', () => {
+ let $document;
+ let $;
+
+ beforeEach(() => {
+ $document = jasmine.createSpyObj('$document', ['on']);
+ $ = jasmine.createSpy('$').and.returnValue($document);
+
+ window.$ = $;
+
+ RavenConfig.bindRavenErrors();
+ });
+
+ it('should call .on', function () {
+ expect($document.on).toHaveBeenCalledWith('ajaxError.raven', RavenConfig.handleRavenErrors);
+ });
+ });
+
+ describe('handleRavenErrors', () => {
+ let event;
+ let req;
+ let config;
+ let err;
+
+ beforeEach(() => {
+ event = {};
+ req = { status: 'status', responseText: 'responseText', statusText: 'statusText' };
+ config = { type: 'type', url: 'url', data: 'data' };
+ err = {};
+
+ spyOn(Raven, 'captureMessage');
+
+ RavenConfig.handleRavenErrors(event, req, config, err);
+ });
+
+ it('should call Raven.captureMessage', () => {
+ expect(Raven.captureMessage).toHaveBeenCalledWith(err, {
+ extra: {
+ type: config.type,
+ url: config.url,
+ data: config.data,
+ status: req.status,
+ response: req.responseText,
+ error: err,
+ event,
+ },
+ });
+ });
+
+ describe('if no err is provided', () => {
+ beforeEach(() => {
+ Raven.captureMessage.calls.reset();
+
+ RavenConfig.handleRavenErrors(event, req, config);
+ });
+
+ it('should use req.statusText as the error value', () => {
+ expect(Raven.captureMessage).toHaveBeenCalledWith(req.statusText, {
+ extra: {
+ type: config.type,
+ url: config.url,
+ data: config.data,
+ status: req.status,
+ response: req.responseText,
+ error: req.statusText,
+ event,
+ },
+ });
+ });
+ });
+
+ describe('if no req.responseText is provided', () => {
+ beforeEach(() => {
+ req.responseText = undefined;
+
+ Raven.captureMessage.calls.reset();
+
+ RavenConfig.handleRavenErrors(event, req, config, err);
+ });
+
+ it('should use `Unknown response text` as the response', () => {
+ expect(Raven.captureMessage).toHaveBeenCalledWith(err, {
+ extra: {
+ type: config.type,
+ url: config.url,
+ data: config.data,
+ status: req.status,
+ response: 'Unknown response text',
+ error: err,
+ event,
+ },
+ });
+ });
+ });
+ });
+
+ describe('shouldSendSample', () => {
+ let randomNumber;
+
+ beforeEach(() => {
+ RavenConfig.SAMPLE_RATE = 50;
+
+ spyOn(Math, 'random').and.callFake(() => randomNumber);
+ });
+
+ it('should call Math.random', () => {
+ RavenConfig.shouldSendSample();
+
+ expect(Math.random).toHaveBeenCalled();
+ });
+
+ it('should return true if the sample rate is greater than the random number * 100', () => {
+ randomNumber = 0.1;
+
+ expect(RavenConfig.shouldSendSample()).toBe(true);
+ });
+
+ it('should return false if the sample rate is less than the random number * 100', () => {
+ randomNumber = 0.9;
+
+ expect(RavenConfig.shouldSendSample()).toBe(false);
+ });
+
+ it('should return true if the sample rate is equal to the random number * 100', () => {
+ randomNumber = 0.5;
+
+ expect(RavenConfig.shouldSendSample()).toBe(true);
+ });
+ });
+});
diff --git a/spec/javascripts/sidebar/assignee_title_spec.js b/spec/javascripts/sidebar/assignee_title_spec.js
new file mode 100644
index 00000000000..5b5b1bf4140
--- /dev/null
+++ b/spec/javascripts/sidebar/assignee_title_spec.js
@@ -0,0 +1,80 @@
+import Vue from 'vue';
+import AssigneeTitle from '~/sidebar/components/assignees/assignee_title';
+
+describe('AssigneeTitle component', () => {
+ let component;
+ let AssigneeTitleComponent;
+
+ beforeEach(() => {
+ AssigneeTitleComponent = Vue.extend(AssigneeTitle);
+ });
+
+ describe('assignee title', () => {
+ it('renders assignee', () => {
+ component = new AssigneeTitleComponent({
+ propsData: {
+ numberOfAssignees: 1,
+ editable: false,
+ },
+ }).$mount();
+
+ expect(component.$el.innerText.trim()).toEqual('Assignee');
+ });
+
+ it('renders 2 assignees', () => {
+ component = new AssigneeTitleComponent({
+ propsData: {
+ numberOfAssignees: 2,
+ editable: false,
+ },
+ }).$mount();
+
+ expect(component.$el.innerText.trim()).toEqual('2 Assignees');
+ });
+ });
+
+ it('does not render spinner by default', () => {
+ component = new AssigneeTitleComponent({
+ propsData: {
+ numberOfAssignees: 0,
+ editable: false,
+ },
+ }).$mount();
+
+ expect(component.$el.querySelector('.fa')).toBeNull();
+ });
+
+ it('renders spinner when loading', () => {
+ component = new AssigneeTitleComponent({
+ propsData: {
+ loading: true,
+ numberOfAssignees: 0,
+ editable: false,
+ },
+ }).$mount();
+
+ expect(component.$el.querySelector('.fa')).not.toBeNull();
+ });
+
+ it('does not render edit link when not editable', () => {
+ component = new AssigneeTitleComponent({
+ propsData: {
+ numberOfAssignees: 0,
+ editable: false,
+ },
+ }).$mount();
+
+ expect(component.$el.querySelector('.edit-link')).toBeNull();
+ });
+
+ it('renders edit link when editable', () => {
+ component = new AssigneeTitleComponent({
+ propsData: {
+ numberOfAssignees: 0,
+ editable: true,
+ },
+ }).$mount();
+
+ expect(component.$el.querySelector('.edit-link')).not.toBeNull();
+ });
+});
diff --git a/spec/javascripts/sidebar/assignees_spec.js b/spec/javascripts/sidebar/assignees_spec.js
new file mode 100644
index 00000000000..c9453a21189
--- /dev/null
+++ b/spec/javascripts/sidebar/assignees_spec.js
@@ -0,0 +1,272 @@
+import Vue from 'vue';
+import Assignee from '~/sidebar/components/assignees/assignees';
+import UsersMock from './mock_data';
+import UsersMockHelper from '../helpers/user_mock_data_helper';
+
+describe('Assignee component', () => {
+ let component;
+ let AssigneeComponent;
+
+ beforeEach(() => {
+ AssigneeComponent = Vue.extend(Assignee);
+ });
+
+ describe('No assignees/users', () => {
+ it('displays no assignee icon when collapsed', () => {
+ component = new AssigneeComponent({
+ propsData: {
+ rootPath: 'http://localhost:3000',
+ users: [],
+ editable: false,
+ },
+ }).$mount();
+
+ const collapsed = component.$el.querySelector('.sidebar-collapsed-icon');
+ expect(collapsed.childElementCount).toEqual(1);
+ expect(collapsed.children[0].getAttribute('aria-label')).toEqual('No Assignee');
+ expect(collapsed.children[0].classList.contains('fa')).toEqual(true);
+ expect(collapsed.children[0].classList.contains('fa-user')).toEqual(true);
+ });
+
+ it('displays only "No assignee" when no users are assigned and the issue is read-only', () => {
+ component = new AssigneeComponent({
+ propsData: {
+ rootPath: 'http://localhost:3000',
+ users: [],
+ editable: false,
+ },
+ }).$mount();
+ const componentTextNoUsers = component.$el.querySelector('.assign-yourself').innerText.trim();
+
+ expect(componentTextNoUsers).toBe('No assignee');
+ expect(componentTextNoUsers.indexOf('assign yourself')).toEqual(-1);
+ });
+
+ it('displays only "No assignee" when no users are assigned and the issue can be edited', () => {
+ component = new AssigneeComponent({
+ propsData: {
+ rootPath: 'http://localhost:3000',
+ users: [],
+ editable: true,
+ },
+ }).$mount();
+ const componentTextNoUsers = component.$el.querySelector('.assign-yourself').innerText.trim();
+
+ expect(componentTextNoUsers.indexOf('No assignee')).toEqual(0);
+ expect(componentTextNoUsers.indexOf('assign yourself')).toBeGreaterThan(0);
+ });
+
+ it('emits the assign-self event when "assign yourself" is clicked', () => {
+ component = new AssigneeComponent({
+ propsData: {
+ rootPath: 'http://localhost:3000',
+ users: [],
+ editable: true,
+ },
+ }).$mount();
+
+ spyOn(component, '$emit');
+ component.$el.querySelector('.assign-yourself .btn-link').click();
+ expect(component.$emit).toHaveBeenCalledWith('assign-self');
+ });
+ });
+
+ describe('One assignee/user', () => {
+ it('displays one assignee icon when collapsed', () => {
+ component = new AssigneeComponent({
+ propsData: {
+ rootPath: 'http://localhost:3000',
+ users: [
+ UsersMock.user,
+ ],
+ editable: false,
+ },
+ }).$mount();
+
+ const collapsed = component.$el.querySelector('.sidebar-collapsed-icon');
+ const assignee = collapsed.children[0];
+ expect(collapsed.childElementCount).toEqual(1);
+ expect(assignee.querySelector('.avatar').getAttribute('src')).toEqual(UsersMock.user.avatar);
+ expect(assignee.querySelector('.avatar').getAttribute('alt')).toEqual(`${UsersMock.user.name}'s avatar`);
+ expect(assignee.querySelector('.author').innerText.trim()).toEqual(UsersMock.user.name);
+ });
+
+ it('Shows one user with avatar, username and author name', () => {
+ component = new AssigneeComponent({
+ propsData: {
+ rootPath: 'http://localhost:3000/',
+ users: [
+ UsersMock.user,
+ ],
+ editable: true,
+ },
+ }).$mount();
+
+ expect(component.$el.querySelector('.author_link')).not.toBeNull();
+ // The image
+ expect(component.$el.querySelector('.author_link img').getAttribute('src')).toEqual(UsersMock.user.avatar);
+ // Author name
+ expect(component.$el.querySelector('.author_link .author').innerText.trim()).toEqual(UsersMock.user.name);
+ // Username
+ expect(component.$el.querySelector('.author_link .username').innerText.trim()).toEqual(`@${UsersMock.user.username}`);
+ });
+
+ it('has the root url present in the assigneeUrl method', () => {
+ component = new AssigneeComponent({
+ propsData: {
+ rootPath: 'http://localhost:3000/',
+ users: [
+ UsersMock.user,
+ ],
+ editable: true,
+ },
+ }).$mount();
+
+ expect(component.assigneeUrl(UsersMock.user).indexOf('http://localhost:3000/')).not.toEqual(-1);
+ });
+ });
+
+ describe('Two or more assignees/users', () => {
+ it('displays two assignee icons when collapsed', () => {
+ const users = UsersMockHelper.createNumberRandomUsers(2);
+ component = new AssigneeComponent({
+ propsData: {
+ rootPath: 'http://localhost:3000',
+ users,
+ editable: false,
+ },
+ }).$mount();
+
+ const collapsed = component.$el.querySelector('.sidebar-collapsed-icon');
+ expect(collapsed.childElementCount).toEqual(2);
+
+ const first = collapsed.children[0];
+ expect(first.querySelector('.avatar').getAttribute('src')).toEqual(users[0].avatar);
+ expect(first.querySelector('.avatar').getAttribute('alt')).toEqual(`${users[0].name}'s avatar`);
+ expect(first.querySelector('.author').innerText.trim()).toEqual(users[0].name);
+
+ const second = collapsed.children[1];
+ expect(second.querySelector('.avatar').getAttribute('src')).toEqual(users[1].avatar);
+ expect(second.querySelector('.avatar').getAttribute('alt')).toEqual(`${users[1].name}'s avatar`);
+ expect(second.querySelector('.author').innerText.trim()).toEqual(users[1].name);
+ });
+
+ it('displays one assignee icon and counter when collapsed', () => {
+ const users = UsersMockHelper.createNumberRandomUsers(3);
+ component = new AssigneeComponent({
+ propsData: {
+ rootPath: 'http://localhost:3000',
+ users,
+ editable: false,
+ },
+ }).$mount();
+
+ const collapsed = component.$el.querySelector('.sidebar-collapsed-icon');
+ expect(collapsed.childElementCount).toEqual(2);
+
+ const first = collapsed.children[0];
+ expect(first.querySelector('.avatar').getAttribute('src')).toEqual(users[0].avatar);
+ expect(first.querySelector('.avatar').getAttribute('alt')).toEqual(`${users[0].name}'s avatar`);
+ expect(first.querySelector('.author').innerText.trim()).toEqual(users[0].name);
+
+ const second = collapsed.children[1];
+ expect(second.querySelector('.avatar-counter').innerText.trim()).toEqual('+2');
+ });
+
+ it('Shows two assignees', () => {
+ const users = UsersMockHelper.createNumberRandomUsers(2);
+ component = new AssigneeComponent({
+ propsData: {
+ rootPath: 'http://localhost:3000',
+ users,
+ editable: true,
+ },
+ }).$mount();
+
+ expect(component.$el.querySelectorAll('.user-item').length).toEqual(users.length);
+ expect(component.$el.querySelector('.user-list-more')).toBe(null);
+ });
+
+ it('Shows the "show-less" assignees label', (done) => {
+ const users = UsersMockHelper.createNumberRandomUsers(6);
+ component = new AssigneeComponent({
+ propsData: {
+ rootPath: 'http://localhost:3000',
+ users,
+ editable: true,
+ },
+ }).$mount();
+
+ expect(component.$el.querySelectorAll('.user-item').length).toEqual(component.defaultRenderCount);
+ expect(component.$el.querySelector('.user-list-more')).not.toBe(null);
+ const usersLabelExpectation = users.length - component.defaultRenderCount;
+ expect(component.$el.querySelector('.user-list-more .btn-link').innerText.trim())
+ .not.toBe(`+${usersLabelExpectation} more`);
+ component.toggleShowLess();
+ Vue.nextTick(() => {
+ expect(component.$el.querySelector('.user-list-more .btn-link').innerText.trim())
+ .toBe('- show less');
+ done();
+ });
+ });
+
+ it('Shows the "show-less" when "n+ more " label is clicked', (done) => {
+ const users = UsersMockHelper.createNumberRandomUsers(6);
+ component = new AssigneeComponent({
+ propsData: {
+ rootPath: 'http://localhost:3000',
+ users,
+ editable: true,
+ },
+ }).$mount();
+
+ component.$el.querySelector('.user-list-more .btn-link').click();
+ Vue.nextTick(() => {
+ expect(component.$el.querySelector('.user-list-more .btn-link').innerText.trim())
+ .toBe('- show less');
+ done();
+ });
+ });
+
+ it('gets the count of avatar via a computed property ', () => {
+ const users = UsersMockHelper.createNumberRandomUsers(6);
+ component = new AssigneeComponent({
+ propsData: {
+ rootPath: 'http://localhost:3000',
+ users,
+ editable: true,
+ },
+ }).$mount();
+
+ expect(component.sidebarAvatarCounter).toEqual(`+${users.length - 1}`);
+ });
+
+ describe('n+ more label', () => {
+ beforeEach(() => {
+ const users = UsersMockHelper.createNumberRandomUsers(6);
+ component = new AssigneeComponent({
+ propsData: {
+ rootPath: 'http://localhost:3000',
+ users,
+ editable: true,
+ },
+ }).$mount();
+ });
+
+ it('shows "+1 more" label', () => {
+ expect(component.$el.querySelector('.user-list-more .btn-link').innerText.trim())
+ .toBe('+ 1 more');
+ });
+
+ it('shows "show less" label', (done) => {
+ component.toggleShowLess();
+
+ Vue.nextTick(() => {
+ expect(component.$el.querySelector('.user-list-more .btn-link').innerText.trim())
+ .toBe('- show less');
+ done();
+ });
+ });
+ });
+ });
+});
diff --git a/spec/javascripts/sidebar/mock_data.js b/spec/javascripts/sidebar/mock_data.js
new file mode 100644
index 00000000000..9fc8667ecc9
--- /dev/null
+++ b/spec/javascripts/sidebar/mock_data.js
@@ -0,0 +1,109 @@
+/* eslint-disable quote-props*/
+
+const sidebarMockData = {
+ 'GET': {
+ '/gitlab-org/gitlab-shell/issues/5.json': {
+ id: 45,
+ iid: 5,
+ author_id: 23,
+ description: 'Nulla ullam commodi delectus adipisci quis sit.',
+ lock_version: null,
+ milestone_id: 21,
+ position: 0,
+ state: 'closed',
+ title: 'Vel et nulla voluptatibus corporis dolor iste saepe laborum.',
+ updated_by_id: 1,
+ created_at: '2017-02-02T21: 49: 49.664Z',
+ updated_at: '2017-05-03T22: 26: 03.760Z',
+ deleted_at: null,
+ time_estimate: 0,
+ total_time_spent: 0,
+ human_time_estimate: null,
+ human_total_time_spent: null,
+ branch_name: null,
+ confidential: false,
+ assignees: [
+ {
+ name: 'User 0',
+ username: 'user0',
+ id: 22,
+ state: 'active',
+ avatar_url: 'http: //www.gravatar.com/avatar/52e4ce24a915fb7e51e1ad3b57f4b00a?s=80\u0026d=identicon',
+ web_url: 'http: //localhost:3001/user0',
+ },
+ {
+ name: 'Marguerite Bartell',
+ username: 'tajuana',
+ id: 18,
+ state: 'active',
+ avatar_url: 'http: //www.gravatar.com/avatar/4852a41fb41616bf8f140d3701673f53?s=80\u0026d=identicon',
+ web_url: 'http: //localhost:3001/tajuana',
+ },
+ {
+ name: 'Laureen Ritchie',
+ username: 'michaele.will',
+ id: 16,
+ state: 'active',
+ avatar_url: 'http: //www.gravatar.com/avatar/e301827eb03be955c9c172cb9a8e4e8a?s=80\u0026d=identicon',
+ web_url: 'http: //localhost:3001/michaele.will',
+ },
+ ],
+ due_date: null,
+ moved_to_id: null,
+ project_id: 4,
+ weight: null,
+ milestone: {
+ id: 21,
+ iid: 1,
+ project_id: 4,
+ title: 'v0.0',
+ description: 'Molestiae commodi laboriosam odio sunt eaque reprehenderit.',
+ state: 'active',
+ created_at: '2017-02-02T21: 49: 30.530Z',
+ updated_at: '2017-02-02T21: 49: 30.530Z',
+ due_date: null,
+ start_date: null,
+ },
+ labels: [],
+ },
+ },
+ 'PUT': {
+ '/gitlab-org/gitlab-shell/issues/5.json': {
+ data: {},
+ },
+ },
+};
+
+export default {
+ mediator: {
+ endpoint: '/gitlab-org/gitlab-shell/issues/5.json',
+ editable: true,
+ currentUser: {
+ id: 1,
+ name: 'Administrator',
+ username: 'root',
+ avatar_url: 'http://www.gravatar.com/avatar/e64c7d89f26bd1972efa854d13d7dd61?s=80&d=identicon',
+ },
+ rootPath: '/',
+ },
+ time: {
+ time_estimate: 3600,
+ total_time_spent: 0,
+ human_time_estimate: '1h',
+ human_total_time_spent: null,
+ },
+ user: {
+ avatar: 'http://gravatar.com/avatar/e64c7d89f26bd1972efa854d13d7dd61?s=80&d=identicon',
+ id: 1,
+ name: 'Administrator',
+ username: 'root',
+ },
+
+ sidebarMockInterceptor(request, next) {
+ const body = sidebarMockData[request.method.toUpperCase()][request.url];
+
+ next(request.respondWith(JSON.stringify(body), {
+ status: 200,
+ }));
+ },
+};
diff --git a/spec/javascripts/sidebar/sidebar_assignees_spec.js b/spec/javascripts/sidebar/sidebar_assignees_spec.js
new file mode 100644
index 00000000000..e0df0a3228f
--- /dev/null
+++ b/spec/javascripts/sidebar/sidebar_assignees_spec.js
@@ -0,0 +1,45 @@
+import Vue from 'vue';
+import SidebarAssignees from '~/sidebar/components/assignees/sidebar_assignees';
+import SidebarMediator from '~/sidebar/sidebar_mediator';
+import SidebarService from '~/sidebar/services/sidebar_service';
+import SidebarStore from '~/sidebar/stores/sidebar_store';
+import Mock from './mock_data';
+
+describe('sidebar assignees', () => {
+ let component;
+ let SidebarAssigneeComponent;
+ preloadFixtures('issues/open-issue.html.raw');
+
+ beforeEach(() => {
+ Vue.http.interceptors.push(Mock.sidebarMockInterceptor);
+ SidebarAssigneeComponent = Vue.extend(SidebarAssignees);
+ spyOn(SidebarMediator.prototype, 'saveAssignees').and.callThrough();
+ spyOn(SidebarMediator.prototype, 'assignYourself').and.callThrough();
+ this.mediator = new SidebarMediator(Mock.mediator);
+ loadFixtures('issues/open-issue.html.raw');
+ this.sidebarAssigneesEl = document.querySelector('#js-vue-sidebar-assignees');
+ });
+
+ afterEach(() => {
+ SidebarService.singleton = null;
+ SidebarStore.singleton = null;
+ SidebarMediator.singleton = null;
+ });
+
+ it('calls the mediator when saves the assignees', () => {
+ component = new SidebarAssigneeComponent()
+ .$mount(this.sidebarAssigneesEl);
+ component.saveAssignees();
+
+ expect(SidebarMediator.prototype.saveAssignees).toHaveBeenCalled();
+ });
+
+ it('calls the mediator when "assignSelf" method is called', () => {
+ component = new SidebarAssigneeComponent()
+ .$mount(this.sidebarAssigneesEl);
+ component.assignSelf();
+
+ expect(SidebarMediator.prototype.assignYourself).toHaveBeenCalled();
+ expect(this.mediator.store.assignees.length).toEqual(1);
+ });
+});
diff --git a/spec/javascripts/sidebar/sidebar_bundle_spec.js b/spec/javascripts/sidebar/sidebar_bundle_spec.js
new file mode 100644
index 00000000000..7760b34e071
--- /dev/null
+++ b/spec/javascripts/sidebar/sidebar_bundle_spec.js
@@ -0,0 +1,42 @@
+import Vue from 'vue';
+import SidebarBundleDomContentLoaded from '~/sidebar/sidebar_bundle';
+import SidebarTimeTracking from '~/sidebar/components/time_tracking/sidebar_time_tracking';
+import SidebarMediator from '~/sidebar/sidebar_mediator';
+import SidebarService from '~/sidebar/services/sidebar_service';
+import SidebarStore from '~/sidebar/stores/sidebar_store';
+import Mock from './mock_data';
+
+describe('sidebar bundle', () => {
+ gl.sidebarOptions = Mock.mediator;
+
+ beforeEach(() => {
+ spyOn(SidebarTimeTracking.methods, 'listenForSlashCommands').and.callFake(() => { });
+ preloadFixtures('issues/open-issue.html.raw');
+ Vue.http.interceptors.push(Mock.sidebarMockInterceptor);
+ loadFixtures('issues/open-issue.html.raw');
+ spyOn(Vue.prototype, '$mount');
+ SidebarBundleDomContentLoaded();
+ this.mediator = new SidebarMediator();
+ });
+
+ afterEach(() => {
+ SidebarService.singleton = null;
+ SidebarStore.singleton = null;
+ SidebarMediator.singleton = null;
+ });
+
+ it('the mediator should be already defined with some data', () => {
+ SidebarBundleDomContentLoaded();
+
+ expect(this.mediator.store).toBeDefined();
+ expect(this.mediator.service).toBeDefined();
+ expect(this.mediator.store.currentUser).toEqual(Mock.mediator.currentUser);
+ expect(this.mediator.store.rootPath).toEqual(Mock.mediator.rootPath);
+ expect(this.mediator.store.endPoint).toEqual(Mock.mediator.endPoint);
+ expect(this.mediator.store.editable).toEqual(Mock.mediator.editable);
+ });
+
+ it('the sidebar time tracking and assignees components to have been mounted', () => {
+ expect(Vue.prototype.$mount).toHaveBeenCalledTimes(2);
+ });
+});
diff --git a/spec/javascripts/sidebar/sidebar_mediator_spec.js b/spec/javascripts/sidebar/sidebar_mediator_spec.js
new file mode 100644
index 00000000000..2b00fa17334
--- /dev/null
+++ b/spec/javascripts/sidebar/sidebar_mediator_spec.js
@@ -0,0 +1,40 @@
+import Vue from 'vue';
+import SidebarMediator from '~/sidebar/sidebar_mediator';
+import SidebarStore from '~/sidebar/stores/sidebar_store';
+import SidebarService from '~/sidebar/services/sidebar_service';
+import Mock from './mock_data';
+
+describe('Sidebar mediator', () => {
+ beforeEach(() => {
+ Vue.http.interceptors.push(Mock.sidebarMockInterceptor);
+ this.mediator = new SidebarMediator(Mock.mediator);
+ });
+
+ afterEach(() => {
+ SidebarService.singleton = null;
+ SidebarStore.singleton = null;
+ SidebarMediator.singleton = null;
+ });
+
+ it('assigns yourself ', () => {
+ this.mediator.assignYourself();
+
+ expect(this.mediator.store.currentUser).toEqual(Mock.mediator.currentUser);
+ expect(this.mediator.store.assignees[0]).toEqual(Mock.mediator.currentUser);
+ });
+
+ it('saves assignees', (done) => {
+ this.mediator.saveAssignees('issue[assignee_ids]')
+ .then((resp) => {
+ expect(resp.status).toEqual(200);
+ done();
+ })
+ .catch(() => {});
+ });
+
+ it('fetches the data', () => {
+ spyOn(this.mediator.service, 'get').and.callThrough();
+ this.mediator.fetch();
+ expect(this.mediator.service.get).toHaveBeenCalled();
+ });
+});
diff --git a/spec/javascripts/sidebar/sidebar_service_spec.js b/spec/javascripts/sidebar/sidebar_service_spec.js
new file mode 100644
index 00000000000..d41162096a6
--- /dev/null
+++ b/spec/javascripts/sidebar/sidebar_service_spec.js
@@ -0,0 +1,32 @@
+import Vue from 'vue';
+import SidebarService from '~/sidebar/services/sidebar_service';
+import Mock from './mock_data';
+
+describe('Sidebar service', () => {
+ beforeEach(() => {
+ Vue.http.interceptors.push(Mock.sidebarMockInterceptor);
+ this.service = new SidebarService('/gitlab-org/gitlab-shell/issues/5.json');
+ });
+
+ afterEach(() => {
+ SidebarService.singleton = null;
+ });
+
+ it('gets the data', (done) => {
+ this.service.get()
+ .then((resp) => {
+ expect(resp).toBeDefined();
+ done();
+ })
+ .catch(() => {});
+ });
+
+ it('updates the data', (done) => {
+ this.service.update('issue[assignee_ids]', [1])
+ .then((resp) => {
+ expect(resp).toBeDefined();
+ done();
+ })
+ .catch(() => {});
+ });
+});
diff --git a/spec/javascripts/sidebar/sidebar_store_spec.js b/spec/javascripts/sidebar/sidebar_store_spec.js
new file mode 100644
index 00000000000..29facf483b5
--- /dev/null
+++ b/spec/javascripts/sidebar/sidebar_store_spec.js
@@ -0,0 +1,80 @@
+import SidebarStore from '~/sidebar/stores/sidebar_store';
+import Mock from './mock_data';
+import UsersMockHelper from '../helpers/user_mock_data_helper';
+
+describe('Sidebar store', () => {
+ const assignee = {
+ id: 2,
+ name: 'gitlab user 2',
+ username: 'gitlab2',
+ avatar_url: 'http://www.gravatar.com/avatar/e64c7d89f26bd1972efa854d13d7dd61?s=80&d=identicon',
+ };
+
+ const anotherAssignee = {
+ id: 3,
+ name: 'gitlab user 3',
+ username: 'gitlab3',
+ avatar_url: 'http://www.gravatar.com/avatar/e64c7d89f26bd1972efa854d13d7dd61?s=80&d=identicon',
+ };
+
+ beforeEach(() => {
+ this.store = new SidebarStore({
+ currentUser: {
+ id: 1,
+ name: 'Administrator',
+ username: 'root',
+ avatar_url: 'http://www.gravatar.com/avatar/e64c7d89f26bd1972efa854d13d7dd61?s=80&d=identicon',
+ },
+ editable: true,
+ rootPath: '/',
+ endpoint: '/gitlab-org/gitlab-shell/issues/5.json',
+ });
+ });
+
+ afterEach(() => {
+ SidebarStore.singleton = null;
+ });
+
+ it('adds a new assignee', () => {
+ this.store.addAssignee(assignee);
+ expect(this.store.assignees.length).toEqual(1);
+ });
+
+ it('removes an assignee', () => {
+ this.store.removeAssignee(assignee);
+ expect(this.store.assignees.length).toEqual(0);
+ });
+
+ it('finds an existent assignee', () => {
+ let foundAssignee;
+
+ this.store.addAssignee(assignee);
+ foundAssignee = this.store.findAssignee(assignee);
+ expect(foundAssignee).toBeDefined();
+ expect(foundAssignee).toEqual(assignee);
+ foundAssignee = this.store.findAssignee(anotherAssignee);
+ expect(foundAssignee).toBeUndefined();
+ });
+
+ it('removes all assignees', () => {
+ this.store.removeAllAssignees();
+ expect(this.store.assignees.length).toEqual(0);
+ });
+
+ it('set assigned data', () => {
+ const users = {
+ assignees: UsersMockHelper.createNumberRandomUsers(3),
+ };
+
+ this.store.setAssigneeData(users);
+ expect(this.store.assignees.length).toEqual(3);
+ });
+
+ it('set time tracking data', () => {
+ this.store.setTimeTrackingData(Mock.time);
+ expect(this.store.timeEstimate).toEqual(Mock.time.time_estimate);
+ expect(this.store.totalTimeSpent).toEqual(Mock.time.total_time_spent);
+ expect(this.store.humanTimeEstimate).toEqual(Mock.time.human_time_estimate);
+ expect(this.store.humanTotalTimeSpent).toEqual(Mock.time.human_total_time_spent);
+ });
+});
diff --git a/spec/javascripts/signin_tabs_memoizer_spec.js b/spec/javascripts/signin_tabs_memoizer_spec.js
index d83d9a57b42..5b4f5933b34 100644
--- a/spec/javascripts/signin_tabs_memoizer_spec.js
+++ b/spec/javascripts/signin_tabs_memoizer_spec.js
@@ -1,3 +1,5 @@
+import AccessorUtilities from '~/lib/utils/accessor';
+
require('~/signin_tabs_memoizer');
((global) => {
@@ -19,6 +21,8 @@ require('~/signin_tabs_memoizer');
beforeEach(() => {
loadFixtures(fixtureTemplate);
+
+ spyOn(AccessorUtilities, 'isLocalStorageAccessSafe').and.returnValue(true);
});
it('does nothing if no tab was previously selected', () => {
@@ -49,5 +53,91 @@ require('~/signin_tabs_memoizer');
expect(memo.readData()).toEqual('#standard');
});
+
+ describe('class constructor', () => {
+ beforeEach(() => {
+ memo = createMemoizer();
+ });
+
+ it('should set .isLocalStorageAvailable', () => {
+ expect(AccessorUtilities.isLocalStorageAccessSafe).toHaveBeenCalled();
+ expect(memo.isLocalStorageAvailable).toBe(true);
+ });
+ });
+
+ describe('saveData', () => {
+ beforeEach(() => {
+ memo = {
+ currentTabKey,
+ };
+
+ spyOn(localStorage, 'setItem');
+ });
+
+ describe('if .isLocalStorageAvailable is `false`', () => {
+ beforeEach(function () {
+ memo.isLocalStorageAvailable = false;
+
+ global.ActiveTabMemoizer.prototype.saveData.call(memo);
+ });
+
+ it('should not call .setItem', () => {
+ expect(localStorage.setItem).not.toHaveBeenCalled();
+ });
+ });
+
+ describe('if .isLocalStorageAvailable is `true`', () => {
+ const value = 'value';
+
+ beforeEach(function () {
+ memo.isLocalStorageAvailable = true;
+
+ global.ActiveTabMemoizer.prototype.saveData.call(memo, value);
+ });
+
+ it('should call .setItem', () => {
+ expect(localStorage.setItem).toHaveBeenCalledWith(currentTabKey, value);
+ });
+ });
+ });
+
+ describe('readData', () => {
+ const itemValue = 'itemValue';
+ let readData;
+
+ beforeEach(() => {
+ memo = {
+ currentTabKey,
+ };
+
+ spyOn(localStorage, 'getItem').and.returnValue(itemValue);
+ });
+
+ describe('if .isLocalStorageAvailable is `false`', () => {
+ beforeEach(function () {
+ memo.isLocalStorageAvailable = false;
+
+ readData = global.ActiveTabMemoizer.prototype.readData.call(memo);
+ });
+
+ it('should not call .getItem and should return `null`', () => {
+ expect(localStorage.getItem).not.toHaveBeenCalled();
+ expect(readData).toBe(null);
+ });
+ });
+
+ describe('if .isLocalStorageAvailable is `true`', () => {
+ beforeEach(function () {
+ memo.isLocalStorageAvailable = true;
+
+ readData = global.ActiveTabMemoizer.prototype.readData.call(memo);
+ });
+
+ it('should call .getItem and return the localStorage value', () => {
+ expect(window.localStorage.getItem).toHaveBeenCalledWith(currentTabKey);
+ expect(readData).toBe(itemValue);
+ });
+ });
+ });
});
})(window);
diff --git a/spec/javascripts/subbable_resource_spec.js b/spec/javascripts/subbable_resource_spec.js
deleted file mode 100644
index 454386697f5..00000000000
--- a/spec/javascripts/subbable_resource_spec.js
+++ /dev/null
@@ -1,63 +0,0 @@
-/* eslint-disable max-len, arrow-parens, comma-dangle */
-
-require('~/subbable_resource');
-
-/*
-* Test that each rest verb calls the publish and subscribe function and passes the correct value back
-*
-*
-* */
-((global) => {
- describe('Subbable Resource', function () {
- describe('PubSub', function () {
- beforeEach(function () {
- this.MockResource = new global.SubbableResource('https://example.com');
- });
- it('should successfully add a single subscriber', function () {
- const callback = () => {};
- this.MockResource.subscribe(callback);
-
- expect(this.MockResource.subscribers.length).toBe(1);
- expect(this.MockResource.subscribers[0]).toBe(callback);
- });
-
- it('should successfully add multiple subscribers', function () {
- const callbackOne = () => {};
- const callbackTwo = () => {};
- const callbackThree = () => {};
-
- this.MockResource.subscribe(callbackOne);
- this.MockResource.subscribe(callbackTwo);
- this.MockResource.subscribe(callbackThree);
-
- expect(this.MockResource.subscribers.length).toBe(3);
- });
-
- it('should successfully publish an update to a single subscriber', function () {
- const state = { myprop: 1 };
-
- const callbacks = {
- one: (data) => expect(data.myprop).toBe(2),
- two: (data) => expect(data.myprop).toBe(2),
- three: (data) => expect(data.myprop).toBe(2)
- };
-
- const spyOne = spyOn(callbacks, 'one');
- const spyTwo = spyOn(callbacks, 'two');
- const spyThree = spyOn(callbacks, 'three');
-
- this.MockResource.subscribe(callbacks.one);
- this.MockResource.subscribe(callbacks.two);
- this.MockResource.subscribe(callbacks.three);
-
- state.myprop += 1;
-
- this.MockResource.publish(state);
-
- expect(spyOne).toHaveBeenCalled();
- expect(spyTwo).toHaveBeenCalled();
- expect(spyThree).toHaveBeenCalled();
- });
- });
- });
-})(window.gl || (window.gl = {}));
diff --git a/spec/lib/banzai/filter/redactor_filter_spec.rb b/spec/lib/banzai/filter/redactor_filter_spec.rb
index 8a6fe1ad6a3..7c4a0f32c7b 100644
--- a/spec/lib/banzai/filter/redactor_filter_spec.rb
+++ b/spec/lib/banzai/filter/redactor_filter_spec.rb
@@ -113,7 +113,7 @@ describe Banzai::Filter::RedactorFilter, lib: true do
it 'allows references for assignee' do
assignee = create(:user)
project = create(:empty_project, :public)
- issue = create(:issue, :confidential, project: project, assignee: assignee)
+ issue = create(:issue, :confidential, project: project, assignees: [assignee])
link = reference_link(project: project.id, issue: issue.id, reference_type: 'issue')
doc = filter(link, current_user: assignee)
diff --git a/spec/lib/constraints/group_url_constrainer_spec.rb b/spec/lib/constraints/group_url_constrainer_spec.rb
index f95adf3a84b..db680489a8d 100644
--- a/spec/lib/constraints/group_url_constrainer_spec.rb
+++ b/spec/lib/constraints/group_url_constrainer_spec.rb
@@ -29,9 +29,37 @@ describe GroupUrlConstrainer, lib: true do
it { expect(subject.matches?(request)).to be_falsey }
end
+
+ context 'when the request matches a redirect route' do
+ context 'for a root group' do
+ let!(:redirect_route) { group.redirect_routes.create!(path: 'gitlabb') }
+
+ context 'and is a GET request' do
+ let(:request) { build_request(redirect_route.path) }
+
+ it { expect(subject.matches?(request)).to be_truthy }
+ end
+
+ context 'and is NOT a GET request' do
+ let(:request) { build_request(redirect_route.path, 'POST') }
+
+ it { expect(subject.matches?(request)).to be_falsey }
+ end
+ end
+
+ context 'for a nested group' do
+ let!(:nested_group) { create(:group, path: 'nested', parent: group) }
+ let!(:redirect_route) { nested_group.redirect_routes.create!(path: 'gitlabb/nested') }
+ let(:request) { build_request(redirect_route.path) }
+
+ it { expect(subject.matches?(request)).to be_truthy }
+ end
+ end
end
- def build_request(path)
- double(:request, params: { id: path })
+ def build_request(path, method = 'GET')
+ double(:request,
+ 'get?': (method == 'GET'),
+ params: { id: path })
end
end
diff --git a/spec/lib/constraints/project_url_constrainer_spec.rb b/spec/lib/constraints/project_url_constrainer_spec.rb
index 4f25ad88960..b6884e37aa3 100644
--- a/spec/lib/constraints/project_url_constrainer_spec.rb
+++ b/spec/lib/constraints/project_url_constrainer_spec.rb
@@ -24,9 +24,26 @@ describe ProjectUrlConstrainer, lib: true do
it { expect(subject.matches?(request)).to be_falsey }
end
end
+
+ context 'when the request matches a redirect route' do
+ let(:old_project_path) { 'old_project_path' }
+ let!(:redirect_route) { project.redirect_routes.create!(path: "#{namespace.full_path}/#{old_project_path}") }
+
+ context 'and is a GET request' do
+ let(:request) { build_request(namespace.full_path, old_project_path) }
+ it { expect(subject.matches?(request)).to be_truthy }
+ end
+
+ context 'and is NOT a GET request' do
+ let(:request) { build_request(namespace.full_path, old_project_path, 'POST') }
+ it { expect(subject.matches?(request)).to be_falsey }
+ end
+ end
end
- def build_request(namespace, project)
- double(:request, params: { namespace_id: namespace, id: project })
+ def build_request(namespace, project, method = 'GET')
+ double(:request,
+ 'get?': (method == 'GET'),
+ params: { namespace_id: namespace, id: project })
end
end
diff --git a/spec/lib/constraints/user_url_constrainer_spec.rb b/spec/lib/constraints/user_url_constrainer_spec.rb
index 207b6fe6c9e..ed69b830979 100644
--- a/spec/lib/constraints/user_url_constrainer_spec.rb
+++ b/spec/lib/constraints/user_url_constrainer_spec.rb
@@ -15,9 +15,26 @@ describe UserUrlConstrainer, lib: true do
it { expect(subject.matches?(request)).to be_falsey }
end
+
+ context 'when the request matches a redirect route' do
+ let(:old_project_path) { 'old_project_path' }
+ let!(:redirect_route) { user.namespace.redirect_routes.create!(path: 'foo') }
+
+ context 'and is a GET request' do
+ let(:request) { build_request(redirect_route.path) }
+ it { expect(subject.matches?(request)).to be_truthy }
+ end
+
+ context 'and is NOT a GET request' do
+ let(:request) { build_request(redirect_route.path, 'POST') }
+ it { expect(subject.matches?(request)).to be_falsey }
+ end
+ end
end
- def build_request(username)
- double(:request, params: { username: username })
+ def build_request(username, method = 'GET')
+ double(:request,
+ 'get?': (method == 'GET'),
+ params: { username: username })
end
end
diff --git a/spec/lib/gitlab/chat_commands/command_spec.rb b/spec/lib/gitlab/chat_commands/command_spec.rb
index b6e924d67be..eb4f06b371c 100644
--- a/spec/lib/gitlab/chat_commands/command_spec.rb
+++ b/spec/lib/gitlab/chat_commands/command_spec.rb
@@ -40,11 +40,15 @@ describe Gitlab::ChatCommands::Command, service: true do
context 'when trying to do deployment' do
let(:params) { { text: 'deploy staging to production' } }
- let!(:build) { create(:ci_build, project: project) }
+ let!(:build) { create(:ci_build, pipeline: pipeline) }
+ let!(:pipeline) { create(:ci_pipeline, project: project) }
let!(:staging) { create(:environment, name: 'staging', project: project) }
let!(:deployment) { create(:deployment, environment: staging, deployable: build) }
+
let!(:manual) do
- create(:ci_build, :manual, project: project, pipeline: build.pipeline, name: 'first', environment: 'production')
+ create(:ci_build, :manual, pipeline: pipeline,
+ name: 'first',
+ environment: 'production')
end
context 'and user can not create deployment' do
@@ -56,7 +60,7 @@ describe Gitlab::ChatCommands::Command, service: true do
context 'and user does have deployment permission' do
before do
- project.team << [user, :developer]
+ build.project.add_master(user)
end
it 'returns action' do
@@ -66,7 +70,9 @@ describe Gitlab::ChatCommands::Command, service: true do
context 'when duplicate action exists' do
let!(:manual2) do
- create(:ci_build, :manual, project: project, pipeline: build.pipeline, name: 'second', environment: 'production')
+ create(:ci_build, :manual, pipeline: pipeline,
+ name: 'second',
+ environment: 'production')
end
it 'returns error' do
diff --git a/spec/lib/gitlab/chat_commands/deploy_spec.rb b/spec/lib/gitlab/chat_commands/deploy_spec.rb
index b3358a32161..b33389d959e 100644
--- a/spec/lib/gitlab/chat_commands/deploy_spec.rb
+++ b/spec/lib/gitlab/chat_commands/deploy_spec.rb
@@ -7,7 +7,7 @@ describe Gitlab::ChatCommands::Deploy, service: true do
let(:regex_match) { described_class.match('deploy staging to production') }
before do
- project.team << [user, :master]
+ project.add_master(user)
end
subject do
@@ -23,7 +23,8 @@ describe Gitlab::ChatCommands::Deploy, service: true do
context 'with environment' do
let!(:staging) { create(:environment, name: 'staging', project: project) }
- let!(:build) { create(:ci_build, project: project) }
+ let!(:pipeline) { create(:ci_pipeline, project: project) }
+ let!(:build) { create(:ci_build, pipeline: pipeline) }
let!(:deployment) { create(:deployment, environment: staging, deployable: build) }
context 'without actions' do
@@ -35,7 +36,9 @@ describe Gitlab::ChatCommands::Deploy, service: true do
context 'with action' do
let!(:manual1) do
- create(:ci_build, :manual, project: project, pipeline: build.pipeline, name: 'first', environment: 'production')
+ create(:ci_build, :manual, pipeline: pipeline,
+ name: 'first',
+ environment: 'production')
end
it 'returns success result' do
@@ -45,7 +48,9 @@ describe Gitlab::ChatCommands::Deploy, service: true do
context 'when duplicate action exists' do
let!(:manual2) do
- create(:ci_build, :manual, project: project, pipeline: build.pipeline, name: 'second', environment: 'production')
+ create(:ci_build, :manual, pipeline: pipeline,
+ name: 'second',
+ environment: 'production')
end
it 'returns error' do
@@ -57,8 +62,7 @@ describe Gitlab::ChatCommands::Deploy, service: true do
context 'when teardown action exists' do
let!(:teardown) do
create(:ci_build, :manual, :teardown_environment,
- project: project, pipeline: build.pipeline,
- name: 'teardown', environment: 'production')
+ pipeline: pipeline, name: 'teardown', environment: 'production')
end
it 'returns the success message' do
diff --git a/spec/lib/gitlab/ci/status/build/action_spec.rb b/spec/lib/gitlab/ci/status/build/action_spec.rb
new file mode 100644
index 00000000000..8c25f72804b
--- /dev/null
+++ b/spec/lib/gitlab/ci/status/build/action_spec.rb
@@ -0,0 +1,56 @@
+require 'spec_helper'
+
+describe Gitlab::Ci::Status::Build::Action do
+ let(:status) { double('core status') }
+ let(:user) { double('user') }
+
+ subject do
+ described_class.new(status)
+ end
+
+ describe '#label' do
+ before do
+ allow(status).to receive(:label).and_return('label')
+ end
+
+ context 'when status has action' do
+ before do
+ allow(status).to receive(:has_action?).and_return(true)
+ end
+
+ it 'does not append text' do
+ expect(subject.label).to eq 'label'
+ end
+ end
+
+ context 'when status does not have action' do
+ before do
+ allow(status).to receive(:has_action?).and_return(false)
+ end
+
+ it 'appends text about action not allowed' do
+ expect(subject.label).to eq 'label (not allowed)'
+ end
+ end
+ end
+
+ describe '.matches?' do
+ subject { described_class.matches?(build, user) }
+
+ context 'when build is an action' do
+ let(:build) { create(:ci_build, :manual) }
+
+ it 'is a correct match' do
+ expect(subject).to be true
+ end
+ end
+
+ context 'when build is not manual' do
+ let(:build) { create(:ci_build) }
+
+ it 'does not match' do
+ expect(subject).to be false
+ end
+ end
+ end
+end
diff --git a/spec/lib/gitlab/ci/status/build/factory_spec.rb b/spec/lib/gitlab/ci/status/build/factory_spec.rb
index e648a3ac3a2..185bb9098da 100644
--- a/spec/lib/gitlab/ci/status/build/factory_spec.rb
+++ b/spec/lib/gitlab/ci/status/build/factory_spec.rb
@@ -204,11 +204,12 @@ describe Gitlab::Ci::Status::Build::Factory do
it 'matches correct extended statuses' do
expect(factory.extended_statuses)
- .to eq [Gitlab::Ci::Status::Build::Play]
+ .to eq [Gitlab::Ci::Status::Build::Play,
+ Gitlab::Ci::Status::Build::Action]
end
- it 'fabricates a play detailed status' do
- expect(status).to be_a Gitlab::Ci::Status::Build::Play
+ it 'fabricates action detailed status' do
+ expect(status).to be_a Gitlab::Ci::Status::Build::Action
end
it 'fabricates status with correct details' do
@@ -216,11 +217,26 @@ describe Gitlab::Ci::Status::Build::Factory do
expect(status.group).to eq 'manual'
expect(status.icon).to eq 'icon_status_manual'
expect(status.favicon).to eq 'favicon_status_manual'
- expect(status.label).to eq 'manual play action'
+ expect(status.label).to include 'manual play action'
expect(status).to have_details
- expect(status).to have_action
expect(status.action_path).to include 'play'
end
+
+ context 'when user has ability to play action' do
+ before do
+ build.project.add_master(user)
+ end
+
+ it 'fabricates status that has action' do
+ expect(status).to have_action
+ end
+ end
+
+ context 'when user does not have ability to play action' do
+ it 'fabricates status that has no action' do
+ expect(status).not_to have_action
+ end
+ end
end
context 'when build is an environment stop action' do
@@ -232,21 +248,24 @@ describe Gitlab::Ci::Status::Build::Factory do
it 'matches correct extended statuses' do
expect(factory.extended_statuses)
- .to eq [Gitlab::Ci::Status::Build::Stop]
+ .to eq [Gitlab::Ci::Status::Build::Stop,
+ Gitlab::Ci::Status::Build::Action]
end
- it 'fabricates a stop detailed status' do
- expect(status).to be_a Gitlab::Ci::Status::Build::Stop
+ it 'fabricates action detailed status' do
+ expect(status).to be_a Gitlab::Ci::Status::Build::Action
end
- it 'fabricates status with correct details' do
- expect(status.text).to eq 'manual'
- expect(status.group).to eq 'manual'
- expect(status.icon).to eq 'icon_status_manual'
- expect(status.favicon).to eq 'favicon_status_manual'
- expect(status.label).to eq 'manual stop action'
- expect(status).to have_details
- expect(status).to have_action
+ context 'when user is not allowed to execute manual action' do
+ it 'fabricates status with correct details' do
+ expect(status.text).to eq 'manual'
+ expect(status.group).to eq 'manual'
+ expect(status.icon).to eq 'icon_status_manual'
+ expect(status.favicon).to eq 'favicon_status_manual'
+ expect(status.label).to eq 'manual stop action (not allowed)'
+ expect(status).to have_details
+ expect(status).not_to have_action
+ end
end
end
end
diff --git a/spec/lib/gitlab/ci/status/build/play_spec.rb b/spec/lib/gitlab/ci/status/build/play_spec.rb
index 6c97a4fe5ca..f5d0f977768 100644
--- a/spec/lib/gitlab/ci/status/build/play_spec.rb
+++ b/spec/lib/gitlab/ci/status/build/play_spec.rb
@@ -1,43 +1,48 @@
require 'spec_helper'
describe Gitlab::Ci::Status::Build::Play do
- let(:status) { double('core') }
- let(:user) { double('user') }
+ let(:user) { create(:user) }
+ let(:build) { create(:ci_build, :manual) }
+ let(:status) { Gitlab::Ci::Status::Core.new(build, user) }
subject { described_class.new(status) }
describe '#label' do
- it { expect(subject.label).to eq 'manual play action' }
+ it 'has a label that says it is a manual action' do
+ expect(subject.label).to eq 'manual play action'
+ end
end
- describe 'action details' do
- let(:user) { create(:user) }
- let(:build) { create(:ci_build) }
- let(:status) { Gitlab::Ci::Status::Core.new(build, user) }
-
- describe '#has_action?' do
- context 'when user is allowed to update build' do
- before { build.project.team << [user, :developer] }
+ describe '#has_action?' do
+ context 'when user is allowed to update build' do
+ context 'when user can push to branch' do
+ before { build.project.add_master(user) }
it { is_expected.to have_action }
end
- context 'when user is not allowed to update build' do
+ context 'when user can not push to the branch' do
+ before { build.project.add_developer(user) }
+
it { is_expected.not_to have_action }
end
end
- describe '#action_path' do
- it { expect(subject.action_path).to include "#{build.id}/play" }
+ context 'when user is not allowed to update build' do
+ it { is_expected.not_to have_action }
end
+ end
- describe '#action_icon' do
- it { expect(subject.action_icon).to eq 'icon_action_play' }
- end
+ describe '#action_path' do
+ it { expect(subject.action_path).to include "#{build.id}/play" }
+ end
- describe '#action_title' do
- it { expect(subject.action_title).to eq 'Play' }
- end
+ describe '#action_icon' do
+ it { expect(subject.action_icon).to eq 'icon_action_play' }
+ end
+
+ describe '#action_title' do
+ it { expect(subject.action_title).to eq 'Play' }
end
describe '.matches?' do
diff --git a/spec/lib/gitlab/ci/status/extended_spec.rb b/spec/lib/gitlab/ci/status/extended_spec.rb
index c2d74ca5cde..6eacb07078b 100644
--- a/spec/lib/gitlab/ci/status/extended_spec.rb
+++ b/spec/lib/gitlab/ci/status/extended_spec.rb
@@ -1,12 +1,8 @@
require 'spec_helper'
describe Gitlab::Ci::Status::Extended do
- subject do
- Class.new.include(described_class)
- end
-
it 'requires subclass to implement matcher' do
- expect { subject.matches?(double, double) }
+ expect { described_class.matches?(double, double) }
.to raise_error(NotImplementedError)
end
end
diff --git a/spec/lib/gitlab/ci/status/group/common_spec.rb b/spec/lib/gitlab/ci/status/group/common_spec.rb
new file mode 100644
index 00000000000..c0ca05881f5
--- /dev/null
+++ b/spec/lib/gitlab/ci/status/group/common_spec.rb
@@ -0,0 +1,20 @@
+require 'spec_helper'
+
+describe Gitlab::Ci::Status::Group::Common do
+ subject do
+ Gitlab::Ci::Status::Core.new(double, double)
+ .extend(described_class)
+ end
+
+ it 'does not have action' do
+ expect(subject).not_to have_action
+ end
+
+ it 'has details' do
+ expect(subject).not_to have_details
+ end
+
+ it 'has no details_path' do
+ expect(subject.details_path).to be_falsy
+ end
+end
diff --git a/spec/lib/gitlab/ci/status/group/factory_spec.rb b/spec/lib/gitlab/ci/status/group/factory_spec.rb
new file mode 100644
index 00000000000..0cd83123938
--- /dev/null
+++ b/spec/lib/gitlab/ci/status/group/factory_spec.rb
@@ -0,0 +1,13 @@
+require 'spec_helper'
+
+describe Gitlab::Ci::Status::Group::Factory do
+ it 'inherits from the core factory' do
+ expect(described_class)
+ .to be < Gitlab::Ci::Status::Factory
+ end
+
+ it 'exposes group helpers' do
+ expect(described_class.common_helpers)
+ .to eq Gitlab::Ci::Status::Group::Common
+ end
+end
diff --git a/spec/lib/gitlab/github_import/issue_formatter_spec.rb b/spec/lib/gitlab/github_import/issue_formatter_spec.rb
index f34d09f2c1d..a4089592cf2 100644
--- a/spec/lib/gitlab/github_import/issue_formatter_spec.rb
+++ b/spec/lib/gitlab/github_import/issue_formatter_spec.rb
@@ -43,7 +43,7 @@ describe Gitlab::GithubImport::IssueFormatter, lib: true do
description: "*Created by: octocat*\n\nI'm having a problem with this.",
state: 'opened',
author_id: project.creator_id,
- assignee_id: nil,
+ assignee_ids: [],
created_at: created_at,
updated_at: updated_at
}
@@ -64,7 +64,7 @@ describe Gitlab::GithubImport::IssueFormatter, lib: true do
description: "*Created by: octocat*\n\nI'm having a problem with this.",
state: 'closed',
author_id: project.creator_id,
- assignee_id: nil,
+ assignee_ids: [],
created_at: created_at,
updated_at: updated_at
}
@@ -77,19 +77,19 @@ describe Gitlab::GithubImport::IssueFormatter, lib: true do
let(:raw_data) { double(base_data.merge(assignee: octocat)) }
it 'returns nil as assignee_id when is not a GitLab user' do
- expect(issue.attributes.fetch(:assignee_id)).to be_nil
+ expect(issue.attributes.fetch(:assignee_ids)).to be_empty
end
it 'returns GitLab user id associated with GitHub id as assignee_id' do
gl_user = create(:omniauth_user, extern_uid: octocat.id, provider: 'github')
- expect(issue.attributes.fetch(:assignee_id)).to eq gl_user.id
+ expect(issue.attributes.fetch(:assignee_ids)).to eq [gl_user.id]
end
it 'returns GitLab user id associated with GitHub email as assignee_id' do
gl_user = create(:user, email: octocat.email)
- expect(issue.attributes.fetch(:assignee_id)).to eq gl_user.id
+ expect(issue.attributes.fetch(:assignee_ids)).to eq [gl_user.id]
end
end
diff --git a/spec/lib/gitlab/gl_repository_spec.rb b/spec/lib/gitlab/gl_repository_spec.rb
new file mode 100644
index 00000000000..ac3558ab386
--- /dev/null
+++ b/spec/lib/gitlab/gl_repository_spec.rb
@@ -0,0 +1,19 @@
+require 'spec_helper'
+
+describe ::Gitlab::GlRepository do
+ describe '.parse' do
+ set(:project) { create(:project) }
+
+ it 'parses a project gl_repository' do
+ expect(described_class.parse("project-#{project.id}")).to eq([project, false])
+ end
+
+ it 'parses a wiki gl_repository' do
+ expect(described_class.parse("wiki-#{project.id}")).to eq([project, true])
+ end
+
+ it 'throws an argument error on an invalid gl_repository' do
+ expect { described_class.parse("badformat-#{project.id}") }.to raise_error(ArgumentError)
+ end
+ end
+end
diff --git a/spec/lib/gitlab/google_code_import/importer_spec.rb b/spec/lib/gitlab/google_code_import/importer_spec.rb
index ccaa88a5c79..622a0f513f4 100644
--- a/spec/lib/gitlab/google_code_import/importer_spec.rb
+++ b/spec/lib/gitlab/google_code_import/importer_spec.rb
@@ -49,7 +49,7 @@ describe Gitlab::GoogleCodeImport::Importer, lib: true do
expect(issue).not_to be_nil
expect(issue.iid).to eq(169)
expect(issue.author).to eq(project.creator)
- expect(issue.assignee).to eq(mapped_user)
+ expect(issue.assignees).to eq([mapped_user])
expect(issue.state).to eq("closed")
expect(issue.label_names).to include("Priority: Medium")
expect(issue.label_names).to include("Status: Fixed")
diff --git a/spec/lib/gitlab/import_export/all_models.yml b/spec/lib/gitlab/import_export/all_models.yml
index 0abf89d060c..baa81870e81 100644
--- a/spec/lib/gitlab/import_export/all_models.yml
+++ b/spec/lib/gitlab/import_export/all_models.yml
@@ -3,12 +3,13 @@ issues:
- subscriptions
- award_emoji
- author
-- assignee
+- assignees
- updated_by
- milestone
- notes
- label_links
- labels
+- last_edited_by
- todos
- user_agent_detail
- moved_to
@@ -16,6 +17,7 @@ issues:
- merge_requests_closing_issues
- metrics
- timelogs
+- issue_assignees
events:
- author
- project
@@ -26,6 +28,7 @@ notes:
- noteable
- author
- updated_by
+- last_edited_by
- resolved_by
- todos
- events
@@ -71,6 +74,7 @@ merge_requests:
- notes
- label_links
- labels
+- last_edited_by
- todos
- target_project
- source_project
@@ -225,6 +229,7 @@ project:
- authorized_users
- project_authorizations
- route
+- redirect_routes
- statistics
- container_repositories
- uploads
diff --git a/spec/lib/gitlab/import_export/project_tree_saver_spec.rb b/spec/lib/gitlab/import_export/project_tree_saver_spec.rb
index 1035428b2e7..5aeb29b7fec 100644
--- a/spec/lib/gitlab/import_export/project_tree_saver_spec.rb
+++ b/spec/lib/gitlab/import_export/project_tree_saver_spec.rb
@@ -203,7 +203,7 @@ describe Gitlab::ImportExport::ProjectTreeSaver, services: true do
end
def setup_project
- issue = create(:issue, assignee: user)
+ issue = create(:issue, assignees: [user])
snippet = create(:project_snippet)
release = create(:release)
group = create(:group)
diff --git a/spec/lib/gitlab/import_export/safe_model_attributes.yml b/spec/lib/gitlab/import_export/safe_model_attributes.yml
index 59c8b48a2be..a66086f8b47 100644
--- a/spec/lib/gitlab/import_export/safe_model_attributes.yml
+++ b/spec/lib/gitlab/import_export/safe_model_attributes.yml
@@ -23,6 +23,8 @@ Issue:
- weight
- time_estimate
- relative_position
+- last_edited_at
+- last_edited_by_id
Event:
- id
- target_type
@@ -154,6 +156,8 @@ MergeRequest:
- approvals_before_merge
- rebase_commit_sha
- time_estimate
+- last_edited_at
+- last_edited_by_id
MergeRequestDiff:
- id
- state
diff --git a/spec/lib/gitlab/project_search_results_spec.rb b/spec/lib/gitlab/project_search_results_spec.rb
index e0ebea63eb4..a7c8e7f1f57 100644
--- a/spec/lib/gitlab/project_search_results_spec.rb
+++ b/spec/lib/gitlab/project_search_results_spec.rb
@@ -89,7 +89,7 @@ describe Gitlab::ProjectSearchResults, lib: true do
let(:project) { create(:empty_project, :internal) }
let!(:issue) { create(:issue, project: project, title: 'Issue 1') }
let!(:security_issue_1) { create(:issue, :confidential, project: project, title: 'Security issue 1', author: author) }
- let!(:security_issue_2) { create(:issue, :confidential, title: 'Security issue 2', project: project, assignee: assignee) }
+ let!(:security_issue_2) { create(:issue, :confidential, title: 'Security issue 2', project: project, assignees: [assignee]) }
it 'does not list project confidential issues for non project members' do
results = described_class.new(non_member, project, query)
diff --git a/spec/lib/gitlab/repo_path_spec.rb b/spec/lib/gitlab/repo_path_spec.rb
index 0fb5d7646f2..f94c9c2e315 100644
--- a/spec/lib/gitlab/repo_path_spec.rb
+++ b/spec/lib/gitlab/repo_path_spec.rb
@@ -1,6 +1,30 @@
require 'spec_helper'
describe ::Gitlab::RepoPath do
+ describe '.parse' do
+ set(:project) { create(:project) }
+
+ it 'parses a full repository path' do
+ expect(described_class.parse(project.repository.path)).to eq([project, false])
+ end
+
+ it 'parses a full wiki path' do
+ expect(described_class.parse(project.wiki.repository.path)).to eq([project, true])
+ end
+
+ it 'parses a relative repository path' do
+ expect(described_class.parse(project.full_path + '.git')).to eq([project, false])
+ end
+
+ it 'parses a relative wiki path' do
+ expect(described_class.parse(project.full_path + '.wiki.git')).to eq([project, true])
+ end
+
+ it 'parses a relative path starting with /' do
+ expect(described_class.parse('/' + project.full_path + '.git')).to eq([project, false])
+ end
+ end
+
describe '.strip_storage_path' do
before do
allow(Gitlab.config.repositories).to receive(:storages).and_return({
diff --git a/spec/lib/gitlab/search_results_spec.rb b/spec/lib/gitlab/search_results_spec.rb
index 847fb977400..31c3cd4d53c 100644
--- a/spec/lib/gitlab/search_results_spec.rb
+++ b/spec/lib/gitlab/search_results_spec.rb
@@ -72,9 +72,9 @@ describe Gitlab::SearchResults do
let(:admin) { create(:admin) }
let!(:issue) { create(:issue, project: project_1, title: 'Issue 1') }
let!(:security_issue_1) { create(:issue, :confidential, project: project_1, title: 'Security issue 1', author: author) }
- let!(:security_issue_2) { create(:issue, :confidential, title: 'Security issue 2', project: project_1, assignee: assignee) }
+ let!(:security_issue_2) { create(:issue, :confidential, title: 'Security issue 2', project: project_1, assignees: [assignee]) }
let!(:security_issue_3) { create(:issue, :confidential, project: project_2, title: 'Security issue 3', author: author) }
- let!(:security_issue_4) { create(:issue, :confidential, project: project_3, title: 'Security issue 4', assignee: assignee) }
+ let!(:security_issue_4) { create(:issue, :confidential, project: project_3, title: 'Security issue 4', assignees: [assignee]) }
let!(:security_issue_5) { create(:issue, :confidential, project: project_4, title: 'Security issue 5') }
it 'does not list confidential issues for non project members' do
diff --git a/spec/lib/gitlab/workhorse_spec.rb b/spec/lib/gitlab/workhorse_spec.rb
index b703e9808a8..beb1791a429 100644
--- a/spec/lib/gitlab/workhorse_spec.rb
+++ b/spec/lib/gitlab/workhorse_spec.rb
@@ -181,10 +181,23 @@ describe Gitlab::Workhorse, lib: true do
let(:user) { create(:user) }
let(:repo_path) { repository.path_to_repo }
let(:action) { 'info_refs' }
+ let(:params) do
+ { GL_ID: "user-#{user.id}", GL_REPOSITORY: "project-#{project.id}", RepoPath: repo_path }
+ end
+
+ subject { described_class.git_http_ok(repository, false, user, action) }
+
+ it { expect(subject).to include(params) }
- subject { described_class.git_http_ok(repository, user, action) }
+ context 'when is_wiki' do
+ let(:params) do
+ { GL_ID: "user-#{user.id}", GL_REPOSITORY: "wiki-#{project.id}", RepoPath: repo_path }
+ end
+
+ subject { described_class.git_http_ok(repository, true, user, action) }
- it { expect(subject).to include({ GL_ID: "user-#{user.id}", RepoPath: repo_path }) }
+ it { expect(subject).to include(params) }
+ end
context 'when Gitaly is enabled' do
let(:gitaly_params) do
diff --git a/spec/mailers/notify_spec.rb b/spec/mailers/notify_spec.rb
index 9f12e40d808..1e6260270fe 100644
--- a/spec/mailers/notify_spec.rb
+++ b/spec/mailers/notify_spec.rb
@@ -36,11 +36,11 @@ describe Notify do
end
context 'for issues' do
- let(:issue) { create(:issue, author: current_user, assignee: assignee, project: project) }
- let(:issue_with_description) { create(:issue, author: current_user, assignee: assignee, project: project, description: 'My awesome description') }
+ let(:issue) { create(:issue, author: current_user, assignees: [assignee], project: project) }
+ let(:issue_with_description) { create(:issue, author: current_user, assignees: [assignee], project: project, description: 'My awesome description') }
describe 'that are new' do
- subject { described_class.new_issue_email(issue.assignee_id, issue.id) }
+ subject { described_class.new_issue_email(issue.assignees.first.id, issue.id) }
it_behaves_like 'an assignee email'
it_behaves_like 'an email starting a new thread with reply-by-email enabled' do
@@ -69,7 +69,7 @@ describe Notify do
end
describe 'that are new with a description' do
- subject { described_class.new_issue_email(issue_with_description.assignee_id, issue_with_description.id) }
+ subject { described_class.new_issue_email(issue_with_description.assignees.first.id, issue_with_description.id) }
it_behaves_like 'it should show Gmail Actions View Issue link'
@@ -79,7 +79,7 @@ describe Notify do
end
describe 'that have been reassigned' do
- subject { described_class.reassigned_issue_email(recipient.id, issue.id, previous_assignee.id, current_user.id) }
+ subject { described_class.reassigned_issue_email(recipient.id, issue.id, [previous_assignee.id], current_user.id) }
it_behaves_like 'a multiple recipients email'
it_behaves_like 'an answer to an existing thread with reply-by-email enabled' do
diff --git a/spec/models/ci/build_spec.rb b/spec/models/ci/build_spec.rb
index 6e8845cdcf4..5231ce28c9d 100644
--- a/spec/models/ci/build_spec.rb
+++ b/spec/models/ci/build_spec.rb
@@ -897,22 +897,26 @@ describe Ci::Build, :models do
end
describe '#persisted_environment' do
- before do
- @environment = create(:environment, project: project, name: "foo-#{project.default_branch}")
+ let!(:environment) do
+ create(:environment, project: project, name: "foo-#{project.default_branch}")
end
subject { build.persisted_environment }
- context 'referenced literally' do
- let(:build) { create(:ci_build, pipeline: pipeline, environment: "foo-#{project.default_branch}") }
+ context 'when referenced literally' do
+ let(:build) do
+ create(:ci_build, pipeline: pipeline, environment: "foo-#{project.default_branch}")
+ end
- it { is_expected.to eq(@environment) }
+ it { is_expected.to eq(environment) }
end
- context 'referenced with a variable' do
- let(:build) { create(:ci_build, pipeline: pipeline, environment: "foo-$CI_COMMIT_REF_NAME") }
+ context 'when referenced with a variable' do
+ let(:build) do
+ create(:ci_build, pipeline: pipeline, environment: "foo-$CI_COMMIT_REF_NAME")
+ end
- it { is_expected.to eq(@environment) }
+ it { is_expected.to eq(environment) }
end
end
@@ -923,26 +927,8 @@ describe Ci::Build, :models do
project.add_developer(user)
end
- context 'when build is manual' do
- it 'enqueues a build' do
- new_build = build.play(user)
-
- expect(new_build).to be_pending
- expect(new_build).to eq(build)
- end
- end
-
- context 'when build is passed' do
- before do
- build.update(status: 'success')
- end
-
- it 'creates a new build' do
- new_build = build.play(user)
-
- expect(new_build).to be_pending
- expect(new_build).not_to eq(build)
- end
+ it 'enqueues the build' do
+ expect(build.play(user)).to be_pending
end
end
diff --git a/spec/models/ci/group_spec.rb b/spec/models/ci/group_spec.rb
new file mode 100644
index 00000000000..62e15093089
--- /dev/null
+++ b/spec/models/ci/group_spec.rb
@@ -0,0 +1,44 @@
+require 'spec_helper'
+
+describe Ci::Group, models: true do
+ subject do
+ described_class.new('test', name: 'rspec', jobs: jobs)
+ end
+
+ let!(:jobs) { build_list(:ci_build, 1, :success) }
+
+ it { is_expected.to include_module(StaticModel) }
+
+ it { is_expected.to respond_to(:stage) }
+ it { is_expected.to respond_to(:name) }
+ it { is_expected.to respond_to(:jobs) }
+ it { is_expected.to respond_to(:status) }
+
+ describe '#size' do
+ it 'returns the number of statuses in the group' do
+ expect(subject.size).to eq(1)
+ end
+ end
+
+ describe '#detailed_status' do
+ context 'when there is only one item in the group' do
+ it 'calls the status from the object itself' do
+ expect(jobs.first).to receive(:detailed_status)
+
+ expect(subject.detailed_status(double(:user)))
+ end
+ end
+
+ context 'when there are more than one commit status in the group' do
+ let(:jobs) do
+ [create(:ci_build, :failed),
+ create(:ci_build, :success)]
+ end
+
+ it 'fabricates a new detailed status object' do
+ expect(subject.detailed_status(double(:user)))
+ .to be_a(Gitlab::Ci::Status::Failed)
+ end
+ end
+ end
+end
diff --git a/spec/models/ci/stage_spec.rb b/spec/models/ci/stage_spec.rb
index c38faf32f7d..372b662fab2 100644
--- a/spec/models/ci/stage_spec.rb
+++ b/spec/models/ci/stage_spec.rb
@@ -28,6 +28,35 @@ describe Ci::Stage, models: true do
end
end
+ describe '#groups' do
+ before do
+ create_job(:ci_build, name: 'rspec 0 2')
+ create_job(:ci_build, name: 'rspec 0 1')
+ create_job(:ci_build, name: 'spinach 0 1')
+ create_job(:commit_status, name: 'aaaaa')
+ end
+
+ it 'returns an array of three groups' do
+ expect(stage.groups).to be_a Array
+ expect(stage.groups).to all(be_a Ci::Group)
+ expect(stage.groups.size).to eq 3
+ end
+
+ it 'returns groups with correctly ordered statuses' do
+ expect(stage.groups.first.jobs.map(&:name))
+ .to eq ['aaaaa']
+ expect(stage.groups.second.jobs.map(&:name))
+ .to eq ['rspec 0 1', 'rspec 0 2']
+ expect(stage.groups.third.jobs.map(&:name))
+ .to eq ['spinach 0 1']
+ end
+
+ it 'returns groups with correct names' do
+ expect(stage.groups.map(&:name))
+ .to eq %w[aaaaa rspec spinach]
+ end
+ end
+
describe '#statuses_count' do
before do
create_job(:ci_build)
@@ -223,7 +252,7 @@ describe Ci::Stage, models: true do
end
end
- def create_job(type, status: 'success', stage: stage_name)
- create(type, pipeline: pipeline, stage: stage, status: status)
+ def create_job(type, status: 'success', stage: stage_name, **opts)
+ create(type, pipeline: pipeline, stage: stage, status: status, **opts)
end
end
diff --git a/spec/models/concerns/issuable_spec.rb b/spec/models/concerns/issuable_spec.rb
index 3ecba2e9687..27890e33b49 100644
--- a/spec/models/concerns/issuable_spec.rb
+++ b/spec/models/concerns/issuable_spec.rb
@@ -10,7 +10,6 @@ describe Issuable do
it { is_expected.to belong_to(:project) }
it { is_expected.to belong_to(:author) }
- it { is_expected.to belong_to(:assignee) }
it { is_expected.to have_many(:notes).dependent(:destroy) }
it { is_expected.to have_many(:todos).dependent(:destroy) }
@@ -66,60 +65,6 @@ describe Issuable do
end
end
- describe 'assignee_name' do
- it 'is delegated to assignee' do
- issue.update!(assignee: create(:user))
-
- expect(issue.assignee_name).to eq issue.assignee.name
- end
-
- it 'returns nil when assignee is nil' do
- issue.assignee_id = nil
- issue.save(validate: false)
-
- expect(issue.assignee_name).to eq nil
- end
- end
-
- describe "before_save" do
- describe "#update_cache_counts" do
- context "when previous assignee exists" do
- before do
- assignee = create(:user)
- issue.project.team << [assignee, :developer]
- issue.update(assignee: assignee)
- end
-
- it "updates cache counts for new assignee" do
- user = create(:user)
-
- expect(user).to receive(:update_cache_counts)
-
- issue.update(assignee: user)
- end
-
- it "updates cache counts for previous assignee" do
- old_assignee = issue.assignee
- allow(User).to receive(:find_by_id).with(old_assignee.id).and_return(old_assignee)
-
- expect(old_assignee).to receive(:update_cache_counts)
-
- issue.update(assignee: nil)
- end
- end
-
- context "when previous assignee does not exist" do
- before{ issue.update(assignee: nil) }
-
- it "updates cache count for the new assignee" do
- expect_any_instance_of(User).to receive(:update_cache_counts)
-
- issue.update(assignee: user)
- end
- end
- end
- end
-
describe ".search" do
let!(:searchable_issue) { create(:issue, title: "Searchable issue") }
@@ -307,7 +252,20 @@ describe Issuable do
end
context "issue is assigned" do
- before { issue.update_attribute(:assignee, user) }
+ before { issue.assignees << user }
+
+ it "returns correct hook data" do
+ expect(data[:assignees].first).to eq(user.hook_attrs)
+ end
+ end
+
+ context "merge_request is assigned" do
+ let(:merge_request) { create(:merge_request) }
+ let(:data) { merge_request.to_hook_data(user) }
+
+ before do
+ merge_request.update_attribute(:assignee, user)
+ end
it "returns correct hook data" do
expect(data[:object_attributes]['assignee_id']).to eq(user.id)
@@ -329,24 +287,6 @@ describe Issuable do
include_examples 'deprecated repository hook data'
end
- describe '#card_attributes' do
- it 'includes the author name' do
- allow(issue).to receive(:author).and_return(double(name: 'Robert'))
- allow(issue).to receive(:assignee).and_return(nil)
-
- expect(issue.card_attributes).
- to eq({ 'Author' => 'Robert', 'Assignee' => nil })
- end
-
- it 'includes the assignee name' do
- allow(issue).to receive(:author).and_return(double(name: 'Robert'))
- allow(issue).to receive(:assignee).and_return(double(name: 'Douwe'))
-
- expect(issue.card_attributes).
- to eq({ 'Author' => 'Robert', 'Assignee' => 'Douwe' })
- end
- end
-
describe '#labels_array' do
let(:project) { create(:empty_project) }
let(:bug) { create(:label, project: project, title: 'bug') }
@@ -475,27 +415,6 @@ describe Issuable do
end
end
- describe '#assignee_or_author?' do
- let(:user) { build(:user, id: 1) }
- let(:issue) { build(:issue) }
-
- it 'returns true for a user that is assigned to an issue' do
- issue.assignee = user
-
- expect(issue.assignee_or_author?(user)).to eq(true)
- end
-
- it 'returns true for a user that is the author of an issue' do
- issue.author = user
-
- expect(issue.assignee_or_author?(user)).to eq(true)
- end
-
- it 'returns false for a user that is not the assignee or author' do
- expect(issue.assignee_or_author?(user)).to eq(false)
- end
- end
-
describe '#spend_time' do
let(:user) { create(:user) }
let(:issue) { create(:issue) }
diff --git a/spec/models/concerns/milestoneish_spec.rb b/spec/models/concerns/milestoneish_spec.rb
index 68e4c0a522b..675b730c557 100644
--- a/spec/models/concerns/milestoneish_spec.rb
+++ b/spec/models/concerns/milestoneish_spec.rb
@@ -11,13 +11,13 @@ describe Milestone, 'Milestoneish' do
let(:milestone) { create(:milestone, project: project) }
let!(:issue) { create(:issue, project: project, milestone: milestone) }
let!(:security_issue_1) { create(:issue, :confidential, project: project, author: author, milestone: milestone) }
- let!(:security_issue_2) { create(:issue, :confidential, project: project, assignee: assignee, milestone: milestone) }
+ let!(:security_issue_2) { create(:issue, :confidential, project: project, assignees: [assignee], milestone: milestone) }
let!(:closed_issue_1) { create(:issue, :closed, project: project, milestone: milestone) }
let!(:closed_issue_2) { create(:issue, :closed, project: project, milestone: milestone) }
let!(:closed_security_issue_1) { create(:issue, :confidential, :closed, project: project, author: author, milestone: milestone) }
- let!(:closed_security_issue_2) { create(:issue, :confidential, :closed, project: project, assignee: assignee, milestone: milestone) }
+ let!(:closed_security_issue_2) { create(:issue, :confidential, :closed, project: project, assignees: [assignee], milestone: milestone) }
let!(:closed_security_issue_3) { create(:issue, :confidential, :closed, project: project, author: author, milestone: milestone) }
- let!(:closed_security_issue_4) { create(:issue, :confidential, :closed, project: project, assignee: assignee, milestone: milestone) }
+ let!(:closed_security_issue_4) { create(:issue, :confidential, :closed, project: project, assignees: [assignee], milestone: milestone) }
let!(:merge_request) { create(:merge_request, source_project: project, target_project: project, milestone: milestone) }
before do
diff --git a/spec/models/concerns/routable_spec.rb b/spec/models/concerns/routable_spec.rb
index 221647d7a48..49a4132f763 100644
--- a/spec/models/concerns/routable_spec.rb
+++ b/spec/models/concerns/routable_spec.rb
@@ -9,6 +9,7 @@ describe Group, 'Routable' do
describe 'Associations' do
it { is_expected.to have_one(:route).dependent(:destroy) }
+ it { is_expected.to have_many(:redirect_routes).dependent(:destroy) }
end
describe 'Callbacks' do
@@ -35,10 +36,53 @@ describe Group, 'Routable' do
describe '.find_by_full_path' do
let!(:nested_group) { create(:group, parent: group) }
- it { expect(described_class.find_by_full_path(group.to_param)).to eq(group) }
- it { expect(described_class.find_by_full_path(group.to_param.upcase)).to eq(group) }
- it { expect(described_class.find_by_full_path(nested_group.to_param)).to eq(nested_group) }
- it { expect(described_class.find_by_full_path('unknown')).to eq(nil) }
+ context 'without any redirect routes' do
+ it { expect(described_class.find_by_full_path(group.to_param)).to eq(group) }
+ it { expect(described_class.find_by_full_path(group.to_param.upcase)).to eq(group) }
+ it { expect(described_class.find_by_full_path(nested_group.to_param)).to eq(nested_group) }
+ it { expect(described_class.find_by_full_path('unknown')).to eq(nil) }
+ end
+
+ context 'with redirect routes' do
+ let!(:group_redirect_route) { group.redirect_routes.create!(path: 'bar') }
+ let!(:nested_group_redirect_route) { nested_group.redirect_routes.create!(path: nested_group.path.sub('foo', 'bar')) }
+
+ context 'without follow_redirects option' do
+ context 'with the given path not matching any route' do
+ it { expect(described_class.find_by_full_path('unknown')).to eq(nil) }
+ end
+
+ context 'with the given path matching the canonical route' do
+ it { expect(described_class.find_by_full_path(group.to_param)).to eq(group) }
+ it { expect(described_class.find_by_full_path(group.to_param.upcase)).to eq(group) }
+ it { expect(described_class.find_by_full_path(nested_group.to_param)).to eq(nested_group) }
+ end
+
+ context 'with the given path matching a redirect route' do
+ it { expect(described_class.find_by_full_path(group_redirect_route.path)).to eq(nil) }
+ it { expect(described_class.find_by_full_path(group_redirect_route.path.upcase)).to eq(nil) }
+ it { expect(described_class.find_by_full_path(nested_group_redirect_route.path)).to eq(nil) }
+ end
+ end
+
+ context 'with follow_redirects option set to true' do
+ context 'with the given path not matching any route' do
+ it { expect(described_class.find_by_full_path('unknown', follow_redirects: true)).to eq(nil) }
+ end
+
+ context 'with the given path matching the canonical route' do
+ it { expect(described_class.find_by_full_path(group.to_param, follow_redirects: true)).to eq(group) }
+ it { expect(described_class.find_by_full_path(group.to_param.upcase, follow_redirects: true)).to eq(group) }
+ it { expect(described_class.find_by_full_path(nested_group.to_param, follow_redirects: true)).to eq(nested_group) }
+ end
+
+ context 'with the given path matching a redirect route' do
+ it { expect(described_class.find_by_full_path(group_redirect_route.path, follow_redirects: true)).to eq(group) }
+ it { expect(described_class.find_by_full_path(group_redirect_route.path.upcase, follow_redirects: true)).to eq(group) }
+ it { expect(described_class.find_by_full_path(nested_group_redirect_route.path, follow_redirects: true)).to eq(nested_group) }
+ end
+ end
+ end
end
describe '.where_full_path_in' do
diff --git a/spec/models/environment_spec.rb b/spec/models/environment_spec.rb
index 070716e859a..28e5c3f80f4 100644
--- a/spec/models/environment_spec.rb
+++ b/spec/models/environment_spec.rb
@@ -206,25 +206,52 @@ describe Environment, models: true do
end
context 'when matching action is defined' do
- let(:build) { create(:ci_build) }
- let!(:deployment) { create(:deployment, environment: environment, deployable: build, on_stop: 'close_app') }
+ let(:pipeline) { create(:ci_pipeline, project: project) }
+ let(:build) { create(:ci_build, pipeline: pipeline) }
+
+ let!(:deployment) do
+ create(:deployment, environment: environment,
+ deployable: build,
+ on_stop: 'close_app')
+ end
- context 'when action did not yet finish' do
- let!(:close_action) { create(:ci_build, :manual, pipeline: build.pipeline, name: 'close_app') }
+ context 'when user is not allowed to stop environment' do
+ let!(:close_action) do
+ create(:ci_build, :manual, pipeline: pipeline, name: 'close_app')
+ end
- it 'returns the same action' do
- expect(subject).to eq(close_action)
- expect(subject.user).to eq(user)
+ it 'raises an exception' do
+ expect { subject }.to raise_error(Gitlab::Access::AccessDeniedError)
end
end
- context 'if action did finish' do
- let!(:close_action) { create(:ci_build, :manual, :success, pipeline: build.pipeline, name: 'close_app') }
+ context 'when user is allowed to stop environment' do
+ before do
+ project.add_master(user)
+ end
+
+ context 'when action did not yet finish' do
+ let!(:close_action) do
+ create(:ci_build, :manual, pipeline: pipeline, name: 'close_app')
+ end
+
+ it 'returns the same action' do
+ expect(subject).to eq(close_action)
+ expect(subject.user).to eq(user)
+ end
+ end
- it 'returns a new action of the same type' do
- is_expected.to be_persisted
- expect(subject.name).to eq(close_action.name)
- expect(subject.user).to eq(user)
+ context 'if action did finish' do
+ let!(:close_action) do
+ create(:ci_build, :manual, :success,
+ pipeline: pipeline, name: 'close_app')
+ end
+
+ it 'returns a new action of the same type' do
+ expect(subject).to be_persisted
+ expect(subject.name).to eq(close_action.name)
+ expect(subject.user).to eq(user)
+ end
end
end
end
diff --git a/spec/models/event_spec.rb b/spec/models/event_spec.rb
index a9c5b604268..b8cb967c4cc 100644
--- a/spec/models/event_spec.rb
+++ b/spec/models/event_spec.rb
@@ -118,8 +118,8 @@ describe Event, models: true do
let(:author) { create(:author) }
let(:assignee) { create(:user) }
let(:admin) { create(:admin) }
- let(:issue) { create(:issue, project: project, author: author, assignee: assignee) }
- let(:confidential_issue) { create(:issue, :confidential, project: project, author: author, assignee: assignee) }
+ let(:issue) { create(:issue, project: project, author: author, assignees: [assignee]) }
+ let(:confidential_issue) { create(:issue, :confidential, project: project, author: author, assignees: [assignee]) }
let(:note_on_commit) { create(:note_on_commit, project: project) }
let(:note_on_issue) { create(:note_on_issue, noteable: issue, project: project) }
let(:note_on_confidential_issue) { create(:note_on_issue, noteable: confidential_issue, project: project) }
diff --git a/spec/models/issue_collection_spec.rb b/spec/models/issue_collection_spec.rb
index d8aed25c041..93c2c538e10 100644
--- a/spec/models/issue_collection_spec.rb
+++ b/spec/models/issue_collection_spec.rb
@@ -28,7 +28,7 @@ describe IssueCollection do
end
it 'returns the issues the user is assigned to' do
- issue1.assignee = user
+ issue1.assignees << user
expect(collection.updatable_by_user(user)).to eq([issue1])
end
diff --git a/spec/models/issue_spec.rb b/spec/models/issue_spec.rb
index 8748b98a4e3..725f5c2311f 100644
--- a/spec/models/issue_spec.rb
+++ b/spec/models/issue_spec.rb
@@ -3,6 +3,7 @@ require 'spec_helper'
describe Issue, models: true do
describe "Associations" do
it { is_expected.to belong_to(:milestone) }
+ it { is_expected.to have_many(:assignees) }
end
describe 'modules' do
@@ -37,6 +38,64 @@ describe Issue, models: true do
end
end
+ describe "before_save" do
+ describe "#update_cache_counts when an issue is reassigned" do
+ let(:issue) { create(:issue) }
+ let(:assignee) { create(:user) }
+
+ context "when previous assignee exists" do
+ before do
+ issue.project.team << [assignee, :developer]
+ issue.assignees << assignee
+ end
+
+ it "updates cache counts for new assignee" do
+ user = create(:user)
+
+ expect(user).to receive(:update_cache_counts)
+
+ issue.assignees << user
+ end
+
+ it "updates cache counts for previous assignee" do
+ issue.assignees.first
+
+ expect_any_instance_of(User).to receive(:update_cache_counts)
+
+ issue.assignees.destroy_all
+ end
+ end
+
+ context "when previous assignee does not exist" do
+ it "updates cache count for the new assignee" do
+ issue.assignees = []
+
+ expect_any_instance_of(User).to receive(:update_cache_counts)
+
+ issue.assignees << assignee
+ end
+ end
+ end
+ end
+
+ describe '#card_attributes' do
+ it 'includes the author name' do
+ allow(subject).to receive(:author).and_return(double(name: 'Robert'))
+ allow(subject).to receive(:assignees).and_return([])
+
+ expect(subject.card_attributes).
+ to eq({ 'Author' => 'Robert', 'Assignee' => '' })
+ end
+
+ it 'includes the assignee name' do
+ allow(subject).to receive(:author).and_return(double(name: 'Robert'))
+ allow(subject).to receive(:assignees).and_return([double(name: 'Douwe')])
+
+ expect(subject.card_attributes).
+ to eq({ 'Author' => 'Robert', 'Assignee' => 'Douwe' })
+ end
+ end
+
describe '#closed_at' do
after do
Timecop.return
@@ -124,13 +183,24 @@ describe Issue, models: true do
end
end
- describe '#is_being_reassigned?' do
- it 'returns true if the issue assignee has changed' do
- subject.assignee = create(:user)
- expect(subject.is_being_reassigned?).to be_truthy
+ describe '#assignee_or_author?' do
+ let(:user) { create(:user) }
+ let(:issue) { create(:issue) }
+
+ it 'returns true for a user that is assigned to an issue' do
+ issue.assignees << user
+
+ expect(issue.assignee_or_author?(user)).to be_truthy
end
- it 'returns false if the issue assignee has not changed' do
- expect(subject.is_being_reassigned?).to be_falsey
+
+ it 'returns true for a user that is the author of an issue' do
+ issue.update(author: user)
+
+ expect(issue.assignee_or_author?(user)).to be_truthy
+ end
+
+ it 'returns false for a user that is not the assignee or author' do
+ expect(issue.assignee_or_author?(user)).to be_falsey
end
end
@@ -383,14 +453,14 @@ describe Issue, models: true do
user1 = create(:user)
user2 = create(:user)
project = create(:empty_project)
- issue = create(:issue, assignee: user1, project: project)
+ issue = create(:issue, assignees: [user1], project: project)
project.add_developer(user1)
project.add_developer(user2)
expect(user1.assigned_open_issues_count).to eq(1)
expect(user2.assigned_open_issues_count).to eq(0)
- issue.assignee = user2
+ issue.assignees = [user2]
issue.save
expect(user1.assigned_open_issues_count).to eq(0)
@@ -676,6 +746,11 @@ describe Issue, models: true do
expect(attrs_hash).to include(:human_total_time_spent)
expect(attrs_hash).to include('time_estimate')
end
+
+ it 'includes assignee_ids and deprecated assignee_id' do
+ expect(attrs_hash).to include(:assignee_id)
+ expect(attrs_hash).to include(:assignee_ids)
+ end
end
describe '#check_for_spam' do
diff --git a/spec/models/merge_request_spec.rb b/spec/models/merge_request_spec.rb
index 8b72125dd5d..6cf3dd30ead 100644
--- a/spec/models/merge_request_spec.rb
+++ b/spec/models/merge_request_spec.rb
@@ -9,6 +9,7 @@ describe MergeRequest, models: true do
it { is_expected.to belong_to(:target_project).class_name('Project') }
it { is_expected.to belong_to(:source_project).class_name('Project') }
it { is_expected.to belong_to(:merge_user).class_name("User") }
+ it { is_expected.to belong_to(:assignee) }
it { is_expected.to have_many(:merge_request_diffs).dependent(:destroy) }
end
@@ -86,6 +87,86 @@ describe MergeRequest, models: true do
end
end
+ describe "before_save" do
+ describe "#update_cache_counts when a merge request is reassigned" do
+ let(:project) { create :project }
+ let(:merge_request) { create(:merge_request, source_project: project, target_project: project) }
+ let(:assignee) { create :user }
+
+ context "when previous assignee exists" do
+ before do
+ project.team << [assignee, :developer]
+ merge_request.update(assignee: assignee)
+ end
+
+ it "updates cache counts for new assignee" do
+ user = create(:user)
+
+ expect(user).to receive(:update_cache_counts)
+
+ merge_request.update(assignee: user)
+ end
+
+ it "updates cache counts for previous assignee" do
+ old_assignee = merge_request.assignee
+ allow(User).to receive(:find_by_id).with(old_assignee.id).and_return(old_assignee)
+
+ expect(old_assignee).to receive(:update_cache_counts)
+
+ merge_request.update(assignee: nil)
+ end
+ end
+
+ context "when previous assignee does not exist" do
+ it "updates cache count for the new assignee" do
+ merge_request.update(assignee: nil)
+
+ expect_any_instance_of(User).to receive(:update_cache_counts)
+
+ merge_request.update(assignee: assignee)
+ end
+ end
+ end
+ end
+
+ describe '#card_attributes' do
+ it 'includes the author name' do
+ allow(subject).to receive(:author).and_return(double(name: 'Robert'))
+ allow(subject).to receive(:assignee).and_return(nil)
+
+ expect(subject.card_attributes).
+ to eq({ 'Author' => 'Robert', 'Assignee' => nil })
+ end
+
+ it 'includes the assignee name' do
+ allow(subject).to receive(:author).and_return(double(name: 'Robert'))
+ allow(subject).to receive(:assignee).and_return(double(name: 'Douwe'))
+
+ expect(subject.card_attributes).
+ to eq({ 'Author' => 'Robert', 'Assignee' => 'Douwe' })
+ end
+ end
+
+ describe '#assignee_or_author?' do
+ let(:user) { create(:user) }
+
+ it 'returns true for a user that is assigned to a merge request' do
+ subject.assignee = user
+
+ expect(subject.assignee_or_author?(user)).to eq(true)
+ end
+
+ it 'returns true for a user that is the author of a merge request' do
+ subject.author = user
+
+ expect(subject.assignee_or_author?(user)).to eq(true)
+ end
+
+ it 'returns false for a user that is not the assignee or author' do
+ expect(subject.assignee_or_author?(user)).to eq(false)
+ end
+ end
+
describe '#cache_merge_request_closes_issues!' do
before do
subject.project.team << [subject.author, :developer]
@@ -295,16 +376,6 @@ describe MergeRequest, models: true do
end
end
- describe '#is_being_reassigned?' do
- it 'returns true if the merge_request assignee has changed' do
- subject.assignee = create(:user)
- expect(subject.is_being_reassigned?).to be_truthy
- end
- it 'returns false if the merge request assignee has not changed' do
- expect(subject.is_being_reassigned?).to be_falsey
- end
- end
-
describe '#for_fork?' do
it 'returns true if the merge request is for a fork' do
subject.source_project = build_stubbed(:empty_project, namespace: create(:group))
diff --git a/spec/models/redirect_route_spec.rb b/spec/models/redirect_route_spec.rb
new file mode 100644
index 00000000000..71827421dd7
--- /dev/null
+++ b/spec/models/redirect_route_spec.rb
@@ -0,0 +1,27 @@
+require 'rails_helper'
+
+describe RedirectRoute, models: true do
+ let(:group) { create(:group) }
+ let!(:redirect_route) { group.redirect_routes.create(path: 'gitlabb') }
+
+ describe 'relationships' do
+ it { is_expected.to belong_to(:source) }
+ end
+
+ describe 'validations' do
+ it { is_expected.to validate_presence_of(:source) }
+ it { is_expected.to validate_presence_of(:path) }
+ it { is_expected.to validate_uniqueness_of(:path) }
+ end
+
+ describe '.matching_path_and_descendants' do
+ let!(:redirect2) { group.redirect_routes.create(path: 'gitlabb/test') }
+ let!(:redirect3) { group.redirect_routes.create(path: 'gitlabb/test/foo') }
+ let!(:redirect4) { group.redirect_routes.create(path: 'gitlabb/test/foo/bar') }
+ let!(:redirect5) { group.redirect_routes.create(path: 'gitlabb/test/baz') }
+
+ it 'returns correct routes' do
+ expect(RedirectRoute.matching_path_and_descendants('gitlabb/test')).to match_array([redirect2, redirect3, redirect4, redirect5])
+ end
+ end
+end
diff --git a/spec/models/route_spec.rb b/spec/models/route_spec.rb
index 171a51fcc5b..c1fe1b06c52 100644
--- a/spec/models/route_spec.rb
+++ b/spec/models/route_spec.rb
@@ -1,19 +1,43 @@
require 'spec_helper'
describe Route, models: true do
- let!(:group) { create(:group, path: 'git_lab', name: 'git_lab') }
- let!(:route) { group.route }
+ let(:group) { create(:group, path: 'git_lab', name: 'git_lab') }
+ let(:route) { group.route }
describe 'relationships' do
it { is_expected.to belong_to(:source) }
end
describe 'validations' do
+ before { route }
it { is_expected.to validate_presence_of(:source) }
it { is_expected.to validate_presence_of(:path) }
it { is_expected.to validate_uniqueness_of(:path) }
end
+ describe 'callbacks' do
+ context 'after update' do
+ it 'calls #create_redirect_for_old_path' do
+ expect(route).to receive(:create_redirect_for_old_path)
+ route.update_attributes(path: 'foo')
+ end
+
+ it 'calls #delete_conflicting_redirects' do
+ expect(route).to receive(:delete_conflicting_redirects)
+ route.update_attributes(path: 'foo')
+ end
+ end
+
+ context 'after create' do
+ it 'calls #delete_conflicting_redirects' do
+ route.destroy
+ new_route = Route.new(source: group, path: group.path)
+ expect(new_route).to receive(:delete_conflicting_redirects)
+ new_route.save!
+ end
+ end
+ end
+
describe '.inside_path' do
let!(:nested_group) { create(:group, path: 'test', name: 'test', parent: group) }
let!(:deep_nested_group) { create(:group, path: 'foo', name: 'foo', parent: nested_group) }
@@ -37,7 +61,7 @@ describe Route, models: true do
context 'when route name is set' do
before { route.update_attributes(path: 'bar') }
- it "updates children routes with new path" do
+ it 'updates children routes with new path' do
expect(described_class.exists?(path: 'bar')).to be_truthy
expect(described_class.exists?(path: 'bar/test')).to be_truthy
expect(described_class.exists?(path: 'bar/test/foo')).to be_truthy
@@ -56,10 +80,24 @@ describe Route, models: true do
expect(route.update_attributes(path: 'bar')).to be_truthy
end
end
+
+ context 'when conflicting redirects exist' do
+ let!(:conflicting_redirect1) { route.create_redirect('bar/test') }
+ let!(:conflicting_redirect2) { route.create_redirect('bar/test/foo') }
+ let!(:conflicting_redirect3) { route.create_redirect('gitlab-org') }
+
+ it 'deletes the conflicting redirects' do
+ route.update_attributes(path: 'bar')
+
+ expect(RedirectRoute.exists?(path: 'bar/test')).to be_falsey
+ expect(RedirectRoute.exists?(path: 'bar/test/foo')).to be_falsey
+ expect(RedirectRoute.exists?(path: 'gitlab-org')).to be_truthy
+ end
+ end
end
context 'name update' do
- it "updates children routes with new path" do
+ it 'updates children routes with new path' do
route.update_attributes(name: 'bar')
expect(described_class.exists?(name: 'bar')).to be_truthy
@@ -77,4 +115,72 @@ describe Route, models: true do
end
end
end
+
+ describe '#create_redirect_for_old_path' do
+ context 'if the path changed' do
+ it 'creates a RedirectRoute for the old path' do
+ redirect_scope = route.source.redirect_routes.where(path: 'git_lab')
+ expect(redirect_scope.exists?).to be_falsey
+ route.path = 'new-path'
+ route.save!
+ expect(redirect_scope.exists?).to be_truthy
+ end
+ end
+ end
+
+ describe '#create_redirect' do
+ it 'creates a RedirectRoute with the same source' do
+ redirect_route = route.create_redirect('foo')
+ expect(redirect_route).to be_a(RedirectRoute)
+ expect(redirect_route).to be_persisted
+ expect(redirect_route.source).to eq(route.source)
+ expect(redirect_route.path).to eq('foo')
+ end
+ end
+
+ describe '#delete_conflicting_redirects' do
+ context 'when a redirect route with the same path exists' do
+ let!(:redirect1) { route.create_redirect(route.path) }
+
+ it 'deletes the redirect' do
+ route.delete_conflicting_redirects
+ expect(route.conflicting_redirects).to be_empty
+ end
+
+ context 'when redirect routes with paths descending from the route path exists' do
+ let!(:redirect2) { route.create_redirect("#{route.path}/foo") }
+ let!(:redirect3) { route.create_redirect("#{route.path}/foo/bar") }
+ let!(:redirect4) { route.create_redirect("#{route.path}/baz/quz") }
+ let!(:other_redirect) { route.create_redirect("other") }
+
+ it 'deletes all redirects with paths that descend from the route path' do
+ route.delete_conflicting_redirects
+ expect(route.conflicting_redirects).to be_empty
+ end
+ end
+ end
+ end
+
+ describe '#conflicting_redirects' do
+ context 'when a redirect route with the same path exists' do
+ let!(:redirect1) { route.create_redirect(route.path) }
+
+ it 'returns the redirect route' do
+ expect(route.conflicting_redirects).to be_an(ActiveRecord::Relation)
+ expect(route.conflicting_redirects).to match_array([redirect1])
+ end
+
+ context 'when redirect routes with paths descending from the route path exists' do
+ let!(:redirect2) { route.create_redirect("#{route.path}/foo") }
+ let!(:redirect3) { route.create_redirect("#{route.path}/foo/bar") }
+ let!(:redirect4) { route.create_redirect("#{route.path}/baz/quz") }
+ let!(:other_redirect) { route.create_redirect("other") }
+
+ it 'returns the redirect routes' do
+ expect(route.conflicting_redirects).to be_an(ActiveRecord::Relation)
+ expect(route.conflicting_redirects).to match_array([redirect1, redirect2, redirect3, redirect4])
+ end
+ end
+ end
+ end
end
diff --git a/spec/models/user_spec.rb b/spec/models/user_spec.rb
index 401eaac07a1..63e71f5ff2f 100644
--- a/spec/models/user_spec.rb
+++ b/spec/models/user_spec.rb
@@ -849,6 +849,65 @@ describe User, models: true do
end
end
+ describe '.find_by_full_path' do
+ let!(:user) { create(:user) }
+
+ context 'with a route matching the given path' do
+ let!(:route) { user.namespace.route }
+
+ it 'returns the user' do
+ expect(User.find_by_full_path(route.path)).to eq(user)
+ end
+
+ it 'is case-insensitive' do
+ expect(User.find_by_full_path(route.path.upcase)).to eq(user)
+ expect(User.find_by_full_path(route.path.downcase)).to eq(user)
+ end
+ end
+
+ context 'with a redirect route matching the given path' do
+ let!(:redirect_route) { user.namespace.redirect_routes.create(path: 'foo') }
+
+ context 'without the follow_redirects option' do
+ it 'returns nil' do
+ expect(User.find_by_full_path(redirect_route.path)).to eq(nil)
+ end
+ end
+
+ context 'with the follow_redirects option set to true' do
+ it 'returns the user' do
+ expect(User.find_by_full_path(redirect_route.path, follow_redirects: true)).to eq(user)
+ end
+
+ it 'is case-insensitive' do
+ expect(User.find_by_full_path(redirect_route.path.upcase, follow_redirects: true)).to eq(user)
+ expect(User.find_by_full_path(redirect_route.path.downcase, follow_redirects: true)).to eq(user)
+ end
+ end
+ end
+
+ context 'without a route or a redirect route matching the given path' do
+ context 'without the follow_redirects option' do
+ it 'returns nil' do
+ expect(User.find_by_full_path('unknown')).to eq(nil)
+ end
+ end
+ context 'with the follow_redirects option set to true' do
+ it 'returns nil' do
+ expect(User.find_by_full_path('unknown', follow_redirects: true)).to eq(nil)
+ end
+ end
+ end
+
+ context 'with a group route matching the given path' do
+ let!(:group) { create(:group, path: 'group_path') }
+
+ it 'returns nil' do
+ expect(User.find_by_full_path('group_path')).to eq(nil)
+ end
+ end
+ end
+
describe 'all_ssh_keys' do
it { is_expected.to have_many(:keys).dependent(:destroy) }
diff --git a/spec/policies/ci/build_policy_spec.rb b/spec/policies/ci/build_policy_spec.rb
index 0f280f32eac..3f4ce222b60 100644
--- a/spec/policies/ci/build_policy_spec.rb
+++ b/spec/policies/ci/build_policy_spec.rb
@@ -89,5 +89,58 @@ describe Ci::BuildPolicy, :models do
end
end
end
+
+ describe 'rules for manual actions' do
+ let(:project) { create(:project) }
+
+ before do
+ project.add_developer(user)
+ end
+
+ context 'when branch build is assigned to is protected' do
+ before do
+ create(:protected_branch, :no_one_can_push,
+ name: 'some-ref', project: project)
+ end
+
+ context 'when build is a manual action' do
+ let(:build) do
+ create(:ci_build, :manual, ref: 'some-ref', pipeline: pipeline)
+ end
+
+ it 'does not include ability to update build' do
+ expect(policies).not_to include :update_build
+ end
+ end
+
+ context 'when build is not a manual action' do
+ let(:build) do
+ create(:ci_build, ref: 'some-ref', pipeline: pipeline)
+ end
+
+ it 'includes ability to update build' do
+ expect(policies).to include :update_build
+ end
+ end
+ end
+
+ context 'when branch build is assigned to is not protected' do
+ context 'when build is a manual action' do
+ let(:build) { create(:ci_build, :manual, pipeline: pipeline) }
+
+ it 'includes ability to update build' do
+ expect(policies).to include :update_build
+ end
+ end
+
+ context 'when build is not a manual action' do
+ let(:build) { create(:ci_build, pipeline: pipeline) }
+
+ it 'includes ability to update build' do
+ expect(policies).to include :update_build
+ end
+ end
+ end
+ end
end
end
diff --git a/spec/policies/environment_policy_spec.rb b/spec/policies/environment_policy_spec.rb
new file mode 100644
index 00000000000..0e15beaa5e8
--- /dev/null
+++ b/spec/policies/environment_policy_spec.rb
@@ -0,0 +1,57 @@
+require 'spec_helper'
+
+describe EnvironmentPolicy do
+ let(:user) { create(:user) }
+ let(:project) { create(:project) }
+
+ let(:environment) do
+ create(:environment, :with_review_app, project: project)
+ end
+
+ let(:policies) do
+ described_class.abilities(user, environment).to_set
+ end
+
+ describe '#rules' do
+ context 'when user does not have access to the project' do
+ let(:project) { create(:project, :private) }
+
+ it 'does not include ability to stop environment' do
+ expect(policies).not_to include :stop_environment
+ end
+ end
+
+ context 'when anonymous user has access to the project' do
+ let(:project) { create(:project, :public) }
+
+ it 'does not include ability to stop environment' do
+ expect(policies).not_to include :stop_environment
+ end
+ end
+
+ context 'when team member has access to the project' do
+ let(:project) { create(:project, :public) }
+
+ before do
+ project.add_master(user)
+ end
+
+ context 'when team member has ability to stop environment' do
+ it 'does includes ability to stop environment' do
+ expect(policies).to include :stop_environment
+ end
+ end
+
+ context 'when team member has no ability to stop environment' do
+ before do
+ create(:protected_branch, :no_one_can_push,
+ name: 'master', project: project)
+ end
+
+ it 'does not include ability to stop environment' do
+ expect(policies).not_to include :stop_environment
+ end
+ end
+ end
+ end
+end
diff --git a/spec/policies/issue_policy_spec.rb b/spec/policies/issue_policy_spec.rb
index 9a870b7fda1..4a07c864428 100644
--- a/spec/policies/issue_policy_spec.rb
+++ b/spec/policies/issue_policy_spec.rb
@@ -15,7 +15,7 @@ describe IssuePolicy, models: true do
context 'a private project' do
let(:non_member) { create(:user) }
let(:project) { create(:empty_project, :private) }
- let(:issue) { create(:issue, project: project, assignee: assignee, author: author) }
+ let(:issue) { create(:issue, project: project, assignees: [assignee], author: author) }
let(:issue_no_assignee) { create(:issue, project: project) }
before do
@@ -69,7 +69,7 @@ describe IssuePolicy, models: true do
end
context 'with confidential issues' do
- let(:confidential_issue) { create(:issue, :confidential, project: project, assignee: assignee, author: author) }
+ let(:confidential_issue) { create(:issue, :confidential, project: project, assignees: [assignee], author: author) }
let(:confidential_issue_no_assignee) { create(:issue, :confidential, project: project) }
it 'does not allow non-members to read confidential issues' do
@@ -110,7 +110,7 @@ describe IssuePolicy, models: true do
context 'a public project' do
let(:project) { create(:empty_project, :public) }
- let(:issue) { create(:issue, project: project, assignee: assignee, author: author) }
+ let(:issue) { create(:issue, project: project, assignees: [assignee], author: author) }
let(:issue_no_assignee) { create(:issue, project: project) }
before do
@@ -157,7 +157,7 @@ describe IssuePolicy, models: true do
end
context 'with confidential issues' do
- let(:confidential_issue) { create(:issue, :confidential, project: project, assignee: assignee, author: author) }
+ let(:confidential_issue) { create(:issue, :confidential, project: project, assignees: [assignee], author: author) }
let(:confidential_issue_no_assignee) { create(:issue, :confidential, project: project) }
it 'does not allow guests to read confidential issues' do
diff --git a/spec/requests/api/helpers/internal_helpers_spec.rb b/spec/requests/api/helpers/internal_helpers_spec.rb
deleted file mode 100644
index db716b340f1..00000000000
--- a/spec/requests/api/helpers/internal_helpers_spec.rb
+++ /dev/null
@@ -1,32 +0,0 @@
-require 'spec_helper'
-
-describe ::API::Helpers::InternalHelpers do
- include described_class
-
- describe '.clean_project_path' do
- project = 'namespace/project'
- namespaced = File.join('namespace2', project)
-
- {
- File.join(Dir.pwd, project) => project,
- File.join(Dir.pwd, namespaced) => namespaced,
- project => project,
- namespaced => namespaced,
- project + '.git' => project,
- namespaced + '.git' => namespaced,
- "/" + project => project,
- "/" + namespaced => namespaced,
- }.each do |project_path, expected|
- context project_path do
- # Relative and absolute storage paths, with and without trailing /
- ['.', './', Dir.pwd, Dir.pwd + '/'].each do |storage_path|
- context "storage path is #{storage_path}" do
- subject { clean_project_path(project_path, [{ 'path' => storage_path }]) }
-
- it { is_expected.to eq(expected) }
- end
- end
- end
- end
- end
-end
diff --git a/spec/requests/api/internal_spec.rb b/spec/requests/api/internal_spec.rb
index 429f1a4e375..2ceb4648ece 100644
--- a/spec/requests/api/internal_spec.rb
+++ b/spec/requests/api/internal_spec.rb
@@ -180,6 +180,7 @@ describe API::Internal do
expect(response).to have_http_status(200)
expect(json_response["status"]).to be_truthy
expect(json_response["repository_path"]).to eq(project.wiki.repository.path_to_repo)
+ expect(json_response["gl_repository"]).to eq("wiki-#{project.id}")
expect(user).not_to have_an_activity_record
end
end
@@ -191,6 +192,7 @@ describe API::Internal do
expect(response).to have_http_status(200)
expect(json_response["status"]).to be_truthy
expect(json_response["repository_path"]).to eq(project.wiki.repository.path_to_repo)
+ expect(json_response["gl_repository"]).to eq("wiki-#{project.id}")
expect(user).to have_an_activity_record
end
end
@@ -202,6 +204,7 @@ describe API::Internal do
expect(response).to have_http_status(200)
expect(json_response["status"]).to be_truthy
expect(json_response["repository_path"]).to eq(project.repository.path_to_repo)
+ expect(json_response["gl_repository"]).to eq("project-#{project.id}")
expect(user).to have_an_activity_record
end
end
@@ -213,6 +216,7 @@ describe API::Internal do
expect(response).to have_http_status(200)
expect(json_response["status"]).to be_truthy
expect(json_response["repository_path"]).to eq(project.repository.path_to_repo)
+ expect(json_response["gl_repository"]).to eq("project-#{project.id}")
expect(user).not_to have_an_activity_record
end
@@ -223,6 +227,7 @@ describe API::Internal do
expect(response).to have_http_status(200)
expect(json_response["status"]).to be_truthy
expect(json_response["repository_path"]).to eq(project.repository.path_to_repo)
+ expect(json_response["gl_repository"]).to eq("project-#{project.id}")
end
end
@@ -233,6 +238,7 @@ describe API::Internal do
expect(response).to have_http_status(200)
expect(json_response["status"]).to be_truthy
expect(json_response["repository_path"]).to eq(project.repository.path_to_repo)
+ expect(json_response["gl_repository"]).to eq("project-#{project.id}")
end
end
end
@@ -444,18 +450,39 @@ describe API::Internal do
expect(json_response).to eq([])
end
+
+ context 'with a gl_repository parameter' do
+ let(:gl_repository) { "project-#{project.id}" }
+
+ it 'returns link to create new merge request' do
+ get api("/internal/merge_request_urls?gl_repository=#{gl_repository}&changes=#{changes}"), secret_token: secret_token
+
+ expect(json_response).to match [{
+ "branch_name" => "new_branch",
+ "url" => "http://#{Gitlab.config.gitlab.host}/#{project.namespace.name}/#{project.path}/merge_requests/new?merge_request%5Bsource_branch%5D=new_branch",
+ "new_merge_request" => true
+ }]
+ end
+ end
end
describe 'POST /notify_post_receive' do
let(:valid_params) do
- { repo_path: project.repository.path, secret_token: secret_token }
+ { project: project.repository.path, secret_token: secret_token }
+ end
+
+ let(:valid_wiki_params) do
+ { project: project.wiki.repository.path, secret_token: secret_token }
end
before do
allow(Gitlab.config.gitaly).to receive(:enabled).and_return(true)
end
- it "calls the Gitaly client if it's enabled" do
+ it "calls the Gitaly client with the project's repository" do
+ expect(Gitlab::GitalyClient::Notifications).
+ to receive(:new).with(gitlab_git_repository_with(path: project.repository.path)).
+ and_call_original
expect_any_instance_of(Gitlab::GitalyClient::Notifications).
to receive(:post_receive)
@@ -464,6 +491,18 @@ describe API::Internal do
expect(response).to have_http_status(200)
end
+ it "calls the Gitaly client with the wiki's repository if it's a wiki" do
+ expect(Gitlab::GitalyClient::Notifications).
+ to receive(:new).with(gitlab_git_repository_with(path: project.wiki.repository.path)).
+ and_call_original
+ expect_any_instance_of(Gitlab::GitalyClient::Notifications).
+ to receive(:post_receive)
+
+ post api("/internal/notify_post_receive"), valid_wiki_params
+
+ expect(response).to have_http_status(200)
+ end
+
it "returns 500 if the gitaly call fails" do
expect_any_instance_of(Gitlab::GitalyClient::Notifications).
to receive(:post_receive).and_raise(GRPC::Unavailable)
@@ -472,6 +511,40 @@ describe API::Internal do
expect(response).to have_http_status(500)
end
+
+ context 'with a gl_repository parameter' do
+ let(:valid_params) do
+ { gl_repository: "project-#{project.id}", secret_token: secret_token }
+ end
+
+ let(:valid_wiki_params) do
+ { gl_repository: "wiki-#{project.id}", secret_token: secret_token }
+ end
+
+ it "calls the Gitaly client with the project's repository" do
+ expect(Gitlab::GitalyClient::Notifications).
+ to receive(:new).with(gitlab_git_repository_with(path: project.repository.path)).
+ and_call_original
+ expect_any_instance_of(Gitlab::GitalyClient::Notifications).
+ to receive(:post_receive)
+
+ post api("/internal/notify_post_receive"), valid_params
+
+ expect(response).to have_http_status(200)
+ end
+
+ it "calls the Gitaly client with the wiki's repository if it's a wiki" do
+ expect(Gitlab::GitalyClient::Notifications).
+ to receive(:new).with(gitlab_git_repository_with(path: project.wiki.repository.path)).
+ and_call_original
+ expect_any_instance_of(Gitlab::GitalyClient::Notifications).
+ to receive(:post_receive)
+
+ post api("/internal/notify_post_receive"), valid_wiki_params
+
+ expect(response).to have_http_status(200)
+ end
+ end
end
def project_with_repo_path(path)
diff --git a/spec/requests/api/issues_spec.rb b/spec/requests/api/issues_spec.rb
index 3ca13111acb..da2b56c040b 100644
--- a/spec/requests/api/issues_spec.rb
+++ b/spec/requests/api/issues_spec.rb
@@ -19,7 +19,7 @@ describe API::Issues do
let!(:closed_issue) do
create :closed_issue,
author: user,
- assignee: user,
+ assignees: [user],
project: project,
state: :closed,
milestone: milestone,
@@ -31,14 +31,14 @@ describe API::Issues do
:confidential,
project: project,
author: author,
- assignee: assignee,
+ assignees: [assignee],
created_at: generate(:past_time),
updated_at: 2.hours.ago
end
let!(:issue) do
create :issue,
author: user,
- assignee: user,
+ assignees: [user],
project: project,
milestone: milestone,
created_at: generate(:past_time),
@@ -265,7 +265,7 @@ describe API::Issues do
let!(:group_closed_issue) do
create :closed_issue,
author: user,
- assignee: user,
+ assignees: [user],
project: group_project,
state: :closed,
milestone: group_milestone,
@@ -276,13 +276,13 @@ describe API::Issues do
:confidential,
project: group_project,
author: author,
- assignee: assignee,
+ assignees: [assignee],
updated_at: 2.hours.ago
end
let!(:group_issue) do
create :issue,
author: user,
- assignee: user,
+ assignees: [user],
project: group_project,
milestone: group_milestone,
updated_at: 1.hour.ago,
@@ -687,6 +687,7 @@ describe API::Issues do
expect(json_response['updated_at']).to be_present
expect(json_response['labels']).to eq(issue.label_names)
expect(json_response['milestone']).to be_a Hash
+ expect(json_response['assignees']).to be_a Array
expect(json_response['assignee']).to be_a Hash
expect(json_response['author']).to be_a Hash
expect(json_response['confidential']).to be_falsy
@@ -759,15 +760,41 @@ describe API::Issues do
end
describe "POST /projects/:id/issues" do
+ context 'support for deprecated assignee_id' do
+ it 'creates a new project issue' do
+ post api("/projects/#{project.id}/issues", user),
+ title: 'new issue', assignee_id: user2.id
+
+ expect(response).to have_http_status(201)
+ expect(json_response['title']).to eq('new issue')
+ expect(json_response['assignee']['name']).to eq(user2.name)
+ expect(json_response['assignees'].first['name']).to eq(user2.name)
+ end
+ end
+
+ context 'CE restrictions' do
+ it 'creates a new project issue with no more than one assignee' do
+ post api("/projects/#{project.id}/issues", user),
+ title: 'new issue', assignee_ids: [user2.id, guest.id]
+
+ expect(response).to have_http_status(201)
+ expect(json_response['title']).to eq('new issue')
+ expect(json_response['assignees'].count).to eq(1)
+ end
+ end
+
it 'creates a new project issue' do
post api("/projects/#{project.id}/issues", user),
- title: 'new issue', labels: 'label, label2'
+ title: 'new issue', labels: 'label, label2', weight: 3,
+ assignee_ids: [user2.id]
expect(response).to have_http_status(201)
expect(json_response['title']).to eq('new issue')
expect(json_response['description']).to be_nil
expect(json_response['labels']).to eq(%w(label label2))
expect(json_response['confidential']).to be_falsy
+ expect(json_response['assignee']['name']).to eq(user2.name)
+ expect(json_response['assignees'].first['name']).to eq(user2.name)
end
it 'creates a new confidential project issue' do
@@ -1057,6 +1084,57 @@ describe API::Issues do
end
end
+ describe 'PUT /projects/:id/issues/:issue_iid to update assignee' do
+ context 'support for deprecated assignee_id' do
+ it 'removes assignee' do
+ put api("/projects/#{project.id}/issues/#{issue.iid}", user),
+ assignee_id: 0
+
+ expect(response).to have_http_status(200)
+
+ expect(json_response['assignee']).to be_nil
+ end
+
+ it 'updates an issue with new assignee' do
+ put api("/projects/#{project.id}/issues/#{issue.iid}", user),
+ assignee_id: user2.id
+
+ expect(response).to have_http_status(200)
+
+ expect(json_response['assignee']['name']).to eq(user2.name)
+ end
+ end
+
+ it 'removes assignee' do
+ put api("/projects/#{project.id}/issues/#{issue.iid}", user),
+ assignee_ids: [0]
+
+ expect(response).to have_http_status(200)
+
+ expect(json_response['assignees']).to be_empty
+ end
+
+ it 'updates an issue with new assignee' do
+ put api("/projects/#{project.id}/issues/#{issue.iid}", user),
+ assignee_ids: [user2.id]
+
+ expect(response).to have_http_status(200)
+
+ expect(json_response['assignees'].first['name']).to eq(user2.name)
+ end
+
+ context 'CE restrictions' do
+ it 'updates an issue with several assignee but only one has been applied' do
+ put api("/projects/#{project.id}/issues/#{issue.iid}", user),
+ assignee_ids: [user2.id, guest.id]
+
+ expect(response).to have_http_status(200)
+
+ expect(json_response['assignees'].size).to eq(1)
+ end
+ end
+ end
+
describe 'PUT /projects/:id/issues/:issue_iid to update labels' do
let!(:label) { create(:label, title: 'dummy', project: project) }
let!(:label_link) { create(:label_link, label: label, target: issue) }
diff --git a/spec/requests/api/jobs_spec.rb b/spec/requests/api/jobs_spec.rb
index decb5b91941..e5e5872dc1f 100644
--- a/spec/requests/api/jobs_spec.rb
+++ b/spec/requests/api/jobs_spec.rb
@@ -1,14 +1,26 @@
require 'spec_helper'
-describe API::Jobs do
+describe API::Jobs, :api do
+ let!(:project) do
+ create(:project, :repository, public_builds: false)
+ end
+
+ let!(:pipeline) do
+ create(:ci_empty_pipeline, project: project,
+ sha: project.commit.id,
+ ref: project.default_branch)
+ end
+
+ let!(:build) { create(:ci_build, pipeline: pipeline) }
+
let(:user) { create(:user) }
let(:api_user) { user }
- let!(:project) { create(:project, :repository, creator: user, public_builds: false) }
- let!(:developer) { create(:project_member, :developer, user: user, project: project) }
- let(:reporter) { create(:project_member, :reporter, project: project) }
- let(:guest) { create(:project_member, :guest, project: project) }
- let!(:pipeline) { create(:ci_empty_pipeline, project: project, sha: project.commit.id, ref: project.default_branch) }
- let!(:build) { create(:ci_build, pipeline: pipeline) }
+ let(:reporter) { create(:project_member, :reporter, project: project).user }
+ let(:guest) { create(:project_member, :guest, project: project).user }
+
+ before do
+ project.add_developer(user)
+ end
describe 'GET /projects/:id/jobs' do
let(:query) { Hash.new }
@@ -211,7 +223,7 @@ describe API::Jobs do
end
describe 'GET /projects/:id/artifacts/:ref_name/download?job=name' do
- let(:api_user) { reporter.user }
+ let(:api_user) { reporter }
let(:build) { create(:ci_build, :artifacts, pipeline: pipeline) }
before do
@@ -235,7 +247,7 @@ describe API::Jobs do
end
context 'when logging as guest' do
- let(:api_user) { guest.user }
+ let(:api_user) { guest }
before do
get_for_ref
@@ -345,7 +357,7 @@ describe API::Jobs do
end
context 'user without :update_build permission' do
- let(:api_user) { reporter.user }
+ let(:api_user) { reporter }
it 'does not cancel job' do
expect(response).to have_http_status(403)
@@ -379,7 +391,7 @@ describe API::Jobs do
end
context 'user without :update_build permission' do
- let(:api_user) { reporter.user }
+ let(:api_user) { reporter }
it 'does not retry job' do
expect(response).to have_http_status(403)
@@ -455,16 +467,39 @@ describe API::Jobs do
describe 'POST /projects/:id/jobs/:job_id/play' do
before do
- post api("/projects/#{project.id}/jobs/#{build.id}/play", user)
+ post api("/projects/#{project.id}/jobs/#{build.id}/play", api_user)
end
context 'on an playable job' do
let(:build) { create(:ci_build, :manual, project: project, pipeline: pipeline) }
- it 'plays the job' do
- expect(response).to have_http_status(200)
- expect(json_response['user']['id']).to eq(user.id)
- expect(json_response['id']).to eq(build.id)
+ context 'when user is authorized to trigger a manual action' do
+ it 'plays the job' do
+ expect(response).to have_http_status(200)
+ expect(json_response['user']['id']).to eq(user.id)
+ expect(json_response['id']).to eq(build.id)
+ expect(build.reload).to be_pending
+ end
+ end
+
+ context 'when user is not authorized to trigger a manual action' do
+ context 'when user does not have access to the project' do
+ let(:api_user) { create(:user) }
+
+ it 'does not trigger a manual action' do
+ expect(build.reload).to be_manual
+ expect(response).to have_http_status(404)
+ end
+ end
+
+ context 'when user is not allowed to trigger the manual action' do
+ let(:api_user) { reporter }
+
+ it 'does not trigger a manual action' do
+ expect(build.reload).to be_manual
+ expect(response).to have_http_status(403)
+ end
+ end
end
end
diff --git a/spec/requests/api/v3/issues_spec.rb b/spec/requests/api/v3/issues_spec.rb
index ef5b10a1615..cc81922697a 100644
--- a/spec/requests/api/v3/issues_spec.rb
+++ b/spec/requests/api/v3/issues_spec.rb
@@ -14,7 +14,7 @@ describe API::V3::Issues do
let!(:closed_issue) do
create :closed_issue,
author: user,
- assignee: user,
+ assignees: [user],
project: project,
state: :closed,
milestone: milestone,
@@ -26,14 +26,14 @@ describe API::V3::Issues do
:confidential,
project: project,
author: author,
- assignee: assignee,
+ assignees: [assignee],
created_at: generate(:past_time),
updated_at: 2.hours.ago
end
let!(:issue) do
create :issue,
author: user,
- assignee: user,
+ assignees: [user],
project: project,
milestone: milestone,
created_at: generate(:past_time),
@@ -247,7 +247,7 @@ describe API::V3::Issues do
let!(:group_closed_issue) do
create :closed_issue,
author: user,
- assignee: user,
+ assignees: [user],
project: group_project,
state: :closed,
milestone: group_milestone,
@@ -258,13 +258,13 @@ describe API::V3::Issues do
:confidential,
project: group_project,
author: author,
- assignee: assignee,
+ assignees: [assignee],
updated_at: 2.hours.ago
end
let!(:group_issue) do
create :issue,
author: user,
- assignee: user,
+ assignees: [user],
project: group_project,
milestone: group_milestone,
updated_at: 1.hour.ago
@@ -737,13 +737,14 @@ describe API::V3::Issues do
describe "POST /projects/:id/issues" do
it 'creates a new project issue' do
post v3_api("/projects/#{project.id}/issues", user),
- title: 'new issue', labels: 'label, label2'
+ title: 'new issue', labels: 'label, label2', assignee_id: assignee.id
expect(response).to have_http_status(201)
expect(json_response['title']).to eq('new issue')
expect(json_response['description']).to be_nil
expect(json_response['labels']).to eq(%w(label label2))
expect(json_response['confidential']).to be_falsy
+ expect(json_response['assignee']['name']).to eq(assignee.name)
end
it 'creates a new confidential project issue' do
@@ -1140,6 +1141,22 @@ describe API::V3::Issues do
end
end
+ describe 'PUT /projects/:id/issues/:issue_id to update assignee' do
+ it 'updates an issue with no assignee' do
+ put v3_api("/projects/#{project.id}/issues/#{issue.id}", user), assignee_id: 0
+
+ expect(response).to have_http_status(200)
+ expect(json_response['assignee']).to eq(nil)
+ end
+
+ it 'updates an issue with assignee' do
+ put v3_api("/projects/#{project.id}/issues/#{issue.id}", user), assignee_id: user2.id
+
+ expect(response).to have_http_status(200)
+ expect(json_response['assignee']['name']).to eq(user2.name)
+ end
+ end
+
describe "DELETE /projects/:id/issues/:issue_id" do
it "rejects a non member from deleting an issue" do
delete v3_api("/projects/#{project.id}/issues/#{issue.id}", non_member)
diff --git a/spec/routing/project_routing_spec.rb b/spec/routing/project_routing_spec.rb
index 163df072cf6..50e96d56191 100644
--- a/spec/routing/project_routing_spec.rb
+++ b/spec/routing/project_routing_spec.rb
@@ -3,7 +3,7 @@ require 'spec_helper'
describe 'project routing' do
before do
allow(Project).to receive(:find_by_full_path).and_return(false)
- allow(Project).to receive(:find_by_full_path).with('gitlab/gitlabhq').and_return(true)
+ allow(Project).to receive(:find_by_full_path).with('gitlab/gitlabhq', any_args).and_return(true)
end
# Shared examples for a resource inside a Project
@@ -93,13 +93,13 @@ describe 'project routing' do
end
context 'name with dot' do
- before { allow(Project).to receive(:find_by_full_path).with('gitlab/gitlabhq.keys').and_return(true) }
+ before { allow(Project).to receive(:find_by_full_path).with('gitlab/gitlabhq.keys', any_args).and_return(true) }
it { expect(get('/gitlab/gitlabhq.keys')).to route_to('projects#show', namespace_id: 'gitlab', id: 'gitlabhq.keys') }
end
context 'with nested group' do
- before { allow(Project).to receive(:find_by_full_path).with('gitlab/subgroup/gitlabhq').and_return(true) }
+ before { allow(Project).to receive(:find_by_full_path).with('gitlab/subgroup/gitlabhq', any_args).and_return(true) }
it { expect(get('/gitlab/subgroup/gitlabhq')).to route_to('projects#show', namespace_id: 'gitlab/subgroup', id: 'gitlabhq') }
end
diff --git a/spec/serializers/build_action_entity_spec.rb b/spec/serializers/build_action_entity_spec.rb
index 54ac17447b1..059deba5416 100644
--- a/spec/serializers/build_action_entity_spec.rb
+++ b/spec/serializers/build_action_entity_spec.rb
@@ -2,9 +2,10 @@ require 'spec_helper'
describe BuildActionEntity do
let(:build) { create(:ci_build, name: 'test_build') }
+ let(:request) { double('request') }
let(:entity) do
- described_class.new(build, request: double)
+ described_class.new(build, request: spy('request'))
end
describe '#as_json' do
diff --git a/spec/serializers/build_entity_spec.rb b/spec/serializers/build_entity_spec.rb
index f76a5cf72d1..897a28b7305 100644
--- a/spec/serializers/build_entity_spec.rb
+++ b/spec/serializers/build_entity_spec.rb
@@ -41,13 +41,37 @@ describe BuildEntity do
it 'does not contain path to play action' do
expect(subject).not_to include(:play_path)
end
+
+ it 'is not a playable job' do
+ expect(subject[:playable]).to be false
+ end
end
context 'when build is a manual action' do
let(:build) { create(:ci_build, :manual) }
- it 'contains path to play action' do
- expect(subject).to include(:play_path)
+ context 'when user is allowed to trigger action' do
+ before do
+ build.project.add_master(user)
+ end
+
+ it 'contains path to play action' do
+ expect(subject).to include(:play_path)
+ end
+
+ it 'is a playable action' do
+ expect(subject[:playable]).to be true
+ end
+ end
+
+ context 'when user is not allowed to trigger action' do
+ it 'does not contain path to play action' do
+ expect(subject).not_to include(:play_path)
+ end
+
+ it 'is not a playable action' do
+ expect(subject[:playable]).to be false
+ end
end
end
end
diff --git a/spec/serializers/label_serializer_spec.rb b/spec/serializers/label_serializer_spec.rb
new file mode 100644
index 00000000000..c58c7da1f9e
--- /dev/null
+++ b/spec/serializers/label_serializer_spec.rb
@@ -0,0 +1,46 @@
+require 'spec_helper'
+
+describe LabelSerializer do
+ let(:user) { create(:user) }
+
+ let(:serializer) do
+ described_class.new(user: user)
+ end
+
+ subject { serializer.represent(resource) }
+
+ describe '#represent' do
+ context 'when a single object is being serialized' do
+ let(:resource) { create(:label) }
+
+ it 'serializes the label object' do
+ expect(subject[:id]).to eq resource.id
+ end
+ end
+
+ context 'when multiple objects are being serialized' do
+ let(:num_labels) { 2 }
+ let(:resource) { create_list(:label, num_labels) }
+
+ it 'serializes the array of labels' do
+ expect(subject.size).to eq(num_labels)
+ end
+ end
+ end
+
+ describe '#represent_appearance' do
+ context 'when represents only appearance' do
+ let(:resource) { create(:label) }
+
+ subject { serializer.represent_appearance(resource) }
+
+ it 'serializes only attributes used for appearance' do
+ expect(subject.keys).to eq([:id, :title, :color, :text_color])
+ expect(subject[:id]).to eq(resource.id)
+ expect(subject[:title]).to eq(resource.title)
+ expect(subject[:color]).to eq(resource.color)
+ expect(subject[:text_color]).to eq(resource.text_color)
+ end
+ end
+ end
+end
diff --git a/spec/serializers/stage_entity_spec.rb b/spec/serializers/stage_entity_spec.rb
index 4ab40d08432..0412b2d7741 100644
--- a/spec/serializers/stage_entity_spec.rb
+++ b/spec/serializers/stage_entity_spec.rb
@@ -47,5 +47,13 @@ describe StageEntity do
it 'contains stage title' do
expect(subject[:title]).to eq 'test: passed'
end
+
+ context 'when the jobs should be grouped' do
+ let(:entity) { described_class.new(stage, request: request, grouped: true) }
+
+ it 'exposes the group key' do
+ expect(subject).to include :groups
+ end
+ end
end
end
diff --git a/spec/services/ci/play_build_service_spec.rb b/spec/services/ci/play_build_service_spec.rb
new file mode 100644
index 00000000000..d6f9fa42045
--- /dev/null
+++ b/spec/services/ci/play_build_service_spec.rb
@@ -0,0 +1,105 @@
+require 'spec_helper'
+
+describe Ci::PlayBuildService, '#execute', :services do
+ let(:user) { create(:user) }
+ let(:project) { create(:empty_project) }
+ let(:pipeline) { create(:ci_pipeline, project: project) }
+ let(:build) { create(:ci_build, :manual, pipeline: pipeline) }
+
+ let(:service) do
+ described_class.new(project, user)
+ end
+
+ context 'when project does not have repository yet' do
+ let(:project) { create(:empty_project) }
+
+ it 'allows user with master role to play build' do
+ project.add_master(user)
+
+ service.execute(build)
+
+ expect(build.reload).to be_pending
+ end
+
+ it 'does not allow user with developer role to play build' do
+ project.add_developer(user)
+
+ expect { service.execute(build) }
+ .to raise_error Gitlab::Access::AccessDeniedError
+ end
+ end
+
+ context 'when project has repository' do
+ let(:project) { create(:project) }
+
+ it 'allows user with developer role to play a build' do
+ project.add_developer(user)
+
+ service.execute(build)
+
+ expect(build.reload).to be_pending
+ end
+ end
+
+ context 'when build is a playable manual action' do
+ let(:build) { create(:ci_build, :manual, pipeline: pipeline) }
+
+ before do
+ project.add_master(user)
+ end
+
+ it 'enqueues the build' do
+ expect(service.execute(build)).to eq build
+ expect(build.reload).to be_pending
+ end
+
+ it 'reassignes build user correctly' do
+ service.execute(build)
+
+ expect(build.reload.user).to eq user
+ end
+ end
+
+ context 'when build is not a playable manual action' do
+ let(:build) { create(:ci_build, when: :manual, pipeline: pipeline) }
+
+ before do
+ project.add_master(user)
+ end
+
+ it 'duplicates the build' do
+ duplicate = service.execute(build)
+
+ expect(duplicate).not_to eq build
+ expect(duplicate).to be_pending
+ end
+
+ it 'assigns users correctly' do
+ duplicate = service.execute(build)
+
+ expect(build.user).not_to eq user
+ expect(duplicate.user).to eq user
+ end
+ end
+
+ context 'when build is not action' do
+ let(:build) { create(:ci_build, :success, pipeline: pipeline) }
+
+ it 'raises an error' do
+ expect { service.execute(build) }
+ .to raise_error Gitlab::Access::AccessDeniedError
+ end
+ end
+
+ context 'when user does not have ability to trigger action' do
+ before do
+ create(:protected_branch, :no_one_can_push,
+ name: build.ref, project: project)
+ end
+
+ it 'raises an error' do
+ expect { service.execute(build) }
+ .to raise_error Gitlab::Access::AccessDeniedError
+ end
+ end
+end
diff --git a/spec/services/ci/process_pipeline_service_spec.rb b/spec/services/ci/process_pipeline_service_spec.rb
index 245e19822f3..cf773866a6f 100644
--- a/spec/services/ci/process_pipeline_service_spec.rb
+++ b/spec/services/ci/process_pipeline_service_spec.rb
@@ -314,6 +314,13 @@ describe Ci::ProcessPipelineService, '#execute', :services do
end
context 'when pipeline is promoted sequentially up to the end' do
+ before do
+ # We are using create(:empty_project), and users has to be master in
+ # order to execute manual action when repository does not exist.
+ #
+ project.add_master(user)
+ end
+
it 'properly processes entire pipeline' do
process_pipeline
diff --git a/spec/services/ci/retry_pipeline_service_spec.rb b/spec/services/ci/retry_pipeline_service_spec.rb
index f1b2d3a4798..40e151545c9 100644
--- a/spec/services/ci/retry_pipeline_service_spec.rb
+++ b/spec/services/ci/retry_pipeline_service_spec.rb
@@ -7,7 +7,9 @@ describe Ci::RetryPipelineService, '#execute', :services do
let(:service) { described_class.new(project, user) }
context 'when user has ability to modify pipeline' do
- let(:user) { create(:admin) }
+ before do
+ project.add_master(user)
+ end
context 'when there are already retried jobs present' do
before do
@@ -227,6 +229,46 @@ describe Ci::RetryPipelineService, '#execute', :services do
end
end
+ context 'when user is not allowed to trigger manual action' do
+ before do
+ project.add_developer(user)
+ end
+
+ context 'when there is a failed manual action present' do
+ before do
+ create_build('test', :failed, 0)
+ create_build('deploy', :failed, 0, when: :manual)
+ create_build('verify', :canceled, 1)
+ end
+
+ it 'does not reprocess manual action' do
+ service.execute(pipeline)
+
+ expect(build('test')).to be_pending
+ expect(build('deploy')).to be_failed
+ expect(build('verify')).to be_created
+ expect(pipeline.reload).to be_running
+ end
+ end
+
+ context 'when there is a failed manual action in later stage' do
+ before do
+ create_build('test', :failed, 0)
+ create_build('deploy', :failed, 1, when: :manual)
+ create_build('verify', :canceled, 2)
+ end
+
+ it 'does not reprocess manual action' do
+ service.execute(pipeline)
+
+ expect(build('test')).to be_pending
+ expect(build('deploy')).to be_failed
+ expect(build('verify')).to be_created
+ expect(pipeline.reload).to be_running
+ end
+ end
+ end
+
def statuses
pipeline.reload.statuses
end
diff --git a/spec/services/ci/stop_environments_service_spec.rb b/spec/services/ci/stop_environments_service_spec.rb
index 32c72a9cf5e..98044ad232e 100644
--- a/spec/services/ci/stop_environments_service_spec.rb
+++ b/spec/services/ci/stop_environments_service_spec.rb
@@ -55,8 +55,22 @@ describe Ci::StopEnvironmentsService, services: true do
end
context 'when user does not have permission to stop environment' do
+ context 'when user has no access to manage deployments' do
+ before do
+ project.team << [user, :guest]
+ end
+
+ it 'does not stop environment' do
+ expect_environment_not_stopped_on('master')
+ end
+ end
+ end
+
+ context 'when branch for stop action is protected' do
before do
- project.team << [user, :guest]
+ project.add_developer(user)
+ create(:protected_branch, :no_one_can_push,
+ name: 'master', project: project)
end
it 'does not stop environment' do
diff --git a/spec/services/issuable/bulk_update_service_spec.rb b/spec/services/issuable/bulk_update_service_spec.rb
index 7a1ac027310..5b1639ca0d6 100644
--- a/spec/services/issuable/bulk_update_service_spec.rb
+++ b/spec/services/issuable/bulk_update_service_spec.rb
@@ -4,11 +4,12 @@ describe Issuable::BulkUpdateService, services: true do
let(:user) { create(:user) }
let(:project) { create(:empty_project, namespace: user.namespace) }
- def bulk_update(issues, extra_params = {})
+ def bulk_update(issuables, extra_params = {})
bulk_update_params = extra_params
- .reverse_merge(issuable_ids: Array(issues).map(&:id).join(','))
+ .reverse_merge(issuable_ids: Array(issuables).map(&:id).join(','))
- Issuable::BulkUpdateService.new(project, user, bulk_update_params).execute('issue')
+ type = Array(issuables).first.model_name.param_key
+ Issuable::BulkUpdateService.new(project, user, bulk_update_params).execute(type)
end
describe 'close issues' do
@@ -47,15 +48,15 @@ describe Issuable::BulkUpdateService, services: true do
end
end
- describe 'updating assignee' do
- let(:issue) { create(:issue, project: project, assignee: user) }
+ describe 'updating merge request assignee' do
+ let(:merge_request) { create(:merge_request, target_project: project, source_project: project, assignee: user) }
context 'when the new assignee ID is a valid user' do
it 'succeeds' do
new_assignee = create(:user)
project.team << [new_assignee, :developer]
- result = bulk_update(issue, assignee_id: new_assignee.id)
+ result = bulk_update(merge_request, assignee_id: new_assignee.id)
expect(result[:success]).to be_truthy
expect(result[:count]).to eq(1)
@@ -65,22 +66,59 @@ describe Issuable::BulkUpdateService, services: true do
assignee = create(:user)
project.team << [assignee, :developer]
- expect { bulk_update(issue, assignee_id: assignee.id) }
- .to change { issue.reload.assignee }.from(user).to(assignee)
+ expect { bulk_update(merge_request, assignee_id: assignee.id) }
+ .to change { merge_request.reload.assignee }.from(user).to(assignee)
end
end
context "when the new assignee ID is #{IssuableFinder::NONE}" do
it "unassigns the issues" do
- expect { bulk_update(issue, assignee_id: IssuableFinder::NONE) }
- .to change { issue.reload.assignee }.to(nil)
+ expect { bulk_update(merge_request, assignee_id: IssuableFinder::NONE) }
+ .to change { merge_request.reload.assignee }.to(nil)
end
end
context 'when the new assignee ID is not present' do
it 'does not unassign' do
- expect { bulk_update(issue, assignee_id: nil) }
- .not_to change { issue.reload.assignee }
+ expect { bulk_update(merge_request, assignee_id: nil) }
+ .not_to change { merge_request.reload.assignee }
+ end
+ end
+ end
+
+ describe 'updating issue assignee' do
+ let(:issue) { create(:issue, project: project, assignees: [user]) }
+
+ context 'when the new assignee ID is a valid user' do
+ it 'succeeds' do
+ new_assignee = create(:user)
+ project.team << [new_assignee, :developer]
+
+ result = bulk_update(issue, assignee_ids: [new_assignee.id])
+
+ expect(result[:success]).to be_truthy
+ expect(result[:count]).to eq(1)
+ end
+
+ it 'updates the assignee to the use ID passed' do
+ assignee = create(:user)
+ project.team << [assignee, :developer]
+ expect { bulk_update(issue, assignee_ids: [assignee.id]) }
+ .to change { issue.reload.assignees.first }.from(user).to(assignee)
+ end
+ end
+
+ context "when the new assignee ID is #{IssuableFinder::NONE}" do
+ it "unassigns the issues" do
+ expect { bulk_update(issue, assignee_ids: [IssuableFinder::NONE.to_s]) }
+ .to change { issue.reload.assignees.count }.from(1).to(0)
+ end
+ end
+
+ context 'when the new assignee ID is not present' do
+ it 'does not unassign' do
+ expect { bulk_update(issue, assignee_ids: []) }
+ .not_to change{ issue.reload.assignees }
end
end
end
diff --git a/spec/services/issues/close_service_spec.rb b/spec/services/issues/close_service_spec.rb
index 7a54373963e..51840531711 100644
--- a/spec/services/issues/close_service_spec.rb
+++ b/spec/services/issues/close_service_spec.rb
@@ -4,7 +4,7 @@ describe Issues::CloseService, services: true do
let(:user) { create(:user) }
let(:user2) { create(:user) }
let(:guest) { create(:user) }
- let(:issue) { create(:issue, assignee: user2) }
+ let(:issue) { create(:issue, assignees: [user2]) }
let(:project) { issue.project }
let!(:todo) { create(:todo, :assigned, user: user, project: project, target: issue, author: user2) }
diff --git a/spec/services/issues/create_service_spec.rb b/spec/services/issues/create_service_spec.rb
index 80bfb731550..01edc46496d 100644
--- a/spec/services/issues/create_service_spec.rb
+++ b/spec/services/issues/create_service_spec.rb
@@ -6,10 +6,10 @@ describe Issues::CreateService, services: true do
describe '#execute' do
let(:issue) { described_class.new(project, user, opts).execute }
+ let(:assignee) { create(:user) }
+ let(:milestone) { create(:milestone, project: project) }
context 'when params are valid' do
- let(:assignee) { create(:user) }
- let(:milestone) { create(:milestone, project: project) }
let(:labels) { create_pair(:label, project: project) }
before do
@@ -20,7 +20,7 @@ describe Issues::CreateService, services: true do
let(:opts) do
{ title: 'Awesome issue',
description: 'please fix',
- assignee_id: assignee.id,
+ assignee_ids: [assignee.id],
label_ids: labels.map(&:id),
milestone_id: milestone.id,
due_date: Date.tomorrow }
@@ -29,7 +29,7 @@ describe Issues::CreateService, services: true do
it 'creates the issue with the given params' do
expect(issue).to be_persisted
expect(issue.title).to eq('Awesome issue')
- expect(issue.assignee).to eq assignee
+ expect(issue.assignees).to eq [assignee]
expect(issue.labels).to match_array labels
expect(issue.milestone).to eq milestone
expect(issue.due_date).to eq Date.tomorrow
@@ -37,6 +37,7 @@ describe Issues::CreateService, services: true do
context 'when current user cannot admin issues in the project' do
let(:guest) { create(:user) }
+
before do
project.team << [guest, :guest]
end
@@ -47,7 +48,7 @@ describe Issues::CreateService, services: true do
expect(issue).to be_persisted
expect(issue.title).to eq('Awesome issue')
expect(issue.description).to eq('please fix')
- expect(issue.assignee).to be_nil
+ expect(issue.assignees).to be_empty
expect(issue.labels).to be_empty
expect(issue.milestone).to be_nil
expect(issue.due_date).to be_nil
@@ -136,10 +137,83 @@ describe Issues::CreateService, services: true do
end
end
- it_behaves_like 'issuable create service'
+ context 'issue create service' do
+ context 'assignees' do
+ before { project.team << [user, :master] }
+
+ it 'removes assignee when user id is invalid' do
+ opts = { title: 'Title', description: 'Description', assignee_ids: [-1] }
+
+ issue = described_class.new(project, user, opts).execute
+
+ expect(issue.assignees).to be_empty
+ end
+
+ it 'removes assignee when user id is 0' do
+ opts = { title: 'Title', description: 'Description', assignee_ids: [0] }
+
+ issue = described_class.new(project, user, opts).execute
+
+ expect(issue.assignees).to be_empty
+ end
+
+ it 'saves assignee when user id is valid' do
+ project.team << [assignee, :master]
+ opts = { title: 'Title', description: 'Description', assignee_ids: [assignee.id] }
+
+ issue = described_class.new(project, user, opts).execute
+
+ expect(issue.assignees).to eq([assignee])
+ end
+
+ context "when issuable feature is private" do
+ before do
+ project.project_feature.update(issues_access_level: ProjectFeature::PRIVATE,
+ merge_requests_access_level: ProjectFeature::PRIVATE)
+ end
+
+ levels = [Gitlab::VisibilityLevel::INTERNAL, Gitlab::VisibilityLevel::PUBLIC]
+
+ levels.each do |level|
+ it "removes not authorized assignee when project is #{Gitlab::VisibilityLevel.level_name(level)}" do
+ project.update(visibility_level: level)
+ opts = { title: 'Title', description: 'Description', assignee_ids: [assignee.id] }
+
+ issue = described_class.new(project, user, opts).execute
+
+ expect(issue.assignees).to be_empty
+ end
+ end
+ end
+ end
+ end
it_behaves_like 'new issuable record that supports slash commands'
+ context 'Slash commands' do
+ context 'with assignee and milestone in params and command' do
+ let(:opts) do
+ {
+ assignee_ids: [create(:user).id],
+ milestone_id: 1,
+ title: 'Title',
+ description: %(/assign @#{assignee.username}\n/milestone %"#{milestone.name}")
+ }
+ end
+
+ before do
+ project.team << [user, :master]
+ project.team << [assignee, :master]
+ end
+
+ it 'assigns and sets milestone to issuable from command' do
+ expect(issue).to be_persisted
+ expect(issue.assignees).to eq([assignee])
+ expect(issue.milestone).to eq(milestone)
+ end
+ end
+ end
+
context 'resolving discussions' do
let(:discussion) { create(:diff_note_on_merge_request).to_discussion }
let(:merge_request) { discussion.noteable }
diff --git a/spec/services/issues/update_service_spec.rb b/spec/services/issues/update_service_spec.rb
index 5b324f3c706..1954d8739f6 100644
--- a/spec/services/issues/update_service_spec.rb
+++ b/spec/services/issues/update_service_spec.rb
@@ -14,7 +14,7 @@ describe Issues::UpdateService, services: true do
let(:issue) do
create(:issue, title: 'Old title',
description: "for #{user2.to_reference}",
- assignee_id: user3.id,
+ assignee_ids: [user3.id],
project: project)
end
@@ -40,7 +40,7 @@ describe Issues::UpdateService, services: true do
{
title: 'New title',
description: 'Also please fix',
- assignee_id: user2.id,
+ assignee_ids: [user2.id],
state_event: 'close',
label_ids: [label.id],
due_date: Date.tomorrow
@@ -53,15 +53,15 @@ describe Issues::UpdateService, services: true do
expect(issue).to be_valid
expect(issue.title).to eq 'New title'
expect(issue.description).to eq 'Also please fix'
- expect(issue.assignee).to eq user2
+ expect(issue.assignees).to match_array([user2])
expect(issue).to be_closed
expect(issue.labels).to match_array [label]
expect(issue.due_date).to eq Date.tomorrow
end
it 'sorts issues as specified by parameters' do
- issue1 = create(:issue, project: project, assignee_id: user3.id)
- issue2 = create(:issue, project: project, assignee_id: user3.id)
+ issue1 = create(:issue, project: project, assignees: [user3])
+ issue2 = create(:issue, project: project, assignees: [user3])
[issue, issue1, issue2].each do |issue|
issue.move_to_end
@@ -87,7 +87,7 @@ describe Issues::UpdateService, services: true do
expect(issue).to be_valid
expect(issue.title).to eq 'New title'
expect(issue.description).to eq 'Also please fix'
- expect(issue.assignee).to eq user3
+ expect(issue.assignees).to match_array [user3]
expect(issue.labels).to be_empty
expect(issue.milestone).to be_nil
expect(issue.due_date).to be_nil
@@ -132,12 +132,23 @@ describe Issues::UpdateService, services: true do
end
end
+ context 'when description changed' do
+ it 'creates system note about description change' do
+ update_issue(description: 'Changed description')
+
+ note = find_note('changed the description')
+
+ expect(note).not_to be_nil
+ expect(note.note).to eq('changed the description')
+ end
+ end
+
context 'when issue turns confidential' do
let(:opts) do
{
title: 'New title',
description: 'Also please fix',
- assignee_id: user2.id,
+ assignee_ids: [user2],
state_event: 'close',
label_ids: [label.id],
confidential: true
@@ -163,12 +174,12 @@ describe Issues::UpdateService, services: true do
it 'does not update assignee_id with unauthorized users' do
project.update(visibility_level: Gitlab::VisibilityLevel::PUBLIC)
update_issue(confidential: true)
- non_member = create(:user)
- original_assignee = issue.assignee
+ non_member = create(:user)
+ original_assignees = issue.assignees
- update_issue(assignee_id: non_member.id)
+ update_issue(assignee_ids: [non_member.id])
- expect(issue.reload.assignee_id).to eq(original_assignee.id)
+ expect(issue.reload.assignees).to eq(original_assignees)
end
end
@@ -205,7 +216,7 @@ describe Issues::UpdateService, services: true do
context 'when is reassigned' do
before do
- update_issue(assignee: user2)
+ update_issue(assignees: [user2])
end
it 'marks previous assignee todos as done' do
@@ -408,6 +419,41 @@ describe Issues::UpdateService, services: true do
end
end
+ context 'updating asssignee_id' do
+ it 'does not update assignee when assignee_id is invalid' do
+ update_issue(assignee_ids: [-1])
+
+ expect(issue.reload.assignees).to eq([user3])
+ end
+
+ it 'unassigns assignee when user id is 0' do
+ update_issue(assignee_ids: [0])
+
+ expect(issue.reload.assignees).to be_empty
+ end
+
+ it 'does not update assignee_id when user cannot read issue' do
+ update_issue(assignee_ids: [create(:user).id])
+
+ expect(issue.reload.assignees).to eq([user3])
+ end
+
+ context "when issuable feature is private" do
+ levels = [Gitlab::VisibilityLevel::INTERNAL, Gitlab::VisibilityLevel::PUBLIC]
+
+ levels.each do |level|
+ it "does not update with unauthorized assignee when project is #{Gitlab::VisibilityLevel.level_name(level)}" do
+ assignee = create(:user)
+ project.update(visibility_level: level)
+ feature_visibility_attr = :"#{issue.model_name.plural}_access_level"
+ project.project_feature.update_attribute(feature_visibility_attr, ProjectFeature::PRIVATE)
+
+ expect{ update_issue(assignee_ids: [assignee.id]) }.not_to change{ issue.assignees }
+ end
+ end
+ end
+ end
+
context 'updating mentions' do
let(:mentionable) { issue }
include_examples 'updating mentions', Issues::UpdateService
diff --git a/spec/services/members/authorized_destroy_service_spec.rb b/spec/services/members/authorized_destroy_service_spec.rb
index 3b35a3b8e3a..ab440d18e9f 100644
--- a/spec/services/members/authorized_destroy_service_spec.rb
+++ b/spec/services/members/authorized_destroy_service_spec.rb
@@ -14,8 +14,8 @@ describe Members::AuthorizedDestroyService, services: true do
it "unassigns issues and merge requests" do
group.add_developer(member_user)
- issue = create :issue, project: group_project, assignee: member_user
- create :issue, assignee: member_user
+ issue = create :issue, project: group_project, assignees: [member_user]
+ create :issue, assignees: [member_user]
merge_request = create :merge_request, target_project: group_project, source_project: group_project, assignee: member_user
create :merge_request, target_project: project, source_project: project, assignee: member_user
@@ -33,7 +33,7 @@ describe Members::AuthorizedDestroyService, services: true do
it "unassigns issues and merge requests" do
project.team << [member_user, :developer]
- create :issue, project: project, assignee: member_user
+ create :issue, project: project, assignees: [member_user]
create :merge_request, target_project: project, source_project: project, assignee: member_user
member = project.members.find_by(user_id: member_user.id)
diff --git a/spec/services/merge_requests/assign_issues_service_spec.rb b/spec/services/merge_requests/assign_issues_service_spec.rb
index fe75757dd29..d3556020d4d 100644
--- a/spec/services/merge_requests/assign_issues_service_spec.rb
+++ b/spec/services/merge_requests/assign_issues_service_spec.rb
@@ -15,14 +15,14 @@ describe MergeRequests::AssignIssuesService, services: true do
expect(service.assignable_issues.map(&:id)).to include(issue.id)
end
- it 'ignores issues already assigned to any user' do
- issue.update!(assignee: create(:user))
+ it 'ignores issues the user cannot update assignee on' do
+ project.team.truncate
expect(service.assignable_issues).to be_empty
end
- it 'ignores issues the user cannot update assignee on' do
- project.team.truncate
+ it 'ignores issues already assigned to any user' do
+ issue.assignees = [create(:user)]
expect(service.assignable_issues).to be_empty
end
@@ -44,7 +44,7 @@ describe MergeRequests::AssignIssuesService, services: true do
end
it 'assigns these to the merge request owner' do
- expect { service.execute }.to change { issue.reload.assignee }.to(user)
+ expect { service.execute }.to change { issue.assignees.first }.to(user)
end
it 'ignores external issues' do
diff --git a/spec/services/merge_requests/create_service_spec.rb b/spec/services/merge_requests/create_service_spec.rb
index 0e16c7cc94b..ace82380cc9 100644
--- a/spec/services/merge_requests/create_service_spec.rb
+++ b/spec/services/merge_requests/create_service_spec.rb
@@ -84,7 +84,87 @@ describe MergeRequests::CreateService, services: true do
end
end
- it_behaves_like 'issuable create service'
+ context 'Slash commands' do
+ context 'with assignee and milestone in params and command' do
+ let(:merge_request) { described_class.new(project, user, opts).execute }
+ let(:milestone) { create(:milestone, project: project) }
+
+ let(:opts) do
+ {
+ assignee_id: create(:user).id,
+ milestone_id: 1,
+ title: 'Title',
+ description: %(/assign @#{assignee.username}\n/milestone %"#{milestone.name}"),
+ source_branch: 'feature',
+ target_branch: 'master'
+ }
+ end
+
+ before do
+ project.team << [user, :master]
+ project.team << [assignee, :master]
+ end
+
+ it 'assigns and sets milestone to issuable from command' do
+ expect(merge_request).to be_persisted
+ expect(merge_request.assignee).to eq(assignee)
+ expect(merge_request.milestone).to eq(milestone)
+ end
+ end
+ end
+
+ context 'merge request create service' do
+ context 'asssignee_id' do
+ let(:assignee) { create(:user) }
+
+ before { project.team << [user, :master] }
+
+ it 'removes assignee_id when user id is invalid' do
+ opts = { title: 'Title', description: 'Description', assignee_id: -1 }
+
+ merge_request = described_class.new(project, user, opts).execute
+
+ expect(merge_request.assignee_id).to be_nil
+ end
+
+ it 'removes assignee_id when user id is 0' do
+ opts = { title: 'Title', description: 'Description', assignee_id: 0 }
+
+ merge_request = described_class.new(project, user, opts).execute
+
+ expect(merge_request.assignee_id).to be_nil
+ end
+
+ it 'saves assignee when user id is valid' do
+ project.team << [assignee, :master]
+ opts = { title: 'Title', description: 'Description', assignee_id: assignee.id }
+
+ merge_request = described_class.new(project, user, opts).execute
+
+ expect(merge_request.assignee).to eq(assignee)
+ end
+
+ context "when issuable feature is private" do
+ before do
+ project.project_feature.update(issues_access_level: ProjectFeature::PRIVATE,
+ merge_requests_access_level: ProjectFeature::PRIVATE)
+ end
+
+ levels = [Gitlab::VisibilityLevel::INTERNAL, Gitlab::VisibilityLevel::PUBLIC]
+
+ levels.each do |level|
+ it "removes not authorized assignee when project is #{Gitlab::VisibilityLevel.level_name(level)}" do
+ project.update(visibility_level: level)
+ opts = { title: 'Title', description: 'Description', assignee_id: assignee.id }
+
+ merge_request = described_class.new(project, user, opts).execute
+
+ expect(merge_request.assignee_id).to be_nil
+ end
+ end
+ end
+ end
+ end
context 'while saving references to issues that the created merge request closes' do
let(:first_issue) { create(:issue, project: project) }
diff --git a/spec/services/merge_requests/update_service_spec.rb b/spec/services/merge_requests/update_service_spec.rb
index f2ca1e6fcbd..31487c0f794 100644
--- a/spec/services/merge_requests/update_service_spec.rb
+++ b/spec/services/merge_requests/update_service_spec.rb
@@ -102,6 +102,13 @@ describe MergeRequests::UpdateService, services: true do
expect(note.note).to eq 'changed title from **{-Old-} title** to **{+New+} title**'
end
+ it 'creates system note about description change' do
+ note = find_note('changed the description')
+
+ expect(note).not_to be_nil
+ expect(note.note).to eq('changed the description')
+ end
+
it 'creates system note about branch change' do
note = find_note('changed target')
@@ -423,6 +430,54 @@ describe MergeRequests::UpdateService, services: true do
end
end
+ context 'updating asssignee_id' do
+ it 'does not update assignee when assignee_id is invalid' do
+ merge_request.update(assignee_id: user.id)
+
+ update_merge_request(assignee_id: -1)
+
+ expect(merge_request.reload.assignee).to eq(user)
+ end
+
+ it 'unassigns assignee when user id is 0' do
+ merge_request.update(assignee_id: user.id)
+
+ update_merge_request(assignee_id: 0)
+
+ expect(merge_request.assignee_id).to be_nil
+ end
+
+ it 'saves assignee when user id is valid' do
+ update_merge_request(assignee_id: user.id)
+
+ expect(merge_request.assignee_id).to eq(user.id)
+ end
+
+ it 'does not update assignee_id when user cannot read issue' do
+ non_member = create(:user)
+ original_assignee = merge_request.assignee
+
+ update_merge_request(assignee_id: non_member.id)
+
+ expect(merge_request.assignee_id).to eq(original_assignee.id)
+ end
+
+ context "when issuable feature is private" do
+ levels = [Gitlab::VisibilityLevel::INTERNAL, Gitlab::VisibilityLevel::PUBLIC]
+
+ levels.each do |level|
+ it "does not update with unauthorized assignee when project is #{Gitlab::VisibilityLevel.level_name(level)}" do
+ assignee = create(:user)
+ project.update(visibility_level: level)
+ feature_visibility_attr = :"#{merge_request.model_name.plural}_access_level"
+ project.project_feature.update_attribute(feature_visibility_attr, ProjectFeature::PRIVATE)
+
+ expect{ update_merge_request(assignee_id: assignee) }.not_to change{ merge_request.assignee }
+ end
+ end
+ end
+ end
+
include_examples 'issuable update service' do
let(:open_issuable) { merge_request }
let(:closed_issuable) { create(:closed_merge_request, source_project: project) }
diff --git a/spec/services/notes/slash_commands_service_spec.rb b/spec/services/notes/slash_commands_service_spec.rb
index 1a64c8bbf00..c9954dc3603 100644
--- a/spec/services/notes/slash_commands_service_spec.rb
+++ b/spec/services/notes/slash_commands_service_spec.rb
@@ -66,7 +66,7 @@ describe Notes::SlashCommandsService, services: true do
expect(content).to eq ''
expect(note.noteable).to be_closed
expect(note.noteable.labels).to match_array(labels)
- expect(note.noteable.assignee).to eq(assignee)
+ expect(note.noteable.assignees).to eq([assignee])
expect(note.noteable.milestone).to eq(milestone)
end
end
@@ -113,7 +113,7 @@ describe Notes::SlashCommandsService, services: true do
expect(content).to eq "HELLO\nWORLD"
expect(note.noteable).to be_closed
expect(note.noteable.labels).to match_array(labels)
- expect(note.noteable.assignee).to eq(assignee)
+ expect(note.noteable.assignees).to eq([assignee])
expect(note.noteable.milestone).to eq(milestone)
end
end
@@ -220,4 +220,31 @@ describe Notes::SlashCommandsService, services: true do
let(:note) { build(:note_on_commit, project: project) }
end
end
+
+ context 'CE restriction for issue assignees' do
+ describe '/assign' do
+ let(:project) { create(:empty_project) }
+ let(:master) { create(:user).tap { |u| project.team << [u, :master] } }
+ let(:assignee) { create(:user) }
+ let(:master) { create(:user) }
+ let(:service) { described_class.new(project, master) }
+ let(:note) { create(:note_on_issue, note: note_text, project: project) }
+
+ let(:note_text) do
+ %(/assign @#{assignee.username} @#{master.username}\n")
+ end
+
+ before do
+ project.team << [master, :master]
+ project.team << [assignee, :master]
+ end
+
+ it 'adds only one assignee from the list' do
+ _, command_params = service.extract_commands(note)
+ service.execute(command_params, note)
+
+ expect(note.noteable.assignees.count).to eq(1)
+ end
+ end
+ end
end
diff --git a/spec/services/notification_service_spec.rb b/spec/services/notification_service_spec.rb
index 989fd90cda9..74f96b97909 100644
--- a/spec/services/notification_service_spec.rb
+++ b/spec/services/notification_service_spec.rb
@@ -4,6 +4,7 @@ describe NotificationService, services: true do
include EmailHelpers
let(:notification) { NotificationService.new }
+ let(:assignee) { create(:user) }
around(:each) do |example|
perform_enqueued_jobs do
@@ -52,7 +53,11 @@ describe NotificationService, services: true do
shared_examples 'participating by assignee notification' do
it 'emails the participant' do
- issuable.update_attribute(:assignee, participant)
+ if issuable.is_a?(Issue)
+ issuable.assignees << participant
+ else
+ issuable.update_attribute(:assignee, participant)
+ end
notification_trigger
@@ -103,14 +108,14 @@ describe NotificationService, services: true do
describe 'Notes' do
context 'issue note' do
let(:project) { create(:empty_project, :private) }
- let(:issue) { create(:issue, project: project, assignee: create(:user)) }
- let(:mentioned_issue) { create(:issue, assignee: issue.assignee) }
+ let(:issue) { create(:issue, project: project, assignees: [assignee]) }
+ let(:mentioned_issue) { create(:issue, assignees: issue.assignees) }
let(:note) { create(:note_on_issue, noteable: issue, project_id: issue.project_id, note: '@mention referenced, @outsider also') }
before do
build_team(note.project)
project.add_master(issue.author)
- project.add_master(issue.assignee)
+ project.add_master(assignee)
project.add_master(note.author)
create(:note_on_issue, noteable: issue, project_id: issue.project_id, note: '@subscribed_participant cc this guy')
update_custom_notification(:new_note, @u_guest_custom, resource: project)
@@ -130,7 +135,7 @@ describe NotificationService, services: true do
should_email(@u_watcher)
should_email(note.noteable.author)
- should_email(note.noteable.assignee)
+ should_email(note.noteable.assignees.first)
should_email(@u_custom_global)
should_email(@u_mentioned)
should_email(@subscriber)
@@ -196,7 +201,7 @@ describe NotificationService, services: true do
notification.new_note(note)
should_email(note.noteable.author)
- should_email(note.noteable.assignee)
+ should_email(note.noteable.assignees.first)
should_email(@u_mentioned)
should_email(@u_custom_global)
should_not_email(@u_guest_custom)
@@ -218,7 +223,7 @@ describe NotificationService, services: true do
let(:member) { create(:user) }
let(:guest) { create(:user) }
let(:admin) { create(:admin) }
- let(:confidential_issue) { create(:issue, :confidential, project: project, author: author, assignee: assignee) }
+ let(:confidential_issue) { create(:issue, :confidential, project: project, author: author, assignees: [assignee]) }
let(:note) { create(:note_on_issue, noteable: confidential_issue, project: project, note: "#{author.to_reference} #{assignee.to_reference} #{non_member.to_reference} #{member.to_reference} #{admin.to_reference}") }
let(:guest_watcher) { create_user_with_notification(:watch, "guest-watcher-confidential") }
@@ -244,8 +249,8 @@ describe NotificationService, services: true do
context 'issue note mention' do
let(:project) { create(:empty_project, :public) }
- let(:issue) { create(:issue, project: project, assignee: create(:user)) }
- let(:mentioned_issue) { create(:issue, assignee: issue.assignee) }
+ let(:issue) { create(:issue, project: project, assignees: [assignee]) }
+ let(:mentioned_issue) { create(:issue, assignees: issue.assignees) }
let(:note) { create(:note_on_issue, noteable: issue, project_id: issue.project_id, note: '@all mentioned') }
before do
@@ -269,7 +274,7 @@ describe NotificationService, services: true do
should_email(@u_guest_watcher)
should_email(note.noteable.author)
- should_email(note.noteable.assignee)
+ should_email(note.noteable.assignees.first)
should_not_email(note.author)
should_email(@u_mentioned)
should_not_email(@u_disabled)
@@ -449,7 +454,7 @@ describe NotificationService, services: true do
let(:group) { create(:group) }
let(:project) { create(:empty_project, :public, namespace: group) }
let(:another_project) { create(:empty_project, :public, namespace: group) }
- let(:issue) { create :issue, project: project, assignee: create(:user), description: 'cc @participant' }
+ let(:issue) { create :issue, project: project, assignees: [assignee], description: 'cc @participant' }
before do
build_team(issue.project)
@@ -465,7 +470,7 @@ describe NotificationService, services: true do
it do
notification.new_issue(issue, @u_disabled)
- should_email(issue.assignee)
+ should_email(assignee)
should_email(@u_watcher)
should_email(@u_guest_watcher)
should_email(@u_guest_custom)
@@ -480,10 +485,10 @@ describe NotificationService, services: true do
end
it do
- create_global_setting_for(issue.assignee, :mention)
+ create_global_setting_for(issue.assignees.first, :mention)
notification.new_issue(issue, @u_disabled)
- should_not_email(issue.assignee)
+ should_not_email(issue.assignees.first)
end
it "emails the author if they've opted into notifications about their activity" do
@@ -528,7 +533,7 @@ describe NotificationService, services: true do
let(:member) { create(:user) }
let(:guest) { create(:user) }
let(:admin) { create(:admin) }
- let(:confidential_issue) { create(:issue, :confidential, project: project, title: 'Confidential issue', author: author, assignee: assignee) }
+ let(:confidential_issue) { create(:issue, :confidential, project: project, title: 'Confidential issue', author: author, assignees: [assignee]) }
it "emails subscribers of the issue's labels that can read the issue" do
project.add_developer(member)
@@ -572,9 +577,9 @@ describe NotificationService, services: true do
end
it 'emails new assignee' do
- notification.reassigned_issue(issue, @u_disabled)
+ notification.reassigned_issue(issue, @u_disabled, [assignee])
- should_email(issue.assignee)
+ should_email(issue.assignees.first)
should_email(@u_watcher)
should_email(@u_guest_watcher)
should_email(@u_guest_custom)
@@ -588,9 +593,8 @@ describe NotificationService, services: true do
end
it 'emails previous assignee even if he has the "on mention" notif level' do
- issue.update_attribute(:assignee, @u_mentioned)
- issue.update_attributes(assignee: @u_watcher)
- notification.reassigned_issue(issue, @u_disabled)
+ issue.assignees = [@u_mentioned]
+ notification.reassigned_issue(issue, @u_disabled, [@u_watcher])
should_email(@u_mentioned)
should_email(@u_watcher)
@@ -606,11 +610,11 @@ describe NotificationService, services: true do
end
it 'emails new assignee even if he has the "on mention" notif level' do
- issue.update_attributes(assignee: @u_mentioned)
- notification.reassigned_issue(issue, @u_disabled)
+ issue.assignees = [@u_mentioned]
+ notification.reassigned_issue(issue, @u_disabled, [@u_mentioned])
- expect(issue.assignee).to be @u_mentioned
- should_email(issue.assignee)
+ expect(issue.assignees.first).to be @u_mentioned
+ should_email(issue.assignees.first)
should_email(@u_watcher)
should_email(@u_guest_watcher)
should_email(@u_guest_custom)
@@ -624,11 +628,11 @@ describe NotificationService, services: true do
end
it 'emails new assignee' do
- issue.update_attribute(:assignee, @u_mentioned)
- notification.reassigned_issue(issue, @u_disabled)
+ issue.assignees = [@u_mentioned]
+ notification.reassigned_issue(issue, @u_disabled, [@u_mentioned])
- expect(issue.assignee).to be @u_mentioned
- should_email(issue.assignee)
+ expect(issue.assignees.first).to be @u_mentioned
+ should_email(issue.assignees.first)
should_email(@u_watcher)
should_email(@u_guest_watcher)
should_email(@u_guest_custom)
@@ -642,17 +646,17 @@ describe NotificationService, services: true do
end
it 'does not email new assignee if they are the current user' do
- issue.update_attribute(:assignee, @u_mentioned)
- notification.reassigned_issue(issue, @u_mentioned)
+ issue.assignees = [@u_mentioned]
+ notification.reassigned_issue(issue, @u_mentioned, [@u_mentioned])
- expect(issue.assignee).to be @u_mentioned
+ expect(issue.assignees.first).to be @u_mentioned
should_email(@u_watcher)
should_email(@u_guest_watcher)
should_email(@u_guest_custom)
should_email(@u_participant_mentioned)
should_email(@subscriber)
should_email(@u_custom_global)
- should_not_email(issue.assignee)
+ should_not_email(issue.assignees.first)
should_not_email(@unsubscriber)
should_not_email(@u_participating)
should_not_email(@u_disabled)
@@ -662,7 +666,7 @@ describe NotificationService, services: true do
it_behaves_like 'participating notifications' do
let(:participant) { create(:user, username: 'user-participant') }
let(:issuable) { issue }
- let(:notification_trigger) { notification.reassigned_issue(issue, @u_disabled) }
+ let(:notification_trigger) { notification.reassigned_issue(issue, @u_disabled, [assignee]) }
end
end
@@ -705,7 +709,7 @@ describe NotificationService, services: true do
it "doesn't send email to anyone but subscribers of the given labels" do
notification.relabeled_issue(issue, [group_label_2, label_2], @u_disabled)
- should_not_email(issue.assignee)
+ should_not_email(issue.assignees.first)
should_not_email(issue.author)
should_not_email(@u_watcher)
should_not_email(@u_guest_watcher)
@@ -729,7 +733,7 @@ describe NotificationService, services: true do
let(:member) { create(:user) }
let(:guest) { create(:user) }
let(:admin) { create(:admin) }
- let(:confidential_issue) { create(:issue, :confidential, project: project, title: 'Confidential issue', author: author, assignee: assignee) }
+ let(:confidential_issue) { create(:issue, :confidential, project: project, title: 'Confidential issue', author: author, assignees: [assignee]) }
let!(:label_1) { create(:label, project: project, issues: [confidential_issue]) }
let!(:label_2) { create(:label, project: project) }
@@ -767,7 +771,7 @@ describe NotificationService, services: true do
it 'sends email to issue assignee and issue author' do
notification.close_issue(issue, @u_disabled)
- should_email(issue.assignee)
+ should_email(issue.assignees.first)
should_email(issue.author)
should_email(@u_watcher)
should_email(@u_guest_watcher)
@@ -798,7 +802,7 @@ describe NotificationService, services: true do
it 'sends email to issue notification recipients' do
notification.reopen_issue(issue, @u_disabled)
- should_email(issue.assignee)
+ should_email(issue.assignees.first)
should_email(issue.author)
should_email(@u_watcher)
should_email(@u_guest_watcher)
@@ -826,7 +830,7 @@ describe NotificationService, services: true do
it 'sends email to issue notification recipients' do
notification.issue_moved(issue, new_issue, @u_disabled)
- should_email(issue.assignee)
+ should_email(issue.assignees.first)
should_email(issue.author)
should_email(@u_watcher)
should_email(@u_guest_watcher)
diff --git a/spec/services/projects/autocomplete_service_spec.rb b/spec/services/projects/autocomplete_service_spec.rb
index 7916c2d957c..c198c3eedfc 100644
--- a/spec/services/projects/autocomplete_service_spec.rb
+++ b/spec/services/projects/autocomplete_service_spec.rb
@@ -11,7 +11,7 @@ describe Projects::AutocompleteService, services: true do
let(:project) { create(:empty_project, :public) }
let!(:issue) { create(:issue, project: project, title: 'Issue 1') }
let!(:security_issue_1) { create(:issue, :confidential, project: project, title: 'Security issue 1', author: author) }
- let!(:security_issue_2) { create(:issue, :confidential, title: 'Security issue 2', project: project, assignee: assignee) }
+ let!(:security_issue_2) { create(:issue, :confidential, title: 'Security issue 2', project: project, assignees: [assignee]) }
it 'does not list project confidential issues for guests' do
autocomplete = described_class.new(project, nil)
diff --git a/spec/services/projects/propagate_service_template_spec.rb b/spec/services/projects/propagate_service_template_spec.rb
new file mode 100644
index 00000000000..90eff3bbc1e
--- /dev/null
+++ b/spec/services/projects/propagate_service_template_spec.rb
@@ -0,0 +1,103 @@
+require 'spec_helper'
+
+describe Projects::PropagateServiceTemplate, services: true do
+ describe '.propagate' do
+ let!(:service_template) do
+ PushoverService.create(
+ template: true,
+ active: true,
+ properties: {
+ device: 'MyDevice',
+ sound: 'mic',
+ priority: 4,
+ user_key: 'asdf',
+ api_key: '123456789'
+ })
+ end
+
+ let!(:project) { create(:empty_project) }
+
+ it 'creates services for projects' do
+ expect(project.pushover_service).to be_nil
+
+ described_class.propagate(service_template)
+
+ expect(project.reload.pushover_service).to be_present
+ end
+
+ it 'creates services for a project that has another service' do
+ BambooService.create(
+ template: true,
+ active: true,
+ project: project,
+ properties: {
+ bamboo_url: 'http://gitlab.com',
+ username: 'mic',
+ password: "password",
+ build_key: 'build'
+ }
+ )
+
+ expect(project.pushover_service).to be_nil
+
+ described_class.propagate(service_template)
+
+ expect(project.reload.pushover_service).to be_present
+ end
+
+ it 'does not create the service if it exists already' do
+ other_service = BambooService.create(
+ template: true,
+ active: true,
+ properties: {
+ bamboo_url: 'http://gitlab.com',
+ username: 'mic',
+ password: "password",
+ build_key: 'build'
+ }
+ )
+
+ Service.build_from_template(project.id, service_template).save!
+ Service.build_from_template(project.id, other_service).save!
+
+ expect { described_class.propagate(service_template) }.
+ not_to change { Service.count }
+ end
+
+ it 'creates the service containing the template attributes' do
+ described_class.propagate(service_template)
+
+ expect(project.pushover_service.properties).to eq(service_template.properties)
+ end
+
+ describe 'bulk update' do
+ it 'creates services for all projects' do
+ project_total = 5
+ stub_const 'Projects::PropagateServiceTemplate::BATCH_SIZE', 3
+
+ project_total.times { create(:empty_project) }
+
+ expect { described_class.propagate(service_template) }.
+ to change { Service.count }.by(project_total + 1)
+ end
+ end
+
+ describe 'external tracker' do
+ it 'updates the project external tracker' do
+ service_template.update!(category: 'issue_tracker', default: false)
+
+ expect { described_class.propagate(service_template) }.
+ to change { project.reload.has_external_issue_tracker }.to(true)
+ end
+ end
+
+ describe 'external wiki' do
+ it 'updates the project external tracker' do
+ service_template.update!(type: 'ExternalWikiService')
+
+ expect { described_class.propagate(service_template) }.
+ to change { project.reload.has_external_wiki }.to(true)
+ end
+ end
+ end
+end
diff --git a/spec/services/slash_commands/interpret_service_spec.rb b/spec/services/slash_commands/interpret_service_spec.rb
index 46cfac4a128..e5e400ee281 100644
--- a/spec/services/slash_commands/interpret_service_spec.rb
+++ b/spec/services/slash_commands/interpret_service_spec.rb
@@ -3,6 +3,7 @@ require 'spec_helper'
describe SlashCommands::InterpretService, services: true do
let(:project) { create(:empty_project, :public) }
let(:developer) { create(:user) }
+ let(:developer2) { create(:user) }
let(:issue) { create(:issue, project: project) }
let(:milestone) { create(:milestone, project: project, title: '9.10') }
let(:inprogress) { create(:label, project: project, title: 'In Progress') }
@@ -42,23 +43,6 @@ describe SlashCommands::InterpretService, services: true do
end
end
- shared_examples 'assign command' do
- it 'fetches assignee and populates assignee_id if content contains /assign' do
- _, updates = service.execute(content, issuable)
-
- expect(updates).to eq(assignee_id: developer.id)
- end
- end
-
- shared_examples 'unassign command' do
- it 'populates assignee_id: nil if content contains /unassign' do
- issuable.update!(assignee_id: developer.id)
- _, updates = service.execute(content, issuable)
-
- expect(updates).to eq(assignee_id: nil)
- end
- end
-
shared_examples 'milestone command' do
it 'fetches milestone and populates milestone_id if content contains /milestone' do
milestone # populate the milestone
@@ -371,14 +355,46 @@ describe SlashCommands::InterpretService, services: true do
let(:issuable) { issue }
end
- it_behaves_like 'assign command' do
+ context 'assign command' do
let(:content) { "/assign @#{developer.username}" }
- let(:issuable) { issue }
+
+ context 'Issue' do
+ it 'fetches assignee and populates assignee_id if content contains /assign' do
+ _, updates = service.execute(content, issue)
+
+ expect(updates).to eq(assignee_ids: [developer.id])
+ end
+ end
+
+ context 'Merge Request' do
+ it 'fetches assignee and populates assignee_id if content contains /assign' do
+ _, updates = service.execute(content, merge_request)
+
+ expect(updates).to eq(assignee_id: developer.id)
+ end
+ end
end
- it_behaves_like 'assign command' do
- let(:content) { "/assign @#{developer.username}" }
- let(:issuable) { merge_request }
+ context 'assign command with multiple assignees' do
+ let(:content) { "/assign @#{developer.username} @#{developer2.username}" }
+
+ before{ project.team << [developer2, :developer] }
+
+ context 'Issue' do
+ it 'fetches assignee and populates assignee_id if content contains /assign' do
+ _, updates = service.execute(content, issue)
+
+ expect(updates[:assignee_ids]).to match_array([developer.id, developer2.id])
+ end
+ end
+
+ context 'Merge Request' do
+ it 'fetches assignee and populates assignee_id if content contains /assign' do
+ _, updates = service.execute(content, merge_request)
+
+ expect(updates).to eq(assignee_id: developer.id)
+ end
+ end
end
it_behaves_like 'empty command' do
@@ -391,14 +407,26 @@ describe SlashCommands::InterpretService, services: true do
let(:issuable) { issue }
end
- it_behaves_like 'unassign command' do
+ context 'unassign command' do
let(:content) { '/unassign' }
- let(:issuable) { issue }
- end
- it_behaves_like 'unassign command' do
- let(:content) { '/unassign' }
- let(:issuable) { merge_request }
+ context 'Issue' do
+ it 'populates assignee_ids: [] if content contains /unassign' do
+ issue.update(assignee_ids: [developer.id])
+ _, updates = service.execute(content, issue)
+
+ expect(updates).to eq(assignee_ids: [])
+ end
+ end
+
+ context 'Merge Request' do
+ it 'populates assignee_id: nil if content contains /unassign' do
+ merge_request.update(assignee_id: developer.id)
+ _, updates = service.execute(content, merge_request)
+
+ expect(updates).to eq(assignee_id: nil)
+ end
+ end
end
it_behaves_like 'milestone command' do
@@ -846,7 +874,7 @@ describe SlashCommands::InterpretService, services: true do
describe 'unassign command' do
let(:content) { '/unassign' }
- let(:issue) { create(:issue, project: project, assignee: developer) }
+ let(:issue) { create(:issue, project: project, assignees: [developer]) }
it 'includes current assignee reference' do
_, explanations = service.explain(content, issue)
diff --git a/spec/services/system_note_service_spec.rb b/spec/services/system_note_service_spec.rb
index 75d7caf2508..516566eddef 100644
--- a/spec/services/system_note_service_spec.rb
+++ b/spec/services/system_note_service_spec.rb
@@ -6,6 +6,7 @@ describe SystemNoteService, services: true do
let(:project) { create(:empty_project) }
let(:author) { create(:user) }
let(:noteable) { create(:issue, project: project) }
+ let(:issue) { noteable }
shared_examples_for 'a system note' do
let(:expected_noteable) { noteable }
@@ -155,6 +156,52 @@ describe SystemNoteService, services: true do
end
end
+ describe '.change_issue_assignees' do
+ subject { described_class.change_issue_assignees(noteable, project, author, [assignee]) }
+
+ let(:assignee) { create(:user) }
+ let(:assignee1) { create(:user) }
+ let(:assignee2) { create(:user) }
+ let(:assignee3) { create(:user) }
+
+ it_behaves_like 'a system note' do
+ let(:action) { 'assignee' }
+ end
+
+ def build_note(old_assignees, new_assignees)
+ issue.assignees = new_assignees
+ described_class.change_issue_assignees(issue, project, author, old_assignees).note
+ end
+
+ it 'builds a correct phrase when an assignee is added to a non-assigned issue' do
+ expect(build_note([], [assignee1])).to eq "assigned to @#{assignee1.username}"
+ end
+
+ it 'builds a correct phrase when assignee removed' do
+ expect(build_note([assignee1], [])).to eq 'removed all assignees'
+ end
+
+ it 'builds a correct phrase when assignees changed' do
+ expect(build_note([assignee1], [assignee2])).to eq \
+ "assigned to @#{assignee2.username} and unassigned @#{assignee1.username}"
+ end
+
+ it 'builds a correct phrase when three assignees removed and one added' do
+ expect(build_note([assignee, assignee1, assignee2], [assignee3])).to eq \
+ "assigned to @#{assignee3.username} and unassigned @#{assignee.username}, @#{assignee1.username}, and @#{assignee2.username}"
+ end
+
+ it 'builds a correct phrase when one assignee changed from a set' do
+ expect(build_note([assignee, assignee1], [assignee, assignee2])).to eq \
+ "assigned to @#{assignee2.username} and unassigned @#{assignee1.username}"
+ end
+
+ it 'builds a correct phrase when one assignee removed from a set' do
+ expect(build_note([assignee, assignee1, assignee2], [assignee, assignee1])).to eq \
+ "unassigned @#{assignee2.username}"
+ end
+ end
+
describe '.change_label' do
subject { described_class.change_label(noteable, project, author, added, removed) }
@@ -292,6 +339,20 @@ describe SystemNoteService, services: true do
end
end
+ describe '.change_description' do
+ subject { described_class.change_description(noteable, project, author) }
+
+ context 'when noteable responds to `description`' do
+ it_behaves_like 'a system note' do
+ let(:action) { 'description' }
+ end
+
+ it 'sets the note text' do
+ expect(subject.note).to eq('changed the description')
+ end
+ end
+ end
+
describe '.change_issue_confidentiality' do
subject { described_class.change_issue_confidentiality(noteable, project, author) }
diff --git a/spec/services/todo_service_spec.rb b/spec/services/todo_service_spec.rb
index 89b3b6aad10..175a42a32d9 100644
--- a/spec/services/todo_service_spec.rb
+++ b/spec/services/todo_service_spec.rb
@@ -25,11 +25,11 @@ describe TodoService, services: true do
end
describe 'Issues' do
- let(:issue) { create(:issue, project: project, assignee: john_doe, author: author, description: "- [ ] Task 1\n- [ ] Task 2 #{mentions}") }
- let(:addressed_issue) { create(:issue, project: project, assignee: john_doe, author: author, description: "#{directly_addressed}\n- [ ] Task 1\n- [ ] Task 2") }
- let(:unassigned_issue) { create(:issue, project: project, assignee: nil) }
- let(:confidential_issue) { create(:issue, :confidential, project: project, author: author, assignee: assignee, description: mentions) }
- let(:addressed_confident_issue) { create(:issue, :confidential, project: project, author: author, assignee: assignee, description: directly_addressed) }
+ let(:issue) { create(:issue, project: project, assignees: [john_doe], author: author, description: "- [ ] Task 1\n- [ ] Task 2 #{mentions}") }
+ let(:addressed_issue) { create(:issue, project: project, assignees: [john_doe], author: author, description: "#{directly_addressed}\n- [ ] Task 1\n- [ ] Task 2") }
+ let(:unassigned_issue) { create(:issue, project: project, assignees: []) }
+ let(:confidential_issue) { create(:issue, :confidential, project: project, author: author, assignees: [assignee], description: mentions) }
+ let(:addressed_confident_issue) { create(:issue, :confidential, project: project, author: author, assignees: [assignee], description: directly_addressed) }
describe '#new_issue' do
it 'creates a todo if assigned' do
@@ -43,7 +43,7 @@ describe TodoService, services: true do
end
it 'creates a todo if assignee is the current user' do
- unassigned_issue.update_attribute(:assignee, john_doe)
+ unassigned_issue.assignees = [john_doe]
service.new_issue(unassigned_issue, john_doe)
should_create_todo(user: john_doe, target: unassigned_issue, author: john_doe, action: Todo::ASSIGNED)
@@ -258,20 +258,20 @@ describe TodoService, services: true do
describe '#reassigned_issue' do
it 'creates a pending todo for new assignee' do
- unassigned_issue.update_attribute(:assignee, john_doe)
+ unassigned_issue.assignees << john_doe
service.reassigned_issue(unassigned_issue, author)
should_create_todo(user: john_doe, target: unassigned_issue, action: Todo::ASSIGNED)
end
it 'does not create a todo if unassigned' do
- issue.update_attribute(:assignee, nil)
+ issue.assignees.destroy_all
should_not_create_any_todo { service.reassigned_issue(issue, author) }
end
it 'creates a todo if new assignee is the current user' do
- unassigned_issue.update_attribute(:assignee, john_doe)
+ unassigned_issue.assignees << john_doe
service.reassigned_issue(unassigned_issue, john_doe)
should_create_todo(user: john_doe, target: unassigned_issue, author: john_doe, action: Todo::ASSIGNED)
@@ -361,7 +361,7 @@ describe TodoService, services: true do
describe '#new_note' do
let!(:first_todo) { create(:todo, :assigned, user: john_doe, project: project, target: issue, author: author) }
let!(:second_todo) { create(:todo, :assigned, user: john_doe, project: project, target: issue, author: author) }
- let(:confidential_issue) { create(:issue, :confidential, project: project, author: author, assignee: assignee) }
+ let(:confidential_issue) { create(:issue, :confidential, project: project, author: author, assignees: [assignee]) }
let(:note) { create(:note, project: project, noteable: issue, author: john_doe, note: mentions) }
let(:addressed_note) { create(:note, project: project, noteable: issue, author: john_doe, note: directly_addressed) }
let(:note_on_commit) { create(:note_on_commit, project: project, author: john_doe, note: mentions) }
@@ -854,7 +854,7 @@ describe TodoService, services: true do
end
it 'updates cached counts when a todo is created' do
- issue = create(:issue, project: project, assignee: john_doe, author: author, description: mentions)
+ issue = create(:issue, project: project, assignees: [john_doe], author: author, description: mentions)
expect(john_doe.todos_pending_count).to eq(0)
expect(john_doe).to receive(:update_todos_count_cache).and_call_original
@@ -866,8 +866,8 @@ describe TodoService, services: true do
end
describe '#mark_todos_as_done' do
- let(:issue) { create(:issue, project: project, author: author, assignee: john_doe) }
- let(:another_issue) { create(:issue, project: project, author: author, assignee: john_doe) }
+ let(:issue) { create(:issue, project: project, author: author, assignees: [john_doe]) }
+ let(:another_issue) { create(:issue, project: project, author: author, assignees: [john_doe]) }
it 'marks a relation of todos as done' do
create(:todo, :mentioned, user: john_doe, target: issue, project: project)
diff --git a/spec/services/users/destroy_service_spec.rb b/spec/services/users/destroy_service_spec.rb
index 4bc30018ebd..de37a61e388 100644
--- a/spec/services/users/destroy_service_spec.rb
+++ b/spec/services/users/destroy_service_spec.rb
@@ -47,7 +47,7 @@ describe Users::DestroyService, services: true do
end
context "for an issue the user was assigned to" do
- let!(:issue) { create(:issue, project: project, assignee: user) }
+ let!(:issue) { create(:issue, project: project, assignees: [user]) }
before do
service.execute(user)
@@ -60,7 +60,7 @@ describe Users::DestroyService, services: true do
it 'migrates the issue so that it is "Unassigned"' do
migrated_issue = Issue.find_by_id(issue.id)
- expect(migrated_issue.assignee).to be_nil
+ expect(migrated_issue.assignees).to be_empty
end
end
end
diff --git a/spec/support/features/issuable_slash_commands_shared_examples.rb b/spec/support/features/issuable_slash_commands_shared_examples.rb
index 610decdcddb..ad46b163cd6 100644
--- a/spec/support/features/issuable_slash_commands_shared_examples.rb
+++ b/spec/support/features/issuable_slash_commands_shared_examples.rb
@@ -25,7 +25,7 @@ shared_examples 'issuable record that supports slash commands in its description
wait_for_ajax
end
- describe "new #{issuable_type}" do
+ describe "new #{issuable_type}", js: true do
context 'with commands in the description' do
it "creates the #{issuable_type} and interpret commands accordingly" do
visit public_send("new_namespace_project_#{issuable_type}_path", project.namespace, project, new_url_opts)
@@ -44,7 +44,7 @@ shared_examples 'issuable record that supports slash commands in its description
end
end
- describe "note on #{issuable_type}" do
+ describe "note on #{issuable_type}", js: true do
before do
visit public_send("namespace_project_#{issuable_type}_path", project.namespace, project, issuable)
end
@@ -63,7 +63,7 @@ shared_examples 'issuable record that supports slash commands in its description
note = issuable.notes.user.first
expect(note.note).to eq "Awesome!"
- expect(issuable.assignee).to eq assignee
+ expect(issuable.assignees).to eq [assignee]
expect(issuable.labels).to eq [label_bug]
expect(issuable.milestone).to eq milestone
end
@@ -81,7 +81,7 @@ shared_examples 'issuable record that supports slash commands in its description
issuable.reload
expect(issuable.notes.user).to be_empty
- expect(issuable.assignee).to eq assignee
+ expect(issuable.assignees).to eq [assignee]
expect(issuable.labels).to eq [label_bug]
expect(issuable.milestone).to eq milestone
end
diff --git a/spec/support/import_export/export_file_helper.rb b/spec/support/import_export/export_file_helper.rb
index 944ea30656f..57b6abe12b7 100644
--- a/spec/support/import_export/export_file_helper.rb
+++ b/spec/support/import_export/export_file_helper.rb
@@ -10,7 +10,7 @@ module ExportFileHelper
create(:release, project: project)
- issue = create(:issue, assignee: user, project: project)
+ issue = create(:issue, assignees: [user], project: project)
snippet = create(:project_snippet, project: project)
label = create(:label, project: project)
milestone = create(:milestone, project: project)
diff --git a/spec/support/matchers/gitlab_git_matchers.rb b/spec/support/matchers/gitlab_git_matchers.rb
new file mode 100644
index 00000000000..c840cd4bf2d
--- /dev/null
+++ b/spec/support/matchers/gitlab_git_matchers.rb
@@ -0,0 +1,6 @@
+RSpec::Matchers.define :gitlab_git_repository_with do |values|
+ match do |actual|
+ actual.is_a?(Gitlab::Git::Repository) &&
+ values.all? { |k, v| actual.send(k) == v }
+ end
+end
diff --git a/spec/support/services/issuable_create_service_shared_examples.rb b/spec/support/services/issuable_create_service_shared_examples.rb
deleted file mode 100644
index 4f0c745b7ee..00000000000
--- a/spec/support/services/issuable_create_service_shared_examples.rb
+++ /dev/null
@@ -1,52 +0,0 @@
-shared_examples 'issuable create service' do
- context 'asssignee_id' do
- let(:assignee) { create(:user) }
-
- before { project.team << [user, :master] }
-
- it 'removes assignee_id when user id is invalid' do
- opts = { title: 'Title', description: 'Description', assignee_id: -1 }
-
- issuable = described_class.new(project, user, opts).execute
-
- expect(issuable.assignee_id).to be_nil
- end
-
- it 'removes assignee_id when user id is 0' do
- opts = { title: 'Title', description: 'Description', assignee_id: 0 }
-
- issuable = described_class.new(project, user, opts).execute
-
- expect(issuable.assignee_id).to be_nil
- end
-
- it 'saves assignee when user id is valid' do
- project.team << [assignee, :master]
- opts = { title: 'Title', description: 'Description', assignee_id: assignee.id }
-
- issuable = described_class.new(project, user, opts).execute
-
- expect(issuable.assignee_id).to eq(assignee.id)
- end
-
- context "when issuable feature is private" do
- before do
- project.project_feature.update(issues_access_level: ProjectFeature::PRIVATE,
- merge_requests_access_level: ProjectFeature::PRIVATE)
- end
-
- levels = [Gitlab::VisibilityLevel::INTERNAL, Gitlab::VisibilityLevel::PUBLIC]
-
- levels.each do |level|
- it "removes not authorized assignee when project is #{Gitlab::VisibilityLevel.level_name(level)}" do
- project.update(visibility_level: level)
- opts = { title: 'Title', description: 'Description', assignee_id: assignee.id }
-
- issuable = described_class.new(project, user, opts).execute
-
- expect(issuable.assignee_id).to be_nil
- end
- end
- end
- end
-end
diff --git a/spec/support/services/issuable_create_service_slash_commands_shared_examples.rb b/spec/support/services/issuable_create_service_slash_commands_shared_examples.rb
index 9e9cdf3e48b..1dd3663b944 100644
--- a/spec/support/services/issuable_create_service_slash_commands_shared_examples.rb
+++ b/spec/support/services/issuable_create_service_slash_commands_shared_examples.rb
@@ -49,23 +49,7 @@ shared_examples 'new issuable record that supports slash commands' do
it 'assigns and sets milestone to issuable' do
expect(issuable).to be_persisted
- expect(issuable.assignee).to eq(assignee)
- expect(issuable.milestone).to eq(milestone)
- end
- end
-
- context 'with assignee and milestone in params and command' do
- let(:example_params) do
- {
- assignee: create(:user),
- milestone_id: 1,
- description: %(/assign @#{assignee.username}\n/milestone %"#{milestone.name}")
- }
- end
-
- it 'assigns and sets milestone to issuable from command' do
- expect(issuable).to be_persisted
- expect(issuable.assignee).to eq(assignee)
+ expect(issuable.assignees).to eq([assignee])
expect(issuable.milestone).to eq(milestone)
end
end
diff --git a/spec/support/services/issuable_update_service_shared_examples.rb b/spec/support/services/issuable_update_service_shared_examples.rb
index 49cea1e608c..8947f20562f 100644
--- a/spec/support/services/issuable_update_service_shared_examples.rb
+++ b/spec/support/services/issuable_update_service_shared_examples.rb
@@ -18,52 +18,4 @@ shared_examples 'issuable update service' do
end
end
end
-
- context 'asssignee_id' do
- it 'does not update assignee when assignee_id is invalid' do
- open_issuable.update(assignee_id: user.id)
-
- update_issuable(assignee_id: -1)
-
- expect(open_issuable.reload.assignee).to eq(user)
- end
-
- it 'unassigns assignee when user id is 0' do
- open_issuable.update(assignee_id: user.id)
-
- update_issuable(assignee_id: 0)
-
- expect(open_issuable.assignee_id).to be_nil
- end
-
- it 'saves assignee when user id is valid' do
- update_issuable(assignee_id: user.id)
-
- expect(open_issuable.assignee_id).to eq(user.id)
- end
-
- it 'does not update assignee_id when user cannot read issue' do
- non_member = create(:user)
- original_assignee = open_issuable.assignee
-
- update_issuable(assignee_id: non_member.id)
-
- expect(open_issuable.assignee_id).to eq(original_assignee.id)
- end
-
- context "when issuable feature is private" do
- levels = [Gitlab::VisibilityLevel::INTERNAL, Gitlab::VisibilityLevel::PUBLIC]
-
- levels.each do |level|
- it "does not update with unauthorized assignee when project is #{Gitlab::VisibilityLevel.level_name(level)}" do
- assignee = create(:user)
- project.update(visibility_level: level)
- feature_visibility_attr = :"#{open_issuable.model_name.plural}_access_level"
- project.project_feature.update_attribute(feature_visibility_attr, ProjectFeature::PRIVATE)
-
- expect{ update_issuable(assignee_id: assignee) }.not_to change{ open_issuable.assignee }
- end
- end
- end
- end
end
diff --git a/spec/support/test_env.rb b/spec/support/test_env.rb
index 0b3c6169c9b..8e31c26591b 100644
--- a/spec/support/test_env.rb
+++ b/spec/support/test_env.rb
@@ -27,6 +27,7 @@ module TestEnv
'expand-collapse-files' => '025db92',
'expand-collapse-lines' => '238e82d',
'video' => '8879059',
+ 'add-balsamiq-file' => 'b89b56d',
'crlf-diff' => '5938907',
'conflict-start' => '824be60',
'conflict-resolvable' => '1450cd6',
diff --git a/spec/support/time_tracking_shared_examples.rb b/spec/support/time_tracking_shared_examples.rb
index e94e17da7e5..84ef46ffa27 100644
--- a/spec/support/time_tracking_shared_examples.rb
+++ b/spec/support/time_tracking_shared_examples.rb
@@ -37,8 +37,7 @@ shared_examples 'issuable time tracker' do
submit_time('/estimate 3w 1d 1h')
submit_time('/remove_estimate')
- wait_for_ajax
- page.within '#issuable-time-tracker' do
+ page.within '.time-tracking-component-wrap' do
expect(page).to have_content 'No estimate or time spent'
end
end
@@ -47,14 +46,13 @@ shared_examples 'issuable time tracker' do
submit_time('/spend 3w 1d 1h')
submit_time('/remove_time_spent')
- wait_for_ajax
- page.within '#issuable-time-tracker' do
+ page.within '.time-tracking-component-wrap' do
expect(page).to have_content 'No estimate or time spent'
end
end
it 'shows the help state when icon is clicked' do
- page.within '#issuable-time-tracker' do
+ page.within '.time-tracking-component-wrap' do
find('.help-button').click
expect(page).to have_content 'Track time with slash commands'
expect(page).to have_content 'Learn more'
@@ -62,7 +60,7 @@ shared_examples 'issuable time tracker' do
end
it 'hides the help state when close icon is clicked' do
- page.within '#issuable-time-tracker' do
+ page.within '.time-tracking-component-wrap' do
find('.help-button').click
find('.close-help-button').click
@@ -72,7 +70,7 @@ shared_examples 'issuable time tracker' do
end
it 'displays the correct help url' do
- page.within '#issuable-time-tracker' do
+ page.within '.time-tracking-component-wrap' do
find('.help-button').click
expect(find_link('Learn more')[:href]).to have_content('/help/workflow/time_tracking.md')
diff --git a/spec/views/projects/environments/terminal.html.haml_spec.rb b/spec/views/projects/environments/terminal.html.haml_spec.rb
new file mode 100644
index 00000000000..d2e47225226
--- /dev/null
+++ b/spec/views/projects/environments/terminal.html.haml_spec.rb
@@ -0,0 +1,32 @@
+require 'spec_helper'
+
+describe 'projects/environments/terminal' do
+ let!(:environment) { create(:environment, :with_review_app) }
+
+ before do
+ assign(:environment, environment)
+ assign(:project, environment.project)
+
+ allow(view).to receive(:can?).and_return(true)
+ end
+
+ context 'when environment has external URL' do
+ it 'shows external URL button' do
+ environment.update_attribute(:external_url, 'https://gitlab.com')
+
+ render
+
+ expect(rendered).to have_link(nil, href: 'https://gitlab.com')
+ end
+ end
+
+ context 'when environment does not have external URL' do
+ it 'shows external URL button' do
+ environment.update_attribute(:external_url, nil)
+
+ render
+
+ expect(rendered).not_to have_link(nil, href: 'https://gitlab.com')
+ end
+ end
+end
diff --git a/spec/workers/post_receive_spec.rb b/spec/workers/post_receive_spec.rb
index 5ab3c4a0e34..0260416dbe2 100644
--- a/spec/workers/post_receive_spec.rb
+++ b/spec/workers/post_receive_spec.rb
@@ -5,6 +5,7 @@ describe PostReceive do
let(:wrongly_encoded_changes) { changes.encode("ISO-8859-1").force_encoding("UTF-8") }
let(:base64_changes) { Base64.encode64(wrongly_encoded_changes) }
let(:project) { create(:project, :repository) }
+ let(:project_identifier) { "project-#{project.id}" }
let(:key) { create(:key, user: project.owner) }
let(:key_id) { key.shell_id }
@@ -14,6 +15,26 @@ describe PostReceive do
end
end
+ context 'with a non-existing project' do
+ let(:project_identifier) { "project-123456789" }
+ let(:error_message) do
+ "Triggered hook for non-existing project with identifier \"#{project_identifier}\""
+ end
+
+ it "returns false and logs an error" do
+ expect(Gitlab::GitLogger).to receive(:error).with("POST-RECEIVE: #{error_message}")
+ expect(described_class.new.perform(project_identifier, key_id, base64_changes)).to be(false)
+ end
+ end
+
+ context "with an absolute path as the project identifier" do
+ it "searches the project by full path" do
+ expect(Project).to receive(:find_by_full_path).with(project.full_path).and_call_original
+
+ described_class.new.perform(pwd(project), key_id, base64_changes)
+ end
+ end
+
describe "#process_project_changes" do
before do
allow_any_instance_of(Gitlab::GitPostReceive).to receive(:identify).and_return(project.owner)
@@ -25,7 +46,7 @@ describe PostReceive do
it "calls GitTagPushService" do
expect_any_instance_of(GitPushService).to receive(:execute).and_return(true)
expect_any_instance_of(GitTagPushService).not_to receive(:execute)
- described_class.new.perform(pwd(project), key_id, base64_changes)
+ described_class.new.perform(project_identifier, key_id, base64_changes)
end
end
@@ -35,7 +56,7 @@ describe PostReceive do
it "calls GitTagPushService" do
expect_any_instance_of(GitPushService).not_to receive(:execute)
expect_any_instance_of(GitTagPushService).to receive(:execute).and_return(true)
- described_class.new.perform(pwd(project), key_id, base64_changes)
+ described_class.new.perform(project_identifier, key_id, base64_changes)
end
end
@@ -45,12 +66,12 @@ describe PostReceive do
it "does not call any of the services" do
expect_any_instance_of(GitPushService).not_to receive(:execute)
expect_any_instance_of(GitTagPushService).not_to receive(:execute)
- described_class.new.perform(pwd(project), key_id, base64_changes)
+ described_class.new.perform(project_identifier, key_id, base64_changes)
end
end
context "gitlab-ci.yml" do
- subject { described_class.new.perform(pwd(project), key_id, base64_changes) }
+ subject { described_class.new.perform(project_identifier, key_id, base64_changes) }
context "creates a Ci::Pipeline for every change" do
before do
@@ -74,8 +95,8 @@ describe PostReceive do
context "webhook" do
it "fetches the correct project" do
- expect(Project).to receive(:find_by_full_path).with(project.path_with_namespace).and_return(project)
- described_class.new.perform(pwd(project), key_id, base64_changes)
+ expect(Project).to receive(:find_by).with(id: project.id.to_s)
+ described_class.new.perform(project_identifier, key_id, base64_changes)
end
it "does not run if the author is not in the project" do
@@ -85,22 +106,22 @@ describe PostReceive do
expect(project).not_to receive(:execute_hooks)
- expect(described_class.new.perform(pwd(project), key_id, base64_changes)).to be_falsey
+ expect(described_class.new.perform(project_identifier, key_id, base64_changes)).to be_falsey
end
it "asks the project to trigger all hooks" do
- allow(Project).to receive(:find_by_full_path).and_return(project)
+ allow(Project).to receive(:find_by).and_return(project)
expect(project).to receive(:execute_hooks).twice
expect(project).to receive(:execute_services).twice
- described_class.new.perform(pwd(project), key_id, base64_changes)
+ described_class.new.perform(project_identifier, key_id, base64_changes)
end
it "enqueues a UpdateMergeRequestsWorker job" do
- allow(Project).to receive(:find_by_full_path).and_return(project)
+ allow(Project).to receive(:find_by).and_return(project)
expect(UpdateMergeRequestsWorker).to receive(:perform_async).with(project.id, project.owner.id, any_args)
- described_class.new.perform(pwd(project), key_id, base64_changes)
+ described_class.new.perform(project_identifier, key_id, base64_changes)
end
end
diff --git a/spec/workers/propagate_service_template_worker_spec.rb b/spec/workers/propagate_service_template_worker_spec.rb
new file mode 100644
index 00000000000..7040d5ef81c
--- /dev/null
+++ b/spec/workers/propagate_service_template_worker_spec.rb
@@ -0,0 +1,29 @@
+require 'spec_helper'
+
+describe PropagateServiceTemplateWorker do
+ let!(:service_template) do
+ PushoverService.create(
+ template: true,
+ active: true,
+ properties: {
+ device: 'MyDevice',
+ sound: 'mic',
+ priority: 4,
+ user_key: 'asdf',
+ api_key: '123456789'
+ })
+ end
+
+ before do
+ allow_any_instance_of(Gitlab::ExclusiveLease).to receive(:try_obtain).
+ and_return(true)
+ end
+
+ describe '#perform' do
+ it 'calls the propagate service with the template' do
+ expect(Projects::PropagateServiceTemplate).to receive(:propagate).with(service_template)
+
+ subject.perform(service_template.id)
+ end
+ end
+end
diff --git a/yarn.lock b/yarn.lock
index 8c72f36af3a..8aac2b1b1cd 100644
--- a/yarn.lock
+++ b/yarn.lock
@@ -3190,7 +3190,7 @@ json-stable-stringify@^1.0.0, json-stable-stringify@^1.0.1:
dependencies:
jsonify "~0.0.0"
-json-stringify-safe@~5.0.1:
+json-stringify-safe@^5.0.1, json-stringify-safe@~5.0.1:
version "5.0.1"
resolved "https://registry.yarnpkg.com/json-stringify-safe/-/json-stringify-safe-5.0.1.tgz#1296a2d58fd45f19a0f6ce01d65701e2c735b6eb"
@@ -4584,6 +4584,12 @@ raphael@^2.2.7:
dependencies:
eve-raphael "0.5.0"
+raven-js@^3.14.0:
+ version "3.14.0"
+ resolved "https://registry.yarnpkg.com/raven-js/-/raven-js-3.14.0.tgz#94dda81d975fdc4a42f193db437cf70021d654e0"
+ dependencies:
+ json-stringify-safe "^5.0.1"
+
raw-body@~2.2.0:
version "2.2.0"
resolved "https://registry.yarnpkg.com/raw-body/-/raw-body-2.2.0.tgz#994976cf6a5096a41162840492f0bdc5d6e7fb96"
@@ -5195,6 +5201,10 @@ sprintf-js@~1.0.2:
version "1.0.3"
resolved "https://registry.yarnpkg.com/sprintf-js/-/sprintf-js-1.0.3.tgz#04e6926f662895354f3dd015203633b857297e2c"
+sql.js@^0.4.0:
+ version "0.4.0"
+ resolved "https://registry.yarnpkg.com/sql.js/-/sql.js-0.4.0.tgz#23be9635520eb0ff43a741e7e830397266e88445"
+
sshpk@^1.7.0:
version "1.10.2"
resolved "https://registry.yarnpkg.com/sshpk/-/sshpk-1.10.2.tgz#d5a804ce22695515638e798dbe23273de070a5fa"