Skip to content

Commit b3635d7

Browse files
committed
Use utilities from setup.py to check if netcdf has parallel support
1 parent 05a5ce4 commit b3635d7

2 files changed

Lines changed: 131 additions & 24 deletions

File tree

‎_build/backend.py‎

Lines changed: 4 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -1,36 +1,16 @@
11
# -*- coding: utf-8 -*-
2-
import logging
3-
import os
42
from setuptools.build_meta import *
5-
import subprocess
63

7-
8-
fmt = logging.Formatter("\n=== NETCDF4 BUILD DEBUG: %(message)s\n")
9-
hdlr = logging.StreamHandler()
10-
hdlr.setFormatter(fmt)
11-
log = logging.getLogger(__name__)
12-
log.setLevel(logging.DEBUG)
13-
log.addHandler(hdlr)
14-
15-
16-
def netcdf_has_parallel_support():
17-
netcdf4_dir = os.environ.get("NETCDF4_DIR")
18-
ncconfig = (
19-
os.path.join(netcdf4_dir, "bin", "nc-config") if netcdf4_dir else "nc-config"
20-
)
21-
log.debug(f"{ncconfig = }")
22-
process = subprocess.run([ncconfig, "--has-parallel4"], capture_output=True)
23-
out = process.stdout.decode("utf-8").rstrip()
24-
return out == "yes"
4+
import utils
255

266

277
def get_requires_for_build_editable(config_settings=None):
28-
return ["mpi4py>=3.1,<4.1"] if netcdf_has_parallel_support() else []
8+
return ["mpi4py>=3.1,<4.1"] if utils.netcdf4_has_parallel_support() else []
299

3010

3111
def get_requires_for_build_sdist(config_settings=None):
32-
return ["mpi4py>=3.1,<4.1"] if netcdf_has_parallel_support() else []
12+
return ["mpi4py>=3.1,<4.1"] if utils.netcdf4_has_parallel_support() else []
3313

3414

3515
def get_requires_for_build_wheel(config_settings=None):
36-
return ["mpi4py>=3.1,<4.1"] if netcdf_has_parallel_support() else []
16+
return ["mpi4py>=3.1,<4.1"] if utils.netcdf4_has_parallel_support() else []

‎_build/utils.py‎

Lines changed: 127 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,127 @@
1+
# -*- coding: utf-8 -*-
2+
"""
3+
This module contains a streamlined version of some utilities defined in `setup.py`, to be at
4+
disposal of in-tree build backends.
5+
"""
6+
7+
import configparser
8+
import os
9+
import subprocess
10+
11+
12+
PROJECT_ROOT_DIR = os.path.abspath(os.path.join(os.path.dirname(__file__), ".."))
13+
OPEN_KWARGS = {"encoding": "utf-8"}
14+
15+
16+
def get_config_flags(command: list[str], flag: str) -> list[str]:
17+
"""Pull out specific flags from a config command (pkg-config or nc-config)"""
18+
flags = subprocess.run(command, capture_output=True, text=True)
19+
return [arg[2:] for arg in flags.stdout.split() if arg.startswith(flag)]
20+
21+
22+
def is_netcdf4_include_dir(inc_dir: str) -> bool:
23+
try:
24+
f = open(os.path.join(inc_dir, "netcdf.h"), **OPEN_KWARGS)
25+
except OSError:
26+
return False
27+
28+
for line in f:
29+
if line.startswith("nc_inq_compound"):
30+
return True
31+
return False
32+
33+
34+
def get_netcdf4_include_dir():
35+
netcdf4_dir = os.environ.get("NETCDF4_DIR")
36+
netcdf4_incdir = os.environ.get("NETCDF4_INCDIR")
37+
38+
if bool(int(os.environ.get("USE_SETUPCFG", 1))) and os.path.exists(
39+
setup_cfg := os.path.join(PROJECT_ROOT_DIR, "setup.cfg")
40+
):
41+
config = configparser.ConfigParser()
42+
config.read(setup_cfg)
43+
44+
netcdf4_dir = config.get("directories", "NETCDF4_DIR", fallback=netcdf4_dir)
45+
netcdf4_incdir = config.get(
46+
"directories", "NETCDF4_INCDIR", fallback=netcdf4_incdir
47+
)
48+
49+
# make sure USE_NCCONFIG from environment takes precedence over use_ncconfig from setup.cfg
50+
# (issue #341)
51+
if "USE_NCCONFIG" in os.environ:
52+
use_ncconfig = bool(int(os.environ.get("USE_NCCONFIG", 0)))
53+
else:
54+
use_ncconfig = config.getboolean("options", "use_ncconfig", fallback=None)
55+
56+
ncconfig = config.get("options", "ncconfig", fallback=None)
57+
else:
58+
use_ncconfig = None
59+
ncconfig = None
60+
61+
try:
62+
if ncconfig is None:
63+
if netcdf4_dir is not None:
64+
ncconfig = os.path.join(netcdf4_dir, "bin", "nc-config")
65+
else: # otherwise, just hope it's in the users PATH
66+
ncconfig = "nc-config"
67+
has_ncconfig = subprocess.call([ncconfig, "--libs"]) == 0
68+
except OSError:
69+
has_ncconfig = False
70+
71+
# if nc-config exists, and USE_NCCONFIG not set, try to use it
72+
if use_ncconfig is None and has_ncconfig:
73+
use_ncconfig = has_ncconfig
74+
75+
dirs_to_search = []
76+
if os.environ.get("CONDA_PREFIX"):
77+
dirs_to_search.append(os.environ["CONDA_PREFIX"]) # linux,macosx
78+
dirs_to_search.append(
79+
os.path.join(os.environ["CONDA_PREFIX"], "Library")
80+
) # windows
81+
dirs_to_search += [
82+
os.path.expanduser("~"),
83+
"/usr/local",
84+
"/sw",
85+
"/opt",
86+
"/opt/local",
87+
"/opt/homebrew",
88+
"/usr",
89+
]
90+
91+
if netcdf4_incdir is None and netcdf4_dir is None:
92+
if use_ncconfig and has_ncconfig:
93+
inc_dirs = get_config_flags([ncconfig, "--cflags"], "-I")
94+
else:
95+
inc_dirs = [os.path.join(dir_, "include") for dir_ in dirs_to_search]
96+
97+
for inc_dir in inc_dirs:
98+
if is_netcdf4_include_dir(inc_dir):
99+
netcdf4_incdir = inc_dir
100+
break
101+
102+
if netcdf4_incdir is None:
103+
raise ValueError("Did not find netCDF version 4 headers.")
104+
else:
105+
if netcdf4_incdir is None:
106+
netcdf4_incdir = os.path.join(netcdf4_dir, "include")
107+
if not is_netcdf4_include_dir(netcdf4_incdir):
108+
raise ValueError(
109+
f"Did not find netCDF version 4 headers under `{netcdf4_incdir}`."
110+
)
111+
112+
return netcdf4_incdir
113+
114+
115+
def netcdf4_has_parallel_support() -> bool:
116+
netcdf4_incdir = get_netcdf4_include_dir()
117+
if os.path.exists(ncmetapath := os.path.join(netcdf4_incdir, "netcdf_meta.h")):
118+
with open(ncmetapath) as f:
119+
for line in f:
120+
if line.startswith("#define NC_HAS_PARALLEL"):
121+
try:
122+
return bool(int(line.split()[2]))
123+
except ValueError:
124+
pass
125+
return False
126+
else:
127+
return False

0 commit comments

Comments
 (0)