Shaka Packager SDK
file_util.cc
1 // Copyright 2016 Google LLC. All rights reserved.
2 //
3 // Use of this source code is governed by a BSD-style
4 // license that can be found in the LICENSE file or at
5 // https://developers.google.com/open-source/licenses/bsd
6 
7 #include <packager/file/file_util.h>
8 
9 #if defined(OS_WIN)
10 #include <windows.h>
11 #else
12 #include <unistd.h>
13 #endif
14 
15 #include <filesystem>
16 #include <thread>
17 
18 #include <absl/strings/str_format.h>
19 
20 namespace shaka {
21 namespace {
22 // Create a temp file name using process id, thread id and current time.
23 std::string TempFileName() {
24 #if defined(OS_WIN)
25  const uint32_t process_id = static_cast<uint32_t>(GetCurrentProcessId());
26 #else
27  const uint32_t process_id = static_cast<uint32_t>(getpid());
28 #endif
29  const size_t thread_id =
30  std::hash<std::thread::id>{}(std::this_thread::get_id());
31 
32  // We may need two or more temporary files in the same thread. There might be
33  // name collision if they are requested around the same time, e.g. called
34  // consecutively. Use a thread_local instance to avoid that.
35  static thread_local uint32_t instance_id = 0;
36  ++instance_id;
37 
38  return absl::StrFormat("packager-tempfile-%x-%zx-%x", process_id, thread_id,
39  instance_id);
40 }
41 } // namespace
42 
43 bool TempFilePath(const std::string& temp_dir, std::string* temp_file_path) {
44  std::filesystem::path temp_dir_path;
45 
46  if (temp_dir.empty()) {
47  temp_dir_path = std::filesystem::temp_directory_path();
48  } else {
49  temp_dir_path = std::filesystem::u8path(temp_dir);
50  }
51 
52  *temp_file_path = (temp_dir_path / TempFileName()).string();
53  return true;
54 }
55 
56 std::string MakePathRelative(const std::filesystem::path& media_path,
57  const std::filesystem::path& parent_path) {
58  auto relative_path = std::filesystem::relative(media_path, parent_path);
59  if (relative_path.empty() || *relative_path.begin() == "..") {
60  // Not related.
61  relative_path = media_path;
62  }
63 
64  return relative_path.lexically_normal().generic_string();
65 }
66 
67 } // namespace shaka
All the methods that are virtual are virtual for mocking.
Definition: crypto_flags.cc:66
bool TempFilePath(const std::string &temp_dir, std::string *temp_file_path)
Definition: file_util.cc:43