Changeset - 747cc853b5e9
[Not reviewed]
Merge stable
54 270 49
Thomas De Schampheleire - 4 years ago 2021-05-27 21:27:37
thomas.de_schampheleire@nokia.com
release: merge default to stable for 0.7.0
61 files changed:
.hgignore
12
8
Changeset was too big and was cut off... Show full diff anyway
0 comments (0 inline, 0 general)
.coveragerc
Show inline comments
 
@@ -8,9 +8,6 @@ omit =
 
    kallithea/lib/dbmigrate/*
 
    # the tests themselves should not be part of the coverage report
 
    kallithea/tests/*
 
    # the scm hooks are not run in the kallithea process
 
    kallithea/config/post_receive_tmpl.py
 
    kallithea/config/pre_receive_tmpl.py
 

	
 
# same omit lines should be present in sections 'run' and 'report'
 
[report]
 
@@ -23,9 +20,6 @@ omit =
 
    kallithea/lib/dbmigrate/*
 
    # the tests themselves should not be part of the coverage report
 
    kallithea/tests/*
 
    # the scm hooks are not run in the kallithea process
 
    kallithea/config/post_receive_tmpl.py
 
    kallithea/config/pre_receive_tmpl.py
 

	
 
[paths]
 
source =
.hgignore
Show inline comments
 
@@ -10,16 +10,15 @@ syntax: glob
 
*.rej
 
*.bak
 
.eggs/
 
tarballcache/
 

	
 
syntax: regexp
 
^rcextensions
 
^build
 
^dist/
 
^docs/build/
 
^docs/_build/
 
^extensions\.py$
 
^build$
 
^dist$
 
^docs/build$
 
^docs/_build$
 
^data$
 
^sql_dumps/
 
^sql_dumps$
 
^\.settings$
 
^\.project$
 
^\.pydevproject$
 
@@ -48,8 +47,13 @@ syntax: regexp
 
^test\.db$
 
^Kallithea\.egg-info$
 
^my\.ini$
 
^fabfile.py
 
^fabfile\.py$
 
^\.idea$
 
^\.cache$
 
^\.pytest_cache$
 
^venv$
 
/__pycache__$
 
^deps\.dot$
 
^deps\.svg$
 
^deps\.txt$
 
^\.pytype/
CONTRIBUTORS
Show inline comments
 
List of contributors to Kallithea project:
 

	
 
    Thomas De Schampheleire <thomas.de_schampheleire@nokia.com> 2014-2020
 
    Mads Kiilerich <mads@kiilerich.com> 2016-2020
 
    Thomas De Schampheleire <thomas.de_schampheleire@nokia.com> 2014-2021
 
    Mads Kiilerich <mads@kiilerich.com> 2016-2021
 
    ssantos <ssantos@web.de> 2018-2021
 
    Private <adamantine.sword@gmail.com> 2019-2021
 
    Étienne Gilli <etienne@gilli.io> 2020-2021
 
    fresh <fresh190@protonmail.com> 2020-2021
 
    robertus <robertuss12@gmail.com> 2020-2021
 
    Eugenia Russell <eugenia.russell2019@gmail.com> 2021
 
    Michalis <michalisntovas@yahoo.gr> 2021
 
    vs <vsuhachev@yandex.ru> 2021
 
    Александр <akonn7@mail.ru> 2021
 
    Asterios Dimitriou <steve@pci.gr> 2016-2017 2020
 
    Allan Nordhøy <epost@anotheragency.no> 2017-2020
 
    Anton Schur <tonich.sh@gmail.com> 2017 2020
 
    ssantos <ssantos@web.de> 2018-2020
 
    Manuel Jacob <me@manueljacob.de> 2019-2020
 
    Private <adamantine.sword@gmail.com> 2019-2020
 
    Artem <kovalevartem.ru@gmail.com> 2020
 
    David Ignjić <ignjic@gmail.com> 2020
 
    Dennis Fink <dennis.fink@c3l.lu> 2020
 
    Étienne Gilli <etienne@gilli.io> 2020
 
    J. Lavoie <j.lavoie@net-c.ca> 2020
 
    robertus <robertuss12@gmail.com> 2020
 
    Ross Thomas <ross@lns-nevasoft.com> 2020
 
    Tim Ooms <tatankat@users.noreply.github.com> 2020
 
    Andrej Shadura <andrew@shadura.me> 2012 2014-2017 2019
 
    Étienne Gilli <etienne.gilli@gmail.com> 2015-2017 2019
 
    Adi Kriegisch <adi@cg.tuwien.ac.at> 2019
MANIFEST.in
Show inline comments
 
@@ -18,7 +18,6 @@ recursive-include docs *
 
recursive-include init.d *
 
recursive-include kallithea/alembic *
 
include           kallithea/bin/ldap_sync.conf
 
include           kallithea/lib/paster_commands/template.ini.mako
 
recursive-include kallithea/front-end *
 
recursive-include kallithea/i18n *
 
recursive-include kallithea/public *
README.rst
Show inline comments
 
@@ -74,8 +74,8 @@ Kallithea features
 
  web interface using simple editor or upload binary files using simple form.
 
- Powerful pull request driven review system with inline commenting, changeset
 
  statuses, and notification system.
 
- Importing and syncing repositories from remote locations for Git_, Mercurial_
 
  and Subversion.
 
- Importing and syncing repositories from remote locations for Git_ and
 
  Mercurial_.
 
- Mako templates let you customize the look and feel of the application.
 
- Beautiful diffs, annotations and source code browsing all colored by
 
  pygments. Raw diffs are made in Git-diff format for both VCS systems,
 
@@ -175,7 +175,6 @@ of Kallithea.
 
.. _Mercurial: http://mercurial.selenic.com/
 
.. _Bitbucket: http://bitbucket.org/
 
.. _GitHub: http://github.com/
 
.. _Subversion: http://subversion.tigris.org/
 
.. _Git: http://git-scm.com/
 
.. _Celery: http://celeryproject.org/
 
.. _Software Freedom Conservancy: http://sfconservancy.org/
dev_requirements.txt
Show inline comments
 
pytest >= 4.6.6, < 5.4
 
pytest >= 4.6.6, < 5.5
 
pytest-sugar >= 0.9.2, < 0.10
 
pytest-benchmark >= 3.2.2, < 3.3
 
pytest-localserver >= 0.5.0, < 0.6
 
mock >= 3.0.0, < 4.1
 
Sphinx >= 1.8.0, < 2.4
 
Sphinx >= 1.8.0, < 3.1
 
WebTest >= 2.0.6, < 2.1
 
isort == 4.3.21
 
pyflakes == 2.1.1
 
isort == 5.1.2
 
pyflakes == 2.2.0
development.ini
Show inline comments
 
@@ -67,11 +67,11 @@ smtp_use_tls = false
 
host = 0.0.0.0
 
port = 5000
 

	
 
## WAITRESS ##
 
## Gearbox serve uses the Waitress web server ##
 
use = egg:waitress#main
 
## number of worker threads
 
## avoid multi threading
 
threads = 1
 
## MAX BODY SIZE 100GB
 
## allow push of repos bigger than the default of 1 GB
 
max_request_body_size = 107374182400
 
## use poll instead of select, fixes fd limits, may not work on old
 
## windows systems.
 
@@ -81,6 +81,7 @@ max_request_body_size = 107374182400
 
#[filter:proxy-prefix]
 
#use = egg:PasteDeploy#prefix
 
#prefix = /<your-prefix>
 
#translate_forwarded_server = False
 

	
 
[app:main]
 
use = egg:kallithea
 
@@ -102,7 +103,7 @@ cache_dir = %(here)s/data
 
index_dir = %(here)s/data/index
 

	
 
## uncomment and set this path to use archive download cache
 
archive_cache_dir = %(here)s/tarballcache
 
archive_cache_dir = %(here)s/data/tarballcache
 

	
 
## change this to unique ID for security
 
#app_instance_uuid = VERY-SECRET
 
@@ -111,11 +112,17 @@ app_instance_uuid = development-not-secr
 
## cut off limit for large diffs (size in bytes)
 
cut_off_limit = 256000
 

	
 
## force https in Kallithea, fixes https redirects, assumes it's always https
 
force_https = false
 
## WSGI environment variable to get the IP address of the client (default REMOTE_ADDR)
 
#remote_addr_variable = HTTP_X_FORWARDED_FOR
 

	
 
## WSGI environment variable to get the protocol (http or https) of the client connection (default wsgi.url_scheme)
 
#url_scheme_variable = HTTP_X_FORWARDED_PROTO
 

	
 
## use Strict-Transport-Security headers
 
use_htsts = false
 
## always pretend the client connected using HTTPS (default false)
 
#force_https = true
 

	
 
## use Strict-Transport-Security headers (default false)
 
#use_htsts = true
 

	
 
## number of commits stats will parse on each iteration
 
commit_parse_limit = 25
 
@@ -259,15 +266,8 @@ use_celery = false
 
## Example: use the message queue on the local virtual host 'kallitheavhost' as the RabbitMQ user 'kallithea':
 
celery.broker_url = amqp://kallithea:thepassword@localhost:5672/kallitheavhost
 

	
 
celery.result_backend = db+sqlite:///celery-results.db
 

	
 
#celery.amqp.task.result.expires = 18000
 

	
 
celery.worker_concurrency = 2
 
celery.worker_max_tasks_per_child = 1
 

	
 
## If true, tasks will never be sent to the queue, but executed locally instead.
 
celery.task_always_eager = false
 
celery.worker_max_tasks_per_child = 100
 

	
 
####################################
 
##          BEAKER CACHE          ##
 
@@ -346,7 +346,6 @@ get trace_errors.smtp_username = smtp_us
 
get trace_errors.smtp_password = smtp_password
 
get trace_errors.smtp_use_tls = smtp_use_tls
 

	
 

	
 
##################################
 
##        LOGVIEW CONFIG        ##
 
##################################
 
@@ -359,10 +358,10 @@ logview.pylons.util = #eee
 
##      DB CONFIG      ##
 
#########################
 

	
 
## SQLITE [default]
 
sqlalchemy.url = sqlite:///%(here)s/kallithea.db?timeout=60
 

	
 
## see sqlalchemy docs for other backends
 
#sqlalchemy.url = postgresql://kallithea:password@localhost/kallithea
 
#sqlalchemy.url = mysql://kallithea:password@localhost/kallithea?charset=utf8mb4
 
## Note: the mysql:// prefix should also be used for MariaDB
 

	
 
sqlalchemy.pool_recycle = 3600
 

	
docs/conf.py
Show inline comments
 
@@ -14,7 +14,7 @@
 
import os
 
import sys
 

	
 
from kallithea import __version__
 
import kallithea
 

	
 

	
 
# If extensions (or modules to document with autodoc) are in another directory,
 
@@ -47,7 +47,7 @@ master_doc = 'index'
 

	
 
# General information about the project.
 
project = 'Kallithea'
 
copyright = '2010-2020 by various authors, licensed as GPLv3.'
 
copyright = '2010-2021 by various authors, licensed as GPLv3.'
 

	
 
# The version info for the project you're documenting, acts as replacement for
 
# |version| and |release|, also used in various other places throughout the
 
@@ -56,9 +56,9 @@ copyright = '2010-2020 by various author
 
# The short X.Y version.
 
root = os.path.dirname(os.path.dirname(__file__))
 
sys.path.append(root)
 
version = __version__
 
version = kallithea.__version__
 
# The full version, including alpha/beta/rc tags.
 
release = __version__
 
release = kallithea.__version__
 

	
 
# The language for content autogenerated by Sphinx. Refer to documentation
 
# for a list of supported languages.
docs/contributing.rst
Show inline comments
 
@@ -26,12 +26,13 @@ for more details.
 
Getting started
 
---------------
 

	
 
To get started with Kallithea development::
 
To get started with Kallithea development run the following commands in your
 
bash shell::
 

	
 
        hg clone https://kallithea-scm.org/repos/kallithea
 
        cd kallithea
 
        python3 -m venv ../kallithea-venv
 
        source ../kallithea-venv/bin/activate
 
        python3 -m venv venv
 
        . venv/bin/activate
 
        pip install --upgrade pip setuptools
 
        pip install --upgrade -e . -r dev_requirements.txt python-ldap python-pam
 
        kallithea-cli config-create my.ini
 
@@ -71,6 +72,94 @@ review and inclusion, via the mailing li
 
.. _contributing-tests:
 

	
 

	
 
Internal dependencies
 
---------------------
 

	
 
We try to keep the code base clean and modular and avoid circular dependencies.
 
Code should only invoke code in layers below itself.
 

	
 
Imports should import whole modules ``from`` their parent module, perhaps
 
``as`` a shortened name. Avoid imports ``from`` modules.
 

	
 
To avoid cycles and partially initialized modules, ``__init__.py`` should *not*
 
contain any non-trivial imports. The top level of a module should *not* be a
 
facade for the module functionality.
 

	
 
Common code for a module is often in ``base.py``.
 

	
 
The important part of the dependency graph is approximately linear. In the
 
following list, modules may only depend on modules below them:
 

	
 
``tests``
 
  Just get the job done - anything goes.
 

	
 
``bin/`` & ``config/`` & ``alembic/``
 
  The main entry points, defined in ``setup.py``. Note: The TurboGears template
 
  use ``config`` for the high WSGI application - this is not for low level
 
  configuration.
 

	
 
``controllers/``
 
  The top level web application, with TurboGears using the ``root`` controller
 
  as entry point, and ``routing`` dispatching to other controllers.
 

	
 
``templates/**.html``
 
  The "view", rendering to HTML. Invoked by controllers which can pass them
 
  anything from lower layers - especially ``helpers`` available as ``h`` will
 
  cut through all layers, and ``c`` gives access to global variables.
 

	
 
``lib/helpers.py``
 
  High level helpers, exposing everything to templates as ``h``. It depends on
 
  everything and has a huge dependency chain, so it should not be used for
 
  anything else. TODO.
 

	
 
``controllers/base.py``
 
  The base class of controllers, with lots of model knowledge.
 

	
 
``lib/auth.py``
 
  All things related to authentication. TODO.
 

	
 
``lib/utils.py``
 
  High level utils with lots of model knowledge. TODO.
 

	
 
``lib/hooks.py``
 
  Hooks into "everything" to give centralized logging to database, cache
 
  invalidation, and extension handling. TODO.
 

	
 
``model/``
 
  Convenience business logic wrappers around database models.
 

	
 
``model/db.py``
 
  Defines the database schema and provides some additional logic.
 

	
 
``model/scm.py``
 
  All things related to anything. TODO.
 

	
 
SQLAlchemy
 
  Database session and transaction in thread-local variables.
 

	
 
``lib/utils2.py``
 
  Low level utils specific to Kallithea.
 

	
 
``lib/webutils.py``
 
  Low level generic utils with awareness of the TurboGears environment.
 

	
 
TurboGears
 
  Request, response and state like i18n gettext in thread-local variables.
 
  External dependency with global state - usage should be minimized.
 

	
 
``lib/vcs/``
 
  Previously an independent library. No awareness of web, database, or state.
 

	
 
``lib/*``
 
  Various "pure" functionality not depending on anything else.
 

	
 
``__init__``
 
  Very basic Kallithea constants - some of them are set very early based on ``.ini``.
 

	
 
This is not exactly how it is right now, but we aim for something like that.
 
Especially the areas marked as TODO have some problems that need untangling.
 

	
 

	
 
Running tests
 
-------------
 

	
 
@@ -84,6 +173,17 @@ Note that on unix systems, the temporary
 
and the test suite creates repositories in the temporary directory. Linux
 
systems with /tmp mounted noexec will thus fail.
 

	
 
Tests can be run on PostgreSQL like::
 

	
 
    sudo -u postgres createuser 'kallithea-test' --pwprompt  # password password
 
    sudo -u postgres createdb 'kallithea-test' --owner 'kallithea-test'
 
    REUSE_TEST_DB='postgresql://kallithea-test:password@localhost/kallithea-test' py.test
 

	
 
Tests can be run on MariaDB/MySQL like::
 

	
 
    echo "GRANT ALL PRIVILEGES ON \`kallithea-test\`.* TO 'kallithea-test'@'localhost' IDENTIFIED BY 'password'" | sudo -u mysql mysql
 
    TEST_DB='mysql://kallithea-test:password@localhost/kallithea-test?charset=utf8mb4' py.test
 

	
 
You can also use ``tox`` to run the tests with all supported Python versions.
 

	
 
When running tests, Kallithea generates a `test.ini` based on template values
 
@@ -147,8 +247,9 @@ committer/contributor and under GPLv3 un
 
lot about preservation of copyright and license information for existing code
 
that is brought into the project.
 

	
 
Contributions will be accepted in most formats -- such as commits hosted on your own Kallithea instance, or patches sent by
 
email to the `kallithea-general`_ mailing list.
 
Contributions will be accepted in most formats -- such as commits hosted on your
 
own Kallithea instance, or patches sent by email to the `kallithea-general`_
 
mailing list.
 

	
 
Make sure to test your changes both manually and with the automatic tests
 
before posting.
docs/index.rst
Show inline comments
 
@@ -81,7 +81,6 @@ Developer guide
 
.. _python: http://www.python.org/
 
.. _django: http://www.djangoproject.com/
 
.. _mercurial: https://www.mercurial-scm.org/
 
.. _subversion: http://subversion.tigris.org/
 
.. _git: http://git-scm.com/
 
.. _celery: http://celeryproject.org/
 
.. _Sphinx: http://sphinx.pocoo.org/
docs/installation.rst
Show inline comments
 
@@ -19,12 +19,12 @@ The following describes three different 
 
  installations side by side or remove it entirely by just removing the
 
  virtualenv directory) and does not require root privileges.
 

	
 
- :ref:`installation-without-virtualenv`: The alternative method of installing
 
  a Kallithea release is using standard pip. The package will be installed in
 
  the same location as all other Python packages you have ever installed. As a
 
  result, removing it is not as straightforward as with a virtualenv, as you'd
 
  have to remove its dependencies manually and make sure that they are not
 
  needed by other packages.
 
- Kallithea can also be installed with plain pip - globally or with ``--user``
 
  or similar. The package will be installed in the same location as all other
 
  Python packages you have ever installed. As a result, removing it is not as
 
  straightforward as with a virtualenv, as you'd have to remove its
 
  dependencies manually and make sure that they are not needed by other
 
  packages. We recommend using virtualenv.
 

	
 
Regardless of the installation method you may need to make sure you have
 
appropriate development packages installed, as installation of some of the
 
@@ -49,17 +49,24 @@ Installation from repository source
 
-----------------------------------
 

	
 
To install Kallithea in a virtualenv using the stable branch of the development
 
repository, follow the instructions below::
 
repository, use the following commands in your bash shell::
 

	
 
        hg clone https://kallithea-scm.org/repos/kallithea -u stable
 
        cd kallithea
 
        python3 -m venv ../kallithea-venv
 
        . ../kallithea-venv/bin/activate
 
        python3 -m venv venv
 
        . venv/bin/activate
 
        pip install --upgrade pip setuptools
 
        pip install --upgrade -e .
 
        python3 setup.py compile_catalog   # for translation of the UI
 

	
 
You can now proceed to :ref:`setup`.
 
.. note::
 
   This will install all Python dependencies into the virtualenv. Kallithea
 
   itself will however only be installed as a pointer to the source location.
 
   The source clone must thus be kept in the same location, and it shouldn't be
 
   updated to other revisions unless you want to upgrade. Edits in the source
 
   tree will have immediate impact (possibly after a restart of the service).
 

	
 
You can now proceed to :ref:`prepare-front-end-files`.
 

	
 
.. _installation-virtualenv:
 

	
 
@@ -73,27 +80,30 @@ main Python installation and other appli
 
problematic when upgrading the system or Kallithea.
 
An additional benefit of virtualenv is that it doesn't require root privileges.
 

	
 
- Assuming you have installed virtualenv, create a new virtual environment
 
  for example, in `/srv/kallithea/venv`, using the venv command::
 
- Don't install as root - install as a dedicated user like ``kallithea``.
 
  If necessary, create the top directory for the virtualenv (like
 
  ``/srv/kallithea/venv``) as root and assign ownership to the user.
 

	
 
  Make a parent folder for the virtualenv (and perhaps also Kallithea
 
  configuration and data files) such as ``/srv/kallithea``. Create the
 
  directory as root if necessary and grant ownership to the ``kallithea`` user.
 

	
 
- Create a new virtual environment, for example in ``/srv/kallithea/venv``,
 
  specifying the right Python binary::
 

	
 
    python3 -m venv /srv/kallithea/venv
 

	
 
- Activate the virtualenv in your current shell session and make sure the
 
  basic requirements are up-to-date by running::
 
  basic requirements are up-to-date by running the following commands in your
 
  bash shell::
 

	
 
    . /srv/kallithea/venv/bin/activate
 
    pip install --upgrade pip setuptools
 

	
 
.. note:: You can't use UNIX ``sudo`` to source the ``virtualenv`` script; it
 
   will "activate" a shell that terminates immediately. It is also perfectly
 
   acceptable (and desirable) to create a virtualenv as a normal user.
 
.. note:: You can't use UNIX ``sudo`` to source the ``activate`` script; it
 
   will "activate" a shell that terminates immediately.
 

	
 
- Make a folder for Kallithea data files, and configuration somewhere on the
 
  filesystem. For example::
 

	
 
    mkdir /srv/kallithea
 

	
 
- Go into the created directory and run this command to install Kallithea::
 
- Install Kallithea in the activated virtualenv::
 

	
 
    pip install --upgrade kallithea
 

	
 
@@ -105,31 +115,30 @@ An additional benefit of virtualenv is t
 
   This might require installation of development packages using your
 
   distribution's package manager.
 

	
 
  Alternatively, download a .tar.gz from http://pypi.python.org/pypi/Kallithea,
 
  extract it and install from source by running::
 
   Alternatively, download a .tar.gz from http://pypi.python.org/pypi/Kallithea,
 
   extract it and install from source by running::
 

	
 
    pip install --upgrade .
 
     pip install --upgrade .
 

	
 
- This will install Kallithea together with all other required
 
  Python libraries into the activated virtualenv.
 

	
 
You can now proceed to :ref:`setup`.
 
You can now proceed to :ref:`prepare-front-end-files`.
 

	
 
.. _installation-without-virtualenv:
 
.. _prepare-front-end-files:
 

	
 

	
 
Installing a released version without virtualenv
 
------------------------------------------------
 

	
 
For installation without virtualenv, 'just' use::
 

	
 
    pip install kallithea
 
Prepare front-end files
 
-----------------------
 

	
 
Note that this method requires root privileges and will install packages
 
globally without using the system's package manager.
 
Finally, the front-end files with CSS and JavaScript must be prepared. This
 
depends on having some commands available in the shell search path: ``npm``
 
version 6 or later, and ``node.js`` (version 12 or later) available as
 
``node``. The installation method for these dependencies varies between
 
operating systems and distributions.
 

	
 
To install as a regular user in ``~/.local``, you can use::
 
Prepare the front-end by running::
 

	
 
    pip install --user kallithea
 
    kallithea-cli front-end-build
 

	
 
You can now proceed to :ref:`setup`.
docs/overview.rst
Show inline comments
 
@@ -20,23 +20,27 @@ installing Kallithea.
 
2. **Install Kallithea software.**
 
    This makes the ``kallithea-cli`` command line tool available.
 

	
 
3. **Create low level configuration file.**
 
3. **Prepare front-end files**
 
    Some front-end files must be fetched or created using ``npm`` and ``node``
 
    tooling so they can be served to the client as static files.
 

	
 
4. **Create low level configuration file.**
 
    Use ``kallithea-cli config-create`` to create a ``.ini`` file with database
 
    connection info, mail server information, configuration for the specified
 
    web server, etc.
 

	
 
4. **Populate the database.**
 
5. **Populate the database.**
 
    Use ``kallithea-cli db-create`` with the ``.ini`` file to create the
 
    database schema and insert the most basic information: the location of the
 
    repository store and an initial local admin user.
 

	
 
5. **Configure the web server.**
 
6. **Configure the web server.**
 
    The web server must invoke the WSGI entrypoint for the Kallithea software
 
    using the ``.ini`` file (and thus the database). This makes the web
 
    application available so the local admin user can log in and tweak the
 
    configuration further.
 

	
 
6. **Configure users.**
 
7. **Configure users.**
 
    The initial admin user can create additional local users, or configure how
 
    users can be created and authenticated from other user directories.
 

	
 
@@ -44,6 +48,45 @@ See the subsequent sections, the separat
 
:ref:`setup` for details on these steps.
 

	
 

	
 
File system location
 
--------------------
 

	
 
Kallithea can be installed in many different ways. The main parts are:
 

	
 
- A location for the Kallithea software and its dependencies. This includes
 
  the Python code, template files, and front-end code. After installation, this
 
  will be read-only (except when upgrading).
 

	
 
- A location for the ``.ini`` configuration file that tells the Kallithea
 
  instance which database to use (and thus also the repository location).
 
  After installation, this will be read-only (except when upgrading).
 

	
 
- A location for various data files and caches for the Kallithea instance. This
 
  is by default in a ``data`` directory next to the ``.ini`` file. This will
 
  have to be writable by the running Kallithea service.
 

	
 
- A database. The ``.ini`` file specifies which database to use. The database
 
  will be a separate service and live elsewhere in the filesystem if using
 
  PostgreSQL or MariaDB/MySQL. If using SQLite, it will by default live next to
 
  the ``.ini`` file, as ``kallithea.db``.
 

	
 
- A location for the repositories that are hosted by this Kallithea instance.
 
  This will have to be writable by the running Kallithea service. The path to
 
  this location will be configured in the database.
 

	
 
For production setups, one recommendation is to use ``/srv/kallithea`` for the
 
``.ini`` and ``data``, place the virtualenv in ``venv``, and use a Kallithea
 
clone in ``kallithea``. Create a ``kallithea`` user, let it own
 
``/srv/kallithea``, and run as that user when installing.
 

	
 
For simple setups, it is fine to just use something like a ``kallithea`` user
 
with home in ``/home/kallithea`` and place everything there.
 

	
 
For experiments, it might be convenient to run everything as yourself and work
 
inside a clone of Kallithea, with the ``.ini`` and SQLite database in the root
 
of the clone, and a virtualenv in ``venv``.
 

	
 

	
 
Python environment
 
------------------
 

	
 
@@ -177,7 +220,7 @@ There are several web server options:
 
  to get a configuration starting point for your choice of web server.
 

	
 
  (Gearbox will do like ``paste`` and use the WSGI application entry point
 
  ``kallithea.config.middleware:make_app`` as specified in ``setup.py``.)
 
  ``kallithea.config.application:make_app`` as specified in ``setup.py``.)
 

	
 
- `Apache httpd`_ can serve WSGI applications directly using mod_wsgi_ and a
 
  simple Python file with the necessary configuration. This is a good option if
 
@@ -216,13 +259,13 @@ continuous hammering from the internet.
 
.. _Python: http://www.python.org/
 
.. _Gunicorn: http://gunicorn.org/
 
.. _Gevent: http://www.gevent.org/
 
.. _Waitress: http://waitress.readthedocs.org/en/latest/
 
.. _Gearbox: http://turbogears.readthedocs.io/en/latest/turbogears/gearbox.html
 
.. _Waitress: https://docs.pylonsproject.org/projects/waitress/
 
.. _Gearbox: https://turbogears.readthedocs.io/en/latest/turbogears/gearbox.html
 
.. _PyPI: https://pypi.python.org/pypi
 
.. _Apache httpd: http://httpd.apache.org/
 
.. _mod_wsgi: https://code.google.com/p/modwsgi/
 
.. _mod_wsgi: https://modwsgi.readthedocs.io/
 
.. _isapi-wsgi: https://github.com/hexdump42/isapi-wsgi
 
.. _uWSGI: https://uwsgi-docs.readthedocs.org/en/latest/
 
.. _uWSGI: https://uwsgi-docs.readthedocs.io/
 
.. _nginx: http://nginx.org/en/
 
.. _iis: http://en.wikipedia.org/wiki/Internet_Information_Services
 
.. _pip: http://en.wikipedia.org/wiki/Pip_%28package_manager%29
docs/setup.rst
Show inline comments
 
@@ -5,35 +5,72 @@ Setup
 
=====
 

	
 

	
 
Setting up Kallithea
 
--------------------
 
Setting up a Kallithea instance
 
-------------------------------
 

	
 
Some further details to the steps mentioned in the overview.
 

	
 
First, you will need to create a Kallithea configuration file. Run the
 
following command to do so::
 
Create low level configuration file
 
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
 

	
 
First, you will need to create a Kallithea configuration file. The
 
configuration file is a ``.ini`` file that contains various low level settings
 
for Kallithea, e.g. configuration of how to use database, web server, email,
 
and logging.
 

	
 
    kallithea-cli config-create my.ini
 
Change to the desired directory (such as ``/srv/kallithea``) as the right user
 
and run the following command to create the file ``my.ini`` in the current
 
directory::
 

	
 
    kallithea-cli config-create my.ini http_server=waitress
 

	
 
This will create the file ``my.ini`` in the current directory. This
 
configuration file contains the various settings for Kallithea, e.g.
 
proxy port, email settings, usage of static files, cache, Celery
 
settings, and logging. Extra settings can be specified like::
 
To get a good starting point for your configuration, specify the http server
 
you intend to use. It can be ``waitress``, ``gearbox``, ``gevent``,
 
``gunicorn``, or ``uwsgi``. (Apache ``mod_wsgi`` will not use this
 
configuration file, and it is fine to keep the default http_server configuration
 
unused. ``mod_wsgi`` is configured using ``httpd.conf`` directives and a WSGI
 
wrapper script.)
 

	
 
Extra custom settings can be specified like::
 

	
 
    kallithea-cli config-create my.ini host=8.8.8.8 "[handler_console]" formatter=color_formatter
 

	
 
Next, you need to create the databases used by Kallithea. It is recommended to
 
use PostgreSQL or SQLite (default). If you choose a database other than the
 
default, ensure you properly adjust the database URL in your ``my.ini``
 
configuration file to use this other database. Kallithea currently supports
 
PostgreSQL, SQLite and MariaDB/MySQL databases. Create the database by running
 
the following command::
 
Populate the database
 
^^^^^^^^^^^^^^^^^^^^^
 

	
 
Next, you need to create the databases used by Kallithea. Kallithea currently
 
supports PostgreSQL, SQLite and MariaDB/MySQL databases. It is recommended to
 
start out using SQLite (the default) and move to PostgreSQL if it becomes a
 
bottleneck or to get a "proper" database. MariaDB/MySQL is also supported.
 

	
 
For PostgreSQL, run ``pip install psycopg2`` to get the database driver. Make
 
sure the PostgreSQL server is initialized and running. Make sure you have a
 
database user with password authentication with permissions to create databases
 
- for example by running::
 

	
 
    sudo -u postgres createuser 'kallithea' --pwprompt --createdb
 

	
 
For MariaDB/MySQL, run ``pip install mysqlclient`` to get the ``MySQLdb``
 
database driver. Make sure the database server is initialized and running. Make
 
sure you have a database user with password authentication with permissions to
 
create the database - for example by running::
 

	
 
    echo 'CREATE USER "kallithea"@"localhost" IDENTIFIED BY "password"' | sudo -u mysql mysql
 
    echo 'GRANT ALL PRIVILEGES ON `kallithea`.* TO "kallithea"@"localhost"' | sudo -u mysql mysql
 

	
 
Check and adjust ``sqlalchemy.url`` in your ``my.ini`` configuration file to use
 
this database.
 

	
 
Create the database, tables, and initial content by running the following
 
command::
 

	
 
    kallithea-cli db-create -c my.ini
 

	
 
This will prompt you for a "root" path. This "root" path is the location where
 
Kallithea will store all of its repositories on the current machine. After
 
entering this "root" path ``db-create`` will also prompt you for a username
 
and password for the initial admin account which ``db-create`` sets
 
up for you.
 
This will first prompt you for a "root" path. This "root" path is the location
 
where Kallithea will store all of its repositories on the current machine. This
 
location must be writable for the running Kallithea application. Next,
 
``db-create`` will prompt you for a username and password for the initial admin
 
account it sets up for you.
 

	
 
The ``db-create`` values can also be given on the command line.
 
Example::
 
@@ -48,19 +85,20 @@ repositories Kallithea will add all of t
 
location to its database.  (Note: make sure you specify the correct
 
path to the root).
 

	
 
.. note:: the given path for Mercurial_ repositories **must** be write
 
          accessible for the application. It's very important since
 
          the Kallithea web interface will work without write access,
 
          but when trying to do a push it will fail with permission
 
          denied errors unless it has write access.
 
.. note:: It is also possible to use an existing database. For example,
 
          when using PostgreSQL without granting general createdb privileges to
 
          the PostgreSQL kallithea user, set ``sqlalchemy.url =
 
          postgresql://kallithea:password@localhost/kallithea`` and create the
 
          database like::
 

	
 
Finally, the front-end files must be prepared. This requires ``npm`` version 6
 
or later, which needs ``node.js`` (version 12 or later). Prepare the front-end
 
by running::
 
              sudo -u postgres createdb 'kallithea' --owner 'kallithea'
 
              kallithea-cli db-create -c my.ini --reuse
 

	
 
    kallithea-cli front-end-build
 
Running
 
^^^^^^^
 

	
 
You are now ready to use Kallithea. To run it simply execute::
 
You are now ready to use Kallithea. To run it using a gearbox web server,
 
simply execute::
 

	
 
    gearbox serve -c my.ini
 

	
 
@@ -186,7 +224,7 @@ Setting up Whoosh full text search
 

	
 
Kallithea provides full text search of repositories using `Whoosh`__.
 

	
 
.. __: https://whoosh.readthedocs.io/en/latest/
 
.. __: https://whoosh.readthedocs.io/
 

	
 
For an incremental index build, run::
 

	
 
@@ -300,15 +338,21 @@ the supported syntax in ``issue_pat``, `
 
Hook management
 
---------------
 

	
 
Hooks can be managed in similar way to that used in ``.hgrc`` files.
 
Custom Mercurial hooks can be managed in a similar way to that used in ``.hgrc`` files.
 
To manage hooks, choose *Admin > Settings > Hooks*.
 

	
 
The built-in hooks cannot be modified, though they can be enabled or disabled in the *VCS* section.
 

	
 
To add another custom hook simply fill in the first textbox with
 
``<name>.<hook_type>`` and the second with the hook path. Example hooks
 
can be found in ``kallithea.lib.hooks``.
 

	
 
Kallithea will also use some hooks internally. They cannot be modified, but
 
some of them can be enabled or disabled in the *VCS* section.
 

	
 
Kallithea does not actively support custom Git hooks, but hooks can be installed
 
manually in the file system. Kallithea will install and use the
 
``post-receive`` Git hook internally, but it will then invoke
 
``post-receive-custom`` if present.
 

	
 

	
 
Changing default encoding
 
-------------------------
 
@@ -362,6 +406,38 @@ for more info.
 
   user that Kallithea runs.
 

	
 

	
 
Proxy setups
 
------------
 

	
 
When Kallithea is processing HTTP requests from a user, it will see and use
 
some of the basic properties of the connection, both at the TCP/IP level and at
 
the HTTP level. The WSGI server will provide this information to Kallithea in
 
the "environment".
 

	
 
In some setups, a proxy server will take requests from users and forward
 
them to the actual Kallithea server. The proxy server will thus be the
 
immediate client of the Kallithea WSGI server, and Kallithea will basically see
 
it as such. To make sure Kallithea sees the request as it arrived from the
 
client to the proxy server, the proxy server must be configured to
 
somehow pass the original information on to Kallithea, and Kallithea must be
 
configured to pick that information up and trust it.
 

	
 
Kallithea will by default rely on its WSGI server to provide the IP of the
 
client in the WSGI environment as ``REMOTE_ADDR``, but it can be configured to
 
get it from an HTTP header that has been set by the proxy server. For
 
example, if the proxy server puts the client IP in the ``X-Forwarded-For``
 
HTTP header, set::
 

	
 
    remote_addr_variable = HTTP_X_FORWARDED_FOR
 

	
 
Kallithea will by default rely on finding the protocol (``http`` or ``https``)
 
in the WSGI environment as ``wsgi.url_scheme``. If the proxy server puts
 
the protocol of the client request in the ``X-Forwarded-Proto`` HTTP header,
 
Kallithea can be configured to trust that header by setting::
 

	
 
    url_scheme_variable = HTTP_X_FORWARDED_PROTO
 

	
 

	
 
HTTPS support
 
-------------
 

	
 
@@ -370,10 +446,9 @@ Kallithea will by default generate URLs 
 
Alternatively, you can use some special configuration settings to control
 
directly which scheme/protocol Kallithea will use when generating URLs:
 

	
 
- With ``https_fixup = true``, the scheme will be taken from the
 
  ``X-Url-Scheme``, ``X-Forwarded-Scheme`` or ``X-Forwarded-Proto`` HTTP header
 
  (default ``http``).
 
- With ``force_https = true`` the default will be ``https``.
 
- With ``url_scheme_variable`` set, the scheme will be taken from that HTTP
 
  header.
 
- With ``force_https = true``, the scheme will be seen as ``https``.
 
- With ``use_htsts = true``, Kallithea will set ``Strict-Transport-Security`` when using https.
 

	
 
.. _nginx_virtual_host:
 
@@ -556,43 +631,19 @@ that, you'll need to:
 

	
 
    WSGIRestrictEmbedded On
 

	
 
- Create a WSGI dispatch script, like the one below. Make sure you
 
  check that the paths correctly point to where you installed Kallithea
 
  and its Python Virtual Environment.
 
- Create a WSGI dispatch script, like the one below. The ``WSGIDaemonProcess``
 
  ``python-home`` directive will make sure it uses the right Python Virtual
 
  Environment and that paste thus can pick up the right Kallithea
 
  application.
 

	
 
  .. code-block:: python
 

	
 
      import os
 
      os.environ['PYTHON_EGG_CACHE'] = '/srv/kallithea/.egg-cache'
 

	
 
      # sometimes it's needed to set the current dir
 
      os.chdir('/srv/kallithea/')
 

	
 
      import site
 
      site.addsitedir("/srv/kallithea/venv/lib/python3.7/site-packages")
 

	
 
      ini = '/srv/kallithea/my.ini'
 
      from logging.config import fileConfig
 
      fileConfig(ini, {'__file__': ini, 'here': '/srv/kallithea'})
 
      from paste.deploy import loadapp
 
      application = loadapp('config:' + ini)
 

	
 
  Or using proper virtualenv activation:
 

	
 
  .. code-block:: python
 

	
 
      activate_this = '/srv/kallithea/venv/bin/activate_this.py'
 
      execfile(activate_this, dict(__file__=activate_this))
 

	
 
      import os
 
      os.environ['HOME'] = '/srv/kallithea'
 

	
 
      ini = '/srv/kallithea/kallithea.ini'
 
      from logging.config import fileConfig
 
      fileConfig(ini, {'__file__': ini, 'here': '/srv/kallithea'})
 
      from paste.deploy import loadapp
 
      application = loadapp('config:' + ini)
 

	
 
- Add the necessary ``WSGI*`` directives to the Apache Virtual Host configuration
 
  file, like in the example below. Notice that the WSGI dispatch script created
 
  above is referred to with the ``WSGIScriptAlias`` directive.
 
@@ -617,15 +668,6 @@ that, you'll need to:
 
      WSGIScriptAlias / /srv/kallithea/dispatch.wsgi
 
      WSGIPassAuthorization On
 

	
 
  Or if using a dispatcher WSGI script with proper virtualenv activation:
 

	
 
  .. code-block:: apache
 

	
 
      WSGIDaemonProcess kallithea processes=5 threads=1 maximum-requests=100 lang=en_US.utf8
 
      WSGIProcessGroup kallithea
 
      WSGIScriptAlias / /srv/kallithea/dispatch.wsgi
 
      WSGIPassAuthorization On
 

	
 

	
 
Other configuration files
 
-------------------------
docs/upgrade.rst
Show inline comments
 
@@ -39,8 +39,8 @@ Back up your configuration
 

	
 
Make a copy of your Kallithea configuration (``.ini``) file.
 

	
 
If you are using :ref:`rcextensions <customization>`, you should also
 
make a copy of the entire ``rcextensions`` directory.
 
If you are using custom :ref:`extensions <customization>`, you should also
 
make a copy of the ``extensions.py`` file.
 

	
 
Back up your database
 
^^^^^^^^^^^^^^^^^^^^^
 
@@ -225,14 +225,21 @@ clear out your log file so that new erro
 
    upgrade.
 

	
 

	
 
10. Update Git repository hooks
 
-------------------------------
 
10. Reinstall internal Git repository hooks
 
-------------------------------------------
 

	
 
It is possible that an upgrade involves changes to the Git hooks installed by
 
Kallithea. As these hooks are created inside the repositories on the server
 
filesystem, they are not updated automatically when upgrading Kallithea itself.
 

	
 
To update the hooks of your Git repositories:
 
To update the hooks of your Git repositories, run::
 

	
 
    kallithea-cli repo-scan -c my.ini --install-git-hooks
 

	
 
Watch out for warnings like ``skipping overwriting hook file X``, then fix it
 
and rerun, or consider using ``--overwrite-git-hooks`` instead.
 

	
 
Or:
 

	
 
* Go to *Admin > Settings > Remap and Rescan*
 
* Select the checkbox *Install Git hooks*
docs/usage/customization.rst
Show inline comments
 
@@ -39,13 +39,14 @@ running::
 
.. _less: http://lesscss.org/
 

	
 

	
 
Behavioral customization: rcextensions
 
--------------------------------------
 
Behavioral customization: Kallithea extensions
 
----------------------------------------------
 

	
 
Some behavioral customization can be done in Python using ``rcextensions``, a
 
custom Python package that can extend Kallithea functionality.
 
Some behavioral customization can be done in Python using Kallithea
 
``extensions``, a custom Python file you can create to extend Kallithea
 
functionality.
 

	
 
With ``rcextensions`` it's possible to add additional mappings for Whoosh
 
With ``extensions`` it's possible to add additional mappings for Whoosh
 
indexing and statistics, to add additional code into the push/pull/create/delete
 
repository hooks (for example to send signals to build bots such as Jenkins) and
 
even to monkey-patch certain parts of the Kallithea source code (for example
 
@@ -55,9 +56,14 @@ To generate a skeleton extensions packag
 

	
 
    kallithea-cli extensions-create -c my.ini
 

	
 
This will create an ``rcextensions`` package next to the specified ``ini`` file.
 
See the ``__init__.py`` file inside the generated ``rcextensions`` package
 
for more details.
 
This will create an ``extensions.py`` file next to the specified ``ini`` file.
 
You can find more details inside this file.
 

	
 
For compatibility with previous releases of Kallithea, a directory named
 
``rcextensions`` with a file ``__init__.py`` inside of it can also be used. If
 
both an ``extensions.py`` file and an ``rcextensions`` directory are found, only
 
``extensions.py`` will be loaded. Note that the name ``rcextensions`` is
 
deprecated and support for it will be removed in a future release.
 

	
 

	
 
Behavioral customization: code changes
docs/usage/email.rst
Show inline comments
 
@@ -89,8 +89,8 @@ a name and an address in the following f
 
References
 
----------
 

	
 
- `Error Middleware (Pylons documentation) <http://pylons-webframework.readthedocs.org/en/latest/debugging.html#error-middleware>`_
 
- `ErrorHandler (Pylons modules documentation) <http://pylons-webframework.readthedocs.org/en/latest/modules/middleware.html#pylons.middleware.ErrorHandler>`_
 
- `Error Middleware (Pylons documentation) <https://pylons-webframework.readthedocs.io/en/latest/debugging.html#error-middleware>`_
 
- `ErrorHandler (Pylons modules documentation) <https://pylons-webframework.readthedocs.io/en/latest/modules/middleware.html#pylons.middleware.ErrorHandler>`_
 

	
 

	
 
.. _backlash: https://github.com/TurboGears/backlash
docs/usage/general.rst
Show inline comments
 
@@ -118,22 +118,15 @@ Trending source files
 

	
 
Trending source files are calculated based on a predefined dictionary of known
 
types and extensions. If an extension is missing or you would like to scan
 
custom files, it is possible to extend the ``LANGUAGES_EXTENSIONS_MAP``
 
dictionary located in ``kallithea/config/conf.py`` with new types.
 
custom files, it is possible to add additional file extensions with
 
``EXTRA_MAPPINGS`` in your custom Kallithea extensions.py file. See
 
:ref:`customization`.
 

	
 

	
 
Cloning remote repositories
 
---------------------------
 

	
 
Kallithea has the ability to clone repositories from given remote locations.
 
Currently it supports the following options:
 

	
 
- hg  -> hg clone
 
- svn -> hg clone
 
- git -> git clone
 

	
 
.. note:: svn -> hg cloning requires the ``hgsubversion`` library to be
 
   installed.
 

	
 
If you need to clone repositories that are protected via basic authentication,
 
you can pass the credentials in the URL, e.g.
docs/usage/performance.rst
Show inline comments
 
@@ -48,42 +48,37 @@ database platform.
 
Horizontal scaling
 
------------------
 

	
 
Scaling horizontally means running several Kallithea instances and let them
 
share the load. That can give huge performance benefits when dealing with large
 
amounts of traffic (many users, CI servers, etc.). Kallithea can be scaled
 
horizontally on one (recommended) or multiple machines.
 
Scaling horizontally means running several Kallithea instances (also known as
 
worker processes) and let them share the load. That is essential to serve other
 
users while processing a long-running request from a user. Usually, the
 
bottleneck on a Kallithea server is not CPU but I/O speed - especially network
 
speed. It is thus a good idea to run multiple worker processes on one server.
 

	
 
It is generally possible to run WSGI applications multithreaded, so that
 
several HTTP requests are served from the same Python process at once. That can
 
in principle give better utilization of internal caches and less process
 
overhead.
 
.. note::
 

	
 
One danger of running multithreaded is that program execution becomes much more
 
complex; programs must be written to consider all combinations of events and
 
problems might depend on timing and be impossible to reproduce.
 
    Kallithea and the embedded Mercurial backend are not thread-safe. Each
 
    worker process must thus be single-threaded.
 

	
 
Kallithea can't promise to be thread-safe, just like the embedded Mercurial
 
backend doesn't make any strong promises when used as Kallithea uses it.
 
Instead, we recommend scaling by using multiple server processes.
 
Web servers can usually launch multiple worker processes - for example ``mod_wsgi`` with the
 
``WSGIDaemonProcess`` ``processes`` parameter or ``uWSGI`` or ``gunicorn`` with
 
their ``workers`` setting.
 

	
 
Web servers with multiple worker processes (such as ``mod_wsgi`` with the
 
``WSGIDaemonProcess`` ``processes`` parameter) will work out of the box.
 

	
 
Kallithea can also be scaled horizontally across multiple machines.
 
In order to scale horizontally on multiple machines, you need to do the
 
following:
 

	
 
    - Each instance's ``data`` storage needs to be configured to be stored on a
 
      shared disk storage, preferably together with repositories. This ``data``
 
      dir contains template caches, sessions, whoosh index and is used for
 
      task locking (so it is safe across multiple instances). Set the
 
      ``cache_dir``, ``index_dir``, ``beaker.cache.data_dir``, ``beaker.cache.lock_dir``
 
      variables in each .ini file to a shared location across Kallithea instances
 
    - If using several Celery instances,
 
      the message broker should be common to all of them (e.g.,  one
 
      shared RabbitMQ server)
 
    - Load balance using round robin or IP hash, recommended is writing LB rules
 
      that will separate regular user traffic from automated processes like CI
 
      servers or build bots.
 
- Each instance's ``data`` storage needs to be configured to be stored on a
 
  shared disk storage, preferably together with repositories. This ``data``
 
  dir contains template caches, sessions, whoosh index and is used for
 
  task locking (so it is safe across multiple instances). Set the
 
  ``cache_dir``, ``index_dir``, ``beaker.cache.data_dir``, ``beaker.cache.lock_dir``
 
  variables in each .ini file to a shared location across Kallithea instances
 
- If using several Celery instances,
 
  the message broker should be common to all of them (e.g.,  one
 
  shared RabbitMQ server)
 
- Load balance using round robin or IP hash, recommended is writing LB rules
 
  that will separate regular user traffic from automated processes like CI
 
  servers or build bots.
 

	
 

	
 
Serve static files directly from the web server
 
@@ -125,3 +120,6 @@ response. See the documentation for your
 

	
 

	
 
.. _SQLAlchemyGrate: https://github.com/shazow/sqlalchemygrate
 
.. _mod_wsgi: https://modwsgi.readthedocs.io/
 
.. _uWSGI: https://uwsgi-docs.readthedocs.io/
 
.. _gunicorn: http://pypi.python.org/pypi/gunicorn
docs/usage/troubleshooting.rst
Show inline comments
 
@@ -43,12 +43,19 @@ Troubleshooting
 
|
 

	
 
:Q: **How can I use hooks in Kallithea?**
 
:A: It's easy if they are Python hooks: just use advanced link in
 
    hooks section in Admin panel, that works only for Mercurial. If
 
    you want to use Git hooks, just install th proper one in the repository,
 
    e.g., create a file `/gitrepo/hooks/pre-receive`. You can also use
 
    Kallithea-extensions to connect to callback hooks, for both Git
 
    and Mercurial.
 
:A: If using Mercurial, use *Admin > Settings > Hooks* to install
 
    global hooks. Inside the hooks, you can use the current working directory to
 
    control different behaviour for different repositories.
 

	
 
    If using Git, install the hooks manually in each repository, for example by
 
    creating a file ``gitrepo/hooks/pre-receive``.
 
    Note that Kallithea uses the ``post-receive`` hook internally.
 
    Kallithea will not work properly if another post-receive hook is installed instead.
 
    You might also accidentally overwrite your own post-receive hook with the Kallithea hook.
 
    Instead, put your post-receive hook in ``post-receive-custom``, and the Kallithea hook will invoke it.
 

	
 
    You can also use Kallithea-extensions to connect to callback hooks,
 
    for both Git and Mercurial.
 

	
 
|
 

	
init.d/kallithea-daemon-debian
Show inline comments
 
@@ -37,7 +37,7 @@ DAEMON_OPTS="serve --daemon \
 

	
 
start() {
 
  echo "Starting $APP_NAME"
 
  PYTHON_EGG_CACHE="/tmp" start-stop-daemon -d $APP_PATH \
 
  start-stop-daemon -d $APP_PATH \
 
      --start --quiet \
 
      --pidfile $PID_PATH \
 
      --user $RUN_AS \
init.d/kallithea-daemon-gentoo
Show inline comments
 
@@ -33,7 +33,7 @@ depend() {
 

	
 
start() {
 
    ebegin "Starting $APP_NAME"
 
    start-stop-daemon -d $APP_PATH -e PYTHON_EGG_CACHE="/tmp" \
 
    start-stop-daemon -d $APP_PATH \
 
        --start --quiet \
 
        --pidfile $PID_PATH \
 
        --user $RUN_AS \
init.d/kallithea-daemon-redhat
Show inline comments
 
@@ -63,7 +63,7 @@ ensure_pid_dir () {
 

	
 
start_kallithea () {
 
    ensure_pid_dir
 
    PYTHON_EGG_CACHE="/tmp" daemon --pidfile $PID_PATH \
 
    daemon --pidfile $PID_PATH \
 
        --user $RUN_AS "$DAEMON $DAEMON_OPTS"
 
    RETVAL=$?
 
    [ $RETVAL -eq 0 ] && touch $LOCK_FILE
kallithea/__init__.py
Show inline comments
 
@@ -30,20 +30,26 @@ Original author and date, and relevant c
 
import platform
 
import sys
 

	
 
import celery
 

	
 

	
 
if sys.version_info < (3, 6):
 
    raise Exception('Kallithea requires python 3.6 or later')
 

	
 
VERSION = (0, 6, 3)
 
VERSION = (0, 6, 99)
 
BACKENDS = {
 
    'hg': 'Mercurial repository',
 
    'git': 'Git repository',
 
}
 

	
 
CELERY_APP = None  # set to Celery app instance if using Celery
 
CELERY_EAGER = False
 
CELERY_APP = celery.Celery()  # needed at import time but is lazy and can be configured later
 

	
 
CONFIG = {}
 
DEFAULT_USER_ID: int  # set by setup_configuration
 
CONFIG = {}  # set to tg.config when TG app is initialized and calls app_cfg
 

	
 
# URL prefix for non repository related links - must start with `/`
 
ADMIN_PREFIX = '/_admin'
 
URL_SEP = '/'
 

	
 
# Linked module for extensions
 
EXTENSIONS = {}
kallithea/alembic/env.py
Show inline comments
 
@@ -21,7 +21,7 @@ from logging.config import fileConfig
 
from alembic import context
 
from sqlalchemy import engine_from_config, pool
 

	
 
from kallithea.model import db
 
from kallithea.model import meta
 

	
 

	
 
# The alembic.config.Config object, which wraps the current .ini file.
 
@@ -93,7 +93,7 @@ def run_migrations_online():
 

	
 
            # Support autogeneration of migration scripts based on "diff" between
 
            # current database schema and kallithea.model.db schema.
 
            target_metadata=db.Base.metadata,
 
            target_metadata=meta.Base.metadata,
 
            include_object=include_in_autogeneration,
 
            render_as_batch=True, # batch mode is needed for SQLite support
 
        )
kallithea/alembic/versions/7ba0d2cad930_hooks_migrate_internal_hooks_to_.py
Show inline comments
 
new file 100644
 
# This program is free software: you can redistribute it and/or modify
 
# it under the terms of the GNU General Public License as published by
 
# the Free Software Foundation, either version 3 of the License, or
 
# (at your option) any later version.
 
#
 
# This program is distributed in the hope that it will be useful,
 
# but WITHOUT ANY WARRANTY; without even the implied warranty of
 
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 
# GNU General Public License for more details.
 
#
 
# You should have received a copy of the GNU General Public License
 
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
 

	
 
"""hooks: migrate internal hooks to kallithea namespace
 

	
 
Revision ID: 7ba0d2cad930
 
Revises: f62826179f39
 
Create Date: 2021-01-11 00:10:13.576586
 

	
 
"""
 

	
 
# The following opaque hexadecimal identifiers ("revisions") are used
 
# by Alembic to track this migration script and its relations to others.
 
revision = '7ba0d2cad930'
 
down_revision = 'f62826179f39'
 
branch_labels = None
 
depends_on = None
 

	
 
from alembic import op
 
from sqlalchemy import MetaData, Table
 

	
 
from kallithea.model import db
 

	
 

	
 
meta = MetaData()
 

	
 

	
 
def upgrade():
 
    meta.bind = op.get_bind()
 
    ui = Table(db.Ui.__tablename__, meta, autoload=True)
 

	
 
    ui.update(values={
 
        'ui_key': 'changegroup.kallithea_update',
 
        'ui_value': 'python:',  # value in db isn't used
 
    }).where(ui.c.ui_key == 'changegroup.update').execute()
 
    ui.update(values={
 
        'ui_key': 'changegroup.kallithea_repo_size',
 
        'ui_value': 'python:',  # value in db isn't used
 
    }).where(ui.c.ui_key == 'changegroup.repo_size').execute()
 

	
 
    # 642847355a10 moved these hooks out of db - remove old entries
 
    ui.delete().where(ui.c.ui_key == 'changegroup.push_logger').execute()
 
    ui.delete().where(ui.c.ui_key == 'outgoing.pull_logger').execute()
 

	
 

	
 
def downgrade():
 
    pass
kallithea/alembic/versions/a020f7044fd6_rename_hooks.py
Show inline comments
 
@@ -29,7 +29,7 @@ depends_on = None
 
from alembic import op
 
from sqlalchemy import MetaData, Table
 

	
 
from kallithea.model.db import Ui
 
from kallithea.model import db
 

	
 

	
 
meta = MetaData()
 
@@ -37,7 +37,7 @@ meta = MetaData()
 

	
 
def upgrade():
 
    meta.bind = op.get_bind()
 
    ui = Table(Ui.__tablename__, meta, autoload=True)
 
    ui = Table(db.Ui.__tablename__, meta, autoload=True)
 

	
 
    ui.update(values={
 
        'ui_key': 'prechangegroup.push_lock_handling',
 
@@ -51,7 +51,7 @@ def upgrade():
 

	
 
def downgrade():
 
    meta.bind = op.get_bind()
 
    ui = Table(Ui.__tablename__, meta, autoload=True)
 
    ui = Table(db.Ui.__tablename__, meta, autoload=True)
 

	
 
    ui.update(values={
 
        'ui_key': 'prechangegroup.pre_push',
kallithea/alembic/versions/ad357ccd9521_drop_locking.py
Show inline comments
 
@@ -30,7 +30,7 @@ import sqlalchemy as sa
 
from alembic import op
 
from sqlalchemy import MetaData, Table
 

	
 
from kallithea.model.db import Ui
 
from kallithea.model import db
 

	
 

	
 
meta = MetaData()
 
@@ -45,7 +45,7 @@ def upgrade():
 
        batch_op.drop_column('enable_locking')
 

	
 
    meta.bind = op.get_bind()
 
    ui = Table(Ui.__tablename__, meta, autoload=True)
 
    ui = Table(db.Ui.__tablename__, meta, autoload=True)
 
    ui.delete().where(ui.c.ui_key == 'prechangegroup.push_lock_handling').execute()
 
    ui.delete().where(ui.c.ui_key == 'preoutgoing.pull_lock_handling').execute()
 

	
kallithea/alembic/versions/f62826179f39_add_unique_constraint_on_.py
Show inline comments
 
new file 100644
 
# This program is free software: you can redistribute it and/or modify
 
# it under the terms of the GNU General Public License as published by
 
# the Free Software Foundation, either version 3 of the License, or
 
# (at your option) any later version.
 
#
 
# This program is distributed in the hope that it will be useful,
 
# but WITHOUT ANY WARRANTY; without even the implied warranty of
 
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 
# GNU General Public License for more details.
 
#
 
# You should have received a copy of the GNU General Public License
 
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
 

	
 
"""add unique constraint on PullRequestReviewer
 

	
 
Revision ID: f62826179f39
 
Revises: a0a1bf09c143
 
Create Date: 2020-06-15 12:30:37.420321
 

	
 
"""
 

	
 
# The following opaque hexadecimal identifiers ("revisions") are used
 
# by Alembic to track this migration script and its relations to others.
 
revision = 'f62826179f39'
 
down_revision = 'a0a1bf09c143'
 
branch_labels = None
 
depends_on = None
 

	
 
import sqlalchemy as sa
 
from alembic import op
 

	
 
from kallithea.model import db
 

	
 

	
 
def upgrade():
 
    session = sa.orm.session.Session(bind=op.get_bind())
 

	
 
    # there may be existing duplicates in the database, remove them first
 

	
 
    seen = set()
 
    # duplicate_values contains one copy of each duplicated pair
 
    duplicate_values = (
 
        session
 
        .query(db.PullRequestReviewer.pull_request_id, db.PullRequestReviewer.user_id)
 
        .group_by(db.PullRequestReviewer.pull_request_id, db.PullRequestReviewer.user_id)
 
        .having(sa.func.count(db.PullRequestReviewer.pull_request_reviewers_id) > 1)
 
    )
 

	
 
    for pull_request_id, user_id in duplicate_values:
 
        # duplicate_occurrences contains all db records of the duplicate_value
 
        # currently being processed
 
        duplicate_occurrences = (
 
            session
 
            .query(db.PullRequestReviewer)
 
            .filter(db.PullRequestReviewer.pull_request_id == pull_request_id)
 
            .filter(db.PullRequestReviewer.user_id == user_id)
 
        )
 
        for prr in duplicate_occurrences:
 
            if (pull_request_id, user_id) in seen:
 
                session.delete(prr)
 
            else:
 
                seen.add((pull_request_id, user_id))
 

	
 
    session.commit()
 

	
 
    # after deleting all duplicates, add the unique constraint
 
    with op.batch_alter_table('pull_request_reviewers', schema=None) as batch_op:
 
        batch_op.create_unique_constraint(batch_op.f('uq_pull_request_reviewers_pull_request_id'), ['pull_request_id', 'user_id'])
 

	
 

	
 
def downgrade():
 
    with op.batch_alter_table('pull_request_reviewers', schema=None) as batch_op:
 
        batch_op.drop_constraint(batch_op.f('uq_pull_request_reviewers_pull_request_id'), type_='unique')
kallithea/bin/kallithea_cli_base.py
Show inline comments
 
@@ -23,7 +23,7 @@ import click
 
import paste.deploy
 

	
 
import kallithea
 
import kallithea.config.middleware
 
import kallithea.config.application
 

	
 

	
 
# kallithea_cli is usually invoked through the 'kallithea-cli' wrapper script
 
@@ -53,10 +53,10 @@ def read_config(ini_file_name, strip_sec
 
def cli():
 
    """Various commands to manage a Kallithea instance."""
 

	
 
def register_command(config_file=False, config_file_initialize_app=False, hidden=False):
 
def register_command(needs_config_file=False, config_file_initialize_app=False, hidden=False):
 
    """Register a kallithea-cli subcommand.
 

	
 
    If one of the config_file flags are true, a config file must be specified
 
    If one of the needs_config_file flags are true, a config file must be specified
 
    with -c and it is read and logging is configured. The configuration is
 
    available in the kallithea.CONFIG dict.
 

	
 
@@ -64,21 +64,23 @@ def register_command(config_file=False, 
 
    (including tg.config), and database access will also be fully initialized.
 
    """
 
    cli_command = cli.command(hidden=hidden)
 
    if config_file or config_file_initialize_app:
 
    if needs_config_file or config_file_initialize_app:
 
        def annotator(annotated):
 
            @click.option('--config_file', '-c', help="Path to .ini file with app configuration.",
 
                type=click.Path(dir_okay=False, exists=True, readable=True), required=True)
 
            @functools.wraps(annotated) # reuse meta data from the wrapped function so click can see other options
 
            def runtime_wrapper(config_file, *args, **kwargs):
 
                path_to_ini_file = os.path.realpath(config_file)
 
                kallithea.CONFIG = paste.deploy.appconfig('config:' + path_to_ini_file)
 
                config = paste.deploy.appconfig('config:' + path_to_ini_file)
 
                cp = configparser.ConfigParser(strict=False)
 
                cp.read_string(read_config(path_to_ini_file, strip_section_prefix=annotated.__name__))
 
                logging.config.fileConfig(cp,
 
                    {'__file__': path_to_ini_file, 'here': os.path.dirname(path_to_ini_file)})
 
                if needs_config_file:
 
                    annotated(*args, config=config, **kwargs)
 
                if config_file_initialize_app:
 
                    kallithea.config.middleware.make_app(kallithea.CONFIG.global_conf, **kallithea.CONFIG.local_conf)
 
                return annotated(*args, **kwargs)
 
                    kallithea.config.application.make_app(config.global_conf, **config.local_conf)
 
                    annotated(*args, **kwargs)
 
            return cli_command(runtime_wrapper)
 
        return annotator
 
    return cli_command
kallithea/bin/kallithea_cli_celery.py
Show inline comments
 
@@ -12,16 +12,18 @@
 
# You should have received a copy of the GNU General Public License
 
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
 

	
 
import celery.bin.worker
 
import click
 
from celery.bin.celery import celery as celery_command
 

	
 
import kallithea
 
import kallithea.bin.kallithea_cli_base as cli_base
 
from kallithea.lib import celery_app
 
from kallithea.lib.utils2 import asbool
 

	
 

	
 
@cli_base.register_command(config_file_initialize_app=True)
 
@cli_base.register_command(needs_config_file=True)
 
@click.argument('celery_args', nargs=-1)
 
def celery_run(celery_args):
 
def celery_run(celery_args, config):
 
    """Start Celery worker(s) for asynchronous tasks.
 

	
 
    This commands starts the Celery daemon which will spawn workers to handle
 
@@ -32,9 +34,20 @@ def celery_run(celery_args):
 
    by this CLI command.
 
    """
 

	
 
    if not kallithea.CELERY_APP:
 
    if not asbool(config.get('use_celery')):
 
        raise Exception('Please set use_celery = true in .ini config '
 
                        'file before running this command')
 

	
 
    cmd = celery.bin.worker.worker(kallithea.CELERY_APP)
 
    return cmd.run_from_argv(None, command='celery-run -c CONFIG_FILE --', argv=list(celery_args))
 
    kallithea.CELERY_APP.config_from_object(celery_app.make_celery_config(config))
 

	
 
    kallithea.CELERY_APP.loader.on_worker_process_init = lambda: kallithea.config.application.make_app(config.global_conf, **config.local_conf)
 

	
 
    args = list(celery_args)
 
    # args[0] is generally ignored when prog_name is specified, but -h *needs* it to be 'worker' ... but will also suggest that users specify 'worker' explicitly
 
    if not args or args[0] != 'worker':
 
        args.insert(0, 'worker')
 

	
 
    # inline kallithea.CELERY_APP.start in order to allow specifying prog_name
 
    assert celery_command.params[0].name == 'app'
 
    celery_command.params[0].default = kallithea.CELERY_APP
 
    celery_command.main(args=args, prog_name='kallithea-cli celery-run -c CONFIG_FILE --')
kallithea/bin/kallithea_cli_config.py
Show inline comments
 
@@ -21,7 +21,7 @@ import click
 
import mako.exceptions
 

	
 
import kallithea.bin.kallithea_cli_base as cli_base
 
import kallithea.lib.locale
 
import kallithea.lib.locales
 
from kallithea.lib import inifile
 

	
 

	
 
@@ -66,7 +66,7 @@ def config_create(config_file, key_value
 
        'git_hook_interpreter': sys.executable,
 
        'user_home_path': os.path.expanduser('~'),
 
        'kallithea_cli_path': cli_base.kallithea_cli_path,
 
        'ssh_locale': kallithea.lib.locale.get_current_locale(),
 
        'ssh_locale': kallithea.lib.locales.get_current_locale(),
 
    }
 
    ini_settings = defaultdict(dict)
 

	
kallithea/bin/kallithea_cli_db.py
Show inline comments
 
@@ -15,11 +15,15 @@ import click
 

	
 
import kallithea
 
import kallithea.bin.kallithea_cli_base as cli_base
 
import kallithea.lib.utils
 
import kallithea.model.scm
 
from kallithea.lib.db_manage import DbManage
 
from kallithea.model.meta import Session
 
from kallithea.model import meta
 

	
 

	
 
@cli_base.register_command(config_file=True)
 
@cli_base.register_command(needs_config_file=True, config_file_initialize_app=True)
 
@click.option('--reuse/--no-reuse', default=False,
 
        help='Reuse and clean existing database instead of dropping and creating (default: no reuse)')
 
@click.option('--user', help='Username of administrator account.')
 
@click.option('--password', help='Password for administrator account.')
 
@click.option('--email', help='Email address of administrator account.')
 
@@ -28,7 +32,7 @@ from kallithea.model.meta import Session
 
@click.option('--force-no', is_flag=True, help='Answer no to every question.')
 
@click.option('--public-access/--no-public-access', default=True,
 
        help='Enable/disable public access on this installation (default: enable)')
 
def db_create(user, password, email, repos, force_yes, force_no, public_access):
 
def db_create(user, password, email, repos, force_yes, force_no, public_access, reuse, config=None):
 
    """Initialize the database.
 

	
 
    Create all required tables in the database specified in the configuration
 
@@ -37,44 +41,43 @@ def db_create(user, password, email, rep
 

	
 
    You can pass the answers to all questions as options to this command.
 
    """
 
    dbconf = kallithea.CONFIG['sqlalchemy.url']
 
    if config is not None:  # first called with config, before app initialization
 
        dbconf = config['sqlalchemy.url']
 

	
 
    # force_ask should be True (yes), False (no), or None (ask)
 
    if force_yes:
 
        force_ask = True
 
    elif force_no:
 
        force_ask = False
 
    else:
 
        force_ask = None
 
        # force_ask should be True (yes), False (no), or None (ask)
 
        if force_yes:
 
            force_ask = True
 
        elif force_no:
 
            force_ask = False
 
        else:
 
            force_ask = None
 

	
 
    cli_args = dict(
 
            username=user,
 
            password=password,
 
            email=email,
 
            repos_location=repos,
 
            force_ask=force_ask,
 
            public_access=public_access,
 
    )
 
    dbmanage = DbManage(dbconf=dbconf, root=kallithea.CONFIG['here'],
 
                        tests=False, cli_args=cli_args)
 
    dbmanage.create_tables(override=True)
 
    repo_root_path = dbmanage.prompt_repo_root_path(None)
 
    dbmanage.create_settings(repo_root_path)
 
    dbmanage.create_default_user()
 
    dbmanage.admin_prompt()
 
    dbmanage.create_permissions()
 
    dbmanage.populate_default_permissions()
 
    Session().commit()
 
        cli_args = dict(
 
                username=user,
 
                password=password,
 
                email=email,
 
                repos_location=repos,
 
                force_ask=force_ask,
 
                public_access=public_access,
 
        )
 
        dbmanage = DbManage(dbconf=dbconf, root=config['here'],
 
                            cli_args=cli_args)
 
        dbmanage.create_tables(reuse_database=reuse)
 
        repo_root_path = dbmanage.prompt_repo_root_path(None)
 
        dbmanage.create_settings(repo_root_path)
 
        dbmanage.create_default_user()
 
        dbmanage.create_admin_user()
 
        dbmanage.create_permissions()
 
        dbmanage.populate_default_permissions()
 
        meta.Session().commit()
 

	
 
    # initial repository scan
 
    kallithea.config.middleware.make_app(
 
            kallithea.CONFIG.global_conf, **kallithea.CONFIG.local_conf)
 
    added, _ = kallithea.lib.utils.repo2db_mapper(kallithea.model.scm.ScmModel().repo_scan())
 
    if added:
 
        click.echo('Initial repository scan: added following repositories:')
 
        click.echo('\t%s' % '\n\t'.join(added))
 
    else:
 
        click.echo('Initial repository scan: no repositories found.')
 
    else:  # then called again after app initialization
 
        added, _ = kallithea.lib.utils.repo2db_mapper(kallithea.model.scm.ScmModel().repo_scan())
 
        if added:
 
            click.echo('Initial repository scan: added following repositories:')
 
            click.echo('\t%s' % '\n\t'.join(added))
 
        else:
 
            click.echo('Initial repository scan: no repositories found.')
 

	
 
    click.echo('Database set up successfully.')
 
    click.echo("Don't forget to build the front-end using 'kallithea-cli front-end-build'.")
 
        click.echo('Database set up successfully.')
 
        click.echo("Don't forget to build the front-end using 'kallithea-cli front-end-build'.")
kallithea/bin/kallithea_cli_extensions.py
Show inline comments
 
@@ -24,24 +24,23 @@ import os
 
import click
 
import pkg_resources
 

	
 
import kallithea
 
import kallithea.bin.kallithea_cli_base as cli_base
 
from kallithea.lib.utils2 import ask_ok
 

	
 

	
 
@cli_base.register_command(config_file=True)
 
def extensions_create():
 
@cli_base.register_command(needs_config_file=True)
 
def extensions_create(config):
 
    """Write template file for extending Kallithea in Python.
 

	
 
    An rcextensions directory with a __init__.py file will be created next to
 
    the ini file. Local customizations in that file will survive upgrades.
 
    The file contains instructions on how it can be customized.
 
    Create a template `extensions.py` file next to the ini file. Local
 
    customizations in that file will survive upgrades. The file contains
 
    instructions on how it can be customized.
 
    """
 
    here = kallithea.CONFIG['here']
 
    here = config['here']
 
    content = pkg_resources.resource_string(
 
        'kallithea', os.path.join('config', 'rcextensions', '__init__.py')
 
        'kallithea', os.path.join('templates', 'py', 'extensions.py')
 
    )
 
    ext_file = os.path.join(here, 'rcextensions', '__init__.py')
 
    ext_file = os.path.join(here, 'extensions.py')
 
    if os.path.exists(ext_file):
 
        msg = ('Extension file %s already exists, do you want '
 
               'to overwrite it ? [y/n] ') % ext_file
kallithea/bin/kallithea_cli_iis.py
Show inline comments
 
@@ -16,7 +16,6 @@ import sys
 

	
 
import click
 

	
 
import kallithea
 
import kallithea.bin.kallithea_cli_base as cli_base
 

	
 

	
 
@@ -57,16 +56,16 @@ if __name__=='__main__':
 
    HandleCommandLine(params)
 
'''
 

	
 
@cli_base.register_command(config_file=True)
 
@cli_base.register_command(needs_config_file=True)
 
@click.option('--virtualdir', default='/',
 
        help='The virtual folder to install into on IIS.')
 
def iis_install(virtualdir):
 
def iis_install(virtualdir, config):
 
    """Install into IIS using isapi-wsgi."""
 

	
 
    config_file_abs = kallithea.CONFIG['__file__']
 
    config_file_abs = config['__file__']
 

	
 
    try:
 
        import isapi_wsgi
 
        import isapi_wsgi  # pytype: disable=import-error
 
        assert isapi_wsgi
 
    except ImportError:
 
        sys.stderr.write('missing requirement: isapi-wsgi not installed\n')
kallithea/bin/kallithea_cli_index.py
Show inline comments
 
@@ -28,7 +28,7 @@ import kallithea
 
import kallithea.bin.kallithea_cli_base as cli_base
 
from kallithea.lib.indexers.daemon import WhooshIndexingDaemon
 
from kallithea.lib.pidlock import DaemonLock, LockHeld
 
from kallithea.lib.utils import load_rcextensions
 
from kallithea.lib.utils import load_extensions
 
from kallithea.model.repo import RepoModel
 

	
 

	
 
@@ -41,7 +41,7 @@ def index_create(repo_location, index_on
 
    """Create or update full text search index"""
 

	
 
    index_location = kallithea.CONFIG['index_dir']
 
    load_rcextensions(kallithea.CONFIG['here'])
 
    load_extensions(kallithea.CONFIG['here'])
 

	
 
    if not repo_location:
 
        repo_location = RepoModel().repos_path
kallithea/bin/kallithea_cli_repo.py
Show inline comments
 
@@ -30,15 +30,18 @@ import kallithea
 
import kallithea.bin.kallithea_cli_base as cli_base
 
from kallithea.lib.utils import REMOVED_REPO_PAT, repo2db_mapper
 
from kallithea.lib.utils2 import ask_ok
 
from kallithea.model.db import Repository
 
from kallithea.model.meta import Session
 
from kallithea.model import db, meta
 
from kallithea.model.scm import ScmModel
 

	
 

	
 
@cli_base.register_command(config_file_initialize_app=True)
 
@click.option('--remove-missing', is_flag=True,
 
        help='Remove missing repositories from the Kallithea database.')
 
def repo_scan(remove_missing):
 
@click.option('--install-git-hooks', is_flag=True,
 
        help='(Re)install Kallithea Git hooks without overwriting other hooks.')
 
@click.option('--overwrite-git-hooks', is_flag=True,
 
        help='(Re)install Kallithea Git hooks, overwriting other hooks.')
 
def repo_scan(remove_missing, install_git_hooks, overwrite_git_hooks):
 
    """Scan filesystem for repositories.
 

	
 
    Search the configured repository root for new repositories and add them
 
@@ -49,7 +52,9 @@ def repo_scan(remove_missing):
 
    """
 
    click.echo('Now scanning root location for new repos ...')
 
    added, removed = repo2db_mapper(ScmModel().repo_scan(),
 
                                    remove_obsolete=remove_missing)
 
                                    remove_obsolete=remove_missing,
 
                                    install_git_hooks=install_git_hooks,
 
                                    overwrite_git_hooks=overwrite_git_hooks)
 
    click.echo('Scan completed.')
 
    if added:
 
        click.echo('Added: %s' % ', '.join(added))
 
@@ -73,11 +78,11 @@ def repo_update_metadata(repositories):
 
    updated.
 
    """
 
    if not repositories:
 
        repo_list = Repository.query().all()
 
        repo_list = db.Repository.query().all()
 
    else:
 
        repo_names = [n.strip() for n in repositories]
 
        repo_list = list(Repository.query()
 
                        .filter(Repository.repo_name.in_(repo_names)))
 
        repo_list = list(db.Repository.query()
 
                        .filter(db.Repository.repo_name.in_(repo_names)))
 

	
 
    for repo in repo_list:
 
        # update latest revision metadata in database
 
@@ -86,7 +91,7 @@ def repo_update_metadata(repositories):
 
        # first access
 
        repo.set_invalidate()
 

	
 
    Session().commit()
 
    meta.Session().commit()
 

	
 
    click.echo('Updated database with information about latest change in the following %s repositories:' % (len(repo_list)))
 
    click.echo('\n'.join(repo.repo_name for repo in repo_list))
kallithea/bin/kallithea_cli_ssh.py
Show inline comments
 
@@ -21,9 +21,9 @@ import click
 

	
 
import kallithea
 
import kallithea.bin.kallithea_cli_base as cli_base
 
from kallithea.lib.utils2 import str2bool
 
from kallithea.lib.vcs.backends.git.ssh import GitSshHandler
 
from kallithea.lib.vcs.backends.hg.ssh import MercurialSshHandler
 
from kallithea.lib.utils2 import asbool
 
from kallithea.lib.vcs.ssh.git import GitSshHandler
 
from kallithea.lib.vcs.ssh.hg import MercurialSshHandler
 
from kallithea.model.ssh_key import SshKeyModel, SshKeyModelException
 

	
 

	
 
@@ -40,8 +40,7 @@ def ssh_serve(user_id, key_id):
 
    protocol access. The access will be granted as the specified user ID, and
 
    logged as using the specified key ID.
 
    """
 
    ssh_enabled = kallithea.CONFIG.get('ssh_enabled', False)
 
    if not str2bool(ssh_enabled):
 
    if not asbool(kallithea.CONFIG.get('ssh_enabled', False)):
 
        sys.stderr.write("SSH access is disabled.\n")
 
        return sys.exit(1)
 

	
 
@@ -70,7 +69,7 @@ def ssh_serve(user_id, key_id):
 
        vcs_handler = VcsHandler.make(ssh_command_parts)
 
        if vcs_handler is not None:
 
            vcs_handler.serve(user_id, key_id, client_ip)
 
            assert False # serve is written so it never will terminate
 
            sys.exit(0)
 

	
 
    sys.stderr.write("This account can only be used for repository access. SSH command %r is not supported.\n" % ssh_original_command)
 
    sys.exit(1)
kallithea/bin/vcs_hooks.py
Show inline comments
 
file copied from kallithea/lib/hooks.py to kallithea/bin/vcs_hooks.py
 
@@ -12,10 +12,10 @@
 
# You should have received a copy of the GNU General Public License
 
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
 
"""
 
kallithea.lib.hooks
 
~~~~~~~~~~~~~~~~~~~
 
kallithea.bin.vcs_hooks
 
~~~~~~~~~~~~~~~~~~~~~~~
 

	
 
Hooks run by Kallithea
 
Entry points for Kallithea hooking into Mercurial and Git.
 

	
 
This file was forked by the Kallithea project in July 2014.
 
Original author and date, and relevant copyright and licensing information is below:
 
@@ -25,279 +25,84 @@ Original author and date, and relevant c
 
:license: GPLv3, see LICENSE.md for more details.
 
"""
 

	
 
import logging
 
import os
 
import sys
 
import time
 

	
 
import mercurial.scmutil
 

	
 
from kallithea.lib import helpers as h
 
from kallithea.lib.exceptions import UserCreationError
 
from kallithea.lib.utils import action_logger, make_ui
 
import mercurial.hg
 
import mercurial.scmutil
 
import paste.deploy
 

	
 
import kallithea
 
import kallithea.config.application
 
from kallithea.lib import hooks, webutils
 
from kallithea.lib.utils2 import HookEnvironmentError, ascii_str, get_hook_environment, safe_bytes, safe_str
 
from kallithea.lib.vcs.backends.base import EmptyChangeset
 
from kallithea.model.db import Repository, User
 
from kallithea.lib.vcs.utils.helpers import get_scm_size
 
from kallithea.model import db
 

	
 

	
 
def _get_scm_size(alias, root_path):
 
    if not alias.startswith('.'):
 
        alias += '.'
 

	
 
    size_scm, size_root = 0, 0
 
    for path, dirs, files in os.walk(root_path):
 
        if path.find(alias) != -1:
 
            for f in files:
 
                try:
 
                    size_scm += os.path.getsize(os.path.join(path, f))
 
                except OSError:
 
                    pass
 
        else:
 
            for f in files:
 
                try:
 
                    size_root += os.path.getsize(os.path.join(path, f))
 
                except OSError:
 
                    pass
 

	
 
    size_scm_f = h.format_byte_size(size_scm)
 
    size_root_f = h.format_byte_size(size_root)
 
    size_total_f = h.format_byte_size(size_root + size_scm)
 

	
 
    return size_scm_f, size_root_f, size_total_f
 
log = logging.getLogger(__name__)
 

	
 

	
 
def repo_size(ui, repo, hooktype=None, **kwargs):
 
    """Show size of Mercurial repository.
 

	
 
    Called as Mercurial hook changegroup.repo_size after push.
 
    Called as Mercurial hook changegroup.kallithea_repo_size after push.
 
    """
 
    size_hg_f, size_root_f, size_total_f = _get_scm_size('.hg', safe_str(repo.root))
 
    size_hg, size_root = get_scm_size('.hg', safe_str(repo.root))
 

	
 
    last_cs = repo[len(repo) - 1]
 

	
 
    msg = ('Repository size .hg: %s Checkout: %s Total: %s\n'
 
           'Last revision is now r%s:%s\n') % (
 
        size_hg_f, size_root_f, size_total_f, last_cs.rev(), ascii_str(last_cs.hex())[:12]
 
        webutils.format_byte_size(size_hg),
 
        webutils.format_byte_size(size_root),
 
        webutils.format_byte_size(size_hg + size_root),
 
        last_cs.rev(),
 
        ascii_str(last_cs.hex())[:12],
 
    )
 
    ui.status(safe_bytes(msg))
 

	
 

	
 
def log_pull_action(ui, repo, **kwargs):
 
    """Logs user last pull action
 

	
 
    Called as Mercurial hook outgoing.pull_logger or from Kallithea before invoking Git.
 

	
 
    Does *not* use the action from the hook environment but is always 'pull'.
 
    """
 
    ex = get_hook_environment()
 
def update(ui, repo, hooktype=None, **kwargs):
 
    """Update repo after push. The equivalent to 'hg update' but using the same
 
    Mercurial as everything else.
 

	
 
    user = User.get_by_username(ex.username)
 
    action = 'pull'
 
    action_logger(user, action, ex.repository, ex.ip, commit=True)
 
    # extension hook call
 
    from kallithea import EXTENSIONS
 
    callback = getattr(EXTENSIONS, 'PULL_HOOK', None)
 
    if callable(callback):
 
        kw = {}
 
        kw.update(ex)
 
        callback(**kw)
 

	
 
    return 0
 
    Called as Mercurial hook changegroup.kallithea_update after push.
 
    """
 
    try:
 
        ui.pushbuffer(error=True, subproc=True)
 
        rev = brev = None
 
        mercurial.hg.updatetotally(ui, repo, rev, brev)
 
    finally:
 
        s = ui.popbuffer()  # usually just "x files updated, x files merged, x files removed, x files unresolved"
 
        log.info('%s update hook output: %s', safe_str(repo.root), safe_str(s).rstrip())
 

	
 

	
 
def log_push_action(ui, repo, node, node_last, **kwargs):
 
def pull_action(ui, repo, **kwargs):
 
    """Logs user pull action
 

	
 
    Called as Mercurial hook outgoing.kallithea_pull_action.
 
    """
 
    hooks.log_pull_action()
 

	
 

	
 
def push_action(ui, repo, node, node_last, **kwargs):
 
    """
 
    Register that changes have been added to the repo - log the action *and* invalidate caches.
 
    Note: This hook is not only logging, but also the side effect invalidating
 
    caches! The function should perhaps be renamed.
 

	
 
    Called as Mercurial hook changegroup.kallithea_log_push_action .
 
    Called as Mercurial hook changegroup.kallithea_push_action .
 

	
 
    The pushed changesets is given by the revset 'node:node_last'.
 
    """
 
    revs = [ascii_str(repo[r].hex()) for r in mercurial.scmutil.revrange(repo, [b'%s:%s' % (node, node_last)])]
 
    process_pushed_raw_ids(revs)
 
    return 0
 

	
 

	
 
def process_pushed_raw_ids(revs):
 
    """
 
    Register that changes have been added to the repo - log the action *and* invalidate caches.
 

	
 
    Called from Mercurial changegroup.kallithea_log_push_action calling hook log_push_action,
 
    or from the Git post-receive hook calling handle_git_post_receive ...
 
    or from scm _handle_push.
 
    """
 
    ex = get_hook_environment()
 

	
 
    action = '%s:%s' % (ex.action, ','.join(revs))
 
    action_logger(ex.username, action, ex.repository, ex.ip, commit=True)
 

	
 
    from kallithea.model.scm import ScmModel
 
    ScmModel().mark_for_invalidation(ex.repository)
 

	
 
    # extension hook call
 
    from kallithea import EXTENSIONS
 
    callback = getattr(EXTENSIONS, 'PUSH_HOOK', None)
 
    if callable(callback):
 
        kw = {'pushed_revs': revs}
 
        kw.update(ex)
 
        callback(**kw)
 

	
 

	
 
def log_create_repository(repository_dict, created_by, **kwargs):
 
    """
 
    Post create repository Hook.
 

	
 
    :param repository: dict dump of repository object
 
    :param created_by: username who created repository
 

	
 
    available keys of repository_dict:
 

	
 
     'repo_type',
 
     'description',
 
     'private',
 
     'created_on',
 
     'enable_downloads',
 
     'repo_id',
 
     'owner_id',
 
     'enable_statistics',
 
     'clone_uri',
 
     'fork_id',
 
     'group_id',
 
     'repo_name'
 

	
 
    """
 
    from kallithea import EXTENSIONS
 
    callback = getattr(EXTENSIONS, 'CREATE_REPO_HOOK', None)
 
    if callable(callback):
 
        kw = {}
 
        kw.update(repository_dict)
 
        kw.update({'created_by': created_by})
 
        kw.update(kwargs)
 
        return callback(**kw)
 

	
 
    return 0
 

	
 

	
 
def check_allowed_create_user(user_dict, created_by, **kwargs):
 
    # pre create hooks
 
    from kallithea import EXTENSIONS
 
    callback = getattr(EXTENSIONS, 'PRE_CREATE_USER_HOOK', None)
 
    if callable(callback):
 
        allowed, reason = callback(created_by=created_by, **user_dict)
 
        if not allowed:
 
            raise UserCreationError(reason)
 
    hooks.process_pushed_raw_ids(revs)
 

	
 

	
 
def log_create_user(user_dict, created_by, **kwargs):
 
    """
 
    Post create user Hook.
 

	
 
    :param user_dict: dict dump of user object
 

	
 
    available keys for user_dict:
 

	
 
     'username',
 
     'full_name_or_username',
 
     'full_contact',
 
     'user_id',
 
     'name',
 
     'firstname',
 
     'short_contact',
 
     'admin',
 
     'lastname',
 
     'ip_addresses',
 
     'ldap_dn',
 
     'email',
 
     'api_key',
 
     'last_login',
 
     'full_name',
 
     'active',
 
     'password',
 
     'emails',
 

	
 
    """
 
    from kallithea import EXTENSIONS
 
    callback = getattr(EXTENSIONS, 'CREATE_USER_HOOK', None)
 
    if callable(callback):
 
        return callback(created_by=created_by, **user_dict)
 

	
 
    return 0
 

	
 

	
 
def log_delete_repository(repository_dict, deleted_by, **kwargs):
 
    """
 
    Post delete repository Hook.
 

	
 
    :param repository: dict dump of repository object
 
    :param deleted_by: username who deleted the repository
 

	
 
    available keys of repository_dict:
 

	
 
     'repo_type',
 
     'description',
 
     'private',
 
     'created_on',
 
     'enable_downloads',
 
     'repo_id',
 
     'owner_id',
 
     'enable_statistics',
 
     'clone_uri',
 
     'fork_id',
 
     'group_id',
 
     'repo_name'
 

	
 
    """
 
    from kallithea import EXTENSIONS
 
    callback = getattr(EXTENSIONS, 'DELETE_REPO_HOOK', None)
 
    if callable(callback):
 
        kw = {}
 
        kw.update(repository_dict)
 
        kw.update({'deleted_by': deleted_by,
 
                   'deleted_on': time.time()})
 
        kw.update(kwargs)
 
        return callback(**kw)
 

	
 
    return 0
 

	
 

	
 
def log_delete_user(user_dict, deleted_by, **kwargs):
 
    """
 
    Post delete user Hook.
 

	
 
    :param user_dict: dict dump of user object
 

	
 
    available keys for user_dict:
 

	
 
     'username',
 
     'full_name_or_username',
 
     'full_contact',
 
     'user_id',
 
     'name',
 
     'firstname',
 
     'short_contact',
 
     'admin',
 
     'lastname',
 
     'ip_addresses',
 
     'ldap_dn',
 
     'email',
 
     'api_key',
 
     'last_login',
 
     'full_name',
 
     'active',
 
     'password',
 
     'emails',
 

	
 
    """
 
    from kallithea import EXTENSIONS
 
    callback = getattr(EXTENSIONS, 'DELETE_USER_HOOK', None)
 
    if callable(callback):
 
        return callback(deleted_by=deleted_by, **user_dict)
 

	
 
    return 0
 

	
 

	
 
def _hook_environment(repo_path):
 
def _git_hook_environment(repo_path):
 
    """
 
    Create a light-weight environment for stand-alone scripts and return an UI and the
 
    db repository.
 
@@ -306,40 +111,32 @@ def _hook_environment(repo_path):
 
    they thus need enough info to be able to create an app environment and
 
    connect to the database.
 
    """
 
    import paste.deploy
 
    import kallithea.config.middleware
 

	
 
    extras = get_hook_environment()
 

	
 
    path_to_ini_file = extras['config']
 
    kallithea.CONFIG = paste.deploy.appconfig('config:' + path_to_ini_file)
 
    config = paste.deploy.appconfig('config:' + path_to_ini_file)
 
    #logging.config.fileConfig(ini_file_path) # Note: we are in a different process - don't use configured logging
 
    kallithea.config.middleware.make_app(kallithea.CONFIG.global_conf, **kallithea.CONFIG.local_conf)
 
    kallithea.config.application.make_app(config.global_conf, **config.local_conf)
 

	
 
    # fix if it's not a bare repo
 
    if repo_path.endswith(os.sep + '.git'):
 
        repo_path = repo_path[:-5]
 

	
 
    repo = Repository.get_by_full_path(repo_path)
 
    repo = db.Repository.get_by_full_path(repo_path)
 
    if not repo:
 
        raise OSError('Repository %s not found in database' % repo_path)
 

	
 
    baseui = make_ui()
 
    return baseui, repo
 
    return repo
 

	
 

	
 
def handle_git_pre_receive(repo_path, git_stdin_lines):
 
    """Called from Git pre-receive hook"""
 
    # Currently unused. TODO: remove?
 
    return 0
 

	
 

	
 
def handle_git_post_receive(repo_path, git_stdin_lines):
 
    """Called from Git post-receive hook"""
 
def post_receive(repo_path, git_stdin_lines):
 
    """Called from Git post-receive hook.
 
    The returned value is used as hook exit code and must be 0.
 
    """
 
    try:
 
        baseui, repo = _hook_environment(repo_path)
 
        repo = _git_hook_environment(repo_path)
 
    except HookEnvironmentError as e:
 
        sys.stderr.write("Skipping Kallithea Git post-recieve hook %r.\nGit was apparently not invoked by Kallithea: %s\n" % (sys.argv[0], e))
 
        sys.stderr.write("Skipping Kallithea Git post-receive hook %r.\nGit was apparently not invoked by Kallithea: %s\n" % (sys.argv[0], e))
 
        return 0
 

	
 
    # the post push hook should never use the cached instance
 
@@ -391,14 +188,16 @@ def handle_git_post_receive(repo_path, g
 
        elif _type == 'tags':
 
            git_revs += ['tag=>%s' % push_ref['name']]
 

	
 
    process_pushed_raw_ids(git_revs)
 
    hooks.process_pushed_raw_ids(git_revs)
 

	
 
    return 0
 

	
 

	
 
# Almost exactly like Mercurial contrib/hg-ssh:
 
def rejectpush(ui, **kwargs):
 
    """Mercurial hook to be installed as pretxnopen and prepushkey for read-only repos"""
 
    """Mercurial hook to be installed as pretxnopen and prepushkey for read-only repos.
 
    Return value 1 will make the hook fail and reject the push.
 
    """
 
    ex = get_hook_environment()
 
    ui.warn(safe_bytes("Push access to %r denied\n" % ex.repository))
 
    return 1
kallithea/config/app_cfg.py
Show inline comments
 
@@ -28,82 +28,57 @@ import tg
 
from alembic.migration import MigrationContext
 
from alembic.script.base import ScriptDirectory
 
from sqlalchemy import create_engine
 
from tg.configuration import AppConfig
 
from tg.support.converters import asbool
 
from tg import FullStackApplicationConfigurator
 

	
 
import kallithea.lib.locale
 
import kallithea.lib.locales
 
import kallithea.model.base
 
import kallithea.model.meta
 
from kallithea.lib import celerypylons
 
from kallithea.lib.middleware.https_fixup import HttpsFixup
 
from kallithea.lib.middleware.permanent_repo_url import PermanentRepoUrl
 
from kallithea.lib.middleware.simplegit import SimpleGit
 
from kallithea.lib.middleware.simplehg import SimpleHg
 
from kallithea.lib.middleware.wrapper import RequestWrapper
 
from kallithea.lib.utils import check_git_version, load_rcextensions, set_app_settings, set_indexer_config, set_vcs_config
 
from kallithea.lib.utils2 import str2bool
 
from kallithea.lib import celery_app
 
from kallithea.lib.utils import load_extensions, set_app_settings, set_indexer_config, set_vcs_config
 
from kallithea.lib.utils2 import asbool, check_git_version
 
from kallithea.model import db
 

	
 

	
 
log = logging.getLogger(__name__)
 

	
 

	
 
class KallitheaAppConfig(AppConfig):
 
    # Note: AppConfig has a misleading name, as it's not the application
 
    # configuration, but the application configurator. The AppConfig values are
 
    # used as a template to create the actual configuration, which might
 
    # overwrite or extend the one provided by the configurator template.
 
base_config = FullStackApplicationConfigurator()
 

	
 
    # To make it clear, AppConfig creates the config and sets into it the same
 
    # values that AppConfig itself has. Then the values from the config file and
 
    # gearbox options are loaded and merged into the configuration. Then an
 
    # after_init_config(conf) method of AppConfig is called for any change that
 
    # might depend on options provided by configuration files.
 
base_config.update_blueprint({
 
    'package': kallithea,
 

	
 
    def __init__(self):
 
        super(KallitheaAppConfig, self).__init__()
 

	
 
        self['package'] = kallithea
 
    # Rendering Engines Configuration
 
    'renderers': [
 
        'json',
 
        'mako',
 
    ],
 
    'default_renderer': 'mako',
 
    'use_dotted_templatenames': False,
 

	
 
        self['prefer_toscawidgets2'] = False
 
        self['use_toscawidgets'] = False
 

	
 
        self['renderers'] = []
 

	
 
        # Enable json in expose
 
        self['renderers'].append('json')
 
    # Configure Sessions, store data as JSON to avoid pickle security issues
 
    'session.enabled': True,
 
    'session.data_serializer': 'json',
 

	
 
        # Configure template rendering
 
        self['renderers'].append('mako')
 
        self['default_renderer'] = 'mako'
 
        self['use_dotted_templatenames'] = False
 
    # Configure the base SQLALchemy Setup
 
    'use_sqlalchemy': True,
 
    'model': kallithea.model.base,
 
    'DBSession': kallithea.model.meta.Session,
 

	
 
        # Configure Sessions, store data as JSON to avoid pickle security issues
 
        self['session.enabled'] = True
 
        self['session.data_serializer'] = 'json'
 

	
 
        # Configure the base SQLALchemy Setup
 
        self['use_sqlalchemy'] = True
 
        self['model'] = kallithea.model.base
 
        self['DBSession'] = kallithea.model.meta.Session
 
    # Configure App without an authentication backend.
 
    'auth_backend': None,
 

	
 
        # Configure App without an authentication backend.
 
        self['auth_backend'] = None
 

	
 
        # Use custom error page for these errors. By default, Turbogears2 does not add
 
        # 400 in this list.
 
        # Explicitly listing all is considered more robust than appending to defaults,
 
        # in light of possible future framework changes.
 
        self['errorpage.status_codes'] = [400, 401, 403, 404]
 
    # Use custom error page for these errors. By default, Turbogears2 does not add
 
    # 400 in this list.
 
    # Explicitly listing all is considered more robust than appending to defaults,
 
    # in light of possible future framework changes.
 
    'errorpage.status_codes': [400, 401, 403, 404],
 

	
 
        # Disable transaction manager -- currently Kallithea takes care of transactions itself
 
        self['tm.enabled'] = False
 
    # Disable transaction manager -- currently Kallithea takes care of transactions itself
 
    'tm.enabled': False,
 

	
 
        # Set the default i18n source language so TG doesn't search beyond 'en' in Accept-Language.
 
        self['i18n.lang'] = 'en'
 

	
 

	
 
base_config = KallitheaAppConfig()
 
    # Set the default i18n source language so TG doesn't search beyond 'en' in Accept-Language.
 
    'i18n.lang': 'en',
 
})
 

	
 
# DebugBar, a debug toolbar for TurboGears2.
 
# (https://github.com/TurboGears/tgext.debugbar)
 
@@ -111,20 +86,20 @@ base_config = KallitheaAppConfig()
 
# 'debug = true' (not in production!)
 
# See the Kallithea documentation for more information.
 
try:
 
    import kajiki  # only to check its existence
 
    from tgext.debugbar import enable_debugbar
 
    import kajiki # only to check its existence
 
    assert kajiki
 
except ImportError:
 
    pass
 
else:
 
    base_config['renderers'].append('kajiki')
 
    base_config.get_blueprint_value('renderers').append('kajiki')
 
    enable_debugbar(base_config)
 

	
 

	
 
def setup_configuration(app):
 
    config = app.config
 

	
 
    if not kallithea.lib.locale.current_locale_is_valid():
 
    if not kallithea.lib.locales.current_locale_is_valid():
 
        log.error("Terminating ...")
 
        sys.exit(1)
 

	
 
@@ -134,7 +109,7 @@ def setup_configuration(app):
 
        mercurial.encoding.encoding = hgencoding
 

	
 
    if config.get('ignore_alembic_revision', False):
 
        log.warn('database alembic revision checking is disabled')
 
        log.warning('database alembic revision checking is disabled')
 
    else:
 
        dbconf = config['sqlalchemy.url']
 
        alembic_cfg = alembic.config.Config()
 
@@ -160,11 +135,11 @@ def setup_configuration(app):
 
    # store some globals into kallithea
 
    kallithea.DEFAULT_USER_ID = db.User.get_default_user().user_id
 

	
 
    if str2bool(config.get('use_celery')):
 
        kallithea.CELERY_APP = celerypylons.make_app()
 
    if asbool(config.get('use_celery')) and not kallithea.CELERY_APP.finalized:
 
        kallithea.CELERY_APP.config_from_object(celery_app.make_celery_config(config))
 
    kallithea.CONFIG = config
 

	
 
    load_rcextensions(root_path=config['here'])
 
    load_extensions(root_path=config['here'])
 

	
 
    set_app_settings(config)
 

	
 
@@ -188,27 +163,3 @@ def setup_configuration(app):
 

	
 

	
 
tg.hooks.register('configure_new_app', setup_configuration)
 

	
 

	
 
def setup_application(app):
 
    config = app.config
 

	
 
    # we want our low level middleware to get to the request ASAP. We don't
 
    # need any stack middleware in them - especially no StatusCodeRedirect buffering
 
    app = SimpleHg(app, config)
 
    app = SimpleGit(app, config)
 

	
 
    # Enable https redirects based on HTTP_X_URL_SCHEME set by proxy
 
    if any(asbool(config.get(x)) for x in ['https_fixup', 'force_https', 'use_htsts']):
 
        app = HttpsFixup(app, config)
 

	
 
    app = PermanentRepoUrl(app, config)
 

	
 
    # Optional and undocumented wrapper - gives more verbose request/response logging, but has a slight overhead
 
    if str2bool(config.get('use_wsgi_wrapper')):
 
        app = RequestWrapper(app, config)
 

	
 
    return app
 

	
 

	
 
tg.hooks.register('before_config', setup_application)
kallithea/config/application.py
Show inline comments
 
file renamed from kallithea/config/middleware.py to kallithea/config/application.py
 
@@ -14,26 +14,46 @@
 
"""WSGI middleware initialization for the Kallithea application."""
 

	
 
from kallithea.config.app_cfg import base_config
 
from kallithea.config.environment import load_environment
 
from kallithea.config.middleware.https_fixup import HttpsFixup
 
from kallithea.config.middleware.permanent_repo_url import PermanentRepoUrl
 
from kallithea.config.middleware.simplegit import SimpleGit
 
from kallithea.config.middleware.simplehg import SimpleHg
 
from kallithea.config.middleware.wrapper import RequestWrapper
 
from kallithea.lib.utils2 import asbool
 

	
 

	
 
__all__ = ['make_app']
 

	
 
# Use base_config to setup the necessary PasteDeploy application factory.
 
# make_base_app will wrap the TurboGears2 app with all the middleware it needs.
 
make_base_app = base_config.setup_tg_wsgi_app(load_environment)
 

	
 
def wrap_app(app):
 
    """Wrap the TG WSGI application in Kallithea middleware"""
 
    config = app.config
 

	
 
    # we want our low level middleware to get to the request ASAP. We don't
 
    # need any stack middleware in them - especially no StatusCodeRedirect buffering
 
    app = SimpleHg(app, config)
 
    app = SimpleGit(app, config)
 

	
 
    # Enable https redirects based on HTTP_X_URL_SCHEME set by proxy
 
    if any(asbool(config.get(x)) for x in ['url_scheme_variable', 'force_https', 'use_htsts']):
 
        app = HttpsFixup(app, config)
 

	
 
    app = PermanentRepoUrl(app, config)
 

	
 
    # Optional and undocumented wrapper - gives more verbose request/response logging, but has a slight overhead
 
    if asbool(config.get('use_wsgi_wrapper')):
 
        app = RequestWrapper(app, config)
 

	
 
    return app
 

	
 

	
 
def make_app(global_conf, full_stack=True, **app_conf):
 
def make_app(global_conf, **app_conf):
 
    """
 
    Set up Kallithea with the settings found in the PasteDeploy configuration
 
    file used.
 

	
 
    :param global_conf: The global settings for Kallithea (those
 
        defined under the ``[DEFAULT]`` section).
 
    :type global_conf: dict
 
    :param full_stack: Should the whole TurboGears2 stack be set up?
 
    :type full_stack: str or bool
 
    :return: The Kallithea application with all the relevant middleware
 
        loaded.
 

	
 
@@ -44,4 +64,5 @@ def make_app(global_conf, full_stack=Tru
 
    """
 
    assert app_conf.get('sqlalchemy.url')  # must be called with a Kallithea .ini file, which for example must have this config option
 
    assert global_conf.get('here') and global_conf.get('__file__')  # app config should be initialized the paste way ...
 
    return make_base_app(global_conf, full_stack=full_stack, **app_conf)
 

	
 
    return base_config.make_wsgi_app(global_conf, app_conf, wrap_app=wrap_app)
kallithea/config/environment.py
Show inline comments
 
deleted file
kallithea/config/middleware/__init__.py
Show inline comments
 
file renamed from kallithea/lib/middleware/__init__.py to kallithea/config/middleware/__init__.py
kallithea/config/middleware/https_fixup.py
Show inline comments
 
file renamed from kallithea/lib/middleware/https_fixup.py to kallithea/config/middleware/https_fixup.py
 
@@ -12,8 +12,8 @@
 
# You should have received a copy of the GNU General Public License
 
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
 
"""
 
kallithea.lib.middleware.https_fixup
 
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
 
kallithea.config.middleware.https_fixup
 
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
 

	
 
middleware to handle https correctly
 

	
 
@@ -26,7 +26,8 @@ Original author and date, and relevant c
 
"""
 

	
 

	
 
from kallithea.lib.utils2 import str2bool
 
import kallithea
 
from kallithea.lib.utils2 import asbool
 

	
 

	
 
class HttpsFixup(object):
 
@@ -37,11 +38,11 @@ class HttpsFixup(object):
 

	
 
    def __call__(self, environ, start_response):
 
        self.__fixup(environ)
 
        debug = str2bool(self.config.get('debug'))
 
        debug = asbool(self.config.get('debug'))
 
        is_ssl = environ['wsgi.url_scheme'] == 'https'
 

	
 
        def custom_start_response(status, headers, exc_info=None):
 
            if is_ssl and str2bool(self.config.get('use_htsts')) and not debug:
 
            if is_ssl and asbool(self.config.get('use_htsts')) and not debug:
 
                headers.append(('Strict-Transport-Security',
 
                                'max-age=8640000; includeSubDomains'))
 
            return start_response(status, headers, exc_info)
 
@@ -54,20 +55,17 @@ class HttpsFixup(object):
 
        middleware you should set this header inside your
 
        proxy ie. nginx, apache etc.
 
        """
 
        # DETECT PROTOCOL !
 
        if 'HTTP_X_URL_SCHEME' in environ:
 
            proto = environ.get('HTTP_X_URL_SCHEME')
 
        elif 'HTTP_X_FORWARDED_SCHEME' in environ:
 
            proto = environ.get('HTTP_X_FORWARDED_SCHEME')
 
        elif 'HTTP_X_FORWARDED_PROTO' in environ:
 
            proto = environ.get('HTTP_X_FORWARDED_PROTO')
 
        else:
 
            proto = 'http'
 
        org_proto = proto
 
        proto = None
 

	
 
        # if we have force, just override
 
        if str2bool(self.config.get('force_https')):
 
        if asbool(self.config.get('force_https')):
 
            proto = 'https'
 
        else:
 
            # get protocol from configured WSGI environment variable
 
            url_scheme_variable = kallithea.CONFIG.get('url_scheme_variable')
 
            if url_scheme_variable:
 
                proto = environ.get(url_scheme_variable)
 

	
 
        environ['wsgi.url_scheme'] = proto
 
        environ['wsgi._org_proto'] = org_proto
 
        if proto:
 
            environ['wsgi._org_proto'] = environ.get('wsgi.url_scheme')
 
            environ['wsgi.url_scheme'] = proto
kallithea/config/middleware/permanent_repo_url.py
Show inline comments
 
file renamed from kallithea/lib/middleware/permanent_repo_url.py to kallithea/config/middleware/permanent_repo_url.py
 
@@ -12,8 +12,8 @@
 
# You should have received a copy of the GNU General Public License
 
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
 
"""
 
kallithea.lib.middleware.permanent_repo_url
 
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
 
kallithea.config.middleware.permanent_repo_url
 
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
 

	
 
middleware to handle permanent repo URLs, replacing PATH_INFO '/_123/yada' with
 
'/name/of/repo/yada' after looking 123 up in the database.
kallithea/config/middleware/pygrack.py
Show inline comments
 
file renamed from kallithea/lib/middleware/pygrack.py to kallithea/config/middleware/pygrack.py
 
@@ -12,8 +12,8 @@
 
# You should have received a copy of the GNU General Public License
 
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
 
"""
 
kallithea.lib.middleware.pygrack
 
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
 
kallithea.config.middleware.pygrack
 
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
 

	
 
Python implementation of git-http-backend's Smart HTTP protocol
 

	
 
@@ -30,11 +30,13 @@ import os
 
import socket
 
import traceback
 

	
 
from dulwich.server import update_server_info
 
from dulwich.web import GunzipFilter, LimitedInputFilter
 
from webob import Request, Response, exc
 

	
 
import kallithea
 
from kallithea.lib.utils2 import ascii_bytes
 
from kallithea.lib.vcs import subprocessio
 
from kallithea.lib.vcs import get_repo, subprocessio
 

	
 

	
 
log = logging.getLogger(__name__)
 
@@ -168,8 +170,6 @@ class GitRepository(object):
 
        if git_command in ['git-receive-pack']:
 
            # updating refs manually after each push.
 
            # Needed for pre-1.7.0.4 git clients using regular HTTP mode.
 
            from kallithea.lib.vcs import get_repo
 
            from dulwich.server import update_server_info
 
            repo = get_repo(self.content_path)
 
            if repo:
 
                update_server_info(repo._repo)
 
@@ -223,6 +223,5 @@ class GitDirectory(object):
 

	
 

	
 
def make_wsgi_app(repo_name, repo_root):
 
    from dulwich.web import LimitedInputFilter, GunzipFilter
 
    app = GitDirectory(repo_root, repo_name)
 
    return GunzipFilter(LimitedInputFilter(app))
kallithea/config/middleware/simplegit.py
Show inline comments
 
file renamed from kallithea/lib/middleware/simplegit.py to kallithea/config/middleware/simplegit.py
 
@@ -12,8 +12,8 @@
 
# You should have received a copy of the GNU General Public License
 
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
 
"""
 
kallithea.lib.middleware.simplegit
 
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
 
kallithea.config.middleware.simplegit
 
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
 

	
 
SimpleGit middleware for handling Git protocol requests (push/clone etc.)
 
It's implemented with basic auth function
 
@@ -31,11 +31,9 @@ Original author and date, and relevant c
 
import logging
 
import re
 

	
 
from kallithea.lib.base import BaseVCSController, get_path_info
 
from kallithea.lib.hooks import log_pull_action
 
from kallithea.lib.middleware.pygrack import make_wsgi_app
 
from kallithea.lib.utils import make_ui
 
from kallithea.model.db import Repository
 
from kallithea.config.middleware.pygrack import make_wsgi_app
 
from kallithea.controllers import base
 
from kallithea.lib import hooks
 

	
 

	
 
log = logging.getLogger(__name__)
 
@@ -50,13 +48,13 @@ cmd_mapping = {
 
}
 

	
 

	
 
class SimpleGit(BaseVCSController):
 
class SimpleGit(base.BaseVCSController):
 

	
 
    scm_alias = 'git'
 

	
 
    @classmethod
 
    def parse_request(cls, environ):
 
        path_info = get_path_info(environ)
 
        path_info = base.get_path_info(environ)
 
        m = GIT_PROTO_PAT.match(path_info)
 
        if m is None:
 
            return None
 
@@ -86,11 +84,8 @@ class SimpleGit(BaseVCSController):
 
            if (parsed_request.cmd == 'info/refs' and
 
                parsed_request.service == 'git-upload-pack'
 
            ):
 
                baseui = make_ui()
 
                repo = Repository.get_by_repo_name(parsed_request.repo_name)
 
                scm_repo = repo.scm_instance
 
                # Run hooks, like Mercurial outgoing.pull_logger does
 
                log_pull_action(ui=baseui, repo=scm_repo._repo)
 
                # Run hooks like Mercurial outgoing.kallithea_pull_action does
 
                hooks.log_pull_action()
 
            # Note: push hooks are handled by post-receive hook
 

	
 
            return pygrack_app(environ, start_response)
kallithea/config/middleware/simplehg.py
Show inline comments
 
file renamed from kallithea/lib/middleware/simplehg.py to kallithea/config/middleware/simplehg.py
 
@@ -12,8 +12,8 @@
 
# You should have received a copy of the GNU General Public License
 
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
 
"""
 
kallithea.lib.middleware.simplehg
 
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
 
kallithea.config.middleware.simplehg
 
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
 

	
 
SimpleHg middleware for handling Mercurial protocol requests (push/clone etc.).
 
It's implemented with basic auth function
 
@@ -34,7 +34,7 @@ import urllib.parse
 

	
 
import mercurial.hgweb
 

	
 
from kallithea.lib.base import BaseVCSController, get_path_info
 
from kallithea.controllers import base
 
from kallithea.lib.utils import make_ui
 
from kallithea.lib.utils2 import safe_bytes
 

	
 
@@ -91,7 +91,7 @@ cmd_mapping = {
 
    }
 

	
 

	
 
class SimpleHg(BaseVCSController):
 
class SimpleHg(base.BaseVCSController):
 

	
 
    scm_alias = 'hg'
 

	
 
@@ -100,7 +100,7 @@ class SimpleHg(BaseVCSController):
 
        http_accept = environ.get('HTTP_ACCEPT', '')
 
        if not http_accept.startswith('application/mercurial'):
 
            return None
 
        path_info = get_path_info(environ)
 
        path_info = base.get_path_info(environ)
 
        if not path_info.startswith('/'): # it must!
 
            return None
 

	
kallithea/config/middleware/wrapper.py
Show inline comments
 
file renamed from kallithea/lib/middleware/wrapper.py to kallithea/config/middleware/wrapper.py
 
@@ -12,8 +12,8 @@
 
# You should have received a copy of the GNU General Public License
 
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
 
"""
 
kallithea.lib.middleware.wrapper
 
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
 
kallithea.config.middleware.wrapper
 
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
 

	
 
Wrap app to measure request and response time ... all the way to the response
 
WSGI iterator has been closed.
 
@@ -29,7 +29,7 @@ Original author and date, and relevant c
 
import logging
 
import time
 

	
 
from kallithea.lib.base import _get_ip_addr, get_path_info
 
from kallithea.controllers import base
 

	
 

	
 
log = logging.getLogger(__name__)
 
@@ -91,8 +91,8 @@ class RequestWrapper(object):
 
    def __call__(self, environ, start_response):
 
        meter = Meter(start_response)
 
        description = "Request from %s for %s" % (
 
            _get_ip_addr(environ),
 
            get_path_info(environ),
 
            base.get_ip_addr(environ),
 
            base.get_path_info(environ),
 
        )
 
        log.info("%s received", description)
 
        try:
kallithea/config/pre_receive_tmpl.py
Show inline comments
 
deleted file
kallithea/controllers/admin/admin.py
Show inline comments
 
@@ -36,12 +36,12 @@ from whoosh import query
 
from whoosh.qparser.dateparse import DateParserPlugin
 
from whoosh.qparser.default import QueryParser
 

	
 
from kallithea.controllers import base
 
from kallithea.lib.auth import HasPermissionAnyDecorator, LoginRequired
 
from kallithea.lib.base import BaseController, render
 
from kallithea.lib.indexers import JOURNAL_SCHEMA
 
from kallithea.lib.page import Page
 
from kallithea.lib.utils2 import remove_prefix, remove_suffix, safe_int
 
from kallithea.model.db import UserLog
 
from kallithea.model import db
 

	
 

	
 
log = logging.getLogger(__name__)
 
@@ -77,15 +77,15 @@ def _journal_filter(user_log, search_ter
 
    def get_filterion(field, val, term):
 

	
 
        if field == 'repository':
 
            field = getattr(UserLog, 'repository_name')
 
            field = getattr(db.UserLog, 'repository_name')
 
        elif field == 'ip':
 
            field = getattr(UserLog, 'user_ip')
 
            field = getattr(db.UserLog, 'user_ip')
 
        elif field == 'date':
 
            field = getattr(UserLog, 'action_date')
 
            field = getattr(db.UserLog, 'action_date')
 
        elif field == 'username':
 
            field = getattr(UserLog, 'username')
 
            field = getattr(db.UserLog, 'username')
 
        else:
 
            field = getattr(UserLog, field)
 
            field = getattr(db.UserLog, field)
 
        log.debug('filter field: %s val=>%s', field, val)
 

	
 
        # sql filtering
 
@@ -102,6 +102,7 @@ def _journal_filter(user_log, search_ter
 
        if not isinstance(qry, query.And):
 
            qry = [qry]
 
        for term in qry:
 
            assert term is not None, term
 
            field = term.fieldname
 
            val = (term.text if not isinstance(term, query.DateRange)
 
                   else [term.startdate, term.enddate])
 
@@ -118,7 +119,7 @@ def _journal_filter(user_log, search_ter
 
    return user_log
 

	
 

	
 
class AdminController(BaseController):
 
class AdminController(base.BaseController):
 

	
 
    @LoginRequired(allow_default_user=True)
 
    def _before(self, *args, **kwargs):
 
@@ -126,15 +127,15 @@ class AdminController(BaseController):
 

	
 
    @HasPermissionAnyDecorator('hg.admin')
 
    def index(self):
 
        users_log = UserLog.query() \
 
                .options(joinedload(UserLog.user)) \
 
                .options(joinedload(UserLog.repository))
 
        users_log = db.UserLog.query() \
 
                .options(joinedload(db.UserLog.user)) \
 
                .options(joinedload(db.UserLog.repository))
 

	
 
        # FILTERING
 
        c.search_term = request.GET.get('filter')
 
        users_log = _journal_filter(users_log, c.search_term)
 

	
 
        users_log = users_log.order_by(UserLog.action_date.desc())
 
        users_log = users_log.order_by(db.UserLog.action_date.desc())
 

	
 
        p = safe_int(request.GET.get('page'), 1)
 

	
 
@@ -142,6 +143,6 @@ class AdminController(BaseController):
 
                           filter=c.search_term)
 

	
 
        if request.environ.get('HTTP_X_PARTIAL_XHR'):
 
            return render('admin/admin_log.html')
 
            return base.render('admin/admin_log.html')
 

	
 
        return render('admin/admin.html')
 
        return base.render('admin/admin.html')
kallithea/controllers/admin/auth_settings.py
Show inline comments
 
@@ -32,20 +32,18 @@ from tg import tmpl_context as c
 
from tg.i18n import ugettext as _
 
from webob.exc import HTTPFound
 

	
 
from kallithea.config.routing import url
 
from kallithea.lib import auth_modules
 
from kallithea.lib import helpers as h
 
from kallithea.controllers import base
 
from kallithea.lib import auth_modules, webutils
 
from kallithea.lib.auth import HasPermissionAnyDecorator, LoginRequired
 
from kallithea.lib.base import BaseController, render
 
from kallithea.model.db import Setting
 
from kallithea.lib.webutils import url
 
from kallithea.model import db, meta
 
from kallithea.model.forms import AuthSettingsForm
 
from kallithea.model.meta import Session
 

	
 

	
 
log = logging.getLogger(__name__)
 

	
 

	
 
class AuthSettingsController(BaseController):
 
class AuthSettingsController(base.BaseController):
 

	
 
    @LoginRequired()
 
    @HasPermissionAnyDecorator('hg.admin')
 
@@ -77,7 +75,7 @@ class AuthSettingsController(BaseControl
 
                if "default" in v:
 
                    c.defaults[fullname] = v["default"]
 
                # Current values will be the default on the form, if there are any
 
                setting = Setting.get_by_name(fullname)
 
                setting = db.Setting.get_by_name(fullname)
 
                if setting is not None:
 
                    c.defaults[fullname] = setting.app_settings_value
 
        if defaults:
 
@@ -88,7 +86,7 @@ class AuthSettingsController(BaseControl
 

	
 
        log.debug('defaults: %s', defaults)
 
        return formencode.htmlfill.render(
 
            render('admin/auth/auth_settings.html'),
 
            base.render('admin/auth/auth_settings.html'),
 
            defaults=c.defaults,
 
            errors=errors,
 
            prefix_error=False,
 
@@ -131,9 +129,9 @@ class AuthSettingsController(BaseControl
 
                    # we want to store it comma separated inside our settings
 
                    v = ','.join(v)
 
                log.debug("%s = %s", k, str(v))
 
                setting = Setting.create_or_update(k, v)
 
            Session().commit()
 
            h.flash(_('Auth settings updated successfully'),
 
                setting = db.Setting.create_or_update(k, v)
 
            meta.Session().commit()
 
            webutils.flash(_('Auth settings updated successfully'),
 
                       category='success')
 
        except formencode.Invalid as errors:
 
            log.error(traceback.format_exc())
 
@@ -144,7 +142,7 @@ class AuthSettingsController(BaseControl
 
            )
 
        except Exception:
 
            log.error(traceback.format_exc())
 
            h.flash(_('error occurred during update of auth settings'),
 
            webutils.flash(_('error occurred during update of auth settings'),
 
                    category='error')
 

	
 
        raise HTTPFound(location=url('auth_home'))
kallithea/controllers/admin/defaults.py
Show inline comments
 
@@ -34,19 +34,18 @@ from tg import request
 
from tg.i18n import ugettext as _
 
from webob.exc import HTTPFound
 

	
 
from kallithea.config.routing import url
 
from kallithea.lib import helpers as h
 
from kallithea.controllers import base
 
from kallithea.lib import webutils
 
from kallithea.lib.auth import HasPermissionAnyDecorator, LoginRequired
 
from kallithea.lib.base import BaseController, render
 
from kallithea.model.db import Setting
 
from kallithea.lib.webutils import url
 
from kallithea.model import db, meta
 
from kallithea.model.forms import DefaultsForm
 
from kallithea.model.meta import Session
 

	
 

	
 
log = logging.getLogger(__name__)
 

	
 

	
 
class DefaultsController(BaseController):
 
class DefaultsController(base.BaseController):
 

	
 
    @LoginRequired()
 
    @HasPermissionAnyDecorator('hg.admin')
 
@@ -54,10 +53,10 @@ class DefaultsController(BaseController)
 
        super(DefaultsController, self)._before(*args, **kwargs)
 

	
 
    def index(self, format='html'):
 
        defaults = Setting.get_default_repo_settings()
 
        defaults = db.Setting.get_default_repo_settings()
 

	
 
        return htmlfill.render(
 
            render('admin/defaults/defaults.html'),
 
            base.render('admin/defaults/defaults.html'),
 
            defaults=defaults,
 
            encoding="UTF-8",
 
            force_defaults=False
 
@@ -69,16 +68,16 @@ class DefaultsController(BaseController)
 
        try:
 
            form_result = _form.to_python(dict(request.POST))
 
            for k, v in form_result.items():
 
                setting = Setting.create_or_update(k, v)
 
            Session().commit()
 
            h.flash(_('Default settings updated successfully'),
 
                setting = db.Setting.create_or_update(k, v)
 
            meta.Session().commit()
 
            webutils.flash(_('Default settings updated successfully'),
 
                    category='success')
 

	
 
        except formencode.Invalid as errors:
 
            defaults = errors.value
 

	
 
            return htmlfill.render(
 
                render('admin/defaults/defaults.html'),
 
                base.render('admin/defaults/defaults.html'),
 
                defaults=defaults,
 
                errors=errors.error_dict or {},
 
                prefix_error=False,
 
@@ -86,7 +85,7 @@ class DefaultsController(BaseController)
 
                force_defaults=False)
 
        except Exception:
 
            log.error(traceback.format_exc())
 
            h.flash(_('Error occurred during update of defaults'),
 
            webutils.flash(_('Error occurred during update of defaults'),
 
                    category='error')
 

	
 
        raise HTTPFound(location=url('defaults'))
kallithea/controllers/admin/gists.py
Show inline comments
 
@@ -35,24 +35,22 @@ from tg import tmpl_context as c
 
from tg.i18n import ugettext as _
 
from webob.exc import HTTPForbidden, HTTPFound, HTTPNotFound
 

	
 
from kallithea.config.routing import url
 
from kallithea.lib import helpers as h
 
from kallithea.controllers import base
 
from kallithea.lib import auth, webutils
 
from kallithea.lib.auth import LoginRequired
 
from kallithea.lib.base import BaseController, jsonify, render
 
from kallithea.lib.page import Page
 
from kallithea.lib.utils2 import safe_int, safe_str, time_to_datetime
 
from kallithea.lib.vcs.exceptions import NodeNotChangedError, VCSError
 
from kallithea.model.db import Gist
 
from kallithea.lib.webutils import url
 
from kallithea.model import db, meta
 
from kallithea.model.forms import GistForm
 
from kallithea.model.gist import GistModel
 
from kallithea.model.meta import Session
 

	
 

	
 
log = logging.getLogger(__name__)
 

	
 

	
 
class GistsController(BaseController):
 
    """REST Controller styled on the Atom Publishing Protocol"""
 
class GistsController(base.BaseController):
 

	
 
    def __load_defaults(self, extra_values=None):
 
        c.lifetime_values = [
 
@@ -77,34 +75,34 @@ class GistsController(BaseController):
 
        elif c.show_private:
 
            url_params['private'] = 1
 

	
 
        gists = Gist().query() \
 
        gists = db.Gist().query() \
 
            .filter_by(is_expired=False) \
 
            .order_by(Gist.created_on.desc())
 
            .order_by(db.Gist.created_on.desc())
 

	
 
        # MY private
 
        if c.show_private and not c.show_public:
 
            gists = gists.filter(Gist.gist_type == Gist.GIST_PRIVATE) \
 
                             .filter(Gist.owner_id == request.authuser.user_id)
 
            gists = gists.filter(db.Gist.gist_type == db.Gist.GIST_PRIVATE) \
 
                             .filter(db.Gist.owner_id == request.authuser.user_id)
 
        # MY public
 
        elif c.show_public and not c.show_private:
 
            gists = gists.filter(Gist.gist_type == Gist.GIST_PUBLIC) \
 
                             .filter(Gist.owner_id == request.authuser.user_id)
 
            gists = gists.filter(db.Gist.gist_type == db.Gist.GIST_PUBLIC) \
 
                             .filter(db.Gist.owner_id == request.authuser.user_id)
 

	
 
        # MY public+private
 
        elif c.show_private and c.show_public:
 
            gists = gists.filter(or_(Gist.gist_type == Gist.GIST_PUBLIC,
 
                                     Gist.gist_type == Gist.GIST_PRIVATE)) \
 
                             .filter(Gist.owner_id == request.authuser.user_id)
 
            gists = gists.filter(or_(db.Gist.gist_type == db.Gist.GIST_PUBLIC,
 
                                     db.Gist.gist_type == db.Gist.GIST_PRIVATE)) \
 
                             .filter(db.Gist.owner_id == request.authuser.user_id)
 

	
 
        # default show ALL public gists
 
        if not c.show_public and not c.show_private:
 
            gists = gists.filter(Gist.gist_type == Gist.GIST_PUBLIC)
 
            gists = gists.filter(db.Gist.gist_type == db.Gist.GIST_PUBLIC)
 

	
 
        c.gists = gists
 
        p = safe_int(request.GET.get('page'), 1)
 
        c.gists_pager = Page(c.gists, page=p, items_per_page=10,
 
                             **url_params)
 
        return render('admin/gists/index.html')
 
        return base.render('admin/gists/index.html')
 

	
 
    @LoginRequired()
 
    def create(self):
 
@@ -113,7 +111,7 @@ class GistsController(BaseController):
 
        try:
 
            form_result = gist_form.to_python(dict(request.POST))
 
            # TODO: multiple files support, from the form
 
            filename = form_result['filename'] or Gist.DEFAULT_FILENAME
 
            filename = form_result['filename'] or db.Gist.DEFAULT_FILENAME
 
            nodes = {
 
                filename: {
 
                    'content': form_result['content'],
 
@@ -121,7 +119,7 @@ class GistsController(BaseController):
 
                }
 
            }
 
            _public = form_result['public']
 
            gist_type = Gist.GIST_PUBLIC if _public else Gist.GIST_PRIVATE
 
            gist_type = db.Gist.GIST_PUBLIC if _public else db.Gist.GIST_PRIVATE
 
            gist = GistModel().create(
 
                description=form_result['description'],
 
                owner=request.authuser.user_id,
 
@@ -130,13 +128,13 @@ class GistsController(BaseController):
 
                gist_type=gist_type,
 
                lifetime=form_result['lifetime']
 
            )
 
            Session().commit()
 
            meta.Session().commit()
 
            new_gist_id = gist.gist_access_id
 
        except formencode.Invalid as errors:
 
            defaults = errors.value
 

	
 
            return formencode.htmlfill.render(
 
                render('admin/gists/new.html'),
 
                base.render('admin/gists/new.html'),
 
                defaults=defaults,
 
                errors=errors.error_dict or {},
 
                prefix_error=False,
 
@@ -145,23 +143,23 @@ class GistsController(BaseController):
 

	
 
        except Exception as e:
 
            log.error(traceback.format_exc())
 
            h.flash(_('Error occurred during gist creation'), category='error')
 
            webutils.flash(_('Error occurred during gist creation'), category='error')
 
            raise HTTPFound(location=url('new_gist'))
 
        raise HTTPFound(location=url('gist', gist_id=new_gist_id))
 

	
 
    @LoginRequired()
 
    def new(self, format='html'):
 
        self.__load_defaults()
 
        return render('admin/gists/new.html')
 
        return base.render('admin/gists/new.html')
 

	
 
    @LoginRequired()
 
    def delete(self, gist_id):
 
        gist = GistModel().get_gist(gist_id)
 
        owner = gist.owner_id == request.authuser.user_id
 
        if h.HasPermissionAny('hg.admin')() or owner:
 
        if auth.HasPermissionAny('hg.admin')() or owner:
 
            GistModel().delete(gist)
 
            Session().commit()
 
            h.flash(_('Deleted gist %s') % gist.gist_access_id, category='success')
 
            meta.Session().commit()
 
            webutils.flash(_('Deleted gist %s') % gist.gist_access_id, category='success')
 
        else:
 
            raise HTTPForbidden()
 

	
 
@@ -169,7 +167,7 @@ class GistsController(BaseController):
 

	
 
    @LoginRequired(allow_default_user=True)
 
    def show(self, gist_id, revision='tip', format='html', f_path=None):
 
        c.gist = Gist.get_or_404(gist_id)
 
        c.gist = db.Gist.get_or_404(gist_id)
 

	
 
        if c.gist.is_expired:
 
            log.error('Gist expired at %s',
 
@@ -188,11 +186,11 @@ class GistsController(BaseController):
 
            )
 
            response.content_type = 'text/plain'
 
            return content
 
        return render('admin/gists/show.html')
 
        return base.render('admin/gists/show.html')
 

	
 
    @LoginRequired()
 
    def edit(self, gist_id, format='html'):
 
        c.gist = Gist.get_or_404(gist_id)
 
        c.gist = db.Gist.get_or_404(gist_id)
 

	
 
        if c.gist.is_expired:
 
            log.error('Gist expired at %s',
 
@@ -205,7 +203,7 @@ class GistsController(BaseController):
 
            raise HTTPNotFound()
 

	
 
        self.__load_defaults(extra_values=('0', _('Unmodified')))
 
        rendered = render('admin/gists/edit.html')
 
        rendered = base.render('admin/gists/edit.html')
 

	
 
        if request.POST:
 
            rpost = request.POST
 
@@ -233,16 +231,16 @@ class GistsController(BaseController):
 
                    lifetime=rpost['lifetime']
 
                )
 

	
 
                Session().commit()
 
                h.flash(_('Successfully updated gist content'), category='success')
 
                meta.Session().commit()
 
                webutils.flash(_('Successfully updated gist content'), category='success')
 
            except NodeNotChangedError:
 
                # raised if nothing was changed in repo itself. We anyway then
 
                # store only DB stuff for gist
 
                Session().commit()
 
                h.flash(_('Successfully updated gist data'), category='success')
 
                meta.Session().commit()
 
                webutils.flash(_('Successfully updated gist data'), category='success')
 
            except Exception:
 
                log.error(traceback.format_exc())
 
                h.flash(_('Error occurred during update of gist %s') % gist_id,
 
                webutils.flash(_('Error occurred during update of gist %s') % gist_id,
 
                        category='error')
 

	
 
            raise HTTPFound(location=url('gist', gist_id=gist_id))
 
@@ -250,9 +248,9 @@ class GistsController(BaseController):
 
        return rendered
 

	
 
    @LoginRequired()
 
    @jsonify
 
    @base.jsonify
 
    def check_revision(self, gist_id):
 
        c.gist = Gist.get_or_404(gist_id)
 
        c.gist = db.Gist.get_or_404(gist_id)
 
        last_rev = c.gist.scm_instance.get_changeset()
 
        success = True
 
        revision = request.POST.get('revision')
kallithea/controllers/admin/my_account.py
Show inline comments
 
@@ -35,16 +35,14 @@ from tg import tmpl_context as c
 
from tg.i18n import ugettext as _
 
from webob.exc import HTTPFound
 

	
 
from kallithea.config.routing import url
 
from kallithea.lib import auth_modules
 
from kallithea.lib import helpers as h
 
from kallithea.controllers import base
 
from kallithea.lib import auth_modules, webutils
 
from kallithea.lib.auth import AuthUser, LoginRequired
 
from kallithea.lib.base import BaseController, IfSshEnabled, render
 
from kallithea.lib.utils2 import generate_api_key, safe_int
 
from kallithea.lib.webutils import url
 
from kallithea.model import db, meta
 
from kallithea.model.api_key import ApiKeyModel
 
from kallithea.model.db import Repository, User, UserEmailMap, UserFollowing
 
from kallithea.model.forms import PasswordChangeForm, UserForm
 
from kallithea.model.meta import Session
 
from kallithea.model.repo import RepoModel
 
from kallithea.model.ssh_key import SshKeyModel, SshKeyModelException
 
from kallithea.model.user import UserModel
 
@@ -53,35 +51,30 @@ from kallithea.model.user import UserMod
 
log = logging.getLogger(__name__)
 

	
 

	
 
class MyAccountController(BaseController):
 
    """REST Controller styled on the Atom Publishing Protocol"""
 
    # To properly map this controller, ensure your config/routing.py
 
    # file has a resource setup:
 
    #     map.resource('setting', 'settings', controller='admin/settings',
 
    #         path_prefix='/admin', name_prefix='admin_')
 
class MyAccountController(base.BaseController):
 

	
 
    @LoginRequired()
 
    def _before(self, *args, **kwargs):
 
        super(MyAccountController, self)._before(*args, **kwargs)
 

	
 
    def __load_data(self):
 
        c.user = User.get(request.authuser.user_id)
 
        c.user = db.User.get(request.authuser.user_id)
 
        if c.user.is_default_user:
 
            h.flash(_("You can't edit this user since it's"
 
            webutils.flash(_("You can't edit this user since it's"
 
                      " crucial for entire application"), category='warning')
 
            raise HTTPFound(location=url('users'))
 

	
 
    def _load_my_repos_data(self, watched=False):
 
        if watched:
 
            admin = False
 
            repos_list = Session().query(Repository) \
 
                         .join(UserFollowing) \
 
                         .filter(UserFollowing.user_id ==
 
            repos_list = meta.Session().query(db.Repository) \
 
                         .join(db.UserFollowing) \
 
                         .filter(db.UserFollowing.user_id ==
 
                                 request.authuser.user_id).all()
 
        else:
 
            admin = True
 
            repos_list = Session().query(Repository) \
 
                         .filter(Repository.owner_id ==
 
            repos_list = meta.Session().query(db.Repository) \
 
                         .filter(db.Repository.owner_id ==
 
                                 request.authuser.user_id).all()
 

	
 
        return RepoModel().get_repos_as_dict(repos_list, admin=admin)
 
@@ -91,7 +84,7 @@ class MyAccountController(BaseController
 
        self.__load_data()
 
        c.perm_user = AuthUser(user_id=request.authuser.user_id)
 
        managed_fields = auth_modules.get_managed_fields(c.user)
 
        def_user_perms = AuthUser(dbuser=User.get_default_user()).permissions['global']
 
        def_user_perms = AuthUser(dbuser=db.User.get_default_user()).global_permissions
 
        if 'hg.register.none' in def_user_perms:
 
            managed_fields.extend(['username', 'firstname', 'lastname', 'email'])
 

	
 
@@ -116,14 +109,14 @@ class MyAccountController(BaseController
 

	
 
                UserModel().update(request.authuser.user_id, form_result,
 
                                   skip_attrs=skip_attrs)
 
                h.flash(_('Your account was updated successfully'),
 
                webutils.flash(_('Your account was updated successfully'),
 
                        category='success')
 
                Session().commit()
 
                meta.Session().commit()
 
                update = True
 

	
 
            except formencode.Invalid as errors:
 
                return htmlfill.render(
 
                    render('admin/my_account/my_account.html'),
 
                    base.render('admin/my_account/my_account.html'),
 
                    defaults=errors.value,
 
                    errors=errors.error_dict or {},
 
                    prefix_error=False,
 
@@ -131,12 +124,12 @@ class MyAccountController(BaseController
 
                    force_defaults=False)
 
            except Exception:
 
                log.error(traceback.format_exc())
 
                h.flash(_('Error occurred during update of user %s')
 
                webutils.flash(_('Error occurred during update of user %s')
 
                        % form_result.get('username'), category='error')
 
        if update:
 
            raise HTTPFound(location='my_account')
 
        return htmlfill.render(
 
            render('admin/my_account/my_account.html'),
 
            base.render('admin/my_account/my_account.html'),
 
            defaults=defaults,
 
            encoding="UTF-8",
 
            force_defaults=False)
 
@@ -153,11 +146,11 @@ class MyAccountController(BaseController
 
            try:
 
                form_result = _form.to_python(request.POST)
 
                UserModel().update(request.authuser.user_id, form_result)
 
                Session().commit()
 
                h.flash(_("Successfully updated password"), category='success')
 
                meta.Session().commit()
 
                webutils.flash(_("Successfully updated password"), category='success')
 
            except formencode.Invalid as errors:
 
                return htmlfill.render(
 
                    render('admin/my_account/my_account.html'),
 
                    base.render('admin/my_account/my_account.html'),
 
                    defaults=errors.value,
 
                    errors=errors.error_dict or {},
 
                    prefix_error=False,
 
@@ -165,9 +158,9 @@ class MyAccountController(BaseController
 
                    force_defaults=False)
 
            except Exception:
 
                log.error(traceback.format_exc())
 
                h.flash(_('Error occurred during update of user password'),
 
                webutils.flash(_('Error occurred during update of user password'),
 
                        category='error')
 
        return render('admin/my_account/my_account.html')
 
        return base.render('admin/my_account/my_account.html')
 

	
 
    def my_account_repos(self):
 
        c.active = 'repos'
 
@@ -175,7 +168,7 @@ class MyAccountController(BaseController
 

	
 
        # data used to render the grid
 
        c.data = self._load_my_repos_data()
 
        return render('admin/my_account/my_account.html')
 
        return base.render('admin/my_account/my_account.html')
 

	
 
    def my_account_watched(self):
 
        c.active = 'watched'
 
@@ -183,36 +176,36 @@ class MyAccountController(BaseController
 

	
 
        # data used to render the grid
 
        c.data = self._load_my_repos_data(watched=True)
 
        return render('admin/my_account/my_account.html')
 
        return base.render('admin/my_account/my_account.html')
 

	
 
    def my_account_perms(self):
 
        c.active = 'perms'
 
        self.__load_data()
 
        c.perm_user = AuthUser(user_id=request.authuser.user_id)
 

	
 
        return render('admin/my_account/my_account.html')
 
        return base.render('admin/my_account/my_account.html')
 

	
 
    def my_account_emails(self):
 
        c.active = 'emails'
 
        self.__load_data()
 

	
 
        c.user_email_map = UserEmailMap.query() \
 
            .filter(UserEmailMap.user == c.user).all()
 
        return render('admin/my_account/my_account.html')
 
        c.user_email_map = db.UserEmailMap.query() \
 
            .filter(db.UserEmailMap.user == c.user).all()
 
        return base.render('admin/my_account/my_account.html')
 

	
 
    def my_account_emails_add(self):
 
        email = request.POST.get('new_email')
 

	
 
        try:
 
            UserModel().add_extra_email(request.authuser.user_id, email)
 
            Session().commit()
 
            h.flash(_("Added email %s to user") % email, category='success')
 
            meta.Session().commit()
 
            webutils.flash(_("Added email %s to user") % email, category='success')
 
        except formencode.Invalid as error:
 
            msg = error.error_dict['email']
 
            h.flash(msg, category='error')
 
            webutils.flash(msg, category='error')
 
        except Exception:
 
            log.error(traceback.format_exc())
 
            h.flash(_('An error occurred during email saving'),
 
            webutils.flash(_('An error occurred during email saving'),
 
                    category='error')
 
        raise HTTPFound(location=url('my_account_emails'))
 

	
 
@@ -220,8 +213,8 @@ class MyAccountController(BaseController
 
        email_id = request.POST.get('del_email_id')
 
        user_model = UserModel()
 
        user_model.delete_extra_email(request.authuser.user_id, email_id)
 
        Session().commit()
 
        h.flash(_("Removed email from user"), category='success')
 
        meta.Session().commit()
 
        webutils.flash(_("Removed email from user"), category='success')
 
        raise HTTPFound(location=url('my_account_emails'))
 

	
 
    def my_account_api_keys(self):
 
@@ -238,59 +231,59 @@ class MyAccountController(BaseController
 
        c.lifetime_options = [(c.lifetime_values, _("Lifetime"))]
 
        c.user_api_keys = ApiKeyModel().get_api_keys(request.authuser.user_id,
 
                                                     show_expired=show_expired)
 
        return render('admin/my_account/my_account.html')
 
        return base.render('admin/my_account/my_account.html')
 

	
 
    def my_account_api_keys_add(self):
 
        lifetime = safe_int(request.POST.get('lifetime'), -1)
 
        description = request.POST.get('description')
 
        ApiKeyModel().create(request.authuser.user_id, description, lifetime)
 
        Session().commit()
 
        h.flash(_("API key successfully created"), category='success')
 
        meta.Session().commit()
 
        webutils.flash(_("API key successfully created"), category='success')
 
        raise HTTPFound(location=url('my_account_api_keys'))
 

	
 
    def my_account_api_keys_delete(self):
 
        api_key = request.POST.get('del_api_key')
 
        if request.POST.get('del_api_key_builtin'):
 
            user = User.get(request.authuser.user_id)
 
            user = db.User.get(request.authuser.user_id)
 
            user.api_key = generate_api_key()
 
            Session().commit()
 
            h.flash(_("API key successfully reset"), category='success')
 
            meta.Session().commit()
 
            webutils.flash(_("API key successfully reset"), category='success')
 
        elif api_key:
 
            ApiKeyModel().delete(api_key, request.authuser.user_id)
 
            Session().commit()
 
            h.flash(_("API key successfully deleted"), category='success')
 
            meta.Session().commit()
 
            webutils.flash(_("API key successfully deleted"), category='success')
 

	
 
        raise HTTPFound(location=url('my_account_api_keys'))
 

	
 
    @IfSshEnabled
 
    @base.IfSshEnabled
 
    def my_account_ssh_keys(self):
 
        c.active = 'ssh_keys'
 
        self.__load_data()
 
        c.user_ssh_keys = SshKeyModel().get_ssh_keys(request.authuser.user_id)
 
        return render('admin/my_account/my_account.html')
 
        return base.render('admin/my_account/my_account.html')
 

	
 
    @IfSshEnabled
 
    @base.IfSshEnabled
 
    def my_account_ssh_keys_add(self):
 
        description = request.POST.get('description')
 
        public_key = request.POST.get('public_key')
 
        try:
 
            new_ssh_key = SshKeyModel().create(request.authuser.user_id,
 
                                               description, public_key)
 
            Session().commit()
 
            meta.Session().commit()
 
            SshKeyModel().write_authorized_keys()
 
            h.flash(_("SSH key %s successfully added") % new_ssh_key.fingerprint, category='success')
 
            webutils.flash(_("SSH key %s successfully added") % new_ssh_key.fingerprint, category='success')
 
        except SshKeyModelException as e:
 
            h.flash(e.args[0], category='error')
 
            webutils.flash(e.args[0], category='error')
 
        raise HTTPFound(location=url('my_account_ssh_keys'))
 

	
 
    @IfSshEnabled
 
    @base.IfSshEnabled
 
    def my_account_ssh_keys_delete(self):
 
        fingerprint = request.POST.get('del_public_key_fingerprint')
 
        try:
 
            SshKeyModel().delete(fingerprint, request.authuser.user_id)
 
            Session().commit()
 
            meta.Session().commit()
 
            SshKeyModel().write_authorized_keys()
 
            h.flash(_("SSH key successfully deleted"), category='success')
 
            webutils.flash(_("SSH key successfully deleted"), category='success')
 
        except SshKeyModelException as e:
 
            h.flash(e.args[0], category='error')
 
            webutils.flash(e.args[0], category='error')
 
        raise HTTPFound(location=url('my_account_ssh_keys'))
kallithea/controllers/admin/permissions.py
Show inline comments
 
@@ -36,24 +36,19 @@ from tg import tmpl_context as c
 
from tg.i18n import ugettext as _
 
from webob.exc import HTTPFound
 

	
 
from kallithea.config.routing import url
 
from kallithea.lib import helpers as h
 
from kallithea.controllers import base
 
from kallithea.lib import webutils
 
from kallithea.lib.auth import AuthUser, HasPermissionAnyDecorator, LoginRequired
 
from kallithea.lib.base import BaseController, render
 
from kallithea.model.db import User, UserIpMap
 
from kallithea.lib.webutils import url
 
from kallithea.model import db, meta
 
from kallithea.model.forms import DefaultPermissionsForm
 
from kallithea.model.meta import Session
 
from kallithea.model.permission import PermissionModel
 

	
 

	
 
log = logging.getLogger(__name__)
 

	
 

	
 
class PermissionsController(BaseController):
 
    """REST Controller styled on the Atom Publishing Protocol"""
 
    # To properly map this controller, ensure your config/routing.py
 
    # file has a resource setup:
 
    #     map.resource('permission', 'permissions')
 
class PermissionsController(base.BaseController):
 

	
 
    @LoginRequired()
 
    @HasPermissionAnyDecorator('hg.admin')
 
@@ -61,18 +56,22 @@ class PermissionsController(BaseControll
 
        super(PermissionsController, self)._before(*args, **kwargs)
 

	
 
    def __load_data(self):
 
        # Permissions for the Default user on new repositories
 
        c.repo_perms_choices = [('repository.none', _('None'),),
 
                                   ('repository.read', _('Read'),),
 
                                   ('repository.write', _('Write'),),
 
                                   ('repository.admin', _('Admin'),)]
 
        # Permissions for the Default user on new repository groups
 
        c.group_perms_choices = [('group.none', _('None'),),
 
                                 ('group.read', _('Read'),),
 
                                 ('group.write', _('Write'),),
 
                                 ('group.admin', _('Admin'),)]
 
        # Permissions for the Default user on new user groups
 
        c.user_group_perms_choices = [('usergroup.none', _('None'),),
 
                                      ('usergroup.read', _('Read'),),
 
                                      ('usergroup.write', _('Write'),),
 
                                      ('usergroup.admin', _('Admin'),)]
 
        # Registration - allow new Users to create an account
 
        c.register_choices = [
 
            ('hg.register.none',
 
                _('Disabled')),
 
@@ -80,26 +79,18 @@ class PermissionsController(BaseControll
 
                _('Allowed with manual account activation')),
 
            ('hg.register.auto_activate',
 
                _('Allowed with automatic account activation')), ]
 

	
 
        # External auth account activation
 
        c.extern_activate_choices = [
 
            ('hg.extern_activate.manual', _('Manual activation of external account')),
 
            ('hg.extern_activate.auto', _('Automatic activation of external account')),
 
        ]
 

	
 
        # Top level repository creation
 
        c.repo_create_choices = [('hg.create.none', _('Disabled')),
 
                                 ('hg.create.repository', _('Enabled'))]
 

	
 
        c.repo_create_on_write_choices = [
 
            ('hg.create.write_on_repogroup.true', _('Enabled')),
 
            ('hg.create.write_on_repogroup.false', _('Disabled')),
 
        ]
 

	
 
        # User group creation
 
        c.user_group_create_choices = [('hg.usergroup.create.false', _('Disabled')),
 
                                       ('hg.usergroup.create.true', _('Enabled'))]
 

	
 
        c.repo_group_create_choices = [('hg.repogroup.create.false', _('Disabled')),
 
                                       ('hg.repogroup.create.true', _('Enabled'))]
 

	
 
        # Repository forking:
 
        c.fork_choices = [('hg.fork.none', _('Disabled')),
 
                          ('hg.fork.repository', _('Enabled'))]
 

	
 
@@ -112,8 +103,6 @@ class PermissionsController(BaseControll
 
                [x[0] for x in c.group_perms_choices],
 
                [x[0] for x in c.user_group_perms_choices],
 
                [x[0] for x in c.repo_create_choices],
 
                [x[0] for x in c.repo_create_on_write_choices],
 
                [x[0] for x in c.repo_group_create_choices],
 
                [x[0] for x in c.user_group_create_choices],
 
                [x[0] for x in c.fork_choices],
 
                [x[0] for x in c.register_choices],
 
@@ -123,15 +112,15 @@ class PermissionsController(BaseControll
 
                form_result = _form.to_python(dict(request.POST))
 
                form_result.update({'perm_user_name': 'default'})
 
                PermissionModel().update(form_result)
 
                Session().commit()
 
                h.flash(_('Global permissions updated successfully'),
 
                meta.Session().commit()
 
                webutils.flash(_('Global permissions updated successfully'),
 
                        category='success')
 

	
 
            except formencode.Invalid as errors:
 
                defaults = errors.value
 

	
 
                return htmlfill.render(
 
                    render('admin/permissions/permissions.html'),
 
                    base.render('admin/permissions/permissions.html'),
 
                    defaults=defaults,
 
                    errors=errors.error_dict or {},
 
                    prefix_error=False,
 
@@ -139,12 +128,12 @@ class PermissionsController(BaseControll
 
                    force_defaults=False)
 
            except Exception:
 
                log.error(traceback.format_exc())
 
                h.flash(_('Error occurred during update of permissions'),
 
                webutils.flash(_('Error occurred during update of permissions'),
 
                        category='error')
 

	
 
            raise HTTPFound(location=url('admin_permissions'))
 

	
 
        c.user = User.get_default_user()
 
        c.user = db.User.get_default_user()
 
        defaults = {'anonymous': c.user.active}
 

	
 
        for p in c.user.user_perms:
 
@@ -157,15 +146,9 @@ class PermissionsController(BaseControll
 
            if p.permission.permission_name.startswith('usergroup.'):
 
                defaults['default_user_group_perm'] = p.permission.permission_name
 

	
 
            if p.permission.permission_name.startswith('hg.create.write_on_repogroup.'):
 
                defaults['create_on_write'] = p.permission.permission_name
 

	
 
            elif p.permission.permission_name.startswith('hg.create.'):
 
                defaults['default_repo_create'] = p.permission.permission_name
 

	
 
            if p.permission.permission_name.startswith('hg.repogroup.'):
 
                defaults['default_repo_group_create'] = p.permission.permission_name
 

	
 
            if p.permission.permission_name.startswith('hg.usergroup.'):
 
                defaults['default_user_group_create'] = p.permission.permission_name
 

	
 
@@ -179,21 +162,21 @@ class PermissionsController(BaseControll
 
                defaults['default_fork'] = p.permission.permission_name
 

	
 
        return htmlfill.render(
 
            render('admin/permissions/permissions.html'),
 
            base.render('admin/permissions/permissions.html'),
 
            defaults=defaults,
 
            encoding="UTF-8",
 
            force_defaults=False)
 

	
 
    def permission_ips(self):
 
        c.active = 'ips'
 
        c.user = User.get_default_user()
 
        c.user_ip_map = UserIpMap.query() \
 
                        .filter(UserIpMap.user == c.user).all()
 
        c.user = db.User.get_default_user()
 
        c.user_ip_map = db.UserIpMap.query() \
 
                        .filter(db.UserIpMap.user == c.user).all()
 

	
 
        return render('admin/permissions/permissions.html')
 
        return base.render('admin/permissions/permissions.html')
 

	
 
    def permission_perms(self):
 
        c.active = 'perms'
 
        c.user = User.get_default_user()
 
        c.user = db.User.get_default_user()
 
        c.perm_user = AuthUser(dbuser=c.user)
 
        return render('admin/permissions/permissions.html')
 
        return base.render('admin/permissions/permissions.html')
kallithea/controllers/admin/repo_groups.py
Show inline comments
 
@@ -36,14 +36,13 @@ from tg.i18n import ugettext as _
 
from tg.i18n import ungettext
 
from webob.exc import HTTPForbidden, HTTPFound, HTTPInternalServerError, HTTPNotFound
 

	
 
from kallithea.config.routing import url
 
from kallithea.lib import helpers as h
 
from kallithea.controllers import base
 
from kallithea.lib import webutils
 
from kallithea.lib.auth import HasPermissionAny, HasRepoGroupPermissionLevel, HasRepoGroupPermissionLevelDecorator, LoginRequired
 
from kallithea.lib.base import BaseController, render
 
from kallithea.lib.utils2 import safe_int
 
from kallithea.model.db import RepoGroup, Repository
 
from kallithea.lib.webutils import url
 
from kallithea.model import db, meta
 
from kallithea.model.forms import RepoGroupForm, RepoGroupPermsForm
 
from kallithea.model.meta import Session
 
from kallithea.model.repo import RepoModel
 
from kallithea.model.repo_group import RepoGroupModel
 
from kallithea.model.scm import AvailableRepoGroupChoices, RepoGroupList
 
@@ -52,7 +51,7 @@ from kallithea.model.scm import Availabl
 
log = logging.getLogger(__name__)
 

	
 

	
 
class RepoGroupsController(BaseController):
 
class RepoGroupsController(base.BaseController):
 

	
 
    @LoginRequired(allow_default_user=True)
 
    def _before(self, *args, **kwargs):
 
@@ -63,7 +62,7 @@ class RepoGroupsController(BaseControlle
 
        exclude is used for not moving group to itself TODO: also exclude descendants
 
        Note: only admin can create top level groups
 
        """
 
        repo_groups = AvailableRepoGroupChoices([], 'admin', extras)
 
        repo_groups = AvailableRepoGroupChoices('admin', extras)
 
        exclude_group_ids = set(rg.group_id for rg in exclude)
 
        c.repo_groups = [rg for rg in repo_groups
 
                         if rg[0] not in exclude_group_ids]
 
@@ -74,7 +73,7 @@ class RepoGroupsController(BaseControlle
 

	
 
        :param group_id:
 
        """
 
        repo_group = RepoGroup.get_or_404(group_id)
 
        repo_group = db.RepoGroup.get_or_404(group_id)
 
        data = repo_group.get_dict()
 
        data['group_name'] = repo_group.name
 

	
 
@@ -98,7 +97,7 @@ class RepoGroupsController(BaseControlle
 
        return False
 

	
 
    def index(self, format='html'):
 
        _list = RepoGroup.query(sorted=True).all()
 
        _list = db.RepoGroup.query(sorted=True).all()
 
        group_iter = RepoGroupList(_list, perm_level='admin')
 
        repo_groups_data = []
 
        _tmpl_lookup = app_globals.mako_lookup
 
@@ -106,22 +105,22 @@ class RepoGroupsController(BaseControlle
 

	
 
        def repo_group_name(repo_group_name, children_groups):
 
            return template.get_def("repo_group_name") \
 
                .render_unicode(repo_group_name, children_groups, _=_, h=h, c=c)
 
                .render_unicode(repo_group_name, children_groups, _=_, webutils=webutils, c=c)
 

	
 
        def repo_group_actions(repo_group_id, repo_group_name, gr_count):
 
            return template.get_def("repo_group_actions") \
 
                .render_unicode(repo_group_id, repo_group_name, gr_count, _=_, h=h, c=c,
 
                .render_unicode(repo_group_id, repo_group_name, gr_count, _=_, webutils=webutils, c=c,
 
                        ungettext=ungettext)
 

	
 
        for repo_gr in group_iter:
 
            children_groups = [g.name for g in repo_gr.parents] + [repo_gr.name]
 
            repo_count = repo_gr.repositories.count()
 
            repo_groups_data.append({
 
                "raw_name": h.escape(repo_gr.group_name),
 
                "raw_name": webutils.escape(repo_gr.group_name),
 
                "group_name": repo_group_name(repo_gr.group_name, children_groups),
 
                "desc": h.escape(repo_gr.group_description),
 
                "desc": webutils.escape(repo_gr.group_description),
 
                "repos": repo_count,
 
                "owner": h.person(repo_gr.owner),
 
                "owner": repo_gr.owner.username,
 
                "action": repo_group_actions(repo_gr.group_id, repo_gr.group_name,
 
                                             repo_count)
 
            })
 
@@ -132,7 +131,7 @@ class RepoGroupsController(BaseControlle
 
            "records": repo_groups_data
 
        }
 

	
 
        return render('admin/repo_groups/repo_groups.html')
 
        return base.render('admin/repo_groups/repo_groups.html')
 

	
 
    def create(self):
 
        self.__load_defaults()
 
@@ -150,11 +149,11 @@ class RepoGroupsController(BaseControlle
 
                owner=request.authuser.user_id, # TODO: make editable
 
                copy_permissions=form_result['group_copy_permissions']
 
            )
 
            Session().commit()
 
            meta.Session().commit()
 
            # TODO: in future action_logger(, '', '', '')
 
        except formencode.Invalid as errors:
 
            return htmlfill.render(
 
                render('admin/repo_groups/repo_group_add.html'),
 
                base.render('admin/repo_groups/repo_group_add.html'),
 
                defaults=errors.value,
 
                errors=errors.error_dict or {},
 
                prefix_error=False,
 
@@ -162,14 +161,14 @@ class RepoGroupsController(BaseControlle
 
                force_defaults=False)
 
        except Exception:
 
            log.error(traceback.format_exc())
 
            h.flash(_('Error occurred during creation of repository group %s')
 
            webutils.flash(_('Error occurred during creation of repository group %s')
 
                    % request.POST.get('group_name'), category='error')
 
            if form_result is None:
 
                raise
 
            parent_group_id = form_result['parent_group_id']
 
            # TODO: maybe we should get back to the main view, not the admin one
 
            raise HTTPFound(location=url('repos_groups', parent_group=parent_group_id))
 
        h.flash(_('Created repository group %s') % gr.group_name,
 
        webutils.flash(_('Created repository group %s') % gr.group_name,
 
                category='success')
 
        raise HTTPFound(location=url('repos_group_home', group_name=gr.group_name))
 

	
 
@@ -181,7 +180,7 @@ class RepoGroupsController(BaseControlle
 
        else:
 
            # we pass in parent group into creation form, thus we know
 
            # what would be the group, we can check perms here !
 
            group = RepoGroup.get(parent_group_id) if parent_group_id else None
 
            group = db.RepoGroup.get(parent_group_id) if parent_group_id else None
 
            group_name = group.group_name if group else None
 
            if HasRepoGroupPermissionLevel('admin')(group_name, 'group create'):
 
                pass
 
@@ -190,7 +189,7 @@ class RepoGroupsController(BaseControlle
 

	
 
        self.__load_defaults()
 
        return htmlfill.render(
 
            render('admin/repo_groups/repo_group_add.html'),
 
            base.render('admin/repo_groups/repo_group_add.html'),
 
            defaults={'parent_group_id': parent_group_id},
 
            errors={},
 
            prefix_error=False,
 
@@ -199,7 +198,7 @@ class RepoGroupsController(BaseControlle
 

	
 
    @HasRepoGroupPermissionLevelDecorator('admin')
 
    def update(self, group_name):
 
        c.repo_group = RepoGroup.guess_instance(group_name)
 
        c.repo_group = db.RepoGroup.guess_instance(group_name)
 
        self.__load_defaults(extras=[c.repo_group.parent_group],
 
                             exclude=[c.repo_group])
 

	
 
@@ -221,8 +220,8 @@ class RepoGroupsController(BaseControlle
 
            form_result = repo_group_form.to_python(dict(request.POST))
 

	
 
            new_gr = RepoGroupModel().update(group_name, form_result)
 
            Session().commit()
 
            h.flash(_('Updated repository group %s')
 
            meta.Session().commit()
 
            webutils.flash(_('Updated repository group %s')
 
                    % form_result['group_name'], category='success')
 
            # we now have new name !
 
            group_name = new_gr.group_name
 
@@ -230,7 +229,7 @@ class RepoGroupsController(BaseControlle
 
        except formencode.Invalid as errors:
 
            c.active = 'settings'
 
            return htmlfill.render(
 
                render('admin/repo_groups/repo_group_edit.html'),
 
                base.render('admin/repo_groups/repo_group_edit.html'),
 
                defaults=errors.value,
 
                errors=errors.error_dict or {},
 
                prefix_error=False,
 
@@ -238,35 +237,35 @@ class RepoGroupsController(BaseControlle
 
                force_defaults=False)
 
        except Exception:
 
            log.error(traceback.format_exc())
 
            h.flash(_('Error occurred during update of repository group %s')
 
            webutils.flash(_('Error occurred during update of repository group %s')
 
                    % request.POST.get('group_name'), category='error')
 

	
 
        raise HTTPFound(location=url('edit_repo_group', group_name=group_name))
 

	
 
    @HasRepoGroupPermissionLevelDecorator('admin')
 
    def delete(self, group_name):
 
        gr = c.repo_group = RepoGroup.guess_instance(group_name)
 
        gr = c.repo_group = db.RepoGroup.guess_instance(group_name)
 
        repos = gr.repositories.all()
 
        if repos:
 
            h.flash(_('This group contains %s repositories and cannot be '
 
            webutils.flash(_('This group contains %s repositories and cannot be '
 
                      'deleted') % len(repos), category='warning')
 
            raise HTTPFound(location=url('repos_groups'))
 

	
 
        children = gr.children.all()
 
        if children:
 
            h.flash(_('This group contains %s subgroups and cannot be deleted'
 
            webutils.flash(_('This group contains %s subgroups and cannot be deleted'
 
                      % (len(children))), category='warning')
 
            raise HTTPFound(location=url('repos_groups'))
 

	
 
        try:
 
            RepoGroupModel().delete(group_name)
 
            Session().commit()
 
            h.flash(_('Removed repository group %s') % group_name,
 
            meta.Session().commit()
 
            webutils.flash(_('Removed repository group %s') % group_name,
 
                    category='success')
 
            # TODO: in future action_logger(, '', '', '')
 
        except Exception:
 
            log.error(traceback.format_exc())
 
            h.flash(_('Error occurred during deletion of repository group %s')
 
            webutils.flash(_('Error occurred during deletion of repository group %s')
 
                    % group_name, category='error')
 

	
 
        if gr.parent_group:
 
@@ -279,7 +278,7 @@ class RepoGroupsController(BaseControlle
 
        the group by id view instead
 
        """
 
        group_name = group_name.rstrip('/')
 
        id_ = RepoGroup.get_by_group_name(group_name)
 
        id_ = db.RepoGroup.get_by_group_name(group_name)
 
        if id_:
 
            return self.show(group_name)
 
        raise HTTPNotFound
 
@@ -288,29 +287,29 @@ class RepoGroupsController(BaseControlle
 
    def show(self, group_name):
 
        c.active = 'settings'
 

	
 
        c.group = c.repo_group = RepoGroup.guess_instance(group_name)
 
        c.group = c.repo_group = db.RepoGroup.guess_instance(group_name)
 

	
 
        groups = RepoGroup.query(sorted=True).filter_by(parent_group=c.group).all()
 
        groups = db.RepoGroup.query(sorted=True).filter_by(parent_group=c.group).all()
 
        repo_groups_list = self.scm_model.get_repo_groups(groups)
 

	
 
        repos_list = Repository.query(sorted=True).filter_by(group=c.group).all()
 
        repos_list = db.Repository.query(sorted=True).filter_by(group=c.group).all()
 
        c.data = RepoModel().get_repos_as_dict(repos_list,
 
                                               repo_groups_list=repo_groups_list,
 
                                               short_name=True)
 

	
 
        return render('admin/repo_groups/repo_group_show.html')
 
        return base.render('admin/repo_groups/repo_group_show.html')
 

	
 
    @HasRepoGroupPermissionLevelDecorator('admin')
 
    def edit(self, group_name):
 
        c.active = 'settings'
 

	
 
        c.repo_group = RepoGroup.guess_instance(group_name)
 
        c.repo_group = db.RepoGroup.guess_instance(group_name)
 
        self.__load_defaults(extras=[c.repo_group.parent_group],
 
                             exclude=[c.repo_group])
 
        defaults = self.__load_data(c.repo_group.group_id)
 

	
 
        return htmlfill.render(
 
            render('admin/repo_groups/repo_group_edit.html'),
 
            base.render('admin/repo_groups/repo_group_edit.html'),
 
            defaults=defaults,
 
            encoding="UTF-8",
 
            force_defaults=False
 
@@ -319,19 +318,19 @@ class RepoGroupsController(BaseControlle
 
    @HasRepoGroupPermissionLevelDecorator('admin')
 
    def edit_repo_group_advanced(self, group_name):
 
        c.active = 'advanced'
 
        c.repo_group = RepoGroup.guess_instance(group_name)
 
        c.repo_group = db.RepoGroup.guess_instance(group_name)
 

	
 
        return render('admin/repo_groups/repo_group_edit.html')
 
        return base.render('admin/repo_groups/repo_group_edit.html')
 

	
 
    @HasRepoGroupPermissionLevelDecorator('admin')
 
    def edit_repo_group_perms(self, group_name):
 
        c.active = 'perms'
 
        c.repo_group = RepoGroup.guess_instance(group_name)
 
        c.repo_group = db.RepoGroup.guess_instance(group_name)
 
        self.__load_defaults()
 
        defaults = self.__load_data(c.repo_group.group_id)
 

	
 
        return htmlfill.render(
 
            render('admin/repo_groups/repo_group_edit.html'),
 
            base.render('admin/repo_groups/repo_group_edit.html'),
 
            defaults=defaults,
 
            encoding="UTF-8",
 
            force_defaults=False
 
@@ -345,13 +344,13 @@ class RepoGroupsController(BaseControlle
 
        :param group_name:
 
        """
 

	
 
        c.repo_group = RepoGroup.guess_instance(group_name)
 
        c.repo_group = db.RepoGroup.guess_instance(group_name)
 
        valid_recursive_choices = ['none', 'repos', 'groups', 'all']
 
        form_result = RepoGroupPermsForm(valid_recursive_choices)().to_python(request.POST)
 
        if not request.authuser.is_admin:
 
            if self._revoke_perms_on_yourself(form_result):
 
                msg = _('Cannot revoke permission for yourself as admin')
 
                h.flash(msg, category='warning')
 
                webutils.flash(msg, category='warning')
 
                raise HTTPFound(location=url('edit_repo_group_perms', group_name=group_name))
 
        recursive = form_result['recursive']
 
        # iterate over all members(if in recursive mode) of this groups and
 
@@ -364,8 +363,8 @@ class RepoGroupsController(BaseControlle
 
        # TODO: implement this
 
        #action_logger(request.authuser, 'admin_changed_repo_permissions',
 
        #              repo_name, request.ip_addr)
 
        Session().commit()
 
        h.flash(_('Repository group permissions updated'), category='success')
 
        meta.Session().commit()
 
        webutils.flash(_('Repository group permissions updated'), category='success')
 
        raise HTTPFound(location=url('edit_repo_group_perms', group_name=group_name))
 

	
 
    @HasRepoGroupPermissionLevelDecorator('admin')
 
@@ -381,7 +380,7 @@ class RepoGroupsController(BaseControlle
 
            if not request.authuser.is_admin:
 
                if obj_type == 'user' and request.authuser.user_id == obj_id:
 
                    msg = _('Cannot revoke permission for yourself as admin')
 
                    h.flash(msg, category='warning')
 
                    webutils.flash(msg, category='warning')
 
                    raise Exception('revoke admin permission on self')
 
            recursive = request.POST.get('recursive', 'none')
 
            if obj_type == 'user':
 
@@ -394,9 +393,9 @@ class RepoGroupsController(BaseControlle
 
                                                   obj_type='user_group',
 
                                                   recursive=recursive)
 

	
 
            Session().commit()
 
            meta.Session().commit()
 
        except Exception:
 
            log.error(traceback.format_exc())
 
            h.flash(_('An error occurred during revoking of permission'),
 
            webutils.flash(_('An error occurred during revoking of permission'),
 
                    category='error')
 
            raise HTTPInternalServerError()
kallithea/controllers/admin/repos.py
Show inline comments
 
@@ -28,7 +28,6 @@ Original author and date, and relevant c
 
import logging
 
import traceback
 

	
 
import celery.result
 
import formencode
 
from formencode import htmlfill
 
from tg import request
 
@@ -37,17 +36,15 @@ from tg.i18n import ugettext as _
 
from webob.exc import HTTPForbidden, HTTPFound, HTTPInternalServerError, HTTPNotFound
 

	
 
import kallithea
 
from kallithea.config.routing import url
 
from kallithea.lib import helpers as h
 
from kallithea.lib.auth import HasPermissionAny, HasRepoPermissionLevelDecorator, LoginRequired, NotAnonymous
 
from kallithea.lib.base import BaseRepoController, jsonify, render
 
from kallithea.controllers import base
 
from kallithea.lib import webutils
 
from kallithea.lib.auth import HasRepoPermissionLevelDecorator, LoginRequired, NotAnonymous
 
from kallithea.lib.exceptions import AttachedForksError
 
from kallithea.lib.utils import action_logger
 
from kallithea.lib.utils2 import safe_int
 
from kallithea.lib.vcs import RepositoryError
 
from kallithea.model.db import RepoGroup, Repository, RepositoryField, Setting, UserFollowing
 
from kallithea.lib.webutils import url
 
from kallithea.model import db, meta, userlog
 
from kallithea.model.forms import RepoFieldForm, RepoForm, RepoPermsForm
 
from kallithea.model.meta import Session
 
from kallithea.model.repo import RepoModel
 
from kallithea.model.scm import AvailableRepoGroupChoices, RepoList, ScmModel
 

	
 
@@ -55,12 +52,7 @@ from kallithea.model.scm import Availabl
 
log = logging.getLogger(__name__)
 

	
 

	
 
class ReposController(BaseRepoController):
 
    """
 
    REST Controller styled on the Atom Publishing Protocol"""
 
    # To properly map this controller, ensure your config/routing.py
 
    # file has a resource setup:
 
    #     map.resource('repo', 'repos')
 
class ReposController(base.BaseRepoController):
 

	
 
    @LoginRequired(allow_default_user=True)
 
    def _before(self, *args, **kwargs):
 
@@ -70,20 +62,14 @@ class ReposController(BaseRepoController
 
        repo_obj = c.db_repo
 

	
 
        if repo_obj is None:
 
            h.not_mapped_error(c.repo_name)
 
            raise HTTPFound(location=url('repos'))
 
            raise HTTPNotFound()
 

	
 
        return repo_obj
 

	
 
    def __load_defaults(self, repo=None):
 
        top_perms = ['hg.create.repository']
 
        if HasPermissionAny('hg.create.write_on_repogroup.true')():
 
            repo_group_perm_level = 'write'
 
        else:
 
            repo_group_perm_level = 'admin'
 
        extras = [] if repo is None else [repo.group]
 

	
 
        c.repo_groups = AvailableRepoGroupChoices(top_perms, repo_group_perm_level, extras)
 
        c.repo_groups = AvailableRepoGroupChoices('write', extras)
 

	
 
        c.landing_revs_choices, c.landing_revs = ScmModel().get_repo_landing_revs(repo)
 

	
 
@@ -101,13 +87,13 @@ class ReposController(BaseRepoController
 
        return defaults
 

	
 
    def index(self, format='html'):
 
        repos_list = RepoList(Repository.query(sorted=True).all(), perm_level='admin')
 
        repos_list = RepoList(db.Repository.query(sorted=True).all(), perm_level='admin')
 
        # the repo list will be filtered to only show repos where the user has read permissions
 
        repos_data = RepoModel().get_repos_as_dict(repos_list, admin=True)
 
        # data used to render the grid
 
        c.data = repos_data
 

	
 
        return render('admin/repos/repos.html')
 
        return base.render('admin/repos/repos.html')
 

	
 
    @NotAnonymous()
 
    def create(self):
 
@@ -120,7 +106,7 @@ class ReposController(BaseRepoController
 
        except formencode.Invalid as errors:
 
            log.info(errors)
 
            return htmlfill.render(
 
                render('admin/repos/repo_add.html'),
 
                base.render('admin/repos/repo_add.html'),
 
                defaults=errors.value,
 
                errors=errors.error_dict or {},
 
                prefix_error=False,
 
@@ -130,18 +116,17 @@ class ReposController(BaseRepoController
 
        try:
 
            # create is done sometimes async on celery, db transaction
 
            # management is handled there.
 
            task = RepoModel().create(form_result, request.authuser.user_id)
 
            task_id = task.task_id
 
            RepoModel().create(form_result, request.authuser.user_id)
 
        except Exception:
 
            log.error(traceback.format_exc())
 
            msg = (_('Error creating repository %s')
 
                   % form_result.get('repo_name'))
 
            h.flash(msg, category='error')
 
            webutils.flash(msg, category='error')
 
            raise HTTPFound(location=url('home'))
 

	
 
        raise HTTPFound(location=h.url('repo_creating_home',
 
        raise HTTPFound(location=webutils.url('repo_creating_home',
 
                              repo_name=form_result['repo_name_full'],
 
                              task_id=task_id))
 
                              ))
 

	
 
    @NotAnonymous()
 
    def create_repository(self):
 
@@ -151,9 +136,9 @@ class ReposController(BaseRepoController
 
        parent_group = request.GET.get('parent_group')
 

	
 
        ## apply the defaults from defaults page
 
        defaults = Setting.get_default_repo_settings(strip_prefix=True)
 
        defaults = db.Setting.get_default_repo_settings(strip_prefix=True)
 
        if parent_group:
 
            prg = RepoGroup.get(parent_group)
 
            prg = db.RepoGroup.get(parent_group)
 
            if prg is None or not any(rgc[0] == prg.group_id
 
                                      for rgc in c.repo_groups):
 
                raise HTTPForbidden
 
@@ -162,7 +147,7 @@ class ReposController(BaseRepoController
 
        defaults.update({'repo_group': parent_group})
 

	
 
        return htmlfill.render(
 
            render('admin/repos/repo_add.html'),
 
            base.render('admin/repos/repo_add.html'),
 
            defaults=defaults,
 
            errors={},
 
            prefix_error=False,
 
@@ -172,39 +157,30 @@ class ReposController(BaseRepoController
 
    @LoginRequired()
 
    def repo_creating(self, repo_name):
 
        c.repo = repo_name
 
        c.task_id = request.GET.get('task_id')
 
        if not c.repo:
 
            raise HTTPNotFound()
 
        return render('admin/repos/repo_creating.html')
 
        return base.render('admin/repos/repo_creating.html')
 

	
 
    @LoginRequired()
 
    @jsonify
 
    @base.jsonify
 
    def repo_check(self, repo_name):
 
        c.repo = repo_name
 
        task_id = request.GET.get('task_id')
 

	
 
        if task_id and task_id not in ['None']:
 
            if kallithea.CELERY_APP:
 
                task_result = celery.result.AsyncResult(task_id, app=kallithea.CELERY_APP)
 
                if task_result.failed():
 
                    raise HTTPInternalServerError(task_result.traceback)
 

	
 
        repo = Repository.get_by_repo_name(repo_name)
 
        if repo and repo.repo_state == Repository.STATE_CREATED:
 
        repo = db.Repository.get_by_repo_name(repo_name)
 
        if repo and repo.repo_state == db.Repository.STATE_CREATED:
 
            if repo.clone_uri:
 
                h.flash(_('Created repository %s from %s')
 
                webutils.flash(_('Created repository %s from %s')
 
                        % (repo.repo_name, repo.clone_uri_hidden), category='success')
 
            else:
 
                repo_url = h.link_to(repo.repo_name,
 
                                     h.url('summary_home',
 
                repo_url = webutils.link_to(repo.repo_name,
 
                                     webutils.url('summary_home',
 
                                           repo_name=repo.repo_name))
 
                fork = repo.fork
 
                if fork is not None:
 
                    fork_name = fork.repo_name
 
                    h.flash(h.HTML(_('Forked repository %s as %s'))
 
                    webutils.flash(webutils.HTML(_('Forked repository %s as %s'))
 
                            % (fork_name, repo_url), category='success')
 
                else:
 
                    h.flash(h.HTML(_('Created repository %s')) % repo_url,
 
                    webutils.flash(webutils.HTML(_('Created repository %s')) % repo_url,
 
                            category='success')
 
            return {'result': True}
 
        return {'result': False}
 
@@ -214,12 +190,12 @@ class ReposController(BaseRepoController
 
        c.repo_info = self._load_repo()
 
        self.__load_defaults(c.repo_info)
 
        c.active = 'settings'
 
        c.repo_fields = RepositoryField.query() \
 
            .filter(RepositoryField.repository == c.repo_info).all()
 
        c.repo_fields = db.RepositoryField.query() \
 
            .filter(db.RepositoryField.repository == c.repo_info).all()
 

	
 
        repo_model = RepoModel()
 
        changed_name = repo_name
 
        repo = Repository.get_by_repo_name(repo_name)
 
        repo = db.Repository.get_by_repo_name(repo_name)
 
        old_data = {
 
            'repo_name': repo_name,
 
            'repo_group': repo.group.get_dict() if repo.group else {},
 
@@ -233,18 +209,18 @@ class ReposController(BaseRepoController
 
            form_result = _form.to_python(dict(request.POST))
 
            repo = repo_model.update(repo_name, **form_result)
 
            ScmModel().mark_for_invalidation(repo_name)
 
            h.flash(_('Repository %s updated successfully') % repo_name,
 
            webutils.flash(_('Repository %s updated successfully') % repo_name,
 
                    category='success')
 
            changed_name = repo.repo_name
 
            action_logger(request.authuser, 'admin_updated_repo',
 
            userlog.action_logger(request.authuser, 'admin_updated_repo',
 
                changed_name, request.ip_addr)
 
            Session().commit()
 
            meta.Session().commit()
 
        except formencode.Invalid as errors:
 
            log.info(errors)
 
            defaults = self.__load_data()
 
            defaults.update(errors.value)
 
            return htmlfill.render(
 
                render('admin/repos/repo_edit.html'),
 
                base.render('admin/repos/repo_edit.html'),
 
                defaults=defaults,
 
                errors=errors.error_dict or {},
 
                prefix_error=False,
 
@@ -253,7 +229,7 @@ class ReposController(BaseRepoController
 

	
 
        except Exception:
 
            log.error(traceback.format_exc())
 
            h.flash(_('Error occurred during update of repository %s')
 
            webutils.flash(_('Error occurred during update of repository %s')
 
                    % repo_name, category='error')
 
        raise HTTPFound(location=url('edit_repo', repo_name=changed_name))
 

	
 
@@ -262,8 +238,7 @@ class ReposController(BaseRepoController
 
        repo_model = RepoModel()
 
        repo = repo_model.get_by_repo_name(repo_name)
 
        if not repo:
 
            h.not_mapped_error(repo_name)
 
            raise HTTPFound(location=url('repos'))
 
            raise HTTPNotFound()
 
        try:
 
            _forks = repo.forks.count()
 
            handle_forks = None
 
@@ -271,23 +246,23 @@ class ReposController(BaseRepoController
 
                do = request.POST['forks']
 
                if do == 'detach_forks':
 
                    handle_forks = 'detach'
 
                    h.flash(_('Detached %s forks') % _forks, category='success')
 
                    webutils.flash(_('Detached %s forks') % _forks, category='success')
 
                elif do == 'delete_forks':
 
                    handle_forks = 'delete'
 
                    h.flash(_('Deleted %s forks') % _forks, category='success')
 
                    webutils.flash(_('Deleted %s forks') % _forks, category='success')
 
            repo_model.delete(repo, forks=handle_forks)
 
            action_logger(request.authuser, 'admin_deleted_repo',
 
            userlog.action_logger(request.authuser, 'admin_deleted_repo',
 
                repo_name, request.ip_addr)
 
            ScmModel().mark_for_invalidation(repo_name)
 
            h.flash(_('Deleted repository %s') % repo_name, category='success')
 
            Session().commit()
 
            webutils.flash(_('Deleted repository %s') % repo_name, category='success')
 
            meta.Session().commit()
 
        except AttachedForksError:
 
            h.flash(_('Cannot delete repository %s which still has forks')
 
            webutils.flash(_('Cannot delete repository %s which still has forks')
 
                        % repo_name, category='warning')
 

	
 
        except Exception:
 
            log.error(traceback.format_exc())
 
            h.flash(_('An error occurred during deletion of %s') % repo_name,
 
            webutils.flash(_('An error occurred during deletion of %s') % repo_name,
 
                    category='error')
 

	
 
        if repo.group:
 
@@ -297,11 +272,11 @@ class ReposController(BaseRepoController
 
    @HasRepoPermissionLevelDecorator('admin')
 
    def edit(self, repo_name):
 
        defaults = self.__load_data()
 
        c.repo_fields = RepositoryField.query() \
 
            .filter(RepositoryField.repository == c.repo_info).all()
 
        c.repo_fields = db.RepositoryField.query() \
 
            .filter(db.RepositoryField.repository == c.repo_info).all()
 
        c.active = 'settings'
 
        return htmlfill.render(
 
            render('admin/repos/repo_edit.html'),
 
            base.render('admin/repos/repo_edit.html'),
 
            defaults=defaults,
 
            encoding="UTF-8",
 
            force_defaults=False)
 
@@ -313,7 +288,7 @@ class ReposController(BaseRepoController
 
        defaults = RepoModel()._get_defaults(repo_name)
 

	
 
        return htmlfill.render(
 
            render('admin/repos/repo_edit.html'),
 
            base.render('admin/repos/repo_edit.html'),
 
            defaults=defaults,
 
            encoding="UTF-8",
 
            force_defaults=False)
 
@@ -326,8 +301,8 @@ class ReposController(BaseRepoController
 
        # TODO: implement this
 
        #action_logger(request.authuser, 'admin_changed_repo_permissions',
 
        #              repo_name, request.ip_addr)
 
        Session().commit()
 
        h.flash(_('Repository permissions updated'), category='success')
 
        meta.Session().commit()
 
        webutils.flash(_('Repository permissions updated'), category='success')
 
        raise HTTPFound(location=url('edit_repo_perms', repo_name=repo_name))
 

	
 
    @HasRepoPermissionLevelDecorator('admin')
 
@@ -353,10 +328,10 @@ class ReposController(BaseRepoController
 
            # TODO: implement this
 
            #action_logger(request.authuser, 'admin_revoked_repo_permissions',
 
            #              repo_name, request.ip_addr)
 
            Session().commit()
 
            meta.Session().commit()
 
        except Exception:
 
            log.error(traceback.format_exc())
 
            h.flash(_('An error occurred during revoking of permission'),
 
            webutils.flash(_('An error occurred during revoking of permission'),
 
                    category='error')
 
            raise HTTPInternalServerError()
 
        return []
 
@@ -364,55 +339,55 @@ class ReposController(BaseRepoController
 
    @HasRepoPermissionLevelDecorator('admin')
 
    def edit_fields(self, repo_name):
 
        c.repo_info = self._load_repo()
 
        c.repo_fields = RepositoryField.query() \
 
            .filter(RepositoryField.repository == c.repo_info).all()
 
        c.repo_fields = db.RepositoryField.query() \
 
            .filter(db.RepositoryField.repository == c.repo_info).all()
 
        c.active = 'fields'
 
        if request.POST:
 

	
 
            raise HTTPFound(location=url('repo_edit_fields'))
 
        return render('admin/repos/repo_edit.html')
 
        return base.render('admin/repos/repo_edit.html')
 

	
 
    @HasRepoPermissionLevelDecorator('admin')
 
    def create_repo_field(self, repo_name):
 
        try:
 
            form_result = RepoFieldForm()().to_python(dict(request.POST))
 
            new_field = RepositoryField()
 
            new_field.repository = Repository.get_by_repo_name(repo_name)
 
            new_field = db.RepositoryField()
 
            new_field.repository = db.Repository.get_by_repo_name(repo_name)
 
            new_field.field_key = form_result['new_field_key']
 
            new_field.field_type = form_result['new_field_type']  # python type
 
            new_field.field_value = form_result['new_field_value']  # set initial blank value
 
            new_field.field_desc = form_result['new_field_desc']
 
            new_field.field_label = form_result['new_field_label']
 
            Session().add(new_field)
 
            Session().commit()
 
            meta.Session().add(new_field)
 
            meta.Session().commit()
 
        except formencode.Invalid as e:
 
            h.flash(_('Field validation error: %s') % e.msg, category='error')
 
            webutils.flash(_('Field validation error: %s') % e.msg, category='error')
 
        except Exception as e:
 
            log.error(traceback.format_exc())
 
            h.flash(_('An error occurred during creation of field: %r') % e, category='error')
 
            webutils.flash(_('An error occurred during creation of field: %r') % e, category='error')
 
        raise HTTPFound(location=url('edit_repo_fields', repo_name=repo_name))
 

	
 
    @HasRepoPermissionLevelDecorator('admin')
 
    def delete_repo_field(self, repo_name, field_id):
 
        field = RepositoryField.get_or_404(field_id)
 
        field = db.RepositoryField.get_or_404(field_id)
 
        try:
 
            Session().delete(field)
 
            Session().commit()
 
            meta.Session().delete(field)
 
            meta.Session().commit()
 
        except Exception as e:
 
            log.error(traceback.format_exc())
 
            msg = _('An error occurred during removal of field')
 
            h.flash(msg, category='error')
 
            webutils.flash(msg, category='error')
 
        raise HTTPFound(location=url('edit_repo_fields', repo_name=repo_name))
 

	
 
    @HasRepoPermissionLevelDecorator('admin')
 
    def edit_advanced(self, repo_name):
 
        c.repo_info = self._load_repo()
 
        c.default_user_id = kallithea.DEFAULT_USER_ID
 
        c.in_public_journal = UserFollowing.query() \
 
            .filter(UserFollowing.user_id == c.default_user_id) \
 
            .filter(UserFollowing.follows_repository == c.repo_info).scalar()
 
        c.in_public_journal = db.UserFollowing.query() \
 
            .filter(db.UserFollowing.user_id == c.default_user_id) \
 
            .filter(db.UserFollowing.follows_repository == c.repo_info).scalar()
 

	
 
        _repos = Repository.query(sorted=True).all()
 
        _repos = db.Repository.query(sorted=True).all()
 
        read_access_repos = RepoList(_repos, perm_level='read')
 
        c.repos_list = [(None, _('-- Not a fork --'))]
 
        c.repos_list += [(x.repo_id, x.repo_name)
 
@@ -428,7 +403,7 @@ class ReposController(BaseRepoController
 
        if request.POST:
 
            raise HTTPFound(location=url('repo_edit_advanced'))
 
        return htmlfill.render(
 
            render('admin/repos/repo_edit.html'),
 
            base.render('admin/repos/repo_edit.html'),
 
            defaults=defaults,
 
            encoding="UTF-8",
 
            force_defaults=False)
 
@@ -443,14 +418,14 @@ class ReposController(BaseRepoController
 
        """
 

	
 
        try:
 
            repo_id = Repository.get_by_repo_name(repo_name).repo_id
 
            repo_id = db.Repository.get_by_repo_name(repo_name).repo_id
 
            user_id = kallithea.DEFAULT_USER_ID
 
            self.scm_model.toggle_following_repo(repo_id, user_id)
 
            h.flash(_('Updated repository visibility in public journal'),
 
            webutils.flash(_('Updated repository visibility in public journal'),
 
                    category='success')
 
            Session().commit()
 
            meta.Session().commit()
 
        except Exception:
 
            h.flash(_('An error occurred during setting this'
 
            webutils.flash(_('An error occurred during setting this'
 
                      ' repository in public journal'),
 
                    category='error')
 
        raise HTTPFound(location=url('edit_repo_advanced', repo_name=repo_name))
 
@@ -467,15 +442,15 @@ class ReposController(BaseRepoController
 
            repo = ScmModel().mark_as_fork(repo_name, fork_id,
 
                                           request.authuser.username)
 
            fork = repo.fork.repo_name if repo.fork else _('Nothing')
 
            Session().commit()
 
            h.flash(_('Marked repository %s as fork of %s') % (repo_name, fork),
 
            meta.Session().commit()
 
            webutils.flash(_('Marked repository %s as fork of %s') % (repo_name, fork),
 
                    category='success')
 
        except RepositoryError as e:
 
            log.error(traceback.format_exc())
 
            h.flash(e, category='error')
 
            webutils.flash(e, category='error')
 
        except Exception as e:
 
            log.error(traceback.format_exc())
 
            h.flash(_('An error occurred during this operation'),
 
            webutils.flash(_('An error occurred during this operation'),
 
                    category='error')
 

	
 
        raise HTTPFound(location=url('edit_repo_advanced', repo_name=repo_name))
 
@@ -487,13 +462,13 @@ class ReposController(BaseRepoController
 
        if request.POST:
 
            try:
 
                ScmModel().pull_changes(repo_name, request.authuser.username, request.ip_addr)
 
                h.flash(_('Pulled from remote location'), category='success')
 
                webutils.flash(_('Pulled from remote location'), category='success')
 
            except Exception as e:
 
                log.error(traceback.format_exc())
 
                h.flash(_('An error occurred during pull from remote location'),
 
                webutils.flash(_('An error occurred during pull from remote location'),
 
                        category='error')
 
            raise HTTPFound(location=url('edit_repo_remote', repo_name=c.repo_name))
 
        return render('admin/repos/repo_edit.html')
 
        return base.render('admin/repos/repo_edit.html')
 

	
 
    @HasRepoPermissionLevelDecorator('admin')
 
    def edit_statistics(self, repo_name):
 
@@ -518,11 +493,11 @@ class ReposController(BaseRepoController
 
        if request.POST:
 
            try:
 
                RepoModel().delete_stats(repo_name)
 
                Session().commit()
 
                meta.Session().commit()
 
            except Exception as e:
 
                log.error(traceback.format_exc())
 
                h.flash(_('An error occurred during deletion of repository stats'),
 
                webutils.flash(_('An error occurred during deletion of repository stats'),
 
                        category='error')
 
            raise HTTPFound(location=url('edit_repo_statistics', repo_name=c.repo_name))
 

	
 
        return render('admin/repos/repo_edit.html')
 
        return base.render('admin/repos/repo_edit.html')
kallithea/controllers/admin/settings.py
Show inline comments
 
@@ -35,18 +35,17 @@ from tg import tmpl_context as c
 
from tg.i18n import ugettext as _
 
from webob.exc import HTTPFound
 

	
 
from kallithea.config.routing import url
 
from kallithea.lib import helpers as h
 
import kallithea
 
import kallithea.lib.indexers.daemon
 
from kallithea.controllers import base
 
from kallithea.lib import webutils
 
from kallithea.lib.auth import HasPermissionAnyDecorator, LoginRequired
 
from kallithea.lib.base import BaseController, render
 
from kallithea.lib.celerylib import tasks
 
from kallithea.lib.exceptions import HgsubversionImportError
 
from kallithea.lib.utils import repo2db_mapper, set_app_settings
 
from kallithea.lib.utils2 import safe_str
 
from kallithea.lib.vcs import VCSError
 
from kallithea.model.db import Repository, Setting, Ui
 
from kallithea.lib.webutils import url
 
from kallithea.model import db, meta, notification
 
from kallithea.model.forms import ApplicationSettingsForm, ApplicationUiSettingsForm, ApplicationVisualisationForm
 
from kallithea.model.meta import Session
 
from kallithea.model.notification import EmailNotificationModel
 
from kallithea.model.scm import ScmModel
 

	
 
@@ -54,19 +53,14 @@ from kallithea.model.scm import ScmModel
 
log = logging.getLogger(__name__)
 

	
 

	
 
class SettingsController(BaseController):
 
    """REST Controller styled on the Atom Publishing Protocol"""
 
    # To properly map this controller, ensure your config/routing.py
 
    # file has a resource setup:
 
    #     map.resource('setting', 'settings', controller='admin/settings',
 
    #         path_prefix='/admin', name_prefix='admin_')
 
class SettingsController(base.BaseController):
 

	
 
    @LoginRequired(allow_default_user=True)
 
    def _before(self, *args, **kwargs):
 
        super(SettingsController, self)._before(*args, **kwargs)
 

	
 
    def _get_hg_ui_settings(self):
 
        ret = Ui.query().all()
 
        ret = db.Ui.query().all()
 

	
 
        settings = {}
 
        for each in ret:
 
@@ -92,7 +86,7 @@ class SettingsController(BaseController)
 
                form_result = application_form.to_python(dict(request.POST))
 
            except formencode.Invalid as errors:
 
                return htmlfill.render(
 
                     render('admin/settings/settings.html'),
 
                     base.render('admin/settings/settings.html'),
 
                     defaults=errors.value,
 
                     errors=errors.error_dict or {},
 
                     prefix_error=False,
 
@@ -101,52 +95,37 @@ class SettingsController(BaseController)
 

	
 
            try:
 
                if c.visual.allow_repo_location_change:
 
                    sett = Ui.get_by_key('paths', '/')
 
                    sett = db.Ui.get_by_key('paths', '/')
 
                    sett.ui_value = form_result['paths_root_path']
 

	
 
                # HOOKS
 
                sett = Ui.get_by_key('hooks', Ui.HOOK_UPDATE)
 
                sett.ui_active = form_result['hooks_changegroup_update']
 
                sett = db.Ui.get_by_key('hooks', db.Ui.HOOK_UPDATE)
 
                sett.ui_active = form_result['hooks_changegroup_kallithea_update']
 

	
 
                sett = Ui.get_by_key('hooks', Ui.HOOK_REPO_SIZE)
 
                sett.ui_active = form_result['hooks_changegroup_repo_size']
 
                sett = db.Ui.get_by_key('hooks', db.Ui.HOOK_REPO_SIZE)
 
                sett.ui_active = form_result['hooks_changegroup_kallithea_repo_size']
 

	
 
                ## EXTENSIONS
 
                sett = Ui.get_or_create('extensions', 'largefiles')
 
                sett = db.Ui.get_or_create('extensions', 'largefiles')
 
                sett.ui_active = form_result['extensions_largefiles']
 

	
 
                sett = Ui.get_or_create('extensions', 'hgsubversion')
 
                sett.ui_active = form_result['extensions_hgsubversion']
 
                if sett.ui_active:
 
                    try:
 
                        import hgsubversion  # pragma: no cover
 
                        assert hgsubversion
 
                    except ImportError:
 
                        raise HgsubversionImportError
 

	
 
#                sett = Ui.get_or_create('extensions', 'hggit')
 
#                sett = db.Ui.get_or_create('extensions', 'hggit')
 
#                sett.ui_active = form_result['extensions_hggit']
 

	
 
                Session().commit()
 

	
 
                h.flash(_('Updated VCS settings'), category='success')
 
                meta.Session().commit()
 

	
 
            except HgsubversionImportError:
 
                log.error(traceback.format_exc())
 
                h.flash(_('Unable to activate hgsubversion support. '
 
                          'The "hgsubversion" library is missing'),
 
                        category='error')
 
                webutils.flash(_('Updated VCS settings'), category='success')
 

	
 
            except Exception:
 
                log.error(traceback.format_exc())
 
                h.flash(_('Error occurred while updating '
 
                webutils.flash(_('Error occurred while updating '
 
                          'application settings'), category='error')
 

	
 
        defaults = Setting.get_app_settings()
 
        defaults = db.Setting.get_app_settings()
 
        defaults.update(self._get_hg_ui_settings())
 

	
 
        return htmlfill.render(
 
            render('admin/settings/settings.html'),
 
            base.render('admin/settings/settings.html'),
 
            defaults=defaults,
 
            encoding="UTF-8",
 
            force_defaults=False)
 
@@ -168,33 +147,33 @@ class SettingsController(BaseController)
 
                                            install_git_hooks=install_git_hooks,
 
                                            user=request.authuser.username,
 
                                            overwrite_git_hooks=overwrite_git_hooks)
 
            added_msg = h.HTML(', ').join(
 
                h.link_to(safe_str(repo_name), h.url('summary_home', repo_name=repo_name)) for repo_name in added
 
            added_msg = webutils.HTML(', ').join(
 
                webutils.link_to(safe_str(repo_name), webutils.url('summary_home', repo_name=repo_name)) for repo_name in added
 
            ) or '-'
 
            removed_msg = h.HTML(', ').join(
 
            removed_msg = webutils.HTML(', ').join(
 
                safe_str(repo_name) for repo_name in removed
 
            ) or '-'
 
            h.flash(h.HTML(_('Repositories successfully rescanned. Added: %s. Removed: %s.')) %
 
            webutils.flash(webutils.HTML(_('Repositories successfully rescanned. Added: %s. Removed: %s.')) %
 
                    (added_msg, removed_msg), category='success')
 

	
 
            if invalidate_cache:
 
                log.debug('invalidating all repositories cache')
 
                i = 0
 
                for repo in Repository.query():
 
                for repo in db.Repository.query():
 
                    try:
 
                        ScmModel().mark_for_invalidation(repo.repo_name)
 
                        i += 1
 
                    except VCSError as e:
 
                        log.warning('VCS error invalidating %s: %s', repo.repo_name, e)
 
                h.flash(_('Invalidated %s repositories') % i, category='success')
 
                webutils.flash(_('Invalidated %s repositories') % i, category='success')
 

	
 
            raise HTTPFound(location=url('admin_settings_mapping'))
 

	
 
        defaults = Setting.get_app_settings()
 
        defaults = db.Setting.get_app_settings()
 
        defaults.update(self._get_hg_ui_settings())
 

	
 
        return htmlfill.render(
 
            render('admin/settings/settings.html'),
 
            base.render('admin/settings/settings.html'),
 
            defaults=defaults,
 
            encoding="UTF-8",
 
            force_defaults=False)
 
@@ -208,7 +187,7 @@ class SettingsController(BaseController)
 
                form_result = application_form.to_python(dict(request.POST))
 
            except formencode.Invalid as errors:
 
                return htmlfill.render(
 
                    render('admin/settings/settings.html'),
 
                    base.render('admin/settings/settings.html'),
 
                    defaults=errors.value,
 
                    errors=errors.error_dict or {},
 
                    prefix_error=False,
 
@@ -223,25 +202,25 @@ class SettingsController(BaseController)
 
                    'captcha_public_key',
 
                    'captcha_private_key',
 
                ):
 
                    Setting.create_or_update(setting, form_result[setting])
 
                    db.Setting.create_or_update(setting, form_result[setting])
 

	
 
                Session().commit()
 
                meta.Session().commit()
 
                set_app_settings(config)
 
                h.flash(_('Updated application settings'), category='success')
 
                webutils.flash(_('Updated application settings'), category='success')
 

	
 
            except Exception:
 
                log.error(traceback.format_exc())
 
                h.flash(_('Error occurred while updating '
 
                webutils.flash(_('Error occurred while updating '
 
                          'application settings'),
 
                          category='error')
 

	
 
            raise HTTPFound(location=url('admin_settings_global'))
 

	
 
        defaults = Setting.get_app_settings()
 
        defaults = db.Setting.get_app_settings()
 
        defaults.update(self._get_hg_ui_settings())
 

	
 
        return htmlfill.render(
 
            render('admin/settings/settings.html'),
 
            base.render('admin/settings/settings.html'),
 
            defaults=defaults,
 
            encoding="UTF-8",
 
            force_defaults=False)
 
@@ -255,7 +234,7 @@ class SettingsController(BaseController)
 
                form_result = application_form.to_python(dict(request.POST))
 
            except formencode.Invalid as errors:
 
                return htmlfill.render(
 
                    render('admin/settings/settings.html'),
 
                    base.render('admin/settings/settings.html'),
 
                    defaults=errors.value,
 
                    errors=errors.error_dict or {},
 
                    prefix_error=False,
 
@@ -277,26 +256,26 @@ class SettingsController(BaseController)
 
                    ('clone_ssh_tmpl', 'clone_ssh_tmpl', 'unicode'),
 
                ]
 
                for setting, form_key, type_ in settings:
 
                    Setting.create_or_update(setting, form_result[form_key], type_)
 
                    db.Setting.create_or_update(setting, form_result[form_key], type_)
 

	
 
                Session().commit()
 
                meta.Session().commit()
 
                set_app_settings(config)
 
                h.flash(_('Updated visualisation settings'),
 
                webutils.flash(_('Updated visualisation settings'),
 
                        category='success')
 

	
 
            except Exception:
 
                log.error(traceback.format_exc())
 
                h.flash(_('Error occurred during updating '
 
                webutils.flash(_('Error occurred during updating '
 
                          'visualisation settings'),
 
                        category='error')
 

	
 
            raise HTTPFound(location=url('admin_settings_visual'))
 

	
 
        defaults = Setting.get_app_settings()
 
        defaults = db.Setting.get_app_settings()
 
        defaults.update(self._get_hg_ui_settings())
 

	
 
        return htmlfill.render(
 
            render('admin/settings/settings.html'),
 
            base.render('admin/settings/settings.html'),
 
            defaults=defaults,
 
            encoding="UTF-8",
 
            force_defaults=False)
 
@@ -310,7 +289,7 @@ class SettingsController(BaseController)
 
            test_body = ('Kallithea Email test, '
 
                               'Kallithea version: %s' % c.kallithea_version)
 
            if not test_email:
 
                h.flash(_('Please enter email address'), category='error')
 
                webutils.flash(_('Please enter email address'), category='error')
 
                raise HTTPFound(location=url('admin_settings_email'))
 

	
 
            test_email_txt_body = EmailNotificationModel() \
 
@@ -322,20 +301,19 @@ class SettingsController(BaseController)
 

	
 
            recipients = [test_email] if test_email else None
 

	
 
            tasks.send_email(recipients, test_email_subj,
 
            notification.send_email(recipients, test_email_subj,
 
                             test_email_txt_body, test_email_html_body)
 

	
 
            h.flash(_('Send email task created'), category='success')
 
            webutils.flash(_('Send email task created'), category='success')
 
            raise HTTPFound(location=url('admin_settings_email'))
 

	
 
        defaults = Setting.get_app_settings()
 
        defaults = db.Setting.get_app_settings()
 
        defaults.update(self._get_hg_ui_settings())
 

	
 
        import kallithea
 
        c.ini = kallithea.CONFIG
 

	
 
        return htmlfill.render(
 
            render('admin/settings/settings.html'),
 
            base.render('admin/settings/settings.html'),
 
            defaults=defaults,
 
            encoding="UTF-8",
 
            force_defaults=False)
 
@@ -352,16 +330,16 @@ class SettingsController(BaseController)
 

	
 
                try:
 
                    ui_key = ui_key and ui_key.strip()
 
                    if ui_key in (x.ui_key for x in Ui.get_custom_hooks()):
 
                        h.flash(_('Hook already exists'), category='error')
 
                    elif ui_key in (x.ui_key for x in Ui.get_builtin_hooks()):
 
                        h.flash(_('Builtin hooks are read-only. Please use another hook name.'), category='error')
 
                    if ui_key in (x.ui_key for x in db.Ui.get_custom_hooks()):
 
                        webutils.flash(_('Hook already exists'), category='error')
 
                    elif ui_key and '.kallithea_' in ui_key:
 
                        webutils.flash(_('Hook names with ".kallithea_" are reserved for internal use. Please use another hook name.'), category='error')
 
                    elif ui_value and ui_key:
 
                        Ui.create_or_update_hook(ui_key, ui_value)
 
                        h.flash(_('Added new hook'), category='success')
 
                        db.Ui.create_or_update_hook(ui_key, ui_value)
 
                        webutils.flash(_('Added new hook'), category='success')
 
                    elif hook_id:
 
                        Ui.delete(hook_id)
 
                        Session().commit()
 
                        db.Ui.delete(hook_id)
 
                        meta.Session().commit()
 

	
 
                    # check for edits
 
                    update = False
 
@@ -370,27 +348,26 @@ class SettingsController(BaseController)
 
                                        _d.get('hook_ui_value_new', []),
 
                                        _d.get('hook_ui_value', [])):
 
                        if v != ov:
 
                            Ui.create_or_update_hook(k, v)
 
                            db.Ui.create_or_update_hook(k, v)
 
                            update = True
 

	
 
                    if update:
 
                        h.flash(_('Updated hooks'), category='success')
 
                    Session().commit()
 
                        webutils.flash(_('Updated hooks'), category='success')
 
                    meta.Session().commit()
 
                except Exception:
 
                    log.error(traceback.format_exc())
 
                    h.flash(_('Error occurred during hook creation'),
 
                    webutils.flash(_('Error occurred during hook creation'),
 
                            category='error')
 

	
 
                raise HTTPFound(location=url('admin_settings_hooks'))
 

	
 
        defaults = Setting.get_app_settings()
 
        defaults = db.Setting.get_app_settings()
 
        defaults.update(self._get_hg_ui_settings())
 

	
 
        c.hooks = Ui.get_builtin_hooks()
 
        c.custom_hooks = Ui.get_custom_hooks()
 
        c.custom_hooks = db.Ui.get_custom_hooks()
 

	
 
        return htmlfill.render(
 
            render('admin/settings/settings.html'),
 
            base.render('admin/settings/settings.html'),
 
            defaults=defaults,
 
            encoding="UTF-8",
 
            force_defaults=False)
 
@@ -401,15 +378,15 @@ class SettingsController(BaseController)
 
        if request.POST:
 
            repo_location = self._get_hg_ui_settings()['paths_root_path']
 
            full_index = request.POST.get('full_index', False)
 
            tasks.whoosh_index(repo_location, full_index)
 
            h.flash(_('Whoosh reindex task scheduled'), category='success')
 
            kallithea.lib.indexers.daemon.whoosh_index(repo_location, full_index)
 
            webutils.flash(_('Whoosh reindex task scheduled'), category='success')
 
            raise HTTPFound(location=url('admin_settings_search'))
 

	
 
        defaults = Setting.get_app_settings()
 
        defaults = db.Setting.get_app_settings()
 
        defaults.update(self._get_hg_ui_settings())
 

	
 
        return htmlfill.render(
 
            render('admin/settings/settings.html'),
 
            base.render('admin/settings/settings.html'),
 
            defaults=defaults,
 
            encoding="UTF-8",
 
            force_defaults=False)
 
@@ -418,17 +395,16 @@ class SettingsController(BaseController)
 
    def settings_system(self):
 
        c.active = 'system'
 

	
 
        defaults = Setting.get_app_settings()
 
        defaults = db.Setting.get_app_settings()
 
        defaults.update(self._get_hg_ui_settings())
 

	
 
        import kallithea
 
        c.ini = kallithea.CONFIG
 
        server_info = Setting.get_server_info()
 
        server_info = db.Setting.get_server_info()
 
        for key, val in server_info.items():
 
            setattr(c, key, val)
 

	
 
        return htmlfill.render(
 
            render('admin/settings/settings.html'),
 
            base.render('admin/settings/settings.html'),
 
            defaults=defaults,
 
            encoding="UTF-8",
 
            force_defaults=False)
kallithea/controllers/admin/user_groups.py
Show inline comments
 
@@ -37,16 +37,15 @@ from tg import tmpl_context as c
 
from tg.i18n import ugettext as _
 
from webob.exc import HTTPFound, HTTPInternalServerError
 

	
 
from kallithea.config.routing import url
 
from kallithea.lib import helpers as h
 
import kallithea.lib.helpers as h
 
from kallithea.controllers import base
 
from kallithea.lib import webutils
 
from kallithea.lib.auth import HasPermissionAnyDecorator, HasUserGroupPermissionLevelDecorator, LoginRequired
 
from kallithea.lib.base import BaseController, render
 
from kallithea.lib.exceptions import RepoGroupAssignmentError, UserGroupsAssignedException
 
from kallithea.lib.utils import action_logger
 
from kallithea.lib.utils2 import safe_int, safe_str
 
from kallithea.model.db import User, UserGroup, UserGroupRepoGroupToPerm, UserGroupRepoToPerm, UserGroupToPerm
 
from kallithea.lib.webutils import url
 
from kallithea.model import db, meta, userlog
 
from kallithea.model.forms import CustomDefaultPermissionsForm, UserGroupForm, UserGroupPermsForm
 
from kallithea.model.meta import Session
 
from kallithea.model.scm import UserGroupList
 
from kallithea.model.user_group import UserGroupModel
 

	
 
@@ -54,8 +53,7 @@ from kallithea.model.user_group import U
 
log = logging.getLogger(__name__)
 

	
 

	
 
class UserGroupsController(BaseController):
 
    """REST Controller styled on the Atom Publishing Protocol"""
 
class UserGroupsController(base.BaseController):
 

	
 
    @LoginRequired(allow_default_user=True)
 
    def _before(self, *args, **kwargs):
 
@@ -67,7 +65,7 @@ class UserGroupsController(BaseControlle
 

	
 
        c.group_members = [(x.user_id, x.username) for x in c.group_members_obj]
 
        c.available_members = sorted(((x.user_id, x.username) for x in
 
                                      User.query().all()),
 
                                      db.User.query().all()),
 
                                     key=lambda u: u[1].lower())
 

	
 
    def __load_defaults(self, user_group_id):
 
@@ -76,13 +74,13 @@ class UserGroupsController(BaseControlle
 

	
 
        :param user_group_id:
 
        """
 
        user_group = UserGroup.get_or_404(user_group_id)
 
        user_group = db.UserGroup.get_or_404(user_group_id)
 
        data = user_group.get_dict()
 
        return data
 

	
 
    def index(self, format='html'):
 
        _list = UserGroup.query() \
 
                        .order_by(func.lower(UserGroup.users_group_name)) \
 
        _list = db.UserGroup.query() \
 
                        .order_by(func.lower(db.UserGroup.users_group_name)) \
 
                        .all()
 
        group_iter = UserGroupList(_list, perm_level='admin')
 
        user_groups_data = []
 
@@ -91,21 +89,21 @@ class UserGroupsController(BaseControlle
 

	
 
        def user_group_name(user_group_id, user_group_name):
 
            return template.get_def("user_group_name") \
 
                .render_unicode(user_group_id, user_group_name, _=_, h=h, c=c)
 
                .render_unicode(user_group_id, user_group_name, _=_, webutils=webutils, c=c)
 

	
 
        def user_group_actions(user_group_id, user_group_name):
 
            return template.get_def("user_group_actions") \
 
                .render_unicode(user_group_id, user_group_name, _=_, h=h, c=c)
 
                .render_unicode(user_group_id, user_group_name, _=_, webutils=webutils, c=c)
 

	
 
        for user_gr in group_iter:
 
            user_groups_data.append({
 
                "raw_name": user_gr.users_group_name,
 
                "group_name": user_group_name(user_gr.users_group_id,
 
                                              user_gr.users_group_name),
 
                "desc": h.escape(user_gr.user_group_description),
 
                "desc": webutils.escape(user_gr.user_group_description),
 
                "members": len(user_gr.members),
 
                "active": h.boolicon(user_gr.users_group_active),
 
                "owner": h.person(user_gr.owner.username),
 
                "owner": user_gr.owner.username,
 
                "action": user_group_actions(user_gr.users_group_id, user_gr.users_group_name)
 
            })
 

	
 
@@ -115,7 +113,7 @@ class UserGroupsController(BaseControlle
 
            "records": user_groups_data
 
        }
 

	
 
        return render('admin/user_groups/user_groups.html')
 
        return base.render('admin/user_groups/user_groups.html')
 

	
 
    @HasPermissionAnyDecorator('hg.admin', 'hg.usergroup.create.true')
 
    def create(self):
 
@@ -128,15 +126,15 @@ class UserGroupsController(BaseControlle
 
                                         active=form_result['users_group_active'])
 

	
 
            gr = form_result['users_group_name']
 
            action_logger(request.authuser,
 
            userlog.action_logger(request.authuser,
 
                          'admin_created_users_group:%s' % gr,
 
                          None, request.ip_addr)
 
            h.flash(h.HTML(_('Created user group %s')) % h.link_to(gr, url('edit_users_group', id=ug.users_group_id)),
 
            webutils.flash(webutils.HTML(_('Created user group %s')) % webutils.link_to(gr, url('edit_users_group', id=ug.users_group_id)),
 
                category='success')
 
            Session().commit()
 
            meta.Session().commit()
 
        except formencode.Invalid as errors:
 
            return htmlfill.render(
 
                render('admin/user_groups/user_group_add.html'),
 
                base.render('admin/user_groups/user_group_add.html'),
 
                defaults=errors.value,
 
                errors=errors.error_dict or {},
 
                prefix_error=False,
 
@@ -144,18 +142,18 @@ class UserGroupsController(BaseControlle
 
                force_defaults=False)
 
        except Exception:
 
            log.error(traceback.format_exc())
 
            h.flash(_('Error occurred during creation of user group %s')
 
            webutils.flash(_('Error occurred during creation of user group %s')
 
                    % request.POST.get('users_group_name'), category='error')
 

	
 
        raise HTTPFound(location=url('users_groups'))
 

	
 
    @HasPermissionAnyDecorator('hg.admin', 'hg.usergroup.create.true')
 
    def new(self, format='html'):
 
        return render('admin/user_groups/user_group_add.html')
 
        return base.render('admin/user_groups/user_group_add.html')
 

	
 
    @HasUserGroupPermissionLevelDecorator('admin')
 
    def update(self, id):
 
        c.user_group = UserGroup.get_or_404(id)
 
        c.user_group = db.UserGroup.get_or_404(id)
 
        c.active = 'settings'
 
        self.__load_data(id)
 

	
 
@@ -169,11 +167,11 @@ class UserGroupsController(BaseControlle
 
            form_result = users_group_form.to_python(request.POST)
 
            UserGroupModel().update(c.user_group, form_result)
 
            gr = form_result['users_group_name']
 
            action_logger(request.authuser,
 
            userlog.action_logger(request.authuser,
 
                          'admin_updated_users_group:%s' % gr,
 
                          None, request.ip_addr)
 
            h.flash(_('Updated user group %s') % gr, category='success')
 
            Session().commit()
 
            webutils.flash(_('Updated user group %s') % gr, category='success')
 
            meta.Session().commit()
 
        except formencode.Invalid as errors:
 
            ug_model = UserGroupModel()
 
            defaults = errors.value
 
@@ -186,7 +184,7 @@ class UserGroupsController(BaseControlle
 
            })
 

	
 
            return htmlfill.render(
 
                render('admin/user_groups/user_group_edit.html'),
 
                base.render('admin/user_groups/user_group_edit.html'),
 
                defaults=defaults,
 
                errors=e,
 
                prefix_error=False,
 
@@ -194,36 +192,36 @@ class UserGroupsController(BaseControlle
 
                force_defaults=False)
 
        except Exception:
 
            log.error(traceback.format_exc())
 
            h.flash(_('Error occurred during update of user group %s')
 
            webutils.flash(_('Error occurred during update of user group %s')
 
                    % request.POST.get('users_group_name'), category='error')
 

	
 
        raise HTTPFound(location=url('edit_users_group', id=id))
 

	
 
    @HasUserGroupPermissionLevelDecorator('admin')
 
    def delete(self, id):
 
        usr_gr = UserGroup.get_or_404(id)
 
        usr_gr = db.UserGroup.get_or_404(id)
 
        try:
 
            UserGroupModel().delete(usr_gr)
 
            Session().commit()
 
            h.flash(_('Successfully deleted user group'), category='success')
 
            meta.Session().commit()
 
            webutils.flash(_('Successfully deleted user group'), category='success')
 
        except UserGroupsAssignedException as e:
 
            h.flash(e, category='error')
 
            webutils.flash(e, category='error')
 
        except Exception:
 
            log.error(traceback.format_exc())
 
            h.flash(_('An error occurred during deletion of user group'),
 
            webutils.flash(_('An error occurred during deletion of user group'),
 
                    category='error')
 
        raise HTTPFound(location=url('users_groups'))
 

	
 
    @HasUserGroupPermissionLevelDecorator('admin')
 
    def edit(self, id, format='html'):
 
        c.user_group = UserGroup.get_or_404(id)
 
        c.user_group = db.UserGroup.get_or_404(id)
 
        c.active = 'settings'
 
        self.__load_data(id)
 

	
 
        defaults = self.__load_defaults(id)
 

	
 
        return htmlfill.render(
 
            render('admin/user_groups/user_group_edit.html'),
 
            base.render('admin/user_groups/user_group_edit.html'),
 
            defaults=defaults,
 
            encoding="UTF-8",
 
            force_defaults=False
 
@@ -231,7 +229,7 @@ class UserGroupsController(BaseControlle
 

	
 
    @HasUserGroupPermissionLevelDecorator('admin')
 
    def edit_perms(self, id):
 
        c.user_group = UserGroup.get_or_404(id)
 
        c.user_group = db.UserGroup.get_or_404(id)
 
        c.active = 'perms'
 

	
 
        defaults = {}
 
@@ -245,7 +243,7 @@ class UserGroupsController(BaseControlle
 
                             p.permission.permission_name})
 

	
 
        return htmlfill.render(
 
            render('admin/user_groups/user_group_edit.html'),
 
            base.render('admin/user_groups/user_group_edit.html'),
 
            defaults=defaults,
 
            encoding="UTF-8",
 
            force_defaults=False
 
@@ -258,7 +256,7 @@ class UserGroupsController(BaseControlle
 

	
 
        :param id:
 
        """
 
        user_group = UserGroup.get_or_404(id)
 
        user_group = db.UserGroup.get_or_404(id)
 
        form = UserGroupPermsForm()().to_python(request.POST)
 

	
 
        # set the permissions !
 
@@ -266,13 +264,13 @@ class UserGroupsController(BaseControlle
 
            UserGroupModel()._update_permissions(user_group, form['perms_new'],
 
                                                 form['perms_updates'])
 
        except RepoGroupAssignmentError:
 
            h.flash(_('Target group cannot be the same'), category='error')
 
            webutils.flash(_('Target group cannot be the same'), category='error')
 
            raise HTTPFound(location=url('edit_user_group_perms', id=id))
 
        # TODO: implement this
 
        #action_logger(request.authuser, 'admin_changed_repo_permissions',
 
        #              repo_name, request.ip_addr)
 
        Session().commit()
 
        h.flash(_('User group permissions updated'), category='success')
 
        meta.Session().commit()
 
        webutils.flash(_('User group permissions updated'), category='success')
 
        raise HTTPFound(location=url('edit_user_group_perms', id=id))
 

	
 
    @HasUserGroupPermissionLevelDecorator('admin')
 
@@ -288,7 +286,7 @@ class UserGroupsController(BaseControlle
 
            if not request.authuser.is_admin:
 
                if obj_type == 'user' and request.authuser.user_id == obj_id:
 
                    msg = _('Cannot revoke permission for yourself as admin')
 
                    h.flash(msg, category='warning')
 
                    webutils.flash(msg, category='warning')
 
                    raise Exception('revoke admin permission on self')
 
            if obj_type == 'user':
 
                UserGroupModel().revoke_user_permission(user_group=id,
 
@@ -296,36 +294,36 @@ class UserGroupsController(BaseControlle
 
            elif obj_type == 'user_group':
 
                UserGroupModel().revoke_user_group_permission(target_user_group=id,
 
                                                              user_group=obj_id)
 
            Session().commit()
 
            meta.Session().commit()
 
        except Exception:
 
            log.error(traceback.format_exc())
 
            h.flash(_('An error occurred during revoking of permission'),
 
            webutils.flash(_('An error occurred during revoking of permission'),
 
                    category='error')
 
            raise HTTPInternalServerError()
 

	
 
    @HasUserGroupPermissionLevelDecorator('admin')
 
    def edit_default_perms(self, id):
 
        c.user_group = UserGroup.get_or_404(id)
 
        c.user_group = db.UserGroup.get_or_404(id)
 
        c.active = 'default_perms'
 

	
 
        permissions = {
 
            'repositories': {},
 
            'repositories_groups': {}
 
        }
 
        ugroup_repo_perms = UserGroupRepoToPerm.query() \
 
            .options(joinedload(UserGroupRepoToPerm.permission)) \
 
            .options(joinedload(UserGroupRepoToPerm.repository)) \
 
            .filter(UserGroupRepoToPerm.users_group_id == id) \
 
        ugroup_repo_perms = db.UserGroupRepoToPerm.query() \
 
            .options(joinedload(db.UserGroupRepoToPerm.permission)) \
 
            .options(joinedload(db.UserGroupRepoToPerm.repository)) \
 
            .filter(db.UserGroupRepoToPerm.users_group_id == id) \
 
            .all()
 

	
 
        for gr in ugroup_repo_perms:
 
            permissions['repositories'][gr.repository.repo_name]  \
 
                = gr.permission.permission_name
 

	
 
        ugroup_group_perms = UserGroupRepoGroupToPerm.query() \
 
            .options(joinedload(UserGroupRepoGroupToPerm.permission)) \
 
            .options(joinedload(UserGroupRepoGroupToPerm.group)) \
 
            .filter(UserGroupRepoGroupToPerm.users_group_id == id) \
 
        ugroup_group_perms = db.UserGroupRepoGroupToPerm.query() \
 
            .options(joinedload(db.UserGroupRepoGroupToPerm.permission)) \
 
            .options(joinedload(db.UserGroupRepoGroupToPerm.group)) \
 
            .filter(db.UserGroupRepoGroupToPerm.users_group_id == id) \
 
            .all()
 

	
 
        for gr in ugroup_group_perms:
 
@@ -346,7 +344,7 @@ class UserGroupsController(BaseControlle
 
        })
 

	
 
        return htmlfill.render(
 
            render('admin/user_groups/user_group_edit.html'),
 
            base.render('admin/user_groups/user_group_edit.html'),
 
            defaults=defaults,
 
            encoding="UTF-8",
 
            force_defaults=False
 
@@ -354,7 +352,7 @@ class UserGroupsController(BaseControlle
 

	
 
    @HasUserGroupPermissionLevelDecorator('admin')
 
    def update_default_perms(self, id):
 
        user_group = UserGroup.get_or_404(id)
 
        user_group = db.UserGroup.get_or_404(id)
 

	
 
        try:
 
            form = CustomDefaultPermissionsForm()()
 
@@ -362,11 +360,11 @@ class UserGroupsController(BaseControlle
 

	
 
            usergroup_model = UserGroupModel()
 

	
 
            defs = UserGroupToPerm.query() \
 
                .filter(UserGroupToPerm.users_group == user_group) \
 
            defs = db.UserGroupToPerm.query() \
 
                .filter(db.UserGroupToPerm.users_group == user_group) \
 
                .all()
 
            for ug in defs:
 
                Session().delete(ug)
 
                meta.Session().delete(ug)
 

	
 
            if form_result['create_repo_perm']:
 
                usergroup_model.grant_perm(id, 'hg.create.repository')
 
@@ -381,29 +379,29 @@ class UserGroupsController(BaseControlle
 
            else:
 
                usergroup_model.grant_perm(id, 'hg.fork.none')
 

	
 
            h.flash(_("Updated permissions"), category='success')
 
            Session().commit()
 
            webutils.flash(_("Updated permissions"), category='success')
 
            meta.Session().commit()
 
        except Exception:
 
            log.error(traceback.format_exc())
 
            h.flash(_('An error occurred during permissions saving'),
 
            webutils.flash(_('An error occurred during permissions saving'),
 
                    category='error')
 

	
 
        raise HTTPFound(location=url('edit_user_group_default_perms', id=id))
 

	
 
    @HasUserGroupPermissionLevelDecorator('admin')
 
    def edit_advanced(self, id):
 
        c.user_group = UserGroup.get_or_404(id)
 
        c.user_group = db.UserGroup.get_or_404(id)
 
        c.active = 'advanced'
 
        c.group_members_obj = sorted((x.user for x in c.user_group.members),
 
                                     key=lambda u: u.username.lower())
 
        return render('admin/user_groups/user_group_edit.html')
 
        return base.render('admin/user_groups/user_group_edit.html')
 

	
 
    @HasUserGroupPermissionLevelDecorator('admin')
 
    def edit_members(self, id):
 
        c.user_group = UserGroup.get_or_404(id)
 
        c.user_group = db.UserGroup.get_or_404(id)
 
        c.active = 'members'
 
        c.group_members_obj = sorted((x.user for x in c.user_group.members),
 
                                     key=lambda u: u.username.lower())
 

	
 
        c.group_members = [(x.user_id, x.username) for x in c.group_members_obj]
 
        return render('admin/user_groups/user_group_edit.html')
 
        return base.render('admin/user_groups/user_group_edit.html')
kallithea/controllers/admin/users.py
Show inline comments
 
@@ -37,18 +37,16 @@ from tg.i18n import ugettext as _
 
from webob.exc import HTTPFound, HTTPNotFound
 

	
 
import kallithea
 
from kallithea.config.routing import url
 
from kallithea.lib import auth_modules
 
from kallithea.lib import helpers as h
 
import kallithea.lib.helpers as h
 
from kallithea.controllers import base
 
from kallithea.lib import auth_modules, webutils
 
from kallithea.lib.auth import AuthUser, HasPermissionAnyDecorator, LoginRequired
 
from kallithea.lib.base import BaseController, IfSshEnabled, render
 
from kallithea.lib.exceptions import DefaultUserException, UserCreationError, UserOwnsReposException
 
from kallithea.lib.utils import action_logger
 
from kallithea.lib.utils2 import datetime_to_time, generate_api_key, safe_int
 
from kallithea.lib.webutils import fmt_date, url
 
from kallithea.model import db, meta, userlog
 
from kallithea.model.api_key import ApiKeyModel
 
from kallithea.model.db import User, UserEmailMap, UserIpMap, UserToPerm
 
from kallithea.model.forms import CustomDefaultPermissionsForm, UserForm
 
from kallithea.model.meta import Session
 
from kallithea.model.ssh_key import SshKeyModel, SshKeyModelException
 
from kallithea.model.user import UserModel
 

	
 
@@ -56,8 +54,7 @@ from kallithea.model.user import UserMod
 
log = logging.getLogger(__name__)
 

	
 

	
 
class UsersController(BaseController):
 
    """REST Controller styled on the Atom Publishing Protocol"""
 
class UsersController(base.BaseController):
 

	
 
    @LoginRequired()
 
    @HasPermissionAnyDecorator('hg.admin')
 
@@ -65,9 +62,9 @@ class UsersController(BaseController):
 
        super(UsersController, self)._before(*args, **kwargs)
 

	
 
    def index(self, format='html'):
 
        c.users_list = User.query().order_by(User.username) \
 
        c.users_list = db.User.query().order_by(db.User.username) \
 
                        .filter_by(is_default_user=False) \
 
                        .order_by(func.lower(User.username)) \
 
                        .order_by(func.lower(db.User.username)) \
 
                        .all()
 

	
 
        users_data = []
 
@@ -78,20 +75,20 @@ class UsersController(BaseController):
 

	
 
        def username(user_id, username):
 
            return template.get_def("user_name") \
 
                .render_unicode(user_id, username, _=_, h=h, c=c)
 
                .render_unicode(user_id, username, _=_, webutils=webutils, c=c)
 

	
 
        def user_actions(user_id, username):
 
            return template.get_def("user_actions") \
 
                .render_unicode(user_id, username, _=_, h=h, c=c)
 
                .render_unicode(user_id, username, _=_, webutils=webutils, c=c)
 

	
 
        for user in c.users_list:
 
            users_data.append({
 
                "gravatar": grav_tmpl % h.gravatar(user.email, size=20),
 
                "raw_name": user.username,
 
                "username": username(user.user_id, user.username),
 
                "firstname": h.escape(user.name),
 
                "lastname": h.escape(user.lastname),
 
                "last_login": h.fmt_date(user.last_login),
 
                "firstname": webutils.escape(user.name),
 
                "lastname": webutils.escape(user.lastname),
 
                "last_login": fmt_date(user.last_login),
 
                "last_login_raw": datetime_to_time(user.last_login),
 
                "active": h.boolicon(user.active),
 
                "admin": h.boolicon(user.admin),
 
@@ -106,41 +103,41 @@ class UsersController(BaseController):
 
            "records": users_data
 
        }
 

	
 
        return render('admin/users/users.html')
 
        return base.render('admin/users/users.html')
 

	
 
    def create(self):
 
        c.default_extern_type = User.DEFAULT_AUTH_TYPE
 
        c.default_extern_type = db.User.DEFAULT_AUTH_TYPE
 
        c.default_extern_name = ''
 
        user_model = UserModel()
 
        user_form = UserForm()()
 
        try:
 
            form_result = user_form.to_python(dict(request.POST))
 
            user = user_model.create(form_result)
 
            action_logger(request.authuser, 'admin_created_user:%s' % user.username,
 
            userlog.action_logger(request.authuser, 'admin_created_user:%s' % user.username,
 
                          None, request.ip_addr)
 
            h.flash(_('Created user %s') % user.username,
 
            webutils.flash(_('Created user %s') % user.username,
 
                    category='success')
 
            Session().commit()
 
            meta.Session().commit()
 
        except formencode.Invalid as errors:
 
            return htmlfill.render(
 
                render('admin/users/user_add.html'),
 
                base.render('admin/users/user_add.html'),
 
                defaults=errors.value,
 
                errors=errors.error_dict or {},
 
                prefix_error=False,
 
                encoding="UTF-8",
 
                force_defaults=False)
 
        except UserCreationError as e:
 
            h.flash(e, 'error')
 
            webutils.flash(e, 'error')
 
        except Exception:
 
            log.error(traceback.format_exc())
 
            h.flash(_('Error occurred during creation of user %s')
 
            webutils.flash(_('Error occurred during creation of user %s')
 
                    % request.POST.get('username'), category='error')
 
        raise HTTPFound(location=url('edit_user', id=user.user_id))
 

	
 
    def new(self, format='html'):
 
        c.default_extern_type = User.DEFAULT_AUTH_TYPE
 
        c.default_extern_type = db.User.DEFAULT_AUTH_TYPE
 
        c.default_extern_name = ''
 
        return render('admin/users/user_add.html')
 
        return base.render('admin/users/user_add.html')
 

	
 
    def update(self, id):
 
        user_model = UserModel()
 
@@ -155,10 +152,10 @@ class UsersController(BaseController):
 

	
 
            user_model.update(id, form_result, skip_attrs=skip_attrs)
 
            usr = form_result['username']
 
            action_logger(request.authuser, 'admin_updated_user:%s' % usr,
 
            userlog.action_logger(request.authuser, 'admin_updated_user:%s' % usr,
 
                          None, request.ip_addr)
 
            h.flash(_('User updated successfully'), category='success')
 
            Session().commit()
 
            webutils.flash(_('User updated successfully'), category='success')
 
            meta.Session().commit()
 
        except formencode.Invalid as errors:
 
            defaults = errors.value
 
            e = errors.error_dict or {}
 
@@ -176,29 +173,33 @@ class UsersController(BaseController):
 
                force_defaults=False)
 
        except Exception:
 
            log.error(traceback.format_exc())
 
            h.flash(_('Error occurred during update of user %s')
 
            webutils.flash(_('Error occurred during update of user %s')
 
                    % form_result.get('username'), category='error')
 
        raise HTTPFound(location=url('edit_user', id=id))
 

	
 
    def delete(self, id):
 
        usr = User.get_or_404(id)
 
        usr = db.User.get_or_404(id)
 
        has_ssh_keys = bool(usr.ssh_keys)
 
        try:
 
            UserModel().delete(usr)
 
            Session().commit()
 
            h.flash(_('Successfully deleted user'), category='success')
 
            meta.Session().commit()
 
            webutils.flash(_('Successfully deleted user'), category='success')
 
        except (UserOwnsReposException, DefaultUserException) as e:
 
            h.flash(e, category='warning')
 
            webutils.flash(e, category='warning')
 
        except Exception:
 
            log.error(traceback.format_exc())
 
            h.flash(_('An error occurred during deletion of user'),
 
            webutils.flash(_('An error occurred during deletion of user'),
 
                    category='error')
 
        else:
 
            if has_ssh_keys:
 
                SshKeyModel().write_authorized_keys()
 
        raise HTTPFound(location=url('users'))
 

	
 
    def _get_user_or_raise_if_default(self, id):
 
        try:
 
            return User.get_or_404(id, allow_default=False)
 
            return db.User.get_or_404(id, allow_default=False)
 
        except DefaultUserException:
 
            h.flash(_("The default user cannot be edited"), category='warning')
 
            webutils.flash(_("The default user cannot be edited"), category='warning')
 
            raise HTTPNotFound
 

	
 
    def _render_edit_profile(self, user):
 
@@ -207,7 +208,7 @@ class UsersController(BaseController):
 
        c.perm_user = AuthUser(dbuser=user)
 
        managed_fields = auth_modules.get_managed_fields(user)
 
        c.readonly = lambda n: 'readonly' if n in managed_fields else None
 
        return render('admin/users/user_edit.html')
 
        return base.render('admin/users/user_edit.html')
 

	
 
    def edit(self, id, format='html'):
 
        user = self._get_user_or_raise_if_default(id)
 
@@ -233,7 +234,7 @@ class UsersController(BaseController):
 
            'fork_repo_perm': umodel.has_perm(c.user, 'hg.fork.repository'),
 
        })
 
        return htmlfill.render(
 
            render('admin/users/user_edit.html'),
 
            base.render('admin/users/user_edit.html'),
 
            defaults=defaults,
 
            encoding="UTF-8",
 
            force_defaults=False)
 
@@ -254,7 +255,7 @@ class UsersController(BaseController):
 
                                                     show_expired=show_expired)
 
        defaults = c.user.get_dict()
 
        return htmlfill.render(
 
            render('admin/users/user_edit.html'),
 
            base.render('admin/users/user_edit.html'),
 
            defaults=defaults,
 
            encoding="UTF-8",
 
            force_defaults=False)
 
@@ -265,8 +266,8 @@ class UsersController(BaseController):
 
        lifetime = safe_int(request.POST.get('lifetime'), -1)
 
        description = request.POST.get('description')
 
        ApiKeyModel().create(c.user.user_id, description, lifetime)
 
        Session().commit()
 
        h.flash(_("API key successfully created"), category='success')
 
        meta.Session().commit()
 
        webutils.flash(_("API key successfully created"), category='success')
 
        raise HTTPFound(location=url('edit_user_api_keys', id=c.user.user_id))
 

	
 
    def delete_api_key(self, id):
 
@@ -275,12 +276,12 @@ class UsersController(BaseController):
 
        api_key = request.POST.get('del_api_key')
 
        if request.POST.get('del_api_key_builtin'):
 
            c.user.api_key = generate_api_key()
 
            Session().commit()
 
            h.flash(_("API key successfully reset"), category='success')
 
            meta.Session().commit()
 
            webutils.flash(_("API key successfully reset"), category='success')
 
        elif api_key:
 
            ApiKeyModel().delete(api_key, c.user.user_id)
 
            Session().commit()
 
            h.flash(_("API key successfully deleted"), category='success')
 
            meta.Session().commit()
 
            webutils.flash(_("API key successfully deleted"), category='success')
 

	
 
        raise HTTPFound(location=url('edit_user_api_keys', id=c.user.user_id))
 

	
 
@@ -301,7 +302,7 @@ class UsersController(BaseController):
 
            'fork_repo_perm': umodel.has_perm(c.user, 'hg.fork.repository'),
 
        })
 
        return htmlfill.render(
 
            render('admin/users/user_edit.html'),
 
            base.render('admin/users/user_edit.html'),
 
            defaults=defaults,
 
            encoding="UTF-8",
 
            force_defaults=False)
 
@@ -315,11 +316,11 @@ class UsersController(BaseController):
 

	
 
            user_model = UserModel()
 

	
 
            defs = UserToPerm.query() \
 
                .filter(UserToPerm.user == user) \
 
            defs = db.UserToPerm.query() \
 
                .filter(db.UserToPerm.user == user) \
 
                .all()
 
            for ug in defs:
 
                Session().delete(ug)
 
                meta.Session().delete(ug)
 

	
 
            if form_result['create_repo_perm']:
 
                user_model.grant_perm(id, 'hg.create.repository')
 
@@ -333,23 +334,23 @@ class UsersController(BaseController):
 
                user_model.grant_perm(id, 'hg.fork.repository')
 
            else:
 
                user_model.grant_perm(id, 'hg.fork.none')
 
            h.flash(_("Updated permissions"), category='success')
 
            Session().commit()
 
            webutils.flash(_("Updated permissions"), category='success')
 
            meta.Session().commit()
 
        except Exception:
 
            log.error(traceback.format_exc())
 
            h.flash(_('An error occurred during permissions saving'),
 
            webutils.flash(_('An error occurred during permissions saving'),
 
                    category='error')
 
        raise HTTPFound(location=url('edit_user_perms', id=id))
 

	
 
    def edit_emails(self, id):
 
        c.user = self._get_user_or_raise_if_default(id)
 
        c.active = 'emails'
 
        c.user_email_map = UserEmailMap.query() \
 
            .filter(UserEmailMap.user == c.user).all()
 
        c.user_email_map = db.UserEmailMap.query() \
 
            .filter(db.UserEmailMap.user == c.user).all()
 

	
 
        defaults = c.user.get_dict()
 
        return htmlfill.render(
 
            render('admin/users/user_edit.html'),
 
            base.render('admin/users/user_edit.html'),
 
            defaults=defaults,
 
            encoding="UTF-8",
 
            force_defaults=False)
 
@@ -361,14 +362,14 @@ class UsersController(BaseController):
 

	
 
        try:
 
            user_model.add_extra_email(id, email)
 
            Session().commit()
 
            h.flash(_("Added email %s to user") % email, category='success')
 
            meta.Session().commit()
 
            webutils.flash(_("Added email %s to user") % email, category='success')
 
        except formencode.Invalid as error:
 
            msg = error.error_dict['email']
 
            h.flash(msg, category='error')
 
            webutils.flash(msg, category='error')
 
        except Exception:
 
            log.error(traceback.format_exc())
 
            h.flash(_('An error occurred during email saving'),
 
            webutils.flash(_('An error occurred during email saving'),
 
                    category='error')
 
        raise HTTPFound(location=url('edit_user_emails', id=id))
 

	
 
@@ -377,22 +378,22 @@ class UsersController(BaseController):
 
        email_id = request.POST.get('del_email_id')
 
        user_model = UserModel()
 
        user_model.delete_extra_email(id, email_id)
 
        Session().commit()
 
        h.flash(_("Removed email from user"), category='success')
 
        meta.Session().commit()
 
        webutils.flash(_("Removed email from user"), category='success')
 
        raise HTTPFound(location=url('edit_user_emails', id=id))
 

	
 
    def edit_ips(self, id):
 
        c.user = self._get_user_or_raise_if_default(id)
 
        c.active = 'ips'
 
        c.user_ip_map = UserIpMap.query() \
 
            .filter(UserIpMap.user == c.user).all()
 
        c.user_ip_map = db.UserIpMap.query() \
 
            .filter(db.UserIpMap.user == c.user).all()
 

	
 
        c.default_user_ip_map = UserIpMap.query() \
 
            .filter(UserIpMap.user_id == kallithea.DEFAULT_USER_ID).all()
 
        c.default_user_ip_map = db.UserIpMap.query() \
 
            .filter(db.UserIpMap.user_id == kallithea.DEFAULT_USER_ID).all()
 

	
 
        defaults = c.user.get_dict()
 
        return htmlfill.render(
 
            render('admin/users/user_edit.html'),
 
            base.render('admin/users/user_edit.html'),
 
            defaults=defaults,
 
            encoding="UTF-8",
 
            force_defaults=False)
 
@@ -403,14 +404,14 @@ class UsersController(BaseController):
 

	
 
        try:
 
            user_model.add_extra_ip(id, ip)
 
            Session().commit()
 
            h.flash(_("Added IP address %s to user whitelist") % ip, category='success')
 
            meta.Session().commit()
 
            webutils.flash(_("Added IP address %s to user whitelist") % ip, category='success')
 
        except formencode.Invalid as error:
 
            msg = error.error_dict['ip']
 
            h.flash(msg, category='error')
 
            webutils.flash(msg, category='error')
 
        except Exception:
 
            log.error(traceback.format_exc())
 
            h.flash(_('An error occurred while adding IP address'),
 
            webutils.flash(_('An error occurred while adding IP address'),
 
                    category='error')
 

	
 
        if 'default_user' in request.POST:
 
@@ -421,26 +422,26 @@ class UsersController(BaseController):
 
        ip_id = request.POST.get('del_ip_id')
 
        user_model = UserModel()
 
        user_model.delete_extra_ip(id, ip_id)
 
        Session().commit()
 
        h.flash(_("Removed IP address from user whitelist"), category='success')
 
        meta.Session().commit()
 
        webutils.flash(_("Removed IP address from user whitelist"), category='success')
 

	
 
        if 'default_user' in request.POST:
 
            raise HTTPFound(location=url('admin_permissions_ips'))
 
        raise HTTPFound(location=url('edit_user_ips', id=id))
 

	
 
    @IfSshEnabled
 
    @base.IfSshEnabled
 
    def edit_ssh_keys(self, id):
 
        c.user = self._get_user_or_raise_if_default(id)
 
        c.active = 'ssh_keys'
 
        c.user_ssh_keys = SshKeyModel().get_ssh_keys(c.user.user_id)
 
        defaults = c.user.get_dict()
 
        return htmlfill.render(
 
            render('admin/users/user_edit.html'),
 
            base.render('admin/users/user_edit.html'),
 
            defaults=defaults,
 
            encoding="UTF-8",
 
            force_defaults=False)
 

	
 
    @IfSshEnabled
 
    @base.IfSshEnabled
 
    def ssh_keys_add(self, id):
 
        c.user = self._get_user_or_raise_if_default(id)
 

	
 
@@ -449,23 +450,23 @@ class UsersController(BaseController):
 
        try:
 
            new_ssh_key = SshKeyModel().create(c.user.user_id,
 
                                               description, public_key)
 
            Session().commit()
 
            meta.Session().commit()
 
            SshKeyModel().write_authorized_keys()
 
            h.flash(_("SSH key %s successfully added") % new_ssh_key.fingerprint, category='success')
 
            webutils.flash(_("SSH key %s successfully added") % new_ssh_key.fingerprint, category='success')
 
        except SshKeyModelException as e:
 
            h.flash(e.args[0], category='error')
 
            webutils.flash(e.args[0], category='error')
 
        raise HTTPFound(location=url('edit_user_ssh_keys', id=c.user.user_id))
 

	
 
    @IfSshEnabled
 
    @base.IfSshEnabled
 
    def ssh_keys_delete(self, id):
 
        c.user = self._get_user_or_raise_if_default(id)
 

	
 
        fingerprint = request.POST.get('del_public_key_fingerprint')
 
        try:
 
            SshKeyModel().delete(fingerprint, c.user.user_id)
 
            Session().commit()
 
            meta.Session().commit()
 
            SshKeyModel().write_authorized_keys()
 
            h.flash(_("SSH key successfully deleted"), category='success')
 
            webutils.flash(_("SSH key successfully deleted"), category='success')
 
        except SshKeyModelException as e:
 
            h.flash(e.args[0], category='error')
 
            webutils.flash(e.args[0], category='error')
 
        raise HTTPFound(location=url('edit_user_ssh_keys', id=c.user.user_id))
kallithea/controllers/api/__init__.py
Show inline comments
 
@@ -35,12 +35,11 @@ import types
 
from tg import Response, TGController, request, response
 
from webob.exc import HTTPError, HTTPException
 

	
 
from kallithea.controllers import base
 
from kallithea.lib import ext_json
 
from kallithea.lib.auth import AuthUser
 
from kallithea.lib.base import _get_ip_addr as _get_ip
 
from kallithea.lib.base import get_path_info
 
from kallithea.lib.utils2 import ascii_bytes
 
from kallithea.model.db import User
 
from kallithea.model import db
 

	
 

	
 
log = logging.getLogger('JSONRPC')
 
@@ -83,9 +82,6 @@ class JSONRPCController(TGController):
 

	
 
     """
 

	
 
    def _get_ip_addr(self, environ):
 
        return _get_ip(environ)
 

	
 
    def _get_method_args(self):
 
        """
 
        Return `self._rpc_args` to dispatched controller method
 
@@ -103,7 +99,7 @@ class JSONRPCController(TGController):
 

	
 
        environ = state.request.environ
 
        start = time.time()
 
        ip_addr = self._get_ip_addr(environ)
 
        ip_addr = base.get_ip_addr(environ)
 
        self._req_id = None
 
        if 'CONTENT_LENGTH' not in environ:
 
            log.debug("No Content-Length")
 
@@ -145,7 +141,7 @@ class JSONRPCController(TGController):
 

	
 
        # check if we can find this session using api_key
 
        try:
 
            u = User.get_by_api_key(self._req_api_key)
 
            u = db.User.get_by_api_key(self._req_api_key)
 
            auth_user = AuthUser.make(dbuser=u, ip_addr=ip_addr)
 
            if auth_user is None:
 
                raise JSONRPCErrorResponse(retid=self._req_id,
 
@@ -208,8 +204,8 @@ class JSONRPCController(TGController):
 
        self._rpc_args['environ'] = environ
 

	
 
        log.info('IP: %s Request to %s time: %.3fs' % (
 
            self._get_ip_addr(environ),
 
            get_path_info(environ), time.time() - start)
 
            base.get_ip_addr(environ),
 
            base.get_path_info(environ), time.time() - start)
 
        )
 

	
 
        state.set_action(self._rpc_call, [])

Changeset was too big and was cut off... Show full diff anyway

0 comments (0 inline, 0 general)