Commit 717ec812 authored by Stan Hu's avatar Stan Hu

Merge branch 'master' into sh-geo-show-event-log-data

parents 2c226d9a 3701599d
...@@ -5,6 +5,7 @@ ...@@ -5,6 +5,7 @@
// %button.js-toggle-button // %button.js-toggle-button
// %div.js-toggle-content // %div.js-toggle-content
// //
import '~/lib/utils/url_utility';
$(() => { $(() => {
function toggleContainer(container, toggleState) { function toggleContainer(container, toggleState) {
......
...@@ -12,3 +12,4 @@ import 'core-js/fn/symbol'; ...@@ -12,3 +12,4 @@ import 'core-js/fn/symbol';
// Browser polyfills // Browser polyfills
import './polyfills/custom_event'; import './polyfills/custom_event';
import './polyfills/element'; import './polyfills/element';
import './polyfills/nodelist';
if (window.NodeList && !NodeList.prototype.forEach) {
NodeList.prototype.forEach = function forEach(callback, thisArg = window) {
for (let i = 0; i < this.length; i += 1) {
callback.call(thisArg, this[i], i, this);
}
};
}
...@@ -4,6 +4,8 @@ ...@@ -4,6 +4,8 @@
import Vue from 'vue'; import Vue from 'vue';
import '../mixins/discussion';
const JumpToDiscussion = Vue.extend({ const JumpToDiscussion = Vue.extend({
mixins: [DiscussionMixins], mixins: [DiscussionMixins],
props: { props: {
......
...@@ -4,6 +4,8 @@ ...@@ -4,6 +4,8 @@
import Vue from 'vue'; import Vue from 'vue';
import '../mixins/discussion';
window.ResolveCount = Vue.extend({ window.ResolveCount = Vue.extend({
mixins: [DiscussionMixins], mixins: [DiscussionMixins],
props: { props: {
......
...@@ -77,10 +77,11 @@ import initSettingsPanels from './settings_panels'; ...@@ -77,10 +77,11 @@ import initSettingsPanels from './settings_panels';
import initExperimentalFlags from './experimental_flags'; import initExperimentalFlags from './experimental_flags';
import OAuthRememberMe from './oauth_remember_me'; import OAuthRememberMe from './oauth_remember_me';
import PerformanceBar from './performance_bar'; import PerformanceBar from './performance_bar';
import GpgBadges from './gpg_badges';
import initNotes from './init_notes'; import initNotes from './init_notes';
import initLegacyFilters from './init_legacy_filters'; import initLegacyFilters from './init_legacy_filters';
import initIssuableSidebar from './init_issuable_sidebar'; import initIssuableSidebar from './init_issuable_sidebar';
import initProjectVisibilitySelector from './project_visibility';
import GpgBadges from './gpg_badges';
import UserFeatureHelper from './helpers/user_feature_helper'; import UserFeatureHelper from './helpers/user_feature_helper';
import initChangesDropdown from './init_changes_dropdown'; import initChangesDropdown from './init_changes_dropdown';
...@@ -657,6 +658,7 @@ import initGroupAnalytics from './init_group_analytics'; ...@@ -657,6 +658,7 @@ import initGroupAnalytics from './init_group_analytics';
break; break;
case 'new': case 'new':
new ProjectNew(); new ProjectNew();
initProjectVisibilitySelector();
break; break;
case 'show': case 'show':
new Star(); new Star();
......
function setVisibilityOptions(namespaceSelector) {
if (!namespaceSelector || !('selectedIndex' in namespaceSelector)) {
return;
}
const selectedNamespace = namespaceSelector.options[namespaceSelector.selectedIndex];
const { name, visibility, visibilityLevel, showPath, editPath } = selectedNamespace.dataset;
document.querySelectorAll('.visibility-level-setting .radio').forEach((option) => {
const optionInput = option.querySelector('input[type=radio]');
const optionValue = optionInput ? optionInput.value : 0;
const optionTitle = option.querySelector('.option-title');
const optionName = optionTitle ? optionTitle.innerText.toLowerCase() : '';
// don't change anything if the option is restricted by admin
if (!option.classList.contains('restricted')) {
if (visibilityLevel < optionValue) {
option.classList.add('disabled');
optionInput.disabled = true;
const reason = option.querySelector('.option-disabled-reason');
if (reason) {
reason.innerHTML =
`This project cannot be ${optionName} because the visibility of
<a href="${showPath}">${name}</a> is ${visibility}. To make this project
${optionName}, you must first <a href="${editPath}">change the visibility</a>
of the parent group.`;
}
} else {
option.classList.remove('disabled');
optionInput.disabled = false;
}
}
});
}
export default function initProjectVisibilitySelector() {
const namespaceSelector = document.querySelector('select.js-select-namespace');
if (namespaceSelector) {
$('.select2.js-select-namespace').on('change', () => setVisibilityOptions(namespaceSelector));
setVisibilityOptions(namespaceSelector);
}
}
/* eslint-disable func-names, space-before-function-paren, no-var, prefer-rest-params, wrap-iife, quotes, prefer-arrow-callback, consistent-return, object-shorthand, no-unused-vars, one-var, one-var-declaration-per-line, no-else-return, comma-dangle, max-len */ /* eslint-disable func-names, space-before-function-paren, no-var, prefer-rest-params, wrap-iife, quotes, prefer-arrow-callback, consistent-return, object-shorthand, no-unused-vars, one-var, one-var-declaration-per-line, no-else-return, comma-dangle, max-len */
/* global Mousetrap */ /* global Mousetrap */
import Cookies from 'js-cookie'; import Cookies from 'js-cookie';
import Mousetrap from 'mousetrap';
import findAndFollowLink from './shortcuts_dashboard_navigation'; import findAndFollowLink from './shortcuts_dashboard_navigation';
......
...@@ -307,28 +307,6 @@ ...@@ -307,28 +307,6 @@
} }
} }
.project-visibility-level-holder {
.radio {
margin-bottom: 10px;
i {
margin: 2px 0;
font-size: 20px;
}
.option-title {
font-weight: $gl-font-weight-normal;
display: inline-block;
color: $gl-text-color;
}
.option-descr {
margin-left: 29px;
color: $project-option-descr-color;
}
}
}
.save-project-loader { .save-project-loader {
margin-top: 50px; margin-top: 50px;
margin-bottom: 50px; margin-bottom: 50px;
......
...@@ -143,6 +143,47 @@ ...@@ -143,6 +143,47 @@
} }
} }
.visibility-level-setting {
.radio {
margin-bottom: 10px;
i.fa {
margin: 2px 0;
font-size: 20px;
}
.option-title {
font-weight: $gl-font-weight-normal;
display: inline-block;
color: $gl-text-color;
}
.option-description,
.option-disabled-reason {
margin-left: 29px;
color: $project-option-descr-color;
}
.option-disabled-reason {
display: none;
}
&.disabled {
i.fa {
opacity: 0.5;
}
.option-description {
display: none;
}
.option-disabled-reason {
display: block;
}
}
}
}
.nested-settings { .nested-settings {
padding-left: 20px; padding-left: 20px;
} }
......
...@@ -22,7 +22,10 @@ class ProjectsController < Projects::ApplicationController ...@@ -22,7 +22,10 @@ class ProjectsController < Projects::ApplicationController
end end
def new def new
@project = Project.new namespace = Namespace.find_by(id: params[:namespace_id]) if params[:namespace_id]
return access_denied! if namespace && !can?(current_user, :create_projects, namespace)
@project = Project.new(namespace_id: namespace&.id)
end end
def edit def edit
......
...@@ -6,7 +6,8 @@ module NamespacesHelper ...@@ -6,7 +6,8 @@ module NamespacesHelper
end end
def namespaces_options(selected = :current_user, display_path: false, extra_group: nil) def namespaces_options(selected = :current_user, display_path: false, extra_group: nil)
groups = current_user.owned_groups + current_user.masters_groups groups = current_user.owned_groups + current_user.masters_groups
users = [current_user.namespace]
unless extra_group.nil? || extra_group.is_a?(Group) unless extra_group.nil? || extra_group.is_a?(Group)
extra_group = Group.find(extra_group) if Namespace.find(extra_group).kind == 'group' extra_group = Group.find(extra_group) if Namespace.find(extra_group).kind == 'group'
...@@ -16,22 +17,9 @@ module NamespacesHelper ...@@ -16,22 +17,9 @@ module NamespacesHelper
groups |= [extra_group] groups |= [extra_group]
end end
users = [current_user.namespace]
data_attr_group = { 'data-options-parent' => 'groups' }
data_attr_users = { 'data-options-parent' => 'users' }
group_opts = [
"Groups", groups.sort_by(&:human_name).map { |g| [display_path ? g.full_path : g.human_name, g.id, data_attr_group] }
]
users_opts = [
"Users", users.sort_by(&:human_name).map { |u| [display_path ? u.path : u.human_name, u.id, data_attr_users] }
]
options = [] options = []
options << group_opts options << options_for_group(groups, display_path: display_path, type: 'group')
options << users_opts options << options_for_group(users, display_path: display_path, type: 'user')
if selected == :current_user && current_user.namespace if selected == :current_user && current_user.namespace
selected = current_user.namespace.id selected = current_user.namespace.id
...@@ -47,4 +35,23 @@ module NamespacesHelper ...@@ -47,4 +35,23 @@ module NamespacesHelper
avatar_icon(namespace.owner.email, size) avatar_icon(namespace.owner.email, size)
end end
end end
private
def options_for_group(namespaces, display_path:, type:)
group_label = type.pluralize
elements = namespaces.sort_by(&:human_name).map! do |n|
[display_path ? n.full_path : n.human_name, n.id,
data: {
options_parent: group_label,
visibility_level: n.visibility_level_value,
visibility: n.visibility,
name: n.name,
show_path: (type == 'group') ? group_path(n) : user_path(n),
edit_path: (type == 'group') ? edit_group_path(n) : nil
}]
end
[group_label.camelize, elements]
end
end end
...@@ -63,6 +63,68 @@ module VisibilityLevelHelper ...@@ -63,6 +63,68 @@ module VisibilityLevelHelper
end end
end end
def restricted_visibility_level_description(level)
level_name = Gitlab::VisibilityLevel.level_name(level)
"#{level_name.capitalize} visibility has been restricted by the administrator."
end
def disallowed_visibility_level_description(level, form_model)
case form_model
when Project
disallowed_project_visibility_level_description(level, form_model)
when Group
disallowed_group_visibility_level_description(level, form_model)
end
end
# Note: these messages closely mirror the form validation strings found in the project
# model and any changes or additons to these may also need to be made there.
def disallowed_project_visibility_level_description(level, project)
level_name = Gitlab::VisibilityLevel.level_name(level).downcase
reasons = []
instructions = ''
unless project.visibility_level_allowed_as_fork?(level)
reasons << "the fork source project has lower visibility"
end
unless project.visibility_level_allowed_by_group?(level)
errors = visibility_level_errors_for_group(project.group, level_name)
reasons << errors[:reason]
instructions << errors[:instruction]
end
reasons = reasons.any? ? ' because ' + reasons.to_sentence : ''
"This project cannot be #{level_name}#{reasons}.#{instructions}".html_safe
end
# Note: these messages closely mirror the form validation strings found in the group
# model and any changes or additons to these may also need to be made there.
def disallowed_group_visibility_level_description(level, group)
level_name = Gitlab::VisibilityLevel.level_name(level).downcase
reasons = []
instructions = ''
unless group.visibility_level_allowed_by_projects?(level)
reasons << "it contains projects with higher visibility"
end
unless group.visibility_level_allowed_by_sub_groups?(level)
reasons << "it contains sub-groups with higher visibility"
end
unless group.visibility_level_allowed_by_parent?(level)
errors = visibility_level_errors_for_group(group.parent, level_name)
reasons << errors[:reason]
instructions << errors[:instruction]
end
reasons = reasons.any? ? ' because ' + reasons.to_sentence : ''
"This group cannot be #{level_name}#{reasons}.#{instructions}".html_safe
end
def visibility_icon_description(form_model) def visibility_icon_description(form_model)
case form_model case form_model
when Project when Project
...@@ -95,7 +157,18 @@ module VisibilityLevelHelper ...@@ -95,7 +157,18 @@ module VisibilityLevelHelper
:default_group_visibility, :default_group_visibility,
to: :current_application_settings to: :current_application_settings
def skip_level?(form_model, level) def disallowed_visibility_level?(form_model, level)
form_model.is_a?(Project) && !form_model.visibility_level_allowed?(level) return false unless form_model.respond_to?(:visibility_level_allowed?)
!form_model.visibility_level_allowed?(level)
end
private
def visibility_level_errors_for_group(group, level_name)
group_name = link_to group.name, group_path(group)
change_visiblity = link_to 'change the visibility', edit_group_path(group)
{ reason: "the visibility of #{group_name} is #{group.visibility}",
instruction: " To make this group #{level_name}, you must first #{change_visiblity} of the parent group." }
end end
end end
...@@ -37,6 +37,8 @@ class Group < Namespace ...@@ -37,6 +37,8 @@ class Group < Namespace
validate :avatar_type, if: ->(user) { user.avatar.present? && user.avatar_changed? } validate :avatar_type, if: ->(user) { user.avatar.present? && user.avatar_changed? }
validate :visibility_level_allowed_by_projects validate :visibility_level_allowed_by_projects
validate :visibility_level_allowed_by_sub_groups
validate :visibility_level_allowed_by_parent
validates :avatar, file_size: { maximum: 200.kilobytes.to_i } validates :avatar, file_size: { maximum: 200.kilobytes.to_i }
...@@ -120,15 +122,24 @@ class Group < Namespace ...@@ -120,15 +122,24 @@ class Group < Namespace
full_name full_name
end end
def visibility_level_allowed_by_projects def visibility_level_allowed_by_parent?(level = self.visibility_level)
allowed_by_projects = self.projects.where('visibility_level > ?', self.visibility_level).none? return true unless parent_id && parent_id.nonzero?
unless allowed_by_projects level <= parent.visibility_level
level_name = Gitlab::VisibilityLevel.level_name(visibility_level).downcase end
self.errors.add(:visibility_level, "#{level_name} is not allowed since there are projects with higher visibility.")
end def visibility_level_allowed_by_projects?(level = self.visibility_level)
!projects.where('visibility_level > ?', level).exists?
end
allowed_by_projects def visibility_level_allowed_by_sub_groups?(level = self.visibility_level)
!children.where('visibility_level > ?', level).exists?
end
def visibility_level_allowed?(level = self.visibility_level)
visibility_level_allowed_by_parent?(level) &&
visibility_level_allowed_by_projects?(level) &&
visibility_level_allowed_by_sub_groups?(level)
end end
def avatar_url(**args) def avatar_url(**args)
...@@ -321,11 +332,29 @@ class Group < Namespace ...@@ -321,11 +332,29 @@ class Group < Namespace
list_of_ids.reverse.map { |group| variables[group.id] }.compact.flatten list_of_ids.reverse.map { |group| variables[group.id] }.compact.flatten
end end
protected private
def update_two_factor_requirement def update_two_factor_requirement
return unless require_two_factor_authentication_changed? || two_factor_grace_period_changed? return unless require_two_factor_authentication_changed? || two_factor_grace_period_changed?
users.find_each(&:update_two_factor_requirement) users.find_each(&:update_two_factor_requirement)
end end
def visibility_level_allowed_by_parent
return if visibility_level_allowed_by_parent?
errors.add(:visibility_level, "#{visibility} is not allowed since the parent group has a #{parent.visibility} visibility.")
end
def visibility_level_allowed_by_projects
return if visibility_level_allowed_by_projects?
errors.add(:visibility_level, "#{visibility} is not allowed since this group contains projects with higher visibility.")
end
def visibility_level_allowed_by_sub_groups
return if visibility_level_allowed_by_sub_groups?
errors.add(:visibility_level, "#{visibility} is not allowed since there are sub-groups with higher visibility.")
end
end end
...@@ -7,15 +7,15 @@ ...@@ -7,15 +7,15 @@
= f.label :default_branch_protection, class: 'control-label col-sm-2' = f.label :default_branch_protection, class: 'control-label col-sm-2'
.col-sm-10 .col-sm-10
= f.select :default_branch_protection, options_for_select(Gitlab::Access.protection_options, @application_setting.default_branch_protection), {}, class: 'form-control' = f.select :default_branch_protection, options_for_select(Gitlab::Access.protection_options, @application_setting.default_branch_protection), {}, class: 'form-control'
.form-group.project-visibility-level-holder .form-group.visibility-level-setting
= f.label :default_project_visibility, class: 'control-label col-sm-2' = f.label :default_project_visibility, class: 'control-label col-sm-2'
.col-sm-10 .col-sm-10
= render('shared/visibility_radios', model_method: :default_project_visibility, form: f, selected_level: @application_setting.default_project_visibility, form_model: Project.new) = render('shared/visibility_radios', model_method: :default_project_visibility, form: f, selected_level: @application_setting.default_project_visibility, form_model: Project.new)
.form-group.project-visibility-level-holder .form-group.visibility-level-setting
= f.label :default_snippet_visibility, class: 'control-label col-sm-2' = f.label :default_snippet_visibility, class: 'control-label col-sm-2'
.col-sm-10 .col-sm-10
= render('shared/visibility_radios', model_method: :default_snippet_visibility, form: f, selected_level: @application_setting.default_snippet_visibility, form_model: ProjectSnippet.new) = render('shared/visibility_radios', model_method: :default_snippet_visibility, form: f, selected_level: @application_setting.default_snippet_visibility, form_model: ProjectSnippet.new)
.form-group.project-visibility-level-holder .form-group.visibility-level-setting
= f.label :default_group_visibility, class: 'control-label col-sm-2' = f.label :default_group_visibility, class: 'control-label col-sm-2'
.col-sm-10 .col-sm-10
= render('shared/visibility_radios', model_method: :default_group_visibility, form: f, selected_level: @application_setting.default_group_visibility, form_model: Group.new) = render('shared/visibility_radios', model_method: :default_group_visibility, form: f, selected_level: @application_setting.default_group_visibility, form_model: Group.new)
......
...@@ -19,8 +19,8 @@ ...@@ -19,8 +19,8 @@
= fg.text_area :key, class: 'form-control thin_area', rows: 5, disabled: disable_key_edit = fg.text_area :key, class: 'form-control thin_area', rows: 5, disabled: disable_key_edit
- unless disable_key_edit - unless disable_key_edit
%p.help-block %p.help-block
Paste a machine public key here for the GitLab user this node runs on. Read more about how to generate it Paste the ssh public key used by the node you are adding. Read more about it
= link_to 'here', help_page_path('ssh/README') = link_to 'here', help_page_path('gitlab-geo/configuration.html', anchor: 'step-5-enabling-the-secondary-gitlab-node')
.form-group.js-namespaces{ class: ('hidden' unless geo_node.new_record? || geo_node.secondary?) } .form-group.js-namespaces{ class: ('hidden' unless geo_node.new_record? || geo_node.secondary?) }
= form.label :namespace_ids, 'Namespaces to replicate', class: 'control-label' = form.label :namespace_ids, 'Namespaces to replicate', class: 'control-label'
......
...@@ -111,7 +111,7 @@ ...@@ -111,7 +111,7 @@
%span.light (optional) %span.light (optional)
= f.text_area :description, placeholder: 'Description format', class: "form-control", rows: 3, maxlength: 250 = f.text_area :description, placeholder: 'Description format', class: "form-control", rows: 3, maxlength: 250
.form-group.project-visibility-level-holder .form-group.visibility-level-setting
= f.label :visibility_level, class: 'label-light' do = f.label :visibility_level, class: 'label-light' do
Visibility Level Visibility Level
= link_to icon('question-circle'), help_page_path("public_access/public_access"), aria: { label: 'Documentation for Visibility Level' } = link_to icon('question-circle'), help_page_path("public_access/public_access"), aria: { label: 'Documentation for Visibility Level' }
......
- with_label = local_assigns.fetch(:with_label, true) - with_label = local_assigns.fetch(:with_label, true)
.form-group.project-visibility-level-holder .form-group.visibility-level-setting
- if with_label - if with_label
= f.label :visibility_level, class: 'control-label' do = f.label :visibility_level, class: 'control-label' do
Visibility Level Visibility Level
......
- Gitlab::VisibilityLevel.values.each do |level| - Gitlab::VisibilityLevel.values.each do |level|
- next if skip_level?(form_model, level) - disallowed = disallowed_visibility_level?(form_model, level)
.radio - restricted = restricted_visibility_levels.include?(level)
- restricted = restricted_visibility_levels.include?(level) - disabled = disallowed || restricted
.radio{ class: [('disabled' if disabled), ('restricted' if restricted)] }
= form.label "#{model_method}_#{level}" do = form.label "#{model_method}_#{level}" do
= form.radio_button model_method, level, checked: (selected_level == level), disabled: restricted = form.radio_button model_method, level, checked: (selected_level == level), disabled: disabled
= visibility_level_icon(level) = visibility_level_icon(level)
.option-title .option-title
= visibility_level_label(level) = visibility_level_label(level)
.option-descr .option-description
= visibility_level_description(level, form_model) = visibility_level_description(level, form_model)
- unless restricted_visibility_levels.empty? .option-disabled-reason
%div - if restricted
%span.info = restricted_visibility_level_description(level)
Some visibility level settings have been restricted by the administrator. - elsif disallowed
= disallowed_visibility_level_description(level, form_model)
---
title: Ensure correct visibility level options shown on all Project, Group, and Snippets
forms
merge_request: 13442
author:
type: fixed
...@@ -26,6 +26,7 @@ Build, test, and deploy the software you develop with [GitLab CI/CD](../ci/READM ...@@ -26,6 +26,7 @@ Build, test, and deploy the software you develop with [GitLab CI/CD](../ci/READM
| Article title | Category | Publishing date | | Article title | Category | Publishing date |
| :------------ | :------: | --------------: | | :------------ | :------: | --------------: |
| [How to test and deploy Laravel/PHP applications with GitLab CI/CD and Envoy](laravel_with_gitlab_and_envoy/index.md) | Tutorial | 2017-08-31 |
| [How to deploy Maven projects to Artifactory with GitLab CI/CD](artifactory_and_gitlab/index.md) | Tutorial | 2017-08-15 | | [How to deploy Maven projects to Artifactory with GitLab CI/CD](artifactory_and_gitlab/index.md) | Tutorial | 2017-08-15 |
| [Making CI Easier with GitLab](https://about.gitlab.com/2017/07/13/making-ci-easier-with-gitlab/) | Concepts | 2017-07-13 | | [Making CI Easier with GitLab](https://about.gitlab.com/2017/07/13/making-ci-easier-with-gitlab/) | Concepts | 2017-07-13 |
| [Dockerizing GitLab Review Apps](https://about.gitlab.com/2017/07/11/dockerizing-review-apps/) | Concepts | 2017-07-11 | | [Dockerizing GitLab Review Apps](https://about.gitlab.com/2017/07/11/dockerizing-review-apps/) | Concepts | 2017-07-11 |
......
# Test and deploy Laravel applications with GitLab CI/CD and Envoy
> **[Article Type](../../development/writing_documentation.md#types-of-technical-articles):** tutorial ||
> **Level:** intermediary ||
> **Author:** [Mehran Rasulian](https://gitlab.com/mehranrasulian) ||
> **Publication date:** 2017-08-31
## Introduction
GitLab features our applications with Continuous Integration, and it is possible to easily deploy the new code changes to the production server whenever we want.
In this tutorial, we'll show you how to initialize a [Laravel](http://laravel.com/) application and setup our [Envoy](https://laravel.com/docs/envoy) tasks, then we'll jump into see how to test and deploy it with [GitLab CI/CD](../../ci/README.md) via [Continuous Delivery](https://about.gitlab.com/2016/08/05/continuous-integration-delivery-and-deployment-with-gitlab/).
We assume you have a basic experience with Laravel, Linux servers,
and you know how to use GitLab.
Laravel is a high quality web framework written in PHP.
It has a great community with a [fantastic documentation](https://laravel.com/docs).
Aside from the usual routing, controllers, requests, responses, views, and (blade) templates, out of the box Laravel provides plenty of additional services such as cache, events, localization, authentication and many others.
We will use [Envoy](https://laravel.com/docs/master/envoy) as an SSH task runner based on PHP.
It uses a clean, minimal [Blade syntax](https://laravel.com/docs/blade) to setup tasks that can run on remote servers, such as, cloning your project from the repository, installing the Composer dependencies, and running [Artisan commands](https://laravel.com/docs/artisan).
## Initialize our Laravel app on GitLab
We assume [you have installed a new laravel project](https://laravel.com/docs/installation#installation), so let's start with a unit test, and initialize Git for the project.
### Unit Test
Every new installation of Laravel (currently 5.4) comes with two type of tests, 'Feature' and 'Unit', placed in the tests directory.
Here's a unit test from `test/Unit/ExampleTest.php`:
```php
<?php
namespace Tests\Unit;
...
class ExampleTest extends TestCase
{
public function testBasicTest()
{
$this->assertTrue(true);
}
}
```
This test is as simple as asserting that the given value is true.
Laravel uses `PHPUnit` for tests by default.
If we run `vendor/bin/phpunit` we should see the green output:
```bash
vendor/bin/phpunit
OK (1 test, 1 assertions)
```
This test will be used later for continuously testing our app with GitLab CI/CD.
### Push to GitLab
Since we have our app up and running locally, it's time to push the codebase to our remote repository.
Let's create [a new project](../../gitlab-basics/create-project.md) in GitLab named `laravel-sample`.
After that, follow the command line instructions displayed on the project's homepage to initiate the repository on our machine and push the first commit.
```bash
cd laravel-sample
git init
git remote add origin git@gitlab.example.com:<USERNAME>/laravel-sample.git
git add .
git commit -m 'Initial Commit'
git push -u origin master
```
## Configure the production server
Before we begin setting up Envoy and GitLab CI/CD, let's quickly make sure the production server is ready for deployment.
We have installed LEMP stack which stands for Linux, Nginx, MySQL and PHP on our Ubuntu 16.04.
### Create a new user
Let's now create a new user that will be used to deploy our website and give it
the needed permissions using [Linux ACL](https://serversforhackers.com/video/linux-acls):
```bash
# Create user deployer
sudo adduser deployer
# Give the read-write-execute permissions to deployer user for directory /var/www
sudo setfacl -R -m u:deployer:rwx /var/www
```
If you don't have ACL installed on your Ubuntu server, use this command to install it:
```bash
sudo apt install acl
```
### Add SSH key
Let's suppose we want to deploy our app to the production server from a private repository on GitLab. First, we need to [generate a new SSH key pair **with no passphrase**](../../ssh/README.md) for the deployer user.
After that, we need to copy the private key, which will be used to connect to our server as the deployer user with SSH, to be able to automate our deployment process:
```bash
# As the deployer user on server
#
# Copy the content of public key to authorized_keys
cat ~/.ssh/id_rsa.pub >> ~/.ssh/authorized_keys
# Copy the private key text block
cat ~/.ssh/id_rsa
```
Now, let's add it to your GitLab project as a [secret variable](../../ci/variables/README.md#secret-variables).
Secret variables are user-defined variables and are stored out of `.gitlab-ci.yml`, for security purposes.
They can be added per project by navigating to the project's **Settings** > **CI/CD**.
![secret variables page](img/secret_variables_page.png)
To the field **KEY**, add the name `SSH_PRIVATE_KEY`, and to the **VALUE** field, paste the private key you've copied earlier.
We'll use this variable in the `.gitlab-ci.yml` later, to easily connect to our remote server as the deployer user without entering its password.
We also need to add the public key to **Project** > **Settings** > **Repository** as [Deploy Keys](../../ssh/README.md/#deploy-keys), which gives us the ability to access our repository from the server through [SSH protocol](../../gitlab-basics/command-line-commands.md/#start-working-on-your-project).
```bash
# As the deployer user on the server
#
# Copy the public key
cat ~/.ssh/id_rsa.pub
```
![deploy keys page](img/deploy_keys_page.png)
To the field **Title**, add any name you want, and paste the public key into the **Key** field.
Now, let's clone our repository on the server just to make sure the `deployer` user has access to the repository.
```bash
# As the deployer user on server
#
git clone git@gitlab.example.com:<USERNAME>/laravel-sample.git
```
>**Note:**
Answer **yes** if asked `Are you sure you want to continue connecting (yes/no)?`.
It adds GitLab.com to the known hosts.
### Configuring Nginx
Now, let's make sure our web server configuration points to the `current/public` rather than `public`.
Open the default Nginx server block configuration file by typing:
```bash
sudo nano /etc/nginx/sites-available/default
```
The configuration should be like this.
```
server {
root /var/www/app/current/public;
server_name example.com;
# Rest of the configuration
}
```
>**Note:**
You may replace the app's name in `/var/www/app/current/public` with the folder name of your application.
## Setting up Envoy
So we have our Laravel app ready for production.
The next thing is to use Envoy to perform the deploy.
To use Envoy, we should first install it on our local machine [using the given instructions by Laravel](https://laravel.com/docs/envoy/#introduction).
### How Envoy works
The pros of Envoy is that it doesn't require Blade engine, it just uses Blade syntax to define tasks.
To start, we create an `Envoy.blade.php` in the root of our app with a simple task to test Envoy.
```php
@servers(['web' => 'remote_username@remote_host'])
@task('list', [on => 'web'])
ls -l
@endtask
```
As you may expect, we have an array within `@servers` directive at the top of the file, which contains a key named `web` with a value of the server's address (e.g. `deployer@192.168.1.1`).
Then within our `@task` directive we define the bash commands that should be run on the server when the task is executed.
On the local machine use the `run` command to run Envoy tasks.
```bash
envoy run list
```
It should execute the `list` task we defined earlier, which connects to the server and lists directory contents.
Envoy is not a dependency of Laravel, therefore you can use it for any PHP application.
### Zero downtime deployment
Every time we deploy to the production server, Envoy downloads the latest release of our app from GitLab repository and replace it with preview's release.
Envoy does this without any [downtime](https://en.wikipedia.org/wiki/Downtime),
so we don't have to worry during the deployment while someone might be reviewing the site.
Our deployment plan is to clone the latest release from GitLab repository, install the Composer dependencies and finally, activate the new release.
#### @setup directive
The first step of our deployment process is to define a set of variables within [@setup](https://laravel.com/docs/envoy/#setup) directive.
You may change the `app` to your application's name:
```php
...
@setup
$repository = 'git@gitlab.example.com:<USERNAME>/laravel-sample.git';
$releases_dir = '/var/www/app/releases';
$app_dir = '/var/www/app';
$release = date('YmdHis');
$new_release_dir = $releases_dir .'/'. $release;
@endsetup
...
```
- `$repository` is the address of our repository
- `$releases_dir` directory is where we deploy the app
- `$app_dir` is the actual location of the app that is live on the server
- `$release` contains a date, so every time that we deploy a new release of our app, we get a new folder with the current date as name
- `$new_release_dir` is the full path of the new release which is used just to make the tasks cleaner
#### @story directive
The [@story](https://laravel.com/docs/envoy/#stories) directive allows us define a list of tasks that can be run as a single task.
Here we have three tasks called `clone_repository`, `run_composer`, `update_symlinks`. These variables are usable to making our task's codes more cleaner:
```php
...
@story('deploy')
clone_repository
run_composer
update_symlinks
@endstory
...
```
Let's create these three tasks one by one.
#### Clone the repository
The first task will create the `releases` directory (if it doesn't exist), and then clone the `master` branch of the repository (by default) into the new release directory, given by the `$new_release_dir` variable.
The `releases` directory will hold all our deployments:
```php
...
@task('clone_repository')
echo 'Cloning repository'
[ -d {{ $releases_dir }} ] || mkdir {{ $releases_dir }}
git clone --depth 1 {{ $repository }} {{ $new_release_dir }}
@endtask
...
```
While our project grows, its Git history will be very very long over time.
Since we are creating a directory per release, it might not be necessary to have the history of the project downloaded for each release.
The `--depth 1` option is a great solution which saves systems time and disk space as well.
#### Installing dependencies with Composer
As you may know, this task just navigates to the new release directory and runs Composer to install the application dependencies:
```php
...
@task('run_composer')
echo "Starting deployment ({{ $release }})"
cd {{ $new_release_dir }}
composer install --prefer-dist --no-scripts -q -o
@endtask
...
```
#### Activate new release
Next thing to do after preparing the requirements of our new release, is to remove the storage directory from it and to create two symbolic links to point the application's `storage` directory and `.env` file to the new release.
Then, we need to create another symbolic link to the new release with the name of `current` placed in the app directory.
The `current` symbolic link always points to the latest release of our app:
```php
...
@task('update_symlinks')
echo "Linking storage directory"
rm -rf {{ $new_release_dir }}/storage
ln -nfs {{ $app_dir }}/storage {{ $new_release_dir }}/storage
echo 'Linking .env file'
ln -nfs {{ $app_dir }}/.env {{ $new_release_dir }}/.env
echo 'Linking current release'
ln -nfs {{ $new_release_dir }} {{ $app_dir }}/current
@endtask
```
As you see, we use `-nfs` as an option for `ln` command, which says that the `storage`, `.env` and `current` no longer points to the preview's release and will point them to the new release by force (`f` from `-nfs` means force), which is the case when we are doing multiple deployments.
### Full script
The script is ready, but make sure to change the `deployer@192.168.1.1` to your server and also change `/var/www/app` with the directory you want to deploy your app.
At the end, our `Envoy.blade.php` file will look like this:
```php
@servers(['web' => 'deployer@192.168.1.1'])
@setup
$repository = 'git@gitlab.example.com:<USERNAME>/laravel-sample.git';
$releases_dir = '/var/www/app/releases';
$app_dir = '/var/www/app';
$release = date('YmdHis');
$new_release_dir = $releases_dir .'/'. $release;
@endsetup
@story('deploy')
clone_repository
run_composer
update_symlinks
@endstory
@task('clone_repository')
echo 'Cloning repository'
[ -d {{ $releases_dir }} ] || mkdir {{ $releases_dir }}
git clone --depth 1 {{ $repository }} {{ $new_release_dir }}
@endtask
@task('run_composer')
echo "Starting deployment ({{ $release }})"
cd {{ $new_release_dir }}
composer install --prefer-dist --no-scripts -q -o
@endtask
@task('update_symlinks')
echo "Linking storage directory"
rm -rf {{ $new_release_dir }}/storage
ln -nfs {{ $app_dir }}/storage {{ $new_release_dir }}/storage
echo 'Linking .env file'
ln -nfs {{ $app_dir }}/.env {{ $new_release_dir }}/.env
echo 'Linking current release'
ln -nfs {{ $new_release_dir }} {{ $app_dir }}/current
@endtask
```
One more thing we should do before any deployment is to manually copy our application `storage` folder to the `/var/www/app` directory on the server for the first time.
You might want to create another Envoy task to do that for you.
We also create the `.env` file in the same path to setup our production environment variables for Laravel.
These are persistent data and will be shared to every new release.
Now, we would need to deploy our app by running `envoy run deploy`, but it won't be necessary since GitLab can handle that for us with CI's [environments](../../ci/environments.md), which will be described [later](#setting-up-gitlab-ci-cd) in this tutorial.
Now it's time to commit [Envoy.blade.php](https://gitlab.com/mehranrasulian/laravel-sample/blob/master/Envoy.blade.php) and push it to the `master` branch.
To keep things simple, we commit directly to `master`, without using [feature-branches](../../workflow/gitlab_flow.md/#github-flow-as-a-simpler-alternative) since collaboration is beyond the scope of this tutorial.
In a real world project, teams may use [Issue Tracker](../../user/project/issues/index.md) and [Merge Requests](../../user/project/merge_requests/index.md) to move their code across branches:
```bash
git add Envoy.blade.php
git commit -m 'Add Envoy'
git push origin master
```
## Continuous Integration with GitLab
We have our app ready on GitLab, and we also can deploy it manually.
But let's take a step forward to do it automatically with [Continuous Delivery](https://about.gitlab.com/2016/08/05/continuous-integration-delivery-and-deployment-with-gitlab/#continuous-delivery) method.
We need to check every commit with a set of automated tests to become aware of issues at the earliest, and then, we can deploy to the target environment if we are happy with the result of the tests.
[GitLab CI/CD](../../ci/README.md) allows us to use [Docker](https://docker.com/) engine to handle the process of testing and deploying our app.
In the case you're not familiar with Docker, refer to [How to Automate Docker Deployments](http://paislee.io/how-to-automate-docker-deployments/).
To be able to build, test, and deploy our app with GitLab CI/CD, we need to prepare our work environment.
To do that, we'll use a Docker image which has the minimum requirements that a Laravel app needs to run.
[There are other ways](../../ci/examples/php.md/#test-php-projects-using-the-docker-executor) to do that as well, but they may lead our builds run slowly, which is not what we want when there are faster options to use.
With Docker images our builds run incredibly faster!
### Create a Container Image
Let's create a [Dockerfile](https://gitlab.com/mehranrasulian/laravel-sample/blob/master/Dockerfile) in the root directory of our app with the following content:
```bash
# Set the base image for subsequent instructions
FROM php:7.1
# Update packages
RUN apt-get update
# Install PHP and composer dependencies
RUN apt-get install -qq git curl libmcrypt-dev libjpeg-dev libpng-dev libfreetype6-dev libbz2-dev
# Clear out the local repository of retrieved package files
RUN apt-get clean
# Install needed extensions
# Here you can install any other extension that you need during the test and deployment process
RUN docker-php-ext-install mcrypt pdo_mysql zip
# Install Composer
RUN curl --silent --show-error https://getcomposer.org/installer | php -- --install-dir=/usr/local/bin --filename=composer
# Install Laravel Envoy
RUN composer global require "laravel/envoy=~1.0"
```
We added the [official PHP 7.1 Docker image](https://hub.docker.com/r/_/php/), which consist of a minimum installation of Debian Jessie with PHP pre-installed, and works perfectly for our use case.
We used `docker-php-ext-install` (provided by the official PHP Docker image) to install the PHP extensions we need.
#### Setting Up GitLab Container Registry
Now that we have our `Dockerfile` let's build and push it to our [GitLab Container Registry](../../user/project/container_registry.md).
> The registry is the place to store and tag images for later use. Developers may want to maintain their own registry for private, company images, or for throw-away images used only in testing. Using GitLab Container Registry means you don't need to set up and administer yet another service or use a public registry.
On your GitLab project repository navigate to the **Registry** tab.
![container registry page empty image](img/container_registry_page_empty_image.png)
You may need to [enable Container Registry](../../user/project/container_registry.md#enable-the-container-registry-for-your-project) to your project to see this tab. You'll find it under your project's **Settings > General > Sharing and permissions**.
![container registry checkbox](img/container_registry_checkbox.png)
To start using Container Registry on our machine, we first need to login to the GitLab registry using our GitLab username and password:
```bash
docker login registry.gitlab.com
```
Then we can build and push our image to GitLab:
```bash
docker build -t registry.gitlab.com/<USERNAME>/laravel-sample .
docker push registry.gitlab.com/<USERNAME>/laravel-sample
```
>**Note:**
To run the above commands, we first need to have [Docker](https://docs.docker.com/engine/installation/) installed on our machine.
Congratulations! You just pushed the first Docker image to the GitLab Registry, and if you refresh the page you should be able to see it:
![container registry page with image](img/container_registry_page_with_image.jpg)
>**Note:**
You can also [use GitLab CI/CD](https://about.gitlab.com/2016/05/23/gitlab-container-registry/#use-with-gitlab-ci) to build and push your Docker images, rather than doing that on your machine.
We'll use this image further down in the `.gitlab-ci.yml` configuration file to handle the process of testing and deploying our app.
Let's commit the `Dockerfile` file.
```bash
git add Dockerfile
git commit -m 'Add Dockerfile'
git push origin master
```
### Setting up GitLab CI/CD
In order to build and test our app with GitLab CI/CD, we need a file called `.gitlab-ci.yml` in our repository's root. It is similar to Circle CI and Travis CI, but built-in GitLab.
Our `.gitlab-ci.yml` file will look like this:
```yaml
image: registry.gitlab.com/<USERNAME>/laravel-sample:latest
services:
- mysql:5.7
variables:
MYSQL_DATABASE: homestead
MYSQL_ROOT_PASSWORD: secret
DB_HOST: mysql
DB_USERNAME: root
stages:
- test
- deploy
unit_test:
stage: test
script:
- composer install
- cp .env.example .env
- php artisan key:generate
- php artisan migrate
- vendor/bin/phpunit
deploy_production:
stage: deploy
script:
- 'which ssh-agent || ( apt-get update -y && apt-get install openssh-client -y )'
- eval $(ssh-agent -s)
- ssh-add <(echo "$SSH_PRIVATE_KEY")
- mkdir -p ~/.ssh
- '[[ -f /.dockerenv ]] && echo -e "Host *\n\tStrictHostKeyChecking no\n\n" > ~/.ssh/config'
- ~/.composer/vendor/bin/envoy run deploy
environment:
name: production
url: http://192.168.1.1
when: manual
only:
- master
```
That's a lot to take in, isn't it? Let's run through it step by step.
#### Image and Services
[GitLab Runners](../../ci/runners/README.md) run the script defined by `.gitlab-ci.yml`.
The `image` keyword tells the Runners which image to use.
The `services` keyword defines additional images [that are linked to the main image](../../ci/docker/using_docker_images.md/#what-is-a-service).
Here we use the container image we created before as our main image and also use MySQL 5.7 as a service.
```yaml
image: registry.gitlab.com/<USERNAME>/laravel-sample:latest
services:
- mysql:5.7
...
```
>**Note:**
If you wish to test your app with different PHP versions and [database management systems](../../ci/services/README.md), you can define different `image` and `services` keywords for each test job.
#### Variables
GitLab CI/CD allows us to use [environment variables](../../ci/yaml/README.md#variables) in our jobs.
We defined MySQL as our database management system, which comes with a superuser root created by default.
So we should adjust the configuration of MySQL instance by defining `MYSQL_DATABASE` variable as our database name and `MYSQL_ROOT_PASSWORD` variable as the password of `root`.
Find out more about MySQL variables at the [official MySQL Docker Image](https://hub.docker.com/r/_/mysql/).
Also set the variables `DB_HOST` to `mysql` and `DB_USERNAME` to `root`, which are Laravel specific variables.
We define `DB_HOST` as `mysql` instead of `127.0.0.1`, as we use MySQL Docker image as a service which [is linked to the main Docker image](../../ci/docker/using_docker_images.md/#how-services-are-linked-to-the-build).
```yaml
...
variables:
MYSQL_DATABASE: homestead
MYSQL_ROOT_PASSWORD: secret
DB_HOST: mysql
DB_USERNAME: root
...
```
#### Unit Test as the first job
We defined the required shell scripts as an array of the [script](../../ci/yaml/README.md#script) variable to be executed when running `unit_test` job.
These scripts are some Artisan commands to prepare the Laravel, and, at the end of the script, we'll run the tests by `PHPUnit`.
```yaml
...
unit_test:
script:
# Install app dependencies
- composer install
# Setup .env
- cp .env.example .env
# Generate an environment key
- php artisan key:generate
# Run migrations
- php artisan migrate
# Run tests
- vendor/bin/phpunit
...
```
#### Deploy to production
The job `deploy_production` will deploy the app to the production server.
To deploy our app with Envoy, we had to set up the `$SSH_PRIVATE_KEY` variable as an [SSH private key](../../ci/ssh_keys/README.md/#ssh-keys-when-using-the-docker-executor).
If the SSH keys have added successfully, we can run Envoy.
As mentioned before, GitLab supports [Continuous Delivery](https://about.gitlab.com/2016/08/05/continuous-integration-delivery-and-deployment-with-gitlab/#continuous-delivery) methods as well.
The [environment](../../ci/yaml/README.md#environment) keyword tells GitLab that this job deploys to the `production` environment.
The `url` keyword is used to generate a link to our application on the GitLab Environments page.
The `only` keyword tells GitLab CI that the job should be executed only when the pipeline is building the `master` branch.
Lastly, `when: manual` is used to turn the job from running automatically to a manual action.
```yaml
...
deploy_production:
script:
# Add the private SSH key to the build environment
- 'which ssh-agent || ( apt-get update -y && apt-get install openssh-client -y )'
- eval $(ssh-agent -s)
- ssh-add <(echo "$SSH_PRIVATE_KEY")
- mkdir -p ~/.ssh
- '[[ -f /.dockerenv ]] && echo -e "Host *\n\tStrictHostKeyChecking no\n\n" > ~/.ssh/config'
# Run Envoy
- ~/.composer/vendor/bin/envoy run deploy
environment:
name: production
url: http://192.168.1.1
when: manual
only:
- master
```
You may also want to add another job for [staging environment](https://about.gitlab.com/2016/08/26/ci-deployment-and-environments), to final test your application before deploying to production.
### Turn on GitLab CI/CD
We have prepared everything we need to test and deploy our app with GitLab CI/CD.
To do that, commit and push `.gitlab-ci.yml` to the `master` branch. It will trigger a pipeline, which you can watch live under your project's **Pipelines**.
![pipelines page](img/pipelines_page.png)
Here we see our **Test** and **Deploy** stages.
The **Test** stage has the `unit_test` build running.
click on it to see the Runner's output.
![pipeline page](img/pipeline_page.png)
After our code passed through the pipeline successfully, we can deploy to our production server by clicking the **play** button on the right side.
![pipelines page deploy button](img/pipelines_page_deploy_button.png)
Once the deploy pipeline passed successfully, navigate to **Pipelines > Environments**.
![environments page](img/environments_page.png)
If something doesn't work as expected, you can roll back to the latest working version of your app.
![environment page](img/environment_page.png)
By clicking on the external link icon specified on the right side, GitLab opens the production website.
Our deployment successfully was done and we can see the application is live.
![laravel welcome page](img/laravel_welcome_page.png)
In the case that you're interested to know how is the application directory structure on the production server after deployment, here are three directories named `current`, `releases` and `storage`.
As you know, the `current` directory is a symbolic link that points to the latest release.
The `.env` file consists of our Laravel environment variables.
![production server app directory](img/production_server_app_directory.png)
If you navigate to the `current` directory, you should see the application's content.
As you see, the `.env` is pointing to the `/var/www/app/.env` file and also `storage` is pointing to the `/var/www/app/storage/` directory.
![production server current directory](img/production_server_current_directory.png)
## Conclusion
We configured GitLab CI to perform automated tests and used the method of [Continuous Delivery](https://continuousdelivery.com/) to deploy to production a Laravel application with Envoy, directly from the codebase.
Envoy also was a great match to help us deploy the application without writing our custom bash script and doing Linux magics.
...@@ -3,7 +3,7 @@ ...@@ -3,7 +3,7 @@
> **Article [Type](../../development/writing_documentation.md#types-of-technical-articles):** tutorial || > **Article [Type](../../development/writing_documentation.md#types-of-technical-articles):** tutorial ||
> **Level:** intermediary || > **Level:** intermediary ||
> **Author:** [Crt Mori](https://gitlab.com/Letme) || > **Author:** [Crt Mori](https://gitlab.com/Letme) ||
> **Publication date:** 2017/08/17 > **Publication date:** 2017-08-17
## Introduction ## Introduction
......
...@@ -114,6 +114,7 @@ Here is an collection of tutorials and guides on setting up your CI pipeline. ...@@ -114,6 +114,7 @@ Here is an collection of tutorials and guides on setting up your CI pipeline.
- [Run PHP Composer & NPM scripts then deploy them to a staging server](examples/deployment/composer-npm-deploy.md) - [Run PHP Composer & NPM scripts then deploy them to a staging server](examples/deployment/composer-npm-deploy.md)
- [Analyze code quality with the Code Climate CLI](examples/code_climate.md) - [Analyze code quality with the Code Climate CLI](examples/code_climate.md)
- **Articles** - **Articles**
- [How to test and deploy Laravel/PHP applications with GitLab CI/CD and Envoy](../articles/laravel_with_gitlab_and_envoy/index.md)
- [How to deploy Maven projects to Artifactory with GitLab CI/CD](../articles/artifactory_and_gitlab/index.md) - [How to deploy Maven projects to Artifactory with GitLab CI/CD](../articles/artifactory_and_gitlab/index.md)
- [Automated Debian packaging](https://about.gitlab.com/2016/10/12/automated-debian-package-build-with-gitlab-ci/) - [Automated Debian packaging](https://about.gitlab.com/2016/10/12/automated-debian-package-build-with-gitlab-ci/)
- [Spring boot application with GitLab CI and Kubernetes](https://about.gitlab.com/2016/12/14/continuous-delivery-of-a-spring-boot-application-with-gitlab-ci-and-kubernetes/) - [Spring boot application with GitLab CI and Kubernetes](https://about.gitlab.com/2016/12/14/continuous-delivery-of-a-spring-boot-application-with-gitlab-ci-and-kubernetes/)
......
...@@ -7,6 +7,38 @@ describe ProjectsController do ...@@ -7,6 +7,38 @@ describe ProjectsController do
let(:jpg) { fixture_file_upload(Rails.root + 'spec/fixtures/rails_sample.jpg', 'image/jpg') } let(:jpg) { fixture_file_upload(Rails.root + 'spec/fixtures/rails_sample.jpg', 'image/jpg') }
let(:txt) { fixture_file_upload(Rails.root + 'spec/fixtures/doc_sample.txt', 'text/plain') } let(:txt) { fixture_file_upload(Rails.root + 'spec/fixtures/doc_sample.txt', 'text/plain') }
describe 'GET new' do
context 'with an authenticated user' do
let(:group) { create(:group) }
before do
sign_in(user)
end
context 'when namespace_id param is present' do
context 'when user has access to the namespace' do
it 'renders the template' do
group.add_owner(user)
get :new, namespace_id: group.id
expect(response).to have_http_status(200)
expect(response).to render_template('new')
end
end
context 'when user does not have access to the namespace' do
it 'responds with status 404' do
get :new, namespace_id: group.id
expect(response).to have_http_status(404)
expect(response).not_to render_template('new')
end
end
end
end
end
describe 'GET index' do describe 'GET index' do
context 'as a user' do context 'as a user' do
it 'redirects to root page' do it 'redirects to root page' do
......
require 'spec_helper' require 'spec_helper'
feature 'New project' do feature 'New project' do
include Select2Helper
let(:user) { create(:admin) } let(:user) { create(:admin) }
before do before do
...@@ -68,26 +70,10 @@ feature 'New project' do ...@@ -68,26 +70,10 @@ feature 'New project' do
expect(namespace.text).to eq group.name expect(namespace.text).to eq group.name
end end
context 'on validation error' do
before do
fill_in('project_path', with: 'private-group-project')
choose('Internal')
click_button('Create project')
expect(page).to have_css '.project-edit-errors .alert.alert-danger'
end
it 'selects the group namespace' do
namespace = find('#project_namespace_id option[selected]')
expect(namespace.text).to eq group.name
end
end
end end
context 'with subgroup namespace' do context 'with subgroup namespace' do
let(:group) { create(:group, :private, owner: user) } let(:group) { create(:group, owner: user) }
let(:subgroup) { create(:group, parent: group) } let(:subgroup) { create(:group, parent: group) }
before do before do
...@@ -101,6 +87,41 @@ feature 'New project' do ...@@ -101,6 +87,41 @@ feature 'New project' do
expect(namespace.text).to eq subgroup.full_path expect(namespace.text).to eq subgroup.full_path
end end
end end
context 'when changing namespaces dynamically', :js do
let(:public_group) { create(:group, :public) }
let(:internal_group) { create(:group, :internal) }
let(:private_group) { create(:group, :private) }
before do
public_group.add_owner(user)
internal_group.add_owner(user)
private_group.add_owner(user)
visit new_project_path(namespace_id: public_group.id)
end
it 'enables the correct visibility options' do
select2(user.namespace_id, from: '#project_namespace_id')
expect(find("#project_visibility_level_#{Gitlab::VisibilityLevel::PRIVATE}")).not_to be_disabled
expect(find("#project_visibility_level_#{Gitlab::VisibilityLevel::INTERNAL}")).not_to be_disabled
expect(find("#project_visibility_level_#{Gitlab::VisibilityLevel::PUBLIC}")).not_to be_disabled
select2(public_group.id, from: '#project_namespace_id')
expect(find("#project_visibility_level_#{Gitlab::VisibilityLevel::PRIVATE}")).not_to be_disabled
expect(find("#project_visibility_level_#{Gitlab::VisibilityLevel::INTERNAL}")).not_to be_disabled
expect(find("#project_visibility_level_#{Gitlab::VisibilityLevel::PUBLIC}")).not_to be_disabled
select2(internal_group.id, from: '#project_namespace_id')
expect(find("#project_visibility_level_#{Gitlab::VisibilityLevel::PRIVATE}")).not_to be_disabled
expect(find("#project_visibility_level_#{Gitlab::VisibilityLevel::INTERNAL}")).not_to be_disabled
expect(find("#project_visibility_level_#{Gitlab::VisibilityLevel::PUBLIC}")).to be_disabled
select2(private_group.id, from: '#project_namespace_id')
expect(find("#project_visibility_level_#{Gitlab::VisibilityLevel::PRIVATE}")).not_to be_disabled
expect(find("#project_visibility_level_#{Gitlab::VisibilityLevel::INTERNAL}")).to be_disabled
expect(find("#project_visibility_level_#{Gitlab::VisibilityLevel::PUBLIC}")).to be_disabled
end
end
end end
context 'Import project options' do context 'Import project options' do
......
...@@ -58,35 +58,82 @@ describe VisibilityLevelHelper do ...@@ -58,35 +58,82 @@ describe VisibilityLevelHelper do
end end
end end
describe "skip_level?" do describe "disallowed_visibility_level?" do
describe "forks" do describe "forks" do
let(:project) { create(:project, :internal) } let(:project) { create(:project, :internal) }
let(:fork_project) { create(:project, forked_from_project: project) } let(:fork_project) { create(:project, forked_from_project: project) }
it "skips levels" do it "disallows levels" do
expect(skip_level?(fork_project, Gitlab::VisibilityLevel::PUBLIC)).to be_truthy expect(disallowed_visibility_level?(fork_project, Gitlab::VisibilityLevel::PUBLIC)).to be_truthy
expect(skip_level?(fork_project, Gitlab::VisibilityLevel::INTERNAL)).to be_falsey expect(disallowed_visibility_level?(fork_project, Gitlab::VisibilityLevel::INTERNAL)).to be_falsey
expect(skip_level?(fork_project, Gitlab::VisibilityLevel::PRIVATE)).to be_falsey expect(disallowed_visibility_level?(fork_project, Gitlab::VisibilityLevel::PRIVATE)).to be_falsey
end end
end end
describe "non-forked project" do describe "non-forked project" do
let(:project) { create(:project, :internal) } let(:project) { create(:project, :internal) }
it "skips levels" do it "disallows levels" do
expect(skip_level?(project, Gitlab::VisibilityLevel::PUBLIC)).to be_falsey expect(disallowed_visibility_level?(project, Gitlab::VisibilityLevel::PUBLIC)).to be_falsey
expect(skip_level?(project, Gitlab::VisibilityLevel::INTERNAL)).to be_falsey expect(disallowed_visibility_level?(project, Gitlab::VisibilityLevel::INTERNAL)).to be_falsey
expect(skip_level?(project, Gitlab::VisibilityLevel::PRIVATE)).to be_falsey expect(disallowed_visibility_level?(project, Gitlab::VisibilityLevel::PRIVATE)).to be_falsey
end end
end end
describe "Snippet" do describe "group" do
let(:group) { create(:group, :internal) }
it "disallows levels" do
expect(disallowed_visibility_level?(group, Gitlab::VisibilityLevel::PUBLIC)).to be_falsey
expect(disallowed_visibility_level?(group, Gitlab::VisibilityLevel::INTERNAL)).to be_falsey
expect(disallowed_visibility_level?(group, Gitlab::VisibilityLevel::PRIVATE)).to be_falsey
end
end
describe "sub-group" do
let(:group) { create(:group, :private) }
let(:subgroup) { create(:group, :private, parent: group) }
it "disallows levels" do
expect(disallowed_visibility_level?(subgroup, Gitlab::VisibilityLevel::PUBLIC)).to be_truthy
expect(disallowed_visibility_level?(subgroup, Gitlab::VisibilityLevel::INTERNAL)).to be_truthy
expect(disallowed_visibility_level?(subgroup, Gitlab::VisibilityLevel::PRIVATE)).to be_falsey
end
end
describe "snippet" do
let(:snippet) { create(:snippet, :internal) } let(:snippet) { create(:snippet, :internal) }
it "skips levels" do it "disallows levels" do
expect(skip_level?(snippet, Gitlab::VisibilityLevel::PUBLIC)).to be_falsey expect(disallowed_visibility_level?(snippet, Gitlab::VisibilityLevel::PUBLIC)).to be_falsey
expect(skip_level?(snippet, Gitlab::VisibilityLevel::INTERNAL)).to be_falsey expect(disallowed_visibility_level?(snippet, Gitlab::VisibilityLevel::INTERNAL)).to be_falsey
expect(skip_level?(snippet, Gitlab::VisibilityLevel::PRIVATE)).to be_falsey expect(disallowed_visibility_level?(snippet, Gitlab::VisibilityLevel::PRIVATE)).to be_falsey
end
end
end
describe "disallowed_visibility_level_description" do
let(:group) { create(:group, :internal) }
let!(:subgroup) { create(:group, :internal, parent: group) }
let!(:project) { create(:project, :internal, group: group) }
describe "project" do
it "provides correct description for disabled levels" do
expect(disallowed_visibility_level?(project, Gitlab::VisibilityLevel::PUBLIC)).to be_truthy
expect(strip_tags disallowed_visibility_level_description(Gitlab::VisibilityLevel::PUBLIC, project))
.to include "the visibility of #{project.group.name} is internal"
end
end
describe "group" do
it "provides correct description for disabled levels" do
expect(disallowed_visibility_level?(group, Gitlab::VisibilityLevel::PRIVATE)).to be_truthy
expect(disallowed_visibility_level_description(Gitlab::VisibilityLevel::PRIVATE, group))
.to include "it contains projects with higher visibility", "it contains sub-groups with higher visibility"
expect(disallowed_visibility_level?(subgroup, Gitlab::VisibilityLevel::PUBLIC)).to be_truthy
expect(strip_tags disallowed_visibility_level_description(Gitlab::VisibilityLevel::PUBLIC, subgroup))
.to include "the visibility of #{group.name} is internal"
end end
end end
end end
......
...@@ -84,6 +84,83 @@ describe Group do ...@@ -84,6 +84,83 @@ describe Group do
expect(group).not_to be_valid expect(group).not_to be_valid
end end
end end
describe '#visibility_level_allowed_by_parent' do
let(:parent) { create(:group, :internal) }
let(:sub_group) { build(:group, parent_id: parent.id) }
context 'without a parent' do
it 'is valid' do
sub_group.parent_id = nil
expect(sub_group).to be_valid
end
end
context 'with a parent' do
context 'when visibility of sub group is greater than the parent' do
it 'is invalid' do
sub_group.visibility_level = Gitlab::VisibilityLevel::PUBLIC
expect(sub_group).to be_invalid
end
end
context 'when visibility of sub group is lower or equal to the parent' do
[Gitlab::VisibilityLevel::INTERNAL, Gitlab::VisibilityLevel::PRIVATE].each do |level|
it 'is valid' do
sub_group.visibility_level = level
expect(sub_group).to be_valid
end
end
end
end
end
describe '#visibility_level_allowed_by_projects' do
let!(:internal_group) { create(:group, :internal) }
let!(:internal_project) { create(:project, :internal, group: internal_group) }
context 'when group has a lower visibility' do
it 'is invalid' do
internal_group.visibility_level = Gitlab::VisibilityLevel::PRIVATE
expect(internal_group).to be_invalid
expect(internal_group.errors[:visibility_level]).to include('private is not allowed since this group contains projects with higher visibility.')
end
end
context 'when group has a higher visibility' do
it 'is valid' do
internal_group.visibility_level = Gitlab::VisibilityLevel::PUBLIC
expect(internal_group).to be_valid
end
end
end
describe '#visibility_level_allowed_by_sub_groups' do
let!(:internal_group) { create(:group, :internal) }
let!(:internal_sub_group) { create(:group, :internal, parent: internal_group) }
context 'when parent group has a lower visibility' do
it 'is invalid' do
internal_group.visibility_level = Gitlab::VisibilityLevel::PRIVATE
expect(internal_group).to be_invalid
expect(internal_group.errors[:visibility_level]).to include('private is not allowed since there are sub-groups with higher visibility.')
end
end
context 'when parent group has a higher visibility' do
it 'is valid' do
internal_group.visibility_level = Gitlab::VisibilityLevel::PUBLIC
expect(internal_group).to be_valid
end
end
end
end end
describe '.visible_to_user' do describe '.visible_to_user' do
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment