Skip to content

Commit a119ef8

Browse files
authored
fix(rust): fix panic when 'dependencies' field is not used in cargo.toml (#3997)
1 parent c8283ce commit a119ef8

File tree

4 files changed

+51
-2
lines changed

4 files changed

+51
-2
lines changed

pkg/fanal/analyzer/language/rust/cargo/cargo.go

+6-2
Original file line numberDiff line numberDiff line change
@@ -176,7 +176,11 @@ func (a cargoAnalyzer) parseCargoTOML(fsys fs.FS, path string) (map[string]strin
176176
return nil, xerrors.Errorf("toml decode error: %w", err)
177177
}
178178

179-
dependencies := tomlFile.Dependencies
179+
// There are cases when toml file doesn't include `Dependencies` field (then map will be nil).
180+
// e.g. when only `workspace.Dependencies` are used
181+
// declare `dependencies` to avoid panic
182+
dependencies := Dependencies{}
183+
maps.Copy(dependencies, tomlFile.Dependencies)
180184

181185
// https://doc.rust-lang.org/cargo/reference/specifying-dependencies.html#platform-specific-dependencies
182186
for _, target := range tomlFile.Target {
@@ -186,7 +190,7 @@ func (a cargoAnalyzer) parseCargoTOML(fsys fs.FS, path string) (map[string]strin
186190
// https://doc.rust-lang.org/cargo/reference/specifying-dependencies.html#inheriting-a-dependency-from-a-workspace
187191
maps.Copy(dependencies, tomlFile.Workspace["dependencies"])
188192

189-
for name, value := range tomlFile.Dependencies {
193+
for name, value := range dependencies {
190194
switch ver := value.(type) {
191195
case string:
192196
// e.g. regex = "1.5"

pkg/fanal/analyzer/language/rust/cargo/cargo_test.go

+21
Original file line numberDiff line numberDiff line change
@@ -92,6 +92,27 @@ func Test_cargoAnalyzer_Analyze(t *testing.T) {
9292
},
9393
},
9494
},
95+
{
96+
name: "Cargo.toml doesn't include `Dependencies` field",
97+
dir: "testdata/toml-only-workspace-deps",
98+
want: &analyzer.AnalysisResult{
99+
Applications: []types.Application{
100+
{
101+
Type: types.Cargo,
102+
FilePath: "Cargo.lock",
103+
Libraries: []types.Package{
104+
{
105+
106+
Name: "memchr",
107+
Version: "2.5.0",
108+
Indirect: false,
109+
Locations: []types.Location{{StartLine: 11, EndLine: 15}},
110+
},
111+
},
112+
},
113+
},
114+
},
115+
},
95116
{
96117
name: "no Cargo.toml",
97118
dir: "testdata/no-cargo-toml",

pkg/fanal/analyzer/language/rust/cargo/testdata/toml-only-workspace-deps/Cargo.lock

+15
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
[package]
2+
name = "app"
3+
version = "0.1.0"
4+
edition = "2021"
5+
6+
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
7+
8+
[workspace.dependencies]
9+
memchr = "2.5"

0 commit comments

Comments
 (0)