plinth/*: Rename plinth/ folder to freedombox/

Signed-off-by: Sunil Mohan Adapa <sunil@medhas.org>
Reviewed-by: James Valleroy <jvalleroy@mailbox.org>
This commit is contained in:
Sunil Mohan Adapa authored and James Valleroy committed 2026-08-28 07:35:01 -04:00
1 parent dd0161a7e5
commit 23b6aff290
1264 files changed

No files matched your search

+255
View File
@@ -0,0 +1,255 @@
# SPDX-License-Identifier: AGPL-3.0-or-later
"""FreedomBox app to configure Gitweb."""
from django.utils.translation import gettext_lazy as _
from plinth import app as app_module
from plinth import frontpage, menu
from plinth.config import DropinConfigs
from plinth.modules.apache.components import Webserver
from plinth.modules.backups.components import BackupRestore
from plinth.modules.firewall.components import Firewall
from plinth.modules.users.components import UsersAndGroups
from plinth.package import Packages
from . import manifest, privileged
from .forms import is_repo_url
from .manifest import GIT_REPO_PATH
_description = [
_('Git is a distributed version-control system for tracking changes in '
'source code during software development. Gitweb provides a web '
'interface to Git repositories. You can browse history and content of '
'source code, use search to find relevant commits and code. '
'You can also clone repositories and upload code changes with a '
'command-line Git client or with multiple available graphical clients. '
'And you can share your code with people around the world.'),
_('To learn more on how to use Git visit '
'<a href="https://git-scm.com/docs/gittutorial">Git tutorial</a>.')
]
class GitwebApp(app_module.App):
"""FreedomBox app for Gitweb."""
app_id = 'gitweb'
_version = 4
def __init__(self) -> None:
"""Create components for the app."""
super().__init__()
groups = {'git-access': _('Read-write access to Git repositories')}
info = app_module.Info(app_id=self.app_id, version=self._version,
name=_('Gitweb'), icon_filename='gitweb',
description=_description, manual_page='GitWeb',
clients=manifest.clients, tags=manifest.tags)
self.add(info)
menu_item = menu.Menu('menu-gitweb', info.name, info.icon_filename,
info.tags, 'gitweb:index',
parent_url_name='apps')
self.add(menu_item)
shortcut = frontpage.Shortcut('shortcut-gitweb', info.name,
icon=info.icon_filename, url='/gitweb/',
clients=info.clients, tags=info.tags,
login_required=True,
allowed_groups=list(groups))
self.add(shortcut)
packages = Packages('packages-gitweb', ['gitweb', 'highlight'])
self.add(packages)
dropin_configs = DropinConfigs('dropin-configs-gitweb', [
'/etc/gitweb-freedombox.conf',
'/etc/apache2/conf-available/gitweb-freedombox.conf',
'/etc/apache2/conf-available/gitweb-freedombox-auth.conf'
])
self.add(dropin_configs)
firewall = Firewall('firewall-gitweb', info.name,
ports=['http', 'https'], is_external=True)
self.add(firewall)
webserver = Webserver('webserver-gitweb', 'gitweb-freedombox',
urls=['https://{host}/gitweb/'])
self.add(webserver)
self.auth_webserver = GitwebWebserverAuth('webserver-gitweb-auth',
'gitweb-freedombox-auth')
self.add(self.auth_webserver)
users_and_groups = UsersAndGroups('users-and-groups-gitweb',
groups=groups)
self.add(users_and_groups)
backup_restore = GitwebBackupRestore('backup-restore-gitweb',
**manifest.backup)
self.add(backup_restore)
def post_init(self):
"""Perform post initialization operations."""
if not self.needs_setup():
self.update_service_access()
def set_shortcut_login_required(self, login_required):
"""Change the login_required property of shortcut."""
self.get_component('shortcut-gitweb').login_required = login_required
def update_service_access(self):
"""Update the frontpage shortcut and webserver auth requirement."""
repos = get_repo_list()
if have_public_repos(repos):
self._enable_public_access()
else:
self._disable_public_access()
def _enable_public_access(self):
"""Allow Gitweb app to be accessed by anyone with access."""
if self.is_enabled():
self.auth_webserver.disable()
self.set_shortcut_login_required(False)
def _disable_public_access(self):
"""Allow Gitweb app to be accessed by logged-in users only."""
if self.is_enabled():
self.auth_webserver.enable()
self.set_shortcut_login_required(True)
def setup(self, old_version):
"""Install and configure the app."""
super().setup(old_version)
privileged.setup()
if not old_version:
self.enable()
def uninstall(self):
"""De-configure and uninstall the app."""
super().uninstall()
privileged.uninstall()
class GitwebWebserverAuth(Webserver):
"""Component to handle Gitweb authentication webserver configuration."""
is_leader = False
def enable(self):
"""Enable apache configuration only if no public repository exists."""
repos = get_repo_list()
if not have_public_repos(repos):
super().enable()
def set_enabled(self, enabled):
"""Update the internal enabled state of the component.
Actually do nothing. This method is called when is_leader = False to
notify the enabled/disabled state of the app. Enabled/disabled state of
this component is actually decided by the webserver configuration. It
is expected that is_enabled is not called on this component to
determine if app is enabled or not.
"""
pass
class GitwebBackupRestore(BackupRestore):
"""Component to handle backup/restore for Gitweb."""
def restore_post(self, packet):
"""Update access after restoration of backups."""
super().restore_post(packet)
self.app.update_service_access()
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 or clone a remote repository."""
kwargs = {
'url': None,
'name': None,
'description': repo_description,
'owner': owner,
'is_private': is_private
}
if is_repo_url(repo):
kwargs['url'] = repo
# create a repo directory and set correct access rights
privileged.create_repo(prepare_only=True, **kwargs)
# start cloning in background
privileged.create_repo(skip_prepare=True, _run_in_background=True,
**kwargs)
else:
kwargs['name'] = repo
privileged.create_repo(**kwargs)
def get_repo_list():
"""List all git repositories."""
repos = []
if GIT_REPO_PATH.exists():
for repo in GIT_REPO_PATH.iterdir():
if not repo.name.endswith('.git') or repo.name.startswith('.'):
continue
repo_info = {}
repo_info['name'] = repo.name[:-4]
private_file = repo / 'private'
if private_file.exists():
repo_info['access'] = 'private'
else:
repo_info['access'] = 'public'
progress_file = repo / 'clone_progress'
if progress_file.exists():
repo_info['clone_progress'] = progress_file.read_text()
repos.append(repo_info)
return sorted(repos, key=lambda repo: repo['name'])
def repo_info(repo):
"""Get information about repository."""
info = privileged.repo_info(repo)
if info['access'] == 'private':
info['is_private'] = True
else:
info['is_private'] = False
del info['access']
return info
def edit_repo(form_initial, form_cleaned):
"""Edit repository data."""
repo = form_initial['name']
if form_cleaned['name'] != repo:
privileged.rename_repo(repo, form_cleaned['name'])
repo = form_cleaned['name']
if form_cleaned['description'] != form_initial['description']:
privileged.set_repo_description(repo, form_cleaned['description'])
if form_cleaned['owner'] != form_initial['owner']:
privileged.set_repo_owner(repo, form_cleaned['owner'])
if form_cleaned['is_private'] != form_initial['is_private']:
if form_cleaned['is_private']:
privileged.set_repo_access(repo, 'private')
else:
privileged.set_repo_access(repo, 'public')
if form_cleaned['default_branch'] != form_initial['default_branch']:
privileged.set_default_branch(repo, form_cleaned['default_branch'])
@@ -0,0 +1,9 @@
##
## Limit access to gitweb web interface. Only users belonging to 'admin' or
## 'git-access' groups are allowed to view the web interface. This configuration
## is to be enabled when there are no public git projects.
##
<Directory /usr/share/gitweb>
Use AuthOpenIDConnect
Use RequireGroup git-access
</Directory>
@@ -0,0 +1,72 @@
##
## On all sites, enable gitweb web interface. Also enable git-http-backend on
## when performing upload/receive operations on the URL.
##
## Requires the following Apache modules to be enabled:
## mod_cgi or mod_cgid
## mod_rewrite
##
# All git operations are handled by git-http-backend CGI script. Rest of the
# HTTP requests (say sent by the browser) are handled by gitweb.
ScriptAliasMatch \
"(?x)^/gitweb/([^/]+/(HEAD | \
info/refs | \
objects/(info/[^/]+ | \
[0-9a-f]{2}/[0-9a-f]{38} | \
pack/pack-[0-9a-f]{40}\.(pack|idx)) | \
git-(upload|receive)-pack))$" \
/usr/lib/git-core/git-http-backend/$1
Alias /gitweb /usr/share/gitweb
<Directory /usr/share/gitweb>
# Make gitweb work with custom FreedomBox configuration.
SetEnv GITWEB_CONFIG /etc/gitweb-freedombox.conf
# Authentication is required for any operation if repository is private.
<If "%{HTTP_COOKIE} =~ /sessionid=/">
Use AuthOpenIDConnect
Use RequireGroup git-access
</If>
# Allow index.cgi symlink to gitweb.cgi to work. Treat gitweb.cgi as CGI
# script and execute it.
Options +FollowSymLinks +ExecCGI
AddHandler cgi-script .cgi
# Allow files in /usr/share/gitweb/static/ to be served directly by Apache.
# Pass every other URL as argument to gitweb.cgi to enable short and clean
# URLs.
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^.* /gitweb/gitweb.cgi/$0 [L,PT]
</Directory>
<Directory /usr/lib/git-core/>
# Configure git-http-backend to work with our repository path.
SetEnv GIT_PROJECT_ROOT /var/lib/git
# Tell git-http-backend to work with all the projects even when they don't
# have the file 'git-daemon-export-ok'.
SetEnv GIT_HTTP_EXPORT_ALL
# Authentication is required when performing git push (git send-pack).
SetEnvIfExpr "%{QUERY_STRING} =~ /service=git-receive-pack/" AUTHREQUIRED
SetEnvIfExpr "%{REQUEST_URI} =~ /git-receive-pack$/" AUTHREQUIRED
# Authentication is required for any operation if repository is private.
SetEnvIfExpr "%{REQUEST_URI} =~ m#^/gitweb/([^/]+)# && ( -f '/var/lib/git/$1/private' || -f '/var/lib/git/$1.git/private' )" AUTHREQUIRED
# Either authentication is not required for this operation and repository
# combination, or...
<RequireAll>
Require all granted
Require not env AUTHREQUIRED
</RequireAll>
# ...user belongs to admin or git-access groups, with basic auth via LDAP.
Include includes/freedombox-auth-ldap.conf
Require ldap-group cn=admin,ou=groups,dc=thisbox
Require ldap-group cn=git-access,ou=groups,dc=thisbox
</Directory>
@@ -0,0 +1,61 @@
# path to git projects (<project>.git)
$projectroot = "/var/lib/git";
# directory to use for temp files
$git_temp = "/tmp";
# target of the home link on top of all pages
#$home_link = $my_uri || "/";
# html text to include at home page
#$home_text = "indextext.html";
# file with project list; by default, simply scan the projectroot dir.
#$projects_list = $projectroot;
# stylesheet to use
@stylesheets = ("/gitweb/static/gitweb.css");
# javascript code for gitweb
$javascript = "/gitweb/static/gitweb.js";
# logo to use
$logo = "/gitweb/static/git-logo.png";
# the 'favicon'
$favicon = "/gitweb/static/git-favicon.png";
# git-diff-tree(1) options to use for generated patches
#@diff_opts = ("-M");
# enable short urls
$feature{'pathinfo'}{'default'} = [1];
# enable git blame
$feature{'blame'}{'default'} = [1];
$feature{'blame'}{'override'} = 1;
# enable pickaxe search
$feature{'pickaxe'}{'default'} = [1];
$feature{'pickaxe'}{'override'} = 1;
# enable syntax highlighting
$feature{'highlight'}{'default'} = [1];
$feature{'highlight'}{'override'} = 1;
# disable snapshots
$feature{'snapshot'}{'default'} = [];
$feature{'snapshot'}{'override'} = 1;
# do not recursively scan for Git repositories
our $project_maxdepth = 1;
# export private repos only if authorized
our $per_request_config = sub {
if(defined $ENV{'REMOTE_USER'}){
our $export_auth_hook = sub { return 1; };
}
else {
our $export_auth_hook = sub { return ! -e "$_[0]/private"; };
}
};
@@ -0,0 +1 @@
plinth.modules.gitweb
+156
View File
@@ -0,0 +1,156 @@
# SPDX-License-Identifier: AGPL-3.0-or-later
"""
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 gettext_lazy as _
from plinth.modules import gitweb
from . import privileged
def _get_branches(repo):
"""Get all the branches in the repository."""
branch_data = privileged.get_branches(repo)
default_branch = branch_data['default_branch']
branches = branch_data['branches']
if default_branch not in branches:
branches.insert(0, default_branch)
return [(branch, branch) for branch in branches]
def get_name_from_url(url):
"""Get a repository name from URL"""
return urlparse(url).path.split('/')[-1]
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 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,
help_text=_('Optional, for displaying on Gitweb.'))
owner = forms.CharField(label=_('Repository\'s owner name'), strip=True,
required=False,
help_text=_('Optional, for displaying on Gitweb.'))
is_private = forms.BooleanField(
label=_('Private repository'), required=False,
help_text=_('Allow only authorized users to access this repository.'))
def __init__(self, *args, **kwargs):
"""Initialize the form with extra request argument."""
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.get_repo_list():
if repo_name == repo['name']:
raise ValidationError(
_('A repository with this name already exists.'))
if is_repo_url(name):
if not privileged.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.'),
)
default_branch = forms.ChoiceField(
label=_('Default branch'),
help_text=_('Gitweb displays this as a default branch.'))
def __init__(self, *args, **kwargs):
"""Initialize the form with extra request argument."""
super().__init__(*args, **kwargs)
branches = _get_branches(self.initial['name'])
self.fields['default_branch'].choices = branches
def clean_name(self):
"""Check if the name is valid."""
name = self.cleaned_data['name']
if 'name' in self.initial and name == self.initial['name']:
return name
if name.endswith('.git'):
name = name[:-4]
for repo in gitweb.get_repo_list():
if name == repo['name']:
raise ValidationError(
_('A repository with this name already exists.'))
return name
+39
View File
@@ -0,0 +1,39 @@
# SPDX-License-Identifier: AGPL-3.0-or-later
import pathlib
from django.utils.translation import gettext_lazy as _
GIT_REPO_PATH = pathlib.Path('/var/lib/git')
REPO_DIR_OWNER = 'www-data'
clients = [
{
'name': _('Gitweb'),
'platforms': [{
'type': 'web',
'url': '/gitweb/'
}]
},
{
'name':
_('Git'),
'platforms': [{
'type': 'download',
'os': 'gnu-linux',
'url': 'https://git-scm.com/download/linux'
}, {
'type': 'download',
'os': 'macos',
'url': 'https://git-scm.com/download/mac'
}, {
'type': 'download',
'os': 'windows',
'url': 'https://git-scm.com/download/windows'
}]
},
]
backup = {'data': {'directories': [str(GIT_REPO_PATH)]}}
tags = [_('Git hosting'), _('Version control'), _('Developer tool')]
+424
View File
@@ -0,0 +1,424 @@
# SPDX-License-Identifier: AGPL-3.0-or-later
"""Configuration helper for Gitweb."""
import configparser
import logging
import os
import pathlib
import re
import shutil
import subprocess
import time
from typing import Any
from urllib import parse
from plinth import action_utils
from plinth.actions import privileged, secret_str
from plinth.modules.gitweb.forms import RepositoryValidator, get_name_from_url
from plinth.modules.gitweb.manifest import GIT_REPO_PATH, REPO_DIR_OWNER
logger = logging.getLogger(__name__)
def validate_repo_name(name: str) -> str:
"""Validate a repository name and add .git extension if necessary."""
RepositoryValidator()(name)
if not name.endswith('.git'):
name = name + '.git'
return name
def validate_repo_url(url: secret_str) -> secret_str:
"""Validate a repository URL."""
RepositoryValidator(input_should_be='url')(url)
return url
@privileged
def setup():
"""Configure Gitweb module."""
# Disable default Apache2 Gitweb configuration.
action_utils.webserver_disable('gitweb')
# Configure Git client.
if not _get_git_global_config('init.defaultBranch'):
_set_git_global_config('init.defaultBranch', 'main')
if not _get_git_global_config('credential.helper'):
_set_git_global_config('credential.helper', 'cache')
def _get_git_global_config(key: str) -> str | None:
"""Return a value from Git global configuration."""
try:
value = action_utils.run(['git', 'config', '--global', '--get', key],
check=True).stdout.decode().strip()
except subprocess.CalledProcessError as exception:
if exception.returncode == 1: # Configuration option doesn't exist
return None
raise
return value
def _set_git_global_config(key: str, value: str) -> None:
"""Set a Git global configuration value."""
action_utils.run(['git', 'config', '--global', key, value], check=True)
def _setup_git_credentials(url: secret_str) -> str:
"""Set up git credential helper and return URL without credentials."""
url_parts = parse.urlsplit(url)
safe_netloc = url_parts.netloc.split('@')[-1]
safe_url = url_parts._replace(netloc=safe_netloc).geturl()
username = url_parts.username or ''
password = url_parts.password or ''
if username or password:
# Feed credentials to Git credential helper
input = (f'protocol={url_parts.scheme}\n'
f'host={safe_netloc}\n'
f'username={username}\n'
f'password={password}\n\n')
env = dict(os.environ, GIT_TERMINAL_PROMPT='0')
action_utils.run(['git', 'credential', 'approve'],
input=input.encode(), stdout=subprocess.DEVNULL,
check=True, env=env)
return safe_url
def _clone_with_progress_report(url: secret_str, repo_dir: pathlib.Path):
"""Clone a repository and write progress info to the file."""
starttime = time.time()
status_file = repo_dir / 'clone_progress'
repo_temp_dir = repo_dir / '.temp'
# do not ask for credidentials and set low speed timeout
env = dict(os.environ, GIT_TERMINAL_PROMPT='0', LC_ALL='C',
GIT_HTTP_LOW_SPEED_LIMIT='100', GIT_HTTP_LOW_SPEED_TIME='60')
safe_url = _setup_git_credentials(url)
logger.info(f'Cloning Git repository {safe_url} ...')
proc = subprocess.Popen(
['git', 'clone', '--bare', '--progress', safe_url,
str(repo_temp_dir)], stderr=subprocess.PIPE, text=True, env=env)
assert proc.stderr is not None
# write clone progress to the file
errors = []
while True:
line = proc.stderr.readline()
if not line:
break
if 'error:' in line or 'fatal:' in line:
errors.append(line.strip())
currenttime = time.time()
if currenttime - starttime > 1:
elapsed = _clone_status_line_to_percent(line)
if elapsed is not None:
try:
status_file.write_text(elapsed)
except OSError as error:
errors.append(str(error))
starttime = currenttime
# make sure process is ended
try:
proc.communicate(timeout=10)
except subprocess.TimeoutExpired:
proc.kill()
status_file.unlink()
if proc.returncode != 0:
shutil.rmtree(repo_dir)
logger.error('Git repository cloning failed: %s', '\n'.join(errors))
raise RuntimeError('Git repository cloning failed.', errors)
def _prepare_clone_repo(url: secret_str, is_private: bool):
"""Prepare cloning a repository."""
repo_name = get_name_from_url(url)
if not repo_name.endswith('.git'):
repo_name = repo_name + '.git'
repo_dir = GIT_REPO_PATH / repo_name
os.mkdir(repo_dir)
status_file = repo_dir / 'clone_progress'
try:
if is_private:
_set_access_status(repo_name, 'private')
status_file.write_text('0')
except OSError:
shutil.rmtree(repo_dir)
raise
def _clone_status_line_to_percent(line):
"""Parse Git clone command output."""
result = re.match(r'.* ([0-9]+)% ', line)
if result is not None:
text = result.group(0)
progress = int(result.group(1))
if 'Counting objects' in text:
total_progress = 0.05 * progress
elif 'Compressing objects' in text:
total_progress = 5 + 0.05 * progress
elif 'Receiving objects' in text:
total_progress = 10 + 0.6 * progress
elif 'Resolving deltas' in text:
total_progress = 70 + 0.3 * progress
else:
return None
return str(int(total_progress))
return None
def _clone_repo(url: secret_str, description: str, owner: str,
keep_ownership: bool):
"""Clone a repository."""
repo = get_name_from_url(url)
if not repo.endswith('.git'):
repo = repo + '.git'
repo_path = GIT_REPO_PATH / repo
repo_temp_path = repo_path / '.temp'
_clone_with_progress_report(url, repo_path)
for item in os.listdir(repo_temp_path):
shutil.move(os.path.join(repo_temp_path, item), repo_path)
shutil.rmtree(repo_temp_path)
if not keep_ownership:
action_utils.run(
['chown', '-R', f'{REPO_DIR_OWNER}:{REPO_DIR_OWNER}', repo],
cwd=GIT_REPO_PATH, check=True)
_set_repo_description(repo, description)
_set_repo_owner(repo, owner)
def _create_repo(repo: str, description: str, owner: str, is_private: bool,
keep_ownership: bool):
"""Create an empty repository."""
try:
action_utils.run(['git', 'init', '-q', '--bare', repo],
cwd=GIT_REPO_PATH, check=True)
if not keep_ownership:
action_utils.run(
['chown', '-R', f'{REPO_DIR_OWNER}:{REPO_DIR_OWNER}', repo],
cwd=GIT_REPO_PATH, check=True)
_set_repo_description(repo, description)
_set_repo_owner(repo, owner)
if is_private:
_set_access_status(repo, 'private')
except (subprocess.CalledProcessError, OSError):
repo_path = GIT_REPO_PATH / repo
if repo_path.is_dir():
shutil.rmtree(repo_path)
raise
def _get_default_branch(repo):
"""Get default branch of the repository."""
repo_path = GIT_REPO_PATH / repo
return action_utils.run_as_user(
['git', '-C',
str(repo_path), 'symbolic-ref', '--short', 'HEAD'],
username=REPO_DIR_OWNER, check=True).stdout.decode().strip()
def _get_repo_description(repo):
"""Set description of the repository."""
description_file = GIT_REPO_PATH / repo / 'description'
if description_file.exists():
description = description_file.read_text()
else:
description = ''
return description
def _set_repo_description(repo, description):
"""Set description of the repository."""
description_file = GIT_REPO_PATH / repo / 'description'
description_file.write_text(description)
def _get_repo_owner(repo):
"""Set repository's owner name."""
repo_config = GIT_REPO_PATH / repo / 'config'
config = configparser.ConfigParser()
config.read(repo_config)
try:
owner = config['gitweb']['owner']
except KeyError:
owner = ''
return owner
def _set_repo_owner(repo, owner):
"""Set repository's owner name."""
repo_config = GIT_REPO_PATH / repo / 'config'
config = configparser.ConfigParser()
config.read(repo_config)
if not config.has_section('gitweb'):
config.add_section('gitweb')
config['gitweb']['owner'] = owner
with repo_config.open('w', encoding='utf-8') as file_handle:
config.write(file_handle)
def _get_access_status(repo):
"""Get repository's access status."""
private_file = GIT_REPO_PATH / repo / 'private'
if private_file.exists():
return 'private'
return 'public'
def _set_access_status(repo, status):
"""Set repository as private or public."""
private_file = GIT_REPO_PATH / repo / 'private'
if status == 'private':
private_file.touch()
elif status == 'public':
private_file.unlink(missing_ok=True)
def _get_branches(repo):
"""Return list of the branches in the repository."""
process = action_utils.run_as_user(
['git', '-C', repo, 'branch', '--format=%(refname:short)'],
cwd=GIT_REPO_PATH, username=REPO_DIR_OWNER, check=True)
return process.stdout.decode().strip().split()
@privileged
def get_branches(name: str) -> dict[str, Any]:
"""Check whether a branch exists in the repository."""
repo = validate_repo_name(name)
return dict(default_branch=_get_default_branch(repo),
branches=_get_branches(repo))
@privileged
def rename_repo(old_name: str, new_name: str):
"""Rename a repository."""
old_name = validate_repo_name(old_name)
new_name = validate_repo_name(new_name)
oldpath = GIT_REPO_PATH / old_name
newpath = GIT_REPO_PATH / new_name
oldpath.rename(newpath)
@privileged
def set_default_branch(name: str, branch: str):
"""Set description of the repository."""
repo = validate_repo_name(name)
if branch not in _get_branches(repo):
raise ValueError('No such branch')
action_utils.run_as_user(
['git', '-C', repo, 'symbolic-ref', 'HEAD', f'refs/heads/{branch}'],
cwd=GIT_REPO_PATH, check=True, username=REPO_DIR_OWNER)
@privileged
def set_repo_description(name: str, description: str):
"""Set description of the repository."""
repo = validate_repo_name(name)
_set_repo_description(repo, description)
@privileged
def set_repo_owner(name: str, owner: str):
"""Set repository's owner name."""
repo = validate_repo_name(name)
_set_repo_owner(repo, owner)
@privileged
def set_repo_access(name: str, access: str):
"""Set repository's access status."""
repo = validate_repo_name(name)
if access not in ('public', 'private'):
raise ValueError('Invalid access parameter')
_set_access_status(repo, access)
@privileged
def repo_info(name: str) -> dict[str, str]:
"""Get information about repository."""
repo = validate_repo_name(name)
repo_path = GIT_REPO_PATH / repo
if not repo_path.exists():
raise RuntimeError('Repository not found')
return dict(name=repo[:-4], description=_get_repo_description(repo),
owner=_get_repo_owner(repo), access=_get_access_status(repo),
default_branch=_get_default_branch(repo))
@privileged
def create_repo(url: secret_str | None = None, name: str | None = None,
description: str = '', owner: str = '',
keep_ownership: bool = False, is_private: bool = False,
skip_prepare: bool = False, prepare_only: bool = False):
"""Create a new or clone a remote repository."""
if url:
url = validate_repo_url(url)
if name:
repo = validate_repo_name(name)
if url:
if not skip_prepare:
_prepare_clone_repo(url, is_private)
if not prepare_only:
_clone_repo(url, description, owner, keep_ownership)
elif repo is not None:
_create_repo(repo, description, owner, is_private, keep_ownership)
@privileged
def repo_exists(url: secret_str) -> bool:
"""Return whether remote repository exists."""
url = validate_repo_url(url)
safe_url = _setup_git_credentials(url)
env = dict(os.environ, GIT_TERMINAL_PROMPT='0')
try:
action_utils.run(['git', 'ls-remote', safe_url, 'HEAD'], timeout=10,
env=env, check=True)
return True
except subprocess.CalledProcessError:
return False
@privileged
def delete_repo(name: str):
"""Delete a git repository."""
repo = validate_repo_name(name)
repo_path = GIT_REPO_PATH / repo
shutil.rmtree(repo_path)
@privileged
def uninstall():
"""Remove git repositories."""
for item in GIT_REPO_PATH.iterdir():
shutil.rmtree(item, ignore_errors=True)
Binary file not shown.

After

Width:  |  Height:  |  Size: 6.0 KiB

@@ -0,0 +1,15 @@
<svg
xmlns="http://www.w3.org/2000/svg"
width="512"
height="512"
viewBox="0 0 512 512" >
<g
transform="matrix(1.7663401,0,0,1.7663401,-4.5673475,9.5668645)">
<path
style="display:inline;fill:#bf0303;stroke-width:0.31999999"
d="M 11.7124,83.16759 V 70.847587 h 36.96 36.96 v 12.320003 12.32 h -36.96 -36.96 z m 98.88,0 V 70.847587 h 36.95999 36.96 v 12.320003 12.32 h -36.96 -36.95999 z m 98.75423,11.81382 c -0.10683,-0.27839 -0.19424,-5.59461 -0.19424,-11.81382 0,-6.219213 0.0874,-11.535437 0.19424,-11.81383 0.17556,-0.457517 3.74373,-0.506173 37.12,-0.506173 h 36.92576 v 12.320003 12.32 h -36.92576 c -33.37627,0 -36.94444,-0.0487 -37.12,-0.50618 z" />
<path
style="display:inline;fill:#007f00;stroke-width:0.31999999"
d="m 36.52795,207.93332 c -0.30094,-0.19113 -0.41625,-3.16879 -0.48,-12.3951 l -0.0839,-12.14353 -12.16,-0.16 -12.16,-0.16 v -12.32 -12.32 l 12.16,-0.16 12.16,-0.16 0.16,-12.16 0.16,-12.16 h 12.16 12.16 l 0.16,12.16 0.16,12.16 12.16,0.16 12.16,0.16 v 12.32 12.32 l -12.16,0.16 -12.16,0.16 -0.0839,12.14353 c -0.0637,9.22631 -0.17906,12.20397 -0.48,12.3951 -0.21785,0.13837 -5.58009,0.25157 -11.91609,0.25157 -6.336,0 -11.69824,-0.1132 -11.91609,-0.25157 z m 98.88,0 c -0.30094,-0.19113 -0.41625,-3.16879 -0.48,-12.3951 l -0.0839,-12.14353 -12.16,-0.16 -12.16,-0.16 v -12.32 -12.32 l 12.16,-0.16 12.16,-0.16 0.16,-12.16 0.16,-12.16 h 12.15999 12.16 l 0.16,12.16 0.16,12.16 12.16,0.16 12.16,0.16 v 12.32 12.32 l -12.16,0.16 -12.16,0.16 -0.0839,12.14353 c -0.0637,9.22631 -0.17906,12.20397 -0.48,12.3951 -0.21785,0.13837 -5.58009,0.25157 -11.91609,0.25157 -6.33599,0 -11.69823,-0.1132 -11.91608,-0.25157 z m 98.87999,0 c -0.30094,-0.19113 -0.41625,-3.16879 -0.48,-12.3951 l -0.0839,-12.14353 -12.16,-0.16 -12.16,-0.16 v -12.32 -12.32 l 12.16,-0.16 12.16,-0.16 0.0838,-12.24379 0.0838,-12.2438 12.2362,0.0838 12.23619,0.0838 0.16,12.16 0.16,12.16 12.16,0.16966 c 6.688,0.0933 12.19771,0.2013 12.2438,0.24 0.0461,0.0387 0.0461,5.57834 0,12.31034 l -0.0838,12.24 -12.16,0.16 -12.16,0.16 -0.0839,12.14353 c -0.0638,9.22631 -0.17906,12.20397 -0.48,12.3951 -0.21785,0.13837 -5.58009,0.25157 -11.91609,0.25157 -6.336,0 -11.69824,-0.1132 -11.91609,-0.25157 z" />
</g>
</svg>

After

Width:  |  Height:  |  Size: 2.2 KiB

@@ -0,0 +1,69 @@
{% extends "app.html" %}
{% comment %}
# SPDX-License-Identifier: AGPL-3.0-or-later
{% endcomment %}
{% load bootstrap %}
{% load i18n %}
{% load static %}
{% load extras %}
{% block configuration %}
{{ block.super }}
<h3>{% trans "Manage Repositories" %}</h3>
<div class="btn-toolbar">
<a href="{% url 'gitweb:create' %}" class="btn btn-default"
role="button" title="{% trans 'Create repository' %}">
{% icon 'plus' %}
{% trans 'Create repository' %}
</a>
</div>
<div class="row">
<div class="col-md-6">
{% if not repos %}
<p>{% trans 'No repositories available.' %}</p>
{% else %}
<div id="gitweb-repo-list" class="list-group list-group-two-column">
{% for repo in repos %}
<div class="list-group-item">
{% if 'clone_progress' in repo %}
<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 %}
{% if 'clone_progress' in repo %}
<span class="repo-cloning secondary">
{% trans 'Cloning…' %} {{ repo.clone_progress }}%
</span>
{% endif %}
{% if repo.access == 'private' %}
{% icon 'lock' class='svg-icon repo-private-icon secondary' %}
{% endif %}
<a class="repo-edit btn btn-sm btn-default secondary {% if 'clone_progress' in repo %} disabled {% endif %}"
href="{% url 'gitweb:edit' repo.name %}">
{% icon 'pencil-square-o' %}
</a>
<a href="{% url 'gitweb:delete' repo.name %}"
class="btn btn-default btn-sm secondary {% if 'clone_progress' in repo %} disabled {% endif %}"
role="button"
title="{% blocktrans %}Delete repository {{ repo.name }}{% endblocktrans %}">
{% icon 'trash-o' %}
</a>
</div>
{% endfor %}
</div>
{% endif %}
</div>
</div>
{% endblock %}
@@ -0,0 +1,30 @@
{% extends "base.html" %}
{% comment %}
# SPDX-License-Identifier: AGPL-3.0-or-later
{% endcomment %}
{% load bootstrap %}
{% load i18n %}
{% block content %}
<h3>
{% blocktrans trimmed %}
Delete Git Repository <em>{{ name }}</em>
{% endblocktrans %}
</h3>
<p>
{% blocktrans trimmed %}
Delete this repository permanently?
{% endblocktrans %}
</p>
<form class="form form-delete" method="post">
{% csrf_token %}
<input type="submit" class="btn btn-md btn-danger"
value="{% blocktrans %}Delete {{ name }}{% endblocktrans %}"/>
</form>
{% endblock %}
Whitespace-only changes.
@@ -0,0 +1,344 @@
# SPDX-License-Identifier: AGPL-3.0-or-later
"""
Functional, browser based tests for gitweb app.
"""
import contextlib
import os
import shutil
import subprocess
import tempfile
import pytest
from plinth.tests import functional
pytestmark = [pytest.mark.apps, pytest.mark.gitweb]
_default_url = functional.config['DEFAULT']['url']
class TestGitwebApp(functional.BaseAppTests):
app_name = 'gitweb'
has_service = False
has_web = True
def test_all_repos_private(self, session_browser):
"""Test repo accessability when all repos are private."""
_create_repo(session_browser, 'Test-repo', 'private',
ok_if_exists=True)
_set_all_repos_private(session_browser)
if not functional.user_exists(session_browser, 'gitweb_user'):
functional.create_user(session_browser, 'gitweb_user',
groups=['git-access'])
if not functional.user_exists(session_browser, 'nogroupuser'):
functional.create_user(session_browser, 'nogroupuser', groups=[])
functional.login_with_account(session_browser, functional.base_url,
'gitweb_user')
assert functional.is_available(session_browser, 'gitweb')
assert len(functional.find_on_front_page(session_browser,
'gitweb')) == 1
functional.login_with_account(session_browser, functional.base_url,
'nogroupuser')
assert not functional.is_available(session_browser, 'gitweb')
assert len(functional.find_on_front_page(session_browser,
'gitweb')) == 0
functional.logout(session_browser)
functional.access_url(session_browser, 'gitweb')
assert functional.is_login_prompt(session_browser)
assert len(functional.find_on_front_page(session_browser,
'gitweb')) == 0
@pytest.mark.backups
def test_backup_restore(self, session_browser):
"""Test backing up and restoring."""
_create_repo(session_browser, 'Test-repo', ok_if_exists=True)
functional.backup_create(session_browser, 'gitweb', 'test_gitweb')
_delete_repo(session_browser, 'Test-repo')
functional.backup_restore(session_browser, 'gitweb', 'test_gitweb')
assert _repo_exists(session_browser, 'Test-repo')
assert functional.is_available(session_browser, 'gitweb')
@pytest.mark.parametrize('access', ['public', 'private'])
@pytest.mark.parametrize('repo_name', ['Test-repo', 'Test-repo.git'])
@pytest.mark.parametrize('app_status', ['enabled', 'disabled'])
def test_create_delete_repo(self, session_browser, access, repo_name,
app_status):
"""Test creating and deleting a repo and accessing with a git
client."""
if app_status == "disabled":
functional.app_disable(session_browser, 'gitweb')
_delete_repo(session_browser, repo_name, ignore_missing=True)
_create_repo(session_browser, repo_name, access)
assert _repo_exists(session_browser, repo_name, access)
if app_status == "enabled":
assert _site_repo_exists(session_browser, repo_name)
if access == "public":
assert _repo_is_readable(repo_name)
else:
assert not _repo_is_readable(repo_name)
assert not _repo_is_writable(repo_name)
assert _repo_is_readable(repo_name, with_auth=True)
assert _repo_is_writable(repo_name, with_auth=True)
_delete_repo(session_browser, repo_name)
assert not _repo_exists(session_browser, repo_name)
def test_both_private_and_public_repo_exist(self, session_browser):
"""Tests when both private and public repo exist."""
_create_repo(session_browser, 'Test-repo', 'public', True)
_create_repo(session_browser, 'Test-repo-private', 'private', True)
functional.logout(session_browser)
assert _site_repo_exists(session_browser, 'Test-repo')
assert not _site_repo_exists(session_browser, 'Test-repo-private')
@pytest.mark.parametrize('app_status', ['enabled', 'disabled'])
def test_edit_repo_metadata(self, session_browser, app_status):
"""Test edit repo metadata."""
if app_status == "disabled":
functional.app_disable(session_browser, 'gitweb')
_create_repo(session_browser, 'Test-repo2', 'public',
ok_if_exists=True)
_delete_repo(session_browser, 'Test-repo', ignore_missing=True)
repo_metadata = {
'name': 'Test-repo',
'description': 'Test Description',
'owner': 'Test Owner',
'access': 'private',
}
_edit_repo_metadata(session_browser, 'Test-repo2', repo_metadata)
assert _get_repo_metadata(session_browser,
"Test-repo") == repo_metadata
if app_status == "enabled":
_create_branch('Test-repo', 'branch1')
_set_default_branch(session_browser, 'Test-repo', 'branch1')
assert _get_gitweb_site_default_repo_branch(
session_browser, 'Test-repo') == 'branch1'
def _create_local_repo(path):
"""Create a local repository."""
shutil.rmtree(path, ignore_errors=True)
os.mkdir(path)
create_repo_commands = [
'git init -q', 'git config http.sslVerify false',
'git -c "user.name=Tester" -c "user.email=tester" '
'commit -q --allow-empty --no-gpg-sign -m "test"'
]
for command in create_repo_commands:
subprocess.check_call(command, shell=True, cwd=path)
def _create_repo(browser, repo, access=None, ok_if_exists=False):
"""Create repository."""
if not _repo_exists(browser, repo, access):
_delete_repo(browser, repo, ignore_missing=True)
browser.links.find_by_href(
'/freedombox/apps/gitweb/create/').first.click()
browser.find_by_id('id_gitweb-name').fill(repo)
if access == 'private':
browser.find_by_id('id_gitweb-is_private').check()
elif access == 'public':
browser.find_by_id('id_gitweb-is_private').uncheck()
functional.submit(browser, form_class='form-gitweb')
elif not ok_if_exists:
assert False, 'Repo already exists.'
def _create_branch(repo, branch):
"""Add a branch to the repo."""
repo_url = _get_repo_url(repo, with_auth=True)
with _gitweb_temp_directory() as temp_directory:
repo_path = os.path.join(temp_directory, repo)
_create_local_repo(repo_path)
add_branch_commands = [['git', 'checkout', '-q', '-b', branch],
[
'git', '-c', 'user.name=Tester', '-c',
'user.email=tester', 'commit', '-q',
'--allow-empty', '--no-gpg-sign', '-m',
'test_branch1'
],
['git', 'push', '-q', '-f', repo_url, branch]]
for command in add_branch_commands:
subprocess.check_call(command, cwd=repo_path)
def _delete_repo(browser, repo, ignore_missing=False):
"""Delete repository."""
functional.nav_to_module(browser, 'gitweb')
if repo.endswith('.git'):
repo = repo[:-4]
delete_link = browser.links.find_by_href(
'/freedombox/apps/gitweb/{}/delete/'.format(repo))
if delete_link or not ignore_missing:
delete_link.first.click()
functional.submit(browser, form_class='form-delete')
def _edit_repo_metadata(browser, repo, metadata):
"""Set repository metadata."""
functional.nav_to_module(browser, 'gitweb')
browser.links.find_by_href(
'/freedombox/apps/gitweb/{}/edit/'.format(repo)).first.click()
browser.find_by_id('id_gitweb-name').fill(metadata['name'])
browser.find_by_id('id_gitweb-description').fill(metadata['description'])
browser.find_by_id('id_gitweb-owner').fill(metadata['owner'])
if metadata['access'] == 'private':
browser.find_by_id('id_gitweb-is_private').check()
else:
browser.find_by_id('id_gitweb-is_private').uncheck()
functional.submit(browser, form_class='form-gitweb')
def _get_gitweb_site_default_repo_branch(browser, repo):
functional.nav_to_module(browser, 'gitweb')
browser.find_by_css('a[href="/gitweb/{0}.git"]'.format(repo)).first.click()
return browser.find_by_css('.head').first.text
def _get_repo_metadata(browser, repo):
"""Get repository metadata."""
functional.nav_to_module(browser, 'gitweb')
browser.links.find_by_href(
'/freedombox/apps/gitweb/{}/edit/'.format(repo)).first.click()
metadata = {}
for item in ['name', 'description', 'owner']:
metadata[item] = browser.find_by_id('id_gitweb-' + item).value
if browser.find_by_id('id_gitweb-is_private').value:
metadata['access'] = 'private'
else:
metadata['access'] = 'public'
return metadata
def _get_repo_url(repo, with_auth):
""""Get repository URL"""
scheme = 'http'
if _default_url.startswith('https://'):
scheme = 'https'
url = _default_url.split(
'://')[1] if '://' in _default_url else _default_url
password = 'gitweb_wrong_password'
if with_auth:
password = functional.config['DEFAULT']['password']
return '{0}://{1}:{2}@{3}/gitweb/{4}'.format(
scheme, functional.config['DEFAULT']['username'], password, url, repo)
def _gitweb_git_command_is_successful(command, cwd):
"""Check if a command runs successfully or gives authentication error"""
# Tell OS not to translate command return messages
env = os.environ.copy()
env['LC_ALL'] = 'C'
process = subprocess.run(command, capture_output=True, cwd=cwd, env=env,
check=False)
if process.returncode != 0:
if 'Authentication failed' in process.stderr.decode():
return False
process.check_returncode() # Raise exception
return True
@contextlib.contextmanager
def _gitweb_temp_directory():
"""Create temporary directory"""
name = tempfile.mkdtemp(prefix='plinth_test_gitweb_')
yield name
shutil.rmtree(name)
def _repo_exists(browser, repo, access=None):
"""Check whether the repository exists."""
functional.nav_to_module(browser, 'gitweb')
if not repo.endswith('.git'):
repo = repo + ".git"
links_found = browser.links.find_by_href('/gitweb/{}'.format(repo))
access_matches = True
if links_found and access:
parent = links_found.first.find_by_xpath('..').first
private_icon = parent.find_by_css('.repo-private-icon')
if access == 'private':
access_matches = bool(private_icon)
if access == 'public':
access_matches = not bool(private_icon)
return bool(links_found) and access_matches
def _repo_is_readable(repo, with_auth=False):
"""Check if a git repo is readable with git client."""
url = _get_repo_url(repo, with_auth)
git_command = ['git', 'clone', '-c', 'http.sslverify=false', url]
with _gitweb_temp_directory() as cwd:
return _gitweb_git_command_is_successful(git_command, cwd)
def _repo_is_writable(repo, with_auth=False):
"""Check if a git repo is writable with git client."""
url = _get_repo_url(repo, with_auth)
with _gitweb_temp_directory() as temp_directory:
repo_directory = os.path.join(temp_directory, 'test-project')
_create_local_repo(repo_directory)
git_push_command = [
'git', '-c', 'push.default=current', 'push', '-qf', url
]
return _gitweb_git_command_is_successful(git_push_command,
repo_directory)
def _set_all_repos_private(browser):
"""Set all repositories private"""
functional.nav_to_module(browser, 'gitweb')
public_repos = []
for element in browser.find_by_css('#gitweb-repo-list .list-group-item'):
if not element.find_by_css('.repo-private-icon'):
repo = element.find_by_css('.repo-label').first.text
public_repos.append(repo)
for repo in public_repos:
_set_repo_access(browser, repo, 'private')
def _set_default_branch(browser, repo, branch):
"""Set default branch of the repository."""
functional.nav_to_module(browser, 'gitweb')
browser.links.find_by_href(
'/freedombox/apps/gitweb/{}/edit/'.format(repo)).first.click()
browser.find_by_id('id_gitweb-default_branch').select(branch)
functional.submit(browser, form_class='form-gitweb')
def _set_repo_access(browser, repo, access):
"""Set repository as public or private."""
functional.nav_to_module(browser, 'gitweb')
browser.links.find_by_href(
'/freedombox/apps/gitweb/{}/edit/'.format(repo)).first.click()
if access == 'private':
browser.find_by_id('id_gitweb-is_private').check()
else:
browser.find_by_id('id_gitweb-is_private').uncheck()
functional.submit(browser, form_class='form-gitweb')
def _site_repo_exists(browser, repo):
"""Check whether the repository exists on Gitweb site."""
browser.visit('{}/gitweb'.format(_default_url))
if not repo.endswith('.git'):
repo = repo + ".git"
return bool(browser.find_by_css('a[href="/gitweb/{0}"]'.format(repo)))
@@ -0,0 +1,148 @@
# SPDX-License-Identifier: AGPL-3.0-or-later
"""Test module for gitweb module operations."""
import pathlib
import subprocess
from unittest.mock import call, patch
import pytest
from django.forms import ValidationError
from plinth.modules.gitweb import privileged
REPO_NAME = 'Test-repo'
REPO_DATA = {
'name': REPO_NAME,
'description': '',
'owner': '',
'access': 'private',
}
pytestmark = pytest.mark.usefixtures('mock_privileged', 'mock_run_as_user')
privileged_modules_to_mock = ['plinth.modules.gitweb.privileged']
git_installed = pytest.mark.skipif(not pathlib.Path('/usr/bin/git').exists(),
reason='git is not installed')
@pytest.fixture(autouse=True)
def fixture_set_repo_path(tmp_path):
"""Set a repository path in the actions module."""
privileged.GIT_REPO_PATH = tmp_path
@pytest.fixture(name='existing_repo')
def fixture_existing_repo():
"""A fixture to create a repository."""
try:
privileged.delete_repo(REPO_NAME)
except FileNotFoundError:
pass
privileged.create_repo(name=REPO_NAME, description='', owner='',
keep_ownership=True, is_private=True)
@git_installed
def test_create_repo():
"""Test creating a repository."""
privileged.create_repo(name=REPO_NAME, description='', owner='',
is_private=True, keep_ownership=True)
repo = privileged.repo_info(REPO_NAME)
default_branch = repo.pop('default_branch')
assert repo == REPO_DATA
assert default_branch
@git_installed
def test_change_repo_medatada(existing_repo):
"""Test change a metadata of the repository."""
new_data = {
'name': REPO_NAME,
'description': 'description2',
'owner': 'owner2',
'access': 'public',
}
privileged.set_repo_description(REPO_NAME, new_data['description'])
privileged.set_repo_owner(REPO_NAME, new_data['owner'])
privileged.set_repo_access(REPO_NAME, new_data['access'])
repo = privileged.repo_info(REPO_NAME)
del repo['default_branch']
assert repo == new_data
@git_installed
def test_rename_repository(existing_repo):
"""Test renaming a repository."""
new_name = 'Test-repo_2'
privileged.rename_repo(REPO_NAME, new_name)
with pytest.raises(RuntimeError, match='Repository not found'):
privileged.repo_info(REPO_NAME)
repo = privileged.repo_info(new_name)
assert repo['name'] == new_name
@git_installed
def test_get_branches(existing_repo):
"""Test getting all the branches of the repository."""
result = privileged.get_branches(REPO_NAME)
assert 'default_branch' in result
assert result['branches'] == []
@git_installed
def test_delete_repository(existing_repo):
"""Test deleting a repository."""
privileged.delete_repo(REPO_NAME)
with pytest.raises(RuntimeError, match='Repository not found'):
privileged.repo_info(REPO_NAME)
@pytest.mark.parametrize(
'name',
['.Test-repo', 'Test-repo.git.git', '/root/Test-repo', 'Test-repö'])
def test_action_create_repo_with_invalid_names(name):
"""Test that creating repository with invalid names fails."""
with pytest.raises(ValidationError):
privileged.create_repo(name=name, description='', owner='',
keep_ownership=True)
@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(url):
"""Test that cloning repository with invalid URL fails."""
with pytest.raises(ValidationError):
privileged.create_repo(url=url, description='', owner='',
keep_ownership=True)
@patch('plinth.action_utils.run')
def test_setup_git_creentials(run):
"""Test that setting up git credentials works."""
url = 'https://user:pass@host.example/path?key=value'
safe_url = privileged._setup_git_credentials(url)
assert safe_url == 'https://host.example/path?key=value'
input_ = b'protocol=https\nhost=host.example\nusername=user\n' \
b'password=pass\n\n'
env = run.mock_calls[0].kwargs.pop('env')
assert env['GIT_TERMINAL_PROMPT'] == '0'
assert run.mock_calls == [
call(['git', 'credential', 'approve'], input=input_,
stdout=subprocess.DEVNULL, check=True)
]
run.reset_mock()
url = 'https://host2.example/path?key=value'
safe_url = privileged._setup_git_credentials(url)
assert safe_url == 'https://host2.example/path?key=value'
run.assert_not_called()
@@ -0,0 +1,360 @@
# SPDX-License-Identifier: AGPL-3.0-or-later
"""
Tests for gitweb views.
"""
from unittest.mock import Mock, patch
import pytest
from django import urls
from django.contrib.messages.storage.fallback import FallbackStorage
from django.http.response import Http404
from plinth import module_loader
from plinth.modules.gitweb import views
# For all tests, use plinth.urls instead of urls configured for testing
pytestmark = pytest.mark.urls('plinth.urls')
EXISTING_REPOS = [
{
'name': 'something',
'description': '',
'owner': '',
'access': 'public',
'is_private': False,
'default_branch': 'main',
},
{
'name': 'something2',
'description': '',
'owner': '',
'access': 'private',
'is_private': True,
'default_branch': 'main',
},
]
@pytest.fixture(autouse=True, scope='module')
def fixture_gitweb_urls():
"""Make sure gitweb app's URLs are part of plinth.urls."""
with patch('plinth.module_loader._modules_to_load', new=[]) as modules, \
patch('plinth.urls.urlpatterns', new=[]):
modules.append('plinth.modules.gitweb')
module_loader.include_urls()
yield
@pytest.fixture(autouse=True)
def gitweb_patch():
"""Patch gitweb."""
privileged = 'plinth.modules.gitweb.privileged'
with patch('plinth.modules.gitweb.get_repo_list') as get_repo_list, \
patch('plinth.app.App.get') as app_get, \
patch(f'{privileged}.create_repo'), \
patch(f'{privileged}.repo_exists') as repo_exists, \
patch(f'{privileged}.repo_info') as repo_info, \
patch(f'{privileged}.rename_repo'), \
patch(f'{privileged}.set_repo_description'), \
patch(f'{privileged}.set_repo_owner'), \
patch(f'{privileged}.set_repo_access'), \
patch(f'{privileged}.set_default_branch'), \
patch(f'{privileged}.delete_repo'), \
patch(f'{privileged}.get_branches') as get_branches:
repo_exists.return_value = True
repo_info.return_value = dict(EXISTING_REPOS[0])
get_branches.return_value = {
'default_branch': 'main',
'branches': ['main', 'branch1']
}
get_repo_list.return_value = [{
'name': EXISTING_REPOS[0]['name']
}, {
'name': EXISTING_REPOS[1]['name']
}]
app = Mock()
app_get.return_value = app
app.update_service_access.return_value = None
yield
def make_request(request, view, **kwargs):
"""Make request with a message storage."""
setattr(request, 'session', 'session')
messages = FallbackStorage(request)
setattr(request, '_messages', messages)
response = view(request, **kwargs)
return response, messages
def test_repos_view(rf):
"""Test that a repo list has correct view data."""
with patch('plinth.views.AppView.get_context_data',
return_value={'is_enabled': True}):
view = views.GitwebAppView.as_view()
response, _ = make_request(rf.get(''), view)
assert response.context_data['repos'] == [{
'name': EXISTING_REPOS[0]['name']
}, {
'name': EXISTING_REPOS[1]['name']
}]
assert response.status_code == 200
def test_create_repo_view(rf):
"""Test that repo create view sends correct success message."""
form_data = {
'gitweb-name': 'something_other',
'gitweb-description': 'test description',
'gitweb-owner': 'test owner',
'gitweb-is_private': True
}
request = rf.post(urls.reverse('gitweb:create'), data=form_data)
view = views.CreateRepoView.as_view()
response, messages = make_request(request, view)
assert list(messages)[0].message == 'Repository created.'
assert response.status_code == 302
def test_create_repo_duplicate_name_view(rf):
"""Test that repo create view shows correct error message."""
form_data = {
'gitweb-name': EXISTING_REPOS[0]['name'],
'gitweb-description': '',
'gitweb-owner': ''
}
request = rf.post(urls.reverse('gitweb:create'), data=form_data)
view = views.CreateRepoView.as_view()
response, _ = make_request(request, view)
assert response.context_data['form'].errors['name'][
0] == 'A repository with this name already exists.'
assert response.status_code == 200
def test_create_repo_invalid_name_view(rf):
"""Test that repo create view shows correct error message."""
form_data = {
'gitweb-name': '.something_other',
'gitweb-description': '',
'gitweb-owner': ''
}
request = rf.post(urls.reverse('gitweb:create'), data=form_data)
view = views.CreateRepoView.as_view()
response, _ = make_request(request, view)
assert response.context_data['form'].errors['name'][
0] == 'Invalid repository name.'
assert response.status_code == 200
def test_create_repo_failed_view(rf):
"""Test that repo creation failure sends correct error message."""
general_error_message = "An error occurred while creating the repository."
error_description = 'some error'
with patch('plinth.modules.gitweb.create_repo',
side_effect=PermissionError(error_description)):
form_data = {
'gitweb-name': 'something_other',
'gitweb-description': '',
'gitweb-owner': ''
}
request = rf.post(urls.reverse('gitweb:create'), data=form_data)
view = views.CreateRepoView.as_view()
response, messages = make_request(request, view)
assert list(messages)[0].message == '{0} {1}'.format(
general_error_message, error_description)
assert response.status_code == 302
def test_clone_repo_view(rf):
"""Test that cloning repo sends correct succcess message."""
form_data = {
'gitweb-name': 'https://example.com/test.git',
'gitweb-description': '',
'gitweb-owner': ''
}
request = rf.post(urls.reverse('gitweb:create'), data=form_data)
view = views.CreateRepoView.as_view()
response, messages = make_request(request, view)
with pytest.raises(AttributeError):
getattr(response.context_data['form'], 'errors')
assert list(messages)[0].message == 'Repository created.'
assert response.status_code == 302
def test_clone_repo_missing_remote_view(rf):
"""Test that cloning non-existing repo shows correct error message."""
with patch('plinth.modules.gitweb.privileged.repo_exists',
return_value=False):
form_data = {
'gitweb-name': 'https://example.com/test.git',
'gitweb-description': '',
'gitweb-owner': ''
}
request = rf.post(urls.reverse('gitweb:create'), data=form_data)
view = views.CreateRepoView.as_view()
response, _ = make_request(request, view)
assert response.context_data['form'].errors['name'][
0] == 'Remote repository is not available.'
assert response.status_code == 200
def test_edit_repository_view(rf):
"""Test that editing repo sends correct success message."""
form_data = {
'gitweb-name': 'something_other.git',
'gitweb-description': 'test-description',
'gitweb-owner': 'test-owner',
'gitweb-is_private': True,
'gitweb-default_branch': 'branch1',
}
url = urls.reverse('gitweb:edit',
kwargs={'name': EXISTING_REPOS[0]['name']})
request = rf.post(url, data=form_data)
view = views.EditRepoView.as_view()
response, messages = make_request(request, view,
name=EXISTING_REPOS[0]['name'])
assert list(messages)[0].message == 'Repository edited.'
assert response.status_code == 302
def test_edit_nonexisting_repository_view(rf):
"""Test that trying to edit non-existing repository raises 404."""
non_existing_repo = {'name': 'something_other'}
request = rf.post(urls.reverse('gitweb:edit', kwargs=non_existing_repo),
data={})
view = views.EditRepoView.as_view()
with pytest.raises(Http404):
make_request(request, view, **non_existing_repo)
def test_edit_repository_duplicate_name_view(rf):
"""Test that renaming to already existing repo name shows correct error
message.
"""
form_data = {
'gitweb-name': EXISTING_REPOS[1]['name'],
'gitweb-description': 'test-description',
'gitweb-owner': 'test-owner'
}
url = urls.reverse('gitweb:edit',
kwargs={'name': EXISTING_REPOS[0]['name']})
request = rf.post(url, data=form_data)
view = views.EditRepoView.as_view()
response, _ = make_request(request, view, **EXISTING_REPOS[0])
assert response.context_data['form'].errors['name'][
0] == 'A repository with this name already exists.'
assert response.status_code == 200
def test_edit_repository_invalid_name_view(rf):
"""Test that renaming repo to invalid name shows correct error message."""
form_data = {
'gitweb-name': '.something',
'gitweb-description': 'test-description',
'gitweb-owner': 'test-owner'
}
url = urls.reverse('gitweb:edit',
kwargs={'name': EXISTING_REPOS[0]['name']})
request = rf.post(url, data=form_data)
view = views.EditRepoView.as_view()
response, _ = make_request(request, view, **EXISTING_REPOS[0])
assert response.context_data['form'].errors['name'][
0] == 'Invalid repository name.'
assert response.status_code == 200
def test_edit_repository_no_change_view(rf):
"""Test that not changing any values don't edit the repo."""
with patch('plinth.modules.gitweb.edit_repo') as edit_repo:
form_data = {
'gitweb-name': EXISTING_REPOS[0]['name'],
'gitweb-description': EXISTING_REPOS[0]['description'],
'gitweb-owner': EXISTING_REPOS[0]['owner'],
'gitweb-default_branch': EXISTING_REPOS[0]['default_branch'],
}
request = rf.post(
urls.reverse('gitweb:edit',
kwargs={'name': EXISTING_REPOS[0]['name']}),
data=form_data)
view = views.EditRepoView.as_view()
response, _ = make_request(request, view, **EXISTING_REPOS[0])
assert not edit_repo.called, 'method should not have been called'
assert response.status_code == 302
def test_edit_repository_failed_view(rf):
"""Test that failed repo editing sends correct error message."""
with patch('plinth.modules.gitweb.edit_repo',
side_effect=PermissionError('Error')):
form_data = {
'gitweb-name': 'something_other',
'gitweb-description': 'test-description',
'gitweb-owner': 'test-owner',
'gitweb-default_branch': 'main',
}
request = rf.post(
urls.reverse('gitweb:edit',
kwargs={'name': EXISTING_REPOS[0]['name']}),
data=form_data)
view = views.EditRepoView.as_view()
response, messages = make_request(request, view, **EXISTING_REPOS[0])
assert list(
messages)[0].message == 'An error occurred during configuration.'
assert response.status_code == 302
def test_delete_repository_confirmation_view(rf):
"""Test that repo deletion confirmation shows correct repo name."""
response, _ = make_request(rf.get(''), views.delete,
name=EXISTING_REPOS[0]['name'])
assert response.context_data['name'] == EXISTING_REPOS[0]['name']
assert response.status_code == 200
def test_delete_repository_view(rf):
"""Test that repo deletion sends correct success message."""
response, messages = make_request(rf.post(''), views.delete,
name=EXISTING_REPOS[0]['name'])
assert list(messages)[0].message == '{} deleted.'.format(
EXISTING_REPOS[0]['name'])
assert response.status_code == 302
def test_delete_repository_fail_view(rf):
"""Test that failed repository deletion sends correct error message."""
with patch('plinth.modules.gitweb.privileged.delete_repo',
side_effect=FileNotFoundError('Error')):
response, messages = make_request(rf.post(''), views.delete,
name=EXISTING_REPOS[0]['name'])
assert list(
messages)[0].message == 'Could not delete {}: Error'.format(
EXISTING_REPOS[0]['name'])
assert response.status_code == 302
def test_delete_non_existing_repository_view(rf):
"""Test that deleting non-existing repository raises 404."""
with pytest.raises(Http404):
make_request(rf.post(''), views.delete, name='unknown_repo')
+23
View File
@@ -0,0 +1,23 @@
# SPDX-License-Identifier: AGPL-3.0-or-later
"""
URLs for the Gitweb module.
"""
from django.urls import re_path
from .views import CreateRepoView, EditRepoView, GitwebAppView, delete
urlpatterns = [
re_path(r'^apps/gitweb/$', GitwebAppView.as_view(), name='index'),
re_path(r'^apps/gitweb/create/$', CreateRepoView.as_view(), name='create'),
re_path(
r'^apps/gitweb/(?P<name>[a-zA-Z0-9-._]+)/edit/$',
EditRepoView.as_view(),
name='edit',
),
re_path(
r'^apps/gitweb/(?P<name>[a-zA-Z0-9-._]+)/delete/$',
delete,
name='delete',
),
]
+153
View File
@@ -0,0 +1,153 @@
# SPDX-License-Identifier: AGPL-3.0-or-later
"""Django views for Gitweb."""
from django.contrib import messages
from django.contrib.messages.views import SuccessMessageMixin
from django.http import Http404
from django.shortcuts import redirect
from django.template.response import TemplateResponse
from django.urls import reverse_lazy
from django.utils.translation import gettext as _
from django.views.generic import FormView
from plinth import app as app_module
from plinth import views
from plinth.modules import gitweb
from . import privileged
from .forms import CreateRepoForm, EditRepoForm
class GitwebAppView(views.AppView):
"""Serve configuration page."""
app_id = 'gitweb'
template_name = 'gitweb_configure.html'
def get_context_data(self, *args, **kwargs):
"""Add repositories to the context data."""
context = super().get_context_data(*args, **kwargs)
repos = gitweb.get_repo_list()
context['repos'] = repos
context['cloning'] = any('clone_progress' in repo for repo in repos)
if context['cloning']:
context['refresh_page_sec'] = 3
return context
class CreateRepoView(SuccessMessageMixin, FormView):
"""View to create a new repository."""
form_class = CreateRepoForm
prefix = 'gitweb'
template_name = 'form.html'
success_url = reverse_lazy('gitweb:index')
success_message = _('Repository created.')
def get_context_data(self, **kwargs):
"""Return additional context for rendering the template."""
context = super().get_context_data(**kwargs)
context['title'] = _('Create Repository')
return context
def form_valid(self, form):
"""Create the repository on valid form submission."""
form_data = {}
for key, value in form.cleaned_data.items():
if value is None:
form_data[key] = ''
else:
form_data[key] = value
try:
gitweb.create_repo(form_data['name'], form_data['description'],
form_data['owner'], form_data['is_private'])
except Exception as error:
self.success_message = ''
messages.error(
self.request, "{0} {1}".format(
_('An error occurred while creating the repository.'),
error))
else:
app_module.App.get('gitweb').update_service_access()
return super().form_valid(form)
class EditRepoView(SuccessMessageMixin, FormView):
"""View to edit an existing repository."""
form_class = EditRepoForm
prefix = 'gitweb'
template_name = 'form.html'
success_url = reverse_lazy('gitweb:index')
success_message = _('Repository edited.')
def get_context_data(self, **kwargs):
"""Return additional context for rendering the template."""
context = super().get_context_data(**kwargs)
context['title'] = _('Edit repository')
return context
def get_initial(self):
"""Load information about repository being edited."""
name = self.kwargs['name']
for repo in gitweb.get_repo_list():
if repo['name'] == name and 'clone_progress' not in repo:
break
else:
raise Http404
return gitweb.repo_info(name)
def form_valid(self, form):
"""Edit the repo on valid form submission."""
if form.initial != form.cleaned_data:
form_data = {}
for key, value in form.cleaned_data.items():
if value is None:
form_data[key] = ''
else:
form_data[key] = value
try:
gitweb.edit_repo(form.initial, form_data)
except Exception:
messages.error(self.request,
_('An error occurred during configuration.'))
app_module.App.get('gitweb').update_service_access()
return super().form_valid(form)
def delete(request, name):
"""Handle deleting repositories, showing a confirmation dialog first.
On GET, display a confirmation page.
On POST, delete the repository.
"""
for repo in gitweb.get_repo_list():
if repo['name'] == name and 'clone_progress' not in repo:
break
else:
raise Http404
app = app_module.App.get('gitweb')
if request.method == 'POST':
try:
privileged.delete_repo(name)
messages.success(request, _('{name} deleted.').format(name=name))
except Exception as error:
messages.error(
request,
_('Could not delete {name}: {error}').format(
name=name, error=error),
)
app.update_service_access()
return redirect(reverse_lazy('gitweb:index'))
return TemplateResponse(request, 'gitweb_delete.html', {
'title': app.info.name,
'name': name
})