parse static method

Curl parse(
  1. String curlString
)

Parse curlString as a Curl class instance.

Example:

print(Curl.parse('curl -X GET https://www.example.com/')); // Curl(method: 'GET', url: 'https://www.example.com/')
print(Curl.parse('1f')); // [Exception] is thrown

Implementation

static Curl parse(String curlString) {
  String? clean(String? url) {
    return url?.replaceAll('"', '').replaceAll("'", '');
  }

  final parser = ArgParser(allowTrailingOptions: true);

  // Define the expected options
  parser.addOption('url');
  parser.addOption('request', abbr: 'X');
  parser.addMultiOption('header', abbr: 'H', splitCommas: false);
  parser.addOption('data', abbr: 'd');
  parser.addOption('cookie', abbr: 'b');
  parser.addOption('user', abbr: 'u');
  parser.addOption('referer', abbr: 'e');
  parser.addOption('user-agent', abbr: 'A');
  parser.addFlag('head', abbr: 'I');
  parser.addFlag('form', abbr: 'F');
  parser.addFlag('insecure', abbr: 'k');
  parser.addFlag('location', abbr: 'L');

  if (!curlString.startsWith('curl ')) {
    throw Exception("curlString doesn't start with 'curl '");
  }

  final splittedCurlString =
      splitAsCommandLineArgs(curlString.replaceFirst('curl ', ''));

  final result = parser.parse(splittedCurlString);

  final method = (result['request'] as String?)?.toUpperCase();

  // Extract the request headers
  Map<String, String>? headers;
  if (result['header'] != null) {
    final List<String> headersList = result['header'];
    if (headersList.isNotEmpty == true) {
      headers = <String, String>{};
      for (var headerString in headersList) {
        final splittedHeaderString = headerString.split(RegExp(r':\s*'));
        if (splittedHeaderString.length != 2) {
          throw Exception('Failed to split the `$headerString` header');
        }
        headers.addAll({splittedHeaderString[0]: splittedHeaderString[1]});
      }
    }
  }

  String? url = clean(result['url']);
  final String? data = result['data'];
  final String? cookie = result['cookie'];
  final String? user = result['user'];
  final String? referer = result['referer'];
  final String? userAgent = result['user-agent'];
  final bool form = result['form'] ?? false;
  final bool head = result['head'] ?? false;
  final bool insecure = result['insecure'] ?? false;
  final bool location = result['location'] ?? false;

  // Extract the request URL
  url ??= result.rest.isNotEmpty ? clean(result.rest.first) : null;
  if (url == null) {
    throw Exception('url is null');
  }
  final uri = Uri.parse(url);

  return Curl(
    method: head ? "HEAD" : (method ?? 'GET'),
    uri: uri,
    headers: headers,
    data: data,
    cookie: cookie,
    user: user,
    referer: referer,
    userAgent: userAgent,
    form: form,
    insecure: insecure,
    location: location,
  );
}