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

HicServices / RDMP / 8390842418

22 Mar 2024 01:09PM UTC coverage: 56.855% (+0.001%) from 56.854%
8390842418

push

github

JFriel
tidy up

10818 of 20503 branches covered (52.76%)

Branch coverage included in aggregate %.

30816 of 52725 relevant lines covered (58.45%)

7369.15 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
                                var newIsLatest = GetReleaseCandidateId(pluginFile) > GetReleaseCandidateId(PluginPathLookup[name]);
×
86
                                if (newIsLatest)
×
87
                                {
88
                                    PluginVersionLookup[name] = version;
×
89
                                    PluginPathLookup[name] = pluginFile;
×
90
                                }
91
                            } else if (newIsReleaseCandidate)
×
92
                            {
93
                                //new version is the latest
94
                                PluginVersionLookup[name] = version;
×
95
                                PluginPathLookup[name] = pluginFile;
×
96
                            }
97

98

99

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

110
            }
111

112
        }
113

114
        return PluginPathLookup;
×
115
    }
116

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

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

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

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

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

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

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

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

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

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

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

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

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

209
            File.WriteAllLines(tmp, list.Union([toCommit.Name]));
×
210
            File.Move(tmp, PluginsList, true);
×
211
        }
×
212
        catch (Exception e)
×
213
        {
214
            checkNotifier.OnCheckPerformed(new CheckEventArgs($"Failed copying plugin {toCommit.Name}",
×
215
                CheckResult.Fail, e));
×
216
            throw;
×
217
        }
218
    }
×
219
}
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