Skip to main content

rust_analyzer/cli/
ssr.rs

1//! Applies structured search replace rules from the command line.
2
3use anyhow::Context;
4use ide_db::{EditionedFileId, base_db::SourceDatabase};
5use ide_ssr::MatchFinder;
6use load_cargo::{LoadCargoConfig, ProcMacroServerChoice, load_workspace_at};
7use project_model::{CargoConfig, RustLibSource};
8
9use crate::cli::flags;
10
11impl flags::Ssr {
12    pub fn run(self) -> anyhow::Result<()> {
13        let cargo_config = CargoConfig {
14            sysroot: Some(RustLibSource::Discover),
15            all_targets: true,
16            set_test: true,
17            ..Default::default()
18        };
19        let load_cargo_config = LoadCargoConfig {
20            load_out_dirs_from_check: true,
21            with_proc_macro_server: ProcMacroServerChoice::Sysroot,
22            prefill_caches: false,
23            num_worker_threads: 1,
24            proc_macro_processes: 1,
25        };
26        let (ref db, vfs, _proc_macro) = load_workspace_at(
27            &std::env::current_dir()?,
28            &cargo_config,
29            &load_cargo_config,
30            &|_| {},
31        )?;
32        let mut match_finder = MatchFinder::at_first_file(db)?;
33        for rule in self.rule {
34            match_finder.add_rule(rule)?;
35        }
36        let edits = match_finder.edits();
37        for (file_id, edit) in edits {
38            if let Some(path) = vfs.file_path(file_id).as_path() {
39                let mut contents = db.file_text(file_id).text(db).to_string();
40                edit.apply(&mut contents);
41                if vfs.line_endings(file_id) == Some(vfs::LineEndings::Dos) {
42                    contents = contents.replace('\n', "\r\n");
43                }
44                std::fs::write(path, contents)
45                    .with_context(|| format!("failed to write {path}"))?;
46            }
47        }
48        Ok(())
49    }
50}
51
52impl flags::Search {
53    /// Searches for `patterns`, printing debug information for any nodes whose text exactly matches
54    /// `debug_snippet`. This is intended for debugging and probably isn't useful in its current
55    /// form for much else.
56    pub fn run(self) -> anyhow::Result<()> {
57        use ide_db::base_db::SourceDatabase;
58        let cargo_config =
59            CargoConfig { all_targets: true, set_test: true, ..CargoConfig::default() };
60        let load_cargo_config = LoadCargoConfig {
61            load_out_dirs_from_check: true,
62            with_proc_macro_server: ProcMacroServerChoice::Sysroot,
63            prefill_caches: false,
64            num_worker_threads: 1,
65            proc_macro_processes: 1,
66        };
67        let (ref db, _vfs, _proc_macro) = load_workspace_at(
68            &std::env::current_dir()?,
69            &cargo_config,
70            &load_cargo_config,
71            &|_| {},
72        )?;
73        let mut match_finder = MatchFinder::at_first_file(db)?;
74        for pattern in self.pattern {
75            match_finder.add_search_pattern(pattern)?;
76        }
77        if let Some(debug_snippet) = &self.debug {
78            for &root in ide_db::LocalRoots::get(db).roots(db).iter() {
79                let sr = db.source_root(root).source_root(db);
80                for file_id in sr.iter() {
81                    for debug_info in match_finder.debug_where_text_equal(
82                        EditionedFileId::current_edition(db, file_id),
83                        debug_snippet,
84                    ) {
85                        println!("{debug_info:#?}");
86                    }
87                }
88            }
89        } else {
90            for m in match_finder.matches().flattened().matches {
91                // We could possibly at some point do something more useful than just printing
92                // the matched text. For now though, that's the easiest thing to do.
93                println!("{}", m.matched_text());
94            }
95        }
96        Ok(())
97    }
98}