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.nio.file.Path;
028import java.util.Collection;
029import java.util.stream.Collectors;
030import java.util.stream.Stream;
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 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(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   *   // Using platform-specific separators.
146   *   assertions.fileExists("foo/bar/baz.txt")...;
147   *
148   *   // Letting JCT infer the correct path separators to use (recommended).
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
154   * error.
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
163  public AbstractPathAssert<?> fileExists(String fragment, String... fragments) {
164    requireNonNull(fragment, "fragment must not be null");
165    requireNonNullValues(fragments, "fragments");
166
167    isNotNull();
168
169    var actualFile = actual.getFile(fragment, fragments);
170
171    if (actualFile != null) {
172      // File exists with this path. Hooray, lets return assertions on it.
173      return assertThat(actualFile);
174    }
175
176    throw createNoFileFoundFuzzyError(fragment, fragments);
177  }
178
179  private AssertionError createNoFileFoundFuzzyError(String fragment, String... fragments) {
180    var userInput = userProvidedPath(fragment, fragments);
181
182    var matchesString = uncheckedIo(actual::listAllFiles)
183        .entrySet()
184        .stream()
185        .flatMap(entry -> findFuzzyMatchesForContainer(
186            fuzzySafePath(combineOneOrMore(fragment, fragments)),
187            entry.getKey().getInnerPathRoot().getPath(),
188            entry.getValue()
189        ))
190        .map(Path::toString)
191        .map("\n  - "::concat)
192        .collect(Collectors.joining());
193
194    var locationName = LocationRepresentation.getInstance().toStringOf(actual.getLocation());
195
196    if (matchesString.isBlank()) {
197      return failure(
198          "No file named \"%s\" found in %s. No similar results found.",
199          userInput,
200          locationName
201      );
202    }
203
204    return failure(
205        "No file named \"%s\" found in %s. Found similar results:\n%s",
206        userInput,
207        locationName,
208        matchesString
209    );
210  }
211
212  private Stream<Path> findFuzzyMatchesForContainer(
213      String query,
214      Path rootPath,
215      Collection<Path> files
216  ) {
217    var relativeFiles = files.stream()
218        .map(rootPath::relativize)
219        // Filter out the root directory itself.
220        .filter(not(path -> path.toString().isBlank()))
221        .collect(Collectors.toSet());
222
223    return FuzzySearch
224        .extractSorted(query, relativeFiles, this::fuzzySafePath, FUZZY_MIN_SCORE)
225        .stream()
226        .limit(FUZZY_MAX_RESULTS)
227        .map(BoundExtractedResult::getReferent);
228  }
229
230  private String fuzzySafePath(Iterable<?> fragments) {
231    // We use the null byte to separate chunks of paths here to reduce the risk of ambiguity between
232    // file systems that use different naming systems and path separators. For the actual resultant
233    // representation, we just use the default path representation instead. This prevents
234    // the user inputting 'foo/bar' and it being considered totally different to 'bar\\foo' on
235    // the default file system on a Windows machine, for example.
236
237    var iterator = fragments.iterator();
238    if (!iterator.hasNext()) {
239      return "";
240    }
241
242    var builder = new StringBuilder();
243    builder.append(iterator.next());
244
245    while (iterator.hasNext()) {
246      builder.append('\0').append(iterator.next());
247    }
248
249    return builder.toString();
250  }
251
252  private String userProvidedPath(String fragment, String... fragments) {
253    return String.join("/", combineOneOrMore(fragment, fragments));
254  }
255}