Skip to content

dcat

source: https://dart.dev/tutorials/server/cmdline

Usage: dart run bin/dcat.dart -n pubspec.yaml

First: Creating the dart app.

dart create dcat
cd dcat
dart pub add args
nvim bin/dcart.dart
In nvim, just type main and let the LSP autocomplete it. Inside the main function just put a print(args). Note that each individual string element in the List was created by the shell (zsh in my case). For instance, zsh understands that in

vector@resonyze ~/development/dcat % dart run bin/dcat.dart "hello there"
[hello there]
"hello there" is taken as one argument.

But without the double quotes:

vector@resonyze ~/development/dcat % dart run bin/dcat.dart "hello there"
[hello, there]
import 'package:args/args.dart';

void main(List<String> args) {
  final parser = ArgParser()
    ..addFlag("line-number", negatable: true, abbr: 'n')
    ..addFlag("quiet", negatable: true, abbr: 'q')
    ..addFlag("help", negatable: true, abbr: 'h');

  ArgResults argResults = parser.parse(args);
  final options = argResults.options;
  final paths = argResults.rest;

  print("Paths: $paths\nOptions: $options");
  print("line-number: ${argResults["line-number"]}");
  print("quiet: ${argResults["quiet"]}");
  print("help: ${argResults["help"]}");
}

About ArgParser

ArgParser is a nifty tool to get individual options and the value supplied to them. In dcat its worthwhile to note how ArgParser is used.

final parser = ArgParser()
  ..addFlag("line-number", negatable: true, abbr: 'n')
  ..addFlag("quiet", negatable: true, abbr: 'q')
  ..addFlag("help", negatable: true, abbr: 'h');

Once the parser is intiailized like this. You can give it the arguments you received in main(List<String> args).

parser.parse(args)

Something like tail -f

import 'dart:async';
import 'dart:convert';
import 'dart:io';

void main() {
  File observedFile = File("/tmp/access.log");
  String lastline = "";
  const int modify = 1 << 1;
  observedFile.watch(events: modify).listen((event) {
    utf8.decoder.bind(File('/tmp/access.log').openRead()).listen((event) {
      var lines = LineSplitter().convert(event);
      if (lines.last != lastline) {
        print(lines.last);
        lastline = lines.last;
      }
    });
  });
}
Note: ut8.decoder.bind is a method of ut8.decoder that takes a Stream<List<int>> and converts it into a Stream<String>. I find it noteworthy that a single event of this stream is the retrieval of a List which actually stands for the entire file.

To get the long ass Stream<List<int>>, we use the File class's openRead method. File('/tmp/access.log').openRead().

Once bind converts the Stream<List<int>> into Stream<String> we the listen method on the stream


Comments