Browse Source

Make the behavior explicitly opt-in

pull/1488/head
Joe4evr 5 years ago
parent
commit
aa9aca50ab
2 changed files with 31 additions and 1 deletions
  1. +27
    -0
      src/Discord.Net.Commands/Attributes/FallbackToDefaultAttribute.cs
  2. +4
    -1
      src/Discord.Net.Commands/Info/ParameterInfo.cs

+ 27
- 0
src/Discord.Net.Commands/Attributes/FallbackToDefaultAttribute.cs View File

@@ -0,0 +1,27 @@
using System;

namespace Discord.Commands
{
/// <summary>
/// When applied to an optional command parameter,
/// indicates that its default value should be used
/// if the TypeReader fails to read a valid value.
/// </summary>
/// <example>
/// <code language="cs">
/// [Command("stats")]
/// public async Task GetStatsAsync([FallbackToDefault] IUser user = null)
/// {
/// if (user is null)
/// {
/// await ReplyAsync("Couldn't find that user");
/// return;
/// }
///
/// // ...pull stats
/// }
/// </code>
/// </example>
[AttributeUsage(AttributeTargets.Parameter, AllowMultiple = false, Inherited = false)]
public sealed class FallbackToDefaultAttribute : Attribute { }
}

+ 4
- 1
src/Discord.Net.Commands/Info/ParameterInfo.cs View File

@@ -3,6 +3,7 @@ using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Collections.Immutable; using System.Collections.Immutable;
using System.Diagnostics; using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks; using System.Threading.Tasks;


namespace Discord.Commands namespace Discord.Commands
@@ -36,6 +37,7 @@ namespace Discord.Commands
/// </summary> /// </summary>
public bool IsRemainder { get; } public bool IsRemainder { get; }
public bool IsMultiple { get; } public bool IsMultiple { get; }
public bool UseDefaultOnFail { get; }
/// <summary> /// <summary>
/// Gets the type of the parameter. /// Gets the type of the parameter.
/// </summary> /// </summary>
@@ -63,6 +65,7 @@ namespace Discord.Commands
IsOptional = builder.IsOptional; IsOptional = builder.IsOptional;
IsRemainder = builder.IsRemainder; IsRemainder = builder.IsRemainder;
IsMultiple = builder.IsMultiple; IsMultiple = builder.IsMultiple;
UseDefaultOnFail = (IsOptional && builder.Attributes.Any(attr => attr is FallbackToDefaultAttribute));


Type = builder.ParameterType; Type = builder.ParameterType;
DefaultValue = builder.DefaultValue; DefaultValue = builder.DefaultValue;
@@ -91,7 +94,7 @@ namespace Discord.Commands
{ {
services = services ?? EmptyServiceProvider.Instance; services = services ?? EmptyServiceProvider.Instance;
var readerResult = await _reader.ReadAsync(context, input, services).ConfigureAwait(false); var readerResult = await _reader.ReadAsync(context, input, services).ConfigureAwait(false);
return (!readerResult.IsSuccess && IsOptional)
return (!readerResult.IsSuccess && UseDefaultOnFail)
? TypeReaderResult.FromSuccess(DefaultValue) ? TypeReaderResult.FromSuccess(DefaultValue)
: readerResult; : readerResult;
} }


Loading…
Cancel
Save