Full Code of openstack/bashate for AI

master ec2f24009152 cached
68 files
78.7 KB
21.3k tokens
73 symbols
1 requests
Download .txt
Repository: openstack/bashate
Branch: master
Commit: ec2f24009152
Files: 68
Total size: 78.7 KB

Directory structure:
gitextract_das1educ/

├── .coveragerc
├── .gitignore
├── .gitreview
├── .mailmap
├── .pre-commit-hooks.yaml
├── .stestr.conf
├── .zuul.d/
│   └── jobs.yaml
├── CONTRIBUTING.rst
├── HACKING.rst
├── LICENSE
├── README.rst
├── bashate/
│   ├── __init__.py
│   ├── __main__.py
│   ├── bashate.py
│   ├── messages.py
│   └── tests/
│       ├── __init__.py
│       ├── base.py
│       ├── samples/
│       │   ├── .E005_excluded
│       │   ├── E001_bad.sh
│       │   ├── E002_bad.sh
│       │   ├── E003_bad.sh
│       │   ├── E003_good.sh
│       │   ├── E004_bad.sh
│       │   ├── E005_bad
│       │   ├── E006_bad.sh
│       │   ├── E006_bad_custom_length.sh
│       │   ├── E006_good.sh
│       │   ├── E010_bad.sh
│       │   ├── E010_good.sh
│       │   ├── E011_bad.sh
│       │   ├── E011_good.sh
│       │   ├── E012_bad.sh
│       │   ├── E040_syntax_error.sh
│       │   ├── E041_bad.sh
│       │   ├── E042_bad.sh
│       │   ├── E043_bad.sh
│       │   ├── E044_bad.sh
│       │   ├── comments.sh
│       │   ├── for_loops.sh
│       │   ├── heredoc_ignore.sh
│       │   └── legacy_sample.sh
│       └── test_bashate.py
├── bindep.txt
├── doc/
│   ├── requirements.txt
│   └── source/
│       ├── conf.py
│       ├── contributor/
│       │   ├── contributing.rst
│       │   └── index.rst
│       ├── index.rst
│       ├── install/
│       │   └── index.rst
│       ├── man/
│       │   └── bashate.rst
│       ├── readme.rst
│       └── user/
│           ├── index.rst
│           └── usage.rst
├── playbooks/
│   └── bashate-devstack-master/
│       └── run.yaml
├── releasenotes/
│   ├── notes/
│   │   ├── 0-dash-6-748e729ee001df73.yaml
│   │   ├── adopt-pycodestyle-output-format-f4d6e35dadfcb6f9.yaml
│   │   ├── custom-line-length-083e8077951a8ead.yaml
│   │   ├── drop-python2.7-064c5e5bcfb4539c.yaml
│   │   ├── heredoc-ignore-905b29053652f90e.yaml
│   │   ├── python-3-4e30b9f2b9e2dcb7.yaml
│   │   └── start-using-reno-eaaafddb3fbf2010.yaml
│   └── source/
│       ├── conf.py
│       └── index.rst
├── requirements.txt
├── setup.cfg
├── setup.py
├── test-requirements.txt
└── tox.ini

================================================
FILE CONTENTS
================================================

================================================
FILE: .coveragerc
================================================
[run]
branch = True
source = bashate
omit = bashate/tests/*

[report]
ignore_errors = True


================================================
FILE: .gitignore
================================================
*.py[cod]

# C extensions
*.so

# Packages
*.egg
*.egg-info
dist
build
eggs
parts
bin
var
sdist
develop-eggs
.installed.cfg
lib
lib64

# Installer logs
pip-log.txt

# Unit test / coverage reports
.coverage
.tox
nosetests.xml
.stestr/
cover/

# Translations
*.mo

# Mr Developer
.mr.developer.cfg
.project
.pydevproject

# Complexity
output/*.html
output/*/index.html

# Sphinx
doc/build

# pbr generates these
AUTHORS
ChangeLog

# Editors
*~
.*.swp

================================================
FILE: .gitreview
================================================
[gerrit]
host=review.opendev.org
port=29418
project=openstack/bashate.git


================================================
FILE: .mailmap
================================================
# Format is:
# <preferred e-mail> <other e-mail 1>
# <preferred e-mail> <other e-mail 2>

================================================
FILE: .pre-commit-hooks.yaml
================================================
---

# For use with pre-commit.
# See usage instructions at https://pre-commit.com

-   id: bashate
    name: bashate
    description: This hook runs bashate for linting shell scripts
    entry: bashate
    language: python
    types: [shell]


================================================
FILE: .stestr.conf
================================================
[DEFAULT]
test_path=./bashate/tests

================================================
FILE: .zuul.d/jobs.yaml
================================================
- project:
    templates:
      - openstack-python3-jobs
      - publish-openstack-docs-pti
      - release-notes-jobs-python3
    check:
      jobs:
        - openstack-tox-pep8
        - openstack-tox-py39
        - openstack-tox-py310
        - openstack-tox-py311
        - openstack-tox-py312
        - bashate-devstack
    gate:
      jobs:
        - openstack-tox-pep8
        - openstack-tox-py39
        - openstack-tox-py310
        - openstack-tox-py311
        - openstack-tox-py312
        - bashate-devstack

- job:
    name: bashate-devstack
    run: playbooks/bashate-devstack-master/run.yaml
    required-projects:
      - openstack/devstack


================================================
FILE: CONTRIBUTING.rst
================================================
The source repository for this project can be found at:

   https://opendev.org/openstack/bashate

Pull requests submitted through GitHub are not monitored.

To start contributing to OpenStack, follow the steps in the contribution guide
to set up and use Gerrit:

   https://docs.openstack.org/contributors/code-and-documentation/quick-start.html

Bugs should be filed on Launchpad:

   https://bugs.launchpad.net/bash8

For more specific information about contributing to this repository, see the
Bashate contributor guide:

   https://docs.openstack.org/bashate/latest/contributor/contributing.html


================================================
FILE: HACKING.rst
================================================
bashate Style Commandments
===============================================

Read the OpenStack Style Commandments http://docs.openstack.org/developer/hacking/


================================================
FILE: LICENSE
================================================

                                 Apache License
                           Version 2.0, January 2004
                        http://www.apache.org/licenses/

   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION

   1. Definitions.

      "License" shall mean the terms and conditions for use, reproduction,
      and distribution as defined by Sections 1 through 9 of this document.

      "Licensor" shall mean the copyright owner or entity authorized by
      the copyright owner that is granting the License.

      "Legal Entity" shall mean the union of the acting entity and all
      other entities that control, are controlled by, or are under common
      control with that entity. For the purposes of this definition,
      "control" means (i) the power, direct or indirect, to cause the
      direction or management of such entity, whether by contract or
      otherwise, or (ii) ownership of fifty percent (50%) or more of the
      outstanding shares, or (iii) beneficial ownership of such entity.

      "You" (or "Your") shall mean an individual or Legal Entity
      exercising permissions granted by this License.

      "Source" form shall mean the preferred form for making modifications,
      including but not limited to software source code, documentation
      source, and configuration files.

      "Object" form shall mean any form resulting from mechanical
      transformation or translation of a Source form, including but
      not limited to compiled object code, generated documentation,
      and conversions to other media types.

      "Work" shall mean the work of authorship, whether in Source or
      Object form, made available under the License, as indicated by a
      copyright notice that is included in or attached to the work
      (an example is provided in the Appendix below).

      "Derivative Works" shall mean any work, whether in Source or Object
      form, that is based on (or derived from) the Work and for which the
      editorial revisions, annotations, elaborations, or other modifications
      represent, as a whole, an original work of authorship. For the purposes
      of this License, Derivative Works shall not include works that remain
      separable from, or merely link (or bind by name) to the interfaces of,
      the Work and Derivative Works thereof.

      "Contribution" shall mean any work of authorship, including
      the original version of the Work and any modifications or additions
      to that Work or Derivative Works thereof, that is intentionally
      submitted to Licensor for inclusion in the Work by the copyright owner
      or by an individual or Legal Entity authorized to submit on behalf of
      the copyright owner. For the purposes of this definition, "submitted"
      means any form of electronic, verbal, or written communication sent
      to the Licensor or its representatives, including but not limited to
      communication on electronic mailing lists, source code control systems,
      and issue tracking systems that are managed by, or on behalf of, the
      Licensor for the purpose of discussing and improving the Work, but
      excluding communication that is conspicuously marked or otherwise
      designated in writing by the copyright owner as "Not a Contribution."

      "Contributor" shall mean Licensor and any individual or Legal Entity
      on behalf of whom a Contribution has been received by Licensor and
      subsequently incorporated within the Work.

   2. Grant of Copyright License. Subject to the terms and conditions of
      this License, each Contributor hereby grants to You a perpetual,
      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
      copyright license to reproduce, prepare Derivative Works of,
      publicly display, publicly perform, sublicense, and distribute the
      Work and such Derivative Works in Source or Object form.

   3. Grant of Patent License. Subject to the terms and conditions of
      this License, each Contributor hereby grants to You a perpetual,
      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
      (except as stated in this section) patent license to make, have made,
      use, offer to sell, sell, import, and otherwise transfer the Work,
      where such license applies only to those patent claims licensable
      by such Contributor that are necessarily infringed by their
      Contribution(s) alone or by combination of their Contribution(s)
      with the Work to which such Contribution(s) was submitted. If You
      institute patent litigation against any entity (including a
      cross-claim or counterclaim in a lawsuit) alleging that the Work
      or a Contribution incorporated within the Work constitutes direct
      or contributory patent infringement, then any patent licenses
      granted to You under this License for that Work shall terminate
      as of the date such litigation is filed.

   4. Redistribution. You may reproduce and distribute copies of the
      Work or Derivative Works thereof in any medium, with or without
      modifications, and in Source or Object form, provided that You
      meet the following conditions:

      (a) You must give any other recipients of the Work or
          Derivative Works a copy of this License; and

      (b) You must cause any modified files to carry prominent notices
          stating that You changed the files; and

      (c) You must retain, in the Source form of any Derivative Works
          that You distribute, all copyright, patent, trademark, and
          attribution notices from the Source form of the Work,
          excluding those notices that do not pertain to any part of
          the Derivative Works; and

      (d) If the Work includes a "NOTICE" text file as part of its
          distribution, then any Derivative Works that You distribute must
          include a readable copy of the attribution notices contained
          within such NOTICE file, excluding those notices that do not
          pertain to any part of the Derivative Works, in at least one
          of the following places: within a NOTICE text file distributed
          as part of the Derivative Works; within the Source form or
          documentation, if provided along with the Derivative Works; or,
          within a display generated by the Derivative Works, if and
          wherever such third-party notices normally appear. The contents
          of the NOTICE file are for informational purposes only and
          do not modify the License. You may add Your own attribution
          notices within Derivative Works that You distribute, alongside
          or as an addendum to the NOTICE text from the Work, provided
          that such additional attribution notices cannot be construed
          as modifying the License.

      You may add Your own copyright statement to Your modifications and
      may provide additional or different license terms and conditions
      for use, reproduction, or distribution of Your modifications, or
      for any such Derivative Works as a whole, provided Your use,
      reproduction, and distribution of the Work otherwise complies with
      the conditions stated in this License.

   5. Submission of Contributions. Unless You explicitly state otherwise,
      any Contribution intentionally submitted for inclusion in the Work
      by You to the Licensor shall be under the terms and conditions of
      this License, without any additional terms or conditions.
      Notwithstanding the above, nothing herein shall supersede or modify
      the terms of any separate license agreement you may have executed
      with Licensor regarding such Contributions.

   6. Trademarks. This License does not grant permission to use the trade
      names, trademarks, service marks, or product names of the Licensor,
      except as required for reasonable and customary use in describing the
      origin of the Work and reproducing the content of the NOTICE file.

   7. Disclaimer of Warranty. Unless required by applicable law or
      agreed to in writing, Licensor provides the Work (and each
      Contributor provides its Contributions) on an "AS IS" BASIS,
      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
      implied, including, without limitation, any warranties or conditions
      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
      PARTICULAR PURPOSE. You are solely responsible for determining the
      appropriateness of using or redistributing the Work and assume any
      risks associated with Your exercise of permissions under this License.

   8. Limitation of Liability. In no event and under no legal theory,
      whether in tort (including negligence), contract, or otherwise,
      unless required by applicable law (such as deliberate and grossly
      negligent acts) or agreed to in writing, shall any Contributor be
      liable to You for damages, including any direct, indirect, special,
      incidental, or consequential damages of any character arising as a
      result of this License or out of the use or inability to use the
      Work (including but not limited to damages for loss of goodwill,
      work stoppage, computer failure or malfunction, or any and all
      other commercial damages or losses), even if such Contributor
      has been advised of the possibility of such damages.

   9. Accepting Warranty or Additional Liability. While redistributing
      the Work or Derivative Works thereof, You may choose to offer,
      and charge a fee for, acceptance of support, warranty, indemnity,
      or other liability obligations and/or rights consistent with this
      License. However, in accepting such obligations, You may act only
      on Your own behalf and on Your sole responsibility, not on behalf
      of any other Contributor, and only if You agree to indemnify,
      defend, and hold each Contributor harmless for any liability
      incurred by, or claims asserted against, such Contributor by reason
      of your accepting any such warranty or additional liability.


================================================
FILE: README.rst
================================================
===============================
bashate
===============================

A pep8 equivalent for bash scripts

This program attempts to be an automated style checker for bash scripts
to fill the same part of code review that pep8 does in most OpenStack
projects. It started from humble beginnings in the DevStack project,
and will continue to evolve over time.

The output format aims to follow `pycodestyle (pep8) default output format
<https://github.com/PyCQA/pycodestyle/blob/master/pycodestyle.py#L108>`_.


- Free software: Apache license
- Documentation: https://docs.openstack.org/bashate
- Source: https://opendev.org/openstack/bashate/
- Bugs: https://bugs.launchpad.net/bash8
- Release notes: https://docs.openstack.org/releasenotes/bashate/index.html
- Contributing: https://docs.openstack.org/bashate/latest/contributor/index.html

Currently Supported Checks
--------------------------

Errors
~~~~~~

Basic white space errors, for consistent indenting

- E001: check that lines do not end with trailing whitespace
- E002: ensure that indents are only spaces, and not hard tabs
- E003: ensure all indents are a multiple of 4 spaces
- E004: file did not end with a newline
- E005: file does not begin with #! or have a .sh prefix
- E006: check for lines longer than 79 columns

Structure Errors
~~~~~~~~~~~~~~~~

A set of rules that help keep things consistent in control blocks.
These are ignored on long lines that have a continuation, because
unrolling that is kind of "interesting"

- E010: *do* not on the same line as *for*
- E011: *then* not on the same line as *if* or *elif*
- E012: heredoc didn't end before EOF
- E020: Function declaration not in format ``^function name {$``

Obsolete, deprecated or unsafe syntax
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Rules to identify obsolete, deprecated or unsafe syntax that should
not be used

- E040: Syntax errors reported by `bash -n`
- E041: Usage of $[ for arithmetic is deprecated for $((
- E042: local declaration hides errors
- E043: arithmetic compound has inconsistent return semantics
- E044: Use [[ for =~,<,> comparisions


================================================
FILE: bashate/__init__.py
================================================
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.

import pbr.version


__version__ = pbr.version.VersionInfo(
    'bashate').version_string_with_vcs()


================================================
FILE: bashate/__main__.py
================================================
from bashate import main
import sys

if __name__ == "__main__":
    sys.exit(main())


================================================
FILE: bashate/bashate.py
================================================
#!/usr/bin/env python
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#    http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.

import argparse
import fileinput
import os
import re
import shlex
import subprocess
import sys

import bashate
from bashate import messages

MESSAGES = messages.MESSAGES


def is_continuation(line):
    return re.search(r'\\\s*$', line)


def check_for_do(line, report):
    if not is_continuation(line):
        match = re.match(r'^\s*(for|while|until)\s', line)
        if match:
            operator = match.group(1).strip()
            if operator == "for":
                # "for i in ..." and "for ((" is bash, but
                # "for (" is likely from an embedded awk script,
                # so skip it
                if re.search(r'for \([^\(]', line):
                    return
            if not re.search(r';\s*do$', line):
                report.print_error((MESSAGES['E010'].msg % operator), line)


def check_if_then(line, report):
    if not is_continuation(line):
        if re.search(r'^\s*(el)?if \[', line):
            if not re.search(r';\s*then$', line):
                report.print_error(MESSAGES['E011'].msg, line)


def check_no_trailing_whitespace(line, report):
    if re.search(r'[ \t]+$', line):
        report.print_error(MESSAGES['E001'].msg, line)


def check_no_long_lines(line, report, max_line_length):
    if len(line.rstrip("\r\n")) > max_line_length:
        report.print_error(MESSAGES['E006'].msg, line)


def check_indents(logical_line, report):
    # this is rather complex to handle argument offset indenting;
    # primarily done by emacs.  If there is an argument, it will try
    # to line up the following arguments underneath it, e.g.
    #   foobar_cmd bar baz \
    #              moo boo
    # Thus the offset in this case might not be a strict multiple of 4

    # Find the offset of the first argument of the command (if it has
    # one)
    m = re.search(r'^(?P<indent>[ \t]+)?(?P<cmd>\S+)(?P<ws>\s+)(?P<arg>\S+)',
                  logical_line[0])
    arg_offset = None
    if m:
        arg_offset = len(m.group('indent')) if m.group('indent') else 0
        arg_offset += len(m.group('cmd')) + len(m.group('ws'))

    # go through each line
    for lineno, line in enumerate(logical_line):
        m = re.search(r'^(?P<indent>[ \t]+)', line)
        if m:
            # no tabs, only spaces
            if re.search(r'\t', m.group('indent')):
                report.print_error(MESSAGES['E002'].msg, line)

            offset = len(m.group('indent'))

            # the first line and lines without an argument should be
            # offset by 4 spaces
            if (lineno == 0) or (arg_offset is None):
                if (offset % 4) != 0:
                    report.print_error(MESSAGES['E003'].msg, line)
            else:
                # other lines are allowed to line up with the first
                # argument, or be multiple-of 4 spaces
                if offset != arg_offset and (offset % 4) != 0:
                    report.print_error(MESSAGES['E003'].msg, line)


def check_function_decl(line, report):
    failed = False
    if line.startswith("function"):
        if not re.search(r'^function [\w-]* \{$', line):
            failed = True
    else:
        # catch the case without "function", e.g.
        # things like '^foo() {'
        if re.search(r'^\s*?\(\)\s*?\{', line):
            failed = True

    if failed:
        report.print_error(MESSAGES['E020'].msg, line)


def starts_heredoc(line):
    # note, watch out for <<EOF and <<'EOF' ; quotes in the
    # deliminator are part of syntax
    m = re.search(r"[^<]<<\s*([\'\"]?)(?P<token>\w+)([\'\"]?)", line)
    return m.group('token') if m else False


def end_of_heredoc(line, token):
    return token and re.search(r"^%s\s*$" % token, line)


def check_arithmetic(line, report):
    if "$[" in line:
        report.print_error(MESSAGES['E041'].msg, line)


def check_bare_arithmetic(line, report):
    if line.lstrip().startswith("(("):
        report.print_error(MESSAGES['E043'].msg, line)


def check_local_subshell(line, report):
    # XXX: should we increase the string checking to see if the $( is
    # anywhere with a string being set?  Risk of false positives?x
    if line.lstrip().startswith('local ') and \
       any(s in line for s in ('=$(', '=`', '="$(', '="`')):
        report.print_error(MESSAGES['E042'].msg, line)


def check_hashbang(line, filename, report):
    # this check only runs on the first line
    #  maybe this should check for shell?
    if (not filename.endswith(".sh") and not line.startswith("#!") and
       not os.path.basename(filename).startswith('.')):
        report.print_error(MESSAGES['E005'].msg, line)


def check_conditional_expression(line, report):
    # We're really starting to push the limits of what we can do without
    # a complete bash syntax parser here.  For example
    # > [[ $foo =~ " [ " ]] && [[ $bar =~ " ] " ]]
    # would be valid but mess up a simple regex matcher for "[.*]".
    # Let alone dealing with multiple-line-spanning etc...
    #
    # So we'll KISS and just look for simple, one line,
    # > if [ $foo =~ "bar" ]; then
    # type statements, which are the vast majority of typo errors.
    #
    # shlex is pretty helpful in getting us something we can walk to
    # find this pattern.  It does however have issues with
    # unterminated quotes on multi-line strings (e.g.)
    #
    # foo="bar   <-- we only see this bit in "line"
    #  baz"
    #
    # So we're just going to ignore parser failures here and move on.
    # Possibly in the future we could pull such multi-line strings
    # into "logical_line" below, and pass that here and have shlex
    # break that up.
    try:
        toks = shlex.shlex(line)
        toks.wordchars = "[]=~"
        toks = list(toks)
    except ValueError:
        return

    in_single_bracket = False
    for tok in toks:
        if tok == '[':
            in_single_bracket = True
        elif tok in ('=~', '<', '>') and in_single_bracket:
            report.print_error(MESSAGES['E044'].msg, line)
        elif tok == ']':
            in_single_bracket = False


def check_syntax(filename, report):
    # run the file through "bash -n" to catch basic syntax errors and
    # other warnings
    matches = []

    # sample lines we want to match:
    # foo.sh: line 4: warning: \
    #    here-document at line 1 delimited by end-of-file (wanted `EOF')
    # foo.sh: line 9: syntax error: unexpected end of file
    # foo.sh: line 7: syntax error near unexpected token `}'
    #
    # i.e. consistency with ":"'s isn't constant, so just do our
    # best...
    r = re.compile(
        '^(?P<file>.*): line (?P<lineno>[0-9]+): (?P<error>.*)')
    # we are parsing the error message, so force it to ignore the
    # system locale so we don't get messages in another language
    bash_environment = os.environ
    bash_environment['LC_ALL'] = 'C'
    proc = subprocess.Popen(
        ['bash', '-n', filename], stdout=subprocess.PIPE,
        stderr=subprocess.PIPE, env=bash_environment,
        universal_newlines=True)
    outputs = proc.communicate()

    for line in outputs[1].split('\n'):
        m = r.match(line)
        if m:
            matches.append(m)

    for m in matches:
        if 'syntax error' in m.group('error'):
            msg = '%s: %s' % (MESSAGES['E040'].msg, m.group('error'))
            report.print_error(msg, filename=filename,
                               filelineno=int(m.group('lineno')))

        # Matching output from bash warning about here-documents not
        # ending.
        # FIXME: are there other warnings that might come out
        # with "bash -n"?  A quick scan of the source code suggests
        # no, but there might be other interesting things we could
        # catch.
        if 'warning:' in m.group('error'):
            if 'delimited by end-of-file' in m.group('error'):
                start = re.match('^.*line (?P<start>[0-9]+).*$',
                                 m.group('error'))
                report.print_error(
                    MESSAGES['E012'].msg % int(start.group('start')),
                    filename=filename,
                    filelineno=int(m.group('lineno')))


class BashateRun(object):

    def __init__(self):
        self.error_count = 0
        self.error_list = None
        self.ignore_list = None
        self.warning_count = 0
        self.warning_list = None

    def register_ignores(self, ignores):
        if ignores:
            self.ignore_list = '^(' + '|'.join(ignores.split(',')) + ')'

    def register_warnings(self, warnings):
        if warnings:
            self.warning_list = '^(' + '|'.join(warnings.split(',')) + ')'

    def register_errors(self, errors):
        if errors:
            self.error_list = '^(' + '|'.join(errors.split(',')) + ')'

    def should_ignore(self, error):
        return self.ignore_list and re.search(self.ignore_list, error)

    def should_warn(self, error):
        # if in the errors list, overrides warning level
        if self.error_list and re.search(self.error_list, error):
            return False
        if messages.is_default_warning(error):
            return True
        return self.warning_list and re.search(self.warning_list, error)

    def print_error(self, error, line='',
                    filename=None, filelineno=None):
        if self.should_ignore(error):
            return

        warn = self.should_warn(error)

        if not filename:
            filename = fileinput.filename()
        if not filelineno:
            filelineno = fileinput.filelineno()
        if warn:
            self.warning_count = self.warning_count + 1
        else:
            self.error_count = self.error_count + 1

        self.log_error(error, line, filename, filelineno, warn)

    def log_error(self, error, line, filename, filelineno, warn=False):
        # following pycodestyle/pep8 default output format
        # https://github.com/PyCQA/pycodestyle/blob/master/pycodestyle.py#L108
        print("%(filename)s:%(filelineno)s:1: %(error)s" %
              {'filename': filename,
               'filelineno': filelineno,
               'error': error.replace(":", "", 1)})

    def check_files(self, files, verbose, max_line_length=79):
        logical_line = ""
        token = False

        # NOTE(mrodden): magic; replace with proper
        # report class when necessary
        report = self

        for fname in files:

            # reset world
            in_heredoc = False
            in_continuation = False

            # simple syntax checking, as files can pass style but still cause
            # syntax errors when you try to run them.
            check_syntax(fname, report)

            for line in fileinput.input(fname):
                if fileinput.isfirstline():

                    check_hashbang(line, fileinput.filename(), report)

                    if verbose:
                        print("Running bashate on %s" % fileinput.filename())

                # Don't run any tests on comment lines (but remember
                # inside a heredoc this might be part of the syntax of
                # an embedded script, just ignore that)
                if line.lstrip().startswith('#') and not in_heredoc:
                    logical_line = [line]
                    check_indents(logical_line, report)
                    continue

                # Strip trailing comments. From bash:
                #
                #   a word beginning with # causes that word and all
                #   remaining characters on that line to be ignored.
                #   ...
                #   A character that, when unquoted, separates
                #   words. One of the following: | & ; ( ) < > space
                #   tab
                #
                # for simplicity, we strip inline comments by
                # matching just '<space>#'.
                if not in_heredoc:
                    ll_split = line.split(' #', 1)
                    if len(ll_split) > 1:
                        line = ll_split[0].rstrip()

                # see if this starts a heredoc
                if not in_heredoc:
                    token = starts_heredoc(line)
                    if token:
                        in_heredoc = True
                        logical_line = [line]
                        continue

                # see if this starts a continuation
                if not in_continuation:
                    if is_continuation(line):
                        in_continuation = True
                        logical_line = [line]
                        continue

                # if we are in a heredoc or continuation, just loop
                # back and keep buffering the lines into
                # "logical_line" until the end of the
                # heredoc/continuation.
                if in_heredoc:
                    logical_line.append(line)
                    if not end_of_heredoc(line, token):
                        continue
                    else:
                        in_heredoc = False
                        # FIXME: if we want to do something with
                        # heredocs in the future, then the whole thing
                        # is now stored in logical_line.  for now,
                        # skip
                        continue
                elif in_continuation:
                    logical_line.append(line)
                    if is_continuation(line):
                        continue
                    else:
                        in_continuation = False
                else:
                    logical_line = [line]

                check_indents(logical_line, report)

                # at this point, logical_line is an array that holds
                # the whole continuation.  XXX : historically, we've
                # just handled every line in a continuation
                # separatley.  Stick with what works...
                for line in logical_line:
                    check_no_trailing_whitespace(line, report)
                    check_no_long_lines(line, report, max_line_length)
                    check_for_do(line, report)
                    check_if_then(line, report)
                    check_function_decl(line, report)
                    check_arithmetic(line, report)
                    check_local_subshell(line, report)
                    check_bare_arithmetic(line, report)
                    check_conditional_expression(line, report)

        # finished processing the file

        # last line should always end with a newline
        if not line.endswith('\n'):
            report.print_error(MESSAGES['E004'].msg, line)


def main(args=None):

    if args is None:
        args = sys.argv[1:]

    parser = argparse.ArgumentParser(
        description='A bash script style checker')
    parser.add_argument('files', metavar='file', nargs='*',
                        help='files to scan for errors')
    parser.add_argument('-i', '--ignore', help='Rules to ignore')
    parser.add_argument('-w', '--warn',
                        help='Rules to always warn (rather than error)')
    parser.add_argument('-e', '--error',
                        help='Rules to always error (rather than warn)')
    parser.add_argument('--max-line-length', default=79, type=int,
                        help='Max line length')
    parser.add_argument('-v', '--verbose', action='store_true', default=False)
    parser.add_argument('--version', action='store_true',
                        help='show bashate version number and exit',
                        default=False)
    parser.add_argument('-s', '--show', action='store_true', default=False)
    opts = parser.parse_args(args)

    if opts.version:
        print("bashate: %s" % bashate.__version__)
        sys.exit(0)

    if opts.show:
        messages.print_messages()
        sys.exit(0)

    files = opts.files
    if not files:
        parser.print_usage()
        return 1

    run = BashateRun()
    run.register_ignores(opts.ignore)
    run.register_warnings(opts.warn)
    run.register_errors(opts.error)

    try:
        run.check_files(files, opts.verbose, opts.max_line_length)
    except IOError as e:
        print("bashate: %s" % e)
        return 1

    if run.warning_count > 0:
        print("%d bashate warning(s) found" % run.warning_count)

    if run.error_count > 0:
        print("%d bashate error(s) found" % run.error_count)
        return 1

    return 0


if __name__ == "__main__":
    sys.exit(main())


================================================
FILE: bashate/messages.py
================================================
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#    http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.

import re
import textwrap


class _Message(object):
    """An individual bashate message.

    This should be accessed via the MESSAGES dict keyed by msg_id,
    e.g.

      from bashate.messages import MESSAGES
      print(MESSAGES['E123'].msg)

    :param msg_id: The unique message id (E...)
    :param msg_str: The short message string, as displayed in program
                     output
    :param long_msg: A longer more involved message, designed for
                     documentation
    """
    def __init__(self, msg_id, msg_str, long_msg, default):
        self.msg_id = msg_id
        self.msg_str = msg_str
        # clean-up from """ to a plain string
        if long_msg:
            self.long_msg = textwrap.dedent(long_msg)
            self.long_msg = self.long_msg.strip()
        else:
            self.long_msg = None
        self.default = default

    @property
    def msg(self):
        # For historical reasons, the code relies on "id: msg" so build
        # that up as .msg property for quick access.
        return "%s: %s" % (self.msg_id, self.msg_str)


_messages = {
    'E001': {
        'msg': 'Trailing Whitespace',
        'long_msg': None,
        'default': 'E'
    },
    'E002': {
        'msg': 'Tab indents',
        'long_msg':
        """
        Spaces are preferred to tabs in source files.
        """,
        'default': 'E'
    },
    'E003': {
        'msg': 'Indent not multiple of 4',
        'long_msg':
        """
        Four spaces should be used to offset logical blocks.
        """,
        'default': 'E'
    },
    'E004': {
        'msg': 'File did not end with a newline',
        'long_msg':
        """
        It is conventional to have a single newline ending files.
        """,
        'default': 'E'
    },
    'E005': {
        'msg': 'File does not begin with #! or have .sh prefix',
        'long_msg':
        """
        This can be useful for tools that use either the interpreter
        directive or the file-exension to select highlighting mode,
        syntax mode or determine MIME-type, such as file, gerrit and
        editors.
        """,
        'default': 'W'
    },
    'E006': {
        'msg': 'Line too long',
        'long_msg':
        """
        This check mimics the widely accepted convention from PEP8 and
        many other places that lines longer than a standard terminal width
        (default=79 columns) can not only cause problems when reading/writing
        code, but also often indicates a bad smell, e.g. too many levels
        of indentation due to overly complex functions which require
        refactoring into smaller chunks.
        """,
        'default': 'W'
    },
    'E010': {
        'msg': 'The "do" should be on same line as %s',
        'long_msg':
        """
        Ensure consistency of "do" directive being on the same line as
        it's command.  For example:

           for i in $(seq 1 100);
           do
              echo "hi"
           done

        will trigger this error
        """,
        'default': 'E'
    },
    'E011': {
        'msg': 'Then keyword is not on same line as if or elif keyword',
        'long_msg':
        """
        Similar to E010, this ensures consistency of if/elif statements
        """,
        'default': 'E'
    },
    'E012': {
        'msg': 'here-document at line %d delimited by end-of-file',
        'long_msg':
        """
        This check ensures the closure of heredocs (<<EOF directives).
        Bash will warn when a heredoc is delimited by end-of-file, but
        it is easily missed and can cause unexpected issues when a
        file is sourced.
        """,
        'default': 'E'
    },
    'E020': {
        'msg': 'Function declaration not in format ^function name {$',
        'long_msg':
        """
        There are several equivalent ways to define functions in Bash.
        This check is for consistency.
        """,
        'default': 'E'
    },
    'E040': {
        'msg': 'Syntax error',
        'long_msg':
        """
        `bash -n` determined that there was a syntax error preventing
        the script from parsing correctly and running.
        """,
        'default': 'E'
    },
    'E041': {
        'msg': 'Arithmetic expansion using $[ is deprecated for $((',
        'long_msg':
        """
        $[ is deprecated and not explained in the Bash manual.  $((
        should be used for arithmetic.
        """,
        'default': 'E'
    },
    'E042': {
        'msg': 'local declaration hides errors',
        'long_msg':
        """
        The return value of "local" is always 0; errors in subshells
        used for declaration are thus hidden and will not trigger "set -e".
        """,
        'default': 'W',
    },
    'E043': {
        'msg': 'Arithmetic compound has inconsistent return semantics',
        'long_msg':
        """
        The return value of ((expr)) is 1 if "expr" evalues to zero,
        otherwise 0.  Combined with "set -e", this can be quite
        confusing when something like ((counter++)) evaluates to zero,
        making the arithmetic evaluation return 1 and triggering the
        an error failure.  It is therefore best to use assignment with
        the $(( operator.
        """,
        'default': 'W',
    },
    'E044': {
        'msg': 'Use [[ for non-POSIX comparisions',
        'long_msg':
        """
        [ is the POSIX test operator, while [[ is the bash keyword
        comparision operator.  Comparisons such as =~, < and > require
        the use of [[.
        """,
        'default': 'E',
    },
}

MESSAGES = {}

_default_errors = []
_default_warnings = []

for k, v in _messages.items():
    MESSAGES[k] = _Message(k, v['msg'], v['long_msg'], v['default'])

    if v['default'] == 'E':
        _default_errors.append(k)
    if v['default'] == 'W':
        _default_warnings.append(k)

# convert this to the regex strings.  This looks a bit weird
# but it fits the current model of error/warning/ignore checking
# easily.
_default_errors = '^(' + '|'.join(_default_errors) + ')'
_default_warnings = '^(' + '|'.join(_default_warnings) + ')'


def is_default_error(error):
    return re.search(_default_errors, error)


def is_default_warning(error):
    return re.search(_default_warnings, error)


def print_messages():

    print("\nAvailable bashate checks")
    print("------------------------\n")
    for k, v in MESSAGES.items():
        print(" [%(default)s] %(id)s : %(string)s" % {
            'default': v.default,
            'id': v.msg_id,
            'string': v.msg_str})
        if v.long_msg:
            for msg_line in v.long_msg.split('\n'):
                print("            %s" % msg_line)
        print("")


================================================
FILE: bashate/tests/__init__.py
================================================


================================================
FILE: bashate/tests/base.py
================================================
# Copyright 2010-2011 OpenStack Foundation
# Copyright (c) 2013 Hewlett-Packard Development Company, L.P.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.

import os

import fixtures
import testtools

_TRUE_VALUES = ('True', 'true', '1', 'yes')


class TestCase(testtools.TestCase):
    """Test case base class for all unit tests."""

    def setUp(self):
        """Run before each test method to initialize test environment."""

        super(TestCase, self).setUp()
        test_timeout = os.environ.get('OS_TEST_TIMEOUT', 0)
        try:
            test_timeout = int(test_timeout)
        except ValueError:
            # If timeout value is invalid do not set a timeout.
            test_timeout = 0
        if test_timeout > 0:
            self.useFixture(fixtures.Timeout(test_timeout, gentle=True))

        self.useFixture(fixtures.NestedTempfile())
        self.useFixture(fixtures.TempHomeDir())

        if os.environ.get('OS_STDOUT_CAPTURE') in _TRUE_VALUES:
            stdout = self.useFixture(fixtures.StringStream('stdout')).stream
            self.useFixture(fixtures.MonkeyPatch('sys.stdout', stdout))
        if os.environ.get('OS_STDERR_CAPTURE') in _TRUE_VALUES:
            stderr = self.useFixture(fixtures.StringStream('stderr')).stream
            self.useFixture(fixtures.MonkeyPatch('sys.stderr', stderr))

        self.log_fixture = self.useFixture(fixtures.FakeLogger())


================================================
FILE: bashate/tests/samples/.E005_excluded
================================================
# this profile/hidden file doesn't start with #!
# and doesn't have a .sh extension

echo hi


================================================
FILE: bashate/tests/samples/E001_bad.sh
================================================
#!/bin/bash

# E001
somefunction args  


================================================
FILE: bashate/tests/samples/E002_bad.sh
================================================
#!/bin/bash

	echo "E002: Has a tab"


================================================
FILE: bashate/tests/samples/E003_bad.sh
================================================
#!/bin/bash

this is \
      bad continuation as it does not match 1st arg or %4

a \
 bad indent

if foo; then
    testing a \
  bad indent, indented
fi


================================================
FILE: bashate/tests/samples/E003_good.sh
================================================
#!/bin/bash

this is \
     a continuation \
     where the continued lines \
     align with the first argument

a \
    is a continuation where there is no \
    argument so we line-up to the default \
    4 spaces

if foo; then

    testing a \
            continuation indented
fi


================================================
FILE: bashate/tests/samples/E004_bad.sh
================================================
this file
has no
newline at end

================================================
FILE: bashate/tests/samples/E005_bad
================================================
# this file doesn't start with #!
# and doesn't have a .sh extension

echo hi


================================================
FILE: bashate/tests/samples/E006_bad.sh
================================================
#!/bin/bash

# lines longer than 79 columns

: 345678901234567890123456789012345678901234567890123456789012345678901234567890
:        1         2         3         4         5         6         7         8
# next line goes over by virtue of trailing whitespace
:        1         2         3         4         5         6         7          


================================================
FILE: bashate/tests/samples/E006_bad_custom_length.sh
================================================
#!/bin/bash

# lines longer than 10 columns give warnings

: 0123456789
:        1         2         3         4         5         6         7         8

: 012345


================================================
FILE: bashate/tests/samples/E006_good.sh
================================================
#!/bin/bash

# Allow lines 79 columns or shorter

: 34567890123456789012345678901234567890123456789012345678901234567890123456789
:        1         2         3         4         5         6         7

# and make sure we allow continuation lines >= 80 columns which are comprised
# of physical lines which are all <= 79 columns.
echo 678901234567890123456789012345678901234567890123456789012345678901234567 \
    567890123456789012345678901234567890123456789012345678901234567890123456789


================================================
FILE: bashate/tests/samples/E010_bad.sh
================================================
#!/bin/bash

while [ 0 ]
do
    zero
done

# for do done in one line
for [ 0 ]; do run_morethings; done


================================================
FILE: bashate/tests/samples/E010_good.sh
================================================
#!/bin/bash

# E010 good
while [ 0 ]; do
    run_things
done

# E010 with comment
while [ 0 ]; do # comment
    run_things
done


================================================
FILE: bashate/tests/samples/E011_bad.sh
================================================
#!/bin/bash

if [ 0 ]
then
    zero
elif [ 1 ]
then
    one
else
    default
fi

# if else fi in one line
if [ 0 ]; then run_morethings; else run_otherthings; fi


================================================
FILE: bashate/tests/samples/E011_good.sh
================================================
#!/bin/bash

# E011 good
if [ 0 ]; then
    run_morethings
else
    run_otherthings
fi

# E011 with comment
if [ 0 ]; then # comment
    run_morethings
fi


================================================
FILE: bashate/tests/samples/E012_bad.sh
================================================
#unexpected end-of-file on this
if foo; then

FOO=<<EOF
blah foo moo


# heredoc not ending



================================================
FILE: bashate/tests/samples/E040_syntax_error.sh
================================================
#!/bin/bash

function myfn {
    if [ '' == '' ]; then
        echo 'Things'
    fii
}


================================================
FILE: bashate/tests/samples/E041_bad.sh
================================================
#!/bin/bash

# E021
foo=$[ 1 + 1 ]


================================================
FILE: bashate/tests/samples/E042_bad.sh
================================================
function hello {
    local foo=$(ls)
}

function hello_too {
    local foo=`ls`
}

function hello_with_quotes {
    local foo="$(ls)"
    local bar="`ls`"
}

hello
hello_too


================================================
FILE: bashate/tests/samples/E043_bad.sh
================================================
count=0
things="0 1 0 0 1"

for i in $things; do
    if [ $i == "1" ]; then
        (( count++ ))
    fi
done

echo "Count is ${count}"


================================================
FILE: bashate/tests/samples/E044_bad.sh
================================================
# =~

if [ "test" =~ "]" ]; then
    echo "Does not work!"
fi

[ "test" =~ "string" ] && echo "Does not work!"

if [[ $foo == bar || "test" =~ "[" ]]; then
    echo "Does work!"
fi

[[ "test" =~ "string" ]] && echo "Does work"

# <

if [ 1 < '2' ]; then
    echo "Does not work!"
fi

[ 1 < 2 ] && echo "Does not work!"

if [[ 1 < 2 ]]; then
    echo "Does work!"
fi

[[ 1 < 2 ]] && echo "Does work"

# >

if [ 1 > 2 ]; then
    echo "Does not work!"
fi

[ 1 > 2 ] && echo "Does not work!"

if [[ 1 > 2 ]]; then
    echo "Does work!"
fi

[[ 1 > 2 ]] && echo "Does work"


================================================
FILE: bashate/tests/samples/comments.sh
================================================
#!/bin/bash

# make sure we're ignoring comments correctly

## multiple

# if [ foo ];
# then
#  echo "blah"
# fi

foo=1 # `test`

if [ foo ]; then # hello
    echo "hi"
fi

if [ foo ]; then ## hello ##
    echo "hi"
fi

# ``RST style comment``

 # ``indented comment`` (E003)

    # ``indented comment`` (4 spaces, ok)

	# ``indented comment`` (tab, E002)

#	tab comment


================================================
FILE: bashate/tests/samples/for_loops.sh
================================================
# for loop examples

# pass
for i in $(seq 1 5); do
    echo $i
done

# pass
for (( i = 0 ; i < 5 ; i++ )); do
    echo $i
done

# fail E010
for i in $(seq 1 5);
do
    echo $i
done

# fail E010
for (( i = 0 ; i < 5 ; i++ ));
do
    echo $i
done

# should ignore "for (" [note single parenthesis] as it is likely awk
awk '{
    for (i = 1; i < 5; i++)
        print $i
}' < /dev/null


================================================
FILE: bashate/tests/samples/heredoc_ignore.sh
================================================
#!/bin/bash

FOO=<<EOF

 this is a file
  that does not obey our indenting
 or our line length -------------------------------------------------

EOF

cat <<EOF > /tmp/tofile

 this is a file
  that does not obey our indenting
 or our line length -------------------------------------------------

EOF

cat << 'EOF' | sed 's/foo/bar'

 this is a file
  that does not obey our indenting
 or our line length -------------------------------------------------

EOF

cat <<"EOF"

 this is a file
  that does not obey our indenting
 or our line length -------------------------------------------------

EOF

cat > foo <<BLAH

 this is a file
  that does not obey our indenting
 or our line length -------------------------------------------------


BLAH


================================================
FILE: bashate/tests/samples/legacy_sample.sh
================================================
#!/bin/bash
# E020
function somefunction () {
	echo "E002: Has a tab"

  echo "E003: Not an indent with multiple of 4"
}

# E001
somefunction args  

# E010
for thing in things
do
    run_things thing
done

while 0
do
    run_thing
done

until 1
do
    run_thing
done

# E011
if [ 0 ]
then
    run_morethings
else
    run_otherthings
fi

# E012
cat <<EOH
this heredoc is bad

# E004

================================================
FILE: bashate/tests/test_bashate.py
================================================
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.

"""
test_bashate
----------------------------------

Tests for `bashate` module.
"""

from unittest import mock

from bashate import bashate
from bashate import messages
from bashate.tests import base


MESSAGES = messages.MESSAGES


class TestBashate(base.TestCase):

    def setUp(self):
        super(TestBashate, self).setUp()
        self.run = bashate.BashateRun()

    @mock.patch('bashate.bashate.BashateRun')
    def test_main_no_files(self, m_bashaterun):
        m_run_obj = mock.MagicMock()
        m_run_obj.error_count = 0
        m_run_obj.warning_count = 0
        m_bashaterun.return_value = m_run_obj

        result = bashate.main([])
        expected_return = 1
        self.assertEqual(expected_return, result)

    @mock.patch('bashate.bashate.BashateRun')
    def test_main_return_one_on_errors(self, m_bashaterun):
        m_run_obj = mock.MagicMock()
        m_run_obj.warning_count = 1
        m_run_obj.error_count = 1
        m_bashaterun.return_value = m_run_obj

        result = bashate.main([])
        expected_return = 1
        self.assertEqual(expected_return, result)

    @mock.patch('bashate.bashate.BashateRun')
    def test_main_return_one_on_ioerror(self, m_bashaterun):
        m_run_obj = mock.MagicMock()
        m_run_obj.error_count = 0
        m_run_obj.check_files = mock.Mock(side_effect=IOError)
        m_bashaterun.return_value = m_run_obj

        result = bashate.main(['--verbose',
                               '/path/to/fileA', '/path/to/fileB'])
        m_run_obj.check_files.assert_called_with(
            ['/path/to/fileA', '/path/to/fileB'],
            True,
            79
        )
        expected_return = 1
        self.assertEqual(expected_return, result)

    def test_multi_ignore_with_slash(self):
        self.run.register_ignores('E001|E011')
        bashate.check_no_trailing_whitespace("if ", self.run)
        bashate.check_if_then("if ", self.run)

        self.assertEqual(0, self.run.error_count)

    def test_multi_ignore_with_comma(self):
        self.run.register_ignores('E001,E011')
        bashate.check_no_trailing_whitespace("if ", self.run)
        bashate.check_if_then("if ", self.run)

        self.assertEqual(0, self.run.error_count)

    def test_multi_ignore_mixed(self):
        self.run.register_ignores('E001|E002,E003|E011')
        bashate.check_no_trailing_whitespace("if ", self.run)
        bashate.check_if_then("if ", self.run)
        bashate.check_indents("  echo", self.run)

        self.assertEqual(0, self.run.error_count)

    def test_ignore(self):
        self.run.register_ignores('E001')
        bashate.check_no_trailing_whitespace("if ", self.run)

        self.assertEqual(0, self.run.error_count)

    @mock.patch('bashate.bashate.BashateRun.print_error')
    def test_while_check_for_do(self, m_print_error):
        test_line = 'while `do something args`'
        bashate.check_for_do(test_line, self.run)

        m_print_error.assert_called_once_with(
            MESSAGES['E010'].msg % 'while', test_line)


class TestBashateSamples(base.TestCase):
    """End to end regression testing of bashate against script samples."""

    def setUp(self):
        super(TestBashateSamples, self).setUp()
        log_error_patcher = mock.patch(
            'bashate.bashate.BashateRun.log_error')
        self.m_log_error = log_error_patcher.start()
        self.run = bashate.BashateRun()
        self.addCleanup(log_error_patcher.stop)

    def assert_error_found(self, error, lineno):
        error_found = False
        for call in self.m_log_error.call_args_list:
            # unwrap args
            args = call[0]
            if (args[0].startswith(error) and lineno == args[3]):
                error_found = True
        if not error_found:
            self.fail('Error %s expected at line %d not found!' %
                      (error, lineno))

    def test_sample_E001(self):
        test_files = ['bashate/tests/samples/E001_bad.sh']
        self.run.check_files(test_files, False)

        self.assert_error_found('E001', 4)

    def test_sample_E002(self):
        test_files = ['bashate/tests/samples/E002_bad.sh']
        self.run.check_files(test_files, False)

        self.assert_error_found('E002', 3)

    def test_sample_E003(self):
        test_files = ['bashate/tests/samples/E003_good.sh']
        self.run.check_files(test_files, False)
        self.assertEqual(0, self.run.error_count)

    def test_sample_E003_bad(self):
        test_files = ['bashate/tests/samples/E003_bad.sh']
        self.run.check_files(test_files, False)
        self.assert_error_found('E003', 4)
        self.assert_error_found('E003', 7)
        self.assert_error_found('E003', 11)

    def test_sample_E004_bad(self):
        test_files = ['bashate/tests/samples/E004_bad.sh']
        self.run.check_files(test_files, False)
        self.assert_error_found('E004', 3)

    def test_sample_E006_bad(self):
        test_files = ['bashate/tests/samples/E006_bad.sh']
        self.run.check_files(test_files, False)

        self.assertEqual(self.run.warning_count, 3)
        self.assert_error_found('E006', 5)
        self.assert_error_found('E006', 6)
        self.assert_error_found('E006', 8)

    def test_sample_E006_bad_ignore_trailing_ws(self):
        self.run.register_ignores('E001')
        test_files = ['bashate/tests/samples/E006_bad.sh']
        self.run.check_files(test_files, False)

        self.assertEqual(self.run.warning_count, 3)
        self.assert_error_found('E006', 5)
        self.assert_error_found('E006', 6)
        self.assert_error_found('E006', 8)

    def test_sample_E006_bad_custom_max_line_length(self):
        test_files = ['bashate/tests/samples/E006_bad_custom_length.sh']
        self.run.check_files(test_files, False, 10)

        self.assertEqual(self.run.warning_count, 2)
        self.assert_error_found('E006', 5)
        self.assert_error_found('E006', 6)

    def test_sample_E006_good(self):
        test_files = ['bashate/tests/samples/E006_good.sh']
        self.run.check_files(test_files, False)

        self.assertEqual(self.run.warning_count, 0)

    def test_sample_E010_good(self):
        test_files = ['bashate/tests/samples/E010_good.sh']
        self.run.check_files(test_files, False)

        self.assertEqual(self.run.error_count, 0)

    def test_sample_E010(self):
        test_files = ['bashate/tests/samples/E010_bad.sh']
        self.run.check_files(test_files, False)

        self.assert_error_found('E010', 3)
        self.assert_error_found('E010', 9)

    def test_sample_E011_good(self):
        test_files = ['bashate/tests/samples/E011_good.sh']
        self.run.check_files(test_files, False)

        self.assertEqual(self.run.error_count, 0)

    def test_sample_E011(self):
        test_files = ['bashate/tests/samples/E011_bad.sh']
        self.run.check_files(test_files, False)

        self.assert_error_found('E011', 3)
        self.assert_error_found('E011', 6)

    def test_sample_E012(self):
        test_files = ['bashate/tests/samples/E012_bad.sh']
        self.run.check_files(test_files, False)

        self.assert_error_found('E012', 9)
        self.assert_error_found('E040', 10)

    def test_sample_E041(self):
        test_files = ['bashate/tests/samples/E041_bad.sh']
        self.run.check_files(test_files, False)

        self.assert_error_found('E041', 4)

    def test_sample_E042(self):
        test_files = ['bashate/tests/samples/E042_bad.sh']
        self.run.register_errors('E042')
        self.run.check_files(test_files, False)

        self.assert_error_found('E042', 2)
        self.assert_error_found('E042', 6)
        self.assert_error_found('E042', 10)
        self.assert_error_found('E042', 11)

    def test_sample_E043(self):
        test_files = ['bashate/tests/samples/E043_bad.sh']
        self.run.register_errors('E043')
        self.run.check_files(test_files, False)

        self.assert_error_found('E043', 6)

    def test_sample_for_loops(self):
        test_files = ['bashate/tests/samples/for_loops.sh']
        self.run.check_files(test_files, False)

        self.assert_error_found('E010', 14)
        self.assert_error_found('E010', 20)

    def test_sample_comments(self):
        test_files = ['bashate/tests/samples/comments.sh']
        self.run.check_files(test_files, False)

        self.assert_error_found('E003', 24)
        self.assert_error_found('E002', 28)
        self.assert_error_found('E003', 28)
        self.assertEqual(3, self.run.error_count)

    def test_sample_E005(self):
        test_files = ['bashate/tests/samples/E005_bad']
        self.run.register_errors('E005')
        self.run.check_files(test_files, False)

        self.assert_error_found('E005', 1)

    def test_sample_E005_excluded(self):
        test_files = ['bashate/tests/samples/.E005_excluded']
        self.run.check_files(test_files, False)

        self.assertEqual(0, self.run.error_count)

    def test_sample_E040(self):
        test_files = ['bashate/tests/samples/E040_syntax_error.sh']
        self.run.register_errors('E040')
        self.run.check_files(test_files, False)

        self.assert_error_found('E040', 7)

    def test_sample_E044(self):
        test_files = ['bashate/tests/samples/E044_bad.sh']
        self.run.check_files(test_files, False)

        self.assert_error_found('E044', 3)
        self.assert_error_found('E044', 7)
        self.assert_error_found('E044', 17)
        self.assert_error_found('E044', 21)
        self.assert_error_found('E044', 31)
        self.assert_error_found('E044', 35)

    def test_sample_warning(self):
        # reuse a couple of the above files to make sure we turn
        # errors down to warnings if requested
        test_files = ['bashate/tests/samples/E011_bad.sh',
                      'bashate/tests/samples/E041_bad.sh']
        self.run.register_warnings('E011,E041')
        self.run.check_files(test_files, False)

        self.assertEqual(0, self.run.error_count)
        self.assertEqual(4, self.run.warning_count)

    def test_ignore_heredoc(self):
        test_files = ['bashate/tests/samples/heredoc_ignore.sh']
        self.run.check_files(test_files, False)
        self.assertEqual(0, self.run.error_count)

    def test_pre_zero_dot_one_sample_file(self):
        """Test the sample file with all pre 0.1.0 release checks.

        This is a legacy compatibility check to make sure we still
        catch the same errors as we did before the first 0.1.0
        release of the bashate pypi package. There were no tests
        before this, so it is our baseline regression check.

        New checks shouldn't need to be added here, and should
        have their own separate unit test and/or sample file checks.
        """

        test_files = ['bashate/tests/samples/legacy_sample.sh']
        self.run.check_files(test_files, False)

        expected_errors = [
            ('E002', 4),
            ('E003', 6),
            ('E001', 10),
            ('E010', 13),
            ('E010', 18),
            ('E010', 23),
            ('E011', 29),
            ('E020', 3)
        ]

        for error in expected_errors:
            self.assert_error_found(*error)


================================================
FILE: bindep.txt
================================================
# This is a cross-platform list tracking distribution packages needed by tests;
# see http://docs.openstack.org/infra/bindep/ for additional information.
# PDF Docs package dependencies
tex-gyre [doc platform:dpkg]


================================================
FILE: doc/requirements.txt
================================================
# The order of packages is significant, because pip processes them in the order
# of appearance. Changing the order has an impact on the overall integration
# process, which may cause wedges in the gate later.

sphinx>=2.0.0,!=2.1.0 # BSD
openstackdocstheme>=2.2.1 # Apache-2.0
reno>=3.1.0 # Apache-2.0


================================================
FILE: doc/source/conf.py
================================================
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#    http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
# implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import os
import sys

sys.path.insert(0, os.path.abspath('../..'))
# -- General configuration ----------------------------------------------------

# Add any Sphinx extension module names here, as strings. They can be
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom ones.
extensions = [
    'sphinx.ext.autodoc',
    #'sphinx.ext.intersphinx',
    'openstackdocstheme',
    'reno.sphinxext'
]

# autodoc generation is a bit aggressive and a nuisance when doing heavy
# text edit cycles.
# execute "export SPHINX_DEBUG=1" in your terminal to disable

# The suffix of source filenames.
source_suffix = '.rst'

# The master toctree document.
master_doc = 'index'

# General information about the project.
project = 'bashate'
copyright = '2017, Bashate Authors'

# If true, '()' will be appended to :func: etc. cross-reference text.
add_function_parentheses = True

# If true, the current module name will be prepended to all description
# unit titles (such as .. function::).
add_module_names = True

# The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'native'

# openstackdocstheme options
openstackdocs_repo_name = 'openstack-dev/bashate'
openstackdocs_bug_project = 'bashate'
openstackdocs_bug_tag = ''
openstackdocs_pdf_link = True

# Grouping the document tree for man pages.
# List of tuples 'sourcefile', 'target', 'title', 'Authors name', 'manual'
man_pages = [
    ('man/bashate', 'bashate', 'Style checker for bash scripts',
     ['OpenStack Foundation'], 1),
]


# -- Options for HTML output --------------------------------------------------

# The theme to use for HTML and HTML Help pages.  Major themes that come with
# Sphinx are currently 'default' and 'sphinxdoc'.
# html_theme = '_theme'
# html_static_path = ['static']

html_theme = 'openstackdocs'

# Output file base name for HTML help builder.
htmlhelp_basename = '%sdoc' % project

# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title, author, documentclass
# [howto/manual]).
latex_documents = [
    ('index',
     'doc-%s.tex' % project,
     'Bashate Documentation',
     'Bashate Authors', 'manual'),
]

# Example configuration for intersphinx: refer to the Python standard library.
#intersphinx_mapping = {'http://docs.python.org/': None}
latex_use_xindy = False
latex_elements = {
    'extraclassoptions': 'openany,oneside',
}


================================================
FILE: doc/source/contributor/contributing.rst
================================================
============================
So You Want to Contribute...
============================

For general information on contributing to OpenStack, please check out the
`contributor guide <https://docs.openstack.org/contributors/>`_ to get started.
It covers all the basics that are common to all OpenStack projects: the accounts
you need, the basics of interacting with our Gerrit review system, how we
communicate as a community, etc.

Below will cover the more project specific information you need to get started
with Bashate.

Communication
~~~~~~~~~~~~~
* IRC channel ``#openstack-qa`` at OFTC
* Mailing list (prefix subjects with ``[qa]`` for faster responses)
  http://lists.openstack.org/cgi-bin/mailman/listinfo/openstack-discuss

Contacting the Core Team
~~~~~~~~~~~~~~~~~~~~~~~~
Please refer to the `Bashate Core Team
<https://review.opendev.org/#/admin/groups/333,members>`_ contacts.

New Feature Planning
~~~~~~~~~~~~~~~~~~~~
If you want to propose a new feature please read `Feature Proposal Process`_

Task Tracking
~~~~~~~~~~~~~
We track our tasks in `Launchpad <https://bugs.launchpad.net/bash8>`__.

Reporting a Bug
~~~~~~~~~~~~~~~
You found an issue and want to make sure we are aware of it? You can do so on
`Launchpad <https://bugs.launchpad.net/bash8/+filebug>`__.
More info about Launchpad usage can be found on `OpenStack docs page
<https://docs.openstack.org/contributors/common/task-tracking.html#launchpad>`_

Getting Your Patch Merged
~~~~~~~~~~~~~~~~~~~~~~~~~
All changes proposed to the Bashate requires single ``Code-Review +2`` votes as minimum from
Bashate core reviewers who can approve patch by giving ``Workflow +1`` vote.

Project Team Lead Duties
~~~~~~~~~~~~~~~~~~~~~~~~
All common PTL duties are enumerated in the `PTL guide
<https://docs.openstack.org/project-team-guide/ptl.html>`_.

The Release Process for QA is documented in `QA Release Process
<https://wiki.openstack.org/wiki/QA/releases>`_.

.. _Feature Proposal Process: https://wiki.openstack.org/wiki/QA#Feature_Proposal_.26_Design_discussions


================================================
FILE: doc/source/contributor/index.rst
================================================
============
Contributing
============

.. toctree::
   :maxdepth: 2

   contributing.rst


================================================
FILE: doc/source/index.rst
================================================
===================================
Welcome to bashate's documentation!
===================================

.. toctree::
   :maxdepth: 2

   readme
   install/index.rst
   user/index.rst
   contributor/index.rst

Indices and tables
==================

* :ref:`genindex`
* :ref:`modindex`
* :ref:`search`


================================================
FILE: doc/source/install/index.rst
================================================
============
Installation
============

At the command line::

    $ pip install bashate

Or, if you have virtualenvwrapper installed::

    $ mkvirtualenv bashate
    $ pip install bashate


================================================
FILE: doc/source/man/bashate.rst
================================================
===========================
:program:`bashate` man page
===========================

.. program:: bashate
.. highlight:: bash

SYNOPSIS
========

:program:`bashate` [options] <file> [files...]

DESCRIPTION
===========

The :program:`bashate` command line utility is a style-checker for
bash scripts.

The name is derived from :program:`pep8`, a Python lint-type tool.

OPTIONS
=======

--help, -h        Print help
--verbose, -v     Verbose output
--ignore, -i      Tests to ignore, comma separated
--error, -e       Tests to trigger errors instead of warnings, comma separated
--warn, -w        Tests to trigger warnings instead of errors, comma separated

EXAMPLES
========

Run all tests on a single file::

    bashate file.sh

Run tests on several files, while also ignoring several errors::

    bashate -i E010,E011 file.sh file2.sh

BUGS
====

http://bugs.launchpad.net/bash8


================================================
FILE: doc/source/readme.rst
================================================
.. include:: ../../README.rst

See also
~~~~~~~~

See also :doc:`/man/bashate`.


================================================
FILE: doc/source/user/index.rst
================================================
=============
Using bashate
=============

.. toctree::
   :maxdepth: 2

   usage.rst
   ../man/bashate.rst



================================================
FILE: doc/source/user/usage.rst
================================================
========
Usage
========

To use bashate in a project::

	import bashate


================================================
FILE: playbooks/bashate-devstack-master/run.yaml
================================================
- hosts: all
  name: Run bashate against devstack master
  roles:
    - bindep
    - role: ensure-tox
      ensure_global_symlinks: true

  tasks:
    - shell: 'tox -e bashate'
      args:
        executable: /bin/bash
        chdir: '{{ ansible_user_dir }}/{{ zuul.projects["opendev.org/openstack/devstack"].src_dir }}'
      environment:
        BASHATE_INSTALL_PATH: 'file://{{ ansible_user_dir }}/{{ zuul.project.src_dir }}'



================================================
FILE: releasenotes/notes/0-dash-6-748e729ee001df73.yaml
================================================
---
features:
  - Python 3.6 support added
  - Hidden files such as ``.bashrc`` are no longer checked for ``#!`` (E005)
  - A basic check for ``[[`` when using non-POSIX comparisions such as
    ``=~`` is added
  - Enable bashate to be called as a module ``python -m bashate ...``
  - Enable `pre-commit.com <https://pre-commit.com>`__ support

================================================
FILE: releasenotes/notes/adopt-pycodestyle-output-format-f4d6e35dadfcb6f9.yaml
================================================
---
features:
  - |
    Adoped pycodestyle/pep8 default output format.


================================================
FILE: releasenotes/notes/custom-line-length-083e8077951a8ead.yaml
================================================
---
features:
  - |
    Adds an option ``--max-line-length`` to specify the maximum length
    of lines for check E006.


================================================
FILE: releasenotes/notes/drop-python2.7-064c5e5bcfb4539c.yaml
================================================
---
deprecations:
  - |
    bashate is now Python 3 only and no longer supports Python 2.

================================================
FILE: releasenotes/notes/heredoc-ignore-905b29053652f90e.yaml
================================================
---
fixes:

  - Ignore contents of ``heredoc`` values.  ``heredocs`` usually
    contain content in a foreign syntax so ``bashate`` will no longer
    consider them.

  - Continuation lines are now parsed into an array, rather than a
    single logical-line.  This fixes continuation lines being
    incorrectly reported as too long.

  - |
    Indentation now allows emacs-formatted idents, where continuation
    lines for long commands align to the first argument above (rather
    than a strict modulo of 4).  e.g.

    ::

       longcommand arg1 arg2 arg3 \
                   arg4 arg5

    will no longer trigger a bad indent warning.

  - Use ``bash -n`` to detect unclosed heredocs, rather than construct
    our own parsing.

  - Correctly check for newlines at the end of all files; even if you
    only specify one file to check.


================================================
FILE: releasenotes/notes/python-3-4e30b9f2b9e2dcb7.yaml
================================================
---
features:

  - Python 3 is supported

================================================
FILE: releasenotes/notes/start-using-reno-eaaafddb3fbf2010.yaml
================================================
---
other:
  - started using reno


================================================
FILE: releasenotes/source/conf.py
================================================
# -*- coding: utf-8 -*-
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#    http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
# implied.
# See the License for the specific language governing permissions and
# limitations under the License.

# Bashate Release Notes documentation build configuration file, created by
# sphinx-quickstart on Tue Nov  3 17:40:50 2015.
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# All configuration values have a default; values that are commented out
# serve to show the default.

# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
# sys.path.insert(0, os.path.abspath('.'))

# -- General configuration ------------------------------------------------

# If your documentation needs a minimal Sphinx version, state it here.
# needs_sphinx = '1.0'

# Add any Sphinx extension module names here, as strings. They can be
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
# ones.
extensions = [
    'openstackdocstheme',
    'reno.sphinxext',
]

# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']

# The suffix of source filenames.
source_suffix = '.rst'

# The encoding of source files.
# source_encoding = 'utf-8-sig'

# The master toctree document.
master_doc = 'index'

# General information about the project.
project = 'Bashate Release Notes'
copyright = '2017, Bashate Developers'

# Release notes are version independent
# The full version, including alpha/beta/rc tags.
release = ''
# The short X.Y version.
version = ''

# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
# language = None

# There are two options for replacing |today|: either, you set today to some
# non-false value, then it is used:
# today = ''
# Else, today_fmt is used as the format for a strftime call.
# today_fmt = '%B %d, %Y'

# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
exclude_patterns = []

# The reST default role (used for this markup: `text`) to use for all
# documents.
# default_role = None

# If true, '()' will be appended to :func: etc. cross-reference text.
# add_function_parentheses = True

# If true, the current module name will be prepended to all description
# unit titles (such as .. function::).
# add_module_names = True

# If true, sectionauthor and moduleauthor directives will be shown in the
# output. They are ignored by default.
# show_authors = False

# The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'native'

# A list of ignored prefixes for module index sorting.
# modindex_common_prefix = []

# If true, keep warnings as "system message" paragraphs in the built documents.
# keep_warnings = False

# openstackdocstheme options
openstackdocs_repo_name = 'openstack-dev/bashate'
openstackdocs_bug_project = 'bashate'
openstackdocs_bug_tag = ''
openstackdocs_auto_name = False

# -- Options for HTML output ----------------------------------------------

# The theme to use for HTML and HTML Help pages.  See the documentation for
# a list of builtin themes.
html_theme = 'openstackdocs'

# Theme options are theme-specific and customize the look and feel of a theme
# further.  For a list of options available for each theme, see the
# documentation.
# html_theme_options = {}

# Add any paths that contain custom themes here, relative to this directory.
# html_theme_path = []

# The name for this set of Sphinx documents.  If None, it defaults to
# "<project> v<release> documentation".
# html_title = None

# A shorter title for the navigation bar.  Default is the same as html_title.
# html_short_title = None

# The name of an image file (relative to this directory) to place at the top
# of the sidebar.
# html_logo = None

# The name of an image file (within the static path) to use as favicon of the
# docs.  This file should be a Windows icon file (.ico) being 16x16 or 32x32
# pixels large.
# html_favicon = None

# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
# html_static_path = ['_static']

# Add any extra paths that contain custom files (such as robots.txt or
# .htaccess) here, relative to this directory. These files are copied
# directly to the root of the documentation.
# html_extra_path = []

# If true, SmartyPants will be used to convert quotes and dashes to
# typographically correct entities.
# html_use_smartypants = True

# Custom sidebar templates, maps document names to template names.
# html_sidebars = {}

# Additional templates that should be rendered to pages, maps page names to
# template names.
# html_additional_pages = {}

# If false, no module index is generated.
# html_domain_indices = True

# If false, no index is generated.
# html_use_index = True

# If true, the index is split into individual pages for each letter.
# html_split_index = False

# If true, links to the reST sources are added to the pages.
# html_show_sourcelink = True

# If true, "Created using Sphinx" is shown in the HTML footer. Default is True.
# html_show_sphinx = True

# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True.
# html_show_copyright = True

# If true, an OpenSearch description file will be output, and all pages will
# contain a <link> tag referring to it.  The value of this option must be the
# base URL from which the finished HTML is served.
# html_use_opensearch = ''

# This is the file name suffix for HTML files (e.g. ".xhtml").
# html_file_suffix = None

# Output file base name for HTML help builder.
htmlhelp_basename = 'BashateReleaseNotesdoc'


# -- Options for LaTeX output ---------------------------------------------

latex_elements = {
    # The paper size ('letterpaper' or 'a4paper').
    # 'papersize': 'letterpaper',

    # The font size ('10pt', '11pt' or '12pt').
    # 'pointsize': '10pt',

    # Additional stuff for the LaTeX preamble.
    # 'preamble': '',
}

# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title,
#  author, documentclass [howto, manual, or own class]).
latex_documents = [
    ('index', 'BashateReleaseNotes.tex',
     'Bashate Release Notes Documentation',
     'Bashate Developers', 'manual'),
]

# The name of an image file (relative to this directory) to place at the top of
# the title page.
# latex_logo = None

# For "manual" documents, if this is true, then toplevel headings are parts,
# not chapters.
# latex_use_parts = False

# If true, show page references after internal links.
# latex_show_pagerefs = False

# If true, show URL addresses after external links.
# latex_show_urls = False

# Documents to append as an appendix to all manuals.
# latex_appendices = []

# If false, no module index is generated.
# latex_domain_indices = True


# -- Options for manual page output ---------------------------------------

# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
man_pages = [
    ('index', 'bashatereleasenotes', 'Bashate Release Notes Documentation',
     ['Bashate Developers'], 1)
]

# If true, show URL addresses after external links.
# man_show_urls = False


# -- Options for Texinfo output -------------------------------------------

# Grouping the document tree into Texinfo files. List of tuples
# (source start file, target name, title, author,
#  dir menu entry, description, category)
texinfo_documents = [
    ('index', 'BashateReleaseNotes', 'Bashate Release Notes Documentation',
     'Bashate Developers', 'BashateReleaseNotes',
     'Style Checker for Bash.',
     'Miscellaneous'),
]

# Documents to append as an appendix to all manuals.
# texinfo_appendices = []

# If false, no module index is generated.
# texinfo_domain_indices = True

# How to display URL addresses: 'footnote', 'no', or 'inline'.
# texinfo_show_urls = 'footnote'

# If true, do not generate a @detailmenu in the "Top" node's menu.
# texinfo_no_detailmenu = False

# -- Options for Internationalization output ------------------------------
locale_dirs = ['locale/']


================================================
FILE: releasenotes/source/index.rst
================================================
=====================
bashate Release Notes
=====================

.. release-notes::


================================================
FILE: requirements.txt
================================================
pbr!=2.1.0,>=2.0.0 # Apache-2.0


================================================
FILE: setup.cfg
================================================
[metadata]
name = bashate
summary = A pep8 equivalent for bash scripts
description_file =
    README.rst
author = OpenStack
author_email = openstack-discuss@lists.openstack.org
home_page = https://docs.openstack.org/bashate/latest/
python_requires = >=3.5
classifier =
    Environment :: OpenStack
    Intended Audience :: Information Technology
    Intended Audience :: System Administrators
    License :: OSI Approved :: Apache Software License
    Operating System :: POSIX :: Linux
    Programming Language :: Python
    Programming Language :: Python :: Implementation :: CPython
    Programming Language :: Python :: 3 :: Only
    Programming Language :: Python :: 3
    Programming Language :: Python :: 3.5
    Programming Language :: Python :: 3.6
    Programming Language :: Python :: 3.7
    Programming Language :: Python :: 3.8
    Programming Language :: Python :: 3.9
    Programming Language :: Python :: 3.10
    Programming Language :: Python :: 3.11

[files]
packages =
    bashate

[entry_points]
console_scripts =
    bashate = bashate.bashate:main


================================================
FILE: setup.py
================================================
# Copyright (c) 2013 Hewlett-Packard Development Company, L.P.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#    http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
# implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import setuptools

setuptools.setup(
    setup_requires=['pbr>=1.8'],
    pbr=True)


================================================
FILE: test-requirements.txt
================================================
hacking>=4.1.0,<4.2.0;python_version<'3.8' # Apache-2.0
hacking>=7.0.0,<7.1.0;python_version>='3.8' # Apache-2.0

coverage>=3.6
discover
fixtures>=1.3.1
python-subunit>=0.0.18
testtools>=2.2.0
stestr>=1.0.0 # Apache-2.0


================================================
FILE: tox.ini
================================================
[tox]
minversion = 3.18.0
envlist = py36,py39,pep8
skipsdist = True
ignore_basepython_conflict = True

[testenv]
basepython = python3
usedevelop = True
setenv =
   VIRTUAL_ENV={envdir}
allowlist_externals = *
deps = -r{toxinidir}/requirements.txt
       -r{toxinidir}/test-requirements.txt
commands =
   stestr run --slowest {posargs}

[testenv:pep8]
commands = flake8

[testenv:docs]
deps = -r{toxinidir}/doc/requirements.txt
commands = sphinx-build -a -W -E -b html doc/source doc/build/html

[testenv:pdf-docs]
deps = {[testenv:docs]deps}
allowlist_externals =
   make
commands =
   sphinx-build -W -b latex doc/source doc/build/pdf
   make -C doc/build/pdf

[testenv:venv]
commands = {posargs}

[testenv:cover]
setenv =
  PYTHON=coverage run --source bashate --parallel-mode
commands =
  coverage erase
  find . -type f -name "*.pyc" -delete
  stestr --test-path ./bashate/tests run {posargs}
  coverage combine
  coverage html -d cover
  coverage xml -o cover/coverage.xml
  coverage report

[testenv:releasenotes]
deps = {[testenv:docs]deps}
commands = sphinx-build -a -W -E -d releasenotes/build/doctrees -b html releasenotes/source releasenotes/build/html

[flake8]
# E123, E125 skipped as they are invalid PEP-8.

show-source = True
ignore = E123,E125,W504
builtins = _
exclude=.venv,.git,.tox,dist,doc,*lib/python*,*egg,build

# This environment can be used to quickly validate that all needed system
# packages required to successfully execute test targets are installed
[testenv:bindep]
# Do not install any requirements. We want this to be fast and work even if
# system dependencies are missing, since it's used to tell you what system
# dependencies are missing! This also means that bindep must be installed
# separately, outside of the requirements files.
deps = bindep
commands = bindep test
Download .txt
gitextract_das1educ/

├── .coveragerc
├── .gitignore
├── .gitreview
├── .mailmap
├── .pre-commit-hooks.yaml
├── .stestr.conf
├── .zuul.d/
│   └── jobs.yaml
├── CONTRIBUTING.rst
├── HACKING.rst
├── LICENSE
├── README.rst
├── bashate/
│   ├── __init__.py
│   ├── __main__.py
│   ├── bashate.py
│   ├── messages.py
│   └── tests/
│       ├── __init__.py
│       ├── base.py
│       ├── samples/
│       │   ├── .E005_excluded
│       │   ├── E001_bad.sh
│       │   ├── E002_bad.sh
│       │   ├── E003_bad.sh
│       │   ├── E003_good.sh
│       │   ├── E004_bad.sh
│       │   ├── E005_bad
│       │   ├── E006_bad.sh
│       │   ├── E006_bad_custom_length.sh
│       │   ├── E006_good.sh
│       │   ├── E010_bad.sh
│       │   ├── E010_good.sh
│       │   ├── E011_bad.sh
│       │   ├── E011_good.sh
│       │   ├── E012_bad.sh
│       │   ├── E040_syntax_error.sh
│       │   ├── E041_bad.sh
│       │   ├── E042_bad.sh
│       │   ├── E043_bad.sh
│       │   ├── E044_bad.sh
│       │   ├── comments.sh
│       │   ├── for_loops.sh
│       │   ├── heredoc_ignore.sh
│       │   └── legacy_sample.sh
│       └── test_bashate.py
├── bindep.txt
├── doc/
│   ├── requirements.txt
│   └── source/
│       ├── conf.py
│       ├── contributor/
│       │   ├── contributing.rst
│       │   └── index.rst
│       ├── index.rst
│       ├── install/
│       │   └── index.rst
│       ├── man/
│       │   └── bashate.rst
│       ├── readme.rst
│       └── user/
│           ├── index.rst
│           └── usage.rst
├── playbooks/
│   └── bashate-devstack-master/
│       └── run.yaml
├── releasenotes/
│   ├── notes/
│   │   ├── 0-dash-6-748e729ee001df73.yaml
│   │   ├── adopt-pycodestyle-output-format-f4d6e35dadfcb6f9.yaml
│   │   ├── custom-line-length-083e8077951a8ead.yaml
│   │   ├── drop-python2.7-064c5e5bcfb4539c.yaml
│   │   ├── heredoc-ignore-905b29053652f90e.yaml
│   │   ├── python-3-4e30b9f2b9e2dcb7.yaml
│   │   └── start-using-reno-eaaafddb3fbf2010.yaml
│   └── source/
│       ├── conf.py
│       └── index.rst
├── requirements.txt
├── setup.cfg
├── setup.py
├── test-requirements.txt
└── tox.ini
Download .txt
SYMBOL INDEX (73 symbols across 4 files)

FILE: bashate/bashate.py
  function is_continuation (line 29) | def is_continuation(line):
  function check_for_do (line 33) | def check_for_do(line, report):
  function check_if_then (line 48) | def check_if_then(line, report):
  function check_no_trailing_whitespace (line 55) | def check_no_trailing_whitespace(line, report):
  function check_no_long_lines (line 60) | def check_no_long_lines(line, report, max_line_length):
  function check_indents (line 65) | def check_indents(logical_line, report):
  function check_function_decl (line 104) | def check_function_decl(line, report):
  function starts_heredoc (line 119) | def starts_heredoc(line):
  function end_of_heredoc (line 126) | def end_of_heredoc(line, token):
  function check_arithmetic (line 130) | def check_arithmetic(line, report):
  function check_bare_arithmetic (line 135) | def check_bare_arithmetic(line, report):
  function check_local_subshell (line 140) | def check_local_subshell(line, report):
  function check_hashbang (line 148) | def check_hashbang(line, filename, report):
  function check_conditional_expression (line 156) | def check_conditional_expression(line, report):
  function check_syntax (line 195) | def check_syntax(filename, report):
  class BashateRun (line 247) | class BashateRun(object):
    method __init__ (line 249) | def __init__(self):
    method register_ignores (line 256) | def register_ignores(self, ignores):
    method register_warnings (line 260) | def register_warnings(self, warnings):
    method register_errors (line 264) | def register_errors(self, errors):
    method should_ignore (line 268) | def should_ignore(self, error):
    method should_warn (line 271) | def should_warn(self, error):
    method print_error (line 279) | def print_error(self, error, line='',
    method log_error (line 297) | def log_error(self, error, line, filename, filelineno, warn=False):
    method check_files (line 305) | def check_files(self, files, verbose, max_line_length=79):
  function main (line 418) | def main(args=None):

FILE: bashate/messages.py
  class _Message (line 17) | class _Message(object):
    method __init__ (line 32) | def __init__(self, msg_id, msg_str, long_msg, default):
    method msg (line 44) | def msg(self):
  function is_default_error (line 220) | def is_default_error(error):
  function is_default_warning (line 224) | def is_default_warning(error):
  function print_messages (line 228) | def print_messages():

FILE: bashate/tests/base.py
  class TestCase (line 24) | class TestCase(testtools.TestCase):
    method setUp (line 27) | def setUp(self):

FILE: bashate/tests/test_bashate.py
  class TestBashate (line 30) | class TestBashate(base.TestCase):
    method setUp (line 32) | def setUp(self):
    method test_main_no_files (line 37) | def test_main_no_files(self, m_bashaterun):
    method test_main_return_one_on_errors (line 48) | def test_main_return_one_on_errors(self, m_bashaterun):
    method test_main_return_one_on_ioerror (line 59) | def test_main_return_one_on_ioerror(self, m_bashaterun):
    method test_multi_ignore_with_slash (line 75) | def test_multi_ignore_with_slash(self):
    method test_multi_ignore_with_comma (line 82) | def test_multi_ignore_with_comma(self):
    method test_multi_ignore_mixed (line 89) | def test_multi_ignore_mixed(self):
    method test_ignore (line 97) | def test_ignore(self):
    method test_while_check_for_do (line 104) | def test_while_check_for_do(self, m_print_error):
  class TestBashateSamples (line 112) | class TestBashateSamples(base.TestCase):
    method setUp (line 115) | def setUp(self):
    method assert_error_found (line 123) | def assert_error_found(self, error, lineno):
    method test_sample_E001 (line 134) | def test_sample_E001(self):
    method test_sample_E002 (line 140) | def test_sample_E002(self):
    method test_sample_E003 (line 146) | def test_sample_E003(self):
    method test_sample_E003_bad (line 151) | def test_sample_E003_bad(self):
    method test_sample_E004_bad (line 158) | def test_sample_E004_bad(self):
    method test_sample_E006_bad (line 163) | def test_sample_E006_bad(self):
    method test_sample_E006_bad_ignore_trailing_ws (line 172) | def test_sample_E006_bad_ignore_trailing_ws(self):
    method test_sample_E006_bad_custom_max_line_length (line 182) | def test_sample_E006_bad_custom_max_line_length(self):
    method test_sample_E006_good (line 190) | def test_sample_E006_good(self):
    method test_sample_E010_good (line 196) | def test_sample_E010_good(self):
    method test_sample_E010 (line 202) | def test_sample_E010(self):
    method test_sample_E011_good (line 209) | def test_sample_E011_good(self):
    method test_sample_E011 (line 215) | def test_sample_E011(self):
    method test_sample_E012 (line 222) | def test_sample_E012(self):
    method test_sample_E041 (line 229) | def test_sample_E041(self):
    method test_sample_E042 (line 235) | def test_sample_E042(self):
    method test_sample_E043 (line 245) | def test_sample_E043(self):
    method test_sample_for_loops (line 252) | def test_sample_for_loops(self):
    method test_sample_comments (line 259) | def test_sample_comments(self):
    method test_sample_E005 (line 268) | def test_sample_E005(self):
    method test_sample_E005_excluded (line 275) | def test_sample_E005_excluded(self):
    method test_sample_E040 (line 281) | def test_sample_E040(self):
    method test_sample_E044 (line 288) | def test_sample_E044(self):
    method test_sample_warning (line 299) | def test_sample_warning(self):
    method test_ignore_heredoc (line 310) | def test_ignore_heredoc(self):
    method test_pre_zero_dot_one_sample_file (line 315) | def test_pre_zero_dot_one_sample_file(self):
Condensed preview — 68 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (88K chars).
[
  {
    "path": ".coveragerc",
    "chars": 91,
    "preview": "[run]\nbranch = True\nsource = bashate\nomit = bashate/tests/*\n\n[report]\nignore_errors = True\n"
  },
  {
    "path": ".gitignore",
    "chars": 448,
    "preview": "*.py[cod]\n\n# C extensions\n*.so\n\n# Packages\n*.egg\n*.egg-info\ndist\nbuild\neggs\nparts\nbin\nvar\nsdist\ndevelop-eggs\n.installed."
  },
  {
    "path": ".gitreview",
    "chars": 74,
    "preview": "[gerrit]\nhost=review.opendev.org\nport=29418\nproject=openstack/bashate.git\n"
  },
  {
    "path": ".mailmap",
    "chars": 88,
    "preview": "# Format is:\n# <preferred e-mail> <other e-mail 1>\n# <preferred e-mail> <other e-mail 2>"
  },
  {
    "path": ".pre-commit-hooks.yaml",
    "chars": 243,
    "preview": "---\n\n# For use with pre-commit.\n# See usage instructions at https://pre-commit.com\n\n-   id: bashate\n    name: bashate\n  "
  },
  {
    "path": ".stestr.conf",
    "chars": 35,
    "preview": "[DEFAULT]\ntest_path=./bashate/tests"
  },
  {
    "path": ".zuul.d/jobs.yaml",
    "chars": 659,
    "preview": "- project:\n    templates:\n      - openstack-python3-jobs\n      - publish-openstack-docs-pti\n      - release-notes-jobs-p"
  },
  {
    "path": "CONTRIBUTING.rst",
    "chars": 601,
    "preview": "The source repository for this project can be found at:\n\n   https://opendev.org/openstack/bashate\n\nPull requests submitt"
  },
  {
    "path": "HACKING.rst",
    "chars": 159,
    "preview": "bashate Style Commandments\n===============================================\n\nRead the OpenStack Style Commandments http:/"
  },
  {
    "path": "LICENSE",
    "chars": 10142,
    "preview": "\n                                 Apache License\n                           Version 2.0, January 2004\n                  "
  },
  {
    "path": "README.rst",
    "chars": 2097,
    "preview": "===============================\nbashate\n===============================\n\nA pep8 equivalent for bash scripts\n\nThis progra"
  },
  {
    "path": "bashate/__init__.py",
    "chars": 647,
    "preview": "# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with "
  },
  {
    "path": "bashate/__main__.py",
    "chars": 85,
    "preview": "from bashate import main\nimport sys\n\nif __name__ == \"__main__\":\n    sys.exit(main())\n"
  },
  {
    "path": "bashate/bashate.py",
    "chars": 17049,
    "preview": "#!/usr/bin/env python\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file ex"
  },
  {
    "path": "bashate/messages.py",
    "chars": 7262,
    "preview": "# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with "
  },
  {
    "path": "bashate/tests/__init__.py",
    "chars": 0,
    "preview": ""
  },
  {
    "path": "bashate/tests/base.py",
    "chars": 1901,
    "preview": "# Copyright 2010-2011 OpenStack Foundation\n# Copyright (c) 2013 Hewlett-Packard Development Company, L.P.\n#\n# Licensed u"
  },
  {
    "path": "bashate/tests/samples/.E005_excluded",
    "chars": 93,
    "preview": "# this profile/hidden file doesn't start with #!\n# and doesn't have a .sh extension\n\necho hi\n"
  },
  {
    "path": "bashate/tests/samples/E001_bad.sh",
    "chars": 40,
    "preview": "#!/bin/bash\n\n# E001\nsomefunction args  \n"
  },
  {
    "path": "bashate/tests/samples/E002_bad.sh",
    "chars": 37,
    "preview": "#!/bin/bash\n\n\techo \"E002: Has a tab\"\n"
  },
  {
    "path": "bashate/tests/samples/E003_bad.sh",
    "chars": 154,
    "preview": "#!/bin/bash\n\nthis is \\\n      bad continuation as it does not match 1st arg or %4\n\na \\\n bad indent\n\nif foo; then\n    test"
  },
  {
    "path": "bashate/tests/samples/E003_good.sh",
    "chars": 285,
    "preview": "#!/bin/bash\n\nthis is \\\n     a continuation \\\n     where the continued lines \\\n     align with the first argument\n\na \\\n  "
  },
  {
    "path": "bashate/tests/samples/E004_bad.sh",
    "chars": 31,
    "preview": "this file\nhas no\nnewline at end"
  },
  {
    "path": "bashate/tests/samples/E005_bad",
    "chars": 78,
    "preview": "# this file doesn't start with #!\n# and doesn't have a .sh extension\n\necho hi\n"
  },
  {
    "path": "bashate/tests/samples/E006_bad.sh",
    "chars": 343,
    "preview": "#!/bin/bash\n\n# lines longer than 79 columns\n\n: 3456789012345678901234567890123456789012345678901234567890123456789012345"
  },
  {
    "path": "bashate/tests/samples/E006_bad_custom_length.sh",
    "chars": 163,
    "preview": "#!/bin/bash\n\n# lines longer than 10 columns give warnings\n\n: 0123456789\n:        1         2         3         4        "
  },
  {
    "path": "bashate/tests/samples/E006_good.sh",
    "chars": 489,
    "preview": "#!/bin/bash\n\n# Allow lines 79 columns or shorter\n\n: 34567890123456789012345678901234567890123456789012345678901234567890"
  },
  {
    "path": "bashate/tests/samples/E010_bad.sh",
    "chars": 104,
    "preview": "#!/bin/bash\n\nwhile [ 0 ]\ndo\n    zero\ndone\n\n# for do done in one line\nfor [ 0 ]; do run_morethings; done\n"
  },
  {
    "path": "bashate/tests/samples/E010_good.sh",
    "chars": 128,
    "preview": "#!/bin/bash\n\n# E010 good\nwhile [ 0 ]; do\n    run_things\ndone\n\n# E010 with comment\nwhile [ 0 ]; do # comment\n    run_thin"
  },
  {
    "path": "bashate/tests/samples/E011_bad.sh",
    "chars": 162,
    "preview": "#!/bin/bash\n\nif [ 0 ]\nthen\n    zero\nelif [ 1 ]\nthen\n    one\nelse\n    default\nfi\n\n# if else fi in one line\nif [ 0 ]; then"
  },
  {
    "path": "bashate/tests/samples/E011_good.sh",
    "chars": 155,
    "preview": "#!/bin/bash\n\n# E011 good\nif [ 0 ]; then\n    run_morethings\nelse\n    run_otherthings\nfi\n\n# E011 with comment\nif [ 0 ]; th"
  },
  {
    "path": "bashate/tests/samples/E012_bad.sh",
    "chars": 93,
    "preview": "#unexpected end-of-file on this\nif foo; then\n\nFOO=<<EOF\nblah foo moo\n\n\n# heredoc not ending\n\n"
  },
  {
    "path": "bashate/tests/samples/E040_syntax_error.sh",
    "chars": 87,
    "preview": "#!/bin/bash\n\nfunction myfn {\n    if [ '' == '' ]; then\n        echo 'Things'\n    fii\n}\n"
  },
  {
    "path": "bashate/tests/samples/E041_bad.sh",
    "chars": 35,
    "preview": "#!/bin/bash\n\n# E021\nfoo=$[ 1 + 1 ]\n"
  },
  {
    "path": "bashate/tests/samples/E042_bad.sh",
    "chars": 174,
    "preview": "function hello {\n    local foo=$(ls)\n}\n\nfunction hello_too {\n    local foo=`ls`\n}\n\nfunction hello_with_quotes {\n    loca"
  },
  {
    "path": "bashate/tests/samples/E043_bad.sh",
    "chars": 136,
    "preview": "count=0\nthings=\"0 1 0 0 1\"\n\nfor i in $things; do\n    if [ $i == \"1\" ]; then\n        (( count++ ))\n    fi\ndone\n\necho \"Cou"
  },
  {
    "path": "bashate/tests/samples/E044_bad.sh",
    "chars": 569,
    "preview": "# =~\n\nif [ \"test\" =~ \"]\" ]; then\n    echo \"Does not work!\"\nfi\n\n[ \"test\" =~ \"string\" ] && echo \"Does not work!\"\n\nif [[ $f"
  },
  {
    "path": "bashate/tests/samples/comments.sh",
    "chars": 372,
    "preview": "#!/bin/bash\n\n# make sure we're ignoring comments correctly\n\n## multiple\n\n# if [ foo ];\n# then\n#  echo \"blah\"\n# fi\n\nfoo=1"
  },
  {
    "path": "bashate/tests/samples/for_loops.sh",
    "chars": 384,
    "preview": "# for loop examples\n\n# pass\nfor i in $(seq 1 5); do\n    echo $i\ndone\n\n# pass\nfor (( i = 0 ; i < 5 ; i++ )); do\n    echo "
  },
  {
    "path": "bashate/tests/samples/heredoc_ignore.sh",
    "chars": 748,
    "preview": "#!/bin/bash\n\nFOO=<<EOF\n\n this is a file\n  that does not obey our indenting\n or our line length -------------------------"
  },
  {
    "path": "bashate/tests/samples/legacy_sample.sh",
    "chars": 382,
    "preview": "#!/bin/bash\n# E020\nfunction somefunction () {\n\techo \"E002: Has a tab\"\n\n  echo \"E003: Not an indent with multiple of 4\"\n}"
  },
  {
    "path": "bashate/tests/test_bashate.py",
    "chars": 11763,
    "preview": "# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with "
  },
  {
    "path": "bindep.txt",
    "chars": 215,
    "preview": "# This is a cross-platform list tracking distribution packages needed by tests;\n# see http://docs.openstack.org/infra/bi"
  },
  {
    "path": "doc/requirements.txt",
    "chars": 303,
    "preview": "# The order of packages is significant, because pip processes them in the order\n# of appearance. Changing the order has "
  },
  {
    "path": "doc/source/conf.py",
    "chars": 2951,
    "preview": "# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with "
  },
  {
    "path": "doc/source/contributor/contributing.rst",
    "chars": 2041,
    "preview": "============================\nSo You Want to Contribute...\n============================\n\nFor general information on contr"
  },
  {
    "path": "doc/source/contributor/index.rst",
    "chars": 90,
    "preview": "============\nContributing\n============\n\n.. toctree::\n   :maxdepth: 2\n\n   contributing.rst\n"
  },
  {
    "path": "doc/source/index.rst",
    "chars": 305,
    "preview": "===================================\nWelcome to bashate's documentation!\n===================================\n\n.. toctree:"
  },
  {
    "path": "doc/source/install/index.rst",
    "chars": 190,
    "preview": "============\nInstallation\n============\n\nAt the command line::\n\n    $ pip install bashate\n\nOr, if you have virtualenvwrap"
  },
  {
    "path": "doc/source/man/bashate.rst",
    "chars": 884,
    "preview": "===========================\n:program:`bashate` man page\n===========================\n\n.. program:: bashate\n.. highlight::"
  },
  {
    "path": "doc/source/readme.rst",
    "chars": 80,
    "preview": ".. include:: ../../README.rst\n\nSee also\n~~~~~~~~\n\nSee also :doc:`/man/bashate`.\n"
  },
  {
    "path": "doc/source/user/index.rst",
    "chars": 109,
    "preview": "=============\nUsing bashate\n=============\n\n.. toctree::\n   :maxdepth: 2\n\n   usage.rst\n   ../man/bashate.rst\n\n"
  },
  {
    "path": "doc/source/user/usage.rst",
    "chars": 72,
    "preview": "========\nUsage\n========\n\nTo use bashate in a project::\n\n\timport bashate\n"
  },
  {
    "path": "playbooks/bashate-devstack-master/run.yaml",
    "chars": 430,
    "preview": "- hosts: all\n  name: Run bashate against devstack master\n  roles:\n    - bindep\n    - role: ensure-tox\n      ensure_globa"
  },
  {
    "path": "releasenotes/notes/0-dash-6-748e729ee001df73.yaml",
    "chars": 343,
    "preview": "---\nfeatures:\n  - Python 3.6 support added\n  - Hidden files such as ``.bashrc`` are no longer checked for ``#!`` (E005)\n"
  },
  {
    "path": "releasenotes/notes/adopt-pycodestyle-output-format-f4d6e35dadfcb6f9.yaml",
    "chars": 71,
    "preview": "---\nfeatures:\n  - |\n    Adoped pycodestyle/pep8 default output format.\n"
  },
  {
    "path": "releasenotes/notes/custom-line-length-083e8077951a8ead.yaml",
    "chars": 120,
    "preview": "---\nfeatures:\n  - |\n    Adds an option ``--max-line-length`` to specify the maximum length\n    of lines for check E006.\n"
  },
  {
    "path": "releasenotes/notes/drop-python2.7-064c5e5bcfb4539c.yaml",
    "chars": 89,
    "preview": "---\ndeprecations:\n  - |\n    bashate is now Python 3 only and no longer supports Python 2."
  },
  {
    "path": "releasenotes/notes/heredoc-ignore-905b29053652f90e.yaml",
    "chars": 843,
    "preview": "---\nfixes:\n\n  - Ignore contents of ``heredoc`` values.  ``heredocs`` usually\n    contain content in a foreign syntax so "
  },
  {
    "path": "releasenotes/notes/python-3-4e30b9f2b9e2dcb7.yaml",
    "chars": 40,
    "preview": "---\nfeatures:\n\n  - Python 3 is supported"
  },
  {
    "path": "releasenotes/notes/start-using-reno-eaaafddb3fbf2010.yaml",
    "chars": 34,
    "preview": "---\nother:\n  - started using reno\n"
  },
  {
    "path": "releasenotes/source/conf.py",
    "chars": 8921,
    "preview": "# -*- coding: utf-8 -*-\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file ex"
  },
  {
    "path": "releasenotes/source/index.rst",
    "chars": 86,
    "preview": "=====================\nbashate Release Notes\n=====================\n\n.. release-notes::\n"
  },
  {
    "path": "requirements.txt",
    "chars": 32,
    "preview": "pbr!=2.1.0,>=2.0.0 # Apache-2.0\n"
  },
  {
    "path": "setup.cfg",
    "chars": 1071,
    "preview": "[metadata]\nname = bashate\nsummary = A pep8 equivalent for bash scripts\ndescription_file =\n    README.rst\nauthor = OpenSt"
  },
  {
    "path": "setup.py",
    "chars": 695,
    "preview": "# Copyright (c) 2013 Hewlett-Packard Development Company, L.P.\n#\n# Licensed under the Apache License, Version 2.0 (the \""
  },
  {
    "path": "test-requirements.txt",
    "chars": 220,
    "preview": "hacking>=4.1.0,<4.2.0;python_version<'3.8' # Apache-2.0\nhacking>=7.0.0,<7.1.0;python_version>='3.8' # Apache-2.0\n\ncovera"
  },
  {
    "path": "tox.ini",
    "chars": 1810,
    "preview": "[tox]\nminversion = 3.18.0\nenvlist = py36,py39,pep8\nskipsdist = True\nignore_basepython_conflict = True\n\n[testenv]\nbasepyt"
  }
]

About this extraction

This page contains the full source code of the openstack/bashate GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 68 files (78.7 KB), approximately 21.3k tokens, and a symbol index with 73 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.

Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.

Copied to clipboard!