Class: Dependabot::NpmAndYarn::FileUpdater::PackageJsonPreparer

Inherits:
Object
  • Object
show all
Defined in:
lib/dependabot/npm_and_yarn/file_updater/package_json_preparer.rb

Instance Method Summary collapse

Constructor Details

#initialize(package_json_content:) ⇒ PackageJsonPreparer

Returns a new instance of PackageJsonPreparer.



10
11
12
# File 'lib/dependabot/npm_and_yarn/file_updater/package_json_preparer.rb', line 10

def initialize(package_json_content:)
  @package_json_content = package_json_content
end

Instance Method Details

#prepared_contentObject



14
15
16
17
18
19
20
# File 'lib/dependabot/npm_and_yarn/file_updater/package_json_preparer.rb', line 14

def prepared_content
  content = package_json_content
  content = replace_ssh_sources(content)
  content = remove_workspace_path_prefixes(content)
  content = remove_invalid_characters(content)
  content
end

#remove_invalid_characters(content) ⇒ Object



53
54
55
56
57
58
# File 'lib/dependabot/npm_and_yarn/file_updater/package_json_preparer.rb', line 53

def remove_invalid_characters(content)
  content.
    gsub(/\{\{[^\}]*?\}\}/, "something"). # {{ nm }} syntax not allowed
    gsub(/(?<!\\)\\ /, " ").          # escaped whitespace not allowed
    gsub(%r{^\s*//.*}, " ")           # comments are not allowed
end

#remove_workspace_path_prefixes(content) ⇒ Object

A bug prevents Yarn recognising that a directory is part of a workspace if it is specified with a ‘./` prefix.



35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
# File 'lib/dependabot/npm_and_yarn/file_updater/package_json_preparer.rb', line 35

def remove_workspace_path_prefixes(content)
  json = JSON.parse(content)
  return content unless json.key?("workspaces")

  workspace_object = json.fetch("workspaces")
  paths_array =
    if workspace_object.is_a?(Hash)
      workspace_object.values_at("packages", "nohoist").
        flatten.compact
    elsif workspace_object.is_a?(Array) then workspace_object
    else raise "Unexpected workspace object"
    end

  paths_array.each { |path| path.gsub!(%r{^\./}, "") }

  json.to_json
end

#replace_ssh_sources(content) ⇒ Object



22
23
24
25
26
27
28
29
30
31
# File 'lib/dependabot/npm_and_yarn/file_updater/package_json_preparer.rb', line 22

def replace_ssh_sources(content)
  updated_content = content

  git_ssh_requirements_to_swap.each do |req|
    new_req = req.gsub(%r{git\+ssh://git@(.*?)[:/]}, 'https://\1/')
    updated_content = updated_content.gsub(req, new_req)
  end

  updated_content
end

#swapped_ssh_requirementsObject



60
61
62
# File 'lib/dependabot/npm_and_yarn/file_updater/package_json_preparer.rb', line 60

def swapped_ssh_requirements
  git_ssh_requirements_to_swap
end