Commit | Line | Data |
---|---|---|
b2441318 | 1 | // SPDX-License-Identifier: GPL-2.0 |
9a3993d4 | 2 | #include "path.h" |
fa0d9846 | 3 | #include "cache.h" |
9a3993d4 | 4 | #include <linux/kernel.h> |
175729fc | 5 | #include <limits.h> |
9a3993d4 | 6 | #include <stdio.h> |
fa0d9846 | 7 | #include <string.h> |
9a3993d4 ACM |
8 | #include <sys/types.h> |
9 | #include <sys/stat.h> | |
06c3f2aa | 10 | #include <dirent.h> |
9a3993d4 | 11 | #include <unistd.h> |
07800601 | 12 | |
07800601 IM |
13 | static char *cleanup_path(char *path) |
14 | { | |
15 | /* Clean it up */ | |
16 | if (!memcmp(path, "./", 2)) { | |
17 | path += 2; | |
18 | while (*path == '/') | |
19 | path++; | |
20 | } | |
21 | return path; | |
22 | } | |
23 | ||
370ce164 | 24 | char *mkpath(char *path_buf, size_t sz, const char *fmt, ...) |
07800601 IM |
25 | { |
26 | va_list args; | |
27 | unsigned len; | |
07800601 IM |
28 | |
29 | va_start(args, fmt); | |
370ce164 | 30 | len = vsnprintf(path_buf, sz, fmt, args); |
07800601 | 31 | va_end(args); |
370ce164 IR |
32 | if (len >= sz) |
33 | strncpy(path_buf, "/bad-path/", sz); | |
34 | return cleanup_path(path_buf); | |
07800601 | 35 | } |
9a3993d4 ACM |
36 | |
37 | int path__join(char *bf, size_t size, const char *path1, const char *path2) | |
38 | { | |
39 | return scnprintf(bf, size, "%s%s%s", path1, path1[0] ? "/" : "", path2); | |
40 | } | |
41 | ||
42 | int path__join3(char *bf, size_t size, const char *path1, const char *path2, const char *path3) | |
43 | { | |
44 | return scnprintf(bf, size, "%s%s%s%s%s", path1, path1[0] ? "/" : "", | |
45 | path2, path2[0] ? "/" : "", path3); | |
46 | } | |
47 | ||
48 | bool is_regular_file(const char *file) | |
49 | { | |
50 | struct stat st; | |
51 | ||
52 | if (stat(file, &st)) | |
53 | return false; | |
54 | ||
55 | return S_ISREG(st.st_mode); | |
56 | } | |
06c3f2aa JO |
57 | |
58 | /* Helper function for filesystems that return a dent->d_type DT_UNKNOWN */ | |
59 | bool is_directory(const char *base_path, const struct dirent *dent) | |
60 | { | |
61 | char path[PATH_MAX]; | |
62 | struct stat st; | |
63 | ||
41204da4 | 64 | snprintf(path, sizeof(path), "%s/%s", base_path, dent->d_name); |
06c3f2aa JO |
65 | if (stat(path, &st)) |
66 | return false; | |
67 | ||
68 | return S_ISDIR(st.st_mode); | |
69 | } | |
41204da4 | 70 | |
f76f94dc IR |
71 | bool is_directory_at(int dir_fd, const char *path) |
72 | { | |
73 | struct stat st; | |
74 | ||
75 | if (fstatat(dir_fd, path, &st, /*flags=*/0)) | |
76 | return false; | |
77 | ||
78 | return S_ISDIR(st.st_mode); | |
79 | } |