Skip to content

Instantly share code, notes, and snippets.

@sommmen
Last active March 15, 2024 15:06
Show Gist options
  • Save sommmen/84343f9546540f68174315c391aed081 to your computer and use it in GitHub Desktop.
Save sommmen/84343f9546540f68174315c391aed081 to your computer and use it in GitHub Desktop.
Add nullable disable to all .cs files
# When enabling nullability globally withing a csproj file, you could get a lot of erros.
# This adds #nullable disable to all files so you may manually fix them.
# Just do a global search for '#nullable disable' in your IDE, remove the line and fix warnings and errors (EF core).
# TODO BUG this could change the file encoding of the file, UTF80 -> win1252 in my case.
[string] $directoryPath = ...
[switch] $dryRun = $true;
# Ensure the directory exists
if (-not (Test-Path -Path $directoryPath -PathType Container)) {
Write-Host "Directory does not exist: $directoryPath"
exit
}
# Define a log file to record actions
$logFile = Join-Path -Path $directoryPath -ChildPath "NullableCheckLog.txt"
if (-not $dryRun) {
# Clear log file at the beginning of the operation if not in dry run
Clear-Content -Path $logFile
}
# Iterate all files in the given directory
Get-ChildItem -Path $directoryPath -File -Recurse -Include '*.cs' -Exclude 'bin\*, obj\*' | ForEach-Object {
$file = $_
$content = Get-Content -Path $file.FullName -Raw
# Check if the string '#nullable enable' exists in the file
if ($content -notmatch '#nullable enable') {
$actionLog = "Adding '#nullable disable' to the top of the file: $($file.FullName)"
if ($dryRun) {
# Log action to console in dry run mode
Write-Host "DRY RUN - $actionLog"
} else {
# Log action to file
Add-Content -Path $logFile -Value $actionLog
# Add '#nullable disable' at the top of the file
$content = '#nullable disable' + [Environment]::NewLine + $content
Set-Content -Path $file.FullName -Value $content
}
} else {
$actionLog = "'#nullable enable' already present in the file: $($file.FullName)"
# Log this action only if not in dry run, as no changes are made
if (-not $dryRun) {
Add-Content -Path $logFile -Value $actionLog
}
}
}
Write-Host "Operation completed. Check the log file at $logFile for details."
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment