/
Zip.cs
73 lines (61 loc) · 2.42 KB
/
Zip.cs
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
using System;
using System.IO;
using System.Linq;
using System.Text;
using Microsoft.Build.Framework;
using Microsoft.Build.Utilities;
using Xamarin.Tools.Zip;
using IOFile = System.IO.File;
namespace Xamarin.Android.Tools.BootstrapTasks
{
public sealed class Zip : Task
{
[Required]
public ITaskItem File { get; set; }
public ITaskItem[] Entries { get; set; }
public ITaskItem Prefix { get; set; }
public bool Overwrite { get; set; }
public override bool Execute ()
{
Log.LogMessage (MessageImportance.Low, $"Task {nameof (Zip)}");
Log.LogMessage (MessageImportance.Low, $" {nameof (File)}: {File.ItemSpec}");
Log.LogMessage (MessageImportance.Low, $" {nameof (Entries)}:");
foreach (var p in Entries ?? Array.Empty<ITaskItem> ()) {
Log.LogMessage (MessageImportance.Low, $" {p.ItemSpec}");
}
Log.LogMessage (MessageImportance.Low, $" {nameof (Overwrite)}: {Overwrite}");
Log.LogMessage (MessageImportance.Low, $" {nameof (Prefix)}: {Prefix?.ItemSpec}");
if (Overwrite) {
IOFile.Delete (File.ItemSpec);
}
var prefix = Prefix == null ? null : Path.GetFullPath (Prefix.ItemSpec);
if (!string.IsNullOrEmpty (prefix) && !prefix.EndsWith (Path.DirectorySeparatorChar.ToString (), StringComparison.OrdinalIgnoreCase)) {
prefix += Path.DirectorySeparatorChar;
}
using (var zip = ZipArchive.Open (File.ItemSpec, FileMode.OpenOrCreate)) {
if (Entries == null)
return !Log.HasLoggedErrors;
foreach (var entry in Entries) {
if (!IOFile.Exists (entry.ItemSpec)) {
Log.LogWarning ($"Could not add file '{entry.ItemSpec}' to file '{File.ItemSpec}'. Skipping...");
continue;
}
var zipDir = (string) null;
var entryPath = Path.GetFullPath (entry.ItemSpec);
var entryDir = Path.GetDirectoryName (entryPath);
if (prefix != null && entryDir.StartsWith (prefix, StringComparison.OrdinalIgnoreCase)) {
zipDir = entryDir.Substring (prefix.Length);
}
if (string.IsNullOrEmpty (zipDir)) {
// JonP can't figure out how to actually clear the archive directory name
// using AddFileToDirectory(). This works as desired.
zip.AddFile (entryPath, Path.GetFileName (entryPath));
} else {
zip.AddFileToDirectory (entryPath, zipDir, useFileDirectory: false);
}
}
}
return !Log.HasLoggedErrors;
}
}
}