├── requirements.txt
├── setup.py
├── .darglint
├── .pre-commit-hooks.yaml
├── .config
└── dictionary.txt
├── cspell.config.yaml
├── setup.cfg
├── pyproject.toml
├── collection_prep
├── utils.py
├── jinja_utils.py
└── cmd
│ ├── version.py
│ ├── runtime.py
│ ├── update.py
│ ├── plugin.rst.j2
│ └── add_docs.py
├── .gitignore
├── .pre-commit-config.yaml
├── README.md
└── LICENSE
/requirements.txt:
--------------------------------------------------------------------------------
1 | ansible-core==2.16
2 | redbaron
3 | ruamel.yaml
4 |
--------------------------------------------------------------------------------
/setup.py:
--------------------------------------------------------------------------------
1 | """Configuration for setuptools."""
2 |
3 | import setuptools
4 |
5 |
6 | setuptools.setup(setup_requires=["pbr"], pbr=True)
7 |
--------------------------------------------------------------------------------
/.darglint:
--------------------------------------------------------------------------------
1 | [darglint]
2 | # NOTE: All `darglint` styles except for `sphinx` hit ridiculously low
3 | # NOTE: performance on some of the in-project Python modules.
4 | # Refs:
5 | # * https://github.com/terrencepreilly/darglint/issues/186
6 | docstring_style = sphinx
7 | strictness = full
8 |
--------------------------------------------------------------------------------
/.pre-commit-hooks.yaml:
--------------------------------------------------------------------------------
1 | ---
2 | - id: autoversion
3 | name: Update galaxy.yml version
4 | description: This hook updates galaxy.yml to have the assumed correct version
5 | entry: collection_prep_version
6 | language: python
7 | files: "plugins/"
8 | types: [python]
9 | pass_filenames: false
10 | args: ["-p", "."]
11 |
12 | - id: update-docs
13 | name: Update documentation
14 | description: This hook runs the collection_prep_add_docs script
15 | entry: collection_prep_add_docs
16 | language: python
17 | files: "plugins/"
18 | types: [python]
19 | pass_filenames: false
20 | args: ["-p", "."]
21 |
--------------------------------------------------------------------------------
/.config/dictionary.txt:
--------------------------------------------------------------------------------
1 | # Ansible jargon
2 | cliconf
3 | devel
4 | fqcn
5 | hostvars
6 | httpapi
7 | netcommon
8 | netconf
9 | restconf
10 | # Resource modules and filter plugins
11 | acls
12 | cidr
13 | hwaddr
14 | ipaddr
15 | ipmath
16 | ipsubnet
17 | ipwrap
18 | lacp
19 | linkagg
20 | macaddr
21 | nthhost
22 | ospfv
23 | slaac
24 | # Python packages
25 | argcomplete
26 | redbaron
27 | ruamel
28 | textfsm
29 | # Jijna / RST / HTML directives
30 | colspan
31 | darkgreen
32 | dictsort
33 | endfor
34 | htmlify
35 | HORIZONTALLINE
36 | larr
37 | nbsp
38 | sameas
39 | seealso
40 | tojson
41 | # Misc
42 | bthornto
43 | levelname
44 | suboptions
45 |
--------------------------------------------------------------------------------
/cspell.config.yaml:
--------------------------------------------------------------------------------
1 | ---
2 | dictionaryDefinitions:
3 | - name: words
4 | path: .config/dictionary.txt
5 | addWords: true
6 | dictionaries:
7 | - bash
8 | - networking-terms
9 | - python
10 | - words
11 | - "!aws"
12 | - "!backwards-compatibility"
13 | - "!cryptocurrencies"
14 | - "!cpp"
15 | ignorePaths:
16 | # All dot files in the root
17 | - \.*
18 | # This file
19 | - cspell.config.yaml
20 | # Ignore licenses
21 | - licenses/*
22 | # The shared file for tool configuration
23 | - pyproject.toml
24 | # The setup file
25 | - setup.cfg
26 | # requirements.txt is generated
27 | - requirements.txt
28 |
--------------------------------------------------------------------------------
/setup.cfg:
--------------------------------------------------------------------------------
1 | [metadata]
2 | name = collection_prep
3 | summary = Ansible collection preparation tools
4 | description-file =
5 | README.md
6 | author = Ansible Network team
7 | home-page = https://www.ansible.com
8 | classifier =
9 | Intended Audience :: Information Technology
10 | Intended Audience :: System Administrators
11 | License :: OSI Approved :: Apache Software License
12 | Operating System :: POSIX :: Linux
13 | Programming Language :: Python :: 3
14 |
15 | [files]
16 | packages = collection_prep
17 |
18 | [entry_points]
19 | console_scripts =
20 | collection_prep_add_docs = collection_prep.cmd.add_docs:main
21 | collection_prep_update = collection_prep.cmd.update:main
22 | collection_prep_runtime = collection_prep.cmd.runtime:main
23 | collection_prep_version = collection_prep.cmd.version:main
24 |
--------------------------------------------------------------------------------
/pyproject.toml:
--------------------------------------------------------------------------------
1 | [tool.black]
2 | line-length = 100
3 |
4 | [tool.pylint]
5 |
6 | [tool.pylint.format]
7 | max-line-length = 100
8 |
9 | [tool.pylint.master]
10 | no-docstring-rgx = "__.*__"
11 |
12 | [tool.pylint.messages_control]
13 | disable = ["duplicate-code", "fixme"]
14 | enable = [
15 | "useless-suppression", # Identify unneeded pylint disable statements
16 |
17 | ]
18 |
19 | [tool.ruff]
20 | line-length = 100
21 | select = [
22 | "D", # pydocstyle
23 | "E", # pycodestyle
24 | "F", # pyflakes
25 | "I", # isort
26 | "UP", # pyupgrade
27 | "W", # pycodestyle
28 | "YTT", # flake8-2020
29 |
30 | ]
31 | builtins = ["_"]
32 | target-version = "py39"
33 |
34 | [tool.ruff.isort]
35 | force-single-line = true # Force from .. import to be 1 per line, minimizing changes at time of implementation
36 | lines-after-imports = 2 # Ensures consistency for cases when there's variable vs function/class definitions after imports
37 | lines-between-types = 1 # Separate import/from with 1 line, minimizing changes at time of implementation
38 | no-lines-before = [
39 | "local-folder"
40 | ] # Keeps local imports bundled with first-party
41 |
42 | [tool.ruff.pydocstyle]
43 | convention = "google"
44 |
--------------------------------------------------------------------------------
/collection_prep/utils.py:
--------------------------------------------------------------------------------
1 | """Get ready for 1.0.0."""
2 | import datetime
3 |
4 | from redbaron import RedBaron
5 |
6 |
7 | COLLECTION_MIN_ANSIBLE_VERSION = ">=2.9"
8 | DEPRECATION_CYCLE_IN_YEAR = 2
9 | REMOVAL_FREQUENCY_IN_MONTHS = 3
10 | REMOVAL_DAY_OF_MONTH = "01"
11 |
12 |
13 | def get_removed_at_date():
14 | """Generate expected date to remove deprecated content.
15 |
16 | :return: The date deprecated content will be removed after, in YYYY-MM-DD format
17 | """
18 | today = datetime.date.today()
19 | deprecation_year = today.year + DEPRECATION_CYCLE_IN_YEAR
20 | if today.month % REMOVAL_FREQUENCY_IN_MONTHS:
21 | deprecation_month = (today.month + REMOVAL_FREQUENCY_IN_MONTHS) - (
22 | today.month % REMOVAL_FREQUENCY_IN_MONTHS
23 | )
24 | else:
25 | deprecation_month = today.month
26 |
27 | deprecation_date = f"{deprecation_year}-{deprecation_month:02d}-{REMOVAL_DAY_OF_MONTH}"
28 |
29 | return deprecation_date
30 |
31 |
32 | def load_py_as_ast(path):
33 | """Load a file as an ast object.
34 |
35 | :param path: The full path to the file
36 | :return: The ast object
37 | """
38 | with open(path, encoding="utf8") as file:
39 | data = file.read()
40 | red = RedBaron(data)
41 | return red
42 |
43 |
44 | def find_assignment_in_ast(name, ast_file):
45 | """Find an assignment in an ast object.
46 |
47 | :param name: The name of the assignment to find
48 | :param ast_file: The ast object
49 | :return: A list of ast object matching
50 | """
51 | res = ast_file.find("assignment", target=lambda x: x.dumps() == name)
52 | return res
53 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | # ansible dist for migration if local
2 | ansible*
3 |
4 | # editor stuff
5 | .vscode/
6 |
7 | # Byte-compiled / optimized / DLL files
8 | __pycache__/
9 | *.py[cod]
10 | *$py.class
11 |
12 | # C extensions
13 | *.so
14 |
15 | # Distribution / packaging
16 | .Python
17 | build/
18 | develop-eggs/
19 | dist/
20 | downloads/
21 | eggs/
22 | .eggs/
23 | lib/
24 | lib64/
25 | parts/
26 | sdist/
27 | var/
28 | wheels/
29 | *.egg-info/
30 | .installed.cfg
31 | *.egg
32 | MANIFEST
33 |
34 | # PyInstaller
35 | # Usually these files are written by a python script from a template
36 | # before PyInstaller builds the exe, so as to inject date/other infos into it.
37 | *.manifest
38 | *.spec
39 |
40 | # Installer logs
41 | pip-log.txt
42 | pip-delete-this-directory.txt
43 |
44 | # Unit test / coverage reports
45 | htmlcov/
46 | .tox/
47 | .coverage
48 | .coverage.*
49 | .cache
50 | nosetests.xml
51 | coverage.xml
52 | *.cover
53 | .hypothesis/
54 | .pytest_cache/
55 |
56 | # Translations
57 | *.mo
58 | *.pot
59 |
60 | # Django stuff:
61 | *.log
62 | local_settings.py
63 | db.sqlite3
64 |
65 | # Flask stuff:
66 | instance/
67 | .webassets-cache
68 |
69 | # Scrapy stuff:
70 | .scrapy
71 |
72 | # Sphinx documentation
73 | docs/_build/
74 |
75 | # PyBuilder
76 | target/
77 |
78 | # Jupyter Notebook
79 | .ipynb_checkpoints
80 |
81 | # pyenv
82 | .python-version
83 |
84 | # celery beat schedule file
85 | celerybeat-schedule
86 |
87 | # SageMath parsed files
88 | *.sage.py
89 |
90 | # Environments
91 | .env
92 | .venv
93 | env/
94 | venv/
95 | ENV/
96 | env.bak/
97 | venv.bak/
98 |
99 | # Spyder project settings
100 | .spyderproject
101 | .spyproject
102 |
103 | # Rope project settings
104 | .ropeproject
105 |
106 | # mkdocs documentation
107 | /site
108 |
109 | # mypy
110 | .mypy_cache/
111 |
112 | # IntelliJ PyCharm
113 | .idea/
114 |
--------------------------------------------------------------------------------
/.pre-commit-config.yaml:
--------------------------------------------------------------------------------
1 | ---
2 | repos:
3 | - repo: https://github.com/charliermarsh/ruff-pre-commit
4 | rev: "v0.0.261"
5 | hooks:
6 | - id: ruff
7 | args:
8 | - "--fix"
9 | - "--exit-non-zero-on-fix"
10 |
11 | - repo: https://github.com/pre-commit/mirrors-prettier
12 | rev: "v3.0.0-alpha.6"
13 | hooks:
14 | - id: prettier
15 | additional_dependencies:
16 | - prettier
17 | - prettier-plugin-toml
18 |
19 | - repo: https://github.com/psf/black
20 | rev: 23.3.0
21 | hooks:
22 | - id: black
23 |
24 | - repo: https://github.com/streetsidesoftware/cspell-cli
25 | rev: v6.31.0
26 | hooks:
27 | - id: cspell
28 | name: Spell check with cspell
29 |
30 | - repo: https://github.com/Lucas-C/pre-commit-hooks
31 | rev: v1.4.2
32 | hooks:
33 | - id: remove-tabs
34 |
35 | - repo: https://github.com/pre-commit/pre-commit-hooks
36 | rev: v4.4.0
37 | hooks:
38 | - id: check-merge-conflict
39 | - id: check-symlinks
40 | - id: debug-statements
41 | - id: end-of-file-fixer
42 | - id: fix-byte-order-marker
43 | - id: no-commit-to-branch
44 | - id: trailing-whitespace
45 |
46 | - repo: https://github.com/codespell-project/codespell
47 | rev: v2.2.4
48 | hooks:
49 | - id: codespell
50 |
51 | - repo: https://github.com/adrienverge/yamllint
52 | rev: v1.30.0
53 | hooks:
54 | - id: yamllint
55 | args:
56 | - --strict
57 | types: [file, yaml]
58 |
59 | - repo: https://github.com/terrencepreilly/darglint
60 | rev: v1.8.1
61 | hooks:
62 | - id: darglint
63 |
64 | - repo: https://github.com/pycqa/pylint
65 | rev: v2.17.1
66 | hooks:
67 | - id: pylint
68 | additional_dependencies:
69 | - ansible-core
70 | - pyyaml
71 | - redbaron
72 | - ruamel.yaml
73 |
--------------------------------------------------------------------------------
/collection_prep/jinja_utils.py:
--------------------------------------------------------------------------------
1 | """Utilities for jinja2."""
2 | import re
3 |
4 | from html import escape as html_escape
5 |
6 | from ansible.module_utils._text import to_text
7 | from ansible.module_utils.six import string_types
8 | from jinja2.runtime import Undefined
9 |
10 |
11 | NS_MAP = {}
12 |
13 | _ITALIC = re.compile(r"I\(([^)]+)\)")
14 | _BOLD = re.compile(r"B\(([^)]+)\)")
15 | _MODULE = re.compile(r"M\(([^)]+)\)")
16 | _URL = re.compile(r"U\(([^)]+)\)")
17 | _LINK = re.compile(r"L\(([^)]+), *([^)]+)\)")
18 | _CONST = re.compile(r"C\(([^)]+)\)")
19 | _RULER = re.compile(r"HORIZONTALLINE")
20 |
21 |
22 | def to_kludge_ns(key, value):
23 | """Save a value for later use.
24 |
25 | :param key: The key to store under
26 | :param value: The value to store
27 | :return: An empty string to not confuse jinja
28 | """
29 | NS_MAP[key] = value
30 | return ""
31 |
32 |
33 | def from_kludge_ns(key):
34 | """Recall a value stored with to_kludge_ns.
35 |
36 | :param key: The key to look for
37 | :return: The value stored under that key
38 | """
39 | return NS_MAP[key]
40 |
41 |
42 | def html_ify(text):
43 | """Convert symbols like I(this is in italics) to valid HTML.
44 |
45 | :param text: The text to transform
46 | :return: An HTML string of the formatted text
47 | """
48 | if not isinstance(text, string_types):
49 | text = to_text(text)
50 |
51 | text = html_escape(text)
52 | text = _ITALIC.sub(r"\1", text)
53 | text = _BOLD.sub(r"\1", text)
54 | text = _MODULE.sub(r"\1", text)
55 | text = _URL.sub(r"\1", text)
56 | text = _LINK.sub(r"\1", text)
57 | text = _CONST.sub(r"\1", text)
58 | text = _RULER.sub(r"
", text)
59 |
60 | return text.strip()
61 |
62 |
63 | def rst_ify(text):
64 | """Convert symbols like I(this is in italics) to valid restructured text.
65 |
66 | :param text: The text to transform
67 | :return: An RST string of the formatted text
68 | """
69 | text = _ITALIC.sub(r"*\1*", text)
70 | text = _BOLD.sub(r"**\1**", text)
71 | text = _MODULE.sub(r":ref:`\1 <\1_module>`", text)
72 | text = _LINK.sub(r"`\1 <\2>`_", text)
73 | text = _URL.sub(r"\1", text)
74 | text = _CONST.sub(r"``\1``", text)
75 | text = _RULER.sub(r"------------", text)
76 |
77 | return text
78 |
79 |
80 | def documented_type(text):
81 | """Convert any python type to a type for documentation.
82 |
83 | :param text: A python type
84 | :return: The associated documentation form of that type
85 | """
86 | if isinstance(text, Undefined):
87 | return "-"
88 | if text == "str":
89 | return "string"
90 | if text == "bool":
91 | return "boolean"
92 | if text == "int":
93 | return "integer"
94 | if text == "dict":
95 | return "dictionary"
96 | return text
97 |
--------------------------------------------------------------------------------
/collection_prep/cmd/version.py:
--------------------------------------------------------------------------------
1 | """Script to guess the next version of an ansible collection."""
2 | import logging
3 | import sys
4 |
5 | from argparse import ArgumentParser
6 | from pathlib import Path
7 |
8 | import ruamel.yaml
9 |
10 |
11 | yaml = ruamel.yaml.YAML()
12 | # Preserve document layout
13 | yaml.block_seq_indent = 2
14 | yaml.explicit_start = True
15 | yaml.preserve_quotes = True
16 |
17 | try:
18 | import argcomplete
19 | except ImportError:
20 | argcomplete = None
21 |
22 |
23 | logging.basicConfig(format="%(levelname)-10s%(message)s", level=logging.INFO)
24 |
25 |
26 | # What level of version to apply for a given change type
27 | RULES = {
28 | "major": [
29 | "major_changes",
30 | "breaking_changes",
31 | "removed_features",
32 | ],
33 | "minor": [
34 | "minor_changes",
35 | "deprecated_features",
36 | ],
37 | "patch": [
38 | "bugfixes",
39 | "security_fixes",
40 | "trivial",
41 | ],
42 | }
43 |
44 |
45 | def get_last_version(path) -> str:
46 | """Get the last released version of a collection.
47 |
48 | :param path: The collection base path
49 | :return: The last version in changelog.yaml, or "0.0.0"
50 | """
51 | changelog_path = path / "changelogs" / "changelog.yaml"
52 | if not changelog_path.exists():
53 | # Collection has not been released?
54 | return "0.0.0"
55 | changelog = yaml.load(changelog_path)
56 | return max(changelog["releases"].keys())
57 |
58 |
59 | def update_version(path: Path, version: str) -> str:
60 | """Generate the likely next version of a collection.
61 |
62 | :param path: The collection base path
63 | :param version: The current collection version
64 | :return: The expected next version
65 | """
66 | version_parts = [int(v) for v in version.split(".")]
67 | fragment_path = path / "changelogs" / "fragments"
68 |
69 | types = {key: False for key in RULES}
70 | if fragment_path.exists() and fragment_path.is_dir():
71 | for file in fragment_path.iterdir():
72 | fragment = yaml.load(file)
73 | if not fragment:
74 | continue
75 |
76 | for level, headings in RULES.items():
77 | for heading in headings:
78 | if heading in fragment:
79 | types[level] = True
80 |
81 | # Bump version accordingly
82 | if types["major"]:
83 | version_parts = version_parts[0] + 1, 0, 0
84 | elif types["minor"]:
85 | version_parts[1:] = version_parts[1] + 1, 0
86 | elif types["patch"]:
87 | version_parts[2] += 1
88 | new_version = ".".join(str(v) for v in version_parts)
89 |
90 | if new_version != version:
91 | new_version += "-dev"
92 |
93 | return new_version
94 |
95 |
96 | def update_galaxy(path: Path, new_version: str) -> bool:
97 | """Update the version in galaxy.yml if necessary.
98 |
99 | :param path: The collection base path
100 | :param new_version: The version that should be in galaxy.yml
101 | :return: True if the version needed to be updated otherwise False
102 | """
103 | galaxy_path = path / "galaxy.yml"
104 | if galaxy_path.exists():
105 | galaxy = yaml.load(galaxy_path)
106 | else:
107 | logging.error("Unable to find galaxy.yml in %s", path)
108 | sys.exit(2)
109 |
110 | logging.info("Current version in galaxy.yml is %s", galaxy["version"])
111 | if galaxy["version"] != new_version:
112 | logging.info("Updating version string in galaxy.yml")
113 | galaxy["version"] = new_version
114 | yaml.dump(galaxy, galaxy_path)
115 | return True
116 | return False
117 |
118 |
119 | def main() -> None:
120 | """Run the script."""
121 | parser = ArgumentParser()
122 | parser.add_argument(
123 | "-p",
124 | "--path",
125 | help="The path to the collection (ie ./ansible.netcommon",
126 | required=True,
127 | )
128 |
129 | if argcomplete:
130 | argcomplete.autocomplete(parser)
131 |
132 | args = parser.parse_args()
133 | path = Path(args.path).absolute()
134 |
135 | version = get_last_version(path)
136 | logging.info("Detected collection version is %s", version)
137 |
138 | new_version = update_version(path, version)
139 | logging.info("Updated collection version is %s", new_version)
140 |
141 | changed = update_galaxy(path, new_version)
142 | sys.exit(int(changed))
143 |
144 |
145 | if __name__ == "__main__":
146 | main()
147 |
--------------------------------------------------------------------------------
/collection_prep/cmd/runtime.py:
--------------------------------------------------------------------------------
1 | """Get ready for 1.0.0."""
2 | import glob
3 | import logging
4 | import os
5 |
6 | from argparse import ArgumentParser
7 |
8 | import ruamel.yaml
9 |
10 | from collection_prep.utils import find_assignment_in_ast
11 | from collection_prep.utils import get_removed_at_date
12 | from collection_prep.utils import load_py_as_ast
13 |
14 |
15 | logging.basicConfig(format="%(levelname)-10s%(message)s", level=logging.INFO)
16 |
17 | COLLECTION_MIN_ANSIBLE_VERSION = ">=2.14.10"
18 | COLLECTION_MAX_ANSIBLE_VERSION = "<2.19"
19 | DEPRECATION_CYCLE_IN_YEAR = 2
20 | REMOVAL_FREQUENCY_IN_MONTHS = 3
21 | REMOVAL_DAY_OF_MONTH = "01"
22 |
23 |
24 | def get_warning_msg():
25 | """Return warning text for a plugin.
26 |
27 | :return: Additional details on the deprecation
28 | """
29 | return "See the plugin documentation for more details"
30 |
31 |
32 | def process_runtime_plugin_routing(
33 | collection, path
34 | ): # pylint: disable-msg=too-many-locals,too-many-branches
35 | """Process collection plugins to generate a plugin routing map.
36 |
37 | :param collection: The name of the collection
38 | :param path: The collections path
39 | :return: A dictionary representing plugins and redirects and deprecations
40 | """
41 | plugin_routing = {}
42 | plugins_path = f"{path}/{collection}/plugins"
43 | modules_path = f"{plugins_path}/modules"
44 | action_path = f"{plugins_path}/action"
45 |
46 | collection = collection.replace("/", ".")
47 | collection_name = collection.split(".")[-1]
48 | if not collection_name:
49 | logging.error("failed to get collection name from %s", collection)
50 |
51 | for fullpath in sorted(glob.glob(f"{modules_path}/*.py")):
52 | filename = fullpath.split("/")[-1]
53 | if not filename.endswith(".py") or filename.endswith("__init__.py"):
54 | continue
55 |
56 | module_name = filename.split(".")[0]
57 |
58 | logging.info("-------------------Processing runtime.yml for module %s", module_name)
59 |
60 | ast_obj = load_py_as_ast(fullpath)
61 | documentation = find_assignment_in_ast(ast_file=ast_obj, name="DOCUMENTATION")
62 | doc_section = ruamel.yaml.load(documentation.value.to_python(), ruamel.yaml.RoundTripLoader)
63 |
64 | try:
65 | module_prefix = module_name.split("_")[0]
66 | except IndexError:
67 | module_prefix = module_name
68 |
69 | short_name = module_name.split("_", 1)[-1]
70 |
71 | # handle action plugin redirection
72 | # if module name and action name is same skip the redirection as Ansible
73 | # by design will invoke action plugin first.
74 | if not os.path.exists(os.path.join(action_path, f"{module_name}.py")):
75 | if (
76 | os.path.exists(os.path.join(action_path, f"{module_prefix}.py"))
77 | and module_prefix == collection_name
78 | ):
79 | fq_action_name = f"{collection}.{module_prefix}"
80 | if not plugin_routing.get("action"):
81 | plugin_routing["action"] = {}
82 | plugin_routing["action"].update({module_name: {"redirect": fq_action_name}})
83 | plugin_routing["action"].update({short_name: {"redirect": fq_action_name}})
84 |
85 | # handle module short name redirection.
86 | # Add short redirection if module prefix and collection name is same
87 | # for example arista.eos.eos_acls will support redirection for arista.eos.acls
88 | # as the prefix of module name (eos) is same as the collection name
89 | if module_prefix == collection_name:
90 | fq_module_name = f"{collection}.{module_name}"
91 | if not plugin_routing.get("modules"):
92 | plugin_routing["modules"] = {}
93 | plugin_routing["modules"].update({short_name: {"redirect": fq_module_name}})
94 |
95 | # handle module deprecation notice
96 | if "deprecated" in doc_section:
97 | logging.info("Found to be deprecated")
98 | if not plugin_routing.get("modules"):
99 | plugin_routing["modules"] = {}
100 | plugin_routing["modules"].update(
101 | {
102 | module_name: {
103 | "deprecation": {
104 | "removal_date": get_removed_at_date(),
105 | "warning_text": get_warning_msg(),
106 | }
107 | }
108 | }
109 | )
110 | if module_prefix == collection_name:
111 | if not plugin_routing["modules"].get(short_name):
112 | plugin_routing["modules"][short_name] = {}
113 |
114 | plugin_routing["modules"][short_name].update(
115 | {
116 | "deprecation": {
117 | "removal_date": get_removed_at_date(),
118 | "warning_text": get_warning_msg(),
119 | }
120 | }
121 | )
122 |
123 | return plugin_routing
124 |
125 |
126 | def process(collection, path):
127 | """Generate or update runtime.yml on a collection.
128 |
129 | :param collection: The collection name
130 | :param path: The collections path
131 | """
132 | rt_obj = {}
133 | collection_path = os.path.join(path, collection)
134 | if not os.path.exists(collection_path):
135 | logging.error("%s does not exist", collection_path)
136 |
137 | supported_ansible_versions = COLLECTION_MIN_ANSIBLE_VERSION
138 | if COLLECTION_MAX_ANSIBLE_VERSION:
139 | supported_ansible_versions += "," + COLLECTION_MAX_ANSIBLE_VERSION
140 | rt_obj["requires_ansible"] = supported_ansible_versions
141 | plugin_routing = process_runtime_plugin_routing(collection, path)
142 | if plugin_routing:
143 | rt_obj["plugin_routing"] = plugin_routing
144 |
145 | # create meta/runtime.yml file
146 | meta_path = os.path.join(collection_path, "meta")
147 | if not os.path.exists(meta_path):
148 | os.makedirs(meta_path)
149 |
150 | runtime_path = os.path.join(meta_path, "runtime.yml")
151 |
152 | yaml = ruamel.yaml.YAML()
153 | yaml.explicit_start = True
154 |
155 | with open(runtime_path, "w", encoding="utf8") as file_obj:
156 | yaml.dump(rt_obj, file_obj)
157 |
158 |
159 | def main():
160 | """Run the script."""
161 | parser = ArgumentParser()
162 | parser.add_argument("-c", "--collection", help="The name of the collection", required=True)
163 | parser.add_argument("-p", "--path", help="The path to the collection", required=True)
164 | args = parser.parse_args()
165 | process(collection=args.collection, path=args.path)
166 |
167 |
168 | if __name__ == "__main__":
169 | main()
170 |
--------------------------------------------------------------------------------
/collection_prep/cmd/update.py:
--------------------------------------------------------------------------------
1 | """Get ready for 1.0.0."""
2 | import logging
3 | import os
4 | import platform
5 | import re
6 | import subprocess
7 | import sys
8 |
9 | from argparse import ArgumentParser
10 |
11 | import ruamel.yaml
12 |
13 | from collection_prep.utils import find_assignment_in_ast
14 | from collection_prep.utils import get_removed_at_date
15 | from collection_prep.utils import load_py_as_ast
16 |
17 |
18 | logging.basicConfig(format="%(levelname)-10s%(message)s", level=logging.INFO)
19 |
20 | SUBDIRS = (
21 | "modules",
22 | "action",
23 | "become",
24 | "cliconf",
25 | "connection",
26 | "filter",
27 | "httpapi",
28 | "netconf",
29 | "terminal",
30 | "inventory",
31 | )
32 | SPECIALS = {"ospfv2": "OSPFv2", "interfaces": "Interfaces", "static": "Static"}
33 |
34 |
35 | def remove_assignment_in_ast(name, ast_file):
36 | """Remove an assignment in an ast object.
37 |
38 | :param name: The name of the assignment to remove
39 | :param ast_file: The ast object
40 | """
41 | res = ast_file.find("assignment", target=lambda x: x.dumps() == name)
42 | if res:
43 | ast_file.remove(res)
44 |
45 |
46 | def retrieve_plugin_name(plugin_type, body_part):
47 | """Retrieve the module name from a docstring.
48 |
49 | :param plugin_type: The plugin's type
50 | :param body_part: The docstring extracted from the ast body
51 | :return: The module name
52 | """
53 | if not body_part:
54 | logging.warning("Failed to find DOCUMENTATION assignment")
55 | return ""
56 | documentation = ruamel.yaml.load(body_part.value.to_python(), ruamel.yaml.RoundTripLoader)
57 |
58 | if plugin_type == "modules":
59 | plugin_type = "module"
60 | name = documentation[plugin_type]
61 | return name
62 |
63 |
64 | def update_deprecation_notice(documentation):
65 | """Update deprecation notices to use removed_at_date instead of removed_in.
66 |
67 | :param documentation: The DOCUMENTATION section of the module
68 | """
69 | if "deprecated" in documentation:
70 | logging.info("Updating deprecation notice")
71 | documentation["deprecated"].update({"removed_at_date": get_removed_at_date()})
72 | documentation["deprecated"].pop("removed_in", None)
73 |
74 |
75 | def update_documentation(body_part):
76 | """Update the documentation of the module.
77 |
78 | :param body_part: The DOCUMENTATION section of the module
79 | """
80 | if not body_part:
81 | logging.warning("Failed to find DOCUMENTATION assignment")
82 | return
83 | documentation = ruamel.yaml.load(body_part.value.to_python(), ruamel.yaml.RoundTripLoader)
84 |
85 | # update deprecation to removed_at_date
86 | update_deprecation_notice(documentation)
87 |
88 | # remove version added
89 | documentation.pop("version_added", None)
90 | desc_idx = [idx for idx, key in enumerate(documentation.keys()) if key == "description"]
91 | # insert version_added after the description
92 | documentation.insert(desc_idx[0] + 1, key="version_added", value="1.0.0")
93 | repl = ruamel.yaml.dump(documentation, None, ruamel.yaml.RoundTripDumper)
94 |
95 | # remove version added from anywhere else in the docstring if preceded by 1+ spaces
96 | example_lines = repl.splitlines()
97 | regex = re.compile(r"^\s+version_added\:\s.*$")
98 | example_lines = [line for line in example_lines if not re.match(regex, line)]
99 | body_part.value.replace('"""\n' + "\n".join(example_lines) + '\n"""')
100 |
101 |
102 | def update_examples(body_part, module_name, collection):
103 | """Update the example.
104 |
105 | :param body_part: The EXAMPLE section of the module
106 | :param module_name: The name of the module
107 | :param collection: The name of the collection
108 | """
109 | if not body_part:
110 | logging.warning("Failed to find EXAMPLES assignment")
111 | return
112 | full_module_name = f"{collection}.{module_name}"
113 | example = ruamel.yaml.load(body_part.value.to_python(), ruamel.yaml.RoundTripLoader)
114 | # check each task and update to fqcn
115 | for idx, task in enumerate(example):
116 | example[idx] = ruamel.yaml.comments.CommentedMap(
117 | [(full_module_name, v) if k == module_name else (k, v) for k, v in task.items()]
118 | )
119 |
120 | repl = ruamel.yaml.dump(example, None, ruamel.yaml.RoundTripDumper)
121 |
122 | # look in yaml comments for the module name as well and replace
123 | example_lines = repl.splitlines()
124 | for idx, line in enumerate(example_lines):
125 | if (
126 | line.startswith("#")
127 | and module_name in line
128 | and module_name
129 | and full_module_name not in line
130 | ):
131 | example_lines[idx] = line.replace(module_name, full_module_name)
132 | body_part.value.replace('"""\n' + "\n".join(example_lines) + '\n"""')
133 |
134 |
135 | def update_short_description(return_, documentation, module_name):
136 | """Update the short description of the module.
137 |
138 | :param return_: The RETURN section of the module
139 | :param documentation: The DOCUMENTATION section of the module
140 | :param module_name: The module name
141 | """
142 | if not return_:
143 | logging.warning("Failed to find RETURN assignment")
144 | return
145 | ret_section = ruamel.yaml.load(return_.value.to_python(), ruamel.yaml.RoundTripLoader)
146 | if not documentation:
147 | logging.warning("Failed to find DOCUMENTATION assignment")
148 | return
149 | doc_section = ruamel.yaml.load(documentation.value.to_python(), ruamel.yaml.RoundTripLoader)
150 | short_description = doc_section["short_description"]
151 |
152 | rm_rets = ["after", "before", "commands"]
153 | if ret_section:
154 | match = [x for x in rm_rets if x in list(ret_section.keys())]
155 | if len(match) == len(rm_rets):
156 | logging.info("Found a resource module")
157 | parts = module_name.split("_")
158 | # things like 'interfaces'
159 | resource = parts[1].lower()
160 | resource = SPECIALS.get(resource, resource.upper())
161 | if resource.lower()[-1].endswith("s"):
162 | chars = list(resource)
163 | chars[-1] = chars[-1].lower()
164 | resource = "".join(chars)
165 | if len(parts) > 2 and parts[2] != "global":
166 | resource += f" {parts[2]}"
167 | short_description = f"{resource} resource module"
168 | # Check for deprecated modules
169 | if "deprecated" in doc_section and not short_description.startswith("(deprecated,"):
170 | logging.info("Found to be deprecated")
171 | short_description = short_description.replace("(deprecated) ", "")
172 | short_description = (
173 | f"(deprecated, removed after {get_removed_at_date()}) {short_description}"
174 | )
175 | # Change short if necessary
176 | if short_description != doc_section["short_description"]:
177 | logging.info("Setting short description to '%s'", short_description)
178 | doc_section["short_description"] = short_description
179 | repl = ruamel.yaml.dump(doc_section, None, ruamel.yaml.RoundTripDumper)
180 | documentation.value.replace('"""\n' + repl + '\n"""')
181 |
182 |
183 | def black(filename):
184 | """Run black against the file.
185 |
186 | :param filename: The full path to the file
187 | """
188 | logging.info("Running black against %s", filename)
189 | subprocess.check_output(["black", "-q", filename])
190 |
191 |
192 | def process(collection, path):
193 | """Process the files in each subdirectory.
194 |
195 | :param collection: The name of the collection
196 | :param path: The collections path
197 | """
198 | for subdir in SUBDIRS:
199 | dirpath = f"{path}{collection}/plugins/{subdir}"
200 | try:
201 | plugin_files = os.listdir(dirpath)
202 | except FileNotFoundError:
203 | # Looks like we don't have any of that type of plugin here
204 | continue
205 |
206 | for filename in plugin_files:
207 | if filename.endswith(".py"):
208 | filename = f"{dirpath}/{filename}"
209 | logging.info("-------------------Processing %s", filename)
210 | ast_obj = load_py_as_ast(filename)
211 |
212 | # Get the module name from the docstring
213 | module_name = retrieve_plugin_name(
214 | subdir,
215 | find_assignment_in_ast(ast_file=ast_obj, name="DOCUMENTATION"),
216 | )
217 | if not module_name:
218 | logging.warning("Skipped %s: No module name found", filename)
219 | continue
220 |
221 | # Remove the metadata
222 | remove_assignment_in_ast(ast_file=ast_obj, name="ANSIBLE_METADATA")
223 | logging.info("Removed metadata in %s", filename)
224 |
225 | # Update the documentation
226 | update_documentation(
227 | body_part=find_assignment_in_ast(ast_file=ast_obj, name="DOCUMENTATION")
228 | )
229 | logging.info("Updated documentation in %s", filename)
230 |
231 | if subdir == "modules":
232 | # Update the short description
233 | update_short_description(
234 | return_=find_assignment_in_ast(ast_file=ast_obj, name="RETURN"),
235 | documentation=find_assignment_in_ast(
236 | ast_file=ast_obj, name="DOCUMENTATION"
237 | ),
238 | module_name=module_name,
239 | )
240 |
241 | # Update the examples
242 | update_examples(
243 | body_part=find_assignment_in_ast(ast_file=ast_obj, name="EXAMPLES"),
244 | module_name=module_name,
245 | collection=collection,
246 | )
247 | logging.info("Updated examples in %s", filename)
248 |
249 | # Write out the file and black
250 | file_contents = ast_obj.dumps()
251 | with open(filename, "w", encoding="utf8") as file_obj:
252 | file_obj.write(file_contents)
253 | logging.info("Wrote %s", filename)
254 | black(filename)
255 |
256 |
257 | def main():
258 | """Run the script."""
259 | if not platform.python_version().startswith("3.8"):
260 | sys.exit("Python 3.8+ required")
261 | parser = ArgumentParser()
262 | parser.add_argument("-c", "--collection", help="The name of the collection", required=True)
263 | parser.add_argument("-p", "--path", help="The path to the collection", required=True)
264 | args = parser.parse_args()
265 | process(collection=args.collection, path=args.path)
266 |
267 |
268 | if __name__ == "__main__":
269 | main()
270 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Collection Prep Engine
2 |
3 | ## INSTALLATION
4 |
5 | ```console
6 | pip install .
7 | ```
8 |
9 | ## CONTENT UPDATER
10 |
11 | ```console
12 | collection_prep_update -c arista.eos -p ./
13 | ```
14 |
15 | ```console
16 | INFO -------------------Processing ./arista.eos/plugins/modules/eos_lacp.py
17 | INFO Updated metadata in ./arista.eos/plugins/modules/eos_lacp.py
18 | INFO Updated documentation in ./arista.eos/plugins/modules/eos_lacp.py
19 | INFO Found a resource module
20 | INFO Setting short description to 'LACP resource module'
21 | INFO Updated examples in ./arista.eos/plugins/modules/eos_lacp.py
22 | INFO Wrote ./arista.eos/plugins/modules/eos_lacp.py
23 | INFO Running black against ./arista.eos/plugins/modules/eos_lacp.py
24 | INFO -------------------Processing ./arista.eos/plugins/modules/eos_static_routes.py
25 | INFO Updated metadata in ./arista.eos/plugins/modules/eos_static_routes.py
26 | INFO Updated documentation in ./arista.eos/plugins/modules/eos_static_routes.py
27 | INFO Found a resource module
28 | INFO Setting short description to 'Static routes resource module'
29 | INFO Updated examples in ./arista.eos/plugins/modules/eos_static_routes.py
30 | INFO Wrote ./arista.eos/plugins/modules/eos_static_routes.py
31 | INFO Running black against ./arista.eos/plugins/modules/eos_static_routes.py
32 | INFO -------------------Processing ./arista.eos/plugins/action/__init__.py
33 | WARNING Failed to find DOCUMENTATION assignment
34 | WARNING Skipped ./arista.eos/plugins/action/__init__.py: No module name found
35 | ```
36 |
37 | ## DOC GENERATOR
38 |
39 | This is intended to operate against the repository clone.
40 |
41 | This will generate an RST file for each plugin in the collection docs folder and add a table of links for all plugin types in the README.md
42 |
43 | This will also pull the requires_ansible information from the runtime.yml file and add an ansible compatibility section to the README.
44 |
45 | For the ansible compatibility, ensure the collection README.md has the following in it:
46 |
47 | ```
48 |
49 |
50 | ```
51 |
52 | For the plugin table, ensure the collection README.md has the following in it:
53 |
54 | ```
55 |
56 |
57 |
58 | ```
59 |
60 | ```console
61 | collection_prep_add_docs -p ./ansible.netcommon
62 | ```
63 |
64 | ```console
65 | INFO Setting collection name to ansible.netcommon
66 | INFO Setting github repository url to https://github.com/ansible-collections/ansible.netcommon
67 | INFO Linking collection to user collection directory
68 | INFO This is required for the Ansible fragment loader to find doc fragments
69 | INFO Attempting to remove existing /home/bthornto/.ansible/collections/ansible_collections/ansible/netcommon
70 | INFO Deleting: /home/bthornto/.ansible/collections/ansible_collections/ansible/netcommon
71 | INFO Creating namespace directory /home/bthornto/.ansible/collections/ansible_collections/ansible
72 | INFO Linking collection /home/bthornto/github/collection_update/ansible.netcommon -> /home/bthornto/.ansible/collections/ansible_collections/ansible/netcommon
73 | INFO Purging content from directory /home/bthornto/github/collection_update/ansible.netcommon/docs
74 | INFO Making docs directory /home/bthornto/github/collection_update/ansible.netcommon/docs
75 | INFO Process content in /home/bthornto/github/collection_update/ansible.netcommon/plugins/become
76 | INFO Processing /home/bthornto/github/collection_update/ansible.netcommon/plugins/become/enable.py
77 | INFO Process content in /home/bthornto/github/collection_update/ansible.netcommon/plugins/connection
78 | INFO Processing /home/bthornto/github/collection_update/ansible.netcommon/plugins/connection/httpapi.py
79 | INFO Processing /home/bthornto/github/collection_update/ansible.netcommon/plugins/connection/network_cli.py
80 | INFO Processing /home/bthornto/github/collection_update/ansible.netcommon/plugins/connection/netconf.py
81 | INFO Processing /home/bthornto/github/collection_update/ansible.netcommon/plugins/connection/napalm.py
82 | INFO Processing /home/bthornto/github/collection_update/ansible.netcommon/plugins/connection/persistent.py
83 | INFO Process content in /home/bthornto/github/collection_update/ansible.netcommon/plugins/filter
84 | INFO Processing /home/bthornto/github/collection_update/ansible.netcommon/plugins/filter/ipaddr.py
85 | INFO Adding filter plugins cidr_merge,ipaddr,ipmath,ipwrap,ip4_hex,ipv4,ipv6,ipsubnet,next_nth_usable,network_in_network,network_in_usable,reduce_on_network,nthhost,previous_nth_usable,slaac,hwaddr,macaddr
86 | INFO Processing /home/bthornto/github/collection_update/ansible.netcommon/plugins/filter/network.py
87 | INFO Adding filter plugins parse_cli,parse_cli_textfsm,parse_xml,type5_pw,hash_salt,comp_type5,vlan_parser
88 | INFO Process content in /home/bthornto/github/collection_update/ansible.netcommon/plugins/modules
89 | INFO Processing /home/bthornto/github/collection_update/ansible.netcommon/plugins/modules/net_l3_interface.py
90 | INFO Processing /home/bthornto/github/collection_update/ansible.netcommon/plugins/modules/restconf_get.py
91 | INFO Processing /home/bthornto/github/collection_update/ansible.netcommon/plugins/modules/net_l2_interface.py
92 | INFO Processing /home/bthornto/github/collection_update/ansible.netcommon/plugins/modules/net_static_route.py
93 | INFO Processing /home/bthornto/github/collection_update/ansible.netcommon/plugins/modules/net_linkagg.py
94 | INFO Processing /home/bthornto/github/collection_update/ansible.netcommon/plugins/modules/net_logging.py
95 | INFO Processing /home/bthornto/github/collection_update/ansible.netcommon/plugins/modules/telnet.py
96 | INFO Processing /home/bthornto/github/collection_update/ansible.netcommon/plugins/modules/net_system.py
97 | INFO Processing /home/bthornto/github/collection_update/ansible.netcommon/plugins/modules/cli_config.py
98 | INFO Processing /home/bthornto/github/collection_update/ansible.netcommon/plugins/modules/net_ping.py
99 | INFO Processing /home/bthornto/github/collection_update/ansible.netcommon/plugins/modules/net_banner.py
100 | INFO Processing /home/bthornto/github/collection_update/ansible.netcommon/plugins/modules/net_lldp.py
101 | INFO Processing /home/bthornto/github/collection_update/ansible.netcommon/plugins/modules/net_interface.py
102 | INFO Processing /home/bthornto/github/collection_update/ansible.netcommon/plugins/modules/restconf_config.py
103 | INFO Processing /home/bthornto/github/collection_update/ansible.netcommon/plugins/modules/netconf_config.py
104 | INFO Processing /home/bthornto/github/collection_update/ansible.netcommon/plugins/modules/net_vrf.py
105 | INFO Processing /home/bthornto/github/collection_update/ansible.netcommon/plugins/modules/net_lldp_interface.py
106 | INFO Processing /home/bthornto/github/collection_update/ansible.netcommon/plugins/modules/netconf_get.py
107 | INFO Processing /home/bthornto/github/collection_update/ansible.netcommon/plugins/modules/netconf_rpc.py
108 | INFO Processing /home/bthornto/github/collection_update/ansible.netcommon/plugins/modules/net_get.py
109 | INFO Processing /home/bthornto/github/collection_update/ansible.netcommon/plugins/modules/net_vlan.py
110 | INFO Processing /home/bthornto/github/collection_update/ansible.netcommon/plugins/modules/net_put.py
111 | INFO Processing /home/bthornto/github/collection_update/ansible.netcommon/plugins/modules/cli_command.py
112 | INFO Processing /home/bthornto/github/collection_update/ansible.netcommon/plugins/modules/net_user.py
113 | INFO Processing 'become' for README
114 | INFO Processing 'connection' for README
115 | INFO Processing 'filter' for README
116 | INFO Processing 'modules' for README
117 | INFO README.md updated
118 | (venv) ➜ collection_update git:(master) ✗
119 | ```
120 |
121 | ## meta/runtime.yml GENERATOR
122 |
123 | This is intended to operate against the repository clone.
124 |
125 | ```console
126 | collection_prep_runtime -c arista.eos -p ./
127 | ```
128 |
129 | ```console
130 | INFO -------------------Processing runtime.yml for module eos_acl_interfaces
131 | INFO -------------------Processing runtime.yml for module eos_acls
132 | INFO -------------------Processing runtime.yml for module eos_banner
133 | INFO -------------------Processing runtime.yml for module eos_bgp
134 | INFO -------------------Processing runtime.yml for module eos_command
135 | INFO -------------------Processing runtime.yml for module eos_config
136 | INFO -------------------Processing runtime.yml for module eos_eapi
137 | INFO -------------------Processing runtime.yml for module eos_facts
138 | INFO -------------------Processing runtime.yml for module eos_interface
139 | INFO Found to be deprecated
140 | INFO -------------------Processing runtime.yml for module eos_interfaces
141 | INFO -------------------Processing runtime.yml for module eos_l2_interface
142 | INFO Found to be deprecated
143 | INFO -------------------Processing runtime.yml for module eos_l2_interfaces
144 | INFO -------------------Processing runtime.yml for module eos_l3_interface
145 | INFO Found to be deprecated
146 | INFO -------------------Processing runtime.yml for module eos_l3_interfaces
147 | INFO -------------------Processing runtime.yml for module eos_lacp
148 | INFO -------------------Processing runtime.yml for module eos_lacp_interfaces
149 | INFO -------------------Processing runtime.yml for module eos_lag_interfaces
150 | INFO -------------------Processing runtime.yml for module eos_linkagg
151 | INFO Found to be deprecated
152 | INFO -------------------Processing runtime.yml for module eos_lldp
153 | INFO -------------------Processing runtime.yml for module eos_lldp_global
154 | INFO -------------------Processing runtime.yml for module eos_lldp_interfaces
155 | INFO -------------------Processing runtime.yml for module eos_logging
156 | INFO -------------------Processing runtime.yml for module eos_static_route
157 | INFO Found to be deprecated
158 | INFO -------------------Processing runtime.yml for module eos_static_routes
159 | INFO -------------------Processing runtime.yml for module eos_system
160 | INFO -------------------Processing runtime.yml for module eos_user
161 | INFO -------------------Processing runtime.yml for module eos_vlan
162 | INFO Found to be deprecated
163 | INFO -------------------Processing runtime.yml for module eos_vlans
164 | INFO -------------------Processing runtime.yml for module eos_vrf
165 | INFO -------------------Processing runtime.yml for module eos_acl_interfaces
166 | INFO -------------------Processing runtime.yml for module eos_acls
167 | INFO -------------------Processing runtime.yml for module eos_banner
168 | INFO -------------------Processing runtime.yml for module eos_bgp
169 | INFO -------------------Processing runtime.yml for module eos_command
170 | INFO -------------------Processing runtime.yml for module eos_config
171 | INFO -------------------Processing runtime.yml for module eos_eapi
172 | INFO -------------------Processing runtime.yml for module eos_facts
173 | INFO -------------------Processing runtime.yml for module eos_interface
174 | INFO Found to be deprecated
175 | INFO -------------------Processing runtime.yml for module eos_interfaces
176 | INFO -------------------Processing runtime.yml for module eos_l2_interface
177 | INFO Found to be deprecated
178 | INFO -------------------Processing runtime.yml for module eos_l2_interfaces
179 | INFO -------------------Processing runtime.yml for module eos_l3_interface
180 | INFO Found to be deprecated
181 | INFO -------------------Processing runtime.yml for module eos_l3_interfaces
182 | INFO -------------------Processing runtime.yml for module eos_lacp
183 | INFO -------------------Processing runtime.yml for module eos_lacp_interfaces
184 | INFO -------------------Processing runtime.yml for module eos_lag_interfaces
185 | INFO -------------------Processing runtime.yml for module eos_linkagg
186 | INFO Found to be deprecated
187 | INFO -------------------Processing runtime.yml for module eos_lldp
188 | INFO -------------------Processing runtime.yml for module eos_lldp_global
189 | INFO -------------------Processing runtime.yml for module eos_lldp_interfaces
190 | INFO -------------------Processing runtime.yml for module eos_logging
191 | INFO -------------------Processing runtime.yml for module eos_static_route
192 | INFO Found to be deprecated
193 | INFO -------------------Processing runtime.yml for module eos_static_routes
194 | INFO -------------------Processing runtime.yml for module eos_system
195 | INFO -------------------Processing runtime.yml for module eos_user
196 | INFO -------------------Processing runtime.yml for module eos_vlan
197 | INFO Found to be deprecated
198 | INFO -------------------Processing runtime.yml for module eos_vlans
199 | INFO -------------------Processing runtime.yml for module eos_vrf
200 | ```
201 |
--------------------------------------------------------------------------------
/collection_prep/cmd/plugin.rst.j2:
--------------------------------------------------------------------------------
1 | .. _@{ module }@_@{ plugin_type }@:
2 | {% for alias in aliases %}
3 | .. _@{ alias }@_@{ plugin_type }@:
4 | {% endfor %}
5 |
6 |
7 | @{ '*' * module|length }@
8 | @{ module }@
9 | @{ '*' * module|length }@
10 |
11 | {% if short_description %}
12 | **@{ short_description | rst_ify}@**
13 | {% endif %}
14 |
15 |
16 | {% if version_added is defined and version_added != '' -%}
17 | Version added: @{ version_added | default('') }@
18 | {% endif %}
19 |
20 | .. contents::
21 | :local:
22 | :depth: 1
23 |
24 | {# ------------------------------------------
25 | #
26 | # Please note: this looks like a core dump
27 | # but it isn't one.
28 | #
29 | --------------------------------------------#}
30 | {% if deprecated is defined -%}
31 |
32 |
33 | DEPRECATED
34 | ----------
35 | {# use unknown here? skip the fields? #}
36 | :Removed in collection release after @{ deprecated['removed_at_date'] | default('') | string | rst_ify }@
37 | :Why: @{ deprecated['why'] | default('') | rst_ify }@
38 | :Alternative: @{ deprecated['alternative'] | default('') | rst_ify }@
39 |
40 |
41 | {% endif %}
42 |
43 | Synopsis
44 | --------
45 | {% if description -%}
46 |
47 | {% for desc in description %}
48 | - @{ desc | rst_ify }@
49 | {% endfor %}
50 |
51 | {% endif %}
52 |
53 | {% if aliases is defined -%}
54 | Aliases: @{ ','.join(aliases) }@
55 | {% endif %}
56 |
57 | {% if requirements -%}
58 |
59 | Requirements
60 | ------------
61 | {% if plugin_type == 'module' %}
62 | The below requirements are needed on the host that executes this @{ plugin_type }@.
63 | {% else %}
64 | The below requirements are needed on the local Ansible controller node that executes this @{ plugin_type }@.
65 | {% endif %}
66 |
67 | {% for req in requirements %}
68 | - @{ req | rst_ify }@
69 | {% endfor %}
70 |
71 | {% endif %}
72 |
73 | {% if options -%}
74 |
75 | Parameters
76 | ----------
77 |
78 | .. raw:: html
79 |
80 |
81 | {# Pre-compute the nesting depth to allocate columns -#}
82 | @{ to_kludge_ns('max_depth', 1) -}@
83 | {% for key, value in options|dictsort recursive -%}
84 | @{ to_kludge_ns('max_depth', [loop.depth, from_kludge_ns('max_depth')] | max) -}@
85 | {% if value.suboptions -%}
86 | {% if value.suboptions.items -%}
87 | @{ loop(value.suboptions.items()) -}@
88 | {% elif value.suboptions[0].items -%}
89 | @{ loop(value.suboptions[0].items()) -}@
90 | {% endif -%}
91 | {% endif -%}
92 | {% endfor -%}
93 | {# Header of the documentation #}
94 |
95 | | Parameter |
96 | Choices/Defaults |
97 | {% if plugin_type != 'module' %}
98 | Configuration |
99 | {% endif %}
100 | Comments |
101 |
102 | {% for key, value in options|dictsort recursive %}
103 |
104 | {# indentation based on nesting level #}
105 | {% for i in range(1, loop.depth) %}
106 | |
107 | {% endfor %}
108 | {# parameter name with required and/or introduced label #}
109 |
110 |
111 | @{ key }@
112 |
113 |
114 | @{ value.type | documented_type }@
115 | {% if value.get('elements') %}
116 | / elements=@{ value.elements | documented_type }@
117 | {% endif %}
118 | {% if value.get('required', False) %}
119 | / required
120 | {% endif %}
121 |
122 | {% if value.version_added %}
123 | added in @{value.version_added}@
124 | {% endif %}
125 | |
126 | {# default / choices #}
127 |
128 | {# Turn boolean values in 'yes' and 'no' values #}
129 | {% if value.default is sameas true %}
130 | {% set _x = value.update({'default': 'yes'}) %}
131 | {% elif value.default is sameas false %}
132 | {% set _x = value.update({'default': 'no'}) %}
133 | {% endif %}
134 | {% if value.type == 'bool' %}
135 | {% set _x = value.update({'choices': ['no', 'yes']}) %}
136 | {% endif %}
137 | {# Show possible choices and highlight details #}
138 | {% if value.choices %}
139 | Choices:
140 | {% for choice in value.choices %}
141 | {# Turn boolean values in 'yes' and 'no' values #}
142 | {% if choice is sameas true %}
143 | {% set choice = 'yes' %}
144 | {% elif choice is sameas false %}
145 | {% set choice = 'no' %}
146 | {% endif %}
147 | {% if (value.default is not list and value.default == choice) or (value.default is list and choice in value.default) %}
148 | @{ choice | escape }@ ←
149 | {% else %}
150 | - @{ choice | escape }@
151 | {% endif %}
152 | {% endfor %}
153 |
154 | {% endif %}
155 | {# Show default value, when multiple choice or no choices #}
156 | {% if value['default'] is defined and value['default'] not in value.get('choices', []) %}
157 | Default:
@{ value.default | tojson | escape }@
158 | {% endif %}
159 | |
160 | {# configuration #}
161 | {% if plugin_type != 'module' %}
162 |
163 | {% if 'ini' in value %}
164 | ini entries:
165 | {% for ini in value.ini %}
166 | [@{ ini.section }@] @{ ini.key }@ = @{ value.default | default('VALUE') }@
167 | {% endfor %}
168 |
169 | {% endif %}
170 | {% if 'env' in value %}
171 | {% for env in value.env %}
172 | env:@{ env.name }@
173 | {% endfor %}
174 | {% endif %}
175 | {% if 'vars' in value %}
176 | {% for var in value.vars %}
177 | var: @{ var.name }@
178 | {% endfor %}
179 | {% endif %}
180 | |
181 | {% endif %}
182 | {# description #}
183 |
184 | {% for desc in value.description %}
185 | @{ desc | replace('\n', '\n ') | html_ify }@
186 | {% endfor %}
187 | {% if 'aliases' in value and value.aliases %}
188 | aliases: @{ value.aliases|join(', ') }@
189 | {% endif %}
190 | |
191 |
192 | {% if value.suboptions %}
193 | {% if value.suboptions.items %}
194 | @{ loop(value.suboptions|dictsort) }@
195 | {% elif value.suboptions[0].items %}
196 | @{ loop(value.suboptions[0]|dictsort) }@
197 | {% endif %}
198 | {% endif %}
199 | {% endfor %}
200 |
201 |
202 |
203 | {% endif %}
204 |
205 | {% if notes -%}
206 | Notes
207 | -----
208 |
209 | .. note::
210 | {% for note in notes %}
211 | - @{ note | rst_ify }@
212 | {% endfor %}
213 |
214 | {% endif %}
215 |
216 | {% if seealso -%}
217 | See Also
218 | --------
219 |
220 | .. seealso::
221 |
222 | {% for item in seealso %}
223 | {% if item.module is defined and item.description is defined %}
224 | :ref:`@{ item.module }@_module`
225 | @{ item.description | rst_ify }@
226 | {% elif item.module is defined %}
227 | :ref:`@{ item.module }@_module`
228 | The official documentation on the **@{ item.module }@** module.
229 | {% elif item.name is defined and item.link is defined and item.description is defined %}
230 | `@{ item.name }@ <@{ item.link }@>`_
231 | @{ item.description | rst_ify }@
232 | {% elif item.ref is defined and item.description is defined %}
233 | :ref:`@{ item.ref }@`
234 | @{ item.description | rst_ify }@
235 | {% endif %}
236 | {% endfor %}
237 |
238 | {% endif %}
239 |
240 | {% if examples or plain_examples -%}
241 |
242 | Examples
243 | --------
244 |
245 | .. code-block:: yaml
246 |
247 | {% for example in examples %}
248 | {% if example['description'] %}@{ example['description'] | indent(4, True) }@{% endif %}
249 | @{ example['code'] | escape | indent(4, True) }@
250 | {% endfor %}
251 | {% if plain_examples %}@{ plain_examples | indent(4, True) }@{% endif %}
252 |
253 | {% endif %}
254 |
255 | {% if not return_facts and return_docs and return_docs.ansible_facts is defined %}
256 | {% set return_facts = return_docs.ansible_facts.contains %}
257 | {% set _x = return_docs.pop('ansible_facts', None) %}
258 | {% endif %}
259 |
260 | {% if return_facts -%}
261 |
262 | Returned Facts
263 | --------------
264 | Facts returned by this module are added/updated in the ``hostvars`` host facts and can be referenced by name just like any other host fact. They do not need to be registered in order to use them.
265 |
266 | .. raw:: html
267 |
268 |
269 | {# Pre-compute the nesting depth to allocate columns #}
270 | @{ to_kludge_ns('max_depth', 1) -}@
271 | {% for key, value in return_facts|dictsort recursive %}
272 | @{ to_kludge_ns('max_depth', [loop.depth, from_kludge_ns('max_depth')] | max) -}@
273 | {% if value.contains -%}
274 | {% if value.contains.items -%}
275 | @{ loop(value.contains.items()) -}@
276 | {% elif value.contains[0].items -%}
277 | @{ loop(value.contains[0].items()) -}@
278 | {% endif -%}
279 | {% endif -%}
280 | {% endfor -%}
281 |
282 | | Fact |
283 | Returned |
284 | Description |
285 |
286 | {% for key, value in return_facts|dictsort recursive %}
287 |
288 | {% for i in range(1, loop.depth) %}
289 | |
290 | {% endfor %}
291 |
292 |
293 | @{ key }@
294 |
295 |
296 | @{ value.type | documented_type }@
297 | {% if value.elements %}
298 | / elements=@{ value.elements | documented_type }@
299 | {% endif %}
300 |
301 | {% if value.version_added %}
302 | added in @{value.version_added}@
303 | {% endif %}
304 | |
305 | @{ value.returned | html_ify }@ |
306 |
307 | {% if value.description is string %}
308 | @{ value.description | html_ify }@
309 |
310 | {% else %}
311 | {% for desc in value.description %}
312 | @{ desc | html_ify }@
313 |
314 | {% endfor %}
315 | {% endif %}
316 |
317 | {% if value.sample is defined and value.sample %}
318 | Sample:
319 | {# TODO: The sample should be escaped, using | escape or | htmlify, but both mess things up beyond repair with dicts #}
320 | @{ value.sample | replace('\n', '\n ') | html_ify }@
321 | {% endif %}
322 | |
323 |
324 | {# ---------------------------------------------------------
325 | # sadly we cannot blindly iterate through the child dicts,
326 | # since in some documentations,
327 | # lists are used instead of dicts. This handles both types
328 | # ---------------------------------------------------------#}
329 | {% if value.contains %}
330 | {% if value.contains.items %}
331 | @{ loop(value.contains|dictsort) }@
332 | {% elif value.contains[0].items %}
333 | @{ loop(value.contains[0]|dictsort) }@
334 | {% endif %}
335 | {% endif %}
336 | {% endfor %}
337 |
338 |
339 |
340 | {% endif %}
341 |
342 | {% if return_docs -%}
343 |
344 | Return Values
345 | -------------
346 | Common return values are documented `here `_, the following are the fields unique to this @{ plugin_type }@:
347 |
348 | .. raw:: html
349 |
350 |
351 | @{ to_kludge_ns('max_depth', 1) -}@
352 | {% for key, value in return_docs|dictsort recursive -%}
353 | @{ to_kludge_ns('max_depth', [loop.depth, from_kludge_ns('max_depth')] | max) -}@
354 | {% if value.contains -%}
355 | {% if value.contains.items -%}
356 | @{ loop(value.contains.items()) -}@
357 | {% elif value.contains[0].items -%}
358 | @{ loop(value.contains[0].items()) -}@
359 | {% endif -%}
360 | {% endif -%}
361 | {% endfor -%}
362 |
363 | | Key |
364 | Returned |
365 | Description |
366 |
367 | {% for key, value in return_docs|dictsort recursive %}
368 |
369 | {% for i in range(1, loop.depth) %}
370 | | |
371 | {% endfor %}
372 |
373 |
374 | @{ key }@
375 |
376 |
377 | @{ value.type | documented_type }@
378 | {% if value.elements %}
379 | / elements=@{ value.elements | documented_type }@
380 | {% endif %}
381 |
382 | {% if value.version_added %}
383 | added in @{value.version_added}@
384 | {% endif %}
385 | |
386 | @{ value.returned | html_ify }@ |
387 |
388 | {% if value.description is string %}
389 | @{ value.description | html_ify |indent(4) | trim}@
390 | {% else %}
391 | {% for desc in value.description %}
392 | @{ desc | html_ify |indent(4) | trim}@
393 | {% endfor %}
394 | {% endif %}
395 |
396 | {% if value.sample is defined and value.sample %}
397 | Sample:
398 | {# TODO: The sample should be escaped, using |escape or |htmlify, but both mess things up beyond repair with dicts #}
399 | @{ value.sample | replace('\n', '\n ') | html_ify }@
400 | {% endif %}
401 | |
402 |
403 | {# ---------------------------------------------------------
404 | # sadly we cannot blindly iterate through the child dicts,
405 | # since in some documentations,
406 | # lists are used instead of dicts. This handles both types
407 | # ---------------------------------------------------------#}
408 | {% if value.contains %}
409 | {% if value.contains.items %}
410 | @{ loop(value.contains|dictsort) }@
411 | {% elif value.contains[0].items %}
412 | @{ loop(value.contains[0]|dictsort) }@
413 | {% endif %}
414 | {% endif %}
415 | {% endfor %}
416 |
417 |
418 |
419 | {% endif %}
420 |
421 | Status
422 | ------
423 |
424 | {% if deprecated %}
425 |
426 | {% if 'removed_in' in deprecated %}
427 | - This @{ plugin_type }@ will be removed in version @{ deprecated['removed_in'] | string | rst_ify }@. *[deprecated]*
428 | {% elif 'removed_at_date' in deprecated %}
429 | - This @{ plugin_type }@ will be removed in a release after @{ deprecated['removed_at_date'] | string | rst_ify }@. *[deprecated]*
430 | {% endif %}
431 | - For more information see `DEPRECATED`_.
432 |
433 | {% endif %}
434 |
435 | {% if author is defined -%}
436 | Authors
437 | ~~~~~~~
438 |
439 | {% for author_name in author %}
440 | - @{ author_name }@
441 | {% endfor %}
442 | {% endif %}
443 | {% if plugin_type != 'module' %}
444 |
445 |
446 | .. hint::
447 | Configuration entries for each entry type have a low to high priority order. For example, a variable that is lower in the list will override a variable that is higher up.
448 | {% endif %}
449 |
--------------------------------------------------------------------------------
/collection_prep/cmd/add_docs.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # PYTHON_ARGCOMPLETE_OK
3 |
4 | """Generate or update collection documentation."""
5 | import ast
6 | import logging
7 | import os
8 | import re
9 | import shutil
10 | import sys
11 | import tempfile
12 |
13 | from argparse import ArgumentParser
14 | from functools import partial
15 | from pathlib import Path
16 | from typing import Optional
17 |
18 | import yaml
19 |
20 | from ansible.module_utils._text import to_text
21 | from ansible.module_utils.common.collections import is_sequence
22 | from ansible.module_utils.six import string_types
23 | from ansible.plugins.loader import fragment_loader
24 | from ansible.utils import plugin_docs
25 | from ansible.utils.collection_loader._collection_finder import _AnsibleCollectionFinder
26 | from jinja2 import Environment
27 | from jinja2 import FileSystemLoader
28 |
29 | from collection_prep.jinja_utils import documented_type
30 | from collection_prep.jinja_utils import from_kludge_ns
31 | from collection_prep.jinja_utils import html_ify
32 | from collection_prep.jinja_utils import rst_ify
33 | from collection_prep.jinja_utils import to_kludge_ns
34 |
35 |
36 | try:
37 | import argcomplete
38 | except ImportError:
39 | argcomplete = None
40 |
41 |
42 | logging.basicConfig(format="%(levelname)-10s%(message)s", level=logging.INFO)
43 |
44 |
45 | IGNORE_FILES = ["__init__.py"]
46 | SUBDIRS = (
47 | "become",
48 | "cliconf",
49 | "connection",
50 | "filter",
51 | "httpapi",
52 | "inventory",
53 | "lookup",
54 | "netconf",
55 | "modules",
56 | "test",
57 | "validate",
58 | )
59 | TEMPLATE_DIR = os.path.dirname(__file__)
60 | ANSIBLE_COMPAT = """## Ansible version compatibility
61 |
62 | This collection has been tested against the following Ansible versions: **{requires_ansible}**.
63 |
64 | Plugins and modules within a collection may be tested with only specific Ansible versions.
65 | A collection may contain metadata that identifies these versions.
66 | PEP440 is the schema used to describe the versions of Ansible.
67 | """
68 |
69 |
70 | def ensure_list(value):
71 | """Ensure the value is a list.
72 |
73 | :param value: The value to check
74 | :type value: Unknown
75 | :return: The value as a list
76 | """
77 | if isinstance(value, list):
78 | return value
79 | return [value]
80 |
81 |
82 | def convert_descriptions(data):
83 | """Convert the descriptions for doc into lists.
84 |
85 | :param data: the chunk from the doc
86 | :type data: dict
87 | """
88 | if data:
89 | for definition in data.values():
90 | if "description" in definition:
91 | definition["description"] = ensure_list(definition["description"])
92 | if "suboptions" in definition:
93 | convert_descriptions(definition["suboptions"])
94 | if "contains" in definition:
95 | convert_descriptions(definition["contains"])
96 |
97 |
98 | def jinja_environment():
99 | """Define the jinja environment.
100 |
101 | :return: A jinja template, with the env set
102 | """
103 | env = Environment(
104 | loader=FileSystemLoader(TEMPLATE_DIR),
105 | variable_start_string="@{",
106 | variable_end_string="}@",
107 | lstrip_blocks=True,
108 | trim_blocks=True,
109 | )
110 | env.filters["rst_ify"] = rst_ify
111 | env.filters["documented_type"] = documented_type
112 | env.tests["list"] = partial(is_sequence, include_strings=False)
113 | env.filters["html_ify"] = html_ify
114 | env.globals["to_kludge_ns"] = to_kludge_ns
115 | env.globals["from_kludge_ns"] = from_kludge_ns
116 | template = env.get_template("plugin.rst.j2")
117 | return template
118 |
119 |
120 | def update_readme(content, path, gh_url, branch_name): # pylint: disable-msg=too-many-locals
121 | """Update the README.md in the repository.
122 |
123 | :param content: The dict containing the content
124 | :type content: dict
125 | :param path: The path to the collection
126 | :type path: str
127 | :param gh_url: The url to the GitHub repository
128 | :type gh_url: str
129 | :param branch_name: The name of the main repository branch
130 | :type branch_name: str
131 | """
132 | data = []
133 | gh_url = re.sub(r"\.git$", "", gh_url)
134 | for plugin_type, plugins in content.items():
135 | logging.info("Processing '%s' for README", plugin_type)
136 | if not plugins:
137 | continue
138 | if plugin_type == "modules":
139 | data.append("### Modules")
140 | else:
141 | data.append(f"### {plugin_type.capitalize()} plugins")
142 | if "_description" in plugins:
143 | data.append(plugins.pop("_description"))
144 | data.append("")
145 | data.append("Name | Description")
146 | data.append("--- | ---")
147 | for plugin, info in sorted(plugins.items()):
148 | if info["has_rst"]:
149 | link = (
150 | f"[{plugin}]({gh_url}/blob/{branch_name}/docs/{plugin}_"
151 | f"{plugin_type.replace('modules', 'module')}.rst)"
152 | )
153 | else:
154 | link = plugin
155 | description = info["comment"].replace("|", "\\|").strip()
156 | data.append(f"{link}|{description}")
157 | data.append("")
158 | readme = os.path.join(path, "README.md")
159 | try:
160 | with open(readme, encoding="utf8") as readme_file:
161 | content = readme_file.read().splitlines()
162 | except FileNotFoundError:
163 | logging.error("README.md not found in %s", path)
164 | logging.error("README.md not updated")
165 | sys.exit(1)
166 | try:
167 | start = content.index("")
168 | end = content.index("")
169 | except ValueError:
170 | logging.error("Content anchors not found in %s", readme)
171 | logging.error("README.md not updated")
172 | sys.exit(1)
173 | if start and end:
174 | new = content[0 : start + 1] + data + content[end:]
175 | with open(readme, "w", encoding="utf8") as readme_file:
176 | readme_file.write("\n".join(new))
177 | # Avoid "No newline at end of file.
178 | # No, I don't know why it has to be two of them.
179 | # Yes, it actually does have to be two of them.
180 | readme_file.write("\n\n")
181 | logging.info("README.md updated")
182 |
183 |
184 | def handle_simple(collection, fullpath, kind): # pylint: disable-msg=too-many-locals
185 | """Process "simple" plugins like filter or test.
186 |
187 | :param collection: The full collection name
188 | :type collection: str
189 | :param fullpath: The full path to the filter plugin file
190 | :type fullpath: str
191 | :param kind: The kind of plugin, filter or test
192 | :type kind: str
193 | :return: A dict of plugins + descriptions
194 | """
195 | if kind == "filter":
196 | class_name = "FilterModule"
197 | map_name = "filter_map"
198 | func_name = "filters"
199 | elif kind == "test":
200 | class_name = "TestModule"
201 | map_name = "test_map"
202 | func_name = "tests"
203 | else:
204 | logging.error("Only filter and test are supported simple types")
205 | sys.exit(1)
206 |
207 | plugins = {}
208 | with open(fullpath, encoding="utf8") as file_obj:
209 | file_contents = file_obj.read()
210 | module = ast.parse(file_contents)
211 | function_definitions = {
212 | node.name: ast.get_docstring(node)
213 | for node in module.body
214 | if isinstance(node, ast.FunctionDef)
215 | }
216 | class_def = [
217 | node for node in module.body if isinstance(node, ast.ClassDef) and node.name == class_name
218 | ]
219 | if not class_def:
220 | return plugins
221 |
222 | docstring = ast.get_docstring(class_def[0], clean=True)
223 | if docstring:
224 | plugins["_description"] = docstring.strip()
225 |
226 | simple_map = next(
227 | (
228 | node
229 | for node in class_def[0].body
230 | if isinstance(node, ast.Assign)
231 | and hasattr(node, "targets")
232 | and node.targets[0].id == map_name
233 | ),
234 | None,
235 | )
236 |
237 | if not simple_map:
238 | simple_func = [
239 | func
240 | for func in class_def[0].body
241 | if isinstance(func, ast.FunctionDef) and func.name == func_name
242 | ]
243 | if not simple_func:
244 | return plugins
245 |
246 | # The filter map is either looked up using the filter_map = {}
247 | # assignment or if return returns a dict literal.
248 | simple_map = next(
249 | (
250 | node
251 | for node in simple_func[0].body
252 | if isinstance(node, ast.Return) and isinstance(node.value, ast.Dict)
253 | ),
254 | None,
255 | )
256 |
257 | if not simple_map:
258 | return plugins
259 |
260 | keys = [k.s for k in simple_map.value.keys]
261 | logging.info("Adding %s plugins %s", kind, ",".join(keys))
262 | values = [k.id for k in simple_map.value.values]
263 | simple_map = dict(zip(keys, values))
264 | for name, func in simple_map.items():
265 | if func in function_definitions:
266 | comment = function_definitions[func] or f"{collection} {name} {kind} plugin"
267 |
268 | # Get the first line from the docstring for the description and
269 | # make that the short description.
270 | comment = next(c for c in comment.splitlines() if c and not c.startswith(":"))
271 | plugins[f"{collection}.{name}"] = {"has_rst": False, "comment": comment}
272 | return plugins
273 |
274 |
275 | def process(collection: str, path: Path): # pylint: disable-msg=too-many-locals,too-many-branches
276 | """Process the files in each subdirectory.
277 |
278 | :param collection: The collection name
279 | :type collection: str
280 | :param path: The path to the collection
281 | :type path: Path
282 | :return: A mapping of plugins to plugin types
283 | """
284 | template = jinja_environment()
285 | docs_path = Path(path, "docs")
286 | if docs_path.is_dir():
287 | logging.info("Purging existing rst files from directory %s", docs_path)
288 | for entry in docs_path.glob("*.rst"):
289 | entry.unlink()
290 | logging.info("Making docs directory %s", docs_path)
291 | Path(docs_path).mkdir(parents=True, exist_ok=True)
292 |
293 | content = {}
294 |
295 | for subdir in SUBDIRS: # pylint: disable-msg=too-many-nested-blocks
296 | if subdir == "modules":
297 | plugin_type = "module"
298 | else:
299 | plugin_type = subdir
300 |
301 | dirpath = Path(path, "plugins", subdir)
302 | if dirpath.is_dir():
303 | content[subdir] = {}
304 | logging.info("Process content in %s", dirpath)
305 | for filename in os.listdir(dirpath):
306 | if filename.endswith(".py") and filename not in IGNORE_FILES:
307 | fullpath = Path(dirpath, filename)
308 | logging.info("Processing %s", fullpath)
309 | (
310 | doc,
311 | examples,
312 | return_docs,
313 | metadata,
314 | ) = plugin_docs.get_docstring(to_text(fullpath), fragment_loader)
315 | if doc is None and subdir in ["filter", "test"]:
316 | name_only = filename.rsplit(".")[0]
317 | combined_ptype = f"{name_only} {subdir}"
318 | content[combined_ptype] = handle_simple(collection, fullpath, subdir)
319 | else:
320 | if doc:
321 | doc["plugin_type"] = plugin_type
322 |
323 | if return_docs:
324 | # Seems a recent change in devel makes this
325 | # return a dict not a yaml string.
326 | if isinstance(return_docs, dict):
327 | doc["return_docs"] = return_docs
328 | else:
329 | doc["return_docs"] = yaml.safe_load(return_docs)
330 | convert_descriptions(doc["return_docs"])
331 |
332 | doc["metadata"] = (metadata,)
333 | if isinstance(examples, string_types):
334 | doc["plain_examples"] = examples.strip()
335 | else:
336 | doc["examples"] = examples
337 |
338 | doc["module"] = f"{collection}." "{plugin_name}".format(
339 | plugin_name=doc.get(plugin_type, doc.get("name"))
340 | )
341 | doc["author"] = ensure_list(doc["author"])
342 | doc["description"] = ensure_list(doc["description"])
343 | try:
344 | convert_descriptions(doc["options"])
345 | except KeyError:
346 | pass # This module takes no options
347 |
348 | module_rst_path = Path(
349 | path,
350 | "docs",
351 | doc["module"] + f"_{plugin_type}" + ".rst",
352 | )
353 |
354 | with open(module_rst_path, "w", encoding="utf8") as doc_file:
355 | doc_file.write(template.render(doc))
356 | content[subdir][doc["module"]] = {
357 | "has_rst": True,
358 | "comment": doc["short_description"],
359 | }
360 | return content
361 |
362 |
363 | def load_galaxy(path):
364 | """Load collection details from the galaxy.yml file in the collection.
365 |
366 | :param path: The path the collection
367 | :return: The collection name and gh url
368 | """
369 | try:
370 | with open(Path(path, "galaxy.yml"), encoding="utf8") as stream:
371 | try:
372 | return yaml.safe_load(stream)
373 | except yaml.YAMLError:
374 | logging.error("Unable to parse galaxy.yml in %s", path)
375 | sys.exit(1)
376 | except FileNotFoundError:
377 | logging.error("Unable to find galaxy.yml in %s", path)
378 | sys.exit(1)
379 |
380 |
381 | def load_runtime(path):
382 | """Load runtime details from the runtime.yml file in the collection.
383 |
384 | :param path: The path the collection
385 | :return: The runtime dict
386 | """
387 | try:
388 | with open(Path(path, "meta/runtime.yml"), encoding="utf8") as stream:
389 | try:
390 | return yaml.safe_load(stream)
391 | except yaml.YAMLError:
392 | logging.error("Unable to parse runtime.yml in %s", path)
393 | sys.exit(1)
394 | except FileNotFoundError:
395 | logging.error("Unable to find runtime.yml in %s", path)
396 | sys.exit(1)
397 |
398 |
399 | def link_collection(path: Path, galaxy: dict, collection_root: Optional[Path] = None):
400 | """Link the provided collection into the Ansible default collection path.
401 |
402 | :param path: A path
403 | :type path: Path
404 | :param galaxy: The galaxy.yml contents
405 | :type galaxy: dict
406 | :param collection_root: The root collections path
407 | """
408 | if collection_root is None:
409 | collection_root = Path(Path.home(), ".ansible/collections/ansible_collections")
410 |
411 | namespace_directory = Path(collection_root, galaxy["namespace"])
412 | collection_directory = Path(namespace_directory, galaxy["name"])
413 |
414 | logging.info("Linking collection to collection path %s", collection_root)
415 | logging.info("This is required for the Ansible fragment loader to find doc fragments")
416 |
417 | if collection_directory.exists():
418 | logging.info("Attempting to remove existing %s", collection_directory)
419 |
420 | if collection_directory.is_symlink():
421 | logging.info("Unlinking: %s", collection_directory)
422 | collection_directory.unlink()
423 | else:
424 | logging.info("Deleting: %s", collection_directory)
425 | shutil.rmtree(collection_directory)
426 |
427 | logging.info("Creating namespace directory %s", namespace_directory)
428 | namespace_directory.mkdir(parents=True, exist_ok=True)
429 |
430 | logging.info("Linking collection %s -> %s", path, collection_directory)
431 | collection_directory.symlink_to(path)
432 |
433 |
434 | def add_collection(path: Path, galaxy: dict) -> Optional[tempfile.TemporaryDirectory]:
435 | """Add path to collections dir so we can find local doc_fragments.
436 |
437 | :param path: The collections path
438 | :param galaxy: The contents of galaxy.yml
439 | :return: A temporary alternate directory if the collection is not in a valid location
440 | """
441 | collections_path = None
442 | tempdir = None
443 |
444 | try:
445 | collections_path = path.parents[1]
446 | except IndexError:
447 | pass
448 |
449 | # Check that parent dir is named ansible_collections
450 | if collections_path and collections_path.name != "ansible_collections":
451 | logging.info("%s doesn't look enough like a collection", collections_path)
452 | collections_path = None
453 |
454 | if collections_path is None:
455 | tempdir = tempfile.TemporaryDirectory() # pylint: disable-msg=consider-using-with
456 | logging.info("Temporary collection path %s created", tempdir.name)
457 | collections_path = Path(tempdir.name) / "ansible_collections"
458 | link_collection(path, galaxy, collection_root=collections_path)
459 |
460 | full_path = collections_path / galaxy["namespace"] / galaxy["name"]
461 | logging.info("Collection path is %s", full_path)
462 |
463 | # Tell ansible about the path
464 | _AnsibleCollectionFinder( # pylint: disable-msg=protected-access
465 | paths=[collections_path, "~/.ansible/collections"]
466 | )._install()
467 |
468 | # This object has to outlive this method or it will be cleaned up before
469 | # we can use it
470 | return tempdir
471 |
472 |
473 | def add_ansible_compatibility(runtime, path):
474 | """Add ansible compatibility information to README.
475 |
476 | :param runtime: runtime.yml contents
477 | :type runtime: dict
478 | :param path: A path
479 | :type path: str
480 | """
481 | requires_ansible = runtime.get("requires_ansible")
482 | if not requires_ansible:
483 | logging.error("Unable to find requires_ansible in runtime.yml, not added to README")
484 | return
485 | readme = os.path.join(path, "README.md")
486 | try:
487 | with open(readme, encoding="utf8") as readme_file:
488 | content = readme_file.read().splitlines()
489 | except FileNotFoundError:
490 | logging.error("README.md not found in %s", path)
491 | logging.error("README.md not updated")
492 | sys.exit(1)
493 | try:
494 | start = content.index("")
495 | end = content.index("")
496 | except ValueError:
497 | logging.error("requires_ansible anchors not found in %s", readme)
498 | logging.error("README.md not updated with ansible compatibility information")
499 | sys.exit(1)
500 | if start and end:
501 | data = ANSIBLE_COMPAT.format(requires_ansible=requires_ansible).splitlines()
502 | new = content[0 : start + 1] + data + content[end:]
503 | with open(readme, "w", encoding="utf8") as readme_file:
504 | readme_file.write("\n".join(new))
505 | logging.info("README.md updated with ansible compatibility information")
506 |
507 |
508 | def main():
509 | """Run the script."""
510 | parser = ArgumentParser()
511 | parser.add_argument(
512 | "-p",
513 | "--path",
514 | help="The path to the collection (ie ./ansible.netcommon",
515 | required=True,
516 | )
517 | parser.add_argument(
518 | "-b",
519 | "--branch-name",
520 | dest="branch_name",
521 | default="main",
522 | help="The name of the main branch of the collection",
523 | )
524 | parser.add_argument(
525 | "--link-collection",
526 | dest="link_collection",
527 | action="store_true",
528 | help="Link the collection in ~/.ansible/collections",
529 | )
530 |
531 | if argcomplete:
532 | argcomplete.autocomplete(parser)
533 |
534 | args = parser.parse_args()
535 | path = Path(args.path).absolute()
536 | galaxy = load_galaxy(path=path)
537 | collection = f"{galaxy['namespace']}.{galaxy['name']}"
538 | logging.info("Setting collection name to %s", collection)
539 | gh_url = galaxy["repository"]
540 | logging.info("Setting GitHub repository url to %s", gh_url)
541 |
542 | tempdir = None
543 | if args.link_collection:
544 | link_collection(path, galaxy)
545 | else:
546 | tempdir = add_collection(path, galaxy)
547 | content = process(collection=collection, path=path)
548 | if tempdir is not None:
549 | tempdir.cleanup()
550 |
551 | update_readme(
552 | content=content,
553 | path=args.path,
554 | gh_url=gh_url,
555 | branch_name=args.branch_name,
556 | )
557 | runtime = load_runtime(path=path)
558 | add_ansible_compatibility(runtime=runtime, path=args.path)
559 |
560 |
561 | if __name__ == "__main__":
562 | main()
563 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 3, 29 June 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU General Public License is a free, copyleft license for
11 | software and other kinds of works.
12 |
13 | The licenses for most software and other practical works are designed
14 | to take away your freedom to share and change the works. By contrast,
15 | the GNU General Public License is intended to guarantee your freedom to
16 | share and change all versions of a program--to make sure it remains free
17 | software for all its users. We, the Free Software Foundation, use the
18 | GNU General Public License for most of our software; it applies also to
19 | any other work released this way by its authors. You can apply it to
20 | your programs, too.
21 |
22 | When we speak of free software, we are referring to freedom, not
23 | price. Our General Public Licenses are designed to make sure that you
24 | have the freedom to distribute copies of free software (and charge for
25 | them if you wish), that you receive source code or can get it if you
26 | want it, that you can change the software or use pieces of it in new
27 | free programs, and that you know you can do these things.
28 |
29 | To protect your rights, we need to prevent others from denying you
30 | these rights or asking you to surrender the rights. Therefore, you have
31 | certain responsibilities if you distribute copies of the software, or if
32 | you modify it: responsibilities to respect the freedom of others.
33 |
34 | For example, if you distribute copies of such a program, whether
35 | gratis or for a fee, you must pass on to the recipients the same
36 | freedoms that you received. You must make sure that they, too, receive
37 | or can get the source code. And you must show them these terms so they
38 | know their rights.
39 |
40 | Developers that use the GNU GPL protect your rights with two steps:
41 | (1) assert copyright on the software, and (2) offer you this License
42 | giving you legal permission to copy, distribute and/or modify it.
43 |
44 | For the developers' and authors' protection, the GPL clearly explains
45 | that there is no warranty for this free software. For both users' and
46 | authors' sake, the GPL requires that modified versions be marked as
47 | changed, so that their problems will not be attributed erroneously to
48 | authors of previous versions.
49 |
50 | Some devices are designed to deny users access to install or run
51 | modified versions of the software inside them, although the manufacturer
52 | can do so. This is fundamentally incompatible with the aim of
53 | protecting users' freedom to change the software. The systematic
54 | pattern of such abuse occurs in the area of products for individuals to
55 | use, which is precisely where it is most unacceptable. Therefore, we
56 | have designed this version of the GPL to prohibit the practice for those
57 | products. If such problems arise substantially in other domains, we
58 | stand ready to extend this provision to those domains in future versions
59 | of the GPL, as needed to protect the freedom of users.
60 |
61 | Finally, every program is threatened constantly by software patents.
62 | States should not allow patents to restrict development and use of
63 | software on general-purpose computers, but in those that do, we wish to
64 | avoid the special danger that patents applied to a free program could
65 | make it effectively proprietary. To prevent this, the GPL assures that
66 | patents cannot be used to render the program non-free.
67 |
68 | The precise terms and conditions for copying, distribution and
69 | modification follow.
70 |
71 | TERMS AND CONDITIONS
72 |
73 | 0. Definitions.
74 |
75 | "This License" refers to version 3 of the GNU General Public License.
76 |
77 | "Copyright" also means copyright-like laws that apply to other kinds of
78 | works, such as semiconductor masks.
79 |
80 | "The Program" refers to any copyrightable work licensed under this
81 | License. Each licensee is addressed as "you". "Licensees" and
82 | "recipients" may be individuals or organizations.
83 |
84 | To "modify" a work means to copy from or adapt all or part of the work
85 | in a fashion requiring copyright permission, other than the making of an
86 | exact copy. The resulting work is called a "modified version" of the
87 | earlier work or a work "based on" the earlier work.
88 |
89 | A "covered work" means either the unmodified Program or a work based
90 | on the Program.
91 |
92 | To "propagate" a work means to do anything with it that, without
93 | permission, would make you directly or secondarily liable for
94 | infringement under applicable copyright law, except executing it on a
95 | computer or modifying a private copy. Propagation includes copying,
96 | distribution (with or without modification), making available to the
97 | public, and in some countries other activities as well.
98 |
99 | To "convey" a work means any kind of propagation that enables other
100 | parties to make or receive copies. Mere interaction with a user through
101 | a computer network, with no transfer of a copy, is not conveying.
102 |
103 | An interactive user interface displays "Appropriate Legal Notices"
104 | to the extent that it includes a convenient and prominently visible
105 | feature that (1) displays an appropriate copyright notice, and (2)
106 | tells the user that there is no warranty for the work (except to the
107 | extent that warranties are provided), that licensees may convey the
108 | work under this License, and how to view a copy of this License. If
109 | the interface presents a list of user commands or options, such as a
110 | menu, a prominent item in the list meets this criterion.
111 |
112 | 1. Source Code.
113 |
114 | The "source code" for a work means the preferred form of the work
115 | for making modifications to it. "Object code" means any non-source
116 | form of a work.
117 |
118 | A "Standard Interface" means an interface that either is an official
119 | standard defined by a recognized standards body, or, in the case of
120 | interfaces specified for a particular programming language, one that
121 | is widely used among developers working in that language.
122 |
123 | The "System Libraries" of an executable work include anything, other
124 | than the work as a whole, that (a) is included in the normal form of
125 | packaging a Major Component, but which is not part of that Major
126 | Component, and (b) serves only to enable use of the work with that
127 | Major Component, or to implement a Standard Interface for which an
128 | implementation is available to the public in source code form. A
129 | "Major Component", in this context, means a major essential component
130 | (kernel, window system, and so on) of the specific operating system
131 | (if any) on which the executable work runs, or a compiler used to
132 | produce the work, or an object code interpreter used to run it.
133 |
134 | The "Corresponding Source" for a work in object code form means all
135 | the source code needed to generate, install, and (for an executable
136 | work) run the object code and to modify the work, including scripts to
137 | control those activities. However, it does not include the work's
138 | System Libraries, or general-purpose tools or generally available free
139 | programs which are used unmodified in performing those activities but
140 | which are not part of the work. For example, Corresponding Source
141 | includes interface definition files associated with source files for
142 | the work, and the source code for shared libraries and dynamically
143 | linked subprograms that the work is specifically designed to require,
144 | such as by intimate data communication or control flow between those
145 | subprograms and other parts of the work.
146 |
147 | The Corresponding Source need not include anything that users
148 | can regenerate automatically from other parts of the Corresponding
149 | Source.
150 |
151 | The Corresponding Source for a work in source code form is that
152 | same work.
153 |
154 | 2. Basic Permissions.
155 |
156 | All rights granted under this License are granted for the term of
157 | copyright on the Program, and are irrevocable provided the stated
158 | conditions are met. This License explicitly affirms your unlimited
159 | permission to run the unmodified Program. The output from running a
160 | covered work is covered by this License only if the output, given its
161 | content, constitutes a covered work. This License acknowledges your
162 | rights of fair use or other equivalent, as provided by copyright law.
163 |
164 | You may make, run and propagate covered works that you do not
165 | convey, without conditions so long as your license otherwise remains
166 | in force. You may convey covered works to others for the sole purpose
167 | of having them make modifications exclusively for you, or provide you
168 | with facilities for running those works, provided that you comply with
169 | the terms of this License in conveying all material for which you do
170 | not control copyright. Those thus making or running the covered works
171 | for you must do so exclusively on your behalf, under your direction
172 | and control, on terms that prohibit them from making any copies of
173 | your copyrighted material outside their relationship with you.
174 |
175 | Conveying under any other circumstances is permitted solely under
176 | the conditions stated below. Sublicensing is not allowed; section 10
177 | makes it unnecessary.
178 |
179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180 |
181 | No covered work shall be deemed part of an effective technological
182 | measure under any applicable law fulfilling obligations under article
183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184 | similar laws prohibiting or restricting circumvention of such
185 | measures.
186 |
187 | When you convey a covered work, you waive any legal power to forbid
188 | circumvention of technological measures to the extent such circumvention
189 | is effected by exercising rights under this License with respect to
190 | the covered work, and you disclaim any intention to limit operation or
191 | modification of the work as a means of enforcing, against the work's
192 | users, your or third parties' legal rights to forbid circumvention of
193 | technological measures.
194 |
195 | 4. Conveying Verbatim Copies.
196 |
197 | You may convey verbatim copies of the Program's source code as you
198 | receive it, in any medium, provided that you conspicuously and
199 | appropriately publish on each copy an appropriate copyright notice;
200 | keep intact all notices stating that this License and any
201 | non-permissive terms added in accord with section 7 apply to the code;
202 | keep intact all notices of the absence of any warranty; and give all
203 | recipients a copy of this License along with the Program.
204 |
205 | You may charge any price or no price for each copy that you convey,
206 | and you may offer support or warranty protection for a fee.
207 |
208 | 5. Conveying Modified Source Versions.
209 |
210 | You may convey a work based on the Program, or the modifications to
211 | produce it from the Program, in the form of source code under the
212 | terms of section 4, provided that you also meet all of these conditions:
213 |
214 | a) The work must carry prominent notices stating that you modified
215 | it, and giving a relevant date.
216 |
217 | b) The work must carry prominent notices stating that it is
218 | released under this License and any conditions added under section
219 | 7. This requirement modifies the requirement in section 4 to
220 | "keep intact all notices".
221 |
222 | c) You must license the entire work, as a whole, under this
223 | License to anyone who comes into possession of a copy. This
224 | License will therefore apply, along with any applicable section 7
225 | additional terms, to the whole of the work, and all its parts,
226 | regardless of how they are packaged. This License gives no
227 | permission to license the work in any other way, but it does not
228 | invalidate such permission if you have separately received it.
229 |
230 | d) If the work has interactive user interfaces, each must display
231 | Appropriate Legal Notices; however, if the Program has interactive
232 | interfaces that do not display Appropriate Legal Notices, your
233 | work need not make them do so.
234 |
235 | A compilation of a covered work with other separate and independent
236 | works, which are not by their nature extensions of the covered work,
237 | and which are not combined with it such as to form a larger program,
238 | in or on a volume of a storage or distribution medium, is called an
239 | "aggregate" if the compilation and its resulting copyright are not
240 | used to limit the access or legal rights of the compilation's users
241 | beyond what the individual works permit. Inclusion of a covered work
242 | in an aggregate does not cause this License to apply to the other
243 | parts of the aggregate.
244 |
245 | 6. Conveying Non-Source Forms.
246 |
247 | You may convey a covered work in object code form under the terms
248 | of sections 4 and 5, provided that you also convey the
249 | machine-readable Corresponding Source under the terms of this License,
250 | in one of these ways:
251 |
252 | a) Convey the object code in, or embodied in, a physical product
253 | (including a physical distribution medium), accompanied by the
254 | Corresponding Source fixed on a durable physical medium
255 | customarily used for software interchange.
256 |
257 | b) Convey the object code in, or embodied in, a physical product
258 | (including a physical distribution medium), accompanied by a
259 | written offer, valid for at least three years and valid for as
260 | long as you offer spare parts or customer support for that product
261 | model, to give anyone who possesses the object code either (1) a
262 | copy of the Corresponding Source for all the software in the
263 | product that is covered by this License, on a durable physical
264 | medium customarily used for software interchange, for a price no
265 | more than your reasonable cost of physically performing this
266 | conveying of source, or (2) access to copy the
267 | Corresponding Source from a network server at no charge.
268 |
269 | c) Convey individual copies of the object code with a copy of the
270 | written offer to provide the Corresponding Source. This
271 | alternative is allowed only occasionally and noncommercially, and
272 | only if you received the object code with such an offer, in accord
273 | with subsection 6b.
274 |
275 | d) Convey the object code by offering access from a designated
276 | place (gratis or for a charge), and offer equivalent access to the
277 | Corresponding Source in the same way through the same place at no
278 | further charge. You need not require recipients to copy the
279 | Corresponding Source along with the object code. If the place to
280 | copy the object code is a network server, the Corresponding Source
281 | may be on a different server (operated by you or a third party)
282 | that supports equivalent copying facilities, provided you maintain
283 | clear directions next to the object code saying where to find the
284 | Corresponding Source. Regardless of what server hosts the
285 | Corresponding Source, you remain obligated to ensure that it is
286 | available for as long as needed to satisfy these requirements.
287 |
288 | e) Convey the object code using peer-to-peer transmission, provided
289 | you inform other peers where the object code and Corresponding
290 | Source of the work are being offered to the general public at no
291 | charge under subsection 6d.
292 |
293 | A separable portion of the object code, whose source code is excluded
294 | from the Corresponding Source as a System Library, need not be
295 | included in conveying the object code work.
296 |
297 | A "User Product" is either (1) a "consumer product", which means any
298 | tangible personal property which is normally used for personal, family,
299 | or household purposes, or (2) anything designed or sold for incorporation
300 | into a dwelling. In determining whether a product is a consumer product,
301 | doubtful cases shall be resolved in favor of coverage. For a particular
302 | product received by a particular user, "normally used" refers to a
303 | typical or common use of that class of product, regardless of the status
304 | of the particular user or of the way in which the particular user
305 | actually uses, or expects or is expected to use, the product. A product
306 | is a consumer product regardless of whether the product has substantial
307 | commercial, industrial or non-consumer uses, unless such uses represent
308 | the only significant mode of use of the product.
309 |
310 | "Installation Information" for a User Product means any methods,
311 | procedures, authorization keys, or other information required to install
312 | and execute modified versions of a covered work in that User Product from
313 | a modified version of its Corresponding Source. The information must
314 | suffice to ensure that the continued functioning of the modified object
315 | code is in no case prevented or interfered with solely because
316 | modification has been made.
317 |
318 | If you convey an object code work under this section in, or with, or
319 | specifically for use in, a User Product, and the conveying occurs as
320 | part of a transaction in which the right of possession and use of the
321 | User Product is transferred to the recipient in perpetuity or for a
322 | fixed term (regardless of how the transaction is characterized), the
323 | Corresponding Source conveyed under this section must be accompanied
324 | by the Installation Information. But this requirement does not apply
325 | if neither you nor any third party retains the ability to install
326 | modified object code on the User Product (for example, the work has
327 | been installed in ROM).
328 |
329 | The requirement to provide Installation Information does not include a
330 | requirement to continue to provide support service, warranty, or updates
331 | for a work that has been modified or installed by the recipient, or for
332 | the User Product in which it has been modified or installed. Access to a
333 | network may be denied when the modification itself materially and
334 | adversely affects the operation of the network or violates the rules and
335 | protocols for communication across the network.
336 |
337 | Corresponding Source conveyed, and Installation Information provided,
338 | in accord with this section must be in a format that is publicly
339 | documented (and with an implementation available to the public in
340 | source code form), and must require no special password or key for
341 | unpacking, reading or copying.
342 |
343 | 7. Additional Terms.
344 |
345 | "Additional permissions" are terms that supplement the terms of this
346 | License by making exceptions from one or more of its conditions.
347 | Additional permissions that are applicable to the entire Program shall
348 | be treated as though they were included in this License, to the extent
349 | that they are valid under applicable law. If additional permissions
350 | apply only to part of the Program, that part may be used separately
351 | under those permissions, but the entire Program remains governed by
352 | this License without regard to the additional permissions.
353 |
354 | When you convey a copy of a covered work, you may at your option
355 | remove any additional permissions from that copy, or from any part of
356 | it. (Additional permissions may be written to require their own
357 | removal in certain cases when you modify the work.) You may place
358 | additional permissions on material, added by you to a covered work,
359 | for which you have or can give appropriate copyright permission.
360 |
361 | Notwithstanding any other provision of this License, for material you
362 | add to a covered work, you may (if authorized by the copyright holders of
363 | that material) supplement the terms of this License with terms:
364 |
365 | a) Disclaiming warranty or limiting liability differently from the
366 | terms of sections 15 and 16 of this License; or
367 |
368 | b) Requiring preservation of specified reasonable legal notices or
369 | author attributions in that material or in the Appropriate Legal
370 | Notices displayed by works containing it; or
371 |
372 | c) Prohibiting misrepresentation of the origin of that material, or
373 | requiring that modified versions of such material be marked in
374 | reasonable ways as different from the original version; or
375 |
376 | d) Limiting the use for publicity purposes of names of licensors or
377 | authors of the material; or
378 |
379 | e) Declining to grant rights under trademark law for use of some
380 | trade names, trademarks, or service marks; or
381 |
382 | f) Requiring indemnification of licensors and authors of that
383 | material by anyone who conveys the material (or modified versions of
384 | it) with contractual assumptions of liability to the recipient, for
385 | any liability that these contractual assumptions directly impose on
386 | those licensors and authors.
387 |
388 | All other non-permissive additional terms are considered "further
389 | restrictions" within the meaning of section 10. If the Program as you
390 | received it, or any part of it, contains a notice stating that it is
391 | governed by this License along with a term that is a further
392 | restriction, you may remove that term. If a license document contains
393 | a further restriction but permits relicensing or conveying under this
394 | License, you may add to a covered work material governed by the terms
395 | of that license document, provided that the further restriction does
396 | not survive such relicensing or conveying.
397 |
398 | If you add terms to a covered work in accord with this section, you
399 | must place, in the relevant source files, a statement of the
400 | additional terms that apply to those files, or a notice indicating
401 | where to find the applicable terms.
402 |
403 | Additional terms, permissive or non-permissive, may be stated in the
404 | form of a separately written license, or stated as exceptions;
405 | the above requirements apply either way.
406 |
407 | 8. Termination.
408 |
409 | You may not propagate or modify a covered work except as expressly
410 | provided under this License. Any attempt otherwise to propagate or
411 | modify it is void, and will automatically terminate your rights under
412 | this License (including any patent licenses granted under the third
413 | paragraph of section 11).
414 |
415 | However, if you cease all violation of this License, then your
416 | license from a particular copyright holder is reinstated (a)
417 | provisionally, unless and until the copyright holder explicitly and
418 | finally terminates your license, and (b) permanently, if the copyright
419 | holder fails to notify you of the violation by some reasonable means
420 | prior to 60 days after the cessation.
421 |
422 | Moreover, your license from a particular copyright holder is
423 | reinstated permanently if the copyright holder notifies you of the
424 | violation by some reasonable means, this is the first time you have
425 | received notice of violation of this License (for any work) from that
426 | copyright holder, and you cure the violation prior to 30 days after
427 | your receipt of the notice.
428 |
429 | Termination of your rights under this section does not terminate the
430 | licenses of parties who have received copies or rights from you under
431 | this License. If your rights have been terminated and not permanently
432 | reinstated, you do not qualify to receive new licenses for the same
433 | material under section 10.
434 |
435 | 9. Acceptance Not Required for Having Copies.
436 |
437 | You are not required to accept this License in order to receive or
438 | run a copy of the Program. Ancillary propagation of a covered work
439 | occurring solely as a consequence of using peer-to-peer transmission
440 | to receive a copy likewise does not require acceptance. However,
441 | nothing other than this License grants you permission to propagate or
442 | modify any covered work. These actions infringe copyright if you do
443 | not accept this License. Therefore, by modifying or propagating a
444 | covered work, you indicate your acceptance of this License to do so.
445 |
446 | 10. Automatic Licensing of Downstream Recipients.
447 |
448 | Each time you convey a covered work, the recipient automatically
449 | receives a license from the original licensors, to run, modify and
450 | propagate that work, subject to this License. You are not responsible
451 | for enforcing compliance by third parties with this License.
452 |
453 | An "entity transaction" is a transaction transferring control of an
454 | organization, or substantially all assets of one, or subdividing an
455 | organization, or merging organizations. If propagation of a covered
456 | work results from an entity transaction, each party to that
457 | transaction who receives a copy of the work also receives whatever
458 | licenses to the work the party's predecessor in interest had or could
459 | give under the previous paragraph, plus a right to possession of the
460 | Corresponding Source of the work from the predecessor in interest, if
461 | the predecessor has it or can get it with reasonable efforts.
462 |
463 | You may not impose any further restrictions on the exercise of the
464 | rights granted or affirmed under this License. For example, you may
465 | not impose a license fee, royalty, or other charge for exercise of
466 | rights granted under this License, and you may not initiate litigation
467 | (including a cross-claim or counterclaim in a lawsuit) alleging that
468 | any patent claim is infringed by making, using, selling, offering for
469 | sale, or importing the Program or any portion of it.
470 |
471 | 11. Patents.
472 |
473 | A "contributor" is a copyright holder who authorizes use under this
474 | License of the Program or a work on which the Program is based. The
475 | work thus licensed is called the contributor's "contributor version".
476 |
477 | A contributor's "essential patent claims" are all patent claims
478 | owned or controlled by the contributor, whether already acquired or
479 | hereafter acquired, that would be infringed by some manner, permitted
480 | by this License, of making, using, or selling its contributor version,
481 | but do not include claims that would be infringed only as a
482 | consequence of further modification of the contributor version. For
483 | purposes of this definition, "control" includes the right to grant
484 | patent sublicenses in a manner consistent with the requirements of
485 | this License.
486 |
487 | Each contributor grants you a non-exclusive, worldwide, royalty-free
488 | patent license under the contributor's essential patent claims, to
489 | make, use, sell, offer for sale, import and otherwise run, modify and
490 | propagate the contents of its contributor version.
491 |
492 | In the following three paragraphs, a "patent license" is any express
493 | agreement or commitment, however denominated, not to enforce a patent
494 | (such as an express permission to practice a patent or covenant not to
495 | sue for patent infringement). To "grant" such a patent license to a
496 | party means to make such an agreement or commitment not to enforce a
497 | patent against the party.
498 |
499 | If you convey a covered work, knowingly relying on a patent license,
500 | and the Corresponding Source of the work is not available for anyone
501 | to copy, free of charge and under the terms of this License, through a
502 | publicly available network server or other readily accessible means,
503 | then you must either (1) cause the Corresponding Source to be so
504 | available, or (2) arrange to deprive yourself of the benefit of the
505 | patent license for this particular work, or (3) arrange, in a manner
506 | consistent with the requirements of this License, to extend the patent
507 | license to downstream recipients. "Knowingly relying" means you have
508 | actual knowledge that, but for the patent license, your conveying the
509 | covered work in a country, or your recipient's use of the covered work
510 | in a country, would infringe one or more identifiable patents in that
511 | country that you have reason to believe are valid.
512 |
513 | If, pursuant to or in connection with a single transaction or
514 | arrangement, you convey, or propagate by procuring conveyance of, a
515 | covered work, and grant a patent license to some of the parties
516 | receiving the covered work authorizing them to use, propagate, modify
517 | or convey a specific copy of the covered work, then the patent license
518 | you grant is automatically extended to all recipients of the covered
519 | work and works based on it.
520 |
521 | A patent license is "discriminatory" if it does not include within
522 | the scope of its coverage, prohibits the exercise of, or is
523 | conditioned on the non-exercise of one or more of the rights that are
524 | specifically granted under this License. You may not convey a covered
525 | work if you are a party to an arrangement with a third party that is
526 | in the business of distributing software, under which you make payment
527 | to the third party based on the extent of your activity of conveying
528 | the work, and under which the third party grants, to any of the
529 | parties who would receive the covered work from you, a discriminatory
530 | patent license (a) in connection with copies of the covered work
531 | conveyed by you (or copies made from those copies), or (b) primarily
532 | for and in connection with specific products or compilations that
533 | contain the covered work, unless you entered into that arrangement,
534 | or that patent license was granted, prior to 28 March 2007.
535 |
536 | Nothing in this License shall be construed as excluding or limiting
537 | any implied license or other defenses to infringement that may
538 | otherwise be available to you under applicable patent law.
539 |
540 | 12. No Surrender of Others' Freedom.
541 |
542 | If conditions are imposed on you (whether by court order, agreement or
543 | otherwise) that contradict the conditions of this License, they do not
544 | excuse you from the conditions of this License. If you cannot convey a
545 | covered work so as to satisfy simultaneously your obligations under this
546 | License and any other pertinent obligations, then as a consequence you may
547 | not convey it at all. For example, if you agree to terms that obligate you
548 | to collect a royalty for further conveying from those to whom you convey
549 | the Program, the only way you could satisfy both those terms and this
550 | License would be to refrain entirely from conveying the Program.
551 |
552 | 13. Use with the GNU Affero General Public License.
553 |
554 | Notwithstanding any other provision of this License, you have
555 | permission to link or combine any covered work with a work licensed
556 | under version 3 of the GNU Affero General Public License into a single
557 | combined work, and to convey the resulting work. The terms of this
558 | License will continue to apply to the part which is the covered work,
559 | but the special requirements of the GNU Affero General Public License,
560 | section 13, concerning interaction through a network will apply to the
561 | combination as such.
562 |
563 | 14. Revised Versions of this License.
564 |
565 | The Free Software Foundation may publish revised and/or new versions of
566 | the GNU General Public License from time to time. Such new versions will
567 | be similar in spirit to the present version, but may differ in detail to
568 | address new problems or concerns.
569 |
570 | Each version is given a distinguishing version number. If the
571 | Program specifies that a certain numbered version of the GNU General
572 | Public License "or any later version" applies to it, you have the
573 | option of following the terms and conditions either of that numbered
574 | version or of any later version published by the Free Software
575 | Foundation. If the Program does not specify a version number of the
576 | GNU General Public License, you may choose any version ever published
577 | by the Free Software Foundation.
578 |
579 | If the Program specifies that a proxy can decide which future
580 | versions of the GNU General Public License can be used, that proxy's
581 | public statement of acceptance of a version permanently authorizes you
582 | to choose that version for the Program.
583 |
584 | Later license versions may give you additional or different
585 | permissions. However, no additional obligations are imposed on any
586 | author or copyright holder as a result of your choosing to follow a
587 | later version.
588 |
589 | 15. Disclaimer of Warranty.
590 |
591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599 |
600 | 16. Limitation of Liability.
601 |
602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610 | SUCH DAMAGES.
611 |
612 | 17. Interpretation of Sections 15 and 16.
613 |
614 | If the disclaimer of warranty and limitation of liability provided
615 | above cannot be given local legal effect according to their terms,
616 | reviewing courts shall apply local law that most closely approximates
617 | an absolute waiver of all civil liability in connection with the
618 | Program, unless a warranty or assumption of liability accompanies a
619 | copy of the Program in return for a fee.
620 |
621 | END OF TERMS AND CONDITIONS
622 |
623 | How to Apply These Terms to Your New Programs
624 |
625 | If you develop a new program, and you want it to be of the greatest
626 | possible use to the public, the best way to achieve this is to make it
627 | free software which everyone can redistribute and change under these terms.
628 |
629 | To do so, attach the following notices to the program. It is safest
630 | to attach them to the start of each source file to most effectively
631 | state the exclusion of warranty; and each file should have at least
632 | the "copyright" line and a pointer to where the full notice is found.
633 |
634 |
635 | Copyright (C)
636 |
637 | This program is free software: you can redistribute it and/or modify
638 | it under the terms of the GNU General Public License as published by
639 | the Free Software Foundation, either version 3 of the License, or
640 | (at your option) any later version.
641 |
642 | This program is distributed in the hope that it will be useful,
643 | but WITHOUT ANY WARRANTY; without even the implied warranty of
644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
645 | GNU General Public License for more details.
646 |
647 | You should have received a copy of the GNU General Public License
648 | along with this program. If not, see .
649 |
650 | Also add information on how to contact you by electronic and paper mail.
651 |
652 | If the program does terminal interaction, make it output a short
653 | notice like this when it starts in an interactive mode:
654 |
655 | Copyright (C)
656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657 | This is free software, and you are welcome to redistribute it
658 | under certain conditions; type `show c' for details.
659 |
660 | The hypothetical commands `show w' and `show c' should show the appropriate
661 | parts of the General Public License. Of course, your program's commands
662 | might be different; for a GUI interface, you would use an "about box".
663 |
664 | You should also get your employer (if you work as a programmer) or school,
665 | if any, to sign a "copyright disclaimer" for the program, if necessary.
666 | For more information on this, and how to apply and follow the GNU GPL, see
667 | .
668 |
669 | The GNU General Public License does not permit incorporating your program
670 | into proprietary programs. If your program is a subroutine library, you
671 | may consider it more useful to permit linking proprietary applications with
672 | the library. If this is what you want to do, use the GNU Lesser General
673 | Public License instead of this License. But first, please read
674 | .
675 |
--------------------------------------------------------------------------------