001/*
002 * Copyright (C) 2022 - 2023, the original author or authors.
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 *    http://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 */
016package io.github.ascopes.jct.assertions;
017
018import static io.github.ascopes.jct.utils.IoExceptionUtils.uncheckedIo;
019import static io.github.ascopes.jct.utils.IterableUtils.combineOneOrMore;
020import static io.github.ascopes.jct.utils.IterableUtils.requireNonNullValues;
021import static java.util.Objects.requireNonNull;
022import static java.util.function.Predicate.not;
023import static org.assertj.core.api.Assertions.assertThat;
024
025import io.github.ascopes.jct.containers.PackageContainerGroup;
026import io.github.ascopes.jct.repr.LocationRepresentation;
027import io.github.ascopes.jct.utils.StringUtils;
028import java.nio.file.Path;
029import java.util.Objects;
030import java.util.Set;
031import java.util.stream.Collectors;
032import java.util.stream.StreamSupport;
033import org.apiguardian.api.API;
034import org.apiguardian.api.API.Status;
035import org.assertj.core.api.AbstractPathAssert;
036import org.jspecify.annotations.Nullable;
037
038/**
039 * Assertions for package container groups.
040 *
041 * @author Ashley Scopes
042 * @since 0.0.1
043 */
044@API(since = "0.0.1", status = Status.STABLE)
045public final class PackageContainerGroupAssert
046    extends AbstractContainerGroupAssert<PackageContainerGroupAssert, PackageContainerGroup> {
047
048  /**
049   * Initialize the container group assertions.
050   *
051   * @param containerGroup the container group to assert upon.
052   */
053  public PackageContainerGroupAssert(@Nullable PackageContainerGroup containerGroup) {
054    super(containerGroup, PackageContainerGroupAssert.class);
055  }
056
057  /**
058   * Assert that all given files exist.
059   *
060   * @param path  the first path to check for
061   * @param paths additional paths to check for.
062   * @return this object for further call chaining.
063   * @throws AssertionError       if the container group is null, or if any of the files do not
064   *                              exist.
065   * @throws NullPointerException if any of the paths are null.
066   */
067  public PackageContainerGroupAssert allFilesExist(String path, String... paths) {
068    requireNonNull(path, "path must not be null");
069    requireNonNullValues(paths, "paths");
070
071    return allFilesExist(combineOneOrMore(path, paths));
072  }
073
074  /**
075   * Assert that all given files exist.
076   *
077   * @param paths paths to check for.
078   * @return this object for further call chaining.
079   * @throws AssertionError       if the container group is null, or if any of the files do not
080   *                              exist.
081   * @throws NullPointerException if any of the paths are null.
082   */
083  public PackageContainerGroupAssert allFilesExist(Iterable<String> paths) {
084    requireNonNullValues(paths, "paths");
085
086    isNotNull();
087
088    assertThat(paths).allSatisfy(this::fileExists);
089    return this;
090  }
091
092  /**
093   * Get assertions to perform on the class loader associated with this container group.
094   *
095   * @return the assertions to perform.
096   * @throws AssertionError if the container group is null.
097   */
098  public ClassLoaderAssert classLoader() {
099    isNotNull();
100
101    return new ClassLoaderAssert(actual.getClassLoader());
102  }
103
104  /**
105   * Assert that the given file does not exist.
106   *
107   * <pre><code>
108   *   // Using platform-specific separators.
109   *   assertions.fileDoesNotExist("foo/bar/baz.txt")...;
110   *
111   *   // Letting JCT infer the correct path separators to use (recommended).
112   *   assertions.fileDoesNotExist("foo", "bar", "baz.txt");
113   * </code></pre>
114   *
115   * @param fragment  the first part of the path.
116   * @param fragments any additional parts of the path.
117   * @return this assertion object for further assertions.
118   * @throws AssertionError       if the file exists, or if the container group is null.
119   * @throws NullPointerException if any of the fragments are null.
120   */
121  public PackageContainerGroupAssert fileDoesNotExist(String fragment, String... fragments) {
122    requireNonNull(fragment, "fragment must not be null");
123    requireNonNullValues(fragments, "fragments");
124
125    isNotNull();
126
127    var actualFile = actual.getFile(fragment, fragments);
128
129    if (actualFile == null) {
130      return this;
131    }
132
133    throw failure(
134        "Expected path \"%s\" to not exist in \"%s\" but it was found at \"%s\"",
135        userProvidedPath(combineOneOrMore(fragment, fragments)),
136        LocationRepresentation.getInstance().toStringOf(actual.getLocation()),
137        actualFile
138    );
139  }
140
141  /**
142   * Assert that the given file exists.
143   *
144   * <pre><code>
145   *   // Letting JCT infer the correct path separators to use (recommended).
146   *   assertions.fileExists("foo", "bar", "baz.txt");
147   *
148   *   // Using platform-specific separators (more likely to produce unexpected results).
149   *   assertions.fileExists("foo/bar/baz.txt")...;
150   * </code></pre>
151   *
152   * <p>If the file does not exist, then this object will attempt to find the
153   * closest matches and list them in an error message along with the assertion error.
154   *
155   * @param fragment  the first part of the path.
156   * @param fragments any additional parts of the path.
157   * @return assertions to perform on the path of the file that exists.
158   * @throws AssertionError       if the file does not exist, or if the container group is null.
159   * @throws NullPointerException if any of the fragments are null.
160   */
161
162  public AbstractPathAssert<?> fileExists(String fragment, String... fragments) {
163    requireNonNull(fragment, "fragment must not be null");
164    requireNonNullValues(fragments, "fragments");
165
166    isNotNull();
167
168    var actualFile = actual.getFile(fragment, fragments);
169
170    if (actualFile != null) {
171      // File exists with this path. Hooray, lets return assertions on it.
172      return assertThat(actualFile);
173    }
174
175    var expected = combineOneOrMore(fragment, fragments);
176    throw failure(StringUtils.resultNotFoundWithFuzzySuggestions(
177        fuzzySafePath(expected),
178        userProvidedPath(expected),
179        listAllUniqueFilesForAllContainers(),
180        this::fuzzySafePath,
181        this::userProvidedPath,
182        "path"
183    ));
184  }
185
186  private Set<Path> listAllUniqueFilesForAllContainers() {
187    return uncheckedIo(actual::listAllFiles)
188        .keySet()
189        .stream()
190        // Make all the files relative to their roots.
191        .flatMap(container -> uncheckedIo(container::listAllFiles)
192            .stream()
193            .map(container.getInnerPathRoot().getPath()::relativize))
194        // Filter out the inner path root itself, preventing few confusing issues with zero-length
195        // file names.
196        .filter(not(path -> path.getFileName().toString().isBlank()))
197        // Remove duplicates (don't think this can ever happen but this is just to be safe).
198        .collect(Collectors.toSet());
199  }
200
201  private <T> String userProvidedPath(Iterable<T> parts) {
202    return StreamSupport
203        .stream(parts.spliterator(), false)
204        .map(Objects::toString)
205        .collect(Collectors.joining("/"));
206  }
207
208  private <T> String fuzzySafePath(Iterable<T> parts) {
209    // Join on null bytes as we don't ever use those in normal path names. This way, we ignore
210    // file-system and OS-specific path separators creating ambiguities (like how Windows uses
211    // backslashes rather than forward slashes to delimit paths).
212    return StreamSupport
213        .stream(parts.spliterator(), false)
214        .map(Objects::toString)
215        .collect(Collectors.joining("\0"));
216  }
217}