// Copyright 2014 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.

package com.google.devtools.build.lib.analysis;

import com.google.devtools.build.lib.analysis.config.ConfigurationEnvironment;
import com.google.devtools.build.lib.analysis.config.InvalidConfigurationException;
import com.google.devtools.build.lib.cmdline.Label;
import com.google.devtools.build.lib.packages.AbstractAttributeMapper;
import com.google.devtools.build.lib.packages.BuildType;
import com.google.devtools.build.lib.packages.NoSuchThingException;
import com.google.devtools.build.lib.packages.Rule;
import com.google.devtools.build.lib.packages.Target;
import com.google.devtools.build.lib.syntax.Type;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import javax.annotation.Nullable;

/**
 * Tool for chasing filegroup redirects. This is mainly intended to be used during
 * BuildConfiguration creation.
 */
public final class RedirectChaser {

  /**
   * Custom attribute mapper that throws an exception if an attribute's value depends on the
   * build configuration.
   */
  private static class StaticValuedAttributeMapper extends AbstractAttributeMapper {
    public StaticValuedAttributeMapper(Rule rule) {
      super(rule.getPackage(), rule.getRuleClassObject(), rule.getLabel(),
          rule.getAttributeContainer());
    }

    /**
     * Returns the value of the given attribute.
     *
     * @throws InvalidConfigurationException if the value is configuration-dependent
     */
    public <T> T getAndValidate(String attributeName, Type<T> type)
        throws InvalidConfigurationException {
      if (getSelectorList(attributeName, type) != null) {
        throw new InvalidConfigurationException
            ("The value of '" + attributeName + "' cannot be configuration-dependent");
      }
      return super.get(attributeName, type);
    }
  }

  /**
   * Follows the 'srcs' attribute of the given label recursively. Keeps repeating as long as the
   * labels are filegroups with a single srcs entry.
   *
   * @param env for loading the packages
   * @param label the label to start at
   * @param name user-meaningful description of the content being resolved
   * @return the label which cannot be further resolved
   * @throws InvalidConfigurationException if something goes wrong
   */
  @Nullable
  public static Label followRedirects(ConfigurationEnvironment env, Label label, String name)
      throws InvalidConfigurationException, InterruptedException {
    Label oldLabel = null;
    Set<Label> visitedLabels = new HashSet<>();
    visitedLabels.add(label);
    try {
      while (true) {
        Target possibleRedirect = env.getTarget(label);
        if (possibleRedirect == null) {
          return null;
        }
        Label newLabel = getFilegroupRedirect(possibleRedirect);
        if (newLabel == null) {
          newLabel = getBindOrAliasRedirect(possibleRedirect);
        }
        if (newLabel == null) {
          return label;
        }

        newLabel = label.resolveRepositoryRelative(newLabel);
        oldLabel = label;
        label = newLabel;
        if (!visitedLabels.add(label)) {
          throw new InvalidConfigurationException("The " + name + " points to a filegroup which "
              + "recursively includes itself. The label " + label + " is part of the loop");
        }
      }
    } catch (NoSuchThingException e) {
      String prefix = oldLabel == null
          ? ""
          : "in target '" + oldLabel + "': ";
      throw new InvalidConfigurationException(prefix + e.getMessage(), e);
    }
  }

  private static Label getFilegroupRedirect(Target target) throws InvalidConfigurationException {
    if (!(target instanceof Rule)) {
      return null;
    }

    Rule rule = (Rule) target;
    if (!rule.getRuleClass().equals("filegroup")) {
      return null;
    }

    List<Label> labels =
        new StaticValuedAttributeMapper(rule).getAndValidate("srcs", BuildType.LABEL_LIST);
    if (labels.size() != 1) {
      return null;
    }

    return labels.get(0);
  }

  private static Label getBindOrAliasRedirect(Target target)
      throws InvalidConfigurationException {
    if (!(target instanceof Rule)) {
      return null;
    }

    Rule rule = (Rule) target;
    if (!rule.getRuleClass().equals("bind") && !rule.getRuleClass().equals("alias")) {
      return null;
    }

    return new StaticValuedAttributeMapper(rule).getAndValidate("actual", BuildType.LABEL);
  }
}

@@ -1255,31 +1255,8 @@
 et;%0A
-import java.util.List;%0A
 impo
@@ -1269,24 +1269,24 @@
 a.util.Set;%0A
+
 import javax
@@ -1332,26 +1332,16 @@
 chasing 
-filegroup 
 redirect
@@ -1355,15 +1355,8 @@
  is 
-mainly 
 inte
@@ -1381,18 +1381,10 @@
 ring
-%0A * BuildC
+ c
 onfi
@@ -2487,43 +2487,60 @@
 are 
-filegroups with a single srcs entry
+either %3Ccode%3Ealias%3C/code%3E or %3Ccode%3Ebind%3C/code%3E rules
 .%0A  
@@ -3293,101 +3293,8 @@
 el =
- getFilegroupRedirect(possibleRedirect);%0A        if (newLabel == null) %7B%0A          newLabel =
  get
@@ -3332,26 +3332,16 @@
 irect);%0A
-        %7D%0A
         
@@ -3634,25 +3634,20 @@
 ts to a 
-filegroup
+rule
  which %22
@@ -3680,14 +3680,16 @@
 ely 
-includ
+referenc
 es i
@@ -3970,24 +3970,24 @@
 sage(), e);%0A
+
     %7D%0A  %7D%0A%0A 
@@ -3989,482 +3989,8 @@
  %7D%0A%0A
-  private static Label getFilegroupRedirect(Target target) throws InvalidConfigurationException %7B%0A    if (!(target instanceof Rule)) %7B%0A      return null;%0A    %7D%0A%0A    Rule rule = (Rule) target;%0A    if (!rule.getRuleClass().equals(%22filegroup%22)) %7B%0A      return null;%0A    %7D%0A%0A    List%3CLabel%3E labels =%0A        new StaticValuedAttributeMapper(rule).getAndValidate(%22srcs%22, BuildType.LABEL_LIST);%0A    if (labels.size() != 1) %7B%0A      return null;%0A    %7D%0A%0A    return labels.get(0);%0A  %7D%0A%0A
   pr

Stop redirect chasing through filegroup() rules.