std::string ReplaceExtension()

in tools/common/path_utils.cc [33:61]


std::string ReplaceExtension(const std::string &path,
                             const std::string &new_extension,
                             bool all_extensions) {
  auto last_slash = path.rfind('/');

  std::string::size_type dot;
  if (all_extensions) {
    // Find the first dot, signifying the first of all extensions.
    if (last_slash != std::string::npos) {
      dot = path.find('.', last_slash);
    } else {
      dot = path.find('.');
    }
  } else {
    // Find the last extension only.
    dot = path.rfind('.');
    if (dot < last_slash) {
      // If the dot was part of a previous path segment, treat it as if it
      // wasn't found (it's not an extension of the filename).
      dot = std::string::npos;
    }
  }

  // If there was no dot append the extension to the path.
  if (dot == std::string::npos) {
    return path + new_extension;
  }
  return path.substr(0, dot) + new_extension;
}