• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

HicServices / RDMP / 8389996116

22 Mar 2024 12:05PM UTC coverage: 56.854% (-0.02%) from 56.872%
8389996116

push

github

JFriel
add todo note

10817 of 20503 branches covered (52.76%)

Branch coverage included in aggregate %.

30816 of 52725 relevant lines covered (58.45%)

7374.1 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

8.21
/Rdmp.Core/Curation/Data/LoadModuleAssembly.cs
1
// Copyright (c) The University of Dundee 2018-2024
2
// This file is part of the Research Data Management Platform (RDMP).
3
// RDMP is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
4
// RDMP is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
5
// You should have received a copy of the GNU General Public License along with RDMP. If not, see <https://www.gnu.org/licenses/>.
6

7
using System;
8
using System.Collections.Generic;
9
using System.IO;
10
using System.Linq;
11
using System.Xml;
12
using ICSharpCode.SharpZipLib.Zip;
13
using Rdmp.Core.ReusableLibraryCode.Checks;
14

15
namespace Rdmp.Core.Curation.Data;
16

17
/// <summary>
18
/// This entity wraps references to plugin .nupkg files on disk.
19
/// </summary>
20
public sealed class LoadModuleAssembly
21
{
22
    private static readonly bool IsWin = AppDomain.CurrentDomain.GetAssemblies()
4✔
23
        .Any(static a => a.FullName?.StartsWith("Rdmp.UI", StringComparison.Ordinal) == true);
354!
24

25
    private static readonly string PluginsList = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "rdmpplugins.txt");
4✔
26

27
    internal static readonly List<LoadModuleAssembly> Assemblies = [];
4✔
28
    private readonly FileInfo _file;
29

30
    private LoadModuleAssembly(FileInfo file)
×
31
    {
32
        _file = file;
×
33
    }
×
34

35

36
    private static bool IsReleaseCandidcate(string filename)
37
    {
38
        return filename.Split('.')[^2].Contains("-rc");
×
39
    }
40

41
    private static int GetReleaseCandidateId(string filename)
42
    {
43
        //expects the rc to be something like My.Plugin.3.0.0-rc2
44
        int.TryParse(filename.Split("-rc")[1].Split('.')[0], out var result);
×
45
        return result;
×
46
    }
47

48
    private static Dictionary<string, string> HandlePluginVersioning()
49
    {
50
        var PluginVersionLookup = new Dictionary<string, string>();
×
51
        var PluginPathLookup = new Dictionary<string, string>();
×
52
        var pluginFiles = Directory.EnumerateFiles(AppDomain.CurrentDomain.BaseDirectory, "*.rdmp");
×
53
        foreach (var pluginFile in pluginFiles)
×
54
        {
55
            using FileStream fs = new(pluginFile, FileMode.Open);
×
56
            using ZipFile zip = new(fs);
×
57
            foreach (ZipEntry ze in zip)
×
58
            {
59
                if (ze.Name.Contains(".nuspec"))
×
60
                {
61
                    using StreamReader sr = new StreamReader(zip.GetInputStream(ze.ZipFileIndex));
×
62
                    var content = sr.ReadToEnd();
×
63
                    var xmlDoc = new XmlDocument();
×
64
                    xmlDoc.LoadXml(content);
×
65

66
                    var name = xmlDoc.GetElementsByTagName("id").Item(0).InnerText;
×
67
                    var version = xmlDoc.GetElementsByTagName("version").Item(0).InnerText;
×
68
                    if (PluginVersionLookup.TryGetValue(name, out var currentVersion))
×
69
                    {
70
                        //already found a version
71
                        var result = new Version(currentVersion).CompareTo(new Version(version));
×
72
                        if (result < 0)
×
73
                        {
74
                            //this version is the latest version
75
                            PluginVersionLookup[name] = version;
×
76
                            PluginPathLookup[name] = pluginFile;
×
77
                        }
78
                        if(result == 0)
×
79
                        {
80
                            //check for RC in the name
81
                            var currentIsReleaseCandidate = IsReleaseCandidcate(PluginPathLookup[name]);
×
82
                            var newIsReleaseCandidate = IsReleaseCandidcate(pluginFile);
×
83
                            if(newIsReleaseCandidate && currentIsReleaseCandidate)
×
84
                            {
85
                                //could this use the archive file creation date instead of trying to parse from the file name??
86
                                var newIsLatest = GetReleaseCandidateId(pluginFile) > GetReleaseCandidateId(PluginPathLookup[name]);
×
87
                                if (newIsLatest)
×
88
                                {
89
                                    PluginVersionLookup[name] = version;
×
90
                                    PluginPathLookup[name] = pluginFile;
×
91
                                }
92
                            } else if (newIsReleaseCandidate)
×
93
                            {
94
                                //new version is the latest
95
                                PluginVersionLookup[name] = version;
×
96
                                PluginPathLookup[name] = pluginFile;
×
97
                            }
98

99

100

101
                        }
102
                    }
103
                    else
104
                    {
105
                        PluginVersionLookup[name] = version;
×
106
                        PluginPathLookup[name] = pluginFile;
×
107
                    }
108
                    break;
×
109
                }
110

111
            }
112

113
        }
114

115
        return PluginPathLookup;
×
116
    }
117

118
    /// <summary>
119
    /// List the plugin files to load
120
    /// </summary>
121
    /// <returns></returns>
122
    internal static IEnumerable<string> PluginFiles()
123
    {
124
        if (Directory.EnumerateFiles(AppDomain.CurrentDomain.BaseDirectory, "*.rdmp").Count() > 0)
16!
125
        {
126
            //use the modern .RDMP plugins
127
            var plugins = HandlePluginVersioning();
×
128
            return plugins.Values.ToArray();
×
129

130
        }
131
        return File.Exists(PluginsList)
16!
132
            ? File.ReadAllLines(PluginsList)
16✔
133
                .Select(static name => Path.Combine(AppDomain.CurrentDomain.BaseDirectory, name))
×
134
            : Directory.EnumerateFiles(AppDomain.CurrentDomain.BaseDirectory, "*.nupkg");
16✔
135
    }
136

137
    /// <summary>
138
    /// Unpack the plugin DLL files, excluding any Windows UI specific dlls when not running a Windows GUI
139
    /// </summary>
140
    internal static IEnumerable<(string, MemoryStream)> GetContents(string path)
141
    {
142
        var info = new FileInfo(path);
×
143
        if (!info.Exists || info.Length < 100) yield break; // Ignore missing or empty files
×
144

145
        var pluginStream = info.OpenRead();
×
146
        if (!pluginStream.CanSeek)
×
147
            throw new ArgumentException("Seek needed", nameof(path));
×
148

149
        Assemblies.Add(new LoadModuleAssembly(info));
×
150

151
        using var zip = new ZipFile(pluginStream);
×
152
        foreach (var e in zip.Cast<ZipEntry>()
×
153
                     .Where(static e => e.IsFile && e.Name.EndsWith(".dll", StringComparison.OrdinalIgnoreCase) &&
154
                                        (IsWin || !e.Name.Contains("/windows/"))))
155
        {
156
            using var s = zip.GetInputStream(e);
×
157
            using var ms2 = new MemoryStream();
×
158
            s.CopyTo(ms2);
×
159
            ms2.Position = 0;
×
160
            yield return (e.Name, ms2);
×
161
        }
×
162
    }
×
163

164
    /// <summary>
165
    /// Copy the plugin nupkg to the given directory
166
    /// </summary>
167
    /// <param name="downloadDirectory"></param>
168
    public void DownloadAssembly(DirectoryInfo downloadDirectory)
169
    {
170
        if (!downloadDirectory.Exists)
×
171
            downloadDirectory.Create();
×
172
        var targetFile = Path.Combine(downloadDirectory.FullName, _file.Name);
×
173
        _file.CopyTo(targetFile, true);
×
174
    }
×
175

176
    /// <summary>
177
    /// Delete the plugin file from disk, and remove it from rdmpplugins.txt if in use
178
    /// </summary>
179
    public void Delete()
180
    {
181
        _file.Delete();
×
182
        if (!File.Exists(PluginsList)) return;
×
183

184
        var tmp = $"{PluginsList}.tmp";
×
185
        File.WriteAllLines(tmp, File.ReadAllLines(PluginsList).Where(l => !l.Contains(_file.Name)));
×
186
        File.Move(tmp, PluginsList, true);
×
187
    }
×
188

189
    public override string ToString() => _file.Name;
×
190

191
    public static void UploadFile(ICheckNotifier checkNotifier, FileInfo toCommit)
192
    {
193
        try
194
        {
195
            toCommit.CopyTo(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, toCommit.Name), true);
×
196
            if (!File.Exists(PluginsList)) return;
×
197

198
            // Now the tricky bit: add this new file, and remove any other versions of the same
199
            // e.g. adding DummyPlugin-1.2.3 should delete DummyPlugin-2.0 and DummyPlugin-1.0 if present
200
            var list = File.ReadAllLines(PluginsList);
×
201
            var tmp = $"{PluginsList}.tmp";
×
202

203
            var versionPos = toCommit.Name.IndexOf('-');
×
204
            if (versionPos != -1)
×
205
            {
206
                var stub = toCommit.Name[..(versionPos + 1)];
×
207
                list = list.Where(l => !l.StartsWith(stub, StringComparison.OrdinalIgnoreCase)).ToArray();
×
208
            }
209

210
            File.WriteAllLines(tmp, list.Union([toCommit.Name]));
×
211
            File.Move(tmp, PluginsList, true);
×
212
        }
×
213
        catch (Exception e)
×
214
        {
215
            checkNotifier.OnCheckPerformed(new CheckEventArgs($"Failed copying plugin {toCommit.Name}",
×
216
                CheckResult.Fail, e));
×
217
            throw;
×
218
        }
219
    }
×
220
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc