aboutsummaryrefslogtreecommitdiffstats
path: root/QtVsTools.Core/MsBuild/QtTool.cs
blob: e5806162e731f1eef62bf57b3faa60dcc085b221 (plain)
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
73
74
// Copyright (C) 2025 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only WITH Qt-GPL-exception-1.0

using System.IO;
using System.Linq;

namespace QtVsTools.Core.MsBuild
{
    using CommandLine;
    using Common;

    public abstract class QtTool
    {
        protected readonly Parser Parser;
        private readonly Option outputOption;
        private Option helpOption;
        private Option versionOption;

        protected QtTool(bool defaultInputOutput = true)
        {
            Parser = new Parser();
            Parser.SetSingleDashWordOptionMode(
                Parser.SingleDashWordOptionMode.ParseAsLongOptions);

            helpOption = Parser.AddHelpOption();
            versionOption = Parser.AddVersionOption();

            if (!defaultInputOutput)
                return;

            Parser.AddOption(outputOption = new Option("o", "file", Option.Flag.ShortOptionStyle));
        }

        protected virtual void ExtractInputOutput(
            string toolExecName,
            out string inputPath,
            out string outputPath)
        {
            inputPath = outputPath = "";

            var filePath = Parser.PositionalArguments
                .FirstOrDefault(arg => !arg.EndsWith(toolExecName, Utils.IgnoreCase));
            if (!string.IsNullOrEmpty(filePath))
                inputPath = filePath;

            if (outputOption != null && Parser.IsSet(outputOption))
                outputPath = Parser.Value(outputOption);
        }

        protected bool ParseCommandLine(
            string commandLine,
            IVsMacroExpander macros,
            string toolExecName,
            out string qtDir,
            out string inputPath,
            out string outputPath)
        {
            qtDir = inputPath = outputPath = "";
            if (!Parser.Parse(commandLine, macros, toolExecName))
                return false;

            var execPath = Parser.PositionalArguments
                .FirstOrDefault(arg => arg.EndsWith(toolExecName, Utils.IgnoreCase));
            if (!string.IsNullOrEmpty(execPath)) {
                var execDir = Path.GetDirectoryName(execPath);
                if (!string.IsNullOrEmpty(execDir))
                    qtDir = HelperFunctions.CanonicalPath(Path.Combine(execDir, ".."));
            }

            ExtractInputOutput(toolExecName, out inputPath, out outputPath);
            return true;
        }
    }
}