Contributing and feedback guidelines
************************************

There are many ways to contribute to Pelican. You can improve the
documentation, add missing features, and fix bugs (or just report
them). You can also help out by reviewing and commenting on existing
issues.

Don’t hesitate to fork Pelican and submit an issue or pull request on
GitHub. When doing so, please adhere to the following guidelines.


Filing issues
=============

* Before you file an issue, try asking for help first.

* If determined to file an issue, first check for existing issues,
  including closed issues.


How to get help
===============

Before you ask for help, please make sure you do the following:

1. Read the documentation thoroughly. If in a hurry, at least use
   the search field that is provided at top-left on the documentation
   pages. Make sure you read the docs for the Pelican version you are
   using.

2. Use a search engine (e.g., DuckDuckGo, Google) to search for a
   solution to your problem. Someone may have already found a
   solution, perhaps in the form of a plugin or a specific combination
   of settings.

3. Try reproducing the issue in a clean environment, ensuring you
   are using:

* latest Pelican release (or an up-to-date git clone of Pelican
  master)

* latest releases of libraries used by Pelican

* no plugins or only those related to the issue

**NOTE:** The most common sources of problems are anomalies in (1)
themes, (2) settings files, and (3) "make"/"fab" automation wrappers.
If you can’t reproduce your problem when using the following steps to
generate your site, then the problem is almost certainly with your
chosen theme and/or settings file (and not Pelican itself):

   cd ~/projects/your-site
   git clone https://github.com/getpelican/pelican ~/projects/pelican
   pelican content -s ~/projects/pelican/samples/pelican.conf.py -t ~/projects/pelican/pelican/themes/notmyidea

If despite the above efforts you still cannot resolve your problem, be
sure to include in your inquiry the following information, preferably
in the form of links to content uploaded to a paste service, GitHub
repository, or other publicly-accessible location:

* Describe what version of Pelican you are running (output of
  "pelican --version" or the HEAD commit hash if you cloned the repo)
  and how exactly you installed it (the full command you used, e.g.
  "pip install pelican").

* If you are looking for a way to get some end result, prepare a
  detailed description of what the end result should look like
  (preferably in the form of an image or a mock-up page) and explain
  in detail what you have done so far to achieve it.

* If you are trying to solve some issue, prepare a detailed
  description of how to reproduce the problem. If the issue cannot be
  easily reproduced, it cannot be debugged by developers or
  volunteers. Describe only the **minimum steps** necessary to
  reproduce it (no extra plugins, etc.).

* Upload your settings file or any other custom code that would
  enable people to reproduce the problem or to see what you have
  already tried to achieve the desired end result.

* Upload detailed and **complete** output logs and backtraces
  (remember to add the "--debug" flag: "pelican --debug content
  [...]")

Once the above preparation is ready, you can contact people willing to
help via (preferably) the "#pelican" IRC channel or send a message to
"authors at getpelican dot com". Remember to include all the
information you prepared.


The #pelican IRC channel
------------------------

* Because of differing time zones, you may not get an immediate
  response to your question, but please be patient and stay logged
  into IRC — someone will almost always respond if you wait long
  enough (it may take a few hours).

* If you don’t have an IRC client handy, use the webchat for quick
  feedback.

* You can direct your IRC client to the channel using this IRC link
  or you can manually join the "#pelican" IRC channel on the freenode
  IRC network.


Contributing code
=================

Before you submit a contribution, please ask whether it is desired so
that you don’t spend a lot of time working on something that would be
rejected for a known reason. Consider also whether your new feature
might be better suited as a plugin — you can ask for help  to make
that determination.


Using Git and GitHub
--------------------

* Create a new git branch specific to your change (as opposed to
  making your commits in the master branch).

* **Don’t put multiple unrelated fixes/features in the same branch /
  pull request.** For example, if you’re hacking on a new feature and
  find a bugfix that doesn’t *require* your new feature, **make a new
  distinct branch and pull request** for the bugfix.

* Check for unnecessary whitespace via "git diff --check" before
  committing.

* First line of your commit message should start with present-tense
  verb, be 50 characters or less, and include the relevant issue
  number(s) if applicable. *Example:* "Ensure proper PLUGIN_PATH
  behavior. Refs #428." If the commit *completely fixes* an existing
  bug report, please use "Fixes #585" or "Fix #585" syntax (so the
  relevant issue is automatically closed upon PR merge).

* After the first line of the commit message, add a blank line and
  then a more detailed explanation (when relevant).

* Squash your commits to eliminate merge commits and ensure a clean
  and readable commit history.

* If you have previously filed a GitHub issue and want to contribute
  code that addresses that issue, **please use** "hub pull-request"
  instead of using GitHub’s web UI to submit the pull request. This
  isn’t an absolute requirement, but makes the maintainers’ lives much
  easier! Specifically: install hub and then run hub pull-request to
  turn your GitHub issue into a pull request containing your code.


Contribution quality standards
------------------------------

* Adhere to PEP8 coding standards whenever possible. This can be
  eased via the pep8 or flake8 tools, the latter of which in
  particular will give you some useful hints about ways in which the
  code/formatting can be improved.

* Make sure your code is compatible with Python 2.7, 3.3, and 3.4 —
  see our compatibility cheatsheet for more details.

* Add docs and tests for your changes. Undocumented and untested
  features will not be accepted.

* Run all the tests **on all versions of Python supported by
  Pelican** to ensure nothing was accidentally broken.

Check out our Git Tips page or ask for help if you need assistance or
have any questions about these guidelines.


Setting up the development environment
======================================

While there are many ways to set up one’s development environment,
following is a method that uses virtualenv. If you don’t have
"virtualenv" installed, you can install it via:

   $ pip install virtualenv

Virtual environments allow you to work on Python projects which are
isolated from one another so you can use different packages (and
package versions) with different projects.

To create and activate a virtual environment, use the following
syntax:

   $ virtualenv ~/virtualenvs/pelican
   $ cd ~/virtualenvs/pelican
   $ . bin/activate

To clone the Pelican source:

   $ git clone https://github.com/getpelican/pelican.git src/pelican

To install the development dependencies:

   $ cd src/pelican
   $ pip install -r requirements/developer.pip

To install Pelican and its dependencies:

   $ python setup.py develop

Or using "pip":

   $ pip install -e .


Building the docs
=================

If you make changes to the documentation, you should preview your
changes before committing them:

   $ pip install sphinx
   $ cd src/pelican/docs
   $ make html

Open "_build/html/index.html" in your browser to preview the
documentation.


Running the test suite
======================

Each time you add a feature, there are two things to do regarding
tests: check that the existing tests pass, and add tests for the new
feature or bugfix.

The tests live in "pelican/tests" and you can run them using the
“discover” feature of "unittest":

   $ python -Wd -m unittest discover

After making your changes and running the tests, you may see a test
failure mentioning that “some generated files differ from the expected
functional tests output.” If you have made changes that affect the
HTML output generated by Pelican, and the changes to that output are
expected and deemed correct given the nature of your changes, then you
should update the output used by the functional tests. To do so,
**make sure you have both ``en_EN.utf8`` and ``fr_FR.utf8`` locales
installed**, and then run the following two commands:

   $ LC_ALL=en_US.utf8 pelican -o pelican/tests/output/custom/ \
       -s samples/pelican.conf.py samples/content/
   $ LC_ALL=fr_FR.utf8 pelican -o pelican/tests/output/custom_locale/ \
       -s samples/pelican.conf_FR.py samples/content/
   $ LC_ALL=en_US.utf8 pelican -o pelican/tests/output/basic/ \
       samples/content/


Testing on Python 2 and 3
-------------------------

Testing on Python 3 currently requires some extra steps: installing
Python 3-compatible versions of dependent packages and plugins.

Tox is a useful tool to run tests on both versions. It will install
the Python 3-compatible version of dependent packages.


Python 3 development tips
=========================

Here are some tips that may be useful when doing some code for both
Python 2.7 and Python 3 at the same time:

* Assume every string and literal is unicode (import
  unicode_literals):

  * Do not use prefix "u'".

  * Do not encode/decode strings in the middle of sth. Follow the
    code to the source (or target) of a string and encode/decode at
    the first/last possible point.

  * In other words, write your functions to expect and to return
    unicode.

  * Encode/decode strings if e.g. the source is a Python function
    that is known to handle this badly, e.g. strftime() in Python 2.

* Use new syntax: print function, “except … *as* e” (not comma) etc.

* Refactor method calls like "dict.iteritems()", "xrange()" etc. in
  a way that runs without code change in both Python versions.

* Do not use magic method "__unicode()__" in new classes. Use only
  "__str()__" and decorate the class with
  "@python_2_unicode_compatible".

* Do not start int literals with a zero. This is a syntax error in
  Py3k.

* Unfortunately I did not find an octal notation that is valid in
  both Pythons. Use decimal instead.

* use six, e.g.:

  * "isinstance(.., basestring) -> isinstance(.., six.string_types)"

  * "isinstance(.., unicode) -> isinstance(.., six.text_type)"

* "setlocale()" in Python 2 bails when we give the locale name as
  unicode, and since we are using "from __future__ import
  unicode_literals", we do that everywhere!  As a workaround, I
  enclosed the localename with "str()"; in Python 2 this casts the
  name to a byte string, in Python 3 this should do nothing, because
  the locale name already had been unicode.

* Kept range() almost everywhere as-is (2to3 suggests
  list(range())), just changed it where I felt necessary.

* Changed xrange() back to range(), so it is valid in both Python
  versions.


Logging tips
============

Try to use logging with appropriate levels.

For logging messages that are not repeated, use the usual Python way:

   # at top of file
   import logging
   logger = logging.getLogger(__name__)

   # when needed
   logger.warning("A warning with %s formatting", arg_to_be_formatted)

Do not format log messages yourself. Use "%s" formatting in messages
and pass arguments to logger. This is important, because Pelican
logger will preprocess some arguments (like Exceptions) for Py2/Py3
compatibility.


Limiting extraneous log messages
--------------------------------

If the log message can occur several times, you may want to limit the
log to prevent flooding. In order to do that, use the "extra" keyword
argument for the logging message in the following format:

   logger.warning("A warning with %s formatting", arg_to_be_formatted,
       extra={'limit_msg': 'A generic message for too many warnings'})

Optionally, you can also set "'limit_args'" as a tuple of arguments in
"extra" dict if your generic message needs formatting.

Limit is set to "5", i.e, first four logs with the same "'limit_msg'"
are outputted normally but the fifth one will be logged using
"'limit_msg'" (and "'limit_args'" if present). After the fifth,
corresponding log messages will be ignored.

For example, if you want to log missing resources, use the following
code:

   for resource in resources:
       if resource.is_missing:
           logger.warning(
               'The resource %s is missing', resource.name,
               extra={'limit_msg': 'Other resources were missing'})

The log messages will be displayed as follows:

   WARNING: The resource prettiest_cat.jpg is missing
   WARNING: The resource best_cat_ever.jpg is missing
   WARNING: The resource cutest_cat.jpg is missing
   WARNING: The resource lolcat.jpg is missing
   WARNING: Other resources were missing


Outputting traceback in the logs
--------------------------------

If you’re logging inside an "except" block, you may want to provide
the traceback information as well. You can do that by setting
"exc_info" keyword argument to "True" during logging. However, doing
so by default can be undesired because tracebacks are long and can be
confusing to regular users. Try to limit them to "--debug" mode like
the following:

   try:
       some_action()
   except Exception as e:
       logger.error('Exception occurred: %s', e,
           exc_info=settings.get('DEBUG', False))
