// Copyright 2024 The Bazel Authors. All rights reserved.
//
// 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.

#include "src/tools/one_version/one_version.h"

#include <string>
#include <vector>

#include "absl/log/die_if_null.h"
#include "absl/strings/match.h"
#include "absl/strings/string_view.h"
#include "absl/strings/strip.h"
#include "src/tools/one_version/duplicate_class_collector.h"
#include "src/tools/singlejar/zip_headers.h"

namespace one_version {

// Record the jar entry (if it's a class file).
void OneVersion::Add(absl::string_view file_name_of_entry, const CDH *jar_entry,
                     const Label &label) {
  if (absl::ConsumeSuffix(&file_name_of_entry, ".class")) {
    if (
        // module-info.class is a Java 9 Module specifier, and isn't a
        // normal class. We expect it to be at the top of the jar or under
        // META-INF/versions/{numeral} in a multi-release JAR.
        file_name_of_entry != "module-info" &&
        !(absl::StartsWith(file_name_of_entry, "META-INF/versions/") &&
          absl::EndsWith(file_name_of_entry, "/module-info")) &&
        // R.class and R$....class should be removed from analysis as they
        // are android resources, and are re-processed during the android
        // binary build.
        !absl::EndsWith(file_name_of_entry, "/R") &&
        !absl::StrContains(file_name_of_entry, "/R$") &&
        // BR.class should be removed from analysis as it is a special class
        // generated by Android databinding, and is re-processed during the
        // android binary build. Once the depot is migrated to Android
        // databinding v2 (see b/73782031), this will no longer be necessary.
        !absl::EndsWith(file_name_of_entry, "/BR")) {
      duplicate_class_collector_.Add(std::string(file_name_of_entry),
                                     ABSL_DIE_IF_NULL(jar_entry)->crc32(),
                                     label);
    }
  }
}

std::vector<one_version::Violation> OneVersion::Report() {
  return whitelist_file_->Apply(duplicate_class_collector_.Violations());
}

}  // namespace one_version
