View Javadoc
1   /*
2    * Licensed to the Apache Software Foundation (ASF) under one
3    * or more contributor license agreements.  See the NOTICE file
4    * distributed with this work for additional information
5    * regarding copyright ownership.  The ASF licenses this file
6    * to you under the Apache License, Version 2.0 (the
7    * "License"); you may not use this file except in compliance
8    * with the License.  You may obtain a copy of the License at
9    *
10   *   http://www.apache.org/licenses/LICENSE-2.0
11   *
12   * Unless required by applicable law or agreed to in writing,
13   * software distributed under the License is distributed on an
14   * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15   * KIND, either express or implied.  See the License for the
16   * specific language governing permissions and limitations
17   * under the License.
18   */
19  package org.apache.maven.cling.invoker;
20  
21  import java.nio.file.Files;
22  import java.nio.file.Path;
23  import java.util.function.Supplier;
24  
25  import org.apache.maven.api.annotations.Nonnull;
26  
27  import static java.util.Objects.requireNonNull;
28  
29  /**
30   * A thin wrapper for a {@link Path} that serves as "current working directory" value. Hence, this class
31   * is mutable (as CWD may be changed), but allows transition only to existing directories.
32   */
33  public final class CWD implements Supplier<Path> {
34      /**
35       * Creates instance out of {@link Path}.
36       */
37      public static CWD create(Path path) {
38          return new CWD(Utils.getCanonicalPath(path));
39      }
40  
41      private Path directory;
42  
43      private CWD(Path directory) {
44          this.directory = directory;
45      }
46  
47      @Nonnull
48      @Override
49      public Path get() {
50          return directory;
51      }
52  
53      /**
54       * Resolves against current cwd, resulting path is normalized.
55       *
56       * @throws NullPointerException if {@code seg} is {@code null}.
57       */
58      @Nonnull
59      public Path resolve(String seg) {
60          requireNonNull(seg, "seg");
61          return directory.resolve(seg).normalize();
62      }
63  
64      /**
65       * Changes current cwd, if the new path is existing directory.
66       *
67       * @throws NullPointerException if {@code seg} is {@code null}.
68       * @throws IllegalArgumentException if {@code seg} leads to non-existent directory.
69       */
70      public void change(String seg) {
71          Path newCwd = resolve(seg);
72          if (Files.isDirectory(newCwd)) {
73              this.directory = newCwd;
74          } else {
75              throw new IllegalArgumentException("Directory '" + directory + "' does not exist");
76          }
77      }
78  }