runmat-config 0.6.2

Shared configuration schema and loaders for RunMat
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
use super::manifest::{path_is_dir_async, ProjectManifest};
use serde::{Deserialize, Serialize};
use std::fs;
use std::path::{Path, PathBuf};
use thiserror::Error;

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)]
pub struct ProjectSourceIndex {
    pub files: Vec<ProjectSourceFile>,
    pub package_dirs: Vec<PathBuf>,
    pub class_dirs: Vec<PathBuf>,
    pub private_dirs: Vec<PathBuf>,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ProjectSourceFile {
    pub source_root: PathBuf,
    pub relative_path: PathBuf,
    pub qualified_name: String,
    #[serde(default)]
    pub package_path: Option<String>,
    #[serde(default)]
    pub class_name: Option<String>,
    /// Canonical class scope contributed by `@Class` folders. This intentionally
    /// excludes the file stem: `@Report/Report.m` and `@Report/title.m` both
    /// belong to class `Report`, while their callable file identities remain
    /// `Report.Report` and `Report.title` respectively.
    #[serde(default)]
    pub class_qualified_name: Option<String>,
    pub is_private: bool,
}

impl ProjectSourceFile {
    /// The canonical name to apply to a parsed `classdef` source.
    pub fn class_definition_qualified_name(&self) -> Option<&str> {
        self.class_qualified_name.as_deref().or_else(|| {
            self.package_path
                .as_ref()
                .map(|_| self.qualified_name.as_str())
        })
    }

    /// The callable identity for a parsed function or class-folder member file.
    pub fn function_qualified_name(&self) -> Option<&str> {
        if self.is_private {
            return None;
        }
        (self.package_path.is_some() || self.class_name.is_some())
            .then_some(self.qualified_name.as_str())
            .filter(|name| name.contains('.'))
    }
}

#[derive(Debug, Error)]
pub enum ProjectSourceIndexError {
    #[error("source root does not exist or is not a directory: {root}")]
    InvalidSourceRoot { root: PathBuf },
    #[error("failed to read source path {path}: {source}")]
    ReadDir {
        path: PathBuf,
        #[source]
        source: std::io::Error,
    },
    #[error("failed to read source entry under {path}: {source}")]
    ReadEntry {
        path: PathBuf,
        #[source]
        source: std::io::Error,
    },
}

pub fn build_project_source_index(
    project_root: &Path,
    manifest: &ProjectManifest,
) -> Result<ProjectSourceIndex, ProjectSourceIndexError> {
    let mut index = ProjectSourceIndex::default();
    for source_root in &manifest.sources.roots {
        let absolute_root = project_root.join(source_root);
        if !absolute_root.is_dir() {
            return Err(ProjectSourceIndexError::InvalidSourceRoot {
                root: source_root.clone(),
            });
        }
        scan_source_dir(
            &absolute_root,
            &absolute_root,
            source_root,
            &ScanState::default(),
            &mut index,
            project_root,
        )?;
    }
    normalize_source_index(&mut index);
    Ok(index)
}

pub async fn build_project_source_index_async(
    project_root: &Path,
    manifest: &ProjectManifest,
) -> Result<ProjectSourceIndex, ProjectSourceIndexError> {
    let mut index = ProjectSourceIndex::default();
    for source_root in &manifest.sources.roots {
        let absolute_root = project_root.join(source_root);
        if !path_is_dir_async(&absolute_root).await {
            return Err(ProjectSourceIndexError::InvalidSourceRoot {
                root: source_root.clone(),
            });
        }
        scan_source_dir_async(
            &absolute_root,
            &absolute_root,
            source_root,
            &ScanState::default(),
            &mut index,
            project_root,
        )
        .await?;
    }
    normalize_source_index(&mut index);
    Ok(index)
}

/// Build the MATLAB lookup index for a folder that has no `runmat.toml`.
pub fn build_loose_source_index(
    root: &Path,
) -> Result<ProjectSourceIndex, ProjectSourceIndexError> {
    let mut index = ProjectSourceIndex::default();
    let entries = fs::read_dir(root).map_err(|source| ProjectSourceIndexError::ReadDir {
        path: root.to_path_buf(),
        source,
    })?;
    let mut entries = entries
        .map(|entry| {
            entry.map_err(|source| ProjectSourceIndexError::ReadEntry {
                path: root.to_path_buf(),
                source,
            })
        })
        .collect::<Result<Vec<_>, _>>()?;
    entries.sort_by_key(|entry| entry.file_name());

    for entry in entries {
        let path = entry.path();
        let file_type = entry
            .file_type()
            .map_err(|source| ProjectSourceIndexError::ReadEntry {
                path: root.to_path_buf(),
                source,
            })?;
        if file_type.is_dir() {
            let name = entry.file_name();
            let name = name.to_string_lossy();
            if name.starts_with('+') || name.starts_with('@') || name == "private" {
                scan_source_dir(
                    &path,
                    root,
                    Path::new("."),
                    &ScanState::default(),
                    &mut index,
                    root,
                )?;
            }
            continue;
        }
        if let Some(source) = project_source_file_from_path(&path, root, Path::new(".")) {
            index.files.push(source);
        }
    }
    normalize_source_index(&mut index);
    Ok(index)
}

pub async fn build_loose_source_index_async(
    root: &Path,
) -> Result<ProjectSourceIndex, ProjectSourceIndexError> {
    let mut index = ProjectSourceIndex::default();
    let mut entries = runmat_filesystem::read_dir_async(root)
        .await
        .map_err(|source| ProjectSourceIndexError::ReadDir {
            path: root.to_path_buf(),
            source,
        })?;
    entries.sort_by_key(|entry| entry.file_name().to_string_lossy().to_string());

    for entry in entries {
        let path = entry.path().to_path_buf();
        if entry.is_dir() {
            let name = entry.file_name().to_string_lossy().to_string();
            if name.starts_with('+') || name.starts_with('@') || name == "private" {
                scan_source_dir_async(
                    &path,
                    root,
                    Path::new("."),
                    &ScanState::default(),
                    &mut index,
                    root,
                )
                .await?;
            }
            continue;
        }
        if let Some(source) = project_source_file_from_path(&path, root, Path::new(".")) {
            index.files.push(source);
        }
    }
    normalize_source_index(&mut index);
    Ok(index)
}

fn normalize_source_index(index: &mut ProjectSourceIndex) {
    index
        .files
        .sort_by(|left, right| left.relative_path.cmp(&right.relative_path));
    index.package_dirs.sort();
    index.package_dirs.dedup();
    index.class_dirs.sort();
    index.class_dirs.dedup();
    index.private_dirs.sort();
    index.private_dirs.dedup();
}

#[derive(Debug, Clone, Default)]
struct ScanState {
    package_segments: Vec<String>,
    module_segments: Vec<String>,
    class_name: Option<String>,
    in_private: bool,
}

/// Normalize one MATLAB source path into the identity used by project
/// composition and loose-file discovery.
pub fn project_source_file_from_path(
    source_path: &Path,
    root_dir: &Path,
    source_root: &Path,
) -> Option<ProjectSourceFile> {
    let relative_path = source_path.strip_prefix(root_dir).ok()?.to_path_buf();
    if !source_path
        .extension()
        .and_then(|extension| extension.to_str())
        .is_some_and(|extension| extension.eq_ignore_ascii_case("m"))
    {
        return None;
    }
    let stem = source_path.file_stem()?.to_str()?.trim();
    if stem.is_empty() {
        return None;
    }

    let mut state = ScanState::default();
    if let Some(parent) = relative_path.parent() {
        for component in parent.components() {
            let segment = component.as_os_str().to_str()?;
            if let Some(package) = segment.strip_prefix('+') {
                if package.is_empty() {
                    return None;
                }
                state.package_segments.push(package.to_string());
            } else if let Some(class) = segment.strip_prefix('@') {
                if class.is_empty() {
                    return None;
                }
                state.class_name = Some(class.to_string());
            } else if segment == "private" {
                state.in_private = true;
            } else {
                state.module_segments.push(segment.to_string());
            }
        }
    }

    let mut qualified_segments = state.package_segments.clone();
    qualified_segments.extend(state.module_segments.iter().cloned());
    let class_qualified_name = state.class_name.as_ref().map(|class_name| {
        let mut class_segments = qualified_segments.clone();
        class_segments.push(class_name.clone());
        class_segments.join(".")
    });
    if let Some(class_name) = &state.class_name {
        qualified_segments.push(class_name.clone());
    }
    qualified_segments.push(stem.to_string());
    let qualified_name = qualified_segments.join(".");
    (!qualified_name.is_empty()).then_some(ProjectSourceFile {
        source_root: source_root.to_path_buf(),
        relative_path,
        qualified_name,
        package_path: (!state.package_segments.is_empty())
            .then(|| state.package_segments.join(".")),
        class_name: state.class_name,
        class_qualified_name,
        is_private: state.in_private,
    })
}

fn scan_source_dir(
    dir: &Path,
    root_absolute: &Path,
    source_root: &Path,
    state: &ScanState,
    index: &mut ProjectSourceIndex,
    project_root: &Path,
) -> Result<(), ProjectSourceIndexError> {
    let mut entries = fs::read_dir(dir).map_err(|source| ProjectSourceIndexError::ReadDir {
        path: dir.to_path_buf(),
        source,
    })?;
    let mut sorted = Vec::new();
    for entry in &mut entries {
        sorted.push(entry.map_err(|source| ProjectSourceIndexError::ReadEntry {
            path: dir.to_path_buf(),
            source,
        })?);
    }
    sorted.sort_by_key(|entry| entry.file_name());

    for entry in sorted {
        let path = entry.path();
        let file_type = entry
            .file_type()
            .map_err(|source| ProjectSourceIndexError::ReadEntry {
                path: dir.to_path_buf(),
                source,
            })?;
        let name = entry.file_name();
        let name = name.to_string_lossy();
        if file_type.is_dir() {
            let mut next = state.clone();
            if let Some(package) = name.strip_prefix('+') {
                if !package.is_empty() {
                    next.package_segments.push(package.to_string());
                    if let Ok(relative) = path.strip_prefix(project_root) {
                        index.package_dirs.push(relative.to_path_buf());
                    }
                }
            } else if let Some(class) = name.strip_prefix('@') {
                if !class.is_empty() {
                    next.class_name = Some(class.to_string());
                    if let Ok(relative) = path.strip_prefix(project_root) {
                        index.class_dirs.push(relative.to_path_buf());
                    }
                }
            } else if name == "private" {
                next.in_private = true;
                if let Ok(relative) = path.strip_prefix(project_root) {
                    index.private_dirs.push(relative.to_path_buf());
                }
            } else {
                next.module_segments.push(name.to_string());
            }
            scan_source_dir(
                &path,
                root_absolute,
                source_root,
                &next,
                index,
                project_root,
            )?;
            continue;
        }
        if let Some(source) = project_source_file_from_path(&path, root_absolute, source_root) {
            index.files.push(source);
        }
    }
    Ok(())
}

async fn scan_source_dir_async(
    dir: &Path,
    root_absolute: &Path,
    source_root: &Path,
    state: &ScanState,
    index: &mut ProjectSourceIndex,
    project_root: &Path,
) -> Result<(), ProjectSourceIndexError> {
    let mut stack = vec![(dir.to_path_buf(), state.clone())];
    while let Some((current_dir, current_state)) = stack.pop() {
        let mut sorted = runmat_filesystem::read_dir_async(&current_dir)
            .await
            .map_err(|source| ProjectSourceIndexError::ReadDir {
                path: current_dir.clone(),
                source,
            })?;
        sorted.sort_by_key(|entry| entry.file_name().to_string_lossy().to_string());

        for entry in sorted {
            let path = entry.path().to_path_buf();
            let name = entry.file_name().to_string_lossy().to_string();
            if entry.is_dir() {
                let mut next = current_state.clone();
                if let Some(package) = name.strip_prefix('+') {
                    if !package.is_empty() {
                        next.package_segments.push(package.to_string());
                        if let Ok(relative) = path.strip_prefix(project_root) {
                            index.package_dirs.push(relative.to_path_buf());
                        }
                    }
                } else if let Some(class) = name.strip_prefix('@') {
                    if !class.is_empty() {
                        next.class_name = Some(class.to_string());
                        if let Ok(relative) = path.strip_prefix(project_root) {
                            index.class_dirs.push(relative.to_path_buf());
                        }
                    }
                } else if name == "private" {
                    next.in_private = true;
                    if let Ok(relative) = path.strip_prefix(project_root) {
                        index.private_dirs.push(relative.to_path_buf());
                    }
                } else {
                    next.module_segments.push(name);
                }
                stack.push((path, next));
                continue;
            }
            if let Some(source) = project_source_file_from_path(&path, root_absolute, source_root) {
                index.files.push(source);
            }
        }
    }
    Ok(())
}