usage.cc 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. //
  2. // Copyright 2019 The Abseil Authors.
  3. //
  4. // Licensed under the Apache License, Version 2.0 (the "License");
  5. // you may not use this file except in compliance with the License.
  6. // You may obtain a copy of the License at
  7. //
  8. // https://www.apache.org/licenses/LICENSE-2.0
  9. //
  10. // Unless required by applicable law or agreed to in writing, software
  11. // distributed under the License is distributed on an "AS IS" BASIS,
  12. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. // See the License for the specific language governing permissions and
  14. // limitations under the License.
  15. #include "absl/flags/usage.h"
  16. #include <stdlib.h>
  17. #include <string>
  18. #include "absl/base/attributes.h"
  19. #include "absl/base/config.h"
  20. #include "absl/base/const_init.h"
  21. #include "absl/base/internal/raw_logging.h"
  22. #include "absl/base/thread_annotations.h"
  23. #include "absl/flags/internal/usage.h"
  24. #include "absl/strings/string_view.h"
  25. #include "absl/synchronization/mutex.h"
  26. namespace absl {
  27. ABSL_NAMESPACE_BEGIN
  28. namespace flags_internal {
  29. namespace {
  30. ABSL_CONST_INIT absl::Mutex usage_message_guard(absl::kConstInit);
  31. ABSL_CONST_INIT std::string* program_usage_message
  32. ABSL_GUARDED_BY(usage_message_guard) = nullptr;
  33. } // namespace
  34. } // namespace flags_internal
  35. // --------------------------------------------------------------------
  36. // Sets the "usage" message to be used by help reporting routines.
  37. void SetProgramUsageMessage(absl::string_view new_usage_message) {
  38. absl::MutexLock l(&flags_internal::usage_message_guard);
  39. if (flags_internal::program_usage_message != nullptr) {
  40. ABSL_INTERNAL_LOG(FATAL, "SetProgramUsageMessage() called twice.");
  41. std::exit(1);
  42. }
  43. flags_internal::program_usage_message = new std::string(new_usage_message);
  44. }
  45. // --------------------------------------------------------------------
  46. // Returns the usage message set by SetProgramUsageMessage().
  47. // Note: We able to return string_view here only because calling
  48. // SetProgramUsageMessage twice is prohibited.
  49. absl::string_view ProgramUsageMessage() {
  50. absl::MutexLock l(&flags_internal::usage_message_guard);
  51. return flags_internal::program_usage_message != nullptr
  52. ? absl::string_view(*flags_internal::program_usage_message)
  53. : "Warning: SetProgramUsageMessage() never called";
  54. }
  55. ABSL_NAMESPACE_END
  56. } // namespace absl