Repository navigation
Expand file tree
/
Copy pathFieldCompatibility.cs
More file actions
55 lines (48 loc) · 2.4 KB
/
Copy pathFieldCompatibility.cs
File metadata and controls
55 lines (48 loc) · 2.4 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
namespace PythonScriptRunner;
/// <summary>Which source types can feed which target types in a binding (spec 003, safe widenings only).</summary>
public static class FieldCompatibility
{
/// <summary>Whether a value of <paramref name="source"/> can be bound to <paramref name="target"/>.</summary>
/// <param name="source">Field that produces the value.</param>
/// <param name="target">Field that receives it.</param>
public static bool IsAssignable(FieldDefinition source, FieldDefinition target)
{
ArgumentNullException.ThrowIfNull(source);
ArgumentNullException.ThrowIfNull(target);
return IsAssignable(source.Type, target.Type, source, target);
}
private static bool IsAssignable(FieldType source, FieldType target, FieldDefinition sourceField, FieldDefinition targetField)
{
if (target.Kind == FieldKind.Json)
{
return !source.IsFile;
}
return (source.Kind, target.Kind) switch
{
(FieldKind.Integer, FieldKind.Number or FieldKind.Decimal) => true,
(FieldKind.Enum, FieldKind.String) => true,
(FieldKind.Enum, FieldKind.Enum) => source.EnumValues!.All(v => target.EnumValues!.Contains(v, StringComparer.Ordinal)),
(FieldKind.Table, FieldKind.Table) => ColumnsCompatible(sourceField.Columns, targetField.Columns),
(FieldKind.File, FieldKind.File) => ContentTypesCompatible(sourceField.ContentTypes, targetField.ContentTypes),
(FieldKind.List, FieldKind.List) => IsAssignable(source.ItemType!, target.ItemType!, sourceField, targetField),
var (s, t) when s == t => true,
_ => false,
};
}
private static bool ColumnsCompatible(IReadOnlyList<TableColumn>? source, IReadOnlyList<TableColumn>? target)
{
if (target is not { Count: > 0 })
{
return true;
}
if (source is not { Count: > 0 })
{
return false;
}
return target.All(t => source.Any(s => s.Name == t.Name
&& IsAssignable(s.Type, t.Type, new FieldDefinition(s.Name, s.Type), new FieldDefinition(t.Name, t.Type))));
}
private static bool ContentTypesCompatible(IReadOnlyList<string>? source, IReadOnlyList<string>? target) =>
source is not { Count: > 0 } || target is not { Count: > 0 }
|| source.Intersect(target, StringComparer.OrdinalIgnoreCase).Any();
}