Commit 04fec273 authored by Maxime Perrotin's avatar Maxime Perrotin
Browse files

Clean code

parent 925151c4
......@@ -16,7 +16,7 @@
__author__ = "Maxime Perrotin"
__license__ = "LGPLv3"
__version__ = "1.0.4"
__version__ = "1.0.5"
__url__ = "http://taste.tuxfamily.org"
import sys
......
......@@ -47,7 +47,7 @@ import opengeode.undoCommands as undo
try:
import dataview_uniq_asn as ASN1
except ImportError:
print 'No Python A mapper generated dataview, SDL handler cannot be used'
#print 'No Python A mapper generated dataview, SDL handler cannot be used'
ASN1 = None
# Unicode separator used by Opengeode in the Ada backend
......
......@@ -30,6 +30,7 @@ import optparse
import os
import logging
import tempfile
import traceback
from shutil import rmtree
import resources
......@@ -39,12 +40,21 @@ __version__ = '1.0.0'
__licence__ = 'LGPL v3'
__url__ = 'http://taste.tuxfamily.org'
from ColorFormatter import ColorFormatter
# Set up the logging facilities
logger = logging.getLogger(__name__)
console = logging.StreamHandler(sys.__stdout__)
console.setFormatter(ColorFormatter())
logger.addHandler(console)
try:
from PySide.QtCore import QFile
from PySide.QtCore import QObject
from PySide.QtGui import QApplication, QToolButton
from PySide.QtUiTools import QUiLoader
from opengeode.Asn1scc import parse_asn1, ASN1
import opengeode.Asn1scc as asn1scc
asn1scc.LOG = logger
except ImportError:
print 'PySide is missing. You must install it...'
print 'Try "sudo apt-get install python-pyside"'
......@@ -61,25 +71,9 @@ try:
# sys.path.append('.')
from asn1_value_editor import asn1Editor
from vn import fromValueNotationToPySide, toASN1ValueNotation
from ColorFormatter import ColorFormatter
except:
usable = False
#******************************************************************************
# Set Logger for module
#******************************************************************************
logger = logging.getLogger(__name__)
try:
from logging import NullHandler
except ImportError:
# This class is null handler to be compatible with python 2.5
class NullHandler(logging.Handler):
def emit(self, record):
pass
h = NullHandler()
logger.addHandler(h)
def asn1sccToasn1ValueEditorTypes(dataview, name, asntype):
''' Convert an ASN.1 type from the Python AST of asn1scc v3
......@@ -155,41 +149,16 @@ class SingleValueEditor(QObject):
self.parent = parent
self.tc = {}
self.tempdir = tempfile.mkdtemp()
sys.path.insert(0, self.tempdir)
# Create list of types
# pyDataViewPath = "{}/DataView.py".format(self.tempdir)
# try:
# logger.info(' '.join(["asn1.exe", "-customStg", PYTHON_STG+":", pyDataViewPath, asnFile]))
# subprocess.check_call(
# ["asn1.exe", "-customStg", PYTHON_STG+':'+pyDataViewPath,
# asnFile])
# except subprocess.CalledProcessError:
# logger.error("ASN1 Compiler returned with value < 0")
# raise ValueError("ASN1 Compiler returned with value < 0")
# except:
# logger.error("Missing ASN1 Compiler")
# raise ValueError("Missing ASN1 Compiler")
# try:
# reload(dataView)
# except:
# try:
# dataView = __import__('DataView')
# except ImportError:
# logger.error('DataView import error')
# raise ValueError('DataView import error')
try:
dataView = parse_asn1(tuple(asn1File),
ast_version=ASN1.UniqueEnumeratedNames,
flags=[ASN1.AstOnly])
except (ImportError, NameError) as err:
# Can happen if DataView.py is not there
logger.info(asnFile)
dataView = asn1scc.parse_asn1([asnFile],
ast_version=asn1scc.ASN1.UniqueEnumeratedNames,
flags=[asn1scc.ASN1.AstOnly])
except (ImportError, NameError, TypeError) as err:
logger.error('Error loading ASN.1 model')
logger.debug(str(err))
except TypeError as err:
logger.debug(traceback.format_exc())
raise ValueError('ASN.1 compiler failed - {}'.format(str(err)))
raise
# convert dataView types to a list of tc as needed by asn1-value-editor
for t, v in dataView.types.items():
......@@ -226,7 +195,7 @@ class SingleValueEditor(QObject):
self.widgets[asnType]['editor'].hideExtraColumns()
self.widgets[asnType]['editor'].setAsn1Model(pyType)
self.initializedWidgets = True
logger.info("Sucesfully created new Single Value Editor")
logger.info("Succesfully created new Single Value Editor")
def _asnTypeWidget(self, name, asnType):
......@@ -257,9 +226,6 @@ class SingleValueEditor(QObject):
self.widgets[name]['editor'].hideExtraColumns()
self.widgets[name]['editor'].setAsn1Model(pyType)
# TODO: Log logger
# Isn't better make widget for type, no for param?
# def _newType(self, types):
def editValue(self, param, defValue=None):
return self.editParam(param, defValue)
......@@ -292,10 +258,6 @@ class SingleValueEditor(QObject):
u""" Return the list of types declared within asn file """
return self.tc.keys()
def cleanUp(self):
''' Remove temp files '''
rmtree(self.tempdir)
def main():
# Exit app on Ctrl-C
......@@ -304,12 +266,7 @@ def main():
usage = 'usage: asn1_value_editor -a file.asn [-t type] [-d default value]'
version = 'ASN.1 Value Editor %s' % (__version__)
# Set up the logging facilities
log = logging.getLogger("asn1-editor")
console = logging.StreamHandler(sys.__stdout__)
console.setFormatter(ColorFormatter())
log.addHandler(console)
log.info('Starting ASN.1 Value Editor')
logger.info('Starting ASN.1 Value Editor')
# Parse the command line
parser = optparse.OptionParser(usage=usage, version=version)
......@@ -319,18 +276,18 @@ def main():
parser.add_option('-d', '--value', dest='asnValue', help='Value of the variable you want to edit')
options, args = parser.parse_args()
if options.verbose:
log.setLevel(logging.DEBUG)
logger.setLevel(logging.DEBUG)
else:
log.setLevel(logging.INFO)
logger.setLevel(logging.INFO)
if options.asn is None or options.asnType is None:
log.error('You must specify an ASN.1 file and specify a type. Check --help for more info')
logger.error('You must specify an ASN.1 file and specify a type. Check --help for more info')
sys.exit(-1)
log.debug('ASN.1 File = ' + options.asn)
log.debug('ASN.1 Type = ' + options.asnType)
logger.debug('ASN.1 File = ' + options.asn)
logger.debug('ASN.1 Type = ' + options.asnType)
if options.asnValue is not None:
log.debug('ASN.1 Value = ' + options.asnValue)
logger.debug('ASN.1 Value = ' + options.asnValue)
# Define a Qt application (mandatory)
app = QApplication(sys.argv)
......@@ -343,7 +300,7 @@ def main():
# Open the value editor and retrieve the value, if Cancel has not been pressed
result = s.editParam(options.asnType, options.asnValue)
s.cleanUp()
# s.cleanUp()
if result is not None:
print result
sys.exit(0)
......
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment