diff --git a/.flake8 b/.flake8 index 4362f4db229d99a71ebbc77bfa3c3b2f8ca50ad3..8e4424874f40d99fdf4d6361f1c0928be59217b4 100644 --- a/.flake8 +++ b/.flake8 @@ -15,7 +15,6 @@ exclude = MantidPlot, MantidQt, QtPropertyBrowser, - scripts/lib1to2, scripts/test, Testing/PerformanceTests, Testing/SystemTests/lib, diff --git a/buildconfig/CMake/PylintSetup.cmake b/buildconfig/CMake/PylintSetup.cmake index bb14937613781d0dd0d99c1774d53c1c41fa18e3..0e79044befdbaa3720fe6edadbcc36cb406f40e9 100644 --- a/buildconfig/CMake/PylintSetup.cmake +++ b/buildconfig/CMake/PylintSetup.cmake @@ -32,7 +32,6 @@ if ( PYLINT_FOUND ) docs/sphinxext/mantiddoc ) set ( PYLINT_EXCLUDES - scripts/lib1to2 scripts/test Testing/SystemTests/tests/analysis/reference ) diff --git a/docs/source/api/python/changes.rst b/docs/source/api/python/changes.rst deleted file mode 100644 index 4bc9c8651fc33cdbc9dee6bd816c91a5185bbd3c..0000000000000000000000000000000000000000 --- a/docs/source/api/python/changes.rst +++ /dev/null @@ -1,131 +0,0 @@ -.. _pythonapi-changes: - -============================= - Changes between 1.0 and 2.0 -============================= - -.. note:: - - This page is intended for those users who have used Python in Mantid v1.x. For - new users, see the `getting started guides <http://www.mantidproject.org/Main_Page>`_. - -After feedback from the usage of Python within Mantid it was decided that -some changes to the API would be helpful to make general usage simpler. Unfortunately, -it was not possible to make these changes without breaking backwards compatability. - -It was therefore decided that a new API would be introduced, running alongside -the existing API for now, to cope with these changes. This page describes the high-level -changes. - -Overview --------- - -The new-style API is now the default in MantidPlot so if all of your scripts run here then -you do not need to worry about importing the correct modules, it has already been done -for you. If you run from a stand-alone interpreter then the quickest way to get access to -the new API is - -.. code-block:: python - - from mantid.simpleapi import * - -Changes -------- - -* The *MantidFramework* module no longer exists, it has been replaced with the *mantid* package, i.e - - * *import MantidFramework* -> *import mantid* - -* The *mtd* object can now only be used to access workspaces from Mantid. In the v1 API there - were many additional functions attached to *mtd* such as *sendLogMessage*, *deleteWorkspace* and *settings*. These - are no longer available, there replacements are: - - * *mtd.initialize()* has been removed and has no counterpart as it is unnecessary - * *mtd.sendLogMessage("msg")* -> *logger.information("msg")* - * *mtd.deleteWorkspace(ws)* -> *DeleteWorkspace(ws)* - * *mtd.settings* -> *config* - * *mtd.getSettings* -> *config* - * *mtd.workspaceExists("ws")* -> *mtd.doesExist("ws")* - * *mtd.settings.facility* -> *config.getFacility* - * *mtd.getConfigProperty* -> *config.getString* - -* *mtd[]* will now raise an *KeyError* if a workspace does not exist rather than returning *None*. - -* The *isGroup* function on a workspace no longer exists. To test for a group use the Python *isinstance* function:: - - ws = mtd["name"] - from mantid.api import WorkspaceGroup # (only required as while the old API still exists.) - if isinstance(ws, WorkspaceGroup): - print "is group" - else: - print "is not a group" - -* The *getSampleDetails()* function has been removed. It should be replaced with *getRun()*. - -* The Axis functions *createNumericAxis*, *createTextAxis*, *createSpectraAxis* have been removed. A spectra axis can no longer be created - from Python as it is the default workspace axis & changing it almost always results in unexpected behaviour. The functions have been - replaced, they new ones take the same arguments, with: - - * *createNumericAxis* -> *NumericAxis.create* - * *createTextAxis* -> *TextAxis.create* - -* The *.workspace()* function on algorithm functions has been removed & they now return their outputs (see here for more details), i.e.:: - - run = Load('SomeRunFile.ext') - print run.getNumberHistograms() - ei, mon_peak, mon_index, tzero = GetEi(run, 1,2, 12.0) # This will run GetEi and return the outputs as a tuple and the Python will unpack them for you - -* The output workspace name is taken from the variable that it is assigned to:: - - run = Load('SomeRunFile.ext') # loads the file into a workspace called "run" - -* It is still possible provide a different workspace name and use mtd:: - - run = Load(Filename='SomeRunFile.ext', OutputWorkspace="rawfile") # name in mantid will be "rawfile" - rawfile = mtd["rawfile"] - print run.getNumberHistograms() - print rawfile.getNumberHistograms() - -* The *qti* module no longer exists. All user scripts should simply use the *mantidplot* module which contains - all of the *qti* functionality but adds protection against crashes from closed windows. - -* There have also been changes with Python algorithm syntax. - -Automatic Migration -------------------- - -A script is included with the distribution that is able to translate simple scripts from the the old API to the new API. It covers the basics of the replacements mentioned -above along with converting some algorithm calls. It will create a backup of the original script with the string *.mantidbackup* appended to it. Currently the script -does not handle - -* old algorithm calls that use a return value, e.g. alg = Load('SomeRunFile.ext','runWS') -* Python algorithms. - -Any script containing the above will raise an error in the migration process and restore the original script from the backup. - -An old API algorithm call that does **NOT** use a return value, such as - -.. code-block:: python - - Load('SomeRunFile.ext','runWS') - -which will be translated to - -.. code-block:: python - - runWS = Load(Filename='SomeRunFile.ext') - -along with any of the text replacements mentioned in the previous section - -In order to run the script you will need to use the command line. On Windows: click start, run and type cmd; on OS X and Linux: open a terminal window. To run the script type:: - - python [MANTIDINSTALL]/scripts/migrate1to2.py file - -where [MANTIDINSTALL] should be replaced by the location of the mantid install: - -* Windows: C:/MantidInstall (only the default, please put the actual location) -* Mac OS X: /Applications/MantidPlot.app -* Linux: /opt/Mantid - -and *file* should be replaced by the path to a single script file. - diff --git a/docs/source/api/python/index.rst b/docs/source/api/python/index.rst index 553a7e12812a2da2dff8b57f2cc1786c183d60c3..18e44ea86b65e6f8bd0aad25756ffff38c738c0d 100644 --- a/docs/source/api/python/index.rst +++ b/docs/source/api/python/index.rst @@ -16,8 +16,6 @@ Reference mantid <mantid/index> mantidplot <mantidplot/index> -Changes between version 1.0 and 2.0 of the API are described :ref:`here <pythonapi-changes>`. - .. toctree:: :hidden: diff --git a/scripts/CMakeLists.txt b/scripts/CMakeLists.txt index f4bbb62ff389494e5e9489aba460c30ce3874d2b..4722740318f42e5d152f15bb251a1592acda7a18 100644 --- a/scripts/CMakeLists.txt +++ b/scripts/CMakeLists.txt @@ -3,7 +3,6 @@ add_subdirectory(FilterEvents) add_subdirectory(HFIRPowderReduction) add_subdirectory(Interface/ui) -add_subdirectory(lib1to2/gui) add_subdirectory(TofConverter) add_subdirectory(HFIR_4Circle_Reduction) @@ -13,7 +12,6 @@ add_custom_target(CompilePyUI DEPENDS CompileUIHFIRPowderReduction CompileUITofConverter CompileUIUI - CompileUILib1To2 CompileUIHFIR_4Circle_Reduction ) @@ -23,7 +21,6 @@ set_property ( TARGET CompileUIFilterEvents PROPERTY FOLDER "CompilePyUI" ) set_property ( TARGET CompileUIHFIRPowderReduction PROPERTY FOLDER "CompilePyUI" ) set_property ( TARGET CompileUITofConverter PROPERTY FOLDER "CompilePyUI" ) set_property ( TARGET CompileUIUI PROPERTY FOLDER "CompilePyUI" ) -set_property ( TARGET CompileUILib1To2 PROPERTY FOLDER "CompilePyUI" ) set_property ( TARGET CompileUIHFIR_4Circle_Reduction PROPERTY FOLDER "CompilePyUI" ) set ( TEST_PY_FILES diff --git a/scripts/lib1to2/__init__.py b/scripts/lib1to2/__init__.py deleted file mode 100644 index 48ddb6fcc9eeb7dff502002a35b4f3d753a17df2..0000000000000000000000000000000000000000 --- a/scripts/lib1to2/__init__.py +++ /dev/null @@ -1 +0,0 @@ -# Intentionally empty \ No newline at end of file diff --git a/scripts/lib1to2/astbuilder.py b/scripts/lib1to2/astbuilder.py deleted file mode 100644 index 458700583416962aa215e5093435c7c3b46633fe..0000000000000000000000000000000000000000 --- a/scripts/lib1to2/astbuilder.py +++ /dev/null @@ -1,115 +0,0 @@ -""" -Module containing functions for parsing and modification of an AST. - -Taken from http://pythoscope.org/ and modified -""" -from lib2to3 import pygram, pytree -from lib2to3.pgen2 import driver, token -from lib2to3.pgen2.parse import ParseError -from lib2to3.pygram import python_symbols as syms -from lib2to3.pytree import Node, Leaf - -__all__ = ["EmptyCode", "Newline", "ParseError", "clone", "create_import", - "insert_after", "insert_before", "parse", "parse_fragment", "regenerate"] - -EmptyCode = lambda: Node(syms.file_input, []) -Newline = lambda: Leaf(token.NEWLINE, "\n") - -def quoted_block(text): - return ''.join(["> %s" % line for line in text.splitlines(True)]) - -def clone(tree): - """Clone the tree, preserving its add_newline attribute. - """ - if tree is None: - return None - - new_tree = tree.clone() - if hasattr(tree, 'added_newline') and tree.added_newline: - new_tree.added_newline = True - return new_tree - -def create_import(import_desc): - """Create an AST representing import statement from given description. - - >>> regenerate(create_import("unittest")) - 'import unittest\\n' - >>> regenerate(create_import(("nose", "SkipTest"))) - 'from nose import SkipTest\\n' - """ - if isinstance(import_desc, tuple): - package, name = import_desc - return Node(syms.import_from, - [Leaf(token.NAME, 'from'), - Leaf(token.NAME, package, prefix=" "), - Leaf(token.NAME, 'import', prefix=" "), - Leaf(token.NAME, name, prefix=" "), - Newline()]) - else: - return Node(syms.import_name, - [Leaf(token.NAME, 'import'), - Leaf(token.NAME, import_desc, prefix=" "), - Newline()]) - -def index(node): - """Return index this node is at in parent's children list. - """ - return node.parent.children.index(node) - -def insert_after(node, code): - if not node.parent: - raise TypeError("Can't insert after node that doesn't have a parent.") - node.parent.insert_child(index(node)+1, code) - -def insert_before(node, code): - if not node.parent: - raise TypeError("Can't insert before node that doesn't have a parent.") - node.parent.insert_child(index(node), code) - -def parse(code): - """String -> AST - - Parse the string and return its AST representation. May raise - a ParseError exception. - """ - added_newline = False - if not code.endswith("\n"): - code += "\n" - added_newline = True - - try: - drv = driver.Driver(pygram.python_grammar, pytree.convert) - result = drv.parse_string(code, True) - except ParseError: - print "Had problems parsing:\n%s\n" % quoted_block(code) - raise - - # Always return a Node, not a Leaf. - if isinstance(result, Leaf): - result = Node(syms.file_input, [result]) - - result.added_newline = added_newline - - return result - -def parse_fragment(code): - """Works like parse() but returns an object stripped of the file_input - wrapper. This eases merging this piece of code into other ones. - """ - parsed_code = parse(code) - - if is_node_of_type(parsed_code, 'file_input') and \ - len(parsed_code.children) == 2 and \ - is_leaf_of_type(parsed_code.children[-1], token.ENDMARKER): - return parsed_code.children[0] - return parsed_code - -def regenerate(tree): - """AST -> String - - Regenerate the source code from the AST tree. - """ - if hasattr(tree, 'added_newline') and tree.added_newline: - return str(tree)[:-1] - else: - return str(tree) diff --git a/scripts/lib1to2/astvisitor.py b/scripts/lib1to2/astvisitor.py deleted file mode 100644 index 7d7e11d1b6b95edf9c456aeb177e9f4a881e9626..0000000000000000000000000000000000000000 --- a/scripts/lib1to2/astvisitor.py +++ /dev/null @@ -1,215 +0,0 @@ -""" -Module containing ASTVistor class and helpers useful for traversing -and extracting information from an AST. - -Taken from http://pythoscope.org/ and modified -""" - -from lib2to3 import pytree -from lib2to3.patcomp import compile_pattern -from lib2to3.pgen2 import token -from lib2to3.pytree import Node, Leaf - -__all__ = ["ASTError", "ASTVisitor", "descend", "find_last_leaf", - "get_starting_whitespace", "is_leaf_of_type", "is_node_of_type", - "remove_trailing_whitespace"] - -def descend(tree, visitor_type): - """Walk over the AST using a visitor of a given type and return the visitor - object once done. - """ - visitor = visitor_type() - visitor.visit(tree) - return visitor - -def find_last_leaf(node): - if isinstance(node, Leaf): - return node - else: - return find_last_leaf(node.children[-1]) - -def get_starting_whitespace(code): - whitespace = "" - for child in code.children: - if is_leaf_of_type(child, token.NEWLINE, token.INDENT): - whitespace += child.value - else: - break - return whitespace - -def remove_trailing_whitespace(code): - leaf = find_last_leaf(code) - leaf.prefix = leaf.prefix.replace(' ', '').replace('\t', '') - -class ASTError(Exception): - pass - -def is_leaf_of_type(leaf, *types): - return isinstance(leaf, Leaf) and leaf.type in types - -def is_node_of_type(node, *types): - return isinstance(node, Node) and pytree.type_repr(node.type) in types - -def leaf_value(leaf): - return leaf.value - -def remove_commas(nodes): - def isnt_comma(node): - return not is_leaf_of_type(node, token.COMMA) - return filter(isnt_comma, nodes) - -def remove_defaults(nodes): - ignore_next = False - for node in nodes: - if ignore_next is True: - ignore_next = False - continue - if is_leaf_of_type(node, token.EQUAL): - ignore_next = True - continue - yield node - -def derive_class_name(node): - return str(node).strip() - -def derive_class_names(node): - if node is None: - return [] - elif is_node_of_type(node, 'arglist'): - return map(derive_class_name, remove_commas(node.children)) - else: - return [derive_class_name(node)] - -def derive_argument(node): - if is_leaf_of_type(node, token.NAME): - return node.value - elif is_node_of_type(node, 'tfpdef'): - return tuple(map(derive_argument, - remove_commas(node.children[1].children))) - -def derive_arguments_from_typedargslist(typedargslist): - prefix = '' - for node in remove_defaults(remove_commas(typedargslist.children)): - if is_leaf_of_type(node, token.STAR): - prefix = '*' - elif is_leaf_of_type(node, token.DOUBLESTAR): - prefix = '**' - elif prefix: - yield prefix + derive_argument(node) - prefix = '' - else: - yield derive_argument(node) - -def derive_arguments(node): - if node == []: - return [] - elif is_node_of_type(node, 'typedargslist'): - return list(derive_arguments_from_typedargslist(node)) - else: - return [derive_argument(node)] - -def derive_import_name(node): - if is_leaf_of_type(node, token.NAME): - return node.value - elif is_node_of_type(node, 'dotted_as_name'): - return (derive_import_name(node.children[0]), - derive_import_name(node.children[2])) - elif is_node_of_type(node, 'dotted_name'): - return "".join(map(leaf_value, node.children)) - -def derive_import_names(node): - if node is None: - return None - elif is_node_of_type(node, 'dotted_as_names', 'import_as_names'): - return map(derive_import_name, - remove_commas(node.children)) - else: - return [derive_import_name(node)] - - -class ASTVisitor(object): - DEFAULT_PATTERNS = [ - ('_visit_all', "file_input< nodes=any* >"), - ('_visit_all', "suite< nodes=any* >"), - ('_visit_class', "body=classdef< 'class' name=NAME ['(' bases=any ')'] ':' any >"), - ('_visit_function', "body=funcdef< 'def' name=NAME parameters< '(' [args=any] ')' > ':' any >"), - ('_visit_import', "body=import_name< 'import' names=any > | body=import_from< 'from' import_from=any 'import' names=any >"), - ('_visit_lambda_assign', "expr_stmt< name=NAME '=' lambdef< 'lambda' [args=any] ':' any > >"), - ('_visit_main_snippet', "body=if_stmt< 'if' comparison< '__name__' '==' (\"'__main__'\" | '\"__main__\"' ) > ':' any >"), - ] - - def __init__(self): - self.patterns = [] - for method, pattern in self.DEFAULT_PATTERNS: - self.register_pattern(method, pattern) - - def register_pattern(self, method, pattern): - """Register method to handle given pattern. - """ - self.patterns.append((method, compile_pattern(pattern))) - - def visit(self, tree): - """Main entry point of the ASTVisitor class. - """ - if isinstance(tree, Leaf): - self.visit_leaf(tree) - elif isinstance(tree, Node): - self.visit_node(tree) - elif isinstance(tree, list): - for subtree in tree: - self.visit(subtree) - else: - raise ASTError("Unknown tree type: %r." % tree) - - def visit_leaf(self, leaf): - pass - - def visit_node(self, node): - for method, pattern in self.patterns: - results = {} - if pattern.match(node, results): - getattr(self, method)(results) - break - else: - # For unknown nodes simply descend to their list of children. - self.visit(node.children) - - def visit_class(self, name, bases, body): - self.visit(body.children) - - def visit_function(self, name, args, body): - self.visit(body.children) - - def visit_import(self, names, import_from, body): - pass - - def visit_lambda_assign(self, name, args): - pass - - def visit_main_snippet(self, body): - pass - - def _visit_all(self, results): - self.visit(results['nodes']) - - def _visit_class(self, results): - self.visit_class(name=results['name'].value, - bases=derive_class_names(results.get('bases')), - body=results['body']) - - def _visit_function(self, results): - self.visit_function(name=results['name'].value, - args=derive_arguments(results.get('args', [])), - body=results['body']) - - def _visit_import(self, results): - self.visit_import(names=derive_import_names(results['names']), - import_from=derive_import_name(results.get('import_from')), - body=results['body']) - - def _visit_lambda_assign(self, results): - self.visit_lambda_assign(name=results['name'].value, - args=derive_arguments(results.get('args', []))) - - def _visit_main_snippet(self, results): - self.visit_main_snippet(body=results['body']) diff --git a/scripts/lib1to2/grammar.py b/scripts/lib1to2/grammar.py deleted file mode 100644 index aa1be750b7c7cff478429ff41c7cd5667b29b02e..0000000000000000000000000000000000000000 --- a/scripts/lib1to2/grammar.py +++ /dev/null @@ -1,40 +0,0 @@ -""" -Defines the grammar translation from version 1 to version 2 of Mantid's Python API. -""" -import messages -import rules -import astbuilder - -class Grammar(object): - """ - Translation from v1->v2 of the Python API - """ - - def __init__(self): - pass - - def translate(self, orig_code): - """ - Translates the input string, assuming it contains code written in - version 1 of Mantid's Python API, to version 2 of the PythonAPI - - @param orig_code The original code string - @returns The translated string - """ - errors = [] - # Simple string replacements - string_replace = rules.SimpleStringReplace() - translated = string_replace.apply(orig_code) - - api_call_replace = rules.SimpleAPIFunctionCallReplace() - # Convert to an abstract syntax tree - # (uses the lib2to3 libraries that can convert AST back to source code) - tree = astbuilder.parse(translated) - tree = api_call_replace.apply_to_ast(tree) - - errors.extend(api_call_replace.errors) - # No python algorithm support yet - if "PythonAlgorithm" in orig_code: - errors.append("Cannot fully migrate PythonAlgorithm.") - - return astbuilder.regenerate(tree), errors diff --git a/scripts/lib1to2/gui/CMakeLists.txt b/scripts/lib1to2/gui/CMakeLists.txt deleted file mode 100644 index 8e23418f58fba8429ac3e39bd2e430f0774e10fe..0000000000000000000000000000000000000000 --- a/scripts/lib1to2/gui/CMakeLists.txt +++ /dev/null @@ -1,10 +0,0 @@ -include(UiToPy) - -# List of UIs to Auto convert -set( UI_FILES - mainwindow.ui -) - -UiToPy( UI_FILES CompileUILib1To2) - - diff --git a/scripts/lib1to2/gui/__init__.py b/scripts/lib1to2/gui/__init__.py deleted file mode 100644 index 16c698fea0a264b10ac1ae6e6725646efe026d27..0000000000000000000000000000000000000000 --- a/scripts/lib1to2/gui/__init__.py +++ /dev/null @@ -1,5 +0,0 @@ -""" -Defines the simple GUI for the migration process -""" - -from main import start \ No newline at end of file diff --git a/scripts/lib1to2/gui/main.py b/scripts/lib1to2/gui/main.py deleted file mode 100644 index 51f73e4800f8817407e62328088d41df11b9abb4..0000000000000000000000000000000000000000 --- a/scripts/lib1to2/gui/main.py +++ /dev/null @@ -1,28 +0,0 @@ -""" - Defines the entry point for the GUI app -""" -import lib1to2.messages as messages -from PyQt4.QtGui import QApplication -from mainwindow import MainWindow - -def _qtapp(): - """Returns a QApplication object - If one does not already then one is created - """ - qapp = QApplication.instance() - if qapp is None: - qapp = QApplication([]) - return qapp - -def start(options, args): - """Starts the GUI and passes the command line - arguments along to the GUI - @param options A dictionary of the options passed to the migration - @param args The positional command line arguments - load into the GUI - """ - messages.notify("Starting GUI") - app = _qtapp() - window = MainWindow() - window.show() - return app.exec_() \ No newline at end of file diff --git a/scripts/lib1to2/gui/mainwindow.py b/scripts/lib1to2/gui/mainwindow.py deleted file mode 100644 index e001821d63b8b0725321ee7f92e9854fa25cfd7c..0000000000000000000000000000000000000000 --- a/scripts/lib1to2/gui/mainwindow.py +++ /dev/null @@ -1,36 +0,0 @@ -""" - The main window for the GUI -""" -from PyQt4.QtCore import SIGNAL, SLOT, pyqtSlot -from PyQt4.QtGui import * -from ui_mainwindow import Ui_MainWindow - -class MainWindow(QMainWindow, Ui_MainWindow): - """The main window for the application - """ - - def __init__(self, parent = None): - """ - Constructs and lays out the main window - """ - QMainWindow.__init__(self, parent) - self.setupUi(self) - - self.connect(self.closeAction, SIGNAL("triggered()"), - qApp, SLOT("quit()")) - - @pyqtSlot() - def chooseFiles(): - """Opens a file browser to allow a user - to select files for migration. - Emits the filesSelected() signal if any files - are selected - """ - pass - - @pyqtSlot() - def addToTable(files): - """ - Adds files to the table, setting the - status to - """ \ No newline at end of file diff --git a/scripts/lib1to2/gui/mainwindow.ui b/scripts/lib1to2/gui/mainwindow.ui deleted file mode 100644 index 80389bb3f11d33954d8888087cf23a0c501da443..0000000000000000000000000000000000000000 --- a/scripts/lib1to2/gui/mainwindow.ui +++ /dev/null @@ -1,133 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<ui version="4.0"> - <class>MainWindow</class> - <widget class="QMainWindow" name="MainWindow"> - <property name="geometry"> - <rect> - <x>0</x> - <y>0</y> - <width>430</width> - <height>278</height> - </rect> - </property> - <property name="windowTitle"> - <string>Python Script Migration</string> - </property> - <widget class="QWidget" name="centralwidget"> - <layout class="QVBoxLayout" name="verticalLayout"> - <item> - <widget class="QScrollArea" name="scrollArea"> - <property name="widgetResizable"> - <bool>true</bool> - </property> - <widget class="QWidget" name="scrollAreaWidgetContents"> - <property name="geometry"> - <rect> - <x>0</x> - <y>0</y> - <width>410</width> - <height>217</height> - </rect> - </property> - <layout class="QVBoxLayout" name="verticalLayout_2"> - <item> - <widget class="QTableWidget" name="tableWidget"> - <property name="sizePolicy"> - <sizepolicy hsizetype="Expanding" vsizetype="Expanding"> - <horstretch>0</horstretch> - <verstretch>0</verstretch> - </sizepolicy> - </property> - <property name="minimumSize"> - <size> - <width>300</width> - <height>150</height> - </size> - </property> - <attribute name="horizontalHeaderCascadingSectionResizes"> - <bool>false</bool> - </attribute> - <attribute name="horizontalHeaderStretchLastSection"> - <bool>false</bool> - </attribute> - <column> - <property name="text"> - <string>Script File</string> - </property> - </column> - <column> - <property name="text"> - <string>Status</string> - </property> - </column> - </widget> - </item> - <item> - <layout class="QHBoxLayout" name="horizontalLayout"> - <item> - <spacer name="horizontalSpacer"> - <property name="orientation"> - <enum>Qt::Horizontal</enum> - </property> - <property name="sizeHint" stdset="0"> - <size> - <width>40</width> - <height>20</height> - </size> - </property> - </spacer> - </item> - <item> - <widget class="QPushButton" name="addFileAction"> - <property name="text"> - <string>Add File(s)</string> - </property> - </widget> - </item> - <item> - <widget class="QPushButton" name="migrateAction"> - <property name="text"> - <string>Migrate</string> - </property> - </widget> - </item> - </layout> - </item> - </layout> - </widget> - </widget> - </item> - </layout> - </widget> - <widget class="QStatusBar" name="statusbar"/> - <widget class="QMenuBar" name="menubar"> - <property name="geometry"> - <rect> - <x>0</x> - <y>0</y> - <width>430</width> - <height>21</height> - </rect> - </property> - <widget class="QMenu" name="menuFile"> - <property name="title"> - <string>File</string> - </property> - <addaction name="separator"/> - <addaction name="separator"/> - <addaction name="closeAction"/> - </widget> - <addaction name="menuFile"/> - </widget> - <action name="closeAction"> - <property name="text"> - <string>Close</string> - </property> - <property name="toolTip"> - <string>Close the application</string> - </property> - </action> - </widget> - <resources/> - <connections/> -</ui> diff --git a/scripts/lib1to2/main.py b/scripts/lib1to2/main.py deleted file mode 100644 index d82df3e7e2b65f1839944239d9986bf0eb41e5dd..0000000000000000000000000000000000000000 --- a/scripts/lib1to2/main.py +++ /dev/null @@ -1,51 +0,0 @@ -""" -Entry point for the 1->2 migration script -""" -import messages -import migrate -import gui - -import optparse - -def main(args): - """ - Starts the migration process - - @param argv The arguments passed to the script - """ - parser = optparse.OptionParser(usage="migrate1to2 [options] file|dir") - parser.add_option("-n", "--nobackups", action="store_true", default=False, - help="Don't write backups for modified files. WARNING: This operation cannot be undone, use with care") - parser.add_option("-g", "--gui", action="store_true", default=False, - help="Starts the GUI") - - options, args = parser.parse_args(args) - backup = not options.nobackups - files = get_files(args[0]) - - if options.gui: - retcode = gui.start(args, options) - else: - retcode = migrate.run(files, backup) - - # Any clean up code - return retcode - -def get_files(path): - """ - Returns the list of files to work on - @param path :: A string interpreted as a file or directory - """ - import os - if not type(path) == str: - raise ValueError("Expected string argument specfying file or path. Found %s" % type(path)) - - py_files = [] - if os.path.isfile(path): - py_files.append(path) - else: - for root, dirs, files in os.walk(path): - for filename in files: - if filename.endswith(".py"): - py_files.append(os.path.join(root,filename)) - return py_files diff --git a/scripts/lib1to2/messages.py b/scripts/lib1to2/messages.py deleted file mode 100644 index 369a8b9046f6de43d8654cb7eac24d8d78554c8f..0000000000000000000000000000000000000000 --- a/scripts/lib1to2/messages.py +++ /dev/null @@ -1,17 +0,0 @@ -""" -Defines functions for displaying messages to the user -""" - -__QUIET__ = False - -def quiet(): - """ - """ - return __QUIET__ - -def notify(msg): - """ - Prints a message to the console - """ - if not quiet(): - print msg \ No newline at end of file diff --git a/scripts/lib1to2/migrate.py b/scripts/lib1to2/migrate.py deleted file mode 100644 index 7e15c968696275abf306f5b361f29bf6708bd300..0000000000000000000000000000000000000000 --- a/scripts/lib1to2/migrate.py +++ /dev/null @@ -1,152 +0,0 @@ -""" -Performs the actual migration -""" -import messages -from grammar import Grammar - -import os -import shutil -import traceback - -def run(files, backup=True): - """ - Runs the migration process - - @param files A list of files to migrate - @param backup If true, the files are backed up before running the migration. The - backup file is the filename plus '.mantidbackup' - """ - if len(files) == 0: - messages.notify("Nothing to do!") - return 0 - if type(files) == str: - files = [files] - - reports = [] - for filename in files: - script = ScriptFile(filename, backup) - try: - msg = script.migrate() - except Exception, exc: - traceback.print_exc() - script.restore_backup() - msg = "%s: Backup restored." % (filename) - reports.append(msg) - del script - - messages.notify("\n" + "="*10 + " Report " + "="*10 + "\n") - for report in reports: - messages.notify(str(report)) - - return 0 - - -class ScriptFile(object): - """ - Encapsulates a script file. The migration - process can be run by calling migrate - """ - _filename = None - dobackup = True - backup_ext = '.mantidbackup' - backup_filename = None - grammar = None - - def getfilename(self): - return self._filename - - def setfilename(self, filename): - """Set the filename along with the backup filename - @param filename The full filename of the input - """ - if os.path.exists(filename): - self._filename = filename - self.backup_filename = filename + self.backup_ext - else: - raise ValueError("Invalid path '%s' passed to ScriptFile" % (filename)) - - filename = property(getfilename, setfilename) - - def __init__(self, filename, backup = True): - self.setfilename(filename) - self.dobackup = backup - self.grammar = Grammar() - - def migrate(self): - """ - Migrate the script to the new API - """ - self.backup() - input_file = open(self.filename, 'r') - input_as_str = input_file.read() - input_file.close() - - converted_str, errors = self.grammar.translate(input_as_str) - - filename = self.filename - if len(errors) > 0: - filename = self.filename + ".partial" - errors.append("Partial translation stored in '%s'" % filename) - - output_file = open(filename, 'w') - output_file.write(converted_str) - output_file.close() - - if len(errors) > 0: - raise RuntimeError("\n".join(errors)) - - outcome = MigrationStatus(MigrationStatus.Migrated) - return Report(self.filename, outcome) - - def backup(self): - """ - Backup the file by copying it to - a different filename with the - extension defined by self.backup_ext - """ - if self.dobackup and self.filename is not None: - messages.notify("Backing up %s to %s" % (self.filename, self.backup_filename)) - shutil.copy(self.filename, self.backup_filename) - - def restore_backup(self): - """ - Copies the file from the backup to the original - location - """ - if not self.dobackup: - messages.notify("Cannot restore from backup, no backup was requested") - if os.path.exists(self.backup_filename): - shutil.copy(self.backup_filename, self.filename) - - -class Report(object): - """Reports the outcome of a single migration""" - - _filename = None - _status = None - - def __init__(self, filename, status): - self._filename = filename - self._status = status - - def __str__(self): - """Returns a string representation of the report""" - return "%s: %s" % (self._filename, str(self._status)) - -class MigrationStatus(object): - - Unconverted = 0 - Migrated = 1 - Errors = 2 - - def __init__(self, status): - self.status = status - - def __str__(self): - """Returns the status as a string""" - if self.status == self.Unconverted: - return "Unconverted" - elif self.status == self.Migrated: - return "Successfully migrated" - else: - return "Errors occurred" diff --git a/scripts/lib1to2/rules/__init__.py b/scripts/lib1to2/rules/__init__.py deleted file mode 100644 index 85fd5b797b6fadce659fb7134a00d3d20a549375..0000000000000000000000000000000000000000 --- a/scripts/lib1to2/rules/__init__.py +++ /dev/null @@ -1,5 +0,0 @@ -"""Defines various classes for applying translation rules -""" -from stringreplace import * -from simpleapireplace import * -from pythonalgorithmreplace import * \ No newline at end of file diff --git a/scripts/lib1to2/rules/pythonalgorithmreplace.py b/scripts/lib1to2/rules/pythonalgorithmreplace.py deleted file mode 100644 index 379a6b71251c5b2a0db37e7be2635670b78c81ed..0000000000000000000000000000000000000000 --- a/scripts/lib1to2/rules/pythonalgorithmreplace.py +++ /dev/null @@ -1,20 +0,0 @@ -"""Defines the rules for translation of Python algorithms -from v1 to v2 -""" -import rules - -class PythonAlgorithmReplace(rules.Rules): - - def __init__(self): - rules.Rules.__init__(self) - - def apply(self, text): - """ - Returns a replacement string for the input text - where the python algorithm calls have been replaced - @param text An input string to match - @returns A string containing the replacement or the original text - if no replacement was needed - """ - - return text diff --git a/scripts/lib1to2/rules/rules.py b/scripts/lib1to2/rules/rules.py deleted file mode 100644 index 02c42d076800bc969aee09814588dd416c5815c7..0000000000000000000000000000000000000000 --- a/scripts/lib1to2/rules/rules.py +++ /dev/null @@ -1,19 +0,0 @@ -"""Defines the rules base class and helper functions -""" - -class Rules(object): - - errors = [] - - def apply_to_ast(self, tree): - """ - Apply the transformation to the AST - """ - raise NotImplementedError("Derived classes should implement apply_to_ast()") - - def apply(self, text): - """ - Interface for applying the rules - """ - raise NotImplementedError("Derived classes should implement apply()") - diff --git a/scripts/lib1to2/rules/simpleapireplace.py b/scripts/lib1to2/rules/simpleapireplace.py deleted file mode 100644 index 0932eb309ae55fb830ec2048df40fb2241f98b65..0000000000000000000000000000000000000000 --- a/scripts/lib1to2/rules/simpleapireplace.py +++ /dev/null @@ -1,172 +0,0 @@ -"""Defines the rules for translation of simple API function calls -from v1 to v2 -""" -from lib2to3.pytree import Node, Leaf -from lib2to3.pygram import python_symbols as syms -from ..astvisitor import ASTVisitor, descend - -import mantid - -import rules -import re -import token - -__FUNCTION_CALL_REGEXSTR = r"""(|\w*\s*) # Any variable on the lhs of the function call - (|=\s*) # The equals sign including any whitespace on the right - (\w*) # The function name - \((.*?)\) # The function call arguments (without the parentheses) - (\.workspace\(\)|) # An optional trailing .workspace() call""" - -__FUNCTION_CALL_REGEX__ = re.compile(__FUNCTION_CALL_REGEXSTR, re.VERBOSE) - -__WHITESPACE_REGEX__ = re.compile("(\s*).*") - -__MANTID_ALGS__ = mantid.api.AlgorithmFactory.getRegisteredAlgorithms(True) - -def _is_mantid_algorithm(name): - """Returns true if the given name is a mantid algorithm""" - if type(name) is not str: - raise ValueError("Expected string name found: %s" % str(name)) - return name in __MANTID_ALGS__ - -class SimpleAPIFunctionCallReplace(rules.Rules): - - func_regex = __FUNCTION_CALL_REGEX__ - current_line = None - - def __init__(self): - rules.Rules.__init__(self) - - def apply(self, text): - """ - """ - raise RuntimeError("Simple API replacement can only be applied to an abstract syntax tree." + \ - "See apply_to_ast()") - - def apply_to_ast(self, tree): - """ - Returns a replacement ast tree for the input tree where the simple - API function calls are replaced by improved ones for the new API. - @param tree An AST tree from lib2to3 - @returns A string containing the replacement of the original text - if no replacement was needed - """ - nodes = self.find_simpleapi_nodes(tree) - for name, parent in nodes: - self.apply_to_node(name, parent) - return tree - - def find_simpleapi_nodes(self, tree): - """ - Find the parent nodes that are a call to the simple api - @param tree The abstract syntax tree - """ - visitor = SimpleAPIVisitor() - return visitor.find_parent_nodes(tree) - - def apply_to_node(self, name, parent): - """Given a node and it's function name, assume it is a v1 API call and update it - to version 2. This replaces everything with keywords - """ - # Transform to all keywords - nchildren = len(parent.children) - no_lhs = True - if nchildren == 2: - # Child 0 = whole function call - fn_call_node = parent.children[0] - no_lhs = True - elif nchildren == 3: - self.errors.append("Unable to handle assignment for '%s' algorithm call" % (name)) - return - - # Get the argument list node: child 1 = arglist parent node then child 1 = arg list - arglist_node = fn_call_node.children[1].children[1] - - # Transform to keywords - alg_object = mantid.api.AlgorithmManager.Instance().createUnmanaged(name) - alg_object.initialize() - arglist_node = self.transform_arglist_to_keywords(arglist_node, alg_object) - # Replace node as a new one may have been created - fn_call_node.children[1].children[1] = arglist_node - - def transform_arglist_to_keywords(self, arglist_node, alg_object): - """Takes a node that points to argument list and transforms - it to all keyword=values - @param arglist_node The node that points to the argument list - @param alg_object The algorithm object that corresponds to this list - """ - ordered_props = alg_object.orderedProperties() - # Special case where the arglist has no children - if len(arglist_node.children) == 0: - arglist_node = Node(syms.argument, [Leaf(token.NAME,ordered_props[0]),Leaf(token.EQUAL,"="), - Leaf(arglist_node.type,arglist_node.value)]) - return arglist_node - # Quick check: A 3 arg leaf list with an equals at the 2nd element needs nothing doing - if len(arglist_node.children) == 3 and arglist_node.children[1].type == token.EQUAL: - return arglist_node - - # Construct our argument list from the children to make sure we separate out whole comma-separated - # sections i.e get embedded lists correct - args = [[]] # Each list will be delimited by a comma - nargs = 0 - index = 0 - for node in arglist_node.children: - if node.type == token.COMMA: - args.append(node) - args.append([]) # new arg list - index += 2 # include comma - nargs += 1 - else: - args[index].append(node) - - # Ordered props - prop_index = 0 # List has commas so standard enumerate won't do the trick - arg_nodes = [] # Holds the final node list - for arg_list in args: - if isinstance(arg_list, Leaf): # Must be comma from construction above - arg_nodes.append(arg_list) - else: - first = arg_list[0] - if not (isinstance(first, Node) and first.type == syms.argument): - prop_name = ordered_props[prop_index] - children=[Leaf(token.NAME,prop_name),Leaf(token.EQUAL,"=")] - children.extend(arg_list) - for c in children: - c.parent = None # A new node requires all old parent nodes to be None - arg_nodes.append(Node(syms.argument, children)) - else: - for node in arg_list: - arg_nodes.append(node) - # Move to the next property - prop_index += 1 - - arglist_node.children = arg_nodes - return arglist_node - -#===================================================================================== - -class SimpleAPIVisitor(ASTVisitor): - """A visitor class that is applies the simple API - fixes to the AST - """ - # Stores the found simple API parent nodes in a tuple with their name - # as the first argument - _nodes = [] - - def __init__(self): - ASTVisitor.__init__(self) - - def find_parent_nodes(self, tree): - self.visit(tree) - return self._nodes - - def visit_node(self, node): - if node.type == syms.power: - child_zero = node.children[0] - if hasattr(child_zero, "value") and \ - _is_mantid_algorithm(child_zero.value): - # Make sure we get the whole expression including any assignment - self._nodes.append(tuple([child_zero.value,node.parent])) - - # Ensure we visit the whole tree - self.visit(node.children) diff --git a/scripts/lib1to2/rules/stringreplace.py b/scripts/lib1to2/rules/stringreplace.py deleted file mode 100644 index b198b6e4b2b30044fa514ccc43d087132a796fee..0000000000000000000000000000000000000000 --- a/scripts/lib1to2/rules/stringreplace.py +++ /dev/null @@ -1,55 +0,0 @@ -"""Defines the rules that simple string replacements that can be applied -to the whole text -""" -import rules -import re - -__STRINGREPLACEMENTS__ = [ - (re.compile("from MantidFramework import \*"), "from mantid import *"), - (re.compile("mtd\.initiali(s|z)e\(\)"), ""), - (re.compile("mtd\.initiali(s|z)e\(False\)"), ""), - (re.compile("mtd\.initiali(s|z)e\(True\)"), ""), - (re.compile("import MantidFramework"), "import mantid"), - (re.compile("from mantidsimple import \*"), "from mantid.simpleapi import *"), - (re.compile("from mantidsimple import"), "from mantid.simpleapi import"), - (re.compile("import mantidsimple as"), "import mantid.simpleapi as"), - (re.compile("import mantidsimple"), "import mantid.simpleapi as simpleapi"), - (re.compile("mantidsimple\."), "simpleapi."), - (re.compile("(MantidFramework\.|)(mtd|mantid)\.initiali[z,s]e\(\)"), ""), - (re.compile("MantidFramework\."), "mantid."), - (re.compile("\.getSampleDetails"), ".getRun"), - (re.compile("mtd\.settings\.facility\("), "config.getFacility("), - (re.compile("mtd\.settings"), "config"), - (re.compile("mtd\.getConfigProperty"), "config.getString"), - (re.compile("mtd\.workspaceExists"), "mtd.doesExist"), - (re.compile("(mtd|mantid).sendErrorMessage"), "logger.error"), - (re.compile("(mtd|mantid).sendWarningMessage"), "logger.warning"), - (re.compile("(mtd|mantid).sendLogMessage"), "logger.notice"), - (re.compile("(mtd|mantid).sendInformationMessage"), "logger.information"), - (re.compile("(mtd|mantid).sendDebugMessage"), "logger.debug"), - (re.compile("(mtd|mantid).deleteWorkspace"), "mtd.remove"), - (re.compile("\.workspace\(\)"), "") -] - -class SimpleStringReplace(rules.Rules): - """ - Implements any rules that are simply a matter of matching a pattern - and replacing it with a fixed string - """ - _rules = None - - def __init__(self): - rules.Rules.__init__(self) - self._rules = __STRINGREPLACEMENTS__ - - def apply(self, text): - """ - Returns a replacement string for the input text - with the simple string relpacements definined by the regexes - @param text An input string to match - @returns A string containing the replacement or the original text - if no replacement was needed - """ - for pattern, replacement in self._rules: - text = pattern.sub(replacement, text) - return text diff --git a/scripts/lib1to2/test/MigrationTest.py b/scripts/lib1to2/test/MigrationTest.py deleted file mode 100644 index 238de1ab105a47255ef7b5627e3bfcf11c42d19e..0000000000000000000000000000000000000000 --- a/scripts/lib1to2/test/MigrationTest.py +++ /dev/null @@ -1,49 +0,0 @@ -"""Base class for all Migration tests. Includes common functionality for preparing/removing the files -""" -import unittest -import os - -from lib1to2 import migrate - -class MigrationTest(unittest.TestCase): - - test_filename = None - test_backupname = None - backup_ext = '.mantidbackup' - - def create_test_file(self, contents): - """Writes a test file out to a temporary location""" - self.test_filename = 'MigrationTest_SimpleAPIFunctionCallReplace.py' - self.test_backupname = self.test_filename + self.backup_ext - _temp_file = file(self.test_filename, 'w') - _temp_file.write(contents) - _temp_file.close() - - def remove_test_files(self): - """Remove the test file""" - try: - os.remove(self.test_filename) - os.remove(self.test_backupname) - except OSError: - pass - self.test_filename = None - self.test_backupname = None - - def do_migration(self, input_contents): - """Run the migration process for the input string""" - self.create_test_file(input_contents) - retcode = migrate.run(self.test_filename) - self.assertEquals(retcode, 0) - - def check_outcome(self, original_input, expected_output): - """Checks the outcome of a migration""" - self.assertTrue(os.path.exists(self.test_backupname)) - self.compare_file_contents(self.test_backupname, original_input) - self.compare_file_contents(self.test_filename, expected_output) - - def compare_file_contents(self, filename, expected_contents): - """Compare the file contents with the string""" - migrated_file = file(filename, 'r') - migrated_string = migrated_file.read() - migrated_file.close() - self.assertEquals(migrated_string, expected_contents) diff --git a/scripts/lib1to2/test/PythonAlgorithmReplaceMigrationTest.py b/scripts/lib1to2/test/PythonAlgorithmReplaceMigrationTest.py deleted file mode 100644 index 149799257dd4a10e8f23c59aba444733a42e25b8..0000000000000000000000000000000000000000 --- a/scripts/lib1to2/test/PythonAlgorithmReplaceMigrationTest.py +++ /dev/null @@ -1,102 +0,0 @@ -"""Tests for the migration with Python algorithms -""" -import unittest -import os - -from MigrationTest import MigrationTest - -class PythonAlgorithmlReplaceMigrationTest(MigrationTest): - - def tearDown(self): - """Clean up after a test""" - self.remove_test_files() - - def test_no_property_alg_is_correct(self): - inputstring = \ - """ - from MantidFramework import * - mtd.initialize() - - class MyAlgorithm(PythonAlgorithm): - - def PyInit(self): - pass - - def PyExec(self): - pass - - mtd.registerPyAlgorithm(MyAlgorithm()) - """ - expected = \ - """ - from mantid import * - from mantid.kernel import * - from mantid.api import * - - class MyAlgorithm(PythonAlgorithm): - - def PyInit(self): - pass - - def PyExec(self): - pass - - registerAlgorithm(MyAlgorithm) - """ - self.do_migration(inputstring) - self.check_outcome(inputstring, expected) - - def test_basic_property_types_replace_correctly(self): - inputstring = \ - """ - from MantidFramework import * - mtd.initialize() - Name, DefaultValue, Validator = None, Description = '', Direction = Direction.Input): - class MyAlgorithm(PythonAlgorithm): - - def PyInit(self): - self.declareProperty(Name="StringKeywords",DefaultValue="", Validator=MandatoryValidator(),Description="description",Direction=Direction.Input) - self.declareProperty("StringNonKeywords","", MandatoryValidator(),"description",Direction.Input) - self.declareProperty("StringNotAllArgs","") - self.declareProperty("StringMixKeywordsAndPos","",Description="desc") - - self.declareProperty(Name="NonStringKeywords",DefaultValue="", Validator=MandatoryValidator(),Description="description",Direction=Direction.Input) - self.declareProperty("NonStringNonKeywords", 1, MandatoryValidator(),"description",Direction.Input) - self.declareProperty("NonStringNotAllArgs",1) - self.declareProperty("NonStringMixKeywordsAndPos",1,Description="desc") - - - def PyExec(self): - pass - - mtd.registerPyAlgorithm(MyAlgorithm()) - """ - expected = \ - """ - from mantid import * - from mantid.kernel import * - from mantid.api import * - - class MyAlgorithm(PythonAlgorithm): - - def PyInit(self): - self.declareProperty(name="StringKeywords",defaultValue="", validator=MandatoryValidator(),doc="description",direction=Direction.Input) - self.declareProperty("StringNonKeywords","", MandatoryValidator(),"description",Direction.Input) - self.declareProperty("StringNotAllArgs","") - self.declareProperty("StringMixKeywordsAndPos","",Description="desc") - - self.declareProperty(Name="NonStringKeywords",DefaultValue="", Validator=MandatoryValidator(),Description="description",Direction=Direction.Input) - self.declareProperty("NonStringNonKeywords", 1, IntMandatoryValidator(),"description",Direction.Input) - self.declareProperty("NonStringNotAllArgs",1) - self.declareProperty("NonStringMixKeywordsAndPos",1,doc="desc") - - def PyExec(self): - pass - - registerAlgorithm(MyAlgorithm) - """ - self.do_migration(inputstring) - self.check_outcome(inputstring, expected) - -if __name__ == "__main__": - unittest.main() diff --git a/scripts/lib1to2/test/SimpleAPIFunctionCallReplaceMigrationTest.py b/scripts/lib1to2/test/SimpleAPIFunctionCallReplaceMigrationTest.py deleted file mode 100644 index adaa1d2be465f9a37937904c8d41b6ebc0536473..0000000000000000000000000000000000000000 --- a/scripts/lib1to2/test/SimpleAPIFunctionCallReplaceMigrationTest.py +++ /dev/null @@ -1,78 +0,0 @@ -"""Tests for the migration with simple api function call replacements -""" -import unittest -import os - -from MigrationTest import MigrationTest - -class SimpleAPIFunctionCallReplaceMigrationTest(MigrationTest): - - _test_filename = None - _test_backupname = None - _backup_ext = '.mantidbackup' - - def tearDown(self): - """Clean up after a test""" - self.remove_test_files() - - def test_single_arg_no_keyword_is_migrated_correctly(self): - inputstring = """DeleteWorkspace(ws)""" - expected = """DeleteWorkspace(Workspace=ws)""" - self.do_migration(inputstring) - self.check_outcome(inputstring, expected) - - def test_single_arg_with_nested_call(self): - inputstring = """DeleteWorkspace(kwargs[ws])""" - expected = """DeleteWorkspace(Workspace=kwargs[ws])""" - self.do_migration(inputstring) - self.check_outcome(inputstring, expected) - - def test_single_arg_keyword_is_migrated_correctly(self): - inputstring = """DeleteWorkspace(Workspace=ws)""" - expected = """DeleteWorkspace(Workspace=ws)""" - self.do_migration(inputstring) - self.check_outcome(inputstring, expected) - - def test_all_keyword_is_untouched(self): - inputstring = """LoadRaw(Filename='test.raw',OutputWorkspace=ws)""" - expected = """LoadRaw(Filename='test.raw',OutputWorkspace=ws)""" - self.do_migration(inputstring) - self.check_outcome(inputstring, expected) - - def test_function_containing_list_arg_is_correctly_migrated(self): - inputstring = """Rebin(ws,ws,[1,2,3])""" - expected = """Rebin(InputWorkspace=ws,OutputWorkspace=ws,Params=[1,2,3])""" - self.do_migration(inputstring) - self.check_outcome(inputstring, expected) - - def test_no_arg_no_indent_is_migrated_correctly(self): - inputstring = """LoadRaw("test-file.raw",'testWS',SpectrumMax=1)""" - expected = """LoadRaw(Filename="test-file.raw",OutputWorkspace='testWS',SpectrumMax=1)""" - self.do_migration(inputstring) - self.check_outcome(inputstring, expected) - - def test_function_returning_no_args_is_replaced_correctly(self): - inputstring = """ -def foo(): - LoadRaw("test-file.raw",'testWS',SpectrumMax=1) -""" - expected = """ -def foo(): - LoadRaw(Filename="test-file.raw",OutputWorkspace='testWS',SpectrumMax=1) -""" - self.do_migration(inputstring) - self.check_outcome(inputstring, expected) - - def test_function_call_split_over_multiple_lines_is_replaced_correctly(self): - inputstring = """ -LoadRaw("test-file.raw",'testWS', - SpectrumMax=1)""" - expected = """ -LoadRaw(Filename="test-file.raw",OutputWorkspace='testWS', - SpectrumMax=1)""" - self.create_test_file(inputstring) - self.do_migration(inputstring) - self.check_outcome(inputstring, expected) - -if __name__ == "__main__": - unittest.main() diff --git a/scripts/lib1to2/test/SimpleStringReplaceMigrationTest.py b/scripts/lib1to2/test/SimpleStringReplaceMigrationTest.py deleted file mode 100644 index 1e867435905b28c66fc8b2c19d9143095c998f8d..0000000000000000000000000000000000000000 --- a/scripts/lib1to2/test/SimpleStringReplaceMigrationTest.py +++ /dev/null @@ -1,55 +0,0 @@ -"""Tests for the migration with simple one-line string replacements -""" -import unittest -import os - -from MigrationTest import MigrationTest - -__INPUTSTRING__ = r""" -from MantidFramework import * -import MantidFramework -mtd.initialize() -mtd.initialise() -from mantidsimple import * -import mantidsimple -from mantidsimple import Load - -MantidFramework.mtd.sendLogMessage("Started") -mtd.sendLogMessage("Started") -mantid.sendLogMessage("Started") -w.getSampleDetails() -mantidsimple.Load -""" - -__EXPECTEDSTRING__ = r""" -from mantid import * -import mantid - - -from mantid.simpleapi import * -import mantid.simpleapi as simpleapi -from mantid.simpleapi import Load - -mantid.logger.notice("Started") -logger.notice("Started") -logger.notice("Started") -w.getRun() -simpleapi.Load -""" - -class SimpleStringReplaceMigrationTest(MigrationTest): - - _test_filename = None - _test_backupname = None - _backup_ext = '.mantidbackup' - - def tearDown(self): - """Clean up after a test""" - self.remove_test_files() - - def test_simple_string_replace_gets_expected_string(self): - self.do_migration(__INPUTSTRING__) - self.check_outcome(__INPUTSTRING__, __EXPECTEDSTRING__) - -if __name__ == "__main__": - unittest.main() diff --git a/scripts/lib1to2/test/__init__.py b/scripts/lib1to2/test/__init__.py deleted file mode 100644 index e7c9954fafbdd9f3713aed0b1c40ad05fc963339..0000000000000000000000000000000000000000 --- a/scripts/lib1to2/test/__init__.py +++ /dev/null @@ -1 +0,0 @@ -# Intentionally blank \ No newline at end of file diff --git a/scripts/lib1to2/test/all_tests.py b/scripts/lib1to2/test/all_tests.py deleted file mode 100644 index 9ad0252be05d5b67f5071566482bdee9e8a595f8..0000000000000000000000000000000000000000 --- a/scripts/lib1to2/test/all_tests.py +++ /dev/null @@ -1,7 +0,0 @@ -import unittest - -from SimpleStringReplaceMigrationTest import * -from SimpleAPIFunctionCallReplaceMigrationTest import * - -if __name__ == "__main__": - unittest.main() diff --git a/scripts/migrate1to2.py b/scripts/migrate1to2.py deleted file mode 100644 index c710b72539465bbe06eebcd5116322b9e95c5721..0000000000000000000000000000000000000000 --- a/scripts/migrate1to2.py +++ /dev/null @@ -1,9 +0,0 @@ -""" -Migrates scripts from version 1 of Mantid's Python API -to version 2. -""" -import lib1to2.main as main - -import sys - -sys.exit(main.main(sys.argv[1:]))