Exemplo n.º 1
0
    def kernel(self, line: str):
        """Notebook kernel management.

        :param line: arguments to `%kernel` magic (see `%kernel --help`)
        :return: None
        """
        parser = MagicParser(
            prog="%kernel",
            description="""
            Install and manage Jupyter kernels.
            """,
        )
        parser.set_defaults(func=_default_kernel_handler)

        subparsers = parser.add_subparsers(dest="command")

        # command: install
        parser_install = subparsers.add_parser(
            "install", description="Install new Jupyter kernel."
        )
        parser_install.add_argument(
            "name",
            nargs="?",
            help="[optional] Kernel name, otherwise use notebook name.",
        )
        parser_install.set_defaults(func=_default_kernel_handler)

        # command: load
        parser_set = subparsers.add_parser(
            "set", description="Set existing kernel as current kernel."
        )
        parser_set.add_argument(
            "name",
            type=str,
            nargs="?",
            help="[optional] Kernel name, otherwise use notebook name.",
        )
        parser_set.set_defaults(func=_default_kernel_handler)

        opts = line.split()

        try:
            args = parser.parse_args(opts)
        except MagicParserError as exc:
            print(f"\n{exc.args[0]}", file=sys.stderr)
            return

        if any([opt in {"-h", "--help"} for opt in opts]):
            # print help and return
            return

        script, params = args.func(args)

        return executejs(script, **params)
Exemplo n.º 2
0
    def requirements(self, line: str, cell: str = None):
        """Notebook requirements management.

        Line magic: Print notebook requirements

        :param line: arguments to `%requirements` magic (see `%requiremnts --help`)
        :param cell: <empty>
        :return: None

        Cell magic: Set notebook requirements

        :param cell: Notebook requirements in Pipfile format.
        :return: None
        """
        params = dict()

        if cell is not None:
            requirements = Pipfile.from_string(cell).to_dict()

            script = """
            require(['nbrequirements'], ({cli, version}) => {
                cli('set', { requirements: $$requirements })
            })
            """
            params["requirements"] = json.dumps(requirements)

        else:
            parser = MagicParser(
                prog="%requirements",
                description="""
                Jupyter magic for managing notebook requirements.
                """,
            )
            parser.set_defaults(func=_default_requirements_handler)

            # main
            parser.add_argument(
                "-I",
                "--ignore-metadata",
                action="store_true",
                help="Whether to ignore embedded notebook metadata.",
            )
            parser.add_argument(
                "-f",
                "--from-file",
                type=argparse.FileType("r", encoding="utf-8"),
                help="Load requirements from a Pipfile.",
            )
            parser.add_argument(
                "--to-json",
                action="store_true",
                help="Whether to display output in JSON format.",
            )
            parser.add_argument(
                "--to-file",
                action="store_true",
                help="Whether to store output to file.",
            )
            parser.add_argument(
                "-w",
                "--overwrite",
                action="store_true",
                help="Whether to overwrite existing file.",
            )

            subparsers = parser.add_subparsers(dest="command")

            # command: add
            parser_add = subparsers.add_parser(
                "add",
                description=
                "Add dependency to notebook metadata without installing it.",
            )
            parser_add.add_argument(
                "-d",
                "--dev",
                action="store_true",
                help="Whether to store the dependency as dev-package.",
            )
            parser_add.add_argument("-v",
                                    "--version",
                                    type=str,
                                    default="*",
                                    help="Version constraint.")
            parser_add.add_argument(
                "-i",
                "--index",
                type=str,
                default="pypi",
                help=("Index (source name) for this dependency."
                      "NOTE: The source of that name must be present!"),
            )
            parser_add.add_argument(
                "--sync",
                action="store_true",
                help="Whether to sync notebook metadata with the Pipfile.",
            )
            parser_add.add_argument(
                "dependency",
                type=str,
                help="The dependency to be added to notebook metadata.",
            )
            parser_add.set_defaults(func=_default_requirements_handler)
            parser_add.add_argument(
                "--alias",
                type=str,
                help=("Alias of a package."
                      "This is useful if package name differs from import."))

            # command: add-source
            parser_source = subparsers.add_parser(
                "add-source",
                description="Add source index to the notebook metadata.")
            parser_source.add_argument("--name",
                                       type=str,
                                       help="Name for this index.")
            parser_source.add_argument("--url",
                                       type=str,
                                       help="URL for this index.")
            parser_source.add_argument(
                "--verify-ssl",
                type=bool,
                default=False,
                help="Whether to set verify_ssl=true",
            )
            parser_source.add_argument(
                "--sync",
                action="store_true",
                help="Whether to sync notebook metadata with the Pipfile.",
            )

            # command: lock
            parser_lock = subparsers.add_parser(
                "lock",
                add_help=False,
                parents=[parser],
                description="Lock (pin down) dependencies.",
            )
            parser_lock.add_argument(
                "--engine",
                choices=["thoth", "pipenv"],
                help="Overwrite default dependency resolution engine.",
            )
            parser_lock.add_argument(
                "-d",
                "--dev-packages",
                action="store_true",
                help=("Install both develop and default packages.\n"
                      "Only applicable when `engine='pipenv'`"),
            )
            parser_lock.add_argument(
                "--pre-releases",
                action="store_true",
                help=
                "Allow pre-releases.\nOnly applicable when `engine='pipenv'`",
            )
            parser_lock.add_argument(
                "--sync",
                action="store_true",
                help="Whether to sync notebook metadata with the Pipfile.lock.",
            )
            parser_lock.set_defaults(func=_requirements_lock)

            # command: config
            parser_config = subparsers.add_parser(
                "config",
                add_help=False,
                parents=[parser],
                description="Generate Thoth config.",
            )
            parser_config.set_defaults(func=_requirements_config)

            # command: install
            parser_install = subparsers.add_parser(
                "install",
                description=
                ("Installs provided packages and adds them to Pipfile, "
                 "or (if no packages are given), installs all packages from Pipfile.lock."
                 ),
            )
            parser_install.add_argument(
                "requirements",
                type=str,
                nargs=argparse.REMAINDER,
                help=(
                    "[optional] Packages to be installed. "
                    "If not provided, install all packages from Pipfile.lock."
                ),
            )
            parser_install.add_argument(
                "-d",
                "--dev",
                action="store_true",
                help="Install both develop and default packages.",
            )
            parser_install.add_argument("--pre",
                                        action="store_true",
                                        help="Allow pre-releases.")
            parser_install.set_defaults(func=_default_requirements_handler)

            # command: ensure
            parser_ensure = subparsers.add_parser(
                "ensure",
                description="\n".join(
                    wrap(
                        "Make sure that the notebook metadata and local files are in sync\n"
                        "with the virtual environment and the Jupyter kernel.\n\n"
                        "Ensure gets a project into a complete, reproducible, and likely compilable state.",
                        width=200,
                        replace_whitespace=False,
                    )),
                formatter_class=argparse.RawTextHelpFormatter,
            )
            parser_ensure.add_argument(
                "--engine",
                choices=["thoth", "pipenv"],
                help="Overwrite default dependency resolution engine.",
            )
            parser_ensure.add_argument(
                "-d",
                "--dev-packages",
                action="store_true",
                help=("Install both develop and default packages.\n"
                      "Only applicable when `engine='pipenv'`"),
            )
            parser_ensure.add_argument(
                "--pre-releases",
                action="store_true",
                help=
                "Allow pre-releases.\nOnly applicable when `engine='pipenv'`",
            )
            parser_ensure.add_argument(
                "-I",
                "--skip-kernel",
                action="store_true",
                help="Skip installation of the Jupyter kernel.",
            )
            parser_ensure.add_argument(
                "name",
                type=str,
                nargs="?",
                help=("[optional] Kernel name, otherwise use notebook name.\n"
                      "Only applicable when `--skip-kernel=false`."),
            )
            parser_ensure.set_defaults(func=_default_requirements_handler)

            # command: clear
            parser_clear = subparsers.add_parser(
                "clear",
                description=
                "Clear notebook requirements and locked requirements metadata.",
            )
            parser_clear.set_defaults(func=_default_requirements_handler)

            opts = line.split()

            try:
                args = parser.parse_args(opts)
            except MagicParserError as exc:
                print(f"\n{exc.args[0]}", file=sys.stderr)
                return

            if any([opt in {"-h", "--help"} for opt in opts]):
                # print help and return
                return

            script, params = args.func(args)

        return executejs(script, **params)
Exemplo n.º 3
0
    def requirements(self, line: str, cell: str = None):
        """
        Get or set notebook requirements.

        Line magic: Print notebook requirements

        :param line: arguments to `%requirements` magic (see `%%requiremnts --help`)
        :param cell: <empty>
        :return: None

        Cell magic: Set notebook requirements

        :param line: arguments to `%%requirements` magic (see `%requiremnts --help`)
        :param cell: Notebook requirements in Pipfile format.
        :return: None
        """
        params = dict()

        if cell is not None:
            requirements = Pipfile.from_string(cell).to_dict()

            script = """
            Jupyter.notebook.set_requirements($$requirements)
            """
            params["requirements"] = json.dumps(requirements)

        else:
            parser = MagicParser(
                prog="%requirements",
                description="""
                Jupyter magic for managing notebook requirements.
                """
            )
            parser.set_defaults(func=_requirements)

            # main
            parser.add_argument(
                "-I", "--ignore-metadata",
                action="store_true",
                help="Whether to ignore embedded notebook metadata."
            )
            parser.add_argument(
                "--to-json",
                action="store_true",
                help="Whether to display output in JSON format."
            )
            parser.add_argument(
                "--to-file",
                action="store_true",
                help="Whether to store output to file."
            )
            parser.add_argument(
                "-w", "--overwrite",
                action="store_true",
                help="Whether to overwrite existing file."
            )

            subparsers = parser.add_subparsers(dest="command")

            # command: lock
            parser_lock = subparsers.add_parser(
                "lock",
                add_help=False,
                parents=[parser],
                description="Lock (pin down) dependencies."
            )
            parser_lock.set_defaults(func=_requirements_lock)

            # command: config
            parser_config = subparsers.add_parser(
                "config",
                add_help=False,
                parents=[parser],
                description="Generate Thoth config."
            )
            parser_config.set_defaults(func=_requirements_config)

            # command: install
            parser_install = subparsers.add_parser(
                "install",
                description=(
                    "Installs provided packages and adds them to Pipfile, "
                    "or (if no packages are given), installs all packages from Pipfile.lock."
                )
            )
            parser_install.add_argument(
                "requirements",
                type=str,
                nargs=argparse.REMAINDER,
                help=(
                    "[optional] Packages to be installed. "
                    "If not provided, install all packages from Pipfile.lock."
                )
            )
            parser_install.add_argument(
                "-d", "--dev",
                action="store_true",
                help="Install both develop and default packages."
            )
            parser_install.add_argument(
                "--pre",
                action="store_true",
                help="Allow pre-releases."
            )
            parser_install.set_defaults(func=_requirements)

            # command: kernel
            parser_kernel = subparsers.add_parser(
                "kernel",
                description="Install and manage Jupyter kernels."
            )
            parser_kernel_subparser = parser_kernel.add_subparsers(dest="sub_command") 

            parser_kernel_install = parser_kernel_subparser.add_parser(
                "install",
                description="Install new Jupyter kernel."
            )
            parser_kernel_install.add_argument(
                "name",
                nargs="?",
                help="[optional] Kernel name, otherwise use notebook name."
            )
            
            parser_kernel_set = parser_kernel_subparser.add_parser(
                "set",
                description="Set existing kernel as current kernel."
            )
            parser_kernel_set.add_argument(
                "name",
                nargs="?",
                help="[optional] Kernel name, otherwise use notebook name."
            )
            parser_kernel.set_defaults(func=_requirements)

            opts = line.split()
            args = parser.parse_args(opts)

            if any([opt in {"-h", "--help"} for opt in opts]):
                # print help and return
                return

            script, params = args.func(args)

        return executejs(script, **params)