1 module clid.validate;
2 
3 import std.stdio : stderr;
4 import std.traits : FunctionTypeOf, Parameters;
5 
6 /**
7  * Validates a command line argument.
8  */
9 bool Validate(alias f)(string arg, int n) @property // @suppress(dscanner.style.phobos_naming_convention)
10 if (is(FunctionTypeOf!(f) == function) && is(Parameters!(f)[1] == int))
11 {
12 	return f(arg, n);
13 }
14 
15 /**
16  * Validates a command line argument.
17  */
18 bool Validate(alias f)(string arg, string str) @property // @suppress(dscanner.style.phobos_naming_convention)
19 if (is(FunctionTypeOf!(f) == function) && is(Parameters!(f)[1] == string))
20 {
21 	return f(arg, str);
22 }
23 
24 /**
25  * Validates that the string is not empty.
26  */
27 bool isNotEmpty(string arg, string str)
28 {
29 	if (str.length == 0)
30 	{
31 		stderr.writeln("Argument " ~ arg ~ " must not be empty string");
32 		return false;
33 	}
34 	return true;
35 }
36 
37 /**
38  * Validates that argument refers to a valid file.
39  */
40 bool isFile(string arg, string str)
41 {
42 	import std.file : exists, fileIsFile = isFile;
43 
44 	if (!str.exists || !str.fileIsFile)
45 	{
46 		stderr.writeln("Argument " ~ arg ~ " must refer to a file that exists");
47 		return false;
48 	}
49 	return true;
50 }
51 
52 /**
53  * Validates that argument refers to a valid directory.
54  */
55 bool isDir(string arg, string str)
56 {
57 	import std.file : exists, dirIsDir = isDir;
58 
59 	if (!str.exists || !str.dirIsDir)
60 	{
61 		stderr.writeln("Argument " ~ arg ~ " must refer to a directory that exists");
62 		return false;
63 	}
64 	return true;
65 }
66 
67 /**
68  * Validates that the argument does not refer to anything on the filesystem.
69  */
70 bool doesNotExist(string arg, string str)
71 {
72 	import std.file : exists;
73 
74 	if (str.exists)
75 	{
76 		stderr.writeln("Argument " ~ arg ~ " must not refer to a file that already exists");
77 		return false;
78 	}
79 	return true;
80 }