Shaka Packager SDK
Loading...
Searching...
No Matches
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#include <cstddef>
10#include <cstdint>
11#include <functional>
12#include <string>
13
14#if defined(OS_WIN)
15#include <windows.h>
16#else
17#include <unistd.h>
18#endif
19
20#include <filesystem>
21#include <thread>
22
23#include <absl/strings/str_format.h>
24
25namespace shaka {
26namespace {
27// Create a temp file name using process id, thread id and current time.
28std::string TempFileName() {
29#if defined(OS_WIN)
30 const uint32_t process_id = static_cast<uint32_t>(GetCurrentProcessId());
31#else
32 const uint32_t process_id = static_cast<uint32_t>(getpid());
33#endif
34 const size_t thread_id =
35 std::hash<std::thread::id>{}(std::this_thread::get_id());
36
37 // We may need two or more temporary files in the same thread. There might be
38 // name collision if they are requested around the same time, e.g. called
39 // consecutively. Use a thread_local instance to avoid that.
40 static thread_local uint32_t instance_id = 0;
41 ++instance_id;
42
43 return absl::StrFormat("packager-tempfile-%x-%zx-%x", process_id, thread_id,
44 instance_id);
45}
46} // namespace
47
48bool TempFilePath(const std::string& temp_dir, std::string* temp_file_path) {
49 std::filesystem::path temp_dir_path;
50
51 if (temp_dir.empty()) {
52 temp_dir_path = std::filesystem::temp_directory_path();
53 } else {
54 temp_dir_path = std::filesystem::u8path(temp_dir);
55 }
56
57 *temp_file_path = (temp_dir_path / TempFileName()).string();
58 return true;
59}
60
61std::string MakePathRelative(const std::filesystem::path& media_path,
62 const std::filesystem::path& parent_path) {
63 auto relative_path = std::filesystem::relative(media_path, parent_path);
64 if (relative_path.empty() || *relative_path.begin() == "..") {
65 // Not related.
66 relative_path = media_path;
67 }
68
69 return relative_path.lexically_normal().generic_string();
70}
71
72} // namespace shaka
All the methods that are virtual are virtual for mocking.
bool TempFilePath(const std::string &temp_dir, std::string *temp_file_path)
Definition file_util.cc:48