Add Javadoc comments to enhance code clarity
[cli-helper.git] / src / main / java / eu / svjatoslav / commons / cli_helper / parameter_parser / parameter / FileOption.java
1 /*
2  * Svjatoslav Commons - shared library of common functionality. Author: Svjatoslav Agejenko.
3  * This project is released under Creative Commons Zero (CC0) license.
4  */
5 package eu.svjatoslav.commons.cli_helper.parameter_parser.parameter;
6
7 import eu.svjatoslav.commons.cli_helper.parameter_parser.ParameterCount;
8 import eu.svjatoslav.commons.cli_helper.parameter_parser.Option;
9
10 import java.io.File;
11
12 /**
13  * This class represents commandline option which accepts exactly one parameter
14  * which is a file.
15  */
16 public class FileOption extends Option<File, FileOption> {
17
18     private ExistenceType existenceType = ExistenceType.DOES_NOT_MATTER;
19
20     public FileOption(final String description) {
21         super(description, ParameterCount.ONE);
22     }
23
24     protected static boolean validateFile(ExistenceType existenceType, String value) {
25         final File file = new File(value);
26
27         if (existenceType == ExistenceType.MUST_EXIST) {
28             return file.exists() && file.isFile();
29         }
30
31         if (existenceType == ExistenceType.MUST_NOT_EXIST) {
32             return !file.exists();
33         }
34
35         if (existenceType == ExistenceType.DOES_NOT_MATTER) {
36             if (file.exists())
37                 if (file.isDirectory())
38                     return false;
39
40             return true;
41         }
42
43         return false;
44     }
45
46     @Override
47     public java.lang.String describeFormat() {
48         switch (existenceType) {
49             case MUST_EXIST:
50                 return "Existing file.";
51             case MUST_NOT_EXIST:
52                 return "Non-existing file.";
53             default:
54                 return "File.";
55         }
56     }
57
58     @Override
59     public File getValue() {
60
61         if (parameters.size() != 1)
62             throw new RuntimeException("Parameter " + description
63                     + " shall have exactly 1 argument.");
64
65         return new File(parameters.get(0));
66     }
67
68     /**
69      * This method sets that file shall exist.
70      *
71      * @return This object.
72      */
73     public FileOption mustExist() {
74         existenceType = ExistenceType.MUST_EXIST;
75         return this;
76     }
77
78     /**
79      * This method sets that file shall not exist.
80      *
81      * @return This object.
82      */
83     public FileOption mustNotExist() {
84         existenceType = ExistenceType.MUST_NOT_EXIST;
85         return this;
86     }
87
88     @Override
89     public boolean isValid(final java.lang.String value) {
90         return validateFile(existenceType, value);
91     }
92
93 }