Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Using argparse in CLI apps. #22

Merged
merged 1 commit into from
Mar 7, 2016
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Using argparse in CLI apps.
  • Loading branch information
Martin Sandve Alnæs committed Mar 7, 2016
commit 1333a20e707ac285d2365a413d72fe34c8de1ac5
83 changes: 67 additions & 16 deletions nbdime/nbdiffapp.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@

import os
import sys
import argparse
import nbformat
import json

Expand All @@ -16,18 +17,14 @@
from .prettyprint import pretty_print_notebook_diff


_usage = """\
Compute the difference between two Jupyter notebooks.
_description = "Compute the difference between two Jupyter notebooks."

This is nbdiff from nbdime version {}.

Example usage:
def main_diff(args):
afn = args.base
bfn = args.remote
dfn = args.output

nbdiff before.ipynb after.ipynb patch.json
""".format(__version__)


def main_diff(afn, bfn, dfn=None):
for fn in (afn, bfn):
if not os.path.exists(fn):
print("Missing file {}".format(fn))
Expand Down Expand Up @@ -55,12 +52,66 @@ def main_diff(afn, bfn, dfn=None):
return 0


# TODO: Reuse these add_*_args functions across the apps
def add_generic_args(parser):
parser.add_argument('--version',
action="version",
version="%(prog)s " + __version__)
parser.add_argument('-o', '--output',
default=None,
help="the output filename.")
if 0: # TODO: Use verbose and quiet across nbdime and enable these:
qv_group = parser.add_mutually_exclusive_group()
qv_group.add_argument('-v', '--verbose',
default=False,
action="store_true",
help="increase verbosity of console output.")
qv_group.add_argument('-q', '--quiet',
default=False,
action="store_true",
help="silence console output.")

def add_webgui_args(parser):
parser.add_argument('-p', '--port',
default=8888,
type=int,
help="specify the port you want the server "
"to run on. Default is 8888.")
cwd = os.path.abspath(os.path.curdir)
parser.add_argument('-w', '--workdirectory',
default=cwd, # TODO: Are there any security implications of doing this?
help="specify the working directory you want "
"the server to run from. Default is the "
"actual cwd at program start.")

def add_diff_args(parser):
# TODO: Add diff strategy options that are reusable for the merge command here

# TODO: Define sensible strategy variables and implement
#parser.add_argument('-d', '--diff-strategy',
# default="default", choices=("foo", "bar"),
# help="specify the diff strategy to use.")
pass


def _build_arg_parser():
"""Creates an argument parser for the nbdiff command."""
parser = argparse.ArgumentParser(
description=_description,
add_help=True,
)
add_generic_args(parser)
#add_webgui_args(parser)
add_diff_args(parser)

parser.add_argument('base',
help="the base notebook file.")
parser.add_argument('remote',
help="the modified notebook file.")
return parser


def main():
args = sys.argv[1:]
if len(args) not in (2, 3):
r = 1
else:
r = main_diff(*args)
if r:
print(_usage)
args = _build_arg_parser().parse_args()
r = main_diff(args)
sys.exit(r)
54 changes: 38 additions & 16 deletions nbdime/nbmergeapp.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,23 +8,21 @@

import os
import sys
import argparse
import nbformat
from ._version import __version__
from .merging import merge_notebooks


_usage = """\
Merge two Jupyter notebooks "local" and "remote" with a common ancestor "base".
_description = 'Merge two Jupyter notebooks "local" and "remote" with a common ancestor "base".'

This is nbmerge from nbdime version {}.

Example usage:
def main_merge(args):
bfn = args.base
lfn = args.local
rfn = args.remote
mfn = args.output

nbmerge base.ipynb local.ipynb remote.ipynb merged.ipynb
""".format(__version__)


def main_merge(bfn, lfn, rfn, mfn):
for fn in (bfn, lfn, rfn):
if not os.path.exists(fn):
print("Cannot find file '{}'".format(fn))
Expand Down Expand Up @@ -66,12 +64,36 @@ def main_merge(bfn, lfn, rfn, mfn):
return 0


def _build_arg_parser():
"""Creates an argument parser for the nbdiff command."""
parser = argparse.ArgumentParser(
description=_description,
add_help=True,
)
from .nbdiffapp import add_generic_args, add_webgui_args, add_diff_args
add_generic_args(parser)
#add_webgui_args(parser)
add_diff_args(parser)

# TODO: Define sensible strategy variables and implement
#parser.add_argument('-m', '--merge-strategy',
# default="default", choices=("foo", "bar"),
# help="Specify the merge strategy to use.")
parser.add_argument('-i', '--ignore-transients',
action="store_true",
default=False,
help="Allow automatic deletion of transient data to resolve conflicts (output, execution count).")

parser.add_argument('base',
help="The base notebook filename.")
parser.add_argument('local',
help="The local modified notebook filename.")
parser.add_argument('remote',
help="The remote modified notebook filename.")
return parser


def main():
args = sys.argv[1:]
if len(args) != 4:
r = 1
else:
r = main_merge(*args)
if r:
print(_usage)
args = _build_arg_parser().parse_args()
r = main_merge(args)
sys.exit(r)
42 changes: 25 additions & 17 deletions nbdime/nbpatchapp.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,24 +8,21 @@

import os
import sys
import nbformat
import argparse
import json
import nbformat
from ._version import __version__
from .patching import patch_notebook
from .diff_format import to_diffentry_dicts

_usage = """\
Apply patch from nbpatch to a Jupyter notebook.

This is nbpatch from nbdime version {}.

Example usage:
_description = "Apply patch from nbpatch to a Jupyter notebook."

nbpatch before.ipynb patch.json after.ipynb
""".format(__version__)

def main_patch(args):
bfn = args.base
dfn = args.patch
afn = args.output

def main_patch(bfn, dfn, afn):
for fn in (bfn, dfn):
if not os.path.exists(fn):
print("Missing file {}".format(fn))
Expand All @@ -49,12 +46,23 @@ def main_patch(bfn, dfn, afn):
return 0


def _build_arg_parser():
"""Creates an argument parser for the nbpatch command."""
parser = argparse.ArgumentParser(
description=_description,
add_help=True,
)
from .nbdiffapp import add_generic_args
add_generic_args(parser)

parser.add_argument('base',
help="The base notebook filename.")
parser.add_argument('patch',
help="The patch filename, output from nbdiff.")
return parser


def main():
args = sys.argv[1:]
if len(args) != 3:
r = 1
else:
r = main_patch(*args)
if r:
print(_usage)
args = _build_arg_parser().parse_args()
r = main_patch(args)
sys.exit(r)
23 changes: 17 additions & 6 deletions nbdime/tests/test_cli_apps.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,11 @@

import pytest
import os
from argparse import Namespace

from .fixtures import filespath

import nbdime
from nbdime.nbdiffapp import main_diff
from nbdime.nbpatchapp import main_patch
from nbdime.nbmergeapp import main_merge
Expand All @@ -15,25 +17,34 @@ def test_nbdiff_app():
p = filespath()
afn = os.path.join(p, "multilevel-test-base.ipynb")
bfn = os.path.join(p, "multilevel-test-local.ipynb")

# When filename is omitted, will print to console instead
dfn = "" # os.path.join(p, "multilevel-test-local-diff.json")
assert 0 == main_diff(afn, bfn, dfn)
#dfn = "" # os.path.join(p, "multilevel-test-local-diff.json")

args = nbdime.nbdiffapp._build_arg_parser().parse_args([afn, bfn])
assert 0 == main_diff(args)


def test_nbpatch_app():
p = filespath()
bfn = os.path.join(p, "multilevel-test-base.ipynb")
dfn = os.path.join(p, "multilevel-test-base-local-diff.json")

# When filename is omitted, will print to console instead
afn = "" # os.path.join(p, "multilevel-test-base-local.ipynb")
assert 0 == main_patch(bfn, dfn, afn)
#afn = "" # os.path.join(p, "multilevel-test-base-local.ipynb")

args = nbdime.nbpatchapp._build_arg_parser().parse_args([bfn, dfn])
assert 0 == main_patch(args)


def test_nbmerge_app():
p = filespath()
bfn = os.path.join(p, "multilevel-test-base.ipynb")
lfn = os.path.join(p, "multilevel-test-local.ipynb")
rfn = os.path.join(p, "multilevel-test-remote.ipynb")

# When filename is omitted, will print to console instead
mfn = "" # os.path.join(temppath, "multilevel-test-merged.ipynb")
assert 0 == main_merge(bfn, lfn, rfn, mfn)
#mfn = "" # os.path.join(temppath, "multilevel-test-merged.ipynb")

args = nbdime.nbmergeapp._build_arg_parser().parse_args([bfn, lfn, rfn])
assert 0 == main_merge(args)