Skip to content

Commit

Permalink
fix(rust): fix panic when 'dependencies' field is not used in cargo.t…
Browse files Browse the repository at this point in the history
…oml (#3997)
  • Loading branch information
DmitriyLewen authored Apr 9, 2023
1 parent c8283ce commit a119ef8
Show file tree
Hide file tree
Showing 4 changed files with 51 additions and 2 deletions.
8 changes: 6 additions & 2 deletions pkg/fanal/analyzer/language/rust/cargo/cargo.go
Original file line number Diff line number Diff line change
Expand Up @@ -176,7 +176,11 @@ func (a cargoAnalyzer) parseCargoTOML(fsys fs.FS, path string) (map[string]strin
return nil, xerrors.Errorf("toml decode error: %w", err)
}

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

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

for name, value := range tomlFile.Dependencies {
for name, value := range dependencies {
switch ver := value.(type) {
case string:
// e.g. regex = "1.5"
Expand Down
21 changes: 21 additions & 0 deletions pkg/fanal/analyzer/language/rust/cargo/cargo_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -92,6 +92,27 @@ func Test_cargoAnalyzer_Analyze(t *testing.T) {
},
},
},
{
name: "Cargo.toml doesn't include `Dependencies` field",
dir: "testdata/toml-only-workspace-deps",
want: &analyzer.AnalysisResult{
Applications: []types.Application{
{
Type: types.Cargo,
FilePath: "Cargo.lock",
Libraries: []types.Package{
{
ID: "[email protected]",
Name: "memchr",
Version: "2.5.0",
Indirect: false,
Locations: []types.Location{{StartLine: 11, EndLine: 15}},
},
},
},
},
},
},
{
name: "no Cargo.toml",
dir: "testdata/no-cargo-toml",
Expand Down

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
[package]
name = "app"
version = "0.1.0"
edition = "2021"

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[workspace.dependencies]
memchr = "2.5"

0 comments on commit a119ef8

Please sign in to comment.