Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
67 changes: 36 additions & 31 deletions Application/FileConverter/PathHelpers.cs
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ public static class PathHelpers
private static Regex pathRegex = new Regex(@"^(?:\\\\[^\\/:*?""<>|\r\n]+\\|[a-zA-Z]:\\)(?:[^\\/:*?""<>|\r\n]+\\)*[^\.\\/:*?""<>|\r\n][^\\/:*?""<>|\r\n]*$");
private static Regex filenameRegex = new Regex(@"[^\\]*", RegexOptions.RightToLeft);
private static Regex directoryRegex = new Regex(@"^(?<drive>\\\\[^\\/:*?""""<>|\r\n]+\\|[A-Za-z]:\\)(?:(?<folders>[^\\]*)\\)*");
private static Regex dateRegex = new Regex(@"\(d:(?<format>[^)]*)\)");
private static Regex templateTokenRegex = new Regex(@"\((?:path|p|filename|f|F|outputext|o|O|inputext|i|I|p:(?:d|documents|m|music|v|videos|p|pictures)|[dD][0-9]+|n:[ic])\)|\(d:(?<format>[^)]*)\)");

public static bool IsPathDriveLetterValid(string path)
{
Expand Down Expand Up @@ -165,50 +165,55 @@ public static string GenerateFilePathFromTemplate(string inputFilePath, OutputTy

string[] directories = parentDirectory.Substring(0, parentDirectory.Length - 1).Split(System.IO.Path.DirectorySeparatorChar);

// Generate output path from template.
string outputPath = outputFilePathTemplate;

outputPath = outputPath.Replace("(path)", parentDirectory);
outputPath = outputPath.Replace("(p)", parentDirectory);

outputPath = outputPath.Replace("(filename)", fileName);
outputPath = outputPath.Replace("(f)", fileName);
outputPath = outputPath.Replace("(F)", fileName.ToUpperInvariant());

outputPath = outputPath.Replace("(outputext)", outputExtension);
outputPath = outputPath.Replace("(o)", outputExtension);
outputPath = outputPath.Replace("(O)", outputExtension.ToUpperInvariant());

outputPath = outputPath.Replace("(inputext)", inputExtension);
outputPath = outputPath.Replace("(i)", inputExtension);
outputPath = outputPath.Replace("(I)", inputExtension.ToUpperInvariant());
var replacements = new Dictionary<string, string>
{
{ "(path)", parentDirectory },
{ "(p)", parentDirectory },
{ "(filename)", fileName },
{ "(f)", fileName },
{ "(F)", fileName.ToUpperInvariant() },
{ "(outputext)", outputExtension },
{ "(o)", outputExtension },
{ "(O)", outputExtension.ToUpperInvariant() },
{ "(inputext)", inputExtension },
{ "(i)", inputExtension },
{ "(I)", inputExtension.ToUpperInvariant() },
{ "(n:i)", numberIndex.ToString() },
{ "(n:c)", numberMax.ToString() },
};

string myDocumentsFolder = System.Environment.GetFolderPath(System.Environment.SpecialFolder.MyDocuments) + "\\";
outputPath = outputPath.Replace("(p:d)", myDocumentsFolder);
outputPath = outputPath.Replace("(p:documents)", myDocumentsFolder);
replacements.Add("(p:d)", myDocumentsFolder);
replacements.Add("(p:documents)", myDocumentsFolder);

string myMusicFolder = System.Environment.GetFolderPath(System.Environment.SpecialFolder.MyMusic) + "\\";
outputPath = outputPath.Replace("(p:m)", myMusicFolder);
outputPath = outputPath.Replace("(p:music)", myMusicFolder);
replacements.Add("(p:m)", myMusicFolder);
replacements.Add("(p:music)", myMusicFolder);

string myVideoFolder = System.Environment.GetFolderPath(System.Environment.SpecialFolder.MyVideos) + "\\";
outputPath = outputPath.Replace("(p:v)", myVideoFolder);
outputPath = outputPath.Replace("(p:videos)", myVideoFolder);
replacements.Add("(p:v)", myVideoFolder);
replacements.Add("(p:videos)", myVideoFolder);

string myPictureFolder = System.Environment.GetFolderPath(System.Environment.SpecialFolder.MyPictures) + "\\";
outputPath = outputPath.Replace("(p:p)", myPictureFolder);
outputPath = outputPath.Replace("(p:pictures)", myPictureFolder);
replacements.Add("(p:p)", myPictureFolder);
replacements.Add("(p:pictures)", myPictureFolder);

for (int index = 0; index < directories.Length; index++)
{
outputPath = outputPath.Replace($"(d{directories.Length - index - 1})", directories[index]);
outputPath = outputPath.Replace($"(D{directories.Length - index - 1})", directories[index].ToUpperInvariant());
replacements.Add($"(d{directories.Length - index - 1})", directories[index]);
replacements.Add($"(D{directories.Length - index - 1})", directories[index].ToUpperInvariant());
}

outputPath = outputPath.Replace("(n:i)", numberIndex.ToString());
outputPath = outputPath.Replace("(n:c)", numberMax.ToString());
// Match only the original template. Inserted filenames and folders are literal data.
string outputPath = templateTokenRegex.Replace(outputFilePathTemplate, match =>
{
if (match.Groups["format"].Success)
{
return DateTime.Now.ToString(match.Groups["format"].Value).Replace('/', '-').Replace(':', '\'');
}

outputPath = dateRegex.Replace(outputPath, match => DateTime.Now.ToString(match.Groups["format"].Value).Replace('/', '-').Replace(':', '\''));
return replacements.TryGetValue(match.Value, out string replacement) ? replacement : match.Value;
});

outputPath += "." + outputExtension;

Expand Down
35 changes: 35 additions & 0 deletions Tests/PathHelpers.Regression.ps1
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
param([Parameter(Mandatory=$true)][string]$Executable)
$ErrorActionPreference='Stop'
$assembly=[Reflection.Assembly]::LoadFrom((Resolve-Path $Executable).Path)
$method=$assembly.GetType('FileConverter.PathHelpers').GetMethod('GenerateFilePathFromTemplate')
$pdf=[Enum]::Parse($assembly.GetType('FileConverter.OutputType'),'Pdf')
$script:count=0
$script:failures=0
function Check($label,$inputPath,$template,$expected) {
$actual=$method.Invoke($null,@($inputPath,$pdf,$template,3,12))
$script:count++
if($actual -cne $expected) { $script:failures++; "FAIL $label`n expected: $expected`n actual: $actual" }
else { "PASS $label => $actual" }
}
Check 'issue797' 'C:\work\99 (O) my file.jpg' '(p)(f)' 'C:\work\99 (O) my file.pdf'
foreach($token in '(O)','(o)','(i)','(I)','(d0)','(D0)','(filename)','(f)','(F)') {
Check "filename literal $token" "C:\work\99 $token my file.jpg" '(p)(f)' "C:\work\99 $token my file.pdf"
Check "folder literal $token" "C:\work $token\plain.jpg" '(p)(f)' "C:\work $token\plain.pdf"
}
Check 'explicit tokens and aliases' 'C:\work\photo.JPG' '(path)(filename)-(outputext)-(o)-(O)-(inputext)-(i)-(I)-(n:i)-(n:c)' 'C:\work\photo-pdf-pdf-PDF-JPG-JPG-JPG-3-12.pdf'
Check 'uppercase filename preserves tokens' 'C:\work\my (o) file.jpg' '(p)(F)' 'C:\work\MY (O) FILE.pdf'
Check 'directory indices' 'C:\first\second\photo.jpg' '(d2)\(d1)\(D0)\(f)' 'C:\first\SECOND\photo.pdf'
Check 'inserted directory stays literal' 'C:\first\(O)\photo.jpg' '(d0)\(f)' '(O)\photo.pdf'
Check 'unknown and out of range tokens' 'C:\work\photo.jpg' '(unknown)-(d99)-(d00)-(N:i)-(f)' '(unknown)-(d99)-(d00)-(N:i)-photo.pdf'
Check 'repeated tokens' 'C:\work\(O).jpg' '(f)-(f)-(O)' '(O)-(O)-PDF.pdf'
Check 'empty default template' 'C:\work\(O).jpg' '' 'C:\work\(O).pdf'
Check 'empty input' '' '(p)(f)' 'Invalid input file path (argument 0).'
Check 'date in template' 'C:\work\photo.jpg' '(d:yyyy)-(f)' "$([DateTime]::Now.ToString('yyyy'))-photo.pdf"
Check 'date format output is literal' 'C:\work\photo.jpg' "(d:'(O')" '(O.pdf'
foreach($pair in @(@('d','documents','MyDocuments'),@('m','music','MyMusic'),@('v','videos','MyVideos'),@('p','pictures','MyPictures'))) {
$folder=[Environment]::GetFolderPath([Environment+SpecialFolder]::$($pair[2]))+'\'
Check "special folder $($pair[1])" 'C:\work\photo.jpg' "(p:$($pair[0]))(f)" ($folder+'photo.pdf')
Check "special folder alias $($pair[1])" 'C:\work\photo.jpg' "(p:$($pair[1]))(f)" ($folder+'photo.pdf')
}
"RESULT: $count checks; $failures failures"
if($failures) { exit 1 }