-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBuild.ps1
More file actions
1081 lines (840 loc) · 37.2 KB
/
Build.ps1
File metadata and controls
1081 lines (840 loc) · 37.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# *****************************************************************************
# (c) 2023, EULANDA Software GmbH
#
# Build process for EulandaConnect
# *****************************************************************************
[cmdletbinding()] Param(
[switch]$updateManifest # 1
,
[switch]$updateMarkdown # 2
,
[switch]$convertToMaml # 3
,
[switch]$newFinalImage # 4
,
[switch]$updateOnlineDocs # 5
,
[switch]$invokePester # 6a + 6b
,
[switch]$publishToPsGallery # 7
,
[switch]$noTelegram # Parameter to modify 'invokePester' to 6a
)
# Imports only the unit without the complete module,
# because the module is temporarily removed in the script
. "$PsScriptRoot\source\public\Get-SignToolPath.ps1"
. "$PsScriptRoot\source\public\Use-Culture.ps1"
function Get-Manifest {
param(
[string]$createDate,
[string]$version,
[string]$functionsToExport,
[string]$assetsFileList
)
Write-Verbose -Message ('Starting: {0}' -f $myInvocation.Mycommand)
[string]$Result = @"
#
# Module manifest for module 'EulandaConnect'
#
# Generated by: Christian Niedergesäß - https://www.eulanda.eu
#
# Generated on: $createDate
#
@{
# Script module or binary module file associated with this manifest.
RootModule = 'EulandaConnect.psm1'
# Version number of this module.
ModuleVersion = '$version'
# Supported PSEditions
CompatiblePSEditions = @('Desktop', 'Core')
# ID used to uniquely identify this module
GUID = 'd80a730f-d7af-49a2-a6bb-49732aa5287d'
# Author of this module
Author = 'Christian Niedergesäß'
# Company or vendor of this module
CompanyName = 'EULANDA Software GmbH'
# Copyright statement for this module
Copyright = '© EULANDA Software GmbH. All rights reserved.'
# Description of the functionality provided by this module
Description = 'EulandaConnect enables the automation of processes both within and beyond your EULANDA ERP software. Compatible with EULANDA ERP 8.x and PowerShell 5.1 or higher, it supports a range of functionalities. These include XML data exchange, Datanorm, delivery bills, order creation, and communication via the Telegram API. In addition, EulandaConnect offers image functions, diagnostic functions, and a suite of MSSQL features such as comprehensive database renaming, data backup, and SQL browser location within the network. With over 250 functions currently available and more in development, EulandaConnect is a powerful extension not only for your ERP system. https://eulandaconnect.eulanda.eu'
# Minimum version of the PowerShell engine required by this module
PowerShellVersion = '5.1'
# Name of the PowerShell host required by this module
# PowerShellHostName = ''
# Minimum version of the PowerShell host required by this module
# PowerShellHostVersion = ''
# Minimum version of Microsoft .NET Framework required by this module. This prerequisite is valid for the PowerShell Desktop edition only.
# DotNetFrameworkVersion = ''
# Minimum version of the common language runtime (CLR) required by this module. This prerequisite is valid for the PowerShell Desktop edition only.
# ClrVersion = ''
# Processor architecture (None, X86, Amd64) required by this module
# ProcessorArchitecture = ''
# Modules that must be imported into the global environment prior to importing this module
# RequiredModules = @()
# Assemblies that must be loaded prior to importing this module
# RequiredAssemblies = @()
# Script files (.ps1) that are run in the caller's environment prior to importing this module.
# ScriptsToProcess = @()
# Type files (.ps1xml) to be loaded when importing this module
# TypesToProcess = @()
# Format files (.ps1xml) to be loaded when importing this module
# FormatsToProcess = @()
# Modules to import as nested modules of the module specified in RootModule/ModuleToProcess
# NestedModules = @()
# Functions to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no functions to export.
FunctionsToExport = @(
'$functionsToExport'
)
# Cmdlets to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no cmdlets to export.
# CmdletsToExport = @()
# Variables to export from this module
VariablesToExport = '*'
# Aliases to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no aliases to export.
# AliasesToExport = @()
# DSC resources to export from this module
# DscResourcesToExport = @()
# List of all modules packaged with this module
ModuleList = @('.\EulandaConnect.psm1')
# List of all files packaged with this module
FileList = @(
$assetsFileList
)
# Private data to pass to the module specified in RootModule/ModuleToProcess. This may also contain a PSData hashtable with additional module metadata used by PowerShell.
PrivateData = @{
PSData = @{
Title = 'Eulanda ERP functions supporting PowerShell'
# Tags applied to this module. These help with module discovery in online galleries.
Tags = @("Eulanda",
"ERP",
"SDK",
"API",
"OEM-Charset",
"DATANORM",
"CUDEL",
"Order",
"Delivery",
"Invoice",
"Shop",
"Store",
"Carrier",
"Textprocessing",
"Slugify",
"LoremIpsum",
"MSSQL",
"Backup",
"Ftp",
"Convert",
"Rename",
"Database",
"VSS",
"Signing",
"Signtool",
"PublicIp",
"XML",
"Telegram",
"SqlBrowser",
"ImageProcessing",
"WIA.ImageFile")
# A URL to the license for this module.
# LicenseUri = 'https://github.com/Eulanda/EulandaConnect/blob/master/License.md'
# A URL to the main website for this project.
ProjectUri = 'https://github.com/Eulanda/EulandaConnect'
# A URL to an icon representing this module.
IconUri = 'https://github.com/Eulanda/EulandaConnect/blob/master/media/EulandaConnect-icon.png?raw=true'
# ReleaseNotes of this module
ReleaseNotes = 'Look at Changelog in Project Site: https://github.com/Eulanda/EulandaConnect/blob/master/docs/general/Changelog.md'
# Prerelease string of this module
# Prerelease = 'beta'
# Flag to indicate whether the module requires explicit user acceptance for install/update/save
RequireLicenseAcceptance = `$false
# External dependent modules of this module
# ExternalModuleDependencies = @()
} # End of PSData hashtable
} # End of PrivateData hashtable
# HelpInfo URI of this module
HelpInfoURI = 'https://github.com/Eulanda/EulandaConnect'
# Default prefix for commands exported from this module. Override the default prefix using Import-Module -Prefix.
# DefaultCommandPrefix = ''
}
"@
Return $result
}
function Get-FunctionsToExport {
Write-Verbose -Message ('Starting: {0}' -f $myInvocation.Mycommand)
# all functions to be exported from the modul, means all in public
$params = @{
Filter = '*.ps1'
Recurse = $true
ErrorAction = 'Stop'
}
try {
$public = @(Get-ChildItem -Path "$projectFolder\source\public" @params)
}
catch {
Write-Error $_
throw 'Scanning public folders, but could not be read successfully'
}
[string]$Result = "$($public.Basename -join("',`n '"))"
Return $Result
}
function Get-SourceFiles {
Write-Verbose -Message ('Starting: {0}' -f $myInvocation.Mycommand)
# All functions to be exported from the modul, means all in public
$params = @{
Filter = '*.ps1'
Recurse = $true
ErrorAction = 'Stop'
}
try {
$public = @(Get-ChildItem -Path "$projectFolder\source\public" @params)
$private = @(Get-ChildItem -Path "$projectFolder\source\private" @params)
$prolog_ = @(Get-ChildItem -Path "$projectFolder\source\others\prolog.ps1")
$variables_ = @(Get-ChildItem -Path "$projectFolder\source\others\variables.ps1")
$initialize_ = @(Get-ChildItem -Path "$projectFolder\source\others\initialize.ps1")
$public_ = @(Get-ChildItem -Path "$projectFolder\source\others\public.ps1")
$private_ = @(Get-ChildItem -Path "$projectFolder\source\others\private.ps1")
}
catch {
Write-Error $_
throw 'Scanning public+private folders, but could not be read successfully'
}
$result = @($prolog_ + $variables_ + $initialize_ + $public_ + $public + $private_ + $private)
Return $result
}
function Get-AssetsFileList {
param(
[switch]$developer
)
Write-Verbose -Message ('Starting: {0}' -f $myInvocation.Mycommand)
# All files are just in final folder, except psd1 and MAML
$params = @{
Filter = '*.*'
Recurse = $false
ErrorAction = 'Stop'
}
try {
if ($developer) {
[string]$folder = Resolve-Path -Path "$projectFolder\assets"
$assets = @((Get-ChildItem -Path "$folder" @params).Name)
for ($i = 0; $i -lt $assets.Length; $i++) {
$assets[$i] = ".\assets\" + $assets[$i]
}
[string]$folder = Resolve-Path -Path "$projectFolder"
$languages = @((Get-ChildItem -Path "$folder" -Filter *.resx -ErrorAction Stop).Name)
for ($i = 0; $i -lt $languages.Length; $i++) {
$languages[$i] = ".\" + $languages[$i]
}
$assets = @('.\EulandaConnect.psd1','.\EulandaConnect.psm1','.\EulandaConnect-help.xml') + $languages + $assets
} else {
[string]$folder = Resolve-Path -Path "$projectFolder\final\EulandaConnect"
$assets = @((Get-ChildItem -Path "$folder" @params).Name)
for ($i = 0; $i -lt $assets.Length; $i++) {
$assets[$i] = ".\" + $assets[$i]
}
$assets = @('.\EulandaConnect.psd1','.\EulandaConnect-help.xml') + $assets
}
}
catch {
Write-Error $_
throw 'Unable to asset file.'
}
$assetsFileList = "`n '$($assets -join("',`n '"))'"
[string]$result = $assetsFileList
Return $result
}
function Test-TokenAvailable {
$iniPath = Resolve-Path ".\source\tests\pester.ini"
$ini = Read-IniFile -path $iniPath.Path
$output = certutil -scinfo -silent 2>&1 | Out-String
$snExists = $output -match $ini['TOKEN']['sn']
$cnExists = $output -match $ini['TOKEN']['cn']
if ($snExists -and $cnExists) {
return $true
}
else {
return $false
}
}
function Test-SftpPort {
param(
[Parameter(Mandatory=$true)]
[string]$ip,
[int]$port = 22,
[int]$timeoutMilliseconds = 2000 # 2 Sekunden Timeout
)
$tcpclient = New-Object Net.Sockets.TcpClient
$connect = $tcpclient.BeginConnect($ip, $port, $null, $null)
$result = $connect.AsyncWaitHandle.WaitOne($timeoutMilliseconds, $true)
$tcpclient.Close()
return $result
}
function Test-TokenPassword {
Write-Host "Signing dummy file to force password on beginning..."
$tempFolder = Join-Path $env:TEMP 'EulandaConnect'
New-Item -ItemType Directory -Force -Path $tempFolder | Out-Null
$testFilePath = Join-Path $tempFolder 'test.ps1'
'Write-Host "Hello, World!"' | Out-File -FilePath $testFilePath
Approve-Signature -Path $testFilePath
Remove-Item -Path $testFilePath
Remove-Item -Path $tempFolder -Force -Recurse
}
function Remove-PesterSftpFolder {
$pesterFolder = Resolve-Path -path ".\source\tests"
$iniPath = Join-Path -path $pesterFolder "pester.ini"
$ini = Read-IniFile -path $iniPath
$path = $ini['SFTP']['SecurePasswordPath']
$path = $path -replace '\$home', $HOME
$secure = Import-Clixml -path $path
$server = $ini['SFTP']['Server']
$user = $ini['SFTP']['User']
$remoteFolder = '/inbox/PESTER'
# Delete all content from /inbox including PESTER folder
try {
if (Test-RemoteFolder -server $server -protocol sftp -user $user -password $secure -remoteFolder $remoteFolder ) {
$files = Get-RemoteDir -server $server -protocol sftp -user $user -password $secure -remoteFolder $remoteFolder
if ($files) {
foreach ($file in $files) {
Remove-RemoteFile -server $server -protocol sftp -user $user -password $secure -remoteFolder $remoteFolder -remoteFile $file
}
}
Remove-RemoteFolder -server $server -protocol sftp -user $user -password $secure -remoteFolder $remoteFolder
}
}
catch {
}
}
function Update-FrontMatter {
param(
[Parameter(Mandatory=$true)]
[string]$frontMatter,
[Parameter(Mandatory=$true)]
[string]$variable,
[Parameter(Mandatory=$true)]
[string]$value
)
Write-Verbose -Message ('Starting: {0}' -f $myInvocation.Mycommand)
if ($frontMatter -match "${variable}: (.*)") {
if ($variable -ne 'weight') {
# If weight is specified in the document it should be used
$frontMatter = $frontMatter -replace "${variable}: (.*)", "${variable}: $value"
}
}
else {
$frontMatter += "`r`n$($variable): $value"
}
$frontMatter = $frontMatter.Replace("`r`n`r`n", "`r`n")
return $frontMatter
}
function Sync-MarkdownFiles {
param(
[Parameter(Mandatory=$true)]
[string]$sourceDir
,
[Parameter(Mandatory=$true)]
[string]$targetDir
,
[Parameter(Mandatory=$false)]
[int]$weight = 10
,
[Parameter(Mandatory=$false)]
[int]$chapterWeight = 10
)
Write-Verbose -Message ('Starting: {0}' -f $myInvocation.Mycommand)
# Readme.md on GitHub is the a chapter. In HUGO, which
# is used for online documentation, this page is named _index.md.
# Get all markdown files from the source (sorted) and target directory
$sourceFiles = Get-ChildItem -Path $SourceDir -Filter '*.md' | Sort-Object Name
$targetFiles = Get-ChildItem -Path $TargetDir -Recurse -Filter *.md
foreach ($sourceFile in $sourceFiles) {
# String to remove in all Readme.md files
[string]$hugoLinks = "> **Local links in this readme document do not work, they are rendered for online documentation in HUGO CMS.**`r`n"
# Read the contents of the source markdown file
$contentOrg = Get-Content -Path $sourceFile.FullName -Raw
# Create the target file path, but change the name of the chapter page for HUGO CMS
if ($sourceFile.Name -eq 'Readme.md') {
$content = $contentOrg.Replace($hugoLinks, '')
$targetFile = Join-Path -Path $TargetDir -ChildPath '_index.md'
} else {
$content = $contentOrg
$targetFile = Join-Path -Path $TargetDir -ChildPath $sourceFile.Name
}
# Identify local links
$localLinks = [regex]::Matches($content, '\]\((?!http|/)([^)]+)\)') | ForEach-Object { $_.Groups[1].Value }
foreach ($link in $localLinks) {
# Remove markdown in the name, because it will be an html folder after creation process in Hugo
$index = $link.LastIndexOf(".md")
if ($index -gt 0) {
$adjustedLink = $link.Substring(0, $index)
} else {
$adjustedLink = $link
}
$filePart = Split-Path -Leaf $adjustedLink
$parts = $link -split '#'
if($parts.Length -gt 1) {
$hashTag = '#' + $parts[1]
} else {
$hashTag = ""
}
$index = $adjustedLink.LastIndexOf("/")
if ($index -ne -1) {
$basePart = $adjustedLink.Substring(0, $index + 1)
} else {
$basePart = ''
}
if ($basePart) {
if (($basePart -eq '../docs/') -or ($basePart -eq './docs/')) {
$newBasePart = '../../Functions/'
} elseif (($basePart -eq '../appendix/') -or ($basePart -eq './appendix/')) {
$newBasePart = '/docs/Appendix/'
} elseif (($basePart -eq '../functions/') -or ($basePart -eq './functions/')) {
$newBasePart = '/docs/Functions/'
} elseif (($basePart -eq '../examples/') -or ($basePart -eq './examples/')) {
$newBasePart = '/docs/Examples/'
} elseif (($basePart -eq '../general/') -or ($basePart -eq './general/')) {
$newBasePart = '/docs/General/'
} elseif ($filePart.IndexOf('.') -ge 0) { # all media are going in the root
$newBasePart = "/"
} elseif ($filePart.IndexOf('Readme') -eq 0) { # allreadme links also with hash tag (#)
$newBasePart = "../../General/"
} elseif ($basePart -eq './') {
$newBasePart = '../'
} elseif ($basepart = "") {
$newBasePart = '/'
} else {
$newBasePart = '../'
}
} else {
$newBasePart = ''
}
$adjustedLink = $newBasePart + $filePart + $hashTag
try {
$content = $content -replace "\]\($link\)", "]($adjustedLink)"
}
catch {
Write-Error "Markdown: $sourceFile | Link: $link | NewLink: $adjustedLink | Exception: $_"
}
}
# Extract the file modification date in local time
$date = $sourceFile.LastWriteTime.ToString("yyyy-MM-dd HH:mm:ss")
if ($sourceFile.Name -eq 'Readme.md') {
[int]$fileWeight = $chapterWeight
} else {
[int]$fileWeight = $weight
}
# Matches FrontMatter by the the first occurrence of "---...---"
if ($content -match "(?s)(---\r?\n.*?\r?\n---)(.*)") {
$originalFrontMatter = $Matches[1]
$remainingContent = $Matches[2]
# Remove the "---" from the original FrontMatter, to get inner data
$originalFrontMatter = $originalFrontMatter -replace '---', ''
$originalFrontMatter = $originalFrontMatter.trim()
$originalFrontMatter = $originalFrontMatter.Replace("`r`n`r`n", "`r`n") # $originalFrontMatter -replace "^\r\n", ""
# Update 'lastMod' in FrontMatter with last file changed date
$frontMatter = Update-FrontMatter -FrontMatter $originalFrontMatter -Variable 'lastMod' -Value $date
# update 'weight' variable in FrontMatter
$frontMatter = Update-FrontMatter -FrontMatter $frontMatter -Variable 'weight' -Value $fileWeight
# Replace the original FrontMatter with the updated one
$content = "---`r`n$frontMatter`r`n---$remainingContent"
}
else {
# If there was no FrontMatter, add 'date' and 'weight'
$content = "---`r`nlastMod: $date`r`nweight: $fileWeight`r`n---`r`n`r`n$content"
}
# Leave some space in the order, but only if it is not a chapter page.
if ($sourceFile.Name -ne 'Readme.md') {
$weight += 10
}
# Write the content to the target file
$path = Split-Path $targetFile
if (-not (Test-Path $path)) {
New-Item -ItemType Directory -Path $path -Force | Out-Null
}
Set-Content -Path $targetFile -Value $content -NoNewline
# Remove the copied file from the targetFiles list
$targetFiles = $targetFiles | Where-Object { $_.FullName -ne $targetFile }
}
}
function ReleaseToGit {
Write-Verbose -Message ('Starting: {0}' -f $myInvocation.Mycommand)
Write-Host "Source to GitHub..."
Push-Location -StackName Github
Set-Location "$projectFolder"
git init
git add *
git commit -m "Final updates for version v$version"
git remote add origin https://github.com/Eulanda/EulandaConnect
git push origin master
# Create a new Release
[string]$Tag = "v$Version"
[string]$Release = gh release list --limit 1
if ($Release.IndexOf($Tag) -ge 0) {
Write-Warning "Release '$Tag' exists on GitHub and will be deleted prior to create a new one!"
gh release delete $tag
}
gh release create $Tag --notes "This version was also uploaded to PowerShell Gallery at 'https://www.powershellgallery.com/packages/EulandaConnect' on $(get-date)." --title "Final $Version"
Pop-Location -StackName Github
}
# *****************************************************************************
# Step 1
# *****************************************************************************
function Update-Manifest {
Write-Verbose -Message ('Starting: {0}' -f $myInvocation.Mycommand)
Write-Host "Project-Folder: $projectFolder"
Remove-Module -Name EulandaConnect -force -ErrorAction SilentlyContinue
if (Test-Path "$projectFolder\EulandaConnect.psd1") {
Remove-Item -Path "$projectFolder\EulandaConnect.psd1" -Force
}
$manifest= Get-Manifest -version $version -createDate $createDate -functionsToExport (Get-FunctionsToExport) -assetsFileList (Get-AssetsFileList -Developer)
$manifest | Set-Content -Path "$projectFolder\EulandaConnect.psd1" -Encoding UTF8 -Force
Import-Module "$projectFolder\eulandaConnect.psd1" -force -scope global
# Import-Module "$projectFolder\eulandaConnect.psd1" -force
}
# *****************************************************************************
# Step 2
# *****************************************************************************
function Update-Markdown {
Write-Verbose -Message ('Starting: {0}' -f $myInvocation.Mycommand)
Write-Host "Project-Folder: $projectFolder"
Import-Module -Name platyps -force
Remove-Module -Name EulandaConnect -force -ErrorAction SilentlyContinue
# UNINSTALL-MODULE is neccessary, because Update-MarkdownHelp takes after removing module tone of the installed versions
# The Problem occurs with Install-SignTool where the new parameter URL was not detected.
Uninstall-Module -Name EulandaConnect -AllVersions -Force -ErrorAction SilentlyContinue
Import-Module -Name "$projectFolder\EulandaConnect.psm1" -force
Update-MarkdownHelp -path "$projectFolder\docs\functions" -force
New-MarkdownHelp -Module EulandaConnect -OutputFolder "$projectFolder\docs\functions" -erroraction silentlycontinue
# Update-ReadmeTableOfContents # we don't need it any more (06/2023)
# Patch for PlatyPS due to the introduction of the -ProgressAction parameter in PowerShell 7.4
$path = "$projectFolder\docs\functions"
# Patch for PlatyPS due to the introduction of the -ProgressAction parameter in PowerShell 7.4
$path = "$projectFolder\docs\functions"
Get-ChildItem -Path $path -Filter *.md | ForEach-Object {
$content = Get-Content $_.FullName -Raw
$startPos = $content.IndexOf("### -ProgressAction")
if ($startPos -ne -1) {
$endPos = $content.IndexOf("### CommonParameters", $startPos)
if ($endPos -ne -1) {
# Correctly calculate the start of the content to be retained after "### CommonParameters"
# and ensure we are adding a newline before it to maintain formatting.
$newContent = $content.Substring(0, $startPos) + "`r`n" + $content.Substring($endPos)
Set-Content -Path $_.FullName -Value $newContent
}
}
}
}
# *****************************************************************************
# Step 3
# *****************************************************************************
function ConvertTo-Maml {
Write-Verbose -Message ('Starting: {0}' -f $myInvocation.Mycommand)
# Delete MAML help
if (Test-Path "$projectFolder\EulandaConnect-help.xml") {
Remove-Item -Path "$projectFolder\EulandaConnect-help.xml" -Force
}
# Get manifest for developer
$manifest= Get-Manifest -version $version -createDate $createDate -functionsToExport (Get-FunctionsToExport) -assetsFileList (Get-AssetsFileList -Developer)
$manifest | Set-Content -Path "$projectFolder\EulandaConnect.psd1" -Encoding UTF8 -Force
# Create a new MAML help from markdown, using this dummy module
Import-Module -Name platyps -force
Import-Module -Name "$projectFolder\EulandaConnect.psm1"
New-ExternalHelp $docFolder -OutputPath $projectFolder -force
# Copy MAML help file to FinalFolder
if (! (Test-Path "$finalFolder\EulandaConnect-help.xml")) {
Copy-Item -Path "$projectFolder\EulandaConnect-help.xml" -Force -Destination $finalFolder
}
}
# *****************************************************************************
# Step 4
# *****************************************************************************
function New-FinalImage {
Write-Verbose -Message ('Starting: {0}' -f $myInvocation.Mycommand)
Write-Host "Build final image into '$finalFolder'..."
# Delete all in FINAL
Remove-Item -Path "$finalFolder\*.*" -Force
# All assets to FINAL
Copy-Item -Path "$projectFolder\assets\*.*" -Force -Destination "$finalFolder"
# Put all ps1 files in one file on put it to FINAL
$moduleContent = Get-SourceFiles | ForEach-Object { $_.OpenText().ReadToEnd() }
$moduleContent | Out-File "$finalFolder\EulandaConnect.psm1" -Encoding UTF8BOM
# All resx resources to FINAL
Copy-Item -Path "$projectFolder\*.resx" -Force -Destination "$finalFolder"
# Get manifest for FINAL
$manifest= Get-Manifest -version $version -createDate $createDate -functionsToExport (Get-FunctionsToExport) -assetsFileList (Get-AssetsFileList)
$manifest | Set-Content -Path "$finalFolder\EulandaConnect.psd1" -Encoding UTF8 -Force
ConvertTo-Maml
Approve-Signature "$finalFolder\EulandaConnect.psm1"
Approve-Signature "$finalFolder\EulandaConnect.psd1"
}
# *****************************************************************************
# STEP 5
# *****************************************************************************
function Publish-ToPsGallery {
Write-Verbose -Message ('Starting: {0}' -f $myInvocation.Mycommand)
Write-Host "Publish to PowerShell Gallery..."
# Save location and go to PsGallery folder
Push-Location -StackName Publishing
Set-Location -Path $finalFolder
# To convert NuGet ApiKey to a SecureString serialized as an Xml file you need pwsh 7
# [string]$ecHomeFolder = "$home\.eulandaconnect"
# [string]$apiKey = "9fiewtYvkix2KcuQXpt2hVJ8r6BrZf4D7pdlGvsRGiHc0Rj"
# [securestring]$secureApiKey = ConvertTo-SecureString -String $apiKey -AsPlainText -Force
# $secureApiKey | Export-Clixml -Path "$ecHomeFolder\secureNuGetApiKey.xml"
# $finalFolder = "C:\Git\Powershell\EulandaConnect\final\EulandaConnect"
# Upload all to PsGallery
[securestring]$secureApiKey = Import-Clixml -Path "$ecHomeFolder\secureNuGetApiKey.xml"
[string]$apiKey = ConvertFrom-SecureString -SecureString $secureApiKey -AsPlainText # -AsPlainText needs pwsh 7
try {
Publish-Module -Path $finalFolder -NuGetApiKey $apiKey -force -SkipAutomaticTags
# Wait 30 seconds to see the module listed
Start-Sleep -Seconds 30
# wait 5 seconds
Find-Module -Name EulandaConnect
# Remove just created EulandaConnect modul from runtime
Remove-Module -Name EulandaConnect -force -ErrorAction SilentlyContinue
# Install new module
Install-Module -Name EulandaConnect -force
# Restore-Location
Pop-Location -StackName Publishing
# Upload all Updates and make an release
ReleaseToGit
# Open explorer in install path
explorer.exe "$home\Documents\PowerShell\Modules"
}
catch {
Throw "$myInvocation.Mycommand failed. $_"
}
}
# *****************************************************************************
# Step 6a+6b
# *****************************************************************************
function Invoke-BuildPester {
param (
[string[]]$tag,
[string[]]$excludeTag
)
Write-Verbose -Message ('Starting: {0}' -f $myInvocation.Mycommand)
# *****************
# Allowed tags
# *****************
# admin Tests that needs admin rights
# eulanda Tests that uses Eulanda specific functions
# ftp Tests that needs an ftp configured in pester.ini
# helper Tests from others folder
# https Tests that uses a internet connection for http or https
# hugo Tests that needs in installed hugo cms system
# input Tests that uses gui or read-host input
# integration Tests that general needs something installed
# mock Tests that uses mock and therefor the InModuleScope block
# openvpn Tests specific for openVPN
# registry Tests that uses the widnows registry
# sftp Tests that needs an sftp configured in pester.ini and installed PWSH-SSH module
# sql Tests that uses an local mssql server
# sqladmin Tests that needs sysadmin role for sql databse
# telegram Tests that uses telegram API and sends real messages
# token Tests that uses an local EV-Signing tokem (USB-Stick)
# *****************
# Prepare
# *****************
1..24 | ForEach-Object { Write-Host "" }
Write-Host "Preparation..."
Remove-Module EulandaConnect -ErrorAction SilentlyContinue
Import-Module .\EulandaConnect.psd1 -force
$iniPath = Resolve-Path ".\source\tests\pester.ini"
$ini = Read-IniFile -path $iniPath.Path
$udl = Resolve-Path ".\source\tests\Eulanda_1 Pester.udl"
# *****************
# Auto-exclude tags
# *****************
# No sftp server available
$ip = $ini['SFTP']['server']
$progressPreference = 'silentlyContinue'
[bool]$noSftp = (-not (Test-SftpPort -ip $ip))
$progressPreference = 'Continue'
if ($noSftp -and $excludeTag -notcontains 'sftp') {
$excludeTag += 'sftp'
}
# No ftp server available
$ip = $ini['SFTP']['server']
$progressPreference = 'silentlyContinue'
[bool]$noFtp = (-not (Test-SftpPort -ip $ip -port 21))
$progressPreference = 'Continue'
if ($noFtp -and $excludeTag -notcontains 'ftp') {
$excludeTag += 'ftp'
}
# No SmartCard or Token for signing available
[bool]$noToken = -not (Test-TokenAvailable)
if ($noToken -and $excludeTag -notcontains 'token') {
$excludeTag += 'token'
}
# No telegram send on normal builds flag is set in tasks.json
if ($noTelegram -and $excludeTag -notcontains 'telegram') {
$excludeTag += 'telegram'
}
# No admin rights
$noAdmin = -not (Test-Administrator)
if ($noAdmin -and $excludeTag -notcontains 'admin') {
$excludeTag += 'admin'
}
# No admin rights on sql server
$conn = Get-Conn -udl $udl
$sql = "SELECT IS_SRVROLEMEMBER('sysadmin')"
$result = $conn.Execute($sql)
if ($result.Fields.Item(0).Value -ne 1) {
if ($excludeTag -notcontains 'sqladmin') {
$excludeTag += 'sqladmin'
}
}
$conn.close()
# ************************
# Prepare test environment
# ************************
if ((! $excludeTag) -or $excludeTag -notcontains 'sftp') {
# Remove all under sftp /inbox
Remove-PesterSftpFolder
}
if ((! $excludeTag) -or $excludeTag -notcontains 'token') {
# Request passwordm first time only
Test-TokenPassword
}
# *****************
# Show used tags
# *****************
if ($tag -or $excludeTag) {
Write-Host "************************************************"
}
Write-Host "Including following test-cases:"
if ($tag) {
$tag
} else
{
Write-Host 'all'
}
Write-Host
if ($excludeTag) {
Write-Host "Excluding following test-cases:"
$excludeTag
}
if ($tag -or $excludeTag) {
Write-Host "************************************************"
}
# *****************
# Accept used tags
# *****************
# Check if there are any tags or excluded tags
if ($tag -or $excludeTag) {
$userResponse = Read-Host "Do you wish to continue with these tag settings? (y/n)"
if ($userResponse.Substring(0,1).ToUpper() -ne 'Y') {
Write-Host "Exiting pester tests due to user response"
return
}
}
# ************************
# Start Pester container
# ************************
$startDate = Get-Date
Write-Host "Started at: $startDate"
# Add variables as a hashtable to the container
$container = New-PesterContainer -Path .\source\test -Data @{noTelegram = $noTelegram}
$testResults = Invoke-Pester -Container $container -Output Detailed -Tag $tag -ExcludeTag $excludeTag -PassThru
$endDate = Get-Date
Write-Host "Finished at: $($endDate)"
1..3 | ForEach-Object { Write-Host "" }
# ************************
# Summary
# ************************
$testResults | Format-List -Property *
$duration = $endDate - $startDate
$minutes = [math]::Truncate($duration.TotalMinutes)
$seconds = [math]::Truncate($duration.TotalSeconds) % 60
Write-Host "Duration (minutes): $minutes`:$seconds"
}
# *****************************************************************************
# Step 7
# *****************************************************************************
function Update-OnlineDocs {
Write-Verbose -Message ('Starting: {0}' -f $myInvocation.Mycommand)
$sourceBase = "$PSScriptRoot\docs"
$targetBase = "C:\Git\Products\EulandaConnect-Hugo"
if (Test-path "$targetBase\content\docs") {
Remove-Item -Path "$targetBase\content\docs" -Recurse -Force
}
New-Item -ItemType Directory -Path "$targetBase\content\docs"
if ((Test-Path $targetBase)){
# The root in HUGOS did not have files in his folder
Sync-MarkdownFiles -SourceDir "$sourceBase\Readme.md" -TargetDir "$targetBase\content" -chapterWeight 10
Sync-MarkdownFiles -SourceDir "$sourceBase\general" -TargetDir "$targetBase\content\docs\General" -chapterWeight 10
Sync-MarkdownFiles -SourceDir "$sourceBase\functions" -TargetDir "$targetBase\content\docs\Functions" -chapterWeight 20
Sync-MarkdownFiles -SourceDir "$sourceBase\examples" -TargetDir "$targetBase\content\docs\Examples" -chapterWeight 30
Sync-MarkdownFiles -SourceDir "$sourceBase\appendix" -TargetDir "$targetBase\content\docs\Appendix"-chapterWeight 40
try {
Push-Location
Set-Location -Path $targetBase
if (Test-path "$targetBase\public") {
Remove-Item -Path "$targetBase\public" -Recurse -Force
}
New-Item -ItemType Directory -Path "$targetBase\public"