From 23375e9dd11b646f0747a59ab8bf625b27c535c5 Mon Sep 17 00:00:00 2001 From: Antony Lee Date: Sat, 27 Aug 2016 10:23:52 -0700 Subject: [PATCH 01/88] Drop support for Octave and pymatbridge. --- .gitignore | 8 +-- README.rst | 18 ++---- matlab_kernel.ipynb | 2 +- matlab_kernel/kernel.py | 140 ++++++++++++++-------------------------- test_matlab_kernel.py | 17 ++--- 5 files changed, 64 insertions(+), 121 deletions(-) diff --git a/.gitignore b/.gitignore index 7de92c5..a4c3223 100644 --- a/.gitignore +++ b/.gitignore @@ -1,7 +1,7 @@ +*.egg-info/ +.cache/ .ipynb_checkpoints/ -MANIFEST -dist/ build/ -*.egg-info/ -__pycache__ +dist/ *.pyc +.*.swp diff --git a/README.rst b/README.rst index 60991cd..30eb5c6 100644 --- a/README.rst +++ b/README.rst @@ -2,8 +2,7 @@ A Jupyter/IPython kernel for Matlab This requires `Jupyter Notebook `_, -and either `pymatbridge `_, or the -`Matlab engine for Python `_. +and the `Matlab engine for Python `_. To install:: @@ -24,18 +23,9 @@ which means it features a standard set of magics. A sample notebook is available online_. -If using `pymatbridge`, you can specify the path to your Matlab executable by -creating a `MATLAB_EXECUTABLE` environment variable:: - - MATLAB_EXECUTABLE=/usr/bin/matlab - ipython notebook --kernel=matlab_kernel - -For example, on OSX, you could add something like the following to ~/.bash_profile:: - - export MATLAB_EXECUTABLE=/Applications/MATLAB_2015b.app/bin/matlab - A note about plotting. After each call to Matlab, we ask Matlab to save any -open figures to image files whose format and resolution are defined using -the `%plot` magic. The resulting image is shown inline in the notebook. +open figures to image files whose format and resolution are defined using the +`%plot` magic. The resulting image is shown inline in the notebook. You can +use `%plot native` to raise normal MATLAB windows instead. .. _online: http://nbviewer.ipython.org/github/Calysto/matlab_kernel/blob/master/matlab_kernel.ipynb diff --git a/matlab_kernel.ipynb b/matlab_kernel.ipynb index e43b8f3..b96ade9 100644 --- a/matlab_kernel.ipynb +++ b/matlab_kernel.ipynb @@ -7,7 +7,7 @@ "Jupyter Matlab Kernel\n", "============\n", "\n", - "Interact with Matlab in Notebook the using the [python-matlab-bridge](https://pypi.python.org/pypi/pymatbridge/0.4.3). All commands are interpreted by Matlab. Since this is a [MetaKernel](https://github.com/Calysto/metakernel), a standard set of magics are available. Help on commands is available using the `%help` magic or using `?` with a command." + "Interact with Matlab in Notebook the using the [Matlab engine for Python](https://www.mathworks.com/help/matlab/matlab-engine-for-python.html). All commands are interpreted by Matlab. Since this is a [MetaKernel](https://github.com/Calysto/metakernel), a standard set of magics are available. Help on commands is available using the `%help` magic or using `?` with a command." ] }, { diff --git a/matlab_kernel/kernel.py b/matlab_kernel/kernel.py index 4bff2e7..3d87578 100644 --- a/matlab_kernel/kernel.py +++ b/matlab_kernel/kernel.py @@ -9,22 +9,8 @@ from metakernel import MetaKernel from IPython.display import Image -# Import the correct engine -if 'OCTAVE_EXECUTABLE' in os.environ: - from pymatbridge import Octave - matlab_native = False -else: - try: - import matlab.engine - from matlab.engine import MatlabExecutionError - matlab_native = True - except ImportError: - try: - from pymatbridge import Matlab - matlab_native = False - except ImportError: - raise ImportError( - "Neither MATLAB native engine nor pymatbridge are available") +import matlab.engine +from matlab.engine import MatlabExecutionError from . import __version__ @@ -32,36 +18,14 @@ class MatlabEngine(object): def __init__(self): - if 'OCTAVE_EXECUTABLE' in os.environ: - self._engine = Octave(os.environ['OCTAVE_EXECUTABLE']) - self._engine.start() - self.name = 'octave' - elif matlab_native: - self._engine = matlab.engine.start_matlab() - self.name = 'matlab' - else: - executable = os.environ.get('MATLAB_EXECUTABLE', 'matlab') - self._engine = Matlab(executable) - self._engine.start() - self.name = 'pymatbridge' + self._engine = matlab.engine.start_matlab() + self.name = "matlab" # add MATLAB-side helper functions to MATLAB's path - if self.name != 'octave': - kernel_path = os.path.dirname(os.path.realpath(__file__)) - toolbox_path = os.path.join(kernel_path, 'toolbox') - self.run_code("addpath('%s');" % toolbox_path) + kernel_path = os.path.dirname(os.path.realpath(__file__)) + toolbox_path = os.path.join(kernel_path, "toolbox") + self.run_code("addpath('%s');" % toolbox_path) def run_code(self, code): - if matlab_native: - return self._run_native(code) - return self._engine.run_code(code) - - def stop(self): - if matlab_native: - self._engine.exit() - else: - self._engine.stop() - - def _run_native(self, code): resp = dict(success=True, content=dict()) out = StringIO() err = StringIO() @@ -69,7 +33,7 @@ def _run_native(self, code): code = str(code) try: self._engine.eval(code, nargout=0, stdout=out, stderr=err) - self._engine.eval(''' + self._engine.eval(""" figures = {}; handles = get(0, 'children'); for hi = 1:length(handles) @@ -78,38 +42,41 @@ def _run_native(self, code): figures{hi} = [fullfile(datadir, ['MatlabFig', sprintf('%03d', hi)]), '.png']; saveas(handles(hi), figures{hi}); if (strcmp(get(handles(hi), 'visible'), 'off')); close(handles(hi)); end - end''', nargout=0, stdout=out, stderr=err) - figures = self._engine.workspace['figures'] + end""", nargout=0, stdout=out, stderr=err) + figures = self._engine.workspace["figures"] except (SyntaxError, MatlabExecutionError) as exc: - resp['content']['stdout'] = exc.args[0] - resp['success'] = False + resp["content"]["stdout"] = exc.args[0] + resp["success"] = False else: - resp['content']['stdout'] = out.getvalue() + resp["content"]["stdout"] = out.getvalue() if figures: - resp['content']['figures'] = figures + resp["content"]["figures"] = figures return resp + def stop(self): + self._engine.exit() + class MatlabKernel(MetaKernel): - implementation = 'Matlab Kernel' + implementation = "Matlab Kernel" implementation_version = __version__, - language = 'matlab' + language = "matlab" language_version = __version__, banner = "Matlab Kernel" language_info = { - 'mimetype': 'text/x-octave', - 'codemirror_mode': 'octave', - 'name': 'matlab', - 'file_extension': '.m', - 'version': __version__, - 'help_links': MetaKernel.help_links, + "mimetype": "text/x-matlab", + "codemirror_mode": "octave", + "name": "matlab", + "file_extension": ".m", + "version": __version__, + "help_links": MetaKernel.help_links, } kernel_json = { "argv": [ sys.executable, "-m", "matlab_kernel", "-f", "{connection_file}"], "display_name": "Matlab", "language": "matlab", - "mimetype": "text/x-octave", + "mimetype": "text/x-matlab", "name": "matlab", } @@ -127,66 +94,63 @@ def do_execute_direct(self, code): self._first = False self.handle_plot_settings() - self.log.debug('execute: %s' % code) + self.log.debug("execute: %s" % code) resp = self._matlab.run_code(code.strip()) - self.log.debug('execute done') - if 'stdout' not in resp['content']: + self.log.debug("execute done") + if "stdout" not in resp["content"]: raise ValueError(resp) - backend = self.plot_settings['backend'] - if 'figures' in resp['content'] and backend == 'inline': - for fname in resp['content']['figures']: + backend = self.plot_settings["backend"] + if "figures" in resp["content"] and backend == "inline": + for fname in resp["content"]["figures"]: try: im = Image(filename=fname) self.Display(im) except Exception as e: self.Error(e) - if not resp['success']: - self.Error(resp['content']['stdout'].strip()) + if not resp["success"]: + self.Error(resp["content"]["stdout"].strip()) else: - stdout = resp['content']['stdout'].strip() + stdout = resp["content"]["stdout"].strip() if stdout: self.Print(stdout) def get_kernel_help_on(self, info, level=0, none_on_fail=False): - obj = info.get('help_obj', '') + obj = info.get("help_obj", "") if not obj or len(obj.split()) > 1: if none_on_fail: return None else: return "" - code = 'help %s' % obj + code = "help %s" % obj resp = self._matlab.run_code(code.strip()) - return resp['content']['stdout'].strip() or None + return resp["content"]["stdout"].strip() or None def get_completions(self, info): """ Get completions from kernel based on info dict. """ - if self._matlab.name != 'octave': - code = "do_matlab_complete('%s')" % info['obj'] - else: - code = 'completion_matches("%s")' % info['obj'] + code = "do_matlab_complete('%s')" % info['obj'] resp = self._matlab.run_code(code.strip()) - return resp['content']['stdout'].strip().splitlines() or [] + return resp["content"]["stdout"].strip().splitlines() or [] def handle_plot_settings(self): """Handle the current plot settings""" settings = self.plot_settings - settings.setdefault('size', (560, 420)) - settings.setdefault('backend', 'inline') + settings.setdefault("size", (560, 420)) + settings.setdefault("backend", "inline") width, height = 560, 420 - if isinstance(settings['size'], tuple): - width, height = settings['size'] - elif settings['size']: + if isinstance(settings["size"], tuple): + width, height = settings["size"] + elif settings["size"]: try: - width, height = settings['size'].split(',') + width, height = settings["size"].split(",") width, height = int(width), int(height) - settings['size'] = width, height + settings["size"] = width, height except Exception as e: self.Error(e) - if settings['backend'] == 'inline': + if settings["backend"] == "inline": code = ["set(0, 'defaultfigurevisible', 'off')"] else: code = ["set(0, 'defaultfigurevisible', 'on')"] @@ -196,22 +160,18 @@ def handle_plot_settings(self): "set(0, 'defaultfigureunits', 'inches')", paper_size % (int(width) / 150., int(height) / 150.), figure_size % (int(width) / 150., int(height) / 150.)] - if sys.platform == 'darwin' and self._matlab.name == 'octave': - code + ['setenv("GNUTERM", "X11")'] - if settings['backend'] != 'inline': - code += ["graphics_toolkit('%s');" % settings['backend']] - self._matlab.run_code(';'.join(code)) + self._matlab.run_code(";".join(code)) def repr(self, obj): return obj def restart_kernel(self): - """Restart the kernel""" self._matlab.stop() def do_shutdown(self, restart): self._matlab.stop() + if __name__ == '__main__': try: from ipykernel.kernelapp import IPKernelApp diff --git a/test_matlab_kernel.py b/test_matlab_kernel.py index 212f819..fbd2e75 100644 --- a/test_matlab_kernel.py +++ b/test_matlab_kernel.py @@ -1,27 +1,20 @@ """Example use of jupyter_kernel_test, with tests for IPython.""" import unittest -import jupyter_kernel_test as jkt +from jupyter_kernel_test import KernelTests import os -os.environ['USE_OCTAVE'] = 'True' - -class MatlabKernelTests(jkt.KernelTests): +class MatlabKernelTests(KernelTests): kernel_name = "matlab" - language_name = "matlab" - code_hello_world = "disp('hello, world')" - completion_samples = [ - { - 'text': 'one', - 'matches': {'ones', 'onenormest'}, - }, + {'text': 'one', + 'matches': {'ones'}}, ] - code_page_something = "ones?" + if __name__ == '__main__': unittest.main() From 57186469a3fc3afcdddd2d84b203293f67899c97 Mon Sep 17 00:00:00 2001 From: Antony Lee Date: Sat, 27 Aug 2016 23:23:06 -0700 Subject: [PATCH 02/88] General cleanup. --- matlab_kernel/kernel.py | 232 ++++++++++-------- matlab_kernel/toolbox/do_matlab_complete.m | 57 ----- .../toolbox/get_completions_prefix.m | 24 -- 3 files changed, 126 insertions(+), 187 deletions(-) delete mode 100644 matlab_kernel/toolbox/do_matlab_complete.m delete mode 100644 matlab_kernel/toolbox/get_completions_prefix.m diff --git a/matlab_kernel/kernel.py b/matlab_kernel/kernel.py index 3d87578..3ffc6d9 100644 --- a/matlab_kernel/kernel.py +++ b/matlab_kernel/kernel.py @@ -1,11 +1,14 @@ -from __future__ import print_function +from __future__ import division, print_function import os +import shutil import sys +import tempfile if sys.version_info[0] < 3: from StringIO import StringIO else: from io import StringIO + from metakernel import MetaKernel from IPython.display import Image @@ -15,48 +18,6 @@ from . import __version__ -class MatlabEngine(object): - - def __init__(self): - self._engine = matlab.engine.start_matlab() - self.name = "matlab" - # add MATLAB-side helper functions to MATLAB's path - kernel_path = os.path.dirname(os.path.realpath(__file__)) - toolbox_path = os.path.join(kernel_path, "toolbox") - self.run_code("addpath('%s');" % toolbox_path) - - def run_code(self, code): - resp = dict(success=True, content=dict()) - out = StringIO() - err = StringIO() - if sys.version_info[0] < 3: - code = str(code) - try: - self._engine.eval(code, nargout=0, stdout=out, stderr=err) - self._engine.eval(""" - figures = {}; - handles = get(0, 'children'); - for hi = 1:length(handles) - datadir = fullfile(tempdir(), 'MatlabData'); - if ~exist(datadir, 'dir'); mkdir(datadir); end - figures{hi} = [fullfile(datadir, ['MatlabFig', sprintf('%03d', hi)]), '.png']; - saveas(handles(hi), figures{hi}); - if (strcmp(get(handles(hi), 'visible'), 'off')); close(handles(hi)); end - end""", nargout=0, stdout=out, stderr=err) - figures = self._engine.workspace["figures"] - except (SyntaxError, MatlabExecutionError) as exc: - resp["content"]["stdout"] = exc.args[0] - resp["success"] = False - else: - resp["content"]["stdout"] = out.getvalue() - if figures: - resp["content"]["figures"] = figures - return resp - - def stop(self): - self._engine.exit() - - class MatlabKernel(MetaKernel): implementation = "Matlab Kernel" implementation_version = __version__, @@ -80,11 +41,16 @@ class MatlabKernel(MetaKernel): "name": "matlab", } - _first = True - def __init__(self, *args, **kwargs): super(MatlabKernel, self).__init__(*args, **kwargs) - self._matlab = MatlabEngine() + self._matlab = matlab.engine.start_matlab() + self._first = True + self._validated_plot_settings = { + "backend": "inline", + "size": (560, 420), + "format": "png", + "resolution": 96, + } def get_usage(self): return "This is the Matlab kernel." @@ -92,84 +58,138 @@ def get_usage(self): def do_execute_direct(self, code): if self._first: self._first = False + self._validated_plot_settings["size"] = tuple( + self._matlab.get(0., "defaultfigureposition")[0][2:]) self.handle_plot_settings() - self.log.debug("execute: %s" % code) - resp = self._matlab.run_code(code.strip()) - self.log.debug("execute done") - if "stdout" not in resp["content"]: - raise ValueError(resp) - backend = self.plot_settings["backend"] - if "figures" in resp["content"] and backend == "inline": - for fname in resp["content"]["figures"]: + out = StringIO() + err = StringIO() + try: + self._matlab.eval(code, nargout=0, stdout=out, stderr=err) + except (SyntaxError, MatlabExecutionError) as exc: + stdout = exc.args[0] + self.Error(stdout) + return + stdout = out.getvalue() + self.Print(stdout) + + settings = self._validated_plot_settings + if settings["backend"] == "inline": + nfig = len(self._matlab.get(0., "children")) + if nfig: + tmpdir = tempfile.mkdtemp() try: - im = Image(filename=fname) - self.Display(im) - except Exception as e: - self.Error(e) - if not resp["success"]: - self.Error(resp["content"]["stdout"].strip()) - else: - stdout = resp["content"]["stdout"].strip() - if stdout: - self.Print(stdout) + self._matlab.eval( + "arrayfun(" + "@(h, i) print(h, sprintf('{}/%i', i), '-d{}', '-r{}')," + "get(0, 'children'), (1:{})')" + .format(tmpdir, settings["format"], settings["resolution"], nfig), + nargout=0) + self._matlab.eval( + "arrayfun(@(h) close(h), get(0, 'children'))", + nargout=0) + for fname in sorted(os.listdir(tmpdir)): + self.Display(Image( + filename="{}/{}".format(tmpdir, fname))) + except Exception as exc: + self.Error(exc) + finally: + shutil.rmtree(tmpdir) def get_kernel_help_on(self, info, level=0, none_on_fail=False): - obj = info.get("help_obj", "") - if not obj or len(obj.split()) > 1: - if none_on_fail: - return None - else: - return "" - code = "help %s" % obj - resp = self._matlab.run_code(code.strip()) - return resp["content"]["stdout"].strip() or None + name = info.get("help_obj", "") + out = StringIO() + self._matlab.help(name, nargout=0, stdout=out) + return out.getvalue() def get_completions(self, info): + """Get completions from kernel based on info dict. """ - Get completions from kernel based on info dict. - """ - code = "do_matlab_complete('%s')" % info['obj'] - resp = self._matlab.run_code(code.strip()) - return resp["content"]["stdout"].strip().splitlines() or [] + + # Only MATLAB versions R2013a, R2014b, and R2015a were available for + # testing. This function is probably incompatible with some or many + # other releases, as the undocumented features it relies on are subject + # to change without notice. + + # grep'ing MATLAB R2014b for "tabcomplet" and dumping the symbols of + # the ELF files that match suggests that the internal tab completion + # is implemented in bin/glnxa64/libmwtabcompletion.so and called + # from /bin/glnxa64/libnativejmi.so, which contains the function + # mtFindAllTabCompletions. We can infer from MATLAB's undocumented + # naming conventions that this function can be accessed as a method of + # com.matlab.jmi.MatlabMCR objects. + + # Trial and error reveals likely function signatures for certain MATLAB + # versions. + # R2014b and R2015a: + # mtFindAllTabCompletions(String substring, int len, int offset) + # where `substring` is the string to be completed, `len` is the + # length of the string, and the first `offset` values returned by the + # engine are ignored. + # R2013a (not supported due to lack of Python engine): + # mtFindAllTabCompletions(String substring, int offset [optional]) + + name = info["obj"] + compls = self._matlab.eval( + "cell(com.mathworks.jmi.MatlabMCR()." + "mtFindAllTabCompletions('{}', {}, 0))" + .format(name, len(name))) + + # For structs, we need to return `structname.fieldname` instead of just + # `fieldname`, which `mtFindAllTabCompletions` does. + + if "." in name: + prefix, _ = name.rsplit(".", 1) + if self._matlab.eval("isstruct({})".format(prefix)): + compls = ["{}.{}".format(prefix, compl) for compl in compls] + + return compls def handle_plot_settings(self): - """Handle the current plot settings""" - settings = self.plot_settings - settings.setdefault("size", (560, 420)) - settings.setdefault("backend", "inline") - - width, height = 560, 420 - if isinstance(settings["size"], tuple): - width, height = settings["size"] - elif settings["size"]: - try: - width, height = settings["size"].split(",") - width, height = int(width), int(height) - settings["size"] = width, height - except Exception as e: - self.Error(e) + raw = self.plot_settings + settings = self._validated_plot_settings + + backends = {"inline": "off", "native": "on"} + backend = raw.get("backend") + if backend is not None: + if backend not in backends: + self.Error("Invalid backend, should be one of {}" + .format(sorted(list(backends)))) + else: + settings["backend"] = backend - if settings["backend"] == "inline": - code = ["set(0, 'defaultfigurevisible', 'off')"] - else: - code = ["set(0, 'defaultfigurevisible', 'on')"] - paper_size = "set(0, 'defaultfigurepaperposition', [0 0 %s %s])" - figure_size = "set(0, 'defaultfigureposition', [0 0 %s %s])" - code += ["set(0, 'defaultfigurepaperunits', 'inches')", - "set(0, 'defaultfigureunits', 'inches')", - paper_size % (int(width) / 150., int(height) / 150.), - figure_size % (int(width) / 150., int(height) / 150.)] - self._matlab.run_code(";".join(code)) + size = raw.get("size") + if size is not None: + try: + width, height = size + except Exception as exc: + self.Error(exc) + else: + settings["size"] = size + + resolution = raw.get("resolution") + if resolution is not None: + settings["resolution"] = resolution + + backend = settings["backend"] + width, height = settings["size"] + resolution = settings["resolution"] + for k, v in { + "defaultfigurevisible": backends[backend], + "defaultfigurepaperpositionmode": "manual", + "defaultfigurepaperposition": + matlab.double([0, 0, width / resolution, height / resolution]), + "defaultfigurepaperunits": "inches"}.items(): + self._matlab.set(0., k, v, nargout=0) def repr(self, obj): return obj def restart_kernel(self): - self._matlab.stop() + self._matlab.exit() def do_shutdown(self, restart): - self._matlab.stop() + self._matlab.exit() if __name__ == '__main__': diff --git a/matlab_kernel/toolbox/do_matlab_complete.m b/matlab_kernel/toolbox/do_matlab_complete.m deleted file mode 100644 index 96af815..0000000 --- a/matlab_kernel/toolbox/do_matlab_complete.m +++ /dev/null @@ -1,57 +0,0 @@ -function do_matlab_complete(substring) -%DO_MATLAB_COMPLETE list tab completion options for string -% do_matlab_complete(substring) prints out the tab completion options for the -% string `substring`, one per line. This required evaluating some undocumented -% internal matlab code in the "base" workspace. -% -% Only MATLAB versions R2013a, R2014b, and R2015a were available for testing. -% This function is probably incompatible with some or many other releases, as -% the undocumented features it relies on are subject to change without notice. - -% grep'ing MATLAB R2014b for "tabcomplet" and dumping the symbols of the ELF -% files that match suggests that the internal tab completion is implemented in -% bin/glnxa64/libmwtabcompletion.so and called from -% /bin/glnxa64/libnativejmi.so, which contains the function -% mtFindAllTabCompletions. We can infer from MATLAB's undocumented naming -% conventions that this function can be accessed as a method of -% com.matlab.jmi.MatlabMCR objects. - -% Trial and error reveals likely function signatures for certain MATLAB versions -% R2014b and R2015a: -% mtFindAllTabCompletions(String substring, int len, int offset) -% where `substring` is the string to be completed, `len` is the length of the -% string, and the first `offset` values returned by the engine are ignored. -% R2013a: -% mtFindAllTabCompletions(String substring, int offset [optional]) - -len = length(substring); -offset = 0; - -if verLessThan('MATLAB','8.4') - % verified for R2013a - args = sprintf('''%s'', %g', substring, offset); -else - % verified for R2014b, 2015a - args = sprintf('''%s'', %g, %g', substring, len, offset); -end - -% variables must be name-mangled to prevent collisions with user variables -% because this code will be executed in the user's actual workspace -get_completions = [ ... - 'matlabMCRinstance_avoid_name_collisions = com.mathworks.jmi.MatlabMCR;' ... - 'completions_output_avoid_name_collisions = ' ... - ' matlabMCRinstance_avoid_name_collisions.mtFindAllTabCompletions(' ... - args ... - ');' ... - 'prefix_avoid_name_collisions = get_completions_prefix(''' substring ''');' ... - 'for i=1:length(completions_output_avoid_name_collisions);' ... - ' fprintf(1, ''%s%s\n'', prefix_avoid_name_collisions, ' ... - ' char(completions_output_avoid_name_collisions(i)));' ... - 'end;' ... - 'clear(''matlabMCRinstance_avoid_name_collisions'', ' ... - ' ''completions_output_avoid_name_collisions'', ' ... - ' ''prefix_avoid_name_collisions'');' ]; - -try - evalin('base', get_completions); -end diff --git a/matlab_kernel/toolbox/get_completions_prefix.m b/matlab_kernel/toolbox/get_completions_prefix.m deleted file mode 100644 index 16f47ee..0000000 --- a/matlab_kernel/toolbox/get_completions_prefix.m +++ /dev/null @@ -1,24 +0,0 @@ -function prefix = get_completions_prefix(substr) -%get_completions_prefix shared prefix for completion results -% prefix = get_completions_prefix(substr) will return the prefix that needs -% to be prepended to the results of mtFindAllTabCompletions in order for -% Python's MetaKernel to use those results correctly. For now, this simply -% fixes a problem where MetaKernel framework expects -% do_matlab_complete('some_struct.long') to return -% `some_struct.long_fieldname`, but mtFindAllTabCompletions returns -% `long_fieldname` instead in this case. - prefix = ''; - period_ind = find(substr == '.'); - if isempty(period_ind) - return; - end - needs_prefix = false; - try - needs_prefix = evalin('base', ['isstruct(' substr(1:period_ind(1)-1) ')']); - catch - end - if needs_prefix - prefix = substr(1:period_ind(1)); - end -end - From 527ab1b941a1065a11893869f789ac0364534465 Mon Sep 17 00:00:00 2001 From: Antony Lee Date: Sun, 28 Aug 2016 11:01:15 -0700 Subject: [PATCH 03/88] Fix shutdown and restart. --- matlab_kernel/kernel.py | 3 +++ 1 file changed, 3 insertions(+) diff --git a/matlab_kernel/kernel.py b/matlab_kernel/kernel.py index 3ffc6d9..59684fd 100644 --- a/matlab_kernel/kernel.py +++ b/matlab_kernel/kernel.py @@ -187,9 +187,12 @@ def repr(self, obj): def restart_kernel(self): self._matlab.exit() + self._matlab = matlab.engine.start_matlab() + self._first = True def do_shutdown(self, restart): self._matlab.exit() + return super(MatlabKernel, self).do_shutdown(restart) if __name__ == '__main__': From 2f6b71ebc09549153770a131496a5883587545d1 Mon Sep 17 00:00:00 2001 From: Antony Lee Date: Tue, 30 Aug 2016 22:21:07 -0700 Subject: [PATCH 04/88] Switch to setuptools+versioneer because why not. --- .gitattributes | 1 + LICENSE.txt | 2 +- MANIFEST.in | 2 + README.rst | 2 + flit.ini | 13 - matlab_kernel/__init__.py | 4 +- matlab_kernel/_version.py | 498 +++++++++++ setup.cfg | 7 + setup.py | 21 + versioneer.py | 1733 +++++++++++++++++++++++++++++++++++++ 10 files changed, 2268 insertions(+), 15 deletions(-) create mode 100644 .gitattributes create mode 100644 MANIFEST.in delete mode 100644 flit.ini create mode 100644 matlab_kernel/_version.py create mode 100644 setup.cfg create mode 100644 setup.py create mode 100644 versioneer.py diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..e9bfe4c --- /dev/null +++ b/.gitattributes @@ -0,0 +1 @@ +matlab_kernel/_version.py export-subst diff --git a/LICENSE.txt b/LICENSE.txt index 97f1d5a..659f3d1 100644 --- a/LICENSE.txt +++ b/LICENSE.txt @@ -1,4 +1,4 @@ -Copyright (c) 2016, Steven Silvester +Copyright (c) 2016, Steven Silvester, Antony Lee All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: diff --git a/MANIFEST.in b/MANIFEST.in new file mode 100644 index 0000000..9344259 --- /dev/null +++ b/MANIFEST.in @@ -0,0 +1,2 @@ +include versioneer.py +include matlab_kernel/_version.py diff --git a/README.rst b/README.rst index 30eb5c6..68ede24 100644 --- a/README.rst +++ b/README.rst @@ -7,6 +7,8 @@ and the `Matlab engine for Python =0.13.1) -dev-requires = jupyter_kernel_test -description-file = README.rst -classifiers = Framework :: IPython - License :: OSI Approved :: BSD License - Programming Language :: Python :: 2 - Programming Language :: Python :: 3 - Topic :: System :: Shells diff --git a/matlab_kernel/__init__.py b/matlab_kernel/__init__.py index 3c48a54..2b87814 100644 --- a/matlab_kernel/__init__.py +++ b/matlab_kernel/__init__.py @@ -1,3 +1,5 @@ """A Matlab kernel for Jupyter""" -__version__ = '0.11.0' +from ._version import get_versions +__version__ = get_versions()['version'] +del get_versions diff --git a/matlab_kernel/_version.py b/matlab_kernel/_version.py new file mode 100644 index 0000000..1d31762 --- /dev/null +++ b/matlab_kernel/_version.py @@ -0,0 +1,498 @@ + +# This file helps to compute a version number in source trees obtained from +# git-archive tarball (such as those provided by githubs download-from-tag +# feature). Distribution tarballs (built by setup.py sdist) and build +# directories (produced by setup.py build) will contain a much shorter file +# that just contains the computed version number. + +# This file is released into the public domain. Generated by +# versioneer-0.16+dev (https://github.com/warner/python-versioneer) + +"""Git implementation of _version.py.""" + +import errno +import os +import re +import subprocess +import sys + + +def get_keywords(): + """Get the keywords needed to look up the version information.""" + # these strings will be replaced by git during git-archive. + # setup.py/versioneer.py will grep for the variable names, so they must + # each be defined on a line of their own. _version.py will just call + # get_keywords(). + git_refnames = "$Format:%d$" + git_full = "$Format:%H$" + keywords = {"refnames": git_refnames, "full": git_full} + return keywords + + +class VersioneerConfig: + """Container for Versioneer configuration parameters.""" + + +def get_config(): + """Create, populate and return the VersioneerConfig() object.""" + # these strings are filled in when 'setup.py versioneer' creates + # _version.py + cfg = VersioneerConfig() + cfg.VCS = "git" + cfg.style = "pep440" + cfg.tag_prefix = "v" + cfg.parentdir_prefix = "matlab_kernel-" + cfg.versionfile_source = "matlab_kernel/_version.py" + cfg.verbose = False + return cfg + + +class NotThisMethod(Exception): + """Exception raised if a method is not valid for the current scenario.""" + + +LONG_VERSION_PY = {} +HANDLERS = {} + + +def register_vcs_handler(vcs, method): # decorator + """Decorator to mark a method as the handler for a particular VCS.""" + def decorate(f): + """Store f in HANDLERS[vcs][method].""" + if vcs not in HANDLERS: + HANDLERS[vcs] = {} + HANDLERS[vcs][method] = f + return f + return decorate + + +def run_command(commands, args, cwd=None, verbose=False, hide_stderr=False, + env=None): + """Call the given command(s).""" + assert isinstance(commands, list) + p = None + for c in commands: + try: + dispcmd = str([c] + args) + # remember shell=False, so use git.cmd on windows, not just git + p = subprocess.Popen([c] + args, cwd=cwd, env=env, + stdout=subprocess.PIPE, + stderr=(subprocess.PIPE if hide_stderr + else None)) + break + except EnvironmentError: + e = sys.exc_info()[1] + if e.errno == errno.ENOENT: + continue + if verbose: + print("unable to run %s" % dispcmd) + print(e) + return None, None + else: + if verbose: + print("unable to find command, tried %s" % (commands,)) + return None, None + stdout = p.communicate()[0].strip() + if sys.version_info[0] >= 3: + stdout = stdout.decode() + if p.returncode != 0: + if verbose: + print("unable to run %s (error)" % dispcmd) + print("stdout was %s" % stdout) + return None, p.returncode + return stdout, p.returncode + + +def versions_from_parentdir(parentdir_prefix, root, verbose): + """Try to determine the version from the parent directory name. + + Source tarballs conventionally unpack into a directory that includes both + the project name and a version string. We will also support searching up + two directory levels for an appropriately named parent directory + """ + rootdirs = [] + + for i in range(3): + dirname = os.path.basename(root) + if dirname.startswith(parentdir_prefix): + return {"version": dirname[len(parentdir_prefix):], + "full-revisionid": None, + "dirty": False, "error": None} + else: + rootdirs.append(root) + root = os.path.dirname(root) # up a level + + if verbose: + print("Tried directories %s but none started with prefix %s" % + (str(rootdirs), parentdir_prefix)) + raise NotThisMethod("rootdir doesn't start with parentdir_prefix") + + +@register_vcs_handler("git", "get_keywords") +def git_get_keywords(versionfile_abs): + """Extract version information from the given file.""" + # the code embedded in _version.py can just fetch the value of these + # keywords. When used from setup.py, we don't want to import _version.py, + # so we do it with a regexp instead. This function is not used from + # _version.py. + keywords = {} + try: + f = open(versionfile_abs, "r") + for line in f.readlines(): + if line.strip().startswith("git_refnames ="): + mo = re.search(r'=\s*"(.*)"', line) + if mo: + keywords["refnames"] = mo.group(1) + if line.strip().startswith("git_full ="): + mo = re.search(r'=\s*"(.*)"', line) + if mo: + keywords["full"] = mo.group(1) + f.close() + except EnvironmentError: + pass + return keywords + + +@register_vcs_handler("git", "keywords") +def git_versions_from_keywords(keywords, tag_prefix, verbose): + """Get version information from git keywords.""" + if not keywords: + raise NotThisMethod("no keywords at all, weird") + refnames = keywords["refnames"].strip() + if refnames.startswith("$Format"): + if verbose: + print("keywords are unexpanded, not using") + raise NotThisMethod("unexpanded keywords, not a git-archive tarball") + refs = set([r.strip() for r in refnames.strip("()").split(",")]) + # starting in git-1.8.3, tags are listed as "tag: foo-1.0" instead of + # just "foo-1.0". If we see a "tag: " prefix, prefer those. + TAG = "tag: " + tags = set([r[len(TAG):] for r in refs if r.startswith(TAG)]) + if not tags: + # Either we're using git < 1.8.3, or there really are no tags. We use + # a heuristic: assume all version tags have a digit. The old git %d + # expansion behaves like git log --decorate=short and strips out the + # refs/heads/ and refs/tags/ prefixes that would let us distinguish + # between branches and tags. By ignoring refnames without digits, we + # filter out many common branch names like "release" and + # "stabilization", as well as "HEAD" and "master". + tags = set([r for r in refs if re.search(r'\d', r)]) + if verbose: + print("discarding '%s', no digits" % ",".join(refs-tags)) + if verbose: + print("likely tags: %s" % ",".join(sorted(tags))) + for ref in sorted(tags): + # sorting will prefer e.g. "2.0" over "2.0rc1" + if ref.startswith(tag_prefix): + r = ref[len(tag_prefix):] + if verbose: + print("picking %s" % r) + return {"version": r, + "full-revisionid": keywords["full"].strip(), + "dirty": False, "error": None + } + # no suitable tags, so version is "0+unknown", but full hex is still there + if verbose: + print("no suitable tags, using unknown + full revision id") + return {"version": "0+unknown", + "full-revisionid": keywords["full"].strip(), + "dirty": False, "error": "no suitable tags"} + + +@register_vcs_handler("git", "pieces_from_vcs") +def git_pieces_from_vcs(tag_prefix, root, verbose, run_command=run_command): + """Get version from 'git describe' in the root of the source tree. + + This only gets called if the git-archive 'subst' keywords were *not* + expanded, and _version.py hasn't already been rewritten with a short + version string, meaning we're inside a checked out source tree. + """ + GITS = ["git"] + if sys.platform == "win32": + GITS = ["git.cmd", "git.exe"] + + out, rc = run_command(GITS, ["rev-parse", "--git-dir"], cwd=root, + hide_stderr=True) + if rc != 0: + if verbose: + print("Directory %s not under git control" % root) + raise NotThisMethod("'git rev-parse --git-dir' returned error") + + # if there is a tag matching tag_prefix, this yields TAG-NUM-gHEX[-dirty] + # if there isn't one, this yields HEX[-dirty] (no NUM) + describe_out, rc = run_command(GITS, ["describe", "--tags", "--dirty", + "--always", "--long", + "--match", "%s*" % tag_prefix], + cwd=root) + # --long was added in git-1.5.5 + if describe_out is None: + raise NotThisMethod("'git describe' failed") + describe_out = describe_out.strip() + full_out, rc = run_command(GITS, ["rev-parse", "HEAD"], cwd=root) + if full_out is None: + raise NotThisMethod("'git rev-parse' failed") + full_out = full_out.strip() + + pieces = {} + pieces["long"] = full_out + pieces["short"] = full_out[:7] # maybe improved later + pieces["error"] = None + + # parse describe_out. It will be like TAG-NUM-gHEX[-dirty] or HEX[-dirty] + # TAG might have hyphens. + git_describe = describe_out + + # look for -dirty suffix + dirty = git_describe.endswith("-dirty") + pieces["dirty"] = dirty + if dirty: + git_describe = git_describe[:git_describe.rindex("-dirty")] + + # now we have TAG-NUM-gHEX or HEX + + if "-" in git_describe: + # TAG-NUM-gHEX + mo = re.search(r'^(.+)-(\d+)-g([0-9a-f]+)$', git_describe) + if not mo: + # unparseable. Maybe git-describe is misbehaving? + pieces["error"] = ("unable to parse git-describe output: '%s'" + % describe_out) + return pieces + + # tag + full_tag = mo.group(1) + if not full_tag.startswith(tag_prefix): + if verbose: + fmt = "tag '%s' doesn't start with prefix '%s'" + print(fmt % (full_tag, tag_prefix)) + pieces["error"] = ("tag '%s' doesn't start with prefix '%s'" + % (full_tag, tag_prefix)) + return pieces + pieces["closest-tag"] = full_tag[len(tag_prefix):] + + # distance: number of commits since tag + pieces["distance"] = int(mo.group(2)) + + # commit: short hex revision ID + pieces["short"] = mo.group(3) + + else: + # HEX: no tags + pieces["closest-tag"] = None + count_out, rc = run_command(GITS, ["rev-list", "HEAD", "--count"], + cwd=root) + pieces["distance"] = int(count_out) # total number of commits + + return pieces + + +def plus_or_dot(pieces): + """Return a + if we don't already have one, else return a .""" + if "+" in pieces.get("closest-tag", ""): + return "." + return "+" + + +def render_pep440(pieces): + """Build up version string, with post-release "local version identifier". + + Our goal: TAG[+DISTANCE.gHEX[.dirty]] . Note that if you + get a tagged build and then dirty it, you'll get TAG+0.gHEX.dirty + + Exceptions: + 1: no tags. git_describe was just HEX. 0+untagged.DISTANCE.gHEX[.dirty] + """ + if pieces["closest-tag"]: + rendered = pieces["closest-tag"] + if pieces["distance"] or pieces["dirty"]: + rendered += plus_or_dot(pieces) + rendered += "%d.g%s" % (pieces["distance"], pieces["short"]) + if pieces["dirty"]: + rendered += ".dirty" + else: + # exception #1 + rendered = "0+untagged.%d.g%s" % (pieces["distance"], + pieces["short"]) + if pieces["dirty"]: + rendered += ".dirty" + return rendered + + +def render_pep440_pre(pieces): + """TAG[.post.devDISTANCE] -- No -dirty. + + Exceptions: + 1: no tags. 0.post.devDISTANCE + """ + if pieces["closest-tag"]: + rendered = pieces["closest-tag"] + if pieces["distance"]: + rendered += ".post.dev%d" % pieces["distance"] + else: + # exception #1 + rendered = "0.post.dev%d" % pieces["distance"] + return rendered + + +def render_pep440_post(pieces): + """TAG[.postDISTANCE[.dev0]+gHEX] . + + The ".dev0" means dirty. Note that .dev0 sorts backwards + (a dirty tree will appear "older" than the corresponding clean one), + but you shouldn't be releasing software with -dirty anyways. + + Exceptions: + 1: no tags. 0.postDISTANCE[.dev0] + """ + if pieces["closest-tag"]: + rendered = pieces["closest-tag"] + if pieces["distance"] or pieces["dirty"]: + rendered += ".post%d" % pieces["distance"] + if pieces["dirty"]: + rendered += ".dev0" + rendered += plus_or_dot(pieces) + rendered += "g%s" % pieces["short"] + else: + # exception #1 + rendered = "0.post%d" % pieces["distance"] + if pieces["dirty"]: + rendered += ".dev0" + rendered += "+g%s" % pieces["short"] + return rendered + + +def render_pep440_old(pieces): + """TAG[.postDISTANCE[.dev0]] . + + The ".dev0" means dirty. + + Eexceptions: + 1: no tags. 0.postDISTANCE[.dev0] + """ + if pieces["closest-tag"]: + rendered = pieces["closest-tag"] + if pieces["distance"] or pieces["dirty"]: + rendered += ".post%d" % pieces["distance"] + if pieces["dirty"]: + rendered += ".dev0" + else: + # exception #1 + rendered = "0.post%d" % pieces["distance"] + if pieces["dirty"]: + rendered += ".dev0" + return rendered + + +def render_git_describe(pieces): + """TAG[-DISTANCE-gHEX][-dirty]. + + Like 'git describe --tags --dirty --always'. + + Exceptions: + 1: no tags. HEX[-dirty] (note: no 'g' prefix) + """ + if pieces["closest-tag"]: + rendered = pieces["closest-tag"] + if pieces["distance"]: + rendered += "-%d-g%s" % (pieces["distance"], pieces["short"]) + else: + # exception #1 + rendered = pieces["short"] + if pieces["dirty"]: + rendered += "-dirty" + return rendered + + +def render_git_describe_long(pieces): + """TAG-DISTANCE-gHEX[-dirty]. + + Like 'git describe --tags --dirty --always -long'. + The distance/hash is unconditional. + + Exceptions: + 1: no tags. HEX[-dirty] (note: no 'g' prefix) + """ + if pieces["closest-tag"]: + rendered = pieces["closest-tag"] + rendered += "-%d-g%s" % (pieces["distance"], pieces["short"]) + else: + # exception #1 + rendered = pieces["short"] + if pieces["dirty"]: + rendered += "-dirty" + return rendered + + +def render(pieces, style): + """Render the given version pieces into the requested style.""" + if pieces["error"]: + return {"version": "unknown", + "full-revisionid": pieces.get("long"), + "dirty": None, + "error": pieces["error"]} + + if not style or style == "default": + style = "pep440" # the default + + if style == "pep440": + rendered = render_pep440(pieces) + elif style == "pep440-pre": + rendered = render_pep440_pre(pieces) + elif style == "pep440-post": + rendered = render_pep440_post(pieces) + elif style == "pep440-old": + rendered = render_pep440_old(pieces) + elif style == "git-describe": + rendered = render_git_describe(pieces) + elif style == "git-describe-long": + rendered = render_git_describe_long(pieces) + else: + raise ValueError("unknown style '%s'" % style) + + return {"version": rendered, "full-revisionid": pieces["long"], + "dirty": pieces["dirty"], "error": None} + + +def get_versions(): + """Get version information or return default if unable to do so.""" + # I am in _version.py, which lives at ROOT/VERSIONFILE_SOURCE. If we have + # __file__, we can work backwards from there to the root. Some + # py2exe/bbfreeze/non-CPython implementations don't do __file__, in which + # case we can only use expanded keywords. + + cfg = get_config() + verbose = cfg.verbose + + try: + return git_versions_from_keywords(get_keywords(), cfg.tag_prefix, + verbose) + except NotThisMethod: + pass + + try: + root = os.path.realpath(__file__) + # versionfile_source is the relative path from the top of the source + # tree (where the .git directory might live) to this file. Invert + # this to find the root from __file__. + for i in cfg.versionfile_source.split('/'): + root = os.path.dirname(root) + except NameError: + return {"version": "0+unknown", "full-revisionid": None, + "dirty": None, + "error": "unable to find root of source tree"} + + try: + pieces = git_pieces_from_vcs(cfg.tag_prefix, root, verbose) + return render(pieces, cfg.style) + except NotThisMethod: + pass + + try: + if cfg.parentdir_prefix: + return versions_from_parentdir(cfg.parentdir_prefix, root, verbose) + except NotThisMethod: + pass + + return {"version": "0+unknown", "full-revisionid": None, + "dirty": None, + "error": "unable to compute version"} diff --git a/setup.cfg b/setup.cfg new file mode 100644 index 0000000..ae049ad --- /dev/null +++ b/setup.cfg @@ -0,0 +1,7 @@ +[versioneer] +VCS = git +style = pep440 +versionfile_source = matlab_kernel/_version.py +versionfile_build = matlab_kernel/_version.py +tag_prefix = v +parentdir_prefix = matlab_kernel- diff --git a/setup.py b/setup.py new file mode 100644 index 0000000..2ea5670 --- /dev/null +++ b/setup.py @@ -0,0 +1,21 @@ +from setuptools import setup, find_packages +import versioneer + + +if __name__ == "__main__": + setup(name="matlab_kernel", + author="Steven Silvester, Antony Lee", + version=versioneer.get_version(), + cmdclass=versioneer.get_cmdclass(), + url="https://github.com/Calysto/matlab_kernel", + license="BSD", + long_description=open("README.rst").read(), + classifiers=["Framework :: IPython", + "License :: OSI Approved :: BSD License", + "Programming Language :: Python :: 2", + "Programming Language :: Python :: 3", + "Topic :: System :: Shells",], + packages=find_packages(include=["matlab_kernel", "matlab_kernel.*"]), + install_requires=["metakernel>=0.13.1", + "wurlitzer>=0.2.0",], + ) diff --git a/versioneer.py b/versioneer.py new file mode 100644 index 0000000..03b9a96 --- /dev/null +++ b/versioneer.py @@ -0,0 +1,1733 @@ + +# Version: 0.16+dev + +"""The Versioneer - like a rocketeer, but for versions. + +The Versioneer +============== + +* like a rocketeer, but for versions! +* https://github.com/warner/python-versioneer +* Brian Warner +* License: Public Domain +* Compatible With: python2.6, 2.7, 3.3, 3.4, 3.5, and pypy +* [![Latest Version] +(https://pypip.in/version/versioneer/badge.svg?style=flat) +](https://pypi.python.org/pypi/versioneer/) +* [![Build Status] +(https://travis-ci.org/warner/python-versioneer.png?branch=master) +](https://travis-ci.org/warner/python-versioneer) + +This is a tool for managing a recorded version number in distutils-based +python projects. The goal is to remove the tedious and error-prone "update +the embedded version string" step from your release process. Making a new +release should be as easy as recording a new tag in your version-control +system, and maybe making new tarballs. + + +## Quick Install + +* `pip install versioneer` to somewhere to your $PATH +* add a `[versioneer]` section to your setup.cfg (see below) +* run `versioneer install` in your source tree, commit the results + +## Version Identifiers + +Source trees come from a variety of places: + +* a version-control system checkout (mostly used by developers) +* a nightly tarball, produced by build automation +* a snapshot tarball, produced by a web-based VCS browser, like github's + "tarball from tag" feature +* a release tarball, produced by "setup.py sdist", distributed through PyPI + +Within each source tree, the version identifier (either a string or a number, +this tool is format-agnostic) can come from a variety of places: + +* ask the VCS tool itself, e.g. "git describe" (for checkouts), which knows + about recent "tags" and an absolute revision-id +* the name of the directory into which the tarball was unpacked +* an expanded VCS keyword ($Id$, etc) +* a `_version.py` created by some earlier build step + +For released software, the version identifier is closely related to a VCS +tag. Some projects use tag names that include more than just the version +string (e.g. "myproject-1.2" instead of just "1.2"), in which case the tool +needs to strip the tag prefix to extract the version identifier. For +unreleased software (between tags), the version identifier should provide +enough information to help developers recreate the same tree, while also +giving them an idea of roughly how old the tree is (after version 1.2, before +version 1.3). Many VCS systems can report a description that captures this, +for example `git describe --tags --dirty --always` reports things like +"0.7-1-g574ab98-dirty" to indicate that the checkout is one revision past the +0.7 tag, has a unique revision id of "574ab98", and is "dirty" (it has +uncommitted changes. + +The version identifier is used for multiple purposes: + +* to allow the module to self-identify its version: `myproject.__version__` +* to choose a name and prefix for a 'setup.py sdist' tarball + +## Theory of Operation + +Versioneer works by adding a special `_version.py` file into your source +tree, where your `__init__.py` can import it. This `_version.py` knows how to +dynamically ask the VCS tool for version information at import time. + +`_version.py` also contains `$Revision$` markers, and the installation +process marks `_version.py` to have this marker rewritten with a tag name +during the `git archive` command. As a result, generated tarballs will +contain enough information to get the proper version. + +To allow `setup.py` to compute a version too, a `versioneer.py` is added to +the top level of your source tree, next to `setup.py` and the `setup.cfg` +that configures it. This overrides several distutils/setuptools commands to +compute the version when invoked, and changes `setup.py build` and `setup.py +sdist` to replace `_version.py` with a small static file that contains just +the generated version data. + +## Installation + +See [INSTALL.md](./INSTALL.md) for detailed installation instructions. + +## Version-String Flavors + +Code which uses Versioneer can learn about its version string at runtime by +importing `_version` from your main `__init__.py` file and running the +`get_versions()` function. From the "outside" (e.g. in `setup.py`), you can +import the top-level `versioneer.py` and run `get_versions()`. + +Both functions return a dictionary with different flavors of version +information: + +* `['version']`: A condensed version string, rendered using the selected + style. This is the most commonly used value for the project's version + string. The default "pep440" style yields strings like `0.11`, + `0.11+2.g1076c97`, or `0.11+2.g1076c97.dirty`. See the "Styles" section + below for alternative styles. + +* `['full-revisionid']`: detailed revision identifier. For Git, this is the + full SHA1 commit id, e.g. "1076c978a8d3cfc70f408fe5974aa6c092c949ac". + +* `['dirty']`: a boolean, True if the tree has uncommitted changes. Note that + this is only accurate if run in a VCS checkout, otherwise it is likely to + be False or None + +* `['error']`: if the version string could not be computed, this will be set + to a string describing the problem, otherwise it will be None. It may be + useful to throw an exception in setup.py if this is set, to avoid e.g. + creating tarballs with a version string of "unknown". + +Some variants are more useful than others. Including `full-revisionid` in a +bug report should allow developers to reconstruct the exact code being tested +(or indicate the presence of local changes that should be shared with the +developers). `version` is suitable for display in an "about" box or a CLI +`--version` output: it can be easily compared against release notes and lists +of bugs fixed in various releases. + +The installer adds the following text to your `__init__.py` to place a basic +version in `YOURPROJECT.__version__`: + + from ._version import get_versions + __version__ = get_versions()['version'] + del get_versions + +## Styles + +The setup.cfg `style=` configuration controls how the VCS information is +rendered into a version string. + +The default style, "pep440", produces a PEP440-compliant string, equal to the +un-prefixed tag name for actual releases, and containing an additional "local +version" section with more detail for in-between builds. For Git, this is +TAG[+DISTANCE.gHEX[.dirty]] , using information from `git describe --tags +--dirty --always`. For example "0.11+2.g1076c97.dirty" indicates that the +tree is like the "1076c97" commit but has uncommitted changes (".dirty"), and +that this commit is two revisions ("+2") beyond the "0.11" tag. For released +software (exactly equal to a known tag), the identifier will only contain the +stripped tag, e.g. "0.11". + +Other styles are available. See details.md in the Versioneer source tree for +descriptions. + +## Debugging + +Versioneer tries to avoid fatal errors: if something goes wrong, it will tend +to return a version of "0+unknown". To investigate the problem, run `setup.py +version`, which will run the version-lookup code in a verbose mode, and will +display the full contents of `get_versions()` (including the `error` string, +which may help identify what went wrong). + +## Known Limitations + +Some situations are known to cause problems for Versioneer. This details the +most significant ones. More can be found on Github +[issues page](https://github.com/warner/python-versioneer/issues). + +### Subprojects + +Versioneer has limited support for source trees in which `setup.py` is not in +the root directory (e.g. `setup.py` and `.git/` are *not* siblings). The are +two common reasons why `setup.py` might not be in the root: + +* Source trees which contain multiple subprojects, such as + [Buildbot](https://github.com/buildbot/buildbot), which contains both + "master" and "slave" subprojects, each with their own `setup.py`, + `setup.cfg`, and `tox.ini`. Projects like these produce multiple PyPI + distributions (and upload multiple independently-installable tarballs). +* Source trees whose main purpose is to contain a C library, but which also + provide bindings to Python (and perhaps other langauges) in subdirectories. + +Versioneer will look for `.git` in parent directories, and most operations +should get the right version string. However `pip` and `setuptools` have bugs +and implementation details which frequently cause `pip install .` from a +subproject directory to fail to find a correct version string (so it usually +defaults to `0+unknown`). + +`pip install --editable .` should work correctly. `setup.py install` might +work too. + +Pip-8.1.1 is known to have this problem, but hopefully it will get fixed in +some later version. + +[Bug #38](https://github.com/warner/python-versioneer/issues/38) is tracking +this issue. The discussion in +[PR #61](https://github.com/warner/python-versioneer/pull/61) describes the +issue from the Versioneer side in more detail. +[pip PR#3176](https://github.com/pypa/pip/pull/3176) and +[pip PR#3615](https://github.com/pypa/pip/pull/3615) contain work to improve +pip to let Versioneer work correctly. + +Versioneer-0.16 and earlier only looked for a `.git` directory next to the +`setup.cfg`, so subprojects were completely unsupported with those releases. + +### Editable installs with setuptools <= 18.5 + +`setup.py develop` and `pip install --editable .` allow you to install a +project into a virtualenv once, then continue editing the source code (and +test) without re-installing after every change. + +"Entry-point scripts" (`setup(entry_points={"console_scripts": ..})`) are a +convenient way to specify executable scripts that should be installed along +with the python package. + +These both work as expected when using modern setuptools. When using +setuptools-18.5 or earlier, however, certain operations will cause +`pkg_resources.DistributionNotFound` errors when running the entrypoint +script, which must be resolved by re-installing the package. This happens +when the install happens with one version, then the egg_info data is +regenerated while a different version is checked out. Many setup.py commands +cause egg_info to be rebuilt (including `sdist`, `wheel`, and installing into +a different virtualenv), so this can be surprising. + +[Bug #83](https://github.com/warner/python-versioneer/issues/83) describes +this one, but upgrading to a newer version of setuptools should probably +resolve it. + +### Unicode version strings + +While Versioneer works (and is continually tested) with both Python 2 and +Python 3, it is not entirely consistent with bytes-vs-unicode distinctions. +Newer releases probably generate unicode version strings on py2. It's not +clear that this is wrong, but it may be surprising for applications when then +write these strings to a network connection or include them in bytes-oriented +APIs like cryptographic checksums. + +[Bug #71](https://github.com/warner/python-versioneer/issues/71) investigates +this question. + + +## Updating Versioneer + +To upgrade your project to a new release of Versioneer, do the following: + +* install the new Versioneer (`pip install -U versioneer` or equivalent) +* edit `setup.cfg`, if necessary, to include any new configuration settings + indicated by the release notes. See [UPGRADING](./UPGRADING.md) for details. +* re-run `versioneer install` in your source tree, to replace + `SRC/_version.py` +* commit any changed files + +## Future Directions + +This tool is designed to make it easily extended to other version-control +systems: all VCS-specific components are in separate directories like +src/git/ . The top-level `versioneer.py` script is assembled from these +components by running make-versioneer.py . In the future, make-versioneer.py +will take a VCS name as an argument, and will construct a version of +`versioneer.py` that is specific to the given VCS. It might also take the +configuration arguments that are currently provided manually during +installation by editing setup.py . Alternatively, it might go the other +direction and include code from all supported VCS systems, reducing the +number of intermediate scripts. + + +## License + +To make Versioneer easier to embed, all its code is dedicated to the public +domain. The `_version.py` that it creates is also in the public domain. +Specifically, both are released under the Creative Commons "Public Domain +Dedication" license (CC0-1.0), as described in +https://creativecommons.org/publicdomain/zero/1.0/ . + +""" + +from __future__ import print_function +try: + import configparser +except ImportError: + import ConfigParser as configparser +import errno +import json +import os +import re +import subprocess +import sys + + +class VersioneerConfig: + """Container for Versioneer configuration parameters.""" + + +def get_root(): + """Get the project root directory. + + We require that all commands are run from the project root, i.e. the + directory that contains setup.py, setup.cfg, and versioneer.py . + """ + root = os.path.realpath(os.path.abspath(os.getcwd())) + setup_py = os.path.join(root, "setup.py") + versioneer_py = os.path.join(root, "versioneer.py") + if not (os.path.exists(setup_py) or os.path.exists(versioneer_py)): + # allow 'python path/to/setup.py COMMAND' + root = os.path.dirname(os.path.realpath(os.path.abspath(sys.argv[0]))) + setup_py = os.path.join(root, "setup.py") + versioneer_py = os.path.join(root, "versioneer.py") + if not (os.path.exists(setup_py) or os.path.exists(versioneer_py)): + err = ("Versioneer was unable to run the project root directory. " + "Versioneer requires setup.py to be executed from " + "its immediate directory (like 'python setup.py COMMAND'), " + "or in a way that lets it use sys.argv[0] to find the root " + "(like 'python path/to/setup.py COMMAND').") + raise VersioneerBadRootError(err) + try: + # Certain runtime workflows (setup.py install/develop in a setuptools + # tree) execute all dependencies in a single python process, so + # "versioneer" may be imported multiple times, and python's shared + # module-import table will cache the first one. So we can't use + # os.path.dirname(__file__), as that will find whichever + # versioneer.py was first imported, even in later projects. + me = os.path.realpath(os.path.abspath(__file__)) + me_dir = os.path.normcase(os.path.splitext(me)[0]) + vsr_dir = os.path.normcase(os.path.splitext(versioneer_py)[0]) + if me_dir != vsr_dir: + print("Warning: build in %s is using versioneer.py from %s" + % (os.path.dirname(me), versioneer_py)) + except NameError: + pass + return root + + +def get_config_from_root(root): + """Read the project setup.cfg file to determine Versioneer config.""" + # This might raise EnvironmentError (if setup.cfg is missing), or + # configparser.NoSectionError (if it lacks a [versioneer] section), or + # configparser.NoOptionError (if it lacks "VCS="). See the docstring at + # the top of versioneer.py for instructions on writing your setup.cfg . + setup_cfg = os.path.join(root, "setup.cfg") + parser = configparser.SafeConfigParser() + with open(setup_cfg, "r") as f: + parser.readfp(f) + VCS = parser.get("versioneer", "VCS") # mandatory + + def get(parser, name): + if parser.has_option("versioneer", name): + return parser.get("versioneer", name) + return None + cfg = VersioneerConfig() + cfg.VCS = VCS + cfg.style = get(parser, "style") or "" + cfg.versionfile_source = get(parser, "versionfile_source") + cfg.versionfile_build = get(parser, "versionfile_build") + cfg.tag_prefix = get(parser, "tag_prefix") + if cfg.tag_prefix in ("''", '""'): + cfg.tag_prefix = "" + cfg.parentdir_prefix = get(parser, "parentdir_prefix") + cfg.verbose = get(parser, "verbose") + return cfg + + +class NotThisMethod(Exception): + """Exception raised if a method is not valid for the current scenario.""" + +# these dictionaries contain VCS-specific tools +LONG_VERSION_PY = {} +HANDLERS = {} + + +def register_vcs_handler(vcs, method): # decorator + """Decorator to mark a method as the handler for a particular VCS.""" + def decorate(f): + """Store f in HANDLERS[vcs][method].""" + if vcs not in HANDLERS: + HANDLERS[vcs] = {} + HANDLERS[vcs][method] = f + return f + return decorate + + +def run_command(commands, args, cwd=None, verbose=False, hide_stderr=False, + env=None): + """Call the given command(s).""" + assert isinstance(commands, list) + p = None + for c in commands: + try: + dispcmd = str([c] + args) + # remember shell=False, so use git.cmd on windows, not just git + p = subprocess.Popen([c] + args, cwd=cwd, env=env, + stdout=subprocess.PIPE, + stderr=(subprocess.PIPE if hide_stderr + else None)) + break + except EnvironmentError: + e = sys.exc_info()[1] + if e.errno == errno.ENOENT: + continue + if verbose: + print("unable to run %s" % dispcmd) + print(e) + return None, None + else: + if verbose: + print("unable to find command, tried %s" % (commands,)) + return None, None + stdout = p.communicate()[0].strip() + if sys.version_info[0] >= 3: + stdout = stdout.decode() + if p.returncode != 0: + if verbose: + print("unable to run %s (error)" % dispcmd) + print("stdout was %s" % stdout) + return None, p.returncode + return stdout, p.returncode +LONG_VERSION_PY['git'] = ''' +# This file helps to compute a version number in source trees obtained from +# git-archive tarball (such as those provided by githubs download-from-tag +# feature). Distribution tarballs (built by setup.py sdist) and build +# directories (produced by setup.py build) will contain a much shorter file +# that just contains the computed version number. + +# This file is released into the public domain. Generated by +# versioneer-0.16+dev (https://github.com/warner/python-versioneer) + +"""Git implementation of _version.py.""" + +import errno +import os +import re +import subprocess +import sys + + +def get_keywords(): + """Get the keywords needed to look up the version information.""" + # these strings will be replaced by git during git-archive. + # setup.py/versioneer.py will grep for the variable names, so they must + # each be defined on a line of their own. _version.py will just call + # get_keywords(). + git_refnames = "%(DOLLAR)sFormat:%%d%(DOLLAR)s" + git_full = "%(DOLLAR)sFormat:%%H%(DOLLAR)s" + keywords = {"refnames": git_refnames, "full": git_full} + return keywords + + +class VersioneerConfig: + """Container for Versioneer configuration parameters.""" + + +def get_config(): + """Create, populate and return the VersioneerConfig() object.""" + # these strings are filled in when 'setup.py versioneer' creates + # _version.py + cfg = VersioneerConfig() + cfg.VCS = "git" + cfg.style = "%(STYLE)s" + cfg.tag_prefix = "%(TAG_PREFIX)s" + cfg.parentdir_prefix = "%(PARENTDIR_PREFIX)s" + cfg.versionfile_source = "%(VERSIONFILE_SOURCE)s" + cfg.verbose = False + return cfg + + +class NotThisMethod(Exception): + """Exception raised if a method is not valid for the current scenario.""" + + +LONG_VERSION_PY = {} +HANDLERS = {} + + +def register_vcs_handler(vcs, method): # decorator + """Decorator to mark a method as the handler for a particular VCS.""" + def decorate(f): + """Store f in HANDLERS[vcs][method].""" + if vcs not in HANDLERS: + HANDLERS[vcs] = {} + HANDLERS[vcs][method] = f + return f + return decorate + + +def run_command(commands, args, cwd=None, verbose=False, hide_stderr=False, + env=None): + """Call the given command(s).""" + assert isinstance(commands, list) + p = None + for c in commands: + try: + dispcmd = str([c] + args) + # remember shell=False, so use git.cmd on windows, not just git + p = subprocess.Popen([c] + args, cwd=cwd, env=env, + stdout=subprocess.PIPE, + stderr=(subprocess.PIPE if hide_stderr + else None)) + break + except EnvironmentError: + e = sys.exc_info()[1] + if e.errno == errno.ENOENT: + continue + if verbose: + print("unable to run %%s" %% dispcmd) + print(e) + return None, None + else: + if verbose: + print("unable to find command, tried %%s" %% (commands,)) + return None, None + stdout = p.communicate()[0].strip() + if sys.version_info[0] >= 3: + stdout = stdout.decode() + if p.returncode != 0: + if verbose: + print("unable to run %%s (error)" %% dispcmd) + print("stdout was %%s" %% stdout) + return None, p.returncode + return stdout, p.returncode + + +def versions_from_parentdir(parentdir_prefix, root, verbose): + """Try to determine the version from the parent directory name. + + Source tarballs conventionally unpack into a directory that includes both + the project name and a version string. We will also support searching up + two directory levels for an appropriately named parent directory + """ + rootdirs = [] + + for i in range(3): + dirname = os.path.basename(root) + if dirname.startswith(parentdir_prefix): + return {"version": dirname[len(parentdir_prefix):], + "full-revisionid": None, + "dirty": False, "error": None} + else: + rootdirs.append(root) + root = os.path.dirname(root) # up a level + + if verbose: + print("Tried directories %%s but none started with prefix %%s" %% + (str(rootdirs), parentdir_prefix)) + raise NotThisMethod("rootdir doesn't start with parentdir_prefix") + + +@register_vcs_handler("git", "get_keywords") +def git_get_keywords(versionfile_abs): + """Extract version information from the given file.""" + # the code embedded in _version.py can just fetch the value of these + # keywords. When used from setup.py, we don't want to import _version.py, + # so we do it with a regexp instead. This function is not used from + # _version.py. + keywords = {} + try: + f = open(versionfile_abs, "r") + for line in f.readlines(): + if line.strip().startswith("git_refnames ="): + mo = re.search(r'=\s*"(.*)"', line) + if mo: + keywords["refnames"] = mo.group(1) + if line.strip().startswith("git_full ="): + mo = re.search(r'=\s*"(.*)"', line) + if mo: + keywords["full"] = mo.group(1) + f.close() + except EnvironmentError: + pass + return keywords + + +@register_vcs_handler("git", "keywords") +def git_versions_from_keywords(keywords, tag_prefix, verbose): + """Get version information from git keywords.""" + if not keywords: + raise NotThisMethod("no keywords at all, weird") + refnames = keywords["refnames"].strip() + if refnames.startswith("$Format"): + if verbose: + print("keywords are unexpanded, not using") + raise NotThisMethod("unexpanded keywords, not a git-archive tarball") + refs = set([r.strip() for r in refnames.strip("()").split(",")]) + # starting in git-1.8.3, tags are listed as "tag: foo-1.0" instead of + # just "foo-1.0". If we see a "tag: " prefix, prefer those. + TAG = "tag: " + tags = set([r[len(TAG):] for r in refs if r.startswith(TAG)]) + if not tags: + # Either we're using git < 1.8.3, or there really are no tags. We use + # a heuristic: assume all version tags have a digit. The old git %%d + # expansion behaves like git log --decorate=short and strips out the + # refs/heads/ and refs/tags/ prefixes that would let us distinguish + # between branches and tags. By ignoring refnames without digits, we + # filter out many common branch names like "release" and + # "stabilization", as well as "HEAD" and "master". + tags = set([r for r in refs if re.search(r'\d', r)]) + if verbose: + print("discarding '%%s', no digits" %% ",".join(refs-tags)) + if verbose: + print("likely tags: %%s" %% ",".join(sorted(tags))) + for ref in sorted(tags): + # sorting will prefer e.g. "2.0" over "2.0rc1" + if ref.startswith(tag_prefix): + r = ref[len(tag_prefix):] + if verbose: + print("picking %%s" %% r) + return {"version": r, + "full-revisionid": keywords["full"].strip(), + "dirty": False, "error": None + } + # no suitable tags, so version is "0+unknown", but full hex is still there + if verbose: + print("no suitable tags, using unknown + full revision id") + return {"version": "0+unknown", + "full-revisionid": keywords["full"].strip(), + "dirty": False, "error": "no suitable tags"} + + +@register_vcs_handler("git", "pieces_from_vcs") +def git_pieces_from_vcs(tag_prefix, root, verbose, run_command=run_command): + """Get version from 'git describe' in the root of the source tree. + + This only gets called if the git-archive 'subst' keywords were *not* + expanded, and _version.py hasn't already been rewritten with a short + version string, meaning we're inside a checked out source tree. + """ + GITS = ["git"] + if sys.platform == "win32": + GITS = ["git.cmd", "git.exe"] + + out, rc = run_command(GITS, ["rev-parse", "--git-dir"], cwd=root, + hide_stderr=True) + if rc != 0: + if verbose: + print("Directory %%s not under git control" %% root) + raise NotThisMethod("'git rev-parse --git-dir' returned error") + + # if there is a tag matching tag_prefix, this yields TAG-NUM-gHEX[-dirty] + # if there isn't one, this yields HEX[-dirty] (no NUM) + describe_out, rc = run_command(GITS, ["describe", "--tags", "--dirty", + "--always", "--long", + "--match", "%%s*" %% tag_prefix], + cwd=root) + # --long was added in git-1.5.5 + if describe_out is None: + raise NotThisMethod("'git describe' failed") + describe_out = describe_out.strip() + full_out, rc = run_command(GITS, ["rev-parse", "HEAD"], cwd=root) + if full_out is None: + raise NotThisMethod("'git rev-parse' failed") + full_out = full_out.strip() + + pieces = {} + pieces["long"] = full_out + pieces["short"] = full_out[:7] # maybe improved later + pieces["error"] = None + + # parse describe_out. It will be like TAG-NUM-gHEX[-dirty] or HEX[-dirty] + # TAG might have hyphens. + git_describe = describe_out + + # look for -dirty suffix + dirty = git_describe.endswith("-dirty") + pieces["dirty"] = dirty + if dirty: + git_describe = git_describe[:git_describe.rindex("-dirty")] + + # now we have TAG-NUM-gHEX or HEX + + if "-" in git_describe: + # TAG-NUM-gHEX + mo = re.search(r'^(.+)-(\d+)-g([0-9a-f]+)$', git_describe) + if not mo: + # unparseable. Maybe git-describe is misbehaving? + pieces["error"] = ("unable to parse git-describe output: '%%s'" + %% describe_out) + return pieces + + # tag + full_tag = mo.group(1) + if not full_tag.startswith(tag_prefix): + if verbose: + fmt = "tag '%%s' doesn't start with prefix '%%s'" + print(fmt %% (full_tag, tag_prefix)) + pieces["error"] = ("tag '%%s' doesn't start with prefix '%%s'" + %% (full_tag, tag_prefix)) + return pieces + pieces["closest-tag"] = full_tag[len(tag_prefix):] + + # distance: number of commits since tag + pieces["distance"] = int(mo.group(2)) + + # commit: short hex revision ID + pieces["short"] = mo.group(3) + + else: + # HEX: no tags + pieces["closest-tag"] = None + count_out, rc = run_command(GITS, ["rev-list", "HEAD", "--count"], + cwd=root) + pieces["distance"] = int(count_out) # total number of commits + + return pieces + + +def plus_or_dot(pieces): + """Return a + if we don't already have one, else return a .""" + if "+" in pieces.get("closest-tag", ""): + return "." + return "+" + + +def render_pep440(pieces): + """Build up version string, with post-release "local version identifier". + + Our goal: TAG[+DISTANCE.gHEX[.dirty]] . Note that if you + get a tagged build and then dirty it, you'll get TAG+0.gHEX.dirty + + Exceptions: + 1: no tags. git_describe was just HEX. 0+untagged.DISTANCE.gHEX[.dirty] + """ + if pieces["closest-tag"]: + rendered = pieces["closest-tag"] + if pieces["distance"] or pieces["dirty"]: + rendered += plus_or_dot(pieces) + rendered += "%%d.g%%s" %% (pieces["distance"], pieces["short"]) + if pieces["dirty"]: + rendered += ".dirty" + else: + # exception #1 + rendered = "0+untagged.%%d.g%%s" %% (pieces["distance"], + pieces["short"]) + if pieces["dirty"]: + rendered += ".dirty" + return rendered + + +def render_pep440_pre(pieces): + """TAG[.post.devDISTANCE] -- No -dirty. + + Exceptions: + 1: no tags. 0.post.devDISTANCE + """ + if pieces["closest-tag"]: + rendered = pieces["closest-tag"] + if pieces["distance"]: + rendered += ".post.dev%%d" %% pieces["distance"] + else: + # exception #1 + rendered = "0.post.dev%%d" %% pieces["distance"] + return rendered + + +def render_pep440_post(pieces): + """TAG[.postDISTANCE[.dev0]+gHEX] . + + The ".dev0" means dirty. Note that .dev0 sorts backwards + (a dirty tree will appear "older" than the corresponding clean one), + but you shouldn't be releasing software with -dirty anyways. + + Exceptions: + 1: no tags. 0.postDISTANCE[.dev0] + """ + if pieces["closest-tag"]: + rendered = pieces["closest-tag"] + if pieces["distance"] or pieces["dirty"]: + rendered += ".post%%d" %% pieces["distance"] + if pieces["dirty"]: + rendered += ".dev0" + rendered += plus_or_dot(pieces) + rendered += "g%%s" %% pieces["short"] + else: + # exception #1 + rendered = "0.post%%d" %% pieces["distance"] + if pieces["dirty"]: + rendered += ".dev0" + rendered += "+g%%s" %% pieces["short"] + return rendered + + +def render_pep440_old(pieces): + """TAG[.postDISTANCE[.dev0]] . + + The ".dev0" means dirty. + + Eexceptions: + 1: no tags. 0.postDISTANCE[.dev0] + """ + if pieces["closest-tag"]: + rendered = pieces["closest-tag"] + if pieces["distance"] or pieces["dirty"]: + rendered += ".post%%d" %% pieces["distance"] + if pieces["dirty"]: + rendered += ".dev0" + else: + # exception #1 + rendered = "0.post%%d" %% pieces["distance"] + if pieces["dirty"]: + rendered += ".dev0" + return rendered + + +def render_git_describe(pieces): + """TAG[-DISTANCE-gHEX][-dirty]. + + Like 'git describe --tags --dirty --always'. + + Exceptions: + 1: no tags. HEX[-dirty] (note: no 'g' prefix) + """ + if pieces["closest-tag"]: + rendered = pieces["closest-tag"] + if pieces["distance"]: + rendered += "-%%d-g%%s" %% (pieces["distance"], pieces["short"]) + else: + # exception #1 + rendered = pieces["short"] + if pieces["dirty"]: + rendered += "-dirty" + return rendered + + +def render_git_describe_long(pieces): + """TAG-DISTANCE-gHEX[-dirty]. + + Like 'git describe --tags --dirty --always -long'. + The distance/hash is unconditional. + + Exceptions: + 1: no tags. HEX[-dirty] (note: no 'g' prefix) + """ + if pieces["closest-tag"]: + rendered = pieces["closest-tag"] + rendered += "-%%d-g%%s" %% (pieces["distance"], pieces["short"]) + else: + # exception #1 + rendered = pieces["short"] + if pieces["dirty"]: + rendered += "-dirty" + return rendered + + +def render(pieces, style): + """Render the given version pieces into the requested style.""" + if pieces["error"]: + return {"version": "unknown", + "full-revisionid": pieces.get("long"), + "dirty": None, + "error": pieces["error"]} + + if not style or style == "default": + style = "pep440" # the default + + if style == "pep440": + rendered = render_pep440(pieces) + elif style == "pep440-pre": + rendered = render_pep440_pre(pieces) + elif style == "pep440-post": + rendered = render_pep440_post(pieces) + elif style == "pep440-old": + rendered = render_pep440_old(pieces) + elif style == "git-describe": + rendered = render_git_describe(pieces) + elif style == "git-describe-long": + rendered = render_git_describe_long(pieces) + else: + raise ValueError("unknown style '%%s'" %% style) + + return {"version": rendered, "full-revisionid": pieces["long"], + "dirty": pieces["dirty"], "error": None} + + +def get_versions(): + """Get version information or return default if unable to do so.""" + # I am in _version.py, which lives at ROOT/VERSIONFILE_SOURCE. If we have + # __file__, we can work backwards from there to the root. Some + # py2exe/bbfreeze/non-CPython implementations don't do __file__, in which + # case we can only use expanded keywords. + + cfg = get_config() + verbose = cfg.verbose + + try: + return git_versions_from_keywords(get_keywords(), cfg.tag_prefix, + verbose) + except NotThisMethod: + pass + + try: + root = os.path.realpath(__file__) + # versionfile_source is the relative path from the top of the source + # tree (where the .git directory might live) to this file. Invert + # this to find the root from __file__. + for i in cfg.versionfile_source.split('/'): + root = os.path.dirname(root) + except NameError: + return {"version": "0+unknown", "full-revisionid": None, + "dirty": None, + "error": "unable to find root of source tree"} + + try: + pieces = git_pieces_from_vcs(cfg.tag_prefix, root, verbose) + return render(pieces, cfg.style) + except NotThisMethod: + pass + + try: + if cfg.parentdir_prefix: + return versions_from_parentdir(cfg.parentdir_prefix, root, verbose) + except NotThisMethod: + pass + + return {"version": "0+unknown", "full-revisionid": None, + "dirty": None, + "error": "unable to compute version"} +''' + + +@register_vcs_handler("git", "get_keywords") +def git_get_keywords(versionfile_abs): + """Extract version information from the given file.""" + # the code embedded in _version.py can just fetch the value of these + # keywords. When used from setup.py, we don't want to import _version.py, + # so we do it with a regexp instead. This function is not used from + # _version.py. + keywords = {} + try: + f = open(versionfile_abs, "r") + for line in f.readlines(): + if line.strip().startswith("git_refnames ="): + mo = re.search(r'=\s*"(.*)"', line) + if mo: + keywords["refnames"] = mo.group(1) + if line.strip().startswith("git_full ="): + mo = re.search(r'=\s*"(.*)"', line) + if mo: + keywords["full"] = mo.group(1) + f.close() + except EnvironmentError: + pass + return keywords + + +@register_vcs_handler("git", "keywords") +def git_versions_from_keywords(keywords, tag_prefix, verbose): + """Get version information from git keywords.""" + if not keywords: + raise NotThisMethod("no keywords at all, weird") + refnames = keywords["refnames"].strip() + if refnames.startswith("$Format"): + if verbose: + print("keywords are unexpanded, not using") + raise NotThisMethod("unexpanded keywords, not a git-archive tarball") + refs = set([r.strip() for r in refnames.strip("()").split(",")]) + # starting in git-1.8.3, tags are listed as "tag: foo-1.0" instead of + # just "foo-1.0". If we see a "tag: " prefix, prefer those. + TAG = "tag: " + tags = set([r[len(TAG):] for r in refs if r.startswith(TAG)]) + if not tags: + # Either we're using git < 1.8.3, or there really are no tags. We use + # a heuristic: assume all version tags have a digit. The old git %d + # expansion behaves like git log --decorate=short and strips out the + # refs/heads/ and refs/tags/ prefixes that would let us distinguish + # between branches and tags. By ignoring refnames without digits, we + # filter out many common branch names like "release" and + # "stabilization", as well as "HEAD" and "master". + tags = set([r for r in refs if re.search(r'\d', r)]) + if verbose: + print("discarding '%s', no digits" % ",".join(refs-tags)) + if verbose: + print("likely tags: %s" % ",".join(sorted(tags))) + for ref in sorted(tags): + # sorting will prefer e.g. "2.0" over "2.0rc1" + if ref.startswith(tag_prefix): + r = ref[len(tag_prefix):] + if verbose: + print("picking %s" % r) + return {"version": r, + "full-revisionid": keywords["full"].strip(), + "dirty": False, "error": None + } + # no suitable tags, so version is "0+unknown", but full hex is still there + if verbose: + print("no suitable tags, using unknown + full revision id") + return {"version": "0+unknown", + "full-revisionid": keywords["full"].strip(), + "dirty": False, "error": "no suitable tags"} + + +@register_vcs_handler("git", "pieces_from_vcs") +def git_pieces_from_vcs(tag_prefix, root, verbose, run_command=run_command): + """Get version from 'git describe' in the root of the source tree. + + This only gets called if the git-archive 'subst' keywords were *not* + expanded, and _version.py hasn't already been rewritten with a short + version string, meaning we're inside a checked out source tree. + """ + GITS = ["git"] + if sys.platform == "win32": + GITS = ["git.cmd", "git.exe"] + + out, rc = run_command(GITS, ["rev-parse", "--git-dir"], cwd=root, + hide_stderr=True) + if rc != 0: + if verbose: + print("Directory %s not under git control" % root) + raise NotThisMethod("'git rev-parse --git-dir' returned error") + + # if there is a tag matching tag_prefix, this yields TAG-NUM-gHEX[-dirty] + # if there isn't one, this yields HEX[-dirty] (no NUM) + describe_out, rc = run_command(GITS, ["describe", "--tags", "--dirty", + "--always", "--long", + "--match", "%s*" % tag_prefix], + cwd=root) + # --long was added in git-1.5.5 + if describe_out is None: + raise NotThisMethod("'git describe' failed") + describe_out = describe_out.strip() + full_out, rc = run_command(GITS, ["rev-parse", "HEAD"], cwd=root) + if full_out is None: + raise NotThisMethod("'git rev-parse' failed") + full_out = full_out.strip() + + pieces = {} + pieces["long"] = full_out + pieces["short"] = full_out[:7] # maybe improved later + pieces["error"] = None + + # parse describe_out. It will be like TAG-NUM-gHEX[-dirty] or HEX[-dirty] + # TAG might have hyphens. + git_describe = describe_out + + # look for -dirty suffix + dirty = git_describe.endswith("-dirty") + pieces["dirty"] = dirty + if dirty: + git_describe = git_describe[:git_describe.rindex("-dirty")] + + # now we have TAG-NUM-gHEX or HEX + + if "-" in git_describe: + # TAG-NUM-gHEX + mo = re.search(r'^(.+)-(\d+)-g([0-9a-f]+)$', git_describe) + if not mo: + # unparseable. Maybe git-describe is misbehaving? + pieces["error"] = ("unable to parse git-describe output: '%s'" + % describe_out) + return pieces + + # tag + full_tag = mo.group(1) + if not full_tag.startswith(tag_prefix): + if verbose: + fmt = "tag '%s' doesn't start with prefix '%s'" + print(fmt % (full_tag, tag_prefix)) + pieces["error"] = ("tag '%s' doesn't start with prefix '%s'" + % (full_tag, tag_prefix)) + return pieces + pieces["closest-tag"] = full_tag[len(tag_prefix):] + + # distance: number of commits since tag + pieces["distance"] = int(mo.group(2)) + + # commit: short hex revision ID + pieces["short"] = mo.group(3) + + else: + # HEX: no tags + pieces["closest-tag"] = None + count_out, rc = run_command(GITS, ["rev-list", "HEAD", "--count"], + cwd=root) + pieces["distance"] = int(count_out) # total number of commits + + return pieces + + +def do_vcs_install(manifest_in, versionfile_source, ipy): + """Git-specific installation logic for Versioneer. + + For Git, this means creating/changing .gitattributes to mark _version.py + for export-time keyword substitution. + """ + GITS = ["git"] + if sys.platform == "win32": + GITS = ["git.cmd", "git.exe"] + files = [manifest_in, versionfile_source] + if ipy: + files.append(ipy) + try: + me = __file__ + if me.endswith(".pyc") or me.endswith(".pyo"): + me = os.path.splitext(me)[0] + ".py" + versioneer_file = os.path.relpath(me) + except NameError: + versioneer_file = "versioneer.py" + files.append(versioneer_file) + present = False + try: + f = open(".gitattributes", "r") + for line in f.readlines(): + if line.strip().startswith(versionfile_source): + if "export-subst" in line.strip().split()[1:]: + present = True + f.close() + except EnvironmentError: + pass + if not present: + f = open(".gitattributes", "a+") + f.write("%s export-subst\n" % versionfile_source) + f.close() + files.append(".gitattributes") + run_command(GITS, ["add", "--"] + files) + + +def versions_from_parentdir(parentdir_prefix, root, verbose): + """Try to determine the version from the parent directory name. + + Source tarballs conventionally unpack into a directory that includes both + the project name and a version string. We will also support searching up + two directory levels for an appropriately named parent directory + """ + rootdirs = [] + + for i in range(3): + dirname = os.path.basename(root) + if dirname.startswith(parentdir_prefix): + return {"version": dirname[len(parentdir_prefix):], + "full-revisionid": None, + "dirty": False, "error": None} + else: + rootdirs.append(root) + root = os.path.dirname(root) # up a level + + if verbose: + print("Tried directories %s but none started with prefix %s" % + (str(rootdirs), parentdir_prefix)) + raise NotThisMethod("rootdir doesn't start with parentdir_prefix") + +SHORT_VERSION_PY = """ +# This file was generated by 'versioneer.py' (0.16+dev) from +# revision-control system data, or from the parent directory name of an +# unpacked source archive. Distribution tarballs contain a pre-generated copy +# of this file. + +import json +import sys + +version_json = ''' +%s +''' # END VERSION_JSON + + +def get_versions(): + return json.loads(version_json) +""" + + +def versions_from_file(filename): + """Try to determine the version from _version.py if present.""" + try: + with open(filename) as f: + contents = f.read() + except EnvironmentError: + raise NotThisMethod("unable to read _version.py") + mo = re.search(r"version_json = '''\n(.*)''' # END VERSION_JSON", + contents, re.M | re.S) + if not mo: + raise NotThisMethod("no version_json in _version.py") + return json.loads(mo.group(1)) + + +def write_to_version_file(filename, versions): + """Write the given version number to the given _version.py file.""" + os.unlink(filename) + contents = json.dumps(versions, sort_keys=True, + indent=1, separators=(",", ": ")) + with open(filename, "w") as f: + f.write(SHORT_VERSION_PY % contents) + + print("set %s to '%s'" % (filename, versions["version"])) + + +def plus_or_dot(pieces): + """Return a + if we don't already have one, else return a .""" + if "+" in pieces.get("closest-tag", ""): + return "." + return "+" + + +def render_pep440(pieces): + """Build up version string, with post-release "local version identifier". + + Our goal: TAG[+DISTANCE.gHEX[.dirty]] . Note that if you + get a tagged build and then dirty it, you'll get TAG+0.gHEX.dirty + + Exceptions: + 1: no tags. git_describe was just HEX. 0+untagged.DISTANCE.gHEX[.dirty] + """ + if pieces["closest-tag"]: + rendered = pieces["closest-tag"] + if pieces["distance"] or pieces["dirty"]: + rendered += plus_or_dot(pieces) + rendered += "%d.g%s" % (pieces["distance"], pieces["short"]) + if pieces["dirty"]: + rendered += ".dirty" + else: + # exception #1 + rendered = "0+untagged.%d.g%s" % (pieces["distance"], + pieces["short"]) + if pieces["dirty"]: + rendered += ".dirty" + return rendered + + +def render_pep440_pre(pieces): + """TAG[.post.devDISTANCE] -- No -dirty. + + Exceptions: + 1: no tags. 0.post.devDISTANCE + """ + if pieces["closest-tag"]: + rendered = pieces["closest-tag"] + if pieces["distance"]: + rendered += ".post.dev%d" % pieces["distance"] + else: + # exception #1 + rendered = "0.post.dev%d" % pieces["distance"] + return rendered + + +def render_pep440_post(pieces): + """TAG[.postDISTANCE[.dev0]+gHEX] . + + The ".dev0" means dirty. Note that .dev0 sorts backwards + (a dirty tree will appear "older" than the corresponding clean one), + but you shouldn't be releasing software with -dirty anyways. + + Exceptions: + 1: no tags. 0.postDISTANCE[.dev0] + """ + if pieces["closest-tag"]: + rendered = pieces["closest-tag"] + if pieces["distance"] or pieces["dirty"]: + rendered += ".post%d" % pieces["distance"] + if pieces["dirty"]: + rendered += ".dev0" + rendered += plus_or_dot(pieces) + rendered += "g%s" % pieces["short"] + else: + # exception #1 + rendered = "0.post%d" % pieces["distance"] + if pieces["dirty"]: + rendered += ".dev0" + rendered += "+g%s" % pieces["short"] + return rendered + + +def render_pep440_old(pieces): + """TAG[.postDISTANCE[.dev0]] . + + The ".dev0" means dirty. + + Eexceptions: + 1: no tags. 0.postDISTANCE[.dev0] + """ + if pieces["closest-tag"]: + rendered = pieces["closest-tag"] + if pieces["distance"] or pieces["dirty"]: + rendered += ".post%d" % pieces["distance"] + if pieces["dirty"]: + rendered += ".dev0" + else: + # exception #1 + rendered = "0.post%d" % pieces["distance"] + if pieces["dirty"]: + rendered += ".dev0" + return rendered + + +def render_git_describe(pieces): + """TAG[-DISTANCE-gHEX][-dirty]. + + Like 'git describe --tags --dirty --always'. + + Exceptions: + 1: no tags. HEX[-dirty] (note: no 'g' prefix) + """ + if pieces["closest-tag"]: + rendered = pieces["closest-tag"] + if pieces["distance"]: + rendered += "-%d-g%s" % (pieces["distance"], pieces["short"]) + else: + # exception #1 + rendered = pieces["short"] + if pieces["dirty"]: + rendered += "-dirty" + return rendered + + +def render_git_describe_long(pieces): + """TAG-DISTANCE-gHEX[-dirty]. + + Like 'git describe --tags --dirty --always -long'. + The distance/hash is unconditional. + + Exceptions: + 1: no tags. HEX[-dirty] (note: no 'g' prefix) + """ + if pieces["closest-tag"]: + rendered = pieces["closest-tag"] + rendered += "-%d-g%s" % (pieces["distance"], pieces["short"]) + else: + # exception #1 + rendered = pieces["short"] + if pieces["dirty"]: + rendered += "-dirty" + return rendered + + +def render(pieces, style): + """Render the given version pieces into the requested style.""" + if pieces["error"]: + return {"version": "unknown", + "full-revisionid": pieces.get("long"), + "dirty": None, + "error": pieces["error"]} + + if not style or style == "default": + style = "pep440" # the default + + if style == "pep440": + rendered = render_pep440(pieces) + elif style == "pep440-pre": + rendered = render_pep440_pre(pieces) + elif style == "pep440-post": + rendered = render_pep440_post(pieces) + elif style == "pep440-old": + rendered = render_pep440_old(pieces) + elif style == "git-describe": + rendered = render_git_describe(pieces) + elif style == "git-describe-long": + rendered = render_git_describe_long(pieces) + else: + raise ValueError("unknown style '%s'" % style) + + return {"version": rendered, "full-revisionid": pieces["long"], + "dirty": pieces["dirty"], "error": None} + + +class VersioneerBadRootError(Exception): + """The project root directory is unknown or missing key files.""" + + +def get_versions(verbose=False): + """Get the project version from whatever source is available. + + Returns dict with two keys: 'version' and 'full'. + """ + if "versioneer" in sys.modules: + # see the discussion in cmdclass.py:get_cmdclass() + del sys.modules["versioneer"] + + root = get_root() + cfg = get_config_from_root(root) + + assert cfg.VCS is not None, "please set [versioneer]VCS= in setup.cfg" + handlers = HANDLERS.get(cfg.VCS) + assert handlers, "unrecognized VCS '%s'" % cfg.VCS + verbose = verbose or cfg.verbose + assert cfg.versionfile_source is not None, \ + "please set versioneer.versionfile_source" + assert cfg.tag_prefix is not None, "please set versioneer.tag_prefix" + + versionfile_abs = os.path.join(root, cfg.versionfile_source) + + # extract version from first of: _version.py, VCS command (e.g. 'git + # describe'), parentdir. This is meant to work for developers using a + # source checkout, for users of a tarball created by 'setup.py sdist', + # and for users of a tarball/zipball created by 'git archive' or github's + # download-from-tag feature or the equivalent in other VCSes. + + get_keywords_f = handlers.get("get_keywords") + from_keywords_f = handlers.get("keywords") + if get_keywords_f and from_keywords_f: + try: + keywords = get_keywords_f(versionfile_abs) + ver = from_keywords_f(keywords, cfg.tag_prefix, verbose) + if verbose: + print("got version from expanded keyword %s" % ver) + return ver + except NotThisMethod: + pass + + try: + ver = versions_from_file(versionfile_abs) + if verbose: + print("got version from file %s %s" % (versionfile_abs, ver)) + return ver + except NotThisMethod: + pass + + from_vcs_f = handlers.get("pieces_from_vcs") + if from_vcs_f: + try: + pieces = from_vcs_f(cfg.tag_prefix, root, verbose) + ver = render(pieces, cfg.style) + if verbose: + print("got version from VCS %s" % ver) + return ver + except NotThisMethod: + pass + + try: + if cfg.parentdir_prefix: + ver = versions_from_parentdir(cfg.parentdir_prefix, root, verbose) + if verbose: + print("got version from parentdir %s" % ver) + return ver + except NotThisMethod: + pass + + if verbose: + print("unable to compute version") + + return {"version": "0+unknown", "full-revisionid": None, + "dirty": None, "error": "unable to compute version"} + + +def get_version(): + """Get the short version string for this project.""" + return get_versions()["version"] + + +def get_cmdclass(): + """Get the custom setuptools/distutils subclasses used by Versioneer.""" + if "versioneer" in sys.modules: + del sys.modules["versioneer"] + # this fixes the "python setup.py develop" case (also 'install' and + # 'easy_install .'), in which subdependencies of the main project are + # built (using setup.py bdist_egg) in the same python process. Assume + # a main project A and a dependency B, which use different versions + # of Versioneer. A's setup.py imports A's Versioneer, leaving it in + # sys.modules by the time B's setup.py is executed, causing B to run + # with the wrong versioneer. Setuptools wraps the sub-dep builds in a + # sandbox that restores sys.modules to it's pre-build state, so the + # parent is protected against the child's "import versioneer". By + # removing ourselves from sys.modules here, before the child build + # happens, we protect the child from the parent's versioneer too. + # Also see https://github.com/warner/python-versioneer/issues/52 + + cmds = {} + + # we add "version" to both distutils and setuptools + from distutils.core import Command + + class cmd_version(Command): + description = "report generated version string" + user_options = [] + boolean_options = [] + + def initialize_options(self): + pass + + def finalize_options(self): + pass + + def run(self): + vers = get_versions(verbose=True) + print("Version: %s" % vers["version"]) + print(" full-revisionid: %s" % vers.get("full-revisionid")) + print(" dirty: %s" % vers.get("dirty")) + if vers["error"]: + print(" error: %s" % vers["error"]) + cmds["version"] = cmd_version + + # we override "build_py" in both distutils and setuptools + # + # most invocation pathways end up running build_py: + # distutils/build -> build_py + # distutils/install -> distutils/build ->.. + # setuptools/bdist_wheel -> distutils/install ->.. + # setuptools/bdist_egg -> distutils/install_lib -> build_py + # setuptools/install -> bdist_egg ->.. + # setuptools/develop -> ? + # pip install: + # copies source tree to a tempdir before running egg_info/etc + # if .git isn't copied too, 'git describe' will fail + # then does setup.py bdist_wheel, or sometimes setup.py install + # setup.py egg_info -> ? + + # we override different "build_py" commands for both environments + if "setuptools" in sys.modules: + from setuptools.command.build_py import build_py as _build_py + else: + from distutils.command.build_py import build_py as _build_py + + class cmd_build_py(_build_py): + def run(self): + root = get_root() + cfg = get_config_from_root(root) + versions = get_versions() + _build_py.run(self) + # now locate _version.py in the new build/ directory and replace + # it with an updated value + if cfg.versionfile_build: + target_versionfile = os.path.join(self.build_lib, + cfg.versionfile_build) + print("UPDATING %s" % target_versionfile) + write_to_version_file(target_versionfile, versions) + cmds["build_py"] = cmd_build_py + + if "cx_Freeze" in sys.modules: # cx_freeze enabled? + from cx_Freeze.dist import build_exe as _build_exe + + class cmd_build_exe(_build_exe): + def run(self): + root = get_root() + cfg = get_config_from_root(root) + versions = get_versions() + target_versionfile = cfg.versionfile_source + print("UPDATING %s" % target_versionfile) + write_to_version_file(target_versionfile, versions) + + _build_exe.run(self) + os.unlink(target_versionfile) + with open(cfg.versionfile_source, "w") as f: + LONG = LONG_VERSION_PY[cfg.VCS] + f.write(LONG % + {"DOLLAR": "$", + "STYLE": cfg.style, + "TAG_PREFIX": cfg.tag_prefix, + "PARENTDIR_PREFIX": cfg.parentdir_prefix, + "VERSIONFILE_SOURCE": cfg.versionfile_source, + }) + cmds["build_exe"] = cmd_build_exe + del cmds["build_py"] + + # we override different "sdist" commands for both environments + if "setuptools" in sys.modules: + from setuptools.command.sdist import sdist as _sdist + else: + from distutils.command.sdist import sdist as _sdist + + class cmd_sdist(_sdist): + def run(self): + versions = get_versions() + self._versioneer_generated_versions = versions + # unless we update this, the command will keep using the old + # version + self.distribution.metadata.version = versions["version"] + return _sdist.run(self) + + def make_release_tree(self, base_dir, files): + root = get_root() + cfg = get_config_from_root(root) + _sdist.make_release_tree(self, base_dir, files) + # now locate _version.py in the new base_dir directory + # (remembering that it may be a hardlink) and replace it with an + # updated value + target_versionfile = os.path.join(base_dir, cfg.versionfile_source) + print("UPDATING %s" % target_versionfile) + write_to_version_file(target_versionfile, + self._versioneer_generated_versions) + cmds["sdist"] = cmd_sdist + + return cmds + + +CONFIG_ERROR = """ +setup.cfg is missing the necessary Versioneer configuration. You need +a section like: + + [versioneer] + VCS = git + style = pep440 + versionfile_source = src/myproject/_version.py + versionfile_build = myproject/_version.py + tag_prefix = + parentdir_prefix = myproject- + +You will also need to edit your setup.py to use the results: + + import versioneer + setup(version=versioneer.get_version(), + cmdclass=versioneer.get_cmdclass(), ...) + +Please read the docstring in ./versioneer.py for configuration instructions, +edit setup.cfg, and re-run the installer or 'python versioneer.py setup'. +""" + +SAMPLE_CONFIG = """ +# See the docstring in versioneer.py for instructions. Note that you must +# re-run 'versioneer.py setup' after changing this section, and commit the +# resulting files. + +[versioneer] +#VCS = git +#style = pep440 +#versionfile_source = +#versionfile_build = +#tag_prefix = +#parentdir_prefix = + +""" + +INIT_PY_SNIPPET = """ +from ._version import get_versions +__version__ = get_versions()['version'] +del get_versions +""" + + +def do_setup(): + """Main VCS-independent setup function for installing Versioneer.""" + root = get_root() + try: + cfg = get_config_from_root(root) + except (EnvironmentError, configparser.NoSectionError, + configparser.NoOptionError) as e: + if isinstance(e, (EnvironmentError, configparser.NoSectionError)): + print("Adding sample versioneer config to setup.cfg", + file=sys.stderr) + with open(os.path.join(root, "setup.cfg"), "a") as f: + f.write(SAMPLE_CONFIG) + print(CONFIG_ERROR, file=sys.stderr) + return 1 + + print(" creating %s" % cfg.versionfile_source) + with open(cfg.versionfile_source, "w") as f: + LONG = LONG_VERSION_PY[cfg.VCS] + f.write(LONG % {"DOLLAR": "$", + "STYLE": cfg.style, + "TAG_PREFIX": cfg.tag_prefix, + "PARENTDIR_PREFIX": cfg.parentdir_prefix, + "VERSIONFILE_SOURCE": cfg.versionfile_source, + }) + + ipy = os.path.join(os.path.dirname(cfg.versionfile_source), + "__init__.py") + if os.path.exists(ipy): + try: + with open(ipy, "r") as f: + old = f.read() + except EnvironmentError: + old = "" + if INIT_PY_SNIPPET not in old: + print(" appending to %s" % ipy) + with open(ipy, "a") as f: + f.write(INIT_PY_SNIPPET) + else: + print(" %s unmodified" % ipy) + else: + print(" %s doesn't exist, ok" % ipy) + ipy = None + + # Make sure both the top-level "versioneer.py" and versionfile_source + # (PKG/_version.py, used by runtime code) are in MANIFEST.in, so + # they'll be copied into source distributions. Pip won't be able to + # install the package without this. + manifest_in = os.path.join(root, "MANIFEST.in") + simple_includes = set() + try: + with open(manifest_in, "r") as f: + for line in f: + if line.startswith("include "): + for include in line.split()[1:]: + simple_includes.add(include) + except EnvironmentError: + pass + # That doesn't cover everything MANIFEST.in can do + # (http://docs.python.org/2/distutils/sourcedist.html#commands), so + # it might give some false negatives. Appending redundant 'include' + # lines is safe, though. + if "versioneer.py" not in simple_includes: + print(" appending 'versioneer.py' to MANIFEST.in") + with open(manifest_in, "a") as f: + f.write("include versioneer.py\n") + else: + print(" 'versioneer.py' already in MANIFEST.in") + if cfg.versionfile_source not in simple_includes: + print(" appending versionfile_source ('%s') to MANIFEST.in" % + cfg.versionfile_source) + with open(manifest_in, "a") as f: + f.write("include %s\n" % cfg.versionfile_source) + else: + print(" versionfile_source already in MANIFEST.in") + + # Make VCS-specific changes. For git, this means creating/changing + # .gitattributes to mark _version.py for export-time keyword + # substitution. + do_vcs_install(manifest_in, cfg.versionfile_source, ipy) + return 0 + + +def scan_setup_py(): + """Validate the contents of setup.py against Versioneer's expectations.""" + found = set() + setters = False + errors = 0 + with open("setup.py", "r") as f: + for line in f.readlines(): + if "import versioneer" in line: + found.add("import") + if "versioneer.get_cmdclass()" in line: + found.add("cmdclass") + if "versioneer.get_version()" in line: + found.add("get_version") + if "versioneer.VCS" in line: + setters = True + if "versioneer.versionfile_source" in line: + setters = True + if len(found) != 3: + print("") + print("Your setup.py appears to be missing some important items") + print("(but I might be wrong). Please make sure it has something") + print("roughly like the following:") + print("") + print(" import versioneer") + print(" setup( version=versioneer.get_version(),") + print(" cmdclass=versioneer.get_cmdclass(), ...)") + print("") + errors += 1 + if setters: + print("You should remove lines like 'versioneer.VCS = ' and") + print("'versioneer.versionfile_source = ' . This configuration") + print("now lives in setup.cfg, and should be removed from setup.py") + print("") + errors += 1 + return errors + +if __name__ == "__main__": + cmd = sys.argv[1] + if cmd == "setup": + errors = do_setup() + errors += scan_setup_py() + if errors: + sys.exit(1) From 30988e37a3472eca540fded01b4130db1d81ae74 Mon Sep 17 00:00:00 2001 From: Antony Lee Date: Tue, 30 Aug 2016 22:07:33 -0700 Subject: [PATCH 05/88] Wrap MATLAB output at C-level for live updates. --- matlab_kernel/kernel.py | 25 ++++++++++++++----------- 1 file changed, 14 insertions(+), 11 deletions(-) diff --git a/matlab_kernel/kernel.py b/matlab_kernel/kernel.py index 59684fd..91889ff 100644 --- a/matlab_kernel/kernel.py +++ b/matlab_kernel/kernel.py @@ -1,5 +1,6 @@ from __future__ import division, print_function +from functools import partial import os import shutil import sys @@ -9,8 +10,9 @@ else: from io import StringIO -from metakernel import MetaKernel from IPython.display import Image +from metakernel import MetaKernel +from wurlitzer import Wurlitzer import matlab.engine from matlab.engine import MatlabExecutionError @@ -18,6 +20,11 @@ from . import __version__ +class _PseudoStream: + def __init__(self, writer): + self.write = writer + + class MatlabKernel(MetaKernel): implementation = "Matlab Kernel" implementation_version = __version__, @@ -62,16 +69,12 @@ def do_execute_direct(self, code): self._matlab.get(0., "defaultfigureposition")[0][2:]) self.handle_plot_settings() - out = StringIO() - err = StringIO() - try: - self._matlab.eval(code, nargout=0, stdout=out, stderr=err) - except (SyntaxError, MatlabExecutionError) as exc: - stdout = exc.args[0] - self.Error(stdout) - return - stdout = out.getvalue() - self.Print(stdout) + with Wurlitzer(_PseudoStream(partial(self.Print, end="")), + _PseudoStream(partial(self.Error, end=""))): + try: + self._matlab.eval(code, nargout=0) + except (SyntaxError, MatlabExecutionError): + return settings = self._validated_plot_settings if settings["backend"] == "inline": From 6a5f2f1a648ff1326fdc953fa799373602b96d6b Mon Sep 17 00:00:00 2001 From: Antony Lee Date: Tue, 30 Aug 2016 22:24:54 -0700 Subject: [PATCH 06/88] Update README; remove outdated HISTORY. --- HISTORY.rst | 29 ----------------------------- README.rst | 20 +++++++++----------- 2 files changed, 9 insertions(+), 40 deletions(-) delete mode 100644 HISTORY.rst diff --git a/HISTORY.rst b/HISTORY.rst deleted file mode 100644 index c1b96d5..0000000 --- a/HISTORY.rst +++ /dev/null @@ -1,29 +0,0 @@ -.. :changelog: - -Release History ---------------- - -0.8 (2016-01-17) -++++++++++++++++ -- Fix startup and add support for Octave. - - -0.7 (2016-01-14) -++++++++++++++++ -- Switch to 2-step install. - - -0.4 (2015-02-27) -+++++++++++++++++ -- Fix first execution command -- Fix restart handling - stop current matlab process - - -0.3 (2015-02-10) -+++++++++++++++++ -- Add support for %plot magic (size) and saner default size - - -0.1 (2015-02-01) -++++++++++++++++++ -- Initial release diff --git a/README.rst b/README.rst index 68ede24..0ccf679 100644 --- a/README.rst +++ b/README.rst @@ -1,24 +1,22 @@ A Jupyter/IPython kernel for Matlab - +=================================== This requires `Jupyter Notebook `_, and the `Matlab engine for Python `_. To install:: - pip install matlab_kernel + $ pip install matlab_kernel # or `pip install git+https://github.com/Calysto/matlab_kernel` # for the devel version. - python -m matlab_kernel install - -To use it, run one of: + $ python -m matlab_kernel install -.. code:: shell +To use it, run one of:: - ipython notebook + $ jupyter notebook # In the notebook interface, select Matlab from the 'New' menu - ipython qtconsole --kernel matlab - ipython console --kernel matlab + $ jupyter qtconsole --kernel matlab + $ jupyter console --kernel matlab This is based on `MetaKernel `_, which means it features a standard set of magics. @@ -27,7 +25,7 @@ A sample notebook is available online_. A note about plotting. After each call to Matlab, we ask Matlab to save any open figures to image files whose format and resolution are defined using the -`%plot` magic. The resulting image is shown inline in the notebook. You can -use `%plot native` to raise normal MATLAB windows instead. +``%plot`` magic. The resulting image is shown inline in the notebook. You can +use ``%plot native`` to raise normal Matlab windows instead. .. _online: http://nbviewer.ipython.org/github/Calysto/matlab_kernel/blob/master/matlab_kernel.ipynb From 6d57d52564f3ebf834c51f60b4de75876c95dd62 Mon Sep 17 00:00:00 2001 From: Antony Lee Date: Wed, 31 Aug 2016 16:06:35 -0700 Subject: [PATCH 07/88] Fix kernel name in example notebook. --- matlab_kernel.ipynb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/matlab_kernel.ipynb b/matlab_kernel.ipynb index b96ade9..be7e02a 100644 --- a/matlab_kernel.ipynb +++ b/matlab_kernel.ipynb @@ -643,7 +643,7 @@ "kernelspec": { "display_name": "Matlab", "language": "matlab", - "name": "matlab_kernel" + "name": "matlab" }, "language_info": { "file_extension": ".m", From a9dfd2bd476551d57fb2873db335db52e5c0abe2 Mon Sep 17 00:00:00 2001 From: Antony Lee Date: Thu, 1 Sep 2016 09:49:50 -0700 Subject: [PATCH 08/88] Call MATLAB asynchronously. Drop Py2 support. --- matlab_kernel/kernel.py | 22 ++++++++++------------ 1 file changed, 10 insertions(+), 12 deletions(-) diff --git a/matlab_kernel/kernel.py b/matlab_kernel/kernel.py index 91889ff..38e1836 100644 --- a/matlab_kernel/kernel.py +++ b/matlab_kernel/kernel.py @@ -1,14 +1,10 @@ -from __future__ import division, print_function - +from concurrent.futures import ThreadPoolExecutor from functools import partial +from io import StringIO import os import shutil import sys import tempfile -if sys.version_info[0] < 3: - from StringIO import StringIO -else: - from io import StringIO from IPython.display import Image from metakernel import MetaKernel @@ -69,12 +65,14 @@ def do_execute_direct(self, code): self._matlab.get(0., "defaultfigureposition")[0][2:]) self.handle_plot_settings() - with Wurlitzer(_PseudoStream(partial(self.Print, end="")), - _PseudoStream(partial(self.Error, end=""))): - try: - self._matlab.eval(code, nargout=0) - except (SyntaxError, MatlabExecutionError): - return + try: + with Wurlitzer(_PseudoStream(partial(self.Print, end="")), + _PseudoStream(partial(self.Error, end=""))), \ + ThreadPoolExecutor(1) as executor: + future = self._matlab.eval(code, nargout=0, async=True) + executor.submit(future.result) + except (SyntaxError, MatlabExecutionError, KeyboardInterrupt): + pass settings = self._validated_plot_settings if settings["backend"] == "inline": From bfd8441158d079222ef08622e0a8a1963ae1fedc Mon Sep 17 00:00:00 2001 From: Antony Lee Date: Tue, 6 Sep 2016 16:29:16 -0700 Subject: [PATCH 09/88] Check for complete statements. Requires Py>=3.4. --- README.rst | 9 +++++-- matlab_kernel/kernel.py | 54 ++++++++++++++++++++++++++--------------- setup.py | 9 +++++-- 3 files changed, 48 insertions(+), 24 deletions(-) diff --git a/README.rst b/README.rst index 0ccf679..23ca2ef 100644 --- a/README.rst +++ b/README.rst @@ -1,8 +1,13 @@ +|Python3x| + +.. |Python3x| image:: https://img.shields.io/badge/python-3.x-blue.svg + A Jupyter/IPython kernel for Matlab =================================== -This requires `Jupyter Notebook `_, -and the `Matlab engine for Python `_. +This requires `Jupyter Notebook `_ +with Python 3.4+, and the +`Matlab engine for Python `_. To install:: diff --git a/matlab_kernel/kernel.py b/matlab_kernel/kernel.py index 38e1836..7eb925f 100644 --- a/matlab_kernel/kernel.py +++ b/matlab_kernel/kernel.py @@ -2,9 +2,9 @@ from functools import partial from io import StringIO import os -import shutil +from pathlib import Path import sys -import tempfile +from tempfile import TemporaryDirectory from IPython.display import Image from metakernel import MetaKernel @@ -78,24 +78,25 @@ def do_execute_direct(self, code): if settings["backend"] == "inline": nfig = len(self._matlab.get(0., "children")) if nfig: - tmpdir = tempfile.mkdtemp() - try: - self._matlab.eval( - "arrayfun(" - "@(h, i) print(h, sprintf('{}/%i', i), '-d{}', '-r{}')," - "get(0, 'children'), (1:{})')" - .format(tmpdir, settings["format"], settings["resolution"], nfig), - nargout=0) - self._matlab.eval( - "arrayfun(@(h) close(h), get(0, 'children'))", - nargout=0) - for fname in sorted(os.listdir(tmpdir)): - self.Display(Image( - filename="{}/{}".format(tmpdir, fname))) - except Exception as exc: - self.Error(exc) - finally: - shutil.rmtree(tmpdir) + with TemporaryDirectory() as tmpdir: + try: + self._matlab.eval( + "arrayfun(" + "@(h, i) print(h, sprintf('{}/%i', i), '-d{}', '-r{}')," + "get(0, 'children'), (1:{})')".format( + tmpdir, + settings["format"], + settings["resolution"], + nfig), + nargout=0) + self._matlab.eval( + "arrayfun(@(h) close(h), get(0, 'children'))", + nargout=0) + for fname in sorted(os.listdir(tmpdir)): + self.Display(Image( + filename="{}/{}".format(tmpdir, fname))) + except Exception as exc: + self.Error(exc) def get_kernel_help_on(self, info, level=0, none_on_fail=False): name = info.get("help_obj", "") @@ -146,6 +147,19 @@ def get_completions(self, info): return compls + def do_is_complete(self, code): + if self.parse_code(code)["magic"]: + return {"status": "complete"} + with TemporaryDirectory() as tmpdir: + Path(tmpdir, "test_complete.m").write_text(code) + self._matlab.eval( + "try, pcode {} -inplace; catch, end".format(tmpdir), + nargout=0) + if Path(tmpdir, "test_complete.p").exists(): + return {"status": "complete"} + else: + return {"status": "incomplete"} + def handle_plot_settings(self): raw = self.plot_settings settings = self._validated_plot_settings diff --git a/setup.py b/setup.py index 2ea5670..8a9110f 100644 --- a/setup.py +++ b/setup.py @@ -1,8 +1,13 @@ +import sys + from setuptools import setup, find_packages import versioneer if __name__ == "__main__": + if sys.version_info < (3, 4): + raise ImportError("matlab_kernel requires Python>=3.4") + setup(name="matlab_kernel", author="Steven Silvester, Antony Lee", version=versioneer.get_version(), @@ -12,8 +17,8 @@ long_description=open("README.rst").read(), classifiers=["Framework :: IPython", "License :: OSI Approved :: BSD License", - "Programming Language :: Python :: 2", - "Programming Language :: Python :: 3", + "Programming Language :: Python :: 3.4", + "Programming Language :: Python :: 3.5", "Topic :: System :: Shells",], packages=find_packages(include=["matlab_kernel", "matlab_kernel.*"]), install_requires=["metakernel>=0.13.1", From 316e878981a233959714bdda065b73cb180f5c0f Mon Sep 17 00:00:00 2001 From: Antony Lee Date: Tue, 6 Sep 2016 17:57:35 -0700 Subject: [PATCH 10/88] Vendor fflush-less wurlitzer. Based on wurlitzer 0.2.0, but without flushing in the forwarder loop to prevent blocking. Also removed non-essential API. --- LICENSE.txt | 25 ++++++ matlab_kernel/kernel.py | 2 +- matlab_kernel/wurlitzer.py | 173 +++++++++++++++++++++++++++++++++++++ setup.py | 3 +- 4 files changed, 200 insertions(+), 3 deletions(-) create mode 100644 matlab_kernel/wurlitzer.py diff --git a/LICENSE.txt b/LICENSE.txt index 659f3d1..576b967 100644 --- a/LICENSE.txt +++ b/LICENSE.txt @@ -10,3 +10,28 @@ Redistribution and use in source and binary forms, with or without modification, 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + + +wurlitzer was originally published under the following license: + +The MIT License (MIT) + +Copyright (c) 2016 Min RK + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/matlab_kernel/kernel.py b/matlab_kernel/kernel.py index 7eb925f..520ec4a 100644 --- a/matlab_kernel/kernel.py +++ b/matlab_kernel/kernel.py @@ -8,12 +8,12 @@ from IPython.display import Image from metakernel import MetaKernel -from wurlitzer import Wurlitzer import matlab.engine from matlab.engine import MatlabExecutionError from . import __version__ +from .wurlitzer import Wurlitzer class _PseudoStream: diff --git a/matlab_kernel/wurlitzer.py b/matlab_kernel/wurlitzer.py new file mode 100644 index 0000000..4ce4020 --- /dev/null +++ b/matlab_kernel/wurlitzer.py @@ -0,0 +1,173 @@ +"""Capture C-level FD output on pipes + +Use `wurlitzer.pipes` or `wurlitzer.sys_pipes` as context managers. +""" +from __future__ import print_function + +__version__ = '0.2.1.dev' + +__all__ = [ + 'Wurlitzer', +] + +from contextlib import contextmanager +import ctypes +from fcntl import fcntl, F_GETFL, F_SETFL +import io +import os +import select +import sys +import threading + +libc = ctypes.CDLL(None) + +try: + c_stdout_p = ctypes.c_void_p.in_dll(libc, 'stdout') + c_stderr_p = ctypes.c_void_p.in_dll(libc, 'stderr') +except ValueError: # pragma: no cover + # libc.stdout is has a funny name on OS X + c_stdout_p = ctypes.c_void_p.in_dll(libc, '__stdoutp') # pragma: no cover + c_stderr_p = ctypes.c_void_p.in_dll(libc, '__stderrp') # pragma: no cover + +STDOUT = 2 +PIPE = 3 + +_default_encoding = getattr(sys.stdin, 'encoding', None) or 'utf8' +if _default_encoding.lower() == 'ascii': + # don't respect ascii + _default_encoding = 'utf8' # pragma: no cover + +class Wurlitzer(object): + """Class for Capturing Process-level FD output via dup2 + + Typically used via `wurlitzer.capture` + """ + flush_interval = 0.2 + + def __init__(self, stdout=None, stderr=None, encoding=_default_encoding): + """ + Parameters + ---------- + stdout: stream or None + The stream for forwarding stdout. + stderr = stream or None + The stream for forwarding stderr. + encoding: str or None + The encoding to use, if streams should be interpreted as text. + """ + self._stdout = stdout + if stderr == STDOUT: + self._stderr = self._stdout + else: + self._stderr = stderr + self.encoding = encoding + self._save_fds = {} + self._real_fds = {} + self._handlers = {} + self._handlers['stderr'] = self._handle_stderr + self._handlers['stdout'] = self._handle_stdout + + def _setup_pipe(self, name): + real_fd = getattr(sys, '__%s__' % name).fileno() + save_fd = os.dup(real_fd) + self._save_fds[name] = save_fd + + pipe_out, pipe_in = os.pipe() + os.dup2(pipe_in, real_fd) + os.close(pipe_in) + self._real_fds[name] = real_fd + + # make pipe_out non-blocking + flags = fcntl(pipe_out, F_GETFL) + fcntl(pipe_out, F_SETFL, flags|os.O_NONBLOCK) + return pipe_out + + def _decode(self, data): + """Decode data, if any + + Called before pasing to stdout/stderr streams + """ + if self.encoding: + data = data.decode(self.encoding, 'replace') + return data + + def _handle_stdout(self, data): + if self._stdout: + self._stdout.write(self._decode(data)) + + def _handle_stderr(self, data): + if self._stderr: + self._stderr.write(self._decode(data)) + + def _setup_handle(self): + """Setup handle for output, if any""" + self.handle = (self._stdout, self._stderr) + + def _finish_handle(self): + """Finish handle, if anything should be done when it's all wrapped up.""" + pass + + def __enter__(self): + # flush anything out before starting + libc.fflush(c_stdout_p) + libc.fflush(c_stderr_p) + # setup handle + self._setup_handle() + + # create pipe for stdout + pipes = [] + names = {} + if self._stdout: + pipe = self._setup_pipe('stdout') + pipes.append(pipe) + names[pipe] = 'stdout' + if self._stderr: + pipe = self._setup_pipe('stderr') + pipes.append(pipe) + names[pipe] = 'stderr' + + def forwarder(): + """Forward bytes on a pipe to stream messages""" + while True: + # flush libc's buffers before calling select + # See Calysto/metakernel#5: flushing sometimes blocks. + # libc.fflush(c_stdout_p) + # libc.fflush(c_stderr_p) + r, w, x = select.select(pipes, [], [], self.flush_interval) + if not r: + # nothing to read, next iteration will flush and check again + continue + for pipe in r: + name = names[pipe] + data = os.read(pipe, 1024) + if not data: + # pipe closed, stop polling + pipes.remove(pipe) + else: + handler = getattr(self, '_handle_%s' % name) + handler(data) + if not pipes: + # pipes closed, we are done + break + self.thread = threading.Thread(target=forwarder) + self.thread.daemon = True + self.thread.start() + + return self.handle + + def __exit__(self, exc_type, exc_value, traceback): + # flush the underlying C buffers + libc.fflush(c_stdout_p) + libc.fflush(c_stderr_p) + # close FDs, signaling output is complete + for real_fd in self._real_fds.values(): + os.close(real_fd) + self.thread.join() + + # restore original state + for name, real_fd in self._real_fds.items(): + save_fd = self._save_fds[name] + os.dup2(save_fd, real_fd) + os.close(save_fd) + # finalize handle + self._finish_handle() diff --git a/setup.py b/setup.py index 8a9110f..3b3fca0 100644 --- a/setup.py +++ b/setup.py @@ -21,6 +21,5 @@ "Programming Language :: Python :: 3.5", "Topic :: System :: Shells",], packages=find_packages(include=["matlab_kernel", "matlab_kernel.*"]), - install_requires=["metakernel>=0.13.1", - "wurlitzer>=0.2.0",], + install_requires=["metakernel>=0.13.1"], ) From fc87d65fc199b7bc397f88a52adc3b013e928667 Mon Sep 17 00:00:00 2001 From: Antony Lee Date: Thu, 8 Sep 2016 10:11:24 -0700 Subject: [PATCH 11/88] No need to wait for the result in another thread. --- matlab_kernel/kernel.py | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/matlab_kernel/kernel.py b/matlab_kernel/kernel.py index 520ec4a..67eac77 100644 --- a/matlab_kernel/kernel.py +++ b/matlab_kernel/kernel.py @@ -1,4 +1,3 @@ -from concurrent.futures import ThreadPoolExecutor from functools import partial from io import StringIO import os @@ -67,10 +66,9 @@ def do_execute_direct(self, code): try: with Wurlitzer(_PseudoStream(partial(self.Print, end="")), - _PseudoStream(partial(self.Error, end=""))), \ - ThreadPoolExecutor(1) as executor: + _PseudoStream(partial(self.Error, end=""))): future = self._matlab.eval(code, nargout=0, async=True) - executor.submit(future.result) + future.result() except (SyntaxError, MatlabExecutionError, KeyboardInterrupt): pass From 28f0271c71755d3de9cd72c0071e3cea6ee23e14 Mon Sep 17 00:00:00 2001 From: Steven Silvester Date: Tue, 20 Dec 2016 10:24:13 -0600 Subject: [PATCH 12/88] Add handling of width and height options --- matlab_kernel/kernel.py | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/matlab_kernel/kernel.py b/matlab_kernel/kernel.py index 67eac77..e83f710 100644 --- a/matlab_kernel/kernel.py +++ b/matlab_kernel/kernel.py @@ -179,6 +179,11 @@ def handle_plot_settings(self): self.Error(exc) else: settings["size"] = size + if "width" in raw: + width, height = settings["size"] + raw.setdefault("width", width) + raw.setdefault("height", height) + settings["size"] = (raw["width"], raw["height"]) resolution = raw.get("resolution") if resolution is not None: From 4e23dd1c49458a0b002562fc7e0cf98a841385ff Mon Sep 17 00:00:00 2001 From: Steven Silvester Date: Mon, 13 Feb 2017 10:18:49 -0600 Subject: [PATCH 13/88] Fix typo in readme --- README.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.rst b/README.rst index 23ca2ef..5fd768b 100644 --- a/README.rst +++ b/README.rst @@ -14,7 +14,7 @@ To install:: $ pip install matlab_kernel # or `pip install git+https://github.com/Calysto/matlab_kernel` # for the devel version. - $ python -m matlab_kernel install + $ python -m matlab_kernel.install To use it, run one of:: From a610333a58e101938855c532072d36764e0f36ac Mon Sep 17 00:00:00 2001 From: Steven Silvester Date: Mon, 13 Feb 2017 10:32:58 -0600 Subject: [PATCH 14/88] Revert readme typo --- README.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.rst b/README.rst index 5fd768b..23ca2ef 100644 --- a/README.rst +++ b/README.rst @@ -14,7 +14,7 @@ To install:: $ pip install matlab_kernel # or `pip install git+https://github.com/Calysto/matlab_kernel` # for the devel version. - $ python -m matlab_kernel.install + $ python -m matlab_kernel install To use it, run one of:: From 53ea9e5ce7dc955dda4a6d21a5bed72801486f08 Mon Sep 17 00:00:00 2001 From: Jan Freyberg Date: Tue, 14 Feb 2017 12:41:45 +0000 Subject: [PATCH 15/88] Include a fallback to start_matlab() Falls back to connect_matlab() if start_matlab fails Note: restart kernel is in this case not really a restart - it re-connects to the matlab installation and clear all --- matlab_kernel/kernel.py | 13 +++++++++++-- 1 file changed, 11 insertions(+), 2 deletions(-) diff --git a/matlab_kernel/kernel.py b/matlab_kernel/kernel.py index 67eac77..090b38b 100644 --- a/matlab_kernel/kernel.py +++ b/matlab_kernel/kernel.py @@ -45,7 +45,10 @@ class MatlabKernel(MetaKernel): def __init__(self, *args, **kwargs): super(MatlabKernel, self).__init__(*args, **kwargs) - self._matlab = matlab.engine.start_matlab() + try: + self._matlab = matlab.engine.start_matlab() + except matlab.engine.EngineError: + self._matlab = matlab.engine.connect_matlab() self._first = True self._validated_plot_settings = { "backend": "inline", @@ -200,7 +203,13 @@ def repr(self, obj): def restart_kernel(self): self._matlab.exit() - self._matlab = matlab.engine.start_matlab() + try: + self._matlab = matlab.engine.start_matlab() + except matlab.engine.EngineError: + # This isn't a true restart + self._matlab = None # disconnect from engine + self._matlab = matlab.engine.connect_matlab() # re-connect + self._matlab.clear('all') # clear all content self._first = True def do_shutdown(self, restart): From eb550b0333278f42ac01e55de94723ad1aa27d98 Mon Sep 17 00:00:00 2001 From: Steven Silvester Date: Wed, 15 Feb 2017 04:41:46 -0600 Subject: [PATCH 16/88] Add support for Windows and Python 2.7 --- README.rst | 4 --- matlab_kernel/kernel.py | 55 ++++++++++++++++++++++++++++++++--------- setup.py | 13 +++++----- 3 files changed, 50 insertions(+), 22 deletions(-) diff --git a/README.rst b/README.rst index 23ca2ef..ba10348 100644 --- a/README.rst +++ b/README.rst @@ -1,12 +1,8 @@ -|Python3x| - -.. |Python3x| image:: https://img.shields.io/badge/python-3.x-blue.svg A Jupyter/IPython kernel for Matlab =================================== This requires `Jupyter Notebook `_ -with Python 3.4+, and the `Matlab engine for Python `_. To install:: diff --git a/matlab_kernel/kernel.py b/matlab_kernel/kernel.py index 090b38b..ffaac35 100644 --- a/matlab_kernel/kernel.py +++ b/matlab_kernel/kernel.py @@ -3,16 +3,29 @@ import os from pathlib import Path import sys -from tempfile import TemporaryDirectory +try: + from tempfile import TemporaryDirectory +except ImportError: + from backports import tempfile from IPython.display import Image from metakernel import MetaKernel -import matlab.engine -from matlab.engine import MatlabExecutionError - from . import __version__ -from .wurlitzer import Wurlitzer + +try: + from .wurlitzer import Wurlitzer +except ImportError: + Wurlitzer = None + +try: + import matlab.engine + from matlab.engine import MatlabExecutionError +except ImportError: + raise ImportError(""" +Matlab engine not installed: +See https://www.mathworks.com/help/matlab/matlab-engine-for-python.htm +""") class _PseudoStream: @@ -67,13 +80,10 @@ def do_execute_direct(self, code): self._matlab.get(0., "defaultfigureposition")[0][2:]) self.handle_plot_settings() - try: - with Wurlitzer(_PseudoStream(partial(self.Print, end="")), - _PseudoStream(partial(self.Error, end=""))): - future = self._matlab.eval(code, nargout=0, async=True) - future.result() - except (SyntaxError, MatlabExecutionError, KeyboardInterrupt): - pass + if Wurlitzer: + self._execute_async(code) + else: + self._execute_sync(code) settings = self._validated_plot_settings if settings["backend"] == "inline": @@ -216,6 +226,27 @@ def do_shutdown(self, restart): self._matlab.exit() return super(MatlabKernel, self).do_shutdown(restart) + def _execute_async(self, code): + try: + with Wurlitzer(_PseudoStream(partial(self.Print, end="")), + _PseudoStream(partial(self.Error, end=""))): + future = self._matlab.eval(code, nargout=0, async=True) + future.result() + except (SyntaxError, MatlabExecutionError, KeyboardInterrupt): + pass + + def _execute_sync(self, code): + out = StringIO() + err = StringIO() + try: + self._matlab.eval(code, nargout=0, stdout=out, stderr=err) + except (SyntaxError, MatlabExecutionError) as exc: + stdout = exc.args[0] + self.Error(stdout) + return + stdout = out.getvalue() + self.Print(stdout) + if __name__ == '__main__': try: diff --git a/setup.py b/setup.py index 3b3fca0..855a887 100644 --- a/setup.py +++ b/setup.py @@ -1,13 +1,9 @@ -import sys from setuptools import setup, find_packages import versioneer if __name__ == "__main__": - if sys.version_info < (3, 4): - raise ImportError("matlab_kernel requires Python>=3.4") - setup(name="matlab_kernel", author="Steven Silvester, Antony Lee", version=versioneer.get_version(), @@ -19,7 +15,12 @@ "License :: OSI Approved :: BSD License", "Programming Language :: Python :: 3.4", "Programming Language :: Python :: 3.5", - "Topic :: System :: Shells",], + "Topic :: System :: Shells"], packages=find_packages(include=["matlab_kernel", "matlab_kernel.*"]), - install_requires=["metakernel>=0.13.1"], + requires=["metakernel (>0.18.0)", "jupyter_client (>=4.4.0)", + "pathlib", 'ipython (>=4.0.0)'], + install_requires=["metakernel>=0.18.0", "jupyter_client >=4.4.0", + "ipython>=4.0.0", + "pathlib;python_version<'3.4'", + "backports.tempfile;python_version<'3.0'"] ) From f9a4e360606b9070da343868646ebdc4d146b562 Mon Sep 17 00:00:00 2001 From: Steven Silvester Date: Sat, 4 Mar 2017 03:45:31 -0600 Subject: [PATCH 17/88] Fix pathlib support on python 3.4 --- matlab_kernel/kernel.py | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/matlab_kernel/kernel.py b/matlab_kernel/kernel.py index 1018543..060dc84 100644 --- a/matlab_kernel/kernel.py +++ b/matlab_kernel/kernel.py @@ -162,7 +162,9 @@ def do_is_complete(self, code): if self.parse_code(code)["magic"]: return {"status": "complete"} with TemporaryDirectory() as tmpdir: - Path(tmpdir, "test_complete.m").write_text(code) + path = Path(tmpdir, "test_complete.m") + with path.open(mode='w') as f: + f.write(code) self._matlab.eval( "try, pcode {} -inplace; catch, end".format(tmpdir), nargout=0) From f443fd9254072697bf4efdc21cb898300b554898 Mon Sep 17 00:00:00 2001 From: Steven Silvester Date: Sat, 4 Mar 2017 03:52:44 -0600 Subject: [PATCH 18/88] Add release notes --- RELEASE.md | 11 +++++++++++ 1 file changed, 11 insertions(+) create mode 100644 RELEASE.md diff --git a/RELEASE.md b/RELEASE.md new file mode 100644 index 0000000..c566556 --- /dev/null +++ b/RELEASE.md @@ -0,0 +1,11 @@ + +## Making a release + +Tag the release using `git tag`, then: + +``` +rm -rf dist +python setup.py sdist +python setup.py bdist_wheel --universal +twine upload dist/* +``` From 3fa48045f68df26cb169eb42dc9380b6b712a6cb Mon Sep 17 00:00:00 2001 From: Steven Silvester Date: Sat, 4 Mar 2017 03:54:38 -0600 Subject: [PATCH 19/88] Add tag push to release notes --- RELEASE.md | 1 + 1 file changed, 1 insertion(+) diff --git a/RELEASE.md b/RELEASE.md index c566556..1999ffd 100644 --- a/RELEASE.md +++ b/RELEASE.md @@ -4,6 +4,7 @@ Tag the release using `git tag`, then: ``` +git push origin --tags rm -rf dist python setup.py sdist python setup.py bdist_wheel --universal From 9912daccd3dcc1f4165c42f2ce9788a0d7623586 Mon Sep 17 00:00:00 2001 From: Steven Silvester Date: Tue, 7 Mar 2017 07:36:02 -0600 Subject: [PATCH 20/88] Fix import on python 2.7 --- matlab_kernel/kernel.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/matlab_kernel/kernel.py b/matlab_kernel/kernel.py index 060dc84..7b3768b 100644 --- a/matlab_kernel/kernel.py +++ b/matlab_kernel/kernel.py @@ -6,7 +6,7 @@ try: from tempfile import TemporaryDirectory except ImportError: - from backports import tempfile + from backports.tempfile import TemporaryDirectory from IPython.display import Image from metakernel import MetaKernel From 7772c6120cf9f0727300e7698f028d8b3b265d5b Mon Sep 17 00:00:00 2001 From: Steven Silvester Date: Fri, 10 Mar 2017 05:24:29 -0600 Subject: [PATCH 21/88] Fix for py27 --- matlab_kernel/kernel.py | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/matlab_kernel/kernel.py b/matlab_kernel/kernel.py index 7b3768b..06c69e7 100644 --- a/matlab_kernel/kernel.py +++ b/matlab_kernel/kernel.py @@ -1,5 +1,8 @@ from functools import partial -from io import StringIO +try: + from StringIO import StringIO +except ImportError: + from io import StringIO import os from pathlib import Path import sys From 4c826a5e8aec310511cabe609c0aba0459a4c399 Mon Sep 17 00:00:00 2001 From: Steven Silvester Date: Sat, 11 Mar 2017 05:48:10 -0600 Subject: [PATCH 22/88] More python2 suport --- matlab_kernel/kernel.py | 2 ++ 1 file changed, 2 insertions(+) diff --git a/matlab_kernel/kernel.py b/matlab_kernel/kernel.py index 06c69e7..13b0839 100644 --- a/matlab_kernel/kernel.py +++ b/matlab_kernel/kernel.py @@ -248,6 +248,8 @@ def _execute_async(self, code): def _execute_sync(self, code): out = StringIO() err = StringIO() + if not isinstance(code, str): + code = code.encode('utf8') try: self._matlab.eval(code, nargout=0, stdout=out, stderr=err) except (SyntaxError, MatlabExecutionError) as exc: From e57b1b070041dae5f45758716886435688e2ea8a Mon Sep 17 00:00:00 2001 From: Steven Silvester Date: Sat, 11 Mar 2017 06:28:39 -0600 Subject: [PATCH 23/88] Switch from versioneer and add a makefile --- matlab_kernel/__init__.py | 4 +- matlab_kernel/_version.py | 498 ----------- matlab_kernel/kernel.py | 11 +- setup.py | 12 +- versioneer.py | 1733 ------------------------------------- 5 files changed, 16 insertions(+), 2242 deletions(-) delete mode 100644 matlab_kernel/_version.py delete mode 100644 versioneer.py diff --git a/matlab_kernel/__init__.py b/matlab_kernel/__init__.py index 2b87814..a549eca 100644 --- a/matlab_kernel/__init__.py +++ b/matlab_kernel/__init__.py @@ -1,5 +1,3 @@ """A Matlab kernel for Jupyter""" -from ._version import get_versions -__version__ = get_versions()['version'] -del get_versions +__version__ = '0.13.4' diff --git a/matlab_kernel/_version.py b/matlab_kernel/_version.py deleted file mode 100644 index 1d31762..0000000 --- a/matlab_kernel/_version.py +++ /dev/null @@ -1,498 +0,0 @@ - -# This file helps to compute a version number in source trees obtained from -# git-archive tarball (such as those provided by githubs download-from-tag -# feature). Distribution tarballs (built by setup.py sdist) and build -# directories (produced by setup.py build) will contain a much shorter file -# that just contains the computed version number. - -# This file is released into the public domain. Generated by -# versioneer-0.16+dev (https://github.com/warner/python-versioneer) - -"""Git implementation of _version.py.""" - -import errno -import os -import re -import subprocess -import sys - - -def get_keywords(): - """Get the keywords needed to look up the version information.""" - # these strings will be replaced by git during git-archive. - # setup.py/versioneer.py will grep for the variable names, so they must - # each be defined on a line of their own. _version.py will just call - # get_keywords(). - git_refnames = "$Format:%d$" - git_full = "$Format:%H$" - keywords = {"refnames": git_refnames, "full": git_full} - return keywords - - -class VersioneerConfig: - """Container for Versioneer configuration parameters.""" - - -def get_config(): - """Create, populate and return the VersioneerConfig() object.""" - # these strings are filled in when 'setup.py versioneer' creates - # _version.py - cfg = VersioneerConfig() - cfg.VCS = "git" - cfg.style = "pep440" - cfg.tag_prefix = "v" - cfg.parentdir_prefix = "matlab_kernel-" - cfg.versionfile_source = "matlab_kernel/_version.py" - cfg.verbose = False - return cfg - - -class NotThisMethod(Exception): - """Exception raised if a method is not valid for the current scenario.""" - - -LONG_VERSION_PY = {} -HANDLERS = {} - - -def register_vcs_handler(vcs, method): # decorator - """Decorator to mark a method as the handler for a particular VCS.""" - def decorate(f): - """Store f in HANDLERS[vcs][method].""" - if vcs not in HANDLERS: - HANDLERS[vcs] = {} - HANDLERS[vcs][method] = f - return f - return decorate - - -def run_command(commands, args, cwd=None, verbose=False, hide_stderr=False, - env=None): - """Call the given command(s).""" - assert isinstance(commands, list) - p = None - for c in commands: - try: - dispcmd = str([c] + args) - # remember shell=False, so use git.cmd on windows, not just git - p = subprocess.Popen([c] + args, cwd=cwd, env=env, - stdout=subprocess.PIPE, - stderr=(subprocess.PIPE if hide_stderr - else None)) - break - except EnvironmentError: - e = sys.exc_info()[1] - if e.errno == errno.ENOENT: - continue - if verbose: - print("unable to run %s" % dispcmd) - print(e) - return None, None - else: - if verbose: - print("unable to find command, tried %s" % (commands,)) - return None, None - stdout = p.communicate()[0].strip() - if sys.version_info[0] >= 3: - stdout = stdout.decode() - if p.returncode != 0: - if verbose: - print("unable to run %s (error)" % dispcmd) - print("stdout was %s" % stdout) - return None, p.returncode - return stdout, p.returncode - - -def versions_from_parentdir(parentdir_prefix, root, verbose): - """Try to determine the version from the parent directory name. - - Source tarballs conventionally unpack into a directory that includes both - the project name and a version string. We will also support searching up - two directory levels for an appropriately named parent directory - """ - rootdirs = [] - - for i in range(3): - dirname = os.path.basename(root) - if dirname.startswith(parentdir_prefix): - return {"version": dirname[len(parentdir_prefix):], - "full-revisionid": None, - "dirty": False, "error": None} - else: - rootdirs.append(root) - root = os.path.dirname(root) # up a level - - if verbose: - print("Tried directories %s but none started with prefix %s" % - (str(rootdirs), parentdir_prefix)) - raise NotThisMethod("rootdir doesn't start with parentdir_prefix") - - -@register_vcs_handler("git", "get_keywords") -def git_get_keywords(versionfile_abs): - """Extract version information from the given file.""" - # the code embedded in _version.py can just fetch the value of these - # keywords. When used from setup.py, we don't want to import _version.py, - # so we do it with a regexp instead. This function is not used from - # _version.py. - keywords = {} - try: - f = open(versionfile_abs, "r") - for line in f.readlines(): - if line.strip().startswith("git_refnames ="): - mo = re.search(r'=\s*"(.*)"', line) - if mo: - keywords["refnames"] = mo.group(1) - if line.strip().startswith("git_full ="): - mo = re.search(r'=\s*"(.*)"', line) - if mo: - keywords["full"] = mo.group(1) - f.close() - except EnvironmentError: - pass - return keywords - - -@register_vcs_handler("git", "keywords") -def git_versions_from_keywords(keywords, tag_prefix, verbose): - """Get version information from git keywords.""" - if not keywords: - raise NotThisMethod("no keywords at all, weird") - refnames = keywords["refnames"].strip() - if refnames.startswith("$Format"): - if verbose: - print("keywords are unexpanded, not using") - raise NotThisMethod("unexpanded keywords, not a git-archive tarball") - refs = set([r.strip() for r in refnames.strip("()").split(",")]) - # starting in git-1.8.3, tags are listed as "tag: foo-1.0" instead of - # just "foo-1.0". If we see a "tag: " prefix, prefer those. - TAG = "tag: " - tags = set([r[len(TAG):] for r in refs if r.startswith(TAG)]) - if not tags: - # Either we're using git < 1.8.3, or there really are no tags. We use - # a heuristic: assume all version tags have a digit. The old git %d - # expansion behaves like git log --decorate=short and strips out the - # refs/heads/ and refs/tags/ prefixes that would let us distinguish - # between branches and tags. By ignoring refnames without digits, we - # filter out many common branch names like "release" and - # "stabilization", as well as "HEAD" and "master". - tags = set([r for r in refs if re.search(r'\d', r)]) - if verbose: - print("discarding '%s', no digits" % ",".join(refs-tags)) - if verbose: - print("likely tags: %s" % ",".join(sorted(tags))) - for ref in sorted(tags): - # sorting will prefer e.g. "2.0" over "2.0rc1" - if ref.startswith(tag_prefix): - r = ref[len(tag_prefix):] - if verbose: - print("picking %s" % r) - return {"version": r, - "full-revisionid": keywords["full"].strip(), - "dirty": False, "error": None - } - # no suitable tags, so version is "0+unknown", but full hex is still there - if verbose: - print("no suitable tags, using unknown + full revision id") - return {"version": "0+unknown", - "full-revisionid": keywords["full"].strip(), - "dirty": False, "error": "no suitable tags"} - - -@register_vcs_handler("git", "pieces_from_vcs") -def git_pieces_from_vcs(tag_prefix, root, verbose, run_command=run_command): - """Get version from 'git describe' in the root of the source tree. - - This only gets called if the git-archive 'subst' keywords were *not* - expanded, and _version.py hasn't already been rewritten with a short - version string, meaning we're inside a checked out source tree. - """ - GITS = ["git"] - if sys.platform == "win32": - GITS = ["git.cmd", "git.exe"] - - out, rc = run_command(GITS, ["rev-parse", "--git-dir"], cwd=root, - hide_stderr=True) - if rc != 0: - if verbose: - print("Directory %s not under git control" % root) - raise NotThisMethod("'git rev-parse --git-dir' returned error") - - # if there is a tag matching tag_prefix, this yields TAG-NUM-gHEX[-dirty] - # if there isn't one, this yields HEX[-dirty] (no NUM) - describe_out, rc = run_command(GITS, ["describe", "--tags", "--dirty", - "--always", "--long", - "--match", "%s*" % tag_prefix], - cwd=root) - # --long was added in git-1.5.5 - if describe_out is None: - raise NotThisMethod("'git describe' failed") - describe_out = describe_out.strip() - full_out, rc = run_command(GITS, ["rev-parse", "HEAD"], cwd=root) - if full_out is None: - raise NotThisMethod("'git rev-parse' failed") - full_out = full_out.strip() - - pieces = {} - pieces["long"] = full_out - pieces["short"] = full_out[:7] # maybe improved later - pieces["error"] = None - - # parse describe_out. It will be like TAG-NUM-gHEX[-dirty] or HEX[-dirty] - # TAG might have hyphens. - git_describe = describe_out - - # look for -dirty suffix - dirty = git_describe.endswith("-dirty") - pieces["dirty"] = dirty - if dirty: - git_describe = git_describe[:git_describe.rindex("-dirty")] - - # now we have TAG-NUM-gHEX or HEX - - if "-" in git_describe: - # TAG-NUM-gHEX - mo = re.search(r'^(.+)-(\d+)-g([0-9a-f]+)$', git_describe) - if not mo: - # unparseable. Maybe git-describe is misbehaving? - pieces["error"] = ("unable to parse git-describe output: '%s'" - % describe_out) - return pieces - - # tag - full_tag = mo.group(1) - if not full_tag.startswith(tag_prefix): - if verbose: - fmt = "tag '%s' doesn't start with prefix '%s'" - print(fmt % (full_tag, tag_prefix)) - pieces["error"] = ("tag '%s' doesn't start with prefix '%s'" - % (full_tag, tag_prefix)) - return pieces - pieces["closest-tag"] = full_tag[len(tag_prefix):] - - # distance: number of commits since tag - pieces["distance"] = int(mo.group(2)) - - # commit: short hex revision ID - pieces["short"] = mo.group(3) - - else: - # HEX: no tags - pieces["closest-tag"] = None - count_out, rc = run_command(GITS, ["rev-list", "HEAD", "--count"], - cwd=root) - pieces["distance"] = int(count_out) # total number of commits - - return pieces - - -def plus_or_dot(pieces): - """Return a + if we don't already have one, else return a .""" - if "+" in pieces.get("closest-tag", ""): - return "." - return "+" - - -def render_pep440(pieces): - """Build up version string, with post-release "local version identifier". - - Our goal: TAG[+DISTANCE.gHEX[.dirty]] . Note that if you - get a tagged build and then dirty it, you'll get TAG+0.gHEX.dirty - - Exceptions: - 1: no tags. git_describe was just HEX. 0+untagged.DISTANCE.gHEX[.dirty] - """ - if pieces["closest-tag"]: - rendered = pieces["closest-tag"] - if pieces["distance"] or pieces["dirty"]: - rendered += plus_or_dot(pieces) - rendered += "%d.g%s" % (pieces["distance"], pieces["short"]) - if pieces["dirty"]: - rendered += ".dirty" - else: - # exception #1 - rendered = "0+untagged.%d.g%s" % (pieces["distance"], - pieces["short"]) - if pieces["dirty"]: - rendered += ".dirty" - return rendered - - -def render_pep440_pre(pieces): - """TAG[.post.devDISTANCE] -- No -dirty. - - Exceptions: - 1: no tags. 0.post.devDISTANCE - """ - if pieces["closest-tag"]: - rendered = pieces["closest-tag"] - if pieces["distance"]: - rendered += ".post.dev%d" % pieces["distance"] - else: - # exception #1 - rendered = "0.post.dev%d" % pieces["distance"] - return rendered - - -def render_pep440_post(pieces): - """TAG[.postDISTANCE[.dev0]+gHEX] . - - The ".dev0" means dirty. Note that .dev0 sorts backwards - (a dirty tree will appear "older" than the corresponding clean one), - but you shouldn't be releasing software with -dirty anyways. - - Exceptions: - 1: no tags. 0.postDISTANCE[.dev0] - """ - if pieces["closest-tag"]: - rendered = pieces["closest-tag"] - if pieces["distance"] or pieces["dirty"]: - rendered += ".post%d" % pieces["distance"] - if pieces["dirty"]: - rendered += ".dev0" - rendered += plus_or_dot(pieces) - rendered += "g%s" % pieces["short"] - else: - # exception #1 - rendered = "0.post%d" % pieces["distance"] - if pieces["dirty"]: - rendered += ".dev0" - rendered += "+g%s" % pieces["short"] - return rendered - - -def render_pep440_old(pieces): - """TAG[.postDISTANCE[.dev0]] . - - The ".dev0" means dirty. - - Eexceptions: - 1: no tags. 0.postDISTANCE[.dev0] - """ - if pieces["closest-tag"]: - rendered = pieces["closest-tag"] - if pieces["distance"] or pieces["dirty"]: - rendered += ".post%d" % pieces["distance"] - if pieces["dirty"]: - rendered += ".dev0" - else: - # exception #1 - rendered = "0.post%d" % pieces["distance"] - if pieces["dirty"]: - rendered += ".dev0" - return rendered - - -def render_git_describe(pieces): - """TAG[-DISTANCE-gHEX][-dirty]. - - Like 'git describe --tags --dirty --always'. - - Exceptions: - 1: no tags. HEX[-dirty] (note: no 'g' prefix) - """ - if pieces["closest-tag"]: - rendered = pieces["closest-tag"] - if pieces["distance"]: - rendered += "-%d-g%s" % (pieces["distance"], pieces["short"]) - else: - # exception #1 - rendered = pieces["short"] - if pieces["dirty"]: - rendered += "-dirty" - return rendered - - -def render_git_describe_long(pieces): - """TAG-DISTANCE-gHEX[-dirty]. - - Like 'git describe --tags --dirty --always -long'. - The distance/hash is unconditional. - - Exceptions: - 1: no tags. HEX[-dirty] (note: no 'g' prefix) - """ - if pieces["closest-tag"]: - rendered = pieces["closest-tag"] - rendered += "-%d-g%s" % (pieces["distance"], pieces["short"]) - else: - # exception #1 - rendered = pieces["short"] - if pieces["dirty"]: - rendered += "-dirty" - return rendered - - -def render(pieces, style): - """Render the given version pieces into the requested style.""" - if pieces["error"]: - return {"version": "unknown", - "full-revisionid": pieces.get("long"), - "dirty": None, - "error": pieces["error"]} - - if not style or style == "default": - style = "pep440" # the default - - if style == "pep440": - rendered = render_pep440(pieces) - elif style == "pep440-pre": - rendered = render_pep440_pre(pieces) - elif style == "pep440-post": - rendered = render_pep440_post(pieces) - elif style == "pep440-old": - rendered = render_pep440_old(pieces) - elif style == "git-describe": - rendered = render_git_describe(pieces) - elif style == "git-describe-long": - rendered = render_git_describe_long(pieces) - else: - raise ValueError("unknown style '%s'" % style) - - return {"version": rendered, "full-revisionid": pieces["long"], - "dirty": pieces["dirty"], "error": None} - - -def get_versions(): - """Get version information or return default if unable to do so.""" - # I am in _version.py, which lives at ROOT/VERSIONFILE_SOURCE. If we have - # __file__, we can work backwards from there to the root. Some - # py2exe/bbfreeze/non-CPython implementations don't do __file__, in which - # case we can only use expanded keywords. - - cfg = get_config() - verbose = cfg.verbose - - try: - return git_versions_from_keywords(get_keywords(), cfg.tag_prefix, - verbose) - except NotThisMethod: - pass - - try: - root = os.path.realpath(__file__) - # versionfile_source is the relative path from the top of the source - # tree (where the .git directory might live) to this file. Invert - # this to find the root from __file__. - for i in cfg.versionfile_source.split('/'): - root = os.path.dirname(root) - except NameError: - return {"version": "0+unknown", "full-revisionid": None, - "dirty": None, - "error": "unable to find root of source tree"} - - try: - pieces = git_pieces_from_vcs(cfg.tag_prefix, root, verbose) - return render(pieces, cfg.style) - except NotThisMethod: - pass - - try: - if cfg.parentdir_prefix: - return versions_from_parentdir(cfg.parentdir_prefix, root, verbose) - except NotThisMethod: - pass - - return {"version": "0+unknown", "full-revisionid": None, - "dirty": None, - "error": "unable to compute version"} diff --git a/matlab_kernel/kernel.py b/matlab_kernel/kernel.py index 13b0839..b51f394 100644 --- a/matlab_kernel/kernel.py +++ b/matlab_kernel/kernel.py @@ -25,13 +25,11 @@ import matlab.engine from matlab.engine import MatlabExecutionError except ImportError: - raise ImportError(""" -Matlab engine not installed: -See https://www.mathworks.com/help/matlab/matlab-engine-for-python.htm -""") + matlab = None class _PseudoStream: + def __init__(self, writer): self.write = writer @@ -61,6 +59,11 @@ class MatlabKernel(MetaKernel): def __init__(self, *args, **kwargs): super(MatlabKernel, self).__init__(*args, **kwargs) + if matlab is None: + raise ImportError(""" + Matlab engine not installed: + See https://www.mathworks.com/help/matlab/matlab-engine-for-python.htm + """) try: self._matlab = matlab.engine.start_matlab() except matlab.engine.EngineError: diff --git a/setup.py b/setup.py index 855a887..8f2fd80 100644 --- a/setup.py +++ b/setup.py @@ -1,13 +1,17 @@ - from setuptools import setup, find_packages -import versioneer + +with open('matlab_kernel/__init__.py', 'rb') as fid: + for line in fid: + line = line.decode('utf-8') + if line.startswith('__version__'): + version = line.strip().split()[-1][1:-1] + break if __name__ == "__main__": setup(name="matlab_kernel", author="Steven Silvester, Antony Lee", - version=versioneer.get_version(), - cmdclass=versioneer.get_cmdclass(), + version=version, url="https://github.com/Calysto/matlab_kernel", license="BSD", long_description=open("README.rst").read(), diff --git a/versioneer.py b/versioneer.py deleted file mode 100644 index 03b9a96..0000000 --- a/versioneer.py +++ /dev/null @@ -1,1733 +0,0 @@ - -# Version: 0.16+dev - -"""The Versioneer - like a rocketeer, but for versions. - -The Versioneer -============== - -* like a rocketeer, but for versions! -* https://github.com/warner/python-versioneer -* Brian Warner -* License: Public Domain -* Compatible With: python2.6, 2.7, 3.3, 3.4, 3.5, and pypy -* [![Latest Version] -(https://pypip.in/version/versioneer/badge.svg?style=flat) -](https://pypi.python.org/pypi/versioneer/) -* [![Build Status] -(https://travis-ci.org/warner/python-versioneer.png?branch=master) -](https://travis-ci.org/warner/python-versioneer) - -This is a tool for managing a recorded version number in distutils-based -python projects. The goal is to remove the tedious and error-prone "update -the embedded version string" step from your release process. Making a new -release should be as easy as recording a new tag in your version-control -system, and maybe making new tarballs. - - -## Quick Install - -* `pip install versioneer` to somewhere to your $PATH -* add a `[versioneer]` section to your setup.cfg (see below) -* run `versioneer install` in your source tree, commit the results - -## Version Identifiers - -Source trees come from a variety of places: - -* a version-control system checkout (mostly used by developers) -* a nightly tarball, produced by build automation -* a snapshot tarball, produced by a web-based VCS browser, like github's - "tarball from tag" feature -* a release tarball, produced by "setup.py sdist", distributed through PyPI - -Within each source tree, the version identifier (either a string or a number, -this tool is format-agnostic) can come from a variety of places: - -* ask the VCS tool itself, e.g. "git describe" (for checkouts), which knows - about recent "tags" and an absolute revision-id -* the name of the directory into which the tarball was unpacked -* an expanded VCS keyword ($Id$, etc) -* a `_version.py` created by some earlier build step - -For released software, the version identifier is closely related to a VCS -tag. Some projects use tag names that include more than just the version -string (e.g. "myproject-1.2" instead of just "1.2"), in which case the tool -needs to strip the tag prefix to extract the version identifier. For -unreleased software (between tags), the version identifier should provide -enough information to help developers recreate the same tree, while also -giving them an idea of roughly how old the tree is (after version 1.2, before -version 1.3). Many VCS systems can report a description that captures this, -for example `git describe --tags --dirty --always` reports things like -"0.7-1-g574ab98-dirty" to indicate that the checkout is one revision past the -0.7 tag, has a unique revision id of "574ab98", and is "dirty" (it has -uncommitted changes. - -The version identifier is used for multiple purposes: - -* to allow the module to self-identify its version: `myproject.__version__` -* to choose a name and prefix for a 'setup.py sdist' tarball - -## Theory of Operation - -Versioneer works by adding a special `_version.py` file into your source -tree, where your `__init__.py` can import it. This `_version.py` knows how to -dynamically ask the VCS tool for version information at import time. - -`_version.py` also contains `$Revision$` markers, and the installation -process marks `_version.py` to have this marker rewritten with a tag name -during the `git archive` command. As a result, generated tarballs will -contain enough information to get the proper version. - -To allow `setup.py` to compute a version too, a `versioneer.py` is added to -the top level of your source tree, next to `setup.py` and the `setup.cfg` -that configures it. This overrides several distutils/setuptools commands to -compute the version when invoked, and changes `setup.py build` and `setup.py -sdist` to replace `_version.py` with a small static file that contains just -the generated version data. - -## Installation - -See [INSTALL.md](./INSTALL.md) for detailed installation instructions. - -## Version-String Flavors - -Code which uses Versioneer can learn about its version string at runtime by -importing `_version` from your main `__init__.py` file and running the -`get_versions()` function. From the "outside" (e.g. in `setup.py`), you can -import the top-level `versioneer.py` and run `get_versions()`. - -Both functions return a dictionary with different flavors of version -information: - -* `['version']`: A condensed version string, rendered using the selected - style. This is the most commonly used value for the project's version - string. The default "pep440" style yields strings like `0.11`, - `0.11+2.g1076c97`, or `0.11+2.g1076c97.dirty`. See the "Styles" section - below for alternative styles. - -* `['full-revisionid']`: detailed revision identifier. For Git, this is the - full SHA1 commit id, e.g. "1076c978a8d3cfc70f408fe5974aa6c092c949ac". - -* `['dirty']`: a boolean, True if the tree has uncommitted changes. Note that - this is only accurate if run in a VCS checkout, otherwise it is likely to - be False or None - -* `['error']`: if the version string could not be computed, this will be set - to a string describing the problem, otherwise it will be None. It may be - useful to throw an exception in setup.py if this is set, to avoid e.g. - creating tarballs with a version string of "unknown". - -Some variants are more useful than others. Including `full-revisionid` in a -bug report should allow developers to reconstruct the exact code being tested -(or indicate the presence of local changes that should be shared with the -developers). `version` is suitable for display in an "about" box or a CLI -`--version` output: it can be easily compared against release notes and lists -of bugs fixed in various releases. - -The installer adds the following text to your `__init__.py` to place a basic -version in `YOURPROJECT.__version__`: - - from ._version import get_versions - __version__ = get_versions()['version'] - del get_versions - -## Styles - -The setup.cfg `style=` configuration controls how the VCS information is -rendered into a version string. - -The default style, "pep440", produces a PEP440-compliant string, equal to the -un-prefixed tag name for actual releases, and containing an additional "local -version" section with more detail for in-between builds. For Git, this is -TAG[+DISTANCE.gHEX[.dirty]] , using information from `git describe --tags ---dirty --always`. For example "0.11+2.g1076c97.dirty" indicates that the -tree is like the "1076c97" commit but has uncommitted changes (".dirty"), and -that this commit is two revisions ("+2") beyond the "0.11" tag. For released -software (exactly equal to a known tag), the identifier will only contain the -stripped tag, e.g. "0.11". - -Other styles are available. See details.md in the Versioneer source tree for -descriptions. - -## Debugging - -Versioneer tries to avoid fatal errors: if something goes wrong, it will tend -to return a version of "0+unknown". To investigate the problem, run `setup.py -version`, which will run the version-lookup code in a verbose mode, and will -display the full contents of `get_versions()` (including the `error` string, -which may help identify what went wrong). - -## Known Limitations - -Some situations are known to cause problems for Versioneer. This details the -most significant ones. More can be found on Github -[issues page](https://github.com/warner/python-versioneer/issues). - -### Subprojects - -Versioneer has limited support for source trees in which `setup.py` is not in -the root directory (e.g. `setup.py` and `.git/` are *not* siblings). The are -two common reasons why `setup.py` might not be in the root: - -* Source trees which contain multiple subprojects, such as - [Buildbot](https://github.com/buildbot/buildbot), which contains both - "master" and "slave" subprojects, each with their own `setup.py`, - `setup.cfg`, and `tox.ini`. Projects like these produce multiple PyPI - distributions (and upload multiple independently-installable tarballs). -* Source trees whose main purpose is to contain a C library, but which also - provide bindings to Python (and perhaps other langauges) in subdirectories. - -Versioneer will look for `.git` in parent directories, and most operations -should get the right version string. However `pip` and `setuptools` have bugs -and implementation details which frequently cause `pip install .` from a -subproject directory to fail to find a correct version string (so it usually -defaults to `0+unknown`). - -`pip install --editable .` should work correctly. `setup.py install` might -work too. - -Pip-8.1.1 is known to have this problem, but hopefully it will get fixed in -some later version. - -[Bug #38](https://github.com/warner/python-versioneer/issues/38) is tracking -this issue. The discussion in -[PR #61](https://github.com/warner/python-versioneer/pull/61) describes the -issue from the Versioneer side in more detail. -[pip PR#3176](https://github.com/pypa/pip/pull/3176) and -[pip PR#3615](https://github.com/pypa/pip/pull/3615) contain work to improve -pip to let Versioneer work correctly. - -Versioneer-0.16 and earlier only looked for a `.git` directory next to the -`setup.cfg`, so subprojects were completely unsupported with those releases. - -### Editable installs with setuptools <= 18.5 - -`setup.py develop` and `pip install --editable .` allow you to install a -project into a virtualenv once, then continue editing the source code (and -test) without re-installing after every change. - -"Entry-point scripts" (`setup(entry_points={"console_scripts": ..})`) are a -convenient way to specify executable scripts that should be installed along -with the python package. - -These both work as expected when using modern setuptools. When using -setuptools-18.5 or earlier, however, certain operations will cause -`pkg_resources.DistributionNotFound` errors when running the entrypoint -script, which must be resolved by re-installing the package. This happens -when the install happens with one version, then the egg_info data is -regenerated while a different version is checked out. Many setup.py commands -cause egg_info to be rebuilt (including `sdist`, `wheel`, and installing into -a different virtualenv), so this can be surprising. - -[Bug #83](https://github.com/warner/python-versioneer/issues/83) describes -this one, but upgrading to a newer version of setuptools should probably -resolve it. - -### Unicode version strings - -While Versioneer works (and is continually tested) with both Python 2 and -Python 3, it is not entirely consistent with bytes-vs-unicode distinctions. -Newer releases probably generate unicode version strings on py2. It's not -clear that this is wrong, but it may be surprising for applications when then -write these strings to a network connection or include them in bytes-oriented -APIs like cryptographic checksums. - -[Bug #71](https://github.com/warner/python-versioneer/issues/71) investigates -this question. - - -## Updating Versioneer - -To upgrade your project to a new release of Versioneer, do the following: - -* install the new Versioneer (`pip install -U versioneer` or equivalent) -* edit `setup.cfg`, if necessary, to include any new configuration settings - indicated by the release notes. See [UPGRADING](./UPGRADING.md) for details. -* re-run `versioneer install` in your source tree, to replace - `SRC/_version.py` -* commit any changed files - -## Future Directions - -This tool is designed to make it easily extended to other version-control -systems: all VCS-specific components are in separate directories like -src/git/ . The top-level `versioneer.py` script is assembled from these -components by running make-versioneer.py . In the future, make-versioneer.py -will take a VCS name as an argument, and will construct a version of -`versioneer.py` that is specific to the given VCS. It might also take the -configuration arguments that are currently provided manually during -installation by editing setup.py . Alternatively, it might go the other -direction and include code from all supported VCS systems, reducing the -number of intermediate scripts. - - -## License - -To make Versioneer easier to embed, all its code is dedicated to the public -domain. The `_version.py` that it creates is also in the public domain. -Specifically, both are released under the Creative Commons "Public Domain -Dedication" license (CC0-1.0), as described in -https://creativecommons.org/publicdomain/zero/1.0/ . - -""" - -from __future__ import print_function -try: - import configparser -except ImportError: - import ConfigParser as configparser -import errno -import json -import os -import re -import subprocess -import sys - - -class VersioneerConfig: - """Container for Versioneer configuration parameters.""" - - -def get_root(): - """Get the project root directory. - - We require that all commands are run from the project root, i.e. the - directory that contains setup.py, setup.cfg, and versioneer.py . - """ - root = os.path.realpath(os.path.abspath(os.getcwd())) - setup_py = os.path.join(root, "setup.py") - versioneer_py = os.path.join(root, "versioneer.py") - if not (os.path.exists(setup_py) or os.path.exists(versioneer_py)): - # allow 'python path/to/setup.py COMMAND' - root = os.path.dirname(os.path.realpath(os.path.abspath(sys.argv[0]))) - setup_py = os.path.join(root, "setup.py") - versioneer_py = os.path.join(root, "versioneer.py") - if not (os.path.exists(setup_py) or os.path.exists(versioneer_py)): - err = ("Versioneer was unable to run the project root directory. " - "Versioneer requires setup.py to be executed from " - "its immediate directory (like 'python setup.py COMMAND'), " - "or in a way that lets it use sys.argv[0] to find the root " - "(like 'python path/to/setup.py COMMAND').") - raise VersioneerBadRootError(err) - try: - # Certain runtime workflows (setup.py install/develop in a setuptools - # tree) execute all dependencies in a single python process, so - # "versioneer" may be imported multiple times, and python's shared - # module-import table will cache the first one. So we can't use - # os.path.dirname(__file__), as that will find whichever - # versioneer.py was first imported, even in later projects. - me = os.path.realpath(os.path.abspath(__file__)) - me_dir = os.path.normcase(os.path.splitext(me)[0]) - vsr_dir = os.path.normcase(os.path.splitext(versioneer_py)[0]) - if me_dir != vsr_dir: - print("Warning: build in %s is using versioneer.py from %s" - % (os.path.dirname(me), versioneer_py)) - except NameError: - pass - return root - - -def get_config_from_root(root): - """Read the project setup.cfg file to determine Versioneer config.""" - # This might raise EnvironmentError (if setup.cfg is missing), or - # configparser.NoSectionError (if it lacks a [versioneer] section), or - # configparser.NoOptionError (if it lacks "VCS="). See the docstring at - # the top of versioneer.py for instructions on writing your setup.cfg . - setup_cfg = os.path.join(root, "setup.cfg") - parser = configparser.SafeConfigParser() - with open(setup_cfg, "r") as f: - parser.readfp(f) - VCS = parser.get("versioneer", "VCS") # mandatory - - def get(parser, name): - if parser.has_option("versioneer", name): - return parser.get("versioneer", name) - return None - cfg = VersioneerConfig() - cfg.VCS = VCS - cfg.style = get(parser, "style") or "" - cfg.versionfile_source = get(parser, "versionfile_source") - cfg.versionfile_build = get(parser, "versionfile_build") - cfg.tag_prefix = get(parser, "tag_prefix") - if cfg.tag_prefix in ("''", '""'): - cfg.tag_prefix = "" - cfg.parentdir_prefix = get(parser, "parentdir_prefix") - cfg.verbose = get(parser, "verbose") - return cfg - - -class NotThisMethod(Exception): - """Exception raised if a method is not valid for the current scenario.""" - -# these dictionaries contain VCS-specific tools -LONG_VERSION_PY = {} -HANDLERS = {} - - -def register_vcs_handler(vcs, method): # decorator - """Decorator to mark a method as the handler for a particular VCS.""" - def decorate(f): - """Store f in HANDLERS[vcs][method].""" - if vcs not in HANDLERS: - HANDLERS[vcs] = {} - HANDLERS[vcs][method] = f - return f - return decorate - - -def run_command(commands, args, cwd=None, verbose=False, hide_stderr=False, - env=None): - """Call the given command(s).""" - assert isinstance(commands, list) - p = None - for c in commands: - try: - dispcmd = str([c] + args) - # remember shell=False, so use git.cmd on windows, not just git - p = subprocess.Popen([c] + args, cwd=cwd, env=env, - stdout=subprocess.PIPE, - stderr=(subprocess.PIPE if hide_stderr - else None)) - break - except EnvironmentError: - e = sys.exc_info()[1] - if e.errno == errno.ENOENT: - continue - if verbose: - print("unable to run %s" % dispcmd) - print(e) - return None, None - else: - if verbose: - print("unable to find command, tried %s" % (commands,)) - return None, None - stdout = p.communicate()[0].strip() - if sys.version_info[0] >= 3: - stdout = stdout.decode() - if p.returncode != 0: - if verbose: - print("unable to run %s (error)" % dispcmd) - print("stdout was %s" % stdout) - return None, p.returncode - return stdout, p.returncode -LONG_VERSION_PY['git'] = ''' -# This file helps to compute a version number in source trees obtained from -# git-archive tarball (such as those provided by githubs download-from-tag -# feature). Distribution tarballs (built by setup.py sdist) and build -# directories (produced by setup.py build) will contain a much shorter file -# that just contains the computed version number. - -# This file is released into the public domain. Generated by -# versioneer-0.16+dev (https://github.com/warner/python-versioneer) - -"""Git implementation of _version.py.""" - -import errno -import os -import re -import subprocess -import sys - - -def get_keywords(): - """Get the keywords needed to look up the version information.""" - # these strings will be replaced by git during git-archive. - # setup.py/versioneer.py will grep for the variable names, so they must - # each be defined on a line of their own. _version.py will just call - # get_keywords(). - git_refnames = "%(DOLLAR)sFormat:%%d%(DOLLAR)s" - git_full = "%(DOLLAR)sFormat:%%H%(DOLLAR)s" - keywords = {"refnames": git_refnames, "full": git_full} - return keywords - - -class VersioneerConfig: - """Container for Versioneer configuration parameters.""" - - -def get_config(): - """Create, populate and return the VersioneerConfig() object.""" - # these strings are filled in when 'setup.py versioneer' creates - # _version.py - cfg = VersioneerConfig() - cfg.VCS = "git" - cfg.style = "%(STYLE)s" - cfg.tag_prefix = "%(TAG_PREFIX)s" - cfg.parentdir_prefix = "%(PARENTDIR_PREFIX)s" - cfg.versionfile_source = "%(VERSIONFILE_SOURCE)s" - cfg.verbose = False - return cfg - - -class NotThisMethod(Exception): - """Exception raised if a method is not valid for the current scenario.""" - - -LONG_VERSION_PY = {} -HANDLERS = {} - - -def register_vcs_handler(vcs, method): # decorator - """Decorator to mark a method as the handler for a particular VCS.""" - def decorate(f): - """Store f in HANDLERS[vcs][method].""" - if vcs not in HANDLERS: - HANDLERS[vcs] = {} - HANDLERS[vcs][method] = f - return f - return decorate - - -def run_command(commands, args, cwd=None, verbose=False, hide_stderr=False, - env=None): - """Call the given command(s).""" - assert isinstance(commands, list) - p = None - for c in commands: - try: - dispcmd = str([c] + args) - # remember shell=False, so use git.cmd on windows, not just git - p = subprocess.Popen([c] + args, cwd=cwd, env=env, - stdout=subprocess.PIPE, - stderr=(subprocess.PIPE if hide_stderr - else None)) - break - except EnvironmentError: - e = sys.exc_info()[1] - if e.errno == errno.ENOENT: - continue - if verbose: - print("unable to run %%s" %% dispcmd) - print(e) - return None, None - else: - if verbose: - print("unable to find command, tried %%s" %% (commands,)) - return None, None - stdout = p.communicate()[0].strip() - if sys.version_info[0] >= 3: - stdout = stdout.decode() - if p.returncode != 0: - if verbose: - print("unable to run %%s (error)" %% dispcmd) - print("stdout was %%s" %% stdout) - return None, p.returncode - return stdout, p.returncode - - -def versions_from_parentdir(parentdir_prefix, root, verbose): - """Try to determine the version from the parent directory name. - - Source tarballs conventionally unpack into a directory that includes both - the project name and a version string. We will also support searching up - two directory levels for an appropriately named parent directory - """ - rootdirs = [] - - for i in range(3): - dirname = os.path.basename(root) - if dirname.startswith(parentdir_prefix): - return {"version": dirname[len(parentdir_prefix):], - "full-revisionid": None, - "dirty": False, "error": None} - else: - rootdirs.append(root) - root = os.path.dirname(root) # up a level - - if verbose: - print("Tried directories %%s but none started with prefix %%s" %% - (str(rootdirs), parentdir_prefix)) - raise NotThisMethod("rootdir doesn't start with parentdir_prefix") - - -@register_vcs_handler("git", "get_keywords") -def git_get_keywords(versionfile_abs): - """Extract version information from the given file.""" - # the code embedded in _version.py can just fetch the value of these - # keywords. When used from setup.py, we don't want to import _version.py, - # so we do it with a regexp instead. This function is not used from - # _version.py. - keywords = {} - try: - f = open(versionfile_abs, "r") - for line in f.readlines(): - if line.strip().startswith("git_refnames ="): - mo = re.search(r'=\s*"(.*)"', line) - if mo: - keywords["refnames"] = mo.group(1) - if line.strip().startswith("git_full ="): - mo = re.search(r'=\s*"(.*)"', line) - if mo: - keywords["full"] = mo.group(1) - f.close() - except EnvironmentError: - pass - return keywords - - -@register_vcs_handler("git", "keywords") -def git_versions_from_keywords(keywords, tag_prefix, verbose): - """Get version information from git keywords.""" - if not keywords: - raise NotThisMethod("no keywords at all, weird") - refnames = keywords["refnames"].strip() - if refnames.startswith("$Format"): - if verbose: - print("keywords are unexpanded, not using") - raise NotThisMethod("unexpanded keywords, not a git-archive tarball") - refs = set([r.strip() for r in refnames.strip("()").split(",")]) - # starting in git-1.8.3, tags are listed as "tag: foo-1.0" instead of - # just "foo-1.0". If we see a "tag: " prefix, prefer those. - TAG = "tag: " - tags = set([r[len(TAG):] for r in refs if r.startswith(TAG)]) - if not tags: - # Either we're using git < 1.8.3, or there really are no tags. We use - # a heuristic: assume all version tags have a digit. The old git %%d - # expansion behaves like git log --decorate=short and strips out the - # refs/heads/ and refs/tags/ prefixes that would let us distinguish - # between branches and tags. By ignoring refnames without digits, we - # filter out many common branch names like "release" and - # "stabilization", as well as "HEAD" and "master". - tags = set([r for r in refs if re.search(r'\d', r)]) - if verbose: - print("discarding '%%s', no digits" %% ",".join(refs-tags)) - if verbose: - print("likely tags: %%s" %% ",".join(sorted(tags))) - for ref in sorted(tags): - # sorting will prefer e.g. "2.0" over "2.0rc1" - if ref.startswith(tag_prefix): - r = ref[len(tag_prefix):] - if verbose: - print("picking %%s" %% r) - return {"version": r, - "full-revisionid": keywords["full"].strip(), - "dirty": False, "error": None - } - # no suitable tags, so version is "0+unknown", but full hex is still there - if verbose: - print("no suitable tags, using unknown + full revision id") - return {"version": "0+unknown", - "full-revisionid": keywords["full"].strip(), - "dirty": False, "error": "no suitable tags"} - - -@register_vcs_handler("git", "pieces_from_vcs") -def git_pieces_from_vcs(tag_prefix, root, verbose, run_command=run_command): - """Get version from 'git describe' in the root of the source tree. - - This only gets called if the git-archive 'subst' keywords were *not* - expanded, and _version.py hasn't already been rewritten with a short - version string, meaning we're inside a checked out source tree. - """ - GITS = ["git"] - if sys.platform == "win32": - GITS = ["git.cmd", "git.exe"] - - out, rc = run_command(GITS, ["rev-parse", "--git-dir"], cwd=root, - hide_stderr=True) - if rc != 0: - if verbose: - print("Directory %%s not under git control" %% root) - raise NotThisMethod("'git rev-parse --git-dir' returned error") - - # if there is a tag matching tag_prefix, this yields TAG-NUM-gHEX[-dirty] - # if there isn't one, this yields HEX[-dirty] (no NUM) - describe_out, rc = run_command(GITS, ["describe", "--tags", "--dirty", - "--always", "--long", - "--match", "%%s*" %% tag_prefix], - cwd=root) - # --long was added in git-1.5.5 - if describe_out is None: - raise NotThisMethod("'git describe' failed") - describe_out = describe_out.strip() - full_out, rc = run_command(GITS, ["rev-parse", "HEAD"], cwd=root) - if full_out is None: - raise NotThisMethod("'git rev-parse' failed") - full_out = full_out.strip() - - pieces = {} - pieces["long"] = full_out - pieces["short"] = full_out[:7] # maybe improved later - pieces["error"] = None - - # parse describe_out. It will be like TAG-NUM-gHEX[-dirty] or HEX[-dirty] - # TAG might have hyphens. - git_describe = describe_out - - # look for -dirty suffix - dirty = git_describe.endswith("-dirty") - pieces["dirty"] = dirty - if dirty: - git_describe = git_describe[:git_describe.rindex("-dirty")] - - # now we have TAG-NUM-gHEX or HEX - - if "-" in git_describe: - # TAG-NUM-gHEX - mo = re.search(r'^(.+)-(\d+)-g([0-9a-f]+)$', git_describe) - if not mo: - # unparseable. Maybe git-describe is misbehaving? - pieces["error"] = ("unable to parse git-describe output: '%%s'" - %% describe_out) - return pieces - - # tag - full_tag = mo.group(1) - if not full_tag.startswith(tag_prefix): - if verbose: - fmt = "tag '%%s' doesn't start with prefix '%%s'" - print(fmt %% (full_tag, tag_prefix)) - pieces["error"] = ("tag '%%s' doesn't start with prefix '%%s'" - %% (full_tag, tag_prefix)) - return pieces - pieces["closest-tag"] = full_tag[len(tag_prefix):] - - # distance: number of commits since tag - pieces["distance"] = int(mo.group(2)) - - # commit: short hex revision ID - pieces["short"] = mo.group(3) - - else: - # HEX: no tags - pieces["closest-tag"] = None - count_out, rc = run_command(GITS, ["rev-list", "HEAD", "--count"], - cwd=root) - pieces["distance"] = int(count_out) # total number of commits - - return pieces - - -def plus_or_dot(pieces): - """Return a + if we don't already have one, else return a .""" - if "+" in pieces.get("closest-tag", ""): - return "." - return "+" - - -def render_pep440(pieces): - """Build up version string, with post-release "local version identifier". - - Our goal: TAG[+DISTANCE.gHEX[.dirty]] . Note that if you - get a tagged build and then dirty it, you'll get TAG+0.gHEX.dirty - - Exceptions: - 1: no tags. git_describe was just HEX. 0+untagged.DISTANCE.gHEX[.dirty] - """ - if pieces["closest-tag"]: - rendered = pieces["closest-tag"] - if pieces["distance"] or pieces["dirty"]: - rendered += plus_or_dot(pieces) - rendered += "%%d.g%%s" %% (pieces["distance"], pieces["short"]) - if pieces["dirty"]: - rendered += ".dirty" - else: - # exception #1 - rendered = "0+untagged.%%d.g%%s" %% (pieces["distance"], - pieces["short"]) - if pieces["dirty"]: - rendered += ".dirty" - return rendered - - -def render_pep440_pre(pieces): - """TAG[.post.devDISTANCE] -- No -dirty. - - Exceptions: - 1: no tags. 0.post.devDISTANCE - """ - if pieces["closest-tag"]: - rendered = pieces["closest-tag"] - if pieces["distance"]: - rendered += ".post.dev%%d" %% pieces["distance"] - else: - # exception #1 - rendered = "0.post.dev%%d" %% pieces["distance"] - return rendered - - -def render_pep440_post(pieces): - """TAG[.postDISTANCE[.dev0]+gHEX] . - - The ".dev0" means dirty. Note that .dev0 sorts backwards - (a dirty tree will appear "older" than the corresponding clean one), - but you shouldn't be releasing software with -dirty anyways. - - Exceptions: - 1: no tags. 0.postDISTANCE[.dev0] - """ - if pieces["closest-tag"]: - rendered = pieces["closest-tag"] - if pieces["distance"] or pieces["dirty"]: - rendered += ".post%%d" %% pieces["distance"] - if pieces["dirty"]: - rendered += ".dev0" - rendered += plus_or_dot(pieces) - rendered += "g%%s" %% pieces["short"] - else: - # exception #1 - rendered = "0.post%%d" %% pieces["distance"] - if pieces["dirty"]: - rendered += ".dev0" - rendered += "+g%%s" %% pieces["short"] - return rendered - - -def render_pep440_old(pieces): - """TAG[.postDISTANCE[.dev0]] . - - The ".dev0" means dirty. - - Eexceptions: - 1: no tags. 0.postDISTANCE[.dev0] - """ - if pieces["closest-tag"]: - rendered = pieces["closest-tag"] - if pieces["distance"] or pieces["dirty"]: - rendered += ".post%%d" %% pieces["distance"] - if pieces["dirty"]: - rendered += ".dev0" - else: - # exception #1 - rendered = "0.post%%d" %% pieces["distance"] - if pieces["dirty"]: - rendered += ".dev0" - return rendered - - -def render_git_describe(pieces): - """TAG[-DISTANCE-gHEX][-dirty]. - - Like 'git describe --tags --dirty --always'. - - Exceptions: - 1: no tags. HEX[-dirty] (note: no 'g' prefix) - """ - if pieces["closest-tag"]: - rendered = pieces["closest-tag"] - if pieces["distance"]: - rendered += "-%%d-g%%s" %% (pieces["distance"], pieces["short"]) - else: - # exception #1 - rendered = pieces["short"] - if pieces["dirty"]: - rendered += "-dirty" - return rendered - - -def render_git_describe_long(pieces): - """TAG-DISTANCE-gHEX[-dirty]. - - Like 'git describe --tags --dirty --always -long'. - The distance/hash is unconditional. - - Exceptions: - 1: no tags. HEX[-dirty] (note: no 'g' prefix) - """ - if pieces["closest-tag"]: - rendered = pieces["closest-tag"] - rendered += "-%%d-g%%s" %% (pieces["distance"], pieces["short"]) - else: - # exception #1 - rendered = pieces["short"] - if pieces["dirty"]: - rendered += "-dirty" - return rendered - - -def render(pieces, style): - """Render the given version pieces into the requested style.""" - if pieces["error"]: - return {"version": "unknown", - "full-revisionid": pieces.get("long"), - "dirty": None, - "error": pieces["error"]} - - if not style or style == "default": - style = "pep440" # the default - - if style == "pep440": - rendered = render_pep440(pieces) - elif style == "pep440-pre": - rendered = render_pep440_pre(pieces) - elif style == "pep440-post": - rendered = render_pep440_post(pieces) - elif style == "pep440-old": - rendered = render_pep440_old(pieces) - elif style == "git-describe": - rendered = render_git_describe(pieces) - elif style == "git-describe-long": - rendered = render_git_describe_long(pieces) - else: - raise ValueError("unknown style '%%s'" %% style) - - return {"version": rendered, "full-revisionid": pieces["long"], - "dirty": pieces["dirty"], "error": None} - - -def get_versions(): - """Get version information or return default if unable to do so.""" - # I am in _version.py, which lives at ROOT/VERSIONFILE_SOURCE. If we have - # __file__, we can work backwards from there to the root. Some - # py2exe/bbfreeze/non-CPython implementations don't do __file__, in which - # case we can only use expanded keywords. - - cfg = get_config() - verbose = cfg.verbose - - try: - return git_versions_from_keywords(get_keywords(), cfg.tag_prefix, - verbose) - except NotThisMethod: - pass - - try: - root = os.path.realpath(__file__) - # versionfile_source is the relative path from the top of the source - # tree (where the .git directory might live) to this file. Invert - # this to find the root from __file__. - for i in cfg.versionfile_source.split('/'): - root = os.path.dirname(root) - except NameError: - return {"version": "0+unknown", "full-revisionid": None, - "dirty": None, - "error": "unable to find root of source tree"} - - try: - pieces = git_pieces_from_vcs(cfg.tag_prefix, root, verbose) - return render(pieces, cfg.style) - except NotThisMethod: - pass - - try: - if cfg.parentdir_prefix: - return versions_from_parentdir(cfg.parentdir_prefix, root, verbose) - except NotThisMethod: - pass - - return {"version": "0+unknown", "full-revisionid": None, - "dirty": None, - "error": "unable to compute version"} -''' - - -@register_vcs_handler("git", "get_keywords") -def git_get_keywords(versionfile_abs): - """Extract version information from the given file.""" - # the code embedded in _version.py can just fetch the value of these - # keywords. When used from setup.py, we don't want to import _version.py, - # so we do it with a regexp instead. This function is not used from - # _version.py. - keywords = {} - try: - f = open(versionfile_abs, "r") - for line in f.readlines(): - if line.strip().startswith("git_refnames ="): - mo = re.search(r'=\s*"(.*)"', line) - if mo: - keywords["refnames"] = mo.group(1) - if line.strip().startswith("git_full ="): - mo = re.search(r'=\s*"(.*)"', line) - if mo: - keywords["full"] = mo.group(1) - f.close() - except EnvironmentError: - pass - return keywords - - -@register_vcs_handler("git", "keywords") -def git_versions_from_keywords(keywords, tag_prefix, verbose): - """Get version information from git keywords.""" - if not keywords: - raise NotThisMethod("no keywords at all, weird") - refnames = keywords["refnames"].strip() - if refnames.startswith("$Format"): - if verbose: - print("keywords are unexpanded, not using") - raise NotThisMethod("unexpanded keywords, not a git-archive tarball") - refs = set([r.strip() for r in refnames.strip("()").split(",")]) - # starting in git-1.8.3, tags are listed as "tag: foo-1.0" instead of - # just "foo-1.0". If we see a "tag: " prefix, prefer those. - TAG = "tag: " - tags = set([r[len(TAG):] for r in refs if r.startswith(TAG)]) - if not tags: - # Either we're using git < 1.8.3, or there really are no tags. We use - # a heuristic: assume all version tags have a digit. The old git %d - # expansion behaves like git log --decorate=short and strips out the - # refs/heads/ and refs/tags/ prefixes that would let us distinguish - # between branches and tags. By ignoring refnames without digits, we - # filter out many common branch names like "release" and - # "stabilization", as well as "HEAD" and "master". - tags = set([r for r in refs if re.search(r'\d', r)]) - if verbose: - print("discarding '%s', no digits" % ",".join(refs-tags)) - if verbose: - print("likely tags: %s" % ",".join(sorted(tags))) - for ref in sorted(tags): - # sorting will prefer e.g. "2.0" over "2.0rc1" - if ref.startswith(tag_prefix): - r = ref[len(tag_prefix):] - if verbose: - print("picking %s" % r) - return {"version": r, - "full-revisionid": keywords["full"].strip(), - "dirty": False, "error": None - } - # no suitable tags, so version is "0+unknown", but full hex is still there - if verbose: - print("no suitable tags, using unknown + full revision id") - return {"version": "0+unknown", - "full-revisionid": keywords["full"].strip(), - "dirty": False, "error": "no suitable tags"} - - -@register_vcs_handler("git", "pieces_from_vcs") -def git_pieces_from_vcs(tag_prefix, root, verbose, run_command=run_command): - """Get version from 'git describe' in the root of the source tree. - - This only gets called if the git-archive 'subst' keywords were *not* - expanded, and _version.py hasn't already been rewritten with a short - version string, meaning we're inside a checked out source tree. - """ - GITS = ["git"] - if sys.platform == "win32": - GITS = ["git.cmd", "git.exe"] - - out, rc = run_command(GITS, ["rev-parse", "--git-dir"], cwd=root, - hide_stderr=True) - if rc != 0: - if verbose: - print("Directory %s not under git control" % root) - raise NotThisMethod("'git rev-parse --git-dir' returned error") - - # if there is a tag matching tag_prefix, this yields TAG-NUM-gHEX[-dirty] - # if there isn't one, this yields HEX[-dirty] (no NUM) - describe_out, rc = run_command(GITS, ["describe", "--tags", "--dirty", - "--always", "--long", - "--match", "%s*" % tag_prefix], - cwd=root) - # --long was added in git-1.5.5 - if describe_out is None: - raise NotThisMethod("'git describe' failed") - describe_out = describe_out.strip() - full_out, rc = run_command(GITS, ["rev-parse", "HEAD"], cwd=root) - if full_out is None: - raise NotThisMethod("'git rev-parse' failed") - full_out = full_out.strip() - - pieces = {} - pieces["long"] = full_out - pieces["short"] = full_out[:7] # maybe improved later - pieces["error"] = None - - # parse describe_out. It will be like TAG-NUM-gHEX[-dirty] or HEX[-dirty] - # TAG might have hyphens. - git_describe = describe_out - - # look for -dirty suffix - dirty = git_describe.endswith("-dirty") - pieces["dirty"] = dirty - if dirty: - git_describe = git_describe[:git_describe.rindex("-dirty")] - - # now we have TAG-NUM-gHEX or HEX - - if "-" in git_describe: - # TAG-NUM-gHEX - mo = re.search(r'^(.+)-(\d+)-g([0-9a-f]+)$', git_describe) - if not mo: - # unparseable. Maybe git-describe is misbehaving? - pieces["error"] = ("unable to parse git-describe output: '%s'" - % describe_out) - return pieces - - # tag - full_tag = mo.group(1) - if not full_tag.startswith(tag_prefix): - if verbose: - fmt = "tag '%s' doesn't start with prefix '%s'" - print(fmt % (full_tag, tag_prefix)) - pieces["error"] = ("tag '%s' doesn't start with prefix '%s'" - % (full_tag, tag_prefix)) - return pieces - pieces["closest-tag"] = full_tag[len(tag_prefix):] - - # distance: number of commits since tag - pieces["distance"] = int(mo.group(2)) - - # commit: short hex revision ID - pieces["short"] = mo.group(3) - - else: - # HEX: no tags - pieces["closest-tag"] = None - count_out, rc = run_command(GITS, ["rev-list", "HEAD", "--count"], - cwd=root) - pieces["distance"] = int(count_out) # total number of commits - - return pieces - - -def do_vcs_install(manifest_in, versionfile_source, ipy): - """Git-specific installation logic for Versioneer. - - For Git, this means creating/changing .gitattributes to mark _version.py - for export-time keyword substitution. - """ - GITS = ["git"] - if sys.platform == "win32": - GITS = ["git.cmd", "git.exe"] - files = [manifest_in, versionfile_source] - if ipy: - files.append(ipy) - try: - me = __file__ - if me.endswith(".pyc") or me.endswith(".pyo"): - me = os.path.splitext(me)[0] + ".py" - versioneer_file = os.path.relpath(me) - except NameError: - versioneer_file = "versioneer.py" - files.append(versioneer_file) - present = False - try: - f = open(".gitattributes", "r") - for line in f.readlines(): - if line.strip().startswith(versionfile_source): - if "export-subst" in line.strip().split()[1:]: - present = True - f.close() - except EnvironmentError: - pass - if not present: - f = open(".gitattributes", "a+") - f.write("%s export-subst\n" % versionfile_source) - f.close() - files.append(".gitattributes") - run_command(GITS, ["add", "--"] + files) - - -def versions_from_parentdir(parentdir_prefix, root, verbose): - """Try to determine the version from the parent directory name. - - Source tarballs conventionally unpack into a directory that includes both - the project name and a version string. We will also support searching up - two directory levels for an appropriately named parent directory - """ - rootdirs = [] - - for i in range(3): - dirname = os.path.basename(root) - if dirname.startswith(parentdir_prefix): - return {"version": dirname[len(parentdir_prefix):], - "full-revisionid": None, - "dirty": False, "error": None} - else: - rootdirs.append(root) - root = os.path.dirname(root) # up a level - - if verbose: - print("Tried directories %s but none started with prefix %s" % - (str(rootdirs), parentdir_prefix)) - raise NotThisMethod("rootdir doesn't start with parentdir_prefix") - -SHORT_VERSION_PY = """ -# This file was generated by 'versioneer.py' (0.16+dev) from -# revision-control system data, or from the parent directory name of an -# unpacked source archive. Distribution tarballs contain a pre-generated copy -# of this file. - -import json -import sys - -version_json = ''' -%s -''' # END VERSION_JSON - - -def get_versions(): - return json.loads(version_json) -""" - - -def versions_from_file(filename): - """Try to determine the version from _version.py if present.""" - try: - with open(filename) as f: - contents = f.read() - except EnvironmentError: - raise NotThisMethod("unable to read _version.py") - mo = re.search(r"version_json = '''\n(.*)''' # END VERSION_JSON", - contents, re.M | re.S) - if not mo: - raise NotThisMethod("no version_json in _version.py") - return json.loads(mo.group(1)) - - -def write_to_version_file(filename, versions): - """Write the given version number to the given _version.py file.""" - os.unlink(filename) - contents = json.dumps(versions, sort_keys=True, - indent=1, separators=(",", ": ")) - with open(filename, "w") as f: - f.write(SHORT_VERSION_PY % contents) - - print("set %s to '%s'" % (filename, versions["version"])) - - -def plus_or_dot(pieces): - """Return a + if we don't already have one, else return a .""" - if "+" in pieces.get("closest-tag", ""): - return "." - return "+" - - -def render_pep440(pieces): - """Build up version string, with post-release "local version identifier". - - Our goal: TAG[+DISTANCE.gHEX[.dirty]] . Note that if you - get a tagged build and then dirty it, you'll get TAG+0.gHEX.dirty - - Exceptions: - 1: no tags. git_describe was just HEX. 0+untagged.DISTANCE.gHEX[.dirty] - """ - if pieces["closest-tag"]: - rendered = pieces["closest-tag"] - if pieces["distance"] or pieces["dirty"]: - rendered += plus_or_dot(pieces) - rendered += "%d.g%s" % (pieces["distance"], pieces["short"]) - if pieces["dirty"]: - rendered += ".dirty" - else: - # exception #1 - rendered = "0+untagged.%d.g%s" % (pieces["distance"], - pieces["short"]) - if pieces["dirty"]: - rendered += ".dirty" - return rendered - - -def render_pep440_pre(pieces): - """TAG[.post.devDISTANCE] -- No -dirty. - - Exceptions: - 1: no tags. 0.post.devDISTANCE - """ - if pieces["closest-tag"]: - rendered = pieces["closest-tag"] - if pieces["distance"]: - rendered += ".post.dev%d" % pieces["distance"] - else: - # exception #1 - rendered = "0.post.dev%d" % pieces["distance"] - return rendered - - -def render_pep440_post(pieces): - """TAG[.postDISTANCE[.dev0]+gHEX] . - - The ".dev0" means dirty. Note that .dev0 sorts backwards - (a dirty tree will appear "older" than the corresponding clean one), - but you shouldn't be releasing software with -dirty anyways. - - Exceptions: - 1: no tags. 0.postDISTANCE[.dev0] - """ - if pieces["closest-tag"]: - rendered = pieces["closest-tag"] - if pieces["distance"] or pieces["dirty"]: - rendered += ".post%d" % pieces["distance"] - if pieces["dirty"]: - rendered += ".dev0" - rendered += plus_or_dot(pieces) - rendered += "g%s" % pieces["short"] - else: - # exception #1 - rendered = "0.post%d" % pieces["distance"] - if pieces["dirty"]: - rendered += ".dev0" - rendered += "+g%s" % pieces["short"] - return rendered - - -def render_pep440_old(pieces): - """TAG[.postDISTANCE[.dev0]] . - - The ".dev0" means dirty. - - Eexceptions: - 1: no tags. 0.postDISTANCE[.dev0] - """ - if pieces["closest-tag"]: - rendered = pieces["closest-tag"] - if pieces["distance"] or pieces["dirty"]: - rendered += ".post%d" % pieces["distance"] - if pieces["dirty"]: - rendered += ".dev0" - else: - # exception #1 - rendered = "0.post%d" % pieces["distance"] - if pieces["dirty"]: - rendered += ".dev0" - return rendered - - -def render_git_describe(pieces): - """TAG[-DISTANCE-gHEX][-dirty]. - - Like 'git describe --tags --dirty --always'. - - Exceptions: - 1: no tags. HEX[-dirty] (note: no 'g' prefix) - """ - if pieces["closest-tag"]: - rendered = pieces["closest-tag"] - if pieces["distance"]: - rendered += "-%d-g%s" % (pieces["distance"], pieces["short"]) - else: - # exception #1 - rendered = pieces["short"] - if pieces["dirty"]: - rendered += "-dirty" - return rendered - - -def render_git_describe_long(pieces): - """TAG-DISTANCE-gHEX[-dirty]. - - Like 'git describe --tags --dirty --always -long'. - The distance/hash is unconditional. - - Exceptions: - 1: no tags. HEX[-dirty] (note: no 'g' prefix) - """ - if pieces["closest-tag"]: - rendered = pieces["closest-tag"] - rendered += "-%d-g%s" % (pieces["distance"], pieces["short"]) - else: - # exception #1 - rendered = pieces["short"] - if pieces["dirty"]: - rendered += "-dirty" - return rendered - - -def render(pieces, style): - """Render the given version pieces into the requested style.""" - if pieces["error"]: - return {"version": "unknown", - "full-revisionid": pieces.get("long"), - "dirty": None, - "error": pieces["error"]} - - if not style or style == "default": - style = "pep440" # the default - - if style == "pep440": - rendered = render_pep440(pieces) - elif style == "pep440-pre": - rendered = render_pep440_pre(pieces) - elif style == "pep440-post": - rendered = render_pep440_post(pieces) - elif style == "pep440-old": - rendered = render_pep440_old(pieces) - elif style == "git-describe": - rendered = render_git_describe(pieces) - elif style == "git-describe-long": - rendered = render_git_describe_long(pieces) - else: - raise ValueError("unknown style '%s'" % style) - - return {"version": rendered, "full-revisionid": pieces["long"], - "dirty": pieces["dirty"], "error": None} - - -class VersioneerBadRootError(Exception): - """The project root directory is unknown or missing key files.""" - - -def get_versions(verbose=False): - """Get the project version from whatever source is available. - - Returns dict with two keys: 'version' and 'full'. - """ - if "versioneer" in sys.modules: - # see the discussion in cmdclass.py:get_cmdclass() - del sys.modules["versioneer"] - - root = get_root() - cfg = get_config_from_root(root) - - assert cfg.VCS is not None, "please set [versioneer]VCS= in setup.cfg" - handlers = HANDLERS.get(cfg.VCS) - assert handlers, "unrecognized VCS '%s'" % cfg.VCS - verbose = verbose or cfg.verbose - assert cfg.versionfile_source is not None, \ - "please set versioneer.versionfile_source" - assert cfg.tag_prefix is not None, "please set versioneer.tag_prefix" - - versionfile_abs = os.path.join(root, cfg.versionfile_source) - - # extract version from first of: _version.py, VCS command (e.g. 'git - # describe'), parentdir. This is meant to work for developers using a - # source checkout, for users of a tarball created by 'setup.py sdist', - # and for users of a tarball/zipball created by 'git archive' or github's - # download-from-tag feature or the equivalent in other VCSes. - - get_keywords_f = handlers.get("get_keywords") - from_keywords_f = handlers.get("keywords") - if get_keywords_f and from_keywords_f: - try: - keywords = get_keywords_f(versionfile_abs) - ver = from_keywords_f(keywords, cfg.tag_prefix, verbose) - if verbose: - print("got version from expanded keyword %s" % ver) - return ver - except NotThisMethod: - pass - - try: - ver = versions_from_file(versionfile_abs) - if verbose: - print("got version from file %s %s" % (versionfile_abs, ver)) - return ver - except NotThisMethod: - pass - - from_vcs_f = handlers.get("pieces_from_vcs") - if from_vcs_f: - try: - pieces = from_vcs_f(cfg.tag_prefix, root, verbose) - ver = render(pieces, cfg.style) - if verbose: - print("got version from VCS %s" % ver) - return ver - except NotThisMethod: - pass - - try: - if cfg.parentdir_prefix: - ver = versions_from_parentdir(cfg.parentdir_prefix, root, verbose) - if verbose: - print("got version from parentdir %s" % ver) - return ver - except NotThisMethod: - pass - - if verbose: - print("unable to compute version") - - return {"version": "0+unknown", "full-revisionid": None, - "dirty": None, "error": "unable to compute version"} - - -def get_version(): - """Get the short version string for this project.""" - return get_versions()["version"] - - -def get_cmdclass(): - """Get the custom setuptools/distutils subclasses used by Versioneer.""" - if "versioneer" in sys.modules: - del sys.modules["versioneer"] - # this fixes the "python setup.py develop" case (also 'install' and - # 'easy_install .'), in which subdependencies of the main project are - # built (using setup.py bdist_egg) in the same python process. Assume - # a main project A and a dependency B, which use different versions - # of Versioneer. A's setup.py imports A's Versioneer, leaving it in - # sys.modules by the time B's setup.py is executed, causing B to run - # with the wrong versioneer. Setuptools wraps the sub-dep builds in a - # sandbox that restores sys.modules to it's pre-build state, so the - # parent is protected against the child's "import versioneer". By - # removing ourselves from sys.modules here, before the child build - # happens, we protect the child from the parent's versioneer too. - # Also see https://github.com/warner/python-versioneer/issues/52 - - cmds = {} - - # we add "version" to both distutils and setuptools - from distutils.core import Command - - class cmd_version(Command): - description = "report generated version string" - user_options = [] - boolean_options = [] - - def initialize_options(self): - pass - - def finalize_options(self): - pass - - def run(self): - vers = get_versions(verbose=True) - print("Version: %s" % vers["version"]) - print(" full-revisionid: %s" % vers.get("full-revisionid")) - print(" dirty: %s" % vers.get("dirty")) - if vers["error"]: - print(" error: %s" % vers["error"]) - cmds["version"] = cmd_version - - # we override "build_py" in both distutils and setuptools - # - # most invocation pathways end up running build_py: - # distutils/build -> build_py - # distutils/install -> distutils/build ->.. - # setuptools/bdist_wheel -> distutils/install ->.. - # setuptools/bdist_egg -> distutils/install_lib -> build_py - # setuptools/install -> bdist_egg ->.. - # setuptools/develop -> ? - # pip install: - # copies source tree to a tempdir before running egg_info/etc - # if .git isn't copied too, 'git describe' will fail - # then does setup.py bdist_wheel, or sometimes setup.py install - # setup.py egg_info -> ? - - # we override different "build_py" commands for both environments - if "setuptools" in sys.modules: - from setuptools.command.build_py import build_py as _build_py - else: - from distutils.command.build_py import build_py as _build_py - - class cmd_build_py(_build_py): - def run(self): - root = get_root() - cfg = get_config_from_root(root) - versions = get_versions() - _build_py.run(self) - # now locate _version.py in the new build/ directory and replace - # it with an updated value - if cfg.versionfile_build: - target_versionfile = os.path.join(self.build_lib, - cfg.versionfile_build) - print("UPDATING %s" % target_versionfile) - write_to_version_file(target_versionfile, versions) - cmds["build_py"] = cmd_build_py - - if "cx_Freeze" in sys.modules: # cx_freeze enabled? - from cx_Freeze.dist import build_exe as _build_exe - - class cmd_build_exe(_build_exe): - def run(self): - root = get_root() - cfg = get_config_from_root(root) - versions = get_versions() - target_versionfile = cfg.versionfile_source - print("UPDATING %s" % target_versionfile) - write_to_version_file(target_versionfile, versions) - - _build_exe.run(self) - os.unlink(target_versionfile) - with open(cfg.versionfile_source, "w") as f: - LONG = LONG_VERSION_PY[cfg.VCS] - f.write(LONG % - {"DOLLAR": "$", - "STYLE": cfg.style, - "TAG_PREFIX": cfg.tag_prefix, - "PARENTDIR_PREFIX": cfg.parentdir_prefix, - "VERSIONFILE_SOURCE": cfg.versionfile_source, - }) - cmds["build_exe"] = cmd_build_exe - del cmds["build_py"] - - # we override different "sdist" commands for both environments - if "setuptools" in sys.modules: - from setuptools.command.sdist import sdist as _sdist - else: - from distutils.command.sdist import sdist as _sdist - - class cmd_sdist(_sdist): - def run(self): - versions = get_versions() - self._versioneer_generated_versions = versions - # unless we update this, the command will keep using the old - # version - self.distribution.metadata.version = versions["version"] - return _sdist.run(self) - - def make_release_tree(self, base_dir, files): - root = get_root() - cfg = get_config_from_root(root) - _sdist.make_release_tree(self, base_dir, files) - # now locate _version.py in the new base_dir directory - # (remembering that it may be a hardlink) and replace it with an - # updated value - target_versionfile = os.path.join(base_dir, cfg.versionfile_source) - print("UPDATING %s" % target_versionfile) - write_to_version_file(target_versionfile, - self._versioneer_generated_versions) - cmds["sdist"] = cmd_sdist - - return cmds - - -CONFIG_ERROR = """ -setup.cfg is missing the necessary Versioneer configuration. You need -a section like: - - [versioneer] - VCS = git - style = pep440 - versionfile_source = src/myproject/_version.py - versionfile_build = myproject/_version.py - tag_prefix = - parentdir_prefix = myproject- - -You will also need to edit your setup.py to use the results: - - import versioneer - setup(version=versioneer.get_version(), - cmdclass=versioneer.get_cmdclass(), ...) - -Please read the docstring in ./versioneer.py for configuration instructions, -edit setup.cfg, and re-run the installer or 'python versioneer.py setup'. -""" - -SAMPLE_CONFIG = """ -# See the docstring in versioneer.py for instructions. Note that you must -# re-run 'versioneer.py setup' after changing this section, and commit the -# resulting files. - -[versioneer] -#VCS = git -#style = pep440 -#versionfile_source = -#versionfile_build = -#tag_prefix = -#parentdir_prefix = - -""" - -INIT_PY_SNIPPET = """ -from ._version import get_versions -__version__ = get_versions()['version'] -del get_versions -""" - - -def do_setup(): - """Main VCS-independent setup function for installing Versioneer.""" - root = get_root() - try: - cfg = get_config_from_root(root) - except (EnvironmentError, configparser.NoSectionError, - configparser.NoOptionError) as e: - if isinstance(e, (EnvironmentError, configparser.NoSectionError)): - print("Adding sample versioneer config to setup.cfg", - file=sys.stderr) - with open(os.path.join(root, "setup.cfg"), "a") as f: - f.write(SAMPLE_CONFIG) - print(CONFIG_ERROR, file=sys.stderr) - return 1 - - print(" creating %s" % cfg.versionfile_source) - with open(cfg.versionfile_source, "w") as f: - LONG = LONG_VERSION_PY[cfg.VCS] - f.write(LONG % {"DOLLAR": "$", - "STYLE": cfg.style, - "TAG_PREFIX": cfg.tag_prefix, - "PARENTDIR_PREFIX": cfg.parentdir_prefix, - "VERSIONFILE_SOURCE": cfg.versionfile_source, - }) - - ipy = os.path.join(os.path.dirname(cfg.versionfile_source), - "__init__.py") - if os.path.exists(ipy): - try: - with open(ipy, "r") as f: - old = f.read() - except EnvironmentError: - old = "" - if INIT_PY_SNIPPET not in old: - print(" appending to %s" % ipy) - with open(ipy, "a") as f: - f.write(INIT_PY_SNIPPET) - else: - print(" %s unmodified" % ipy) - else: - print(" %s doesn't exist, ok" % ipy) - ipy = None - - # Make sure both the top-level "versioneer.py" and versionfile_source - # (PKG/_version.py, used by runtime code) are in MANIFEST.in, so - # they'll be copied into source distributions. Pip won't be able to - # install the package without this. - manifest_in = os.path.join(root, "MANIFEST.in") - simple_includes = set() - try: - with open(manifest_in, "r") as f: - for line in f: - if line.startswith("include "): - for include in line.split()[1:]: - simple_includes.add(include) - except EnvironmentError: - pass - # That doesn't cover everything MANIFEST.in can do - # (http://docs.python.org/2/distutils/sourcedist.html#commands), so - # it might give some false negatives. Appending redundant 'include' - # lines is safe, though. - if "versioneer.py" not in simple_includes: - print(" appending 'versioneer.py' to MANIFEST.in") - with open(manifest_in, "a") as f: - f.write("include versioneer.py\n") - else: - print(" 'versioneer.py' already in MANIFEST.in") - if cfg.versionfile_source not in simple_includes: - print(" appending versionfile_source ('%s') to MANIFEST.in" % - cfg.versionfile_source) - with open(manifest_in, "a") as f: - f.write("include %s\n" % cfg.versionfile_source) - else: - print(" versionfile_source already in MANIFEST.in") - - # Make VCS-specific changes. For git, this means creating/changing - # .gitattributes to mark _version.py for export-time keyword - # substitution. - do_vcs_install(manifest_in, cfg.versionfile_source, ipy) - return 0 - - -def scan_setup_py(): - """Validate the contents of setup.py against Versioneer's expectations.""" - found = set() - setters = False - errors = 0 - with open("setup.py", "r") as f: - for line in f.readlines(): - if "import versioneer" in line: - found.add("import") - if "versioneer.get_cmdclass()" in line: - found.add("cmdclass") - if "versioneer.get_version()" in line: - found.add("get_version") - if "versioneer.VCS" in line: - setters = True - if "versioneer.versionfile_source" in line: - setters = True - if len(found) != 3: - print("") - print("Your setup.py appears to be missing some important items") - print("(but I might be wrong). Please make sure it has something") - print("roughly like the following:") - print("") - print(" import versioneer") - print(" setup( version=versioneer.get_version(),") - print(" cmdclass=versioneer.get_cmdclass(), ...)") - print("") - errors += 1 - if setters: - print("You should remove lines like 'versioneer.VCS = ' and") - print("'versioneer.versionfile_source = ' . This configuration") - print("now lives in setup.cfg, and should be removed from setup.py") - print("") - errors += 1 - return errors - -if __name__ == "__main__": - cmd = sys.argv[1] - if cmd == "setup": - errors = do_setup() - errors += scan_setup_py() - if errors: - sys.exit(1) From 8bc019e8fc50928d8dec437984fa817e11965566 Mon Sep 17 00:00:00 2001 From: Steven Silvester Date: Sat, 11 Mar 2017 06:28:45 -0600 Subject: [PATCH 24/88] Add files --- .travis.yml | 8 ++++++++ Makefile | 26 ++++++++++++++++++++++++++ 2 files changed, 34 insertions(+) create mode 100644 .travis.yml create mode 100644 Makefile diff --git a/.travis.yml b/.travis.yml new file mode 100644 index 0000000..80d1898 --- /dev/null +++ b/.travis.yml @@ -0,0 +1,8 @@ +language: python +python: + - "2.7" + - "3.5" +install: + - pip install . +script: + - make test diff --git a/Makefile b/Makefile new file mode 100644 index 0000000..dcca854 --- /dev/null +++ b/Makefile @@ -0,0 +1,26 @@ +# Note: This is meant for octave_kernel developer use only +.PHONY: all clean test release + +export NAME=matlab_kernel +export VERSION=`python -c "import $(NAME); print($(NAME).__version__)"` + +all: clean + python setup.py install + +clean: + rm -rf build + rm -rf dist + +test: clean + python setup.py build + python -m matlab_kernel install + +release: test clean + pip install wheel + python setup.py register + python setup.py bdist_wheel --universal + python setup.py sdist + git tag v$(VERSION) + git push origin --all + git push origin --tags + twine upload dist/* From fb11c94fa7c6da3ee35efa388c8a44766b2b15d7 Mon Sep 17 00:00:00 2001 From: Steven Silvester Date: Sat, 11 Mar 2017 06:29:12 -0600 Subject: [PATCH 25/88] Remove release notes --- RELEASE.md | 12 ------------ 1 file changed, 12 deletions(-) delete mode 100644 RELEASE.md diff --git a/RELEASE.md b/RELEASE.md deleted file mode 100644 index 1999ffd..0000000 --- a/RELEASE.md +++ /dev/null @@ -1,12 +0,0 @@ - -## Making a release - -Tag the release using `git tag`, then: - -``` -git push origin --tags -rm -rf dist -python setup.py sdist -python setup.py bdist_wheel --universal -twine upload dist/* -``` From 1808d54243a32801d5b3ec21bf672e2e0fb76ffd Mon Sep 17 00:00:00 2001 From: Steven Silvester Date: Sat, 11 Mar 2017 06:52:34 -0600 Subject: [PATCH 26/88] Clean up makefile --- Makefile | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Makefile b/Makefile index dcca854..eb267a0 100644 --- a/Makefile +++ b/Makefile @@ -1,8 +1,8 @@ # Note: This is meant for octave_kernel developer use only .PHONY: all clean test release -export NAME=matlab_kernel -export VERSION=`python -c "import $(NAME); print($(NAME).__version__)"` +export NAME=`python setup.py --name 2>/dev/null` +export VERSION=`python setup.py --version 2>/dev/null` all: clean python setup.py install From c348638ac00df5455326a2114b894226934c0d38 Mon Sep 17 00:00:00 2001 From: Steven Silvester Date: Sat, 11 Mar 2017 08:45:50 -0600 Subject: [PATCH 27/88] Remove use of pathlib --- matlab_kernel/kernel.py | 7 +++---- setup.py | 1 - 2 files changed, 3 insertions(+), 5 deletions(-) diff --git a/matlab_kernel/kernel.py b/matlab_kernel/kernel.py index b51f394..89f4562 100644 --- a/matlab_kernel/kernel.py +++ b/matlab_kernel/kernel.py @@ -4,7 +4,6 @@ except ImportError: from io import StringIO import os -from pathlib import Path import sys try: from tempfile import TemporaryDirectory @@ -168,13 +167,13 @@ def do_is_complete(self, code): if self.parse_code(code)["magic"]: return {"status": "complete"} with TemporaryDirectory() as tmpdir: - path = Path(tmpdir, "test_complete.m") - with path.open(mode='w') as f: + path = os.path.join(tmpdir, "test_complete.m") + with open(path, mode='w') as f: f.write(code) self._matlab.eval( "try, pcode {} -inplace; catch, end".format(tmpdir), nargout=0) - if Path(tmpdir, "test_complete.p").exists(): + if os.path.exists(os.path.join(tmpdir, "test_complete.p")): return {"status": "complete"} else: return {"status": "incomplete"} diff --git a/setup.py b/setup.py index 8f2fd80..6e57924 100644 --- a/setup.py +++ b/setup.py @@ -25,6 +25,5 @@ "pathlib", 'ipython (>=4.0.0)'], install_requires=["metakernel>=0.18.0", "jupyter_client >=4.4.0", "ipython>=4.0.0", - "pathlib;python_version<'3.4'", "backports.tempfile;python_version<'3.0'"] ) From 54f6ea4694105c4c7f4a5eada2c2113162a95ef2 Mon Sep 17 00:00:00 2001 From: Steven Silvester Date: Sat, 11 Mar 2017 08:46:09 -0600 Subject: [PATCH 28/88] Bump to 0.14.0 --- matlab_kernel/__init__.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/matlab_kernel/__init__.py b/matlab_kernel/__init__.py index a549eca..34267c4 100644 --- a/matlab_kernel/__init__.py +++ b/matlab_kernel/__init__.py @@ -1,3 +1,3 @@ """A Matlab kernel for Jupyter""" -__version__ = '0.13.4' +__version__ = '0.14.0' From 7cd508c5e5cbaa37aa24863fa005b60b3a1ab45b Mon Sep 17 00:00:00 2001 From: Steven Silvester Date: Sat, 11 Mar 2017 09:16:45 -0600 Subject: [PATCH 29/88] Remove pathlib requires --- setup.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/setup.py b/setup.py index 6e57924..a19f870 100644 --- a/setup.py +++ b/setup.py @@ -22,7 +22,7 @@ "Topic :: System :: Shells"], packages=find_packages(include=["matlab_kernel", "matlab_kernel.*"]), requires=["metakernel (>0.18.0)", "jupyter_client (>=4.4.0)", - "pathlib", 'ipython (>=4.0.0)'], + "ipython (>=4.0.0)"], install_requires=["metakernel>=0.18.0", "jupyter_client >=4.4.0", "ipython>=4.0.0", "backports.tempfile;python_version<'3.0'"] From ae1329963a4ac52a0877aefc27823e36c012063e Mon Sep 17 00:00:00 2001 From: Steven Silvester Date: Sat, 11 Mar 2017 09:17:32 -0600 Subject: [PATCH 30/88] Release 0.14.1 --- Makefile | 1 + matlab_kernel/__init__.py | 2 +- 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/Makefile b/Makefile index eb267a0..9a0eee2 100644 --- a/Makefile +++ b/Makefile @@ -20,6 +20,7 @@ release: test clean python setup.py register python setup.py bdist_wheel --universal python setup.py sdist + git commit -a -m "Release $(VERSION)" git tag v$(VERSION) git push origin --all git push origin --tags diff --git a/matlab_kernel/__init__.py b/matlab_kernel/__init__.py index 34267c4..1074a9d 100644 --- a/matlab_kernel/__init__.py +++ b/matlab_kernel/__init__.py @@ -1,3 +1,3 @@ """A Matlab kernel for Jupyter""" -__version__ = '0.14.0' +__version__ = '0.14.1' From cf97eed8d11eb89f00ed4f43fac09d941b452af1 Mon Sep 17 00:00:00 2001 From: Steven Silvester Date: Sat, 11 Mar 2017 10:55:39 -0600 Subject: [PATCH 31/88] Fix readme --- README.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.rst b/README.rst index ba10348..16f8f97 100644 --- a/README.rst +++ b/README.rst @@ -2,7 +2,7 @@ A Jupyter/IPython kernel for Matlab =================================== -This requires `Jupyter Notebook `_ +This requires `Jupyter Notebook `_ and the `Matlab engine for Python `_. To install:: From db43ea83e6d75b7e08858f3d3486b4189cb00ea4 Mon Sep 17 00:00:00 2001 From: Steven Silvester Date: Sat, 11 Mar 2017 10:57:35 -0600 Subject: [PATCH 32/88] Fix readme --- README.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.rst b/README.rst index 16f8f97..e9e313c 100644 --- a/README.rst +++ b/README.rst @@ -2,7 +2,7 @@ A Jupyter/IPython kernel for Matlab =================================== -This requires `Jupyter Notebook `_ and the +Prerequisites: Install `Jupyter Notebook `_ and the `Matlab engine for Python `_. To install:: From a6e3533207c0885f7dfa91abf25864d97a04c04a Mon Sep 17 00:00:00 2001 From: Steven Silvester Date: Sat, 11 Mar 2017 11:00:18 -0600 Subject: [PATCH 33/88] Update readme --- README.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.rst b/README.rst index e9e313c..e50aa79 100644 --- a/README.rst +++ b/README.rst @@ -1,5 +1,5 @@ -A Jupyter/IPython kernel for Matlab +A Jupyter kernel for Matlab =================================== Prerequisites: Install `Jupyter Notebook `_ and the From 12817c818fcdfcca67601f360c5d9d2db9c1478f Mon Sep 17 00:00:00 2001 From: Steven Silvester Date: Sat, 11 Mar 2017 11:04:13 -0600 Subject: [PATCH 34/88] Update title --- README.rst | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.rst b/README.rst index e50aa79..8dd5252 100644 --- a/README.rst +++ b/README.rst @@ -1,6 +1,6 @@ -A Jupyter kernel for Matlab -=================================== +A Matlab kernel for Jupyter +=========================== Prerequisites: Install `Jupyter Notebook `_ and the `Matlab engine for Python `_. From d26ca4f6fadc1330dbcad7d27021a127df1cec3b Mon Sep 17 00:00:00 2001 From: Joo-won Kim Date: Sat, 11 Mar 2017 22:03:56 -0500 Subject: [PATCH 35/88] change \\ to / --- matlab_kernel/kernel.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/matlab_kernel/kernel.py b/matlab_kernel/kernel.py index 89f4562..1de2e92 100644 --- a/matlab_kernel/kernel.py +++ b/matlab_kernel/kernel.py @@ -100,7 +100,7 @@ def do_execute_direct(self, code): "arrayfun(" "@(h, i) print(h, sprintf('{}/%i', i), '-d{}', '-r{}')," "get(0, 'children'), (1:{})')".format( - tmpdir, + '/'.join(tmpdir.split(os.sep)), settings["format"], settings["resolution"], nfig), From d77931be94c2007361e0da5c11371eb86116bffb Mon Sep 17 00:00:00 2001 From: Steven Silvester Date: Sun, 12 Mar 2017 05:09:36 -0500 Subject: [PATCH 36/88] Release 0.14.2 --- matlab_kernel/__init__.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/matlab_kernel/__init__.py b/matlab_kernel/__init__.py index 1074a9d..9974256 100644 --- a/matlab_kernel/__init__.py +++ b/matlab_kernel/__init__.py @@ -1,3 +1,3 @@ """A Matlab kernel for Jupyter""" -__version__ = '0.14.1' +__version__ = '0.14.2' From 2090e3e8206e990a0ebb1646288dad1218f19493 Mon Sep 17 00:00:00 2001 From: Steven Silvester Date: Wed, 15 Mar 2017 04:01:23 -0500 Subject: [PATCH 37/88] Fix makefile --- Makefile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Makefile b/Makefile index 9a0eee2..e40c01f 100644 --- a/Makefile +++ b/Makefile @@ -20,7 +20,7 @@ release: test clean python setup.py register python setup.py bdist_wheel --universal python setup.py sdist - git commit -a -m "Release $(VERSION)" + git commit -a -m "Release $(VERSION)"; true git tag v$(VERSION) git push origin --all git push origin --tags From e3ce32e373b93396ed3f4748c839fa35888b159a Mon Sep 17 00:00:00 2001 From: Steven Silvester Date: Wed, 19 Apr 2017 19:38:12 -0500 Subject: [PATCH 38/88] Import the matlab engine first --- matlab_kernel/kernel.py | 11 +++++------ 1 file changed, 5 insertions(+), 6 deletions(-) diff --git a/matlab_kernel/kernel.py b/matlab_kernel/kernel.py index 1de2e92..2102c69 100644 --- a/matlab_kernel/kernel.py +++ b/matlab_kernel/kernel.py @@ -1,3 +1,8 @@ +try: + import matlab.engine + from matlab.engine import MatlabExecutionError +except ImportError: + matlab = None from functools import partial try: from StringIO import StringIO @@ -20,12 +25,6 @@ except ImportError: Wurlitzer = None -try: - import matlab.engine - from matlab.engine import MatlabExecutionError -except ImportError: - matlab = None - class _PseudoStream: From 84e04573bf3bc7241f76a3ccfdf2b3df7252c1b7 Mon Sep 17 00:00:00 2001 From: Steven Silvester Date: Wed, 19 Apr 2017 19:39:08 -0500 Subject: [PATCH 39/88] Release 0.14.3 --- Makefile | 5 +++-- matlab_kernel/__init__.py | 2 +- 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/Makefile b/Makefile index e40c01f..a48a82f 100644 --- a/Makefile +++ b/Makefile @@ -17,11 +17,12 @@ test: clean release: test clean pip install wheel + git commit -a -m "Release $(VERSION)"; true + git tag v$(VERSION) + rm -rf dist python setup.py register python setup.py bdist_wheel --universal python setup.py sdist - git commit -a -m "Release $(VERSION)"; true - git tag v$(VERSION) git push origin --all git push origin --tags twine upload dist/* diff --git a/matlab_kernel/__init__.py b/matlab_kernel/__init__.py index 9974256..d443e05 100644 --- a/matlab_kernel/__init__.py +++ b/matlab_kernel/__init__.py @@ -1,3 +1,3 @@ """A Matlab kernel for Jupyter""" -__version__ = '0.14.2' +__version__ = '0.14.3' From 3755cb29ead4bf0acf9dd3c5989f608c3fe44a82 Mon Sep 17 00:00:00 2001 From: Doug Blank Date: Sat, 22 Apr 2017 09:29:42 -0400 Subject: [PATCH 40/88] Update README.rst Added information on removing kernel listing. --- README.rst | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/README.rst b/README.rst index 8dd5252..1619bc1 100644 --- a/README.rst +++ b/README.rst @@ -18,8 +18,14 @@ To use it, run one of:: # In the notebook interface, select Matlab from the 'New' menu $ jupyter qtconsole --kernel matlab $ jupyter console --kernel matlab + +To remove from kernel listings:: -This is based on `MetaKernel `_, + $ jupyter kernelspec remove matlab + +Additional information:: + +The Matlab kernel is based on `MetaKernel `_, which means it features a standard set of magics. A sample notebook is available online_. From 1f3084d919cf4795d20be2c1223b0318941df655 Mon Sep 17 00:00:00 2001 From: Steven Silvester Date: Tue, 17 Oct 2017 15:56:25 -0500 Subject: [PATCH 41/88] Clean up installation --- MANIFEST.in | 2 ++ Makefile | 6 +++--- README.rst | 7 ++++++- matlab_kernel/kernel.json | 8 ++++++++ matlab_kernel/kernel.py | 22 +++++++++++++--------- setup.py | 14 ++++++++++++++ 6 files changed, 46 insertions(+), 13 deletions(-) create mode 100644 matlab_kernel/kernel.json diff --git a/MANIFEST.in b/MANIFEST.in index 9344259..0317e07 100644 --- a/MANIFEST.in +++ b/MANIFEST.in @@ -1,2 +1,4 @@ include versioneer.py include matlab_kernel/_version.py +include matlab_kernel/kernel.json +recursive-include matlab_kernel *.png diff --git a/Makefile b/Makefile index a48a82f..ee707b6 100644 --- a/Makefile +++ b/Makefile @@ -5,15 +5,15 @@ export NAME=`python setup.py --name 2>/dev/null` export VERSION=`python setup.py --version 2>/dev/null` all: clean - python setup.py install + pip install . clean: rm -rf build rm -rf dist test: clean - python setup.py build - python -m matlab_kernel install + pip install . + python -c "from jupyter_client.kernelspec import find_kernel_specs; assert 'matlab' in find_kernel_specs()" release: test clean pip install wheel diff --git a/README.rst b/README.rst index 1619bc1..d300963 100644 --- a/README.rst +++ b/README.rst @@ -10,7 +10,6 @@ To install:: $ pip install matlab_kernel # or `pip install git+https://github.com/Calysto/matlab_kernel` # for the devel version. - $ python -m matlab_kernel install To use it, run one of:: @@ -35,4 +34,10 @@ open figures to image files whose format and resolution are defined using the ``%plot`` magic. The resulting image is shown inline in the notebook. You can use ``%plot native`` to raise normal Matlab windows instead. + +Advanced Installation Notes:: + +We automatically install a Jupyter kernelspec when installing the python package. This location can be found using ``jupyter kernelspec list``. If the default location is not desired, you can remove the directory for the octave kernel, and install using python -m matlab_kernel install. See python -m matlab_kernel install --help for available options. + + .. _online: http://nbviewer.ipython.org/github/Calysto/matlab_kernel/blob/master/matlab_kernel.ipynb diff --git a/matlab_kernel/kernel.json b/matlab_kernel/kernel.json new file mode 100644 index 0000000..7d1adb8 --- /dev/null +++ b/matlab_kernel/kernel.json @@ -0,0 +1,8 @@ +{ + "argv": [ + "python", "-m", "matlab_kernel", "-f", "{connection_file}"], + "display_name": "Matlab", + "language": "matlab", + "mimetype": "text/x-octave", + "name": "matlab", +} diff --git a/matlab_kernel/kernel.py b/matlab_kernel/kernel.py index 2102c69..0e5fe8e 100644 --- a/matlab_kernel/kernel.py +++ b/matlab_kernel/kernel.py @@ -8,6 +8,7 @@ from StringIO import StringIO except ImportError: from io import StringIO +import json import os import sys try: @@ -32,6 +33,16 @@ def __init__(self, writer): self.write = writer +def get_kernel_json(): + """Get the kernel json for the kernel. + """ + here = os.path.dirname(__file__) + with open(os.path.join(here, 'kernel.json')) as fid: + data = json.load(fid) + data['argv'][0] = sys.executable + return data + + class MatlabKernel(MetaKernel): implementation = "Matlab Kernel" implementation_version = __version__, @@ -39,21 +50,14 @@ class MatlabKernel(MetaKernel): language_version = __version__, banner = "Matlab Kernel" language_info = { - "mimetype": "text/x-matlab", + "mimetype": "text/x-octave", "codemirror_mode": "octave", "name": "matlab", "file_extension": ".m", "version": __version__, "help_links": MetaKernel.help_links, } - kernel_json = { - "argv": [ - sys.executable, "-m", "matlab_kernel", "-f", "{connection_file}"], - "display_name": "Matlab", - "language": "matlab", - "mimetype": "text/x-matlab", - "name": "matlab", - } + kernel_json = get_kernel_json() def __init__(self, *args, **kwargs): super(MatlabKernel, self).__init__(*args, **kwargs) diff --git a/setup.py b/setup.py index a19f870..464c888 100644 --- a/setup.py +++ b/setup.py @@ -1,3 +1,4 @@ +import glob from setuptools import setup, find_packages with open('matlab_kernel/__init__.py', 'rb') as fid: @@ -7,6 +8,16 @@ version = line.strip().split()[-1][1:-1] break +DISTNAME = 'matlab_kernel' +PACKAGE_DATA = { + DISTNAME: ['*.m'] + glob.glob('%s/**/*.*' % DISTNAME) +} +DATA_FILES = [ + ('share/jupyter/kernels/octave', [ + '%s/kernel.json' % DISTNAME + ] + glob.glob('%s/images/*.png' % DISTNAME) + ) +] if __name__ == "__main__": setup(name="matlab_kernel", @@ -21,6 +32,9 @@ "Programming Language :: Python :: 3.5", "Topic :: System :: Shells"], packages=find_packages(include=["matlab_kernel", "matlab_kernel.*"]), + package_data=PACKAGE_DATA, + include_package_data=True, + data_files=DATA_FILES, requires=["metakernel (>0.18.0)", "jupyter_client (>=4.4.0)", "ipython (>=4.0.0)"], install_requires=["metakernel>=0.18.0", "jupyter_client >=4.4.0", From aee2d064468e6e5c2bfc9714cb0c6d318fe4f2de Mon Sep 17 00:00:00 2001 From: Steven Silvester Date: Tue, 17 Oct 2017 15:59:46 -0500 Subject: [PATCH 42/88] Cleanup --- matlab_kernel/kernel.json | 2 +- setup.py | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/matlab_kernel/kernel.json b/matlab_kernel/kernel.json index 7d1adb8..adce8b8 100644 --- a/matlab_kernel/kernel.json +++ b/matlab_kernel/kernel.json @@ -4,5 +4,5 @@ "display_name": "Matlab", "language": "matlab", "mimetype": "text/x-octave", - "name": "matlab", + "name": "matlab" } diff --git a/setup.py b/setup.py index 464c888..bc7d363 100644 --- a/setup.py +++ b/setup.py @@ -13,7 +13,7 @@ DISTNAME: ['*.m'] + glob.glob('%s/**/*.*' % DISTNAME) } DATA_FILES = [ - ('share/jupyter/kernels/octave', [ + ('share/jupyter/kernels/matlab', [ '%s/kernel.json' % DISTNAME ] + glob.glob('%s/images/*.png' % DISTNAME) ) From 571f6a14ab64bf1b4cde37f3abe3f89db4bd2d15 Mon Sep 17 00:00:00 2001 From: Steven Silvester Date: Tue, 17 Oct 2017 16:03:58 -0500 Subject: [PATCH 43/88] Make sure advanced install works --- .travis.yml | 1 + 1 file changed, 1 insertion(+) diff --git a/.travis.yml b/.travis.yml index 80d1898..ccaefff 100644 --- a/.travis.yml +++ b/.travis.yml @@ -6,3 +6,4 @@ install: - pip install . script: - make test + - python -m matlab_kernel install --user From db5487c8f937a2d84a2e2b6840c99fbaaf1e9eca Mon Sep 17 00:00:00 2001 From: Steven Silvester Date: Tue, 17 Oct 2017 16:34:43 -0500 Subject: [PATCH 44/88] Update metakernel dep --- setup.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/setup.py b/setup.py index bc7d363..7f696fc 100644 --- a/setup.py +++ b/setup.py @@ -35,9 +35,9 @@ package_data=PACKAGE_DATA, include_package_data=True, data_files=DATA_FILES, - requires=["metakernel (>0.18.0)", "jupyter_client (>=4.4.0)", + requires=["metakernel (>0.20.8.0)", "jupyter_client (>=4.4.0)", "ipython (>=4.0.0)"], - install_requires=["metakernel>=0.18.0", "jupyter_client >=4.4.0", + install_requires=["metakernel>=0.20.8", "jupyter_client >=4.4.0", "ipython>=4.0.0", "backports.tempfile;python_version<'3.0'"] ) From 515f0ec49a73ba148694596d45960077e4aede1d Mon Sep 17 00:00:00 2001 From: Steven Silvester Date: Tue, 17 Oct 2017 16:35:46 -0500 Subject: [PATCH 45/88] Fix version number --- setup.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/setup.py b/setup.py index 7f696fc..ca5b809 100644 --- a/setup.py +++ b/setup.py @@ -35,7 +35,7 @@ package_data=PACKAGE_DATA, include_package_data=True, data_files=DATA_FILES, - requires=["metakernel (>0.20.8.0)", "jupyter_client (>=4.4.0)", + requires=["metakernel (>0.20.8)", "jupyter_client (>=4.4.0)", "ipython (>=4.0.0)"], install_requires=["metakernel>=0.20.8", "jupyter_client >=4.4.0", "ipython>=4.0.0", From 9a8a3deb10d39068ae1221daa1c48fbf03d187f7 Mon Sep 17 00:00:00 2001 From: Steven Silvester Date: Tue, 17 Oct 2017 16:38:31 -0500 Subject: [PATCH 46/88] Release 0.15.0 --- matlab_kernel/__init__.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/matlab_kernel/__init__.py b/matlab_kernel/__init__.py index d443e05..5b63132 100644 --- a/matlab_kernel/__init__.py +++ b/matlab_kernel/__init__.py @@ -1,3 +1,3 @@ """A Matlab kernel for Jupyter""" -__version__ = '0.14.3' +__version__ = '0.15.0' From cc1ae5d3b27ac449d4e8ea75327fa3434e0ff96b Mon Sep 17 00:00:00 2001 From: Doug Blank Date: Fri, 10 Nov 2017 16:19:03 -0500 Subject: [PATCH 47/88] Update README.rst Make note about Matlab versions and Python 3.5 --- README.rst | 2 ++ 1 file changed, 2 insertions(+) diff --git a/README.rst b/README.rst index d300963..5b7bffc 100644 --- a/README.rst +++ b/README.rst @@ -41,3 +41,5 @@ We automatically install a Jupyter kernelspec when installing the python package .. _online: http://nbviewer.ipython.org/github/Calysto/matlab_kernel/blob/master/matlab_kernel.ipynb + +It has been reported that Matlab version 2016b works fine. However, Matlab 2014b does not work with Python 3.5. From 952532352cb4d082db9ab72af6f11d914f54edf3 Mon Sep 17 00:00:00 2001 From: Todd Date: Sat, 9 Jun 2018 23:21:32 -0400 Subject: [PATCH 48/88] Include LICENSE.txt file in wheels The license requires that all copies of the software include the license. This makes sure the license is included in the wheels. See the wheel documentation [here](https://wheel.readthedocs.io/en/stable/#including-the-license-in-the-generated-wheel-file) for more information. --- setup.cfg | 3 +++ 1 file changed, 3 insertions(+) diff --git a/setup.cfg b/setup.cfg index ae049ad..097ca9e 100644 --- a/setup.cfg +++ b/setup.cfg @@ -1,3 +1,6 @@ +[metadata] +license_file = LICENSE.txt + [versioneer] VCS = git style = pep440 From 616c495aac2628ef095ede71f039eafdfc4eb9f5 Mon Sep 17 00:00:00 2001 From: Steven Silvester Date: Mon, 11 Jun 2018 08:10:40 -0500 Subject: [PATCH 49/88] Release 0.15.1 --- matlab_kernel/__init__.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/matlab_kernel/__init__.py b/matlab_kernel/__init__.py index 5b63132..aeb03e0 100644 --- a/matlab_kernel/__init__.py +++ b/matlab_kernel/__init__.py @@ -1,3 +1,3 @@ """A Matlab kernel for Jupyter""" -__version__ = '0.15.0' +__version__ = '0.15.1' From 4c6c566433216f0da9e314fd99bc78767309877c Mon Sep 17 00:00:00 2001 From: jayendra Date: Fri, 5 Oct 2018 19:06:41 +0530 Subject: [PATCH 50/88] returning ExceptionWrapper object if excution halts with error --- matlab_kernel/kernel.py | 15 +++++++++------ 1 file changed, 9 insertions(+), 6 deletions(-) diff --git a/matlab_kernel/kernel.py b/matlab_kernel/kernel.py index 0e5fe8e..f402e90 100644 --- a/matlab_kernel/kernel.py +++ b/matlab_kernel/kernel.py @@ -17,7 +17,7 @@ from backports.tempfile import TemporaryDirectory from IPython.display import Image -from metakernel import MetaKernel +from metakernel import MetaKernel, ExceptionWrapper from . import __version__ @@ -89,9 +89,9 @@ def do_execute_direct(self, code): self.handle_plot_settings() if Wurlitzer: - self._execute_async(code) + retval = self._execute_async(code) else: - self._execute_sync(code) + retval = self._execute_sync(code) settings = self._validated_plot_settings if settings["backend"] == "inline": @@ -117,6 +117,8 @@ def do_execute_direct(self, code): except Exception as exc: self.Error(exc) + return retval + def get_kernel_help_on(self, info, level=0, none_on_fail=False): name = info.get("help_obj", "") out = StringIO() @@ -247,8 +249,9 @@ def _execute_async(self, code): _PseudoStream(partial(self.Error, end=""))): future = self._matlab.eval(code, nargout=0, async=True) future.result() - except (SyntaxError, MatlabExecutionError, KeyboardInterrupt): - pass + except (SyntaxError, MatlabExecutionError, KeyboardInterrupt) as exc: + stdout = exc.args[0] + return ExceptionWrapper("Error", -1, stdout) def _execute_sync(self, code): out = StringIO() @@ -260,7 +263,7 @@ def _execute_sync(self, code): except (SyntaxError, MatlabExecutionError) as exc: stdout = exc.args[0] self.Error(stdout) - return + return ExceptionWrapper("Error", -1, stdout) stdout = out.getvalue() self.Print(stdout) From 64095d1bb3816b17678b66d6484e3b677f9ce733 Mon Sep 17 00:00:00 2001 From: Steven Silvester Date: Fri, 5 Oct 2018 08:44:42 -0500 Subject: [PATCH 51/88] Release 0.15.2 --- matlab_kernel/__init__.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/matlab_kernel/__init__.py b/matlab_kernel/__init__.py index aeb03e0..b51ee90 100644 --- a/matlab_kernel/__init__.py +++ b/matlab_kernel/__init__.py @@ -1,3 +1,3 @@ """A Matlab kernel for Jupyter""" -__version__ = '0.15.1' +__version__ = '0.15.2' From bb35bb870785d5f325d5baab2f7d4a5358817cb0 Mon Sep 17 00:00:00 2001 From: jayendra Date: Fri, 30 Nov 2018 11:59:25 +0530 Subject: [PATCH 52/88] added wurlitzer as a dependency --- matlab_kernel/kernel.py | 15 +--- matlab_kernel/wurlitzer.py | 173 ------------------------------------- setup.py | 3 +- 3 files changed, 6 insertions(+), 185 deletions(-) delete mode 100644 matlab_kernel/wurlitzer.py diff --git a/matlab_kernel/kernel.py b/matlab_kernel/kernel.py index f402e90..d220dfc 100644 --- a/matlab_kernel/kernel.py +++ b/matlab_kernel/kernel.py @@ -18,14 +18,10 @@ from IPython.display import Image from metakernel import MetaKernel, ExceptionWrapper +from wurlitzer import pipes from . import __version__ -try: - from .wurlitzer import Wurlitzer -except ImportError: - Wurlitzer = None - class _PseudoStream: @@ -88,10 +84,7 @@ def do_execute_direct(self, code): self._matlab.get(0., "defaultfigureposition")[0][2:]) self.handle_plot_settings() - if Wurlitzer: - retval = self._execute_async(code) - else: - retval = self._execute_sync(code) + retval = self._execute_async(code) settings = self._validated_plot_settings if settings["backend"] == "inline": @@ -245,8 +238,8 @@ def do_shutdown(self, restart): def _execute_async(self, code): try: - with Wurlitzer(_PseudoStream(partial(self.Print, end="")), - _PseudoStream(partial(self.Error, end=""))): + with pipes(stdout=_PseudoStream(partial(self.Print, end="")), + stderr=_PseudoStream(partial(self.Error, end=""))): future = self._matlab.eval(code, nargout=0, async=True) future.result() except (SyntaxError, MatlabExecutionError, KeyboardInterrupt) as exc: diff --git a/matlab_kernel/wurlitzer.py b/matlab_kernel/wurlitzer.py deleted file mode 100644 index 4ce4020..0000000 --- a/matlab_kernel/wurlitzer.py +++ /dev/null @@ -1,173 +0,0 @@ -"""Capture C-level FD output on pipes - -Use `wurlitzer.pipes` or `wurlitzer.sys_pipes` as context managers. -""" -from __future__ import print_function - -__version__ = '0.2.1.dev' - -__all__ = [ - 'Wurlitzer', -] - -from contextlib import contextmanager -import ctypes -from fcntl import fcntl, F_GETFL, F_SETFL -import io -import os -import select -import sys -import threading - -libc = ctypes.CDLL(None) - -try: - c_stdout_p = ctypes.c_void_p.in_dll(libc, 'stdout') - c_stderr_p = ctypes.c_void_p.in_dll(libc, 'stderr') -except ValueError: # pragma: no cover - # libc.stdout is has a funny name on OS X - c_stdout_p = ctypes.c_void_p.in_dll(libc, '__stdoutp') # pragma: no cover - c_stderr_p = ctypes.c_void_p.in_dll(libc, '__stderrp') # pragma: no cover - -STDOUT = 2 -PIPE = 3 - -_default_encoding = getattr(sys.stdin, 'encoding', None) or 'utf8' -if _default_encoding.lower() == 'ascii': - # don't respect ascii - _default_encoding = 'utf8' # pragma: no cover - -class Wurlitzer(object): - """Class for Capturing Process-level FD output via dup2 - - Typically used via `wurlitzer.capture` - """ - flush_interval = 0.2 - - def __init__(self, stdout=None, stderr=None, encoding=_default_encoding): - """ - Parameters - ---------- - stdout: stream or None - The stream for forwarding stdout. - stderr = stream or None - The stream for forwarding stderr. - encoding: str or None - The encoding to use, if streams should be interpreted as text. - """ - self._stdout = stdout - if stderr == STDOUT: - self._stderr = self._stdout - else: - self._stderr = stderr - self.encoding = encoding - self._save_fds = {} - self._real_fds = {} - self._handlers = {} - self._handlers['stderr'] = self._handle_stderr - self._handlers['stdout'] = self._handle_stdout - - def _setup_pipe(self, name): - real_fd = getattr(sys, '__%s__' % name).fileno() - save_fd = os.dup(real_fd) - self._save_fds[name] = save_fd - - pipe_out, pipe_in = os.pipe() - os.dup2(pipe_in, real_fd) - os.close(pipe_in) - self._real_fds[name] = real_fd - - # make pipe_out non-blocking - flags = fcntl(pipe_out, F_GETFL) - fcntl(pipe_out, F_SETFL, flags|os.O_NONBLOCK) - return pipe_out - - def _decode(self, data): - """Decode data, if any - - Called before pasing to stdout/stderr streams - """ - if self.encoding: - data = data.decode(self.encoding, 'replace') - return data - - def _handle_stdout(self, data): - if self._stdout: - self._stdout.write(self._decode(data)) - - def _handle_stderr(self, data): - if self._stderr: - self._stderr.write(self._decode(data)) - - def _setup_handle(self): - """Setup handle for output, if any""" - self.handle = (self._stdout, self._stderr) - - def _finish_handle(self): - """Finish handle, if anything should be done when it's all wrapped up.""" - pass - - def __enter__(self): - # flush anything out before starting - libc.fflush(c_stdout_p) - libc.fflush(c_stderr_p) - # setup handle - self._setup_handle() - - # create pipe for stdout - pipes = [] - names = {} - if self._stdout: - pipe = self._setup_pipe('stdout') - pipes.append(pipe) - names[pipe] = 'stdout' - if self._stderr: - pipe = self._setup_pipe('stderr') - pipes.append(pipe) - names[pipe] = 'stderr' - - def forwarder(): - """Forward bytes on a pipe to stream messages""" - while True: - # flush libc's buffers before calling select - # See Calysto/metakernel#5: flushing sometimes blocks. - # libc.fflush(c_stdout_p) - # libc.fflush(c_stderr_p) - r, w, x = select.select(pipes, [], [], self.flush_interval) - if not r: - # nothing to read, next iteration will flush and check again - continue - for pipe in r: - name = names[pipe] - data = os.read(pipe, 1024) - if not data: - # pipe closed, stop polling - pipes.remove(pipe) - else: - handler = getattr(self, '_handle_%s' % name) - handler(data) - if not pipes: - # pipes closed, we are done - break - self.thread = threading.Thread(target=forwarder) - self.thread.daemon = True - self.thread.start() - - return self.handle - - def __exit__(self, exc_type, exc_value, traceback): - # flush the underlying C buffers - libc.fflush(c_stdout_p) - libc.fflush(c_stderr_p) - # close FDs, signaling output is complete - for real_fd in self._real_fds.values(): - os.close(real_fd) - self.thread.join() - - # restore original state - for name, real_fd in self._real_fds.items(): - save_fd = self._save_fds[name] - os.dup2(save_fd, real_fd) - os.close(save_fd) - # finalize handle - self._finish_handle() diff --git a/setup.py b/setup.py index ca5b809..a0390b9 100644 --- a/setup.py +++ b/setup.py @@ -39,5 +39,6 @@ "ipython (>=4.0.0)"], install_requires=["metakernel>=0.20.8", "jupyter_client >=4.4.0", "ipython>=4.0.0", - "backports.tempfile;python_version<'3.0'"] + "backports.tempfile;python_version<'3.0'", + "wurlitzer>=1.0.2"] ) From a3ce18e58048680473145cf66e5637bfae0ded9f Mon Sep 17 00:00:00 2001 From: jayendra Date: Fri, 30 Nov 2018 12:00:18 +0530 Subject: [PATCH 53/88] removed unused import for os --- test_matlab_kernel.py | 1 - 1 file changed, 1 deletion(-) diff --git a/test_matlab_kernel.py b/test_matlab_kernel.py index fbd2e75..5100596 100644 --- a/test_matlab_kernel.py +++ b/test_matlab_kernel.py @@ -2,7 +2,6 @@ import unittest from jupyter_kernel_test import KernelTests -import os class MatlabKernelTests(KernelTests): From c470e825fe176be6bf980723d4af04b9f4c2c61b Mon Sep 17 00:00:00 2001 From: Steven Silvester Date: Fri, 30 Nov 2018 08:43:36 -0600 Subject: [PATCH 54/88] Release 0.16.0 --- matlab_kernel/__init__.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/matlab_kernel/__init__.py b/matlab_kernel/__init__.py index b51ee90..dbb982e 100644 --- a/matlab_kernel/__init__.py +++ b/matlab_kernel/__init__.py @@ -1,3 +1,3 @@ """A Matlab kernel for Jupyter""" -__version__ = '0.15.2' +__version__ = '0.16.0' From 5b0f4ae64cc0e2f428749a23a27b2ed3064f3b13 Mon Sep 17 00:00:00 2001 From: Steven Silvester Date: Fri, 30 Nov 2018 14:53:57 -0600 Subject: [PATCH 55/88] Fix windows support --- matlab_kernel/__init__.py | 2 +- matlab_kernel/kernel.py | 13 ++++++++++--- setup.py | 2 +- 3 files changed, 12 insertions(+), 5 deletions(-) diff --git a/matlab_kernel/__init__.py b/matlab_kernel/__init__.py index dbb982e..8cf09e0 100644 --- a/matlab_kernel/__init__.py +++ b/matlab_kernel/__init__.py @@ -1,3 +1,3 @@ """A Matlab kernel for Jupyter""" -__version__ = '0.16.0' +__version__ = '0.16.1' diff --git a/matlab_kernel/kernel.py b/matlab_kernel/kernel.py index d220dfc..b3c6013 100644 --- a/matlab_kernel/kernel.py +++ b/matlab_kernel/kernel.py @@ -18,7 +18,11 @@ from IPython.display import Image from metakernel import MetaKernel, ExceptionWrapper -from wurlitzer import pipes + +try: + from wurlitzer import pipes +except Exception: + pipes = None from . import __version__ @@ -84,7 +88,10 @@ def do_execute_direct(self, code): self._matlab.get(0., "defaultfigureposition")[0][2:]) self.handle_plot_settings() - retval = self._execute_async(code) + if pipes: + retval = self._execute_async(code) + else: + retval = self._execute_sync(code) settings = self._validated_plot_settings if settings["backend"] == "inline": @@ -229,7 +236,7 @@ def restart_kernel(self): # This isn't a true restart self._matlab = None # disconnect from engine self._matlab = matlab.engine.connect_matlab() # re-connect - self._matlab.clear('all') # clear all content + self._matlab.clear('all') # clear all content self._first = True def do_shutdown(self, restart): diff --git a/setup.py b/setup.py index a0390b9..313419f 100644 --- a/setup.py +++ b/setup.py @@ -40,5 +40,5 @@ install_requires=["metakernel>=0.20.8", "jupyter_client >=4.4.0", "ipython>=4.0.0", "backports.tempfile;python_version<'3.0'", - "wurlitzer>=1.0.2"] + 'wurlitzer>=1.0.2;platform_system!="Windows"'] ) From 5b33f36060e438b434556e3e0f0a8aef4d3f5d38 Mon Sep 17 00:00:00 2001 From: Steven Silvester Date: Tue, 2 Apr 2019 10:44:16 -0500 Subject: [PATCH 56/88] Fix py37 syntax --- matlab_kernel/kernel.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/matlab_kernel/kernel.py b/matlab_kernel/kernel.py index b3c6013..dcfdad5 100644 --- a/matlab_kernel/kernel.py +++ b/matlab_kernel/kernel.py @@ -247,7 +247,8 @@ def _execute_async(self, code): try: with pipes(stdout=_PseudoStream(partial(self.Print, end="")), stderr=_PseudoStream(partial(self.Error, end=""))): - future = self._matlab.eval(code, nargout=0, async=True) + kwargs = { 'nargout': 0, 'async': True } + future = self._matlab.eval(code, **kwargs) future.result() except (SyntaxError, MatlabExecutionError, KeyboardInterrupt) as exc: stdout = exc.args[0] From 7828a07c1126c91d0bfe220f102b61760603a164 Mon Sep 17 00:00:00 2001 From: Steven Silvester Date: Tue, 2 Apr 2019 10:47:42 -0500 Subject: [PATCH 57/88] Release 0.16.2 --- matlab_kernel/__init__.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/matlab_kernel/__init__.py b/matlab_kernel/__init__.py index 8cf09e0..b82676c 100644 --- a/matlab_kernel/__init__.py +++ b/matlab_kernel/__init__.py @@ -1,3 +1,3 @@ """A Matlab kernel for Jupyter""" -__version__ = '0.16.1' +__version__ = '0.16.2' From 98295f52498328d0ac98a783dd8fe08b8baf8869 Mon Sep 17 00:00:00 2001 From: Steven Silvester Date: Fri, 3 May 2019 07:35:56 -0500 Subject: [PATCH 58/88] Add a check file --- README.rst | 30 +++++++++++++++++++++++------- matlab_kernel/check.py | 19 +++++++++++++++++++ 2 files changed, 42 insertions(+), 7 deletions(-) create mode 100644 matlab_kernel/check.py diff --git a/README.rst b/README.rst index 5b7bffc..036636e 100644 --- a/README.rst +++ b/README.rst @@ -2,10 +2,13 @@ A Matlab kernel for Jupyter =========================== -Prerequisites: Install `Jupyter Notebook `_ and the +Prerequisites +------------- +Install `Jupyter Notebook `_ and the `Matlab engine for Python `_. -To install:: +Installation +------------ $ pip install matlab_kernel # or `pip install git+https://github.com/Calysto/matlab_kernel` @@ -17,12 +20,24 @@ To use it, run one of:: # In the notebook interface, select Matlab from the 'New' menu $ jupyter qtconsole --kernel matlab $ jupyter console --kernel matlab - + To remove from kernel listings:: $ jupyter kernelspec remove matlab - -Additional information:: + + +Troubleshooting +--------------- +If the kernel is not starting, try running the following from a terminal. + +.. code + python -m matlab_kernel.check + +Please include that output if opening an issue. + + +Additional information +---------------------- The Matlab kernel is based on `MetaKernel `_, which means it features a standard set of magics. @@ -35,11 +50,12 @@ open figures to image files whose format and resolution are defined using the use ``%plot native`` to raise normal Matlab windows instead. -Advanced Installation Notes:: +Advanced Installation Notes +--------------------------- We automatically install a Jupyter kernelspec when installing the python package. This location can be found using ``jupyter kernelspec list``. If the default location is not desired, you can remove the directory for the octave kernel, and install using python -m matlab_kernel install. See python -m matlab_kernel install --help for available options. .. _online: http://nbviewer.ipython.org/github/Calysto/matlab_kernel/blob/master/matlab_kernel.ipynb -It has been reported that Matlab version 2016b works fine. However, Matlab 2014b does not work with Python 3.5. +It has been reported that Matlab version 2016b works fine. However, Matlab 2014b does not work with Python 3.5. diff --git a/matlab_kernel/check.py b/matlab_kernel/check.py new file mode 100644 index 0000000..8dc513f --- /dev/null +++ b/matlab_kernel/check.py @@ -0,0 +1,19 @@ +import sys +from metakernel import __version__ as mversion +from . import __version__ +from .kernel import MatlabKernel + + +if __name__ == "__main__": + print('Matlab kernel v%s' % __version__) + print('Metakernel v%s' % mversion) + print('Python v%s' % sys.version) + print('Python path: %s' % sys.executable) + print('\nConnecting to Matlab...') + try: + m = MatlabKernel() + m.makeWrapper() + print('Matlab connection established') + print(o.banner) + except Exception as e: + print(e) From 3b29e77b499b4b0e1bdc680ce48cc23336a1efca Mon Sep 17 00:00:00 2001 From: Steven Silvester Date: Fri, 3 May 2019 07:38:04 -0500 Subject: [PATCH 59/88] cleanup --- matlab_kernel/check.py | 1 - 1 file changed, 1 deletion(-) diff --git a/matlab_kernel/check.py b/matlab_kernel/check.py index 8dc513f..1a1f2d0 100644 --- a/matlab_kernel/check.py +++ b/matlab_kernel/check.py @@ -12,7 +12,6 @@ print('\nConnecting to Matlab...') try: m = MatlabKernel() - m.makeWrapper() print('Matlab connection established') print(o.banner) except Exception as e: From 0a0a4d5502d98b359dbd0ca45ed00c6d048b18a2 Mon Sep 17 00:00:00 2001 From: Steven Silvester Date: Fri, 3 May 2019 07:41:09 -0500 Subject: [PATCH 60/88] Release 0.16.3 --- README.rst | 3 ++- matlab_kernel/__init__.py | 2 +- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/README.rst b/README.rst index 036636e..b6b503a 100644 --- a/README.rst +++ b/README.rst @@ -40,7 +40,8 @@ Additional information ---------------------- The Matlab kernel is based on `MetaKernel `_, -which means it features a standard set of magics. +which means it features a standard set of magics. For a full list of magics, +run ``%lsmagic`` in a cell. A sample notebook is available online_. diff --git a/matlab_kernel/__init__.py b/matlab_kernel/__init__.py index b82676c..153a0e7 100644 --- a/matlab_kernel/__init__.py +++ b/matlab_kernel/__init__.py @@ -1,3 +1,3 @@ """A Matlab kernel for Jupyter""" -__version__ = '0.16.2' +__version__ = '0.16.3' From 3ce32943831a9ea7859d0b41dbdd20929c0e095c Mon Sep 17 00:00:00 2001 From: Steven Silvester Date: Fri, 10 May 2019 03:05:58 -0500 Subject: [PATCH 61/88] update readme --- README.rst | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/README.rst b/README.rst index b6b503a..f814c03 100644 --- a/README.rst +++ b/README.rst @@ -28,6 +28,9 @@ To remove from kernel listings:: Troubleshooting --------------- + +Kernel Times Out While Starting +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ If the kernel is not starting, try running the following from a terminal. .. code @@ -36,6 +39,23 @@ If the kernel is not starting, try running the following from a terminal. Please include that output if opening an issue. +Kernel is Not Listed +~~~~~~~~~~~~~~~~~~~~ +If the kernel is not listed as an available kernel, first try the following command: + +.. code:: shell + + python -m matlab_kernel install --user + +If the kernel is still not listed, verify that the following point to the same +version of python: + +.. code:: shell + + which python # use "where" if using cmd.exe + which jupyter + + Additional information ---------------------- From 83187a7b5791c99300055a322b003c9f8c5d100b Mon Sep 17 00:00:00 2001 From: Steven Silvester Date: Fri, 10 May 2019 06:52:58 -0500 Subject: [PATCH 62/88] readme cleanup --- README.rst | 13 ++++++++----- 1 file changed, 8 insertions(+), 5 deletions(-) diff --git a/README.rst b/README.rst index f814c03..4ca3f64 100644 --- a/README.rst +++ b/README.rst @@ -10,11 +10,13 @@ Install `Jupyter Notebook Date: Sat, 11 May 2019 07:46:06 -0500 Subject: [PATCH 63/88] Release 0.16.4 --- README.rst | 13 +++++++++++++ matlab_kernel/__init__.py | 2 +- matlab_kernel/kernel.py | 1 + setup.py | 4 ++-- 4 files changed, 17 insertions(+), 3 deletions(-) diff --git a/README.rst b/README.rst index 4ca3f64..41442c4 100644 --- a/README.rst +++ b/README.rst @@ -28,6 +28,19 @@ To remove from kernel listings:: $ jupyter kernelspec remove matlab +Configuration +------------- +The kernel can be configured by adding an ``matlab_kernel_config.py`` file to the +``jupyter`` config path. The ``MatlabKernel`` class offers ``plot_settings`` as a configurable traits. +The available plot settings are: +'format', 'backend', 'width', 'height', and 'resolution'. + +.. code:: bash + + cat ~/.jupyter/matlab_kernel_config.py + c.MatlabKernel.plot_settings = dict(format='svg') + + Troubleshooting --------------- diff --git a/matlab_kernel/__init__.py b/matlab_kernel/__init__.py index 153a0e7..4d1bb4c 100644 --- a/matlab_kernel/__init__.py +++ b/matlab_kernel/__init__.py @@ -1,3 +1,3 @@ """A Matlab kernel for Jupyter""" -__version__ = '0.16.3' +__version__ = '0.16.4' diff --git a/matlab_kernel/kernel.py b/matlab_kernel/kernel.py index dcfdad5..9e265e3 100644 --- a/matlab_kernel/kernel.py +++ b/matlab_kernel/kernel.py @@ -44,6 +44,7 @@ def get_kernel_json(): class MatlabKernel(MetaKernel): + app_name = 'matlab_kernel' implementation = "Matlab Kernel" implementation_version = __version__, language = "matlab" diff --git a/setup.py b/setup.py index 313419f..0647318 100644 --- a/setup.py +++ b/setup.py @@ -35,9 +35,9 @@ package_data=PACKAGE_DATA, include_package_data=True, data_files=DATA_FILES, - requires=["metakernel (>0.20.8)", "jupyter_client (>=4.4.0)", + requires=["metakernel (>0.23.0)", "jupyter_client (>=4.4.0)", "ipython (>=4.0.0)"], - install_requires=["metakernel>=0.20.8", "jupyter_client >=4.4.0", + install_requires=["metakernel>=0.23.0", "jupyter_client >=4.4.0", "ipython>=4.0.0", "backports.tempfile;python_version<'3.0'", 'wurlitzer>=1.0.2;platform_system!="Windows"'] From 0e39230874115685ffdd73e5d04a1c52a958ef80 Mon Sep 17 00:00:00 2001 From: Steven Silvester Date: Wed, 15 May 2019 05:31:02 -0500 Subject: [PATCH 64/88] lazily use the matlab engine --- matlab_kernel/kernel.py | 30 ++++++++++++++---------------- 1 file changed, 14 insertions(+), 16 deletions(-) diff --git a/matlab_kernel/kernel.py b/matlab_kernel/kernel.py index 9e265e3..836b8f0 100644 --- a/matlab_kernel/kernel.py +++ b/matlab_kernel/kernel.py @@ -60,35 +60,34 @@ class MatlabKernel(MetaKernel): } kernel_json = get_kernel_json() - def __init__(self, *args, **kwargs): - super(MatlabKernel, self).__init__(*args, **kwargs) + def get_usage(self): + return "This is the Matlab kernel." + + @property + def _matlab(self): + if self.__matlab: + return self.__matlab + if matlab is None: raise ImportError(""" Matlab engine not installed: See https://www.mathworks.com/help/matlab/matlab-engine-for-python.htm """) try: - self._matlab = matlab.engine.start_matlab() + self.__matlab = matlab.engine.start_matlab() except matlab.engine.EngineError: - self._matlab = matlab.engine.connect_matlab() - self._first = True + self.__matlab = matlab.engine.connect_matlab() self._validated_plot_settings = { "backend": "inline", "size": (560, 420), "format": "png", "resolution": 96, } - - def get_usage(self): - return "This is the Matlab kernel." + self._validated_plot_settings["size"] = tuple( + self._matlab.get(0., "defaultfigureposition")[0][2:]) + self.handle_plot_settings() def do_execute_direct(self, code): - if self._first: - self._first = False - self._validated_plot_settings["size"] = tuple( - self._matlab.get(0., "defaultfigureposition")[0][2:]) - self.handle_plot_settings() - if pipes: retval = self._execute_async(code) else: @@ -152,7 +151,6 @@ def get_completions(self, info): # engine are ignored. # R2013a (not supported due to lack of Python engine): # mtFindAllTabCompletions(String substring, int offset [optional]) - name = info["obj"] compls = self._matlab.eval( "cell(com.mathworks.jmi.MatlabMCR()." @@ -238,7 +236,7 @@ def restart_kernel(self): self._matlab = None # disconnect from engine self._matlab = matlab.engine.connect_matlab() # re-connect self._matlab.clear('all') # clear all content - self._first = True + self.__matlab = None def do_shutdown(self, restart): self._matlab.exit() From fbdb3dd1194ecdc7c42f7febf4d01bef9fc400fb Mon Sep 17 00:00:00 2001 From: Steven Silvester Date: Fri, 31 May 2019 06:54:43 -0500 Subject: [PATCH 65/88] fix #122 --- matlab_kernel/__init__.py | 2 +- matlab_kernel/kernel.py | 4 ++++ 2 files changed, 5 insertions(+), 1 deletion(-) diff --git a/matlab_kernel/__init__.py b/matlab_kernel/__init__.py index 4d1bb4c..75f0f94 100644 --- a/matlab_kernel/__init__.py +++ b/matlab_kernel/__init__.py @@ -1,3 +1,3 @@ """A Matlab kernel for Jupyter""" -__version__ = '0.16.4' +__version__ = '0.16.5' diff --git a/matlab_kernel/kernel.py b/matlab_kernel/kernel.py index 836b8f0..dedf455 100644 --- a/matlab_kernel/kernel.py +++ b/matlab_kernel/kernel.py @@ -60,6 +60,10 @@ class MatlabKernel(MetaKernel): } kernel_json = get_kernel_json() + def __init__(self, *args, **kwargs): + super(MatlabKernel, self).__init__(*args, **kwargs) + self.__matlab = None + def get_usage(self): return "This is the Matlab kernel." From 744425ea70b795674e42dbce6c733bfdec033115 Mon Sep 17 00:00:00 2001 From: Steven Silvester Date: Sun, 2 Jun 2019 04:04:36 -0500 Subject: [PATCH 66/88] Release 0.16.6 --- matlab_kernel/__init__.py | 2 +- matlab_kernel/check.py | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/matlab_kernel/__init__.py b/matlab_kernel/__init__.py index 75f0f94..1a437c9 100644 --- a/matlab_kernel/__init__.py +++ b/matlab_kernel/__init__.py @@ -1,3 +1,3 @@ """A Matlab kernel for Jupyter""" -__version__ = '0.16.5' +__version__ = '0.16.6' diff --git a/matlab_kernel/check.py b/matlab_kernel/check.py index 1a1f2d0..0a9a0ab 100644 --- a/matlab_kernel/check.py +++ b/matlab_kernel/check.py @@ -13,6 +13,6 @@ try: m = MatlabKernel() print('Matlab connection established') - print(o.banner) + print(m.banner) except Exception as e: print(e) From d529ce233a1bd57a60a98961204cc2a9cff63bc4 Mon Sep 17 00:00:00 2001 From: Steven Silvester Date: Sun, 2 Jun 2019 04:07:22 -0500 Subject: [PATCH 67/88] add long_description_content_type --- setup.py | 1 + 1 file changed, 1 insertion(+) diff --git a/setup.py b/setup.py index 0647318..4ee9581 100644 --- a/setup.py +++ b/setup.py @@ -26,6 +26,7 @@ url="https://github.com/Calysto/matlab_kernel", license="BSD", long_description=open("README.rst").read(), + long_description_content_type='text/x-rst', classifiers=["Framework :: IPython", "License :: OSI Approved :: BSD License", "Programming Language :: Python :: 3.4", From 13d76fb898527be8b051f4aa3522d351a90e042b Mon Sep 17 00:00:00 2001 From: Andras Retzler Date: Mon, 10 Jun 2019 13:30:19 +0200 Subject: [PATCH 68/88] Fix issue #121 and #123 --- matlab_kernel/kernel.py | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/matlab_kernel/kernel.py b/matlab_kernel/kernel.py index dedf455..ebda495 100644 --- a/matlab_kernel/kernel.py +++ b/matlab_kernel/kernel.py @@ -90,6 +90,7 @@ def _matlab(self): self._validated_plot_settings["size"] = tuple( self._matlab.get(0., "defaultfigureposition")[0][2:]) self.handle_plot_settings() + return self.__matlab def do_execute_direct(self, code): if pipes: @@ -248,14 +249,15 @@ def do_shutdown(self, restart): def _execute_async(self, code): try: - with pipes(stdout=_PseudoStream(partial(self.Print, end="")), - stderr=_PseudoStream(partial(self.Error, end=""))): + with pipes(stdout=_PseudoStream(partial(self.Print, sep="", end="")), + stderr=_PseudoStream(partial(self.Error, sep="", end=""))): kwargs = { 'nargout': 0, 'async': True } future = self._matlab.eval(code, **kwargs) future.result() except (SyntaxError, MatlabExecutionError, KeyboardInterrupt) as exc: - stdout = exc.args[0] - return ExceptionWrapper("Error", -1, stdout) + pass + #stdout = exc.args[0] + #return ExceptionWrapper("Error", "-1", stdout) def _execute_sync(self, code): out = StringIO() @@ -267,7 +269,7 @@ def _execute_sync(self, code): except (SyntaxError, MatlabExecutionError) as exc: stdout = exc.args[0] self.Error(stdout) - return ExceptionWrapper("Error", -1, stdout) + return ExceptionWrapper("Error", "-1", stdout) stdout = out.getvalue() self.Print(stdout) From 954619ca3ac4825408342343cd9b03408d404fc9 Mon Sep 17 00:00:00 2001 From: Andras Retzler Date: Mon, 10 Jun 2019 13:43:24 +0200 Subject: [PATCH 69/88] sep="" is not needed to fix Calysto#121, so we undo it --- matlab_kernel/kernel.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/matlab_kernel/kernel.py b/matlab_kernel/kernel.py index ebda495..3a5958a 100644 --- a/matlab_kernel/kernel.py +++ b/matlab_kernel/kernel.py @@ -249,8 +249,8 @@ def do_shutdown(self, restart): def _execute_async(self, code): try: - with pipes(stdout=_PseudoStream(partial(self.Print, sep="", end="")), - stderr=_PseudoStream(partial(self.Error, sep="", end=""))): + with pipes(stdout=_PseudoStream(partial(self.Print, end="")), + stderr=_PseudoStream(partial(self.Error, end=""))): kwargs = { 'nargout': 0, 'async': True } future = self._matlab.eval(code, **kwargs) future.result() From 865dfa65edbe8790ebde0eab8332a252b6032065 Mon Sep 17 00:00:00 2001 From: Andras Retzler Date: Mon, 10 Jun 2019 13:54:11 +0200 Subject: [PATCH 70/88] undo "-1" --- matlab_kernel/kernel.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/matlab_kernel/kernel.py b/matlab_kernel/kernel.py index 3a5958a..33e8466 100644 --- a/matlab_kernel/kernel.py +++ b/matlab_kernel/kernel.py @@ -257,7 +257,7 @@ def _execute_async(self, code): except (SyntaxError, MatlabExecutionError, KeyboardInterrupt) as exc: pass #stdout = exc.args[0] - #return ExceptionWrapper("Error", "-1", stdout) + #return ExceptionWrapper("Error", -1, stdout) def _execute_sync(self, code): out = StringIO() @@ -269,7 +269,7 @@ def _execute_sync(self, code): except (SyntaxError, MatlabExecutionError) as exc: stdout = exc.args[0] self.Error(stdout) - return ExceptionWrapper("Error", "-1", stdout) + return ExceptionWrapper("Error", -1, stdout) stdout = out.getvalue() self.Print(stdout) From d8ac7d8444527d093a712bba8f7c481f7ca33795 Mon Sep 17 00:00:00 2001 From: Steven Silvester Date: Wed, 12 Jun 2019 04:51:12 -0500 Subject: [PATCH 71/88] Release 0.16.7 --- matlab_kernel/__init__.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/matlab_kernel/__init__.py b/matlab_kernel/__init__.py index 1a437c9..cfa3620 100644 --- a/matlab_kernel/__init__.py +++ b/matlab_kernel/__init__.py @@ -1,3 +1,3 @@ """A Matlab kernel for Jupyter""" -__version__ = '0.16.6' +__version__ = '0.16.7' From 7cba49c14f5c33ce3d76cce923ea42c4257d15a9 Mon Sep 17 00:00:00 2001 From: Steven Silvester Date: Sat, 10 Aug 2019 16:46:33 -0500 Subject: [PATCH 72/88] fix readme rendering --- README.rst | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/README.rst b/README.rst index 41442c4..912fcbf 100644 --- a/README.rst +++ b/README.rst @@ -48,7 +48,8 @@ Kernel Times Out While Starting ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ If the kernel is not starting, try running the following from a terminal. -.. code +.. code::shell + python -m matlab_kernel.check Please include that output if opening an issue. From 83bc70da9438cb7c4f8bb7ccd7a4b6557570ef60 Mon Sep 17 00:00:00 2001 From: Steven Silvester Date: Sat, 10 Aug 2019 16:46:58 -0500 Subject: [PATCH 73/88] fix readme rendering --- README.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.rst b/README.rst index 912fcbf..4205bee 100644 --- a/README.rst +++ b/README.rst @@ -48,7 +48,7 @@ Kernel Times Out While Starting ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ If the kernel is not starting, try running the following from a terminal. -.. code::shell +.. code:: shell python -m matlab_kernel.check From c7d81782f7077a7e322048abc3a103339aec38cf Mon Sep 17 00:00:00 2001 From: Steven Silvester Date: Tue, 3 Mar 2020 11:03:58 -0600 Subject: [PATCH 74/88] Update check to use matlab engine --- .travis.yml | 1 + matlab_kernel/check.py | 1 + matlab_kernel/kernel.py | 2 ++ 3 files changed, 4 insertions(+) diff --git a/.travis.yml b/.travis.yml index ccaefff..426f99b 100644 --- a/.travis.yml +++ b/.travis.yml @@ -7,3 +7,4 @@ install: script: - make test - python -m matlab_kernel install --user + - python -m matlab_kernel.check diff --git a/matlab_kernel/check.py b/matlab_kernel/check.py index 0a9a0ab..aea0722 100644 --- a/matlab_kernel/check.py +++ b/matlab_kernel/check.py @@ -14,5 +14,6 @@ m = MatlabKernel() print('Matlab connection established') print(m.banner) + print(m.do_execute_direct('disp("hi from Matlab!")')) except Exception as e: print(e) diff --git a/matlab_kernel/kernel.py b/matlab_kernel/kernel.py index 33e8466..296a3f9 100644 --- a/matlab_kernel/kernel.py +++ b/matlab_kernel/kernel.py @@ -3,6 +3,8 @@ from matlab.engine import MatlabExecutionError except ImportError: matlab = None + class MatlabExecutionError(Exception): + pass from functools import partial try: from StringIO import StringIO From b69b445ab8089c5e006f5a807dbc727aac0c36cd Mon Sep 17 00:00:00 2001 From: Steven Silvester Date: Tue, 3 Mar 2020 11:11:01 -0600 Subject: [PATCH 75/88] Release 0.16.8 --- matlab_kernel/__init__.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/matlab_kernel/__init__.py b/matlab_kernel/__init__.py index cfa3620..a68c7b6 100644 --- a/matlab_kernel/__init__.py +++ b/matlab_kernel/__init__.py @@ -1,3 +1,3 @@ """A Matlab kernel for Jupyter""" -__version__ = '0.16.7' +__version__ = '0.16.8' From f439f962dcccd72f99c8ed93a75a90f74d366b97 Mon Sep 17 00:00:00 2001 From: Steven Silvester Date: Fri, 13 Mar 2020 16:18:33 -0500 Subject: [PATCH 76/88] Add development notes --- README.rst | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/README.rst b/README.rst index 4205bee..a36a4cd 100644 --- a/README.rst +++ b/README.rst @@ -97,3 +97,13 @@ It has been reported that Matlab version 2016b works fine. However, Matlab 2014b .. _online: http://nbviewer.ipython.org/github/Calysto/matlab_kernel/blob/master/matlab_kernel.ipynb +Development +~~~~~~~~~~~ + +Install the package locally:: + + $ pip install -e . + $ python -m matlab_kernel install + +As you make changes, test them in a notebook (restart the kernel between changes). + From bdf0c4b160419c45d9d6300eefa6333d78e27827 Mon Sep 17 00:00:00 2001 From: Marc Vaillant Date: Fri, 3 Apr 2020 10:35:52 -0400 Subject: [PATCH 77/88] Fix for the figure order issue #134, copied from @robjhornby --- matlab_kernel/kernel.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/matlab_kernel/kernel.py b/matlab_kernel/kernel.py index 296a3f9..90b61ea 100644 --- a/matlab_kernel/kernel.py +++ b/matlab_kernel/kernel.py @@ -108,8 +108,8 @@ def do_execute_direct(self, code): try: self._matlab.eval( "arrayfun(" - "@(h, i) print(h, sprintf('{}/%i', i), '-d{}', '-r{}')," - "get(0, 'children'), (1:{})')".format( + "@(h, i) print(h, sprintf('{}/%06i', i), '-d{}', '-r{}')," + "get(0, 'children'), ({}:-1:1)')".format( '/'.join(tmpdir.split(os.sep)), settings["format"], settings["resolution"], From ab41f9bea94eb909578ddf06fb08891952dd69ab Mon Sep 17 00:00:00 2001 From: Steven Silvester Date: Tue, 7 Apr 2020 03:59:42 -0500 Subject: [PATCH 78/88] Release 0.16.9 --- matlab_kernel/__init__.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/matlab_kernel/__init__.py b/matlab_kernel/__init__.py index a68c7b6..0cb8acb 100644 --- a/matlab_kernel/__init__.py +++ b/matlab_kernel/__init__.py @@ -1,3 +1,3 @@ """A Matlab kernel for Jupyter""" -__version__ = '0.16.8' +__version__ = '0.16.9' From be8ac96d76492fb92ef4cc7633b64bf943810fcc Mon Sep 17 00:00:00 2001 From: Davide Cester Date: Wed, 21 Oct 2020 10:40:51 +0200 Subject: [PATCH 79/88] FIX: issue #146 (No output in Matlab 2020b) --- matlab_kernel/kernel.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/matlab_kernel/kernel.py b/matlab_kernel/kernel.py index 90b61ea..7832e68 100644 --- a/matlab_kernel/kernel.py +++ b/matlab_kernel/kernel.py @@ -253,7 +253,7 @@ def _execute_async(self, code): try: with pipes(stdout=_PseudoStream(partial(self.Print, end="")), stderr=_PseudoStream(partial(self.Error, end=""))): - kwargs = { 'nargout': 0, 'async': True } + kwargs = { 'nargout': 0, 'background': True } future = self._matlab.eval(code, **kwargs) future.result() except (SyntaxError, MatlabExecutionError, KeyboardInterrupt) as exc: From 0ee1bfd41760f7eb8a5348c41e35d362fc9aa152 Mon Sep 17 00:00:00 2001 From: Davide Cester Date: Sun, 1 Nov 2020 19:42:25 +0100 Subject: [PATCH 80/88] FIX: issue #146, back-comp for Matlab <= R2017a --- matlab_kernel/kernel.py | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/matlab_kernel/kernel.py b/matlab_kernel/kernel.py index 7832e68..7f4b22f 100644 --- a/matlab_kernel/kernel.py +++ b/matlab_kernel/kernel.py @@ -83,6 +83,14 @@ def _matlab(self): self.__matlab = matlab.engine.start_matlab() except matlab.engine.EngineError: self.__matlab = matlab.engine.connect_matlab() + # detecting the correct kwargs for async running + # matlab 'async' param is deprecated since it became a keyword in python 3.7 + # instead, 'background' param is available and recommended since Matlab R2017b + self._async_kwargs = {'nargout': 0, 'async': True} + try: + self._matlab.eval('version', **self._async_kwargs) + except SyntaxError: + self._async_kwargs = {'nargout': 0, 'background': True} self._validated_plot_settings = { "backend": "inline", "size": (560, 420), @@ -253,8 +261,7 @@ def _execute_async(self, code): try: with pipes(stdout=_PseudoStream(partial(self.Print, end="")), stderr=_PseudoStream(partial(self.Error, end=""))): - kwargs = { 'nargout': 0, 'background': True } - future = self._matlab.eval(code, **kwargs) + future = self._matlab.eval(code, **self._async_kwargs) future.result() except (SyntaxError, MatlabExecutionError, KeyboardInterrupt) as exc: pass From 2ae3b3b4fcacf63367e0303a00821868c44fde23 Mon Sep 17 00:00:00 2001 From: Steven Silvester Date: Mon, 2 Nov 2020 12:57:33 -0600 Subject: [PATCH 81/88] Release 0.16.10 --- matlab_kernel/__init__.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/matlab_kernel/__init__.py b/matlab_kernel/__init__.py index 0cb8acb..48d02ee 100644 --- a/matlab_kernel/__init__.py +++ b/matlab_kernel/__init__.py @@ -1,3 +1,3 @@ """A Matlab kernel for Jupyter""" -__version__ = '0.16.9' +__version__ = '0.16.10' From 071c1868cc3aa9546ef09d152d7c1f3f801987cd Mon Sep 17 00:00:00 2001 From: yuta_kudo Date: Sat, 7 Nov 2020 14:32:57 +0900 Subject: [PATCH 82/88] Add auto completion for table --- matlab_kernel/kernel.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/matlab_kernel/kernel.py b/matlab_kernel/kernel.py index 7f4b22f..836d2f5 100644 --- a/matlab_kernel/kernel.py +++ b/matlab_kernel/kernel.py @@ -174,10 +174,11 @@ def get_completions(self, info): # For structs, we need to return `structname.fieldname` instead of just # `fieldname`, which `mtFindAllTabCompletions` does. + # For tables also. if "." in name: prefix, _ = name.rsplit(".", 1) - if self._matlab.eval("isstruct({})".format(prefix)): + if self._matlab.eval("isstruct({})".format(prefix)) or self._matlab.eval("istable({})".format(prefix)): compls = ["{}.{}".format(prefix, compl) for compl in compls] return compls From 3bedbae28638f7a8feaa5ee5ace171924376bacb Mon Sep 17 00:00:00 2001 From: yuta_kudo Date: Sat, 7 Nov 2020 14:40:17 +0900 Subject: [PATCH 83/88] Add auto completion for table into kernel.py --- matlab_kernel/kernel.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/matlab_kernel/kernel.py b/matlab_kernel/kernel.py index 836d2f5..96f81c8 100644 --- a/matlab_kernel/kernel.py +++ b/matlab_kernel/kernel.py @@ -178,7 +178,7 @@ def get_completions(self, info): if "." in name: prefix, _ = name.rsplit(".", 1) - if self._matlab.eval("isstruct({})".format(prefix)) or self._matlab.eval("istable({})".format(prefix)): + if self._matlab.eval("isstruct({})".format(prefix)) | self._matlab.eval("istable({})".format(prefix)): compls = ["{}.{}".format(prefix, compl) for compl in compls] return compls From 1bc5c7677736b766c853898e70ab852c90c88ba6 Mon Sep 17 00:00:00 2001 From: Steven Silvester Date: Mon, 9 Nov 2020 14:41:43 -0600 Subject: [PATCH 84/88] Release 0.16.11 --- matlab_kernel/__init__.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/matlab_kernel/__init__.py b/matlab_kernel/__init__.py index 48d02ee..a37547e 100644 --- a/matlab_kernel/__init__.py +++ b/matlab_kernel/__init__.py @@ -1,3 +1,3 @@ """A Matlab kernel for Jupyter""" -__version__ = '0.16.10' +__version__ = '0.16.11' From f5ffd70c7c6e90aef4ad98f7451345f68f29cc64 Mon Sep 17 00:00:00 2001 From: RibomBalt Date: Tue, 19 Apr 2022 23:34:23 +0800 Subject: [PATCH 85/88] add a kernel that priorly links to a existing matlab engine --- .gitignore | 2 ++ MANIFEST.in | 2 +- matlab_kernel/kernel.py | 21 +++++++++----- .../{kernel.json => kernel_template.json} | 0 setup.py | 28 ++++++++++++++++++- 5 files changed, 44 insertions(+), 9 deletions(-) rename matlab_kernel/{kernel.json => kernel_template.json} (100%) diff --git a/.gitignore b/.gitignore index a4c3223..6d29828 100644 --- a/.gitignore +++ b/.gitignore @@ -5,3 +5,5 @@ build/ dist/ *.pyc .*.swp +matlab_kernel/matlab/ +matlab_kernel/matlab_connect/ diff --git a/MANIFEST.in b/MANIFEST.in index 0317e07..2e162d9 100644 --- a/MANIFEST.in +++ b/MANIFEST.in @@ -1,4 +1,4 @@ include versioneer.py include matlab_kernel/_version.py -include matlab_kernel/kernel.json +include matlab_kernel/kernel_template.json recursive-include matlab_kernel *.png diff --git a/matlab_kernel/kernel.py b/matlab_kernel/kernel.py index 96f81c8..7065109 100644 --- a/matlab_kernel/kernel.py +++ b/matlab_kernel/kernel.py @@ -28,7 +28,7 @@ class MatlabExecutionError(Exception): from . import __version__ - +IS_CONNECT = "connect-to-existing-kernel" in os.environ.keys() class _PseudoStream: def __init__(self, writer): @@ -39,9 +39,10 @@ def get_kernel_json(): """Get the kernel json for the kernel. """ here = os.path.dirname(__file__) - with open(os.path.join(here, 'kernel.json')) as fid: + kernel_name = 'matlab_connect' if IS_CONNECT else 'matlab' + with open(os.path.join(here, kernel_name ,'kernel.json')) as fid: data = json.load(fid) - data['argv'][0] = sys.executable + # data['argv'][0] = sys.executable return data @@ -79,10 +80,16 @@ def _matlab(self): Matlab engine not installed: See https://www.mathworks.com/help/matlab/matlab-engine-for-python.htm """) - try: - self.__matlab = matlab.engine.start_matlab() - except matlab.engine.EngineError: - self.__matlab = matlab.engine.connect_matlab() + if IS_CONNECT: + try: + self.__matlab = matlab.engine.connect_matlab() + except matlab.engine.EngineError: + self.__matlab = matlab.engine.start_matlab() + else: + try: + self.__matlab = matlab.engine.start_matlab() + except matlab.engine.EngineError: + self.__matlab = matlab.engine.connect_matlab() # detecting the correct kwargs for async running # matlab 'async' param is deprecated since it became a keyword in python 3.7 # instead, 'background' param is available and recommended since Matlab R2017b diff --git a/matlab_kernel/kernel.json b/matlab_kernel/kernel_template.json similarity index 100% rename from matlab_kernel/kernel.json rename to matlab_kernel/kernel_template.json diff --git a/setup.py b/setup.py index 4ee9581..3967ba1 100644 --- a/setup.py +++ b/setup.py @@ -1,4 +1,7 @@ import glob +import json +import os +import sys from setuptools import setup, find_packages with open('matlab_kernel/__init__.py', 'rb') as fid: @@ -9,12 +12,35 @@ break DISTNAME = 'matlab_kernel' + +# generating kernel.json for both kernels +os.makedirs(os.path.join(DISTNAME, 'matlab'), exist_ok=True) +with open(os.path.join(DISTNAME, 'kernel_template.json'), 'r') as fp: + matlab_json = json.load(fp) +matlab_json['argv'][0] = sys.executable +with open(os.path.join(DISTNAME, 'matlab','kernel.json'), 'w') as fp: + json.dump(matlab_json, fp) + +os.makedirs(os.path.join(DISTNAME, 'matlab_connect'), exist_ok=True) +with open(os.path.join(DISTNAME, 'kernel_template.json'), 'r') as fp: + matlab_json = json.load(fp) +matlab_json['argv'][0] = sys.executable +matlab_json['display_name'] = 'Matlab (Connection)' +matlab_json['name'] = "matlab_connect" +matlab_json['env'] = {'connect-to-existing-kernel': '1'} +with open(os.path.join(DISTNAME, 'matlab_connect','kernel.json'), 'w') as fp: + json.dump(matlab_json, fp) + PACKAGE_DATA = { DISTNAME: ['*.m'] + glob.glob('%s/**/*.*' % DISTNAME) } DATA_FILES = [ ('share/jupyter/kernels/matlab', [ - '%s/kernel.json' % DISTNAME + '%s/matlab/kernel.json' % DISTNAME + ] + glob.glob('%s/images/*.png' % DISTNAME) + ), + ('share/jupyter/kernels/matlab_connect', [ + '%s/matlab_connect/kernel.json' % DISTNAME ] + glob.glob('%s/images/*.png' % DISTNAME) ) ] From 433723db67c75b4c3da0e08166827578a3e8bccc Mon Sep 17 00:00:00 2001 From: Steven Silvester Date: Fri, 22 Apr 2022 12:58:52 -0500 Subject: [PATCH 86/88] Release 0.17.0 --- matlab_kernel/__init__.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/matlab_kernel/__init__.py b/matlab_kernel/__init__.py index a37547e..3722fa8 100644 --- a/matlab_kernel/__init__.py +++ b/matlab_kernel/__init__.py @@ -1,3 +1,3 @@ """A Matlab kernel for Jupyter""" -__version__ = '0.16.11' +__version__ = '0.17.0' From f2b5e0f62ede8900ada3841b0a462a13dceeb23e Mon Sep 17 00:00:00 2001 From: RibomBalt Date: Sat, 7 May 2022 17:30:25 +0800 Subject: [PATCH 87/88] handle python executable when building wheels --- setup.py | 13 +++++++++++-- 1 file changed, 11 insertions(+), 2 deletions(-) diff --git a/setup.py b/setup.py index 3967ba1..452985a 100644 --- a/setup.py +++ b/setup.py @@ -12,19 +12,28 @@ break DISTNAME = 'matlab_kernel' +PY_EXECUTABLE = 'python' + +# when building wheels, directly use 'python' in the kernelspec. +if any(a.startswith("bdist") for a in sys.argv): + PY_EXECUTABLE = 'python' + +# when directly installing, use sys.executable to get python full path. +if any(a.startswith("install") for a in sys.argv): + PY_EXECUTABLE = sys.executable # generating kernel.json for both kernels os.makedirs(os.path.join(DISTNAME, 'matlab'), exist_ok=True) with open(os.path.join(DISTNAME, 'kernel_template.json'), 'r') as fp: matlab_json = json.load(fp) -matlab_json['argv'][0] = sys.executable +matlab_json['argv'][0] = PY_EXECUTABLE with open(os.path.join(DISTNAME, 'matlab','kernel.json'), 'w') as fp: json.dump(matlab_json, fp) os.makedirs(os.path.join(DISTNAME, 'matlab_connect'), exist_ok=True) with open(os.path.join(DISTNAME, 'kernel_template.json'), 'r') as fp: matlab_json = json.load(fp) -matlab_json['argv'][0] = sys.executable +matlab_json['argv'][0] = PY_EXECUTABLE matlab_json['display_name'] = 'Matlab (Connection)' matlab_json['name'] = "matlab_connect" matlab_json['env'] = {'connect-to-existing-kernel': '1'} From 3ce23d95322c703221bcd4a10ec59aaddaaf4c8c Mon Sep 17 00:00:00 2001 From: Steven Silvester Date: Mon, 9 May 2022 05:21:01 -0500 Subject: [PATCH 88/88] Release 0.17.1 --- matlab_kernel/__init__.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/matlab_kernel/__init__.py b/matlab_kernel/__init__.py index 3722fa8..eeebea6 100644 --- a/matlab_kernel/__init__.py +++ b/matlab_kernel/__init__.py @@ -1,3 +1,3 @@ """A Matlab kernel for Jupyter""" -__version__ = '0.17.0' +__version__ = '0.17.1'