aboutsummaryrefslogtreecommitdiff
path: root/src/WixToolset.Core/Bind/ExtractEmbeddedFilesCommand.cs
blob: 7e7c21b1210bb69a73ab4c09cd7bffb3af474875 (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
// Copyright (c) .NET Foundation and contributors. All rights reserved. Licensed under the Microsoft Reciprocal License. See LICENSE.TXT file in the project root for full license information.

namespace WixToolset.Core.Bind
{
    using System.Collections.Generic;
    using System.IO;
    using System.Linq;
    using System.Reflection;
    using WixToolset.Data;
    using WixToolset.Extensibility;

    public class ExtractEmbeddedFilesCommand
    {
        public ExtractEmbeddedFilesCommand(IEnumerable<IExpectedExtractFile> embeddedFiles)
        {
            this.FilesWithEmbeddedFiles = embeddedFiles;
        }

        private IEnumerable<IExpectedExtractFile> FilesWithEmbeddedFiles { get; }

        public void Execute()
        {
            var group = this.FilesWithEmbeddedFiles.GroupBy(e => e.Uri);

            foreach (var expectedEmbeddedFileByUri in group)
            {
                var baseUri = expectedEmbeddedFileByUri.Key;

                Stream stream = null;
                try
                {
                    // If the embedded files are stored in an assembly resource stream (usually
                    // a .wixlib embedded in a WixExtension).
                    if ("embeddedresource" == baseUri.Scheme)
                    {
                        var assemblyPath = Path.GetFullPath(baseUri.LocalPath);
                        var resourceName = baseUri.Fragment.TrimStart('#');

                        var assembly = Assembly.LoadFile(assemblyPath);
                        stream = assembly.GetManifestResourceStream(resourceName);
                    }
                    else // normal file (usually a binary .wixlib on disk).
                    {
                        stream = File.OpenRead(baseUri.LocalPath);
                    }

                    using (var fs = FileStructure.Read(stream))
                    {
                        var uniqueIndicies = new SortedSet<int>();

                        foreach (var embeddedFile in expectedEmbeddedFileByUri)
                        {
                            if (uniqueIndicies.Add(embeddedFile.EmbeddedFileIndex))
                            {
                                fs.ExtractEmbeddedFile(embeddedFile.EmbeddedFileIndex, embeddedFile.OutputPath);
                            }
                        }
                    }
                }
                finally
                {
                    stream?.Close();
                }
            }
        }
    }
}