-
Notifications
You must be signed in to change notification settings - Fork 19
Expand file tree
/
Copy pathDeployRpsAddinCommand.cs
More file actions
335 lines (288 loc) · 13.8 KB
/
DeployRpsAddinCommand.cs
File metadata and controls
335 lines (288 loc) · 13.8 KB
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
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Reflection;
using System.Reflection.Emit;
using System.Xml.Linq;
using System.Windows.Forms;
using RevitPythonShell.RpsRuntime;
using System.Security.AccessControl;
using Autodesk.Navisworks.Api.Plugins;
namespace RevitPythonShell
{
/// <summary>
/// Ask the user for an RpsAddin xml file. Create a subfolder
/// with timestamp containing the deployable version of the RPS scripts.
///
/// This includes the RpsRuntime.dll (see separate project) that recreates some
/// of the RPS experience for canned commands.
/// </summary>
[PluginAttribute("RevitPythonShell.DeployRpsAddinCommand",
"ACOM",
ToolTip = "NPS plugin deployment",
DisplayName = "Deploy NPS Addin")]
public class DeployRpsAddinCommand: AddInPlugin
{
private string _outputFolder;
private string _rootFolder;
private string _addinName;
private XDocument _doc;
public override int Execute(params string[] parameters)
{
string message = "";
try
{
// read in rpsaddin.xml
var rpsAddinXmlPath = GetAddinXmlPath(); // FIXME: do some argument checking here
_addinName = Path.GetFileNameWithoutExtension(rpsAddinXmlPath);
_rootFolder = Path.GetDirectoryName(rpsAddinXmlPath);
_doc = XDocument.Load(rpsAddinXmlPath);
// create subfolder
_outputFolder = CreateOutputFolder();
// copy static stuff (rpsaddin runtime, ironpython dlls etc., addin installation utilities)
CopyFile(typeof(RpsExternalApplicationBase).Assembly.Location); // RpsRuntime.dll
var ironPythonPath = Path.GetDirectoryName(this.GetType().Assembly.Location);
CopyFile(Path.Combine(ironPythonPath, "IronPython.dll")); // IronPython.dll
CopyFile(Path.Combine(ironPythonPath, "IronPython.Modules.dll")); // IronPython.Modules.dll
CopyFile(Path.Combine(ironPythonPath, "Microsoft.Scripting.dll")); // Microsoft.Scripting.dll
CopyFile(Path.Combine(ironPythonPath, "Microsoft.Scripting.Metadata.dll")); // Microsoft.Scripting.Metadata.dll
CopyFile(Path.Combine(ironPythonPath, "Microsoft.Dynamic.dll")); // Microsoft.Dynamic.dll
// copy files mentioned (they must all be unique)
CopyIcons();
CopyExplicitFiles();
// create addin assembly
CreateAssembly();
MessageBox.Show("Deploy RpsAddin", "Deployment complete - see folder: " + _outputFolder);
return 0;
}
catch (Exception exception)
{
MessageBox.Show("Deploy RpsAddin", "Error deploying addin: " + exception.ToString() );
return -1;
}
}
/// <summary>
/// Copy any icon files mentioned in PushButton tags.
///
/// The PythonScript16x16.png and PythonScript32x32.png icons will be used as default,
/// if no icons are found (they are embedded in the RpsRuntime.dll)
///
/// as always, relative paths are assumed to be relative to rootFolder, that
/// is the folder that the RpsAddin xml file came from.
/// </summary>
private void CopyIcons()
{
HashSet<string> copiedIcons = new HashSet<string>();
foreach (var pb in _doc.Descendants("PushButton"))
{
CopyReferencedFileToOutputFolder(pb.Attribute("largeImage"));
CopyReferencedFileToOutputFolder(pb.Attribute("smallImage"));
}
}
/// <summary>
/// Copy a file to the output folder ("flat" folder structure!)
/// </summary>
private void CopyFile(string path)
{
File.Copy(path, Path.Combine(_outputFolder, Path.GetFileName(path)));
}
/// <summary>
/// Copy all files mentioned in /Files/File tags.
/// </summary>
private void CopyExplicitFiles()
{
foreach (var xmlFile in _doc.Descendants("Files").SelectMany(f => f.Descendants("File")))
{
var source = xmlFile.Attribute("src").Value;
var sourcePath = GetRootedPath(_rootFolder, source);
if (!File.Exists(sourcePath))
{
throw new FileNotFoundException(
"Could not find the explicitly referenced file",
source);
}
var fileName = Path.GetFileName(sourcePath);
File.Copy(sourcePath, Path.Combine(_outputFolder, fileName));
// remove path information for deployment
xmlFile.Attribute("src").Value = fileName;
}
}
/// <summary>
/// Copies a referenced file to the output folder, unless it could not find that
/// file.
/// </summary>
private void CopyReferencedFileToOutputFolder(XAttribute attr)
{
if (attr == null)
{
return;
}
var path = GetRootedPath(_rootFolder, attr.Value);
if (path != null)
{
if (!File.Exists(path))
{
throw new FileNotFoundException(
"Could not find the file referenced by attribute " + attr.Name,
attr.Value);
}
var fileName = Path.GetFileName(path);
File.Copy(path, Path.Combine(_outputFolder, fileName));
// make the new value relative, for the embedded RpsAddin xml
attr.Value = fileName;
}
}
/// <summary>
/// Show a FileDialog for the RpsAddinXml file and return the path.
/// </summary>
private string GetAddinXmlPath()
{
var dialog = new OpenFileDialog();
dialog.CheckFileExists = true;
dialog.CheckPathExists = true;
dialog.Multiselect = false;
dialog.DefaultExt = "xml";
dialog.Filter = "RpsAddin xml files (*.xml)|*.xml";
dialog.ShowDialog();
return dialog.FileName;
}
/// <summary>
/// Create a new dll Assembly in the outputFolder with the addinName and
/// add the RpsAddin xml file and all script files referenced by PushButton tags
/// as embedded resources, plus, for each such script, add a subclass of
/// RpsExternalCommand to load the script from.
/// </summary>
private void CreateAssembly()
{
var assemblyName = new AssemblyName { Name = _addinName + ".dll", Version = new Version(1, 0, 0, 0) }; // FIXME: read version from doc
var assemblyBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.RunAndSave, _outputFolder);
var moduleBuilder = assemblyBuilder.DefineDynamicModule("RpsAddinModule", _addinName + ".dll");
foreach (var xmlPushButton in _doc.Descendants("PushButton"))
{
string scriptFileName;
if (xmlPushButton.Attribute("src") != null)
{
scriptFileName = xmlPushButton.Attribute("src").Value;
}
else if (xmlPushButton.Attribute("script") != null) // Backwards compatibility
{
scriptFileName = xmlPushButton.Attribute("script").Value;
}
else
{
throw new ApplicationException("<PushButton/> tag missing a src attribute in addin manifest");
}
var scriptFile = GetRootedPath(_rootFolder, scriptFileName); // e.g. "C:\projects\helloworld\helloworld.py" or "..\helloworld.py"
var newScriptFile = Path.GetFileName(scriptFile); // e.g. "helloworld.py" - strip path for embedded resource
var className = "ec_" + Path.GetFileNameWithoutExtension(newScriptFile); // e.g. "ec_helloworld", "ec" stands for ExternalCommand
var scriptStream = File.OpenRead(scriptFile);
moduleBuilder.DefineManifestResource(newScriptFile, scriptStream, ResourceAttributes.Public);
// script has new path inside assembly, rename it for the RpsAddin xml file we intend to save as a resource
xmlPushButton.Attribute("src").Value = newScriptFile;
var typeBuilder = moduleBuilder.DefineType(
className,
TypeAttributes.Class | TypeAttributes.Public,
typeof(RpsExternalCommandBase));
// AddRegenerationAttributeToType(typeBuilder);
// AddTransactionAttributeToType(typeBuilder);
typeBuilder.CreateType();
}
// add StartupScript to addin assembly
if (_doc.Descendants("StartupScript").Count() > 0)
{
var tag = _doc.Descendants("StartupScript").First();
var scriptFile = GetRootedPath(_rootFolder, tag.Attribute("src").Value);
var newScriptFile = Path.GetFileName(scriptFile);
var scriptStream = File.OpenRead(scriptFile);
moduleBuilder.DefineManifestResource(newScriptFile, scriptStream, ResourceAttributes.Public);
// script has new path inside assembly, rename it for the RpsAddin xml file we intend to save as a resource
tag.Attribute("src").Value = newScriptFile;
}
AddRpsAddinXmlToAssembly(_addinName, _doc, moduleBuilder);
AddExternalApplicationToAssembly(_addinName, moduleBuilder);
assemblyBuilder.Save(_addinName + ".dll");
}
/// <summary>
/// Returns the possiblyRelativePath rooted in sourceFolder,
/// if it is relative or unchanged if it is absolute already.
/// if the input is null or an empty string, returns null.
/// </summary>
private static string GetRootedPath(string sourceFolder, string possiblyRelativePath)
{
if (string.IsNullOrEmpty(possiblyRelativePath))
{
return null;
}
if (!Path.IsPathRooted(possiblyRelativePath))
{
return Path.Combine(sourceFolder, possiblyRelativePath);
}
return possiblyRelativePath;
}
/// <summary>
/// Adds a subclass of RpsExternalApplicationBase to make the assembly
/// work as an external application.
/// </summary>
private void AddExternalApplicationToAssembly(string addinName, ModuleBuilder moduleBuilder)
{
var typeBuilder = moduleBuilder.DefineType(
addinName,
TypeAttributes.Class | TypeAttributes.Public,
typeof(RpsExternalApplicationBase));
// AddRegenerationAttributeToType(typeBuilder);
// AddTransactionAttributeToType(typeBuilder);
typeBuilder.CreateType();
}
// /// <summary>
// /// Adds the [Transaction(TransactionMode.Manual)] attribute to the type.
// /// </summary>
// private void AddTransactionAttributeToType(TypeBuilder typeBuilder)
// {
// var transactionConstructorInfo = typeof(TransactionAttribute).GetConstructor(new Type[] { typeof(TransactionMode) });
// var transactionAttributeBuilder = new CustomAttributeBuilder(transactionConstructorInfo, new object[] { TransactionMode.Manual });
// typeBuilder.SetCustomAttribute(transactionAttributeBuilder);
// }
//
// /// <summary>
// /// Adds the [Transaction(TransactionMode.Manual)] attribute to the type.
// /// </summary>
// /// <param name="typeBuilder"></param>
// private void AddRegenerationAttributeToType(TypeBuilder typeBuilder)
// {
// var regenerationConstrutorInfo = typeof(RegenerationAttribute).GetConstructor(new Type[] { typeof(RegenerationOption) });
// var regenerationAttributeBuilder = new CustomAttributeBuilder(regenerationConstrutorInfo, new object[] { RegenerationOption.Manual });
// typeBuilder.SetCustomAttribute(regenerationAttributeBuilder);
// }
private void AddRpsAddinXmlToAssembly(string addinName, XDocument doc, ModuleBuilder moduleBuilder)
{
var stream = new MemoryStream();
var writer = new StreamWriter(stream);
writer.Write(doc.ToString());
writer.Flush();
stream.Position = 0;
moduleBuilder.DefineManifestResource(addinName + ".xml", stream, ResourceAttributes.Public);
}
/// <summary>
/// Creates a subfolder in rootFolder with the basename of the
/// RpsAddin xml file and returns the name of that folder.
///
/// deletes previous folders.
///
/// result: "Output_HelloWorld"
/// </summary>
private string CreateOutputFolder()
{
var folderName = string.Format("{0}_{1}", "Output", _addinName);
var folderPath = Path.Combine(_rootFolder, folderName);
if (Directory.Exists(folderPath))
{
// delete existing folder
Directory.Delete(folderPath, true);
}
Directory.CreateDirectory(folderPath, Directory.GetAccessControl(_rootFolder));
return folderPath;
}
}
}