FairShip
Loading...
Searching...
No Matches
saveBasicParameters.py
Go to the documentation of this file.
1# SPDX-License-Identifier: LGPL-3.0-or-later
2# SPDX-FileCopyrightText: Copyright CERN for the benefit of the SHiP Collaboration
3
4import contextlib
5import os
6import re
7import subprocess
8
9import ROOT
10from ShipGeoConfig import Config
11
12
13def libraryPath(library):
14 """Path of the library this process has loaded, else of the one it would load."""
15 for path in str(ROOT.gSystem.GetLibraries(library, "", False)).split():
16 if os.path.basename(path).startswith(library + "."):
17 return path
18 return ROOT.gSystem.FindDynamicLibrary(ROOT.TString(library), True)
19
20
21def versionFromHeader(library, header, version_macro, git_macro):
22 """Version of a library, from the version header installed with it.
23
24 The library is the loaded one, or the one that would be loaded if it is not
25 loaded yet. The header is next to the library's lib/ directory: in include/
26 of an install prefix (conda, cmake --install), or at the top of a build
27 directory.
28 """
29 path = libraryPath(library)
30 if not path:
31 return None
32 prefix = os.path.dirname(os.path.dirname(path))
33 for candidate in (os.path.join(prefix, "include", header), os.path.join(prefix, header)):
34 with contextlib.suppress(OSError):
35 with open(candidate) as f:
36 macros = dict(re.findall(r'#define\s+(\w+)\s+"([^"]*)"', f.read()))
37 version = macros.get(version_macro)
38 if not version:
39 continue
40 git = macros.get(git_macro)
41 return f"{version} ({git})" if git else version
42 return None
43
44
46 """Record the versions this run uses, dropping any it cannot determine.
47
48 FairShip is the Python source (FAIRSHIP_HASH from aliBuild, else its git
49 commit), FairShipLibrary the compiled libraries, which differ from it when
50 they come from the conda package.
51 """
52 versions = {"FairShip": None}
53 if "FAIRSHIP_HASH" in os.environ:
54 versions["FairShip"] = os.environ["FAIRSHIP_HASH"]
55 else:
56 source_dir = os.environ.get("FAIRSHIP", os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
57 with contextlib.suppress(subprocess.CalledProcessError, FileNotFoundError):
58 versions["FairShip"] = subprocess.check_output(
59 ["git", "-C", source_dir, "rev-parse", "HEAD"],
60 text=True,
61 stderr=subprocess.DEVNULL,
62 ).strip()
63 versions["FairShipLibrary"] = versionFromHeader(
64 "libShipData", "FairShipVersion.h", "FAIRSHIP_VERSION", "FAIRSHIP_GIT_HASH"
65 )
66 versions["FairRoot"] = os.environ.get("FAIRROOT_HASH") or versionFromHeader(
67 "libBase", "FairVersion.h", "FAIRROOT_VERSION", "FAIRROOT_GIT_VERSION"
68 )
69 for key, version in versions.items():
70 if version:
71 o[key] = version
72 else:
73 o.pop(key, None)
74 return o
75
76
77def execute(f, ox, name="ShipGeo"):
78 """Save geometry configuration to ROOT file as JSON string"""
79 if isinstance(ox, str):
80 # A string input is the JSON serialisation of the config; parse it into a
81 # Config so the content is preserved and dumps_json() is available.
82 ox = Config().loads_json(ox)
83 o = retrieveGitTags(ox)
84
85 if isinstance(f, str):
86 fg = ROOT.TFile.Open(f, "update")
87 else:
88 fg = f
89
90 # Serialize to JSON
91 json_str = o.dumps_json()
92
93 # Save as std::string in ROOT file
94 fg.cd()
95 config_str = ROOT.std.string(json_str)
96 fg.WriteObject(config_str, name)
97 fg.Flush()
98
99 if isinstance(f, str):
100 fg.Close()
execute(f, ox, name="ShipGeo")
versionFromHeader(library, header, version_macro, git_macro)