Welcome to mirror list, hosted at ThFree Co, Russian Federation.

Utils.cs « Common « tasks « src - github.com/dotnet/runtime.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: b7c1fd6d91ef313f355ee26e95d304159ea13fe4 (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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Text;
using Microsoft.Build.Framework;
using Microsoft.Build.Utilities;

internal static class Utils
{
    private static readonly object s_SyncObj = new object();

    public static string GetEmbeddedResource(string file)
    {
        using Stream stream = typeof(Utils).Assembly
            .GetManifestResourceStream($"{typeof(Utils).Assembly.GetName().Name}.Templates.{file}")!;
        using var reader = new StreamReader(stream);
        return reader.ReadToEnd();
    }

    public static string RunProcess(
        string path,
        string args = "",
        IDictionary<string, string>? envVars = null,
        string? workingDir = null,
        bool ignoreErrors = false,
        bool silent = true,
        MessageImportance outputMessageImportance=MessageImportance.High,
        MessageImportance debugMessageImportance=MessageImportance.High)
    {
        LogInfo($"Running: {path} {args}", debugMessageImportance);
        var outputBuilder = new StringBuilder();
        var errorBuilder = new StringBuilder();
        var processStartInfo = new ProcessStartInfo
        {
            FileName = path,
            UseShellExecute = false,
            CreateNoWindow = true,
            RedirectStandardError = true,
            RedirectStandardOutput = true,
            Arguments = args,
        };

        if (workingDir != null)
            processStartInfo.WorkingDirectory = workingDir;

        LogInfo($"Using working directory: {workingDir ?? Environment.CurrentDirectory}", debugMessageImportance);

        if (envVars != null)
        {
            if (envVars.Count > 0)
                Logger?.LogMessage(MessageImportance.Low, "Setting environment variables for execution:");

            foreach (KeyValuePair<string, string> envVar in envVars)
            {
                processStartInfo.EnvironmentVariables[envVar.Key] = envVar.Value;
                Logger?.LogMessage(MessageImportance.Low, $"\t{envVar.Key} = {envVar.Value}");
            }
        }

        Process? process = Process.Start(processStartInfo);
        if (process == null)
            throw new ArgumentException($"Process.Start({path} {args}) returned null process");

        process.ErrorDataReceived += (sender, e) =>
        {
            lock (s_SyncObj)
            {
                if (!silent)
                {
                    LogWarning(e.Data);
                    outputBuilder.AppendLine(e.Data);
                }
                errorBuilder.AppendLine(e.Data);
            }
        };
        process.OutputDataReceived += (sender, e) =>
        {
            lock (s_SyncObj)
            {
                if (!silent)
                {
                    LogInfo(e.Data, outputMessageImportance);
                    outputBuilder.AppendLine(e.Data);
                }
            }
        };
        process.BeginOutputReadLine();
        process.BeginErrorReadLine();
        process.WaitForExit();

        if (process.ExitCode != 0)
        {
            Logger?.LogMessage(MessageImportance.Low, $"Exit code: {process.ExitCode}");
            if (!ignoreErrors)
                throw new Exception("Error: " + errorBuilder);
        }

        return outputBuilder.ToString().Trim('\r', '\n');
    }

    public static void DirectoryCopy(string sourceDir, string destDir, Func<string, bool> predicate)
    {
        string[] files = Directory.GetFiles(sourceDir, "*", SearchOption.AllDirectories);
        foreach (string file in files)
        {
            if (!predicate(file))
                continue;

            string relativePath = Path.GetRelativePath(sourceDir, file);
            string? relativeDir = Path.GetDirectoryName(relativePath);
            if (!string.IsNullOrEmpty(relativeDir))
                Directory.CreateDirectory(Path.Combine(destDir, relativeDir));

            File.Copy(file, Path.Combine(destDir, relativePath), true);
        }
    }

    public static TaskLoggingHelper? Logger { get; set; }

    public static void LogInfo(string? msg, MessageImportance importance=MessageImportance.High)
    {
        if (msg != null)
            Logger?.LogMessage(importance, msg);
    }

    public static void LogWarning(string? msg)
    {
        if (msg != null)
            Logger?.LogWarning(msg);
    }

    public static void LogError(string? msg)
    {
        if (msg != null)
            Logger?.LogError(msg);
    }
}