cargo/diagnostics/rules/
non_kebab_case_bins.rs1use std::path::Path;
2
3use cargo_util_terminal::report::AnnotationKind;
4use cargo_util_terminal::report::Group;
5use cargo_util_terminal::report::Level;
6use cargo_util_terminal::report::Origin;
7use cargo_util_terminal::report::Patch;
8use cargo_util_terminal::report::Snippet;
9use tracing::instrument;
10
11use super::STYLE;
12use crate::CargoResult;
13use crate::GlobalContext;
14use crate::diagnostics::AsIndex;
15use crate::diagnostics::Lint;
16use crate::diagnostics::LintLevel;
17use crate::diagnostics::LintLevelProduct;
18use crate::diagnostics::LintLevelSource;
19use crate::diagnostics::ScopedDiagnosticStats;
20use crate::diagnostics::get_key_value_span;
21use crate::diagnostics::workspace_rel_path;
22use crate::workspace::Package;
23use crate::workspace::Workspace;
24
25pub static LINT: &Lint = &Lint {
26 name: "non_kebab_case_bins",
27 primary_group: &STYLE,
28 msrv: Some(super::CARGO_LINTS_MSRV),
29 feature_gate: None,
30 docs: Some(
31 r#"
32### What it does
33
34Detect binary names, explicit and implicit, that are not kebab-case
35
36### Why is this bad?
37
38Kebab-case binary names is a common convention among command line tools.
39
40### Drawbacks
41
42It would be disruptive to existing users to change the binary name.
43
44A binary may need to conform to externally controlled conventions which can include a different naming convention.
45
46GUI applications may wish to choose a more user focused naming convention, like "Title Case" or "Sentence case".
47
48### Example
49
50```toml
51[[bin]]
52name = "foo_bar"
53```
54
55Should be written as:
56
57```toml
58[[bin]]
59name = "foo-bar"
60```
61"#,
62 ),
63};
64
65#[instrument(skip_all)]
66pub(crate) fn lint_package(
67 ws: &Workspace<'_>,
68 pkg: &Package,
69 manifest_path: &Path,
70 level: LintLevelProduct,
71 pkg_stats: &mut ScopedDiagnosticStats<'_>,
72 gctx: &GlobalContext,
73) -> CargoResult<()> {
74 let LintLevelProduct {
75 level: lint_level,
76 source,
77 } = level;
78
79 let manifest_path = workspace_rel_path(ws, manifest_path);
80
81 lint_package_inner(ws, pkg, &manifest_path, lint_level, source, pkg_stats, gctx)
82}
83
84fn lint_package_inner(
85 ws: &Workspace<'_>,
86 pkg: &Package,
87 manifest_path: &str,
88 lint_level: LintLevel,
89 source: LintLevelSource,
90 pkg_stats: &mut ScopedDiagnosticStats<'_>,
91 gctx: &GlobalContext,
92) -> CargoResult<()> {
93 let manifest = pkg.manifest();
94
95 for (i, bin) in manifest.normalized_toml().bin.iter().flatten().enumerate() {
96 let Some(original_name) = bin.name.as_deref() else {
97 continue;
98 };
99 let kebab_case = heck::ToKebabCase::to_kebab_case(original_name);
100 if kebab_case == original_name {
101 continue;
102 }
103
104 let document = manifest.document();
105 let contents = manifest.contents();
106 let level = lint_level.to_diagnostic_level();
107 let emitted_source = LINT.emitted_source(lint_level, source);
108
109 let mut primary_source = ws.target_dir().as_path_unlocked().to_owned();
110 primary_source.push("...");
112 primary_source.push("");
113 let mut primary_source = primary_source.display().to_string();
114 let primary_span_start = primary_source.len();
115 let primary_span_end = primary_span_start + original_name.len();
116 primary_source.push_str(original_name);
117 primary_source.push_str(std::env::consts::EXE_SUFFIX);
118 let mut primary_group = level
119 .primary_title(format!(
120 "binary `{original_name}` should have a kebab-case name"
121 ))
122 .element(
123 Snippet::source(&primary_source)
124 .annotation(AnnotationKind::Primary.span(primary_span_start..primary_span_end)),
125 );
126 if i == 0 {
127 primary_group = primary_group.element(Level::NOTE.message(emitted_source));
128 }
129 let mut report = vec![primary_group];
130
131 if let Some((i, _target)) = manifest
132 .original_toml()
133 .iter()
134 .flat_map(|m| m.bin.iter().flatten())
135 .enumerate()
136 .find(|(_i, t)| t.name.as_deref() == Some(original_name))
137 {
138 let mut help = Group::with_title(Level::HELP.secondary_title(format!(
139 "to change the binary name to `{kebab_case}`, convert `bin.name`"
140 )));
141 if let Some(document) = document
142 && let Some(contents) = contents
143 && let Some(span) = get_key_value_span(
144 document,
145 &["bin".as_index(), i.as_index(), "name".as_index()],
146 )
147 {
148 help = help.element(
149 Snippet::source(contents)
150 .path(manifest_path)
151 .patch(Patch::new(span.value, format!("\"{kebab_case}\""))),
152 );
153 } else {
154 help = help.element(Origin::path(manifest_path));
155 }
156 report.push(help);
157 } else if is_default_main(bin.path.as_ref())
158 && manifest
159 .original_toml()
160 .iter()
161 .flat_map(|m| m.bin.iter().flatten())
162 .all(|t| t.path != bin.path)
163 && manifest
164 .original_toml()
165 .and_then(|t| t.package.as_ref())
166 .map(|p| p.name.is_some())
167 .unwrap_or(false)
168 {
169 let help_package_name =
172 format!("to change the binary name to `{kebab_case}`, convert `package.name`");
173 let help_bin_table =
177 format!("to change the binary name to `{kebab_case}`, specify `bin.name`");
178 if let Some(document) = document
179 && let Some(contents) = contents
180 && let Some(span) = get_key_value_span(document, &["package", "name"])
181 {
182 report.push(
183 Level::HELP.secondary_title(help_package_name).element(
184 Snippet::source(contents)
185 .path(manifest_path)
186 .patch(Patch::new(span.value, format!("\"{kebab_case}\""))),
187 ),
188 );
189 report.push(
190 Level::HELP.secondary_title(help_bin_table).element(
191 Snippet::source(contents)
192 .path(manifest_path)
193 .patch(Patch::new(
194 contents.len()..contents.len(),
195 format!(
196 r#"
197[[bin]]
198name = "{kebab_case}"
199path = "src/main.rs""#
200 ),
201 )),
202 ),
203 );
204 } else {
205 report.push(
206 Level::HELP
207 .secondary_title(help_package_name)
208 .element(Origin::path(manifest_path)),
209 );
210 report.push(
211 Level::HELP
212 .secondary_title(help_bin_table)
213 .element(Origin::path(manifest_path)),
214 );
215 }
216 } else {
217 let path = bin
218 .path
219 .as_ref()
220 .expect("normalized have a path")
221 .0
222 .as_path();
223 let display_path = path.as_os_str().to_string_lossy();
224 let end = display_path.len() - if display_path.ends_with(".rs") { 3 } else { 0 };
225 let start = path
226 .parent()
227 .map(|p| {
228 let p = p.as_os_str().to_string_lossy();
229 p.len() + if p.is_empty() { 0 } else { 1 }
231 })
232 .unwrap_or(0);
233 let help = Level::HELP
234 .secondary_title(format!(
235 "to change the binary name to `{kebab_case}`, convert the file stem"
236 ))
237 .element(Snippet::source(display_path).patch(Patch::new(start..end, kebab_case)));
238 report.push(help);
239 }
240
241 pkg_stats.record_lint(lint_level);
242 gctx.shell().print_report(&report, lint_level.force())?;
243 }
244
245 Ok(())
246}
247
248fn is_default_main(path: Option<&cargo_util_schemas::manifest::PathValue>) -> bool {
249 let Some(path) = path else {
250 return false;
251 };
252 path.0 == std::path::Path::new("src/main.rs")
253}