buildImage method

Future<(String, List<Map<String, dynamic>>)> buildImage(
  1. String contextPath, {
  2. String? tag,
  3. bool noCache = false,
  4. String? dockerfile,
})

Builds an image from a local context directory and returns its ID and build logs.

The entire contextPath directory is tar-archived in memory and sent to POST /build.

Parameters:

  • contextPath — path to the Docker build context.
  • tag — optional name:tag to apply to the built image.
  • noCache — disable the build cache. Default: false.
  • dockerfile — optional Dockerfile path relative to contextPath.

Returns a record (imageId, logs) where imageId is the built image's ID (or the tag string when the ID cannot be parsed from build output) and logs is the streaming build log as a list of JSON objects.

Implementation

Future<(String, List<Map<String, dynamic>>)> buildImage(
  String contextPath, {
  String? tag,
  bool noCache = false,
  String? dockerfile,
}) async {
  final tarData = _buildContextTar(contextPath);
  final queryParams = <String, String>{
    if (tag != null) 't': tag,
    if (noCache) 'nocache': 'true',
    if (dockerfile != null) 'dockerfile': dockerfile,
  };
  final resp = await _request(
    'POST',
    '/build',
    queryParams: queryParams,
    body: tarData,
  );
  _throwIfError(resp);
  String? imageId;
  final logs = <Map<String, dynamic>>[];
  for (final line in resp.bodyString.split('\n')) {
    if (line.isEmpty) {
      continue;
    }
    try {
      final parsed = jsonDecode(line) as Map<String, dynamic>;
      logs.add(parsed);
      if (parsed['aux'] != null) {
        imageId = (parsed['aux'] as Map<String, dynamic>)['ID'] as String?;
      }
    } catch (_) {}
  }
  return (imageId ?? tag ?? '', logs);
}