Skip to main content

dora_core/
lib.rs

1//! **Internal to dora — not a public API.**
2//!
3//! This crate is published to crates.io only because cargo requires every
4//! dependency of a published crate to be published; `dora-node-api` and
5//! `dora-cli` depend on it. It is not covered by dora's 1.0 stability
6//! guarantee and may change in any release, including a patch.
7//!
8//! Depend on it directly at your own risk. See the "Stability scope at 1.0"
9//! section of `docs/api-rust.md`.
10//!
11use eyre::{Context, bail, eyre};
12use std::{
13    env::consts::{DLL_PREFIX, DLL_SUFFIX},
14    path::Path,
15};
16
17pub use dora_message::{config, uhlc};
18
19#[cfg(feature = "build")]
20pub mod build;
21pub mod debug_topic;
22pub mod descriptor;
23pub mod manifest;
24pub mod schema_once;
25pub mod topics;
26pub mod types;
27
28/// Adjusts a shared library path by adding the platform-specific prefix and suffix.
29///
30/// Takes a base path (without platform-specific prefix and extension) and returns
31/// a path with the appropriate shared library naming conventions using
32/// [`DLL_PREFIX`] and [`DLL_SUFFIX`].
33///
34/// # Errors
35///
36/// Returns an error if the path has no file name, contains invalid UTF-8,
37/// already starts with `lib`, or already has an extension.
38///
39/// # Example
40///
41/// ```
42/// use std::path::Path;
43/// use dora_core::adjust_shared_library_path;
44///
45/// let adjusted = adjust_shared_library_path(Path::new("mylib")).unwrap();
46/// let expected = format!("{}mylib{}", std::env::consts::DLL_PREFIX, std::env::consts::DLL_SUFFIX);
47/// assert_eq!(adjusted.file_name().unwrap().to_str().unwrap(), expected);
48/// ```
49pub fn adjust_shared_library_path(path: &Path) -> Result<std::path::PathBuf, eyre::ErrReport> {
50    let file_name = path
51        .file_name()
52        .ok_or_else(|| eyre!("shared library path has no file name"))?
53        .to_str()
54        .ok_or_else(|| eyre!("shared library file name is not valid UTF8"))?;
55    if file_name.starts_with("lib") {
56        bail!("Shared library file name must not start with `lib`, prefix is added automatically");
57    }
58    if path.extension().is_some() {
59        bail!("Shared library file name must have no extension, it is added automatically");
60    }
61
62    let library_filename = format!("{DLL_PREFIX}{file_name}{DLL_SUFFIX}");
63
64    let path = path.with_file_name(library_filename);
65    Ok(path)
66}
67
68/// Locate a Python 3 interpreter, in order of preference:
69///
70/// 1. If `uv` is available, use `uv python find` to get the Python path.
71/// 2. Otherwise, try `python` and check it is not Python 2.
72/// 3. Fall back to `python3` if `python` is Python 2 (or absent).
73///
74/// Returns an error only if none of the above yields a usable Python 3.
75pub fn get_python_path() -> Result<std::path::PathBuf, eyre::ErrReport> {
76    // First, try using uv if available
77    if let Ok(uv_path) = get_uv_path() {
78        let output = std::process::Command::new(&uv_path)
79            .args(["python", "find"])
80            .output();
81
82        if let Ok(output) = output
83            && output.status.success()
84        {
85            let python_path = String::from_utf8_lossy(&output.stdout).trim().to_string();
86            if !python_path.is_empty() {
87                let path = std::path::PathBuf::from(&python_path);
88                if path.exists() {
89                    return Ok(path);
90                }
91            }
92        }
93    }
94
95    // Fall back to finding python directly
96    if let Ok(python) = which::which("python") {
97        // Check if it's Python 2
98        if !is_python2(&python) {
99            return Ok(python);
100        }
101    }
102
103    // Fall back to python3
104    which::which("python3").context(
105        "failed to find a valid Python 3 installation. Make sure that python3 is available.",
106    )
107}
108
109fn is_python2(python_path: &std::path::Path) -> bool {
110    let output = std::process::Command::new(python_path)
111        .args(["--version"])
112        .output();
113
114    match output {
115        Ok(output) => {
116            // Python 2 prints version to stderr, Python 3 to stdout
117            let version = if output.stdout.is_empty() {
118                String::from_utf8_lossy(&output.stderr)
119            } else {
120                String::from_utf8_lossy(&output.stdout)
121            };
122            version.starts_with("Python 2")
123        }
124        Err(_) => false,
125    }
126}
127
128/// Locate the `uv` binary on `PATH`, erroring with an install hint if it is
129/// not found.
130pub fn get_uv_path() -> Result<std::path::PathBuf, eyre::ErrReport> {
131    which::which("uv")
132        .context("failed to find `uv`. Make sure to install it using: https://docs.astral.sh/uv/getting-started/installation/")
133}