Shaka Packager SDK
Loading...
Searching...
No Matches
file_test_util.cc
1// Copyright 2022 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_test_util.h>
8
9#include <stdlib.h>
10
11#if defined(OS_WIN)
12#include <windows.h>
13#else
14#include <unistd.h>
15#endif
16
17#include <filesystem>
18#include <string>
19#include <system_error>
20
21namespace shaka {
22
23std::string generate_unique_temp_path() {
24 // Generate a unique name for a temporary file, using standard library
25 // routines, to avoid a circular dependency on any of our own code for
26 // generating temporary files. The template must end in 6 X's.
27 auto temp_path_template =
28 std::filesystem::temp_directory_path() / "packager-test.XXXXXX";
29 std::string temp_path_template_string = temp_path_template.string();
30#if defined(OS_WIN)
31 // _mktemp will modify the string passed to it to reflect the generated name
32 // (replacing the X characters with something else).
33 _mktemp(temp_path_template_string.data());
34#else
35 // mkstemp will create and open the file, modify the character points to
36 // reflect the generated name (replacing the X characters with something
37 // else), and return an open file descriptor. Then we close it and use the
38 // generated name.
39 int fd = mkstemp(temp_path_template_string.data());
40 close(fd);
41#endif
42 return temp_path_template_string;
43}
44
45void delete_file(const std::string& path) {
46 std::error_code ec;
47 std::filesystem::remove(std::filesystem::u8path(path), ec);
48 // Ignore errors.
49}
50
51TempFile::TempFile() : path_(generate_unique_temp_path()) {}
52
53TempFile::~TempFile() {
54 std::error_code ec;
55 std::filesystem::remove(std::filesystem::u8path(path_), ec);
56 // Ignore errors.
57}
58
59} // namespace shaka
All the methods that are virtual are virtual for mocking.