View Javadoc
1   /*
2    *    Copyright 2006-2023 the original author or authors.
3    *
4    *    Licensed under the Apache License, Version 2.0 (the "License");
5    *    you may not use this file except in compliance with the License.
6    *    You may obtain a copy of the License at
7    *
8    *       https://www.apache.org/licenses/LICENSE-2.0
9    *
10   *    Unless required by applicable law or agreed to in writing, software
11   *    distributed under the License is distributed on an "AS IS" BASIS,
12   *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13   *    See the License for the specific language governing permissions and
14   *    limitations under the License.
15   */
16  package org.mybatis.generator.internal;
17  
18  import static org.mybatis.generator.internal.util.messages.Messages.getString;
19  
20  import java.io.File;
21  import java.util.StringTokenizer;
22  
23  import org.mybatis.generator.api.ShellCallback;
24  import org.mybatis.generator.exception.ShellException;
25  
26  public class DefaultShellCallback implements ShellCallback {
27  
28      private final boolean overwrite;
29  
30      public DefaultShellCallback(boolean overwrite) {
31          super();
32          this.overwrite = overwrite;
33      }
34  
35      @Override
36      public File getDirectory(String targetProject, String targetPackage) throws ShellException {
37          // targetProject is interpreted as a directory that must already exist
38          //
39          // targetPackage is interpreted as a subdirectory, but in package
40          // format (with dots instead of slashes). The subdirectory will be
41          // created if it does not already exist
42  
43          File targetProjectDirectory = new File(targetProject);
44          if (!targetProjectDirectory.isDirectory()) {
45              throw new ShellException(getString("Warning.9", //$NON-NLS-1$
46                      targetProject));
47          }
48  
49          StringBuilder sb = new StringBuilder();
50          StringTokenizer st = new StringTokenizer(targetPackage, "."); //$NON-NLS-1$
51          while (st.hasMoreTokens()) {
52              sb.append(st.nextToken());
53              sb.append(File.separatorChar);
54          }
55  
56          File directory = new File(targetProjectDirectory, sb.toString());
57          if (!directory.isDirectory()) {
58              boolean rc = directory.mkdirs();
59              if (!rc) {
60                  throw new ShellException(getString("Warning.10", //$NON-NLS-1$
61                          directory.getAbsolutePath()));
62              }
63          }
64  
65          return directory;
66      }
67  
68      @Override
69      public boolean isOverwriteEnabled() {
70          return overwrite;
71      }
72  }