Skip to content

Commit

Permalink
fix: powershell $PSHOME variable is not expanded
Browse files Browse the repository at this point in the history
  • Loading branch information
cuinixam committed Nov 28, 2024
1 parent ba3813f commit a750b93
Show file tree
Hide file tree
Showing 4 changed files with 31 additions and 8 deletions.
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@ match = "(?!main$)"
prerelease = true

[tool.pytest.ini_options]
addopts = "-v -Wdefault --cov=py_app_dev --cov-report=term-missing:skip-covered"
addopts = "-vv -Wdefault --cov=py_app_dev --cov-report=term-missing:skip-covered -s"
pythonpath = ["src"]

[tool.coverage.run]
Expand Down
14 changes: 8 additions & 6 deletions src/py_app_dev/core/scoop_wrapper.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import json
import os
import re
from concurrent.futures import ThreadPoolExecutor, as_completed
from dataclasses import dataclass, field
Expand Down Expand Up @@ -209,13 +208,16 @@ def do_install_missing(
with TemporaryDirectory() as tmp_dir:
tmp_scoop_file = Path(tmp_dir).joinpath("scoopfile.json")
ScoopInstallConfigFile(scoop_install_config.buckets, apps_to_install).to_file(tmp_scoop_file)
# (!) Make sure powershell core module does not pollute the module path. Without this change scoop.ps1 fails because 'Get-FileHash' cannot be found.
# See more details here: https://github.com/PowerShell/PowerShell/issues/8635
env = os.environ.copy()
env["PSMODULEPATH"] = f"$PSHOME/Modules;{env.get('PSMODULEPATH', '')}"
SubprocessExecutor(["powershell.exe", self.scoop_script, "import", tmp_scoop_file], env=env).execute()
self.run_powershell_command(f"{self.scoop_script} import {tmp_scoop_file}")
return apps_to_install

@staticmethod
def run_powershell_command(command: str, update_ps_module_path: bool = True) -> None:
# (!) Make sure powershell core module does not pollute the module path. Without this change scoop.ps1 fails because 'Get-FileHash' cannot be found.
# See more details here: https://github.com/PowerShell/PowerShell/issues/8635
ps_command = f'$env:PSModulePath=\\"$PSHOME\\Modules;$env:PSMODULEPATH\\"; {command}' if update_ps_module_path else f"{command}"
SubprocessExecutor(["powershell.exe", "-Command", ps_command]).execute()

@staticmethod
def map_required_apps_to_installed_apps(
app_names: List[str],
Expand Down
2 changes: 1 addition & 1 deletion src/py_app_dev/core/subprocess.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ def execute(self) -> None:
self.logger.info(f"Running command: {self.command}")
cwd_path = (self.current_working_directory or Path.cwd()).as_posix()
with subprocess.Popen(
self.command.split(),
self.command,
cwd=cwd_path,
stdout=(subprocess.PIPE if self.capture_output else subprocess.DEVNULL),
stderr=(subprocess.STDOUT if self.capture_output else subprocess.DEVNULL),
Expand Down
21 changes: 21 additions & 0 deletions tests/test_scoop_wrapper.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
import json
import sys
import textwrap
from pathlib import Path
from typing import Optional
from unittest.mock import Mock, patch
Expand Down Expand Up @@ -258,3 +260,22 @@ def test_do_install_missing(scoop_dir: Path) -> None:
assert len(scoop_wrapper.do_install_missing(scoop_install_config, [app1, app2])) == 0
assert len(scoop_wrapper.do_install_missing(scoop_install_config, [app1])) == 1
assert len(scoop_wrapper.do_install_missing(scoop_install_config, [app3])) == 2


@pytest.mark.skipif(sys.platform != "win32", reason="It requires powershell.")
def test_scoop_powershell_execution(tmp_path: Path) -> None:
# Create a temporary powershell file to use Get-FileHash.
ps_file = tmp_path / "test.ps1"
ps_file.write_text(
textwrap.dedent("""\
Write-Host "PSHOME: $PSHOME"
Write-Host "PSModulePath: $env:PSModulePath"
# Get the hash of the script itself
$hash = Get-FileHash -Path $MyInvocation.MyCommand.Path -Algorithm SHA256
Write-Host $hash.Hash
# Write hash to a file in the same directory
$hash | ConvertTo-Json | Set-Content -Path $PSCommandPath.Replace(".ps1", ".hash")
""")
)
ScoopWrapper.run_powershell_command(f"{ps_file.absolute()}", update_ps_module_path=True)
assert (tmp_path / "test.hash").exists()

0 comments on commit a750b93

Please sign in to comment.