是否有任何Dart资源可以将一个命令行字符串分割成一个List<String>的参数?

问题描述 投票:0回答:1

是否有任何 Dart 资源,这将使命令行的 String 变成 List<String> 的论点?

ArgsParserList<String> 已经拆分的参数,通常来自 main(List<String>).

shell dart command-line
1个回答
0
投票

回答我自己的问题。

我把一个我喜欢的Java函数转换成了Dart的函数 Converter<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;
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.