[Git][NTPsec/ntpsec][master] Fix indentation of python code to match pep8 standards

Matt Selsky gitlab at mg.gitlab.com
Sun Dec 3 02:21:23 UTC 2017


Matt Selsky pushed to branch master at NTPsec / ntpsec


Commits:
f6edb8d0 by Matt Selsky at 2017-12-02T21:06:39-05:00
Fix indentation of python code to match pep8 standards

- - - - -


8 changed files:

- devel/python_paths.py
- ntpclients/ntpq.py
- ntpclients/ntpviz.py
- pylib/util.py
- wafhelpers/probes.py
- wafhelpers/rtems_trace.py
- wafhelpers/test.py
- wafhelpers/waf.py


Changes:

=====================================
devel/python_paths.py
=====================================
--- a/devel/python_paths.py
+++ b/devel/python_paths.py
@@ -18,9 +18,9 @@ import sys
 import traceback
 
 try:
-  reduce
+    reduce
 except NameError:  # For Python 3
-  from functools import reduce  # pylint: disable=redefined-builtin
+    from functools import reduce  # pylint: disable=redefined-builtin
 
 PYTHON_PATTERNS = ['python', 'python[1-9]', 'python[1-9].[0-9]']
 
@@ -41,111 +41,111 @@ PYTHON_PREFIX_NAMES = 'sys-prefix std-prefix exec-prefix'.split()
 
 
 class BadReturn(Exception):
-  """Bad return from subprocess."""
-  pass
+    """Bad return from subprocess."""
+    pass
 
 
 def _print(arg):
-  """Python3-compatible print, without depending on future import."""
-  print(arg)  # pylint: disable=superfluous-parens
+    """Python3-compatible print, without depending on future import."""
+    print(arg)  # pylint: disable=superfluous-parens
 
 
 def GetPaths():
-  """Get list of directories in PATH."""
-  return os.environ['PATH'].split(':')
+    """Get list of directories in PATH."""
+    return os.environ['PATH'].split(':')
 
 
 def MakePatterns(paths, patterns):
-  """Construct Cartesian product of paths and file patterns."""
-  return [os.path.join(path, pat) for path in paths for pat in patterns]
+    """Construct Cartesian product of paths and file patterns."""
+    return [os.path.join(path, pat) for path in paths for pat in patterns]
 
 
 def FileList(patterns):
-  """Get list of files from list of glob patterns."""
-  return reduce(operator.add, map(glob.glob, patterns), [])
+    """Get list of files from list of glob patterns."""
+    return reduce(operator.add, map(glob.glob, patterns), [])
 
 
 def ExeFilter(files):
-  """Filter list of files based on executability."""
-  return [f for f in files if os.access(f, os.X_OK)]
+    """Filter list of files based on executability."""
+    return [f for f in files if os.access(f, os.X_OK)]
 
 
 def PythonCommands(python, commands):
-  """Run a multiline Python command string in a specified Python."""
-  proc = subprocess.Popen(python,
-                          stdin=subprocess.PIPE, stdout=subprocess.PIPE,
-                          universal_newlines=True)  # Force text mode in Python3
-  try:
-    result, _ = proc.communicate(commands)
-  except TypeError:  # For Python 3.1 only
-    result, _ = proc.communicate(bytes(commands, encoding='latin-1'))
-  if proc.returncode:
-    raise BadReturn(proc.returncode)
-  return result.splitlines()
+    """Run a multiline Python command string in a specified Python."""
+    proc = subprocess.Popen(python,
+                            stdin=subprocess.PIPE, stdout=subprocess.PIPE,
+                            universal_newlines=True)  # Force text mode in Python3
+    try:
+        result, _ = proc.communicate(commands)
+    except TypeError:  # For Python 3.1 only
+        result, _ = proc.communicate(bytes(commands, encoding='latin-1'))
+    if proc.returncode:
+        raise BadReturn(proc.returncode)
+    return result.splitlines()
 
 
 def PrintExe(prefix, exe, real):
-  """Print executable path with optional symlink reporting."""
-  if real == exe:
-    _print('%s: %s' % (prefix, exe))
-  else:
-    _print('%s: %s -> %s' % (prefix, exe, real))
+    """Print executable path with optional symlink reporting."""
+    if real == exe:
+        _print('%s: %s' % (prefix, exe))
+    else:
+        _print('%s: %s -> %s' % (prefix, exe, real))
 
 
 def main(argv=None):  # pylint: disable=too-many-locals
-  """Top-level main function."""
-  if argv and len(argv) >= 2:  # If arg is given, run entire script remotely
-    sys.stderr.write('NOTE:  Remote PATH may be incomplete.\n')
-    this_file = open(__file__)
-    this_script = this_file.read()
-    this_file.close()
-    result = PythonCommands(['ssh', '-T', argv[1], 'python'], this_script)
-    if result and result[-1]:
-      result += ['']  #  Add trailing EOL if needed
-    sys.stdout.write('\n'.join(result))
+    """Top-level main function."""
+    if argv and len(argv) >= 2:  # If arg is given, run entire script remotely
+        sys.stderr.write('NOTE:  Remote PATH may be incomplete.\n')
+        this_file = open(__file__)
+        this_script = this_file.read()
+        this_file.close()
+        result = PythonCommands(['ssh', '-T', argv[1], 'python'], this_script)
+        if result and result[-1]:
+            result += ['']  #  Add trailing EOL if needed
+        sys.stdout.write('\n'.join(result))
+        return 0
+    python_list = ExeFilter(FileList(MakePatterns(GetPaths(), PYTHON_PATTERNS)))
+    done = set()
+    unique = total = 0
+    for python in python_list:
+        try:
+            values = PythonCommands([python], '\n'.join(PYTHON_COMMANDS))
+        except (OSError, BadReturn):  # Avoid 'as' for <2.6 compatibility
+            exmsg = traceback.format_exception_only(*sys.exc_info()[:2])[-1].strip()
+            _print('Skipping %s due to %s' % (python, exmsg))
+            continue
+        if len(values) != len(PYTHON_VALUE_NAMES):
+            _print('Skipping %s due to number of results (%d) != %d'
+                   % (python, len(values), len(PYTHON_VALUE_NAMES)))
+            continue
+        valdict = dict(zip(PYTHON_VALUE_NAMES, values))
+        total += 1
+        exe = valdict['exec']
+        real = os.path.realpath(exe)
+        if real in done:
+            PrintExe('Redundant', python, os.path.realpath(python))
+            PrintExe(' (Executable)', exe, real)
+            continue
+        done |= set([real])
+        unique += 1
+        PrintExe('Command', python, os.path.realpath(python))
+        PrintExe(' Executable', exe, real)
+        if valdict['lib-noarch'] == valdict['lib-arch']:
+            _print(' Libs(all): %s' % valdict['lib-noarch'])
+        else:
+            _print(' Libs(arch=any): %s' % valdict['lib-noarch'])
+            _print(' Libs(arch=specific): %s' % valdict['lib-arch'])
+        if len(set([valdict[x] for x in PYTHON_PREFIX_NAMES])) == 1:
+            _print(' Prefix(all): %s' % valdict['sys-prefix'])
+        else:
+            _print(' Prefix(sys): %s' % valdict['sys-prefix'])
+            _print(' Prefix(std): %s' % valdict['std-prefix'])
+            _print(' Prefix(exec): %s' % valdict['exec-prefix'])
+    plural = unique != 1 and 's' or ''  # pylint: disable=consider-using-ternary
+    print('Found %d unique Python installation%s out of %d total'
+          % (unique, plural, total))
     return 0
-  python_list = ExeFilter(FileList(MakePatterns(GetPaths(), PYTHON_PATTERNS)))
-  done = set()
-  unique = total = 0
-  for python in python_list:
-    try:
-      values = PythonCommands([python], '\n'.join(PYTHON_COMMANDS))
-    except (OSError, BadReturn):  # Avoid 'as' for <2.6 compatibility
-      exmsg = traceback.format_exception_only(*sys.exc_info()[:2])[-1].strip()
-      _print('Skipping %s due to %s' % (python, exmsg))
-      continue
-    if len(values) != len(PYTHON_VALUE_NAMES):
-      _print('Skipping %s due to number of results (%d) != %d'
-             % (python, len(values), len(PYTHON_VALUE_NAMES)))
-      continue
-    valdict = dict(zip(PYTHON_VALUE_NAMES, values))
-    total += 1
-    exe = valdict['exec']
-    real = os.path.realpath(exe)
-    if real in done:
-      PrintExe('Redundant', python, os.path.realpath(python))
-      PrintExe(' (Executable)', exe, real)
-      continue
-    done |= set([real])
-    unique += 1
-    PrintExe('Command', python, os.path.realpath(python))
-    PrintExe(' Executable', exe, real)
-    if valdict['lib-noarch'] == valdict['lib-arch']:
-      _print(' Libs(all): %s' % valdict['lib-noarch'])
-    else:
-      _print(' Libs(arch=any): %s' % valdict['lib-noarch'])
-      _print(' Libs(arch=specific): %s' % valdict['lib-arch'])
-    if len(set([valdict[x] for x in PYTHON_PREFIX_NAMES])) == 1:
-      _print(' Prefix(all): %s' % valdict['sys-prefix'])
-    else:
-      _print(' Prefix(sys): %s' % valdict['sys-prefix'])
-      _print(' Prefix(std): %s' % valdict['std-prefix'])
-      _print(' Prefix(exec): %s' % valdict['exec-prefix'])
-  plural = unique != 1 and 's' or ''  # pylint: disable=consider-using-ternary
-  print('Found %d unique Python installation%s out of %d total'
-        % (unique, plural, total))
-  return 0
 
 
 if __name__ == '__main__':
-  sys.exit(main(sys.argv))  # pragma: no cover
+    sys.exit(main(sys.argv))  # pragma: no cover


=====================================
ntpclients/ntpq.py
=====================================
--- a/ntpclients/ntpq.py
+++ b/ntpclients/ntpq.py
@@ -1014,8 +1014,8 @@ usage: writevar assocID name=value,[...]
     def do_mreadlist(self, line):
         "read the peer variables in the variable list for multiple peers"
         if not line:
-                self.warn("usage: mreadlist assocIDlow assocIDhigh\n")
-                return
+            self.warn("usage: mreadlist assocIDlow assocIDhigh\n")
+            return
         idrange = self.__assoc_range_valid(line)
         if not idrange:
             return
@@ -1036,8 +1036,8 @@ usage: mreadlist assocIDlow assocIDhigh
     def do_mrl(self, line):
         "read the peer variables in the variable list for multiple peers"
         if not line:
-                self.warn("usage: mrl assocIDlow assocIDhigh\n")
-                return
+            self.warn("usage: mrl assocIDlow assocIDhigh\n")
+            return
         self.do_mreadlist(line)
 
     def help_mrl(self):
@@ -1049,9 +1049,9 @@ usage: mrl assocIDlow assocIDhigh
     def do_mreadvar(self, line):
         "read peer variables from multiple peers"
         if not line:
-                self.warn("usage: mreadvar assocIDlow assocIDhigh  "
-                          "[ name=value[,...] ]\n")
-                return
+            self.warn("usage: mreadvar assocIDlow assocIDhigh  "
+                      "[ name=value[,...] ]\n")
+            return
         idrange = self.__assoc_range_valid(line)
         if not idrange:
             return
@@ -1073,9 +1073,9 @@ usage: mreadvar assocIDlow assocIDhigh [name=value[,...]]
     def do_mrv(self, line):
         "read peer variables from multiple peers"
         if not line:
-                self.warn(
-                    "usage: mrv assocIDlow assocIDhigh [name=value[,...]]\n")
-                return
+            self.warn(
+                "usage: mrv assocIDlow assocIDhigh [name=value[,...]]\n")
+            return
         self.do_mreadvar(line)
 
     def help_mrv(self):
@@ -1151,8 +1151,8 @@ usage: cv [ assocID ] [ name=value[,...] ]
             ("candidate", "candidate order:     ", NTP_INT),
         )
         if not line:
-                self.warn("usage: pstats assocID\n")
-                return
+            self.warn("usage: pstats assocID\n")
+            return
         associd = self.__assoc_valid(line)
         if associd >= 0:
             self.collect_display(associd=associd,


=====================================
ntpclients/ntpviz.py
=====================================
--- a/ntpclients/ntpviz.py
+++ b/ntpclients/ntpviz.py
@@ -754,8 +754,8 @@ component of frequency drift.</p>
                 out['min_y'] = out['max_y'] * 0.8
                 out['max_y'] = out['max_y'] * 1.2
         elif 2 > out['min_y']:
-                # scale 0:max_x
-                out['min_y'] = 0
+            # scale 0:max_x
+            out['min_y'] = 0
 
         # recalc fmt
         out['fmt'] = gnuplot_fmt(out["min_y"], out["max_y"])


=====================================
pylib/util.py
=====================================
--- a/pylib/util.py
+++ b/pylib/util.py
@@ -657,7 +657,7 @@ class PeerStatusWord:
                 else:
                     self.condition = ""
             elif (statval & 0x3) == OLD_CTL_PST_SEL_SELCAND:
-                    self.condition = "sel_cand"
+                self.condition = "sel_cand"
             elif (statval & 0x3) == OLD_CTL_PST_SEL_SYNCCAND:
                 self.condition = "sync_cand"
             elif (statval & 0x3) == OLD_CTL_PST_SEL_SYSPEER:


=====================================
wafhelpers/probes.py
=====================================
--- a/wafhelpers/probes.py
+++ b/wafhelpers/probes.py
@@ -5,45 +5,45 @@ up the logic in the main configure.py.
 
 
 def probe_header_with_prerequisites(ctx, header, prerequisites, use=None):
-        "Check that a header (with its prerequisites) compiles."
-        src = ""
-        for hdr in prerequisites + [header]:
-            src += "#include <%s>\n" % hdr
-        src += "int main(void) { return 0; }\n"
-        have_name = "HAVE_%s" \
-            % header.replace(".", "_").replace("/", "_").upper()
-        ctx.check_cc(
-            comment="<%s> header" % header,
-            define_name=have_name,
-            fragment=src,
-            includes=ctx.env.PLATFORM_INCLUDES,
-            mandatory=False,
-            msg="Checking for header %s" % header,
-            use=use or [],
-        )
-        return ctx.get_define(have_name)
+    "Check that a header (with its prerequisites) compiles."
+    src = ""
+    for hdr in prerequisites + [header]:
+        src += "#include <%s>\n" % hdr
+    src += "int main(void) { return 0; }\n"
+    have_name = "HAVE_%s" \
+        % header.replace(".", "_").replace("/", "_").upper()
+    ctx.check_cc(
+        comment="<%s> header" % header,
+        define_name=have_name,
+        fragment=src,
+        includes=ctx.env.PLATFORM_INCLUDES,
+        mandatory=False,
+        msg="Checking for header %s" % header,
+        use=use or [],
+    )
+    return ctx.get_define(have_name)
 
 
 def probe_function_with_prerequisites(ctx, function, prerequisites, use=None):
-        "Check that a function (with its prerequisites) compiles."
-        src = ""
-        for hdr in prerequisites:
-                src += "#include <%s>\n" % hdr
-        src += """int main(void) {
+    "Check that a function (with its prerequisites) compiles."
+    src = ""
+    for hdr in prerequisites:
+        src += "#include <%s>\n" % hdr
+    src += """int main(void) {
         void *p = (void*)(%s);
         return (int)p;
 }
 """ % function
-        have_name = "HAVE_%s" % function.upper()
-        ctx.check_cc(
-            comment="Whether %s() exists" % function,
-            define_name=have_name,
-            fragment=src,
-            includes=ctx.env.PLATFORM_INCLUDES,
-            mandatory=False,
-            msg="Checking for function %s" % function,
-            use=use or [],
-        )
-        return ctx.get_define(have_name)
+    have_name = "HAVE_%s" % function.upper()
+    ctx.check_cc(
+        comment="Whether %s() exists" % function,
+        define_name=have_name,
+        fragment=src,
+        includes=ctx.env.PLATFORM_INCLUDES,
+        mandatory=False,
+        msg="Checking for function %s" % function,
+        use=use or [],
+    )
+    return ctx.get_define(have_name)
 
 # end


=====================================
wafhelpers/rtems_trace.py
=====================================
--- a/wafhelpers/rtems_trace.py
+++ b/wafhelpers/rtems_trace.py
@@ -4,6 +4,6 @@ from waflib.TaskGen import feature, after_method
 @feature("rtems_trace")
 @after_method('apply_link')
 def rtems_trace(self):
-        if self.env.RTEMS_TEST_ENABLE:
-                self.link_task.env.LINK_CC = self.env.BIN_RTEMS_TLD \
-                    + self.env.RTEMS_TEST_FLAGS + ['--']
+    if self.env.RTEMS_TEST_ENABLE:
+        self.link_task.env.LINK_CC = self.env.BIN_RTEMS_TLD \
+            + self.env.RTEMS_TEST_FLAGS + ['--']


=====================================
wafhelpers/test.py
=====================================
--- a/wafhelpers/test.py
+++ b/wafhelpers/test.py
@@ -4,38 +4,38 @@ from waflib.Logs import pprint
 
 
 def test_write_log(ctx):
-        file_out = "%s/test.log" % ctx.bldnode.abspath()
+    file_out = "%s/test.log" % ctx.bldnode.abspath()
 
-        log = getattr(ctx, 'utest_results', [])
+    log = getattr(ctx, 'utest_results', [])
 
-        if not log:
-                return
+    if not log:
+        return
 
-        with open(file_out, "w") as fp:
-                for binary, retval, lines, error in ctx.utest_results:
-                        fp.write("BINARY      : %s\n" % binary)
-                        fp.write("RETURN VALUE: %s\n" % retval)
-                        fp.write("\n*** stdout ***\n")
-                        fp.write(str(lines))
-                        fp.write("\n*** stderr ***\n")
-                        fp.write(str(error))
-                        fp.write("\n\n\n")
+    with open(file_out, "w") as fp:
+        for binary, retval, lines, error in ctx.utest_results:
+            fp.write("BINARY      : %s\n" % binary)
+            fp.write("RETURN VALUE: %s\n" % retval)
+            fp.write("\n*** stdout ***\n")
+            fp.write(str(lines))
+            fp.write("\n*** stderr ***\n")
+            fp.write(str(error))
+            fp.write("\n\n\n")
 
-        pprint("BLUE", "Wrote test log to: ", file_out)
+    pprint("BLUE", "Wrote test log to: ", file_out)
 
 
 def test_print_log(ctx):
-        for binary, retval, lines, error in ctx.utest_results:
-                pprint("YELLOW", "BINARY      :", binary)
-                pprint("YELLOW", "RETURN VALUE:", retval)
-                print("")
+    for binary, retval, lines, error in ctx.utest_results:
+        pprint("YELLOW", "BINARY      :", binary)
+        pprint("YELLOW", "RETURN VALUE:", retval)
+        print("")
 
-                if retval or error:
-                        pprint("RED", "****** ERROR ******\n")
+        if retval or error:
+            pprint("RED", "****** ERROR ******\n")
 
-                        print(error or lines)
+            print(error or lines)
 
-                if (not retval) and (not error):
-                        pprint("GREEN", "****** LOG ******\n", lines)
+        if (not retval) and (not error):
+            pprint("GREEN", "****** LOG ******\n", lines)
 
-                print("")
+        print("")


=====================================
wafhelpers/waf.py
=====================================
--- a/wafhelpers/waf.py
+++ b/wafhelpers/waf.py
@@ -5,46 +5,46 @@ from waflib.TaskGen import feature, before_method
 @before_method('apply_incpaths')
 @feature('bld_include')
 def insert_blddir(self):
-        bldnode = self.bld.bldnode.parent.abspath()
-        self.includes += [bldnode]
+    bldnode = self.bld.bldnode.parent.abspath()
+    self.includes += [bldnode]
 
 
 @before_method('apply_incpaths')
 @feature('src_include')
 def insert_srcdir(self):
-        srcnode = self.bld.srcnode.abspath()
-        self.includes += ["%s/include" % srcnode]
+    srcnode = self.bld.srcnode.abspath()
+    self.includes += ["%s/include" % srcnode]
 
 
 def manpage_subst_fun(task, text):
-        return text.replace("include::../docs/", "include::../../../docs/")
+    return text.replace("include::../docs/", "include::../../../docs/")
 
 
 @conf
 def manpage(ctx, section, source):
 
-        # ctx.install_files('${MANDIR}' + "/man%s/" % section,
-        #                   source.replace("-man.txt", ".%s" % section))
+    # ctx.install_files('${MANDIR}' + "/man%s/" % section,
+    #                   source.replace("-man.txt", ".%s" % section))
 
-        if not ctx.env.ENABLE_DOC or ctx.env.DISABLE_MANPAGE:
-                return
+    if not ctx.env.ENABLE_DOC or ctx.env.DISABLE_MANPAGE:
+        return
 
-        ctx(features="subst",
-            source=source,
-            target=source + '.man-tmp',
-            subst_fun=manpage_subst_fun)
+    ctx(features="subst",
+        source=source,
+        target=source + '.man-tmp',
+        subst_fun=manpage_subst_fun)
 
-        ctx(source=source + '.man-tmp', section=section)
+    ctx(source=source + '.man-tmp', section=section)
 
 
 @conf
 def ntp_test(ctx, **kwargs):
-        bldnode = ctx.bldnode.abspath()
-        tg = ctx(**kwargs)
+    bldnode = ctx.bldnode.abspath()
+    tg = ctx(**kwargs)
 
-        args = ["%s/tests/%s" % (bldnode, tg.target), "-v"]
+    args = ["%s/tests/%s" % (bldnode, tg.target), "-v"]
 
-        if hasattr(tg, "test_args"):
-                args += tg.test_args
+    if hasattr(tg, "test_args"):
+        args += tg.test_args
 
-        tg.ut_exec = args
+    tg.ut_exec = args



View it on GitLab: https://gitlab.com/NTPsec/ntpsec/commit/f6edb8d0c4f1e0ef59cafc39d2e6ac303a04a856

---
View it on GitLab: https://gitlab.com/NTPsec/ntpsec/commit/f6edb8d0c4f1e0ef59cafc39d2e6ac303a04a856
You're receiving this email because of your account on gitlab.com.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.ntpsec.org/pipermail/vc/attachments/20171203/2f12d2cb/attachment.html>


More information about the vc mailing list