Browse code

CLI: ansible-doc shows lists of modules & module docs on command-line check path is directory added manpage & setup small cleanup shut up module_formatter in utils to avoid trace print on crud files in library

Jan-Piet Mens authored on 2012/11/28 17:39:26
Showing 6 changed files
... ...
@@ -22,7 +22,7 @@ OS = $(shell uname -s)
22 22
 # directory of the target file ($@), kinda like `dirname`.
23 23
 ASCII2MAN = a2x -D $(dir $@) -d manpage -f manpage $<
24 24
 ASCII2HTMLMAN = a2x -D docs/html/man/ -d manpage -f xhtml
25
-MANPAGES := docs/man/man1/ansible.1 docs/man/man1/ansible-playbook.1 docs/man/man1/ansible-pull.1
25
+MANPAGES := docs/man/man1/ansible.1 docs/man/man1/ansible-playbook.1 docs/man/man1/ansible-pull.1 docs/man/man1/ansible-doc.1
26 26
 
27 27
 SITELIB = $(shell python -c "from distutils.sysconfig import get_python_lib; print get_python_lib()")
28 28
 
29 29
new file mode 100755
... ...
@@ -0,0 +1,203 @@
0
+#!/usr/bin/env python
1
+
2
+# (c) 2012, Jan-Piet Mens <jpmens () gmail.com>
3
+#
4
+# This file is part of Ansible
5
+#
6
+# Ansible is free software: you can redistribute it and/or modify
7
+# it under the terms of the GNU General Public License as published by
8
+# the Free Software Foundation, either version 3 of the License, or
9
+# (at your option) any later version.
10
+#
11
+# Ansible is distributed in the hope that it will be useful,
12
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
13
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14
+# GNU General Public License for more details.
15
+#
16
+# You should have received a copy of the GNU General Public License
17
+# along with Ansible.  If not, see <http://www.gnu.org/licenses/>.
18
+#
19
+
20
+import os
21
+import sys
22
+import yaml
23
+import json
24
+import ast
25
+import textwrap
26
+import re
27
+import optparse
28
+import time
29
+import datetime
30
+from ansible import utils
31
+from ansible import errors
32
+from ansible.utils import module_docs
33
+import ansible.constants as C
34
+
35
+MODULEDIR = C.DEFAULT_MODULE_PATH
36
+
37
+_ITALIC = re.compile(r"I\(([^)]+)\)")
38
+_BOLD   = re.compile(r"B\(([^)]+)\)")
39
+_MODULE = re.compile(r"M\(([^)]+)\)")
40
+_URL    = re.compile(r"U\(([^)]+)\)")
41
+_CONST  = re.compile(r"C\(([^)]+)\)")
42
+
43
+def tty_ify(text):
44
+
45
+    t = _ITALIC.sub("`" + r"\1" + "'", text)    # I(word) => `word'
46
+    t = _BOLD.sub("*" + r"\1" + "*", t)         # B(word) => *word*
47
+    t = _MODULE.sub("[" + r"\1" + "]", t)       # M(word) => [word]
48
+    t = _URL.sub(r"\1", t)                      # U(word) => word
49
+    t = _CONST.sub("`" + r"\1" + "'", t)        # C(word) => `word'
50
+
51
+    return t
52
+
53
+def print_man(doc):
54
+
55
+    opt_indent="        "
56
+    print "> %s\n" % doc['module'].upper()
57
+
58
+    desc = "".join(doc['description'])
59
+
60
+    print "%s\n" % textwrap.fill(tty_ify(desc), initial_indent="  ", subsequent_indent="  ")
61
+    
62
+    print "Options (= is mandatory):\n"
63
+
64
+    for o in doc['option_keys']:
65
+        opt = doc['options'][o]
66
+
67
+        if opt.get('required', False):
68
+            opt_leadin = "="
69
+        else:
70
+            opt_leadin = "-"
71
+
72
+        print "%s %s" % (opt_leadin, o)
73
+        desc = "".join(opt['description'])
74
+
75
+        if 'choices' in opt:
76
+            choices = ", ".join(opt['choices'])
77
+            desc = desc + " (Choices: " + choices + ")"
78
+        print "%s\n" % textwrap.fill(tty_ify(desc), initial_indent=opt_indent,
79
+                            subsequent_indent=opt_indent)
80
+
81
+    if 'notes' in doc:
82
+        notes = "".join(doc['notes'])
83
+        print "Notes:%s\n" % textwrap.fill(tty_ify(notes), initial_indent="  ",
84
+                            subsequent_indent=opt_indent)
85
+
86
+
87
+    for ex in doc['examples']:
88
+        print "%s%s" % (opt_indent, ex['code'])
89
+
90
+def print_snippet(doc):
91
+
92
+    desc = tty_ify("".join(doc['short_description']))
93
+    print "- name: %s" % (desc)
94
+    print "  action: %s" % (doc['module'])
95
+
96
+    for o in doc['options']:
97
+        opt = doc['options'][o]
98
+        desc = tty_ify("".join(opt['description']))
99
+        s = o + "="
100
+        print "      %-20s   # %s" % (s, desc[0:60])
101
+
102
+def main():
103
+
104
+    p = optparse.OptionParser(
105
+        version='%prog 1.0',
106
+        usage='usage: %prog [options] [module...]',
107
+        description='Show Ansible module documentation',
108
+    )
109
+
110
+    p.add_option("-M", "--module-path",
111
+            action="store",
112
+            dest="module_path",
113
+            default=MODULEDIR,
114
+            help="Ansible modules/ directory")
115
+    p.add_option("-l", "--list",
116
+            action="store_true",
117
+            default=False,
118
+            dest='list_dir',
119
+            help='List available modules')
120
+    p.add_option("-s", "--snippet",
121
+            action="store_true",
122
+            default=False,
123
+            dest='show_snippet',
124
+            help='Show playbook snippet for specified module(s)')
125
+    p.add_option('-v', action='version', help='Show version number and exit')
126
+
127
+    (options, args) = p.parse_args()
128
+
129
+    if options.module_path is not None:
130
+        utils.plugins.vars_loader.add_directory(options.module_path)
131
+
132
+    if options.list_dir:
133
+        # list all modules
134
+        paths = utils.plugins.module_finder._get_paths()
135
+        module_list = []
136
+        for path in paths:
137
+            # os.system("ls -C %s" % (path))
138
+            if os.path.isdir(path):
139
+                for module in os.listdir(path):
140
+                    module_list.append(module)
141
+
142
+        for module in sorted(module_list):
143
+
144
+            if module in module_docs.BLACKLIST_MODULES:
145
+                continue
146
+
147
+            filename = utils.plugins.module_finder.find_plugin(module)
148
+            try:
149
+                doc = utils.module_docs.get_docstring(filename)
150
+                desc = tty_ify(doc.get('short_description', '?'))
151
+                if len(desc) > 55:
152
+                    desc = desc + '...'
153
+                print "%-20s %-60.60s" % (module, desc)
154
+            except:
155
+                sys.stderr.write("ERROR: module %s missing documentation\n" % module)
156
+                pass
157
+
158
+        sys.exit()
159
+
160
+    module_list = []
161
+
162
+    if len(args) == 0:
163
+        p.print_help()
164
+    
165
+    for module in args:
166
+
167
+        filename = utils.plugins.module_finder.find_plugin(module)
168
+        if filename is None:
169
+            sys.stderr.write("module %s not found in %s\n" % (module,
170
+                    utils.plugins.module_finder.print_paths()))
171
+            continue
172
+
173
+        if filename.endswith(".swp"):
174
+            continue
175
+
176
+        try:
177
+            doc = utils.module_docs.get_docstring(filename)
178
+        except:
179
+            sys.stderr.write("ERROR: module %s missing documentation\n" % module)
180
+            continue
181
+
182
+        if not doc is None:
183
+
184
+            all_keys = []
185
+            for (k,v) in doc['options'].iteritems():
186
+                all_keys.append(k)
187
+            all_keys = sorted(all_keys)
188
+            doc['option_keys'] = all_keys
189
+
190
+            doc['filename']         = filename
191
+            doc['docuri']           = doc['module'].replace('_', '-')
192
+            doc['now_date']         = datetime.date.today().strftime('%Y-%m-%d')
193
+
194
+            if options.show_snippet:
195
+                print_snippet(doc)
196
+            else:
197
+                print_man(doc)
198
+        else:
199
+            sys.stderr.write("ERROR: module %s missing documentation\n" % module)
200
+
201
+if __name__ == '__main__':
202
+    main()
0 203
new file mode 100644
... ...
@@ -0,0 +1,72 @@
0
+'\" t
1
+.\"     Title: ansible-doc
2
+.\"    Author: :doctype:manpage
3
+.\" Generator: DocBook XSL Stylesheets v1.76.1 <http://docbook.sf.net/>
4
+.\"      Date: 11/28/2012
5
+.\"    Manual: System administration commands
6
+.\"    Source: Ansible 0.9
7
+.\"  Language: English
8
+.\"
9
+.TH "ANSIBLE\-DOC" "1" "11/28/2012" "Ansible 0\&.9" "System administration commands"
10
+.\" -----------------------------------------------------------------
11
+.\" * Define some portability stuff
12
+.\" -----------------------------------------------------------------
13
+.\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
14
+.\" http://bugs.debian.org/507673
15
+.\" http://lists.gnu.org/archive/html/groff/2009-02/msg00013.html
16
+.\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
17
+.ie \n(.g .ds Aq \(aq
18
+.el       .ds Aq '
19
+.\" -----------------------------------------------------------------
20
+.\" * set default formatting
21
+.\" -----------------------------------------------------------------
22
+.\" disable hyphenation
23
+.nh
24
+.\" disable justification (adjust text to left margin only)
25
+.ad l
26
+.\" -----------------------------------------------------------------
27
+.\" * MAIN CONTENT STARTS HERE *
28
+.\" -----------------------------------------------------------------
29
+.SH "NAME"
30
+ansible-doc \- show documentation on Ansible modules
31
+.SH "SYNOPSIS"
32
+.sp
33
+ansible\-doc [\-M module_path] [\-l] [\-s] [module\&...]
34
+.SH "DESCRIPTION"
35
+.sp
36
+\fBansible\-doc\fR displays information on modules installed in Ansible libraries\&. It displays a terse listing of modules and their short descriptions, provides a printout of their DOCUMENTATION strings, and it can create a short "snippet" which can be pasted into a playbook\&.
37
+.SH "OPTIONS"
38
+.PP
39
+\fB\-M\fR \fIdirectory\fR, \fB\-\-module\-path=\fR\fIdirectory\fR
40
+.RS 4
41
+Add an additional directory to the default path for finding module libraries\&.
42
+.RE
43
+.PP
44
+\fB\-s\fR, \fB\-\-snippet=\fR
45
+.RS 4
46
+Produce a snippet which can be copied into a playbook for modification, like a kind of task template\&.
47
+.RE
48
+.PP
49
+\fB\-l\fR, \fB\-\-list=\fR
50
+.RS 4
51
+Produce a terse listing of modules and a short description of each\&.
52
+.RE
53
+.SH "AUTHOR"
54
+.sp
55
+ansible\-doc was originally written by Jan\-Piet Mens\&. See the AUTHORS file for a complete list of contributors\&.
56
+.SH "COPYRIGHT"
57
+.sp
58
+Copyright \(co 2012, Jan\-Piet Mens
59
+.sp
60
+Ansible is released under the terms of the GPLv3 License\&.
61
+.SH "SEE ALSO"
62
+.sp
63
+\fBansible\-playbook\fR(1), \fBansible\fR(1)
64
+.sp
65
+Extensive documentation as well as IRC and mailing list info is available on the ansible home page: https://ansible\&.github\&.com/
66
+.SH "AUTHOR"
67
+.PP
68
+\fB:doctype:manpage\fR
69
+.RS 4
70
+Author.
71
+.RE
0 72
new file mode 100644
... ...
@@ -0,0 +1,65 @@
0
+ansible-doc(1)
1
+==============
2
+:doctype:manpage
3
+:man source:   Ansible
4
+:man version:  %VERSION%
5
+:man manual:   System administration commands
6
+
7
+NAME
8
+----
9
+ansible-doc - show documentation on Ansible modules
10
+
11
+
12
+SYNOPSIS
13
+--------
14
+ansible-doc [-M module_path] [-l] [-s] [module...]
15
+
16
+
17
+DESCRIPTION
18
+-----------
19
+
20
+*ansible-doc* displays information on modules installed in Ansible
21
+libraries. It displays a terse listing of modules and their short
22
+descriptions, provides a printout of their DOCUMENTATION strings,
23
+and it can create a short "snippet" which can be pasted into a
24
+playbook.
25
+
26
+
27
+OPTIONS
28
+-------
29
+
30
+*-M* 'directory', *--module-path=*'directory'::
31
+
32
+Add an additional directory to the default path for finding module libraries.
33
+
34
+*-s*, *--snippet=*::
35
+
36
+Produce a snippet which can be copied into a playbook for modification, like
37
+a kind of task template.
38
+
39
+*-l*, *--list=*::
40
+
41
+Produce a terse listing of modules and a short description of each.
42
+
43
+AUTHOR
44
+------
45
+
46
+ansible-doc was originally written by Jan-Piet Mens. See the AUTHORS file
47
+for a complete list of contributors.
48
+
49
+
50
+COPYRIGHT
51
+---------
52
+
53
+Copyright © 2012, Jan-Piet Mens
54
+
55
+Ansible is released under the terms of the GPLv3 License.
56
+
57
+
58
+SEE ALSO
59
+--------
60
+
61
+*ansible-playbook*(1), *ansible*(1)
62
+
63
+Extensive documentation as well as IRC and mailing list info
64
+is available on the ansible home page: <https://ansible.github.com/>
... ...
@@ -45,6 +45,7 @@ def get_docstring(filename, verbose=False):
45 45
                     doc = yaml.load(child.value.s)
46 46
 
47 47
     except:
48
-        traceback.print_exc()
49
-        print "unable to parse %s" % filename
48
+        if verbose == True:
49
+            traceback.print_exc()
50
+            print "unable to parse %s" % filename
50 51
     return doc
... ...
@@ -40,7 +40,8 @@ setup(name='ansible',
40 40
       scripts=[
41 41
          'bin/ansible',
42 42
          'bin/ansible-playbook',
43
-         'bin/ansible-pull'
43
+         'bin/ansible-pull',
44
+         'bin/ansible-doc'
44 45
       ],
45 46
       data_files=data_files
46 47
 )