Class: Bibliothecary::Parsers::Maven

Inherits:
Object
  • Object
show all
Includes:
Analyser
Defined in:
lib/bibliothecary/parsers/maven.rb

Constant Summary collapse

GRADLE_TYPE_REGEX =

e.g. “annotationProcessor - Annotation processors and their dependencies for source set ‘main’.”

/^(\w+)/
GRADLE_DEP_REGEX =

“| \— com.google.guava:guava:23.5-jre (*)”

/(\+---|\\---){1}/
GRADLE_DEPENDENCY_METHODS =
%w(api compile compileClasspath compileOnly compileOnlyApi implementation runtime runtimeClasspath runtimeOnly testCompile testCompileOnly testImplementation testRuntime testRuntimeOnly)
GRADLE_VERSION_REGEX =

Intentionally overly-simplified regexes to scrape deps from build.gradle (Groovy) and build.gradle.kts (Kotlin) files. To be truly useful bibliothecary would need full Groovy / Kotlin parsers that speaks Gradle, because the Groovy and Kotlin DSLs have many dynamic ways of declaring dependencies.

/[\w.-]+/
GRADLE_VAR_INTERPOLATION_REGEX =

e.g. ‘$myVersion’

/\$\w+/
GRADLE_CODE_INTERPOLATION_REGEX =

e.g. ‘$"version"’

/\$\{.*\}/
GRADLE_GAV_REGEX =

e.g. “group:artifactId:1.2.3”

/([\w.-]+)\:([\w.-]+)(?:\:(#{GRADLE_VERSION_REGEX}|#{GRADLE_VAR_INTERPOLATION_REGEX}|#{GRADLE_CODE_INTERPOLATION_REGEX}))?/
GRADLE_GROOVY_SIMPLE_REGEX =
/(#{GRADLE_DEPENDENCY_METHODS.join('|')})\s*\(?\s*['"]#{GRADLE_GAV_REGEX}['"]/m
GRADLE_KOTLIN_SIMPLE_REGEX =
/(#{GRADLE_DEPENDENCY_METHODS.join('|')})\s*\(\s*"#{GRADLE_GAV_REGEX}"/m
MAVEN_PROPERTY_REGEX =
/\$\{(.+?)\}/
MAX_DEPTH =
5
SBT_TYPE_REGEX =

e.g. “[info] test:”

/^\[info\]\s+([-\w]+):$/
SBT_DEP_REGEX =

e.g. “[info] org.typelevel:spire-util_2.12”

/^\[info\]\s+(.+)$/
SBT_VERSION_REGEX =

e.g. “[info] - 1.7.5”

/^\[info\]\s+-\s+(.+)$/
SBT_FIELD_REGEX =

e.g. “[info] homepage: www.slf4j.org

/^\[info\]\s+([^:]+):\s+(.+)$/
SBT_IGNORE_REGEX =

e.g. “[info] ”

/^\[info\]\s*$/

Class Method Summary collapse

Methods included from Analyser

create_analysis, create_error_analysis, included

Class Method Details

.extract_pom_dep_info(xml, dependency, name, parent_properties = {}) ⇒ Object



295
296
297
298
299
300
301
302
303
304
305
306
307
# File 'lib/bibliothecary/parsers/maven.rb', line 295

def self.extract_pom_dep_info(xml, dependency, name, parent_properties = {})
  field = dependency.locate(name).first
  return nil if field.nil?

  value = field.nodes.first
  value = value.value if value.is_a?(Ox::CData)
  match = value&.match(MAVEN_PROPERTY_REGEX)
  if match
    return extract_property(xml, match[1], value, parent_properties)
  else
    return value
  end
end

.extract_pom_info(xml, location, parent_properties = {}) ⇒ Object



291
292
293
# File 'lib/bibliothecary/parsers/maven.rb', line 291

def self.extract_pom_info(xml, location, parent_properties = {})
  extract_pom_dep_info(xml, xml, location, parent_properties)
end

.extract_property(xml, property_name, value, parent_properties = {}, depth = 0) ⇒ Object



313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
# File 'lib/bibliothecary/parsers/maven.rb', line 313

def self.extract_property(xml, property_name, value, parent_properties = {}, depth = 0)
  prop_value = property_value(xml, property_name, parent_properties)
  return value unless prop_value
  # don't resolve more than 5 levels deep to avoid potential circular references

  resolved_value = replace_value_with_prop(value, prop_value, property_name)
  # check to see if we just resolved to another property name
  match = resolved_value.match(MAVEN_PROPERTY_REGEX)
  if match && depth < MAX_DEPTH
    depth += 1
    return extract_property(xml, match[1], resolved_value, parent_properties, depth)
  else
    return resolved_value
  end
end

.gradle_dependency_name(group, name) ⇒ Object



277
278
279
280
281
282
283
284
285
286
287
288
289
# File 'lib/bibliothecary/parsers/maven.rb', line 277

def self.gradle_dependency_name(group, name)
  if group.empty? && name.include?(":")
    group, name = name.split(":", 2)
  end

  # Strip comments, and single/doublequotes
  [group, name].map do |part|
    part
      .gsub(/\s*\/\/.*$/, "") # Comments
      .gsub(/^["']/, "") # Beginning single/doublequotes
      .gsub(/["']$/, "") # Ending single/doublequotes
  end.join(":")
end

.ivy_report?(file_contents) ⇒ Boolean

Returns:

  • (Boolean)


104
105
106
107
108
109
110
111
112
113
# File 'lib/bibliothecary/parsers/maven.rb', line 104

def self.ivy_report?(file_contents)
  doc = Ox.parse file_contents
  root = doc&.locate("ivy-report")&.first
  return !root.nil?
rescue Exception # rubocop:disable Lint/RescueException
  # We rescue exception here since native libs can throw a non-StandardError
  # We don't want to throw errors during the matching phase, only during
  # parsing after we match.
  false
end

.mappingObject



47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
# File 'lib/bibliothecary/parsers/maven.rb', line 47

def self.mapping
  {
    match_filename("ivy.xml", case_insensitive: true) => {
      kind: 'manifest',
      parser: :parse_ivy_manifest
    },
    match_filename("pom.xml", case_insensitive: true) => {
      kind: 'manifest',
      parser: :parse_standalone_pom_manifest
    },
    match_filename("build.gradle", case_insensitive: true) => {
      kind: 'manifest',
      parser: :parse_gradle
    },
    match_filename("build.gradle.kts", case_insensitive: true) => {
      kind: 'manifest',
      parser: :parse_gradle_kts
    },
    match_extension(".xml", case_insensitive: true) => {
      content_matcher: :ivy_report?,
      kind: 'lockfile',
      parser: :parse_ivy_report
    },
    match_filename("gradle-dependencies-q.txt", case_insensitive: true) => {
      kind: 'lockfile',
      parser: :parse_gradle_resolved
    },
    match_filename("maven-resolved-dependencies.txt", case_insensitive: true) => {
      kind: 'lockfile',
      parser: :parse_maven_resolved
    },
    match_filename("sbt-update-full.txt", case_insensitive: true) => {
      kind: 'lockfile',
      parser: :parse_sbt_update_full
    },
    match_filename("maven-dependency-tree.txt", case_insensitive: true) => {
      kind: 'lockfile',
      parser: :parse_maven_tree
    }
  }
end

.parse_gradle(file_contents, options: {}) ⇒ Object



251
252
253
254
255
256
257
258
259
260
261
262
# File 'lib/bibliothecary/parsers/maven.rb', line 251

def self.parse_gradle(file_contents, options: {})
  file_contents
  .scan(GRADLE_GROOVY_SIMPLE_REGEX)                                                # match 'implementation "group:artifactId:version"'
  .reject { |(_type, group, artifactId, _version)| group.nil? || artifactId.nil? } # remove any matches with missing group/artifactId
  .map { |(type, group, artifactId, version)|
    {
      name: [group, artifactId].join(":"),
      requirement: version || "*",
      type: type
    }
  }
end

.parse_gradle_kts(file_contents, options: {}) ⇒ Object



264
265
266
267
268
269
270
271
272
273
274
275
# File 'lib/bibliothecary/parsers/maven.rb', line 264

def self.parse_gradle_kts(file_contents, options: {})
  file_contents
    .scan(GRADLE_KOTLIN_SIMPLE_REGEX)                                                # match 'implementation("group:artifactId:version")'
    .reject { |(_type, group, artifactId, _version)| group.nil? || artifactId.nil? } # remove any matches with missing group/artifactId
    .map { |(type, group, artifactId, version)|
      {
        name: [group, artifactId].join(":"),
        requirement: version || "*",
        type: type
      }
    }
end

.parse_gradle_resolved(file_contents, options: {}) ⇒ Object



140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
# File 'lib/bibliothecary/parsers/maven.rb', line 140

def self.parse_gradle_resolved(file_contents, options: {})
  type = nil
  file_contents.split("\n").map do |line|
    type_match = GRADLE_TYPE_REGEX.match(line)
    type = type_match.captures[0] if type_match

    gradle_dep_match = GRADLE_DEP_REGEX.match(line)
    next unless gradle_dep_match

    split = gradle_dep_match.captures[0]

    dep = line
      .split(split)[1].sub(/(\((c|n|\*)\))$/, "") # line ending legend: (c) means a dependency constraint, (n) means not resolved, or (*) means resolved previously, e.g. org.springframework.boot:spring-boot-starter-web:2.1.0.M3 (*)
      .sub(/ FAILED$/, "") # dependency could not be resolved (but still may have a version)
      .sub(" -> ", ":") # handle version arrow syntax
      .strip.split(":")

    # A testImplementation line can look like this so just skip those
    # \--- org.springframework.security:spring-security-test (n)
    next unless dep.length >= 3

    if dep.count == 6
      # get name from renamed package resolution "org:name:version -> renamed_org:name:version"
      {
        original_name: dep[0,2].join(":"),
        original_requirement: dep[2],
        name: dep[-3..-2].join(":"),
        requirement: dep[-1],
        type: type
      }
    else
      # get name from version conflict resolution ("org:name:version -> version") and no-resolution ("org:name:version")
      {
        name: dep[0..1].join(":"),
        requirement: dep[-1],
        type: type
      }
    end
  end
    .compact
    # Prefer duplicate deps with the aliased ones first, so we don't lose the aliases in the next uniq step.
    .sort_by { |dep| dep.key?(:original_name) || dep.key?(:original_requirement) ? 0 : 1 }
    .uniq { |item| [item[:name], item[:requirement], item[:type]] }
end

.parse_ivy_manifest(file_contents, options: {}) ⇒ Object



92
93
94
95
96
97
98
99
100
101
102
# File 'lib/bibliothecary/parsers/maven.rb', line 92

def self.parse_ivy_manifest(file_contents, options: {})
  manifest = Ox.parse file_contents
  manifest.dependencies.locate('dependency').map do |dependency|
    attrs = dependency.attributes
    {
      name: "#{attrs[:org]}:#{attrs[:name]}",
      requirement: attrs[:rev],
      type: 'runtime'
    }
  end
end

.parse_ivy_report(file_contents, options: {}) ⇒ Object



115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
# File 'lib/bibliothecary/parsers/maven.rb', line 115

def self.parse_ivy_report(file_contents, options: {})
  doc = Ox.parse file_contents
  root = doc.locate("ivy-report").first
  raise "ivy-report document does not have ivy-report at the root" if root.nil?
  info = doc.locate("ivy-report/info").first
  raise "ivy-report document lacks <info> element" if info.nil?
  type = info.attributes[:conf]
  type = "unknown" if type.nil?
  modules = doc.locate("ivy-report/dependencies/module")
  modules.map do |mod|
    attrs = mod.attributes
    org = attrs[:organisation]
    name = attrs[:name]
    version = mod.locate('revision').first&.attributes[:name]

    next nil if org.nil? or name.nil? or version.nil?

    {
      name: "#{org}:#{name}",
      requirement: version,
      type: type
    }
  end.compact
end

.parse_maven_resolved(file_contents, options: {}) ⇒ Object



185
186
187
188
189
190
191
# File 'lib/bibliothecary/parsers/maven.rb', line 185

def self.parse_maven_resolved(file_contents, options: {})
  Strings::ANSI.sanitize(file_contents)
    .split("\n")
    .map(&method(:parse_resolved_dep_line))
    .compact
    .uniq
end

.parse_maven_tree(file_contents, options: {}) ⇒ Object



193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
# File 'lib/bibliothecary/parsers/maven.rb', line 193

def self.parse_maven_tree(file_contents, options: {})
  file_contents = file_contents.gsub(/\r\n?/, "\n")
  captures = file_contents.scan(/^\[INFO\](?:(?:\+-)|\||(?:\\-)|\s)+((?:[\w\.-]+:)+[\w\.\-${}]+)/).flatten.uniq

  deps = captures.map do |item|
    parts = item.split(":")
    case parts.count
    when 4
      version = parts[-1]
      type = parts[-2]
    when 5..6
      version, type = parts[-2..]
    end
    {
      name: parts[0..1].join(":"),
      requirement: version,
      type: type
    }
  end

  # First dep line will be the package itself (unless we're only analyzing a single line)
  package = deps[0]
  deps.size < 2 ? deps : deps[1..-1].reject { |d| d[:name] == package[:name] && d[:requirement] == package[:requirement] }
end

.parse_pom_manifest(file_contents, parent_properties = {}, options: {}) ⇒ Object



235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
# File 'lib/bibliothecary/parsers/maven.rb', line 235

def self.parse_pom_manifest(file_contents, parent_properties = {}, options: {})
  manifest = Ox.parse file_contents
  xml = manifest.respond_to?('project') ? manifest.project : manifest
  [].tap do |deps|
    ['dependencies/dependency', 'dependencyManagement/dependencies/dependency'].each do |deps_xpath|
      xml.locate(deps_xpath).each do |dep|
        deps.push({
          name: "#{extract_pom_dep_info(xml, dep, 'groupId', parent_properties)}:#{extract_pom_dep_info(xml, dep, 'artifactId', parent_properties)}",
          requirement: extract_pom_dep_info(xml, dep, 'version', parent_properties),
          type: extract_pom_dep_info(xml, dep, 'scope', parent_properties) || 'runtime'
        })
      end
    end
  end
end

.parse_resolved_dep_line(line) ⇒ Object



218
219
220
221
222
223
224
225
226
227
# File 'lib/bibliothecary/parsers/maven.rb', line 218

def self.parse_resolved_dep_line(line)
  dep_parts = line.strip.split(":")
  return unless dep_parts.length == 5
  # org.springframework.boot:spring-boot-starter-web:jar:2.0.3.RELEASE:compile -- module spring.boot.starter.web [auto]
  {
    name: dep_parts[0, 2].join(":"),
    requirement: dep_parts[3],
    type: dep_parts[4].split("--").first.strip
  }
end

.parse_sbt_deps(type, lines) ⇒ Object



389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
# File 'lib/bibliothecary/parsers/maven.rb', line 389

def self.parse_sbt_deps(type, lines)
  deps = []
  while lines.any? and not SBT_TYPE_REGEX.match(lines[0])
    line = lines.shift

    next if SBT_IGNORE_REGEX.match(line)

    dep_match = SBT_DEP_REGEX.match(line)
    if dep_match
      versions = parse_sbt_versions(type, dep_match.captures[0], lines)
      deps.concat(versions)
    else
      lines.unshift(line)
      break
    end
  end

  deps
end

.parse_sbt_update_full(file_contents, options: {}) ⇒ Object



352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
# File 'lib/bibliothecary/parsers/maven.rb', line 352

def self.parse_sbt_update_full(file_contents, options: {})
  all_deps = []
  type = nil
  lines = file_contents.split("\n")
  while lines.any?
    line = lines.shift

    type_match = SBT_TYPE_REGEX.match(line)
    next unless type_match
    type = type_match.captures[0]

    deps = parse_sbt_deps(type, lines)
    all_deps.concat(deps)
  end

  # strip out evicted dependencies
  all_deps.select! do |dep|
    dep[:fields]["evicted"] != "true"
  end

  # in the future, we could use "callers" in the fields to
  # decide which deps are direct root deps and which are
  # pulled in by another dep.  The direct deps have the sbt
  # project name as a caller.

  # clean out any duplicates (I'm pretty sure sbt will have done this for
  # us so this is paranoia, basically)
  squished = all_deps.compact.uniq {|item| [item[:name], item[:requirement], item[:type]]}

  # get rid of the fields
  squished.each do |dep|
    dep.delete(:fields)
  end

  return squished
end

.parse_sbt_version(type, name, version, lines) ⇒ Object



426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
# File 'lib/bibliothecary/parsers/maven.rb', line 426

def self.parse_sbt_version(type, name, version, lines)
  fields = {}
  while lines.any? and not SBT_TYPE_REGEX.match(lines[0])
    line = lines.shift

    field_match = SBT_FIELD_REGEX.match(line)
    if field_match
      fields[field_match.captures[0]] = field_match.captures[1]
    else
      lines.unshift(line)
      break
    end
  end

  {
    name: name,
    requirement: version,
    type: type,
    # we post-process using some of these fields and then delete them again
    fields: fields
  }
end

.parse_sbt_versions(type, name, lines) ⇒ Object



409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
# File 'lib/bibliothecary/parsers/maven.rb', line 409

def self.parse_sbt_versions(type, name, lines)
  versions = []
  while lines.any? and not SBT_TYPE_REGEX.match(lines[0])
    line = lines.shift

    version_match = SBT_VERSION_REGEX.match(line)
    if version_match
      versions.push(parse_sbt_version(type, name, version_match.captures[0], lines))
    else
      lines.unshift(line)
      break
    end
  end

  versions
end

.parse_standalone_pom_manifest(file_contents, options: {}) ⇒ Object



229
230
231
# File 'lib/bibliothecary/parsers/maven.rb', line 229

def self.parse_standalone_pom_manifest(file_contents, options: {})
  parse_pom_manifest(file_contents, {}, options: options)
end

.property_value(xml, property_name, parent_properties) ⇒ Object



329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
# File 'lib/bibliothecary/parsers/maven.rb', line 329

def self.property_value(xml, property_name, parent_properties)
  # the xml root is <project> so lookup the non property name in the xml
  # this converts ${project/group.id} -> ${group/id}
  non_prop_name = property_name.gsub(".", "/").gsub("project/", "")
  return "${#{property_name}}" if !xml.respond_to?("properties") && parent_properties.empty? && xml.locate(non_prop_name).empty?

  prop_field = xml.properties.locate(property_name).first if xml.respond_to?("properties")
  parent_prop = parent_properties[property_name]
  if prop_field
    prop_field.nodes.first
  elsif parent_prop
    parent_prop
  elsif xml.locate(non_prop_name).first
    # see if the value to look up is a field under the project
    # examples are ${project.groupId} or ${project.version}
    xml.locate(non_prop_name).first.nodes.first
  elsif xml.locate("parent/#{non_prop_name}").first
    # see if the value to look up is a field under the project parent
    # examples are ${project.groupId} or ${project.version}
    xml.locate("parent/#{non_prop_name}").first.nodes.first
  end
end

.replace_value_with_prop(original_value, property_value, property_name) ⇒ Object



309
310
311
# File 'lib/bibliothecary/parsers/maven.rb', line 309

def self.replace_value_with_prop(original_value, property_value, property_name)
  original_value.gsub("${#{property_name}}", property_value)
end