nautilus_core/python/
version.rs

1// -------------------------------------------------------------------------------------------------
2//  Copyright (C) 2015-2025 Nautech Systems Pty Ltd. All rights reserved.
3//  https://nautechsystems.io
4//
5//  Licensed under the GNU Lesser General Public License Version 3.0 (the "License");
6//  You may not use this file except in compliance with the License.
7//  You may obtain a copy of the License at https://www.gnu.org/licenses/lgpl-3.0.en.html
8//
9//  Unless required by applicable law or agreed to in writing, software
10//  distributed under the License is distributed on an "AS IS" BASIS,
11//  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12//  See the License for the specific language governing permissions and
13//  limitations under the License.
14// -------------------------------------------------------------------------------------------------
15
16use pyo3::{prelude::*, types::PyTuple};
17
18#[must_use]
19pub fn get_python_version() -> String {
20    Python::with_gil(|py| {
21        let sys = match py.import("sys") {
22            Ok(mod_sys) => mod_sys,
23            Err(_) => return "Unavailable (failed to import sys)".to_string(),
24        };
25
26        let version_info = match sys.getattr("version_info") {
27            Ok(info) => info,
28            Err(_) => return "Unavailable (version_info not found)".to_string(),
29        };
30
31        let version_tuple: &Bound<'_, PyTuple> = version_info
32            .downcast::<PyTuple>()
33            .expect("Failed to extract version_info");
34
35        let major = version_tuple
36            .get_item(0)
37            .expect("Failed to get major version")
38            .extract::<i32>()
39            .unwrap_or(-1);
40        let minor = version_tuple
41            .get_item(1)
42            .expect("Failed to get minor version")
43            .extract::<i32>()
44            .unwrap_or(-1);
45        let micro = version_tuple
46            .get_item(2)
47            .expect("Failed to get micro version")
48            .extract::<i32>()
49            .unwrap_or(-1);
50
51        if major == -1 || minor == -1 || micro == -1 {
52            "Unavailable (failed to extract version components)".to_string()
53        } else {
54            format!("{major}.{minor}.{micro}")
55        }
56    })
57}
58
59#[must_use]
60pub fn get_python_package_version(package_name: &str) -> String {
61    Python::with_gil(|py| match py.import(package_name) {
62        Ok(package) => match package.getattr("__version__") {
63            Ok(version_attr) => match version_attr.extract::<String>() {
64                Ok(version) => version,
65                Err(_) => "Unavailable (failed to extract version)".to_string(),
66            },
67            Err(_) => "Unavailable (__version__ attribute not found)".to_string(),
68        },
69        Err(_) => "Unavailable (failed to import package)".to_string(),
70    })
71}