diff --git a/Test/include/Mock_datehelper.ps1 b/Test/include/Mock_datehelper.ps1 new file mode 100644 index 0000000..97948d3 --- /dev/null +++ b/Test/include/Mock_datehelper.ps1 @@ -0,0 +1,17 @@ + +$mockDate = "1975-02-18 00:12:15" +$mockDatetime = [DateTime]::ParseExact($mockDate, 'yyyy-MM-dd HH:mm:ss', $null) +$mockDatetimeUtc = [DateTime]::SpecifyKind($mockDatetime, [DateTimeKind]::Utc) + +function Mock_GetToday{ + + return $mockDatetime + +} + +function MockCall_DateHelper { + + MockCallToObject -command "Get-Date" -OutObject $mockDatetime + MockCallToObject -command "Get-Date -Format 'yyyy-MM-dd'" -OutObject $mockDatetime.ToString("yyyy-MM-dd") + MockCallToObject -command "Get-Date -AsUTC" -OutObject $mockDatetimeUtc +} diff --git a/Test/include/invokeCommand.mock.ps1 b/Test/include/invokeCommand.mock.ps1 index ad8f4c7..6cd8d3a 100644 --- a/Test/include/invokeCommand.mock.ps1 +++ b/Test/include/invokeCommand.mock.ps1 @@ -173,7 +173,7 @@ function Get-MockFileContent{ $filePath = Get-MockFileFullPath -fileName $fileName - $content = Get-Content -Path $filePath | Out-String + $content = (Get-Content -Path $filePath) -join "`n" return $content } Export-ModuleMember -Function Get-MockFileContent diff --git a/Test/include/run_BeforeAfter.ps1 b/Test/include/run_BeforeAfter.ps1 index 2ddb3d1..7968d46 100644 --- a/Test/include/run_BeforeAfter.ps1 +++ b/Test/include/run_BeforeAfter.ps1 @@ -20,6 +20,10 @@ function Run_BeforeEach{ # Write-Verbose "Run_BeforeEach" Disable-IncludeHelperDebug + Reset-InvokeCommandMock + + # Mock get the now date + MockCall_DateHelper } # function Run_AfterEach{ diff --git a/Test/public/addIncludeToWorkspace.test.ps1 b/Test/public/addIncludeToWorkspace.test.ps1 index 5d21023..f11c339 100644 --- a/Test/public/addIncludeToWorkspace.test.ps1 +++ b/Test/public/addIncludeToWorkspace.test.ps1 @@ -82,6 +82,8 @@ function Test_AddIncludeToWorkspace_IfExists{ $moduleName = "TestModule" Import-Module -Name TestingHelper + $header = Build-VersionHeader -Version "1.0.0" -Source "IncludeHelper" + # Test for Include $includefiles = Get-IncludeFile $include1 = $includefiles | Where-Object { $_.FolderName -eq "Helper" } | Select-Object -First 1 @@ -97,18 +99,28 @@ function Test_AddIncludeToWorkspace_IfExists{ #Act $includefiles | Add-IncludeToWorkspace -DestinationModulePath $moduleName -IfExists - #Assert + #Assert check that existing files were updatated $filesDest1 = Get-ChildItem -Path $destFolder1 Assert-Count -Expected 1 -Presented $filesDest1 - $contentFile1 = Get-Content -Path $filesDest1.FullName | Out-String - $sourceFile1 = Get-Content -Path $include1.Path | Out-String - Assert-AreEqual -Expected $sourceFile1.Trim() -Presented $contentFile1.Trim() + $targetFile1 = Get-Content -Path $filesDest1.FullName + $sourceFile1 = (Get-Content -Path $include1.Path) + + # Remove the header as they may be different due to the versioning and date of the file + $targetFile1 = (Remove-VersionHeader -Content $targetFile1) -join "`n" + $sourceFile1 = (Remove-VersionHeader -Content $sourceFile1) -join "`n" + + Assert-AreEqual -Expected $sourceFile1.Trim() -Presented $targetFile1.Trim() $filesDest2 = Get-ChildItem -Path $destFolder2 Assert-Count -Expected 1 -Presented $filesDest2 - $contentFile2 = Get-Content -Path $filesDest2.FullName | Out-String - $sourceFile2 = Get-Content -Path $include2.Path | Out-String - Assert-AreEqual -Expected $sourceFile2.Trim() -Presented $contentFile2.Trim() + $targetFile2 = Get-Content -Path $filesDest2.FullName + $sourceFile2 = $header + (Get-Content -Path $include2.Path) + + # Remove the header as they may be different due to the versioning and date of the file + $targetFile2 = (Remove-VersionHeader -Content $targetFile2) -join "`n" + $sourceFile2 = (Remove-VersionHeader -Content $sourceFile2) -join "`n" + + Assert-AreEqual -Expected $sourceFile2.Trim() -Presented $targetFile2.Trim() } function Test_AddIncludeToWorkspace_PipeParameters{ @@ -134,13 +146,10 @@ function Test_AddIncludeToWorkspace_PipeParameters{ $folderNamePath = get-Modulefolder -FolderName "TestInclude" -ModuleRootPath $destinationModulePath $path = $folderNamePath | Join-Path -ChildPath "config.mock.ps1" Assert-ItemExist -path $path - } function Test_AddIncludeToWorkspace_WithoutSource_WithoutDestination{ - Reset-InvokeCommandMock - Import-Module -Name TestingHelper New-ModuleV3 -Name TestModule @@ -150,7 +159,6 @@ function Test_AddIncludeToWorkspace_WithoutSource_WithoutDestination{ $destinationFilePath = $destinationPath | Join-Path -ChildPath $destinationName Remove-Item -Path $destinationFilePath -ErrorAction SilentlyContinue - # Act Assert-itemNotExist -path $destinationFilePath @@ -164,8 +172,6 @@ function Test_AddIncludeToWorkspace_WithoutSource_WithoutDestination{ function Test_AddIncludeToWorkspace_FromSourceToDestination{ - Reset-InvokeCommandMock - $TargetModuleName = "TargetModule" $SourceModuleName = "SourceModule" @@ -198,8 +204,6 @@ function Test_AddIncludeToWorkspace_FromSourceToDestination{ # With soruce not destination function Test_AddIncludeToWorkspace_FromSourceToDestination_WithoutDestination{ - Reset-InvokeCommandMock - $FileName1 = "MyInclude1.ps1" $FileName2 = "MyInclude2.ps1" diff --git a/Test/public/callAPI.test.ps1 b/Test/public/callAPI.test.ps1 index 64912fe..a667648 100644 --- a/Test/public/callAPI.test.ps1 +++ b/Test/public/callAPI.test.ps1 @@ -1,7 +1,7 @@ function Test_CallAPI_RESTAPI_Withpagination_1{ Assert-SkipTest "This test is not implemented" - Reset-InvokeCommandMock + Enable-InvokeCommandAliasModule # Act @@ -20,7 +20,6 @@ function Test_CallAPI_RESTAPI_Withpagination_2{ Assert-SkipTest "This test is not implemented" - Reset-InvokeCommandMock Enable-InvokeCommandAliasModule # Act @@ -34,7 +33,6 @@ function Test_Call_API_GraphQL{ Assert-SkipTest "This test is not implemented" - Reset-InvokeCommandMock Enable-InvokeCommandAliasModule $query = @' @@ -54,7 +52,6 @@ function Test_Call_API_GraphQL_outfile{ Assert-SkipTest "This test is not implemented" - Reset-InvokeCommandMock Enable-InvokeCommandAliasModule $file = "outfile.json" diff --git a/Test/public/databasev2.test.ps1 b/Test/public/databasev2.test.ps1 index fc81e77..1dc874a 100644 --- a/Test/public/databasev2.test.ps1 +++ b/Test/public/databasev2.test.ps1 @@ -1,7 +1,6 @@ function Test_Database{ - Reset-InvokeCommandMock Mock_Database -ResetDatabase # Load include files needed to test database @@ -47,7 +46,6 @@ function Test_Database{ function Test_Database_JSON{ - Reset-InvokeCommandMock Mock_Database -ResetDatabase # Load include files needed to test database @@ -93,7 +91,6 @@ function Test_Database_JSON{ function Test_Database_JSON_ComplexObject{ - Reset-InvokeCommandMock Mock_Database -ResetDatabase # Load include files needed to test database @@ -133,7 +130,6 @@ function Test_Database_JSON_ComplexObject{ function Test_Database_XML{ - Reset-InvokeCommandMock Mock_Database -ResetDatabase # Load include files needed to test database @@ -179,7 +175,6 @@ function Test_Database_XML{ function Test_Database_TXT{ - Reset-InvokeCommandMock Mock_Database -ResetDatabase # Load include files needed to test database @@ -225,7 +220,6 @@ function Test_Database_TXT{ function Test_Database_MultyKey{ - Reset-InvokeCommandMock Mock_Database -ResetDatabase . $(Get-Ps1FullPath -Name "databaseV2.ps1" -FolderName "Include" -ModuleRootPath $MODULE_ROOT_PATH) diff --git a/Test/public/datehelper.test.ps1 b/Test/public/datehelper.test.ps1 index da5a704..37e07ac 100644 --- a/Test/public/datehelper.test.ps1 +++ b/Test/public/datehelper.test.ps1 @@ -53,21 +53,23 @@ function Test_GetDaysBetweenDates_OneYear { } function Test_GetDaysBetweenDates_DefaultStartDate { + # Arrange - Reset-InvokeCommandMock - $now = Get-Date -Format 'yyyy-MM-dd' MockCallToObject -Command "GetNow" -OutObject $now + $futureDate = (Mock_GetToday).AddDays(10) + $futureDateString = $futureDate | Get-Date -Format 'yyyy-MM-dd' - # Act & Assert - Invoke-PrivateContext { - $futureDate = (Get-Date).AddDays(10) | Get-Date -Format 'yyyy-MM-dd' - - $result = Get-DaysBetweenDates -EndDate $futureDate - - # Result should be approximately 10 days (allowing for same-day test execution) - Assert-AreEqual -Expected 10 -Presented $result - } + # Act + $result = Invoke-PrivateContext { + param($Arguments) + + Get-DaysBetweenDates -EndDate $Arguments[0] + + } -Arguments $futureDateString + + # Result should be approximately 10 days (allowing for same-day test execution) + Assert-AreEqual -Expected 10 -Presented $result } function Test_ConvertFromEpochTime_OneDay { diff --git a/Test/public/dependencies.test.ps1 b/Test/public/dependencies.test.ps1 index 0c866de..cc23bb3 100644 --- a/Test/public/dependencies.test.ps1 +++ b/Test/public/dependencies.test.ps1 @@ -2,7 +2,6 @@ function Test_ImportDepepency_Already_loaded{ $name = "TargetModule" ; $modulesFolder = "ModulesFolder" - Reset-InvokeCommandMock New-moduleV3 -Name $name -Path $modulesFolder @@ -27,7 +26,6 @@ function Test_ImportDepepency_Already_loaded{ function Test_ImportDepepency_SideBySide{ $name = "TargetModule" ; $modulesFolder = "ModulesFolder" - Reset-InvokeCommandMock # Create new module on test folder New-moduleV3 -Name $name -Path $modulesFolder @@ -59,8 +57,6 @@ function Test_ImportDepepency_Import_From_Module_Manager{ $name = "TargetModule" ; $modulesFolder = "ModulesFolder" - Reset-InvokeCommandMock - New-ModuleV3 -Name $name -Path $modulesFolder # Mock Get-Module to Null @@ -92,7 +88,6 @@ function Test_ImportDepepency_Import_From_Module_Manager{ function Test_ImportDepepency_Install_From_Gallery{ $name = "TargetModule" ; $modulesFolder = "ModulesFolder" - Reset-InvokeCommandMock New-ModuleV3 -Name $name -Path $modulesFolder # Mock Get-Module to Null @@ -134,7 +129,6 @@ function Test_ImportDependency_Clone_From_GitHub{ $name = "TargetModule" ; $modulesFolder = "ModulesFolder" $owner = "rulasg" - Reset-InvokeCommandMock # Mock Get-Module to Null Mock_GetModule_Null -Name $name diff --git a/Test/public/getfileversion.test.ps1 b/Test/public/getfileversion.test.ps1 index c1ce95b..fc66154 100644 --- a/Test/public/getfileversion.test.ps1 +++ b/Test/public/getfileversion.test.ps1 @@ -10,7 +10,6 @@ function Test_GetFileVersion_EmptyFile{ function Test_GetFileVersion_NoVersion{ - New-Testingfile -Name "TestFile.ps1" -Content $FILE_FACKE_CONTENT # Act @@ -18,7 +17,6 @@ function Test_GetFileVersion_NoVersion{ # Assert Assert-IsNull -Object $result - } function Test_GetFileVersion_OnlyVersion{ @@ -27,7 +25,9 @@ function Test_GetFileVersion_OnlyVersion{ $headerversion = 1 $version = "1.0.0" $date = "1975-02-18" - $json = Build-TestFileVersionJson $Version $Date $headerversion + $source = "IncludeHelper" + + $json = Build-TestFileVersionJson $Version $Date $source $headerversion New-Testingfile -Name "TestFile.ps1" -Content $("# $json") Assert-FileVersion -Path "TestFile.ps1" -Version $version -Date $date @@ -38,6 +38,8 @@ function Test_GetFileVersion_OnlyVersion{ Assert-IsNotNull -Object $result Assert-AreEqual -Expected $version -Presented $result.Version Assert-AreEqual -Expected $date -Presented $result.Date + Assert-AreEqual -Expected $source -Presented $result.Source + Assert-AreEqual -Expected $headerversion -Presented $result.HeaderVersion } function Test_GetFileVersion_VersionAndBody{ @@ -46,11 +48,12 @@ function Test_GetFileVersion_VersionAndBody{ $headerversion = 1 $version = "1.0.0" $date = "1975-02-18" - $header = Build-TestVersionHeader $Version $Date $headerversion + $source = "IncludeHelper" + $header = Build-TestVersionHeader $Version $Date $source $headerversion $body = $FILE_FACKE_CONTENT - $content = $header + $body | Out-String + $content = ($header + $body) -join "`n" New-Testingfile -Name "TestFile.ps1" -Content $content - Assert-FileVersion -Path "TestFile.ps1" -Version $version -Date $date -Body $body + Assert-FileVersion -Path "TestFile.ps1" -Version $version -Date $date -Body $body # Act $result = Get-IncludeFileVersion -Path "TestFile.ps1" diff --git a/Test/public/githelper.test.ps1 b/Test/public/githelper.test.ps1 new file mode 100644 index 0000000..e89f53d --- /dev/null +++ b/Test/public/githelper.test.ps1 @@ -0,0 +1,38 @@ +function Test_TestRepoFileChanged_Changed{ + + + $repo = "reponame" + New-TestingFolder -Path $repo + git init $repo + + # Arrange Not changed + $folder = "folder1/folder2" + $file = "file1.txt" + New-TestingFile -Path "$repo/$folder" -Name $file -Content "Hello World" + $targetpath = Join-Path -Path $repo -childPath $folder -AdditionalChildPath $file + + # Act + $result = Test-RepoFileChanged -Path $targetpath + + # Assert + Assert-IsTrue -Condition $result + + # Arrange Not Changed + git -C $repo add . + git -C $repo commit -m "Initial commit" + + # Act + $result = Test-RepoFileChanged -Path $targetpath + + # Assert + Assert-IsFalse -Condition $result -Comment "File should not be marked as changed after commit" + + # Arrange change the file again + Set-Content -Path $targetpath -Value "Hello World Changed" + + # Act + $result = Test-RepoFileChanged -Path $targetpath + + # Assert + Assert-IsTrue -Condition $result -Comment "File should be marked as changed after modification" +} diff --git a/Test/public/invokeCommand.mock.test.ps1 b/Test/public/invokeCommand.mock.test.ps1 index 3830091..c4e121e 100644 --- a/Test/public/invokeCommand.mock.test.ps1 +++ b/Test/public/invokeCommand.mock.test.ps1 @@ -1,8 +1,6 @@ function Test_MockCallJson{ - Reset-InvokeCommandMock - $fileName = 'test.json' MockCallJson -Command 'Test-Command' -filename $fileName @@ -16,8 +14,6 @@ function Test_MockCallJson{ function Test_MockCallJson_AsHashtable{ - Reset-InvokeCommandMock - $fileName = 'test.json' # Act @@ -33,8 +29,6 @@ function Test_MockCallJson_AsHashtable{ function Test_MockCallToObject{ - Reset-InvokeCommandMock - $data = @{ Name = 'Test' Value = 42 @@ -50,6 +44,7 @@ function Test_MockCallToObject{ function Test_MockCallToObject_ResetMockObject{ + # Reset again toremove the preset dates variables Reset-InvokeCommandMock MockCallToObject -Command 'kk1' -OutObject 'Testkk1' @@ -71,8 +66,6 @@ function Test_MockCallToObject_ResetMockObject{ function Test_MockCallExpression{ - Reset-InvokeCommandMock - $expression = @' echo "new string from mock 2" echo "more things to say" diff --git a/Test/public/module.helper.test.ps1 b/Test/public/module.helper.test.ps1 index a4abb4f..6e8826b 100644 --- a/Test/public/module.helper.test.ps1 +++ b/Test/public/module.helper.test.ps1 @@ -15,9 +15,8 @@ function Test_ModuleHelper_AreEqual_InModule_And_TestModule{ $filePath[$_]= $path | Join-Path -ChildPath $files[$_].Name } - $content1 = Get-Content -Path $filePath[0] | Out-String - $content2 = Get-Content -Path $filePath[1] | Out-String - + $content1 = (Get-Content -Path $filePath[0]) -join "`n" + $content2 = (Get-Content -Path $filePath[1]) -join "`n" Assert-AreEqual -Expected $content1 -Presented $content2 } diff --git a/Test/public/openFilesUrls.test.ps1 b/Test/public/openFilesUrls.test.ps1 index f786081..92c21a6 100644 --- a/Test/public/openFilesUrls.test.ps1 +++ b/Test/public/openFilesUrls.test.ps1 @@ -5,7 +5,6 @@ function Test_OpenUrl_SingleUrl { # Arrange - Reset-InvokeCommandMock $url = "https://github.com" $tag = New-Guid @@ -28,7 +27,6 @@ function Test_OpenUrl_SingleUrl { function Test_OpenUrl_MultipleUrls_Pipeline { # Arrange - Reset-InvokeCommandMock $url1 = "https://github.com" $url2 = "https://google.com" $url3 = "https://microsoft.com" diff --git a/Test/public/setfileversion.test.ps1 b/Test/public/setfileversion.test.ps1 index c859531..e534b1b 100644 --- a/Test/public/setfileversion.test.ps1 +++ b/Test/public/setfileversion.test.ps1 @@ -1,29 +1,31 @@ function Test_SetFileVersion_EmptyFile{ $version = "1.0.0" + $source = "kk" touch "TestFile.ps1" # Act - $result = Set-IncludeFileVersion -Path "TestFile.ps1" -Version $version + $result = Set-IncludeFileVersion -Path "TestFile.ps1" -Version $version -Source $source # Assert Assert-IsTrue -Condition $result - Assert-FileVersion -Path "TestFile.ps1" -Version $version + Assert-FileVersion -Path "TestFile.ps1" -Version $version -source $source } function Test_SetFileVersion_NoVersion{ $version = "1.0.0" + $source = "kk" New-Testingfile -Name "TestFile.ps1" -Content $FILE_FACKE_CONTENT # Act - $result = Set-IncludeFileVersion -Path "TestFile.ps1" -Version $version + $result = Set-IncludeFileVersion -Path "TestFile.ps1" -Version $version -Source $source # Assert Assert-IsTrue -Condition $result - Assert-FileVersion -Path "TestFile.ps1" -Version $version -Body $FILE_FACKE_CONTENT + Assert-FileVersion -Path "TestFile.ps1" -Version $version -Body $FILE_FACKE_CONTENT -Source $source } @@ -35,37 +37,39 @@ function Test_SetFileVersion_OnlyVersion{ $headerversion = 1 $version = "1.0.0" $date = "1975-02-18" - $json = Build-TestFileVersionJson $Version $Date $headerversion + $source = "kk" + $json = Build-TestFileVersionJson $Version $Date $source $headerversion New-Testingfile -Name "TestFile.ps1" -Content $("# $json") - Assert-FileVersion -Path "TestFile.ps1" -Version $version -Date $date + Assert-FileVersion -Path "TestFile.ps1" -Version $version -Date $date -Source $source # Act - $result = Set-IncludeFileVersion -Path "TestFile.ps1" -Version $version + $result = Set-IncludeFileVersion -Path "TestFile.ps1" -Version $version -Source $source # Assert Assert-IsTrue -Condition $result - Assert-FileVersion -Path "TestFile.ps1" -Version $version + Assert-FileVersion -Path "TestFile.ps1" -Version $version -Source $source } function Test_SetFileVersion_VersionAndBody{ $version = "3.2.1" + $source = "kk" # Arrange version in file $headerversion = 1 $version = "1.0.0" $date = "1975-02-18" - $json = Build-TestFileVersionJson $Version $Date $headerversion + $json = Build-TestFileVersionJson $Version $Date $source $headerversion New-Testingfile -Name "TestFile.ps1" -Content $("# $json") - Assert-FileVersion -Path "TestFile.ps1" -Version $version -Date $date + Assert-FileVersion -Path "TestFile.ps1" -Version $version -Date $date -Source $source # Act - $result = Set-IncludeFileVersion -Path "TestFile.ps1" -Version $version + $result = Set-IncludeFileVersion -Path "TestFile.ps1" -Version $version -Source $source # Assert Assert-IsTrue -Condition $result Enable-IncludeHelperDebug -Section "Assert-FileVersion" - Assert-FileVersion -Path "TestFile.ps1" -Version $version -Body $body + Assert-FileVersion -Path "TestFile.ps1" -Version $version -Body $body -Source $source Disable-IncludeHelperDebug } @@ -82,14 +86,15 @@ function Assert-FileVersion{ [string]$Path, [string]$Version, [string]$Date = (Get-Date -Format "yyyy-MM-dd"), - [string]$Body + [string]$Body, + [string]$Source = "IncludeHelper" ) $headerversion = 1 $headeersizeinlines = $script:TEST_HEADER_V1.Count - $content = Get-Content -Path $Path | Out-String - $json = Build-TestFileVersionJson $Version $Date $headerversion + $content = (Get-Content -Path $Path) -join "`n" + $json = Build-TestFileVersionJson $Version $Date $Source $headerversion $expected = "# $json" $content = @(Get-Content -Path $Path) @@ -101,23 +106,23 @@ function Assert-FileVersion{ # Assert content if provided if(-not [string]::IsNullOrWhiteSpace($Body)){ # "Comparing body" | Write-MyDebug -Section "Assert-FileVersion" - # Remove the first line from content + + # Remove header from content to compare with body $rest = $content | Select-Object -Skip $headeersizeinlines - # join string[] to string $rest = $rest -join "`n" - # "Body presented:" | Write-MyDebug -Section "Assert-FileVersion" -Object $Body - # "Rest Content :" | Write-MyDebug -Section "Assert-FileVersion" -Object $rest - Assert-AreEqual -Expected $Body -Presented $rest -Comment "Rest of the file content should be the same" + + Assert-AreEqual -Expected $Body -Presented $rest } } -function Build-TestFileVersionJson($Version, $Date, $Headerversion){ +function Build-TestFileVersionJson($Version, $Date, $Source, $Headerversion){ # Need to create the full object to control the order of members for mocking if(-not [string]::IsNullOrWhiteSpace($Headerversion)){ $json = [pscustomobject]@{ Version = $Version Date = $Date + Source = $Source HeaderVersion = $Headerversion } } else { @@ -133,11 +138,11 @@ function Build-TestFileVersionJson($Version, $Date, $Headerversion){ } $script:TEST_HEADER_V1 = @( - '# {"Version":"{version}","Date":"{date}","HeaderVersion":{headerversion}}', + '# {"Version":"{version}","Date":"{date}","Source":"{source}","HeaderVersion":{headerversion}}', "# DO NOT MODIFY THIS FILE MANUALLY. IT IS GENERATED BY THE IncludeHelper MODULE." ) -function Build-TestVersionHeader($version, $Date, $headerversion){ +function Build-TestVersionHeader($version, $Date, $source,$headerversion){ # Sync this code with Build-VersionHeader at public/setfileversion.ps1 $headerversion = $headerversion @@ -146,6 +151,7 @@ function Build-TestVersionHeader($version, $Date, $headerversion){ # replace the {json} placeholder with the actual json $header = $header | ForEach-Object { $_ -replace "{headerversion}", "$headerversion" } + $header = $header | ForEach-Object { $_ -replace "{source}", "IncludeHelper" } $header = $header | ForEach-Object { $_ -replace "{version}", $Version } $header = $header | ForEach-Object { $_ -replace "{date}", $Date } diff --git a/helper/invokeCommand.helper.ps1 b/helper/invokeCommand.helper.ps1 index 5a08f46..25da803 100644 --- a/helper/invokeCommand.helper.ps1 +++ b/helper/invokeCommand.helper.ps1 @@ -1,3 +1,5 @@ +# {"Version":"1.3.0","Date":"","Source":"IncludeHelper","HeaderVersion":1} +# DO NOT MODIFY THIS FILE MANUALLY. IT IS GENERATED BY THE IncludeHelper MODULE. # SET MY INVOKE COMMAND ALIAS # @@ -21,6 +23,17 @@ function Set-MyInvokeCommandAlias{ } } +function Reset-MyInvokeCommandAlias{ + [CmdletBinding(SupportsShouldProcess)] + param() + + # throw if MODULE_INVOKATION_TAG is not set or is "MyModuleModule" + if (-not $MODULE_INVOKATION_TAG) { + throw "MODULE_INVOKATION_TAG is not set. Please set it to a unique value before calling Set-MyInvokeCommandAlias." + } + InvokeHelper\Reset-InvokeCommandAlias -Tag $MODULE_INVOKATION_TAG +} + function Invoke-MyCommand{ [CmdletBinding()] param( @@ -33,17 +46,84 @@ function Invoke-MyCommand{ return InvokeHelper\Invoke-MyCommand -Command $Command -Parameters $Parameters } +function Invoke-MyCommandAsync{ + [CmdletBinding()] + param( + [Parameter(Mandatory,ValueFromPipeline,Position=0)][string]$Command, + [Parameter(Position=1)][hashtable]$Parameters + ) -function Reset-MyInvokeCommandAlias{ - [CmdletBinding(SupportsShouldProcess)] - param() + Write-MyDebug "invoke" $Command $Parameters - # throw if MODULE_INVOKATION_TAG is not set or is "MyModuleModule" - if (-not $MODULE_INVOKATION_TAG) { - throw "MODULE_INVOKATION_TAG is not set. Please set it to a unique value before calling Set-MyInvokeCommandAlias." + $job = InvokeHelper\Start-MyJob -Command $Command -Parameters $Parameters + + $call = [pscustomobject]@{ + Job = $job + Command = $Command + Parameters = $Parameters + } + + return $call +} + +function Wait-MyCommandAsync{ + [CmdletBinding()] + param( + [Parameter(Mandatory,ValueFromPipeline,Position=0)][pscustomobject]$call + ) + + begin{ + $jobs = @() + } + + process{ + + $jobs += $call.Job + + } + + end { + + $waitingJobs = $jobs + + $all = $waitingJobs.Count + "Waiting for [$all] jobs to complete " | Write-MyHost -noNewline + + while ($waitingJobs.Count -ne 0) { + + $waitings = $waitingJobs | Wait-Job -Any + + "." | Write-MyHost -NoNewline + + # Remove completed jobs from the waiting list + $waitingJobs = $waitingJobs | Where-Object { $_.Id -ne $waitings.Id } + + } + + $completed = $jobs | Where-Object { $_.State -eq 'Completed' } | Measure-Object | Select-Object -ExpandProperty Count + $failed = $jobs | Where-Object { $_.State -eq 'Failed' } | Measure-Object | Select-Object -ExpandProperty Count + $all = $jobs.Count + + "" | Write-MyHost + "Completed [$completed] Failed [$failed]" | Write-MyHost + } +} + +function Receive-MyCommandAsync{ + [CmdletBinding()] + param( + [Parameter(Mandatory,ValueFromPipeline,Position=0)][pscustomobject]$call + ) + + $res = Receive-Job -Job $call.Job -ErrorAction SilentlyContinue + + # Check for false if update failed + if(-not $res){ + "Failed calling to update project [$($call.Parameters.projectnumber)]." | Write-MyError + } else { + $res } - InvokeHelper\Reset-InvokeCommandAlias -Tag $MODULE_INVOKATION_TAG } # Reset all aliases for this module on each refresh -Reset-MyInvokeCommandAlias +Reset-MyInvokeCommandAlias \ No newline at end of file diff --git a/include/MyWrite.ps1 b/include/MyWrite.ps1 index 607b4ac..d6ce0bc 100644 --- a/include/MyWrite.ps1 +++ b/include/MyWrite.ps1 @@ -1,6 +1,6 @@ -# {"Version":"1.0.2","Date":"2026-06-16","HeaderVersion":1} +# {"Version":"1.6.0","Date":"2026-07-17","Source":"includehelper","HeaderVersion":1} # DO NOT MODIFY THIS FILE MANUALLY. IT IS GENERATED BY THE IncludeHelper MODULE. -# + # Include MyWrite.ps1 # Provides Write-MyError, Write-MyWarning, Write-MyVerbose, Write-MyHost, Write-MyDebug # and Test-MyVerbose, Test-MyDebug functions for consistent logging and debugging output. @@ -22,10 +22,19 @@ function Write-MyError { param( [Parameter(Mandatory, ValueFromPipeline)][string]$Message ) + $script:LastError= $Message # Write-Host "Error: $message" -ForegroundColor $ERROR_COLOR Write-ToConsole "Error: $message" -Color $ERROR_COLOR } +function Get-ModuleLastError { + [CmdletBinding()] + param() + + return $script:LastError +}Copy-Item -path Function:Get-ModuleLastError -Destination Function:"Get-$($MODULE_NAME)LastError" +Export-ModuleMember -Function "Get-$($MODULE_NAME)LastError" + function Write-MyWarning { [CmdletBinding()] [Alias("Write-Warning")] @@ -54,9 +63,14 @@ function Write-MyHost { param( [Parameter(ValueFromPipeline)][string]$Message, [Parameter()][string]$ForegroundColor = $OUTPUT_COLOR, - [Parameter()][switch]$NoNewLine + [Parameter()][switch]$NoNewLine, + [Parameter()][switch]$InNewLine + ) + # Add starting new line if InNewLine is specified + if ($InNewLine) { $Message = "`n" + $Message } + Write-MyDebug -Section "MyHost" -Message $Message # Write-Host $message -ForegroundColor $OUTPUT_COLOR @@ -67,7 +81,7 @@ function Clear-MyHost { [CmdletBinding()] param() -© # If debug do not clear host page + # If debug do not clear host page if (-not (Test-MyDebug -section "donotclearhost")) { Clear-Host } @@ -79,7 +93,10 @@ function Write-MyDebug { param( [Parameter(Position = 0)][string]$section = "none", [Parameter(Position = 1, ValueFromPipeline)][string]$Message, - [Parameter(Position = 2)][object]$Object + [Parameter(Position = 2)][object]$Object, + [Parameter()][int]$objectDepth = 10, + [Parameter()][switch]$ObjectNotCompress, + [Parameter()][switch]$InNewLine ) process{ @@ -87,12 +104,17 @@ function Write-MyDebug { if (Test-MyDebug -section $section) { if ($Object) { - $objString = $Object | Get-ObjetString + $compress = -not $ObjectNotCompress + $objString = $Object | Get-ObjetString -Depth $objectDepth -Compress:$compress $message = $message + " - " + $objString } $logMessage = normalizeMessage -Message $message -Section $section -Tag "D" + if ($InNewLine) { + $logMessage = "`n" + $logMessage + } + $logMessage | Write-ToConsole -Color $DEBUG_COLOR $logMessage | Write-MyDebugLogging } @@ -256,7 +278,8 @@ function Enable-ModuleNameDebug{ param( [Parameter(Position = 0)][string[]]$Sections, [Parameter()][string[]]$AddSections, - [Parameter()][string]$LoggingFilePath + [Parameter()][string]$LoggingFilePath, + [Parameter()][switch]$DoNotClearHost ) # Check if logging file path is provided @@ -269,6 +292,10 @@ function Enable-ModuleNameDebug{ } } + if($DoNotClearHost){ + $sectons += "donotclearhost" + } + $sectionsString = $sections -join " " $addedFlagsString = $AddSections -join " " @@ -342,7 +369,9 @@ Export-ModuleMember -Function "Get-$($MODULE_NAME)Debug" function Get-ObjetString { param( - [Parameter(ValueFromPipeline, Position = 0)][object]$Object + [Parameter(ValueFromPipeline, Position = 0)][object]$Object, + [Parameter()][int]$Depth = 10, + [Parameter()][switch]$Compress ) process{ @@ -355,7 +384,7 @@ function Get-ObjetString { return $Object } - return $Object | ConvertTo-Json -Depth 10 -ErrorAction SilentlyContinue + return $Object | ConvertTo-Json -Depth $Depth -ErrorAction SilentlyContinue -Compress:$Compress } } diff --git a/include/datehelper.ps1 b/include/datehelper.ps1 index 97f5cd2..45bb438 100644 --- a/include/datehelper.ps1 +++ b/include/datehelper.ps1 @@ -1,3 +1,5 @@ +# {"Version":"1.0.0","Date":"2026-06-18","Source":"IncludeHelper","HeaderVersion":1} +# DO NOT MODIFY THIS FILE MANUALLY. IT IS GENERATED BY THE IncludeHelper MODULE. # DATE HELPER # @@ -9,8 +11,22 @@ # - Getting current date and time (with Invoke-MyCommand pattern for testability) # -Set-MyInvokeCommandAlias -Alias GetNow -Command "Get-Date -Format 'yyyy-MM-dd'" +Set-MyInvokeCommandAlias -Alias GetNowString -Command "Get-Date -Format 'yyyy-MM-dd'" Set-MyInvokeCommandAlias -Alias GetUtcNow -Command "Get-Date -AsUTC" +Set-MyInvokeCommandAlias -Alias GetNow -Command "Get-Date" + +function Get-DateString{ + [CmdletBinding()] + param( + [Parameter(Position = 0)][DateTime]$Date + ) + + $date = $Date ?? (Invoke-MyCommand -Command GetNow) + + $datestring = $date.ToString("yyyy-MM-dd") + + return $datestring +} function Get-DaysBetweenDates { [CmdletBinding()] @@ -20,7 +36,7 @@ function Get-DaysBetweenDates { ) if ([string]::IsNullOrWhiteSpace($StartDate)) { - $StartDate = Invoke-MyCommand -Command GetNow + $StartDate = Invoke-MyCommand -Command GetNowString } $start = [DateTime]::ParseExact($StartDate, 'yyyy-MM-dd', $null) @@ -69,4 +85,4 @@ function ConvertTo-EpochTime { $timeSpan = $DateTime.ToUniversalTime() - $epoch return [long]$timeSpan.TotalSeconds -} +} \ No newline at end of file diff --git a/include/functionParameterHelper.ps1 b/include/functionParameterHelper.ps1 index d9abb5e..eef7606 100644 --- a/include/functionParameterHelper.ps1 +++ b/include/functionParameterHelper.ps1 @@ -1,3 +1,5 @@ +# {"Version":"1.0.0","Date":"2026-06-23","Source":"IncludeHelper","HeaderVersion":1} +# DO NOT MODIFY THIS FILE MANUALLY. IT IS GENERATED BY THE IncludeHelper MODULE. # Register-ArgumentCompleter # # To control the parametrs autofil we can register a scriptblock variable with a function to manage diff --git a/public/addIncludeToWorkspace.ps1 b/public/addIncludeToWorkspace.ps1 index 0e1d968..010afaf 100644 --- a/public/addIncludeToWorkspace.ps1 +++ b/public/addIncludeToWorkspace.ps1 @@ -26,6 +26,7 @@ Add-IncludeToWorkspace -Name "TestInclude.txt" -FolderName "TestInclude" #> function Add-IncludeToWorkspace { [CmdletBinding(SupportsShouldProcess)] + [Alias("aif")] param ( [Parameter(Mandatory,ValueFromPipelineByPropertyName,Position=0)][string]$Name, [Parameter(Mandatory,ValueFromPipelineByPropertyName, Position = 1)] @@ -110,15 +111,34 @@ function Add-IncludeToWorkspace { } if ($PSCmdlet.ShouldProcess("$sourceFile", "copy to $destinationFile")) { - # TODO: Add version info header to each file. + # Add version info header to each file. # The header will contain a do not modify this file manually message # Avoid using Set-Content as it adds an empty tail line at the end of the file # Implement a Get-ModuleInfo function on module.helper.ps1 to get module name and version # This function will read the psd1 file that has the same name as the folder name. This will allow having more than one psd1 file in the same folder # - Copy-Item -Path $sourceFile -Destination $destinationFile -Force - # Set-Content -Path $destinationFile -Value $content -Force - Write-Output $destinationFile + $content = Get-Content -Path $sourceFile + $version = Get-VersionFromHeader $content + # Find the name of the source module for leater adding to version header + $sourceModuleRootPath = Find-ModuleRootPath -Path $sourcePath | split-path -Leaf + + if($version){ + + # If version header exists, update the version header with the new module name and version + $newVersionHeader = Build-VersionHeader -Version $version.Version -Source $sourceModuleRootPath + $content = Remove-VersionHeader -content $content + } else { + $newVersionHeader = Build-VersionHeader -Version "1.0.0" -Source $sourceModuleRootPath + } + + # Build new content + $content = @($newVersionHeader) + $content + + # write fto file + $finalContent = $content -join "`n" + $finalContent | Out-File -Path $destinationFile -NoNewline -Force + + return $destinationFile } } @@ -126,7 +146,7 @@ function Add-IncludeToWorkspace { #"<< Add-IncludeToWorkspace" | Write-MyDebug } -} Export-ModuleMember -Function Add-IncludeToWorkspace +} Export-ModuleMember -Function Add-IncludeToWorkspace -Alias "aif" function Resolve-SourceDestinationPath{ [CmdletBinding()] diff --git a/public/getfileversion.ps1 b/public/getfileversion.ps1 index c47eb6b..8a55e5b 100644 --- a/public/getfileversion.ps1 +++ b/public/getfileversion.ps1 @@ -16,18 +16,9 @@ function Get-IncludeFileVersion{ return $null } - $version = Get-VersionHeader -content $content + $version = Get-VersionFromHeader -content $content - if($version){ - $ret = [PsCustomObject]@{ - Version = $version.Version - Date = $version.Date - } - } else { - $ret = $null - } - - return $ret + return $version } Export-ModuleMember -Function Get-IncludeFileVersion diff --git a/public/githelper.ps1 b/public/githelper.ps1 new file mode 100644 index 0000000..ac62984 --- /dev/null +++ b/public/githelper.ps1 @@ -0,0 +1,40 @@ +function Test-RepoFileChanged { + [CmdletBinding()] + param( + [Parameter(Mandatory, ValueFromPipeline, Position = 0)] + [string]$Path + ) + + process { + try { + if ([string]::IsNullOrWhiteSpace($Path)) { + return $false + } + + # convert to full routed path + $absolutePath = $Path | Convert-Path + + "Testing [$Path] converted to absolute path [$absolutePath]" | Write-MyDebug -Section "githelper" + + # Get the reporoot. needed for git commands + $parentDir = Split-Path -Path $absolutePath -Parent + $repoRoot = git -C $parentDir rev-parse --show-toplevel 2>$null + if ($LASTEXITCODE -ne 0 -or [string]::IsNullOrWhiteSpace($repoRoot)) { + "Not a git repository: $parentDir" | Write-MyDebug -Section "githelper" + return $false + } + + # Check status of the file using absolute path and repo root + $status = (& git -C $repoRoot status --porcelain -- $absolutePath 2>$null) + $ret = -not [string]::IsNullOrWhiteSpace($status) + + # return + "Testing [$ret] for [$Path] absolute path [$absolutePath] repoRoot [$repoRoot] status [$status]" | Write-MyDebug -Section "githelper" + return $ret + } + catch { + "Error occurred while testing [$Path]: $_" | Write-MyDebug -Section "githelper" + return $false + } + } +} Export-ModuleMember -Function Test-RepoFileChanged \ No newline at end of file diff --git a/public/listIncludes.ps1 b/public/listIncludes.ps1 index d60ab72..4d8eb73 100644 --- a/public/listIncludes.ps1 +++ b/public/listIncludes.ps1 @@ -32,6 +32,7 @@ Displays the available includes. #> function Get-IncludeFile{ [CmdletBinding()] + [Alias("gif")] param( #add filter pattern [Parameter( Position = 0 )] [string]$Filter = '*', @@ -70,11 +71,26 @@ function Get-IncludeFile{ $items = Get-ChildItem -Path $path -Filter "*$Filter*" -File -ErrorAction SilentlyContinue | ForEach-Object { + $content = Get-Content -Path $_.FullName + $version = Get-VersionFromHeader -content $content + if($version){ + $body = Remove-VersionHeader -content $content + } else { + $body = $content + } + + $sha = $body -join "`n" | Get-HashCode + $gitStatus = $(Test-RepoFileChanged -Path $_.FullName )? "Modified" : "Unmodified" + [PSCustomObject]@{ Name = Compress-FileNameTransformation -FileName $_.Name -SourceModulePath $ModuleRootPath FolderName = $FolderName ModuleName = $moduleName Path = $_.FullName + Version = $version.Version + Date = $version.Date + Sha = $sha + GitStatus = $gitStatus } } if ($items.Count -ne 0) { @@ -84,7 +100,7 @@ function Get-IncludeFile{ return $ret -} Export-ModuleMember -Function Get-IncludeFile +} Export-ModuleMember -Function Get-IncludeFile -Alias "gif" <# .SYNOPSIS @@ -130,3 +146,90 @@ function Open-IncludeFile{ } } Export-ModuleMember -Function Open-IncludeFile + +function Compare-IncludeFile{ + [CmdletBinding()] + [Alias("cif")] + param( + #add filter pattern + [Parameter( Position = 0 )] [string]$Filter = '*', + [Parameter()][string[]]$Folders, + [Parameter()][string]$ModuleRootPath, + [Parameter()][switch]$PassThru, + [Parameter()][switch]$All, + [Parameter()][switch]$Opendiff + + ) + + # If not ModuleRootPath specified, use local + if([string]::IsNullOrWhiteSpace($ModuleRootPath)){ $local = $true } + + $allLocal = Get-IncludeFile -Filter $Filter -Folders $Folders -ModuleRootPath:$ModuleRootPath -Local:$Local + $allRemote = Get-IncludeFile -Filter $Filter -Folders $Folders -ModuleRootPath $ModuleRootPath + + $allLocal =$allLocal ?? @() + $allRemote =$allRemote ?? @() + + "Found $($allLocal.Count) local and $($allRemote.Count) remote include files for filter [$Filter] in folders [$($Folders -join ', ')]" | Write-MyDebug -Section "cif" + + $ret = @() + $done = @() + + # Compare existing files + $allItems = $All ? $($allLocal + $allRemote) : $alllocal + + $allItems | ForEach-Object { + # Check if done + $filetag = "$($_.FolderName)_$($_.Name)" + + if($done -notcontains $filetag){ + + $done += $filetag + + $local = $allLocal | Where-Object { "$($_.FolderName)_$($_.Name)" -eq $filetag } + $remote = $allRemote | Where-Object { "$($_.FolderName)_$($_.Name)" -eq $filetag } + "Local : $($local.Name) $($local.FolderName) $($local.Version) $($local.Date) $($local.Sha) $($local.GitStatus)" | Write-MyDebug -Section "cif" + "Remote : $($remote.Name) $($remote.FolderName) $($remote.Version) $($remote.Date) $($remote.Sha) $($remote.GitStatus)" | Write-MyDebug -Section "cif" + + $areEqual = $local.Sha -eq $remote.Sha + + $item = [PsCustomObject]@{ + Name = $_.Name + FolderName = $_.FolderName + + AreEqual = $areEqual + + LocalVersion = $local.Version + LocalDate = $local.Date + LocalGitStatus = $local.GitStatus + LocalPath = $local.Path + + RemoteVersion = $remote.Version + RemoteDate = $remote.Date + RemoteGitStatus = $remote.GitStatus + RemotePath = $remote.Path + } + $ret += $item + } + } + + $ret = $ret |sort-object -Property AreEqual,FolderName, Name + + if($OpenDiff){ + $ret | foreach-object{ + if(-not $_.AreEqual){ + Write-MyDebug "Opening diff for $($_.Name) in folder $($_.FolderName)" -Section "cif" + code --diff $($_.LocalPath) $($_.RemotePath) + } else { + Write-MyDebug "Skipping diff for $($_.Name) in folder $($_.FolderName) as they are equal" -Section "cif" + } + } + } + + if($PassThru){ + return $ret + } else { + $ret | Format-Table -Property Name,FolderName,AreEqual,LocalVersion,LocalDate,LocalGitStatus,RemoteVersion,RemoteDate,RemoteGitStatus -AutoSize + } + +} Export-ModuleMember -Function Compare-IncludeFile -Alias "cif" diff --git a/public/setfileversion.ps1 b/public/setfileversion.ps1 index d06b4c0..ba44f44 100644 --- a/public/setfileversion.ps1 +++ b/public/setfileversion.ps1 @@ -2,9 +2,10 @@ function Set-IncludeFileVersion{ [CmdletBinding()] [outputtype([bool])] param( - [string]$Path, - [string]$Version, - [string]$Date + [parameter(Mandatory,ValueFromPipelineByPropertyName)][string]$Path, + [parameter(Mandatory)][string]$Version, + [parameter()][string]$Date, + [parameter()][string]$Source ) # Return of file does not exist @@ -19,22 +20,27 @@ function Set-IncludeFileVersion{ $content = Get-Content -Path $Path # Get actual version - $actualVersion = $null -eq $content ? $null : $(Get-VersionHeader -content $content) + $actualVersion = $null -eq $content ? $null : $(Get-VersionFromHeader -content $content) - if($actualVersion){ - # Check if actual version is the same as the new version, if so return true - if(($actualVersion.Version -eq $Version) -and ($actualVersion.Date -eq $Date)){ - return $true - } - } + # if($actualVersion){ + # # Check if actual version is the same as the new version, if so return true + # if(($actualVersion.Version -eq $Version) -and ($actualVersion.Date -eq $Date)){ + # return $true + # } + # } # If version remove header if($actualVersion){ $content = Remove-VersionHeader -content $content } + # If source not specified, get the source from the path + if([string]::IsNullOrEmpty($Source)){ + $source = Find-ModuleRootPath -Path $Path | split-path -Leaf + } + # Build Target version line - $tragetFirstLine = Build-VersionHeader -Version $Version -Date $Date + $tragetFirstLine = Build-VersionHeader -Version $Version -Date $Date -Source $source # Add the new version header as the first line of the file $newContent = @($tragetFirstLine) + $content @@ -47,7 +53,7 @@ function Set-IncludeFileVersion{ } Export-ModuleMember -Function Set-IncludeFileVersion $script:HEADER_V1 = @( - '# {"Version":"{version}","Date":"{date}","HeaderVersion":{headerversion}}', + '# {"Version":"{version}","Date":"{date}","Source":"{source}","HeaderVersion":{headerversion}}', "# DO NOT MODIFY THIS FILE MANUALLY. IT IS GENERATED BY THE IncludeHelper MODULE." ) @@ -55,27 +61,31 @@ function Build-VersionHeader_V1{ [alias("Build-VersionHeader")] param( [string]$Version, - [string]$Date + [string]$Date, + [string]$Source ) $headerversion = 1 $header = $script:HEADER_V1 - + + $Date = [string]::IsNullOrEmpty($Date) ? (Get-DateString) : $Date + # replace the {json} placeholder with the actual json $header = $header | ForEach-Object { $_ -replace "{headerversion}", "$headerversion" } $header = $header | ForEach-Object { $_ -replace "{version}", $Version } $header = $header | ForEach-Object { $_ -replace "{date}", $Date } + $header = $header | ForEach-Object { $_ -replace "{source}", $Source } return $header -} +} Export-ModuleMember -Function Build-VersionHeader_V1 -Alias Build-VersionHeader function Remove-VersionHeader($content){ $headerSizeV0 = 1 $headersSizeV1 = $script:HEADER_V1.Count - $version = Get-VersionHeader -content $content + $version = Get-VersionFromHeader -content $content if(-not $version){ throw "No version header found in content" @@ -95,9 +105,9 @@ function Remove-VersionHeader($content){ } return $content -} +} Export-ModuleMember -Function Remove-VersionHeader -function Get-VersionHeader($content){ +function Get-VersionFromHeader($content){ # So far the version json is always on the first line @@ -115,5 +125,5 @@ function Get-VersionHeader($content){ try { $version = $json | ConvertFrom-Json } catch { return $null } return $version -} +} export-ModuleMember -Function Get-VersionFromHeader