-
-
Notifications
You must be signed in to change notification settings - Fork 254
/
FilePathNotExistsAttributeBase.cs
71 lines (61 loc) · 2.61 KB
/
FilePathNotExistsAttributeBase.cs
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
// Copyright (c) Nate McMaster.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.ComponentModel.DataAnnotations;
using System.IO;
using McMaster.Extensions.CommandLineUtils.Abstractions;
namespace McMaster.Extensions.CommandLineUtils.Validation
{
/// <summary>
/// Base type for attributes that check for files or directories not existing.
/// </summary>
[AttributeUsage(AttributeTargets.Property)]
public abstract class FilePathNotExistsAttributeBase : ValidationAttribute
{
private readonly FilePathType _filePathType;
/// <summary>
/// Initializes an instance of <see cref="FilePathNotExistsAttributeBase"/>.
/// </summary>
/// <param name="filePathType">Acceptable file path types</param>
internal FilePathNotExistsAttributeBase(FilePathType filePathType)
: base(GetDefaultErrorMessage(filePathType))
{
_filePathType = filePathType;
}
/// <inheritdoc />
protected override ValidationResult? IsValid(object? value, ValidationContext validationContext)
{
if (value is not string path || path.Length == 0 || path.IndexOfAny(Path.GetInvalidPathChars()) >= 0)
{
return new ValidationResult(FormatErrorMessage(value?.ToString() ?? string.Empty));
}
if (!Path.IsPathRooted(path)
&& validationContext.GetService(typeof(CommandLineContext)) is CommandLineContext context)
{
path = Path.Combine(context.WorkingDirectory, path);
}
if ((_filePathType == FilePathType.File) && !File.Exists(path))
{
return ValidationResult.Success;
}
if ((_filePathType == FilePathType.Directory) && !Directory.Exists(path))
{
return ValidationResult.Success;
}
if ((_filePathType == FilePathType.Any) && !File.Exists(path) && !Directory.Exists(path))
{
return ValidationResult.Success;
}
return new ValidationResult(FormatErrorMessage(value?.ToString() ?? string.Empty));
}
private static string GetDefaultErrorMessage(FilePathType filePathType)
{
return filePathType switch
{
FilePathType.File => "The file '{0}' already exists.",
FilePathType.Directory => "The directory '{0}' already exists.",
_ => "The file path '{0}' already exists."
};
}
}
}