# Intended to be invoked from cmake - don't run directly.

import os
import pathlib
import setuptools
import setuptools.command.build_ext
import setuptools.command.build_py
import shutil
import subprocess
import sys

MODE = None

curpath = pathlib.Path(os.path.dirname(os.path.realpath(__file__)))
os.chdir(curpath)

libpaths = None
js_bundle_dir = None

# Create my own build_ext class, which simply copies the file to the correct
# location.
# Inspired by: https://github.com/pybind/cmake_example/blob/master/setup.py
class MyBuildExt(setuptools.command.build_ext.build_ext):
    def run(self):
        ext, = self.extensions
        assert len(libpaths) == 1, \
            'Expected exactly one shared library file but found ' \
            f'{len(libpaths)}: ' + str(libpaths)

        destpath = self.get_ext_fullpath(ext.name)
        destdir = pathlib.Path(destpath).parent
        destdir.mkdir(parents=True, exist_ok=True)
        shutil.copy(src=libpaths[0], dst=destpath)

        # Also populate 'is_nodev.py' to let the library know that this is not a
        # development environment.
        with open(destdir / 'is_nodev.py', 'wt') as f:
            f.write(
'''# This file doesn't exist in the source tree, and is generated by setup.py so
# that the croquis library can tell if it's running inside a dev environment.
pass
''')

# Copy the generated js bundle files.
# Copied from: https://digip.org/blog/2011/01/generating-data-files-in-setup.py.html
class MyBuildPy(setuptools.command.build_py.build_py):
    def run(self):
        static_dir = pathlib.Path(self.build_lib) / 'croquis_fe' / 'static'
        self.mkpath(str(static_dir))
        for fn in 'croquis_fe.js', 'croquis_fe.js.map':
            shutil.copy(src=(js_bundle_dir / fn), dst=(static_dir / fn))

        super().run()

if __name__ == '__main__':
    MODE = sys.argv[1] if len(sys.argv) >= 2 else None

    if MODE == '-CMAKE':
        print('*** setup.py invoked from cmake: ', ' '.join(sys.argv))
        del sys.argv[1]
        print('*** Cleaning build directory ...')
        if (curpath / 'build').exists():
            shutil.rmtree(curpath / 'build')
        libpaths = [sys.argv.pop(1)]
        js_bundle_dir = pathlib.Path(sys.argv.pop(1))

    elif MODE == '-f':
        print('*** setup.py invoked directly: ' +
              "I assume you know what you're doing ...")
        del sys.argv[1]
        libpaths = list(curpath.glob('src/croquis/lib/_csrc*'))
        js_bundle_dir = curpath / 'src' / 'js' / 'dist'

    else:
        print('''
*** This setup.py is not supposed to be invoked directly.
*** Instead, please generate the package via cmake:

        # You can use any directory for cmake, but don't use "build" because
        # setuptools will also try to use it!
        mkdir build.cmake
        cd build.cmake
        cmake -DCMAKE_BUILD_TYPE=Release ../src
        make wheel  # or make VERBOSE=1 wheel

*** If you *really* want to run setup.py directly, first build the C library via
*** cmake, put the library file under src/croquis/lib/, and invoke setup.py with
*** -f:

        python setup.py -f bdist_wheel  # or some other command you want to run.
    ''')
        sys.exit(1)

    with open(curpath / 'README.md', 'rt') as f:
        long_description = f.read()

    csrc = setuptools.Extension(name='croquis.lib._csrc', sources=[])

    setuptools.setup(
        name='croquis',
        version=os.environ.get('CR_PKG_VERSION', '0.1.0'),
        author='<NAME>',
        description='Library for plotting interactive graphs on Jupyter Notebook',
        long_description=long_description,
        long_description_content_type='text/markdown',
        url='https://github.com/yongjik/croquis',
        classifiers=[
            "Framework :: Jupyter",
            "Programming Language :: Python :: 3",
            "Programming Language :: Python :: 3.6",
            "Programming Language :: Python :: 3.7",
            "Programming Language :: Python :: 3.8",
            "Programming Language :: Python :: 3.9",
            "Programming Language :: Python :: Implementation :: CPython",
            "License :: OSI Approved :: MIT License",
            "Operating System :: MacOS :: MacOS X",
            "Operating System :: POSIX :: Linux",
            # "Operating System :: OS Independent",
        ],
        python_requires='>=3.6',
        install_requires=[
            'jinja2',

            # Minimum version to support np.argsort(kind='stable').
            'numpy>=1.15.0',
        ],

        ext_modules=[csrc],
        # package_data={'': ['lib/_csrc*']},
        cmdclass={
            'build_ext': MyBuildExt,
            'build_py': MyBuildPy,
        },

        #-----------------------------------------
        # Install nbextension at install time.
        # Basic idea is stolen from plotly/setup.py (version 4.14.3)
        # See also: https://jupyter-notebook.readthedocs.io/en/stable/examples/Notebook/Distributing%20Jupyter%20Extensions%20as%20Python%20Packages.html

        # Not completely sure, but it seems like we need a separate __init__.py
        # for Jupyter to run, so it's probably better to have a separate "fe"
        # module.  (Plotly similary has `plotlywidget`.)
        packages=['croquis', 'croquis_fe'],

        package_dir={
            'croquis': 'src/croquis',
            'croquis_fe': 'croquis_fe',
        },
        package_data={
            'croquis_fe': [
                # Symlinked to src/js.
                'static/croquis_fe.css',
                'static/croquis_loader.js',

                # croquis_fe.js & croquis_fe.js.map cannot be added like this,
                # because they're not in the correct directory.  Instead, they
                # are added by MyBuildPy class.
            ],
        },

        # TODO: We're duplicating these files?  (Once under croquis_fe/, and
        # then under share/jupyter/...)
        data_files=[
            (
                'share/jupyter/nbextensions/croquis_fe', [
                    'src/js/croquis_fe.css',
                    'src/js/croquis_loader.js',
                    str(js_bundle_dir / 'croquis_fe.js'),
                    str(js_bundle_dir / 'croquis_fe.js.map'),
                ],
            ),
            (
                'etc/jupyter/nbconfig/notebook.d',
                ['croquis_fe/croquis_fe.json'],
            ),
        ],
        zip_safe=False,
    )

# Intended to be invoked from cmake - don't run directly.

import os
import pathlib
import setuptools
import setuptools.command.build_ext
import setuptools.command.build_py
import shutil
import subprocess
import sys

MODE = None

curpath = pathlib.Path(os.path.dirname(os.path.realpath(__file__)))
os.chdir(curpath)

libpaths = None
js_bundle_dir = None

# Create my own build_ext class, which simply copies the file to the correct
# location.
# Inspired by: https://github.com/pybind/cmake_example/blob/master/setup.py
class MyBuildExt(setuptools.command.build_ext.build_ext):
    def run(self):
        ext, = self.extensions
        assert len(libpaths) == 1, \
            'Expected exactly one shared library file but found ' \
            f'{len(libpaths)}: ' + str(libpaths)

        destpath = self.get_ext_fullpath(ext.name)
        destdir = pathlib.Path(destpath).parent
        destdir.mkdir(parents=True, exist_ok=True)
        shutil.copy(src=libpaths[0], dst=destpath)

        # Also populate 'is_nodev.py' to let the library know that this is not a
        # development environment.
        with open(destdir / 'is_nodev.py', 'wt') as f:
            f.write(
'''# This file doesn't exist in the source tree, and is generated by setup.py so
# that the croquis library can tell if it's running inside a dev environment.
pass
''')

# Copy the generated js bundle files.
# Copied from: https://digip.org/blog/2011/01/generating-data-files-in-setup.py.html
class MyBuildPy(setuptools.command.build_py.build_py):
    def run(self):
        static_dir = pathlib.Path(self.build_lib) / 'croquis_fe' / 'static'
        self.mkpath(str(static_dir))
        for fn in 'croquis_fe.js', 'croquis_fe.js.map':
            shutil.copy(src=(js_bundle_dir / fn), dst=(static_dir / fn))

        super().run()

if __name__ == '__main__':
    MODE = sys.argv[1] if len(sys.argv) >= 2 else None

    if MODE == '-CMAKE':
        print('*** setup.py invoked from cmake: ', ' '.join(sys.argv))
        del sys.argv[1]
        print('*** Cleaning build directory ...')
        if (curpath / 'build').exists():
            shutil.rmtree(curpath / 'build')
        libpaths = [sys.argv.pop(1)]
        js_bundle_dir = pathlib.Path(sys.argv.pop(1))

    elif MODE == '-f':
        print('*** setup.py invoked directly: ' +
              "I assume you know what you're doing ...")
        del sys.argv[1]
        libpaths = list(curpath.glob('src/croquis/lib/_csrc*'))
        js_bundle_dir = curpath / 'src' / 'js' / 'dist'

    else:
        print('''
*** This setup.py is not supposed to be invoked directly.
*** Instead, please generate the package via cmake:

        # You can use any directory for cmake, but don't use "build" because
        # setuptools will also try to use it!
        mkdir build.cmake
        cd build.cmake
        cmake -DCMAKE_BUILD_TYPE=Release ../src
        make wheel  # or make VERBOSE=1 wheel

*** If you *really* want to run setup.py directly, first build the C library via
*** cmake, put the library file under src/croquis/lib/, and invoke setup.py with
*** -f:

        python setup.py -f bdist_wheel  # or some other command you want to run.
    ''')
        sys.exit(1)

    with open(curpath / 'README.md', 'rt') as f:
        long_description = f.read()

    csrc = setuptools.Extension(name='croquis.lib._csrc', sources=[])

    setuptools.setup(
        name='croquis',
        version=os.environ.get('CR_PKG_VERSION', '0.1.0'),
        author='<NAME>',
        description='Library for plotting interactive graphs on Jupyter Notebook',
        long_description=long_description,
        long_description_content_type='text/markdown',
        url='https://github.com/yongjik/croquis',
        classifiers=[
            "Framework :: Jupyter",
            "Programming Language :: Python :: 3",
            "Programming Language :: Python :: 3.6",
            "Programming Language :: Python :: 3.7",
            "Programming Language :: Python :: 3.8",
            "Programming Language :: Python :: 3.9",
            "Programming Language :: Python :: Implementation :: CPython",
            "License :: OSI Approved :: MIT License",
            "Operating System :: MacOS :: MacOS X",
            "Operating System :: POSIX :: Linux",
            # "Operating System :: OS Independent",
        ],
        python_requires='>=3.6',
        install_requires=[
            'jinja2',

            # Minimum version to support np.argsort(kind='stable').
            'numpy>=1.15.0',
        ],

        ext_modules=[csrc],
        # package_data={'': ['lib/_csrc*']},
        cmdclass={
            'build_ext': MyBuildExt,
            'build_py': MyBuildPy,
        },

        #-----------------------------------------
        # Install nbextension at install time.
        # Basic idea is stolen from plotly/setup.py (version 4.14.3)
        # See also: https://jupyter-notebook.readthedocs.io/en/stable/examples/Notebook/Distributing%20Jupyter%20Extensions%20as%20Python%20Packages.html

        # Not completely sure, but it seems like we need a separate __init__.py
        # for Jupyter to run, so it's probably better to have a separate "fe"
        # module.  (Plotly similary has `plotlywidget`.)
        packages=['croquis', 'croquis_fe'],

        package_dir={
            'croquis': 'src/croquis',
            'croquis_fe': 'croquis_fe',
        },
        package_data={
            'croquis_fe': [
                # Symlinked to src/js.
                'static/croquis_fe.css',
                'static/croquis_loader.js',

                # croquis_fe.js & croquis_fe.js.map cannot be added like this,
                # because they're not in the correct directory.  Instead, they
                # are added by MyBuildPy class.
            ],
        },

        # TODO: We're duplicating these files?  (Once under croquis_fe/, and
        # then under share/jupyter/...)
        data_files=[
            (
                'share/jupyter/nbextensions/croquis_fe', [
                    'src/js/croquis_fe.css',
                    'src/js/croquis_loader.js',
                    str(js_bundle_dir / 'croquis_fe.js'),
                    str(js_bundle_dir / 'croquis_fe.js.map'),
                ],
            ),
            (
                'etc/jupyter/nbconfig/notebook.d',
                ['croquis_fe/croquis_fe.json'],
            ),
        ],
        zip_safe=False,
    )

# Intended to be invoked from cmake - don't run directly. # Create my own build_ext class, which simply copies the file to the correct # location. # Inspired by: https://github.com/pybind/cmake_example/blob/master/setup.py # Also populate 'is_nodev.py' to let the library know that this is not a # development environment. # This file doesn't exist in the source tree, and is generated by setup.py so # that the croquis library can tell if it's running inside a dev environment. pass # Copy the generated js bundle files. # Copied from: https://digip.org/blog/2011/01/generating-data-files-in-setup.py.html *** This setup.py is not supposed to be invoked directly. *** Instead, please generate the package via cmake:          # You can use any directory for cmake, but don't use "build" because         # setuptools will also try to use it!         mkdir build.cmake         cd build.cmake         cmake -DCMAKE_BUILD_TYPE=Release ../src         make wheel  # or make VERBOSE=1 wheel  *** If you *really* want to run setup.py directly, first build the C library via *** cmake, put the library file under src/croquis/lib/, and invoke setup.py with *** -f:          python setup.py -f bdist_wheel  # or some other command you want to run. # "Operating System :: OS Independent", # Minimum version to support np.argsort(kind='stable'). # package_data={'': ['lib/_csrc*']}, #----------------------------------------- # Install nbextension at install time. # Basic idea is stolen from plotly/setup.py (version 4.14.3) # See also: https://jupyter-notebook.readthedocs.io/en/stable/examples/Notebook/Distributing%20Jupyter%20Extensions%20as%20Python%20Packages.html # Not completely sure, but it seems like we need a separate __init__.py # for Jupyter to run, so it's probably better to have a separate "fe" # module.  (Plotly similary has `plotlywidget`.) # Symlinked to src/js. # croquis_fe.js & croquis_fe.js.map cannot be added like this, # because they're not in the correct directory.  Instead, they # are added by MyBuildPy class. # TODO: We're duplicating these files?  (Once under croquis_fe/, and # then under share/jupyter/...)