Struct LocList

Source
pub struct LocList {
    pub locs: Vec<Loc>,
}
Expand description

A list of Lines of Code

To sort it, you focus it, which specifies the area to sort, then you call sort it.

Fields§

§locs: Vec<Loc>

Implementations§

Source§

impl LocList

Source

pub fn read<R: BufRead>(reader: R, lang: Language) -> CsResult<Self>

Source

pub fn read_str(s: &str, lang: Language) -> CsResult<LocList>

Source

pub fn read_file<P: AsRef<Path>>(path: P, lang: Language) -> CsResult<LocList>

Examples found in repository?
examples/explain/main.rs (line 22)
20fn main() -> CsResult<()> {
21    let args = Args::parse();
22    let loc_list = LocList::read_file(&args.path, Language::Rust)?;
23    let Some(sort_around) = args.sort_around else {
24        loc_list.print_debug(" WHOLE FILE ");
25        return Ok(());
26    };
27    let focused = loc_list.focus_around_line_number(sort_around)?;
28    focused.print_debug();
29    let blocks = focused.clone().focus.into_blocks();
30    for (i, block) in blocks.iter().enumerate() {
31        block.print_debug(&format!(" BLOCK {i} "));
32    }
33    let loc_list = focused.sort();
34    println!("------------ RESULT ------------");
35    print!("{}", loc_list);
36    Ok(())
37}
More examples
Hide additional examples
examples/list-invalid-files/main.rs (line 75)
67fn main() {
68    let args = Args::parse();
69    let files = get_all_rust_files(args.path, &args.include).unwrap();
70    eprintln!("Found {} rust files", files.len());
71    let mut no_complete_count = 0;
72    let mut errors = 0;
73    let mut ok_count = 0;
74    for file in files {
75        let loc_list = LocList::read_file(file.to_str().unwrap(), Language::Rust);
76        let loc_list = match loc_list {
77            Ok(loc_list) => loc_list,
78            Err(e) => {
79                eprintln!("{} {:?} : {}", "ERROR".red(), file, e);
80                errors += 1;
81                continue;
82            }
83        };
84        if loc_list.is_complete() {
85            ok_count += 1;
86            continue;
87        }
88        if !loc_list.has_content() {
89            eprintln!("{} {:?}", "EMPTY".yellow(), file);
90            ok_count += 1;
91            continue;
92        }
93        eprintln!("{} {:?}", "NOT COMPLETE".yellow(), file);
94        no_complete_count += 1;
95    }
96    eprintln!("OK files: {}", ok_count);
97    eprintln!("Erroring files: {}", errors);
98    eprintln!("Uncomplete files: {}", no_complete_count);
99}
examples/sort-all-enums/main.rs (line 99)
86fn main() -> CsResult<()> {
87    let start = std::time::Instant::now();
88    let args = Args::parse();
89    let files = get_all_rust_files(args.path, &args.include, &args.exclude)?;
90    eprintln!("Found {} rust files", files.len());
91    let mut sorted_enum_count = 0;
92    let mut ok_files_count = 0;
93    let mut invalid_files_count = 0;
94    let mut incomplete_files_count = 0;
95    let mut excluded_enums_count = 0;
96    let mut modified_files_count = 0;
97    let mut empty_files_count = 0;
98    for file in &files {
99        let loc_list = LocList::read_file(file, Language::Rust);
100        let mut loc_list = match loc_list {
101            Ok(loc_list) => loc_list,
102            Err(e) => {
103                eprintln!("{} in {}: {:?}", "ERROR".red(), file.display(), e);
104                invalid_files_count += 1;
105                continue;
106            }
107        };
108        if !loc_list.has_content() {
109            empty_files_count += 1;
110            continue;
111        }
112        if !loc_list.is_complete() {
113            eprintln!(
114                "skipping {} ({})",
115                file.display(),
116                "not consistent enough".yellow()
117            );
118            incomplete_files_count += 1;
119            continue;
120        }
121        let mut modified = false;
122        let mut line_idx = 0;
123        ok_files_count += 1;
124        while line_idx + 2 < loc_list.len() {
125            let loc = &loc_list.locs[line_idx];
126            if !loc.starts_normal {
127                line_idx += 1;
128                continue;
129            }
130            let content = &loc.content;
131            let Some((_, name)) =
132                regex_captures!(r"^[\s\w()]*\benum\s+([^({]+)\s+\{\s**$", content)
133            else {
134                line_idx += 1;
135                continue;
136            };
137
138            // We look whether the annotations before the enum contain any one
139            // of the excluding keywords
140            let whole_enum_range = loc_list
141                .block_range_of_line_number(LineNumber::from_index(line_idx))
142                .unwrap();
143            let whole_enum_range = loc_list.trimmed_range(whole_enum_range);
144            let excluding_keyword = EXCLUDING_KEYWORDS.iter().find(|&keyword| {
145                loc_list.locs[whole_enum_range.start.to_index()..line_idx]
146                    .iter()
147                    .any(|loc| loc.sort_key.contains(keyword))
148            });
149            if let Some(excluding_keyword) = excluding_keyword {
150                eprintln!("skipping enum {} ({})", name, excluding_keyword.yellow());
151                excluded_enums_count += 1;
152                line_idx = whole_enum_range.end.to_index() + 1;
153                continue;
154            }
155            loc_list.print_range_debug(
156                &format!(" sorting enum {} ", name.blue()),
157                whole_enum_range,
158            );
159            let range = loc_list.range_around_line_index(line_idx + 1).unwrap();
160            loc_list.sort_range(range).unwrap();
161            line_idx = range.end.to_index() + 2;
162            sorted_enum_count += 1;
163            modified = true;
164        }
165        if modified {
166            loc_list.write_file(file)?;
167            eprintln!("wrote {}", file.display());
168            modified_files_count += 1;
169        }
170    }
171    eprintln!("\nDone in {:.3}s\n", start.elapsed().as_secs_f32());
172    eprintln!("I analyzed {} files", files.len());
173    let mut problems = Vec::new();
174    if empty_files_count > 0 {
175        problems.push(format!("{} empty files", empty_files_count));
176    }
177    if incomplete_files_count > 0 {
178        problems.push(format!("{} incomplete files", incomplete_files_count));
179    }
180    if invalid_files_count > 0 {
181        problems.push(format!("{} invalid files", invalid_files_count));
182    }
183    if problems.is_empty() {
184        eprintln!("All {} files were ok", ok_files_count);
185    } else {
186        eprintln!(
187            "{} files were OK but I encountered {}",
188            ok_files_count,
189            problems.join(", ")
190        );
191    }
192    if excluded_enums_count > 0 {
193        eprintln!(
194            "I excluded {} enums whose annotation contained excluding keywords",
195            excluded_enums_count
196        );
197    }
198    eprintln!(
199        "I sorted {} enums in {} files",
200        sorted_enum_count, modified_files_count
201    );
202    Ok(())
203}
Source

pub fn write_file<P: AsRef<Path>>(&self, path: P) -> CsResult<()>

Examples found in repository?
examples/sort-all-enums/main.rs (line 166)
86fn main() -> CsResult<()> {
87    let start = std::time::Instant::now();
88    let args = Args::parse();
89    let files = get_all_rust_files(args.path, &args.include, &args.exclude)?;
90    eprintln!("Found {} rust files", files.len());
91    let mut sorted_enum_count = 0;
92    let mut ok_files_count = 0;
93    let mut invalid_files_count = 0;
94    let mut incomplete_files_count = 0;
95    let mut excluded_enums_count = 0;
96    let mut modified_files_count = 0;
97    let mut empty_files_count = 0;
98    for file in &files {
99        let loc_list = LocList::read_file(file, Language::Rust);
100        let mut loc_list = match loc_list {
101            Ok(loc_list) => loc_list,
102            Err(e) => {
103                eprintln!("{} in {}: {:?}", "ERROR".red(), file.display(), e);
104                invalid_files_count += 1;
105                continue;
106            }
107        };
108        if !loc_list.has_content() {
109            empty_files_count += 1;
110            continue;
111        }
112        if !loc_list.is_complete() {
113            eprintln!(
114                "skipping {} ({})",
115                file.display(),
116                "not consistent enough".yellow()
117            );
118            incomplete_files_count += 1;
119            continue;
120        }
121        let mut modified = false;
122        let mut line_idx = 0;
123        ok_files_count += 1;
124        while line_idx + 2 < loc_list.len() {
125            let loc = &loc_list.locs[line_idx];
126            if !loc.starts_normal {
127                line_idx += 1;
128                continue;
129            }
130            let content = &loc.content;
131            let Some((_, name)) =
132                regex_captures!(r"^[\s\w()]*\benum\s+([^({]+)\s+\{\s**$", content)
133            else {
134                line_idx += 1;
135                continue;
136            };
137
138            // We look whether the annotations before the enum contain any one
139            // of the excluding keywords
140            let whole_enum_range = loc_list
141                .block_range_of_line_number(LineNumber::from_index(line_idx))
142                .unwrap();
143            let whole_enum_range = loc_list.trimmed_range(whole_enum_range);
144            let excluding_keyword = EXCLUDING_KEYWORDS.iter().find(|&keyword| {
145                loc_list.locs[whole_enum_range.start.to_index()..line_idx]
146                    .iter()
147                    .any(|loc| loc.sort_key.contains(keyword))
148            });
149            if let Some(excluding_keyword) = excluding_keyword {
150                eprintln!("skipping enum {} ({})", name, excluding_keyword.yellow());
151                excluded_enums_count += 1;
152                line_idx = whole_enum_range.end.to_index() + 1;
153                continue;
154            }
155            loc_list.print_range_debug(
156                &format!(" sorting enum {} ", name.blue()),
157                whole_enum_range,
158            );
159            let range = loc_list.range_around_line_index(line_idx + 1).unwrap();
160            loc_list.sort_range(range).unwrap();
161            line_idx = range.end.to_index() + 2;
162            sorted_enum_count += 1;
163            modified = true;
164        }
165        if modified {
166            loc_list.write_file(file)?;
167            eprintln!("wrote {}", file.display());
168            modified_files_count += 1;
169        }
170    }
171    eprintln!("\nDone in {:.3}s\n", start.elapsed().as_secs_f32());
172    eprintln!("I analyzed {} files", files.len());
173    let mut problems = Vec::new();
174    if empty_files_count > 0 {
175        problems.push(format!("{} empty files", empty_files_count));
176    }
177    if incomplete_files_count > 0 {
178        problems.push(format!("{} incomplete files", incomplete_files_count));
179    }
180    if invalid_files_count > 0 {
181        problems.push(format!("{} invalid files", invalid_files_count));
182    }
183    if problems.is_empty() {
184        eprintln!("All {} files were ok", ok_files_count);
185    } else {
186        eprintln!(
187            "{} files were OK but I encountered {}",
188            ok_files_count,
189            problems.join(", ")
190        );
191    }
192    if excluded_enums_count > 0 {
193        eprintln!(
194            "I excluded {} enums whose annotation contained excluding keywords",
195            excluded_enums_count
196        );
197    }
198    eprintln!(
199        "I sorted {} enums in {} files",
200        sorted_enum_count, modified_files_count
201    );
202    Ok(())
203}
Source

pub fn len(&self) -> usize

Examples found in repository?
examples/sort-all-enums/main.rs (line 124)
86fn main() -> CsResult<()> {
87    let start = std::time::Instant::now();
88    let args = Args::parse();
89    let files = get_all_rust_files(args.path, &args.include, &args.exclude)?;
90    eprintln!("Found {} rust files", files.len());
91    let mut sorted_enum_count = 0;
92    let mut ok_files_count = 0;
93    let mut invalid_files_count = 0;
94    let mut incomplete_files_count = 0;
95    let mut excluded_enums_count = 0;
96    let mut modified_files_count = 0;
97    let mut empty_files_count = 0;
98    for file in &files {
99        let loc_list = LocList::read_file(file, Language::Rust);
100        let mut loc_list = match loc_list {
101            Ok(loc_list) => loc_list,
102            Err(e) => {
103                eprintln!("{} in {}: {:?}", "ERROR".red(), file.display(), e);
104                invalid_files_count += 1;
105                continue;
106            }
107        };
108        if !loc_list.has_content() {
109            empty_files_count += 1;
110            continue;
111        }
112        if !loc_list.is_complete() {
113            eprintln!(
114                "skipping {} ({})",
115                file.display(),
116                "not consistent enough".yellow()
117            );
118            incomplete_files_count += 1;
119            continue;
120        }
121        let mut modified = false;
122        let mut line_idx = 0;
123        ok_files_count += 1;
124        while line_idx + 2 < loc_list.len() {
125            let loc = &loc_list.locs[line_idx];
126            if !loc.starts_normal {
127                line_idx += 1;
128                continue;
129            }
130            let content = &loc.content;
131            let Some((_, name)) =
132                regex_captures!(r"^[\s\w()]*\benum\s+([^({]+)\s+\{\s**$", content)
133            else {
134                line_idx += 1;
135                continue;
136            };
137
138            // We look whether the annotations before the enum contain any one
139            // of the excluding keywords
140            let whole_enum_range = loc_list
141                .block_range_of_line_number(LineNumber::from_index(line_idx))
142                .unwrap();
143            let whole_enum_range = loc_list.trimmed_range(whole_enum_range);
144            let excluding_keyword = EXCLUDING_KEYWORDS.iter().find(|&keyword| {
145                loc_list.locs[whole_enum_range.start.to_index()..line_idx]
146                    .iter()
147                    .any(|loc| loc.sort_key.contains(keyword))
148            });
149            if let Some(excluding_keyword) = excluding_keyword {
150                eprintln!("skipping enum {} ({})", name, excluding_keyword.yellow());
151                excluded_enums_count += 1;
152                line_idx = whole_enum_range.end.to_index() + 1;
153                continue;
154            }
155            loc_list.print_range_debug(
156                &format!(" sorting enum {} ", name.blue()),
157                whole_enum_range,
158            );
159            let range = loc_list.range_around_line_index(line_idx + 1).unwrap();
160            loc_list.sort_range(range).unwrap();
161            line_idx = range.end.to_index() + 2;
162            sorted_enum_count += 1;
163            modified = true;
164        }
165        if modified {
166            loc_list.write_file(file)?;
167            eprintln!("wrote {}", file.display());
168            modified_files_count += 1;
169        }
170    }
171    eprintln!("\nDone in {:.3}s\n", start.elapsed().as_secs_f32());
172    eprintln!("I analyzed {} files", files.len());
173    let mut problems = Vec::new();
174    if empty_files_count > 0 {
175        problems.push(format!("{} empty files", empty_files_count));
176    }
177    if incomplete_files_count > 0 {
178        problems.push(format!("{} incomplete files", incomplete_files_count));
179    }
180    if invalid_files_count > 0 {
181        problems.push(format!("{} invalid files", invalid_files_count));
182    }
183    if problems.is_empty() {
184        eprintln!("All {} files were ok", ok_files_count);
185    } else {
186        eprintln!(
187            "{} files were OK but I encountered {}",
188            ok_files_count,
189            problems.join(", ")
190        );
191    }
192    if excluded_enums_count > 0 {
193        eprintln!(
194            "I excluded {} enums whose annotation contained excluding keywords",
195            excluded_enums_count
196        );
197    }
198    eprintln!(
199        "I sorted {} enums in {} files",
200        sorted_enum_count, modified_files_count
201    );
202    Ok(())
203}
Source

pub fn sort_range(&mut self, range: LineNumberRange) -> CsResult<()>

Examples found in repository?
examples/sort-all-enums/main.rs (line 160)
86fn main() -> CsResult<()> {
87    let start = std::time::Instant::now();
88    let args = Args::parse();
89    let files = get_all_rust_files(args.path, &args.include, &args.exclude)?;
90    eprintln!("Found {} rust files", files.len());
91    let mut sorted_enum_count = 0;
92    let mut ok_files_count = 0;
93    let mut invalid_files_count = 0;
94    let mut incomplete_files_count = 0;
95    let mut excluded_enums_count = 0;
96    let mut modified_files_count = 0;
97    let mut empty_files_count = 0;
98    for file in &files {
99        let loc_list = LocList::read_file(file, Language::Rust);
100        let mut loc_list = match loc_list {
101            Ok(loc_list) => loc_list,
102            Err(e) => {
103                eprintln!("{} in {}: {:?}", "ERROR".red(), file.display(), e);
104                invalid_files_count += 1;
105                continue;
106            }
107        };
108        if !loc_list.has_content() {
109            empty_files_count += 1;
110            continue;
111        }
112        if !loc_list.is_complete() {
113            eprintln!(
114                "skipping {} ({})",
115                file.display(),
116                "not consistent enough".yellow()
117            );
118            incomplete_files_count += 1;
119            continue;
120        }
121        let mut modified = false;
122        let mut line_idx = 0;
123        ok_files_count += 1;
124        while line_idx + 2 < loc_list.len() {
125            let loc = &loc_list.locs[line_idx];
126            if !loc.starts_normal {
127                line_idx += 1;
128                continue;
129            }
130            let content = &loc.content;
131            let Some((_, name)) =
132                regex_captures!(r"^[\s\w()]*\benum\s+([^({]+)\s+\{\s**$", content)
133            else {
134                line_idx += 1;
135                continue;
136            };
137
138            // We look whether the annotations before the enum contain any one
139            // of the excluding keywords
140            let whole_enum_range = loc_list
141                .block_range_of_line_number(LineNumber::from_index(line_idx))
142                .unwrap();
143            let whole_enum_range = loc_list.trimmed_range(whole_enum_range);
144            let excluding_keyword = EXCLUDING_KEYWORDS.iter().find(|&keyword| {
145                loc_list.locs[whole_enum_range.start.to_index()..line_idx]
146                    .iter()
147                    .any(|loc| loc.sort_key.contains(keyword))
148            });
149            if let Some(excluding_keyword) = excluding_keyword {
150                eprintln!("skipping enum {} ({})", name, excluding_keyword.yellow());
151                excluded_enums_count += 1;
152                line_idx = whole_enum_range.end.to_index() + 1;
153                continue;
154            }
155            loc_list.print_range_debug(
156                &format!(" sorting enum {} ", name.blue()),
157                whole_enum_range,
158            );
159            let range = loc_list.range_around_line_index(line_idx + 1).unwrap();
160            loc_list.sort_range(range).unwrap();
161            line_idx = range.end.to_index() + 2;
162            sorted_enum_count += 1;
163            modified = true;
164        }
165        if modified {
166            loc_list.write_file(file)?;
167            eprintln!("wrote {}", file.display());
168            modified_files_count += 1;
169        }
170    }
171    eprintln!("\nDone in {:.3}s\n", start.elapsed().as_secs_f32());
172    eprintln!("I analyzed {} files", files.len());
173    let mut problems = Vec::new();
174    if empty_files_count > 0 {
175        problems.push(format!("{} empty files", empty_files_count));
176    }
177    if incomplete_files_count > 0 {
178        problems.push(format!("{} incomplete files", incomplete_files_count));
179    }
180    if invalid_files_count > 0 {
181        problems.push(format!("{} invalid files", invalid_files_count));
182    }
183    if problems.is_empty() {
184        eprintln!("All {} files were ok", ok_files_count);
185    } else {
186        eprintln!(
187            "{} files were OK but I encountered {}",
188            ok_files_count,
189            problems.join(", ")
190        );
191    }
192    if excluded_enums_count > 0 {
193        eprintln!(
194            "I excluded {} enums whose annotation contained excluding keywords",
195            excluded_enums_count
196        );
197    }
198    eprintln!(
199        "I sorted {} enums in {} files",
200        sorted_enum_count, modified_files_count
201    );
202    Ok(())
203}
Source

pub fn sort_around_line_index(&mut self, line_index: LineIndex) -> CsResult<()>

Source

pub fn sort_around_line_number( &mut self, line_number: LineNumber, ) -> CsResult<()>

Source

pub fn focus_all(self) -> CsResult<Focused>

Source

pub fn focus(self, range: LineNumberRange) -> CsResult<Focused>

Source

pub fn focus_around_line_index(self, line_idx: LineIndex) -> CsResult<Focused>

Source

pub fn focus_around_line_number( self, line_number: LineNumber, ) -> CsResult<Focused>

Examples found in repository?
examples/explain/main.rs (line 27)
20fn main() -> CsResult<()> {
21    let args = Args::parse();
22    let loc_list = LocList::read_file(&args.path, Language::Rust)?;
23    let Some(sort_around) = args.sort_around else {
24        loc_list.print_debug(" WHOLE FILE ");
25        return Ok(());
26    };
27    let focused = loc_list.focus_around_line_number(sort_around)?;
28    focused.print_debug();
29    let blocks = focused.clone().focus.into_blocks();
30    for (i, block) in blocks.iter().enumerate() {
31        block.print_debug(&format!(" BLOCK {i} "));
32    }
33    let loc_list = focused.sort();
34    println!("------------ RESULT ------------");
35    print!("{}", loc_list);
36    Ok(())
37}
Source

pub fn line_at_number(&self, line_number: LineNumber) -> Option<&Loc>

Source

pub fn print_range_debug(&self, label: &str, range: LineNumberRange)

Examples found in repository?
examples/sort-all-enums/main.rs (lines 155-158)
86fn main() -> CsResult<()> {
87    let start = std::time::Instant::now();
88    let args = Args::parse();
89    let files = get_all_rust_files(args.path, &args.include, &args.exclude)?;
90    eprintln!("Found {} rust files", files.len());
91    let mut sorted_enum_count = 0;
92    let mut ok_files_count = 0;
93    let mut invalid_files_count = 0;
94    let mut incomplete_files_count = 0;
95    let mut excluded_enums_count = 0;
96    let mut modified_files_count = 0;
97    let mut empty_files_count = 0;
98    for file in &files {
99        let loc_list = LocList::read_file(file, Language::Rust);
100        let mut loc_list = match loc_list {
101            Ok(loc_list) => loc_list,
102            Err(e) => {
103                eprintln!("{} in {}: {:?}", "ERROR".red(), file.display(), e);
104                invalid_files_count += 1;
105                continue;
106            }
107        };
108        if !loc_list.has_content() {
109            empty_files_count += 1;
110            continue;
111        }
112        if !loc_list.is_complete() {
113            eprintln!(
114                "skipping {} ({})",
115                file.display(),
116                "not consistent enough".yellow()
117            );
118            incomplete_files_count += 1;
119            continue;
120        }
121        let mut modified = false;
122        let mut line_idx = 0;
123        ok_files_count += 1;
124        while line_idx + 2 < loc_list.len() {
125            let loc = &loc_list.locs[line_idx];
126            if !loc.starts_normal {
127                line_idx += 1;
128                continue;
129            }
130            let content = &loc.content;
131            let Some((_, name)) =
132                regex_captures!(r"^[\s\w()]*\benum\s+([^({]+)\s+\{\s**$", content)
133            else {
134                line_idx += 1;
135                continue;
136            };
137
138            // We look whether the annotations before the enum contain any one
139            // of the excluding keywords
140            let whole_enum_range = loc_list
141                .block_range_of_line_number(LineNumber::from_index(line_idx))
142                .unwrap();
143            let whole_enum_range = loc_list.trimmed_range(whole_enum_range);
144            let excluding_keyword = EXCLUDING_KEYWORDS.iter().find(|&keyword| {
145                loc_list.locs[whole_enum_range.start.to_index()..line_idx]
146                    .iter()
147                    .any(|loc| loc.sort_key.contains(keyword))
148            });
149            if let Some(excluding_keyword) = excluding_keyword {
150                eprintln!("skipping enum {} ({})", name, excluding_keyword.yellow());
151                excluded_enums_count += 1;
152                line_idx = whole_enum_range.end.to_index() + 1;
153                continue;
154            }
155            loc_list.print_range_debug(
156                &format!(" sorting enum {} ", name.blue()),
157                whole_enum_range,
158            );
159            let range = loc_list.range_around_line_index(line_idx + 1).unwrap();
160            loc_list.sort_range(range).unwrap();
161            line_idx = range.end.to_index() + 2;
162            sorted_enum_count += 1;
163            modified = true;
164        }
165        if modified {
166            loc_list.write_file(file)?;
167            eprintln!("wrote {}", file.display());
168            modified_files_count += 1;
169        }
170    }
171    eprintln!("\nDone in {:.3}s\n", start.elapsed().as_secs_f32());
172    eprintln!("I analyzed {} files", files.len());
173    let mut problems = Vec::new();
174    if empty_files_count > 0 {
175        problems.push(format!("{} empty files", empty_files_count));
176    }
177    if incomplete_files_count > 0 {
178        problems.push(format!("{} incomplete files", incomplete_files_count));
179    }
180    if invalid_files_count > 0 {
181        problems.push(format!("{} invalid files", invalid_files_count));
182    }
183    if problems.is_empty() {
184        eprintln!("All {} files were ok", ok_files_count);
185    } else {
186        eprintln!(
187            "{} files were OK but I encountered {}",
188            ok_files_count,
189            problems.join(", ")
190        );
191    }
192    if excluded_enums_count > 0 {
193        eprintln!(
194            "I excluded {} enums whose annotation contained excluding keywords",
195            excluded_enums_count
196        );
197    }
198    eprintln!(
199        "I sorted {} enums in {} files",
200        sorted_enum_count, modified_files_count
201    );
202    Ok(())
203}
Source

pub fn print_debug(&self, label: &str)

Examples found in repository?
examples/explain/main.rs (line 24)
20fn main() -> CsResult<()> {
21    let args = Args::parse();
22    let loc_list = LocList::read_file(&args.path, Language::Rust)?;
23    let Some(sort_around) = args.sort_around else {
24        loc_list.print_debug(" WHOLE FILE ");
25        return Ok(());
26    };
27    let focused = loc_list.focus_around_line_number(sort_around)?;
28    focused.print_debug();
29    let blocks = focused.clone().focus.into_blocks();
30    for (i, block) in blocks.iter().enumerate() {
31        block.print_debug(&format!(" BLOCK {i} "));
32    }
33    let loc_list = focused.sort();
34    println!("------------ RESULT ------------");
35    print!("{}", loc_list);
36    Ok(())
37}
Source

pub fn trimmed_range(&self, range: LineNumberRange) -> LineNumberRange

Examples found in repository?
examples/sort-all-enums/main.rs (line 143)
86fn main() -> CsResult<()> {
87    let start = std::time::Instant::now();
88    let args = Args::parse();
89    let files = get_all_rust_files(args.path, &args.include, &args.exclude)?;
90    eprintln!("Found {} rust files", files.len());
91    let mut sorted_enum_count = 0;
92    let mut ok_files_count = 0;
93    let mut invalid_files_count = 0;
94    let mut incomplete_files_count = 0;
95    let mut excluded_enums_count = 0;
96    let mut modified_files_count = 0;
97    let mut empty_files_count = 0;
98    for file in &files {
99        let loc_list = LocList::read_file(file, Language::Rust);
100        let mut loc_list = match loc_list {
101            Ok(loc_list) => loc_list,
102            Err(e) => {
103                eprintln!("{} in {}: {:?}", "ERROR".red(), file.display(), e);
104                invalid_files_count += 1;
105                continue;
106            }
107        };
108        if !loc_list.has_content() {
109            empty_files_count += 1;
110            continue;
111        }
112        if !loc_list.is_complete() {
113            eprintln!(
114                "skipping {} ({})",
115                file.display(),
116                "not consistent enough".yellow()
117            );
118            incomplete_files_count += 1;
119            continue;
120        }
121        let mut modified = false;
122        let mut line_idx = 0;
123        ok_files_count += 1;
124        while line_idx + 2 < loc_list.len() {
125            let loc = &loc_list.locs[line_idx];
126            if !loc.starts_normal {
127                line_idx += 1;
128                continue;
129            }
130            let content = &loc.content;
131            let Some((_, name)) =
132                regex_captures!(r"^[\s\w()]*\benum\s+([^({]+)\s+\{\s**$", content)
133            else {
134                line_idx += 1;
135                continue;
136            };
137
138            // We look whether the annotations before the enum contain any one
139            // of the excluding keywords
140            let whole_enum_range = loc_list
141                .block_range_of_line_number(LineNumber::from_index(line_idx))
142                .unwrap();
143            let whole_enum_range = loc_list.trimmed_range(whole_enum_range);
144            let excluding_keyword = EXCLUDING_KEYWORDS.iter().find(|&keyword| {
145                loc_list.locs[whole_enum_range.start.to_index()..line_idx]
146                    .iter()
147                    .any(|loc| loc.sort_key.contains(keyword))
148            });
149            if let Some(excluding_keyword) = excluding_keyword {
150                eprintln!("skipping enum {} ({})", name, excluding_keyword.yellow());
151                excluded_enums_count += 1;
152                line_idx = whole_enum_range.end.to_index() + 1;
153                continue;
154            }
155            loc_list.print_range_debug(
156                &format!(" sorting enum {} ", name.blue()),
157                whole_enum_range,
158            );
159            let range = loc_list.range_around_line_index(line_idx + 1).unwrap();
160            loc_list.sort_range(range).unwrap();
161            line_idx = range.end.to_index() + 2;
162            sorted_enum_count += 1;
163            modified = true;
164        }
165        if modified {
166            loc_list.write_file(file)?;
167            eprintln!("wrote {}", file.display());
168            modified_files_count += 1;
169        }
170    }
171    eprintln!("\nDone in {:.3}s\n", start.elapsed().as_secs_f32());
172    eprintln!("I analyzed {} files", files.len());
173    let mut problems = Vec::new();
174    if empty_files_count > 0 {
175        problems.push(format!("{} empty files", empty_files_count));
176    }
177    if incomplete_files_count > 0 {
178        problems.push(format!("{} incomplete files", incomplete_files_count));
179    }
180    if invalid_files_count > 0 {
181        problems.push(format!("{} invalid files", invalid_files_count));
182    }
183    if problems.is_empty() {
184        eprintln!("All {} files were ok", ok_files_count);
185    } else {
186        eprintln!(
187            "{} files were OK but I encountered {}",
188            ok_files_count,
189            problems.join(", ")
190        );
191    }
192    if excluded_enums_count > 0 {
193        eprintln!(
194            "I excluded {} enums whose annotation contained excluding keywords",
195            excluded_enums_count
196        );
197    }
198    eprintln!(
199        "I sorted {} enums in {} files",
200        sorted_enum_count, modified_files_count
201    );
202    Ok(())
203}
Source

pub fn count_blank_lines_at_start(&self) -> usize

Source

pub fn full_range(&self) -> Option<LineNumberRange>

If the list isn’t empty, return a range covering it wholly

Source

pub fn check_range(&self, range: LineNumberRange) -> CsResult<()>

Source

pub fn range_exists(&self, range: LineNumberRange) -> bool

Check whether the range is valid and contains at least one line

Source

pub fn range_has_content(&self, range: LineNumberRange) -> bool

Source

pub fn has_content(&self) -> bool

Examples found in repository?
examples/list-invalid-files/main.rs (line 88)
67fn main() {
68    let args = Args::parse();
69    let files = get_all_rust_files(args.path, &args.include).unwrap();
70    eprintln!("Found {} rust files", files.len());
71    let mut no_complete_count = 0;
72    let mut errors = 0;
73    let mut ok_count = 0;
74    for file in files {
75        let loc_list = LocList::read_file(file.to_str().unwrap(), Language::Rust);
76        let loc_list = match loc_list {
77            Ok(loc_list) => loc_list,
78            Err(e) => {
79                eprintln!("{} {:?} : {}", "ERROR".red(), file, e);
80                errors += 1;
81                continue;
82            }
83        };
84        if loc_list.is_complete() {
85            ok_count += 1;
86            continue;
87        }
88        if !loc_list.has_content() {
89            eprintln!("{} {:?}", "EMPTY".yellow(), file);
90            ok_count += 1;
91            continue;
92        }
93        eprintln!("{} {:?}", "NOT COMPLETE".yellow(), file);
94        no_complete_count += 1;
95    }
96    eprintln!("OK files: {}", ok_count);
97    eprintln!("Erroring files: {}", errors);
98    eprintln!("Uncomplete files: {}", no_complete_count);
99}
More examples
Hide additional examples
examples/sort-all-enums/main.rs (line 108)
86fn main() -> CsResult<()> {
87    let start = std::time::Instant::now();
88    let args = Args::parse();
89    let files = get_all_rust_files(args.path, &args.include, &args.exclude)?;
90    eprintln!("Found {} rust files", files.len());
91    let mut sorted_enum_count = 0;
92    let mut ok_files_count = 0;
93    let mut invalid_files_count = 0;
94    let mut incomplete_files_count = 0;
95    let mut excluded_enums_count = 0;
96    let mut modified_files_count = 0;
97    let mut empty_files_count = 0;
98    for file in &files {
99        let loc_list = LocList::read_file(file, Language::Rust);
100        let mut loc_list = match loc_list {
101            Ok(loc_list) => loc_list,
102            Err(e) => {
103                eprintln!("{} in {}: {:?}", "ERROR".red(), file.display(), e);
104                invalid_files_count += 1;
105                continue;
106            }
107        };
108        if !loc_list.has_content() {
109            empty_files_count += 1;
110            continue;
111        }
112        if !loc_list.is_complete() {
113            eprintln!(
114                "skipping {} ({})",
115                file.display(),
116                "not consistent enough".yellow()
117            );
118            incomplete_files_count += 1;
119            continue;
120        }
121        let mut modified = false;
122        let mut line_idx = 0;
123        ok_files_count += 1;
124        while line_idx + 2 < loc_list.len() {
125            let loc = &loc_list.locs[line_idx];
126            if !loc.starts_normal {
127                line_idx += 1;
128                continue;
129            }
130            let content = &loc.content;
131            let Some((_, name)) =
132                regex_captures!(r"^[\s\w()]*\benum\s+([^({]+)\s+\{\s**$", content)
133            else {
134                line_idx += 1;
135                continue;
136            };
137
138            // We look whether the annotations before the enum contain any one
139            // of the excluding keywords
140            let whole_enum_range = loc_list
141                .block_range_of_line_number(LineNumber::from_index(line_idx))
142                .unwrap();
143            let whole_enum_range = loc_list.trimmed_range(whole_enum_range);
144            let excluding_keyword = EXCLUDING_KEYWORDS.iter().find(|&keyword| {
145                loc_list.locs[whole_enum_range.start.to_index()..line_idx]
146                    .iter()
147                    .any(|loc| loc.sort_key.contains(keyword))
148            });
149            if let Some(excluding_keyword) = excluding_keyword {
150                eprintln!("skipping enum {} ({})", name, excluding_keyword.yellow());
151                excluded_enums_count += 1;
152                line_idx = whole_enum_range.end.to_index() + 1;
153                continue;
154            }
155            loc_list.print_range_debug(
156                &format!(" sorting enum {} ", name.blue()),
157                whole_enum_range,
158            );
159            let range = loc_list.range_around_line_index(line_idx + 1).unwrap();
160            loc_list.sort_range(range).unwrap();
161            line_idx = range.end.to_index() + 2;
162            sorted_enum_count += 1;
163            modified = true;
164        }
165        if modified {
166            loc_list.write_file(file)?;
167            eprintln!("wrote {}", file.display());
168            modified_files_count += 1;
169        }
170    }
171    eprintln!("\nDone in {:.3}s\n", start.elapsed().as_secs_f32());
172    eprintln!("I analyzed {} files", files.len());
173    let mut problems = Vec::new();
174    if empty_files_count > 0 {
175        problems.push(format!("{} empty files", empty_files_count));
176    }
177    if incomplete_files_count > 0 {
178        problems.push(format!("{} incomplete files", incomplete_files_count));
179    }
180    if invalid_files_count > 0 {
181        problems.push(format!("{} invalid files", invalid_files_count));
182    }
183    if problems.is_empty() {
184        eprintln!("All {} files were ok", ok_files_count);
185    } else {
186        eprintln!(
187            "{} files were OK but I encountered {}",
188            ok_files_count,
189            problems.join(", ")
190        );
191    }
192    if excluded_enums_count > 0 {
193        eprintln!(
194            "I excluded {} enums whose annotation contained excluding keywords",
195            excluded_enums_count
196        );
197    }
198    eprintln!(
199        "I sorted {} enums in {} files",
200        sorted_enum_count, modified_files_count
201    );
202    Ok(())
203}
Source

pub fn last_significant_char(&self) -> Option<char>

Source

pub fn last_line_with_content(&self) -> Option<&Loc>

Source

pub fn last_line_in_range_with_content( &self, range: LineNumberRange, ) -> Option<&Loc>

Source

pub fn is_range_complete(&self, range: LineNumberRange) -> bool

Warning: doesn’t check whether a bigger range wouldn’t be complete too, so a range being complete doesn’t mean it is a block.

Source

pub fn is_complete(&self) -> bool

Examples found in repository?
examples/list-invalid-files/main.rs (line 84)
67fn main() {
68    let args = Args::parse();
69    let files = get_all_rust_files(args.path, &args.include).unwrap();
70    eprintln!("Found {} rust files", files.len());
71    let mut no_complete_count = 0;
72    let mut errors = 0;
73    let mut ok_count = 0;
74    for file in files {
75        let loc_list = LocList::read_file(file.to_str().unwrap(), Language::Rust);
76        let loc_list = match loc_list {
77            Ok(loc_list) => loc_list,
78            Err(e) => {
79                eprintln!("{} {:?} : {}", "ERROR".red(), file, e);
80                errors += 1;
81                continue;
82            }
83        };
84        if loc_list.is_complete() {
85            ok_count += 1;
86            continue;
87        }
88        if !loc_list.has_content() {
89            eprintln!("{} {:?}", "EMPTY".yellow(), file);
90            ok_count += 1;
91            continue;
92        }
93        eprintln!("{} {:?}", "NOT COMPLETE".yellow(), file);
94        no_complete_count += 1;
95    }
96    eprintln!("OK files: {}", ok_count);
97    eprintln!("Erroring files: {}", errors);
98    eprintln!("Uncomplete files: {}", no_complete_count);
99}
More examples
Hide additional examples
examples/sort-all-enums/main.rs (line 112)
86fn main() -> CsResult<()> {
87    let start = std::time::Instant::now();
88    let args = Args::parse();
89    let files = get_all_rust_files(args.path, &args.include, &args.exclude)?;
90    eprintln!("Found {} rust files", files.len());
91    let mut sorted_enum_count = 0;
92    let mut ok_files_count = 0;
93    let mut invalid_files_count = 0;
94    let mut incomplete_files_count = 0;
95    let mut excluded_enums_count = 0;
96    let mut modified_files_count = 0;
97    let mut empty_files_count = 0;
98    for file in &files {
99        let loc_list = LocList::read_file(file, Language::Rust);
100        let mut loc_list = match loc_list {
101            Ok(loc_list) => loc_list,
102            Err(e) => {
103                eprintln!("{} in {}: {:?}", "ERROR".red(), file.display(), e);
104                invalid_files_count += 1;
105                continue;
106            }
107        };
108        if !loc_list.has_content() {
109            empty_files_count += 1;
110            continue;
111        }
112        if !loc_list.is_complete() {
113            eprintln!(
114                "skipping {} ({})",
115                file.display(),
116                "not consistent enough".yellow()
117            );
118            incomplete_files_count += 1;
119            continue;
120        }
121        let mut modified = false;
122        let mut line_idx = 0;
123        ok_files_count += 1;
124        while line_idx + 2 < loc_list.len() {
125            let loc = &loc_list.locs[line_idx];
126            if !loc.starts_normal {
127                line_idx += 1;
128                continue;
129            }
130            let content = &loc.content;
131            let Some((_, name)) =
132                regex_captures!(r"^[\s\w()]*\benum\s+([^({]+)\s+\{\s**$", content)
133            else {
134                line_idx += 1;
135                continue;
136            };
137
138            // We look whether the annotations before the enum contain any one
139            // of the excluding keywords
140            let whole_enum_range = loc_list
141                .block_range_of_line_number(LineNumber::from_index(line_idx))
142                .unwrap();
143            let whole_enum_range = loc_list.trimmed_range(whole_enum_range);
144            let excluding_keyword = EXCLUDING_KEYWORDS.iter().find(|&keyword| {
145                loc_list.locs[whole_enum_range.start.to_index()..line_idx]
146                    .iter()
147                    .any(|loc| loc.sort_key.contains(keyword))
148            });
149            if let Some(excluding_keyword) = excluding_keyword {
150                eprintln!("skipping enum {} ({})", name, excluding_keyword.yellow());
151                excluded_enums_count += 1;
152                line_idx = whole_enum_range.end.to_index() + 1;
153                continue;
154            }
155            loc_list.print_range_debug(
156                &format!(" sorting enum {} ", name.blue()),
157                whole_enum_range,
158            );
159            let range = loc_list.range_around_line_index(line_idx + 1).unwrap();
160            loc_list.sort_range(range).unwrap();
161            line_idx = range.end.to_index() + 2;
162            sorted_enum_count += 1;
163            modified = true;
164        }
165        if modified {
166            loc_list.write_file(file)?;
167            eprintln!("wrote {}", file.display());
168            modified_files_count += 1;
169        }
170    }
171    eprintln!("\nDone in {:.3}s\n", start.elapsed().as_secs_f32());
172    eprintln!("I analyzed {} files", files.len());
173    let mut problems = Vec::new();
174    if empty_files_count > 0 {
175        problems.push(format!("{} empty files", empty_files_count));
176    }
177    if incomplete_files_count > 0 {
178        problems.push(format!("{} incomplete files", incomplete_files_count));
179    }
180    if invalid_files_count > 0 {
181        problems.push(format!("{} invalid files", invalid_files_count));
182    }
183    if problems.is_empty() {
184        eprintln!("All {} files were ok", ok_files_count);
185    } else {
186        eprintln!(
187            "{} files were OK but I encountered {}",
188            ok_files_count,
189            problems.join(", ")
190        );
191    }
192    if excluded_enums_count > 0 {
193        eprintln!(
194            "I excluded {} enums whose annotation contained excluding keywords",
195            excluded_enums_count
196        );
197    }
198    eprintln!(
199        "I sorted {} enums in {} files",
200        sorted_enum_count, modified_files_count
201    );
202    Ok(())
203}
Source

pub fn block_ranges_in_range( &self, range: LineNumberRange, ) -> Vec<LineNumberRange>

Assuming the provided range you pass is valid enough, give the ranges of the blocks in it.

Source

pub fn block_range_of_line_number( &self, line_number: LineNumber, ) -> CsResult<LineNumberRange>

Find the block the line is part of

For example, if you give the opening line of a struct (i.e a like like pub struct Foo {), you’ll get the whole struct with its doc comments, annotations, inner fields, til the closing brace. You also get the empty lines before which should stick with the block.

If you give the line of a field, you’ll get the field definition with its own comment and annotation.

Examples found in repository?
examples/sort-all-enums/main.rs (line 141)
86fn main() -> CsResult<()> {
87    let start = std::time::Instant::now();
88    let args = Args::parse();
89    let files = get_all_rust_files(args.path, &args.include, &args.exclude)?;
90    eprintln!("Found {} rust files", files.len());
91    let mut sorted_enum_count = 0;
92    let mut ok_files_count = 0;
93    let mut invalid_files_count = 0;
94    let mut incomplete_files_count = 0;
95    let mut excluded_enums_count = 0;
96    let mut modified_files_count = 0;
97    let mut empty_files_count = 0;
98    for file in &files {
99        let loc_list = LocList::read_file(file, Language::Rust);
100        let mut loc_list = match loc_list {
101            Ok(loc_list) => loc_list,
102            Err(e) => {
103                eprintln!("{} in {}: {:?}", "ERROR".red(), file.display(), e);
104                invalid_files_count += 1;
105                continue;
106            }
107        };
108        if !loc_list.has_content() {
109            empty_files_count += 1;
110            continue;
111        }
112        if !loc_list.is_complete() {
113            eprintln!(
114                "skipping {} ({})",
115                file.display(),
116                "not consistent enough".yellow()
117            );
118            incomplete_files_count += 1;
119            continue;
120        }
121        let mut modified = false;
122        let mut line_idx = 0;
123        ok_files_count += 1;
124        while line_idx + 2 < loc_list.len() {
125            let loc = &loc_list.locs[line_idx];
126            if !loc.starts_normal {
127                line_idx += 1;
128                continue;
129            }
130            let content = &loc.content;
131            let Some((_, name)) =
132                regex_captures!(r"^[\s\w()]*\benum\s+([^({]+)\s+\{\s**$", content)
133            else {
134                line_idx += 1;
135                continue;
136            };
137
138            // We look whether the annotations before the enum contain any one
139            // of the excluding keywords
140            let whole_enum_range = loc_list
141                .block_range_of_line_number(LineNumber::from_index(line_idx))
142                .unwrap();
143            let whole_enum_range = loc_list.trimmed_range(whole_enum_range);
144            let excluding_keyword = EXCLUDING_KEYWORDS.iter().find(|&keyword| {
145                loc_list.locs[whole_enum_range.start.to_index()..line_idx]
146                    .iter()
147                    .any(|loc| loc.sort_key.contains(keyword))
148            });
149            if let Some(excluding_keyword) = excluding_keyword {
150                eprintln!("skipping enum {} ({})", name, excluding_keyword.yellow());
151                excluded_enums_count += 1;
152                line_idx = whole_enum_range.end.to_index() + 1;
153                continue;
154            }
155            loc_list.print_range_debug(
156                &format!(" sorting enum {} ", name.blue()),
157                whole_enum_range,
158            );
159            let range = loc_list.range_around_line_index(line_idx + 1).unwrap();
160            loc_list.sort_range(range).unwrap();
161            line_idx = range.end.to_index() + 2;
162            sorted_enum_count += 1;
163            modified = true;
164        }
165        if modified {
166            loc_list.write_file(file)?;
167            eprintln!("wrote {}", file.display());
168            modified_files_count += 1;
169        }
170    }
171    eprintln!("\nDone in {:.3}s\n", start.elapsed().as_secs_f32());
172    eprintln!("I analyzed {} files", files.len());
173    let mut problems = Vec::new();
174    if empty_files_count > 0 {
175        problems.push(format!("{} empty files", empty_files_count));
176    }
177    if incomplete_files_count > 0 {
178        problems.push(format!("{} incomplete files", incomplete_files_count));
179    }
180    if invalid_files_count > 0 {
181        problems.push(format!("{} invalid files", invalid_files_count));
182    }
183    if problems.is_empty() {
184        eprintln!("All {} files were ok", ok_files_count);
185    } else {
186        eprintln!(
187            "{} files were OK but I encountered {}",
188            ok_files_count,
189            problems.join(", ")
190        );
191    }
192    if excluded_enums_count > 0 {
193        eprintln!(
194            "I excluded {} enums whose annotation contained excluding keywords",
195            excluded_enums_count
196        );
197    }
198    eprintln!(
199        "I sorted {} enums in {} files",
200        sorted_enum_count, modified_files_count
201    );
202    Ok(())
203}
Source

pub fn into_blocks(self) -> Vec<LocList>

Examples found in repository?
examples/explain/main.rs (line 29)
20fn main() -> CsResult<()> {
21    let args = Args::parse();
22    let loc_list = LocList::read_file(&args.path, Language::Rust)?;
23    let Some(sort_around) = args.sort_around else {
24        loc_list.print_debug(" WHOLE FILE ");
25        return Ok(());
26    };
27    let focused = loc_list.focus_around_line_number(sort_around)?;
28    focused.print_debug();
29    let blocks = focused.clone().focus.into_blocks();
30    for (i, block) in blocks.iter().enumerate() {
31        block.print_debug(&format!(" BLOCK {i} "));
32    }
33    let loc_list = focused.sort();
34    println!("------------ RESULT ------------");
35    print!("{}", loc_list);
36    Ok(())
37}
Source

pub fn range_around_line_number( &self, line_number: LineNumber, ) -> CsResult<LineNumberRange>

Source

pub fn range_around_line_index( &self, line_idx: LineIndex, ) -> CsResult<LineNumberRange>

Examples found in repository?
examples/sort-all-enums/main.rs (line 159)
86fn main() -> CsResult<()> {
87    let start = std::time::Instant::now();
88    let args = Args::parse();
89    let files = get_all_rust_files(args.path, &args.include, &args.exclude)?;
90    eprintln!("Found {} rust files", files.len());
91    let mut sorted_enum_count = 0;
92    let mut ok_files_count = 0;
93    let mut invalid_files_count = 0;
94    let mut incomplete_files_count = 0;
95    let mut excluded_enums_count = 0;
96    let mut modified_files_count = 0;
97    let mut empty_files_count = 0;
98    for file in &files {
99        let loc_list = LocList::read_file(file, Language::Rust);
100        let mut loc_list = match loc_list {
101            Ok(loc_list) => loc_list,
102            Err(e) => {
103                eprintln!("{} in {}: {:?}", "ERROR".red(), file.display(), e);
104                invalid_files_count += 1;
105                continue;
106            }
107        };
108        if !loc_list.has_content() {
109            empty_files_count += 1;
110            continue;
111        }
112        if !loc_list.is_complete() {
113            eprintln!(
114                "skipping {} ({})",
115                file.display(),
116                "not consistent enough".yellow()
117            );
118            incomplete_files_count += 1;
119            continue;
120        }
121        let mut modified = false;
122        let mut line_idx = 0;
123        ok_files_count += 1;
124        while line_idx + 2 < loc_list.len() {
125            let loc = &loc_list.locs[line_idx];
126            if !loc.starts_normal {
127                line_idx += 1;
128                continue;
129            }
130            let content = &loc.content;
131            let Some((_, name)) =
132                regex_captures!(r"^[\s\w()]*\benum\s+([^({]+)\s+\{\s**$", content)
133            else {
134                line_idx += 1;
135                continue;
136            };
137
138            // We look whether the annotations before the enum contain any one
139            // of the excluding keywords
140            let whole_enum_range = loc_list
141                .block_range_of_line_number(LineNumber::from_index(line_idx))
142                .unwrap();
143            let whole_enum_range = loc_list.trimmed_range(whole_enum_range);
144            let excluding_keyword = EXCLUDING_KEYWORDS.iter().find(|&keyword| {
145                loc_list.locs[whole_enum_range.start.to_index()..line_idx]
146                    .iter()
147                    .any(|loc| loc.sort_key.contains(keyword))
148            });
149            if let Some(excluding_keyword) = excluding_keyword {
150                eprintln!("skipping enum {} ({})", name, excluding_keyword.yellow());
151                excluded_enums_count += 1;
152                line_idx = whole_enum_range.end.to_index() + 1;
153                continue;
154            }
155            loc_list.print_range_debug(
156                &format!(" sorting enum {} ", name.blue()),
157                whole_enum_range,
158            );
159            let range = loc_list.range_around_line_index(line_idx + 1).unwrap();
160            loc_list.sort_range(range).unwrap();
161            line_idx = range.end.to_index() + 2;
162            sorted_enum_count += 1;
163            modified = true;
164        }
165        if modified {
166            loc_list.write_file(file)?;
167            eprintln!("wrote {}", file.display());
168            modified_files_count += 1;
169        }
170    }
171    eprintln!("\nDone in {:.3}s\n", start.elapsed().as_secs_f32());
172    eprintln!("I analyzed {} files", files.len());
173    let mut problems = Vec::new();
174    if empty_files_count > 0 {
175        problems.push(format!("{} empty files", empty_files_count));
176    }
177    if incomplete_files_count > 0 {
178        problems.push(format!("{} incomplete files", incomplete_files_count));
179    }
180    if invalid_files_count > 0 {
181        problems.push(format!("{} invalid files", invalid_files_count));
182    }
183    if problems.is_empty() {
184        eprintln!("All {} files were ok", ok_files_count);
185    } else {
186        eprintln!(
187            "{} files were OK but I encountered {}",
188            ok_files_count,
189            problems.join(", ")
190        );
191    }
192    if excluded_enums_count > 0 {
193        eprintln!(
194            "I excluded {} enums whose annotation contained excluding keywords",
195            excluded_enums_count
196        );
197    }
198    eprintln!(
199        "I sorted {} enums in {} files",
200        sorted_enum_count, modified_files_count
201    );
202    Ok(())
203}

Trait Implementations§

Source§

impl Clone for LocList

Source§

fn clone(&self) -> LocList

Returns a duplicate of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for LocList

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Default for LocList

Source§

fn default() -> LocList

Returns the “default value” for a type. Read more
Source§

impl Display for LocList

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Ord for LocList

Source§

fn cmp(&self, other: &Self) -> Ordering

This method returns an Ordering between self and other. Read more
1.21.0 · Source§

fn max(self, other: Self) -> Self
where Self: Sized,

Compares and returns the maximum of two values. Read more
1.21.0 · Source§

fn min(self, other: Self) -> Self
where Self: Sized,

Compares and returns the minimum of two values. Read more
1.50.0 · Source§

fn clamp(self, min: Self, max: Self) -> Self
where Self: Sized,

Restrict a value to a certain interval. Read more
Source§

impl PartialEq for LocList

Source§

fn eq(&self, other: &Self) -> bool

Tests for self and other values to be equal, and is used by ==.
1.0.0 · Source§

fn ne(&self, other: &Rhs) -> bool

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
Source§

impl PartialOrd for LocList

Source§

fn partial_cmp(&self, other: &Self) -> Option<Ordering>

This method returns an ordering between self and other values if one exists. Read more
1.0.0 · Source§

fn lt(&self, other: &Rhs) -> bool

Tests less than (for self and other) and is used by the < operator. Read more
1.0.0 · Source§

fn le(&self, other: &Rhs) -> bool

Tests less than or equal to (for self and other) and is used by the <= operator. Read more
1.0.0 · Source§

fn gt(&self, other: &Rhs) -> bool

Tests greater than (for self and other) and is used by the > operator. Read more
1.0.0 · Source§

fn ge(&self, other: &Rhs) -> bool

Tests greater than or equal to (for self and other) and is used by the >= operator. Read more
Source§

impl Eq for LocList

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T> ToString for T
where T: Display + ?Sized,

Source§

fn to_string(&self) -> String

Converts the given value to a String. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.