clippier 0.2.0

MoosicBox clippier package
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
423
424
425
426
427
428
429
430
431
432
//! Test helpers and fixture loaders for clippier integration tests.

use std::path::Path;

/// Test resources and utilities for creating test workspaces.
///
/// This module provides helper functions and types for loading test workspaces,
/// creating temporary workspace structures, and loading Cargo.lock files for testing.
pub mod test_resources {
    use super::Path;
    use serde::{Deserialize, Serialize};
    use switchy_fs::TempDir;

    /// Representation of a Cargo.lock file for testing.
    ///
    /// A simplified version of Cargo.lock used in test resources, serializable
    /// to/from JSON for easy test fixture creation.
    #[derive(Debug, Clone, Serialize, Deserialize)]
    pub struct CargoLock {
        /// Cargo.lock format version (typically 3 or 4)
        pub version: u32,
        /// List of locked packages with their versions and dependencies
        pub package: Vec<CargoLockPackage>,
    }

    /// A single package entry in a test Cargo.lock file.
    #[derive(Debug, Clone, Serialize, Deserialize)]
    pub struct CargoLockPackage {
        /// Package name
        pub name: String,
        /// Package version (semver string)
        pub version: String,
        /// Package source (registry URL, git URL, or path)
        #[serde(skip_serializing_if = "Option::is_none")]
        pub source: Option<String>,
        /// List of dependencies (name and version)
        #[serde(skip_serializing_if = "Option::is_none")]
        pub dependencies: Option<Vec<String>>,
    }

    impl From<CargoLock> for crate::CargoLock {
        fn from(cargo_lock: CargoLock) -> Self {
            Self {
                version: cargo_lock.version,
                package: cargo_lock.package.into_iter().map(Into::into).collect(),
            }
        }
    }

    impl From<CargoLockPackage> for crate::CargoLockPackage {
        fn from(package: CargoLockPackage) -> Self {
            Self {
                name: package.name,
                version: package.version,
                source: package.source,
                dependencies: package.dependencies,
            }
        }
    }

    // Conversions for git_diff types
    #[cfg(feature = "git-diff")]
    impl From<crate::CargoLock> for crate::git_diff::CargoLock {
        fn from(cargo_lock: crate::CargoLock) -> Self {
            Self {
                version: cargo_lock.version,
                package: cargo_lock.package.into_iter().map(Into::into).collect(),
            }
        }
    }

    #[cfg(feature = "git-diff")]
    impl From<crate::CargoLockPackage> for crate::git_diff::CargoLockPackage {
        fn from(package: crate::CargoLockPackage) -> Self {
            Self {
                name: package.name,
                version: package.version,
                source: package.source,
                dependencies: package.dependencies,
            }
        }
    }

    /// Load a Cargo.lock file for `git_diff` functions
    #[cfg(feature = "git-diff")]
    #[must_use]
    pub fn load_cargo_lock_for_git_diff(
        workspace_name: &str,
        cargo_lock_name: &str,
    ) -> crate::git_diff::CargoLock {
        load_cargo_lock(workspace_name, cargo_lock_name).into()
    }

    /// Load a test workspace from the test-resources directory
    ///
    /// # Errors
    ///
    /// * If the workspace directory cannot be found
    /// * If the workspace Cargo.toml file cannot be read
    /// * If the workspace Cargo.toml file cannot be parsed
    ///
    /// # Panics
    ///
    /// * If fails to create a temporary directory
    /// * If fails to copy workspace files to the temporary directory
    /// * If fails to parse the workspace Cargo.toml file
    #[must_use]
    pub fn load_test_workspace(workspace_name: &str) -> (TempDir, Vec<String>) {
        let test_resources_path = Path::new(env!("CARGO_MANIFEST_DIR"))
            .join("test-resources")
            .join("workspaces")
            .join(workspace_name);

        let temp_dir = TempDir::new().expect("Failed to create temp directory");

        // Copy workspace files to temp directory
        copy_dir_recursive(&test_resources_path, temp_dir.path())
            .expect("Failed to copy test workspace");

        // Get workspace members from the workspace Cargo.toml
        let workspace_cargo_toml = temp_dir.path().join("Cargo.toml");
        let workspace_content = switchy_fs::sync::read_to_string(&workspace_cargo_toml)
            .expect("Failed to read workspace Cargo.toml");

        let workspace_toml: toml::Value =
            toml::from_str(&workspace_content).expect("Failed to parse workspace Cargo.toml");

        let workspace_members = workspace_toml
            .get("workspace")
            .and_then(|w| w.get("members"))
            .and_then(|m| m.as_array())
            .and_then(|arr| {
                arr.iter()
                    .map(|v| v.as_str().map(std::string::ToString::to_string))
                    .collect::<Option<Vec<_>>>()
            })
            .unwrap_or_default();

        (temp_dir, workspace_members)
    }

    /// Load a Cargo.lock file from the test resources
    ///
    /// # Panics
    ///
    /// * If fails to read the Cargo.lock file
    #[must_use]
    pub fn load_cargo_lock(workspace_name: &str, cargo_lock_name: &str) -> crate::CargoLock {
        let cargo_locks_dir = Path::new(env!("CARGO_MANIFEST_DIR"))
            .join("test-resources")
            .join("workspaces")
            .join(workspace_name)
            .join("cargo-locks");
        let cargo_lock_path = cargo_locks_dir.join(format!("{cargo_lock_name}.json"));

        // Seed from real filesystem when in simulator mode
        // seed_from_real_fs expects a directory, so seed the cargo-locks directory
        switchy_fs::seed_from_real_fs_same_path(&cargo_locks_dir)
            .expect("Failed to seed cargo locks directory");

        let cargo_lock_content =
            switchy_fs::sync::read_to_string(&cargo_lock_path).unwrap_or_else(|e| {
                panic!(
                    "Failed to read cargo lock file {}: {}",
                    cargo_lock_path.display(),
                    e
                )
            });

        let cargo_lock: CargoLock = serde_json::from_str(&cargo_lock_content).unwrap_or_else(|e| {
            panic!(
                "Failed to parse cargo lock file {}: {}",
                cargo_lock_path.display(),
                e
            )
        });

        cargo_lock.into()
    }

    /// Create a simple workspace structure for testing
    ///
    /// # Panics
    ///
    /// * If fails to create a temporary directory
    /// * If fails to write the workspace Cargo.toml file
    /// * If fails to write the package Cargo.toml files
    #[must_use]
    pub fn create_simple_workspace(
        workspace_members: &[&str],
        workspace_dependencies: &[&str],
        package_configs: &[(&str, &[&str])], // (package_name, dependencies)
    ) -> (TempDir, Vec<String>) {
        use std::fmt::Write;

        let temp_dir = TempDir::new().expect("Failed to create temp directory");

        // Create workspace root Cargo.toml
        let mut workspace_toml = String::new();
        workspace_toml.push_str("[workspace]\nmembers = [\n");
        for member in workspace_members {
            writeln!(workspace_toml, "    \"packages/{member}\",").unwrap();
        }
        workspace_toml.push_str("]\n\n[workspace.dependencies]\n");
        for dep in workspace_dependencies {
            writeln!(workspace_toml, "{dep} = \"1.0\"").unwrap();
        }

        switchy_fs::sync::write(temp_dir.path().join("Cargo.toml"), workspace_toml)
            .expect("Failed to write workspace Cargo.toml");

        // Create package directories and Cargo.toml files
        for (package_name, dependencies) in package_configs {
            let package_path = temp_dir.path().join("packages").join(package_name);
            switchy_fs::sync::create_dir_all(package_path.join("src"))
                .expect("Failed to create package directory");

            let mut package_toml = format!(
                "[package]\nname = \"{package_name}\"\nversion = \"0.1.0\"\nedition = \"2021\"\n\n[dependencies]\n"
            );

            for dep in *dependencies {
                if workspace_members.contains(dep) {
                    writeln!(package_toml, "{dep} = {{ path = \"../{dep}\" }}").unwrap();
                } else {
                    writeln!(package_toml, "{dep} = {{ workspace = true }}").unwrap();
                }
            }

            switchy_fs::sync::write(package_path.join("Cargo.toml"), package_toml)
                .expect("Failed to write package Cargo.toml");
        }

        let workspace_members = workspace_members
            .iter()
            .map(|m| format!("packages/{m}"))
            .collect();
        (temp_dir, workspace_members)
    }

    /// Load a Node.js test workspace from the test-resources directory.
    ///
    /// This function loads a Node.js workspace (npm, pnpm, or bun) and returns
    /// the temporary directory and list of workspace package paths.
    ///
    /// # Arguments
    ///
    /// * `workspace_name` - Name of the workspace directory under test-resources/workspaces/
    ///
    /// # Returns
    ///
    /// A tuple of (`TempDir`, `Vec<String>`) where the Vec contains workspace member paths.
    ///
    /// # Panics
    ///
    /// * If fails to create a temporary directory
    /// * If fails to copy workspace files to the temporary directory
    /// * If fails to read pnpm-workspace.yaml or package.json
    /// * If fails to parse package.json as JSON
    #[must_use]
    pub fn load_node_test_workspace(workspace_name: &str) -> (TempDir, Vec<String>) {
        let test_resources_path = Path::new(env!("CARGO_MANIFEST_DIR"))
            .join("test-resources")
            .join("workspaces")
            .join(workspace_name);

        let temp_dir = TempDir::new().expect("Failed to create temp directory");

        // Copy workspace files to temp directory
        copy_dir_recursive(&test_resources_path, temp_dir.path())
            .expect("Failed to copy test workspace");

        // Try to get workspace members from pnpm-workspace.yaml first
        let pnpm_workspace_path = temp_dir.path().join("pnpm-workspace.yaml");
        let package_json_path = temp_dir.path().join("package.json");

        let workspace_patterns = if switchy_fs::exists(&pnpm_workspace_path) {
            // Parse pnpm-workspace.yaml
            let content = switchy_fs::sync::read_to_string(&pnpm_workspace_path)
                .expect("Failed to read pnpm-workspace.yaml");
            parse_pnpm_workspace_patterns(&content)
        } else if switchy_fs::exists(&package_json_path) {
            // Parse package.json workspaces field
            let content = switchy_fs::sync::read_to_string(&package_json_path)
                .expect("Failed to read package.json");
            parse_npm_workspace_patterns(&content)
        } else {
            vec![]
        };

        // Expand glob patterns to actual package paths
        let workspace_members =
            expand_node_workspace_patterns(temp_dir.path(), &workspace_patterns);

        (temp_dir, workspace_members)
    }

    /// Parse pnpm-workspace.yaml to extract workspace patterns.
    fn parse_pnpm_workspace_patterns(content: &str) -> Vec<String> {
        // Simple YAML parsing for packages field
        // Format: packages:\n  - "pattern1"\n  - "pattern2"
        let mut patterns = vec![];
        let mut in_packages = false;

        for line in content.lines() {
            let trimmed = line.trim();
            if trimmed == "packages:" {
                in_packages = true;
                continue;
            }
            if in_packages {
                if trimmed.starts_with('-') {
                    let pattern = trimmed
                        .trim_start_matches('-')
                        .trim()
                        .trim_matches('"')
                        .trim_matches('\'');
                    if !pattern.is_empty() {
                        patterns.push(pattern.to_string());
                    }
                } else if !trimmed.is_empty() && !trimmed.starts_with('#') {
                    // End of packages section
                    break;
                }
            }
        }

        patterns
    }

    /// Parse package.json to extract workspace patterns.
    fn parse_npm_workspace_patterns(content: &str) -> Vec<String> {
        let json: serde_json::Value =
            serde_json::from_str(content).expect("Failed to parse package.json");

        json.get("workspaces")
            .and_then(|w| w.as_array())
            .map(|arr| {
                arr.iter()
                    .filter_map(|v| v.as_str().map(std::string::ToString::to_string))
                    .collect()
            })
            .unwrap_or_default()
    }

    /// Expand workspace patterns (e.g., "packages/*") to actual package paths.
    fn expand_node_workspace_patterns(root: &Path, patterns: &[String]) -> Vec<String> {
        let mut members = vec![];

        for pattern in patterns {
            if pattern.ends_with("/*") {
                // Simple glob: packages/*
                let dir = pattern.trim_end_matches("/*");
                let dir_path = root.join(dir);

                if switchy_fs::exists(&dir_path)
                    && let Ok(entries) = switchy_fs::sync::read_dir_sorted(&dir_path)
                {
                    for entry in entries {
                        let entry_path = entry.path();
                        let package_json = entry_path.join("package.json");
                        if switchy_fs::exists(&package_json)
                            && let Ok(rel_path) = entry_path.strip_prefix(root)
                        {
                            members.push(rel_path.to_string_lossy().to_string());
                        }
                    }
                }
            } else {
                // Exact path
                let package_json = root.join(pattern).join("package.json");
                if switchy_fs::exists(&package_json) {
                    members.push(pattern.clone());
                }
            }
        }

        members
    }

    /// Get the workspace root path for a test workspace without copying to temp.
    ///
    /// Useful for tests that need to directly access test fixtures.
    ///
    /// # Panics
    ///
    /// * If fails to seed the fixture into the simulator filesystem (when simulator is enabled)
    #[must_use]
    pub fn get_test_workspace_path(workspace_name: &str) -> std::path::PathBuf {
        let path = Path::new(env!("CARGO_MANIFEST_DIR"))
            .join("test-resources")
            .join("workspaces")
            .join(workspace_name);

        // Seed the fixture directory into the simulator filesystem if enabled
        if switchy_fs::is_simulator_enabled() {
            switchy_fs::seed_from_real_fs_same_path(&path)
                .expect("Failed to seed fixture into simulator filesystem");
        }

        path
    }

    /// Copies a directory recursively from the real filesystem to the `switchy_fs` filesystem.
    ///
    /// This function reads from the real filesystem (for test resources) and writes
    /// to the `switchy_fs` filesystem (which may be simulated or real depending on features).
    fn copy_dir_recursive(src: &Path, dst: &Path) -> std::io::Result<()> {
        if !switchy_fs::exists(dst) {
            switchy_fs::sync::create_dir_all(dst)?;
        }

        // Read from real filesystem since test-resources are on disk
        let mut entries: Vec<_> = std::fs::read_dir(src)?.collect::<Result<Vec<_>, _>>()?;
        entries.sort_by_key(std::fs::DirEntry::file_name);

        for entry in entries {
            let src_path = entry.path();
            let dst_path = dst.join(entry.file_name());

            if src_path.is_dir() {
                copy_dir_recursive(&src_path, &dst_path)?;
            } else {
                // Read from real filesystem, write to switchy_fs
                let content = std::fs::read(&src_path)?;
                switchy_fs::sync::write(&dst_path, content)?;
            }
        }

        Ok(())
    }
}