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

#include <cerrno>

#include "cmSystemTools.h"

cmWorkingDirectory::cmWorkingDirectory(std::string const& newdir)
{
  OldDir = cmSystemTools::GetCurrentWorkingDirectory();
  SetDirectory(newdir);
}

cmWorkingDirectory::~cmWorkingDirectory()
{
  Pop();
}

bool cmWorkingDirectory::SetDirectory(std::string const& newdir)
{
  if (cmSystemTools::ChangeDirectory(newdir) == 0) {
    ResultCode = 0;
    return true;
  }
  ResultCode = errno;
  return false;
}

void cmWorkingDirectory::Pop()
{
  if (!OldDir.empty()) {
    SetDirectory(OldDir);
    OldDir.clear();
  }
}
