1 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
2 /* vim: set ts=8 sts=2 et sw=2 tw=80: */
3 /* This Source Code Form is subject to the terms of the Mozilla Public
4 * License, v. 2.0. If a copy of the MPL was not distributed with this
5 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
6
7 #include "LogCommandLineHandler.h"
8
9 #include "mozilla/Tokenizer.h"
10 #include "nsDebug.h"
11
12 namespace mozilla {
13
LoggingHandleCommandLineArgs(int argc,char const * const * argv,std::function<void (nsACString const &)> const & consumer)14 void LoggingHandleCommandLineArgs(
15 int argc, char const* const* argv,
16 std::function<void(nsACString const&)> const& consumer) {
17 // Keeps the name of a pending env var (MOZ_LOG or MOZ_LOG_FILE) that
18 // we expect to get a value for in the next iterated arg.
19 // Used for the `-MOZ_LOG <modules>` form of argument.
20 nsAutoCString env;
21
22 auto const names = {"MOZ_LOG"_ns, "MOZ_LOG_FILE"_ns};
23
24 for (int arg = 1; arg < argc; ++arg) {
25 Tokenizer p(argv[arg]);
26
27 if (!env.IsEmpty() && p.CheckChar('-')) {
28 NS_WARNING(
29 "Expects value after -MOZ_LOG(_FILE) argument, but another argument "
30 "found");
31
32 // We only expect values for the pending env var, start over
33 p.Rollback();
34 env.Truncate();
35 }
36
37 if (env.IsEmpty()) {
38 if (!p.CheckChar('-')) {
39 continue;
40 }
41 // We accept `-MOZ_LOG` as well as `--MOZ_LOG`.
42 Unused << p.CheckChar('-');
43
44 for (auto const& name : names) {
45 if (!p.CheckWord(name)) {
46 continue;
47 }
48
49 env.Assign(name);
50 env.Append('=');
51 break;
52 }
53
54 if (env.IsEmpty()) {
55 // An unknonwn argument, ignore.
56 continue;
57 }
58
59 // We accept `-MOZ_LOG <modules>` as well as `-MOZ_LOG=<modules>`.
60
61 if (p.CheckEOF()) {
62 // We have a lone `-MOZ_LOG` arg, the next arg is expected to be
63 // the value, |env| is now prepared as `MOZ_LOG=`.
64 continue;
65 }
66
67 if (!p.CheckChar('=')) {
68 // There is a character after the arg name and it's not '=',
69 // ignore this argument.
70 NS_WARNING("-MOZ_LOG(_FILE) argument not in a proper form");
71
72 env.Truncate();
73 continue;
74 }
75 }
76
77 // This can be non-empty from previous iteration or in this iteration.
78 if (!env.IsEmpty()) {
79 nsDependentCSubstring value;
80 Unused << p.ReadUntil(Tokenizer::Token::EndOfFile(), value);
81 env.Append(value);
82
83 consumer(env);
84
85 env.Truncate();
86 }
87 }
88 }
89
90 } // namespace mozilla
91