summaryrefslogtreecommitdiffstats
path: root/tools/slang-cpp-extractor/file-util.cpp
blob: 1d37df650f910d39b90dbb8be494309fdabf23e7 (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
#include "file-util.h"

#include "../../source/core/slang-io.h"

namespace CppExtract {
using namespace Slang;

/* static */SlangResult FileUtil::readAllText(const Slang::String& fileName, DiagnosticSink* sink, String& outRead)
{
    try
    {
        StreamReader reader(new FileStream(fileName, FileMode::Open, FileAccess::Read, FileShare::ReadWrite));
        outRead = reader.ReadToEnd();
    }
    catch (const IOException&)
    {
        if (sink)
        {
            sink->diagnose(SourceLoc(), CPPDiagnostics::cannotOpenFile, fileName);
        }
        return SLANG_FAIL;
    }
    catch (...)
    {
        if (sink)
        {
            sink->diagnose(SourceLoc(), CPPDiagnostics::cannotOpenFile, fileName);
        }
        return SLANG_FAIL;
    }

    return SLANG_OK;
}

/* static */SlangResult FileUtil::writeAllText(const Slang::String& fileName, DiagnosticSink* sink, const UnownedStringSlice& text)
{
    try
    {
        if (File::exists(fileName))
        {
            String existingText;

            if (readAllText(fileName, nullptr, existingText) == SLANG_OK)
            {
                if (existingText == text)
                    return SLANG_OK;
            }
        }
        StreamWriter writer(new FileStream(fileName, FileMode::Create));
        writer.Write(text);
    }
    catch (const IOException&)
    {
        if (sink)
        {
            sink->diagnose(SourceLoc(), CPPDiagnostics::cannotOpenFile, fileName);
        }
        return SLANG_FAIL;
    }

    return SLANG_OK;
}

/* static */ void FileUtil::indent(Index indentCount, StringBuilder& out)
{
    for (Index i = 0; i < indentCount; ++i)
    {
        out << CPP_EXTRACT_INDENT_STRING;
    }
}

} // namespace CppExtract