fix(rust): fix panic when 'dependencies' field is not used in cargo.toml (#3997)

This commit is contained in:
DmitriyLewen
2023-04-09 14:06:57 +06:00
committed by GitHub
parent c8283cebde
commit a119ef86ea
4 changed files with 51 additions and 2 deletions

View File

@@ -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 {
@@ -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"

View File

@@ -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: "memchr@2.5.0",
Name: "memchr",
Version: "2.5.0",
Indirect: false,
Locations: []types.Location{{StartLine: 11, EndLine: 15}},
},
},
},
},
},
},
{
name: "no Cargo.toml",
dir: "testdata/no-cargo-toml",

View File

@@ -0,0 +1,15 @@
# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
[[package]]
name = "app"
version = "0.1.0"
dependencies = [
"memchr 2.5.0 (registry+https://github.com/rust-lang/crates.io-index)",
]
[[package]]
name = "memchr"
version = "2.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2dffe52ecf27772e601905b7522cb4ef790d2cc203488bbd0e2fe85fcb74566d"

View File

@@ -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"