w32_util.c 2.36 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
/*
 * Copyright (C) the libgit2 contributors. All rights reserved.
 *
 * This file is part of libgit2, distributed under the GNU GPL v2 with
 * a Linking Exception. For full terms see the included COPYING file.
 */

#include "w32_util.h"

/**
 * Creates a FindFirstFile(Ex) filter string from a UTF-8 path.
 * The filter string enumerates all items in the directory.
 *
 * @param dest The buffer to receive the filter string.
 * @param src The UTF-8 path of the directory to enumerate.
 * @return True if the filter string was created successfully; false otherwise
 */
bool git_win32__findfirstfile_filter(git_win32_path dest, const char *src)
{
	static const wchar_t suffix[] = L"\\*";
	int len = git_win32_path_from_utf8(dest, src);

	/* Ensure the path was converted */
	if (len < 0)
		return false;

27 28 29 30
	/* Ensure that the path does not end with a trailing slash,
	 * because we're about to add one. Don't rely our trim_end
	 * helper, because we want to remove the backslash even for
	 * drive letter paths, in this case. */
31 32 33 34 35 36 37
	if (len > 0 &&
		(dest[len - 1] == L'/' || dest[len - 1] == L'\\')) {
		dest[len - 1] = L'\0';
		len--;
	}

	/* Ensure we have enough room to add the suffix */
38
	if ((size_t)len >= GIT_WIN_PATH_UTF16 - CONST_STRLEN(suffix))
39 40 41 42 43 44 45 46 47 48 49 50
		return false;

	wcscat(dest, suffix);
	return true;
}

/**
 * Ensures the given path (file or folder) has the +H (hidden) attribute set.
 *
 * @param path The path which should receive the +H bit.
 * @return 0 on success; -1 on failure
 */
51
int git_win32__set_hidden(const char *path, bool hidden)
52 53
{
	git_win32_path buf;
54
	DWORD attrs, newattrs;
55 56 57 58 59 60 61

	if (git_win32_path_from_utf8(buf, path) < 0)
		return -1;

	attrs = GetFileAttributesW(buf);

	/* Ensure the path exists */
62
	if (attrs == INVALID_FILE_ATTRIBUTES)
63 64
		return -1;

65 66 67 68 69 70
	if (hidden)
		newattrs = attrs | FILE_ATTRIBUTE_HIDDEN;
	else
		newattrs = attrs & ~FILE_ATTRIBUTE_HIDDEN;

	if (attrs != newattrs && !SetFileAttributesW(buf, newattrs)) {
71
		git_error_set(GIT_ERROR_OS, "failed to %s hidden bit for '%s'",
72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90
			hidden ? "set" : "unset", path);
		return -1;
	}

	return 0;
}

int git_win32__hidden(bool *out, const char *path)
{
	git_win32_path buf;
	DWORD attrs;

	if (git_win32_path_from_utf8(buf, path) < 0)
		return -1;

	attrs = GetFileAttributesW(buf);

	/* Ensure the path exists */
	if (attrs == INVALID_FILE_ATTRIBUTES)
91 92
		return -1;

93
	*out = (attrs & FILE_ATTRIBUTE_HIDDEN) ? true : false;
94 95
	return 0;
}