Maxime Vidori 9 years ago
parent
commit
cb6defe7a1

+ 79 - 0
content/blog/2015-04-14-pytest-fixture.md

@@ -0,0 +1,79 @@
+Title: Pytest Fixture
+Category: tuto
+Tags: python, dev
+
+[TOC]
+
+# toto
+I am a huge fan of python (one of the best language in my toolbox). And
+when it comes to tests, [pytest](http://pytest.org/) is *THE* library to use.
+
+I also use [Flask](http://flask.pocoo.org/) a lot, so today I will show you
+some of my snippets.
+
+First one the app fixture:
+
+```python
+@pytest.fixture(autouse=True)
+def app():
+    """Load flask in testing mode"""
+    app_test = myapp
+    app_test.config['TESTING'] = True
+    app_test.json_encoder = my_encoder
+
+    return app_test.test_client()
+```
+
+This create an app fixture which will be used to test the application, it
+returns a test client to interact with my Flask application.
+
+It is an adaptation of the documentation [testing skeleton]
+(http://flask.pocoo.org/docs/0.10/testing/#the-testing-skeleton)
+
+I also replace the json encoder by a custom one (it allows me to dump mock
+object for example).
+
+```python
+@pytest.yield_fixture
+def request_context(app):
+    """Provide a Flask request context for testing purpose"""
+
+    with app.application.test_request_context() as req_context:
+        yield req_context
+```
+
+This one applies a request context on a testing function, this can be
+useful if you manipulate werzeug interactions (flask request attribute mostly).
+This has to be use when the
+`RuntimeError: working outside of application context` error is raised.
+
+In the most common use case you will not need the `req_context` variable during
+your test. To avoid to have an unused argument, you can simply use the
+`@pytest.mark.usefixtures('request_context')` decorator on your testing
+function.
+
+Last one is also an opportunity to talk about
+[peewee](http://peewee.readthedocs.org/en/latest/) which is a great lightweight
+ORM. Like a lot of ORM peewee provides a [transaction decorator]
+(http://docs.peewee-orm.com/en/latest/peewee/transactions.html)
+, in unittest you may want to test endpoints without connecting to a db.
+So, here is an example on how you can replace the decorator
+(or contextmanager) by a dummy one.
+
+```python
+import imp
+import contextlib
+import pytest
+
+import database
+
+@pytest.fixture(autouse=True, scope='session')
+def mock_transaction():
+    """Replace the atomic decorator from peewee to a noop one"""
+
+    database.atomic = contextlib.contextmanager(lambda: (yield))
+    imp.reload(module.using.db.transactions)
+```
+
+Pytest use a lot of the python flexibility and I must confess that I love it.
+

+ 12 - 14
content/pages/02_gitoyen.md

@@ -1,8 +1,6 @@
 Title: Gitoyen
 Title: Gitoyen
 
 
-[TOC]
-
-# Qui est Gitoyen
+## Qui est Gitoyen
 
 
 Gitoyen est depuis Janvier 2012 une association loi 1901. Elle a pour
 Gitoyen est depuis Janvier 2012 une association loi 1901. Elle a pour
 but de faciliter l'émergence et l'existence de petits opérateurs
 but de faciliter l'émergence et l'existence de petits opérateurs
@@ -16,7 +14,7 @@ fabrication de l'Internet en dehors du champ mercantile.
 L'association Gitoyen est ouverte aux structures qui partageraient sa
 L'association Gitoyen est ouverte aux structures qui partageraient sa
 démarche.
 démarche.
 
 
-# Nos valeurs
+## Nos valeurs
 
 
 Notre participation à Gitoyen, sous forme de bénévolat, nous permet de :
 Notre participation à Gitoyen, sous forme de bénévolat, nous permet de :
 
 
@@ -24,16 +22,16 @@ Notre participation à Gitoyen, sous forme de bénévolat, nous permet de :
 * partager nos connaissances, nos expériences avec les autres bénévoles,
 * partager nos connaissances, nos expériences avec les autres bénévoles,
 * aider d'autres opérateurs sans but lucratif à faire de même.
 * aider d'autres opérateurs sans but lucratif à faire de même.
 
 
-# Histoire de l'association
+## Histoire de l'association
 
 
-## La rencontre
+### La rencontre
 
 
 C'est lors de la Zelig Conf de 2001, réunion d'activistes et médias
 C'est lors de la Zelig Conf de 2001, réunion d'activistes et médias
 alternatifs œuvrant entre autre sur Internet, que se sont rencontrés
 alternatifs œuvrant entre autre sur Internet, que se sont rencontrés
 Globenet, Placenet et Netaktiv, bien vite rejoint par FDN et Gandi, un
 Globenet, Placenet et Netaktiv, bien vite rejoint par FDN et Gandi, un
 nouveau bourgeon de l'Internet solidaire pouvait naître ...
 nouveau bourgeon de l'Internet solidaire pouvait naître ...
 
 
-## L'objet connecté non identifié
+### L'objet connecté non identifié
 
 
 Depuis le temps qu'on en rêvait, nous autres qui croyions à un
 Depuis le temps qu'on en rêvait, nous autres qui croyions à un
 Internet qui serait d'abord un outil citoyen avant d'être un système
 Internet qui serait d'abord un outil citoyen avant d'être un système
@@ -77,7 +75,7 @@ ne nécessite aucun apport extérieur. À l'image d'Internet tout entier,
 c'est la mise en commun des ressources qui a permis les économies
 c'est la mise en commun des ressources qui a permis les économies
 d'échelle nécessaires à la réalisation de ce rêve.
 d'échelle nécessaires à la réalisation de ce rêve.
 
 
-## Un long chemin
+### Un long chemin
 
 
 Le rêve s'est donc réalisé en 2001. Comme tout projet un peu fou, il emprunta
 Le rêve s'est donc réalisé en 2001. Comme tout projet un peu fou, il emprunta
 alors un chemin sinueux vers une maturité désormais acquise. Certains sont
 alors un chemin sinueux vers une maturité désormais acquise. Certains sont
@@ -85,7 +83,7 @@ partis (Gandi, Placenet, Cursys, Artefact) et d'autres nous ont rejoint (Altern,
 L'autre.net, LDN, Neutrinet, Franciliens.net, Ilico, Illyse, Grenode et
 L'autre.net, LDN, Neutrinet, Franciliens.net, Ilico, Illyse, Grenode et
 Tetaneutral.net), et l'esprit du réseau reste le même.
 Tetaneutral.net), et l'esprit du réseau reste le même.
 
 
-# L'équipage
+## L'équipage
 
 
 Une partie d'entre nous a étudié l'informatique à l'école, l'autre non. Au fil
 Une partie d'entre nous a étudié l'informatique à l'école, l'autre non. Au fil
 des années, nous avons acquis de bonnes connaissances dans le domaine des
 des années, nous avons acquis de bonnes connaissances dans le domaine des
@@ -100,9 +98,9 @@ Notre participation à Gitoyen, sous forme de bénévolat, nous permet de :
 * partager nos connaissances, nos expériences avec les autres bénévoles,
 * partager nos connaissances, nos expériences avec les autres bénévoles,
 * aider d'autres opérateurs sans but lucratif à faire de même.
 * aider d'autres opérateurs sans but lucratif à faire de même.
 
 
-# Règlement Intérieur
+## Règlement Intérieur
 
 
-# Gitoyen est membre de
+## Gitoyen est membre de
 
 
 FIXME
 FIXME
 
 
@@ -119,7 +117,7 @@ Gitoyen est membre ou est présent sur plusieurs points d'échange (aussi appel
 
 
 Nos points de peering sont listés sur la page de l'AS20766 sur [peeringdb](https://www.peeringdb.com/view.php?asn=20766)
 Nos points de peering sont listés sur la page de l'AS20766 sur [peeringdb](https://www.peeringdb.com/view.php?asn=20766)
 
 
-# Les membres de Gitoyen
+## Les membres de Gitoyen
 
 
 Les membres de Gitoyen sont, à ce jour
 Les membres de Gitoyen sont, à ce jour
 
 
@@ -136,11 +134,11 @@ Les membres de Gitoyen sont, à ce jour
 * [Neutrinet](http://neutrine.be/), Association fournisseur d'accès à Internet en Belgique.
 * [Neutrinet](http://neutrine.be/), Association fournisseur d'accès à Internet en Belgique.
 * [Tetaneutral.net](http://tetaneutral.net/), Association fournisseur d'accès à Internet à Toulouse.
 * [Tetaneutral.net](http://tetaneutral.net/), Association fournisseur d'accès à Internet à Toulouse.
 
 
-# Les Statuts
+## Les Statuts
 
 
 Voir les [Statuts](Statuts.md)
 Voir les [Statuts](Statuts.md)
 
 
-# Comment adhérer à l'association
+## Comment adhérer à l'association
 
 
 Gitoyen est depuis Janvier 2012 une association. Elle a pour but de
 Gitoyen est depuis Janvier 2012 une association. Elle a pour but de
 faciliter l'émergence et l'existence de petits opérateurs réseaux, en
 faciliter l'émergence et l'existence de petits opérateurs réseaux, en

+ 102 - 2
content/pages/03_services.md

@@ -1,3 +1,103 @@
-Title: Nos services
+Entry: Nos Services
+Title: Services de Gitoyen
 
 
-Nos services
+
+Gitoyen fournit plusieurs services à ses membres et ses clients.
+
+# Description des services
+
+## Transit Internet
+
+Gitoyen est un opérateur Internet disposant de ses propres liens de
+communication avec le reste d'Internet. Dans ce cadre nous sommes en mesure de
+fournir une vue complète d'Internet (du **Transit**)  à nos membres ou nos
+clients.
+
+## Hébergement d'équipement
+
+Gitoyen dispose de deux points de présence basés à Paris avec notre propre
+espace d'hébergement d'équipement. L'un à Téléhouse - Paris Voltaire et l'autre
+à Paris Bourse.
+
+Nous sommes en mesure de proposer de l'**hébergement d'équipement** à nos
+membres et nos clients.
+
+## LIR / Obtention de ressources Internet
+
+Gitoyen est un *registre local d'Internet* (LIR). Cela lui donne la possibilité
+d'assigner des ressources : blocs d'adresses IP ou numéros d'AS.
+
+Il y a deux types de ressources facturées :
+
+* Celles nécessitant un contrat spécifique avec le LIR pour laquelle le RIPE
+  impose une facturation spécifique (les ressources **Provider Independant
+  (PI)**) ;
+
+* Les autres ne nécessitant pas de contrat spécifique (**Provider Aggregate
+  (PA)**, **Autonomous System (AS)**.
+
+## Commutation et Routage
+
+Nous proposons à nos membres la possibilité d'utiliser :
+
+* **l'infrastructure de commutation** de Gitoyen, c'est à dire l'utilisation de
+  ports réseaux de nos switchs pour leurs besoins propres ;
+
+* **l'infrastructure de routage** de Gitoyen, c'est à dire la possibilité
+  d'utiliser les routeurs et l'AS de Gitoyen pour annoncer leurs propres
+  réseaux. L'infrastructure de routage inclut la commutation.
+
+# Les tarifs
+
+TODO: ajouter le pdf ou bien faire un tableau html
+
+
+## Quelques cas d'usage
+
+### Ressources Internet pour monter un petit FAI ou un hébergeur de services
+
+Pour une petite structure nécessitant du réseau, il vous sera nécessaire
+d'avoir vos propres blocs d'adresses. Pour cela il vous suffit d'adhérer et de
+prendre une ressource pour un bloc d'adresses IPv4, une autre pour un bloc
+d'adresses IPv6 et éventuellement une dernière pour avoir un AS, selon les
+besoins.
+
+### Livraison réseau via Gitoyen
+
+Pour avoir une livraison chez Gitoyen (par exemple en amenant un câble, ou en
+utilisant une machine virtuelle d'infrastructure chez Gitoyen), cela signifie
+payer le transit et l'infrastructure de commutation.
+
+**Remarque :** la machine virtuelle d'infrastructure est à la discrétion du
+membre mais n'a pour but que d'établir un lien Ethernet « virtuel » entre
+Gitoyen et le réseau du membre (via openvpn, gre, ipsec, etc.).
+
+### Annoncer son réseau avec les routeurs de Gitoyen
+
+Il est aussi possible d'utiliser directement les routeurs et l'AS de Gitoyen
+pour annoncer son réseau, dans ce cas il s'agit du tarif infrastructure de
+routage (qui comprend l'infrastructure de commutation).
+
+Pour un exemple chiffré (par rapport à Gitoyen), pour une petite asso (moins de
+20 000 € de CA) dans un cas type, sans parler de l'adhésion cela donne :
+
+# Peering
+
+Gitoyen est un opérateur courtois et ouvert. Notre politique de
+peering est ouverte elle aussi : Il vous suffit de nous demander par
+mail à peering (at) gitoyen (dot) net.
+
+Nous avons déjà une bonne centaine d'accords de peering. Vous pouvez aussi utiliser l'outil Looking Glass ou voir la base RPSL de nos peerings dans la base du RIPE-NCC.
+
+## Comment établir un peering avec Gitoyen ?
+
+Pour monter un peering avec Gitoyen, vous aurez besoin des informations techniques suivantes :
+
+* Notre numéro de système autonome est AS20766
+* Nous annonçons l'AS-Macro AS-GITOYEN.
+* l'email du NOC est `noc@`
+* Nous n'utilisons pas la signature MD5 des sessions BGP. Si vous vous demandez pourquoi, rendez-vous dans la RFC 2385 chapitre 4.
+
+## Points de peering
+
+Nos points de peering sont listés sur la page de l'AS20766 sur [peeringdb](https://www.peeringdb.com/view.php?asn=20766)

+ 0 - 1
content/pages/06_contact.md

@@ -1,6 +1,5 @@
 Title: Contact
 Title: Contact
 
 
-[TOC]
 
 
 # Contact
 # Contact
 
 

+ 7 - 2
pelicanconf.py

@@ -38,8 +38,13 @@ PAGE_SAVE_AS = '{slug}.html'
 
 
 INDEX_SAVE_AS = 'blog.html'
 INDEX_SAVE_AS = 'blog.html'
 PLUGIN_PATHS = ['plugins']
 PLUGIN_PATHS = ['plugins']
-PLUGINS = ['extract_toc']
+PLUGINS = ['pelican-toc']
 
 
-MD_EXTENSIONS = (['toc'])
+TOC = {
+    'TOC_HEADERS' : '^h[2]',
+    'TOC_RUN': 'true'
+}
+
+MD_EXTENSIONS = ([])
 # Uncomment following line if you want document-relative URLs when developing
 # Uncomment following line if you want document-relative URLs when developing
 #RELATIVE_URLS = True
 #RELATIVE_URLS = True

+ 55 - 0
plugins/pelican-toc/.gitignore

@@ -0,0 +1,55 @@
+# Byte-compiled / optimized / DLL files
+__pycache__/
+*.py[cod]
+
+# C extensions
+*.so
+
+# Distribution / packaging
+.Python
+env/
+bin/
+build/
+develop-eggs/
+dist/
+eggs/
+lib/
+lib64/
+parts/
+sdist/
+var/
+*.egg-info/
+.installed.cfg
+*.egg
+
+# Installer logs
+pip-log.txt
+pip-delete-this-directory.txt
+
+# Unit test / coverage reports
+htmlcov/
+.tox/
+.coverage
+.cache
+nosetests.xml
+coverage.xml
+
+# Translations
+*.mo
+
+# Mr Developer
+.mr.developer.cfg
+.project
+.pydevproject
+
+# Rope
+.ropeproject
+
+# Django stuff:
+*.log
+*.pot
+
+# Sphinx documentation
+docs/_build/
+
+*.swp

+ 23 - 0
plugins/pelican-toc/.travis.yml

@@ -0,0 +1,23 @@
+sudo: false
+language: python
+python:
+  - "2.7"
+env:
+  - TOX_ENV=py27-pelican34
+  - TOX_ENV=py27-pelican35
+  - TOX_ENV=py27-pelican36
+  - TOX_ENV=py27-pelicandev
+
+  - TOX_ENV=py33-pelican34
+  - TOX_ENV=py33-pelican35
+  - TOX_ENV=py33-pelican36
+  - TOX_ENV=py33-pelicandev
+
+  - TOX_ENV=py34-pelican34
+  - TOX_ENV=py34-pelican35
+  - TOX_ENV=py34-pelican36
+  - TOX_ENV=py34-pelicandev
+
+install:
+  - pip install tox==2.0.1
+script: tox -e $TOX_ENV

+ 339 - 0
plugins/pelican-toc/LICENSE

@@ -0,0 +1,339 @@
+GNU GENERAL PUBLIC LICENSE
+                       Version 2, June 1991
+
+ Copyright (C) 1989, 1991 Free Software Foundation, Inc., <http://fsf.org/>
+ 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ Everyone is permitted to copy and distribute verbatim copies
+ of this license document, but changing it is not allowed.
+
+                            Preamble
+
+  The licenses for most software are designed to take away your
+freedom to share and change it.  By contrast, the GNU General Public
+License is intended to guarantee your freedom to share and change free
+software--to make sure the software is free for all its users.  This
+General Public License applies to most of the Free Software
+Foundation's software and to any other program whose authors commit to
+using it.  (Some other Free Software Foundation software is covered by
+the GNU Lesser General Public License instead.)  You can apply it to
+your programs, too.
+
+  When we speak of free software, we are referring to freedom, not
+price.  Our General Public Licenses are designed to make sure that you
+have the freedom to distribute copies of free software (and charge for
+this service if you wish), that you receive source code or can get it
+if you want it, that you can change the software or use pieces of it
+in new free programs; and that you know you can do these things.
+
+  To protect your rights, we need to make restrictions that forbid
+anyone to deny you these rights or to ask you to surrender the rights.
+These restrictions translate to certain responsibilities for you if you
+distribute copies of the software, or if you modify it.
+
+  For example, if you distribute copies of such a program, whether
+gratis or for a fee, you must give the recipients all the rights that
+you have.  You must make sure that they, too, receive or can get the
+source code.  And you must show them these terms so they know their
+rights.
+
+  We protect your rights with two steps: (1) copyright the software, and
+(2) offer you this license which gives you legal permission to copy,
+distribute and/or modify the software.
+
+  Also, for each author's protection and ours, we want to make certain
+that everyone understands that there is no warranty for this free
+software.  If the software is modified by someone else and passed on, we
+want its recipients to know that what they have is not the original, so
+that any problems introduced by others will not reflect on the original
+authors' reputations.
+
+  Finally, any free program is threatened constantly by software
+patents.  We wish to avoid the danger that redistributors of a free
+program will individually obtain patent licenses, in effect making the
+program proprietary.  To prevent this, we have made it clear that any
+patent must be licensed for everyone's free use or not licensed at all.
+
+  The precise terms and conditions for copying, distribution and
+modification follow.
+
+                    GNU GENERAL PUBLIC LICENSE
+   TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
+
+  0. This License applies to any program or other work which contains
+a notice placed by the copyright holder saying it may be distributed
+under the terms of this General Public License.  The "Program", below,
+refers to any such program or work, and a "work based on the Program"
+means either the Program or any derivative work under copyright law:
+that is to say, a work containing the Program or a portion of it,
+either verbatim or with modifications and/or translated into another
+language.  (Hereinafter, translation is included without limitation in
+the term "modification".)  Each licensee is addressed as "you".
+
+Activities other than copying, distribution and modification are not
+covered by this License; they are outside its scope.  The act of
+running the Program is not restricted, and the output from the Program
+is covered only if its contents constitute a work based on the
+Program (independent of having been made by running the Program).
+Whether that is true depends on what the Program does.
+
+  1. You may copy and distribute verbatim copies of the Program's
+source code as you receive it, in any medium, provided that you
+conspicuously and appropriately publish on each copy an appropriate
+copyright notice and disclaimer of warranty; keep intact all the
+notices that refer to this License and to the absence of any warranty;
+and give any other recipients of the Program a copy of this License
+along with the Program.
+
+You may charge a fee for the physical act of transferring a copy, and
+you may at your option offer warranty protection in exchange for a fee.
+
+  2. You may modify your copy or copies of the Program or any portion
+of it, thus forming a work based on the Program, and copy and
+distribute such modifications or work under the terms of Section 1
+above, provided that you also meet all of these conditions:
+
+    a) You must cause the modified files to carry prominent notices
+    stating that you changed the files and the date of any change.
+
+    b) You must cause any work that you distribute or publish, that in
+    whole or in part contains or is derived from the Program or any
+    part thereof, to be licensed as a whole at no charge to all third
+    parties under the terms of this License.
+
+    c) If the modified program normally reads commands interactively
+    when run, you must cause it, when started running for such
+    interactive use in the most ordinary way, to print or display an
+    announcement including an appropriate copyright notice and a
+    notice that there is no warranty (or else, saying that you provide
+    a warranty) and that users may redistribute the program under
+    these conditions, and telling the user how to view a copy of this
+    License.  (Exception: if the Program itself is interactive but
+    does not normally print such an announcement, your work based on
+    the Program is not required to print an announcement.)
+
+These requirements apply to the modified work as a whole.  If
+identifiable sections of that work are not derived from the Program,
+and can be reasonably considered independent and separate works in
+themselves, then this License, and its terms, do not apply to those
+sections when you distribute them as separate works.  But when you
+distribute the same sections as part of a whole which is a work based
+on the Program, the distribution of the whole must be on the terms of
+this License, whose permissions for other licensees extend to the
+entire whole, and thus to each and every part regardless of who wrote it.
+
+Thus, it is not the intent of this section to claim rights or contest
+your rights to work written entirely by you; rather, the intent is to
+exercise the right to control the distribution of derivative or
+collective works based on the Program.
+
+In addition, mere aggregation of another work not based on the Program
+with the Program (or with a work based on the Program) on a volume of
+a storage or distribution medium does not bring the other work under
+the scope of this License.
+
+  3. You may copy and distribute the Program (or a work based on it,
+under Section 2) in object code or executable form under the terms of
+Sections 1 and 2 above provided that you also do one of the following:
+
+    a) Accompany it with the complete corresponding machine-readable
+    source code, which must be distributed under the terms of Sections
+    1 and 2 above on a medium customarily used for software interchange; or,
+
+    b) Accompany it with a written offer, valid for at least three
+    years, to give any third party, for a charge no more than your
+    cost of physically performing source distribution, a complete
+    machine-readable copy of the corresponding source code, to be
+    distributed under the terms of Sections 1 and 2 above on a medium
+    customarily used for software interchange; or,
+
+    c) Accompany it with the information you received as to the offer
+    to distribute corresponding source code.  (This alternative is
+    allowed only for noncommercial distribution and only if you
+    received the program in object code or executable form with such
+    an offer, in accord with Subsection b above.)
+
+The source code for a work means the preferred form of the work for
+making modifications to it.  For an executable work, complete source
+code means all the source code for all modules it contains, plus any
+associated interface definition files, plus the scripts used to
+control compilation and installation of the executable.  However, as a
+special exception, the source code distributed need not include
+anything that is normally distributed (in either source or binary
+form) with the major components (compiler, kernel, and so on) of the
+operating system on which the executable runs, unless that component
+itself accompanies the executable.
+
+If distribution of executable or object code is made by offering
+access to copy from a designated place, then offering equivalent
+access to copy the source code from the same place counts as
+distribution of the source code, even though third parties are not
+compelled to copy the source along with the object code.
+
+  4. You may not copy, modify, sublicense, or distribute the Program
+except as expressly provided under this License.  Any attempt
+otherwise to copy, modify, sublicense or distribute the Program is
+void, and will automatically terminate your rights under this License.
+However, parties who have received copies, or rights, from you under
+this License will not have their licenses terminated so long as such
+parties remain in full compliance.
+
+  5. You are not required to accept this License, since you have not
+signed it.  However, nothing else grants you permission to modify or
+distribute the Program or its derivative works.  These actions are
+prohibited by law if you do not accept this License.  Therefore, by
+modifying or distributing the Program (or any work based on the
+Program), you indicate your acceptance of this License to do so, and
+all its terms and conditions for copying, distributing or modifying
+the Program or works based on it.
+
+  6. Each time you redistribute the Program (or any work based on the
+Program), the recipient automatically receives a license from the
+original licensor to copy, distribute or modify the Program subject to
+these terms and conditions.  You may not impose any further
+restrictions on the recipients' exercise of the rights granted herein.
+You are not responsible for enforcing compliance by third parties to
+this License.
+
+  7. If, as a consequence of a court judgment or allegation of patent
+infringement or for any other reason (not limited to patent issues),
+conditions are imposed on you (whether by court order, agreement or
+otherwise) that contradict the conditions of this License, they do not
+excuse you from the conditions of this License.  If you cannot
+distribute so as to satisfy simultaneously your obligations under this
+License and any other pertinent obligations, then as a consequence you
+may not distribute the Program at all.  For example, if a patent
+license would not permit royalty-free redistribution of the Program by
+all those who receive copies directly or indirectly through you, then
+the only way you could satisfy both it and this License would be to
+refrain entirely from distribution of the Program.
+
+If any portion of this section is held invalid or unenforceable under
+any particular circumstance, the balance of the section is intended to
+apply and the section as a whole is intended to apply in other
+circumstances.
+
+It is not the purpose of this section to induce you to infringe any
+patents or other property right claims or to contest validity of any
+such claims; this section has the sole purpose of protecting the
+integrity of the free software distribution system, which is
+implemented by public license practices.  Many people have made
+generous contributions to the wide range of software distributed
+through that system in reliance on consistent application of that
+system; it is up to the author/donor to decide if he or she is willing
+to distribute software through any other system and a licensee cannot
+impose that choice.
+
+This section is intended to make thoroughly clear what is believed to
+be a consequence of the rest of this License.
+
+  8. If the distribution and/or use of the Program is restricted in
+certain countries either by patents or by copyrighted interfaces, the
+original copyright holder who places the Program under this License
+may add an explicit geographical distribution limitation excluding
+those countries, so that distribution is permitted only in or among
+countries not thus excluded.  In such case, this License incorporates
+the limitation as if written in the body of this License.
+
+  9. The Free Software Foundation may publish revised and/or new versions
+of the General Public License from time to time.  Such new versions will
+be similar in spirit to the present version, but may differ in detail to
+address new problems or concerns.
+
+Each version is given a distinguishing version number.  If the Program
+specifies a version number of this License which applies to it and "any
+later version", you have the option of following the terms and conditions
+either of that version or of any later version published by the Free
+Software Foundation.  If the Program does not specify a version number of
+this License, you may choose any version ever published by the Free Software
+Foundation.
+
+  10. If you wish to incorporate parts of the Program into other free
+programs whose distribution conditions are different, write to the author
+to ask for permission.  For software which is copyrighted by the Free
+Software Foundation, write to the Free Software Foundation; we sometimes
+make exceptions for this.  Our decision will be guided by the two goals
+of preserving the free status of all derivatives of our free software and
+of promoting the sharing and reuse of software generally.
+
+                            NO WARRANTY
+
+  11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
+FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW.  EXCEPT WHEN
+OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
+PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
+OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
+MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.  THE ENTIRE RISK AS
+TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU.  SHOULD THE
+PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
+REPAIR OR CORRECTION.
+
+  12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
+WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
+REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
+INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
+OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
+TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
+YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
+PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
+POSSIBILITY OF SUCH DAMAGES.
+
+                     END OF TERMS AND CONDITIONS
+
+            How to Apply These Terms to Your New Programs
+
+  If you develop a new program, and you want it to be of the greatest
+possible use to the public, the best way to achieve this is to make it
+free software which everyone can redistribute and change under these terms.
+
+  To do so, attach the following notices to the program.  It is safest
+to attach them to the start of each source file to most effectively
+convey the exclusion of warranty; and each file should have at least
+the "copyright" line and a pointer to where the full notice is found.
+
+    {description}
+    Copyright (C) {year}  {fullname}
+
+    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 2 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, write to the Free Software Foundation, Inc.,
+    51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
+
+Also add information on how to contact you by electronic and paper mail.
+
+If the program is interactive, make it output a short notice like this
+when it starts in an interactive mode:
+
+    Gnomovision version 69, Copyright (C) year name of author
+    Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
+    This is free software, and you are welcome to redistribute it
+    under certain conditions; type `show c' for details.
+
+The hypothetical commands `show w' and `show c' should show the appropriate
+parts of the General Public License.  Of course, the commands you use may
+be called something other than `show w' and `show c'; they could even be
+mouse-clicks or menu items--whatever suits your program.
+
+You should also get your employer (if you work as a programmer) or your
+school, if any, to sign a "copyright disclaimer" for the program, if
+necessary.  Here is a sample; alter the names:
+
+  Yoyodyne, Inc., hereby disclaims all copyright interest in the program
+  `Gnomovision' (which makes passes at compilers) written by James Hacker.
+
+  {signature of Ty Coon}, 1 April 1989
+  Ty Coon, President of Vice
+
+This General Public License does not permit incorporating your program into
+proprietary programs.  If your program is a subroutine library, you may
+consider it more useful to permit linking proprietary applications with the
+library.  If this is what you want to do, use the GNU Lesser General
+Public License instead of this License.

+ 66 - 0
plugins/pelican-toc/README.md

@@ -0,0 +1,66 @@
+pelican-toc [![Build Status](https://travis-ci.org/ingwinlu/pelican-toc.svg?branch=master)](https://travis-ci.org/ingwinlu/pelican-toc)
+===================================
+
+This plugin generates a table of contents for pelican articles and pages, available for themes via `article.toc`.
+
+#Usage
+##requirements
+Beautifulsoup4 - install via `pip install beautifulsoup4`
+##theme
+```
+{% if article.toc %}
+<div class="col-lg-3 hidden-xs hidden-sm">
+    {{article.toc}}
+</div>
+{% endif %}
+```
+##article
+```
+Title: Peeking at erlang/chicagoboss
+###Intro
+###Chicagoboss Magic
+###Result
+```
+##output
+```
+<div class="col-lg-3 hidden-xs hidden-sm">
+    <div id="toc">
+      <ul>
+        <li>
+          <a href="#" title="Peeking at&nbsp;erlang/chicagoboss">Peeking at&nbsp;erlang/chicagoboss</a>
+          <ul>
+            <li>
+              <a href="#intro" title="Intro">Intro</a>
+            </li>
+            <li>
+              <a href="#chicagoboss-magic" title="Chicagoboss&nbsp;Magic">Chicagoboss&nbsp;Magic</a>
+            </li>
+            <li>
+              <a href="#result" title="Result">Result</a>
+            </li>
+          </ul>
+        </li>
+      </ul>
+    </div>
+</div>
+```
+
+##settings
+```
+TOC = {
+    'TOC_HEADERS' : '^h[1-6]',  # What headers should be included in the generated toc
+                                # Expected format is a regular expression
+
+    'TOC_RUN'     : 'true'      # Default value for toc generation, if it does not evaluate
+                                # to 'true' no toc will be generated
+}
+```
+All those settings can be overwritten on a per page/article basis via metadata.
+Just use the respective keyword as metadata (example: `toc_headers: ^h[1-4]`)
+
+#Differences between pelican-toc and pelican-extract-toc
+`extract-toc` uses a markdown extension to generate a toc and then extract it via beautifulsoup.
+This extension generates the toc itself, removing the need to write `[ToC]` in your articles.
+There also is a 'health' check on id's which should be generated via markdown.extensions.headerid per default, but somehow don't always end up in the output. 
+
+

+ 1 - 0
plugins/pelican-toc/__init__.py

@@ -0,0 +1 @@
+from .toc import *

+ 1 - 0
plugins/pelican-toc/dev_requirements.txt

@@ -0,0 +1 @@
+Markdown

+ 11 - 0
plugins/pelican-toc/test_data/article_with_headers.md

@@ -0,0 +1,11 @@
+Title: Peeking at erlang/chicagoboss
+Date: 2014-03-07 00:19:24
+
+###Intro
+
+an article with headers
+
+###Magic
+
+###Result
+

+ 15 - 0
plugins/pelican-toc/test_data/article_with_headers_exclude_small_headers.md

@@ -0,0 +1,15 @@
+Title: headers of all sizes
+Date: 2015-06-02 00:56:24
+
+# 1
+
+## 2
+
+### 3
+
+#### 4
+
+##### 5
+
+###### 6
+

+ 16 - 0
plugins/pelican-toc/test_data/article_with_headers_exclude_small_headers_metadata.md

@@ -0,0 +1,16 @@
+Title: headers of all sizes
+Date: 2015-06-02 00:56:24
+toc_headers: ^h[1-3]
+
+# 1
+
+## 2
+
+### 3
+
+#### 4
+
+##### 5
+
+###### 6
+

+ 12 - 0
plugins/pelican-toc/test_data/article_with_headers_metadata.md

@@ -0,0 +1,12 @@
+Title: Peeking at erlang/chicagoboss
+Date: 2014-03-07 00:19:24
+toc_run: false
+
+###Intro
+
+an article with headers
+
+###Magic
+
+###Result
+

+ 15 - 0
plugins/pelican-toc/test_data/article_with_headers_nonascii.md

@@ -0,0 +1,15 @@
+Title: headers in non ascii
+Date: 2015-06-01 00:19:24
+
+###введение
+
+russian intro
+
+###魔術
+
+traditional chinese magic
+
+###αποτέλεσμα
+
+greek result
+

+ 1 - 0
plugins/pelican-toc/test_data/article_with_headers_toc.html

@@ -0,0 +1 @@
+<div id="toc"><ul><li><a class="toc-href" href="#" title="Peeking at erlang/chicagoboss">Peeking at erlang/chicagoboss</a><ul><li><a class="toc-href" href="#intro" title="Intro">Intro</a></li><li><a class="toc-href" href="#magic" title="Magic">Magic</a></li><li><a class="toc-href" href="#result" title="Result">Result</a></li></ul></li></ul></div>

+ 1 - 0
plugins/pelican-toc/test_data/article_with_headers_toc_exclude_small_headers.html

@@ -0,0 +1 @@
+<div id="toc"><ul><li><a class="toc-href" href="#" title="headers of all sizes">headers of all sizes</a><ul><li><a class="toc-href" href="#1" title="1">1</a><ul><li><a class="toc-href" href="#2" title="2">2</a><ul><li><a class="toc-href" href="#3" title="3">3</a></li></ul></li></ul></li></ul></li></ul></div>

+ 1 - 0
plugins/pelican-toc/test_data/article_with_headers_toc_nonascii.html

@@ -0,0 +1 @@
+<div id="toc"><ul><li><a class="toc-href" href="#" title="headers in non ascii">headers in non ascii</a><ul><li><a class="toc-href" href="#vvedenie" title="введение">введение</a></li><li><a class="toc-href" href="#mo-shu" title="魔術">魔術</a></li><li><a class="toc-href" href="#apotelesma" title="&alpha;&pi;&omicron;&tau;έ&lambda;&epsilon;&sigma;&mu;&alpha;">&alpha;&pi;&omicron;&tau;έ&lambda;&epsilon;&sigma;&mu;&alpha;</a></li></ul></li></ul></div>

+ 5 - 0
plugins/pelican-toc/test_data/article_without_headers.md

@@ -0,0 +1,5 @@
+Title: Peeking at erlang/chicagoboss
+Date: 2014-03-07 00:19:24
+
+an article without headers
+

+ 94 - 0
plugins/pelican-toc/test_toc.py

@@ -0,0 +1,94 @@
+from io import open
+
+import unittest
+import re
+import toc
+
+from pelican.readers import MarkdownReader
+from pelican.contents import Article
+from pelican.tests.support import get_settings
+
+
+class TestToCGeneration(unittest.TestCase):
+
+    @classmethod
+    def setUpClass(cls):
+        toc.init_default_config(None)
+        cls.settings = get_settings()
+        cls.md_reader = MarkdownReader(cls.settings)
+
+    def setUp(self):
+        # have to reset the default, because shallow copies
+        self.settings['TOC']['TOC_HEADERS'] = '^h[1-6]'
+        self.settings['TOC']['TOC_RUN'] = 'true'
+
+    def _handle_article_generation(self, path):
+        content, metadata = self.md_reader.read(path)
+        return Article(content=content, metadata=metadata)
+
+    def _generate_toc(self, article_path, expected_path):
+        result = self._handle_article_generation(article_path)
+        toc.generate_toc(result)
+        expected = ""
+        with open(expected_path, 'r') as f:
+            expected = f.read()
+        return result, expected
+
+
+    def test_toc_generation(self):
+        result, expected = self._generate_toc(
+                "test_data/article_with_headers.md",
+                "test_data/article_with_headers_toc.html"
+            )
+        self.assertEqual(result.toc, expected)
+
+    def test_toc_generation_nonascii(self):
+        result, expected = self._generate_toc(
+                "test_data/article_with_headers_nonascii.md",
+                "test_data/article_with_headers_toc_nonascii.html"
+            )
+        self.assertEqual(result.toc, expected)
+
+    def test_toc_generation_exclude_small_headers(self):
+        self.settings['TOC']['TOC_HEADERS'] = '^h[1-3]'
+        result, expected = self._generate_toc(
+                "test_data/article_with_headers_exclude_small_headers.md",
+                "test_data/article_with_headers_toc_exclude_small_headers.html"
+            )
+        self.assertEqual(result.toc, expected)
+
+    def test_toc_generation_exclude_small_headers_metadata(self):
+        result, expected = self._generate_toc(
+                "test_data/article_with_headers_exclude_small_headers_metadata.md",
+                "test_data/article_with_headers_toc_exclude_small_headers.html"
+            )
+        self.assertEqual(result.toc, expected)
+
+
+    def test_bad_TOC_HEADERS(self):
+        self.settings['TOC']['TOC_HEADERS'] = '^[1-'
+        with self.assertRaises(re.error):
+            self._generate_toc(
+                "test_data/article_with_headers_exclude_small_headers.md",
+                "test_data/article_with_headers_toc_exclude_small_headers.html"
+            )
+
+    def test_no_toc_generation(self):
+        article_without_headers_path = "test_data/article_without_headers.md"
+        article_without_headers = self._handle_article_generation(
+            article_without_headers_path)
+        toc.generate_toc(article_without_headers)
+        with self.assertRaises(AttributeError):
+            self.assertIsNone(article_without_headers.toc)
+
+    def test_no_toc_generation_metadata(self):
+        article_without_headers_path = "test_data/article_with_headers_metadata.md"
+        article_without_headers = self._handle_article_generation(
+            article_without_headers_path)
+        toc.generate_toc(article_without_headers)
+        with self.assertRaises(AttributeError):
+            self.assertIsNone(article_without_headers.toc)
+ 
+
+if __name__ == "__main__":
+    unittest.main()

+ 145 - 0
plugins/pelican-toc/toc.py

@@ -0,0 +1,145 @@
+'''
+toc
+===================================
+
+This plugin generates tocs for pages and articles.
+'''
+
+from __future__ import unicode_literals
+
+import logging
+import re
+
+from bs4 import BeautifulSoup, Comment
+
+from pelican import contents, signals
+from pelican.utils import python_2_unicode_compatible, slugify
+
+
+logger = logging.getLogger(__name__)
+
+'''
+https://github.com/waylan/Python-Markdown/blob/master/markdown/extensions/headerid.py
+'''
+IDCOUNT_RE = re.compile(r'^(.*)_([0-9]+)$')
+
+
+def unique(id, ids):
+    """ Ensure id is unique in set of ids. Append '_1', '_2'... if not """
+    while id in ids or not id:
+        m = IDCOUNT_RE.match(id)
+        if m:
+            id = '%s_%d' % (m.group(1), int(m.group(2)) + 1)
+        else:
+            id = '%s_%d' % (id, 1)
+    ids.add(id)
+    return id
+'''
+end
+'''
+
+
+@python_2_unicode_compatible
+class HtmlTreeNode(object):
+    def __init__(self, parent, header, level, id):
+        self.children = []
+        self.parent = parent
+        self.header = header
+        self.level = level
+        self.id = id
+
+    def add(self, new_header, ids):
+        new_level = new_header.name
+        new_string = new_header.string
+        new_id = new_header.attrs.get('id')
+
+        if not new_string:
+            new_string = new_header.find_all(
+                    text=lambda t: not isinstance(t, Comment),
+                    recursive=True)
+            new_string = "".join(new_string)
+
+        if not new_id:
+            new_id = slugify(new_string, ())
+
+        new_id = unique(new_id, ids)  # make sure id is unique
+        new_header.attrs['id'] = new_id
+        if(self.level < new_level):
+            new_node = HtmlTreeNode(self, new_string, new_level, new_id)
+            self.children += [new_node]
+            return new_node, new_header
+        elif(self.level == new_level):
+            new_node = HtmlTreeNode(self.parent, new_string, new_level, new_id)
+            self.parent.children += [new_node]
+            return new_node, new_header
+        elif(self.level > new_level):
+            return self.parent.add(new_header, ids)
+
+    def __str__(self):
+        ret = "<a class='toc-href' href='#{0}' title='{1}'>{1}</a>".format(
+                self.id, self.header)
+
+        if self.children:
+            ret += "<ul>{}</ul>".format('{}'*len(self.children)).format(
+                    *self.children)
+
+        ret = "<li>{}</li>".format(ret)
+
+        if not self.parent:
+            ret = "<div id='toc'><ul>{}</ul></div>".format(ret)
+
+        return ret
+
+
+def init_default_config(pelican):
+    from pelican.settings import DEFAULT_CONFIG
+
+    TOC_DEFAULT = {
+        'TOC_HEADERS': '^h[1-6]',
+        'TOC_RUN': 'true'
+    }
+
+    DEFAULT_CONFIG.setdefault('TOC', TOC_DEFAULT)
+    if(pelican):
+        pelican.settings.setdefault('TOC', TOC_DEFAULT)
+
+
+def generate_toc(content):
+    if isinstance(content, contents.Static):
+        return
+
+    _toc_run = content.metadata.get(
+            'toc_run',
+            content.settings['TOC']['TOC_RUN'])
+    if not _toc_run == 'true':
+        return
+
+    all_ids = set()
+    title = content.metadata.get('title', 'Title')
+    tree = node = HtmlTreeNode(None, title, 'h0', '')
+    soup = BeautifulSoup(content._content, 'html.parser')
+    settoc = False
+
+    try:
+        header_re = re.compile(content.metadata.get(
+            'toc_headers', content.settings['TOC']['TOC_HEADERS']))
+    except re.error as e:
+        logger.error("TOC_HEADERS '%s' is not a valid re\n%s",
+                     content.settings['TOC']['TOC_HEADERS'])
+        raise e
+
+    for header in soup.findAll(header_re):
+        settoc = True
+        node, new_header = node.add(header, all_ids)
+        header.replaceWith(new_header)  # to get our ids back into soup
+
+    if (settoc):
+        tree_string = '{}'.format(tree)
+        tree_soup = BeautifulSoup(tree_string, 'html.parser')
+        content.toc = tree_soup.decode(formatter='html')
+    content._content = soup.decode(formatter='html')
+
+
+def register():
+    signals.initialized.connect(init_default_config)
+    signals.content_object_init.connect(generate_toc)

+ 36 - 0
plugins/pelican-toc/tox.ini

@@ -0,0 +1,36 @@
+[tox]
+skipsdist = true
+envlist = py{27,33,34}-pelican{34,35,36,dev}
+
+[testenv]
+basepython =
+    py27: python2.7
+    py33: python3.3
+    py34: python3.4
+deps =
+    pelican34: git+https://github.com/getpelican/pelican.git@3.4.0#egg=pelican
+    pelican35: git+https://github.com/getpelican/pelican.git@3.5.0#egg=pelican
+    pelican36: git+https://github.com/getpelican/pelican.git@3.6.3#egg=pelican
+    pelicandev: git+https://github.com/getpelican/pelican.git#egg=pelican
+    beautifulsoup4
+    -rdev_requirements.txt
+passenv = *
+install_command= pip install {opts} -e {packages}
+commands =
+    {envpython} --version
+    pelican --version
+    {envpython} test_toc.py
+
+[flake8]
+application-import-names=toc
+import-order-style=cryptography
+
+[testenv:flake8]
+basepython = python2.7
+deps =
+    flake8 <= 2.4.1
+    git+https://github.com/public/flake8-import-order@2ac7052a4e02b4a8a0125a106d87465a3b9fd688
+install_command= pip install {opts} {packages}
+commands =
+    flake8 --version
+    flake8 toc.py