opencrates 3.0.1

Enterprise-grade AI-powered Rust development companion with comprehensive automation, monitoring, and deployment capabilities
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
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
use anyhow::Result;
use serde::{Deserialize, Serialize};
use std::path::{Path, PathBuf};
use tokio::fs;
use walkdir::WalkDir;

/// Comprehensive analysis result for a Rust project
#[derive(Debug, Clone, Serialize, Deserialize)]
// TODO: document this
// TODO: document this
// TODO: document this
pub struct ProjectAnalysis {
    /// Name of the project
    // TODO: document this
    // TODO: document this
    pub name: String,
    /// Root path of the project
    // TODO: document this
    // TODO: document this
    pub path: PathBuf,
    /// File and directory structure analysis
    // TODO: document this
    // TODO: document this
    pub structure: ProjectStructure,
    /// Code metrics and statistics
    // TODO: document this
    // TODO: document this
    pub metrics: ProjectMetrics,
    /// Project dependencies from Cargo.toml
    // TODO: document this
    // TODO: document this
    pub dependencies: Vec<Dependency>,
    /// Detected issues and potential problems
    // TODO: document this
    // TODO: document this
    pub issues: Vec<Issue>,
}

/// File and directory structure information for a project
#[derive(Debug, Clone, Serialize, Deserialize)]
// TODO: document this
// TODO: document this
// TODO: document this
pub struct ProjectStructure {
    /// List of all files in the project
    // TODO: document this
    // TODO: document this
    pub files: Vec<FileInfo>,
    /// List of all directories in the project
    // TODO: document this
    // TODO: document this
    pub directories: Vec<String>,
    /// Total size of all files in bytes
    // TODO: document this
    // TODO: document this
    pub total_size: u64,
}

/// Information about a single file in the project
#[derive(Debug, Clone, Serialize, Deserialize)]
// TODO: document this
// TODO: document this
// TODO: document this
pub struct FileInfo {
    /// Relative path from project root
    // TODO: document this
    // TODO: document this
    pub path: String,
    /// File size in bytes
    // TODO: document this
    // TODO: document this
    pub size: u64,
    /// Number of lines in the file
    // TODO: document this
    // TODO: document this
    pub lines: usize,
    /// Detected programming language or file type
    // TODO: document this
    // TODO: document this
    pub language: String,
}

/// Code metrics and statistics for a project
#[derive(Debug, Clone, Serialize, Deserialize)]
// TODO: document this
// TODO: document this
// TODO: document this
pub struct ProjectMetrics {
    /// Total number of files
    // TODO: document this
    // TODO: document this
    pub total_files: usize,
    /// Number of Rust source files
    // TODO: document this
    // TODO: document this
    pub rust_files: usize,
    /// Number of test files
    // TODO: document this
    // TODO: document this
    pub test_files: usize,
    /// Number of documentation files
    // TODO: document this
    // TODO: document this
    pub doc_files: usize,
    /// Total lines of code across all files
    // TODO: document this
    // TODO: document this
    pub total_lines: usize,
    /// Estimated lines of actual code
    // TODO: document this
    // TODO: document this
    pub code_lines: usize,
    /// Estimated lines of comments
    // TODO: document this
    // TODO: document this
    pub comment_lines: usize,
    /// Estimated blank lines
    // TODO: document this
    // TODO: document this
    pub blank_lines: usize,
}

/// A project dependency from Cargo.toml
#[derive(Debug, Clone, Serialize, Deserialize)]
// TODO: document this
// TODO: document this
// TODO: document this
pub struct Dependency {
    /// Name of the dependency crate
    // TODO: document this
    // TODO: document this
    pub name: String,
    /// Version specification
    // TODO: document this
    // TODO: document this
    pub version: String,
    /// Enabled features for this dependency
    // TODO: document this
    // TODO: document this
    pub features: Vec<String>,
    /// Whether this dependency is optional
    // TODO: document this
    // TODO: document this
    pub optional: bool,
}

/// An issue or potential problem detected in the project
#[derive(Debug, Clone, Serialize, Deserialize)]
// TODO: document this
// TODO: document this
// TODO: document this
pub struct Issue {
    /// Severity level of the issue
    // TODO: document this
    // TODO: document this
    pub severity: IssueSeverity,
    /// Category or type of issue
    // TODO: document this
    // TODO: document this
    pub category: IssueCategory,
    /// Human-readable description of the issue
    // TODO: document this
    // TODO: document this
    pub message: String,
    /// File where the issue was found (if applicable)
    // TODO: document this
    // TODO: document this
    pub file: Option<String>,
    /// Line number where the issue was found (if applicable)
    // TODO: document this
    // TODO: document this
    pub line: Option<usize>,
}

/// Severity levels for project issues
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
// TODO: document this
// TODO: document this
// TODO: document this
pub enum IssueSeverity {
    /// Critical error that prevents compilation or execution
    Error,
    /// Warning that should be addressed
    Warning,
    /// Informational notice
    Info,
}

/// Categories of project issues
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
// TODO: document this
// TODO: document this
// TODO: document this
pub enum IssueCategory {
    /// Security-related issues
    Security,
    /// Performance-related issues
    Performance,
    /// Code style and formatting issues
    Style,
    /// Documentation-related issues
    Documentation,
    /// Dependency-related issues
    Dependency,
}

/// Analyzer for Rust projects that provides comprehensive analysis
// TODO: document this
// TODO: document this
// TODO: document this
pub struct ProjectAnalyzer;

impl Default for ProjectAnalyzer {
    fn default() -> Self {
        Self::new()
    }
}

impl ProjectAnalyzer {
    /// Create a new project analyzer
    // TODO: document this
    // TODO: document this
    // TODO: document this
    // TODO: document this
    #[must_use]
    pub fn new() -> Self {
        Self
    }

    /// Perform comprehensive analysis of a Rust project
    ///
    /// # Arguments
    /// * `project_path` - Path to the root directory of the project
    ///
    /// # Returns
    /// A `ProjectAnalysis` containing all analysis results
    // TODO: document this
    // TODO: document this
    // TODO: document this
    // TODO: document this
    pub async fn analyze(&self, project_path: &Path) -> Result<ProjectAnalysis> {
        let name = project_path
            .file_name()
            .and_then(|n| n.to_str())
            .unwrap_or("unknown")
            .to_string();

        let structure = self.analyze_structure(project_path).await?;
        let metrics = self.calculate_metrics(&structure);
        let dependencies = self.analyze_dependencies(project_path).await?;
        let issues = self
            .detect_issues(project_path, &structure, &dependencies)
            .await?;

        Ok(ProjectAnalysis {
            name,
            path: project_path.to_path_buf(),
            structure,
            metrics,
            dependencies,
            issues,
        })
    }

    async fn analyze_structure(&self, project_path: &Path) -> Result<ProjectStructure> {
        let mut files = Vec::new();
        let mut directories = Vec::new();
        let mut total_size = 0;

        for entry in WalkDir::new(project_path)
            .follow_links(true)
            .into_iter()
            .filter_entry(|e| !is_ignored(e.path()))
        {
            let entry = entry?;
            let path = entry.path();

            if path.is_file() {
                let relative_path = path
                    .strip_prefix(project_path)?
                    .to_string_lossy()
                    .to_string();
                let metadata = fs::metadata(path).await?;
                let size = metadata.len();

                let (lines, language) = if let Ok(content) = fs::read_to_string(path).await {
                    let lines = content.lines().count();
                    let language = detect_language(path);
                    (lines, language)
                } else {
                    (0, "binary".to_string())
                };

                files.push(FileInfo {
                    path: relative_path,
                    size,
                    lines,
                    language,
                });

                total_size += size;
            } else if path.is_dir() {
                let relative_path = path
                    .strip_prefix(project_path)?
                    .to_string_lossy()
                    .to_string();
                if !relative_path.is_empty() {
                    directories.push(relative_path);
                }
            }
        }

        Ok(ProjectStructure {
            files,
            directories,
            total_size,
        })
    }

    fn calculate_metrics(&self, structure: &ProjectStructure) -> ProjectMetrics {
        let mut metrics = ProjectMetrics {
            total_files: structure.files.len(),
            rust_files: 0,
            test_files: 0,
            doc_files: 0,
            total_lines: 0,
            code_lines: 0,
            comment_lines: 0,
            blank_lines: 0,
        };

        for file in &structure.files {
            metrics.total_lines += file.lines;

            if file.language == "rust" {
                metrics.rust_files += 1;

                if file.path.contains("test") || file.path.contains("tests/") {
                    metrics.test_files += 1;
                }
            }

            if file.path.ends_with(".md") || file.path.ends_with(".txt") {
                metrics.doc_files += 1;
            }
        }

        // Estimate code/comment/blank lines (simplified)
        metrics.code_lines = (metrics.total_lines as f64 * 0.6) as usize;
        metrics.comment_lines = (metrics.total_lines as f64 * 0.2) as usize;
        metrics.blank_lines = (metrics.total_lines as f64 * 0.2) as usize;

        metrics
    }

    async fn analyze_dependencies(&self, project_path: &Path) -> Result<Vec<Dependency>> {
        let cargo_toml_path = project_path.join("Cargo.toml");

        if !cargo_toml_path.exists() {
            return Ok(Vec::new());
        }

        let content = fs::read_to_string(&cargo_toml_path).await?;
        let manifest: toml::Value = toml::from_str(&content)?;

        let mut dependencies = Vec::new();

        if let Some(deps) = manifest.get("dependencies").and_then(|d| d.as_table()) {
            for (name, value) in deps {
                let (version, features, optional) = parse_dependency_value(value);

                dependencies.push(Dependency {
                    name: name.clone(),
                    version,
                    features,
                    optional,
                });
            }
        }

        Ok(dependencies)
    }

    async fn detect_issues(
        &self,
        project_path: &Path,
        structure: &ProjectStructure,
        dependencies: &[Dependency],
    ) -> Result<Vec<Issue>> {
        let mut issues = Vec::new();

        // Check for missing documentation
        if !project_path.join("README.md").exists() {
            issues.push(Issue {
                severity: IssueSeverity::Warning,
                category: IssueCategory::Documentation,
                message: "Missing README.md file".to_string(),
                file: None,
                line: None,
            });
        }

        // Check for missing tests
        if structure
            .files
            .iter()
            .filter(|f| f.path.contains("test"))
            .count()
            == 0
        {
            issues.push(Issue {
                severity: IssueSeverity::Warning,
                category: IssueCategory::Documentation,
                message: "No test files found".to_string(),
                file: None,
                line: None,
            });
        }

        // Check for outdated dependencies (simplified)
        for dep in dependencies {
            if dep.version.starts_with("0.") {
                issues.push(Issue {
                    severity: IssueSeverity::Info,
                    category: IssueCategory::Dependency,
                    message: format!("Dependency '{}' is using a pre-1.0 version", dep.name),
                    file: Some("Cargo.toml".to_string()),
                    line: None,
                });
            }
        }

        Ok(issues)
    }
}

fn is_ignored(path: &Path) -> bool {
    let ignored_dirs = ["target", ".git", "node_modules", ".idea", ".vscode"];
    let ignored_files = [".DS_Store", "Thumbs.db"];

    if let Some(file_name) = path.file_name().and_then(|n| n.to_str()) {
        if ignored_files.contains(&file_name) {
            return true;
        }
    }

    path.components().any(|component| {
        if let Some(name) = component.as_os_str().to_str() {
            ignored_dirs.contains(&name)
        } else {
            false
        }
    })
}

fn detect_language(path: &Path) -> String {
    match path.extension().and_then(|ext| ext.to_str()) {
        Some("rs") => "rust".to_string(),
        Some("toml") => "toml".to_string(),
        Some("md") => "markdown".to_string(),
        Some("yml" | "yaml") => "yaml".to_string(),
        Some("json") => "json".to_string(),
        Some("sh") => "shell".to_string(),
        Some("py") => "python".to_string(),
        Some("js") => "javascript".to_string(),
        Some("ts") => "typescript".to_string(),
        _ => "unknown".to_string(),
    }
}

fn parse_dependency_value(value: &toml::Value) -> (String, Vec<String>, bool) {
    match value {
        toml::Value::String(version) => (version.clone(), Vec::new(), false),
        toml::Value::Table(table) => {
            let version = table
                .get("version")
                .and_then(|v| v.as_str())
                .unwrap_or("*")
                .to_string();

            let features = table
                .get("features")
                .and_then(|v| v.as_array())
                .map(|arr| {
                    arr.iter()
                        .filter_map(|v| v.as_str())
                        .map(std::string::ToString::to_string)
                        .collect()
                })
                .unwrap_or_default();

            let optional = table
                .get("optional")
                .and_then(toml::Value::as_bool)
                .unwrap_or(false);

            (version, features, optional)
        }
        _ => ("*".to_string(), Vec::new(), false),
    }
}