aboutsummaryrefslogtreecommitdiff
path: root/src/WixToolset.Core/Bind/FileResolver.cs
blob: 8d624e6f68a81d467dfd050e225431b8ea039a83 (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
230
231
// 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;
    using System.Collections.Generic;
    using System.IO;
    using System.Linq;
    using System.Runtime.InteropServices;
    using WixToolset.Data;
    using WixToolset.Data.Bind;
    using WixToolset.Extensibility;

    internal class FileResolver
    {
        private const string BindPathOpenString = "!(bindpath.";

        private FileResolver(IEnumerable<BindPath> bindPaths)
        {
            this.BindPaths = (bindPaths ?? Array.Empty<BindPath>()).ToLookup(b => b.Stage);
            this.RebaseTarget = this.BindPaths[BindStage.Target].Any();
            this.RebaseUpdated = this.BindPaths[BindStage.Updated].Any();
        }

        public FileResolver(IEnumerable<BindPath> bindPaths, IEnumerable<IBinderExtension> extensions) : this(bindPaths)
        {
            this.BinderExtensions = extensions ?? Array.Empty<IBinderExtension>();
        }

        public FileResolver(IEnumerable<BindPath> bindPaths, IEnumerable<ILibrarianExtension> extensions) : this(bindPaths)
        {
            this.LibrarianExtensions = extensions ?? Array.Empty<ILibrarianExtension>();
        }

        private ILookup<BindStage, BindPath> BindPaths { get; }

        public bool RebaseTarget { get; }

        public bool RebaseUpdated { get; }

        private IEnumerable<IBinderExtension> BinderExtensions { get; }

        private IEnumerable<ILibrarianExtension> LibrarianExtensions { get; }

        /// <summary>
        /// Copies a file.
        /// </summary>
        /// <param name="source">The file to copy.</param>
        /// <param name="destination">The destination file.</param>
        /// <param name="overwrite">true if the destination file can be overwritten; otherwise, false.</param>
        public bool CopyFile(string source, string destination, bool overwrite)
        {
            foreach (var extension in this.BinderExtensions)
            {
                if (extension.CopyFile(source, destination, overwrite))
                {
                    return true;
                }
            }

            if (overwrite && File.Exists(destination))
            {
                File.Delete(destination);
            }

            if (!CreateHardLink(destination, source, IntPtr.Zero))
            {
#if DEBUG
                int er = Marshal.GetLastWin32Error();
#endif

                File.Copy(source, destination, overwrite);
            }

            return true;
        }

        /// <summary>
        /// Moves a file.
        /// </summary>
        /// <param name="source">The file to move.</param>
        /// <param name="destination">The destination file.</param>
        public bool MoveFile(string source, string destination, bool overwrite)
        {
            foreach (var extension in this.BinderExtensions)
            {
                if (extension.MoveFile(source, destination, overwrite))
                {
                    return true;
                }
            }

            if (overwrite && File.Exists(destination))
            {
                File.Delete(destination);
            }

            var directory = Path.GetDirectoryName(destination);
            if (!String.IsNullOrEmpty(directory))
            {
                Directory.CreateDirectory(directory);
            }

            File.Move(source, destination);

            return true;
        }

        public string Resolve(SourceLineNumber sourceLineNumbers, string table, string path)
        {
            foreach (var extension in this.LibrarianExtensions)
            {
                var resolved = extension.Resolve(sourceLineNumbers, table, path);

                if (null != resolved)
                {
                    return resolved;
                }
            }

            return this.ResolveUsingBindPaths(path, table, sourceLineNumbers, BindStage.Normal);
        }

        /// <summary>
        /// Resolves the source path of a file using binder extensions.
        /// </summary>
        /// <param name="source">Original source value.</param>
        /// <param name="type">Optional type of source file being resolved.</param>
        /// <param name="sourceLineNumbers">Optional source line of source file being resolved.</param>
        /// <param name="bindStage">The binding stage used to determine what collection of bind paths will be used</param>
        /// <returns>Should return a valid path for the stream to be imported.</returns>
        public string ResolveFile(string source, string type, SourceLineNumber sourceLineNumbers, BindStage bindStage)
        {
            foreach (var extension in this.BinderExtensions)
            {
                var resolved = extension.ResolveFile(source, type, sourceLineNumbers, bindStage);

                if (null != resolved)
                {
                    return resolved;
                }
            }

            return this.ResolveUsingBindPaths(source, type, sourceLineNumbers, bindStage);
        }

        private string ResolveUsingBindPaths(string source, string type, SourceLineNumber sourceLineNumbers, BindStage bindStage)
        {
            string resolved = null;

            // If the file exists, we're good to go.
            if (CheckFileExists(source))
            {
                resolved = source;
            }
            else if (Path.IsPathRooted(source)) // path is rooted so bindpaths won't help, bail since the file apparently doesn't exist.
            {
                resolved = null;
            }
            else // not a rooted path so let's try applying all the different source resolution options.
            {
                string bindName = String.Empty;
                var path = source;
                string pathWithoutSourceDir = null;

                if (source.StartsWith(BindPathOpenString, StringComparison.Ordinal))
                {
                    int closeParen = source.IndexOf(')', BindPathOpenString.Length);
                    if (-1 != closeParen)
                    {
                        bindName = source.Substring(BindPathOpenString.Length, closeParen - BindPathOpenString.Length);
                        path = source.Substring(BindPathOpenString.Length + bindName.Length + 1); // +1 for the closing brace.
                        path = path.TrimStart('\\'); // remove starting '\\' char so the path doesn't look rooted.
                    }
                }
                else if (source.StartsWith("SourceDir\\", StringComparison.Ordinal) || source.StartsWith("SourceDir/", StringComparison.Ordinal))
                {
                    pathWithoutSourceDir = path.Substring(10);
                }

                var bindPaths = this.BindPaths[bindStage];

                foreach (var bindPath in bindPaths)
                {
                    if (!String.IsNullOrEmpty(pathWithoutSourceDir))
                    {
                        var filePath = Path.Combine(bindPath.Path, pathWithoutSourceDir);

                        if (CheckFileExists(filePath))
                        {
                            resolved = filePath;
                        }
                    }

                    if (String.IsNullOrEmpty(resolved))
                    {
                        var filePath = Path.Combine(bindPath.Path, path);

                        if (CheckFileExists(filePath))
                        {
                            resolved = filePath;
                        }
                    }
                }
            }

            if (null == resolved)
            {
                throw new WixFileNotFoundException(sourceLineNumbers, source, type);
            }

            // Didn't find the file.
            return resolved;
        }

        private static bool CheckFileExists(string path)
        {
            try
            {
                return File.Exists(path);
            }
            catch (ArgumentException)
            {
                throw new WixException(WixErrors.IllegalCharactersInPath(path));
            }
        }

        [DllImport("Kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
        private static extern bool CreateHardLink(string lpFileName, string lpExistingFileName, IntPtr lpSecurityAttributes);
    }
}