1 /*
2  * Copyright (c) 2002-2019, the original author or authors.
3  *
4  * This software is distributable under the BSD license. See the terms of the
5  * BSD license in the documentation provided with this software.
6  *
7  * https://opensource.org/licenses/BSD-3-Clause
8  */
9 package jdk.internal.org.jline.reader;
10 
11 import java.io.IOException;
12 import java.nio.file.Path;
13 
14 public class ConfigurationPath {
15     private Path appConfig;
16     private Path userConfig;
17 
18     /**
19      * Configuration class constructor.
20      * @param appConfig   Application configuration directory
21      * @param userConfig  User private configuration directory
22      */
ConfigurationPath(Path appConfig, Path userConfig)23     public ConfigurationPath(Path appConfig, Path userConfig) {
24         this.appConfig = appConfig;
25         this.userConfig = userConfig;
26     }
27 
28     /**
29      * Search configuration file first from userConfig and then appConfig directory. Returns null if file is not found.
30      * @param  name    Configuration file name.
31      * @return         Configuration file.
32      *
33      */
getConfig(String name)34     public Path getConfig(String name) {
35         Path out = null;
36         if (userConfig != null && userConfig.resolve(name).toFile().exists()) {
37             out = userConfig.resolve(name);
38         } else if (appConfig != null && appConfig.resolve(name).toFile().exists()) {
39             out = appConfig.resolve(name);
40         }
41         return out;
42     }
43 
44     /**
45      * Search configuration file from userConfig directory. Returns null if file is not found.
46      * @param  name    Configuration file name.
47      * @return         Configuration file.
48      * @throws         IOException   When we do not have read access to the file or directory.
49      *
50      */
getUserConfig(String name)51     public Path getUserConfig(String name) throws IOException {
52         return getUserConfig(name, false);
53     }
54 
55     /**
56      * Search configuration file from userConfig directory. Returns null if file is not found.
57      * @param  name    Configuration file name
58      * @param  create  When true configuration file is created if not found.
59      * @return         Configuration file.
60      * @throws         IOException   When we do not have read/write access to the file or directory.
61      */
getUserConfig(String name, boolean create)62     public Path getUserConfig(String name, boolean create) throws IOException {
63         Path out = null;
64         if (userConfig != null) {
65             if (!userConfig.resolve(name).toFile().exists() && create) {
66                 userConfig.resolve(name).toFile().createNewFile();
67             }
68             if (userConfig.resolve(name).toFile().exists()) {
69                 out = userConfig.resolve(name);
70             }
71         }
72         return out;
73     }
74 
75 }
76