Skip to content
Snippets Groups Projects
Code owners
Assign users and groups as approvers for specific file changes. Learn more.
utils.h 1.97 KiB
/*
 * This file is a part of the CaosDB Project.
 *
 * Copyright (C) 2021 Timm Fitschen <t.fitschen@indiscale.com>
 * Copyright (C) 2021 IndiScale GmbH <info@indiscale.com>
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program. If not, see <https://www.gnu.org/licenses/>.
 *
 */

#ifndef UTILS_H
#define UTILS_H
#include <string_view>
#include <fstream>
#include <string>
#include <cstdlib>

namespace caosdb::utils {

/**
 * @brief Read a text file into a string and return the file's content.
 * @todo use boost-filesystem's "load_string_file"!
 */
inline auto load_string_file(const std::string &path) -> std::string {
  const auto path_view = std::string_view{path};
  constexpr auto size = std::size_t{4096};
  auto stream = std::ifstream{path_view.data()};
  stream.exceptions(std::ios_base::badbit);

  auto result = std::string();
  auto buffer = std::string(size, '\0');
  while (stream.read(&buffer[0], size)) {
    result.append(buffer, 0, stream.gcount());
  }
  result.append(buffer, 0, stream.gcount());
  return result;
}

/**
 * @brief Return the value of an environment variable or - if undefined - the
 * fall_back value.
 */
inline auto get_env_var(const std::string &key, const std::string &fall_back)
  -> const std::string {
  const char *val = getenv(key.c_str());
  if (val == nullptr) {
    return fall_back;
  } else {
    const auto result = std::string(val);
    return result;
  }
}

} // namespace caosdb::utils
#endif