adamabdelhamed / PowerArgs

The ultimate .NET Standard command line argument parser
MIT License
568 stars 56 forks source link

Allow complex default values #137

Closed floatas closed 5 years ago

floatas commented 5 years ago

Hi, I'm just starting to use this library and wanted to discuss one issue before making any real changes and pull requests. I wanted to set temp directory path as default value. I come up with solution, but it's not prettiest solution and can be improved by making few small changes to PowerArgs. Maybe there is different way to achieve same result ?

Complex default value now:

    [AttributeUsage(AttributeTargets.Property | AttributeTargets.Parameter)]
    public class TempDirPathAsDefaultValue : DefaultValueAttribute
    {
        static string TempDir = "";
        static TempDirPathAsDefaultValue()
        {
            TempDir = System.IO.Path.GetTempPath();
        }

        public TempDirPathAsDefaultValue() : base(TempDir)
        {
        }
    }

Two small changes are required (see comments in code):

    [AttributeUsage(AttributeTargets.Property | AttributeTargets.Parameter)]
    public class DefaultValueAttribute : ArgHook, ICommandLineArgumentMetadata
    {
        public object Value { get; protected set; }//<- Protected setter

        public DefaultValueAttribute(object value)
        {
            Value = value;
        }

        protected DefaultValueAttribute()//<- protected constructor
        {
        }

        public override void BeforePopulateProperty(HookContext Context)
        {
            if (Context.ArgumentValue == null) Context.ArgumentValue = Value.ToString();
        }
    }

Complex default value after changes:

    [AttributeUsage(AttributeTargets.Property | AttributeTargets.Parameter)]
    public class TempDirPathAsDefaultValue : DefaultValueAttribute
    {
        public TempDirPathAsDefaultValue() : base()
        {
            Value = System.IO.Path.GetTempPath();
        }
    }

Let me know what you think, I can make pull request for this + tests if needed.

adamabdelhamed commented 5 years ago

For complex default values you can always just make the getter of your property do the work like this. No need to add more complexity to PowerArgs.


private string _tempPath;
public string TempPath
{
    get
    {
        return _tempPath || System.IO.Path.GetTempPath();
    }
    set
    {
        _tempPath = value;
    }
}