forked from ch-robinson/dotnet-avro
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathClrTypeOptions.cs
76 lines (70 loc) · 2.29 KB
/
ClrTypeOptions.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
73
74
75
76
using System;
using System.IO;
using System.Reflection;
namespace Chr.Avro.Cli
{
public interface IClrTypeOptions
{
string AssemblyName { get; }
string TypeName { get; }
}
internal static class TypeOptionExtensions
{
public static Assembly ResolveAssembly(this IClrTypeOptions options)
{
if (string.IsNullOrEmpty(options.AssemblyName))
{
return null;
}
try
{
return Assembly.Load(options.AssemblyName);
}
catch (FileNotFoundException)
{
// nbd
}
catch (FileLoadException)
{
// also nbd
}
try
{
return Assembly.LoadFrom(Path.GetFullPath(options.AssemblyName));
}
catch (FileNotFoundException)
{
throw new ProgramException(message: "The assembly could not be found. Make sure that you’ve provided either a recognizable name (e.g. System.Runtime) or a valid assembly path.");
}
catch (BadImageFormatException)
{
throw new ProgramException(message: "The assembly is not valid. Check that the path you’re providing points to a valid assembly file.");
}
}
public static Type ResolveType(this IClrTypeOptions options)
{
if (options.ResolveAssembly() is var assembly && assembly == null)
{
try
{
return Type.GetType(options.TypeName, ignoreCase: true, throwOnError: true);
}
catch (TypeLoadException)
{
throw new ProgramException(message: "The type could not be found. You may need to provide an assembly as well.");
}
}
else
{
try
{
return assembly.GetType(options.TypeName, ignoreCase: true, throwOnError: true);
}
catch (TypeLoadException)
{
throw new ProgramException(message: "The type could not be found in the provided assembly.");
}
}
}
}
}