mirror of
https://github.com/freedombox/FreedomBox.git
synced 2026-11-29 08:25:10 +00:00
gitweb: Allow to import from a remote repository
- Allow to enter either name or URL when creating repository - Validate a repository URL, allow only http and https schemes - Set autocomplete off on the name/URL field because URL may contain username:password - Check whether the repository actually exists before cloning - Show progress info while cloning - Actions script: new subcommand check-repo-exists and new arguments for the create-repo: --url, --prepare-only and --skip-prepare - Add test for invalid URLs Closes #1670 Signed-off-by: Veiko Aasa <veiko17@disroot.org> [sunil: Fix validating repo name in edit form] [sunil: Don't pipe stdin of clone process, it may lead to a hang] [sunil: Always run clone process with 'C' locale since we are parsing output] [sunil: Cosmetic changes] Signed-off-by: Sunil Mohan Adapa <sunil@medhas.org> Reviewed-by: Sunil Mohan Adapa <sunil@medhas.org>
This commit is contained in:
1 parent
ca0c991562
commit
c99b33b40e
6 files changed
+378
-88
No files matched your search
@@ -26,10 +26,12 @@ from django.utils.translation import ugettext_lazy as _
|
||||
from plinth import action_utils, actions
|
||||
from plinth import app as app_module
|
||||
from plinth import frontpage, menu
|
||||
from plinth.errors import ActionError
|
||||
from plinth.modules.apache.components import Webserver
|
||||
from plinth.modules.firewall.components import Firewall
|
||||
from plinth.modules.users import register_group
|
||||
|
||||
from .forms import is_repo_url
|
||||
from .manifest import GIT_REPO_PATH, backup, clients # noqa, pylint: disable=unused-import
|
||||
|
||||
clients = clients
|
||||
@@ -102,13 +104,26 @@ class GitwebApp(app_module.App):
|
||||
repos = []
|
||||
if os.path.exists(GIT_REPO_PATH):
|
||||
for repo in os.listdir(GIT_REPO_PATH):
|
||||
if not repo.endswith('.git'):
|
||||
if not repo.endswith('.git') or repo.startswith('.'):
|
||||
continue
|
||||
|
||||
repo_info = {}
|
||||
repo_info['name'] = repo[:-4]
|
||||
|
||||
private_file = os.path.join(GIT_REPO_PATH, repo, 'private')
|
||||
access = 'public'
|
||||
if os.path.exists(private_file):
|
||||
access = 'private'
|
||||
repos.append({'name': repo[:-4], 'access': access})
|
||||
repo_info['access'] = 'private'
|
||||
else:
|
||||
repo_info['access'] = 'public'
|
||||
|
||||
progress_file = os.path.join(GIT_REPO_PATH, repo,
|
||||
'clone_progress')
|
||||
if os.path.exists(progress_file):
|
||||
with open(progress_file) as file_handle:
|
||||
clone_progress = file_handle.read()
|
||||
repo_info['clone_progress'] = clone_progress
|
||||
|
||||
repos.append(repo_info)
|
||||
|
||||
return sorted(repos, key=lambda repo: repo['name'])
|
||||
|
||||
@@ -189,21 +204,36 @@ def restore_post(packet):
|
||||
app.update_service_access()
|
||||
|
||||
|
||||
def repo_exists(name):
|
||||
"""Check whether a remote repository exists."""
|
||||
try:
|
||||
actions.run('gitweb', ['check-repo-exists', '--url', name])
|
||||
except ActionError:
|
||||
return False
|
||||
|
||||
return True
|
||||
|
||||
|
||||
def have_public_repos(repos):
|
||||
"""Check for public repositories"""
|
||||
return any((repo['access'] == 'public' for repo in repos))
|
||||
|
||||
|
||||
def create_repo(repo, repo_description, owner, is_private):
|
||||
"""Create a new repository by calling the action script."""
|
||||
args = [
|
||||
'create-repo', '--name', repo, '--description', repo_description,
|
||||
'--owner', owner
|
||||
]
|
||||
"""Create a new repository or clone a remote repository."""
|
||||
args = ['--description', repo_description, '--owner', owner]
|
||||
if is_private:
|
||||
args.append('--is-private')
|
||||
|
||||
actions.superuser_run('gitweb', args)
|
||||
if is_repo_url(repo):
|
||||
args = ['create-repo', '--url', repo] + args
|
||||
# create a repo directory and set correct access rights
|
||||
actions.superuser_run('gitweb', args + ['--prepare-only'])
|
||||
# start cloning in background
|
||||
actions.superuser_run('gitweb', args + ['--skip-prepare'],
|
||||
run_in_background=True)
|
||||
else:
|
||||
args = ['create-repo', '--name', repo] + args
|
||||
actions.superuser_run('gitweb', args)
|
||||
|
||||
|
||||
def repo_info(repo):
|
||||
|
||||
@@ -19,37 +19,65 @@ Django form for configuring Gitweb.
|
||||
"""
|
||||
|
||||
import re
|
||||
from urllib.parse import urlparse
|
||||
|
||||
from django import forms
|
||||
from django.core.exceptions import ValidationError
|
||||
from django.core.validators import URLValidator
|
||||
from django.utils.translation import ugettext_lazy as _
|
||||
|
||||
from plinth.modules import gitweb
|
||||
|
||||
|
||||
def validate_repository(name):
|
||||
"""Validate a Git repository name."""
|
||||
|
||||
if not re.match(r'^[a-zA-Z0-9-._]+$', name):
|
||||
raise ValidationError(_('Invalid repository name.'))
|
||||
|
||||
if name.startswith(('-', '.')):
|
||||
raise ValidationError(_('Invalid repository name.'))
|
||||
|
||||
if name.endswith('.git.git'):
|
||||
raise ValidationError(_('Invalid repository name.'))
|
||||
def get_name_from_url(url):
|
||||
"""Get a repository name from URL"""
|
||||
return urlparse(url).path.split('/')[-1]
|
||||
|
||||
|
||||
class EditRepoForm(forms.Form):
|
||||
def is_repo_url(url):
|
||||
"""Check if URL is valid."""
|
||||
try:
|
||||
RepositoryValidator(input_should_be='url')(url)
|
||||
except ValidationError:
|
||||
return False
|
||||
|
||||
return True
|
||||
|
||||
|
||||
class RepositoryValidator:
|
||||
input_should_be = 'name'
|
||||
|
||||
def __init__(self, input_should_be=None):
|
||||
if input_should_be is not None:
|
||||
self.input_should_be = input_should_be
|
||||
|
||||
def __call__(self, value):
|
||||
"""Validate that the input is a correct repository name or URL"""
|
||||
if self.input_should_be in ('url', 'url_or_name'):
|
||||
try:
|
||||
URLValidator(schemes=['http', 'https'],
|
||||
message=_('Invalid repository URL.'))(value)
|
||||
except ValidationError:
|
||||
if self.input_should_be == 'url':
|
||||
raise
|
||||
else:
|
||||
value = get_name_from_url(value)
|
||||
|
||||
if (not re.match(r'^[a-zA-Z0-9-._]+$', value)) \
|
||||
or value.startswith(('-', '.')) \
|
||||
or value.endswith('.git.git'):
|
||||
raise ValidationError(_('Invalid repository name.'), 'invalid')
|
||||
|
||||
|
||||
class CreateRepoForm(forms.Form):
|
||||
"""Form to create and edit a new repository."""
|
||||
|
||||
name = forms.CharField(
|
||||
label=_('Name of the repository'),
|
||||
strip=True,
|
||||
validators=[validate_repository],
|
||||
help_text=_(
|
||||
'An alpha-numeric string that uniquely identifies a repository.'),
|
||||
)
|
||||
label=_(
|
||||
'Name of a new repository or URL to import an existing repository.'
|
||||
), strip=True,
|
||||
validators=[RepositoryValidator(input_should_be='url_or_name')],
|
||||
widget=forms.TextInput(attrs={'autocomplete': 'off'}))
|
||||
|
||||
description = forms.CharField(
|
||||
label=_('Description of the repository'), strip=True, required=False,
|
||||
@@ -68,6 +96,40 @@ class EditRepoForm(forms.Form):
|
||||
super().__init__(*args, **kwargs)
|
||||
self.fields['name'].widget.attrs.update({'autofocus': 'autofocus'})
|
||||
|
||||
def clean_name(self):
|
||||
"""Check if the name is valid."""
|
||||
name = self.cleaned_data['name']
|
||||
|
||||
repo_name = name
|
||||
if is_repo_url(name):
|
||||
repo_name = get_name_from_url(name)
|
||||
|
||||
if repo_name.endswith('.git'):
|
||||
repo_name = repo_name[:-4]
|
||||
|
||||
for repo in gitweb.app.get_repo_list():
|
||||
if repo_name == repo['name']:
|
||||
raise ValidationError(
|
||||
_('A repository with this name already exists.'))
|
||||
|
||||
if is_repo_url(name):
|
||||
if not gitweb.repo_exists(name):
|
||||
raise ValidationError('Remote repository is not available.')
|
||||
|
||||
return name
|
||||
|
||||
|
||||
class EditRepoForm(CreateRepoForm):
|
||||
"""Form to create and edit a new repository."""
|
||||
|
||||
name = forms.CharField(
|
||||
label=_('Name of the repository'),
|
||||
strip=True,
|
||||
validators=[RepositoryValidator()],
|
||||
help_text=_(
|
||||
'An alpha-numeric string that uniquely identifies a repository.'),
|
||||
)
|
||||
|
||||
def clean_name(self):
|
||||
"""Check if the name is valid."""
|
||||
name = self.cleaned_data['name']
|
||||
|
||||
@@ -20,6 +20,7 @@
|
||||
|
||||
{% load bootstrap %}
|
||||
{% load i18n %}
|
||||
{% load static %}
|
||||
|
||||
{% block page_head %}
|
||||
<style type="text/css">
|
||||
@@ -33,6 +34,9 @@
|
||||
.list-group-item .btn {
|
||||
margin: -5px 2px;
|
||||
}
|
||||
.repo-cloning {
|
||||
margin: 0px 10px;
|
||||
}
|
||||
</style>
|
||||
{% endblock %}
|
||||
|
||||
@@ -58,13 +62,13 @@
|
||||
{% for repo in repos %}
|
||||
<div class="list-group-item clearfix">
|
||||
<a href="{% url 'gitweb:delete' repo.name %}"
|
||||
class="btn btn-default btn-sm pull-right"
|
||||
class="btn btn-default btn-sm pull-right {% if 'clone_progress' in repo %} disabled {% endif %}"
|
||||
role="button"
|
||||
title="{% blocktrans %}Delete repository {{ repo.name }}{% endblocktrans %}">
|
||||
<span class="fa fa-trash-o" aria-hidden="true"></span>
|
||||
</a>
|
||||
|
||||
<a class="repo-edit btn btn-sm btn-default pull-right"
|
||||
<a class="repo-edit btn btn-sm btn-default pull-right {% if 'clone_progress' in repo %} disabled {% endif %}"
|
||||
href="{% url 'gitweb:edit' repo.name %}">
|
||||
<span class="fa fa-pencil-square-o" aria-hidden="true"></span>
|
||||
</a>
|
||||
@@ -74,10 +78,17 @@
|
||||
aria-label="private"></span>
|
||||
{% endif %}
|
||||
|
||||
<a class="repo-label" href="/gitweb/{{ repo.name }}.git"
|
||||
title="{% blocktrans %}Go to repository {{ repo.name }}{% endblocktrans %}">
|
||||
{{ repo.name }}
|
||||
</a>
|
||||
{% if 'clone_progress' in repo %}
|
||||
<span class="repo-cloning pull-right">
|
||||
{% trans 'Cloning...' %} {{ repo.clone_progress }}%
|
||||
</span>
|
||||
<span class="repo-label">{{ repo.name }}<span>
|
||||
{% else %}
|
||||
<a class="repo-label" href="/gitweb/{{ repo.name }}.git"
|
||||
title="{% blocktrans %}Go to repository {{ repo.name }}{% endblocktrans %}">
|
||||
{{ repo.name }}
|
||||
</a>
|
||||
{% endif %}
|
||||
</div>
|
||||
{% endfor %}
|
||||
</div>
|
||||
@@ -86,3 +97,12 @@
|
||||
</div>
|
||||
|
||||
{% endblock %}
|
||||
|
||||
|
||||
{% block page_js %}
|
||||
|
||||
{% if cloning %}
|
||||
<script type="text/javascript" src="{% static 'theme/js/refresh.js' %}"></script>
|
||||
{% endif %}
|
||||
|
||||
{% endblock %}
|
||||
@@ -104,3 +104,16 @@ def test_action_create_repo_with_invalid_names(call_action, name):
|
||||
'create-repo', '--name', name, '--description', '', '--owner', '',
|
||||
'--keep-ownership'
|
||||
])
|
||||
|
||||
|
||||
@pytest.mark.parametrize('url', [
|
||||
'Test-repo', 'file://root/Test-repo', 'localhost/Test-repo',
|
||||
'ssh://localhost/Test-repo', 'https://localhost/.Test-repo'
|
||||
])
|
||||
def test_action_create_repo_with_invalid_urls(call_action, url):
|
||||
"""Test that cloning repository with invalid URL fails."""
|
||||
with pytest.raises(ValidationError):
|
||||
call_action([
|
||||
'create-repo', '--url', url, '--description', '', '--owner', '',
|
||||
'--keep-ownership'
|
||||
])
|
||||
@@ -31,7 +31,7 @@ from plinth import actions, views
|
||||
from plinth.errors import ActionError
|
||||
from plinth.modules import gitweb
|
||||
|
||||
from .forms import EditRepoForm
|
||||
from .forms import CreateRepoForm, EditRepoForm
|
||||
|
||||
|
||||
class GitwebAppView(views.AppView):
|
||||
@@ -48,14 +48,16 @@ class GitwebAppView(views.AppView):
|
||||
def get_context_data(self, *args, **kwargs):
|
||||
"""Add repositories to the context data."""
|
||||
context = super().get_context_data(*args, **kwargs)
|
||||
context['repos'] = gitweb.app.get_repo_list()
|
||||
repos = gitweb.app.get_repo_list()
|
||||
context['repos'] = repos
|
||||
context['cloning'] = any('clone_progress' in repo for repo in repos)
|
||||
return context
|
||||
|
||||
|
||||
class CreateRepoView(SuccessMessageMixin, FormView):
|
||||
"""View to create a new repository."""
|
||||
|
||||
form_class = EditRepoForm
|
||||
form_class = CreateRepoForm
|
||||
prefix = 'gitweb'
|
||||
template_name = 'gitweb_create_edit.html'
|
||||
success_url = reverse_lazy('gitweb:index')
|
||||
@@ -75,9 +77,13 @@ class CreateRepoView(SuccessMessageMixin, FormView):
|
||||
form_data[key] = ''
|
||||
else:
|
||||
form_data[key] = value
|
||||
|
||||
gitweb.create_repo(form_data['name'], form_data['description'],
|
||||
form_data['owner'], form_data['is_private'])
|
||||
try:
|
||||
gitweb.create_repo(form_data['name'], form_data['description'],
|
||||
form_data['owner'], form_data['is_private'])
|
||||
except ActionError:
|
||||
messages.error(
|
||||
self.request,
|
||||
_('An error occurred while creating the repository.'))
|
||||
gitweb.app.update_service_access()
|
||||
|
||||
return super().form_valid(form)
|
||||
@@ -102,7 +108,7 @@ class EditRepoView(SuccessMessageMixin, FormView):
|
||||
"""Load information about repository being edited."""
|
||||
name = self.kwargs['name']
|
||||
for repo in gitweb.app.get_repo_list():
|
||||
if repo['name'] == name:
|
||||
if repo['name'] == name and 'clone_progress' not in repo:
|
||||
break
|
||||
else:
|
||||
raise Http404
|
||||
@@ -136,7 +142,7 @@ def delete(request, name):
|
||||
On POST, delete the repository.
|
||||
"""
|
||||
for repo in gitweb.app.get_repo_list():
|
||||
if repo['name'] == name:
|
||||
if repo['name'] == name and 'clone_progress' not in repo:
|
||||
break
|
||||
else:
|
||||
raise Http404
|
||||
|
||||
Reference in new issue
Block a user