PowerShell / PowerShell/PSScriptAnalyzer

PSUseConsistentIndentation flattens the indentation of commented-out code

未關閉
#2,217 1 則留言 0 個 reaction 已指派 0 人 在 GitHub 檢視

還沒有人認領這個 Issue。

主要語言
C#
星號
2.2k
分支
415
平均合併
13 小時 1 分鐘
30 天內合併 PR
2

描述

Summary

PSUseConsistentIndentation rewrites the whitespace before each comment's #, aligning every comment line in a block to the block indentation. When a run of comments is commented-out code (where the nested structure is expressed by the indentation before #), the rule flattens it, so the structure is lost. Whitespace after the # is preserved, so the two styles behave differently:

# preserved - the extra indentation is after the '#'
	# if ($b) {
	#     doThing
	# }

# flattened - the extra indentation is before the '#'
	# if ($b) {
		# doThing
	# }

Steps to reproduce

Only the one rule is enabled:

$settings = @{
	IncludeRules = @('PSUseConsistentIndentation')
	Rules        = @{
		PSUseConsistentIndentation = @{ Enable = $true; IndentationSize = 4; PipelineIndentation = 'NoIndentation'; Kind = 'tab' }
	}
}

Input:

if ($a) {
	# if ($b) {
		# doThing
	# }
}

Actual (Invoke-Formatter -ScriptDefinition $code -Settings $settings):

if ($a) {
	# if ($b) {
	# doThing
	# }
}

Expected: the commented-out block keeps its relative indentation (at most the whole comment run may be shifted to the code indentation).

The same happens with Kind = 'space' and when there is real code after the comment run.

Environment

  • PSScriptAnalyzer 1.25.0
  • PowerShell 7.6.6 on Windows

Why it matters

Commenting out a block is a common way to keep code around; flattening the indentation makes the commented-out block unreadable. Tooling that encodes directives as comments (e.g. sources that are uncommented by an external preprocessor) also relies on the indentation before # being preserved.

Related: #2151 asks for an ignore-range directive, but this is about the default behaviour of the indentation rule on ordinary comment runs.

貢獻指南

開啟貢獻指南

從這裡開始

  1. 先讀完整個 Issue,再讀專案的貢獻指南。
  2. 在 Issue 下留言說明你要接手 —— 這能避免兩個人做同樣的事。
  3. Fork 儲存庫,在一個分支上完成修改。
  4. 送出 Pull Request,並在描述裡引用這個 Issue 編號。

研究方向

先找到 PSUseConsistentIndentation 規則及其 formatter 測試,然後使用此處顯示的設定和輸入,透過 Invoke-Formatter 重現問題。為使用定位字元和空格縮排的巢狀註解程式碼新增涵蓋測試,並確認 # 前的相對縮排獲得保留,同時不會破壞包含實際程式碼的連續區段。

由索引模型根據 Issue 內容生成。

評估

技術堆疊
csharp, powershell
領域
tooling
Issue 類型
缺陷
難度
3/5
預估耗時
1-2 天
活躍度
活躍
描述清晰度
描述清楚
新手友好度
72/100

把新 issue 寄到你的電子郵件信箱

精選適合新手參與的 GitHub issue 摘要。