Skip to content

WinClean v2.21

Choose a tag to compare

@bivlked bivlked released this 22 Jul 21:38
· 27 commits to main since this release
126d6f9

WinClean v2.21

A release about telling the truth on the way out. The self-update could change a file other than the one being run and still print "Update complete", and the exit code called a perfectly good maintenance run a failure whenever the machine simply lacked an optional tool or a network.

Раунд про честность на выходе. Авто-обновление могло изменить не тот файл, который выполняется, и всё равно напечатать "Update complete", а код возврата объявлял провалом вполне успешный прогон обслуживания всякий раз, когда на машине просто не было необязательного инструмента или сети.

The self-update updated the wrong file / Авто-обновление меняло не тот файл

The check asked whether a Gallery copy existed anywhere on the machine, and the answer was used as if it had been "is the file I am running that copy". Both are routinely true at once: install.ps1 installs into %ProgramFiles%\WinClean, which is what the desktop shortcut starts, while an older Install-Script copy can still sit in Documents. Update-Script updated the copy in Documents, printed "Update complete! Please run WinClean again to use the new version", and exited 0 - and the shortcut kept starting the untouched old file. Forever, with no error anywhere.

The running file is now compared against the Gallery install location, and a self-update is offered only when they are the same file. Every other copy is told the method that actually applies to it. The advice shown to those copies used to be Install-Script, which installs a second copy - it built the very state that made the update target the wrong file.

Проверка спрашивала, есть ли копия из галереи где-нибудь на машине, а ответ использовался так, будто это ответ на вопрос "является ли выполняемый файл той самой копией". Оба условия штатно истинны одновременно: install.ps1 ставит копию в %ProgramFiles%\WinClean, куда смотрит ярлык, а старая копия из Install-Script остаётся в Documents. Update-Script обновлял копию в Documents, печатал "Update complete! Please run WinClean again", выходил с кодом 0 - и ярлык продолжал запускать нетронутый старый файл. Бесконечно, без единой ошибки.

Теперь выполняемый файл сравнивается с местом установки из галереи, и авто-обновление предлагается только когда это один и тот же файл. Остальным называется способ, который к ним реально применим. Прежний совет для таких копий предлагал Install-Script, который создаёт вторую установку - то есть сам строил конфигурацию, породившую дефект.

Also in this area / Там же:

  • Several Gallery installations disable the automatic update instead of changing one at random. Update-Script has no -Scope, so nothing directs it at the copy being executed; WinClean now says so and prints the path it is running from, so the installations can be told apart.

  • Both package providers are supported end to end. Every step used to be PowerShellGet (Find-Script, Update-Script), so on a machine carrying only PSResourceGet the check failed, the failure was read as "no update available", and the whole path was dead. Discovery, the update and the printed advice now each use whichever provider is present - and the one that answered discovery is preferred, so a broken provider is not chosen again. An AllUsers install is no longer invisible.

  • An update that reports success is verified against the version of the file on disk. A provider that changes nothing is reported instead of being announced as complete.

  • Несколько установок из галереи отключают авто-обновление вместо изменения случайной копии. У Update-Script нет -Scope, поэтому нацелить его на выполняемую копию нечем; WinClean говорит об этом прямо и печатает путь, из которого запущен, чтобы копии можно было различить.

  • Оба провайдера пакетов поддержаны сквозь весь путь. Раньше каждый шаг был PowerShellGet (Find-Script, Update-Script), поэтому на машине только с PSResourceGet проверка падала, отказ читался как "обновлений нет", и вся ветка не работала. Теперь обнаружение, обновление и печатаемый совет используют тот провайдер, который есть, причём предпочтение отдаётся ответившему - чтобы сломанный не выбирался снова. Установка AllUsers больше не невидима.

  • Обновление, сообщившее об успехе, проверяется по версии файла на диске. Провайдер, ничего не изменивший, теперь об этом сообщает, а не объявляется завершившим работу.

Honest exit codes / Честный код возврата

The exit code is computed from the error count alone. Three things were counted as errors that are not failures of the run:

  • a missing winget - a machine without App Installer ended every run with code 1 while all nine phases completed;
  • no internet connection - a laptop doing maintenance away from the network reported failure on every run;
  • a failed self-update - it logged an error and still exited 0, which is a contradiction in the one place that has to be believable.

All three are warnings now. A winget that is present and then fails is still an error, and so is a PowerShell Gallery blocked while the network works: an absent precondition and an attempted operation that failed are different things, and the exit code distinguishes them.

Код возврата считается только по количеству ошибок. Три вещи считались ошибками, не будучи отказом прогона:

  • отсутствие winget - машина без App Installer завершала каждый прогон с кодом 1 при девяти выполненных фазах;
  • отсутствие интернета - ноутбук, обслуживаемый вне сети, рапортовал провал на каждом запуске;
  • неудача авто-обновления - писала ошибку в лог и всё равно выходила с кодом 0, а это противоречие ровно там, где нужна достоверность.

Все три стали предупреждениями. winget, который есть и не отработал, по-прежнему ошибка, как и PowerShell Gallery, заблокированная при рабочей сети: отсутствующая предпосылка и неудавшаяся операция - разные вещи, и код возврата их различает.

Result JSON

  • AppUpdatesStatus - checked, check-failed, skipped-no-winget, skipped-offline, skipped-parameter or not-run. AppUpdatesOffered: 0 alone cannot say whether winget was asked; demoting a missing winget to a warning removed the only other signal, so this one replaces it.

  • Aborted gains UpdatedAndExited. The self-update path exits before the run's normal end, so it now writes the result file first - previously a consumer saw exit code 0 and no artefact at all.

  • AppUpdatesStatus - checked, check-failed, skipped-no-winget, skipped-offline, skipped-parameter или not-run. Само по себе AppUpdatesOffered: 0 не говорит, спрашивали ли winget; понижение отсутствующего winget до предупреждения убрало единственный оставшийся признак, и это поле его заменяет.

  • Aborted получает значение UpdatedAndExited. Путь авто-обновления завершает процесс до обычного конца прогона, поэтому теперь сначала пишет файл результата - раньше потребитель видел код 0 и полное отсутствие артефакта.

Under the hood / Под капотом

452 to 573 automated tests. Twenty-one mutations were run against the new guards, and every one of them failed a test. This change set went through sixteen rounds of external review plus four specialised review agents; the agents found defects ten rounds of review had missed - including one introduced by an earlier fix in this same release, where swallowing a provider error made "the Gallery could not be asked" indistinguishable from "you are up to date".

452 -> 573 автоматических теста. Против новых защит прогнана 21 мутация, и каждая была поймана тестом. Изменения прошли шестнадцать раундов внешнего ревью плюс четыре специализированных агента; агенты нашли дефекты, которые десять раундов ревью пропустили - включая внесённый более ранним исправлением этого же релиза, где проглоченная ошибка провайдера сделала "не смогли спросить галерею" неотличимым от "у вас последняя версия".

Install / Установка

# Run once / Разовый запуск
irm https://raw.githubusercontent.com/bivlked/WinClean/main/get.ps1 | iex

# Install with a desktop shortcut / Установка с ярлыком
irm https://raw.githubusercontent.com/bivlked/WinClean/main/install.ps1 | iex

# PowerShell Gallery
Install-PSResource WinClean

Both bootstrap scripts verify the SHA256 of the release asset and refuse to run on a mismatch.

Оба bootstrap-скрипта сверяют SHA256 ассета релиза и отказываются запускаться при расхождении.