当前位置: 移动技术网 > IT编程>开发语言>.net > 使用.Net Core编写命令行工具(CLI)的方法

使用.Net Core编写命令行工具(CLI)的方法

2020年06月23日  | 移动技术网IT编程  | 我要评论

房价下跌的后果,鞍山信息港,真空过滤装置

命令行工具(cli)

  命令行工具(cli)是在图形用户界面得到普及之前使用最为广泛的用户界面,它通常不支持鼠标,用户通过键盘输入指令,计算机接收到指令后,予以执行。

  通常认为,命令行工具(cli)没有图形用户界面(gui)那么方便用户操作。因为,命令行工具的软件通常需要用户记忆操作的命令,但是,由于其本身的特点,命令行工具要较图形用户界面节约计算机系统的资源。在熟记命令的前提下,使用命令行工具往往要较使用图形用户界面的操作速度要快。所以,图形用户界面的操作系统中,都保留着可选的命令行工具。

  另外,命令行工具(cli)应该是一个开箱即用的工具,不需要安装任何依赖。

  一些熟悉的cli工具如下:

  1.

  2.

  3.

  4.

  5.

指令设计

  本文将使用.net core(版本3.1.102)编写一个cli工具,实现配置管理以及条目(item)管理(调用webapi实现),详情如下:

  

框架说明

  编写cli使用的主要框架是commandlineutils,它主要有以下优势:

  1. 良好的语法设计

  2. 支持依赖注入

  3. 支持generic host

webapi

  提供api让cli调用,实现条目(item)的增删改查:

[route("api/items")]
[apicontroller]
public class itemscontroller : controllerbase
{
  private readonly imemorycache _cache;
  private readonly string _key = "items";

  public itemscontroller(imemorycache memorycache)
  {
    _cache = memorycache;
  }

  [httpget]
  public iactionresult list()
  {
    var items = _cache.get<list<item>>(_key);
    return ok(items);
  }

  [httpget("{id}")]
  public iactionresult get(string id)
  {
    var item = _cache.get<list<item>>(_key).firstordefault(n => n.id == id);
    return ok(item);
  }

  [httppost]
  public iactionresult create(itemform form)
  {
    var items = _cache.get<list<item>>(_key) ?? new list<item>();

    var item = new item
    {
      id = guid.newguid().tostring("n"),
      name = form.name,
      age = form.age
    };

    items.add(item);

    _cache.set(_key, items);
    
    return ok(item);
  }

  [httpdelete("{id}")]
  public iactionresult delete(string id)
  {
    var items = _cache.get<list<item>>(_key);

    var item = items?.singleordefault(n => n.id == id);
    if (item == null)
    {
      return notfound();
    }

    items.remove(item);
    _cache.set(_key, items);

    return ok();
  }
}

cli

  1. program - 函数入口

[helpoption(inherited = true)] //显示指令帮助,并且让子指令也继承此设置
[command(description = "a tool to communicate with web api"), //指令描述
 subcommand(typeof(configcommand), typeof(itemcommand))] //子指令
class program
{
  public static int main(string[] args)
  {
    //配置依赖注入
    var servicecollection = new servicecollection();

    servicecollection.addsingleton(physicalconsole.singleton);
    servicecollection.addsingleton<iconfigservice, configservice>();
    servicecollection.addhttpclient<iitemclient, itemclient>();

    var services = servicecollection.buildserviceprovider();

    var app = new commandlineapplication<program>();
    app.conventions
      .usedefaultconventions()
      .useconstructorinjection(services);

    var console = (iconsole)services.getservice(typeof(iconsole));

    try
    {
      return app.execute(args);
    }
    catch (unrecognizedcommandparsingexception ex) //处理未定义指令
    {
      console.writeline(ex.message);
      return -1;
    }
  }

  //指令逻辑
  private int onexecute(commandlineapplication app, iconsole console)
  {
    console.writeline("please specify a command.");
    app.showhelp();
    return 1;
  }
}

  2. configcommand和itemcommand - 实现的功能比较简单,主要是指令描述以及指定对应的子指令

[command("config", description = "manage config"),
 subcommand(typeof(getcommand), typeof(setcommand))]
public class configcommand
{
  private int onexecute(commandlineapplication app, iconsole console)
  {
    console.error.writeline("please submit a sub command.");
    app.showhelp();
    return 1;
  }
}

[command("item", description = "manage item"),
 subcommand(typeof(createcommand), typeof(getcommand), typeof(listcommand), typeof(deletecommand))]
public class itemcommand
{
  private int onexecute(commandlineapplication app, iconsole console)
  {
    console.error.writeline("please submit a sub command.");
    app.showhelp();
    return 1;
  }
}

  3.configservice - 配置管理的具体实现,主要是文件读写

public interface iconfigservice
{
  void set();

  config get();
}

public class configservice: iconfigservice
{
  private readonly iconsole _console;
  private readonly string _directoryname;
  private readonly string _filename;

  public configservice(iconsole console)
  {
    _console = console;
    _directoryname = ".api-cli";
    _filename = "config.json";
  }

  public void set()
  {
    var directory = path.combine(environment.getfolderpath(environment.specialfolder.userprofile), _directoryname);
    if (!directory.exists(directory))
    {
      directory.createdirectory(directory);
    }

    var config = new config
    {
      //弹出交互框,让用户输入,设置默认值为http://localhost:5000/
      endpoint = prompt.getstring("specify the endpoint:", "http://localhost:5000/")
    };

    if (!config.endpoint.endswith("/"))
    {
      config.endpoint += "/";
    }

    var filepath = path.combine(directory, _filename);

    using (var outputfile = new streamwriter(filepath, false, encoding.utf8))
    {
      outputfile.writeline(jsonconvert.serializeobject(config, formatting.indented));
    }
    _console.writeline($"config saved in {filepath}.");
  }

  public config get()
  {
    var filepath = path.combine(environment.getfolderpath(environment.specialfolder.userprofile), _directoryname, _filename);

    if (file.exists(filepath))
    {
      var content = file.readalltext(filepath);
      try
      {
        var config = jsonconvert.deserializeobject<config>(content);
        return config;
      }
      catch
      {
        _console.writeline("the config is invalid, please use 'config set' command to reset one.");
      }
    }
    else
    {
      _console.writeline("config is not existed, please use 'config set' command to set one.");
    }

    return null;
  }
}

  4.itemclient - 调用web api的具体实现,使用httpclientfactory的方式

public interface iitemclient
{
  task<string> create(itemform form);

  task<string> get(string id);

  task<string> list();

  task<string> delete(string id);
}

public class itemclient : iitemclient
{
  public httpclient client { get; }

  public itemclient(httpclient client, iconfigservice configservice)
  {
    var config = configservice.get();
    if (config == null)
    {
      return;
    }

    client.baseaddress = new uri(config.endpoint);

    client = client;
  }

  public async task<string> create(itemform form)
  {
    var content = new stringcontent(jsonconvert.serializeobject(form), encoding.utf8, "application/json");
    var result = await client.postasync("/api/items", content);

    if (result.issuccessstatuscode)
    {
      var stream = await result.content.readasstreamasync();
      var item = deserialize<item>(stream);
      return $"item created, info:{item}";
    }

    return "error occur, please again later.";
  }

  public async task<string> get(string id)
  {
    var result = await client.getasync($"/api/items/{id}");

    if (result.issuccessstatuscode)
    {
      var stream = await result.content.readasstreamasync();
      var item = deserialize<item>(stream);

      var response = new stringbuilder();
      response.appendline($"{"id".padright(40, ' ')}{"name".padright(20, ' ')}age");
      response.appendline($"{item.id.padright(40, ' ')}{item.name.padright(20, ' ')}{item.age}");
      return response.tostring();
    }

    return "error occur, please again later.";
  }

  public async task<string> list()
  {
    var result = await client.getasync($"/api/items");

    if (result.issuccessstatuscode)
    {
      var stream = await result.content.readasstreamasync();
      var items = deserialize<list<item>>(stream);

      var response = new stringbuilder();
      response.appendline($"{"id".padright(40, ' ')}{"name".padright(20, ' ')}age");

      if (items != null && items.count > 0)
      {
        foreach (var item in items)
        {
          response.appendline($"{item.id.padright(40, ' ')}{item.name.padright(20, ' ')}{item.age}");
        }
      }
      
      return response.tostring();
    }

    return "error occur, please again later.";
  }

  public async task<string> delete(string id)
  {
    var result = await client.deleteasync($"/api/items/{id}");

    if (result.issuccessstatuscode)
    {
      return $"item {id} deleted.";
    }

    if (result.statuscode == httpstatuscode.notfound)
    {
      return $"item {id} not found.";
    }

    return "error occur, please again later.";
  }

  private static t deserialize<t>(stream stream)
  {
    using var reader = new jsontextreader(new streamreader(stream));
    var serializer = new jsonserializer();
    return (t)serializer.deserialize(reader, typeof(t));
  }
}

如何发布

  在项目文件中设置发布程序的名称(assemblyname):

 <propertygroup>
   <outputtype>exe</outputtype>
   <targetframework>netcoreapp3.1</targetframework>
   <assemblyname>api-cli</assemblyname>
  </propertygroup>

  进入控制台程序目录:

cd src/netcorecli

  发布linux使用版本:

 dotnet publish -c release -r linux-x64 /p:publishsinglefile=true

  发布windows使用版本:

dotnet publish -c release -r win-x64 /p:publishsinglefile=true

  发布mac使用版本:

 dotnet publish -c release -r osx-x64 /p:publishsinglefile=true
 

使用示例

  这里使用linux作为示例环境。

  1. 以docker的方式启动web api

  2. 虚拟机上没有安装.net core的环境

  3. 把编译好的cli工具拷贝到虚拟机上,授权并移动到path中(如果不移动,可以通过./api-cli的方式调用)

sudo chmod +x api-cli #授权
sudo mv ./api-cli /usr/local/bin/api-cli #移动到path

  4. 设置配置文件:api-cli config set

  5. 查看配置文件:api-cli config get

  6. 创建条目:api-cli item create

  7. 条目列表:api-cli item list

  8. 获取条目:api-cli item get

  9. 删除条目:api-cli item delete

  10. 指令帮助:api-cli -h, api-cli config -h, api-cli item -h

  11. 错误指令:api-cli xxx

源码地址

  https://github.com/erikxu/netcorecli

参考资料

  

  

到此这篇关于使用.net core编写命令行工具(cli)的方法的文章就介绍到这了,更多相关.net core 命令行工具内容请搜索移动技术网以前的文章或继续浏览下面的相关文章希望大家以后多多支持移动技术网!

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网