通过控制台运行脚本插入Dart字符串



我正在使用Dart,使用我在工具目录中制作的脚本将控制器类生成到项目框架中。脚本使用以下终端命令运行(当然是在项目目录中):

dart tool/controller_create.dart controllerName

这将运行以下脚本,并使用字符串插值将名称注入必要的区域,将控制台中的第一个参数"controllerName"用作脚本中"name"变量的值:

import 'dart:io';
void main(String name)
{
  String content = """
  part of controllers;
  class $name extends Controller
  {
    //-------------------------------------------------------------------------------------------
    // Functions
    //-------------------------------------------------------------------------------------------
    /**
     * Passes parameters and initialises superclass constructor
     */
    $name () : super(new VirtualDirectory(root_package_dir))
    {
      virtualDirectory.allowDirectoryListing = false;
      virtualDirectory.jailRoot = true;
    }
    //-------------------------------------------------------------------------------------------
    // Functions - Controllers
    //-------------------------------------------------------------------------------------------
    void index (HttpRequest request)
    {
      virtualDirectory.serveFile(new File(views_dir + "/index.html"), request);
    }
  }
  """;
  new File('$name.dart').writeAsString(content).then((File file)
  {
  });
}

然而,我遇到的问题是,给定的字符串不仅将"controllerName"注入指定的区域,而且还将"[controllerName]"注入,这让我想知道是什么导致了这种情况,以及如何避免这种情况?

感谢您的阅读!这是我制作的第一个终端驱动脚本,所以如果这是终端传递变量的正常行为,我深表歉意。

尽管main有方法签名,但命令行参数实际上是以List<String>的形式传递的。因此,字符串插值看到一个包含一个元素controllerName的列表。

将main更改为void main(List<String> args)并创建一个新字段var name = args[0]

另一个答案是,main使用List<String> args,但您可以执行您想要执行的操作,即为每个参数(包括选项和标志)单独设置参数,例如String name,使用无脚本包。

最新更新