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 java.io.File;
028import java.nio.file.Files;
029import java.nio.file.Path;
030import java.util.stream.Collectors;
031import me.xdrop.fuzzywuzzy.FuzzySearch;
032import me.xdrop.fuzzywuzzy.model.BoundExtractedResult;
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 expectedFile = fragmentPathToString(fragment, fragments);
128    var actualFile = actual.getFile(fragment, fragments);
129
130    if (actualFile == null) {
131      return this;
132    }
133
134    var locationName = LocationRepresentation.getInstance().toStringOf(actual.getLocation());
135
136    throw failure(
137        "Expected path \"%s\" to not exist in \"%s\" but it was found at \"%s\"",
138        expectedFile,
139        locationName,
140        actualFile
141    );
142  }
143
144
145  /**
146   * Assert that the given file exists.
147   *
148   * <pre><code>
149   *   // Using platform-specific separators.
150   *   assertions.fileExists("foo/bar/baz.txt")...;
151   *
152   *   // Letting JCT infer the correct path separators to use (recommended).
153   *   assertions.fileExists("foo", "bar", "baz.txt");
154   * </code></pre>
155   *
156   * @param fragment  the first part of the path.
157   * @param fragments any additional parts of the path.
158   * @return assertions to perform on the path of the file that exists.
159   * @throws AssertionError       if the file does not exist, or if the container group is null.
160   * @throws NullPointerException if any of the fragments are null.
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 expectedFile = fragmentPathToString(fragment, fragments);
169    var actualFile = actual.getFile(fragment, fragments);
170
171    if (actualFile != null) {
172      return assertThat(actualFile);
173    }
174
175    var closestMatches = FuzzySearch
176        .extractSorted(
177            expectedFile,
178            actual
179                .getPackages()
180                .stream()
181                .flatMap(container -> uncheckedIo(() -> container
182                    .listAllFiles()
183                    .stream()
184                    .filter(not(Files::isDirectory))
185                    .map(container.getPathRoot().getPath()::relativize)
186                ))
187                .collect(Collectors.toList()),
188            Path::toString
189        )
190        .stream()
191        .limit(FUZZY_CUTOFF)
192        .map(BoundExtractedResult::getReferent)
193        .sorted()
194        .collect(Collectors.toList());
195
196    var locationName = LocationRepresentation.getInstance().toStringOf(actual.getLocation());
197
198    if (closestMatches.isEmpty()) {
199      throw failure("No file in %s files found named \"%s\"", locationName, expectedFile);
200    } else {
201      throw failure(
202          "No file named \"%s\" found in %s. Did you mean...%s",
203          expectedFile,
204          locationName,
205          closestMatches
206              .stream()
207              .map(Path::toString)
208              .map("\n\t - "::concat)
209              .collect(Collectors.joining())
210      );
211    }
212  }
213
214  private static String fragmentPathToString(String fragment, String... fragments) {
215    // Path#toString uses the default separator if we use Path#of
216    return String.join(File.separator, combineOneOrMore(fragment, fragments));
217  }
218}