Preserve Correct Indentation When Uncommenting Lines #873
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
🌈
Problem
When using Thor's
uncomment_lines
method to programmatically uncomment lines in YAML files or similar, the method was found to inaccurately handle the preservation of indentation spaces before the comment hash (#
). Particularly, when uncommenting lines in structured files where indentation is crucial (like YAML files), the original method removed not only the comment hash but also all horizontal whitespace between the hash and the beginning of the content. This behavior led to a disruption in the file's structure and could potentially cause errors when the file was processed or parsed afterward.For example, in a
.github/workflows/ci.yml
file containing commented-out configuration for Redis:Applying
uncomment_lines
with the previous implementation would result in incorrectly formatted YAML due to the removal of spaces before the content, immediately after the comment hash, disrupting the indentation structure crucial for YAML files.Solution
The proposed change corrects the regex pattern used in the
uncomment_lines
method from^(\s*)#[[:blank:]]*(.*#{flag})
to^(\s*)#[[:blank:]]?(.*#{flag})
. This adjustment ensures that:This means that the indentation structure of the uncommented lines remains intact, preserving the file's integrity and adherence to YAML or other structured file formats' syntax requirements.
Impact
This change significantly improves the utility of the
uncomment_lines
method for Rails developers and others using Thor for automation scripts, particularly when working with YAML files for CI/CD pipelines, configurations, etc. It ensures that the uncommented lines blend seamlessly into the document's structure without introducing syntax errors or misinterpretations by parsers.