Skip to content

Commit

Permalink
Get-PSModulePath: Throw exception on missing My Documents folder (#125
Browse files Browse the repository at this point in the history
)
  • Loading branch information
johlju authored Jul 20, 2024
1 parent 1c5763d commit f081589
Show file tree
Hide file tree
Showing 6 changed files with 126 additions and 2 deletions.
13 changes: 12 additions & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,17 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

## [Unreleased]

### Added

- Public command:
- `Get-UserName` - get current user name cross platform.

### Fixed

- `Get-PSModulePath`
- Throws an exception if the My Documents folder cannot be found when
calling the command with the scope `CurrentUser` ([issue #122](https://github.com/dsccommunity/DscResource.Common/issues/122)).

## [0.17.1] - 2024-04-23

### Added
Expand All @@ -25,7 +36,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- Was using the wrong path separator on Linux and macOS.
- `Get-LocalizedData`
- Wrongly returned one or more boolean values in addition to
the localized string array. This was becuase the return value
the localized string array. This was because the return value
was not handled when calling `Add()` and `Remove()` methods of
`$PSBoundParameters` so it was returned to the pipeline.

Expand Down
13 changes: 13 additions & 0 deletions source/Public/Get-PSModulePath.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -131,6 +131,19 @@ function Get-PSModulePath
{
$documentsFolder = [Environment]::GetFolderPath('MyDocuments')

# When the $documentsFolder is null or empty string the folder does not exist.
if ([System.String]::IsNullOrEmpty($documentsFolder))
{
$PSCmdlet.ThrowTerminatingError(
[System.Management.Automation.ErrorRecord]::new(
($script:localizedData.PSModulePath_MissingMyDocumentsPath -f (Get-UserName)),
'MissingMyDocumentsPath',
[System.Management.Automation.ErrorCategory]::ResourceUnavailable,
(Get-UserName)
)
)
}

if ($IsCoreCLR)
{
Join-Path -Path $documentsFolder -ChildPath 'PowerShell/Modules'
Expand Down
37 changes: 37 additions & 0 deletions source/Public/Get-UserName.ps1
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
<#
.SYNOPSIS
Returns the user name cross-plattform.
.DESCRIPTION
Returns the current user name cross-plattform. The variable `$env:USERNAME`
does not exist cross-platform which hinders development and testing on
macOS and Linux. Instead this command can be used to get the user name
cross-plattform.
.OUTPUTS
System.String
.EXAMPLE
Get-UserName
Returns the user name regardless of platform.
#>
function Get-UserName
{
[CmdletBinding()]
[OutputType([System.String])]
param ()

$userName = $null

if ($IsLinux -or $IsMacOs)
{
$userName = $env:USER
}
else
{
$userName = $env:USERNAME
}

return $userName
}
3 changes: 3 additions & 0 deletions source/en-US/DscResource.Common.strings.psd1
Original file line number Diff line number Diff line change
Expand Up @@ -47,4 +47,7 @@ ConvertFrom-StringData @'
## Find-Certificate
CertificatePathError = Certificate Path '{0}' is not valid. (DRC0046)
SearchingForCertificateUsingFilters = Looking for certificate in Store '{0}' using filter '{1}'. (DRC0047)
## Get-PSModulePath
PSModulePath_MissingMyDocumentsPath = The My Documents folder does not exist for user '{0}'. (DRC0048)
'@
2 changes: 1 addition & 1 deletion tests/Integration/Public/Set-PSModulePath.Tests.ps1
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
BeforeDiscovery {
# Determines if we should skip tests.
if ($isWindows -or $PSEdition -eq 'Desktop')
if ($IsWindows -or $PSEdition -eq 'Desktop')
{
$currentPrincipal = New-Object Security.Principal.WindowsPrincipal([Security.Principal.WindowsIdentity]::GetCurrent())

Expand Down
60 changes: 60 additions & 0 deletions tests/Unit/Public/Get-UserName.Tests.ps1
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseDeclaredVarsMoreThanAssignments', '')]
param ()

BeforeDiscovery {
try
{
if (-not (Get-Module -Name 'DscResource.Test'))
{
# Assumes dependencies has been resolved, so if this module is not available, run 'noop' task.
if (-not (Get-Module -Name 'DscResource.Test' -ListAvailable))
{
# Redirect all streams to $null, except the error stream (stream 2)
& "$PSScriptRoot/../../build.ps1" -Tasks 'noop' 2>&1 4>&1 5>&1 6>&1 > $null
}

# If the dependencies has not been resolved, this will throw an error.
Import-Module -Name 'DscResource.Test' -Force -ErrorAction 'Stop'
}
}
catch [System.IO.FileNotFoundException]
{
throw 'DscResource.Test module dependency not found. Please run ".\build.ps1 -ResolveDependency -Tasks build" first.'
}
}

BeforeAll {
$script:moduleName = 'DscResource.Common'

# Make sure there are not other modules imported that will conflict with mocks.
Get-Module -Name $script:moduleName -All | Remove-Module -Force

# Re-import the module using force to get any code changes between runs.
Import-Module -Name $script:moduleName -Force -ErrorAction 'Stop'

$PSDefaultParameterValues['InModuleScope:ModuleName'] = $script:moduleName
$PSDefaultParameterValues['Mock:ModuleName'] = $script:moduleName
$PSDefaultParameterValues['Should:ModuleName'] = $script:moduleName
}

AfterAll {
$PSDefaultParameterValues.Remove('Mock:ModuleName')
$PSDefaultParameterValues.Remove('InModuleScope:ModuleName')
$PSDefaultParameterValues.Remove('Should:ModuleName')

Remove-Module -Name $script:moduleName
}

Describe 'Get-UserName' {
Context 'When getting user name on Windows' -Skip:($IsLinux -or $IsMacOs) {
It 'Should return the correct user name' {
Get-UserName | Should -Be $env:USERNAME
}
}

Context 'When getting user name' -Skip:($IsWindows -or $PSEdition -eq 'Desktop') {
It 'Should return the correct user name' {
Get-UserName | Should -Be $env:USER
}
}
}

0 comments on commit f081589

Please sign in to comment.