-
Notifications
You must be signed in to change notification settings - Fork 437
/
WixHelper.scala
276 lines (260 loc) · 11.6 KB
/
WixHelper.scala
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
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
package com.typesafe.sbt
package packager
package windows
import Keys._
import sbt._
import collection.mutable.ArrayBuffer
case class WindowsProductInfo(
id: String, // UUID of the package
title: String, // Human readable name of the package
version: String, // Windows version
maintainer: String,
description: String,
upgradeId: String, // UUID for upgrading
comments: String = "",
installScope: String = "perMachine",
installerVersion: String = "200",
compressed: Boolean = true)
sealed trait FeatureComponent
/** Define a new feature, that will be selectable in the default MSI. */
case class WindowsFeature(
id: String,
title: String,
desc: String,
absent: String = "allow",
level: String = "1",
display: String = "collapse",
components: Seq[FeatureComponent] = Seq.empty) extends FeatureComponent {}
/** Adds a file into a given windows feature. */
case class ComponentFile(
source: String,
editable: Boolean = false) extends FeatureComponent
/**
* Will add the directory to the windows path. NOTE: Only one of these
* per MSI.
*/
case class AddDirectoryToPath(dir: String = "") extends FeatureComponent
case class AddShortCuts(
target: Seq[String],
workingDir: String = "INSTALLDIR") extends FeatureComponent
// TODO - Shortcut as a component element.
/** Helper functions to deal with Wix/CAB craziness. */
object WixHelper {
/** Generates a windows friendly GUID for use in random locations in the build. */
def makeGUID: String = java.util.UUID.randomUUID.toString
// TODO - Fragment out this function a bit so it's not so ugly/random.
def makeWixProductConfig(name: String, product: WindowsProductInfo, features: Seq[WindowsFeature], license: Option[File] = None): scala.xml.Node = {
// TODO - First we find directories...
// Adds all subdirectories... there was a bug when there were directories with only subdirs and no files in the tree,
// so there was a gap and dirXml failed to create some directories
def allParentDirs(f: File): Seq[File] = Option(f).toSeq.flatMap(f => f +: allParentDirs(f.getParentFile))
val filenamesPrep =
for {
f <- features
ComponentFile(name, _) <- f.components
} yield allParentDirs(file(name))
val filenames = filenamesPrep.flatten.map(_.toString.replaceAll("\\\\", "/")).filter(_ != "")
// Now for directories...
def parentDir(filename: String) = { filename take (filename lastIndexOf '/') }
def simpleName(filename: String) = {
val lastSlash =
if (filename contains '/') filename lastIndexOf '/'
else filename lastIndexOf '\\'
filename drop (lastSlash + 1)
}
val dirs = (filenames map parentDir).distinct;
// Now we need our directory tree xml?
val dirToChildren = dirs groupBy parentDir;
def dirXml(currentDir: String): scala.xml.Node = if (!currentDir.isEmpty) {
val children = dirToChildren.getOrElse(currentDir, Seq.empty)
<Directory Id={ cleanStringForId(currentDir) } Name={ simpleName(currentDir) }>
{
children map dirXml
}
</Directory>
} else <!-- -->
// We need component helpers...
case class ComponentInfo(id: String, xml: scala.xml.Node)
def makeComponentInfo(c: FeatureComponent): ComponentInfo = c match {
case w: WindowsFeature => sys.error("Nested windows features currently unsupported!")
case AddDirectoryToPath(dir) =>
val dirRef = if (dir.isEmpty) "INSTALLDIR" else cleanStringForId(dir)
val homeEnvVar = archetypes.JavaAppBatScript.makeEnvFriendlyName(name) + "_HOME"
val pathAddition =
if (dir.isEmpty) "%" + homeEnvVar + "%"
else "[INSTALLDIR]" + dir.replaceAll("\\/", "\\\\")
val id = cleanStringForId(dir).takeRight(65) + "PathC"
val guid = makeGUID
val xml =
<DirectoryRef Id={ dirRef }>
<Component Id={ id } Guid={ guid }>
<CreateFolder/>
<Environment Id={ homeEnvVar } Name={ homeEnvVar } Value="[INSTALLDIR]" Permanent="no" Action="set" System="yes"/>
<Environment Id="PATH" Name="PATH" Value={ pathAddition } Permanent="no" Part="last" Action="set" System="yes"/>
</Component>
</DirectoryRef>
ComponentInfo(id, xml)
case ComponentFile(name, editable) =>
val uname = name.replaceAll("\\\\", "/")
val dir = parentDir(uname).replaceAll("//", "/").stripSuffix("/").stripSuffix("/")
val dirRef = if (dir.isEmpty) "INSTALLDIR" else cleanStringForId(dir)
val fname = simpleName(uname)
val id = cleanStringForId(uname).takeRight(67) // Room for "fl_"
val xml =
<DirectoryRef Id={ dirRef }>
<Component Id={ id } Guid={ makeGUID }>
<File Id={ "fl_" + id } Name={ cleanFileName(fname) } DiskId='1' Source={ cleanFileName(uname) }>
{
if (editable) {
<xml:group>
<util:PermissionEx User="Administrators" GenericAll="yes"/>
<util:PermissionEx User="Users" GenericAll="yes"/>
</xml:group>
} else Seq.empty
}
</File>
</Component>
</DirectoryRef>
ComponentInfo(id, xml)
// TODO - To have shortcuts, you MUST put something in the registry. Here,
// We should have shortcuts actually provide us with what they want in the registry,
// rather than forcing it to be something.
// Also, we need some mechanism to ensure the start menu folder is removed in the event
// that we remove all menu items.
case AddShortCuts(targets, workingDir) =>
val targetSize = targets.size.toString.size
val id = cleanStringForId("shortcut_" + makeGUID).takeRight(67 - targetSize) // Room for "_SC"+incremental number
val xml =
<DirectoryRef Id="ApplicationProgramsFolder">
<Component Id={ id } Guid={ makeGUID }>
{
for ((target, i) <- targets.zipWithIndex) yield {
val name = simpleName(target)
val desc = "Edit configuration file: " + name
val cleanName = name.replaceAll("[\\.-\\\\//]+", "_")
<Shortcut Id={ id + "_SC" + (s"%0${targetSize}d").format(i+1) } Name={ cleanName } Description={ desc } Target={ "[INSTALLDIR]\\" + target.replaceAll("\\/", "\\\\") } WorkingDirectory="INSTALLDIR"/>
}
}
<RemoveFolder Id="ApplicationProgramsFolderRemove" Directory="ApplicationProgramsFolder" On="uninstall"/>
<RegistryValue Root="HKCU" Key={ "Software\\" + product.maintainer + "\\" + name } Name="installed" Type="integer" Value="1" KeyPath="yes"/>
</Component>
</DirectoryRef>
ComponentInfo(id, xml)
}
val componentMap =
(for (f <- features) yield {
// TODO - we need to support more than "Component File".
val componentInfos =
f.components map makeComponentInfo
f.id -> componentInfos
}).toMap
<xml:group>
<!-- Define the directories we use -->
<Directory Id='TARGETDIR' Name='SourceDir'>
<Directory Id="ProgramMenuFolder">
<Directory Id="ApplicationProgramsFolder" Name={ name }/>
</Directory>
<Directory Id='ProgramFilesFolder' Name='PFiles'>
<Directory Id='INSTALLDIR' Name={ name }>
{ dirToChildren("") map dirXml }
</Directory>
</Directory>
</Directory>
<!-- Now define the components -->
{
for {
(fid, components) <- componentMap
ComponentInfo(cid, xml) <- components
} yield xml
}
<!-- Now define the features! -->
<Feature Id='Complete' Title={ product.title } Description={ product.description } Display='expand' Level='1' ConfigurableDirectory='INSTALLDIR'>
{
for (f <- features)
yield <Feature Id={ f.id } Title={ f.title } Description={ f.desc } Level={ f.level } Absent={ f.absent }>
{
for (ComponentInfo(id, _) <- componentMap.getOrElse(f.id, Seq.empty))
yield <ComponentRef Id={ id }/>
}
</Feature>
}
</Feature>
<MajorUpgrade AllowDowngrades="no" Schedule="afterInstallInitialize" DowngradeErrorMessage="A later version of [ProductName] is already installed. Setup will now exit."/>
<UIRef Id="WixUI_FeatureTree"/>
<UIRef Id="WixUI_ErrorProgressText"/>
<Property Id="WIXUI_INSTALLDIR" Value="INSTALLDIR"/>
{
license.toSeq map { file =>
<WixVariable Id="WixUILicenseRtf" Value={ file.getAbsolutePath }/>
}
}
</xml:group>
}
def makeWixConfig(
name: String, // package name
product: WindowsProductInfo,
rest: xml.Node): xml.Node = {
<Wix xmlns='http://schemas.microsoft.com/wix/2006/wi' xmlns:util='http://schemas.microsoft.com/wix/UtilExtension'>
<Product Id={ product.id } Name={ product.title } Language='1033' Version={ product.version } Manufacturer={ product.maintainer } UpgradeCode={ product.upgradeId }>
<Package Description={ product.description } Comments={ product.comments } Manufacturer={ product.maintainer } InstallScope={ product.installScope } InstallerVersion={ product.installerVersion } Compressed={ if (product.compressed) "yes" else "no" }/>
<Media Id='1' Cabinet={ cleanStringForId(name.toLowerCase).takeRight(66) + ".cab" } EmbedCab='yes'/>
{ rest }
</Product>
</Wix>
}
/**
* Modifies a string to be Wix ID friendly by removing all the bad
* characters and replacing with _. Also limits the width to 70 (rather than
* 72) so we can safely add a few later.
*/
def cleanStringForId(n: String) = {
n.replaceAll("[^0-9a-zA-Z_]", "_").takeRight(60) + (math.abs(n.hashCode).toString + "xxxxxxxxx").substring(0, 9)
}
/** Cleans a file name for the Wix pre-processor. Every $ should be doubled. */
def cleanFileName(n: String) = {
n.replaceAll("\\$", "\\$\\$").replaceAll("\\/", "\\\\")
}
/** Takes a file and generates an ID for it. */
def makeIdFromFile(f: File) = cleanStringForId(f.getName)
/**
* Constructs a set of componentRefs and the directory/file WIX for
* all files in a given directory.
*
* @return A tuple where the first item is all the Component Ids created,
* and the second is the Directory/File/Component XML.
*/
@deprecated
def generateComponentsAndDirectoryXml(dir: File, id_prefix: String = ""): (Seq[String], scala.xml.Node) = {
def makeId(f: File) = cleanStringForId(IO.relativize(dir, f) map (id_prefix+) getOrElse (id_prefix + f.getName))
def handleFile(f: File): (Seq[String], scala.xml.Node) = {
val id = makeId(f)
val xml = (
<Component Id={ id } Guid='*'>
<File Id={ cleanStringForId(id + "_file") } Name={ cleanFileName(f.getName) } DiskId='1' Source={ cleanFileName(f.getAbsolutePath) }/>
</Component>
)
(Seq(id), xml)
}
def handleDirectory(dir: File): (Seq[String], scala.xml.Node) = {
val buf: ArrayBuffer[String] = ArrayBuffer.empty
val xml = (
<Directory Id={ makeId(dir) } Name={ dir.getName }>
{
for {
file <- IO.listFiles(dir)
(ids, xml) = recursiveHelper(file)
} yield {
buf.appendAll(ids)
xml
}
}
</Directory>
)
(buf.toSeq, xml)
}
def recursiveHelper(f: File): (Seq[String], scala.xml.Node) =
if (f.isDirectory) handleDirectory(f)
else handleFile(f)
recursiveHelper(dir)
}
}