首页 > 解决方案 > 是否有任何 Dart 资源可以将命令行字符串拆分为列表论据?

问题描述

是否有任何Dart资源可以将命令行String拆分List<String>为参数?

ArgsParser通常List<String>main(List<String>).

标签: shelldartcommand-line

解决方案


为了回答我自己的问题,

我已经将我喜欢的 Java 函数转换为 DartConverter<String, List<String>)类:

import 'dart:convert';

/// Splits a `String` into a list of command-line argument parts.
/// e.g. "command -p param" -> ["command", "-p", "param"]
///
class CommandlineConverter extends Converter<String, List<String>>
{
  @override
  List<String> convert(String input) 
  {
    if (input == null || input.isEmpty) 
    {
        //no command? no string
        return [];
    }

    final List<String> result = new List<String>();

    var current = "";

    String inQuote;
    bool   lastTokenHasBeenQuoted = false;

    for (int index = 0; index < input.length; index++)
    {
        final token = input[index];

        if (inQuote != null)
        {
          if   (token == inQuote) 
          {
              lastTokenHasBeenQuoted = true;
              inQuote                = null;
          } 
          else 
          {
              current += token;
          }
        }
        else
        {
          switch (token) 
          {
            case "'": // '
            case '"': // ""

              inQuote = token;
              continue;

            case " ": // space

              if (lastTokenHasBeenQuoted || current.isNotEmpty) 
              {
                  result.add(current);
                  current = "";
              }
              break;

            default:

              current               += token;
              lastTokenHasBeenQuoted = false;
          }
        }
    }

    if (lastTokenHasBeenQuoted || current.isNotEmpty) 
    {
        result.add(current);
    }

    if (inQuote != null)
    {
        throw new Exception("Unbalanced quote $inQuote in input:\n$input");
    }

    return result;
  }
}

推荐阅读