summaryrefslogtreecommitdiff
path: root/python-cmake-build-extension.spec
blob: 72f57ea1c26a2900fd8dae4cf72ede2143892f94 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
%global _empty_manifest_terminate_build 0
Name:		python-cmake-build-extension
Version:	0.5.1
Release:	1
Summary:	Setuptools extension to build and package CMake projects.
License:	MIT
URL:		https://github.com/diegoferigo/cmake-build-extension
Source0:	https://mirrors.nju.edu.cn/pypi/web/packages/dc/21/401a64c77dba9e1f3bc4b949c10708c5d943765d55c0b1a4925b96e3fcde/cmake-build-extension-0.5.1.tar.gz
BuildArch:	noarch

Requires:	python3-cmake
Requires:	python3-ninja
Requires:	python3-GitPython
Requires:	python3-setuptools-scm

%description
# cmake-build-extension

[![Version](https://img.shields.io/pypi/v/cmake-build-extension.svg)][pypi]
[![Python versions](https://img.shields.io/pypi/pyversions/cmake-build-extension.svg)][pypi]
[![Status](https://img.shields.io/pypi/status/cmake-build-extension.svg)][pypi]
[![Format](https://img.shields.io/pypi/format/cmake-build-extension.svg)][pypi]
[![License](https://img.shields.io/pypi/l/cmake-build-extension.svg)][pypi]
[![Python CI/CD](https://github.com/diegoferigo/cmake-build-extension/workflows/Python%20CI/CD/badge.svg)][ci_cd]

[pypi]: https://pypi.org/project/cmake-build-extension/
[ci_cd]: https://github.com/diegoferigo/cmake-build-extension/actions/workflows/python.yml

**Setuptools extension to build and package CMake projects.**

This project aims to simplify the integration of C++ projects based on CMake with Python packaging tools.
CMake provides out-of-the-box support to either [SWIG][swig] and [pybind11][pybind11],
that are two among the most used projects to create Python bindings from C++ sources.

[swig]: https://github.com/swig/swig
[pybind11]: https://github.com/pybind/pybind11

If you have any experience with these hybrid projects, you know the challenges to make packaging right!
This project takes inspiration from pre-existing examples 
([`pybind/cmake_example`][pybind11_example], among many others)
and provides a simple, flexible, and reusable setuptools extension with the following features:

- Bridge between CMake projects and Python packaging.
- Configure and build the CMake project from `setup.py`. 
- Install the CMake project in the resulting Python package.
- Allow passing custom CMake options.
- Allow creating a top-level `__init__.py`.
- Expose C++ executables to the Python environment.
- Provide a context manager to import reliably CPython modules on all major OSs.
- Disable the C++ extension in editable installations (requiring to manually call CMake to install the C++ project).

[pybind11_example]: https://github.com/pybind/cmake_example

Have a look to the [example](example/) for an overview of what can be done with this extension.
It shows how to create SWIG and pybind11 bindings for a project composed by a small C++ library with NumPy support 
and an executable. 

### Advanced features

1. This extension supports creating packages [PEP517] and [PEP518] compliant ([more details][pyproject]).
2. If the CMake project [exports the targets][export_targets], downstream projects can:
   1. Extend their `CMAKE_MODULE_PATH` with the root of your installed Python package,
      that could be obtained with:
      ```bash
      python -c "import <pkg>, pathlib; print(pathlib.Path(<pkg>.__file__).parent)"
      ```
      and consume the exported CMake targets.
   1. Use `cmake-build-extension` with the `cmake_depends_on` option and link against the exported CMake targets
      during the downstream packaging.

Note that the second feature allows distributing C++ dependencies through PyPI.
The resulting package structure is similar to other projects like [pybind11][pybind11_pypi] and [CasADi][casadi_pypi].
Be aware that ensuring ABI compatibility could be problematic in edge cases, 
and the usage of a proper [compatible release pattern][pep440] (`~=`) could be necessary.

[pep440]: https://www.python.org/dev/peps/pep-0440/#compatible-release
[pep517]: https://www.python.org/dev/peps/pep-0517/
[pep518]: https://www.python.org/dev/peps/pep-0518/

[pyproject]: https://snarky.ca/what-the-heck-is-pyproject-toml/
[export_targets]: https://cmake.org/cmake/help/git-stage/guide/importing-exporting/index.html

[pybind11_pypi]: https://pypi.org/project/pybind11/
[casadi_pypi]: https://pypi.org/project/casadi/

## Installation

From PyPI:

```bash
pip install cmake-build-extension
```

From the repository:

```bash
pip install git+https://github.com/diegoferigo/cmake-build-extension
```

## Usage

Once both CMake project and `setup.py|setup.cfg|pyproject.toml` of your hybrid package are correctly configured
to use the resources provided by cmake-build-extension, the following commands can be used:

```bash
# ============
# Create sdist
# ============

# Calling setup.py
python setup.py sdist

# Using pypa/build
python -m build --sdist

# ============
# Create wheel
# ============

# Calling setup.py
python setup.py bdist_wheel

# Using pip
pip wheel -w dist/ .

# Using pypa/build
python -m build --wheel

# ==========================================================
# Create wheel or install package passing additional options
# ==========================================================

# Calling setup.py
python setup.py {bdist_wheel|install} build_ext -D"BAR=Foo;VAR=TRUE"

# Using pip
pip {wheel|install} --global-option="build_ext" --global-option="-DBAR=Foo;VAR=TRUE" .

# Using pypa/build (only wheel creation)
python -m build --wheel "-C--global-option=build_ext" "-C--global-option=-DBAR=Foo;VAR=TRUE"
```

## Caveats

### `manylinux*` support

This extension, beyond packaging the hybrid C++ / Python project, 
also allows the inclusion of the exported CMake targets in the resulting wheel.
This result depends on how the CMake project is configured, 
and whether the [exported targets][exp_imp_wiki] are installed together with the other files.

[exp_imp_wiki]: https://gitlab.kitware.com/cmake/community/-/wikis/doc/tutorials/Exporting-and-Importing-Targets

Such hybrid packages can then be uploaded to PyPI. 
Though, on GNU/Linux, the generated wheel is not compliant by default with any [`manylinux*`][manylinux] standard.
Tools such [auditwheel][auditwheel] exist to fix these wheels, but they require running on selected distributions.
Luckily, other projects like [cibuildwheel][cibuildwheel] greatly simplify the process in CI.

[manylinux]: https://github.com/pypa/manylinux
[auditwheel]: https://github.com/pypa/auditwheel
[cibuildwheel]: https://github.com/joerick/cibuildwheel

This being said, `manylinux*` guidelines could still work against you.
In fact, wheels supporting `manylinux2010|manylinux2014` are built [with gcc4][pep599_manylinux2014] 
that does not support the new C++11 ABIs.
In few words, this means that the exported libraries bundled in the wheel cannot 
be imported in a downstream project using relatively new C++ standards!
For more details visit [robotology/idyntree#776](https://github.com/robotology/idyntree/issues/776). 

[pep599_manylinux2014]: https://www.python.org/dev/peps/pep-0599/#the-manylinux2014-policy

Luckily, the situation changed thanks to the finalization of [PEP600][pep600], i.e. `manylinuxX_YY` :tada: 
If you build a PEP600 compliant wheel (nowadays compatible with most of the commonly used distributions), 
your exported CMake project bundled in the wheel can be successfully imported downstream.
If you want to support this use case, make sure to produce and distribute wheels compliant with PEP600.

[pep600]: https://www.python.org/dev/peps/pep-0600/

### Loading CPython modules in Windows

Python 3.8 [changed][changelog_3_8] how DLL are resolved.
By default, modules that could be imported in Python 3.7 stopped working, and using the new 
[`os.add_dll_directory`][add_dll_directory] is now necessary.

In order to streamline the process, `cmake-build-extension` implements a context manager that can be used 
to import reliably the bindings module:

```python
import cmake_build_extension

with cmake_build_extension.build_extension_env():
    from . import bindings
```

It will take care to temporarily fix the search path.

For more details, refer to [#8][windows_import_issue] and [#12][windows_import_pr].

[changelog_3_8]: https://docs.python.org/3/whatsnew/3.8.html#bpo-36085-whatsnew
[add_dll_directory]: https://docs.python.org/3/library/os.html#os.add_dll_directory
[windows_import_issue]: https://github.com/diegoferigo/cmake-build-extension/issues/8
[windows_import_pr]: https://github.com/diegoferigo/cmake-build-extension/pull/12

### `setup.py|setup.cfg|pyproject.toml` files in subfolder

Sometimes hybrid projects are C++ centric, and keeping these files in the top-level folder is not desirable.
In this setup, however, problems occur if the main `CMakeLists.txt` is kept in the top-level folder 
(see [pypa/build#322][sdist_issue]).
To solve this problem, `cmake-build-extension` provides custom commands to create source distribution.
You can use one of the following custom `sdist` options in `setup.py`:

```python
setuptools.setup(
    cmdclass=dict(
        # [...]
        # Pack the whole git folder:
        sdist=cmake_build_extension.GitSdistFolder,
        # Pack only the git tree:
        sdist=cmake_build_extension.GitSdistTree,
        # Or, inherit from cmake_build_extension.sdist_command.GitSdistABC and
        # make your own custom sdist including only the files you are interested
    ),
)
```

[sdist_issue]: https://github.com/pypa/build/issues/322

## Downstream projects

If the provided example is not enough complex, find here below a list of projects using `cmake-build-extension`: 

- [`robotology/idyntree`](https://github.com/robotology/idyntree/)
- [`robotology/yarp`](https://github.com/robotology/yarp/)
- [`robotology/ycm`](https://github.com/robotology/ycm/)
- [`diegoferigo/gazebo-yarp-synchronizer`](https://github.com/diegoferigo/gazebo-yarp-synchronizer)
- [`robotology/gym-ignition@scenario`](https://github.com/robotology/gym-ignition/tree/devel/scenario)
- [`dic-iit/gazebo-scenario-plugins`](https://github.com/dic-iit/gazebo-scenario-plugins/)
- [`dic-iit/bipedal-locomotion-framework`](https://github.com/dic-iit/bipedal-locomotion-framework)
- [`artivis/manif`](https://github.com/artivis/manif)

## Contributing

Pull requests are welcome. For major changes, please open an issue first to discuss what you would like to change.

## License

[MIT](https://choosealicense.com/licenses/mit/)


%package -n python3-cmake-build-extension
Summary:	Setuptools extension to build and package CMake projects.
Provides:	python-cmake-build-extension
BuildRequires:	python3-devel
BuildRequires:	python3-setuptools
BuildRequires:	python3-pip
%description -n python3-cmake-build-extension
# cmake-build-extension

[![Version](https://img.shields.io/pypi/v/cmake-build-extension.svg)][pypi]
[![Python versions](https://img.shields.io/pypi/pyversions/cmake-build-extension.svg)][pypi]
[![Status](https://img.shields.io/pypi/status/cmake-build-extension.svg)][pypi]
[![Format](https://img.shields.io/pypi/format/cmake-build-extension.svg)][pypi]
[![License](https://img.shields.io/pypi/l/cmake-build-extension.svg)][pypi]
[![Python CI/CD](https://github.com/diegoferigo/cmake-build-extension/workflows/Python%20CI/CD/badge.svg)][ci_cd]

[pypi]: https://pypi.org/project/cmake-build-extension/
[ci_cd]: https://github.com/diegoferigo/cmake-build-extension/actions/workflows/python.yml

**Setuptools extension to build and package CMake projects.**

This project aims to simplify the integration of C++ projects based on CMake with Python packaging tools.
CMake provides out-of-the-box support to either [SWIG][swig] and [pybind11][pybind11],
that are two among the most used projects to create Python bindings from C++ sources.

[swig]: https://github.com/swig/swig
[pybind11]: https://github.com/pybind/pybind11

If you have any experience with these hybrid projects, you know the challenges to make packaging right!
This project takes inspiration from pre-existing examples 
([`pybind/cmake_example`][pybind11_example], among many others)
and provides a simple, flexible, and reusable setuptools extension with the following features:

- Bridge between CMake projects and Python packaging.
- Configure and build the CMake project from `setup.py`. 
- Install the CMake project in the resulting Python package.
- Allow passing custom CMake options.
- Allow creating a top-level `__init__.py`.
- Expose C++ executables to the Python environment.
- Provide a context manager to import reliably CPython modules on all major OSs.
- Disable the C++ extension in editable installations (requiring to manually call CMake to install the C++ project).

[pybind11_example]: https://github.com/pybind/cmake_example

Have a look to the [example](example/) for an overview of what can be done with this extension.
It shows how to create SWIG and pybind11 bindings for a project composed by a small C++ library with NumPy support 
and an executable. 

### Advanced features

1. This extension supports creating packages [PEP517] and [PEP518] compliant ([more details][pyproject]).
2. If the CMake project [exports the targets][export_targets], downstream projects can:
   1. Extend their `CMAKE_MODULE_PATH` with the root of your installed Python package,
      that could be obtained with:
      ```bash
      python -c "import <pkg>, pathlib; print(pathlib.Path(<pkg>.__file__).parent)"
      ```
      and consume the exported CMake targets.
   1. Use `cmake-build-extension` with the `cmake_depends_on` option and link against the exported CMake targets
      during the downstream packaging.

Note that the second feature allows distributing C++ dependencies through PyPI.
The resulting package structure is similar to other projects like [pybind11][pybind11_pypi] and [CasADi][casadi_pypi].
Be aware that ensuring ABI compatibility could be problematic in edge cases, 
and the usage of a proper [compatible release pattern][pep440] (`~=`) could be necessary.

[pep440]: https://www.python.org/dev/peps/pep-0440/#compatible-release
[pep517]: https://www.python.org/dev/peps/pep-0517/
[pep518]: https://www.python.org/dev/peps/pep-0518/

[pyproject]: https://snarky.ca/what-the-heck-is-pyproject-toml/
[export_targets]: https://cmake.org/cmake/help/git-stage/guide/importing-exporting/index.html

[pybind11_pypi]: https://pypi.org/project/pybind11/
[casadi_pypi]: https://pypi.org/project/casadi/

## Installation

From PyPI:

```bash
pip install cmake-build-extension
```

From the repository:

```bash
pip install git+https://github.com/diegoferigo/cmake-build-extension
```

## Usage

Once both CMake project and `setup.py|setup.cfg|pyproject.toml` of your hybrid package are correctly configured
to use the resources provided by cmake-build-extension, the following commands can be used:

```bash
# ============
# Create sdist
# ============

# Calling setup.py
python setup.py sdist

# Using pypa/build
python -m build --sdist

# ============
# Create wheel
# ============

# Calling setup.py
python setup.py bdist_wheel

# Using pip
pip wheel -w dist/ .

# Using pypa/build
python -m build --wheel

# ==========================================================
# Create wheel or install package passing additional options
# ==========================================================

# Calling setup.py
python setup.py {bdist_wheel|install} build_ext -D"BAR=Foo;VAR=TRUE"

# Using pip
pip {wheel|install} --global-option="build_ext" --global-option="-DBAR=Foo;VAR=TRUE" .

# Using pypa/build (only wheel creation)
python -m build --wheel "-C--global-option=build_ext" "-C--global-option=-DBAR=Foo;VAR=TRUE"
```

## Caveats

### `manylinux*` support

This extension, beyond packaging the hybrid C++ / Python project, 
also allows the inclusion of the exported CMake targets in the resulting wheel.
This result depends on how the CMake project is configured, 
and whether the [exported targets][exp_imp_wiki] are installed together with the other files.

[exp_imp_wiki]: https://gitlab.kitware.com/cmake/community/-/wikis/doc/tutorials/Exporting-and-Importing-Targets

Such hybrid packages can then be uploaded to PyPI. 
Though, on GNU/Linux, the generated wheel is not compliant by default with any [`manylinux*`][manylinux] standard.
Tools such [auditwheel][auditwheel] exist to fix these wheels, but they require running on selected distributions.
Luckily, other projects like [cibuildwheel][cibuildwheel] greatly simplify the process in CI.

[manylinux]: https://github.com/pypa/manylinux
[auditwheel]: https://github.com/pypa/auditwheel
[cibuildwheel]: https://github.com/joerick/cibuildwheel

This being said, `manylinux*` guidelines could still work against you.
In fact, wheels supporting `manylinux2010|manylinux2014` are built [with gcc4][pep599_manylinux2014] 
that does not support the new C++11 ABIs.
In few words, this means that the exported libraries bundled in the wheel cannot 
be imported in a downstream project using relatively new C++ standards!
For more details visit [robotology/idyntree#776](https://github.com/robotology/idyntree/issues/776). 

[pep599_manylinux2014]: https://www.python.org/dev/peps/pep-0599/#the-manylinux2014-policy

Luckily, the situation changed thanks to the finalization of [PEP600][pep600], i.e. `manylinuxX_YY` :tada: 
If you build a PEP600 compliant wheel (nowadays compatible with most of the commonly used distributions), 
your exported CMake project bundled in the wheel can be successfully imported downstream.
If you want to support this use case, make sure to produce and distribute wheels compliant with PEP600.

[pep600]: https://www.python.org/dev/peps/pep-0600/

### Loading CPython modules in Windows

Python 3.8 [changed][changelog_3_8] how DLL are resolved.
By default, modules that could be imported in Python 3.7 stopped working, and using the new 
[`os.add_dll_directory`][add_dll_directory] is now necessary.

In order to streamline the process, `cmake-build-extension` implements a context manager that can be used 
to import reliably the bindings module:

```python
import cmake_build_extension

with cmake_build_extension.build_extension_env():
    from . import bindings
```

It will take care to temporarily fix the search path.

For more details, refer to [#8][windows_import_issue] and [#12][windows_import_pr].

[changelog_3_8]: https://docs.python.org/3/whatsnew/3.8.html#bpo-36085-whatsnew
[add_dll_directory]: https://docs.python.org/3/library/os.html#os.add_dll_directory
[windows_import_issue]: https://github.com/diegoferigo/cmake-build-extension/issues/8
[windows_import_pr]: https://github.com/diegoferigo/cmake-build-extension/pull/12

### `setup.py|setup.cfg|pyproject.toml` files in subfolder

Sometimes hybrid projects are C++ centric, and keeping these files in the top-level folder is not desirable.
In this setup, however, problems occur if the main `CMakeLists.txt` is kept in the top-level folder 
(see [pypa/build#322][sdist_issue]).
To solve this problem, `cmake-build-extension` provides custom commands to create source distribution.
You can use one of the following custom `sdist` options in `setup.py`:

```python
setuptools.setup(
    cmdclass=dict(
        # [...]
        # Pack the whole git folder:
        sdist=cmake_build_extension.GitSdistFolder,
        # Pack only the git tree:
        sdist=cmake_build_extension.GitSdistTree,
        # Or, inherit from cmake_build_extension.sdist_command.GitSdistABC and
        # make your own custom sdist including only the files you are interested
    ),
)
```

[sdist_issue]: https://github.com/pypa/build/issues/322

## Downstream projects

If the provided example is not enough complex, find here below a list of projects using `cmake-build-extension`: 

- [`robotology/idyntree`](https://github.com/robotology/idyntree/)
- [`robotology/yarp`](https://github.com/robotology/yarp/)
- [`robotology/ycm`](https://github.com/robotology/ycm/)
- [`diegoferigo/gazebo-yarp-synchronizer`](https://github.com/diegoferigo/gazebo-yarp-synchronizer)
- [`robotology/gym-ignition@scenario`](https://github.com/robotology/gym-ignition/tree/devel/scenario)
- [`dic-iit/gazebo-scenario-plugins`](https://github.com/dic-iit/gazebo-scenario-plugins/)
- [`dic-iit/bipedal-locomotion-framework`](https://github.com/dic-iit/bipedal-locomotion-framework)
- [`artivis/manif`](https://github.com/artivis/manif)

## Contributing

Pull requests are welcome. For major changes, please open an issue first to discuss what you would like to change.

## License

[MIT](https://choosealicense.com/licenses/mit/)


%package help
Summary:	Development documents and examples for cmake-build-extension
Provides:	python3-cmake-build-extension-doc
%description help
# cmake-build-extension

[![Version](https://img.shields.io/pypi/v/cmake-build-extension.svg)][pypi]
[![Python versions](https://img.shields.io/pypi/pyversions/cmake-build-extension.svg)][pypi]
[![Status](https://img.shields.io/pypi/status/cmake-build-extension.svg)][pypi]
[![Format](https://img.shields.io/pypi/format/cmake-build-extension.svg)][pypi]
[![License](https://img.shields.io/pypi/l/cmake-build-extension.svg)][pypi]
[![Python CI/CD](https://github.com/diegoferigo/cmake-build-extension/workflows/Python%20CI/CD/badge.svg)][ci_cd]

[pypi]: https://pypi.org/project/cmake-build-extension/
[ci_cd]: https://github.com/diegoferigo/cmake-build-extension/actions/workflows/python.yml

**Setuptools extension to build and package CMake projects.**

This project aims to simplify the integration of C++ projects based on CMake with Python packaging tools.
CMake provides out-of-the-box support to either [SWIG][swig] and [pybind11][pybind11],
that are two among the most used projects to create Python bindings from C++ sources.

[swig]: https://github.com/swig/swig
[pybind11]: https://github.com/pybind/pybind11

If you have any experience with these hybrid projects, you know the challenges to make packaging right!
This project takes inspiration from pre-existing examples 
([`pybind/cmake_example`][pybind11_example], among many others)
and provides a simple, flexible, and reusable setuptools extension with the following features:

- Bridge between CMake projects and Python packaging.
- Configure and build the CMake project from `setup.py`. 
- Install the CMake project in the resulting Python package.
- Allow passing custom CMake options.
- Allow creating a top-level `__init__.py`.
- Expose C++ executables to the Python environment.
- Provide a context manager to import reliably CPython modules on all major OSs.
- Disable the C++ extension in editable installations (requiring to manually call CMake to install the C++ project).

[pybind11_example]: https://github.com/pybind/cmake_example

Have a look to the [example](example/) for an overview of what can be done with this extension.
It shows how to create SWIG and pybind11 bindings for a project composed by a small C++ library with NumPy support 
and an executable. 

### Advanced features

1. This extension supports creating packages [PEP517] and [PEP518] compliant ([more details][pyproject]).
2. If the CMake project [exports the targets][export_targets], downstream projects can:
   1. Extend their `CMAKE_MODULE_PATH` with the root of your installed Python package,
      that could be obtained with:
      ```bash
      python -c "import <pkg>, pathlib; print(pathlib.Path(<pkg>.__file__).parent)"
      ```
      and consume the exported CMake targets.
   1. Use `cmake-build-extension` with the `cmake_depends_on` option and link against the exported CMake targets
      during the downstream packaging.

Note that the second feature allows distributing C++ dependencies through PyPI.
The resulting package structure is similar to other projects like [pybind11][pybind11_pypi] and [CasADi][casadi_pypi].
Be aware that ensuring ABI compatibility could be problematic in edge cases, 
and the usage of a proper [compatible release pattern][pep440] (`~=`) could be necessary.

[pep440]: https://www.python.org/dev/peps/pep-0440/#compatible-release
[pep517]: https://www.python.org/dev/peps/pep-0517/
[pep518]: https://www.python.org/dev/peps/pep-0518/

[pyproject]: https://snarky.ca/what-the-heck-is-pyproject-toml/
[export_targets]: https://cmake.org/cmake/help/git-stage/guide/importing-exporting/index.html

[pybind11_pypi]: https://pypi.org/project/pybind11/
[casadi_pypi]: https://pypi.org/project/casadi/

## Installation

From PyPI:

```bash
pip install cmake-build-extension
```

From the repository:

```bash
pip install git+https://github.com/diegoferigo/cmake-build-extension
```

## Usage

Once both CMake project and `setup.py|setup.cfg|pyproject.toml` of your hybrid package are correctly configured
to use the resources provided by cmake-build-extension, the following commands can be used:

```bash
# ============
# Create sdist
# ============

# Calling setup.py
python setup.py sdist

# Using pypa/build
python -m build --sdist

# ============
# Create wheel
# ============

# Calling setup.py
python setup.py bdist_wheel

# Using pip
pip wheel -w dist/ .

# Using pypa/build
python -m build --wheel

# ==========================================================
# Create wheel or install package passing additional options
# ==========================================================

# Calling setup.py
python setup.py {bdist_wheel|install} build_ext -D"BAR=Foo;VAR=TRUE"

# Using pip
pip {wheel|install} --global-option="build_ext" --global-option="-DBAR=Foo;VAR=TRUE" .

# Using pypa/build (only wheel creation)
python -m build --wheel "-C--global-option=build_ext" "-C--global-option=-DBAR=Foo;VAR=TRUE"
```

## Caveats

### `manylinux*` support

This extension, beyond packaging the hybrid C++ / Python project, 
also allows the inclusion of the exported CMake targets in the resulting wheel.
This result depends on how the CMake project is configured, 
and whether the [exported targets][exp_imp_wiki] are installed together with the other files.

[exp_imp_wiki]: https://gitlab.kitware.com/cmake/community/-/wikis/doc/tutorials/Exporting-and-Importing-Targets

Such hybrid packages can then be uploaded to PyPI. 
Though, on GNU/Linux, the generated wheel is not compliant by default with any [`manylinux*`][manylinux] standard.
Tools such [auditwheel][auditwheel] exist to fix these wheels, but they require running on selected distributions.
Luckily, other projects like [cibuildwheel][cibuildwheel] greatly simplify the process in CI.

[manylinux]: https://github.com/pypa/manylinux
[auditwheel]: https://github.com/pypa/auditwheel
[cibuildwheel]: https://github.com/joerick/cibuildwheel

This being said, `manylinux*` guidelines could still work against you.
In fact, wheels supporting `manylinux2010|manylinux2014` are built [with gcc4][pep599_manylinux2014] 
that does not support the new C++11 ABIs.
In few words, this means that the exported libraries bundled in the wheel cannot 
be imported in a downstream project using relatively new C++ standards!
For more details visit [robotology/idyntree#776](https://github.com/robotology/idyntree/issues/776). 

[pep599_manylinux2014]: https://www.python.org/dev/peps/pep-0599/#the-manylinux2014-policy

Luckily, the situation changed thanks to the finalization of [PEP600][pep600], i.e. `manylinuxX_YY` :tada: 
If you build a PEP600 compliant wheel (nowadays compatible with most of the commonly used distributions), 
your exported CMake project bundled in the wheel can be successfully imported downstream.
If you want to support this use case, make sure to produce and distribute wheels compliant with PEP600.

[pep600]: https://www.python.org/dev/peps/pep-0600/

### Loading CPython modules in Windows

Python 3.8 [changed][changelog_3_8] how DLL are resolved.
By default, modules that could be imported in Python 3.7 stopped working, and using the new 
[`os.add_dll_directory`][add_dll_directory] is now necessary.

In order to streamline the process, `cmake-build-extension` implements a context manager that can be used 
to import reliably the bindings module:

```python
import cmake_build_extension

with cmake_build_extension.build_extension_env():
    from . import bindings
```

It will take care to temporarily fix the search path.

For more details, refer to [#8][windows_import_issue] and [#12][windows_import_pr].

[changelog_3_8]: https://docs.python.org/3/whatsnew/3.8.html#bpo-36085-whatsnew
[add_dll_directory]: https://docs.python.org/3/library/os.html#os.add_dll_directory
[windows_import_issue]: https://github.com/diegoferigo/cmake-build-extension/issues/8
[windows_import_pr]: https://github.com/diegoferigo/cmake-build-extension/pull/12

### `setup.py|setup.cfg|pyproject.toml` files in subfolder

Sometimes hybrid projects are C++ centric, and keeping these files in the top-level folder is not desirable.
In this setup, however, problems occur if the main `CMakeLists.txt` is kept in the top-level folder 
(see [pypa/build#322][sdist_issue]).
To solve this problem, `cmake-build-extension` provides custom commands to create source distribution.
You can use one of the following custom `sdist` options in `setup.py`:

```python
setuptools.setup(
    cmdclass=dict(
        # [...]
        # Pack the whole git folder:
        sdist=cmake_build_extension.GitSdistFolder,
        # Pack only the git tree:
        sdist=cmake_build_extension.GitSdistTree,
        # Or, inherit from cmake_build_extension.sdist_command.GitSdistABC and
        # make your own custom sdist including only the files you are interested
    ),
)
```

[sdist_issue]: https://github.com/pypa/build/issues/322

## Downstream projects

If the provided example is not enough complex, find here below a list of projects using `cmake-build-extension`: 

- [`robotology/idyntree`](https://github.com/robotology/idyntree/)
- [`robotology/yarp`](https://github.com/robotology/yarp/)
- [`robotology/ycm`](https://github.com/robotology/ycm/)
- [`diegoferigo/gazebo-yarp-synchronizer`](https://github.com/diegoferigo/gazebo-yarp-synchronizer)
- [`robotology/gym-ignition@scenario`](https://github.com/robotology/gym-ignition/tree/devel/scenario)
- [`dic-iit/gazebo-scenario-plugins`](https://github.com/dic-iit/gazebo-scenario-plugins/)
- [`dic-iit/bipedal-locomotion-framework`](https://github.com/dic-iit/bipedal-locomotion-framework)
- [`artivis/manif`](https://github.com/artivis/manif)

## Contributing

Pull requests are welcome. For major changes, please open an issue first to discuss what you would like to change.

## License

[MIT](https://choosealicense.com/licenses/mit/)


%prep
%autosetup -n cmake-build-extension-0.5.1

%build
%py3_build

%install
%py3_install
install -d -m755 %{buildroot}/%{_pkgdocdir}
if [ -d doc ]; then cp -arf doc %{buildroot}/%{_pkgdocdir}; fi
if [ -d docs ]; then cp -arf docs %{buildroot}/%{_pkgdocdir}; fi
if [ -d example ]; then cp -arf example %{buildroot}/%{_pkgdocdir}; fi
if [ -d examples ]; then cp -arf examples %{buildroot}/%{_pkgdocdir}; fi
pushd %{buildroot}
if [ -d usr/lib ]; then
	find usr/lib -type f -printf "/%h/%f\n" >> filelist.lst
fi
if [ -d usr/lib64 ]; then
	find usr/lib64 -type f -printf "/%h/%f\n" >> filelist.lst
fi
if [ -d usr/bin ]; then
	find usr/bin -type f -printf "/%h/%f\n" >> filelist.lst
fi
if [ -d usr/sbin ]; then
	find usr/sbin -type f -printf "/%h/%f\n" >> filelist.lst
fi
touch doclist.lst
if [ -d usr/share/man ]; then
	find usr/share/man -type f -printf "/%h/%f.gz\n" >> doclist.lst
fi
popd
mv %{buildroot}/filelist.lst .
mv %{buildroot}/doclist.lst .

%files -n python3-cmake-build-extension -f filelist.lst
%dir %{python3_sitelib}/*

%files help -f doclist.lst
%{_docdir}/*

%changelog
* Fri May 05 2023 Python_Bot <Python_Bot@openeuler.org> - 0.5.1-1
- Package Spec generated