nl.nlsw.FileSystem.psm1

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
# __ _ ____ _ _ _ _ ____ ____ ____ ____ ____ ___ _ _ ____ ____ ____
# | \| |=== |/\| |___ | |--- |=== ==== [__] |--- | |/\| |--| |--< |===
#
# @file nl.nlsw.FileSystem.psm1
# @copyright Ernst van der Pols, Licensed under the EUPL-1.2-or-later
# @date 2022-10-21
#requires -version 5

class nlswFilesystem {

    # convert any (range of) invalid path characters to '_'
    static $invalidPathCharRegEx = [regex]"[$([string]([System.IO.Path]::GetInvalidPathChars()))\*\?]+"
    # convert any (range of) invalid filename characters to '_'
    static $invalidFileCharRegEx = [regex]"[$([string]([System.IO.Path]::GetInvalidFileNameChars()))\*\?]+"

    # Replace any (range of) invalid filename characters with an underscore to get a valid filename.
    # @param $filename the filename to validate
    # @return a valid filename
    static [string] GetValidFileName([string]$filename) {
        # convert any (range of) invalid filename characters to '_'
        $leaf = $filename | Split-Path -leaf
        $parent = $filename | Split-Path -parent
        return [System.IO.Path]::Combine([nlswFilesystem]::invalidPathCharRegEx.Replace($parent,"_"),[nlswFilesystem]::invalidFileCharRegEx.Replace($leaf,"_"));
    }

    static [bool] TestFileIsVersioned([string]$filename) {
        # run this test in the CurrentDirectory of the file system
        # @todo check this
        if (Test-Path $filename) {
            # ensure
            # get the svn stat info in verbose xml format
            $fileStat = [xml]$(svn stat --verbose --xml "$filename")
            # test if the file is not under version control
            #write-host $fileStat.status.target.entry."wc-status".item

            if (!$fileStat.status.target.entry -or
                (($fileStat.status.target.entry.path -eq $filename) -and
                 ($fileStat.status.target.entry."wc-status".item -eq "unversioned"))) {
                write-verbose " unversioned $filename"
                return $false
            }
            write-verbose " versioned $filename"
            return $true
        }
        # file does not exist
        write-verbose " new $filename"
        return $false
    }

    static [System.IO.FileInfo] MoveVersionedFile([System.IO.FileInfo]$oldFile, [string]$newFileName) {
        if ($oldFile.Name -ne $newFileName) {
            # get svn status of the old file
            $renamedFile = $null
            if ([nlswFilesystem]::TestFileIsVersioned($oldFile)) {
                write-verbose " (svn)renaming $($oldFile.Name) > $($newFileName)"
                push-location $oldFile.DirectoryName
                try {
                    svn move $oldFile.Name $newFileName
                    $renamedFile = get-item $newFileName
                }
                finally {
                    pop-location
                }
            }
            else {
                write-verbose " renaming $($oldFile.Name) > $($newFileName)"
                $renamedFile = Move-Item $oldFile.FullName $newFileName  -passThru #-WhatIf:$WhatIf
            }
            write-verbose " renamed $renamedFile"
            $oldFile = $renamedFile
        }
        return $oldFile
    }
}

<#
.SYNOPSIS
 Replace any (range of) invalid filename characters with an underscore '_' to get a valid filename.
 
.DESCRIPTION
 The function replaces any invalid filename character with an underscore.
 The path and filename parts of the input string are handled separately,
 since these have a slightly different set of invalid characters.
 
 The invalid characters are defined by the System.IO.Path class.
 
.PARAMETER Path
 The filename to make valid. May be piped.
 
.INPUT
 System.String
 
.OUTPUT
 System.String
#>

function Get-ValidFileName {
    [CmdletBinding()]
    [OutputType([System.String])]
    param (
        [Parameter(Mandatory=$true, ValueFromPipeline = $true, ValueFromPipelinebyPropertyName = $true)]
        [string]$Path
    )
    process {
        # convert any (range of) invalid filename characters to '_'
        [nlswFilesystem]::GetValidFileName($Path)
    }
}

<#
.SYNOPSIS
 Create a new unique output file name from the specified path.
 
.DESCRIPTION
 The input Path is expanded to an absolute path, the directory (folder) is
 created if not already exsiting, and the filename is made unique if
 necessary by appending "(<n>)" to the base filename, where "<n>" is
 a decimal number.
 
 Invalid filename characters in the input are replaced by an underscore '_'.
 
.PARAMETER Path
 The path to make a unique output file name from.
 
.PARAMETER AllowClobber
 Do not change the filename with an incremental index "(<n>)" in case the file already exists.
 When using this switch in a typical application, the existing file will be overwritten.
 
.INPUT
 System.String
 
.OUTPUT
 System.String
#>

function New-IncrementalFileName {
    [CmdletBinding(SupportsShouldProcess=$true, ConfirmImpact='Low')]
    [OutputType([System.String])]
    param (
        [Parameter(Mandatory=$true, ValueFromPipeline = $true, ValueFromPipelinebyPropertyName = $true)]
        [string]$Path,

        [Parameter(Mandatory=$false)]
        [switch]$AllowClobber
    )
    begin {
    }
    process {
        if ($PSCmdlet.ShouldProcess($Path)) {
            # convert any (range of) invalid filename characters to '_'
            # and determine absolute path, to avoid difference between Environment.CurrentDirectory i.s.o. $pwd
            $filepath = [System.IO.Path]::GetFullPath([System.IO.Path]::Combine($(Get-Location),[nlswFilesystem]::GetValidFileName($Path)))
            # create folder, if non-existing
            $filefolder = [System.IO.Path]::GetDirectoryName($filepath)
            if (!(test-path $filefolder)) {
                new-item -path $filefolder -itemtype Directory | out-null
            }
            # make output file unique with "(n)" extension
            if ((test-path $filepath) -and !$AllowClobber) {
                $name = [System.IO.Path]::GetFileNameWithoutExtension($filepath)
                $ext = [System.IO.Path]::GetExtension($filepath)
                $i = 0;
                do {
                    $i++
                    $filepath = [System.IO.Path]::Combine($filefolder,"$name($i)$ext")
                } while (test-path $filepath)
            }
            return $filepath
        }
    }
}

<#
.SYNOPSIS
 Create a new (temporary) folder in the specified base folder.
 
.DESCRIPTION
 The new folder has a GUID as name.
 
.PARAMETER Path
 The filesystem path name of the directory to create a temporary folder in.
 
.INPUTS
 System.String
 
.OUTPUTS
 System.IO.DirectoryInfo
#>

function New-TempFolder {
    [CmdletBinding(SupportsShouldProcess=$true, ConfirmImpact='Low')]
    [OutputType([System.IO.DirectoryInfo])]
    param (
        [Parameter(Mandatory=$false, ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true)]
        [string]$Path = "."
    )
    process {
        if ($PSCmdlet.ShouldProcess($Path)) {
            $Guid = [System.Guid]::NewGuid().ToString()
            $TempFolder = $(Join-Path $Path $Guid)
            return New-Item -Type Directory -Path $TempFolder
        }
    }
}

<#
.SYNOPSIS
 Remove the specified folder.
 
.DESCRIPTION
 Removes a (temporary) folder, created with New-TempFolder.
 Note that current implementation will remove any specified folder, and any files
 or subfolders it contains.
 
.PARAMETER Path
 The filesystem path name of the directory to remove.
 
.INPUTS
 System.String
#>

function Remove-TempFolder {
    [CmdletBinding(SupportsShouldProcess=$true, ConfirmImpact='Medium')]
    param (
        [Parameter(Mandatory=$false, ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true)]
        [string]$Path
    )
    process {
        if ($PSCmdlet.ShouldProcess($Path)) {
            Push-Location $Path
            Remove-Item '*.*' -Recurse -Force
            Pop-Location
            Remove-Item $Path
        }
    }
}

<#
.SYNOPSIS
 Remove a file system item to the recycle bin, with or without confirmation dialog.
 
.DESCRIPTION
 Replacement of Remove-Item in case you want a file or folder to be moved to the
 recycle bin. This function uses the VisualBasic operations of .NET for the implementation.
 
.PARAMETER Path
 The path name of the item(s) to remove.
 
.PARAMETER PassThru
 Outputs the FileSystemInfo object of the original item if the file system item has been removed
 to the recycle bin. NOTE that this item is no longer at its original location, so use the object with care.
 
.INPUTS
 System.String[]
 
.OUTPUTS
 System.IO.FileSystemInfo
 
.LINK
 https://www.powershellgallery.com/packages/Recycle/1.0.2/Content/Recycle.psm1
 
.NOTES
 This code is based on the Recycle PS module of Brian Dukes.
 This function supports the ShouldProcess feature https://vexx32.github.io/2018/11/22/Implementing-ShouldProcess/
#>

function Remove-ItemToRecycleBin {
    [CmdletBinding(SupportsShouldProcess=$true, ConfirmImpact='Medium')]
    [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSReviewUnusedParameter', 'PassThru', Justification="false positive")]
    [OutputType([System.IO.FileSystemInfo])]
    param (
        [Parameter(Mandatory=$true, Position=0, ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true)]
        [SupportsWildcards()]
        [ValidateNotNullOrEmpty()]
        [string[]]$Path,

        [Parameter(Mandatory=$false)]
        [switch]$PassThru
    )
    begin {
        $shell = new-object -comobject "Shell.Application"
    }
    process {
        $Path | Get-Item -ErrorAction "Stop" | foreach-object {
            $item = $_
            if ($PSCmdlet.ShouldProcess($item)) {
                $fullpath = $item.FullName
                $directoryPath = Split-Path $item -Parent
                $shellFolder = $shell.Namespace($directoryPath)
                $shellItem = $shellFolder.ParseName($item.Name)
                $shellItem.InvokeVerb("delete")

                if ($PassThru -and !(Test-Path $fullpath)) {
                    $item
                }
            }
        }
    }
    end {
    }
}

<#
.SYNOPSIS
 Rename or move a file that might be under under version control to another location.
 
.DESCRIPTION
 A file under version control requires certain operations to be handled via
 the version control interface, e.g. renaming and moving.
 
 Use this function to rename or move a file that might be under version control.
 
 Version control systems supported:
 - Subversion
 
.PARAMETER Path
 The path name of the file to rename or move. Wildcards are permitted.
 Use a dot '.' to specify the current location. The default is the current directory.
 Use the wildcard '*' to specify all items in the current location.
 
.PARAMETER Destination
 The path to the location where the items are to be moved. By default, the current directory.
 Wildcards are permitted, but the result must specify a single location.
 To rename the item being moved, specify a new name in the value of this parameter.
 
.PARAMETER PassThru
 Pass the object created through the pipeline.
 
.INPUTS
 string
 
.OUTPUTS
 System.IO.FileInfo
#>

function Move-VersionControlledFile {
    [CmdletBinding()]
    [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSReviewUnusedParameter', 'Destination', Justification="false positive")]
    [OutputType([System.IO.FileInfo])]
    param (
        [Parameter(Mandatory=$true, Position=0, ValueFromPipeline=$true)]
        [SupportsWildcards()]
        [ValidateNotNullOrEmpty()]
        [string]$Path,

        [Parameter(Mandatory=$true, Position=1, ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true)]
        [string]$Destination
    )
    begin {
    }
    process {
        $Path | get-item | foreach-object {
            [nlswFilesystem]::MoveVersionedFile($_, $Destination)
        }
    }
    end {
    }
}


<#
.SYNOPSIS
 Test if a file exists and is under version control.
 
.DESCRIPTION
 A file under version control requires certain operations to be handled via
 the version control interface, e.g. renaming.
 
 Use this function to test if a file exists and is under version control.
 
 Version control systems supported:
 - Subversion
 
.PARAMETER Path
 The path name of the file to test.
 
.INPUTS
 System.String[]
 
.OUTPUTS
 bool
#>

function Test-VersionControlledFile {
    [CmdletBinding()]
    param (
        [Parameter(Mandatory=$true, Position=0, ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true)]
        [SupportsWildcards()]
        [ValidateNotNullOrEmpty()]
        [string[]]$Path
    )
    begin {
    }
    process {
        $Path | get-item | foreach-object { [nlswFilesystem]::TestFileIsVersioned($_) }
    }
    end {
    }
}


Export-ModuleMember -Function *