From 36dfd7c87bdb76771f3f56bfe5d9c13f983ff07c Mon Sep 17 00:00:00 2001 From: Jurre Stender Date: Thu, 24 Feb 2022 17:05:08 +0100 Subject: [PATCH] Respect package.json indentation when updating the lockfile --- .../file_updater/npm_lockfile_updater.rb | 17 +++++++++++-- .../package.json | 24 +++++++++---------- 2 files changed, 27 insertions(+), 14 deletions(-) diff --git a/npm_and_yarn/lib/dependabot/npm_and_yarn/file_updater/npm_lockfile_updater.rb b/npm_and_yarn/lib/dependabot/npm_and_yarn/file_updater/npm_lockfile_updater.rb index 91d13a8db8..68a7ce4c4e 100644 --- a/npm_and_yarn/lib/dependabot/npm_and_yarn/file_updater/npm_lockfile_updater.rb +++ b/npm_and_yarn/lib/dependabot/npm_and_yarn/file_updater/npm_lockfile_updater.rb @@ -476,6 +476,7 @@ def write_temporary_dependency_files(update_package_json: true) updated_content = lock_deps_with_latest_reqs(updated_content) updated_content = sanitized_package_json_content(updated_content) + File.write(file.name, updated_content) end end @@ -495,6 +496,16 @@ def write_lockfiles end end + # Takes a JSON string and detects if it is spaces or tabs and how many + # levels deep it is indented. + def detect_indentation(json) + indentation = json.scan(/^\s+/).min_by(&:length) + indentation_size = indentation.length + indentation_type = indentation.scan(/\t/).any? ? "\t" : " " + + indentation_type * indentation_size + end + def lock_git_deps(content) return content if git_dependencies_to_lock.empty? @@ -508,7 +519,8 @@ def lock_git_deps(content) end end - json.to_json + indent = detect_indentation(content) + JSON.pretty_generate(json, indent: indent) end def git_dependencies_to_lock @@ -549,7 +561,8 @@ def lock_deps_with_latest_reqs(content) end end - json.to_json + indent = detect_indentation(content) + JSON.pretty_generate(json, indent: indent) end def replace_ssh_sources(content) diff --git a/npm_and_yarn/spec/fixtures/projects/npm7/subdependency_update_tab_indentation/package.json b/npm_and_yarn/spec/fixtures/projects/npm7/subdependency_update_tab_indentation/package.json index b6c36e22ad..dc507bd4ce 100644 --- a/npm_and_yarn/spec/fixtures/projects/npm7/subdependency_update_tab_indentation/package.json +++ b/npm_and_yarn/spec/fixtures/projects/npm7/subdependency_update_tab_indentation/package.json @@ -1,14 +1,14 @@ { - "name": "npm-sub-dep-test", - "version": "1.0.0", - "description": "", - "main": "index.js", - "scripts": { - "test": "echo \"Error: no test specified\" && exit 1" - }, - "author": "", - "license": "ISC", - "dependencies": { - "test-old-npm-sub-dependency": "github:dependabot-fixtures/test-old-npm-sub-dependency" - } + "name": "npm-sub-dep-test", + "version": "1.0.0", + "description": "", + "main": "index.js", + "scripts": { + "test": "echo \"Error: no test specified\" && exit 1" + }, + "author": "", + "license": "ISC", + "dependencies": { + "test-old-npm-sub-dependency": "github:dependabot-fixtures/test-old-npm-sub-dependency" + } }