aboutsummaryrefslogtreecommitdiff
path: root/src/WixToolset.Core/Librarian.cs
blob: f4191e86e6f10ee92f55031d5948a66c00e35ee8 (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
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
// 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
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using WixToolset.Core.Bind;
    using WixToolset.Core.Link;
    using WixToolset.Data;
    using WixToolset.Extensibility;
    using WixToolset.Extensibility.Services;

    /// <summary>
    /// Core librarian tool.
    /// </summary>
    public sealed class Librarian
    {
        public Librarian(IServiceProvider serviceProvider)
        {
            this.ServiceProvider = serviceProvider;
        }

        private IServiceProvider ServiceProvider { get; }

        private ILibraryContext Context { get; set; }

        public bool BindFiles { get; set; }

        public IEnumerable<BindPath> BindPaths { get; set; }

        public IEnumerable<Localization> Localizations { get; set; }

        public IEnumerable<Intermediate> Intermediates { get; set; }

        /// <summary>
        /// Create a library by combining several intermediates (objects).
        /// </summary>
        /// <param name="sections">The sections to combine into a library.</param>
        /// <returns>Returns the new library.</returns>
        public Intermediate Execute()
        {
            this.Context = new LibraryContext(this.ServiceProvider);
            this.Context.Messaging = this.ServiceProvider.GetService<IMessaging>();
            this.Context.BindFiles = this.BindFiles;
            this.Context.BindPaths = this.BindPaths;
            this.Context.Extensions = this.ServiceProvider.GetService<IExtensionManager>().Create<ILibrarianExtension>();
            this.Context.Localizations = this.Localizations;
            this.Context.LibraryId = Convert.ToBase64String(Guid.NewGuid().ToByteArray()).TrimEnd('=').Replace('+', '.').Replace('/', '_');
            this.Context.Intermediates = this.Intermediates;

            foreach (var extension in this.Context.Extensions)
            {
                extension.PreCombine(this.Context);
            }

            var sections = this.Context.Intermediates.SelectMany(i => i.Sections).ToList();

            var embedFilePaths = this.ResolveFilePathsToEmbed(sections);

            var localizationsByCulture = this.CollateLocalizations(this.Context.Localizations);

            if (this.Context.Messaging.EncounteredError)
            {
                return null;
            }

            foreach (var section in sections)
            {
                section.LibraryId = this.Context.LibraryId;
            }

            var library = new Intermediate(this.Context.LibraryId, sections, localizationsByCulture, embedFilePaths);

            this.Validate(library);

            foreach (var extension in this.Context.Extensions)
            {
                extension.PostCombine(library);
            }

            return library;
        }

        /// <summary>
        /// Validate that a library contains one entry section and no duplicate symbols.
        /// </summary>
        /// <param name="library">Library to validate.</param>
        private Intermediate Validate(Intermediate library)
        {
            FindEntrySectionAndLoadSymbolsCommand find = new FindEntrySectionAndLoadSymbolsCommand(this.Context.Messaging, library.Sections);
            find.Execute();

            // TODO: Consider bringing this sort of verification back.
            // foreach (Section section in library.Sections)
            // {
            //     ResolveReferencesCommand resolve = new ResolveReferencesCommand(find.EntrySection, find.Symbols);
            //     resolve.Execute();
            //
            //     ReportDuplicateResolvedSymbolErrorsCommand reportDupes = new ReportDuplicateResolvedSymbolErrorsCommand(find.SymbolsWithDuplicates, resolve.ResolvedSections);
            //     reportDupes.Execute();
            // }

            return (this.Context.Messaging.EncounteredError ? null : library);
        }

        private Dictionary<string, Localization> CollateLocalizations(IEnumerable<Localization> localizations)
        {
            var localizationsByCulture = new Dictionary<string, Localization>(StringComparer.OrdinalIgnoreCase);

            foreach (var localization in localizations)
            {
                if (localizationsByCulture.TryGetValue(localization.Culture, out var existingCulture))
                {
                    try
                    {
                        existingCulture.Merge(localization);
                    }
                    catch (WixException e)
                    {
                        this.Context.Messaging.Write(e.Error);
                    }
                }
                else
                {
                    localizationsByCulture.Add(localization.Culture, localization);
                }
            }

            return localizationsByCulture;
        }

        private List<string> ResolveFilePathsToEmbed(IEnumerable<IntermediateSection> sections)
        {
            var embedFilePaths = new List<string>();

            // Resolve paths to files that are to be embedded in the library.
            if (this.Context.BindFiles)
            {
                var variableResolver = new WixVariableResolver(this.Context.Messaging);

                var fileResolver = new FileResolver(this.Context.BindPaths, this.Context.Extensions);

                foreach (var tuple in sections.SelectMany(s => s.Tuples))
                {
                    foreach (var field in tuple.Fields.Where(f => f?.Type == IntermediateFieldType.Path))
                    {
                        var pathField = field.AsPath();

                        if (pathField != null)
                        {
                            var resolution = variableResolver.ResolveVariables(tuple.SourceLineNumbers, pathField.Path, false);

                            var file = fileResolver.Resolve(tuple.SourceLineNumbers, tuple.Definition, resolution.Value);

                            if (!String.IsNullOrEmpty(file))
                            {
                                // File was successfully resolved so track the embedded index as the embedded file index.
                                field.Set(new IntermediateFieldPathValue { EmbeddedFileIndex = embedFilePaths.Count });

                                embedFilePaths.Add(file);
                            }
                            else
                            {
                                this.Context.Messaging.Write(ErrorMessages.FileNotFound(tuple.SourceLineNumbers, pathField.Path, tuple.Definition.Name));
                            }
                        }
                    }
                }
            }

            return embedFilePaths;
        }
    }
}