/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
   file Copyright.txt or https://cmake.org/licensing for details.  */

#include "cmStateDirectory.h"

#include <algorithm>
#include <cassert>
#include <vector>

#include <cm/iterator>
#include <cmext/algorithm>

#include "cmAlgorithms.h"
#include "cmProperty.h"
#include "cmPropertyMap.h"
#include "cmRange.h"
#include "cmState.h"
#include "cmStatePrivate.h"
#include "cmStateTypes.h"
#include "cmSystemTools.h"

static std::string const kBINARY_DIR = "BINARY_DIR";
static std::string const kBUILDSYSTEM_TARGETS = "BUILDSYSTEM_TARGETS";
static std::string const kSOURCE_DIR = "SOURCE_DIR";
static std::string const kSUBDIRECTORIES = "SUBDIRECTORIES";

void cmStateDirectory::ComputeRelativePathTopSource()
{
  // Relative path conversion inside the source tree is not used to
  // construct relative paths passed to build tools so it is safe to use
  // even when the source is a network path.

  cmStateSnapshot snapshot = Snapshot_;
  std::vector<cmStateSnapshot> snapshots;
  snapshots.push_back(snapshot);
  while (true) {
    snapshot = snapshot.GetBuildsystemDirectoryParent();
    if (snapshot.IsValid()) {
      snapshots.push_back(snapshot);
    } else {
      break;
    }
  }

  std::string result = snapshots.front().GetDirectory().GetCurrentSource();

  for (cmStateSnapshot const& snp : cmMakeRange(snapshots).advance(1)) {
    std::string currentSource = snp.GetDirectory().GetCurrentSource();
    if (cmSystemTools::IsSubDirectory(result, currentSource)) {
      result = currentSource;
    }
  }
  DirectoryState->RelativePathTopSource = result;
}

void cmStateDirectory::ComputeRelativePathTopBinary()
{
  cmStateSnapshot snapshot = Snapshot_;
  std::vector<cmStateSnapshot> snapshots;
  snapshots.push_back(snapshot);
  while (true) {
    snapshot = snapshot.GetBuildsystemDirectoryParent();
    if (snapshot.IsValid()) {
      snapshots.push_back(snapshot);
    } else {
      break;
    }
  }

  std::string result = snapshots.front().GetDirectory().GetCurrentBinary();

  for (cmStateSnapshot const& snp : cmMakeRange(snapshots).advance(1)) {
    std::string currentBinary = snp.GetDirectory().GetCurrentBinary();
    if (cmSystemTools::IsSubDirectory(result, currentBinary)) {
      result = currentBinary;
    }
  }

  // The current working directory on Windows cannot be a network
  // path.  Therefore relative paths cannot work when the binary tree
  // is a network path.
  if (result.size() < 2 || result.substr(0, 2) != "//") {
    DirectoryState->RelativePathTopBinary = result;
  } else {
    DirectoryState->RelativePathTopBinary.clear();
  }
}

std::string const& cmStateDirectory::GetCurrentSource() const
{
  return DirectoryState->Location;
}

void cmStateDirectory::SetCurrentSource(std::string const& dir)
{
  std::string& loc = DirectoryState->Location;
  loc = dir;
  cmSystemTools::ConvertToUnixSlashes(loc);
  loc = cmSystemTools::CollapseFullPath(loc);

  ComputeRelativePathTopSource();

  Snapshot_.SetDefinition("CMAKE_CURRENT_SOURCE_DIR", loc);
}

std::string const& cmStateDirectory::GetCurrentBinary() const
{
  return DirectoryState->OutputLocation;
}

void cmStateDirectory::SetCurrentBinary(std::string const& dir)
{
  std::string& loc = DirectoryState->OutputLocation;
  loc = dir;
  cmSystemTools::ConvertToUnixSlashes(loc);
  loc = cmSystemTools::CollapseFullPath(loc);

  ComputeRelativePathTopBinary();

  Snapshot_.SetDefinition("CMAKE_CURRENT_BINARY_DIR", loc);
}

std::string const& cmStateDirectory::GetRelativePathTopSource() const
{
  return DirectoryState->RelativePathTopSource;
}

std::string const& cmStateDirectory::GetRelativePathTopBinary() const
{
  return DirectoryState->RelativePathTopBinary;
}

void cmStateDirectory::SetRelativePathTopSource(const char* dir)
{
  DirectoryState->RelativePathTopSource = dir;
}

void cmStateDirectory::SetRelativePathTopBinary(const char* dir)
{
  DirectoryState->RelativePathTopBinary = dir;
}

bool cmStateDirectory::ContainsBoth(std::string const& local_path,
                                    std::string const& remote_path) const
{
  auto PathEqOrSubDir = [](std::string const& a, std::string const& b) {
    return (cmSystemTools::ComparePath(a, b) ||
            cmSystemTools::IsSubDirectory(a, b));
  };

  bool bothInBinary = PathEqOrSubDir(local_path, GetRelativePathTopBinary()) &&
    PathEqOrSubDir(remote_path, GetRelativePathTopBinary());

  bool bothInSource = PathEqOrSubDir(local_path, GetRelativePathTopSource()) &&
    PathEqOrSubDir(remote_path, GetRelativePathTopSource());

  return bothInBinary || bothInSource;
}

std::string cmStateDirectory::ConvertToRelPathIfNotContained(
  std::string const& local_path, std::string const& remote_path) const
{
  if (!ContainsBoth(local_path, remote_path)) {
    return remote_path;
  }
  return cmSystemTools::ForceToRelativePath(local_path, remote_path);
}

cmStateDirectory::cmStateDirectory(
  cmLinkedTree<cmStateDetail::BuildsystemDirectoryStateType>::iterator iter,
  const cmStateSnapshot& snapshot)
  : DirectoryState(iter)
  , Snapshot_(snapshot)
{
}

template <typename T, typename U>
cmStringRange GetPropertyContent(T const& content, U contentEndPosition)
{
  auto end = content.begin() + contentEndPosition;

  auto rbegin = cm::make_reverse_iterator(end);
  rbegin = std::find(rbegin, content.rend(), cmPropertySentinal);

  return cmMakeRange(rbegin.base(), end);
}

template <typename T, typename U, typename V>
cmBacktraceRange GetPropertyBacktraces(T const& content, U const& backtraces,
                                       V contentEndPosition)
{
  auto entryEnd = content.begin() + contentEndPosition;

  auto rbegin = cm::make_reverse_iterator(entryEnd);
  rbegin = std::find(rbegin, content.rend(), cmPropertySentinal);

  auto it = backtraces.begin() + std::distance(content.begin(), rbegin.base());

  auto end = backtraces.end();
  return cmMakeRange(it, end);
}

template <typename T, typename U, typename V>
void AppendEntry(T& content, U& backtraces, V& endContentPosition,
                 const std::string& value, const cmListFileBacktrace& lfbt)
{
  if (value.empty()) {
    return;
  }

  assert(endContentPosition == content.size());

  content.push_back(value);
  backtraces.push_back(lfbt);

  endContentPosition = content.size();
}

template <typename T, typename U, typename V>
void SetContent(T& content, U& backtraces, V& endContentPosition,
                const std::string& vec, const cmListFileBacktrace& lfbt)
{
  assert(endContentPosition == content.size());

  content.resize(content.size() + 2);
  backtraces.resize(backtraces.size() + 2);

  content.back() = vec;
  backtraces.back() = lfbt;

  endContentPosition = content.size();
}

template <typename T, typename U, typename V>
void ClearContent(T& content, U& backtraces, V& endContentPosition)
{
  assert(endContentPosition == content.size());

  content.resize(content.size() + 1);
  backtraces.resize(backtraces.size() + 1);

  endContentPosition = content.size();
}

cmStringRange cmStateDirectory::GetIncludeDirectoriesEntries() const
{
  return GetPropertyContent(DirectoryState->IncludeDirectories,
                            Snapshot_.Position->IncludeDirectoryPosition);
}

cmBacktraceRange cmStateDirectory::GetIncludeDirectoriesEntryBacktraces() const
{
  return GetPropertyBacktraces(DirectoryState->IncludeDirectories,
                               DirectoryState->IncludeDirectoryBacktraces,
                               Snapshot_.Position->IncludeDirectoryPosition);
}

void cmStateDirectory::AppendIncludeDirectoriesEntry(
  const std::string& vec, const cmListFileBacktrace& lfbt)
{
  AppendEntry(DirectoryState->IncludeDirectories,
              DirectoryState->IncludeDirectoryBacktraces,
              Snapshot_.Position->IncludeDirectoryPosition, vec, lfbt);
}

void cmStateDirectory::PrependIncludeDirectoriesEntry(
  const std::string& vec, const cmListFileBacktrace& lfbt)
{
  auto entryEnd = DirectoryState->IncludeDirectories.begin() +
    Snapshot_.Position->IncludeDirectoryPosition;

  auto rend = DirectoryState->IncludeDirectories.rend();
  auto rbegin = cm::make_reverse_iterator(entryEnd);
  rbegin = std::find(rbegin, rend, cmPropertySentinal);

  auto entryIt = rbegin.base();
  auto entryBegin = DirectoryState->IncludeDirectories.begin();

  auto btIt = DirectoryState->IncludeDirectoryBacktraces.begin() +
    std::distance(entryBegin, entryIt);

  DirectoryState->IncludeDirectories.insert(entryIt, vec);
  DirectoryState->IncludeDirectoryBacktraces.insert(btIt, lfbt);

  Snapshot_.Position->IncludeDirectoryPosition =
    DirectoryState->IncludeDirectories.size();
}

void cmStateDirectory::SetIncludeDirectories(const std::string& vec,
                                             const cmListFileBacktrace& lfbt)
{
  SetContent(DirectoryState->IncludeDirectories,
             DirectoryState->IncludeDirectoryBacktraces,
             Snapshot_.Position->IncludeDirectoryPosition, vec, lfbt);
}

void cmStateDirectory::ClearIncludeDirectories()
{
  ClearContent(DirectoryState->IncludeDirectories,
               DirectoryState->IncludeDirectoryBacktraces,
               Snapshot_.Position->IncludeDirectoryPosition);
}

cmStringRange cmStateDirectory::GetCompileDefinitionsEntries() const
{
  return GetPropertyContent(DirectoryState->CompileDefinitions,
                            Snapshot_.Position->CompileDefinitionsPosition);
}

cmBacktraceRange cmStateDirectory::GetCompileDefinitionsEntryBacktraces() const
{
  return GetPropertyBacktraces(DirectoryState->CompileDefinitions,
                               DirectoryState->CompileDefinitionsBacktraces,
                               Snapshot_.Position->CompileDefinitionsPosition);
}

void cmStateDirectory::AppendCompileDefinitionsEntry(
  const std::string& vec, const cmListFileBacktrace& lfbt)
{
  AppendEntry(DirectoryState->CompileDefinitions,
              DirectoryState->CompileDefinitionsBacktraces,
              Snapshot_.Position->CompileDefinitionsPosition, vec, lfbt);
}

void cmStateDirectory::SetCompileDefinitions(const std::string& vec,
                                             const cmListFileBacktrace& lfbt)
{
  SetContent(DirectoryState->CompileDefinitions,
             DirectoryState->CompileDefinitionsBacktraces,
             Snapshot_.Position->CompileDefinitionsPosition, vec, lfbt);
}

void cmStateDirectory::ClearCompileDefinitions()
{
  ClearContent(DirectoryState->CompileDefinitions,
               DirectoryState->CompileDefinitionsBacktraces,
               Snapshot_.Position->CompileDefinitionsPosition);
}

cmStringRange cmStateDirectory::GetCompileOptionsEntries() const
{
  return GetPropertyContent(DirectoryState->CompileOptions,
                            Snapshot_.Position->CompileOptionsPosition);
}

cmBacktraceRange cmStateDirectory::GetCompileOptionsEntryBacktraces() const
{
  return GetPropertyBacktraces(DirectoryState->CompileOptions,
                               DirectoryState->CompileOptionsBacktraces,
                               Snapshot_.Position->CompileOptionsPosition);
}

void cmStateDirectory::AppendCompileOptionsEntry(
  const std::string& vec, const cmListFileBacktrace& lfbt)
{
  AppendEntry(DirectoryState->CompileOptions,
              DirectoryState->CompileOptionsBacktraces,
              Snapshot_.Position->CompileOptionsPosition, vec, lfbt);
}

void cmStateDirectory::SetCompileOptions(const std::string& vec,
                                         const cmListFileBacktrace& lfbt)
{
  SetContent(DirectoryState->CompileOptions,
             DirectoryState->CompileOptionsBacktraces,
             Snapshot_.Position->CompileOptionsPosition, vec, lfbt);
}

void cmStateDirectory::ClearCompileOptions()
{
  ClearContent(DirectoryState->CompileOptions,
               DirectoryState->CompileOptionsBacktraces,
               Snapshot_.Position->CompileOptionsPosition);
}

cmStringRange cmStateDirectory::GetLinkOptionsEntries() const
{
  return GetPropertyContent(DirectoryState->LinkOptions,
                            Snapshot_.Position->LinkOptionsPosition);
}

cmBacktraceRange cmStateDirectory::GetLinkOptionsEntryBacktraces() const
{
  return GetPropertyBacktraces(DirectoryState->LinkOptions,
                               DirectoryState->LinkOptionsBacktraces,
                               Snapshot_.Position->LinkOptionsPosition);
}

void cmStateDirectory::AppendLinkOptionsEntry(const std::string& vec,
                                              const cmListFileBacktrace& lfbt)
{
  AppendEntry(DirectoryState->LinkOptions,
              DirectoryState->LinkOptionsBacktraces,
              Snapshot_.Position->LinkOptionsPosition, vec, lfbt);
}

void cmStateDirectory::SetLinkOptions(const std::string& vec,
                                      const cmListFileBacktrace& lfbt)
{
  SetContent(DirectoryState->LinkOptions,
             DirectoryState->LinkOptionsBacktraces,
             Snapshot_.Position->LinkOptionsPosition, vec, lfbt);
}

void cmStateDirectory::ClearLinkOptions()
{
  ClearContent(DirectoryState->LinkOptions,
               DirectoryState->LinkOptionsBacktraces,
               Snapshot_.Position->LinkOptionsPosition);
}

cmStringRange cmStateDirectory::GetLinkDirectoriesEntries() const
{
  return GetPropertyContent(DirectoryState->LinkDirectories,
                            Snapshot_.Position->LinkDirectoriesPosition);
}

cmBacktraceRange cmStateDirectory::GetLinkDirectoriesEntryBacktraces() const
{
  return GetPropertyBacktraces(DirectoryState->LinkDirectories,
                               DirectoryState->LinkDirectoriesBacktraces,
                               Snapshot_.Position->LinkDirectoriesPosition);
}

void cmStateDirectory::AppendLinkDirectoriesEntry(
  const std::string& vec, const cmListFileBacktrace& lfbt)
{
  AppendEntry(DirectoryState->LinkDirectories,
              DirectoryState->LinkDirectoriesBacktraces,
              Snapshot_.Position->LinkDirectoriesPosition, vec, lfbt);
}
void cmStateDirectory::PrependLinkDirectoriesEntry(
  const std::string& vec, const cmListFileBacktrace& lfbt)
{
  auto entryEnd = DirectoryState->LinkDirectories.begin() +
    Snapshot_.Position->LinkDirectoriesPosition;

  auto rend = DirectoryState->LinkDirectories.rend();
  auto rbegin = cm::make_reverse_iterator(entryEnd);
  rbegin = std::find(rbegin, rend, cmPropertySentinal);

  auto entryIt = rbegin.base();
  auto entryBegin = DirectoryState->LinkDirectories.begin();

  auto btIt = DirectoryState->LinkDirectoriesBacktraces.begin() +
    std::distance(entryBegin, entryIt);

  DirectoryState->LinkDirectories.insert(entryIt, vec);
  DirectoryState->LinkDirectoriesBacktraces.insert(btIt, lfbt);

  Snapshot_.Position->LinkDirectoriesPosition =
    DirectoryState->LinkDirectories.size();
}

void cmStateDirectory::SetLinkDirectories(const std::string& vec,
                                          const cmListFileBacktrace& lfbt)
{
  SetContent(DirectoryState->LinkDirectories,
             DirectoryState->LinkDirectoriesBacktraces,
             Snapshot_.Position->LinkDirectoriesPosition, vec, lfbt);
}

void cmStateDirectory::ClearLinkDirectories()
{
  ClearContent(DirectoryState->LinkDirectories,
               DirectoryState->LinkDirectoriesBacktraces,
               Snapshot_.Position->LinkDirectoriesPosition);
}

void cmStateDirectory::SetProperty(const std::string& prop, const char* value,
                                   cmListFileBacktrace const& lfbt)
{
  if (prop == "INCLUDE_DIRECTORIES") {
    if (!value) {
      ClearIncludeDirectories();
      return;
    }
    SetIncludeDirectories(value, lfbt);
    return;
  }
  if (prop == "COMPILE_OPTIONS") {
    if (!value) {
      ClearCompileOptions();
      return;
    }
    SetCompileOptions(value, lfbt);
    return;
  }
  if (prop == "COMPILE_DEFINITIONS") {
    if (!value) {
      ClearCompileDefinitions();
      return;
    }
    SetCompileDefinitions(value, lfbt);
    return;
  }
  if (prop == "LINK_OPTIONS") {
    if (!value) {
      ClearLinkOptions();
      return;
    }
    SetLinkOptions(value, lfbt);
    return;
  }
  if (prop == "LINK_DIRECTORIES") {
    if (!value) {
      ClearLinkDirectories();
      return;
    }
    SetLinkDirectories(value, lfbt);
    return;
  }

  DirectoryState->Properties.SetProperty(prop, value);
}

void cmStateDirectory::AppendProperty(const std::string& prop,
                                      const std::string& value, bool asString,
                                      cmListFileBacktrace const& lfbt)
{
  if (prop == "INCLUDE_DIRECTORIES") {
    AppendIncludeDirectoriesEntry(value, lfbt);
    return;
  }
  if (prop == "COMPILE_OPTIONS") {
    AppendCompileOptionsEntry(value, lfbt);
    return;
  }
  if (prop == "COMPILE_DEFINITIONS") {
    AppendCompileDefinitionsEntry(value, lfbt);
    return;
  }
  if (prop == "LINK_OPTIONS") {
    AppendLinkOptionsEntry(value, lfbt);
    return;
  }
  if (prop == "LINK_DIRECTORIES") {
    AppendLinkDirectoriesEntry(value, lfbt);
    return;
  }

  DirectoryState->Properties.AppendProperty(prop, value, asString);
}

cmProp cmStateDirectory::GetProperty(const std::string& prop) const
{
  const bool chain =
    Snapshot_.State->IsPropertyChained(prop, cmProperty::DIRECTORY);
  return GetProperty(prop, chain);
}

cmProp cmStateDirectory::GetProperty(const std::string& prop, bool chain) const
{
  static std::string output;
  output.clear();
  if (prop == "PARENT_DIRECTORY") {
    cmStateSnapshot parent = Snapshot_.GetBuildsystemDirectoryParent();
    if (parent.IsValid()) {
      return &parent.GetDirectory().GetCurrentSource();
    }
    return &output;
  }
  if (prop == kBINARY_DIR) {
    output = GetCurrentBinary();
    return &output;
  }
  if (prop == kSOURCE_DIR) {
    output = GetCurrentSource();
    return &output;
  }
  if (prop == kSUBDIRECTORIES) {
    std::vector<std::string> child_dirs;
    std::vector<cmStateSnapshot> const& children = DirectoryState->Children;
    child_dirs.reserve(children.size());
    for (cmStateSnapshot const& ci : children) {
      child_dirs.push_back(ci.GetDirectory().GetCurrentSource());
    }
    output = cmJoin(child_dirs, ";");
    return &output;
  }
  if (prop == kBUILDSYSTEM_TARGETS) {
    output = cmJoin(DirectoryState->NormalTargetNames, ";");
    return &output;
  }

  if (prop == "LISTFILE_STACK") {
    std::vector<std::string> listFiles;
    cmStateSnapshot snp = Snapshot_;
    while (snp.IsValid()) {
      listFiles.push_back(snp.GetExecutionListFile());
      snp = snp.GetCallStackParent();
    }
    std::reverse(listFiles.begin(), listFiles.end());
    output = cmJoin(listFiles, ";");
    return &output;
  }
  if (prop == "CACHE_VARIABLES") {
    output = cmJoin(Snapshot_.State->GetCacheEntryKeys(), ";");
    return &output;
  }
  if (prop == "VARIABLES") {
    std::vector<std::string> res = Snapshot_.ClosureKeys();
    cm::append(res, Snapshot_.State->GetCacheEntryKeys());
    std::sort(res.begin(), res.end());
    output = cmJoin(res, ";");
    return &output;
  }
  if (prop == "INCLUDE_DIRECTORIES") {
    output = cmJoin(GetIncludeDirectoriesEntries(), ";");
    return &output;
  }
  if (prop == "COMPILE_OPTIONS") {
    output = cmJoin(GetCompileOptionsEntries(), ";");
    return &output;
  }
  if (prop == "COMPILE_DEFINITIONS") {
    output = cmJoin(GetCompileDefinitionsEntries(), ";");
    return &output;
  }
  if (prop == "LINK_OPTIONS") {
    output = cmJoin(GetLinkOptionsEntries(), ";");
    return &output;
  }
  if (prop == "LINK_DIRECTORIES") {
    output = cmJoin(GetLinkDirectoriesEntries(), ";");
    return &output;
  }

  cmProp retVal = DirectoryState->Properties.GetPropertyValue(prop);
  if (!retVal && chain) {
    cmStateSnapshot parentSnapshot = Snapshot_.GetBuildsystemDirectoryParent();
    if (parentSnapshot.IsValid()) {
      return parentSnapshot.GetDirectory().GetProperty(prop, chain);
    }
    return Snapshot_.State->GetGlobalProperty(prop);
  }

  return retVal;
}

bool cmStateDirectory::GetPropertyAsBool(const std::string& prop) const
{
  return cmIsOn(GetProperty(prop));
}

std::vector<std::string> cmStateDirectory::GetPropertyKeys() const
{
  return DirectoryState->Properties.GetKeys();
}

void cmStateDirectory::AddNormalTargetName(std::string const& name)
{
  DirectoryState->NormalTargetNames.push_back(name);
}
