aboutsummaryrefslogtreecommitdiff
path: root/src/zencore/commandline.cpp
blob: c801bf151caf5bf385fe32f9974a91f91418a1cf (plain) (blame)
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
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
// Copyright Epic Games, Inc. All Rights Reserved.

#include <zencore/commandline.h>
#include <zencore/string.h>

#if ZEN_PLATFORM_WINDOWS
#	include <zencore/windows.h>
ZEN_THIRD_PARTY_INCLUDES_START
#	include <shellapi.h>  // For command line parsing
ZEN_THIRD_PARTY_INCLUDES_END
#endif

#include <functional>

namespace zen {

void
IterateCommandlineArgs(std::function<void(const std::string_view& Arg)>& ProcessArg)
{
#if ZEN_PLATFORM_WINDOWS
	int			  ArgC	  = 0;
	const LPWSTR  CmdLine = ::GetCommandLineW();
	const LPWSTR* ArgV	  = ::CommandLineToArgvW(CmdLine, &ArgC);

	if (ArgC > 1)
	{
		for (int i = 1; i < ArgC; ++i)
		{
			StringBuilder<4096> ArgString8;

			WideToUtf8(ArgV[i], ArgString8);

			ProcessArg(ArgString8);
		}
	}

	::LocalFree(HLOCAL(ArgV));
#elif ZEN_PLATFORM_LINUX || ZEN_PLATFORM_MAC
	if (FILE* CmdLineFile = fopen("/proc/self/cmdline", "r"))
	{
		const char* ArgV[255] = {};
		int			ArgC	  = 0;

		char*  Arg	= nullptr;
		size_t Size = 0;
		while (getdelim(&Arg, &Size, 0, CmdLineFile) != -1)
		{
			ArgV[ArgC++] = Arg;
			Arg			 = nullptr;	 // getdelim will allocate buffer for next Arg
		}
		fclose(CmdLineFile);

		if (ArgC > 1)
		{
			for (int i = 1; i < ArgC; ++i)
			{
				ProcessArg(ArgV[i]);
			}
		}

		// cleanup after getdelim
		while (ArgC > 0)
		{
			free((void*)ArgV[--ArgC]);
		}
	}
#else
#	error Unknown platform
#endif
}

}  // namespace zen