<commit_before>/*
 * Copyright 2016-present Facebook, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may
 * not use this file except in compliance with the License. You may obtain
 * a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations
 * under the License.
 */

package com.facebook.buck.doctor;

import static com.facebook.buck.log.MachineReadableLogConfig.PREFIX_EXIT_CODE;
import static com.facebook.buck.log.MachineReadableLogConfig.PREFIX_INVOCATION_INFO;

import com.facebook.buck.doctor.config.BuildLogEntry;
import com.facebook.buck.io.ProjectFilesystem;
import com.facebook.buck.model.BuildId;
import com.facebook.buck.util.BuckConstant;
import com.facebook.buck.util.MoreCollectors;
import com.facebook.buck.util.ObjectMappers;
import com.fasterxml.jackson.core.type.TypeReference;
import com.google.common.collect.ImmutableList;
import java.io.BufferedReader;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.FileVisitResult;
import java.nio.file.FileVisitor;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.OptionalInt;

/** Methods for finding and inspecting buck log files. */
public class BuildLogHelper {

  private final ProjectFilesystem projectFilesystem;

  private static final String INFO_FIELD_UNEXPANDED_CMD_ARGS = "unexpandedCommandArgs";

  public BuildLogHelper(ProjectFilesystem projectFilesystem) {
    this.projectFilesystem = projectFilesystem;
  }

  public ImmutableList<BuildLogEntry> getBuildLogs() throws IOException {
    // Remove commands with unknown args or invocations of buck rage.
    // Sort the remaining logs based on time, reverse order.
    ImmutableList.Builder<BuildLogEntry> logEntries = ImmutableList.builder();
    for (Path logFile : getAllBuckLogFiles()) {
      BuildLogEntry entry = newBuildLogEntry(logFile);
      if (entry.getCommandArgs().isPresent()
          && !entry.getCommandArgs().get().matches("^(rage|doctor|server|launch)\\b.*")) {
        logEntries.add(newBuildLogEntry(logFile));
      }
    }
    return logEntries
        .build()
        .stream()
        .sorted(Comparator.comparing(BuildLogEntry::getLastModifiedTime).reversed())
        .collect(MoreCollectors.toImmutableList());
  }

  @SuppressWarnings("unchecked")
  private BuildLogEntry newBuildLogEntry(Path logFile) throws IOException {
    BuildLogEntry.Builder builder = BuildLogEntry.builder();

    Path machineReadableLogFile =
        logFile.getParent().resolve(BuckConstant.BUCK_MACHINE_LOG_FILE_NAME);
    if (projectFilesystem.isFile(machineReadableLogFile)) {
      String invocationInfoLine =
          Files.lines(projectFilesystem.resolve(machineReadableLogFile))
              .filter(line -> line.startsWith(PREFIX_INVOCATION_INFO))
              .map(line -> line.substring(PREFIX_INVOCATION_INFO.length()))
              .findFirst()
              .get();

      // TODO(mikath): Keep this for a while for compatibility for commandArgs, then replace with
      // a proper ObjectMapper deserialization of InvocationInfo.
      Map<String, Object> invocationInfo =
          ObjectMappers.readValue(invocationInfoLine, new TypeReference<Map<String, Object>>() {});
      Optional<String> commandArgs = Optional.empty();
      if (invocationInfo.containsKey(INFO_FIELD_UNEXPANDED_CMD_ARGS)
          && invocationInfo.get(INFO_FIELD_UNEXPANDED_CMD_ARGS) instanceof List) {
        commandArgs =
            Optional.of(
                String.join(
                    " ", (List<String>) invocationInfo.get(INFO_FIELD_UNEXPANDED_CMD_ARGS)));<commit_msg>Fix a stream leak<commit_after>/*
 * Copyright 2016-present Facebook, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may
 * not use this file except in compliance with the License. You may obtain
 * a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations
 * under the License.
 */

package com.facebook.buck.doctor;

import static com.facebook.buck.log.MachineReadableLogConfig.PREFIX_EXIT_CODE;
import static com.facebook.buck.log.MachineReadableLogConfig.PREFIX_INVOCATION_INFO;

import com.facebook.buck.doctor.config.BuildLogEntry;
import com.facebook.buck.io.ProjectFilesystem;
import com.facebook.buck.model.BuildId;
import com.facebook.buck.util.BuckConstant;
import com.facebook.buck.util.MoreCollectors;
import com.facebook.buck.util.ObjectMappers;
import com.fasterxml.jackson.core.type.TypeReference;
import com.google.common.collect.ImmutableList;
import java.io.BufferedReader;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.FileVisitResult;
import java.nio.file.FileVisitor;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.OptionalInt;
import java.util.stream.Stream;

/** Methods for finding and inspecting buck log files. */
public class BuildLogHelper {

  private final ProjectFilesystem projectFilesystem;

  private static final String INFO_FIELD_UNEXPANDED_CMD_ARGS = "unexpandedCommandArgs";

  public BuildLogHelper(ProjectFilesystem projectFilesystem) {
    this.projectFilesystem = projectFilesystem;
  }

  public ImmutableList<BuildLogEntry> getBuildLogs() throws IOException {
    // Remove commands with unknown args or invocations of buck rage.
    // Sort the remaining logs based on time, reverse order.
    ImmutableList.Builder<BuildLogEntry> logEntries = ImmutableList.builder();
    for (Path logFile : getAllBuckLogFiles()) {
      BuildLogEntry entry = newBuildLogEntry(logFile);
      if (entry.getCommandArgs().isPresent()
          && !entry.getCommandArgs().get().matches("^(rage|doctor|server|launch)\\b.*")) {
        logEntries.add(newBuildLogEntry(logFile));
      }
    }
    return logEntries
        .build()
        .stream()
        .sorted(Comparator.comparing(BuildLogEntry::getLastModifiedTime).reversed())
        .collect(MoreCollectors.toImmutableList());
  }

  @SuppressWarnings("unchecked")
  private BuildLogEntry newBuildLogEntry(Path logFile) throws IOException {
    BuildLogEntry.Builder builder = BuildLogEntry.builder();

    Path machineReadableLogFile =
        logFile.getParent().resolve(BuckConstant.BUCK_MACHINE_LOG_FILE_NAME);
    if (projectFilesystem.isFile(machineReadableLogFile)) {
      String invocationInfoLine;
      try (Stream<String> logLines =
          Files.lines(projectFilesystem.resolve(machineReadableLogFile))) {
        invocationInfoLine =
            logLines
                .filter(line -> line.startsWith(PREFIX_INVOCATION_INFO))
                .map(line -> line.substring(PREFIX_INVOCATION_INFO.length()))
                .findFirst()
                .get();
      }

      // TODO(mikath): Keep this for a while for compatibility for commandArgs, then replace with
      // a proper ObjectMapper deserialization of InvocationInfo.
      Map<String, Object> invocationInfo =
          ObjectMappers.readValue(invocationInfoLine, new TypeReference<Map<String, Object>>() {});
      Optional<String> commandArgs = Optional.empty();
      if (invocationInfo.containsKey(INFO_FIELD_UNEXPANDED_CMD_ARGS)
          && invocationInfo.get(INFO_FIELD_UNEXPANDED_CMD_ARGS) instanceof List) {
        commandArgs =
            Optional.of(
                String.join(
                    " ", (List<String>) invocationInfo.get(INFO_FIELD_UNEXPANDED_CMD_ARGS)));
{'fraction_non_alphanumeric': 0.09576601014270551, 'fraction_numerical': 0.0018870149781813894, 'mean_word_length': 4.002949852507375, 'pattern_counts': {'":': 0, '<': 18, '<?xml version=': 0, '>': 22, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 2}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 2, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '5556394', 'n_tokens_mistral': 2406, 'n_tokens_neox': 2331, 'n_words': 553}