Esempio n. 1
0
 protected void WritePrependNewlines(TomlObject obj)
 {
     if (this.ShouldPrependWithNewline(obj))
     {
         this.writer.WriteLine();
     }
 }
Esempio n. 2
0
 protected void WriteAppendComments(TomlObject obj)
 {
     var append = obj.Comments.Where((c) => this.config.GetCommentLocation(c) == TomlCommentLocation.Append);
     foreach (var a in append)
     {
         this.writer.Write(" #");
         this.writer.Write(FixMultilineComment(a.Text));
     }
 }
Esempio n. 3
0
 protected void WritePrependComments(TomlObject obj)
 {
     var prepend = obj.Comments.Where((c) => this.config.GetCommentLocation(c) == TomlCommentLocation.Prepend);
     foreach (var p in prepend)
     {
         this.writer.Write('#');
         this.writer.Write(FixMultilineComment(p.Text));
         this.writer.WriteLine();
     }
 }
Esempio n. 4
0
        private static IEnumerable <TomlObject> ProcessArray(TomlObject obj, ReadOnlyMemory <char> pathM)
        {
            var path = pathM.Span;

            if (path[0] != '[')
            {
                throw new ArgumentException("Expected array open breacket", nameof(pathM));
            }
            for (int i = 1; i < path.Length; i++)
            {
                if (path[i] == ']')
                {
                    if (i == 0)
                    {
                        throw new ArgumentException("Empty array indexer", nameof(pathM));
                    }
                    var  indexer = path.Slice(1, i - 1);
                    var  rest    = pathM.Slice(i + 1);
                    bool cont    = rest.Length > 0;

                    // select
                    if (indexer.Length == 1 && indexer[0] == '*')
                    {
                        var ret = obj.GetAllArrayItems();
                        if (cont)
                        {
                            if (IsArray(rest.Span))
                            {
                                return(ret.SelectMany(x => ProcessArray(x, rest)));
                            }
                            else if (IsDot(rest.Span))
                            {
                                return(ret.SelectMany(x => ProcessDot(x, rest)));
                            }
                            else
                            {
                                throw new ArgumentException("Invalid expression after array indexer", nameof(pathM));
                            }
                        }

                        return(ret);
                    }
                    else
                    {
                        var ret = obj.GetArrayItemByIndex(indexer);
                        if (ret is null)
                        {
                            return(Enumerable.Empty <TomlObject>());
                        }

                        if (cont)
                        {
                            if (IsArray(rest.Span))
                            {
                                return(ProcessArray(ret, rest));
                            }
                            else if (IsDot(rest.Span))
                            {
                                return(ProcessDot(ret, rest));
                            }
                            else
                            {
                                throw new ArgumentException("Invalid expression after array indexer", nameof(pathM));
                            }
                        }
                        return(new[] { ret });
                    }
                }
            }
            throw new ArgumentException("Missing array close bracket", nameof(pathM));
        }
Esempio n. 5
0
        private static IEnumerable <TomlObject> ProcessIdentifier(TomlObject obj, ReadOnlyMemory <char> pathM)
        {
            if (pathM.IsEmpty)
            {
                return(Enumerable.Empty <TomlObject>());
            }

            var path = pathM.Span;

            switch (path[0])
            {
            case '*':
            {
                var rest = pathM.Slice(1);
                if (rest.IsEmpty)
                {
                    return(obj.GetAllSubItems());
                }

                if (IsArray(rest.Span))
                {
                    return(obj.GetAllSubItems().SelectMany(x => ProcessArray(x, rest)));
                }
                else if (IsDot(rest.Span))
                {
                    return(obj.GetAllSubItems().SelectMany(x => ProcessDot(x, rest)));
                }
                else
                {
                    throw new ArgumentException("Invalid expression after wildcard", nameof(pathM));
                }
            }

            case '[':
                throw new ArgumentException("Invalid array open bracket", nameof(pathM));

            case ']':
                throw new ArgumentException("Invalid array close bracket", nameof(pathM));

            case '.':
                throw new ArgumentException("Invalid dot", nameof(pathM));

            default:
            {
                var  subItemName = path;
                var  rest        = ReadOnlyMemory <char> .Empty;
                bool cont        = false;
                for (int i = 0; i < path.Length; i++)
                {
                    // todo allow in future
                    if (path[i] == '*')
                    {
                        throw new ArgumentException("Invalid wildcard position", nameof(pathM));
                    }

                    var currentSub = path.Slice(i);
                    if (!IsIdentifier(currentSub))                             // if (!IsName)
                    {
                        cont        = true;
                        subItemName = path.Slice(0, i);
                        rest        = pathM.Slice(i);
                        break;
                    }
                }
                var item = obj.GetSubItemByName(subItemName);
                if (item is null)
                {
                    return(Enumerable.Empty <TomlObject>());
                }

                if (cont)
                {
                    if (IsArray(rest.Span))
                    {
                        return(ProcessArray(item, rest));
                    }
                    else if (IsDot(rest.Span))
                    {
                        return(ProcessDot(item, rest));
                    }
                    else
                    {
                        throw new ArgumentException("Invalid expression name identifier", nameof(pathM));
                    }
                }
                return(new[] { item });
            }
            }
        }
Esempio n. 6
0
        // *** Convenience method for setting values to a toml object. ***

        public static TomlObject Set <T>(this TomlTable tomlTable, string key, T value)
        {
            if (tomlTable is null)
            {
                throw new ArgumentNullException(nameof(tomlTable));
            }
            if (key is null)
            {
                throw new ArgumentNullException(nameof(key));
            }

            // I literally have no idea how to write it better with this toml library.

            // Note for TimeSpan: since TimeSpan as Nett (de)serializes it is not standartized we have to cast it manually

            TomlObject retobj = tomlTable.TryGetValue(key);

            if (retobj is null)
            {
                if (typeof(T) == typeof(bool))
                {
                    return(tomlTable.Add(key, (bool)(object)value).Added);
                }
                else if (typeof(T) == typeof(string))
                {
                    return(tomlTable.Add(key, (string)(object)value).Added);
                }
                else if (typeof(T) == typeof(double))
                {
                    return(tomlTable.Add(key, (double)(object)value).Added);
                }
                else if (typeof(T) == typeof(float))
                {
                    return(tomlTable.Add(key, (float)(object)value).Added);
                }
                else if (typeof(T) == typeof(ushort))
                {
                    return(tomlTable.Add(key, /*auto*/ (ushort)(object)value).Added);
                }
                else if (typeof(T) == typeof(int))
                {
                    return(tomlTable.Add(key, (int)(object)value).Added);
                }
                else if (typeof(T) == typeof(long))
                {
                    return(tomlTable.Add(key, (long)(object)value).Added);
                }
                else if (typeof(T) == typeof(ulong))
                {
                    return(tomlTable.Add(key, (long)(ulong)(object)value).Added);
                }
                else if (typeof(T) == typeof(TimeSpan))
                {
                    return(tomlTable.Add(key, SerializeTime((TimeSpan)(object)value)).Added);
                }
                else if (typeof(T) == typeof(DateTime))
                {
                    return(tomlTable.Add(key, (DateTime)(object)value).Added);
                }
                else if (typeof(T).IsEnum)
                {
                    return(tomlTable.Add(key, value.ToString()).Added);
                }
                else if (value is IEnumerable <bool> enubool)
                {
                    return(tomlTable.Add(key, enubool).Added);
                }
                else if (value is IEnumerable <string> enustring)
                {
                    return(tomlTable.Add(key, enustring).Added);
                }
                else if (value is IEnumerable <double> enudouble)
                {
                    return(tomlTable.Add(key, enudouble).Added);
                }
                else if (value is IEnumerable <float> enufloat)
                {
                    return(tomlTable.Add(key, enufloat).Added);
                }
                else if (value is IEnumerable <ushort> enuushort)
                {
                    return(tomlTable.Add(key, enuushort.Select(x => (int)x)).Added);
                }
                else if (value is IEnumerable <int> enuint)
                {
                    return(tomlTable.Add(key, enuint).Added);
                }
                else if (value is IEnumerable <long> enulong)
                {
                    return(tomlTable.Add(key, enulong).Added);
                }
                else if (value is IEnumerable <ulong> enuulong)
                {
                    return(tomlTable.Add(key, enuulong.Select(x => (long)x)).Added);
                }
                else if (value is IEnumerable <TimeSpan> enuTimeSpan)
                {
                    return(tomlTable.Add(key, enuTimeSpan.Select(SerializeTime)).Added);
                }
                else if (value is IEnumerable <DateTime> enuDateTime)
                {
                    return(tomlTable.Add(key, enuDateTime).Added);
                }
            }
            else
            {
                TomlComment[] docs = null;
                if (retobj.Comments.Any())
                {
                    docs = retobj.Comments.ToArray();
                }
                if (typeof(T) == typeof(bool))
                {
                    retobj = tomlTable.Update(key, (bool)(object)value).Added;
                }
                else if (typeof(T) == typeof(string))
                {
                    retobj = tomlTable.Update(key, (string)(object)value).Added;
                }
                else if (typeof(T) == typeof(double))
                {
                    retobj = tomlTable.Update(key, (double)(object)value).Added;
                }
                else if (typeof(T) == typeof(float))
                {
                    retobj = tomlTable.Update(key, (float)(object)value).Added;
                }
                else if (typeof(T) == typeof(ushort))
                {
                    retobj = tomlTable.Update(key, /*auto*/ (ushort)(object)value).Added;
                }
                else if (typeof(T) == typeof(int))
                {
                    retobj = tomlTable.Update(key, /*auto*/ (int)(object)value).Added;
                }
                else if (typeof(T) == typeof(long))
                {
                    retobj = tomlTable.Update(key, (long)(object)value).Added;
                }
                else if (typeof(T) == typeof(ulong))
                {
                    retobj = tomlTable.Update(key, (long)(ulong)(object)value).Added;
                }
                else if (typeof(T) == typeof(TimeSpan))
                {
                    retobj = tomlTable.Update(key, SerializeTime((TimeSpan)(object)value)).Added;
                }
                else if (typeof(T) == typeof(DateTime))
                {
                    retobj = tomlTable.Update(key, (DateTime)(object)value).Added;
                }
                else if (typeof(T).IsEnum)
                {
                    retobj = tomlTable.Update(key, value.ToString()).Added;
                }
                else if (value is IEnumerable <bool> enubool)
                {
                    return(tomlTable.Update(key, enubool).Added);
                }
                else if (value is IEnumerable <string> enustring)
                {
                    return(tomlTable.Update(key, enustring).Added);
                }
                else if (value is IEnumerable <double> enudouble)
                {
                    return(tomlTable.Update(key, enudouble).Added);
                }
                else if (value is IEnumerable <float> enufloat)
                {
                    return(tomlTable.Update(key, enufloat).Added);
                }
                else if (value is IEnumerable <ushort> enuushort)
                {
                    return(tomlTable.Update(key, enuushort.Select(x => (int)x)).Added);
                }
                else if (value is IEnumerable <int> enuint)
                {
                    return(tomlTable.Update(key, enuint).Added);
                }
                else if (value is IEnumerable <long> enulong)
                {
                    return(tomlTable.Update(key, enulong).Added);
                }
                else if (value is IEnumerable <ulong> enuulong)
                {
                    return(tomlTable.Update(key, enuulong.Select(x => (long)x)).Added);
                }
                else if (value is IEnumerable <TimeSpan> enuTimeSpan)
                {
                    return(tomlTable.Update(key, enuTimeSpan.Select(SerializeTime)).Added);
                }
                else if (value is IEnumerable <DateTime> enuDateTime)
                {
                    return(tomlTable.Update(key, enuDateTime).Added);
                }
                else
                {
                    throw new NotSupportedException("The type is not supported");
                }
                if (docs != null)
                {
                    retobj.AddComments(docs);
                }
                return(retobj);
            }
            throw new NotSupportedException("The type is not supported");
        }
Esempio n. 7
0
        private static void DowngradeMelonPreferences(string destination, bool legacy_version)
        {
            if (!legacy_version || (Program.CurrentInstalledVersion == null) || (Program.CurrentInstalledVersion.CompareTo(new Version("0.3.0")) < 0))
            {
                return;
            }
            string userdatapath = Path.Combine(destination, "UserData");

            if (!Directory.Exists(userdatapath))
            {
                return;
            }
            string oldfilepath = Path.Combine(userdatapath, "MelonPreferences.cfg");

            if (!File.Exists(oldfilepath))
            {
                return;
            }
            string filestr = File.ReadAllText(oldfilepath);

            if (string.IsNullOrEmpty(filestr))
            {
                return;
            }
            DocumentSyntax docsyn = Toml.Parse(filestr);

            if (docsyn == null)
            {
                return;
            }
            TomlTable model = docsyn.ToModel();

            if (model.Count <= 0)
            {
                return;
            }
            string newfilepath = Path.Combine(userdatapath, "modprefs.ini");

            if (File.Exists(newfilepath))
            {
                File.Delete(newfilepath);
            }
            IniFile iniFile = new IniFile(newfilepath);

            foreach (KeyValuePair <string, object> keypair in model)
            {
                string    category_name = keypair.Key;
                TomlTable tbl           = (TomlTable)keypair.Value;
                if (tbl.Count <= 0)
                {
                    continue;
                }
                foreach (KeyValuePair <string, object> tblkeypair in tbl)
                {
                    string name = tblkeypair.Key;
                    if (string.IsNullOrEmpty(name))
                    {
                        continue;
                    }
                    TomlObject obj = TomlObject.ToTomlObject(tblkeypair.Value);
                    if (obj == null)
                    {
                        continue;
                    }
                    switch (obj.Kind)
                    {
                    case ObjectKind.String:
                        iniFile.SetString(category_name, name, ((TomlString)obj).Value);
                        break;

                    case ObjectKind.Boolean:
                        iniFile.SetBool(category_name, name, ((TomlBoolean)obj).Value);
                        break;

                    case ObjectKind.Integer:
                        iniFile.SetInt(category_name, name, (int)((TomlInteger)obj).Value);
                        break;

                    case ObjectKind.Float:
                        iniFile.SetFloat(category_name, name, (float)((TomlFloat)obj).Value);
                        break;

                    default:
                        break;
                    }
                }
            }
            File.Delete(oldfilepath);
        }
Esempio n. 8
0
 private bool ShouldPrependWithNewline(TomlObject obj) =>
 (obj.TomlType == TomlObjectType.Table && ((TomlTable)obj).TableType != TomlTable.TableTypes.Inline) ||
 obj.TomlType == TomlObjectType.ArrayOfTables;
Esempio n. 9
0
 public T ConvertFrom(TomlObject value, ITomlSerializerContext context)
 => value is TomlValue <T> tomlValue
Esempio n. 10
0
 public TCollection ConvertFrom(TomlObject value, ITomlSerializerContext context)
 => value is TomlArray tomlArray
Esempio n. 11
0
 public TNewType ConvertFrom(TomlObject value, ITomlSerializerContext context)
 => _constructor(_innerConverter.ConvertFrom(value, context));
Esempio n. 12
0
 public override bool Clear(TomlObject target)
 => target switch
 {
Esempio n. 13
0
 public override TomlObject Get(TomlObject target)
 => target switch
 {
Esempio n. 14
0
        public override bool ParseKey(string key, TomlObject tomlObj, ParseContext ctx)
        {
            if (base.ParseKey(key, tomlObj, ctx))
            {
                return(true);
            }

            switch (key)
            {
            case "host":
                MatchHost = TomlTools.GetValues <string>(tomlObj);
                if (MatchHost == null)
                {
                    ctx.Errors.Add("<host> Field has invalid data.");
                }
                return(true);

            case "groupid":
                MatchClientGroupId = TomlTools.GetValues <ulong>(tomlObj);
                if (MatchClientGroupId == null)
                {
                    ctx.Errors.Add("<groupid> Field has invalid data.");
                }
                return(true);

            case "useruid":
                MatchClientUid = TomlTools.GetValues <string>(tomlObj);
                if (MatchClientUid == null)
                {
                    ctx.Errors.Add("<useruid> Field has invalid data.");
                }
                return(true);

            case "perm":
                MatchPermission = TomlTools.GetValues <string>(tomlObj);
                if (MatchPermission == null)
                {
                    ctx.Errors.Add("<perm> Field has invalid data.");
                }
                return(true);

            case "rule":
                if (tomlObj.TomlType == TomlObjectType.ArrayOfTables)
                {
                    var childTables = (TomlTableArray)tomlObj;
                    foreach (var childTable in childTables.Items)
                    {
                        var rule = new RightsRule();
                        Children.Add(rule);
                        rule.Parent = this;
                        rule.ParseChilden(childTable, ctx);
                    }
                    return(true);
                }
                else
                {
                    ctx.Errors.Add("Misused key with reserved name \"rule\".");
                    return(false);
                }

            default:
                // group
                if (key.StartsWith("$"))
                {
                    if (tomlObj.TomlType == TomlObjectType.Table)
                    {
                        var childTable = (TomlTable)tomlObj;
                        var group      = new RightsGroup(key);
                        Children.Add(group);
                        group.Parent = this;
                        group.ParseChilden(childTable, ctx);
                        return(true);
                    }
                    else
                    {
                        ctx.Errors.Add($"Misused key for group declaration: {key}.");
                    }
                }
                return(false);
            }
        }
Esempio n. 15
0
 private bool ShouldPrependWithNewline(TomlObject obj) =>
     (obj.TomlType == TomlObjectType.Table && ((TomlTable)obj).TableType != TomlTable.TableTypes.Inline)
     || obj.TomlType == TomlObjectType.ArrayOfTables;
        private void WhenTargetPropertyNotFound(string[] tomlKeyChain, object targetObject, TomlObject targetValue)
        {
            var lineNumber = GuessSourceLine(tomlKeyChain, targetValue);

            var targetType = targetObject
                             .GetType();

            var typeName = targetType
                           .FullName
                           ?.Replace($"{nameof(TabularCsv)}.", string.Empty);

            var propertyName = $"{typeName}.{string.Join(".", tomlKeyChain)}";

            var targetPropertyName = tomlKeyChain.LastOrDefault();
            var targetSectionName  = tomlKeyChain.Length > 1
                ? tomlKeyChain[tomlKeyChain.Length - 2]
                : default;

            var message = $"'{propertyName}' is not a known property name.";

            if (!string.IsNullOrEmpty(targetPropertyName) && !string.IsNullOrEmpty(targetSectionName))
            {
                message = $"'{targetPropertyName}' is not a known [{targetSectionName}] property name.";
            }

            if (!string.IsNullOrEmpty(targetPropertyName))
            {
                var bestGuess = BestGuess(
                    targetPropertyName,
                    targetType
                    .GetProperties(BindingFlags.Public | BindingFlags.Instance | BindingFlags.SetProperty)
                    .Where(p => !ExcludedPropertyNames.Contains(p.Name)),
                    propertyInfo => propertyInfo.Name);

                if (!string.IsNullOrEmpty(bestGuess))
                {
                    message = $"{message} {bestGuess}";
                }
            }

            message = $"{message} See https://github.com/AquaticInformatics/tabular-field-data-plugin/wiki/Configuration-Fields for details.";

            if (lineNumber.HasValue)
            {
                throw new ParseException($"Line {lineNumber}: {message}");
            }

            throw new ParseException(message);
        }
Esempio n. 17
0
 internal override void Load(MelonPreferences_Entry entry, TomlObject obj) =>
 entry.SetValue(((TomlArray)obj).ToArray <int>());
Esempio n. 18
0
 public Guid ConvertFrom(TomlObject value, ITomlSerializerContext context)
 => Guid.Parse(context.GetConverter <string>().ConvertFrom(value, context));
Esempio n. 19
0
 public override TomlObject Apply(TomlObject obj, Func <TomlObject> _, PathSettings settings)
 => this.ApplyKey(obj, this.ThrowWhenKeyNotFound, ThrowOnError, settings);
Esempio n. 20
0
        public static TomlTable TransformToSourceTable(this TomlTable table, IConfigSource source, TomlObject rootSource = null)
        {
            table.CheckNotNull(nameof(table));

            var sourcesTable = rootSource == null
                ? Toml.Create(table.TableType)
                : TomlObjectFactory.CreateEmptyAttachedTable(rootSource, table.TableType);

            foreach (var r in table.Rows)
            {
                if (r.Value.TomlType == TomlObjectType.Table)
                {
                    sourcesTable[r.Key] = ((TomlTable)r.Value).TransformToSourceTable(source, sourcesTable);
                }
                else if (r.Value.TomlType == TomlObjectType.ArrayOfTables)
                {
                    var arr          = (TomlTableArray)r.Value;
                    var sourcesArray = new TomlTableArray(table.Root, arr.Items.Select(t => t.TransformToSourceTable(source, sourcesTable)));
                    sourcesTable[r.Key] = sourcesArray;
                }
                else
                {
                    sourcesTable[r.Key] = new TomlSource(sourcesTable.Root, source);
                }
            }

            return(sourcesTable);
        }
Esempio n. 21
0
 public override TomlObject TryApply(TomlObject obj, Func <TomlObject> __, PathSettings settings)
 => this.ApplyKey(obj, _ => null, ReturnDefaultOnError, settings);
Esempio n. 22
0
        // *** TomlPath engine ***

        public static IEnumerable <TomlObject> ByPath(this TomlObject obj, string path)
        {
            var pathM = path.AsMemory();

            return(ProcessIdentifier(obj, pathM));
        }
Esempio n. 23
0
 public abstract void FromToml(TomlObject tomlObject);
Esempio n. 24
0
        public static bool TryGetValue <T>(this TomlObject tomlObj, out T value)
        {
            switch (tomlObj.TomlType)
            {
            case TomlObjectType.Int:
                if (typeof(T) == typeof(long))
                {
                    // The base storage type for TomlInt is long, so we can simply return it.
                    value = (T)(object)((TomlInt)tomlObj).Value;
                    return(true);
                }
                else if (typeof(T) == typeof(ulong))
                {
                    // ulong is the only type which needs to be casted so we can use it.
                    // This might not be the greatest solution, but we can express ulong.MaxValue with -1 for example.
                    value = (T)(object)(ulong)((TomlInt)tomlObj).Value;
                    return(true);
                }
                else if (typeof(T) == typeof(uint) || typeof(T) == typeof(int) ||
                         typeof(T) == typeof(ushort) || typeof(T) == typeof(short) ||
                         typeof(T) == typeof(byte) || typeof(T) == typeof(sbyte) ||
                         typeof(T) == typeof(float) || typeof(T) == typeof(double))
                {
                    // All other types will be converted to catch overflow issues.
                    try
                    {
                        value = (T)Convert.ChangeType(((TomlInt)tomlObj).Value, typeof(T));
                        return(true);
                    }
                    catch (OverflowException) { }
                }
                break;

            case TomlObjectType.Float:
                if (typeof(T) == typeof(double))
                {
                    // Same here, double is the base type for TomlFloat.
                    value = (T)(object)((TomlFloat)tomlObj).Value;
                    return(true);
                }
                else if (typeof(T) == typeof(float))
                {
                    // double -> float cast works as we expect it.
                    value = (T)(object)(float)((TomlFloat)tomlObj).Value;
                    return(true);
                }
                break;

            case TomlObjectType.Bool:
            case TomlObjectType.DateTime:
            case TomlObjectType.TimeSpan:
                if (tomlObj is TomlValue <T> tomlValue && typeof(T) == tomlValue.Value.GetType())
                {
                    value = tomlValue.Value;
                    return(true);
                }
                break;

            case TomlObjectType.String:
                if (typeof(T).IsEnum)
                {
                    try
                    {
                        value = (T)Enum.Parse(typeof(T), ((TomlString)tomlObj).Value, true);
                        return(true);
                    }
                    catch (ArgumentException) { }
                    catch (OverflowException) { }
                }
                else if (typeof(T) == typeof(string))
                {
                    value = ((TomlValue <T>)tomlObj).Value;
                    return(true);
                }
                else if (typeof(T) == typeof(TimeSpan))
                {
                    try
                    {
                        value = (T)(object)TextUtil.ParseTime(((TomlString)tomlObj).Value);
                        return(true);
                    }
                    catch (FormatException) { }
                }
                break;
            }
            value = default;
            return(false);
        }
Esempio n. 25
0
File: TPath.cs Progetto: zanedp/Nett
        public void SetValue(TomlObject applyTo, TomlObject value, PathSettings settings = PathSettings.CreateTables)
        {
            var target = this.prefixPath.Apply(applyTo, settings);

            this.segment.SetValue(target, value, settings);
        }
Esempio n. 26
0
        private static TomlTable TryGetTableEntry(TomlObject obj)
        {
            if (obj == null) { return null; }
            var tbl = obj as TomlTable;
            var arr = obj as TomlTableArray;

            return tbl ?? arr?.Last();
        }
Esempio n. 27
0
 public void RemoveItem(string key)
 {
     dynamicTables.Remove(key);
     TomlObject.Remove(key);
 }
Esempio n. 28
0
        public override bool ParseKey(string key, TomlObject tomlObj, ParseContext ctx)
        {
            if (base.ParseKey(key, tomlObj, ctx))
            {
                return(true);
            }

            switch (key)
            {
            case "host":
                if (tomlObj.TryGetValueArray <string>(out var host))
                {
                    Matcher.Add(new MatchHost(host));
                }
                else
                {
                    ctx.Errors.Add("<host> Field has invalid data.");
                }
                return(true);

            case "groupid":
                if (tomlObj.TryGetValueArray <ulong>(out var servergroupid))
                {
                    Matcher.Add(new MatchServerGroupId(servergroupid.Select(ServerGroupId.To)));
                }
                else
                {
                    ctx.Errors.Add("<groupid> Field has invalid data.");
                }
                return(true);

            case "channelgroupid":
                if (tomlObj.TryGetValueArray <ulong>(out var channelgroupid))
                {
                    Matcher.Add(new MatchChannelGroupId(channelgroupid.Select(ChannelGroupId.To)));
                }
                else
                {
                    ctx.Errors.Add("<channelgroupid> Field has invalid data.");
                }
                return(true);

            case "useruid":
                if (tomlObj.TryGetValueArray <string>(out var useruid))
                {
                    Matcher.Add(new MatchClientUid(useruid.Select(Uid.To)));
                }
                else
                {
                    ctx.Errors.Add("<useruid> Field has invalid data.");
                }
                return(true);

            case "perm":
                if (tomlObj.TryGetValueArray <string>(out var perm))
                {
                    Matcher.Add(new MatchPermission(perm, ctx));
                }
                else
                {
                    ctx.Errors.Add("<perm> Field has invalid data.");
                }
                return(true);

            case "apitoken":
                if (tomlObj.TryGetValueArray <string>(out var apitoken))
                {
                    Matcher.Add(new MatchToken(apitoken));
                }
                else
                {
                    ctx.Errors.Add("<apitoken> Field has invalid data.");
                }
                return(true);

            case "bot":
                if (tomlObj.TryGetValueArray <string>(out var bot))
                {
                    Matcher.Add(new MatchBot(bot));
                }
                else
                {
                    ctx.Errors.Add("<bot> Field has invalid data.");
                }
                return(true);

            case "isapi":
                if (tomlObj.TryGetValue <bool>(out var isapi))
                {
                    Matcher.Add(new MatchIsApi(isapi));
                }
                else
                {
                    ctx.Errors.Add("<isapi> Field has invalid data.");
                }
                return(true);

            case "ip":
                if (tomlObj.TryGetValueArray <string>(out var ip))
                {
                    Matcher.Add(new MatchApiCallerIp(ip.Select(x =>
                    {
                        if (IPAddress.TryParse(x, out var ipa))
                        {
                            return(ipa);
                        }
                        ctx.Errors.Add($"<ip> Field value '{x}' could not be parsed.");
                        return(null !);
                    }).Where(x => x != null)));
                }
                else
                {
                    ctx.Errors.Add("<ip> Field has invalid data.");
                }
                return(true);

            case "visibility":
                if (tomlObj.TryGetValueArray <TextMessageTargetMode>(out var visibility))
                {
                    Matcher.Add(new MatchVisibility(visibility));
                }
                else
                {
                    ctx.Errors.Add("<visibility> Field has invalid data.");
                }
                return(true);

            case "rule":
                if (tomlObj.TomlType == TomlObjectType.ArrayOfTables)
                {
                    var childTables = (TomlTableArray)tomlObj;
                    foreach (var childTable in childTables.Items)
                    {
                        var rule = new RightsRule();
                        Children.Add(rule);
                        rule.Parent = this;
                        rule.ParseChilden(childTable, ctx);
                    }
                    return(true);
                }
                else
                {
                    ctx.Errors.Add("Misused key with reserved name \"rule\".");
                    return(false);
                }

            default:
                // group
                if (key.StartsWith("$"))
                {
                    if (tomlObj.TomlType == TomlObjectType.Table)
                    {
                        var childTable = (TomlTable)tomlObj;
                        var group      = new RightsGroup(key);
                        Children.Add(group);
                        group.Parent = this;
                        group.ParseChilden(childTable, ctx);
                        return(true);
                    }
                    else
                    {
                        ctx.Errors.Add($"Misused key for group declaration: {key}.");
                    }
                }
                return(false);
            }
        }
Esempio n. 29
0
 public TDictionary ConvertFrom(TomlObject value, ITomlSerializerContext context)
 => value is TomlTable tomlTable
Esempio n. 30
0
 private bool ShouldAppendWithNewline(TomlObject obj) => !this.ShouldPrependWithNewline(obj);
Esempio n. 31
0
        private static void AssertCommentsAre(TomlObject o, params string[] comments)
        {
            var tc = comments.Select(c => new TomlComment(c));

            o.Comments.Should().BeEquivalentTo(tc);
        }
Esempio n. 32
0
        private void WriteValue(TomlObject obj)
        {
            switch (obj.TomlType)
            {
                case TomlObjectType.Bool: this.writer.Write(((TomlBool)obj).Value.ToString().ToLower()); break;
                case TomlObjectType.Float: this.writer.Write("{0:0.0###############}", ((TomlFloat)obj).Value); break;
                case TomlObjectType.Int: this.writer.Write(((TomlInt)obj).Value); break;
                case TomlObjectType.DateTime: this.writer.Write(((TomlDateTime)obj).ToString()); break;
                case TomlObjectType.TimeSpan: this.writer.Write(((TomlTimeSpan)obj).Value); break;
                case TomlObjectType.String:
                    {
                        this.writer.Write('\"');
                        this.writer.Write(((TomlString)obj).Value.Escape() ?? string.Empty);
                        this.writer.Write('\"');
                        break;
                    }

                default:
                    Assert(false, "This method should only get called for simple TOML Types. Check invocation code.");
                    break;
            }
        }
Esempio n. 33
0
        public void Set(TomlObject target, Func <TomlObject, TomlObject> createNewValueObject)
        {
            var tgt = this.parent?.Resolve(target) ?? target;

            this.segment.Set(tgt, createNewValueObject);
        }
Esempio n. 34
0
 private bool ShouldAppendWithNewline(TomlObject obj) => !this.ShouldPrependWithNewline(obj);
Esempio n. 35
0
        public TomlObject Get(TomlObject target)
        {
            var tgt = this.parent?.Get(target) ?? target;

            return(this.segment.Get(tgt));
        }
Esempio n. 36
0
        public override bool ParseKey(string key, TomlObject tomlObj, ParseContext ctx)
        {
            if (base.ParseKey(key, tomlObj, ctx))
            {
                return(true);
            }

            switch (key)
            {
            case "host":
                var host = TomlTools.GetValues <string>(tomlObj);
                if (host == null)
                {
                    ctx.Errors.Add("<host> Field has invalid data.");
                }
                else
                {
                    MatchHost = new HashSet <string>(host);
                }
                return(true);

            case "groupid":
                var groupid = TomlTools.GetValues <ulong>(tomlObj);
                if (groupid == null)
                {
                    ctx.Errors.Add("<groupid> Field has invalid data.");
                }
                else
                {
                    MatchClientGroupId = new HashSet <ulong>(groupid);
                }
                return(true);

            case "channelgroupid":
                var cgroupid = TomlTools.GetValues <ulong>(tomlObj);
                if (cgroupid == null)
                {
                    ctx.Errors.Add("<channelgroupid> Field has invalid data.");
                }
                else
                {
                    MatchChannelGroupId = new HashSet <ulong>(cgroupid);
                }
                return(true);

            case "useruid":
                var useruid = TomlTools.GetValues <string>(tomlObj);
                if (useruid == null)
                {
                    ctx.Errors.Add("<useruid> Field has invalid data.");
                }
                else
                {
                    MatchClientUid = new HashSet <string>(useruid);
                }
                return(true);

            case "perm":
                var perm = TomlTools.GetValues <string>(tomlObj);
                if (perm == null)
                {
                    ctx.Errors.Add("<perm> Field has invalid data.");
                }
                else
                {
                    MatchPermission = new HashSet <string>(perm);
                }
                return(true);

            case "apitoken":
                var apitoken = TomlTools.GetValues <string>(tomlObj);
                if (apitoken == null)
                {
                    ctx.Errors.Add("<apitoken> Field has invalid data.");
                }
                else
                {
                    MatchToken = new HashSet <string>(apitoken);
                }
                return(true);

            case "isapi":
                if (!TomlTools.TryGetValue <bool>(tomlObj, out var isapi))
                {
                    ctx.Errors.Add("<isapi> Field has invalid data.");
                }
                else
                {
                    MatchIsApi = isapi;
                }
                return(true);

            case "visibility":
                var visibility = TomlTools.GetValues <TextMessageTargetMode>(tomlObj);
                if (visibility == null)
                {
                    ctx.Errors.Add("<visibility> Field has invalid data.");
                }
                else
                {
                    MatchVisibility = visibility;
                }
                return(true);

            case "rule":
                if (tomlObj.TomlType == TomlObjectType.ArrayOfTables)
                {
                    var childTables = (TomlTableArray)tomlObj;
                    foreach (var childTable in childTables.Items)
                    {
                        var rule = new RightsRule();
                        Children.Add(rule);
                        rule.Parent = this;
                        rule.ParseChilden(childTable, ctx);
                    }
                    return(true);
                }
                else
                {
                    ctx.Errors.Add("Misused key with reserved name \"rule\".");
                    return(false);
                }

            default:
                // group
                if (key.StartsWith("$"))
                {
                    if (tomlObj.TomlType == TomlObjectType.Table)
                    {
                        var childTable = (TomlTable)tomlObj;
                        var group      = new RightsGroup(key);
                        Children.Add(group);
                        group.Parent = this;
                        group.ParseChilden(childTable, ctx);
                        return(true);
                    }
                    else
                    {
                        ctx.Errors.Add($"Misused key for group declaration: {key}.");
                    }
                }
                return(false);
            }
        }
Esempio n. 37
0
 public void WriteDottedKeyValue(TomlObject value, params TomlKey[] keySegments)
 {
     this.WriteDotteKey(keySegments);
     this.WriteValue(value);
 }