rails / thor

Thor is a toolkit for building powerful command-line interfaces.
http://whatisthor.com/
MIT License
5.11k stars 552 forks source link

Preserve Correct Indentation When Uncommenting Lines #873

Closed viktorianer closed 4 months ago

viktorianer commented 4 months ago

🌈

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:

# redis:
#   image: redis
#   ports:
#     - 6379:6379
#   options: --health-cmd "redis-cli ping" --health-interval 10s --health-timeout 5s --health-retries 5

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.