File tree Expand file tree Collapse file tree 2 files changed +49
-1
lines changed
pkg/dependency/parser/nodejs/npm Expand file tree Collapse file tree 2 files changed +49
-1
lines changed Original file line number Diff line number Diff line change @@ -345,7 +345,15 @@ func (p *Parser) pkgNameFromPath(pkgPath string) string {
345345 // node_modules/function1
346346 // node_modules/nested_func/node_modules/debug
347347 if index := strings .LastIndex (pkgPath , nodeModulesDir ); index != - 1 {
348- return pkgPath [index + len (nodeModulesDir )+ 1 :]
348+ pkgName := pkgPath [index + len (nodeModulesDir ):]
349+ pkgName = strings .TrimPrefix (pkgName , "/" )
350+
351+ if pkgName == "" {
352+ p .logger .Warn ("Invalid package-lock.json file. Package path doesn't have package name suffix" , log .String ("pkg_path" , pkgPath ))
353+ return ""
354+ }
355+
356+ return pkgName
349357 }
350358 p .logger .Warn ("Package path doesn't have `node_modules` prefix" , log .String ("pkg_path" , pkgPath ))
351359 return pkgPath
Original file line number Diff line number Diff line change @@ -88,3 +88,43 @@ func TestParse(t *testing.T) {
8888 })
8989 }
9090}
91+
92+ func TestPkgNameFromPath (t * testing.T ) {
93+ tests := []struct {
94+ path string
95+ expected string
96+ }{
97+ {
98+ path : "node_modules/package-name" ,
99+ expected : "package-name" ,
100+ },
101+ {
102+ path : "node_modules/@package-namespace/package-name" ,
103+ expected : "@package-namespace/package-name" ,
104+ },
105+ {
106+ path : "node_modules/package-name/node_modules/sub-sub-package" ,
107+ expected : "sub-sub-package" ,
108+ },
109+ {
110+ path : "no/node/modules/dir" ,
111+ expected : "no/node/modules/dir" ,
112+ },
113+ {
114+ path : "node_modules" ,
115+ expected : "" ,
116+ },
117+ {
118+ path : "node_modules/" ,
119+ expected : "" ,
120+ },
121+ }
122+
123+ parser := NewParser ()
124+ for _ , test := range tests {
125+ t .Run (test .path , func (t * testing.T ) {
126+ path := parser .pkgNameFromPath (test .path )
127+ assert .Equal (t , test .expected , path )
128+ })
129+ }
130+ }
You can’t perform that action at this time.
0 commit comments