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

suitesparse-config: new recipe #23540

Open
wants to merge 5 commits into
base: master
Choose a base branch
from
Open
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
4 changes: 4 additions & 0 deletions recipes/suitesparse-config/all/conandata.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
sources:
"7.7.0":
url: "https://github.com/DrTimothyAldenDavis/SuiteSparse/archive/refs/tags/v7.7.0.tar.gz"
sha256: "529b067f5d80981f45ddf6766627b8fc5af619822f068f342aab776e683df4f3"
103 changes: 103 additions & 0 deletions recipes/suitesparse-config/all/conanfile.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,103 @@
import os
import re

from conan import ConanFile
from conan.tools.cmake import CMake, CMakeDeps, CMakeToolchain, cmake_layout
from conan.tools.env import VirtualBuildEnv
from conan.tools.files import get, rm, rmdir, load, save

required_conan_version = ">=1.53.0"


class SuiteSparseConfigConan(ConanFile):
name = "suitesparse-config"
description = "Configuration for SuiteSparse libraries"
license = "BSD-3-Clause"
url = "https://github.com/conan-io/conan-center-index"
homepage = "https://people.engr.tamu.edu/davis/suitesparse.html"
topics = ("mathematics", "sparse-matrix", "linear-algebra")

package_type = "library"
settings = "os", "arch", "compiler", "build_type"
options = {
"shared": [True, False],
"fPIC": [True, False],
}
default_options = {
"shared": False,
"fPIC": True,
}

def config_options(self):
if self.settings.os == "Windows":
del self.options.fPIC

def configure(self):
if self.options.shared:
self.options.rm_safe("fPIC")
self.settings.rm_safe("compiler.cppstd")
self.settings.rm_safe("compiler.libcxx")

def layout(self):
cmake_layout(self, src_folder="src")

def requirements(self):
self.requires("openblas/0.3.28", transitive_headers=True, transitive_libs=True)
self.requires("llvm-openmp/18.1.8", transitive_headers=True, transitive_libs=True)

def build_requirements(self):
self.tool_requires("cmake/[>=3.22 <4]")

def source(self):
get(self, **self.conan_data["sources"][self.version], strip_root=True)

def generate(self):
venv = VirtualBuildEnv(self)
venv.generate()

tc = CMakeToolchain(self)
tc.variables["BUILD_SHARED_LIBS"] = self.options.shared
tc.variables["BUILD_STATIC_LIBS"] = not self.options.shared
tc.variables["SUITESPARSE_USE_OPENMP"] = True
tc.variables["SUITESPARSE_USE_CUDA"] = False
tc.variables["BLA_VENDOR"] = "OpenBLAS"
tc.variables["SUITESPARSE_DEMOS"] = False
tc.variables["SUITESPARSE_USE_STRICT"] = True # don't allow implicit dependencies
tc.variables["SUITESPARSE_USE_FORTRAN"] = False # Fortran sources are translated to C instead
tc.generate()

deps = CMakeDeps(self)
deps.generate()

def build(self):
cmake = CMake(self)
cmake.configure(build_script_folder=os.path.join(self.source_folder, "SuiteSparse_config"))
cmake.build()

def _copy_license(self):
# Extract the license applicable to SuiteSparse_config from all licenses in SuiteSparse
full_license_info = load(self, os.path.join(self.source_folder, "LICENSE.txt"))
bsd3 = re.search(r"==> Example License <==\n\n(.+?)\n==> ParU License <==", full_license_info, re.DOTALL).group(1)
save(self, os.path.join(self.package_folder, "licenses", "LICENSE.txt"), bsd3)

def package(self):
self._copy_license()
cmake = CMake(self)
cmake.install()
rmdir(self, os.path.join(self.package_folder, "lib", "pkgconfig"))
rmdir(self, os.path.join(self.package_folder, "lib", "cmake"))
rmdir(self, os.path.join(self.package_folder, "share"))
rm(self, "*.pdb", self.package_folder, recursive=True)

def package_info(self):
self.cpp_info.set_property("cmake_file_name", "SuiteSparse_config")
self.cpp_info.set_property("cmake_target_name", "SuiteSparse::SuiteSparseConfig")
if not self.options.shared:
self.cpp_info.set_property("cmake_target_aliases", ["SuiteSparse::SuiteSparseConfig_static"])
self.cpp_info.set_property("pkg_config_name", "SuiteSparse_config")

self.cpp_info.libs = ["suitesparseconfig"]
self.cpp_info.includedirs.append(os.path.join("include", "suitesparse"))

if self.settings.os in ["Linux", "FreeBSD"]:
self.cpp_info.system_libs.append("m")
8 changes: 8 additions & 0 deletions recipes/suitesparse-config/all/test_package/CMakeLists.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
cmake_minimum_required(VERSION 3.15)
project(test_package LANGUAGES C)

find_package(SuiteSparse_config REQUIRED CONFIG)

add_executable(${PROJECT_NAME} test_package.c)
target_link_libraries(${PROJECT_NAME} PRIVATE SuiteSparse::SuiteSparseConfig)
target_compile_features(${PROJECT_NAME} PRIVATE c_std_99)
26 changes: 26 additions & 0 deletions recipes/suitesparse-config/all/test_package/conanfile.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
from conan import ConanFile
from conan.tools.build import can_run
from conan.tools.cmake import cmake_layout, CMake
import os


class TestPackageConan(ConanFile):
settings = "os", "arch", "compiler", "build_type"
generators = "CMakeDeps", "CMakeToolchain", "VirtualRunEnv"
test_type = "explicit"

def requirements(self):
self.requires(self.tested_reference_str)

def layout(self):
cmake_layout(self)

def build(self):
cmake = CMake(self)
cmake.configure()
cmake.build()

def test(self):
if can_run(self):
bin_path = os.path.join(self.cpp.build.bindir, "test_package")
self.run(bin_path, env="conanrun")
7 changes: 7 additions & 0 deletions recipes/suitesparse-config/all/test_package/test_package.c
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
#include <SuiteSparse_config.h>

int main() {
void* x = SuiteSparse_config_malloc(10);
SuiteSparse_config_free(x);
return 0;
}
3 changes: 3 additions & 0 deletions recipes/suitesparse-config/config.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
versions:
"7.7.0":
folder: all
133 changes: 133 additions & 0 deletions recipes/suitesparse-config/update_suitesparse.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,133 @@
#!/usr/bin/env python3

# Usage: ./update_suitesparse.py <new_version>
#
# Updates all `suitesparse-*` sub-packages based on the source archive automatically downloaded of the given version.

import hashlib
import io
import re
import sys
import tarfile
import textwrap
from pathlib import Path

import requests
import yaml
from conan.tools.scm import Version

recipes_root = Path(__file__).resolve().parent.parent

def quoted_presenter(dumper, data):
return dumper.represent_scalar('tag:yaml.org,2002:str', data, style='"')

yaml.add_representer(str, quoted_presenter)

def download(url):
print(f"Downloading {url}...")
r = requests.get(url)
r.raise_for_status()
return r.content


def sha256(data):
sha = hashlib.sha256()
sha.update(data)
return sha.hexdigest()


def extract_version(content):
major = re.search(r"^set *\( *(\w+)_VERSION_MAJOR +(\d+) ", content, re.M).group(2)
minor = re.search(r"^set *\( *(\w+)_VERSION_MINOR +(\d+) ", content, re.M).group(2)
sub = re.search(r"^set *\( *(\w+)_VERSION_(?:SUB|PATCH|UPDATE) +(\d+) ", content, re.M).group(2)
return f"{major}.{minor}.{sub}"


def load_versions(tar_gz_bytes):
versions = {}
tar_gz_file = io.BytesIO(tar_gz_bytes)
with tarfile.open(fileobj=tar_gz_file, mode="r:gz") as tar:
for member in tar.getmembers():
if not member.isfile():
continue
if m := re.fullmatch(r"SuiteSparse-[^/]+/(\w+)/CMakeLists.txt", member.name):
name = m.group(1)
if name in ["Example", "GraphBLAS", "CSparse"]:
continue
content = tar.extractfile(member).read().decode("utf8")
pkg_name = "suitesparse-config" if name == "SuiteSparse_config" else "suitesparse-" + name.lower()
versions[pkg_name] = extract_version(content)
elif member.name.endswith("GraphBLAS_version.cmake"):
content = tar.extractfile(member).read().decode("utf8")
versions["suitesparse-graphblas"] = extract_version(content)
return versions


def update_config_yml(pkg_name, new_version):
config_yml_path = recipes_root / pkg_name / "config.yml"
info = yaml.safe_load(config_yml_path.read_text("utf8"))
latest = str(max(Version(v) for v in info["versions"]))
if latest == new_version:
print(f"{pkg_name}: already up-to-date ({latest})")
return False
print(f"{pkg_name}: updating from {latest} to {new_version}...")
content = config_yml_path.read_text("utf8")
content, n = re.subn("versions:\n", f'versions:\n "{new_version}":\n folder: all\n', content)
if n != 1:
raise ValueError("Failed to update versions in config.yml")
config_yml_path.write_text(content, "utf8")
return True

def update_conandata_yml(pkg_name, new_version, url, archive_hash):
config_yml_path = recipes_root / pkg_name / "all" / "conandata.yml"
content = config_yml_path.read_text("utf8")
conandata = yaml.safe_load(content)
content, n = re.subn("sources:\n", f'sources:\n "{new_version}":\n url: "{url}"\n sha256: "{archive_hash}"\n', content)
if n != 1:
raise ValueError("Failed to update sources in conandata.yml")
if "patches" in conandata:
newest = str(max(Version(v) for v in conandata["patches"]))
patches = conandata["patches"][newest]
patches_yaml = textwrap.indent(yaml.dump(patches, default_flow_style=False, sort_keys=False), " ")
patches_yaml = re.sub(r'"(\w+)":', r'\1:', patches_yaml)
content, n = re.subn("patches:\n", f'patches:\n "{new_version}":\n{patches_yaml}', content)
if n != 1:
raise ValueError("Failed to update patches in conandata.yml")
config_yml_path.write_text(content, "utf8")


def update_conanfile_py(pkg_name, versions):
conanfile_py_path = recipes_root / pkg_name / "all" / "conanfile.py"
content = conanfile_py_path.read_text("utf8")
# update dependency versions
for pkg, new_version in versions.items():
content = re.sub(rf'"{pkg}/\S+"', f'"{pkg}/{new_version}"', content)
conanfile_py_path.write_text(content, "utf8")


def main(suitesparse_version):
suitesparse_url = (
f"https://github.com/DrTimothyAldenDavis/SuiteSparse/archive/refs/tags/v{suitesparse_version}.tar.gz"
)
tar_gz_bytes = download(suitesparse_url)
suitesparse_hash = sha256(tar_gz_bytes)
print("Reading versions from CMakeLists.txt files...")
versions = load_versions(tar_gz_bytes)
for pkg_name, new_version in versions.items():
needs_updating = update_config_yml(pkg_name, new_version)
if needs_updating:
if pkg_name == "suitesparse-graphblas":
graphblas_url = f"https://github.com/DrTimothyAldenDavis/GraphBLAS/archive/refs/tags/v{new_version}.tar.gz"
graphblas_hash = sha256(download(graphblas_url))
update_conandata_yml(pkg_name, new_version, graphblas_url, graphblas_hash)
else:
update_conandata_yml(pkg_name, new_version, suitesparse_url, suitesparse_hash)
update_conanfile_py(pkg_name, versions)


if __name__ == "__main__":
if len(sys.argv) != 2:
print("Usage: ./update_suitesparse.py <new_version>")
sys.exit(1)
suitesparse_version = sys.argv[1]
main(suitesparse_version)