Browse Source

Remove "cleanup" tools

There were a couple of scripts here:

- prettify.py
- remove_trailing_whitespaces.sh
- remove_unnecessary_spaces.py
- retf

Most of them are self-explanatory with the exception of 'retf', which I
don't understand but which looks untouched in years and therefore
useless. For the other three, we have tooling in place to ensure these
"issues" don't get into source control and, even if they did, there's
questionable value in rewriting stuff just to remove excess whitespace.
Kill them all.

Change-Id: Ifbd2d50a669251484056552da21d23906f8d6178
Stephen Finucane 1 year ago
parent
commit
ca9ff17d27

+ 0
- 72
cleanup/prettify.py View File

@@ -1,72 +0,0 @@
1
-#!/usr/bin/env python
2
-
3
-"""A script to prettify HTML and XML syntax.
4
-
5
-Some examples of the prettified syntax are available
6
-in the following changes:
7
-
8
-* https://review.openstack.org/#/c/98652/
9
-* https://review.openstack.org/#/c/98653/
10
-* https://review.openstack.org/#/c/98655/
11
-"""
12
-
13
-# Licensed under the Apache License, Version 2.0 (the "License"); you may
14
-# not use this file except in compliance with the License. You may obtain
15
-# a copy of the License at
16
-#
17
-#      http://www.apache.org/licenses/LICENSE-2.0
18
-#
19
-# Unless required by applicable law or agreed to in writing, software
20
-# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
21
-# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
22
-# License for the specific language governing permissions and limitations
23
-# under the License.
24
-
25
-
26
-from __future__ import print_function
27
-import argparse
28
-import sys
29
-
30
-from bs4 import BeautifulSoup
31
-
32
-
33
-def parse_command_line_arguments():
34
-    """Parse the command line arguments."""
35
-    parser = argparse.ArgumentParser()
36
-    parser.add_argument("--write-changes", action="store_true", default=False,
37
-                        help="Write prettified XML or HTML syntax "
38
-                             "back to file.")
39
-    parser.add_argument("file", type=str, default=None,
40
-                        help="A XML or HTML File to prettify.")
41
-    return parser.parse_args()
42
-
43
-
44
-def main():
45
-    """Entry point for this script."""
46
-
47
-    args = parse_command_line_arguments()
48
-
49
-    try:
50
-        soup = BeautifulSoup(open(args.file))
51
-    except IOError as exception:
52
-        print("ERROR: File '%s' could not be parsed: %s"
53
-              % (args.file, exception))
54
-        return 1
55
-
56
-    if args.write_changes:
57
-        try:
58
-            with open(args.file, 'wb') as output:
59
-                prettified = soup.prettify(encoding="utf8")
60
-                output.write(prettified)
61
-        except IOError as exception:
62
-            print("ERROR: File '%s' could not be written: %s"
63
-                  % (args.file, exception))
64
-            return 1
65
-    else:
66
-        prettified = soup.prettify(encoding="utf8")
67
-        print(prettified)
68
-
69
-    return 0
70
-
71
-if __name__ == '__main__':
72
-    sys.exit(main())

+ 0
- 24
cleanup/remove_trailing_whitespaces.sh View File

@@ -1,24 +0,0 @@
1
-#!/bin/sh
2
-
3
-## copyright: B1 Systems GmbH   <info@b1-systems.de>,    2013.
4
-##    author: Christian Berendt <berendt@b1-systems.de>, 2013.
5
-
6
-# Licensed under the Apache License, Version 2.0 (the "License"); you may
7
-# not use this file except in compliance with the License. You may obtain
8
-# a copy of the License at
9
-#
10
-#      http://www.apache.org/licenses/LICENSE-2.0
11
-#
12
-# Unless required by applicable law or agreed to in writing, software
13
-# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
14
-# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
15
-# License for the specific language governing permissions and limitations
16
-# under the License.
17
-
18
-# Call ./tools/cleanup/remove_trailing_whitespaces.sh in the
19
-# root of openstack-manuals.
20
-
21
-files=$(find doc -name *.xml -not -name pom.xml)
22
-for file in $files; do
23
-    sed -i -e 's/[[:space:]]*$//' $file
24
-done

+ 0
- 69
cleanup/remove_unnecessary_spaces.py View File

@@ -1,69 +0,0 @@
1
-#!/usr/bin/env python
2
-
3
-# copyright: B1 Systems GmbH   <info@b1-systems.de>,    2013.
4
-
5
-# Licensed under the Apache License, Version 2.0 (the "License"); you may
6
-# not use this file except in compliance with the License. You may obtain
7
-# a copy of the License at
8
-#
9
-#      http://www.apache.org/licenses/LICENSE-2.0
10
-#
11
-# Unless required by applicable law or agreed to in writing, software
12
-# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
13
-# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
14
-# License for the specific language governing permissions and limitations
15
-# under the License.
16
-
17
-# Call ./tools/cleanup/remove_unnecessary_spaces.py in the
18
-# root of openstack-manuals.
19
-
20
-import os
21
-import re
22
-import shutil
23
-import tempfile
24
-
25
-# should be the same like in tools/validate.py
26
-FILE_EXCEPTIONS = ['ha-guide-docinfo.xml',
27
-                   'bk001-ch003-associate-general.xml']
28
-
29
-elements = [
30
-    'listitem',
31
-    'para',
32
-    'td',
33
-    'th',
34
-    'command',
35
-    'literal',
36
-    'title',
37
-    'caption',
38
-    'filename',
39
-    'userinput',
40
-    'programlisting'
41
-]
42
-
43
-checks = []
44
-for element in elements:
45
-    checks.append(re.compile("(.*<%s>)\s+([\w\-().:!?{}\[\]]+.*\n)"
46
-                             % element)),
47
-    checks.append(re.compile("(.*[\w\-().:!?{}\[\]]+)\s+(<\/%s>.*\n)"
48
-                             % element))
49
-
50
-for root, dirs, files in os.walk('doc/'):
51
-    for f in files:
52
-        if (not (f.endswith('.xml') and
53
-                 f != 'pom.xml' and
54
-                 f not in FILE_EXCEPTIONS)):
55
-            continue
56
-        docfile = os.path.abspath(os.path.join(root, f))
57
-        tmpfile = tempfile.mkstemp()
58
-        tmpfd = os.fdopen(tmpfile[0], "w")
59
-        match = False
60
-        for line in open(docfile, 'r'):
61
-            for check in checks:
62
-                if check.match(line):
63
-                    line = check.sub(r"\1\2", line)
64
-                    match = True
65
-            tmpfd.write(line)
66
-        tmpfd.close()
67
-        if match:
68
-            shutil.copyfile(tmpfile[1], docfile)
69
-        os.unlink(tmpfile[1])

+ 0
- 69
cleanup/retf/README.md View File

@@ -1,69 +0,0 @@
1
-# retf.py
2
-
3
-This script applies a set of regular expressions onto a set of files
4
-to automatically identify and fix typographical errors.
5
-
6
-## What does RETF mean?
7
-
8
-RETF means RegExTypoFix or Regular Expression Typographical error Fixer
9
-and is a set of regular expressions to find and fix common misspellings
10
-and grammatical errors.
11
-
12
-The regular expressions are available at
13
-https://en.wikipedia.org/wiki/Wikipedia:AutoWikiBrowser/Typos.
14
-
15
-## Usage
16
-
17
-There are two ways to define the set of files. First you can simply add
18
-single files using the parameter ```--file```.
19
-
20
-```$ ./retf.py --file path/to/file1 path/to/file2 path/to/file3```
21
-
22
-Also you can specify paths using the parameter ```--path``` that should be
23
-scanned for files.
24
-
25
-```$ ./retf.py --path path/with/files/1 path/with/files/2```
26
-
27
-To not use all files inside the specified paths it's possible to filter
28
-by the file extension.
29
-
30
-```$ ./retf.py --path path/with/files --extension xml txt rst```
31
-
32
-It's possible to use the parameters ```--path``` and ```--file``` together.
33
-
34
-By default the script will only check for findings in all specified files.
35
-
36
-To automatically write back resolved findings add the parameter
37
-```--write-changes```. Findings will then be written to a copy with
38
-the ending ```.retf```.
39
-
40
-To fix findings directly in the files add the parameter
41
-```--in-place```. Findings will than be fixed directly in the files. A backup file
42
-with the ending ```.orig``` will be created. To disable backups add the
43
-paramter ```--no-backup```.
44
-
45
-To only check if there are findings inside the defined set of files add
46
-
47
-To download the latest RETF rules from Wikipedia use the parameter ```--download```.
48
-
49
-## Needed Python modules
50
-
51
-* beautifulsoup4 / bs4 (https://pypi.python.org/pypi/beautifulsoup4)
52
-* glob2 (https://pypi.python.org/pypi/glob2)
53
-* pyyaml (https://pypi.python.org/pypi/pyaml)
54
-* regex (https://pypi.python.org/pypi/regex)
55
-* six (https://pypi.python.org/pypi/six)
56
-
57
-To install the needed modules you can use pip or the package management system included
58
-in your distribution. When using the package management system maybe the name of the
59
-packages differ. When using pip it's maybe necessary to install some development packages.
60
-For example on Ubuntu 14.04 LTS you have to install ```libyaml-dev``` for ```pyyaml```
61
-and ```python-dev``` for ```regex```.
62
-
63
-```
64
-$ pip install beautifulsoup4
65
-$ pip install glob2
66
-$ pip install pyyaml
67
-$ pip install regex
68
-$ pip install six
69
-```

+ 0
- 1
cleanup/retf/disabled_rules.yaml View File

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

+ 0
- 307
cleanup/retf/retf.py View File

@@ -1,307 +0,0 @@
1
-#!/usr/bin/env python
2
-
3
-"""This script applies a set of regular expressions onto a set of files
4
-to automatically identify and fix typographical errors.
5
-"""
6
-
7
-# Licensed under the Apache License, Version 2.0 (the "License"); you may
8
-# not use this file except in compliance with the License. You may obtain
9
-# a copy of the License at
10
-#
11
-#      http://www.apache.org/licenses/LICENSE-2.0
12
-#
13
-# Unless required by applicable law or agreed to in writing, software
14
-# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
15
-# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
16
-# License for the specific language governing permissions and limitations
17
-# under the License.
18
-
19
-# Based on the idea of 'Topy' written by Marti Raudsepp <marti@juffo.org>.
20
-# Topy is available on Github at https://github.com/intgr/topy.
21
-
22
-import argparse
23
-import logging
24
-import os
25
-import shutil
26
-import sys
27
-
28
-from six.moves.urllib import error as urlerr
29
-from six.moves.urllib import request as urlreq
30
-
31
-from bs4 import BeautifulSoup
32
-import glob2
33
-import regex
34
-import six
35
-import yaml
36
-
37
-
38
-class DownloadRetfListingFailed(Exception):
39
-    """Exception for failed downloads of the RETF listing.
40
-
41
-    Exception will be raised when the download of the RETF
42
-    listing failed or the destination file could not be written.
43
-
44
-    """
45
-
46
-    pass
47
-
48
-
49
-def download_listing(dest):
50
-    """Download the latest RETF listing from Wikipedia."""
51
-    logger = logging.getLogger('retf')
52
-    try:
53
-        url = ('https://en.wikipedia.org/wiki/Wikipedia:AutoWikiBrowser/'
54
-               'Typos?action=raw')
55
-        logger.debug("Downloading latest RETF listing from %s into %s.",
56
-                     url, dest)
57
-        response = urlreq.urlopen(url)
58
-        data = response.read()
59
-        logger.info("Downloading latest RETF listing from %s succeeded.", url)
60
-    except urlerr.HTTPError as ex:
61
-        raise DownloadRetfListingFailed(six.text_type(ex))
62
-    except urlerr.URLError as ex:
63
-        raise DownloadRetfListingFailed(six.text_type(ex))
64
-
65
-    try:
66
-        with open(dest, 'w+') as write:
67
-            write.write(data)
68
-        logger.info("Writing RETF listing to file %s succeeded.", dest)
69
-    except IOError as ex:
70
-        raise DownloadRetfListingFailed(six.text_type(ex))
71
-
72
-
73
-def soupify_listing(src):
74
-    """Parse a RETF listing."""
75
-    return BeautifulSoup(open(src))
76
-
77
-
78
-def generate_listing(src):
79
-    """Compile all regular expressions in a RETF listing."""
80
-    logger = logging.getLogger('retf')
81
-    result = []
82
-
83
-    soup = soupify_listing(src)
84
-
85
-    for typo in soup.findAll('typo'):
86
-        try:
87
-            word = typo.attrs.get('word').encode('utf8')
88
-            find = typo.attrs.get('find').encode('utf8')
89
-            replace = typo.attrs.get('replace').encode('utf8')
90
-            replace = replace.replace(b'$', b'\\')
91
-        except AttributeError:
92
-            continue
93
-
94
-        # pylint: disable=W0703
95
-        try:
96
-            logger.debug("Compiling regular expression: %s.", find)
97
-            compiled = regex.compile(find, flags=regex.V1)
98
-        except Exception:
99
-            logger.error("Compilation of regular expression %f failed.", find)
100
-            continue
101
-        # pylint: enable=W0703
102
-
103
-        entry = {
104
-            'description': word,
105
-            'find': find,
106
-            'replace': replace,
107
-            'regex': compiled
108
-        }
109
-
110
-        result.append(entry)
111
-
112
-    logger.debug("Compiled %d regular expression(s).", len(result))
113
-
114
-    return result
115
-
116
-
117
-def load_text_from_file(src):
118
-    """Load content from a file."""
119
-    logger = logging.getLogger('retf')
120
-    logger.debug("Loading text from file %s.", src)
121
-    with open(src, 'rb') as fpointer:
122
-        text = fpointer.read()
123
-
124
-    return text
125
-
126
-
127
-def write_text_to_file(dest, text, no_backup, in_place):
128
-    """Write content into a file."""
129
-    logger = logging.getLogger('retf')
130
-
131
-    if not no_backup:
132
-        logger.debug("Copying %s to backup file %s.orig.", dest, dest)
133
-        shutil.copy2(dest, "%s.orig" % dest)
134
-
135
-    if not in_place:
136
-        dest = "%s.retf" % dest
137
-
138
-    logger.debug("Writing text to file %s.", dest)
139
-    with open(dest, 'wb') as fpointer:
140
-        fpointer.write(text)
141
-
142
-
143
-def initialize_logging(debug, less_verbose):
144
-    """Initialize the Logger."""
145
-    logger = logging.getLogger(name='retf')
146
-    formatter = logging.Formatter('%(asctime)s %(levelname)-8s %(message)s')
147
-    handler = logging.StreamHandler()
148
-    handler.setFormatter(formatter)
149
-    logger.addHandler(handler)
150
-
151
-    logger.setLevel(logging.INFO)
152
-
153
-    if less_verbose:
154
-        logger.setLevel(logging.WARN)
155
-
156
-    if debug:
157
-        logger.setLevel(logging.DEBUG)
158
-
159
-    return logging.getLogger('retf')
160
-
161
-
162
-def parse_command_line_arguments():
163
-    """Parse the command line arguments."""
164
-    parser = argparse.ArgumentParser()
165
-    parser.add_argument("--debug", help="Print debugging messages.",
166
-                        action="store_true", default=False)
167
-    parser.add_argument("--download", help="Download the latest RETF listing.",
168
-                        action="store_true", default=False)
169
-    parser.add_argument("--less-verbose", help="Be less verbose.",
170
-                        action="store_true", default=False)
171
-    parser.add_argument("--no-backup", help="Don't backup files.",
172
-                        action="store_true", default=False)
173
-    parser.add_argument("--in-place", help="Resolve found errors in place.",
174
-                        action="store_true", default=False)
175
-    parser.add_argument("--write-changes", action="store_true", default=False,
176
-                        help="Write resolved findings back to files.")
177
-    parser.add_argument("--disabled", type=str, default=None,
178
-                        help="File containing the disabled rules.")
179
-    parser.add_argument("--listing", help="File containing the RETF listing.",
180
-                        type=str, default=os.path.join(
181
-                            os.path.dirname(os.path.realpath(__file__)),
182
-                            'retf.lst'))
183
-    parser.add_argument("--path", type=str, nargs='*', default=[],
184
-                        help="Path(s) that should be checked.")
185
-    parser.add_argument("--extension", type=str, nargs='*', default=[],
186
-                        help="Only check files with specified extension(s).")
187
-    parser.add_argument("--file", nargs='*', type=str, default=[],
188
-                        help="File(s) to check for typographical errors.")
189
-    return (parser, parser.parse_args())
190
-
191
-
192
-def load_disabled_rules(src):
193
-    """Load disabled rules from YAML file."""
194
-    logger = logging.getLogger('retf')
195
-    listing = []
196
-
197
-    if src:
198
-        try:
199
-            listing = yaml.safe_load(open(src))
200
-            for rule in listing:
201
-                logger.debug("Rule '%s' is disabled.", rule)
202
-
203
-        except IOError:
204
-            logger.error("loading disabled rules from file %s failed", src)
205
-
206
-    return listing
207
-
208
-
209
-def get_file_listing(paths, files, extensions):
210
-    """Generate listing with all files that should be check."""
211
-    result = []
212
-    if files:
213
-        result += files
214
-
215
-    # pylint: disable=E1101
216
-    for path in paths:
217
-        if extensions:
218
-            for extension in extensions:
219
-                result += glob2.glob("%s/**/*.%s" % (path, extension))
220
-        else:
221
-            result += glob2.glob("%s/**/*" % path)
222
-    # pylint: enable=E1101
223
-
224
-    return result
225
-
226
-
227
-def check_file(src, rules, disabled):
228
-    """Applies a set of rules on a file."""
229
-    logger = logging.getLogger('retf')
230
-    logger.info("Checking file %s for typographical errors.", src)
231
-    content = load_text_from_file(src)
232
-    findings = 0
233
-
234
-    for rule in rules:
235
-        if rule.get('description') in disabled:
236
-            continue
237
-
238
-        logger.debug("%s: checking rule '%s'.", src,
239
-                     rule.get('description'))
240
-        logger.debug(rule.get('find'))
241
-        newcontent, count = rule.get('regex').subn(
242
-            rule.get('replace'), content
243
-        )
244
-
245
-        if count > 0:
246
-            logger.warning("%d match(s) in file %s : %s.", count, src,
247
-                           rule.get('description'))
248
-            findings += count
249
-        content = newcontent
250
-
251
-    return (findings, content)
252
-
253
-
254
-def main():
255
-    """Entry point for this script."""
256
-
257
-    parser, args = parse_command_line_arguments()
258
-    logger = initialize_logging(args.debug, args.less_verbose)
259
-
260
-    result = 0
261
-
262
-    if args.download:
263
-        try:
264
-            download_listing(args.listing)
265
-        except DownloadRetfListingFailed as ex:
266
-            logger.error("Downloading latest RETF listing failed: %s.", ex)
267
-            result = 1
268
-
269
-    if not args.path and not args.file and not args.download:
270
-        parser.print_help()
271
-        result = 2
272
-
273
-    if not result and not os.path.isfile(args.listing):
274
-        logger.error("RETF listing not found at %s.", args.listing)
275
-        logger.info("Please download the RETF listing first by using the "
276
-                    "parameter --download.")
277
-        result = 1
278
-
279
-    if not result:
280
-        files = get_file_listing(args.path, args.file, args.extension)
281
-
282
-        rules = generate_listing(args.listing)
283
-        disabled = load_disabled_rules(args.disabled)
284
-
285
-        all_findings = 0
286
-        for check in files:
287
-            if not os.path.isfile(check):
288
-                continue
289
-
290
-            (findings, content) = check_file(check, rules, disabled)
291
-
292
-            if findings > 0:
293
-                all_findings += findings
294
-                logger.warning("%s finding(s) in file %s.", findings, check)
295
-
296
-            if findings > 0 and args.write_changes:
297
-                write_text_to_file(check, content, args.no_backup,
298
-                                   args.in_place)
299
-
300
-        if all_findings > 0:
301
-            logger.warning("%s finding(s) in all checked files.", all_findings)
302
-            result = 1
303
-
304
-    return result
305
-
306
-if __name__ == "__main__":
307
-    sys.exit(main())

+ 11
- 0
releasenotes/notes/the-great-doc-tools-cleanup-1a79e2c200232489.yaml View File

@@ -12,3 +12,14 @@ upgrade:
12 12
     superseded by the ``cliff.sphinxext`` `Sphinx extensions`__.
13 13
 
14 14
     __ https://docs.openstack.org/cliff/latest/user/sphinxext.html
15
+  - |
16
+    The following scripts and tools have been removed:
17
+
18
+    - prettify.py$
19
+    - remove_trailing_whitespaces.sh$
20
+    - remove_unnecessary_spaces.py$
21
+    - retf$
22
+
23
+    These were all indented to cleanup docs once they were already in tree, but
24
+    our tooling and review process should be sufficient to catch most issues
25
+    and there's limited value in submitting whitespace-fixup patches.

+ 0
- 1
setup.cfg View File

@@ -24,7 +24,6 @@ packages =
24 24
     os_doc_tools
25 25
 data_files =
26 26
     share/openstack-doc-tools/sitemap = sitemap/*
27
-    share/openstack-doc-tools/cleanup = cleanup/*
28 27
 scripts =
29 28
     bin/doc-tools-check-languages
30 29
     bin/doc-tools-build-rst

+ 2
- 3
tox.ini View File

@@ -25,11 +25,10 @@ commands =
25 25
     doc8 -e txt -e rst doc/source/ HACKING.rst
26 26
     # Run bashate during pep8 runs to ensure violations are caught by
27 27
     # the check and gate queues.
28
-    bashate bin/doc-tools-check-languages \
29
-        cleanup/remove_trailing_whitespaces.sh
28
+    bashate bin/doc-tools-check-languages
30 29
 
31 30
 [testenv:pylint]
32
-commands = pylint os_doc_tools cleanup sitemap
31
+commands = pylint os_doc_tools sitemap
33 32
 
34 33
 [testenv:releasenotes]
35 34
 commands = sphinx-build -a -E -W -d releasenotes/build/doctrees -b html releasenotes/source releasenotes/build/html

Loading…
Cancel
Save