/****************************************************************************
**
** Copyright (C) 2021 The Qt Company Ltd.
** Contact: https://www.qt.io/licensing/
**
** This file is part of the tools applications of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:GPL-EXCEPT$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see https://www.qt.io/terms-conditions. For further
** information use the contact form at https://www.qt.io/contact-us.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3 as published by the Free Software
** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
** included in the packaging of this file. Please review the following
** information to ensure the GNU General Public License requirements will
** be met: https://www.gnu.org/licenses/gpl-3.0.html.
**
** $QT_END_LICENSE$
**
****************************************************************************/

#ifndef QTBASE_DEPFILE_SHARED_H
#define QTBASE_DEPFILE_SHARED_H

#include <QByteArray>
#include <QString>
#include <QFile>

// Escape characters in given path. Dependency paths are Make-style, not NMake/Jom style.
// The paths can also be consumed by Ninja.
// "$" replaced by "$$"
// "#" replaced by "\#"
// " " replaced by "\ "
// "\#" replaced by "\\#"
// "\ " replaced by "\\\ "
//
// The escape rules are according to what clang / llvm escapes when generating a Make-style
// dependency file.
// Is a template function, because input param can be either a QString or a QByteArray.
template <typename T> struct CharType;
template <> struct CharType<QString> { using type = QLatin1Char; };
template <> struct CharType<QByteArray> { using type = char; };
template <typename StringType>
StringType escapeDependencyPath(const StringType &path)
{
    using CT = typename CharType<StringType>::type;
    StringType escapedPath;
    int size = path.size();
    escapedPath.reserve(size);
    for (int i = 0; i < size; ++i) {
        if (path[i] == CT('$')) {
            escapedPath.append(CT('$'));
        } else if (path[i] == CT('#')) {
            escapedPath.append(CT('\\'));
        } else if (path[i] == CT(' ')) {
            escapedPath.append(CT('\\'));
            int backwards_it = i - 1;
            while (backwards_it > 0 && path[backwards_it] == CT('\\')) {
                escapedPath.append(CT('\\'));
                --backwards_it;
            }
        }
        escapedPath.append(path[i]);
    }
    return escapedPath;
}

static inline QByteArray escapeAndEncodeDependencyPath(const QString &path)
{
    return QFile::encodeName(escapeDependencyPath(path));
}

#endif // QTBASE_DEPFILE_SHARED_H
