Logo (Windows): supports glob and environment variables in source paths

This commit is contained in:
Carter Li committed 2026-11-15 12:00:17 +08:00
1 parent aef14850a1
commit 73368d36d9
11 files changed
+718 -22

No files matched your search

+3
View File
@@ -1,5 +1,8 @@
# Unreleased
Features:
* Added glob and environment variable expansion to logo sources on Windows. `%VAR%`, `$VAR` and `${VAR}` are supported, and a glob matching several files picks one randomly. (#2718, Logo, Windows)
Changes:
* Improved PCI GPU name resolution by checking udev's hardware database and the NVIDIA driver's procfs before falling back to pci.ids. (GPU, Linux)
+13
View File
@@ -1148,6 +1148,7 @@ elseif(WIN32)
src/common/windows/getline.c
src/common/windows/com.c
src/common/windows/folders.c
src/common/windows/glob.c
src/common/windows/registry.c
src/common/windows/unicode.c
src/common/windows/variant.cpp
@@ -2371,6 +2372,15 @@ if (BUILD_TESTS)
PRIVATE libfastfetch
)
if (WIN32)
add_executable(fastfetch-test-glob
tests/glob.c
)
target_link_libraries(fastfetch-test-glob
PRIVATE libfastfetch
)
endif()
add_executable(fastfetch-test-spin
tests/spin.c
)
@@ -2507,6 +2517,9 @@ if (BUILD_TESTS)
enable_testing()
add_test(NAME test-cache COMMAND fastfetch-test-cache)
add_test(NAME test-logo COMMAND fastfetch-test-logo)
if (WIN32)
add_test(NAME test-glob COMMAND fastfetch-test-glob)
endif()
add_test(NAME test-spin COMMAND fastfetch-test-spin)
add_test(NAME test-strbuf COMMAND fastfetch-test-strbuf)
add_test(NAME test-list COMMAND fastfetch-test-list)
+1 -1
View File
@@ -176,7 +176,7 @@
"short": "l",
"long": "logo",
"desc": "Set the logo source. Use \"none\" to disable logo output",
"remark": "Use either a built-in logo name or a path to an image file. See also https://github.com/fastfetch-cli/fastfetch/wiki/Logo-options",
"remark": "Use either a built-in logo name or a path to an image file. Environment variables and glob patterns are expanded; if several files match a glob, one is selected randomly. See also https://github.com/fastfetch-cli/fastfetch/wiki/Logo-options",
"arg": {
"type": "logo"
}
+1 -1
View File
@@ -665,7 +665,7 @@
},
"source": {
"type": "string",
"description": "Path to the logo source file. For the spin logo: `auto` (the detected OS), any built-in logo name, or a text file in fastfetch logo syntax"
"description": "Path to the logo source file. Environment variables (`%VAR%` on Windows, `$VAR` or `${VAR}`) and glob patterns (`*`, `?`, `[...]`) are expanded. If several files match a glob, one is selected randomly. For the spin logo: `auto` (the detected OS), any built-in logo name, or a text file in fastfetch logo syntax"
},
"spin": {
"type": "object",
+7 -20
View File
@@ -3,6 +3,7 @@
#include "common/io.h"
#include "common/strutil.h"
#include "common/time.h"
#include "common/windows/glob.h"
#include "common/windows/nt.h"
#include "common/windows/unicode.h"
@@ -284,28 +285,14 @@ HANDLE openat(HANDLE dfd, const char* fileName, int oflag) {
}
bool ffPathExpandEnv(const char* in, FFstrbuf* out) {
if (in[0] == '~') {
if ((in[1] == '/' || in[1] == '\\' || in[1] == '\0') && !ffStrContainsC(in, '%')) {
ffStrbufSet(out, &instance.state.platform.homeDir);
ffStrbufAppendS(out, in + 1);
return true;
}
if (in[0] == '~' && (in[1] == '/' || in[1] == '\\' || in[1] == '\0')) {
FF_STRBUF_AUTO_DESTROY expanded = ffStrbufCreate();
ffStrbufSet(&expanded, &instance.state.platform.homeDir);
ffStrbufAppendS(&expanded, in + 1);
return ffGlobWindows(expanded.chars, out);
}
wchar_t pathInW[MAX_PATH], pathOutW[MAX_PATH];
ULONG len = (ULONG) strlen(in);
if (!NT_SUCCESS(RtlUTF8ToUnicodeN(pathInW, (ULONG) sizeof(pathInW), &len, in, len))) {
return false;
}
len /= sizeof(wchar_t); // convert from bytes to characters
SIZE_T outLen; // in characters, including null terminator
if (!NT_SUCCESS(RtlExpandEnvironmentStrings(nullptr, pathInW, len, pathOutW, ARRAY_SIZE(pathOutW), &outLen))) {
return false;
}
ffStrbufSetNWS(out, (uint32_t) outLen - 1, pathOutW);
return true;
return ffGlobWindows(in, out);
}
bool ffSuppressIO(bool suppress) {
+393
View File
@@ -0,0 +1,393 @@
#include "common/windows/glob.h"
#include "common/FFlist.h"
#include "common/mallocHelper.h"
#include "common/time.h"
#include "common/windows/nt.h"
#include "common/windows/unicode.h"
#include <wchar.h>
#include <windows.h>
// Windows has no glob(3). FindFirstFileW() accepts wildcards only in the last component, and its
// wildcard matching follows the old DOS rules (a `?` can match a zero-length suffix, and `*.ext`
// matches files whose 8.3 short name has that extension). Enumerating a directory with `*` and
// applying our own matcher gives the same semantics as glob(3) on Unix, including character classes
// and wildcards in intermediate components.
//
// Everything below works on UTF-16 so that names outside the ANSI code page survive, and so that
// `?` matches one Unicode character instead of one UTF-8 byte.
static bool isEnvNameStart(wchar_t value) {
return (value >= L'A' && value <= L'Z') || (value >= L'a' && value <= L'z') || value == L'_';
}
static bool isEnvNameChar(wchar_t value) {
return isEnvNameStart(value) || (value >= L'0' && value <= L'9');
}
// Appends the value of the environment variable whose name is `name[0 .. nameLength)`.
// Returns false when the variable is not defined, so the caller can leave the original
// `%NAME%` / `$NAME` text in place.
static bool appendEnvValue(const wchar_t* name, uint32_t nameLength, FFWStrbuf* out) {
if (nameLength == 0 || nameLength > 0x7FFF) {
return false;
}
wchar_t stackName[128];
wchar_t* nameBuffer = nameLength < ARRAY_SIZE(stackName)
? stackName
: (wchar_t*) malloc(((size_t) nameLength + 1) * sizeof(wchar_t));
if (nameBuffer == nullptr) {
return false;
}
memcpy(nameBuffer, name, (size_t) nameLength * sizeof(wchar_t));
nameBuffer[nameLength] = L'\0';
// An empty variable is reported as a required length of zero; the last error tells it apart
// from a variable that does not exist at all.
SetLastError(ERROR_SUCCESS);
DWORD needed = GetEnvironmentVariableW(nameBuffer, nullptr, 0);
bool found = false;
if (needed == 0) {
found = GetLastError() == ERROR_SUCCESS;
} else {
FF_AUTO_FREE wchar_t* value = (wchar_t*) malloc((size_t) needed * sizeof(wchar_t));
if (value != nullptr) {
DWORD written = GetEnvironmentVariableW(nameBuffer, value, needed);
if (written > 0) {
ffWStrbufAppendNS(out, (uint32_t) written, value);
found = true;
}
}
}
if (nameBuffer != stackName) {
free(nameBuffer);
}
return found;
}
// Expands `%NAME%`, `$NAME` and `${NAME}` in one pass. Values inserted by the expansion are not
// expanded again.
static void expandEnv(const wchar_t* in, FFWStrbuf* out) {
for (const wchar_t* p = in; *p != L'\0';) {
if (*p == L'%') {
const wchar_t* end = wcschr(p + 1, L'%');
if (end != nullptr && end != p + 1 && appendEnvValue(p + 1, (uint32_t) (end - p - 1), out)) {
p = end + 1;
continue;
}
ffWStrbufAppendC(out, *p++);
} else if (*p == L'$') {
const wchar_t* name = p + 1;
const wchar_t* after = nullptr;
if (*name == L'{') {
const wchar_t* end = wcschr(name + 1, L'}');
if (end != nullptr && end != name + 1) {
++name;
after = end + 1;
if (appendEnvValue(name, (uint32_t) (end - name), out)) {
p = after;
continue;
}
}
} else if (isEnvNameStart(*name)) {
const wchar_t* end = name + 1;
while (isEnvNameChar(*end)) {
++end;
}
after = end;
if (appendEnvValue(name, (uint32_t) (end - name), out)) {
p = after;
continue;
}
}
ffWStrbufAppendC(out, *p++);
} else {
ffWStrbufAppendC(out, *p++);
}
}
}
static bool isSeparator(wchar_t value) {
return value == L'\\' || value == L'/';
}
static const wchar_t* findSeparator(const wchar_t* value) {
while (*value != L'\0' && !isSeparator(*value)) {
++value;
}
return *value == L'\0' ? nullptr : value;
}
static void appendPathComponent(FFWStrbuf* path, const wchar_t* component, uint32_t length) {
// `C:` is drive-relative: `C:foo`, not `C:\foo`.
if (path->length > 0 && !isSeparator(path->chars[path->length - 1]) &&
!(path->length == 2 && path->chars[1] == L':')) {
ffWStrbufAppendC(path, L'\\');
}
ffWStrbufAppendNS(path, length, component);
}
static bool componentHasWildcard(const wchar_t* value, uint32_t length) {
for (uint32_t i = 0; i < length; ++i) {
if (value[i] == L'*' || value[i] == L'?' || value[i] == L'[') {
return true;
}
}
return false;
}
// Returns -1 if the pattern is not a valid bracket expression, 0 if it is valid but does not
// match `value`, and 1 if it matches.
static int matchBracket(wchar_t value, const wchar_t* pattern, uint32_t length, uint32_t* consumed) {
assert(length > 0 && pattern[0] == L'[');
uint32_t i = 1;
bool negate = false;
if (i < length && (pattern[i] == L'!' || pattern[i] == L'^')) {
negate = true;
++i;
}
bool matched = false;
bool first = true;
uint32_t closing = UINT32_MAX;
wchar_t upperValue = (wchar_t) RtlUpcaseUnicodeChar(value);
while (i < length) {
if (pattern[i] == L']' && !first) {
closing = i;
break;
}
first = false;
wchar_t start = pattern[i];
wchar_t end = start;
uint32_t next = i + 1;
if (next + 1 < length && pattern[next] == L'-' && pattern[next + 1] != L']') {
end = pattern[next + 1];
next += 2;
}
wchar_t upperStart = (wchar_t) RtlUpcaseUnicodeChar(start);
wchar_t upperEnd = (wchar_t) RtlUpcaseUnicodeChar(end);
if (upperValue >= upperStart && upperValue <= upperEnd) {
matched = true;
}
i = next;
}
if (closing == UINT32_MAX) {
return -1;
}
*consumed = closing + 1;
return negate ? !matched : matched;
}
// Matches one character, and reports how many pattern characters were consumed.
static bool matchOne(wchar_t value, const wchar_t* pattern, uint32_t length, uint32_t* consumed) {
if (pattern[0] == L'?') {
*consumed = 1;
return true;
}
if (pattern[0] == L'[') {
int result = matchBracket(value, pattern, length, consumed);
if (result >= 0) {
return result != 0;
}
// Not a valid bracket expression: treat '[' as a literal character.
}
*consumed = 1;
return RtlUpcaseUnicodeChar(value) == RtlUpcaseUnicodeChar(pattern[0]);
}
static bool wildcardMatch(const wchar_t* name, uint32_t nameLength, const wchar_t* pattern, uint32_t patternLength) {
uint32_t nameIndex = 0;
uint32_t patternIndex = 0;
uint32_t starPattern = UINT32_MAX;
uint32_t starName = 0;
while (nameIndex < nameLength) {
if (patternIndex < patternLength && pattern[patternIndex] == L'*') {
while (patternIndex < patternLength && pattern[patternIndex] == L'*') {
++patternIndex;
}
if (patternIndex == patternLength) {
return true;
}
starPattern = patternIndex;
starName = nameIndex;
continue;
}
uint32_t consumed = 0;
if (patternIndex < patternLength &&
matchOne(name[nameIndex], pattern + patternIndex, patternLength - patternIndex, &consumed)) {
++nameIndex;
patternIndex += consumed;
continue;
}
if (starPattern == UINT32_MAX) {
return false;
}
patternIndex = starPattern;
nameIndex = ++starName;
}
while (patternIndex < patternLength && pattern[patternIndex] == L'*') {
++patternIndex;
}
return patternIndex == patternLength;
}
// Splits the volume / root prefix from `pattern` and appends it to `path`.
static const wchar_t* parseRoot(FFWStrbuf* path, const wchar_t* pattern) {
if (isSeparator(pattern[0]) && isSeparator(pattern[1])) {
// UNC path: \\server\share\...
const wchar_t* server = pattern + 2;
const wchar_t* serverEnd = findSeparator(server);
if (serverEnd == nullptr) {
uint32_t length = (uint32_t) wcslen(pattern);
ffWStrbufAppendNS(path, length, pattern);
return pattern + length;
}
const wchar_t* shareEnd = findSeparator(serverEnd + 1);
if (shareEnd == nullptr) {
uint32_t length = (uint32_t) wcslen(pattern);
ffWStrbufAppendNS(path, length, pattern);
return pattern + length;
}
uint32_t prefixLength = (uint32_t) (shareEnd + 1 - pattern);
ffWStrbufAppendNS(path, prefixLength, pattern);
return shareEnd + 1;
}
if (((pattern[0] >= L'A' && pattern[0] <= L'Z') || (pattern[0] >= L'a' && pattern[0] <= L'z')) &&
pattern[1] == L':') {
ffWStrbufAppendNS(path, 2, pattern);
if (isSeparator(pattern[2])) {
ffWStrbufAppendC(path, L'\\');
return pattern + 3;
}
return pattern + 2;
}
if (isSeparator(pattern[0])) {
ffWStrbufAppendC(path, L'\\');
return pattern + 1;
}
return pattern;
}
static void globRecurse(FFWStrbuf* path, const wchar_t* pattern, FFlist* results) {
while (isSeparator(*pattern)) {
++pattern;
}
if (*pattern == L'\0') {
if (GetFileAttributesW(path->chars) == INVALID_FILE_ATTRIBUTES) {
return;
}
FFstrbuf* result = FF_LIST_ADD(FFstrbuf, *results);
ffStrbufInitNWS(result, path->length, path->chars);
return;
}
const wchar_t* end = pattern;
while (*end != L'\0' && !isSeparator(*end)) {
++end;
}
uint32_t componentLength = (uint32_t) (end - pattern);
uint32_t savedLength = path->length;
if (!componentHasWildcard(pattern, componentLength)) {
appendPathComponent(path, pattern, componentLength);
globRecurse(path, end, results);
path->length = savedLength;
path->chars[savedLength] = L'\0';
return;
}
appendPathComponent(path, L"*", 1);
WIN32_FIND_DATAW entry;
HANDLE handle = FindFirstFileW(path->chars, &entry);
path->length = savedLength;
path->chars[savedLength] = L'\0';
if (handle == INVALID_HANDLE_VALUE) {
return;
}
do {
// Like glob(3), a wildcard does not match entries whose name starts with a dot unless the
// pattern itself starts with one. `.` and `..` are never returned as glob results.
if (entry.cFileName[0] == L'.' && pattern[0] != L'.') {
continue;
}
if (entry.cFileName[0] == L'.' &&
(entry.cFileName[1] == L'\0' || (entry.cFileName[1] == L'.' && entry.cFileName[2] == L'\0'))) {
continue;
}
uint32_t nameLength = (uint32_t) wcslen(entry.cFileName);
if (!wildcardMatch(entry.cFileName, nameLength, pattern, componentLength)) {
continue;
}
uint32_t lengthBeforeEntry = path->length;
appendPathComponent(path, entry.cFileName, nameLength);
globRecurse(path, end, results);
path->length = lengthBeforeEntry;
path->chars[lengthBeforeEntry] = L'\0';
} while (FindNextFileW(handle, &entry));
FindClose(handle);
}
bool ffGlobWindows(const char* in, FFstrbuf* out) {
FF_WSTRBUF_AUTO_DESTROY wide = ffWStrbufCreateUtf8(in);
if (wide.chars == nullptr) {
return false;
}
FF_WSTRBUF_AUTO_DESTROY expanded = ffWStrbufCreate();
expandEnv(wide.chars, &expanded);
if (wcspbrk(expanded.chars, L"*?[") == nullptr) {
ffStrbufSetNWS(out, expanded.length, expanded.chars);
return true;
}
FF_WSTRBUF_AUTO_DESTROY path = ffWStrbufCreate();
const wchar_t* components = parseRoot(&path, expanded.chars);
FF_LIST_AUTO_DESTROY results = ffListCreate();
globRecurse(&path, components, &results);
bool found = results.length > 0;
if (found) {
uint32_t index = results.length > 1 ? (uint32_t) (ffTimeGetNow() % results.length) : 0;
ffStrbufSet(out, FF_LIST_GET(FFstrbuf, results, index));
}
if (results.length > 0) {
FF_LIST_FOR_EACH (FFstrbuf, result, results) {
ffStrbufDestroy(result);
}
}
return found;
}
+16
View File
@@ -0,0 +1,16 @@
#pragma once
#include "common/FFstrbuf.h"
// Expands environment variables and glob patterns in a Windows path.
//
// Environment variables may be written as `%NAME%` for compatibility with existing
// configurations, or as `$NAME` / `${NAME}`. A variable that is not defined is left
// untouched, so paths that legitimately contain a `$` or `%` keep working.
//
// Glob patterns support `*`, `?` and `[...]` character classes. Both `/` and `\` are
// accepted as path separators. If more than one path matches, one is chosen
// pseudo-randomly, mirroring the Unix implementation in io_unix.c.
//
// Returns false if a wildcard pattern matches nothing.
[[gnu::nonnull(1, 2)]] bool ffGlobWindows(const char* in, FFstrbuf* out);
+3
View File
@@ -778,6 +778,9 @@ NTSYSAPI NTSTATUS NTAPI RtlUTF8ToUnicodeN(
_In_reads_bytes_(UTF8StringByteCount) PCCH UTF8StringSource,
_In_ ULONG UTF8StringByteCount);
NTSYSAPI WCHAR NTAPI RtlUpcaseUnicodeChar(
_In_ WCHAR SourceCharacter);
#define RTL_MAX_DRIVE_LETTERS 32
typedef struct _RTL_DRIVE_LETTER_CURDIR {
USHORT Flags;
+23
View File
@@ -2,6 +2,29 @@
#include "common/windows/nt.h"
FFWStrbuf ffWStrbufCreateUtf8(const char* in) {
FFWStrbuf strbuf = { .chars = nullptr, .length = 0, .capacity = 0 };
ULONG inputLength = (ULONG) strlen(in) + 1;
ULONG size = 0;
(void) RtlUTF8ToUnicodeN(nullptr, 0, &size, in, inputLength);
if (size == 0) {
return strbuf;
}
wchar_t* result = (wchar_t*) malloc(size);
ULONG written = 0;
if (!result || !NT_SUCCESS(RtlUTF8ToUnicodeN(result, size, &written, in, inputLength))) {
free(result);
return strbuf;
}
strbuf.chars = result;
strbuf.capacity = (uint32_t) (size / sizeof(wchar_t));
strbuf.length = (uint32_t) wcslen(result);
return strbuf;
}
void ffStrbufSetNWS(FFstrbuf* result, uint32_t length, const wchar_t* source) {
if (!length) {
ffStrbufClear(result);
+77
View File
@@ -3,6 +3,83 @@
#include "common/FFstrbuf.h"
#include <wchar.h>
// ---------------------------------------------------------------------------------------------
// A wide-character string buffer for building UTF-16 paths. It follows the FFstrbuf
// Init / Create / Destroy / Append* conventions, but is always heap allocated: `capacity`
// counts wchar_t slots including the null terminator. A destroyed buffer (or the result of a
// failed conversion) is zeroed with `chars == nullptr`, which is safe to destroy again.
// ---------------------------------------------------------------------------------------------
#define FASTFETCH_WSTRBUF_DEFAULT_ALLOC 64
typedef struct FFWStrbuf {
wchar_t* chars;
uint32_t length;
uint32_t capacity;
} FFWStrbuf;
[[gnu::nonnull(1)]] static inline void ffWStrbufEnsureFree(FFWStrbuf* strbuf, uint32_t free) {
uint64_t required = (uint64_t) strbuf->length + free + 1; // +1 for the null terminator
if (required <= strbuf->capacity) {
return;
}
uint32_t capacity = strbuf->capacity == 0 ? FASTFETCH_WSTRBUF_DEFAULT_ALLOC : strbuf->capacity;
while (capacity < required) {
if (capacity > UINT32_MAX / 2) {
capacity = (uint32_t) required;
break;
}
capacity *= 2;
}
strbuf->chars = (wchar_t*) realloc(strbuf->chars, (size_t) capacity * sizeof(wchar_t));
strbuf->capacity = capacity;
}
[[gnu::nonnull(1)]] static inline void ffWStrbufInit(FFWStrbuf* strbuf) {
strbuf->chars = nullptr;
strbuf->length = 0;
strbuf->capacity = 0;
ffWStrbufEnsureFree(strbuf, 0);
strbuf->chars[0] = L'\0';
}
// Despite the name, resets the buffer to the initial, unallocated state
[[gnu::nonnull(1)]] static inline void ffWStrbufDestroy(FFWStrbuf* strbuf) {
free(strbuf->chars);
strbuf->chars = nullptr;
strbuf->length = 0;
strbuf->capacity = 0;
}
[[gnu::nonnull(1)]] static inline void ffWStrbufAppendNS(FFWStrbuf* strbuf, uint32_t length, const wchar_t* value) {
ffWStrbufEnsureFree(strbuf, length);
if (length > 0) {
memcpy(strbuf->chars + strbuf->length, value, (size_t) length * sizeof(wchar_t));
}
strbuf->length += length;
strbuf->chars[strbuf->length] = L'\0';
}
[[gnu::nonnull(1)]] static inline void ffWStrbufAppendC(FFWStrbuf* strbuf, wchar_t value) {
ffWStrbufEnsureFree(strbuf, 1);
strbuf->chars[strbuf->length++] = value;
strbuf->chars[strbuf->length] = L'\0';
}
[[nodiscard]] static inline FFWStrbuf ffWStrbufCreate(void) {
FFWStrbuf strbuf;
ffWStrbufInit(&strbuf);
return strbuf;
}
// Converts a null-terminated UTF-8 string into a new UTF-16 buffer. `chars` is nullptr if the
// conversion failed; the returned value is always safe to pass to ffWStrbufDestroy.
[[gnu::nonnull(1), nodiscard]] FFWStrbuf ffWStrbufCreateUtf8(const char* in);
#define FF_WSTRBUF_AUTO_DESTROY [[gnu::cleanup(ffWStrbufDestroy)]] FFWStrbuf
void ffStrbufSetNWS(FFstrbuf* result, uint32_t length, const wchar_t* source);
void ffStrbufAppendNWS(FFstrbuf* result, uint32_t length, const wchar_t* source);
+181
View File
@@ -0,0 +1,181 @@
#include "common/windows/glob.h"
#include "common/windows/unicode.h"
#include "common/textModifier.h"
#include <windows.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdnoreturn.h>
#include <string.h>
#include <wchar.h>
noreturn static void testFailed(const char* expression, int lineNo) {
fprintf(stderr, FASTFETCH_TEXT_MODIFIER_ERROR "[%d] %s\n" FASTFETCH_TEXT_MODIFIER_RESET, lineNo, expression);
exit(1);
}
#define VERIFY(expression) \
if (!(expression)) testFailed(#expression, __LINE__)
static void joinPath(wchar_t* result, size_t capacity, const wchar_t* base, const wchar_t* name) {
if (swprintf(result, capacity, L"%ls\\%ls", base, name) < 0) {
testFailed("swprintf", __LINE__);
}
}
static void writeFile(const wchar_t* path) {
HANDLE handle = CreateFileW(path, GENERIC_WRITE, 0, nullptr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr);
if (handle == INVALID_HANDLE_VALUE) {
testFailed("CreateFileW", __LINE__);
}
CloseHandle(handle);
}
static void createDirectory(const wchar_t* path) {
if (!CreateDirectoryW(path, nullptr)) {
testFailed("CreateDirectoryW", __LINE__);
}
}
static void createFileIn(const wchar_t* directory, const wchar_t* name) {
wchar_t path[MAX_PATH];
joinPath(path, MAX_PATH, directory, name);
writeFile(path);
}
static void expectGlob(const wchar_t* pattern, const wchar_t* expected) {
FF_STRBUF_AUTO_DESTROY patternUtf8 = ffStrbufCreateWS(pattern);
FF_STRBUF_AUTO_DESTROY expectedUtf8 = ffStrbufCreateWS(expected);
FF_STRBUF_AUTO_DESTROY result = ffStrbufCreate();
if (!ffGlobWindows(patternUtf8.chars, &result) || !ffStrbufEqual(&result, &expectedUtf8)) {
fprintf(stderr, FASTFETCH_TEXT_MODIFIER_ERROR "glob mismatch for %ls: expected %ls, got %s\n" FASTFETCH_TEXT_MODIFIER_RESET, pattern, expected, result.chars ? result.chars : "(null)");
exit(1);
}
}
static void expectNoGlob(const wchar_t* pattern) {
FF_STRBUF_AUTO_DESTROY patternUtf8 = ffStrbufCreateWS(pattern);
FF_STRBUF_AUTO_DESTROY result = ffStrbufCreate();
if (ffGlobWindows(patternUtf8.chars, &result)) {
fprintf(stderr, FASTFETCH_TEXT_MODIFIER_ERROR "glob unexpectedly matched %ls: %s\n" FASTFETCH_TEXT_MODIFIER_RESET, pattern, result.chars);
exit(1);
}
}
int main(void) {
wchar_t tempPath[MAX_PATH];
DWORD tempLength = GetTempPathW(MAX_PATH, tempPath);
VERIFY(tempLength > 0 && tempLength < MAX_PATH);
wchar_t root[MAX_PATH];
VERIFY(swprintf(root, MAX_PATH, L"%lsfastfetch-glob-%lu-%lu", tempPath, GetCurrentProcessId(), GetTickCount()) > 0);
createDirectory(root);
wchar_t sub[MAX_PATH], dot[MAX_PATH], weirdDollar[MAX_PATH], weirdPercent[MAX_PATH];
joinPath(sub, MAX_PATH, root, L"sub");
joinPath(dot, MAX_PATH, root, L"dot");
joinPath(weirdDollar, MAX_PATH, root, L"$weird");
joinPath(weirdPercent, MAX_PATH, root, L"%weird%");
createDirectory(sub);
createDirectory(dot);
createDirectory(weirdDollar);
createDirectory(weirdPercent);
createFileIn(root, L"a.txt");
createFileIn(root, L"b.txt");
createFileIn(root, L"c.log");
createFileIn(root, L"d.pngx");
createFileIn(root, L".hidden.txt");
createFileIn(sub, L"x.txt");
createFileIn(dot, L"only.txt");
createFileIn(dot, L".hidden.txt");
createFileIn(weirdDollar, L"z.txt");
createFileIn(weirdPercent, L"w.txt");
wchar_t pattern[MAX_PATH], expected[MAX_PATH];
// Plain paths are returned as they are.
joinPath(pattern, MAX_PATH, root, L"a.txt");
expectGlob(pattern, pattern);
// `?`, character classes and negated classes.
VERIFY(swprintf(pattern, MAX_PATH, L"%ls\\?.log", root) > 0);
joinPath(expected, MAX_PATH, root, L"c.log");
expectGlob(pattern, expected);
VERIFY(swprintf(pattern, MAX_PATH, L"%ls\\[a].txt", root) > 0);
joinPath(expected, MAX_PATH, root, L"a.txt");
expectGlob(pattern, expected);
VERIFY(swprintf(pattern, MAX_PATH, L"%ls\\[!a].txt", root) > 0);
joinPath(expected, MAX_PATH, root, L"b.txt");
expectGlob(pattern, expected);
// Wildcards work in intermediate components too.
VERIFY(swprintf(pattern, MAX_PATH, L"%ls\\*\\x.txt", root) > 0);
joinPath(expected, MAX_PATH, sub, L"x.txt");
expectGlob(pattern, expected);
// Dot files are excluded unless the pattern starts with a dot.
VERIFY(swprintf(pattern, MAX_PATH, L"%ls\\dot\\*.txt", root) > 0);
joinPath(expected, MAX_PATH, dot, L"only.txt");
expectGlob(pattern, expected);
// `%NAME%`, `$NAME` and `${NAME}` are all accepted.
joinPath(expected, MAX_PATH, sub, L"x.txt");
VERIFY(SetEnvironmentVariableW(L"FASTFETCH_TEST_GLOB_DIR", sub));
VERIFY(swprintf(pattern, MAX_PATH, L"%%FASTFETCH_TEST_GLOB_DIR%%\\x.txt") > 0);
expectGlob(pattern, expected);
VERIFY(swprintf(pattern, MAX_PATH, L"$FASTFETCH_TEST_GLOB_DIR\\x.txt") > 0);
expectGlob(pattern, expected);
VERIFY(swprintf(pattern, MAX_PATH, L"${FASTFETCH_TEST_GLOB_DIR}\\x.txt") > 0);
expectGlob(pattern, expected);
VERIFY(SetEnvironmentVariableW(L"FASTFETCH_TEST_GLOB_DIR", nullptr));
// Undefined variables are literal, so paths containing `$` or `%` still work.
VERIFY(SetEnvironmentVariableW(L"weird", nullptr));
joinPath(pattern, MAX_PATH, weirdDollar, L"z.txt");
expectGlob(pattern, pattern);
joinPath(pattern, MAX_PATH, weirdPercent, L"w.txt");
expectGlob(pattern, pattern);
// No match is reported as such. `*.png` must not fall back to the 8.3 short name of `d.pngx`,
// and `?` must not match an empty suffix.
VERIFY(swprintf(pattern, MAX_PATH, L"%ls\\nope*.txt", root) > 0);
expectNoGlob(pattern);
VERIFY(swprintf(pattern, MAX_PATH, L"%ls\\*.png", root) > 0);
expectNoGlob(pattern);
VERIFY(swprintf(pattern, MAX_PATH, L"%ls\\c?.log", root) > 0);
expectNoGlob(pattern);
wchar_t path[MAX_PATH];
const wchar_t* files[] = { L"a.txt", L"b.txt", L"c.log", L"d.pngx", L".hidden.txt" };
for (uint32_t i = 0; i < ARRAY_SIZE(files); ++i) {
joinPath(path, MAX_PATH, root, files[i]);
DeleteFileW(path);
}
const wchar_t* subFiles[] = { L"x.txt" };
for (uint32_t i = 0; i < ARRAY_SIZE(subFiles); ++i) {
joinPath(path, MAX_PATH, sub, subFiles[i]);
DeleteFileW(path);
}
const wchar_t* dotFiles[] = { L"only.txt", L".hidden.txt" };
for (uint32_t i = 0; i < ARRAY_SIZE(dotFiles); ++i) {
joinPath(path, MAX_PATH, dot, dotFiles[i]);
DeleteFileW(path);
}
joinPath(path, MAX_PATH, weirdDollar, L"z.txt");
DeleteFileW(path);
joinPath(path, MAX_PATH, weirdPercent, L"w.txt");
DeleteFileW(path);
RemoveDirectoryW(sub);
RemoveDirectoryW(dot);
RemoveDirectoryW(weirdDollar);
RemoveDirectoryW(weirdPercent);
RemoveDirectoryW(root);
puts("\033[32mAll tests passed!" FASTFETCH_TEXT_MODIFIER_RESET);
return 0;
}