Compare commits

...

4 Commits

Author SHA1 Message Date
0e02ae3182 changelog 2019-03-24 20:27:26 +01:00
ac42fd509c remove documentation (now in a separate project) 2019-03-24 20:26:51 +01:00
4709ac5f01 corrections in debug logger 2019-03-23 08:26:39 +01:00
cab8dae15a requirement can have callback 2019-03-13 08:49:18 +01:00
48 changed files with 766 additions and 2977 deletions

View File

@ -1,13 +1,21 @@
Sun Mar 24 20:24:34 2019
* version 3.0 rc3
* corrections in debug logger
* requirement can have callback
* version 3.0 rc2
* add cidr notation to domainnameoption if allow_ip is True (fixes #5)
* safer option.type() (ref #4)
Tue Mar 5 08:22:12 2018 +0200 Emmanuel Garette <egarette@cadoles.com>
* version 3.0 rc2
* simplifying netmaskoption
* multiple option call (fixes #1)
* doesn't check follower requirement with an other follower or a leader if idx is None (fixes #3)
Mon Feb 25 10:12:35 2018 +0200 Emmanuel Garette <egarette@cadoles.com>
Mon Feb 25 10:12:35 2019 +0200 Emmanuel Garette <egarette@cadoles.com>
* version 3.0 rc1
Sat Sep 8 22:54:12 2018 +0200 Emmanuel Garette <egarette@cadoles.com>
Sat Sep 8 22:54:12 2019 +0200 Emmanuel Garette <egarette@cadoles.com>
* propose a new API to access to Tiramisu Option
This new API is totally incompatible with older's one

View File

@ -1,153 +0,0 @@
# Makefile for Sphinx documentation
#
# You can set these variables from the command line.
SPHINXOPTS =
SPHINXBUILD = sphinx-build
PAPER =
BUILDDIR = _build
# Internal variables.
PAPEROPT_a4 = -D latex_paper_size=a4
PAPEROPT_letter = -D latex_paper_size=letter
ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) .
# the i18n builder cannot share the environment and doctrees with the others
I18NSPHINXOPTS = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) .
.PHONY: help clean html dirhtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest gettext
help:
@echo "Please use \`make <target>' where <target> is one of"
@echo " html to make standalone HTML files"
@echo " dirhtml to make HTML files named index.html in directories"
@echo " singlehtml to make a single large HTML file"
@echo " pickle to make pickle files"
@echo " json to make JSON files"
@echo " htmlhelp to make HTML files and a HTML help project"
@echo " qthelp to make HTML files and a qthelp project"
@echo " devhelp to make HTML files and a Devhelp project"
@echo " epub to make an epub"
@echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter"
@echo " latexpdf to make LaTeX files and run them through pdflatex"
@echo " text to make text files"
@echo " man to make manual pages"
@echo " texinfo to make Texinfo files"
@echo " info to make Texinfo files and run them through makeinfo"
@echo " gettext to make PO message catalogs"
@echo " changes to make an overview of all changed/added/deprecated items"
@echo " linkcheck to check all external links for integrity"
@echo " doctest to run all doctests embedded in the documentation (if enabled)"
clean:
-rm -rf $(BUILDDIR)/*
html:
$(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html
@echo
@echo "Build finished. The HTML pages are in $(BUILDDIR)/html."
dirhtml:
$(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml
@echo
@echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml."
singlehtml:
$(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml
@echo
@echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml."
pickle:
$(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle
@echo
@echo "Build finished; now you can process the pickle files."
json:
$(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json
@echo
@echo "Build finished; now you can process the JSON files."
htmlhelp:
$(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp
@echo
@echo "Build finished; now you can run HTML Help Workshop with the" \
".hhp project file in $(BUILDDIR)/htmlhelp."
qthelp:
$(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp
@echo
@echo "Build finished; now you can run "qcollectiongenerator" with the" \
".qhcp project file in $(BUILDDIR)/qthelp, like this:"
@echo "# qcollectiongenerator $(BUILDDIR)/qthelp/tiramisu.qhcp"
@echo "To view the help file:"
@echo "# assistant -collectionFile $(BUILDDIR)/qthelp/tiramisu.qhc"
devhelp:
$(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp
@echo
@echo "Build finished."
@echo "To view the help file:"
@echo "# mkdir -p $$HOME/.local/share/devhelp/tiramisu"
@echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/tiramisu"
@echo "# devhelp"
epub:
$(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub
@echo
@echo "Build finished. The epub file is in $(BUILDDIR)/epub."
latex:
$(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex
@echo
@echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex."
@echo "Run \`make' in that directory to run these through (pdf)latex" \
"(use \`make latexpdf' here to do that automatically)."
latexpdf:
$(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex
@echo "Running LaTeX files through pdflatex..."
$(MAKE) -C $(BUILDDIR)/latex all-pdf
@echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex."
text:
$(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text
@echo
@echo "Build finished. The text files are in $(BUILDDIR)/text."
man:
$(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man
@echo
@echo "Build finished. The manual pages are in $(BUILDDIR)/man."
texinfo:
$(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo
@echo
@echo "Build finished. The Texinfo files are in $(BUILDDIR)/texinfo."
@echo "Run \`make' in that directory to run these through makeinfo" \
"(use \`make info' here to do that automatically)."
info:
$(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo
@echo "Running Texinfo files through makeinfo..."
make -C $(BUILDDIR)/texinfo info
@echo "makeinfo finished; the Info files are in $(BUILDDIR)/texinfo."
gettext:
$(SPHINXBUILD) -b gettext $(I18NSPHINXOPTS) $(BUILDDIR)/locale
@echo
@echo "Build finished. The message catalogs are in $(BUILDDIR)/locale."
changes:
$(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes
@echo
@echo "The overview file is in $(BUILDDIR)/changes."
linkcheck:
$(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck
@echo
@echo "Link check complete; look for any errors in the above output " \
"or in $(BUILDDIR)/linkcheck/output.txt."
doctest:
$(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest
@echo "Testing of doctests in the sources finished, look at the " \
"results in $(BUILDDIR)/doctest/output.txt."

View File

@ -1,6 +0,0 @@
{{ fullname }}
{{ underline }}
.. automodule:: {{ fullname }}
:members:
:noindex:

View File

@ -1,15 +0,0 @@
Auto generated library's API
================================
.. autosummary::
:toctree: api
:template: module.rst
tiramisu.option
tiramisu.setting
tiramisu.config
tiramisu.value
tiramisu.autolib
tiramisu.error
tiramisu.storage

View File

@ -1,6 +0,0 @@
tiramisu.autolib
================
.. automodule:: tiramisu.autolib
:members:
:noindex:

View File

@ -1,6 +0,0 @@
tiramisu.config
===============
.. automodule:: tiramisu.config
:members:
:noindex:

View File

@ -1,6 +0,0 @@
tiramisu.error
==============
.. automodule:: tiramisu.error
:members:
:noindex:

View File

@ -1,6 +0,0 @@
tiramisu.option
===============
.. automodule:: tiramisu.option
:members:
:noindex:

View File

@ -1,5 +0,0 @@
tiramisu.setting
================
.. automodule:: tiramisu.setting
:members:

View File

@ -1,6 +0,0 @@
tiramisu.storage
================
.. automodule:: tiramisu.storage
:members:
:noindex:

View File

@ -1,5 +0,0 @@
tiramisu.value
==============
.. automodule:: tiramisu.value
:members:

View File

@ -1,295 +0,0 @@
# -*- coding: utf-8 -*-
#
# tiramisu documentation build configuration file, created by
# sphinx-quickstart on Tue Nov 20 14:29:31 2012.
#
# This file is execfile()d with the current directory set to its containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# All configuration values have a default; values that are commented out
# serve to show the default.
import sys, os
# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
#sys.path.insert(0, os.path.abspath('.'))
# -- General configuration -----------------------------------------------------
# If your documentation needs a minimal Sphinx version, state it here.
#needs_sphinx = '1.0'
# Add any Sphinx extension module names here, as strings. They can be extensions
# coming with Sphinx (named 'sphinx.ext.*') or your custom ones.
extensions = ['sphinx.ext.autodoc', 'sphinx.ext.todo', 'sphinx.ext.coverage', 'sphinx.ext.viewcode', 'sphinx.ext.autosummary', 'sphinx.ext.extlinks']
# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']
# The suffix of source filenames.
source_suffix = '.txt'
# The encoding of source files.
#source_encoding = 'utf-8-sig'
# The master toctree document.
master_doc = 'index'
# General information about the project.
project = u'tiramisu'
copyright = u'2013, tiramisu team'
# The version info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the
# built documents.
#
# The short X.Y version.
version = '1'
# The full version, including alpha/beta/rc tags.
release = '1.0'
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
#language = None
# There are two options for replacing |today|: either, you set today to some
# non-false value, then it is used:
#today = ''
# Else, today_fmt is used as the format for a strftime call.
#today_fmt = '%B %d, %Y'
# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
exclude_patterns = ['_build']
# The reST default role (used for this markup: `text`) to use for all documents.
#default_role = None
# If true, '()' will be appended to :func: etc. cross-reference text.
#add_function_parentheses = True
# If true, the current module name will be prepended to all description
# unit titles (such as .. function::).
#add_module_names = True
# If true, sectionauthor and moduleauthor directives will be shown in the
# output. They are ignored by default.
#show_authors = False
# The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'sphinx'
# A list of ignored prefixes for module index sorting.
#modindex_common_prefix = []
# -- Options for HTML output ---------------------------------------------------
# The theme to use for HTML and HTML Help pages. See the documentation for
# a list of builtin themes.
html_theme = 'traditional'
# Theme options are theme-specific and customize the look and feel of a theme
# further. For a list of options available for each theme, see the
# documentation.
#html_theme_options = {}
# Add any paths that contain custom themes here, relative to this directory.
#html_theme_path = []
# The name for this set of Sphinx documents. If None, it defaults to
# "<project> v<release> documentation".
#html_title = None
# A shorter title for the navigation bar. Default is the same as html_title.
#html_short_title = None
# The name of an image file (relative to this directory) to place at the top
# of the sidebar.
#html_logo = None
# The name of an image file (within the static path) to use as favicon of the
# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32
# pixels large.
#html_favicon = None
# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ['_static']
# If not '', a 'Last updated on:' timestamp is inserted at every page bottom,
# using the given strftime format.
#html_last_updated_fmt = '%b %d, %Y'
# If true, SmartyPants will be used to convert quotes and dashes to
# typographically correct entities.
#html_use_smartypants = True
# Custom sidebar templates, maps document names to template names.
#html_sidebars = {}
# Additional templates that should be rendered to pages, maps page names to
# template names.
#html_additional_pages = {}
# If false, no module index is generated.
#html_domain_indices = True
# If false, no index is generated.
#html_use_index = True
# If true, the index is split into individual pages for each letter.
#html_split_index = False
# If true, links to the reST sources are added to the pages.
#html_show_sourcelink = True
# If true, "Created using Sphinx" is shown in the HTML footer. Default is True.
#html_show_sphinx = True
# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True.
#html_show_copyright = True
# If true, an OpenSearch description file will be output, and all pages will
# contain a <link> tag referring to it. The value of this option must be the
# base URL from which the finished HTML is served.
#html_use_opensearch = ''
# This is the file name suffix for HTML files (e.g. ".xhtml").
#html_file_suffix = None
# Output file base name for HTML help builder.
htmlhelp_basename = 'tiramisudoc'
# -- Options for LaTeX output --------------------------------------------------
latex_elements = {
# The paper size ('letterpaper' or 'a4paper').
#'papersize': 'letterpaper',
# The font size ('10pt', '11pt' or '12pt').
#'pointsize': '10pt',
# Additional stuff for the LaTeX preamble.
#'preamble': '',
}
# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title, author, documentclass [howto/manual]).
latex_documents = [
('index', 'tiramisu.tex', u'tiramisu Documentation',
u'gwen', 'manual'),
]
# The name of an image file (relative to this directory) to place at the top of
# the title page.
#latex_logo = None
# For "manual" documents, if this is true, then toplevel headings are parts,
# not chapters.
#latex_use_parts = False
# If true, show page references after internal links.
#latex_show_pagerefs = False
# If true, show URL addresses after external links.
#latex_show_urls = False
# Documents to append as an appendix to all manuals.
#latex_appendices = []
# If false, no module index is generated.
#latex_domain_indices = True
# -- Options for manual page output --------------------------------------------
# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
man_pages = [
('index', 'tiramisu', u'tiramisu Documentation',
[u'gwen'], 1)
]
# If true, show URL addresses after external links.
#man_show_urls = False
# -- Options for Texinfo output ------------------------------------------------
# Grouping the document tree into Texinfo files. List of tuples
# (source start file, target name, title, author,
# dir menu entry, description, category)
texinfo_documents = [
('index', 'tiramisu', u'tiramisu Documentation',
u'gwen', 'tiramisu', 'One line description of project.',
'Miscellaneous'),
]
# Documents to append as an appendix to all manuals.
#texinfo_appendices = []
# If false, no module index is generated.
#texinfo_domain_indices = True
# How to display URL addresses: 'footnote', 'no', or 'inline'.
#texinfo_show_urls = 'footnote'
# -- Options for Epub output ---------------------------------------------------
# Bibliographic Dublin Core info.
epub_title = u'tiramisu'
epub_author = u'gwen'
epub_publisher = u'gwen'
epub_copyright = u'2012, gwen'
# The language of the text. It defaults to the language option
# or en if the language is not set.
#epub_language = ''
# The scheme of the identifier. Typical schemes are ISBN or URL.
#epub_scheme = ''
# The unique identifier of the text. This can be a ISBN number
# or the project homepage.
#epub_identifier = ''
# A unique identification for the text.
#epub_uid = ''
# A tuple containing the cover image and cover page html template filenames.
#epub_cover = ()
# HTML files that should be inserted before the pages created by sphinx.
# The format is a list of tuples containing the path and title.
#epub_pre_files = []
# HTML files shat should be inserted after the pages created by sphinx.
# The format is a list of tuples containing the path and title.
#epub_post_files = []
# A list of files that should not be packed into the epub file.
#epub_exclude_files = []
# The depth of the table of contents in toc.ncx.
#epub_tocdepth = 3
# Allow duplicate toc entries.
#epub_tocdup = True
todo_include_todos = True
extlinks = {'api': ('./api/tiramisu.%s', ""),
'test': ('./api/test.%s', "")}
autosummary_generate = True

Binary file not shown.

Before

Width:  |  Height:  |  Size: 15 KiB

View File

@ -1,257 +0,0 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!-- Created with Inkscape (http://www.inkscape.org/) -->
<svg
xmlns:dc="http://purl.org/dc/elements/1.1/"
xmlns:cc="http://creativecommons.org/ns#"
xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
xmlns:svg="http://www.w3.org/2000/svg"
xmlns="http://www.w3.org/2000/svg"
xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd"
xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape"
width="400"
height="200"
id="svg2"
version="1.1"
inkscape:version="0.48.4 r9939"
sodipodi:docname="test.svg"
inkscape:export-filename="/home/gnunux/git/tiramisu/doc/storage.png"
inkscape:export-xdpi="135"
inkscape:export-ydpi="135">
<defs
id="defs4">
<inkscape:perspective
sodipodi:type="inkscape:persp3d"
inkscape:vp_x="0 : 526.18109 : 1"
inkscape:vp_y="0 : 1000 : 0"
inkscape:vp_z="744.09448 : 526.18109 : 1"
inkscape:persp3d-origin="372.04724 : 350.78739 : 1"
id="perspective3827" />
</defs>
<sodipodi:namedview
id="base"
pagecolor="#ffffff"
bordercolor="#666666"
borderopacity="1.0"
inkscape:pageopacity="1"
inkscape:pageshadow="2"
inkscape:zoom="1"
inkscape:cx="73.881208"
inkscape:cy="154.11692"
inkscape:document-units="px"
inkscape:current-layer="layer1"
showgrid="false"
inkscape:window-width="1600"
inkscape:window-height="841"
inkscape:window-x="0"
inkscape:window-y="27"
inkscape:window-maximized="1" />
<metadata
id="metadata7">
<rdf:RDF>
<cc:Work
rdf:about="">
<dc:format>image/svg+xml</dc:format>
<dc:type
rdf:resource="http://purl.org/dc/dcmitype/StillImage" />
<dc:title></dc:title>
</cc:Work>
</rdf:RDF>
</metadata>
<g
inkscape:label="Calque 1"
inkscape:groupmode="layer"
id="layer1"
transform="translate(0,-852.36218)">
<g
id="g4206"
transform="translate(32.34835,646.56497)">
<text
sodipodi:linespacing="686.00001%"
id="text2985"
y="368.36218"
x="98"
style="font-size:10px;font-style:normal;font-weight:normal;line-height:686.00001335%;letter-spacing:0px;word-spacing:0px;fill:#000000;fill-opacity:1;stroke:none;font-family:Sans"
xml:space="preserve"><tspan
y="368.36218"
x="98"
id="tspan2987"
sodipodi:role="line">Config</tspan></text>
<rect
y="351.36218"
x="81"
height="30"
width="63"
id="rect3757"
style="fill:none;stroke:#000000;stroke-linejoin:round;stroke-opacity:1" />
</g>
<g
id="g4211"
transform="translate(-21.922096,643.64303)">
<rect
y="312.36218"
x="189.5"
height="30"
width="63"
id="rect3757-2"
style="fill:none;stroke:#000000;stroke-linejoin:round;stroke-opacity:1" />
<text
sodipodi:linespacing="100%"
id="text3777"
y="325.76599"
x="220.51762"
style="font-size:10px;font-style:normal;font-weight:normal;text-align:center;line-height:100%;letter-spacing:0px;word-spacing:0px;text-anchor:middle;fill:#000000;fill-opacity:1;stroke:none;font-family:Sans"
xml:space="preserve"><tspan
y="325.76599"
x="220.51762"
id="tspan3779"
sodipodi:role="line">Option</tspan><tspan
y="335.76599"
x="220.51762"
sodipodi:role="line"
id="tspan3022">Description</tspan></text>
</g>
<g
id="g4201"
transform="translate(11,622)">
<rect
y="293.42468"
x="81"
height="30"
width="63"
id="rect3757-5"
style="fill:none;stroke:#000000;stroke-linejoin:round;stroke-opacity:1" />
<text
sodipodi:linespacing="100%"
id="text4190"
y="309.42468"
x="110.27588"
style="font-size:10px;font-style:normal;font-weight:normal;text-align:center;line-height:100%;letter-spacing:0px;word-spacing:0px;text-anchor:middle;fill:#000000;fill-opacity:1;stroke:none;font-family:Sans"
xml:space="preserve"><tspan
id="tspan4194"
y="309.42468"
x="110.27588"
sodipodi:role="line">Option</tspan></text>
</g>
<g
id="g4201-9"
transform="translate(85.749784,621.95117)">
<rect
y="293.42468"
x="81"
height="30"
width="63"
id="rect3757-5-1"
style="fill:none;stroke:#000000;stroke-linejoin:round;stroke-opacity:1" />
<text
sodipodi:linespacing="100%"
id="text4190-0"
y="309.42468"
x="110.27588"
style="font-size:10px;font-style:normal;font-weight:normal;text-align:center;line-height:100%;letter-spacing:0px;word-spacing:0px;text-anchor:middle;fill:#000000;fill-opacity:1;stroke:none;font-family:Sans"
xml:space="preserve"><tspan
id="tspan4194-2"
y="309.42468"
x="110.27588"
sodipodi:role="line">Option</tspan></text>
</g>
<g
id="g4211-4"
transform="translate(52.525433,602.85429)">
<rect
y="312.36218"
x="189.5"
height="30"
width="63"
id="rect3757-2-3"
style="fill:none;stroke:#000000;stroke-linejoin:round;stroke-opacity:1" />
<text
sodipodi:linespacing="100%"
id="text3777-0"
y="325.76599"
x="220.51762"
style="font-size:10px;font-style:normal;font-weight:normal;text-align:center;line-height:100%;letter-spacing:0px;word-spacing:0px;text-anchor:middle;fill:#000000;fill-opacity:1;stroke:none;font-family:Sans"
xml:space="preserve"><tspan
y="325.76599"
x="220.51762"
id="tspan3779-1"
sodipodi:role="line">Option</tspan><tspan
y="335.76599"
x="220.51762"
sodipodi:role="line"
id="tspan3022-7">Description</tspan></text>
</g>
<g
id="g4201-1"
transform="translate(123.6527,582.89051)">
<rect
y="293.42468"
x="81"
height="30"
width="63"
id="rect3757-5-7"
style="fill:none;stroke:#000000;stroke-linejoin:round;stroke-opacity:1" />
<text
sodipodi:linespacing="100%"
id="text4190-2"
y="309.42468"
x="110.27588"
style="font-size:10px;font-style:normal;font-weight:normal;text-align:center;line-height:100%;letter-spacing:0px;word-spacing:0px;text-anchor:middle;fill:#000000;fill-opacity:1;stroke:none;font-family:Sans"
xml:space="preserve"><tspan
id="tspan4194-8"
y="309.42468"
x="110.27588"
sodipodi:role="line">Option</tspan></text>
</g>
<path
style="fill:none;stroke:#000000;stroke-width:1px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1"
d="m 151.43627,945.42468 19.70537,10.58053"
id="path3110"
inkscape:connector-type="polyline"
inkscape:connector-curvature="0"
inkscape:connection-start="#g4201"
inkscape:connection-start-point="d4"
inkscape:connection-end="#g4211"
inkscape:connection-end-point="d4" />
<path
style="fill:none;stroke:#000000;stroke-width:1px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1"
d="m 198.77217,956.00521 -0.21665,-10.62936"
id="path3112"
inkscape:connector-type="polyline"
inkscape:connector-curvature="0"
inkscape:connection-start="#g4211"
inkscape:connection-start-point="d4"
inkscape:connection-end="#g4201-9"
inkscape:connection-end-point="d4" />
<path
style="fill:none;stroke:#000000;stroke-width:1px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1"
d="m 226.45587,956.00521 19.69159,-10.78874"
id="path3114"
inkscape:connector-type="polyline"
inkscape:connector-curvature="0"
inkscape:connection-start="#g4211"
inkscape:connection-start-point="d4"
inkscape:connection-end="#g4211-4"
inkscape:connection-end-point="d4" />
<path
style="fill:none;stroke:#000000;stroke-width:1px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1"
d="m 259.11483,915.21647 -8.55152,-8.90128"
id="path3116"
inkscape:connector-type="polyline"
inkscape:connector-curvature="0"
inkscape:connection-start="#g4211-4"
inkscape:connection-start-point="d4"
inkscape:connection-end="#g4201-1"
inkscape:connection-end-point="d4" />
<path
style="fill:none;stroke:#000000;stroke-width:1px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1"
d="m 164.25211,997.92715 15.42203,-11.92194"
id="path3118"
inkscape:connector-type="polyline"
inkscape:connector-curvature="0"
inkscape:connection-start="#g4206"
inkscape:connection-start-point="d4"
inkscape:connection-end="#g4211"
inkscape:connection-end-point="d4" />
</g>
</svg>

Before

Width:  |  Height:  |  Size: 9.0 KiB

View File

@ -1,570 +0,0 @@
.. default-role:: literal
===============================
Options handling basics
===============================
Tiramisu is made of almost three main objects :
- :class:`tiramisu.option.Option` stands for the option types
- :class:`tiramisu.option.OptionDescription` is the shema, the option's structure
- :class:`tiramisu.config.Config` which is the whole configuration entry point
Accessing the `Option`'s
-------------------------
The :class:`~tiramisu.config.Config` object attribute access notation stands for
the value of the configuration's :class:`~tiramisu.option.Option`.
:class:`~tiramisu.config.Config`'s object attribute is the name of the option,
and the value is the value accessed by the `__getattr__` attribute access
mechanism.
If the attribute of the `Config` called by `__getattr__` has not been set before
(by the classic `__setattr__` mechanism), the default value of the `Option`
object is returned, and if no `Option` has been declared in the
`OptionDescription` (that is the schema of the configuration), an
`AttributeError` is raised.
::
>>> from tiramisu.config import Config
>>> from tiramisu.option import BoolOption, OptionDescription
>>>
>>> gcdummy = BoolOption('dummy', 'dummy', default=False)
>>> gcdummy.impl_getdefault()
False
>>> cfg.dummy
False
>>> descr = OptionDescription('tiramisu', '', [gcdummy])
>>> cfg = Config(descr)
>>> cfg.dummy = True
>>> cfg.dummy
True
>>> cfg.idontexist
AttributeError: 'OptionDescription' object has no attribute 'idontexist'
The `Option` objects (in this case the :class:`~tiramisu.option.BoolOption`),
are organized into a tree into nested
:class:`~tiramisu.option.OptionDescription` objects.
.. image:: config.png
Every option has a name, as does every option group. The parts
of the full name of the option are separated by dots: e.g.
``cfg.optgroup.optname``.
Let's make the protocol of accessing a `Config`'s attribute explicit
(because explicit is better than implicit):
1. If the option has not been declared, an `AttributeError` is raised,
2. If an option is declared, but neither a value nor a default value has
been set, the returned value is `None`,
3. If an option is declared and a default value has been set, but no value
has been set, the returned value is the default value of the option,
4. If an option is declared, and a value has been set, the returned value is
the value of the option.
But there are special exceptions. We will see later on that an option can be a
:term:`mandatory option`. A mandatory option is an option that must have a value
defined.
Setting the value of an option
------------------------------
An important part of the setting's configuration consists of setting the
value's option. There are different ways of setting values,
the first one is of course the `__setattr__` method
::
cfg.name = value
And if you wanna come back to a default value, use the builtin `del()` function::
del(cfg.name)
.. module:: tiramisu.config
.. _`tree`:
The handling of options
~~~~~~~~~~~~~~~~~~~~~~~~~~
The handling of options is split into two parts: the description of
which options are available, what their possible values and defaults are
and how they are organized into a tree. A specific choice of options is
bundled into a configuration object which has a reference to its option
description (and therefore makes sure that the configuration values
adhere to the option description).
Common manipulations
------------------------
Let's perform some common manipulation on some options
>>> from tiramisu.config import Config
>>> from tiramisu.option import UnicodeOption, OptionDescription
>>> #
>>> var1 = UnicodeOption('var1', 'first variable')
>>> var2 = UnicodeOption('var2', '', u'value')
>>> #
>>> od1 = OptionDescription('od1', 'first OD', [var1, var2])
>>> rootod = OptionDescription('rootod', '', [od1])
let's set somme access rules on the main namespace
>>> c = Config(rootod)
>>> c.read_write()
let's travel the namespaces
>>> print c
[od1]
>>> print c.od1
var1 = None
var2 = value
>>> print c.od1.var1
None
>>> print c.od1.var2
value
let's modify a value (be careful to the value's type...)
>>> c.od1.var1 = 'value'
Traceback (most recent call last):
ValueError: invalid value value for option var1
>>> c.od1.var1 = u'value'
>>> print c.od1.var1
value
>>> c.od1.var2 = u'value2'
>>> print c.od1.var2
value2
let's come back to the default value
>>> del(c.od1.var2)
>>> print c.od1.var2
value
The value is saved in a :class:`~tiramisu.value.Value` object. It is on this
object that we have to trigger the `reset`, which take the option itself
(`var2`) as a parameter.
On the other side, in the `read_only` mode, it is not possible to modify the value
>>> c.read_only()
>>> c.od1.var2 = u'value2'
Traceback (most recent call last):
tiramisu.error.PropertiesOptionError: cannot change the value for option var2 this option is frozen
let's retrieve the option `var1` description
>>> var1.impl_get_information('doc')
'first variable'
And if the option has been lost, it is possible to retrieve it again:
>>> c.unwrap_from_path('od1.var1').impl_get_information('doc')
'first variable'
Searching for an option
~~~~~~~~~~~~~~~~~~~~~~~~~~
In an application, knowing the path of an option is not always feasible.
That's why a tree of options can easily be searched. First, let's build such a tree::
>>> var1 = UnicodeOption('var1', '')
>>> var2 = UnicodeOption('var2', '')
>>> var3 = UnicodeOption('var3', '')
>>> od1 = OptionDescription('od1', '', [var1, var2, var3])
>>> var4 = UnicodeOption('var4', '')
>>> var5 = UnicodeOption('var5', '')
>>> var6 = UnicodeOption('var6', '')
>>> var7 = UnicodeOption('var1', '', u'value')
>>> od2 = OptionDescription('od2', '', [var4, var5, var6, var7])
>>> rootod = OptionDescription('rootod', '', [od1, od2])
>>> c = Config(rootod)
>>> c.read_write()
Second, let's find an option by it's name::
>>> print c.find(byname='var1')
[<tiramisu.option.UnicodeOption object at 0x7ff1bf7d6ef0>,
<tiramisu.option.UnicodeOption object at 0x7ff1b90c7290>]
If the option name is unique, the search can be stopped once one matched option
has been found:
>>> print c.find_first(byname='var1')
<tiramisu.option.UnicodeOption object at 0x7ff1bf7d6ef0>
Instead of the option's object, the value or path can be retrieved:
>>> print c.find(byname='var1', type_='value')
[None, u'value']
>>> print c.find(byname='var1', type_='path')
['od1.var1', 'od2.var1']
Finaly, a search can be performed on the values, the type or even a combination
of all these criteria:
>>> print c.find(byvalue=u'value', type_='path')
['od2.var1']
>>> print c.find(bytype=UnicodeOption, type_='path')
['od1.var1', 'od1.var2', 'od1.var3', 'od2.var4', 'od2.var5', 'od2.var6', 'od2.var1']
>>> print c.find(byvalue=u'value', byname='var1', bytype=UnicodeOption, type_='path')
['od2.var1']
The search can be performed in a subtree:
>>> print c.od1.find(byname='var1', type_='path')
['od1.var1']
In a root tree or in a subtree, all option can be retrieved in a dict container:
>>> print c.make_dict()
{'od2.var4': None, 'od2.var5': None, 'od2.var6': None, 'od2.var1': u'value',
'od1.var1': None, 'od1.var3': None, 'od1.var2': None}
If the organisation in a tree is not important,
:meth:`~config.SubConfig.make_dict()` results can be flattened
>>> print c.make_dict(flatten=True)
{'var5': None, 'var4': None, 'var6': None, 'var1': u'value', 'var3': None,
'var2': None}
.. note:: be carefull with this `flatten` parameter, here we have just lost
two options named `var1`
One can export only interesting parts of a tree of options into a dict, for
example the options that are in the same group that a given `var1` option::
>>> print c.make_dict(withoption='var1')
{'od2.var4': None, 'od2.var5': None, 'od2.var6': None, 'od2.var1': u'value',
'od1.var1': None, 'od1.var3': None, 'od1.var2': None}
>>> print c.make_dict(withoption='var1', withvalue=u'value')
{'od2.var4': None, 'od2.var5': None, 'od2.var6': None, 'od2.var1': u'value'}
and of course, :meth:`~config.SubConfig.make_dict()` can be called in a subtree:
>>> print c.od1.make_dict(withoption='var1')
{'var1': None, 'var3': None, 'var2': None}
The owners
~~~~~~~~~~~
.. glossary::
owner
When a value is set on an option, an owner is set too, that's why one can know
at any time if a value is a default value or not. Let's create a tree::
>>> var1 = UnicodeOption('var1', '', u'oui')
>>> od1 = OptionDescription('od1', '', [var1])
>>> rootod = OptionDescription('rootod', '', [od1])
>>> c = Config(rootod)
>>> c.read_write()
Then let's retrieve the owner associated to an option::
>>> print c.getowner(var1)
default
>>> c.od1.var1 = u'no'
>>> print c.getowner(var1)
user
>>> del(c.var1)
>>> print c.getowner(var1)
default
You can create your own owner, for example to distinguish modification made by
one user to an other one's.
>>> from tiramisu.setting import owners
>>> owners.addowner('toto')
>>> c.cfgimpl_get_settings().setowner(owners.toto)
>>> print c.getowner(var1)
default
>>> c.od1.var1 = u'no'
>>> print c.getowner(var1)
toto
The properties
~~~~~~~~~~~~~~
A property is an information on an option's state.
Let's create options with properties::
>>> var1 = UnicodeOption('var1', '', u'value', properties=('hidden',))
>>> var2 = UnicodeOption('var2', '', properties=('mandatory',))
>>> var3 = UnicodeOption('var3', '', u'value', properties=('frozen', 'unknown'))
>>> var4 = UnicodeOption('var4', '', u'value')
>>> od1 = OptionDescription('od1', '', [var1, var2, var3])
>>> od2 = OptionDescription('od2', '', [var4], properties=('hidden',))
>>> rootod = OptionDescription('rootod', '', [od1, od2])
>>> c = Config(rootod)
>>> c.read_write()
A hidden value is a value that cannot be accessed in read/write mode. This
option cannot be modified any more. Let's try to access to an option's value
with a hidden option::
>>> print c.od1.var1
Traceback (most recent call last):
tiramisu.error.PropertiesOptionError: trying to access to an option named: var1
with properties ['hidden']
>>> c.read_only()
>>> print c.od1.var1
value
A mandatory option is an option with a value that shall not be `None`. The
value has to be defined. Accessing to such an option is easy in read/write
mode. But in read only mode, an error is raised if no value has been defined::
>>> c.read_write()
>>> print c.od1.var2
None
>>> c.read_only()
>>> print c.od1.var2
Traceback (most recent call last):
tiramisu.error.PropertiesOptionError: trying to access to an option named: var2
with properties ['mandatory']
>>> c.read_write()
>>> c.od1.var2 = u'value'
>>> c.read_only()
>>> print c.od1.var2
value
A frozen option, is an option that cannot be modified by a user.
Let's try to modify a frozen option::
>>> c.read_write()
>>> print c.od1.var3
value
>>> c.od1.var3 = u'value2'
Traceback (most recent call last):
tiramisu.error.PropertiesOptionError: cannot change the value for option var3 this option is frozen
>>> c.read_only()
>>> print c.od1.var3
value
Tiramisu allows us to use user defined properties. Let's define and use one in
read/write or read only mode::
>>> c.cfgimpl_get_settings().append('unknown')
>>> print c.od1.var3
Traceback (most recent call last):
tiramisu.error.PropertiesOptionError: trying to access to an option named:
var3 with properties ['unknown']
>>> c.cfgimpl_get_settings().remove('unknown')
>>> print c.od1.var3
value
Many properties can be defined at the same time on an option::
>>> c.cfgimpl_get_settings().extend(['unknown1', 'unknown2'])
Properties can also be defined on an option group (that is, on an
:term:`option description`) let's hide a group and try to access to it::
>>> c.read_write()
>>> print c.od2.var4
Traceback (most recent call last):
tiramisu.error.PropertiesOptionError: trying to access to an option named: od2
with properties ['hidden']
>>> c.read_only()
>>> print c.od2.var4
value
Furthermore, let's retrieve the properties, delete and add the `hidden` property::
>>> c.read_write()
>>> c.cfgimpl_get_settings()[rootod.od1.var1]
['hidden']
>>> print c.od1.var1
Traceback (most recent call last):
tiramisu.error.PropertiesOptionError: trying to access to an option named:
var1 with properties ['hidden']
>>> c.cfgimpl_get_settings()[rootod.od1.var1].remove('hidden')
>>> c.cfgimpl_get_settings()[rootod.od1.var1]
[]
>>> print c.od1.var1
value
>>> c.cfgimpl_get_settings()[rootod.od1.var1].append('hidden')
>>> c.cfgimpl_get_settings()[rootod.od1.var1]
['hidden']
>>> print c.od1.var1
Traceback (most recent call last):
tiramisu.error.PropertiesOptionError: trying to access to an option named:
var1 with properties ['hidden']
.. _multi-option:
The multi-options
~~~~~~~~~~~~~~~~~~~~~
.. glossary::
multi-option
Multi-options are normal options that have list of values (multiple values)
instead of values::
>>> var1 = UnicodeOption('var1', '', [u'val1', u'val2'], multi=True)
>>> od1 = OptionDescription('od1', '', [var1])
>>> rootod = OptionDescription('rootod', '', [od1])
>>> c = Config(rootod)
>>> c.read_write()
A multi-option's value can be manipulated like a list::
>>> print c.od1.var1
[u'val1', u'val2']
>>> c.od1.var1 = [u'var1']
>>> print c.od1.var1
[u'var1']
>>> c.od1.var1.append(u'val3')
>>> print c.od1.var1
[u'var1', u'val3']
>>> c.od1.var1.pop(1)
u'val3'
>>> print c.od1.var1
[u'var1']
But it is not possible to set a value to a multi-option which is not a list::
>>> c.od1.var1 = u'error'
Traceback (most recent call last):
ValueError: invalid value error for option var1 which must be a list
The master/slave groups
~~~~~~~~~~~~~~~~~~~~~~~~~
.. glossary::
master/slave
A master/slave group is an :class:`~tiramisu.option.OptionDescription` and the
options that lives inside.
Inside this group, a special option, named master option, has the same name as
the group. The group (the option description) is set to type `master`.
All options in a master group is a multi-option (see :ref:`multi-option`).
The slave options have a `default_multi` attribute set to `True`::
>>> from tiramisu.setting import groups
>>> from tiramisu.config import Config
>>> from tiramisu.option import UnicodeOption, OptionDescription
>>>
>>> var1 = UnicodeOption('master', '', multi=True)
>>> var2 = UnicodeOption('slave1', '', multi=True)
>>> var3 = UnicodeOption('slave2', '', multi=True, default_multi=u"default")
>>>
>>> od1 = OptionDescription('master', '', [var1, var2, var3])
>>> od1.impl_set_group_type(groups.master)
>>>
>>> rootod = OptionDescription('rootod', '', [od1])
>>> c = Config(rootod)
>>> c.read_write()
The length of the lists can be modified::
>>> print c.master
master = []
slave1 = []
slave2 = []
>>> c.master.master.append(u'oui')
>>> print c.master
master = [u'oui']
slave1 = [None]
slave2 = [u'default']
>>> c.master.master = [u'non']
>>> print c.master
master = [u'non']
slave1 = [None]
slave2 = [u'default']
>>>
>>> c.master.master = [u'oui', u'non']
>>> print c.master
master = [u'oui', u'non']
slave1 = [None, None]
slave2 = [u'default', u'default']
But it is forbidden to change the lenght of a slave::
>>> c.master.slave1[0] = u'super'
>>> print c.master
master = [u'oui', u'non']
slave1 = [u'super', None]
slave2 = [u'default', u'default']
>>> c.master.slave1 = [u'new1', u'new2']
>>> print c.master
master = [u'oui', u'non']
slave1 = [u'new1', u'new2']
slave2 = [u'default', u'default']
>>> c.master.slave1 = [u'new1']
Traceback (most recent call last):
tiramisu.error.SlaveError: invalid len for the slave: slave1 which has master.master as master
>>> c.master.slave1 = [u'new1', u'new2', u'new3']
tiramisu.error.SlaveError: invalid len for the slave: slave1 which has master.master as master
you have to call the `pop` function on the master::
>>> c.master.master = [u'oui']
Traceback (most recent call last):
tiramisu.error.SlaveError: invalid len for the master: master which has slave1 as slave with greater len
>>> c.master.master.pop(0)
u'oui'
>>> print c.master
master = [u'non']
slave1 = [u'new2']
slave2 = [u'default']
Configuration's interesting methods
------------------------------------------
A `Config` object is informed by an `option.OptionDescription`
instance. The attributes of the ``Config`` objects are the names of the
children of the ``OptionDescription``.
Here are the (useful) methods on ``Config`` (or `SubConfig`).
.. currentmodule:: tiramisu.config
.. class:: Config
.. autoclass:: SubConfig
:members: find, find_first, __iter__, iter_groups, iter_all, make_dict
.. automethod:: __init__
.. rubric:: Summary
.. autosummary::
find
find_first
__iter__
iter_groups
iter_all
make_dict
.. rubric:: Methods
A :class:`~config.CommonConfig` is a abstract base class. A
:class:`~config.SubConfig` is an just in time created objects that wraps an
::class:`~option.OptionDescription`. A SubConfig differs from a Config in the
fact that a config is a root object and has an environnement, a context which
defines the different properties, access rules, vs... There is generally only
one Config, and many SubConfigs.

View File

@ -1,306 +0,0 @@
.. default-role:: literal
.. currentmodule:: tiramisu
The global consistency
===========================
Identical option names
----------------------
If an :class:`~option.Option()` happens to be defined twice in the
:term:`schema` (e.g. the :class:`~option.OptionDescription()`),
that is the two options actually have the same name, an exception is raised.
The calculation is currently carried out in the samespace, for example
if `config.gc.name` is defined, another option in `gc` with the name
`name` is **not** allowed, whereas `config.whateverelse.name` is still
allowed.
Option's values type validation
--------------------------------
When a value is set to the option, the value is validated by the
option's :class:`option.Option()` validator's type.
Notice that if the option is `multi`, that is the `multi` attribute is set to
`True`, then the validation of the option value accepts a list of values
of the same type.
For example, an :class:`option.IntOption` validator waits for an `int` object of
course, an :class:`option.StrOption` validator waits for an `str`, vs...
Where are located the values
-------------------------------
The entry point of the acces to the values is the :class:`setting.Setting()` of
the root configuration object, but the values are actually located in the
:class:`value.Values()` object, in order to be delegated in some kind of a
`tiramisu.storage`, which can be a in-memory storage, or a persistent (for the
time being, a sqlite3) storage.
:class:`value.Values()` is also responsible of the owners and the calculation
of the options that have callbacks.
Requirements
------------
Configuration options can specify requirements as parameters at the init
time, the specification of some links between options or groups allows
to carry out a dependencies calculation. For example, an option can ben
hidden if another option has been set with some expected value. This is
just an example, the possibilities are hudge.
A requirement is a list of dictionaries that have fairly this form::
[{'option': a, 'expected': False, 'action': 'disabled', 'inverse': True,
'transitive':True, 'same_action': True}]
Actually a transformation is made to this dictionary during the validation of
this requires at the :class:`~option.Option()`'s init. The dictionary becomes
a tuple, wich is passed to the :meth:`~setting.Settings.apply_requires()`
method. Take a look at the code to fully understand the exact meaning of the
requirements:
.. automethod:: tiramisu.setting.Settings.apply_requires
The path of the option is required, the second element is the value wich is
expected to trigger the callback, it is required too, and the third one is the
callback's action name (`hide`, `show`...), wich is a
:class:`~setting.Property()`. Requirements are validated in
:class:`setting.Setting`.
Let's create an option wich has requirements::
>>> from tiramisu.option import *
>>> from tiramisu.config import *
>>> var2 = UnicodeOption('var2', '', u'oui')
>>> var1 = UnicodeOption('var1', '', u'value', requires=[{'option':var2, 'expected':u'non', 'action':'hidden'}])
>>> var3 = UnicodeOption('var3', '', u'value', requires=[{'option':var2, 'expected':u'non', 'action':'hidden'}, {'option':var2, 'expected':u'non', 'action':'disabled'}])
>>> var4 = UnicodeOption('var4', '', u'oui')
>>> od1 = OptionDescription('od1', '', [var1, var2, var3])
>>> od2 = OptionDescription('od2', '', [var4], requires=[{'option':od1.var2, 'expected':u'oui', 'action':'hidden', 'inverse':True}])
>>> rootod = OptionDescription('rootod', '', [od1, od2])
>>> c = Config(rootod)
>>> c.read_write()
The requirement here is the dict `{'option':var2, 'expected':u'non',
'action':'hidden'}` wich means that is the option `'od1.var2'` is set to
`'non'`, the option `'od1.var1'` is gonna be hidden. On the other hand, if the
option `'od1.var2'` is different from `'non'`, the option `'od1.var1'` is not
hidden any more::
>>> print c.cfgimpl_get_settings()[rootod.od1.var1]
[]
>>> print c.od1.var1
value
>>> print c.od1.var2
oui
>>> c.od1.var2 = u'non'
>>> print c.cfgimpl_get_settings()[rootod.od1.var1]
['hidden']
>>> print c.od1.var1
Traceback (most recent call last):
tiramisu.error.PropertiesOptionError: trying to access to an option named:
var1 with properties ['hidden']
>>> c.od1.var2 = u'oui'
>>> print c.cfgimpl_get_settings()[rootod.od1.var1]
[]
>>> print c.od1.var1
value
The requirement on `od2` is `{'option':od1.var2, 'expected':u'oui',
'action':'hidden', 'inverse':True}`, which means that if the option `od1.var2`
is set to `oui`, the option is not hidden (because of the `True` at the end of
the tuple wich means 'inverted', take a look at the :doc:`consistency`
document.)::
>>> print c.od2.var4
oui
>>> c.od1.var2 = u'non'
>>> print c.od2.var4
Traceback (most recent call last):
tiramisu.error.PropertiesOptionError: trying to access to an option named: od2 with properties ['hidden']
>>> c.od1.var2 = u'oui'
>>> print c.od2.var4
oui
Requirements can be accumulated
>>> print c.cfgimpl_get_settings()[rootod.od1.var3]
[]
>>> c.od1.var2 = u'non'
>>> print c.cfgimpl_get_settings()[rootod.od1.var3]
['disabled', 'hidden']
>>> c.od1.var2 = u'oui'
>>> print c.cfgimpl_get_settings()[rootod.od1.var3]
[]
Requirements can be accumulated for different or identical properties (inverted
or not)::
>>> a = UnicodeOption('var3', '', u'value', requires=[{'option':od1.var2,
... 'expected':'non', 'action':'hidden'}, {'option':od1.var1, 'expected':'oui',
... 'action':'hidden'}])
>>> a = UnicodeOption('var3', '', u'value', requires=[{'option':od1.var2,
... 'expected':'non', 'action':'hidden'}, {'option':od1.var1, 'excepted':'oui',
... 'action':'disabled', 'inverse':True}])
But it is not possible to have inverted requirements on the same property.
Here is an impossible situation::
>>> a = UnicodeOption('var3', '', u'value', requires=[{'option':od1.var2,
... 'expected':'non', 'action':'hidden'}, {'option':od1.var1, 'expected':'oui',
... 'hidden', True}])
Traceback (most recent call last):
ValueError: inconsistency in action types for option: var3 action: hidden
Validation upon a whole configuration object
----------------------------------------------
An option's integrity can be validated towards a whole configuration.
This type of validation is very open. Let's take a use case : an option
has a certain value, and the value of this option can change the owner
of another option or option group... Everything is possible.
.. currentmodule:: tiramisu.option
Other hooks are availables to validate upon a whole configuration at any time,
for example the consistency between two options (typically, an
:class:`IPOption` and a :class:`NetworkOption`).
Let's define validator (wich is a normal python function)::
>>> def valid_a(value, letter=''):
... return value.startswith(letter)
Here is an option wich uses this validator::
>>> var1 = UnicodeOption('var1', '', u'oui', validator=valid_a, validator_args={'letter': 'o'})
>>> od1 = OptionDescription('od1', '', [var1])
>>> rootod = OptionDescription('rootod', '', [od1])
>>> c = Config(rootod)
>>> c.read_write()
The validation is applied at the modification time::
>>> c.od1.var1 = u'non'
Traceback (most recent call last):
ValueError: invalid value non for option var1
>>> c.od1.var1 = u'oh non'
You can disabled this validation::
>>> c.cfgimpl_get_settings().remove('validator')
>>> c.od1.var1 = u'non'
Values that are calculated
--------------------------------
An option that have a callback is considered to have a value that is to be
calculated.
An option's property with a `force_store_value` attribute is considered to be
modified at the first calculation.
.. automodule:: tiramisu.autolib
:members:
This is the typically protocol for accessing a option's for a calculated value,
but some twisted ways are also possible, take a look at the `force_store_value`
attribute.
.. glossary::
force store value
A calculated value (that is, an option that has a callback) with the
attribute `force_store_value` enabled is considered to be modified at
the first calculation
Let's create four calculation functions::
def return_calc():
#return an unicode value
return u'calc'
def return_value(value):
return value
def return_value_param(param=u''):
return param
def return_no_value_if_non(value):
#if value is not u'non' return value
if value == u'non':
return None
else:
return value
Then we create four options using theses functions::
>>> var1 = UnicodeOption('var1', '', callback=return_calc)
>>> var2 = UnicodeOption('var2', '', callback=return_value, callback_params={'': (u'value',)})
>>> var3 = UnicodeOption('var3', '', callback=return_value_param, callback_params={'param': (u'value_param',)})
>>> var4 = UnicodeOption('var4', '', callback=return_no_value_if_non, callback_params={'': (('od1.var5', False),)})
>>> var5 = UnicodeOption('var5', '', u'oui')
>>> od1 = OptionDescription('od1', '', [var1, var2, var3, var4, var5])
>>> rootod = OptionDescription('rootod', '', [od1])
>>> c = Config(rootod)
>>> c.read_write()
The first option `var1` returns the result of the `return_calc` function, wich
is `u'calc'`::
>>> print c.od1.var1
calc
The second option `var2` returns the result of the `return_value` fucntion,
wich is `value`. The parameter `u'value'` is passed to this function::
>>> print c.od1.var2
value
The third option `var3` returns the result of the function `return_value_param`
with the named parameter `param` and the value `u'value_param'`::
>>> print c.od1.var3
value_param
The fourth option `var4` returns the reslut of the function `return_no_value_if_non`
that is the value of `od1.var5` exceptif the value is u`non`::
>>> print c.od1.var4
oui
>>> c.od1.var5 = u'new'
>>> print c.od1.var4
new
>>> c.od1.var5 = u'non'
>>> print c.od1.var4
None
The calculation replaces the default value.
If we modify the value, the calculation is not carried out any more::
>>> print c.od1.var1
calc
>>> c.od1.var1 = u'new_value'
>>> print c.od1.var1
new_value
To force the calculation to be carried out in some cases, one must add the
`frozen` and the `force_default_on_freeze` properties::
>>> c.cfgimpl_get_settings()[rootod.od1.var1].append('frozen')
>>> c.cfgimpl_get_settings()[rootod.od1.var1].append('force_default_on_freeze')
>>> print c.od1.var1
calc
>>> c.cfgimpl_get_settings()[rootod.od1.var1].remove('frozen')
>>> c.cfgimpl_get_settings()[rootod.od1.var1].remove('force_default_on_freeze')
>>> print c.od1.var1
new_value

View File

@ -1,92 +0,0 @@
Test framework
==================
Have a look at the :file:`test` subdirectory of the project.
We are using py.test_
.. _py.test: http://pytest.org/latest/
config APIs
-----------------
.. automodule:: test.test_config
:members:
option APIs
---------------
.. automodule:: test.test_option
:members:
others
----------
.. automodule:: test.test_mandatory
:members:
.. automodule:: test.test_config_big_example
:members:
.. automodule:: test.test_option_default
:members:
.. automodule:: test.test_option_consistency
:members:
.. automodule:: test.test_cache
:members:
.. automodule:: test.test_option_setting
:members:
.. automodule:: test.test_freeze
:members:
.. automodule:: test.test_config_ip
:members:
.. automodule:: test.test_slots
:members:
.. automodule:: test.test_reverse_from_path
:members:
.. automodule:: test.test_requires
:members:
.. automodule:: test.test_option_owner
:members:
.. automodule:: test.test_permissive
:members:
.. automodule:: test.test_option_type
:members:
.. automodule:: test.test_dereference
:members:
.. automodule:: test.test_storage
:members:
.. automodule:: test.test_option_calculation
:members:
.. automodule:: test.test_option_with_special_name
:members:
.. automodule:: test.test_config_domain
:members:
.. automodule:: test.test_symlink
:members:
.. automodule:: test.test_metaconfig
:members:
.. automodule:: test.test_parsing_group
:members:

View File

@ -1,12 +0,0 @@
SRC=$(wildcard *.tex)
OBJ=$(subst .tex,.pdf,$(SRC))
pdf: $(OBJ)
%.pdf: %.tex
pdflatex $<
clean:
rm -f $(OBJ)
rm -f *.aux *.log *.toc *.snm *.out *.nav

View File

@ -1,69 +0,0 @@
\begin{frame}
\frametitle{Comparaison entre le noyau de Créole et Tiramisu}
\begin{itemize}
\item \emph{Tiramisu} a pour objectif de
\begin{itemize}
\item remplacer le noyau \emph{Creole} (\texttt{EoleDict}) de manière transparente ;
\item résoudre les problèmes inhérents à \texttt{CreoleServ} ;
\end{itemize}
\item au niveau du code, il y a enfin une vraie séparation du c\oe ur et du fonctionnel ;
\item valide le type \emph{et la structure}, l'ajout de types est aisé.
\item \emph{Creole} : \texttt{EoleDict, EoleVars} $ \Leftrightarrow $ \texttt{Config, Option}\\
cf \texttt{tiramisu/doc/build/pydoc/index.html}
\item intégré à \texttt{gen\_config}, \texttt{cheetah}, \texttt{DTD Creole}, syntaxe \texttt{Creole} \dots
\item \texttt{eole-report/D02CoherenceVariables.pdf}
\end{itemize}
\end{frame}
\begin{frame}
\frametitle{Gestionnaire de configuration existants}
\begin{itemize}
\item Le gestionnaire de conf de Victor Stinner $\Rightarrow$ \emph{NuFw};
\item puppet, cfgengine... $\Rightarrow$ intéressant, de nombreux comportements peuvent être repris, mais tel quel difficilement compatible avec \emph{Creole};
\item \emph{Creole} $\Leftrightarrow$ \texttt{tiramisu/doc/build/glossary.html}
\end{itemize}
\end{frame}
\begin{frame}
\frametitle{Un "vrai" serveur de config}
\begin{itemize}
\item un serveur de données de configuration ;
\item $1^{ere}$ méthode : exportation (snapshot) d'un état de la config $ \Rightarrow $ Créole ;
\item $2^{eme}$ méthode : JIT (just in time) calculation, une modification
de l'état de la configuration est possible \emph{pendant} la manipulation et l'utilisation de la conf $ \Rightarrow $ Tiramisu.
\item \texttt{doc/getting-started.html}
\end{itemize}
\end{frame}
\begin{frame}
\frametitle{Qu'est-ce qu'un gestionnaire de conf moderne ?}
\begin{itemize}
\item c'est une organisation arborescente des données (les données sont imbriquées) ;
\item c'est un accès facile aux données (typiquement une interface de type \emph{dictionnaire}) ;
\item clefs-valeurs, mais quelles valeurs exactement ? $ \Rightarrow $ calcul JIT (just in time) ;
\item \texttt{eole-report/D01AccesVariables.pdf}
\end{itemize}
\end{frame}
\begin{frame}
\frametitle{Définition d'un gestionnaire de configuration}
\begin{itemize}
\item les families, groups, master \dots~ ce sont des \emph{schémas} de données (\texttt{OptionDescription}) ;
\item c'est la configuration (\texttt{Config}) qui est responsable de l'accès aux valeurs ;
\item la configuration est aisément manipulable, et a un point d'entrée unique ;
\item l'accès aux valeurs des \texttt{Options} de configuration ne peut se faire \emph{que} depuis la conf racine.
\item \texttt{eole-report/D01AccesVariables.pdf}
\end{itemize}
\end{frame}
\begin{frame}
\frametitle{Organisation en espace de nommage}
\begin{itemize}
\item dans \emph{tiramisu} l'accent est mis sur l'organisation arborescente des données ;
\item la validation des options de configuration se fait par l'appartenance aux groupes (families, master/slaves \dots) ;
\item l'organisation en groupes est unifiée par l'espace de nommage ;
\item \texttt{eole-report/D03ReglesEtats.pdf}
\item lisibilité d'une config : \texttt{tiramisu/report/build/index.html} rapport html d'une config
\end{itemize}
\end{frame}

View File

@ -1,61 +0,0 @@
\begin{frame}
\frametitle{Etats ("status") de la configuration}
\begin{itemize}
\item système d'états de la configuration par \emph{droits d'accès} ;
\item \texttt{read write}, \texttt{read only} ;
\item correspond à \texttt{freeze}, \texttt{hidden}, \texttt{disabled} \dots ;
\item \texttt{doc/status.html} ;
\item \texttt{eole-report/D03ReglesEtats.pdf} ;
\end{itemize}
\end{frame}
\begin{frame}
\frametitle{hidden if in, hidden if not in}
\begin{itemize}
\item les hidden if in, disabled if, \dots sont généralisés
\item dans tiramisu, ce sont des pré-requis sur une (des) variables
\item \texttt{eole-report/D03ReglesEtats.pdf}
\item \texttt{doc/consistency.html}
\end{itemize}
\end{frame}
\begin{frame}
\frametitle{un peu de mathématiques : prévenir les deadlocks}
\begin{itemize}
\item sûreté : prévention des deadlocks ;
\item dans tiramisu, le modèle est suffisamment abstrait pour que son exploitation mathématique soit
réalisable par les techniques de \emph{Model Checking} ;
\item soit on a besoin de ne connaître que l'ensemble des états, pas leurs liens $\Rightarrow$ espace d'états ;
\item soit on a besoin de connaître toutes les relations $\Rightarrow$ graphe d'accessibilité ;
\item la configuration est modélisable en une structure de \emph{Kripe} ;
\item déjà le parsing de la conf est facile, la preuve : \texttt{tiramisu/report/build/index.html}
\end{itemize}
\end{frame}
\begin{frame}
\frametitle{un peu de mathématiques (suite) CreoleLint}
\begin{itemize}
\item exemple : $ P = 3 \wedge Q = 1 \triangleleft \langle P = 1 \hookleftarrow Q = 0 \rangle$
\item la propriété \og dans aucun état on a $P = 3$ et $Q = 1$ \fg~ est-elle vraie ?
Pour vérifier cette propriété, on a besoin de connaître l'espace d'états ;
\item la propriété \og chaque chemin débutant dans un état accessible $P=1$ passe par un état où $Q=3$ et $P=2$ \fg~
est-elle vraie ? Cela demande de connaître le graphe d'accessibilité ;
\item les structures de \emph{Kripe} sont des machines à états étiquetées par les valuations de toutes les variables propositionnelles ;
\item une compliation statique devient possible dans \emph{CreoleLint} \dots
\end{itemize}
\end{frame}
\begin{frame}
\frametitle{compatibilité Créole : ce qui reste à faire}
\begin{itemize}
\item les options spéciales sont implémentées (auto, fill, obligatoire, \dots) reste la librairie des fonctions pour les variables automatiques \texttt{eosfunc} ;
\item tous les états sont implémentés (hidden, disabled, mode (normal/expert), \dots), il faut fixer les comportement \texttt{read write} ;
\item les "valprec" (valeur précédentes) et une mémoire de \emph{tous} les états antérieurs ;
\item fixer les comportement des hides (sous-groupes récursifs, \dots) ;
\item validations master/slaves, validations globales au regard de la configuration entière puisque c'est possible maintenant.
\end{itemize}
\end{frame}

View File

@ -1,36 +0,0 @@
%%presentation
\documentclass{beamer}
\usepackage{beamerthemetree}
%%impression
%\documentclass[a4paper,9pt]{extarticle}
%\usepackage{beamerarticle}
%%
% class FR
\usepackage[T1]{fontenc}
\usepackage[utf8]{inputenc}
\usepackage[frenchb]{babel}
% image
%% \usepackage{graphicx}
\usepackage{alltt}
\usecolortheme{crane}
\beamertemplatetransparentcovered
%\logo{\includegraphics[height=1cm]{ban.png}}
\title{Tiramisu}
\subtitle{gestionnaire de configuration}
\author{Gwen}
\institute{\texttt{git clone git://git.labs.libre-entreprise.org/tiramisu.git} \\
\texttt{firefox tiramisu/doc/build/index.html}}
\date{\today}
\begin{document}
\frame{\titlepage}
\include{definition}
\include{statut}
\end{document}

View File

@ -1,19 +0,0 @@
Errors that may be encountered
==================================
Three builtins exceptions are used :
-----------------------------------------
- **ValueError** : Validation error, parameters error, a list instead
of a Multi, or if the value does not make sense
- **TypeError** : type error in a parameter
- **AttributeError** : wrong path or unknownd option or optiondescription
And five other exceptions :
------------------------------
.. automodule:: tiramisu.error
:members:

View File

@ -1,86 +0,0 @@
==================================
Getting started
==================================
What is options handling ?
=================================
Due to more and more available options required to set up an operating system,
compiler options or whatever, it became quite annoying to hand the necessary
options to where they are actually used and even more annoying to add new
options. To circumvent these problems the configuration control was
introduced...
What is Tiramisu ?
===================
Tiramisu is an options handler and an options controller, which aims at
producing flexible and fast options access. The main advantages are its access
rules and the fact that the whole consistency is preserved at any time, see
:doc:`consistency`. There is of course type and structure validations, but also
validations towards the whole options. Furthermore, options can be reached and
changed according to the access rules from nearly everywhere in your appliance.
Just the facts
==============
.. _gettingtiramisu:
`tiramisu`\ 's home page is here_
.. _here: https://forge.cadoles.com/Cadoles/tiramisu
Download
---------
To obtain a copy of the sources, check it out from the repository using `git`.
We suggest using `git` if one wants to access to the current developments.
::
git clone https://forge.cadoles.com/Cadoles/tiramisu.git
This will get you a fresh checkout of the code repository in a local directory
named ``tiramisu``.
Getting started
-------------------
Option objects can be created in different ways. Let's perform very basic
:class:`~tiramisu.option.Option` and :class:`~tiramisu.config.Config` object
manipulations:
::
>>> from tiramisu.config import Config
>>> from tiramisu.option import OptionDescription, BoolOption
>>> # let's create a group of options... with only one option inside
>>> descr = OptionDescription("optgroup", "", [
... BoolOption("bool", "", default=False)])
>>> # c is a namespace as well as a container for the options
>>> c = Config(descr)
>>> c.bool
False
>>> c.bool = True
>>> c.bool
True
So by now, we have:
- a namespace (which is `c` here)
- the access of an option's value by the
attribute access way (here `bool`, which is a boolean option
:class:`~tiramisu.option.BoolOption()`.
So, option objects are produced at the entry point `c` and then handed down to
where they are actually used when `c.bool` is triggered. This keeps options
local but available at any timer and consistent.
Once the namespace is created, we can set a
:meth:`~config.CommonConfig.read_write()` access to the options::
>>> c.read_write()
which enables us to set a bunch of access rules that we wil explain later in
:doc:`status`.

View File

@ -1,86 +0,0 @@
.. default-role:: literal
Glossary
==========
.. glossary::
configuration
Global configuration object, wich contains the whole configuration
options *and* their descriptions (option types and group)
schema
option description
see :class:`tiramisu.option.OptionDescription`
The schema of a configuration :
- the option types
- how they are organised in groups or even subgroups, that's why we
call them **groups** too.
configuration option
An option object wich has a name and a value and can be accessed
from the configuration object
access rules
Global access rules are : :meth:`~config.CommonConfig.read_write()` or
:meth:`~config.Config.read_only()`, see :doc:`status`
default value
Default value of a configuration option. The default value can be
set at instanciation time, or even at any moment. Remember that if
you reset the default value, the owner reset to `default`
freeze
A whole configuration can be frozen (used in read only access). See
:ref:`frozen` for details.
A single option can be frozen too.
value owner
When an option is modified, including at the instanciation, we
always know who has modified it. It's the owner of the option, see
:doc:`status` for more details.
option with properties
an option wich has property like 'hidden' or 'disabled' is an option
wich has restricted acces rules
hidden option
a hidden option has a different behaviour on regards to the access
of the value in the configuration, see :doc:`status` for more details.
disabled option
a disabled option has a different behaviour on regards to the access
of the value in the configuration, see :doc:`status` for more details.
mandatory option
A mandatory option is a configuration option wich value has to be
set, that is the default value cannot be `None`.
consistency
Preserving the consistency in a whole configuration is a tricky thing,
tiramisu takes care of it for you, see :doc:`consistency` for details.
context
The context is a :class:`tiramisu.setting.Setting()` object in the
configuration that enables us to access to the global properties
for example the `read_write` or `read_only` :term:`access rules`

View File

@ -1,62 +0,0 @@
.. default-role:: literal
.. meta::
:description: configuration management
:keywords: config, configuration
.. title:: tiramisu
The tasting of `Tiramisu`
=========================
.. image:: logo.png
:height: 150px
`Tiramisu`
is a cool, refreshing Italian dessert,
it is also an `options controller tool`_.
.. _`options controller tool`: http://en.wikipedia.org/wiki/Configuration_management#Overview
It's a pretty small, local (that is, straight on the operating system) options
handler and controller.
controlling options explanations
--------------------------------------
.. toctree::
:maxdepth: 1
getting-started
config
option
storage
status
consistency
error
glossary
api
doctest
Indices and tables
==================
* :ref:`genindex`
* :ref:`modindex`
* :ref:`search`
.. note:: The tiramisu code is licensed under the `LGPL licence`_
and this documentation is licensed under the `Creative Commons
Attribution-ShareAlike 3.0 Unported License`_\ .
.. _`Creative Commons Attribution-ShareAlike 3.0 Unported License`: http://creativecommons.org/licenses/by-sa/3.0/deed.en_US
.. _`LGPL licence`: http://www.gnu.org/licenses/lgpl.html
.. todolist::

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.5 KiB

View File

@ -1,125 +0,0 @@
.. default-role:: literal
.. module:: tiramisu.option
The options types
===================
Description of Options
----------------------
All the constructors take a ``name`` and a ``doc`` argument as first
arguments to give to the option or option description a name and a description document.
Most constructors take a ``default`` argument that specifies the default
value of the option. If this argument is not supplied the default value
is assumed to be ``None``.
The `Option` base class
-------------------------
It's the abstract base class for almost all options (except the symlink).
.. _optioninit:
.. autoclass:: Option
:special-members:
:members:
All option types
------------------
BoolOption
~~~~~~~~~~
.. autoclass:: BoolOption
:private-members:
IntOption
~~~~~~~~~
.. autoclass:: IntOption
:private-members:
FloatOption
~~~~~~~~~~~
.. autoclass:: FloatOption
:private-members:
StrOption
~~~~~~~~~
.. autoclass:: StrOption
:private-members:
UnicodeOption
~~~~~~~~~~~~~
.. autoclass:: UnicodeOption
:private-members:
SymLinkOption
~~~~~~~~~~~~~
.. autoclass:: SymLinkOption
:private-members:
``SymLinkOption`` redirects to another configuration option in the
configuration, that is :
- retrieves the value of the target,
- can set the value of the target too
IPOption
~~~~~~~~
.. autoclass:: IPOption
:private-members:
PortOption
~~~~~~~~~~
.. autoclass:: PortOption
:private-members:
NetmaskOption
~~~~~~~~~~~~~
.. autoclass:: NetmaskOption
:private-members:
NetworkOption
~~~~~~~~~~~~~
.. autoclass:: NetworkOption
:private-members:
DomainnameOption
~~~~~~~~~~~~~~~~
.. autoclass:: DomainnameOption
:private-members:
ChoiceOption
~~~~~~~~~~~~
.. autoclass:: ChoiceOption
:private-members:
.. _optdescr:
The `OptionDescription` class
-------------------------------
.. autoclass:: OptionDescription
:special-members:
:members:
If you need to access to an option object, you can do it with the
OptionDescription object. Not only the value of the option by attribute access,
but the option object itself that lives behind the scene. It can always be
accessed internally. The option objects are in the `_children`
`OptionDescription`'s attribute.

View File

@ -1,155 +0,0 @@
.. default-role:: literal
Local statuses and global settings
=====================================
Available configuration statuses
----------------------------------
.. currentmodule:: tiramisu
The configuration's status lives in an :class:`setting.Setting()` object.
This configuration status corresponds to specific attributes or bunch of
attributes that can be accessed together with some `setting.Setting`
method:
**read write status**
The configuration can be accessed by `__get__` and `__set__`
properties, except for the `hidden` configuration options but, yes, it is
possible to modify a disabled option.
To enable read-write status, call
:class:`~config.CommonConfig.read_write()` on the config.
**read only status**
The whole configuration is `frozen`, that is modifiying a value is
forbidden. We can access to a configuration option only with the
`__getattr__` property.
The configuration has not an access to the hidden options
but can read the disabled options.
To enable read only status, call :class:`~config.SubConfig.read_only()` on
the config.
.. csv-table:: **Configuration's statuses summary**
:header: " ", "Hidden", "Disabled", "Mandatory"
"read only status", `False`, `True`, `True`
"read-write status", `True`, `False`, `False`
.. _`frozen`:
Freezing a configuration
---------------------------
At the configuration level, :class:`~setting.Setting()` enables us to freeze the
whole configuration, wich means that the frozen :class:`~option.Option()`'s
values cannot be modified.
It is possible to *freeze* a single :class:`~option.Option()` object with
:meth:`~config.SubConfig.cfgimpl_get_settings()`. If you try to modify a frozen
option, it raises a `TypeError: trying to change a frozen option object`.
To find out if an option `myoption` is frozen, just make an assertion on the
settings like that::
'frozen' in cfg.cfgimpl_get_settings()[myoption]
Moreover, frozen option can return their default values if
:meth:`~option.Option.force_default()` is called on this option.
.. glossary::
force default on freeze
A single option is frozen and we want the option to return something
else than his value, typically it is his default value.
In the option's values, an attribute can be set
:attr:`force_default_on_freeze`, that forces this behavior.
Restricted access to an `Option()`
-----------------------------------
.. autoclass:: tiramisu.setting.Property
The `properties` attribute is in charge of the access rules' option's value.
Configuration options access statuses are defined at configuration level
that corresponds to the `option.Option()`'s `properties` attribute,
for example: hidden, disabled.
Use the pythonic way to know if a property is there::
'hidden' in c.cfgimpl_get_settings()
'frozen' in c.cfgimpl_get_settings()[opt]
To access to the global settings::
cfg.cfgimpl_get_settings()
cfg.cfgimpl_get_settings()[option1]
to add, or suppress a global property::
cfg.cfgimpl_get_settings()[option1].append('hidden')
cfg.cfgimpl_get_settings()[option1].remove('hidden')
to activate, deactivate properties::
cfg.cfgimpl_get_settings().append('hidden')
cfg.cfgimpl_get_settings().remove('hidden')
The global properties are living in e :class:`~setting.Setting` object. A
`Setting` object also takes care of the way to access option values and the
storage in the cache.
Value owners
-------------
Every configuration option has a **owner**. When the option is instanciated,
the owner is :obj:`setting.owners.default` because a default value has been set
(including `None`, wich means that no value has been set yet).
.. method:: config.CommonConfig.getowner()
This method can retrieve an Option's owner.
- At the instance of the `Config` object, the value owner is
:obj:`setting.owners.default` because
the default values are set at the instance of the configuration option
object,
- at the modification of an option, the owner is `owners.default`, (which is
:obj:`owners.user`)
Special behaviors for an option
---------------------------------
**mandatory**
A mandatory option shall return a value. If a value, or a default value
has not been set, a error is raised.
**has a callback**
This means that it is a calculated value and therefore automatically
protected it cannot be modified by attribute access.
**force_store_value**
if the configuration option has a default value, the default is
returned, otherwise the value is calculated.
Its inner state is represented by `option.Option.force_default()`
Configuration options have default values that are stored in the
`Option()` object itself. Default values, the `default`, can be set in
various ways.
If a default value is modified by overriding it, not only the value of
the option resets to the default that is proposed, but the owner is
modified too, it is reseted to `owners.default`.

Binary file not shown.

Before

Width:  |  Height:  |  Size: 16 KiB

View File

@ -1,265 +0,0 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!-- Created with Inkscape (http://www.inkscape.org/) -->
<svg
xmlns:dc="http://purl.org/dc/elements/1.1/"
xmlns:cc="http://creativecommons.org/ns#"
xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
xmlns:svg="http://www.w3.org/2000/svg"
xmlns="http://www.w3.org/2000/svg"
xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd"
xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape"
width="400"
height="200"
id="svg2"
version="1.1"
inkscape:version="0.48.4 r9939"
sodipodi:docname="test.svg"
inkscape:export-filename="/home/gnunux/git/tiramisu/doc/storage.png"
inkscape:export-xdpi="135"
inkscape:export-ydpi="135">
<defs
id="defs4">
<inkscape:perspective
sodipodi:type="inkscape:persp3d"
inkscape:vp_x="0 : 526.18109 : 1"
inkscape:vp_y="0 : 1000 : 0"
inkscape:vp_z="744.09448 : 526.18109 : 1"
inkscape:persp3d-origin="372.04724 : 350.78739 : 1"
id="perspective3827" />
</defs>
<sodipodi:namedview
id="base"
pagecolor="#ffffff"
bordercolor="#666666"
borderopacity="1.0"
inkscape:pageopacity="1"
inkscape:pageshadow="2"
inkscape:zoom="1"
inkscape:cx="106.95445"
inkscape:cy="208.15932"
inkscape:document-units="px"
inkscape:current-layer="layer1"
showgrid="false"
inkscape:window-width="1600"
inkscape:window-height="841"
inkscape:window-x="0"
inkscape:window-y="27"
inkscape:window-maximized="1" />
<metadata
id="metadata7">
<rdf:RDF>
<cc:Work
rdf:about="">
<dc:format>image/svg+xml</dc:format>
<dc:type
rdf:resource="http://purl.org/dc/dcmitype/StillImage" />
<dc:title></dc:title>
</cc:Work>
</rdf:RDF>
</metadata>
<g
inkscape:label="Calque 1"
inkscape:groupmode="layer"
id="layer1"
transform="translate(0,-852.36218)">
<path
style="fill:none;stroke:#000000;stroke-width:1px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1"
d="M 235.5,78.588237 306,109"
id="path4403"
inkscape:connector-type="polyline"
inkscape:connector-curvature="0"
inkscape:connection-start="#g4211"
inkscape:connection-start-point="d4"
transform="translate(0,852.36218)" />
<path
style="fill:none;stroke:#000000;stroke-width:1px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1"
d="M 235.5,131.08416 305,107"
id="path4405"
inkscape:connector-type="polyline"
inkscape:connector-curvature="0"
inkscape:connection-start="#g4216"
inkscape:connection-start-point="d4"
transform="translate(0,852.36218)" />
<g
id="g4206"
transform="translate(-17,590)">
<text
sodipodi:linespacing="686.00001%"
id="text2985"
y="368.36218"
x="98"
style="font-size:10px;font-style:normal;font-weight:normal;line-height:686.00001335%;letter-spacing:0px;word-spacing:0px;fill:#000000;fill-opacity:1;stroke:none;font-family:Sans"
xml:space="preserve"><tspan
y="368.36218"
x="98"
id="tspan2987"
sodipodi:role="line">Config</tspan></text>
<rect
y="351.36218"
x="81"
height="30"
width="63"
id="rect3757"
style="fill:none;stroke:#000000;stroke-linejoin:round;stroke-opacity:1" />
</g>
<g
id="g4211"
transform="translate(-17,590)">
<rect
y="312.36218"
x="189.5"
height="30"
width="63"
id="rect3757-2"
style="fill:none;stroke:#000000;stroke-linejoin:round;stroke-opacity:1" />
<text
sodipodi:linespacing="686.00001%"
id="text3777"
y="330.36218"
x="206"
style="font-size:10px;font-style:normal;font-weight:normal;line-height:686.00001335%;letter-spacing:0px;word-spacing:0px;fill:#000000;fill-opacity:1;stroke:none;font-family:Sans"
xml:space="preserve"><tspan
y="330.36218"
x="206"
id="tspan3779"
sodipodi:role="line">Values</tspan></text>
</g>
<g
id="g4216"
transform="translate(-17,590)">
<rect
y="389.36218"
x="189.5"
height="30"
width="63"
id="rect3757-4"
style="fill:none;stroke:#000000;stroke-linejoin:round;stroke-opacity:1" />
<text
sodipodi:linespacing="686.00001%"
id="text3799"
y="407.36218"
x="200"
style="font-size:10px;font-style:normal;font-weight:normal;line-height:686.00001335%;letter-spacing:0px;word-spacing:0px;fill:#000000;fill-opacity:1;stroke:none;font-family:Sans"
xml:space="preserve"><tspan
y="407.36218"
x="200"
id="tspan3801"
sodipodi:role="line">Settings</tspan></text>
</g>
<path
style="fill:none;stroke:#000000;stroke-width:1px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1"
d="m 127,967.39444 45.5,15.93548"
id="path4028"
inkscape:connector-type="polyline"
inkscape:connector-curvature="0" />
<path
style="fill:none;stroke:#000000;stroke-width:1px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1"
d="m 127,945.0396 45.5,-16.35484"
id="path4030"
inkscape:connector-type="polyline"
inkscape:connector-curvature="0" />
<rect
style="fill:#ffffff;fill-opacity:1;stroke:none"
id="rect4161"
width="55.5"
height="26"
x="277.5"
y="946.36218" />
<path
sodipodi:type="arc"
style="fill:none;stroke:#000000;stroke-width:1.96347165;stroke-linejoin:round;stroke-miterlimit:4;stroke-opacity:1;stroke-dasharray:none"
id="path3843"
sodipodi:cx="401"
sodipodi:cy="334.86218"
sodipodi:rx="38"
sodipodi:ry="10.5"
d="m 439,334.86218 a 38,10.5 0 1 1 -76,0 38,10.5 0 1 1 76,0 z"
transform="matrix(0.71325325,0,0,0.57998971,18.66254,749.17042)" />
<path
transform="matrix(0.71325325,0,0,0.57998971,18.57337,775.05247)"
sodipodi:type="arc"
style="fill:none;stroke:#000000;stroke-width:1.96347165;stroke-linejoin:round;stroke-miterlimit:4;stroke-opacity:1;stroke-dasharray:none"
id="path3843-3"
sodipodi:cx="401"
sodipodi:cy="334.86218"
sodipodi:rx="38"
sodipodi:ry="10.5"
d="m 439,334.86218 a 38,10.5 0 1 1 -76,0 38,10.5 0 1 1 76,0 z" />
<path
transform="matrix(0.71325325,0,0,0.57998971,18.52879,762.07519)"
sodipodi:type="arc"
style="fill:none;stroke:#000000;stroke-width:1.96347165;stroke-linejoin:round;stroke-miterlimit:4;stroke-opacity:1;stroke-dasharray:none"
id="path3843-3-0"
sodipodi:cx="401"
sodipodi:cy="334.86218"
sodipodi:rx="38"
sodipodi:ry="10.5"
d="m 439,334.86218 a 38,10.5 0 1 1 -76,0 38,10.5 0 1 1 76,0 z" />
<rect
style="fill:#ffffff;fill-opacity:1;stroke:none"
id="rect3883"
width="62.989182"
height="6.7061315"
x="274.72043"
y="949.91193" />
<rect
style="fill:#ffffff;fill-opacity:1;stroke:none"
id="rect3883-3"
width="58.087975"
height="6.4161367"
x="277.34818"
y="962.78046" />
<path
style="fill:none;stroke:#000000;stroke-width:1.26286423;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-opacity:1;stroke-dasharray:none;display:inline"
d="m 277.52869,943.35095 -0.0442,26.02673"
id="path3917"
inkscape:connector-type="polyline"
inkscape:connector-curvature="0" />
<path
style="fill:none;stroke:#000000;stroke-width:1.26286423;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-opacity:1;stroke-dasharray:none;display:inline"
d="m 331.64698,969.26909 0.13377,-26.17203"
id="path3921"
inkscape:connector-type="polyline"
inkscape:connector-curvature="0" />
<text
xml:space="preserve"
style="font-size:10px;font-style:normal;font-weight:normal;line-height:686.00001335%;letter-spacing:0px;word-spacing:0px;fill:#000000;fill-opacity:1;stroke:none;font-family:Sans"
x="286.33643"
y="958.32324"
id="text3821"
sodipodi:linespacing="686.00001%"><tspan
sodipodi:role="line"
id="tspan3823"
x="286.33643"
y="958.32324">Storage</tspan></text>
<g
id="g4201"
transform="translate(-17,590)">
<rect
y="293.42468"
x="81"
height="30"
width="63"
id="rect3757-5"
style="fill:none;stroke:#000000;stroke-linejoin:round;stroke-opacity:1" />
<text
sodipodi:linespacing="100%"
id="text4190"
y="309.42468"
x="110.27588"
style="font-size:10px;font-style:normal;font-weight:normal;text-align:center;line-height:100%;letter-spacing:0px;word-spacing:0px;text-anchor:middle;fill:#000000;fill-opacity:1;stroke:none;font-family:Sans"
xml:space="preserve"><tspan
id="tspan4194"
y="309.42468"
x="110.27588"
sodipodi:role="line">Option</tspan></text>
</g>
<path
style="fill:none;stroke:#000000;stroke-width:1px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1"
d="m 95.5,913.42468 0,27.9375"
id="path4199"
inkscape:connector-type="polyline"
inkscape:connector-curvature="0" />
</g>
</svg>

Before

Width:  |  Height:  |  Size: 9.4 KiB

View File

@ -1,52 +0,0 @@
Storage
=======
.. automodule:: tiramisu.storage
.. automethod:: tiramisu.storage.set_storage
.. image:: storage.png
Dictionary
~~~~~~~~~~
.. automodule:: tiramisu.storage.dictionary
Dictionary settings:
.. automethod:: tiramisu.storage.dictionary.storage.Setting
Sqlite3
~~~~~~~
.. automodule:: tiramisu.storage.sqlite3
Sqlite3 settings:
.. automethod:: tiramisu.storage.sqlite3.storage.Setting
Example
~~~~~~~
>>> from tiramisu.option import StrOption, OptionDescription
>>> from tiramisu.config import Config
>>> from tiramisu.storage import set_storage
>>> set_storage('sqlite3', dir_database='/tmp/tiramisu')
>>> s = StrOption('str', '')
>>> o = OptionDescription('od', '', [s])
>>> c1 = Config(o, persistent=True, session_id='xxxx')
>>> c1.str
>>> c1.str = 'yes'
>>> c1.str
'yes'
>>> del(c1)
>>> c2 = Config(o, persistent=True, session_id='xxxx')
>>> c2.str
'yes'
>>> del(c2)
>>> list_sessions()
['xxxx']
>>> delete_session('xxxx')
>>> c3 = Config(o, persistent=True, session_id='xxxx')
>>> c3.str

View File

@ -1240,7 +1240,6 @@ def test_calc_value_condition():
def test_calc_value_allow_none():
from tiramisu import calc_value, StrOption, OptionDescription, Config, Params, ParamOption, ParamValue
val1 = StrOption('val1', "", 'val1')
val2 = StrOption('val2', "")
val3 = StrOption('val3', "", multi=True, callback=calc_value, callback_params=Params((ParamOption(val1), ParamOption(val2)), multi=ParamValue(True), allow_none=ParamValue(True)))
@ -1250,7 +1249,6 @@ def test_calc_value_allow_none():
def test_calc_value_remove_duplicate():
from tiramisu import calc_value, StrOption, OptionDescription, Config, Params, ParamOption, ParamValue
val1 = StrOption('val1', "", 'val1')
val2 = StrOption('val2', "", 'val1')
val3 = StrOption('val3', "", multi=True, callback=calc_value, callback_params=Params((ParamOption(val1), ParamOption(val2)), multi=ParamValue(True), remove_duplicate_value=ParamValue(True)))
@ -1260,7 +1258,6 @@ def test_calc_value_remove_duplicate():
def test_calc_value_join():
from tiramisu import calc_value, StrOption, OptionDescription, Config, Params, ParamOption, ParamValue
val1 = StrOption('val1', "", 'val1')
val2 = StrOption('val2', "", 'val2')
val3 = StrOption('val3', "", callback=calc_value, callback_params=Params((ParamOption(val1), ParamOption(val2)), join=ParamValue('.')))
@ -1270,7 +1267,6 @@ def test_calc_value_join():
def test_calc_value_min():
from tiramisu import calc_value, StrOption, OptionDescription, Config, Params, ParamOption, ParamValue
val1 = StrOption('val1', "", 'val1')
val2 = StrOption('val2', "", 'val2')
val3 = StrOption('val3', "", 'val3')
@ -1284,7 +1280,6 @@ def test_calc_value_min():
def test_calc_value_add():
from tiramisu import calc_value, IntOption, OptionDescription, Config, Params, ParamOption, ParamValue
val1 = IntOption('val1', "", 1)
val2 = IntOption('val2', "", 2)
val3 = IntOption('val3', "", callback=calc_value, callback_params=Params((ParamOption(val1), ParamOption(val2)), operator=ParamValue('add')))

View File

@ -8,7 +8,7 @@ from tiramisu.setting import groups
from tiramisu import setting
setting.expires_time = 1
from tiramisu import IPOption, OptionDescription, BoolOption, IntOption, StrOption, \
Leadership, Config
Leadership, Config, calc_value, Params, ParamOption
from tiramisu.error import PropertiesOptionError, RequirementError
from py.test import raises
from tiramisu.storage import list_sessions, delete_session
@ -65,6 +65,27 @@ def test_requires():
api.option('ip_address_service').value.get()
def test_requires_callback():
a = BoolOption('activate_service', '', True)
b = IPOption('ip_address_service', '',
requires=[{'callback': calc_value, 'callback_params': Params(ParamOption(a)), 'expected': False, 'action': 'disabled'}])
od = OptionDescription('service', '', [a, b])
api = Config(od)
api.property.read_write()
assert not api.option('activate_service').option.requires()
assert api.option('ip_address_service').option.requires()
api.option('ip_address_service').value.get()
api.option('activate_service').value.set(False)
props = []
try:
api.option('ip_address_service').value.get()
except PropertiesOptionError as err:
props = err.proptype
assert frozenset(props) == frozenset(['disabled'])
api.option('activate_service').value.set(True)
api.option('ip_address_service').value.get()
def test_requires_inverse():
a = BoolOption('activate_service', '', True)
b = IPOption('ip_address_service', '',
@ -179,6 +200,44 @@ def test_requires_same_action():
assert frozenset(props) == frozenset(['disabled'])
def test_requires_same_action_callback():
activate_service = BoolOption('activate_service', '', True)
activate_service_web = BoolOption('activate_service_web', '', True,
requires=[{'callback': calc_value, 'callback_params': Params(ParamOption(activate_service)), 'expected': False,
'action': 'new'}])
ip_address_service_web = IPOption('ip_address_service_web', '',
requires=[{'option': activate_service_web, 'expected': False,
'action': 'disabled', 'inverse': False,
'transitive': True, 'same_action': False}])
od1 = OptionDescription('service', '', [activate_service, activate_service_web, ip_address_service_web])
api = Config(od1)
api.property.read_write()
api.property.add('new')
api.option('activate_service').value.get()
api.option('activate_service_web').value.get()
api.option('ip_address_service_web').value.get()
api.option('activate_service').value.set(False)
#
props = []
try:
api.option('activate_service_web').value.get()
except PropertiesOptionError as err:
props = err.proptype
assert frozenset(props) == frozenset(['new'])
#
props = []
try:
api.option('ip_address_service_web').value.get()
except PropertiesOptionError as err:
props = err.proptype
submsg = '"disabled" (' + _('the calculated value is {0}').format('"False"') + ')'
assert str(err) == str(_('cannot access to {0} "{1}" because has {2} {3}').format('option', 'ip_address_service_web', 'property', submsg))
#access to cache
assert str(err) == str(_('cannot access to {0} "{1}" because has {2} {3}').format('option', 'ip_address_service_web', 'property', submsg))
assert frozenset(props) == frozenset(['disabled'])
def test_multiple_requires():
a = StrOption('activate_service', '')
b = IPOption('ip_address_service', '',
@ -326,6 +385,36 @@ def test_requires_transitive():
assert frozenset(props) == frozenset(['disabled'])
def test_requires_transitive_callback():
a = BoolOption('activate_service', '', True)
b = BoolOption('activate_service_web', '', True,
requires=[{'callback': calc_value, 'callback_params': Params(ParamOption(a)), 'expected': False, 'action': 'disabled'}])
d = IPOption('ip_address_service_web', '',
requires=[{'callback': calc_value, 'callback_params': Params(ParamOption(b)), 'expected': False, 'action': 'disabled'}])
od = OptionDescription('service', '', [a, b, d])
api = Config(od)
api.property.read_write()
api.option('activate_service').value.get()
api.option('activate_service_web').value.get()
api.option('ip_address_service_web').value.get()
api.option('activate_service').value.set(False)
#
props = []
try:
api.option('activate_service_web').value.get()
except PropertiesOptionError as err:
props = err.proptype
assert frozenset(props) == frozenset(['disabled'])
#
props = []
try:
api.option('ip_address_service_web').value.get()
except PropertiesOptionError as err:
props = err.proptype
assert frozenset(props) == frozenset(['disabled'])
def test_requires_transitive_unrestraint():
a = BoolOption('activate_service', '', True)
b = BoolOption('activate_service_web', '', True,
@ -589,6 +678,46 @@ def test_requires_multi_disabled():
assert frozenset(props) == frozenset(['disabled'])
def test_requires_multi_disabled_callback():
a = BoolOption('activate_service', '')
b = IntOption('num_service', '')
c = IPOption('ip_address_service', '',
requires=[{'callback': calc_value, 'callback_params': Params(ParamOption(a)), 'expected': True, 'action': 'disabled'},
{'callback': calc_value, 'callback_params': Params(ParamOption(b)), 'expected': 1, 'action': 'disabled'}])
od = OptionDescription('service', '', [a, b, c])
api = Config(od)
api.property.read_write()
api.option('ip_address_service').value.get()
api.option('activate_service').value.set(True)
props = []
try:
api.option('ip_address_service').value.get()
except PropertiesOptionError as err:
props = err.proptype
assert frozenset(props) == frozenset(['disabled'])
api.option('activate_service').value.set(False)
api.option('ip_address_service').value.get()
api.option('num_service').value.set(1)
props = []
try:
api.option('ip_address_service').value.get()
except PropertiesOptionError as err:
props = err.proptype
assert frozenset(props) == frozenset(['disabled'])
api.option('activate_service').value.set(True)
props = []
try:
api.option('ip_address_service').value.get()
except PropertiesOptionError as err:
props = err.proptype
assert frozenset(props) == frozenset(['disabled'])
def test_requires_multi_disabled_new_format():
a = BoolOption('activate_service', '')
b = IntOption('num_service', '')
@ -1006,6 +1135,56 @@ def test_leadership_requires():
del ret['ip_admin_eth0.netmask_admin_eth0']
def test_leadership_requires_callback():
ip_admin_eth0 = StrOption('ip_admin_eth0', "ip réseau autorisé", multi=True)
netmask_admin_eth0 = StrOption('netmask_admin_eth0', "masque du sous-réseau", multi=True,
requires=[{'callback': calc_value, 'callback_params': Params(ParamOption(ip_admin_eth0)), 'expected': '192.168.1.1', 'action': 'disabled'}])
interface1 = Leadership('ip_admin_eth0', '', [ip_admin_eth0, netmask_admin_eth0])
maconfig = OptionDescription('toto', '', [interface1])
api = Config(maconfig)
api.property.read_write()
assert api.option('ip_admin_eth0.ip_admin_eth0').value.get() == []
api.option('ip_admin_eth0.ip_admin_eth0').value.set(['192.168.1.2'])
assert api.option('ip_admin_eth0.netmask_admin_eth0', 0).value.get() is None
assert api.option('ip_admin_eth0.ip_admin_eth0').value.get() == ['192.168.1.2']
#
api.option('ip_admin_eth0.ip_admin_eth0').value.set(['192.168.1.2', '192.168.1.1'])
assert api.option('ip_admin_eth0.netmask_admin_eth0', 0).value.get() is None
raises(PropertiesOptionError, "api.option('ip_admin_eth0.netmask_admin_eth0', 1).value.get()")
#
api.option('ip_admin_eth0.ip_admin_eth0').value.set(['192.168.1.2', '192.168.1.2'])
assert api.option('ip_admin_eth0.netmask_admin_eth0', 0).value.get() is None
assert api.option('ip_admin_eth0.netmask_admin_eth0', 1).value.get() is None
api.option('ip_admin_eth0.netmask_admin_eth0', 1).value.set('255.255.255.255')
assert api.option('ip_admin_eth0.netmask_admin_eth0', 1).value.get() == '255.255.255.255'
assert api.value.dict() == {'ip_admin_eth0.ip_admin_eth0': ['192.168.1.2', '192.168.1.2'],
'ip_admin_eth0.netmask_admin_eth0': [None, '255.255.255.255']}
#
api.option('ip_admin_eth0.ip_admin_eth0').value.set(['192.168.1.2', '192.168.1.1'])
assert api.option('ip_admin_eth0.netmask_admin_eth0', 0).value.get() is None
raises(PropertiesOptionError, "api.option('ip_admin_eth0.netmask_admin_eth0', 1).value.get()")
ret = api.value.dict()
assert set(ret.keys()) == set(['ip_admin_eth0.ip_admin_eth0', 'ip_admin_eth0.netmask_admin_eth0'])
assert ret['ip_admin_eth0.ip_admin_eth0'] == ['192.168.1.2', '192.168.1.1']
assert len(ret['ip_admin_eth0.netmask_admin_eth0']) == 2
assert ret['ip_admin_eth0.netmask_admin_eth0'][0] is None
assert isinstance(ret['ip_admin_eth0.netmask_admin_eth0'][1], PropertiesOptionError)
del ret['ip_admin_eth0.netmask_admin_eth0'][1]
del ret['ip_admin_eth0.netmask_admin_eth0'][0]
del ret['ip_admin_eth0.netmask_admin_eth0']
#
api.option('ip_admin_eth0.netmask_admin_eth0', 0).value.set('255.255.255.255')
ret = api.value.dict()
assert set(ret.keys()) == set(['ip_admin_eth0.ip_admin_eth0', 'ip_admin_eth0.netmask_admin_eth0'])
assert ret['ip_admin_eth0.ip_admin_eth0'] == ['192.168.1.2', '192.168.1.1']
assert len(ret['ip_admin_eth0.netmask_admin_eth0']) == 2
assert ret['ip_admin_eth0.netmask_admin_eth0'][0] == '255.255.255.255'
assert isinstance(ret['ip_admin_eth0.netmask_admin_eth0'][1], PropertiesOptionError)
del ret['ip_admin_eth0.netmask_admin_eth0'][1]
del ret['ip_admin_eth0.netmask_admin_eth0'][0]
del ret['ip_admin_eth0.netmask_admin_eth0']
def test_leadership_requires_both():
ip_admin = StrOption('ip_admin_eth0', "ip réseau autorisé")
ip_admin_eth0 = StrOption('ip_admin_eth0', "ip réseau autorisé", multi=True,
@ -1037,7 +1216,7 @@ def test_leadership_requires_properties():
netmask_admin_eth0 = StrOption('netmask_admin_eth0', "masque du sous-réseau", multi=True,
requires=[{'option': ip_admin_eth0, 'expected': '192.168.1.1', 'action': 'disabled'}])
Leadership('ip_admin_eth0', '', [ip_admin_eth0, netmask_admin_eth0], properties=('hidden',),
requires=[{'option': ip_admin, 'expected': '192.168.1.1', 'action': 'disabled'}])
requires=[{'option': ip_admin, 'expected': '192.168.1.1', 'action': 'disabled'}])
def test_leadership_requires_leader():
@ -1068,6 +1247,34 @@ def test_leadership_requires_leader():
assert api.value.dict() == {'activate': False}
def test_leadership_requires_leader_callback():
activate = BoolOption('activate', "Activer l'accès au réseau", True)
ip_admin_eth0 = StrOption('ip_admin_eth0', "ip réseau autorisé", multi=True,
requires=[{'callback': calc_value, 'callback_params': Params(ParamOption(activate)), 'expected': False, 'action': 'disabled'}])
netmask_admin_eth0 = StrOption('netmask_admin_eth0', "masque du sous-réseau", multi=True)
interface1 = Leadership('ip_admin_eth0', '', [ip_admin_eth0, netmask_admin_eth0])
maconfig = OptionDescription('toto', '', [activate, interface1])
api = Config(maconfig)
api.property.read_write()
#
assert api.option('ip_admin_eth0.ip_admin_eth0').value.get() == []
api.option('ip_admin_eth0.ip_admin_eth0').value.set(['192.168.1.2'])
assert api.option('ip_admin_eth0.netmask_admin_eth0', 0).value.get() is None
assert api.option('ip_admin_eth0.ip_admin_eth0').value.get() == ['192.168.1.2']
#
api.option('activate').value.set(False)
raises(PropertiesOptionError, "api.option('ip_admin_eth0.ip_admin_eth0').value.get()")
raises(PropertiesOptionError, "api.option('ip_admin_eth0.netmask_admin_eth0', 0).value.get()")
#
api.option('activate').value.set(True)
assert api.option('ip_admin_eth0.netmask_admin_eth0', 0).value.get() is None
#
api.option('activate').value.set(False)
raises(PropertiesOptionError, "api.option('ip_admin_eth0.ip_admin_eth0').value.get()")
raises(PropertiesOptionError, "api.option('ip_admin_eth0.netmask_admin_eth0', 0).value.get()")
assert api.value.dict() == {'activate': False}
def test_leadership_requires_leadership():
activate = BoolOption('activate', "Activer l'accès au réseau", True)
ip_admin_eth0 = StrOption('ip_admin_eth0', "ip réseau autorisé", multi=True)
@ -1096,6 +1303,34 @@ def test_leadership_requires_leadership():
assert api.value.dict() == {'activate': False}
def test_leadership_requires_leadership_callback():
activate = BoolOption('activate', "Activer l'accès au réseau", True)
ip_admin_eth0 = StrOption('ip_admin_eth0', "ip réseau autorisé", multi=True)
netmask_admin_eth0 = StrOption('netmask_admin_eth0', "masque du sous-réseau", multi=True)
interface1 = Leadership('ip_admin_eth0', '', [ip_admin_eth0, netmask_admin_eth0],
requires=[{'callback': calc_value, 'callback_params': Params(ParamOption(activate)), 'expected': False, 'action': 'disabled'}])
maconfig = OptionDescription('toto', '', [activate, interface1])
api = Config(maconfig)
api.property.read_write()
#
assert api.option('ip_admin_eth0.ip_admin_eth0').value.get() == []
api.option('ip_admin_eth0.ip_admin_eth0').value.set(['192.168.1.2'])
assert api.option('ip_admin_eth0.netmask_admin_eth0', 0).value.get() is None
assert api.option('ip_admin_eth0.ip_admin_eth0').value.get() == ['192.168.1.2']
#
api.option('activate').value.set(False)
raises(PropertiesOptionError, "api.option('ip_admin_eth0.ip_admin_eth0').value.get()")
raises(PropertiesOptionError, "api.option('ip_admin_eth0.netmask_admin_eth0', 0).value.get()")
#
api.option('activate').value.set(True)
assert api.option('ip_admin_eth0.netmask_admin_eth0', 0).value.get() is None
#
api.option('activate').value.set(False)
raises(PropertiesOptionError, "api.option('ip_admin_eth0.ip_admin_eth0').value.get()")
raises(PropertiesOptionError, "api.option('ip_admin_eth0.netmask_admin_eth0', 0).value.get()")
assert api.value.dict() == {'activate': False}
def test_leadership_requires_no_leader():
activate = BoolOption('activate', "Activer l'accès au réseau", True)
ip_admin_eth0 = StrOption('ip_admin_eth0', "ip réseau autorisé", multi=True)
@ -1125,6 +1360,40 @@ def test_leadership_requires_no_leader():
assert api.value.dict() == {'ip_admin_eth0.ip_admin_eth0': ['192.168.1.2', '192.168.1.1'], 'activate': False}
def test_leadership_requires_no_leader_callback():
activate = BoolOption('activate', "Activer l'accès au réseau", True)
ip_admin_eth0 = StrOption('ip_admin_eth0', "ip réseau autorisé", multi=True)
netmask_admin_eth0 = StrOption('netmask_admin_eth0', "masque du sous-réseau", multi=True,
requires=[{'callback': calc_value, 'callback_params': Params(ParamOption(activate)), 'expected': False, 'action': 'disabled'}])
interface1 = Leadership('ip_admin_eth0', '', [ip_admin_eth0, netmask_admin_eth0])
maconfig = OptionDescription('toto', '', [activate, interface1])
api = Config(maconfig)
api.property.read_write()
assert api.option('ip_admin_eth0.ip_admin_eth0').value.get() == []
api.option('ip_admin_eth0.ip_admin_eth0').value.set(['192.168.1.2'])
assert api.option('ip_admin_eth0.netmask_admin_eth0', 0).value.get() is None
assert api.option('ip_admin_eth0.ip_admin_eth0').value.get() == ['192.168.1.2']
api.option('activate').value.set(False)
api.option('ip_admin_eth0.ip_admin_eth0').value.set(['192.168.1.2', '192.168.1.1'])
assert api.option('ip_admin_eth0.ip_admin_eth0').value.get() == ['192.168.1.2', '192.168.1.1']
raises(PropertiesOptionError, "api.option('ip_admin_eth0.netmask_admin_eth0', 0).value.get()")
raises(PropertiesOptionError, "api.option('ip_admin_eth0.netmask_admin_eth0', 1).value.get()")
api.option('activate').value.set(True)
assert api.option('ip_admin_eth0.netmask_admin_eth0', 0).value.get() is None
assert api.option('ip_admin_eth0.netmask_admin_eth0', 1).value.get() is None
api.option('ip_admin_eth0.netmask_admin_eth0', 1).value.set('255.255.255.255')
assert api.option('ip_admin_eth0.netmask_admin_eth0', 1).value.get() == '255.255.255.255'
api.option('activate').value.set(False)
raises(PropertiesOptionError, "api.option('ip_admin_eth0.netmask_admin_eth0', 0).value.get()")
raises(PropertiesOptionError, "api.option('ip_admin_eth0.netmask_admin_eth0', 1).value.get()")
dico = api.value.dict()
assert set(dico.keys()) == {'activate', 'ip_admin_eth0.ip_admin_eth0', 'ip_admin_eth0.netmask_admin_eth0'}
dico['ip_admin_eth0.ip_admin_eth0'] == ['192.168.1.2', '192.168.1.1']
dico['activate'] == False
del dico['ip_admin_eth0.netmask_admin_eth0'][1]
del dico['ip_admin_eth0.netmask_admin_eth0'][0]
def test_leadership_requires_complet():
optiontoto = StrOption('unicodetoto', "Unicode leader")
option = StrOption('unicode', "Unicode leader", multi=True)
@ -1212,6 +1481,106 @@ def test_leadership_requires_complet():
del dico['options.unicode.unicode7']
def test_leadership_requires_complet_callback():
optiontoto = StrOption('unicodetoto', "Unicode leader")
option = StrOption('unicode', "Unicode leader", multi=True)
option1 = StrOption('unicode1', "Unicode follower 1", multi=True)
option2 = StrOption('unicode2', "Values 'test' must show 'Unicode follower 3'", multi=True)
option3 = StrOption('unicode3', "Unicode follower 3", requires=[{'callback': calc_value,
'callback_params': Params(ParamOption(option)),
'expected': u'test',
'action': 'hidden',
'inverse': True}],
multi=True)
option4 = StrOption('unicode4', "Unicode follower 4", requires=[{'callback': calc_value,
'callback_params': Params(ParamOption(option2)),
'expected': u'test',
'action': 'hidden',
'inverse': True}],
multi=True)
option5 = StrOption('unicode5', "Unicode follower 5", requires=[{'callback': calc_value,
'callback_params': Params(ParamOption(optiontoto)),
'expected': u'test',
'action': 'hidden',
'inverse': True}],
multi=True)
option6 = StrOption('unicode6', "Unicode follower 6", requires=[{'callback': calc_value,
'callback_params': Params(ParamOption(optiontoto)),
'expected': u'test',
'action': 'hidden',
'inverse': True},
{'callback': calc_value,
'callback_params': Params(ParamOption(option2)),
'expected': u'test',
'action': 'hidden',
'inverse': True}],
multi=True)
option7 = StrOption('unicode7', "Unicode follower 7", requires=[{'callback': calc_value,
'callback_params': Params(ParamOption(option2)),
'expected': u'test',
'action': 'hidden',
'inverse': True},
{'callback': calc_value,
'callback_params': Params(ParamOption(optiontoto)),
'expected': u'test',
'action': 'hidden',
'inverse': True}],
multi=True)
descr1 = Leadership("unicode", "Common configuration 1",
[option, option1, option2, option3, option4, option5, option6, option7])
descr = OptionDescription("options", "Common configuration 2", [descr1, optiontoto])
descr = OptionDescription("unicode1_leadership_requires", "Leader followers with Unicode follower 3 hidden when Unicode follower 2 is test", [descr])
config = Config(descr)
config.property.read_write()
config.option('options.unicode.unicode').value.set(['test', 'trah'])
config.option('options.unicode.unicode2', 0).value.set('test')
dico = config.value.dict()
assert dico.keys() == set(['options.unicode.unicode', 'options.unicode.unicode1', 'options.unicode.unicode2', 'options.unicode.unicode3', 'options.unicode.unicode4', 'options.unicode.unicode5', 'options.unicode.unicode6', 'options.unicode.unicode7', 'options.unicodetoto'])
assert dico['options.unicode.unicode'] == ['test', 'trah']
assert dico['options.unicode.unicode1'] == [None, None]
assert dico['options.unicode.unicode2'] == ['test', None]
assert dico['options.unicode.unicode3'][0] is None
assert isinstance(dico['options.unicode.unicode3'][1], PropertiesOptionError)
assert dico['options.unicode.unicode4'][0] is None
assert isinstance(dico['options.unicode.unicode4'][1], PropertiesOptionError)
assert dico['options.unicodetoto'] is None
del dico['options.unicode.unicode3'][1]
del dico['options.unicode.unicode3']
del dico['options.unicode.unicode4'][1]
del dico['options.unicode.unicode4']
del dico['options.unicode.unicode5'][0]
del dico['options.unicode.unicode5'][0]
del dico['options.unicode.unicode6'][0]
del dico['options.unicode.unicode6'][0]
del dico['options.unicode.unicode7'][0]
del dico['options.unicode.unicode7'][0]
#
config.option('options.unicodetoto').value.set('test')
dico = config.value.dict()
assert dico.keys() == set(['options.unicode.unicode', 'options.unicode.unicode1', 'options.unicode.unicode2', 'options.unicode.unicode3', 'options.unicode.unicode4', 'options.unicode.unicode5', 'options.unicode.unicode6', 'options.unicode.unicode7', 'options.unicodetoto'])
assert dico['options.unicode.unicode'] == ['test', 'trah']
assert dico['options.unicode.unicode1'] == [None, None]
assert dico['options.unicode.unicode2'] == ['test', None]
assert dico['options.unicode.unicode3'][0] is None
assert isinstance(dico['options.unicode.unicode3'][1], PropertiesOptionError)
assert dico['options.unicode.unicode4'][0] is None
assert isinstance(dico['options.unicode.unicode4'][1], PropertiesOptionError)
assert dico['options.unicode.unicode5'] == [None, None]
assert dico['options.unicode.unicode6'][0] is None
assert isinstance(dico['options.unicode.unicode6'][1], PropertiesOptionError)
assert dico['options.unicode.unicode7'][0] is None
assert isinstance(dico['options.unicode.unicode7'][1], PropertiesOptionError)
assert dico['options.unicodetoto'] == 'test'
del dico['options.unicode.unicode3'][1]
del dico['options.unicode.unicode3']
del dico['options.unicode.unicode4'][1]
del dico['options.unicode.unicode4']
del dico['options.unicode.unicode6'][1]
del dico['options.unicode.unicode6']
del dico['options.unicode.unicode7'][1]
del dico['options.unicode.unicode7']
def test_leadership_requires_transitive():
optiontoto = StrOption('unicodetoto', "Unicode leader")
option = StrOption('unicode', "Unicode leader", multi=True)
@ -1325,3 +1694,124 @@ def test_leadership_requires_transitive():
del (dico['options.unicode.unicode4'][2])
del (dico['options.unicode.unicode4'][1])
del (dico['options.unicode.unicode4'][0])
def test_leadership_requires_transitive_callback():
optiontoto = StrOption('unicodetoto', "Unicode leader")
option = StrOption('unicode', "Unicode leader", multi=True)
option1 = StrOption('unicode1', "Unicode follower 1", multi=True)
option2 = StrOption('unicode2', "Unicode follower 2", requires=[{'callback': calc_value,
'callback_params': Params(ParamOption(optiontoto)),
'expected': u'test',
'action': 'disabled',
'transitive': True,
'inverse': True}],
multi=True)
option3 = StrOption('unicode3', "Unicode follower 3", requires=[{'callback': calc_value,
'callback_params': Params(ParamOption(option2)),
'expected': u'test',
'action': 'disabled',
'transitive': True,
'inverse': True}],
multi=True)
option4 = StrOption('unicode4', "Unicode follower 4", requires=[{'callback': calc_value,
'callback_params': Params(ParamOption(option3)),
'expected': u'test',
'action': 'disabled',
'transitive': True,
'inverse': True}],
multi=True)
descr1 = Leadership("unicode", "Common configuration 1",
[option, option1, option2, option3, option4])
descr = OptionDescription("options", "Common configuration 2", [descr1, optiontoto])
descr = OptionDescription("unicode1", "", [descr])
config = Config(descr)
config.property.read_write()
assert config.value.dict() == {'options.unicode.unicode': [], 'options.unicode.unicode1': [], 'options.unicode.unicode2': [], 'options.unicode.unicode3': [], 'options.unicode.unicode4': [], 'options.unicodetoto': None}
#
config.option('options.unicodetoto').value.set('test')
assert config.value.dict() == {'options.unicode.unicode': [], 'options.unicode.unicode1': [], 'options.unicode.unicode2': [], 'options.unicode.unicode3': [], 'options.unicode.unicode4': [], 'options.unicodetoto': 'test'}
#
config.option('options.unicode.unicode').value.set(['a', 'b', 'c'])
dico = config.value.dict()
assert list(dico.keys()) == ['options.unicode.unicode', 'options.unicode.unicode1', 'options.unicode.unicode2', 'options.unicode.unicode3', 'options.unicode.unicode4', 'options.unicodetoto']
assert dico['options.unicodetoto'] == 'test'
assert dico['options.unicode.unicode'] == ['a', 'b', 'c']
assert dico['options.unicode.unicode1'] == [None, None, None]
assert dico['options.unicode.unicode2'] == [None, None, None]
assert isinstance(dico['options.unicode.unicode3'][0], PropertiesOptionError)
assert isinstance(dico['options.unicode.unicode3'][1], PropertiesOptionError)
assert isinstance(dico['options.unicode.unicode3'][2], PropertiesOptionError)
assert isinstance(dico['options.unicode.unicode4'][0], PropertiesOptionError)
assert isinstance(dico['options.unicode.unicode4'][1], PropertiesOptionError)
assert isinstance(dico['options.unicode.unicode4'][2], PropertiesOptionError)
del (dico['options.unicode.unicode3'][2])
del (dico['options.unicode.unicode3'][1])
del (dico['options.unicode.unicode3'][0])
del (dico['options.unicode.unicode4'][2])
del (dico['options.unicode.unicode4'][1])
del (dico['options.unicode.unicode4'][0])
#
config.option('options.unicode.unicode2', 1).value.set('test')
config.option('options.unicode.unicode3', 1).value.set('test')
dico = config.value.dict()
assert list(dico.keys()) == ['options.unicode.unicode', 'options.unicode.unicode1', 'options.unicode.unicode2', 'options.unicode.unicode3', 'options.unicode.unicode4', 'options.unicodetoto']
assert dico['options.unicodetoto'] == 'test'
assert dico['options.unicode.unicode'] == ['a', 'b', 'c']
assert dico['options.unicode.unicode1'] == [None, None, None]
assert dico['options.unicode.unicode2'] == [None, 'test', None]
assert isinstance(dico['options.unicode.unicode3'][0], PropertiesOptionError)
assert dico['options.unicode.unicode3'][1] == 'test'
assert isinstance(dico['options.unicode.unicode3'][2], PropertiesOptionError)
assert isinstance(dico['options.unicode.unicode4'][0], PropertiesOptionError)
assert dico['options.unicode.unicode4'][1] == None
assert isinstance(dico['options.unicode.unicode4'][2], PropertiesOptionError)
del (dico['options.unicode.unicode3'][2])
del (dico['options.unicode.unicode3'][1])
del (dico['options.unicode.unicode3'][0])
del (dico['options.unicode.unicode4'][2])
del (dico['options.unicode.unicode4'][1])
del (dico['options.unicode.unicode4'][0])
#
config.option('options.unicode.unicode2', 1).value.set('rah')
dico = config.value.dict()
assert list(dico.keys()) == ['options.unicode.unicode', 'options.unicode.unicode1', 'options.unicode.unicode2', 'options.unicode.unicode3', 'options.unicode.unicode4', 'options.unicodetoto']
assert dico['options.unicodetoto'] == 'test'
assert dico['options.unicode.unicode'] == ['a', 'b', 'c']
assert dico['options.unicode.unicode1'] == [None, None, None]
assert dico['options.unicode.unicode2'] == [None, 'rah', None]
assert isinstance(dico['options.unicode.unicode3'][0], PropertiesOptionError)
assert isinstance(dico['options.unicode.unicode3'][1], PropertiesOptionError)
assert isinstance(dico['options.unicode.unicode3'][2], PropertiesOptionError)
assert isinstance(dico['options.unicode.unicode4'][0], PropertiesOptionError)
assert isinstance(dico['options.unicode.unicode4'][1], PropertiesOptionError)
assert isinstance(dico['options.unicode.unicode4'][2], PropertiesOptionError)
del (dico['options.unicode.unicode3'][2])
del (dico['options.unicode.unicode3'][1])
del (dico['options.unicode.unicode3'][0])
del (dico['options.unicode.unicode4'][2])
del (dico['options.unicode.unicode4'][1])
del (dico['options.unicode.unicode4'][0])
#
config.option('options.unicode.unicode2', 1).value.set('test')
config.option('options.unicodetoto').value.set('rah')
dico = config.value.dict()
assert list(dico.keys()) == ['options.unicode.unicode', 'options.unicode.unicode1', 'options.unicode.unicode2', 'options.unicode.unicode3', 'options.unicode.unicode4', 'options.unicodetoto']
assert dico['options.unicodetoto'] == 'rah'
assert dico['options.unicode.unicode'] == ['a', 'b', 'c']
assert dico['options.unicode.unicode1'] == [None, None, None]
assert isinstance(dico['options.unicode.unicode3'][0], PropertiesOptionError)
assert isinstance(dico['options.unicode.unicode3'][1], PropertiesOptionError)
assert isinstance(dico['options.unicode.unicode3'][2], PropertiesOptionError)
assert isinstance(dico['options.unicode.unicode4'][0], PropertiesOptionError)
assert isinstance(dico['options.unicode.unicode4'][1], PropertiesOptionError)
assert isinstance(dico['options.unicode.unicode4'][2], PropertiesOptionError)
del (dico['options.unicode.unicode2'][2])
del (dico['options.unicode.unicode2'][1])
del (dico['options.unicode.unicode2'][0])
del (dico['options.unicode.unicode3'][2])
del (dico['options.unicode.unicode3'][1])
del (dico['options.unicode.unicode3'][0])
del (dico['options.unicode.unicode4'][2])
del (dico['options.unicode.unicode4'][1])
del (dico['options.unicode.unicode4'][0])

View File

@ -465,8 +465,9 @@ class _TiramisuOptionValueOption:
if isinstance(value, list):
while undefined in value:
idx = value.index(undefined)
value[idx] = values.getdefaultvalue(self._option_bag,
force_index=idx)
soption_bag = self._option_bag.copy()
soption_bag.index = idx
value[idx] = values.getdefaultvalue(soption_bag)
elif value == undefined:
value = values.getdefaultvalue(self._option_bag)
self._subconfig.setattr(value,

View File

@ -90,11 +90,11 @@ def manager_callback(callbk: Union[ParamOption, ParamValue],
return value[index]
return value
except PropertiesOptionError as err:
# raise because must not add value None in carry_out_calculation
# raise PropertiesOptionError (which is catched) because must not add value None in carry_out_calculation
if callbk.notraisepropertyerror:
raise err
raise ConfigError(_('unable to carry out a calculation for "{}"'
', {}').format(option.impl_get_display_name(), err))
', {}').format(option.impl_get_display_name(), err), err)
def carry_out_calculation(option,

View File

@ -116,7 +116,7 @@ class PropertiesOptionError(AttributeError):
self._name,
prop_msg,
msg))
del self._requires, self._opt_type, self._name, self._option_bag
del self._requires, self._opt_type, self._name
del self._settings, self._orig_opt
return self.msg
@ -127,7 +127,11 @@ class ConfigError(Exception):
"""attempt to change an option's owner without a value
or in case of `_cfgimpl_descr` is None
or if a calculation cannot be carried out"""
pass
def __init__(self,
exp,
ori_err=None):
super().__init__(exp)
self.ori_err = ori_err
class ConflictError(Exception):

View File

@ -49,9 +49,12 @@ class Param:
class ParamOption(Param):
__slots__ = ('option', 'notraisepropertyerror')
def __init__(self, option, notraisepropertyerror=False):
if not hasattr(option, 'impl_is_symlinkoption'):
__slots__ = ('option',
'notraisepropertyerror')
def __init__(self,
option: 'Option',
notraisepropertyerror: bool=False) -> None:
if __debug__ and not hasattr(option, 'impl_is_symlinkoption'):
raise ValueError(_('paramoption needs an option not {}').format(type(option)))
if option.impl_is_symlinkoption():
cur_opt = option.impl_getopt()
@ -95,6 +98,7 @@ def calc_value(*args: List[Any],
join: Optional[str]=None,
min_args_len: Optional[int]=None,
operator: Optional[str]=None,
index: Optional[int]=None,
**kwargs) -> Any:
"""calculate value
:param multi: value returns must be a list of value
@ -181,7 +185,6 @@ def calc_value(*args: List[Any],
>>> cfg.value.dict()
{'val1': 'val1', 'val2': 'val1', 'val3': ['val1']}
* you want to join two values with '.'
>>> from tiramisu import calc_value, StrOption, OptionDescription, Config, Params, ParamOption, ParamValue
>>> val1 = StrOption('val1', "", 'val1')
@ -305,6 +308,11 @@ def calc_value(*args: List[Any],
value = None
else:
value = value[0]
if isinstance(value, list) and index is not None:
if len(value) > index:
value = value[index]
else:
value = None
elif None in value and not allow_none:
value = []
elif remove_duplicate_value:

View File

@ -15,9 +15,16 @@
# You should have received a copy of the GNU Lesser General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
# ____________________________________________________________
from logging import getLogger
from logging import getLogger, DEBUG, basicConfig, StreamHandler, Formatter
import os
log = getLogger('tiramisu')
# import logging
# logging.basicConfig(format='%(levelname)s:%(message)s', level=logging.DEBUG)
if os.environ.get('TIRAMISU_DEBUG') == 'True':
log.setLevel(DEBUG)
handler = StreamHandler()
handler.setLevel(DEBUG)
formatter = Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
handler.setFormatter(formatter)
log.addHandler(handler)

View File

@ -170,7 +170,7 @@ class Base:
param.option._add_dependency(self)
if type_ == 'validator':
self._has_dependency = True
is_multi = self.impl_is_dynoptiondescription() or self.impl_is_multi()
is_multi = self.impl_is_optiondescription() or self.impl_is_multi()
func_args, func_kwargs, func_positional, func_keyword = self._get_function_args(calculator)
calculator_args, calculator_kwargs = self._get_parameters_args(calculator_params, add_value)
# remove knowned kwargs
@ -253,13 +253,14 @@ class Base:
def _impl_set_callback(self,
callback: Callable,
callback_params: Optional[Params]=None) -> None:
if callback is None and callback_params is not None:
raise ValueError(_("params defined for a callback function but "
"no callback defined"
' yet for option "{0}"').format(
self.impl_getname()))
self._validate_calculator(callback,
callback_params)
if __debug__:
if callback is None and callback_params is not None:
raise ValueError(_("params defined for a callback function but "
"no callback defined"
' yet for option "{0}"').format(
self.impl_getname()))
self._validate_calculator(callback,
callback_params)
if callback is not None:
callback_params = self._build_calculator_params(callback,
callback_params,
@ -443,17 +444,25 @@ def validate_requires_arg(new_option: BaseOption,
the description of the requires dictionary
"""
def get_option(require):
option = require['option']
if option == 'self':
option = new_option
if not isinstance(option, BaseOption):
raise ValueError(_('malformed requirements '
'must be an option in option {0}').format(name))
if not multi and option.impl_is_multi():
raise ValueError(_('malformed requirements '
'multi option must not set '
'as requires of non multi option {0}').format(name))
option._add_dependency(new_option)
if 'option' in require:
option = require['option']
if option == 'self':
option = new_option
if __debug__:
if not isinstance(option, BaseOption):
raise ValueError(_('malformed requirements '
'must be an option in option {0}').format(name))
if not multi and option.impl_is_multi():
raise ValueError(_('malformed requirements '
'multi option must not set '
'as requires of non multi option {0}').format(name))
option._add_dependency(new_option)
else:
callback = require['callback']
callback_params = new_option._build_calculator_params(callback,
require.get('callback_params'),
'callback')
option = (callback, callback_params)
return option
def _set_expected(action,
@ -482,11 +491,11 @@ def validate_requires_arg(new_option: BaseOption,
operator = get_operator(require)
if isinstance(expected, list):
for exp in expected:
if set(exp.keys()) != {'option', 'value'}:
if __debug__ and set(exp.keys()) != {'option', 'value'}:
raise ValueError(_('malformed requirements expected must have '
'option and value for option {0}').format(name))
option = get_option(exp)
if option is not None:
if __debug__:
try:
option._validate(exp['value'], undefined)
except ValueError as err:
@ -502,7 +511,7 @@ def validate_requires_arg(new_option: BaseOption,
operator)
else:
option = get_option(require)
if expected is not None:
if __debug__ and not isinstance(option, tuple) and expected is not None:
try:
option._validate(expected, undefined)
except ValueError as err:
@ -560,25 +569,29 @@ def validate_requires_arg(new_option: BaseOption,
# start parsing all requires given by user (has dict)
# transforme it to a tuple
for require in requires:
if not isinstance(require, dict):
raise ValueError(_("malformed requirements type for option:"
" {0}, must be a dict").format(name))
valid_keys = ('option', 'expected', 'action', 'inverse', 'transitive',
'same_action', 'operator')
unknown_keys = frozenset(require.keys()) - frozenset(valid_keys)
if unknown_keys != frozenset():
raise ValueError(_('malformed requirements for option: {0}'
' unknown keys {1}, must only '
'{2}').format(name,
unknown_keys,
valid_keys))
# prepare all attributes
if not ('expected' in require and isinstance(require['expected'], list)) and \
not ('option' in require and 'expected' in require) or \
'action' not in require:
raise ValueError(_("malformed requirements for option: {0}"
" require must have option, expected and"
" action keys").format(name))
if __debug__:
if not isinstance(require, dict):
raise ValueError(_("malformed requirements type for option:"
" {0}, must be a dict").format(name))
valid_keys = ('option', 'expected', 'action', 'inverse', 'transitive',
'same_action', 'operator', 'callback', 'callback_params')
unknown_keys = frozenset(require.keys()) - frozenset(valid_keys)
if unknown_keys != frozenset():
raise ValueError(_('malformed requirements for option: {0}'
' unknown keys {1}, must only '
'{2}').format(name,
unknown_keys,
valid_keys))
# {'expected': ..., 'option': ..., 'action': ...}
# {'expected': [{'option': ..., 'value': ...}, ...}], 'action': ...}
# {'expected': ..., 'callback': ..., 'action': ...}
if not 'expected' in require or not 'action' in require or \
not (isinstance(require['expected'], list) or \
'option' in require or \
'callback' in require):
raise ValueError(_("malformed requirements for option: {0}"
" require must have option, expected and"
" action keys").format(name))
action = get_action(require)
config_action.add(action)
if action not in ret_requires:

View File

@ -109,7 +109,7 @@ class Leadership(OptionDescription):
for requires_ in getattr(self, '_requires', ()):
for require in requires_:
for require_opt, values in require[0]:
if require_opt.impl_is_multi() and require_opt.impl_get_leadership():
if not isinstance(require_opt, tuple) and require_opt.impl_is_multi() and require_opt.impl_get_leadership():
raise ValueError(_('malformed requirements option "{0}" '
'must not be in follower for "{1}"').format(
require_opt.impl_getname(),

View File

@ -139,7 +139,7 @@ class CacheOptionDescription(BaseOption):
# * current option must be a follower (and only a follower)
# * option in require and current option must be in same leadership
for require_opt, values in require[0]:
if require_opt.impl_is_multi():
if not isinstance(require_opt, tuple) and require_opt.impl_is_multi():
if is_follower is None:
is_follower = option.impl_is_follower()
if is_follower:

View File

@ -509,43 +509,59 @@ class Settings(object):
exps, action, inverse, transitive, same_action, operator = require
breaked = False
for option, expected in exps:
if option.issubdyn():
option = option.to_dynoption(option_bag.option.rootpath,
option_bag.option.impl_getsuffix())
reqpath = option.impl_getpath()
#FIXME too later!
if reqpath.startswith(option_bag.path + '.'):
raise RequirementError(_("malformed requirements "
"imbrication detected for option:"
" '{0}' with requirement on: "
"'{1}'").format(option_bag.path, reqpath))
idx = None
is_indexed = False
if option.impl_is_follower():
idx = option_bag.index
if idx is None:
if not isinstance(option, tuple):
if option.issubdyn():
option = option.to_dynoption(option_bag.option.rootpath,
option_bag.option.impl_getsuffix())
reqpath = option.impl_getpath()
if __debug__ and reqpath.startswith(option_bag.path + '.'):
# FIXME too later!
raise RequirementError(_("malformed requirements "
"imbrication detected for option:"
" '{0}' with requirement on: "
"'{1}'").format(option_bag.path, reqpath))
idx = None
is_indexed = False
if option.impl_is_follower():
idx = option_bag.index
if idx is None:
continue
elif option.impl_is_leader() and option_bag.index is None:
continue
elif option.impl_is_leader() and option_bag.index is None:
continue
elif option.impl_is_multi() and option_bag.index is not None:
is_indexed = True
config_bag = option_bag.config_bag.copy()
soption_bag = OptionBag()
soption_bag.set_option(option,
reqpath,
idx,
config_bag)
if option_bag.option == option:
soption_bag.config_bag.unrestraint()
soption_bag.config_bag.remove_validation()
soption_bag.apply_requires = False
elif option.impl_is_multi() and option_bag.index is not None:
is_indexed = True
config_bag = option_bag.config_bag.copy()
soption_bag = OptionBag()
soption_bag.set_option(option,
reqpath,
idx,
config_bag)
if option_bag.option == option:
soption_bag.config_bag.unrestraint()
soption_bag.config_bag.remove_validation()
soption_bag.apply_requires = False
else:
soption_bag.config_bag.properties = soption_bag.config_bag.true_properties
soption_bag.config_bag.set_permissive()
else:
soption_bag.config_bag.properties = soption_bag.config_bag.true_properties
soption_bag.config_bag.set_permissive()
if not option_bag.option.impl_is_optiondescription() and option_bag.option.impl_is_follower():
idx = option_bag.index
if idx is None:
continue
is_indexed = False
try:
value = context.getattr(reqpath,
soption_bag)
except PropertiesOptionError as err:
if not isinstance(option, tuple):
value = context.getattr(reqpath,
soption_bag)
else:
value = context.cfgimpl_get_values().carry_out_calculation(option_bag,
option[0],
option[1])
except (PropertiesOptionError, ConfigError) as err:
if isinstance(err, ConfigError):
if not isinstance(err.ori_err, PropertiesOptionError):
raise err
err = err.ori_err
properties = err.proptype
# if not transitive, properties must be verify in current requires
# otherwise if same_action, property must be in properties
@ -586,13 +602,19 @@ class Settings(object):
inverse and value not in expected):
if operator != 'and':
if readable:
if not inverse:
msg = _('the value of "{0}" is {1}')
display_value = display_list(expected, 'or', add_quote=True)
if isinstance(option, tuple):
if not inverse:
msg = _('the calculated value is {0}').format(display_value)
else:
msg = _('the calculated value is not {0}').format(display_value)
else:
msg = _('the value of "{0}" is not {1}')
calc_properties.setdefault(action, []).append(
msg.format(option.impl_get_display_name(),
display_list(expected, 'or', add_quote=True)))
name = option.impl_get_display_name()
if not inverse:
msg = _('the value of "{0}" is {1}').format(name, display_value)
else:
msg = _('the value of "{0}" is not {1}').format(name, display_value)
calc_properties.setdefault(action, []).append(msg)
else:
calc_properties.add(action)
breaked = True

View File

@ -32,16 +32,16 @@ class Properties(Cache):
# properties
def setproperties(self, path, properties):
log.debug('setproperties', path, properties)
log.debug('setproperties %s %s', path, properties)
self._properties[path] = properties
def getproperties(self, path, default_properties):
ret = self._properties.get(path, frozenset(default_properties))
log.debug('getproperties', path, ret)
log.debug('getproperties %s %s', path, ret)
return ret
def delproperties(self, path):
log.debug('delproperties', path)
log.debug('delproperties %s', path)
if path in self._properties:
del(self._properties[path])
@ -64,7 +64,7 @@ class Permissives(Cache):
super(Permissives, self).__init__(storage)
def setpermissives(self, path, permissives):
log.debug('setpermissives', path, permissives)
log.debug('setpermissives %s %s', path, permissives)
if not permissives:
if path in self._permissives:
del self._permissives[path]
@ -73,7 +73,7 @@ class Permissives(Cache):
def getpermissives(self, path=None):
ret = self._permissives.get(path, frozenset())
log.debug('getpermissives', path, ret)
log.debug('getpermissives %s %s', path, ret)
return ret
def exportation(self):
@ -86,6 +86,6 @@ class Permissives(Cache):
self._permissives = permissives
def delpermissive(self, path):
log.debug('delpermissive', path)
log.debug('delpermissive %s', path)
if path in self._permissives:
del(self._permissives[path])

View File

@ -76,7 +76,7 @@ class Values(Cache):
"""set value for a path
a specified value must be associated to an owner
"""
log.debug('setvalue', path, value, owner, index, id(self))
log.debug('setvalue %s %s %s %s %s', path, value, owner, index, id(self))
values = []
vidx = None
@ -97,7 +97,7 @@ class Values(Cache):
return: boolean
"""
has_path = path in self._values[0]
log.debug('hasvalue', path, index, has_path, id(self))
log.debug('hasvalue %s %s %s %s', path, index, has_path, id(self))
if index is None:
return has_path
elif has_path:
@ -110,7 +110,7 @@ class Values(Cache):
"""
_values == ((path1, path2), ((idx1_1, idx1_2), None), ((value1_1, value1_2), value2), ((owner1_1, owner1_2), owner2))
"""
log.debug('reduce_index', path, index, id(self))
log.debug('reduce_index %s %s %s', path, index, id(self))
path_idx = self._values[0].index(path)
# get the "index" position
subidx = self._values[1][path_idx].index(index)
@ -129,7 +129,7 @@ class Values(Cache):
path,
index,
commit):
log.debug('resetvalue_index', path, index, id(self))
log.debug('resetvalue_index %s %s %s', path, index, id(self))
def _resetvalue(nb):
values_idx = list(values[nb])
del(values_idx[path_idx])
@ -163,7 +163,7 @@ class Values(Cache):
commit):
"""remove value means delete value in storage
"""
log.debug('resetvalue', path, id(self))
log.debug('resetvalue %s %s', path, id(self))
def _resetvalue(nb):
lst = list(self._values[nb])
lst.pop(idx)
@ -216,7 +216,7 @@ class Values(Cache):
with_value)
if owner is undefined:
owner = default
log.debug('getvalue', path, index, value, owner, id(self))
log.debug('getvalue %s %s %s %s %s', path, index, value, owner, id(self))
if with_value:
return owner, value
else:

View File

@ -81,7 +81,7 @@ class Permissives(Sqlite3DB):
# permissive
def setpermissives(self, path, permissive):
path = self._sqlite_encode_path(path)
log.debug('setpermissive', path, permissive, id(self))
log.debug('setpermissive %s %s %s', path, permissive, id(self))
self._storage.execute("DELETE FROM permissive WHERE path = ? AND session_id = ?",
(path, self._session_id),
False)
@ -99,7 +99,7 @@ class Permissives(Sqlite3DB):
ret = frozenset()
else:
ret = frozenset(self._sqlite_decode(permissives[0]))
log.debug('getpermissive', path, ret, id(self))
log.debug('getpermissive %s %s %s', path, ret, id(self))
return ret
def delpermissive(self, path):

View File

@ -54,7 +54,7 @@ class Values(Sqlite3DB):
"""set value for an option
a specified value must be associated to an owner
"""
log.debug('setvalue', path, value, owner, index, commit)
log.debug('setvalue %s %s %s %s %s', path, value, owner, index, commit)
path = self._sqlite_encode_path(path)
if index is not None:
self.resetvalue_index(path,
@ -81,7 +81,7 @@ class Values(Sqlite3DB):
"""if opt has a value
return: boolean
"""
log.debug('hasvalue', path, index)
log.debug('hasvalue %s %s', path, index)
path = self._sqlite_encode_path(path)
return self._sqlite_select(path, index) is not None
@ -91,7 +91,7 @@ class Values(Sqlite3DB):
_values == ((path1, path2), ((idx1_1, idx1_2), None),
((value1_1, value1_2), value2), ((owner1_1, owner1_2), owner2))
"""
log.debug('reduce_index', path, index, id(self))
log.debug('reduce_index %s %s %s', path, index, id(self))
self._storage.execute("UPDATE value SET idx = ? WHERE path = ? and idx = ? "
"AND session_id = ?",
(index - 1, path, index, self._session_id))
@ -102,7 +102,7 @@ class Values(Sqlite3DB):
commit=True):
"""remove value means delete value in storage
"""
log.debug('resetvalue_index', path, index, commit)
log.debug('resetvalue_index %s %s %s', path, index, commit)
path = self._sqlite_encode_path(path)
self._storage.execute("DELETE FROM value WHERE path = ? AND session_id = ? AND idx = ?",
(path, self._session_id, index),
@ -113,7 +113,7 @@ class Values(Sqlite3DB):
commit):
"""remove value means delete value in storage
"""
log.debug('resetvalue', path, commit)
log.debug('resetvalue %s %s', path, commit)
path = self._sqlite_encode_path(path)
self._storage.execute("DELETE FROM value WHERE path = ? AND session_id = ?",
(path, self._session_id),
@ -126,7 +126,7 @@ class Values(Sqlite3DB):
index=None):
"""change owner for an option
"""
log.debug('setowner', path, owner, index)
log.debug('setowner %s %s %s', path, owner, index)
path = self._sqlite_encode_path(path)
if index is None:
self._storage.execute("UPDATE value SET owner = ? WHERE path = ? AND session_id = ?",
@ -143,7 +143,7 @@ class Values(Sqlite3DB):
"""get owner for an option
return: owner object
"""
log.debug('getowner', path, default, index, with_value)
log.debug('getowner %s %s %s %s', path, default, index, with_value)
path = self._sqlite_encode_path(path)
request = "SELECT owner, value FROM value WHERE path = ? AND session_id = ?"
if index is not None:
@ -178,7 +178,7 @@ class Values(Sqlite3DB):
:param key: information's key (ex: "help", "doc"
:param value: information's value (ex: "the help string")
"""
log.debug('set_information', key, value)
log.debug('set_information %s %s', key, value)
path = self._sqlite_encode_path(path)
self._storage.execute("DELETE FROM information WHERE key = ? AND session_id = ? AND path = ?",
(key, self._session_id, path),
@ -191,7 +191,7 @@ class Values(Sqlite3DB):
:param key: the item string (ex: "help")
"""
log.debug('get_information', key, default)
log.debug('get_information %s %s', key, default)
path = self._sqlite_encode_path(path)
value = self._storage.select("SELECT value FROM information WHERE key = ? AND "
"session_id = ? AND path = ?",
@ -205,7 +205,7 @@ class Values(Sqlite3DB):
return self._sqlite_decode(value[0])
def del_information(self, path, key, raises):
log.debug('del_information', key, raises)
log.debug('del_information %s %s', key, raises)
path = self._sqlite_encode_path(path)
if raises and self._storage.select("SELECT value FROM information WHERE key = ? "
"AND session_id = ? AND path = ?",
@ -282,7 +282,7 @@ class Values(Sqlite3DB):
def get_max_length(self,
path):
log.debug('get_max_length', path)
log.debug('get_max_length %s', path)
val_max = self._storage.select("SELECT max(idx) FROM value WHERE path = ? AND session_id = ?",
(path, self._session_id), False)
if val_max[0][0] is None:

View File

@ -75,16 +75,16 @@ class Cache(DictCache):
'expire' in self_props):
ntime = int(time())
if timestamp + expiration_time >= ntime:
log.debug('getcache in cache (1)', path, value, _display_classname(self),
log.debug('getcache in cache (1) %s %s %s %s %s', path, value, _display_classname(self),
id(self), index)
return True, value
else:
log.debug('getcache expired value for path {} < {}'.format(
timestamp + expiration_time, ntime))
# if expired, remove from cache
#self.delcache(path)
#else:
# log.debug('getcache expired value for path {} < {}'.format(
# timestamp + expiration_time, ntime))
# # if expired, remove from cache
# #self.delcache(path)
else:
log.debug('getcache in cache (2)', path, value, _display_classname(self),
log.debug('getcache in cache (2) %s %s %s %s %s', path, value, _display_classname(self),
id(self), index)
return True, value
log.debug('getcache {} with index {} not in {} cache'.format(path, index,
@ -94,13 +94,13 @@ class Cache(DictCache):
def delcache(self, path):
"""remove cache for a specified path
"""
log.debug('delcache', path, _display_classname(self), id(self))
log.debug('delcache %s %s %s', path, _display_classname(self), id(self))
if path in self._cache:
self._delcache(path)
def reset_all_cache(self):
"empty the cache"
log.debug('reset_all_cache', _display_classname(self), id(self))
log.debug('reset_all_cache %s %s', _display_classname(self), id(self))
self._reset_all_cache()
def get_cached(self):

View File

@ -16,10 +16,11 @@
# along with this program. If not, see <http://www.gnu.org/licenses/>.
# ____________________________________________________________
import weakref
from typing import Optional
from typing import Optional, Any, Callable
from .error import ConfigError, PropertiesOptionError
from .setting import owners, undefined, forbidden_owners, OptionBag, ConfigBag
from .autolib import carry_out_calculation
from .function import Params
from .i18n import _
@ -135,26 +136,48 @@ class Values(object):
return self.getdefaultvalue(option_bag)
def getdefaultvalue(self,
option_bag,
force_index: Optional[int]=None):
option_bag):
"""get default value:
- get meta config value or
- get calculated value or
- get default value
:param opt: the `option.Option()` object
:param path: path for `option.Option()` object
:type path: str
:param index: index of a multi/submulti
:type index: int
:returns: default value
"""
moption_bag = self._get_meta(option_bag)
if moption_bag:
# retrieved value from meta config
return moption_bag.config_bag.context.cfgimpl_get_values().get_cached_value(moption_bag)
if option_bag.option.impl_has_callback():
# default value is a calculated value
value = self.calculate_value(option_bag)
if value is not undefined:
return value
# now try to get default value:
value = option_bag.option.impl_getdefault()
# - if option is a submulti, return a list a list
# - if option is a multi, return a list
# - default value
if option_bag.option.impl_is_multi() and option_bag.index is not None:
# if index, must return good value for this index
if len(value) > option_bag.index:
value = value[option_bag.index]
else:
# no value for this index, retrieve default multi value
# default_multi is already a list for submulti
value = option_bag.option.impl_getdefault_multi()
return value
def calculate_value(self,
option_bag: OptionBag) -> Any:
def _reset_cache(_value):
if not 'expire' in option_bag.properties:
return
is_cache, cache_value = self._p_.getcache(option_bag.path,
None,
index,
config_bag.properties,
option_bag.index,
option_bag.config_bag.properties,
option_bag.properties,
'value')
if not is_cache or cache_value == _value:
@ -162,75 +185,55 @@ class Values(object):
# so do not invalidate cache
return
# calculated value is a new value, so reset cache
config_bag.context.cfgimpl_reset_cache(option_bag)
option_bag.config_bag.context.cfgimpl_reset_cache(option_bag)
config_bag = option_bag.config_bag
opt = option_bag.option
if force_index is not None:
index = force_index
else:
index = option_bag.index
moption_bag = self._get_meta(option_bag)
if moption_bag:
# retrieved value from meta config
return moption_bag.config_bag.context.cfgimpl_get_values().get_cached_value(moption_bag)
if opt.impl_has_callback():
# if value has callback, calculate value
callback, callback_params = opt.impl_get_callback()
value = carry_out_calculation(opt,
callback=callback,
callback_params=callback_params,
index=index,
config_bag=config_bag,
fromconsistency=option_bag.fromconsistency)
if isinstance(value, list) and index is not None:
# if value is a list and index is set
if opt.impl_is_submulti() and (value == [] or not isinstance(value[0], list)):
# return value only if it's a submulti and not a list of list
_reset_cache(value)
return value
if len(value) > index:
# return the value for specified index if found
_reset_cache(value[index])
return value[index]
# there is no calculate value for this index,
# so return an other default value
else:
if opt.impl_is_submulti():
if isinstance(value, list):
# value is a list, but no index specified
if (value != [] and not isinstance(value[0], list)):
# if submulti, return a list of value
value = [value]
elif index is not None:
# if submulti, return a list of value
value = [value]
else:
# return a list of list for a submulti
value = [[value]]
elif opt.impl_is_multi() and not isinstance(value, list) and index is None:
# return a list for a multi
value = [value]
# if value has callback, calculate value
callback, callback_params = option_bag.option.impl_get_callback()
value = self.carry_out_calculation(option_bag,
callback,
callback_params)
if isinstance(value, list) and option_bag.index is not None:
# if value is a list and index is set
if option_bag.option.impl_is_submulti() and (value == [] or not isinstance(value[0], list)):
# return value only if it's a submulti and not a list of list
_reset_cache(value)
return value
if len(value) > option_bag.index:
# return the value for specified index if found
_reset_cache(value[option_bag.index])
return value[option_bag.index]
# there is no calculate value for this index,
# so return an other default value
else:
if option_bag.option.impl_is_submulti():
if isinstance(value, list):
# value is a list, but no index specified
if (value != [] and not isinstance(value[0], list)):
# if submulti, return a list of value
value = [value]
elif option_bag.index is not None:
# if submulti, return a list of value
value = [value]
else:
# return a list of list for a submulti
value = [[value]]
elif option_bag.option.impl_is_multi() and not isinstance(value, list) and option_bag.index is None:
# return a list for a multi
value = [value]
_reset_cache(value)
return value
return undefined
# now try to get default value:
# - if opt is a submulti, return a list a list
# - if opt is a multi, return a list
# - default value
value = opt.impl_getdefault()
if opt.impl_is_multi() and index is not None:
# if index, must return good value for this index
if len(value) > index:
value = value[index]
else:
# no value for this index, retrieve default multi value
# default_multi is already a list for submulti
value = opt.impl_getdefault_multi()
return value
def carry_out_calculation(self,
option_bag: OptionBag,
callback: Callable,
callback_params: Optional[Params]) -> Any:
return carry_out_calculation(option_bag.option,
callback=callback,
callback_params=callback_params,
index=option_bag.index,
config_bag=option_bag.config_bag,
fromconsistency=option_bag.fromconsistency)
def isempty(self,
opt,
value,