aboutsummaryrefslogtreecommitdiff
path: root/src/WixToolset.Core/ExtensibilityServices/ExtensionManager.cs
blob: c23c83833c0225fa2feb351dde3dcbd35cebae02 (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
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
// 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.ExtensibilityServices
{
    using System;
    using System.Collections.Generic;
    using System.IO;
    using System.Linq;
    using System.Reflection;
    using WixToolset.Data;
    using WixToolset.Extensibility;
    using WixToolset.Extensibility.Services;

    internal class ExtensionManager : IExtensionManager
    {
        private List<IExtensionFactory> extensionFactories = new List<IExtensionFactory>();
        private Dictionary<Type, List<object>> loadedExtensionsByType = new Dictionary<Type, List<object>>();

        public ExtensionManager(IWixToolsetCoreServiceProvider serviceProvider)
        {
            this.ServiceProvider = serviceProvider;
        }

        private IWixToolsetCoreServiceProvider ServiceProvider { get; }

        public void Add(Assembly extensionAssembly)
        {
            var types = extensionAssembly.GetTypes().Where(t => !t.IsAbstract && !t.IsInterface && typeof(IExtensionFactory).IsAssignableFrom(t));
            var factories = types.Select(this.CreateExtensionFactory).ToList();

            if (!factories.Any())
            {
                var path = Path.GetFullPath(new Uri(extensionAssembly.CodeBase).LocalPath);
                throw new WixException(ErrorMessages.InvalidExtension(path, "The extension does not implement IExtensionFactory. All extensions must have at least one implementation of IExtensionFactory."));
            }

            this.extensionFactories.AddRange(factories);
        }

        public void Load(string extensionPath)
        {
            var checkPath = extensionPath;
            var checkedPaths = new List<string> { checkPath };
            try
            {
                if (!TryLoadFromPath(checkPath, out var assembly) && !Path.IsPathRooted(extensionPath))
                {
                    if (TryParseExtensionReference(extensionPath, out var extensionId, out var extensionVersion))
                    {
                        foreach (var cachePath in this.CacheLocations())
                        {
                            var extensionFolder = Path.Combine(cachePath, extensionId);

                            var versionFolder = extensionVersion;
                            if (String.IsNullOrEmpty(versionFolder) && !TryFindLatestVersionInFolder(extensionFolder, out versionFolder))
                            {
                                checkedPaths.Add(extensionFolder);
                                continue;
                            }

                            checkPath = Path.Combine(extensionFolder, versionFolder, "tools", extensionId + ".dll");
                            checkedPaths.Add(checkPath);

                            if (TryLoadFromPath(checkPath, out assembly))
                            {
                                break;
                            }
                        }
                    }
                }

                if (assembly == null)
                {
                    throw new WixException(ErrorMessages.CouldNotFindExtensionInPaths(extensionPath, checkedPaths));
                }

                this.Add(assembly);
            }
            catch (ReflectionTypeLoadException rtle)
            {
                throw new WixException(ErrorMessages.InvalidExtension(checkPath, String.Join(Environment.NewLine, rtle.LoaderExceptions.Select(le => le.ToString()))));
            }
            catch (WixException)
            {
                throw;
            }
            catch (Exception e)
            {
                throw new WixException(ErrorMessages.InvalidExtension(checkPath, e.Message), e);
            }
        }

        public IEnumerable<T> GetServices<T>() where T : class
        {
            if (!this.loadedExtensionsByType.TryGetValue(typeof(T), out var extensions))
            {
                extensions = new List<object>();

                foreach (var factory in this.extensionFactories)
                {
                    if (factory.TryCreateExtension(typeof(T), out var obj) && obj is T extension)
                    {
                        extensions.Add(extension);
                    }
                }

                this.loadedExtensionsByType.Add(typeof(T), extensions);
            }

            return extensions.Cast<T>().ToList();
        }

        private IExtensionFactory CreateExtensionFactory(Type type)
        {
            var constructor = type.GetConstructor(new[] { typeof(IWixToolsetCoreServiceProvider) });
            if (constructor != null)
            {
                return (IExtensionFactory)constructor.Invoke(new[] { this.ServiceProvider });
            }

            return (IExtensionFactory)Activator.CreateInstance(type);
        }

        private IEnumerable<string> CacheLocations()
        {
            var path = Path.Combine(Environment.CurrentDirectory, ".wix", "extensions");
            if (Directory.Exists(path))
            {
                yield return path;
            }

            path = Environment.GetEnvironmentVariable("WIX_EXTENSIONS") ?? Environment.GetFolderPath(Environment.SpecialFolder.UserProfile);
            path = Path.Combine(path, ".wix", "extensions");
            if (Directory.Exists(path))
            {
                yield return path;
            }

            if (Environment.Is64BitOperatingSystem)
            {
                path = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.CommonProgramFiles), @"WixToolset\extensions\");
                if (Directory.Exists(path))
                {
                    yield return path;
                }
            }

            path = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.CommonProgramFilesX86), @"WixToolset\extensions\");
            if (Directory.Exists(path))
            {
                yield return path;
            }

            path = Path.Combine(Path.GetDirectoryName(new Uri(Assembly.GetCallingAssembly().CodeBase).LocalPath), @"extensions\");
            if (Directory.Exists(path))
            {
                yield return path;
            }
        }

        private static bool TryParseExtensionReference(string extensionReference, out string extensionId, out string extensionVersion)
        {
            extensionId = extensionReference ?? String.Empty;
            extensionVersion = String.Empty;

            var index = extensionId.LastIndexOf('/');
            if (index > 0)
            {
                extensionVersion = extensionReference.Substring(index + 1);
                extensionId = extensionReference.Substring(0, index);

                if (!NuGet.Versioning.NuGetVersion.TryParse(extensionVersion, out _))
                {
                    return false;
                }

                if (String.IsNullOrEmpty(extensionId))
                {
                    return false;
                }
            }

            return true;
        }

        private static bool TryFindLatestVersionInFolder(string basePath, out string foundVersionFolder)
        {
            foundVersionFolder = null;

            try
            {
                NuGet.Versioning.NuGetVersion version = null;
                foreach (var versionPath in Directory.GetDirectories(basePath))
                {
                    var versionFolder = Path.GetFileName(versionPath);
                    if (NuGet.Versioning.NuGetVersion.TryParse(versionFolder, out var checkVersion) &&
                        (version == null || version < checkVersion))
                    {
                        foundVersionFolder = versionFolder;
                        version = checkVersion;
                    }
                }
            }
            catch (IOException)
            {
            }

            return !String.IsNullOrEmpty(foundVersionFolder);
        }

        private static bool TryLoadFromPath(string extensionPath, out Assembly assembly)
        {
            try
            {
                if (File.Exists(extensionPath))
                {
                    assembly = Assembly.LoadFrom(extensionPath);
                    return true;
                }
            }
            catch (IOException e) when (e is FileLoadException || e is FileNotFoundException)
            {
            }

            assembly = null;
            return false;
        }
    }
}