dart-decimate 0.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (188) hide show
  1. package/Cargo.lock +572 -0
  2. package/Cargo.toml +41 -0
  3. package/LICENSE +21 -0
  4. package/README.md +617 -0
  5. package/assets/dart-decimate-banner.png +0 -0
  6. package/npm/bin/dart-decimate-mcp.js +48 -0
  7. package/npm/bin/dart-decimate.js +48 -0
  8. package/npm/scripts/postinstall.js +46 -0
  9. package/npm/scripts/test-npx-local.js +54 -0
  10. package/npm/scripts/test-npx-mcp-local.js +56 -0
  11. package/package.json +45 -0
  12. package/src/baseline.rs +643 -0
  13. package/src/bin/dart-decimate-mcp.rs +11 -0
  14. package/src/boundaries/tests.rs +60 -0
  15. package/src/boundaries.rs +317 -0
  16. package/src/changed_scope.rs +117 -0
  17. package/src/ci_template.rs +399 -0
  18. package/src/cli/analyze.rs +462 -0
  19. package/src/cli/analyzer_options.rs +82 -0
  20. package/src/cli/audit_run.rs +327 -0
  21. package/src/cli/boundary_args.rs +44 -0
  22. package/src/cli/ci_template_run.rs +196 -0
  23. package/src/cli/command_name.rs +20 -0
  24. package/src/cli/common_args.rs +167 -0
  25. package/src/cli/config_run.rs +78 -0
  26. package/src/cli/coverage_run.rs +393 -0
  27. package/src/cli/decision_surface_run.rs +99 -0
  28. package/src/cli/default_command.rs +69 -0
  29. package/src/cli/dupes_args.rs +150 -0
  30. package/src/cli/entry_points.rs +121 -0
  31. package/src/cli/error.rs +149 -0
  32. package/src/cli/error_output.rs +68 -0
  33. package/src/cli/explain_run.rs +72 -0
  34. package/src/cli/fix_run.rs +162 -0
  35. package/src/cli/flags_args.rs +23 -0
  36. package/src/cli/health_args.rs +200 -0
  37. package/src/cli/hooks_run.rs +191 -0
  38. package/src/cli/impact_run.rs +95 -0
  39. package/src/cli/init_run.rs +49 -0
  40. package/src/cli/inspect_args.rs +20 -0
  41. package/src/cli/inspect_run.rs +66 -0
  42. package/src/cli/issue_filter_args.rs +240 -0
  43. package/src/cli/list_run.rs +311 -0
  44. package/src/cli/mode_args.rs +72 -0
  45. package/src/cli/output_format.rs +62 -0
  46. package/src/cli/regression_args.rs +156 -0
  47. package/src/cli/request_args.rs +175 -0
  48. package/src/cli/schema_commands.rs +72 -0
  49. package/src/cli/scope_args.rs +174 -0
  50. package/src/cli/security_args.rs +175 -0
  51. package/src/cli/security_gate_run.rs +66 -0
  52. package/src/cli/security_summary_run.rs +43 -0
  53. package/src/cli/summary_args.rs +12 -0
  54. package/src/cli/tests.rs +516 -0
  55. package/src/cli/trace_args.rs +67 -0
  56. package/src/cli/trace_run.rs +131 -0
  57. package/src/cli/trace_tests.rs +235 -0
  58. package/src/cli/unsupported_run.rs +116 -0
  59. package/src/cli/watch_run.rs +153 -0
  60. package/src/cli.rs +603 -0
  61. package/src/config/boundary_config.rs +235 -0
  62. package/src/config/cache.rs +25 -0
  63. package/src/config/dependencies.rs +114 -0
  64. package/src/config/health.rs +237 -0
  65. package/src/config/jsonc.rs +66 -0
  66. package/src/config/policy.rs +91 -0
  67. package/src/config/rule_aliases.rs +487 -0
  68. package/src/config/rules.rs +339 -0
  69. package/src/config.rs +635 -0
  70. package/src/coverage.rs +469 -0
  71. package/src/dart_parser.rs +673 -0
  72. package/src/decision_surface.rs +405 -0
  73. package/src/dependencies/analyze.rs +218 -0
  74. package/src/dependencies/codegen.rs +118 -0
  75. package/src/dependencies/discovery.rs +60 -0
  76. package/src/dependencies/overrides.rs +76 -0
  77. package/src/dependencies/private_src_imports.rs +32 -0
  78. package/src/dependencies/pubspec_document.rs +86 -0
  79. package/src/dependencies/pubspec_entry.rs +96 -0
  80. package/src/dependencies/tests.rs +544 -0
  81. package/src/dependencies/usage.rs +33 -0
  82. package/src/dependencies.rs +553 -0
  83. package/src/dependency_scripts.rs +91 -0
  84. package/src/dupes/lex.rs +236 -0
  85. package/src/dupes/tests.rs +119 -0
  86. package/src/dupes.rs +625 -0
  87. package/src/explain.rs +692 -0
  88. package/src/extract/directives.rs +252 -0
  89. package/src/extract/error_tests.rs +25 -0
  90. package/src/extract/members.rs +210 -0
  91. package/src/extract/primary_constructors.rs +421 -0
  92. package/src/extract/references.rs +151 -0
  93. package/src/extract/routes.rs +691 -0
  94. package/src/extract/signatures.rs +266 -0
  95. package/src/extract/string_tests.rs +18 -0
  96. package/src/extract/strings.rs +107 -0
  97. package/src/extract/tests.rs +697 -0
  98. package/src/extract.rs +680 -0
  99. package/src/feature_flags/tests.rs +76 -0
  100. package/src/feature_flags.rs +453 -0
  101. package/src/finding_identity.rs +60 -0
  102. package/src/fix.rs +551 -0
  103. package/src/generated.rs +53 -0
  104. package/src/graph/augment_tests.rs +212 -0
  105. package/src/graph/conditionals.rs +74 -0
  106. package/src/graph/package_config_tests.rs +100 -0
  107. package/src/graph/parts.rs +248 -0
  108. package/src/graph/pubspec_tests.rs +119 -0
  109. package/src/graph/tests.rs +837 -0
  110. package/src/graph/uri_tests.rs +102 -0
  111. package/src/graph.rs +644 -0
  112. package/src/health/coverage.rs +309 -0
  113. package/src/health/ownership.rs +175 -0
  114. package/src/health/runtime_coverage.rs +616 -0
  115. package/src/health/runtime_intelligence.rs +511 -0
  116. package/src/health/scores.rs +296 -0
  117. package/src/health/tests.rs +240 -0
  118. package/src/health/threshold_types.rs +163 -0
  119. package/src/health/thresholds.rs +229 -0
  120. package/src/health/types.rs +636 -0
  121. package/src/health.rs +597 -0
  122. package/src/hooks/agent_settings.rs +175 -0
  123. package/src/hooks/templates.rs +51 -0
  124. package/src/hooks.rs +569 -0
  125. package/src/impact.rs +287 -0
  126. package/src/init.rs +237 -0
  127. package/src/inspect.rs +142 -0
  128. package/src/intelligence/tests.rs +232 -0
  129. package/src/intelligence.rs +305 -0
  130. package/src/lib.rs +198 -0
  131. package/src/main.rs +5 -0
  132. package/src/manifest/mcp.rs +565 -0
  133. package/src/manifest.rs +552 -0
  134. package/src/mcp/cli_args/value_args.rs +175 -0
  135. package/src/mcp/cli_args.rs +658 -0
  136. package/src/mcp/cli_args_tests.rs +522 -0
  137. package/src/mcp/code_execute.rs +671 -0
  138. package/src/mcp/tools.rs +660 -0
  139. package/src/mcp.rs +325 -0
  140. package/src/output/audit_risk.rs +135 -0
  141. package/src/output/dependency_findings.rs +327 -0
  142. package/src/output/duplication_findings.rs +114 -0
  143. package/src/output/feature_flag_findings.rs +122 -0
  144. package/src/output/format.rs +31 -0
  145. package/src/output/graph_findings.rs +461 -0
  146. package/src/output/health_findings.rs +612 -0
  147. package/src/output/human.rs +27 -0
  148. package/src/output/next_steps.rs +92 -0
  149. package/src/output/route_findings.rs +76 -0
  150. package/src/output/runtime_coverage.rs +515 -0
  151. package/src/output/scope.rs +183 -0
  152. package/src/output/security_findings.rs +390 -0
  153. package/src/output/security_sarif.rs +150 -0
  154. package/src/output/suppressions.rs +323 -0
  155. package/src/output/symbol_findings.rs +257 -0
  156. package/src/output/tests.rs +114 -0
  157. package/src/output/types.rs +604 -0
  158. package/src/output/widget_findings.rs +213 -0
  159. package/src/output.rs +682 -0
  160. package/src/package_map.rs +495 -0
  161. package/src/policy/packs.rs +232 -0
  162. package/src/policy/tests.rs +134 -0
  163. package/src/policy.rs +640 -0
  164. package/src/project_list.rs +376 -0
  165. package/src/report_schema/inventory.rs +418 -0
  166. package/src/report_schema.rs +488 -0
  167. package/src/routes.rs +354 -0
  168. package/src/scan/tests.rs +250 -0
  169. package/src/scan.rs +275 -0
  170. package/src/security/detect.rs +639 -0
  171. package/src/security/tests.rs +178 -0
  172. package/src/security.rs +373 -0
  173. package/src/security_gate.rs +555 -0
  174. package/src/symbols/path_filters.rs +27 -0
  175. package/src/symbols/private_type_leaks.rs +125 -0
  176. package/src/symbols/riverpod.rs +113 -0
  177. package/src/symbols/tests.rs +692 -0
  178. package/src/symbols.rs +693 -0
  179. package/src/trace/tests.rs +225 -0
  180. package/src/trace.rs +690 -0
  181. package/src/unsupported.rs +47 -0
  182. package/src/widgets/lifecycle.rs +484 -0
  183. package/src/widgets/params.rs +236 -0
  184. package/src/widgets/tests.rs +430 -0
  185. package/src/widgets/top_level.rs +110 -0
  186. package/src/widgets/unrendered.rs +374 -0
  187. package/src/widgets.rs +590 -0
  188. package/src/workspace_scope.rs +358 -0
@@ -0,0 +1,76 @@
1
+ use std::fs;
2
+
3
+ use tempfile::TempDir;
4
+
5
+ use crate::{FeatureFlagOptions, detect_feature_flags, scan_project};
6
+
7
+ #[test]
8
+ fn detects_dart_and_flutter_feature_flag_patterns() -> Result<(), Box<dyn std::error::Error>> {
9
+ let fixture = tempfile::tempdir()?;
10
+ write(
11
+ &fixture,
12
+ "lib/main.dart",
13
+ "import 'dart:io';
14
+ import 'package:firebase_remote_config/firebase_remote_config.dart';
15
+
16
+ const newUi = bool.fromEnvironment('FEATURE_NEW_UI');
17
+ const cohort = String.fromEnvironment('EXPERIMENT_COHORT');
18
+
19
+ void main() {
20
+ if (Platform.environment['ENABLE_PAYWALL'] == 'true') {}
21
+ final remoteConfig = FirebaseRemoteConfig.instance;
22
+ if (remoteConfig.getBool('new_checkout')) {}
23
+ final enabled = client.boolVariation('checkout-redesign', false);
24
+ print(enabled);
25
+ }
26
+ ",
27
+ )?;
28
+ let project = scan_project(fixture.path())?;
29
+
30
+ let report = detect_feature_flags(&project, &FeatureFlagOptions::default())?;
31
+
32
+ let names = report
33
+ .flags
34
+ .iter()
35
+ .map(|flag| flag.name.as_str())
36
+ .collect::<Vec<_>>();
37
+ assert_eq!(report.total_occurrences, 5);
38
+ assert!(names.contains(&"FEATURE_NEW_UI"));
39
+ assert!(names.contains(&"EXPERIMENT_COHORT"));
40
+ assert!(names.contains(&"ENABLE_PAYWALL"));
41
+ assert!(names.contains(&"new_checkout"));
42
+ assert!(names.contains(&"checkout-redesign"));
43
+
44
+ Ok(())
45
+ }
46
+
47
+ #[test]
48
+ fn skips_comments_and_generated_files() -> Result<(), Box<dyn std::error::Error>> {
49
+ let fixture = tempfile::tempdir()?;
50
+ write(
51
+ &fixture,
52
+ "lib/main.dart",
53
+ "// bool.fromEnvironment('FEATURE_COMMENTED')\nvoid main() {}\n",
54
+ )?;
55
+ write(
56
+ &fixture,
57
+ "lib/app.g.dart",
58
+ "const generated = bool.fromEnvironment('FEATURE_GENERATED');\n",
59
+ )?;
60
+ let project = scan_project(fixture.path())?;
61
+
62
+ let report = detect_feature_flags(&project, &FeatureFlagOptions::default())?;
63
+
64
+ assert!(report.flags.is_empty());
65
+ assert_eq!(report.total_occurrences, 0);
66
+
67
+ Ok(())
68
+ }
69
+
70
+ fn write(fixture: &TempDir, path: &str, source: &str) -> Result<(), std::io::Error> {
71
+ let path = fixture.path().join(path);
72
+ if let Some(parent) = path.parent() {
73
+ fs::create_dir_all(parent)?;
74
+ }
75
+ fs::write(path, source)
76
+ }
@@ -0,0 +1,453 @@
1
+ use std::collections::{BTreeMap, BTreeSet};
2
+ use std::fs;
3
+ use std::path::{Path, PathBuf};
4
+
5
+ use serde::{Deserialize, Serialize};
6
+ use thiserror::Error;
7
+
8
+ use crate::generated::is_generated_dart_path;
9
+ use crate::graph::normalize_against;
10
+ use crate::{Location, ScannedProject};
11
+
12
+ /// Feature flag detector options.
13
+ #[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
14
+ pub struct FeatureFlagOptions {
15
+ /// Limit output to the N most frequently referenced flags.
16
+ pub top: Option<usize>,
17
+ }
18
+
19
+ /// Feature flag report.
20
+ #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
21
+ pub struct FeatureFlagReport {
22
+ /// Options used to compute this report.
23
+ pub options: FeatureFlagOptions,
24
+ /// Dart files included in flag detection.
25
+ pub analyzed_files: usize,
26
+ /// Grouped feature flags.
27
+ pub flags: Vec<FeatureFlag>,
28
+ /// Raw feature flag occurrence count.
29
+ pub total_occurrences: usize,
30
+ }
31
+
32
+ /// One grouped feature flag.
33
+ #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
34
+ pub struct FeatureFlag {
35
+ /// Flag key/name.
36
+ pub name: String,
37
+ /// Detection source category.
38
+ pub source: FeatureFlagSource,
39
+ /// Provider or platform surface.
40
+ pub provider: String,
41
+ /// Detection confidence.
42
+ pub confidence: FeatureFlagConfidence,
43
+ /// Occurrences for this flag.
44
+ pub occurrences: Vec<FeatureFlagOccurrence>,
45
+ }
46
+
47
+ /// Feature flag source category.
48
+ #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
49
+ #[serde(rename_all = "kebab-case")]
50
+ pub enum FeatureFlagSource {
51
+ /// Dart compilation configuration environment.
52
+ CompileTimeEnvironment,
53
+ /// Native process environment.
54
+ ProcessEnvironment,
55
+ /// Feature flag SDK or service call.
56
+ SdkCall,
57
+ }
58
+
59
+ /// Detection confidence.
60
+ #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
61
+ #[serde(rename_all = "kebab-case")]
62
+ pub enum FeatureFlagConfidence {
63
+ /// Low-confidence heuristic.
64
+ Low,
65
+ /// Medium-confidence heuristic.
66
+ Medium,
67
+ /// High-confidence known flag surface.
68
+ High,
69
+ }
70
+
71
+ /// One feature flag occurrence.
72
+ #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
73
+ pub struct FeatureFlagOccurrence {
74
+ /// Dart file path.
75
+ pub path: PathBuf,
76
+ /// Location of the call/property access.
77
+ pub location: Location,
78
+ /// Matched expression or API surface.
79
+ pub expression: String,
80
+ }
81
+
82
+ /// Errors returned while detecting feature flags.
83
+ #[derive(Debug, Error)]
84
+ pub enum FeatureFlagError {
85
+ /// A Dart file could not be read.
86
+ #[error("failed to read Dart file {path}: {source}")]
87
+ ReadFile {
88
+ /// File path.
89
+ path: PathBuf,
90
+ /// Underlying IO error.
91
+ source: std::io::Error,
92
+ },
93
+ }
94
+
95
+ #[derive(Debug, Clone, PartialEq, Eq)]
96
+ struct FlagGroup {
97
+ name: String,
98
+ source: FeatureFlagSource,
99
+ provider: String,
100
+ confidence: FeatureFlagConfidence,
101
+ occurrences: Vec<FeatureFlagOccurrence>,
102
+ }
103
+
104
+ /// Detect Dart and Flutter feature flag patterns.
105
+ ///
106
+ /// # Errors
107
+ ///
108
+ /// Returns [`FeatureFlagError`] if a scanned Dart file cannot be read.
109
+ pub fn detect_feature_flags(
110
+ project: &ScannedProject,
111
+ options: &FeatureFlagOptions,
112
+ ) -> Result<FeatureFlagReport, FeatureFlagError> {
113
+ let mut groups = BTreeMap::<(String, FeatureFlagSource, String), FlagGroup>::new();
114
+ let mut analyzed_files = 0;
115
+
116
+ for file in &project.files {
117
+ let path = normalize_against(&project.root, &file.path);
118
+ if !path.starts_with(&project.root) || is_generated_dart_path(&path) {
119
+ continue;
120
+ }
121
+ analyzed_files += 1;
122
+ let source = fs::read_to_string(&path).map_err(|source| FeatureFlagError::ReadFile {
123
+ path: path.clone(),
124
+ source,
125
+ })?;
126
+ for detected in detect_in_source(&path, &source) {
127
+ let key = (
128
+ detected.name.clone(),
129
+ detected.source,
130
+ detected.provider.clone(),
131
+ );
132
+ let group = groups.entry(key).or_insert_with(|| FlagGroup {
133
+ name: detected.name.clone(),
134
+ source: detected.source,
135
+ provider: detected.provider.clone(),
136
+ confidence: detected.confidence,
137
+ occurrences: Vec::new(),
138
+ });
139
+ group.confidence = group.confidence.max(detected.confidence);
140
+ group.occurrences.push(detected.occurrence);
141
+ }
142
+ }
143
+
144
+ let total_occurrences = groups
145
+ .values()
146
+ .map(|group| group.occurrences.len())
147
+ .sum::<usize>();
148
+ let mut flags = groups
149
+ .into_values()
150
+ .map(FeatureFlag::from)
151
+ .collect::<Vec<_>>();
152
+ flags.sort_by(|left, right| {
153
+ (
154
+ std::cmp::Reverse(left.occurrences.len()),
155
+ &left.name,
156
+ left.source,
157
+ &left.provider,
158
+ )
159
+ .cmp(&(
160
+ std::cmp::Reverse(right.occurrences.len()),
161
+ &right.name,
162
+ right.source,
163
+ &right.provider,
164
+ ))
165
+ });
166
+ if let Some(top) = options.top {
167
+ flags.truncate(top);
168
+ }
169
+
170
+ Ok(FeatureFlagReport {
171
+ options: options.clone(),
172
+ analyzed_files,
173
+ flags,
174
+ total_occurrences,
175
+ })
176
+ }
177
+
178
+ impl From<FlagGroup> for FeatureFlag {
179
+ fn from(group: FlagGroup) -> Self {
180
+ let mut seen = BTreeSet::new();
181
+ let mut occurrences = group
182
+ .occurrences
183
+ .into_iter()
184
+ .filter(|occurrence| {
185
+ seen.insert((
186
+ occurrence.path.clone(),
187
+ occurrence.location.line,
188
+ occurrence.location.column,
189
+ occurrence.expression.clone(),
190
+ ))
191
+ })
192
+ .collect::<Vec<_>>();
193
+ occurrences.sort_by(|left, right| {
194
+ (&left.path, left.location.line, left.location.column).cmp(&(
195
+ &right.path,
196
+ right.location.line,
197
+ right.location.column,
198
+ ))
199
+ });
200
+ Self {
201
+ name: group.name,
202
+ source: group.source,
203
+ provider: group.provider,
204
+ confidence: group.confidence,
205
+ occurrences,
206
+ }
207
+ }
208
+ }
209
+
210
+ #[derive(Debug, Clone, PartialEq, Eq)]
211
+ struct DetectedFlag {
212
+ name: String,
213
+ source: FeatureFlagSource,
214
+ provider: String,
215
+ confidence: FeatureFlagConfidence,
216
+ occurrence: FeatureFlagOccurrence,
217
+ }
218
+
219
+ struct DetectionSpec<'a> {
220
+ name: String,
221
+ source_kind: FeatureFlagSource,
222
+ provider: &'a str,
223
+ confidence: FeatureFlagConfidence,
224
+ expression: &'a str,
225
+ }
226
+
227
+ fn detect_in_source(path: &Path, source: &str) -> Vec<DetectedFlag> {
228
+ let mut flags = Vec::new();
229
+ detect_compile_time_environment(path, source, &mut flags);
230
+ detect_platform_environment(path, source, &mut flags);
231
+ detect_firebase_remote_config(path, source, &mut flags);
232
+ detect_launchdarkly(path, source, &mut flags);
233
+ flags
234
+ }
235
+
236
+ fn detect_compile_time_environment(path: &Path, source: &str, flags: &mut Vec<DetectedFlag>) {
237
+ for pattern in [
238
+ "bool.fromEnvironment(",
239
+ "bool.hasEnvironment(",
240
+ "String.fromEnvironment(",
241
+ "int.fromEnvironment(",
242
+ ] {
243
+ for (index, name) in string_args_for_pattern(source, pattern) {
244
+ let bool_env = pattern.starts_with("bool.");
245
+ if bool_env || is_flag_like_name(&name) {
246
+ flags.push(detected(
247
+ path,
248
+ source,
249
+ index,
250
+ DetectionSpec {
251
+ name,
252
+ source_kind: FeatureFlagSource::CompileTimeEnvironment,
253
+ provider: "dart:core",
254
+ confidence: if bool_env {
255
+ FeatureFlagConfidence::High
256
+ } else {
257
+ FeatureFlagConfidence::Medium
258
+ },
259
+ expression: pattern.trim_end_matches('('),
260
+ },
261
+ ));
262
+ }
263
+ }
264
+ }
265
+ }
266
+
267
+ fn detect_platform_environment(path: &Path, source: &str, flags: &mut Vec<DetectedFlag>) {
268
+ for pattern in ["Platform.environment[", "Platform.environment.containsKey("] {
269
+ for (index, name) in string_args_for_pattern(source, pattern) {
270
+ if is_flag_like_name(&name) {
271
+ flags.push(detected(
272
+ path,
273
+ source,
274
+ index,
275
+ DetectionSpec {
276
+ name,
277
+ source_kind: FeatureFlagSource::ProcessEnvironment,
278
+ provider: "dart:io",
279
+ confidence: FeatureFlagConfidence::High,
280
+ expression: pattern.trim_end_matches(['(', '[']),
281
+ },
282
+ ));
283
+ }
284
+ }
285
+ }
286
+ }
287
+
288
+ fn detect_firebase_remote_config(path: &Path, source: &str, flags: &mut Vec<DetectedFlag>) {
289
+ if !source.contains("FirebaseRemoteConfig") && !source.contains("remoteConfig.") {
290
+ return;
291
+ }
292
+ for receiver in ["remoteConfig.", "FirebaseRemoteConfig.instance."] {
293
+ for method in ["getBool(", "getString(", "getInt(", "getDouble("] {
294
+ let pattern = format!("{receiver}{method}");
295
+ for (index, name) in string_args_for_pattern(source, &pattern) {
296
+ flags.push(detected(
297
+ path,
298
+ source,
299
+ index,
300
+ DetectionSpec {
301
+ name,
302
+ source_kind: FeatureFlagSource::SdkCall,
303
+ provider: "firebase_remote_config",
304
+ confidence: FeatureFlagConfidence::High,
305
+ expression: pattern.trim_end_matches('('),
306
+ },
307
+ ));
308
+ }
309
+ }
310
+ }
311
+ }
312
+
313
+ fn detect_launchdarkly(path: &Path, source: &str, flags: &mut Vec<DetectedFlag>) {
314
+ let launchdarkly_context = source.contains("LaunchDarkly") || source.contains("LDClient");
315
+ for method in [
316
+ ".boolVariation(",
317
+ ".stringVariation(",
318
+ ".intVariation(",
319
+ ".doubleVariation(",
320
+ ".jsonVariation(",
321
+ ".variation(",
322
+ ] {
323
+ if method == ".variation(" && !launchdarkly_context {
324
+ continue;
325
+ }
326
+ for (index, name) in string_args_for_pattern(source, method) {
327
+ flags.push(detected(
328
+ path,
329
+ source,
330
+ index,
331
+ DetectionSpec {
332
+ name,
333
+ source_kind: FeatureFlagSource::SdkCall,
334
+ provider: "launchdarkly",
335
+ confidence: if launchdarkly_context {
336
+ FeatureFlagConfidence::High
337
+ } else {
338
+ FeatureFlagConfidence::Medium
339
+ },
340
+ expression: method.trim_start_matches('.').trim_end_matches('('),
341
+ },
342
+ ));
343
+ }
344
+ }
345
+ }
346
+
347
+ fn detected(path: &Path, source: &str, index: usize, spec: DetectionSpec<'_>) -> DetectedFlag {
348
+ DetectedFlag {
349
+ name: spec.name,
350
+ source: spec.source_kind,
351
+ provider: spec.provider.to_owned(),
352
+ confidence: spec.confidence,
353
+ occurrence: FeatureFlagOccurrence {
354
+ path: path.to_path_buf(),
355
+ location: location_for_index(source, index),
356
+ expression: spec.expression.to_owned(),
357
+ },
358
+ }
359
+ }
360
+
361
+ fn string_args_for_pattern(source: &str, pattern: &str) -> Vec<(usize, String)> {
362
+ let mut matches = Vec::new();
363
+ let mut offset = 0;
364
+ while let Some(relative) = source[offset..].find(pattern) {
365
+ let index = offset + relative;
366
+ offset = index + pattern.len();
367
+ if is_comment_match(source, index) {
368
+ continue;
369
+ }
370
+ if let Some((name, _literal_index)) = first_string_literal(source, offset) {
371
+ matches.push((index, name));
372
+ }
373
+ }
374
+ matches
375
+ }
376
+
377
+ fn first_string_literal(source: &str, mut index: usize) -> Option<(String, usize)> {
378
+ let bytes = source.as_bytes();
379
+ while index < bytes.len() && bytes[index].is_ascii_whitespace() {
380
+ index += 1;
381
+ }
382
+ if index < bytes.len()
383
+ && matches!(bytes[index], b'r' | b'R')
384
+ && index + 1 < bytes.len()
385
+ && matches!(bytes[index + 1], b'\'' | b'"')
386
+ {
387
+ index += 1;
388
+ }
389
+ if index >= bytes.len() || !matches!(bytes[index], b'\'' | b'"') {
390
+ return None;
391
+ }
392
+ let quote = bytes[index];
393
+ let literal_start = index;
394
+ index += 1;
395
+ let value_start = index;
396
+ while index < bytes.len() {
397
+ if bytes[index] == b'\\' {
398
+ index = (index + 2).min(bytes.len());
399
+ continue;
400
+ }
401
+ if bytes[index] == quote {
402
+ return Some((source[value_start..index].to_owned(), literal_start));
403
+ }
404
+ index += 1;
405
+ }
406
+ None
407
+ }
408
+
409
+ fn is_comment_match(source: &str, index: usize) -> bool {
410
+ let line_start = source[..index]
411
+ .rfind('\n')
412
+ .map_or(0, |position| position + 1);
413
+ if source[line_start..index].contains("//") {
414
+ return true;
415
+ }
416
+ let last_block_open = source[..index].rfind("/*");
417
+ let last_block_close = source[..index].rfind("*/");
418
+ last_block_open.is_some_and(|open| last_block_close.is_none_or(|close| open > close))
419
+ }
420
+
421
+ fn location_for_index(source: &str, index: usize) -> Location {
422
+ let line = source[..index]
423
+ .bytes()
424
+ .filter(|byte| *byte == b'\n')
425
+ .count()
426
+ + 1;
427
+ let column = source[..index]
428
+ .rfind('\n')
429
+ .map_or(index, |position| index - position - 1);
430
+ Location { line, column }
431
+ }
432
+
433
+ fn is_flag_like_name(name: &str) -> bool {
434
+ let upper = name.to_ascii_uppercase();
435
+ let lower = name.to_ascii_lowercase();
436
+ upper.starts_with("FEATURE_")
437
+ || upper.starts_with("ENABLE_")
438
+ || upper.starts_with("DISABLE_")
439
+ || upper.starts_with("EXPERIMENT_")
440
+ || upper.starts_with("FLAG_")
441
+ || upper.starts_with("FF_")
442
+ || lower.contains("feature")
443
+ || lower.contains("flag")
444
+ || lower.contains("enable")
445
+ || lower.contains("experiment")
446
+ || lower.contains("toggle")
447
+ || lower.contains("beta")
448
+ || lower.contains("rollout")
449
+ || lower.contains("logging")
450
+ }
451
+
452
+ #[cfg(test)]
453
+ mod tests;
@@ -0,0 +1,60 @@
1
+ use crate::output::{Finding, FindingEdge, FindingKind};
2
+
3
+ #[must_use]
4
+ pub(crate) fn finding_identity(finding: &Finding) -> String {
5
+ if let Some(fingerprint) = finding.fingerprint.as_deref() {
6
+ let text = format!("{}\n{:?}\n{}", finding.rule_id, finding.kind, fingerprint);
7
+ return format!("finding:{:016x}", fnv64(&text));
8
+ }
9
+
10
+ if complexity_kind(finding.kind) {
11
+ let text = format!(
12
+ "{}\n{:?}\n{}\n{}",
13
+ finding.rule_id,
14
+ finding.kind,
15
+ finding.path,
16
+ complexity_symbol(&finding.message)
17
+ );
18
+ return format!("finding:{:016x}", fnv64(&text));
19
+ }
20
+
21
+ let text = format!(
22
+ "{}\n{:?}\n{}\n{}\n{}\n{}",
23
+ finding.rule_id,
24
+ finding.kind,
25
+ finding.path,
26
+ finding.edge.as_ref().map_or(String::new(), edge_identity),
27
+ finding.files.join("\n"),
28
+ finding.message
29
+ );
30
+ format!("finding:{:016x}", fnv64(&text))
31
+ }
32
+
33
+ fn edge_identity(edge: &FindingEdge) -> String {
34
+ format!("{}:{}:{}:{}", edge.from, edge.to, edge.specifier, edge.kind)
35
+ }
36
+
37
+ fn complexity_symbol(message: &str) -> &str {
38
+ message
39
+ .split_once(" has cyclomatic complexity ")
40
+ .map_or(message, |(symbol, _)| symbol)
41
+ }
42
+
43
+ const fn complexity_kind(kind: FindingKind) -> bool {
44
+ matches!(
45
+ kind,
46
+ FindingKind::HighCyclomaticComplexity
47
+ | FindingKind::HighCognitiveComplexity
48
+ | FindingKind::HighComplexity
49
+ | FindingKind::HighCrapScore
50
+ )
51
+ }
52
+
53
+ fn fnv64(text: &str) -> u64 {
54
+ let mut hash = 0xcbf2_9ce4_8422_2325_u64;
55
+ for byte in text.as_bytes() {
56
+ hash ^= u64::from(*byte);
57
+ hash = hash.wrapping_mul(0x0000_0100_0000_01b3);
58
+ }
59
+ hash
60
+ }