Made flake8 compliant

This commit is contained in:
Salvador E. Tropea 2020-03-22 20:16:57 -03:00
parent d4f12a1d13
commit 9267597330
5 changed files with 121 additions and 96 deletions

View File

@ -1,7 +1,6 @@
# -*- coding: utf-8 -*-
import argparse
import logging
import os
import sys
@ -27,11 +26,12 @@ def main():
parser.add_argument('-i', '--invert-sel', action='store_true',
help='Generate the outputs not listed as targets')
group.add_argument('-q', '--quiet', action='store_true',
help='remove information logs')
help='remove information logs')
parser.add_argument('-s', '--skip-pre', nargs=1,
help='skip pre-flight actions, comma separated list or `all`')
help='skip pre-flight actions, comma separated list '
'or `all`')
group.add_argument('-v', '--verbose', action='store_true',
help='show debugging information')
help='show debugging information')
args = parser.parse_args()
@ -39,12 +39,11 @@ def main():
logger = log.init(args.verbose, args.quiet)
if not os.path.isfile(args.board_file):
logger.error("Board file not found: {}".format(args.board_file))
logger.error("Board file not found: "+args.board_file)
sys.exit(misc.NO_PCB_FILE)
if not os.path.isfile(args.plot_config):
logger.error("Plot config file not found: {}"
.format(args.plot_config))
logger.error("Plot config file not found: "+args.plot_config)
sys.exit(misc.EXIT_BAD_ARGS)
cr = config_reader.CfgYamlReader(args.board_file)

View File

@ -2,14 +2,12 @@
Class to read KiPlot config files
"""
import os
import re
import sys
import pcbnew
from . import plot_config as PC
from . import error
from . import log
from . import misc
@ -17,8 +15,8 @@ logger = log.get_logger(__name__)
try:
import yaml
except:
log.init(False,False)
except ImportError:
log.init(False, False)
logger.error('No yaml module for Python, install python3-yaml')
sys.exit(misc.NO_YAML_MODULE)
@ -27,31 +25,34 @@ class CfgReader(object):
def __init__(self):
pass
def config_error(msg):
logger.error(msg)
sys.exit(misc.EXIT_BAD_CONFIG)
def load_layers(kicad_pcb_file):
layer_names=['-']*50
pcb_file = open(kicad_pcb_file,"r")
collect_layers=False
layer_names = ['-']*50
pcb_file = open(kicad_pcb_file, "r")
collect_layers = False
for line in pcb_file:
if collect_layers:
z=re.match('\s+\((\d+)\s+(\S+)',line)
if z:
res=z.groups()
#print(res[1]+'->'+res[0])
layer_names[int(res[0])]=res[1]
else:
if re.search('^\s+\)$',line):
collect_layers=False
break
z = re.match(r'\s+\((\d+)\s+(\S+)', line)
if z:
res = z.groups()
# print(res[1]+'->'+res[0])
layer_names[int(res[0])] = res[1]
else:
if re.search(r'^\s+\)$', line):
collect_layers = False
break
else:
if re.search('\s+\(layers',line):
collect_layers=True
if re.search(r'\s+\(layers', line):
collect_layers = True
pcb_file.close()
return layer_names
class CfgYamlReader(CfgReader):
def __init__(self, brd_file):
@ -75,7 +76,8 @@ class CfgYamlReader(CfgReader):
try:
val = data[key]
except (KeyError, TypeError):
config_error("Missing `"+key+"' "+('' if context is None else context))
config_error("Missing `"+key+"' "+(''
if context is None else context))
return val
@ -105,11 +107,12 @@ class CfgYamlReader(CfgReader):
opts = PC.DrillReportOptions()
opts.filename = self._get_required(report_opts, 'filename', 'in drill report section')
opts.filename = self._get_required(report_opts, 'filename',
'in drill report section')
return opts
def _perform_config_mapping(self, otype, cfg_options, mapping_list,
def _perform_config_mapping(self, otype, cfg_options, mapping_list,
target):
"""
Map a config dict onto a target object given a mapping list
@ -125,7 +128,8 @@ class CfgYamlReader(CfgReader):
# set the internal option as needed
if mapping['required'](cfg_options):
cfg_val = self._get_required(cfg_options, key, 'in '+otype+' section')
cfg_val = self._get_required(cfg_options, key, 'in ' +
otype + ' section')
elif not(cfg_options is None) and key in cfg_options:
# not required but given anyway
cfg_val = cfg_options[key]
@ -355,7 +359,7 @@ class CfgYamlReader(CfgReader):
},
{
'key': 'format',
'types': ['position','kibom'],
'types': ['position', 'kibom'],
'to': 'format',
'required': lambda opts: True,
},
@ -450,13 +454,14 @@ class CfgYamlReader(CfgReader):
try:
# 2) List from the PCB
id = self.layer_names.index(s)
layer = PC.LayerInfo(id, id<pcbnew.B_Cu, s)
except:
layer = PC.LayerInfo(id, id < pcbnew.B_Cu, s)
except ValueError:
# 3) Inner.N names
if s.startswith("Inner"):
m = re.match(r"^Inner\.([0-9]+)$", s)
if not m:
config_error('Malformed inner layer name: '+s+', use Inner.N')
config_error('Malformed inner layer name: ' +
s + ', use Inner.N')
layer = PC.LayerInfo(int(m.group(1)), True, s)
else:
@ -499,13 +504,14 @@ class CfgYamlReader(CfgReader):
try:
options = o_obj['options']
except KeyError:
if not otype in ['ibom', 'pdf_sch_print']:
if otype not in ['ibom', 'pdf_sch_print']:
config_error("Output '"+name+"' needs options")
options = None
logger.debug("Parsing output options for {} ({})".format(name, otype))
outdir = self._get_required(o_obj, 'dir', 'in section `'+name+'` ('+otype+')')
outdir = self._get_required(o_obj, 'dir', 'in section `' + name +
'` ('+otype+')')
output_opts = self._parse_out_opts(otype, options)
@ -516,12 +522,14 @@ class CfgYamlReader(CfgReader):
layers = o_obj['layers']
except KeyError:
if otype == 'pdf_pcb_print':
logger.error('You must specify the layers for `'+name+'` ('+otype+')')
logger.error('You must specify the layers for `' + name +
'` ('+otype+')')
sys.exit(misc.EXIT_BAD_CONFIG)
layers = []
for l in layers:
o_cfg.layers.append(self._parse_layer(l, 'in section '+name+' ('+otype+')'))
o_cfg.layers.append(self._parse_layer(l, 'in section ' + name +
' ('+otype+')'))
return o_cfg
@ -553,7 +561,7 @@ class CfgYamlReader(CfgReader):
try:
data = yaml.load(fstream)
except yaml.YAMLError as e:
except yaml.YAMLError:
config_error("Error loading YAML")
self._check_version(data)

View File

@ -7,7 +7,8 @@ import os
from sys import exit
import operator
from shutil import which
from subprocess import call, run, PIPE, check_output, CalledProcessError, STDOUT
from subprocess import (call, run, PIPE, check_output, CalledProcessError,
STDOUT)
import logging
from distutils.version import StrictVersion
import re
@ -23,11 +24,10 @@ try:
import pcbnew
from pcbnew import GERBER_JOBFILE_WRITER
except ImportError:
log.init(False,False)
log.init(False, False)
logger.error("Failed to import pcbnew Python module."
" Is KiCad installed?"
" Do you need to add it to PYTHONPATH?")
import sys
" Is KiCad installed?"
" Do you need to add it to PYTHONPATH?")
exit(misc.NO_PCBNEW_MODULE)
@ -35,23 +35,27 @@ def check_version(command, version):
cmd = [command, '--version']
logger.debug('Running: '+str(cmd))
result = run(cmd, stdout=PIPE, stderr=PIPE, universal_newlines=True)
z=re.match(command+' (\d+\.\d+\.\d+)', result.stdout)
z = re.match(command + r' (\d+\.\d+\.\d+)', result.stdout)
if not z:
logger.error('Unable to determine '+command+' version:\n'+result.stdout)
logger.error('Unable to determine ' + command + ' version:\n' +
result.stdout)
exit(misc.MISSING_TOOL)
res=z.groups()
res = z.groups()
if StrictVersion(res[0]) < StrictVersion(version):
logger.error('Wrong version for `'+command+'` ('+res[0]+'), must be '+version+' or newer.')
logger.error('Wrong version for `'+command+'` ('+res[0]+'), must be ' +
version+' or newer.')
exit(misc.MISSING_TOOL)
def check_script(cmd, url, version=None):
if which(cmd) is None:
logger.error('No `'+cmd+'` command found.\n'
'Please install it, visit: '+url)
exit(misc.MISSING_TOOL)
if not version is None:
if version is not None:
check_version(cmd, version)
def check_eeschema_do(file):
check_script(misc.CMD_EESCHEMA_DO, misc.URL_EESCHEMA_DO, '1.1.1')
sch_file = os.path.splitext(file)[0] + '.sch'
@ -93,7 +97,8 @@ class Plotter(object):
if (n == 0) or ((op.name in target) ^ invert):
logger.debug("Processing output: {}".format(op.name))
logger.info('- %s (%s) [%s]' % (op.description,op.name,op.options.type))
logger.info('- %s (%s) [%s]' % (op.description, op.name,
op.options.type))
# fresh plot controller
pc = pcbnew.PLOT_CONTROLLER(board)
@ -118,11 +123,10 @@ class Plotter(object):
else:
logger.debug('Skipping %s output', op.name)
def _preflight_checks(self, brd_file, skip_pre):
logger.debug("Preflight checks")
if not skip_pre is None:
if skip_pre is not None:
if skip_pre[0] == 'all':
logger.debug("Skipping all pre-flight actions")
return
@ -130,7 +134,8 @@ class Plotter(object):
skip_list = skip_pre[0].split(',')
for skip in skip_list:
if skip == 'all':
logger.error('All can\'t be part of a list of actions to skip. Use `--skip all`')
logger.error('All can\'t be part of a list of actions '
'to skip. Use `--skip all`')
exit(misc.EXIT_BAD_ARGS)
elif skip == 'run_drc':
self.cfg.run_drc = False
@ -149,7 +154,8 @@ class Plotter(object):
if self.cfg.update_xml:
self._update_xml(brd_file)
if self.cfg.run_drc:
self._run_drc(brd_file, self.cfg.ignore_unconnected, self.cfg.check_zone_fills)
self._run_drc(brd_file, self.cfg.ignore_unconnected,
self.cfg.check_zone_fills)
def _run_erc(self, brd_file):
sch_file = check_eeschema_do(brd_file)
@ -301,7 +307,7 @@ class Plotter(object):
# Plot single layer to file
logger.debug("Opening plot file for layer {} ({})"
.format(layer.layer, suffix))
.format(layer.layer, suffix))
plot_ctrl.OpenPlotfile(suffix, plot_format, desc)
logger.debug("Plotting layer {} to {}".format(
@ -309,16 +315,17 @@ class Plotter(object):
plot_ctrl.PlotLayer()
plot_ctrl.ClosePlot()
if create_job:
jobfile_writer.AddGbrFile(layer.layer,
os.path.basename(plot_ctrl.GetPlotFileName()));
jobfile_writer.AddGbrFile(layer.layer, os.path.basename(
plot_ctrl.GetPlotFileName()))
if create_job:
base_fn = os.path.dirname(plot_ctrl.GetPlotFileName())+'/'+os.path.basename(file_name)
base_fn = os.path.join(
os.path.dirname(plot_ctrl.GetPlotFileName()),
os.path.basename(file_name))
base_fn = os.path.splitext(base_fn)[0]
job_fn = base_fn+'-job.gbrjob'
jobfile_writer.CreateJobFile(job_fn)
def _configure_excellon_drill_writer(self, board, offset, options):
drill_writer = pcbnew.EXCELLON_WRITER(board)
@ -373,25 +380,24 @@ class Plotter(object):
gen_report = to.generate_report
if gen_drill:
logger.debug("Generating drill files in {}"
.format(outdir))
logger.debug("Generating drill files in "+outdir)
if gen_map:
drill_writer.SetMapFileFormat(to.map_options.type)
logger.debug("Generating drill map type {} in {}"
.format(to.map_options.type, outdir))
.format(to.map_options.type, outdir))
drill_writer.CreateDrillandMapFilesSet(outdir, gen_drill, gen_map)
if gen_report:
drill_report_file = os.path.join(outdir,
to.report_options.filename)
logger.debug("Generating drill report: {}"
.format(drill_report_file))
logger.debug("Generating drill report: "+drill_report_file)
drill_writer.GenDrillReportFile(drill_report_file)
def _do_position_plot_ascii(self, board, plot_ctrl, output, columns, modulesStr, maxSizes):
def _do_position_plot_ascii(self, board, plot_ctrl, output, columns,
modulesStr, maxSizes):
to = output.options.type_options
outdir = plot_ctrl.GetPlotOptions().GetOutputDirectory()
if not os.path.exists(outdir):
@ -459,7 +465,8 @@ class Plotter(object):
if bothf is not None:
bothf.close()
def _do_position_plot_csv(self, board, plot_ctrl, output, columns, modulesStr):
def _do_position_plot_csv(self, board, plot_ctrl, output, columns,
modulesStr):
to = output.options.type_options
outdir = plot_ctrl.GetPlotOptions().GetOutputDirectory()
if not os.path.exists(outdir):
@ -517,8 +524,9 @@ class Plotter(object):
# Format all strings
modules = []
for m in sorted(board.GetModules(), key=operator.methodcaller('GetReference')):
if (to.only_smd and m.GetAttributes()==1) or not to.only_smd:
for m in sorted(board.GetModules(),
key=operator.methodcaller('GetReference')):
if (to.only_smd and m.GetAttributes() == 1) or not to.only_smd:
center = m.GetCenter()
# See PLACE_FILE_EXPORTER::GenPositionData() in
# export_footprints_placefile.cpp for C++ version of this.
@ -539,10 +547,11 @@ class Plotter(object):
maxlengths[col] = max(maxlengths[col], len(modules[row][col]))
if to.format.lower() == 'ascii':
self._do_position_plot_ascii(board, plot_ctrl, output, columns, modules,
maxlengths)
self._do_position_plot_ascii(board, plot_ctrl, output, columns,
modules, maxlengths)
elif to.format.lower() == 'csv':
self._do_position_plot_csv(board, plot_ctrl, output, columns, modules)
self._do_position_plot_csv(board, plot_ctrl, output, columns,
modules)
else:
raise PlotError("Format is invalid: {}".format(to.format))
@ -564,10 +573,11 @@ class Plotter(object):
cur = os.path.join(outdir, os.path.splitext(brd_file)[0]) + '.pdf'
new = os.path.join(outdir, to.output)
logger.debug('Moving '+cur+' -> '+new)
os.rename(cur,new)
os.rename(cur, new)
def _do_pcb_print(self, board, plot_ctrl, output, brd_file):
check_script(misc.CMD_PCBNEW_PRINT_LAYERS,misc.URL_PCBNEW_PRINT_LAYERS,'1.1.2')
check_script(misc.CMD_PCBNEW_PRINT_LAYERS,
misc.URL_PCBNEW_PRINT_LAYERS, '1.1.2')
to = output.options.type_options
outdir = plot_ctrl.GetPlotOptions().GetOutputDirectory()
cmd = [misc.CMD_PCBNEW_PRINT_LAYERS,
@ -592,7 +602,7 @@ class Plotter(object):
self._do_ibom(board, plot_ctrl, output, brd_file)
def _do_kibom(self, board, plot_ctrl, output, brd_file):
check_script(misc.CMD_KIBOM,misc.URL_KIBOM)
check_script(misc.CMD_KIBOM, misc.URL_KIBOM)
to = output.options.type_options
format = to.format.lower()
outdir = plot_ctrl.GetPlotOptions().GetOutputDirectory()
@ -600,7 +610,8 @@ class Plotter(object):
os.makedirs(outdir)
prj = os.path.splitext(os.path.relpath(brd_file))[0]
logger.debug('Doing BoM, format '+format+' prj: '+prj)
cmd = [ misc.CMD_KIBOM, prj+'.xml', os.path.join(outdir, prj)+'.'+format ]
cmd = [misc.CMD_KIBOM, prj+'.xml',
os.path.join(outdir, prj)+'.'+format]
logger.debug('Running: '+str(cmd))
try:
check_output(cmd, stderr=STDOUT)
@ -609,15 +620,15 @@ class Plotter(object):
exit(misc.BOM_ERROR)
def _do_ibom(self, board, plot_ctrl, output, brd_file):
check_script(misc.CMD_IBOM,misc.URL_IBOM)
check_script(misc.CMD_IBOM, misc.URL_IBOM)
outdir = plot_ctrl.GetPlotOptions().GetOutputDirectory()
if not os.path.exists(outdir):
os.makedirs(outdir)
prj = os.path.splitext(os.path.relpath(brd_file))[0]
logger.debug('Doing Interactive BoM, prj: '+prj)
cmd = [ misc.CMD_IBOM, brd_file,
'--dest-dir', outdir,
'--no-browser', ]
cmd = [misc.CMD_IBOM, brd_file,
'--dest-dir', outdir,
'--no-browser', ]
to = output.options.type_options
if to.blacklist:
cmd.append('--blacklist')
@ -766,7 +777,6 @@ class Plotter(object):
elif output.options.type == PCfg.OutputOptions.PDF_PCB_PRINT:
self._configure_pcb_print_opts(po, output)
po.SetDrillMarksType(opts.drill_marks)
# We'll come back to this on a per-layer basis

View File

@ -8,9 +8,14 @@ import logging
# Default domain, base name for the tool
domain = 'kilog'
def get_logger(name=None):
"""Get a module for a submodule or the root logger if no name is provided"""
return logging.getLogger(domain+'.'+name) if name else logging.getLogger(domain)
"""Get a module for a submodule or the root logger if no name is
provided"""
if name:
return logging.getLogger(domain+'.'+name)
return logging.getLogger(domain)
def set_domain(name):
"""Set the base name for the tool"""
@ -19,7 +24,8 @@ def set_domain(name):
def init(verbose, quiet):
"""Initialize the logging feature using a custom format and the specified verbosity level"""
"""Initialize the logging feature using a custom format and the specified
verbosity level"""
log_level = logging.INFO
if verbose:
@ -27,7 +33,7 @@ def init(verbose, quiet):
if quiet:
log_level = logging.WARNING
logger=get_logger()
logger = get_logger()
logger.setLevel(log_level)
ch = logging.StreamHandler()
ch.setFormatter(CustomFormatter())
@ -40,20 +46,21 @@ class CustomFormatter(logging.Formatter):
"""Logging Formatter to add colors"""
if sys.stderr.isatty():
grey = "\x1b[38;21m"
yellow = "\x1b[93;1m"
red = "\x1b[91;1m"
bold_red = "\x1b[91;21m"
cyan = "\x1b[36;1m"
reset = "\x1b[0m"
grey = "\x1b[38;21m"
yellow = "\x1b[93;1m"
red = "\x1b[91;1m"
bold_red = "\x1b[91;21m"
cyan = "\x1b[36;1m"
reset = "\x1b[0m"
else:
grey = ""
yellow = ""
red = ""
bold_red = ""
cyan = ""
reset = ""
#format = "%(asctime)s - %(name)s - %(levelname)s - %(message)s (%(filename)s:%(lineno)d)"
grey = ""
yellow = ""
red = ""
bold_red = ""
cyan = ""
reset = ""
# format = "%(asctime)s - %(name)s - %(levelname)s - %(message)s "
# "(%(filename)s:%(lineno)d)"
format = "%(levelname)s:%(message)s (%(name)s - %(filename)s:%(lineno)d)"
format_simple = "%(message)s"

View File

@ -395,6 +395,7 @@ class IBoMOptions(TypeOptions):
self.blacklist = None
self.name_format = None
class SchPrintOptions(TypeOptions):
def __init__(self):