Returns a stream suitable for stdout for the download progress (or the cache).

@param {DockerodePromise} docker wrapper.
@param {String} image docker image name.
@param {Object} [options] docker pull options.
@return {Promise[Stream]}
509656
function pullImageIfMissing(docker, image, options) {
  debug('ensure image', image);
  var pullStream = new PullStatusStream();

  // first attempt to find the image locally...
  docker.getImage(image).inspect().then(
    function inspection(gotImg) {
      // push a value directly to the result without the transform.
      pullStream.push(image + ' exists in the cache.\r\n');
      // end the stream.
      pullStream.end();
    },

    function missingImage() {
      debug('image is missing pull', image);
      // image is missing so pull it
      return docker.pull(image, options || {}).then(function(rawPullStream) {
        rawPullStream.pipe(pullStream);
      });
    }
  ).then(
    null,
    function handleErrors(err) {
      pullStream.emit('error', err);
    }
  );

  return pullStream;
}
530320
function deliverImage(path, res) {
  var stream = lib.fs.createReadStream(path);
  /* @todo: set headers 'n stuff */
  lib.util.pump(stream, res, function (err) {
    if (err) {
      /* @todo: handle errors. */
      console.log('errors', err);
    }
  });
}
212194
function download(uri, dest, progressCallback) {
    "use strict";
    progressCallback = progressCallback || function() {};
    var parsedUrl = url.parse(uri, false, true);
    var makeRequest = parsedUrl.protocol === 'https:' ? https.request.bind(https) : http.request.bind(http);
    var serverPort = parsedUrl.port ? parsedUrl.port : parsedUrl.protocol === 'https:' ? 443 : 80;
    var agent = parsedUrl.protocol === 'https:' ? httpsAgent : httpAgent;
    var file = fs.createWriteStream(dest);

    var options = {
        host: parsedUrl.host,
        path: parsedUrl.path,
        agent: agent,
        port: serverPort,
        method: 'GET'
    };

    return new Promise(function (resolve, reject) {

        var req = makeRequest(options, function (response) {
            var size = response.headers['content-length'];
            var progress = 0;

            response.on('data', function(chunk) {
                progress += chunk.length;
                progressCallback(size, progress);
            });

            response.pipe(file);
            file.on('finish', function() {
                resolve({
                    status: response.statusCode
                });
            });
        });

        req.on('error', function(error) {
            file.end();
            rimraf.sync(dest);
            reject(error);
        });

        req.end();
    });
}
1016368
function image(input) {
        return new Promise(function (valid, invalid) {
            if (input.getAttribute('type') === 'file' && input.getAttribute('accept').indexOf('image') > -1 && _bn_getFile(input) !== false) {
                BunnyFile.getSignature(_bn_getFile(input)).then(function (signature) {
                    if (BunnyFile.isJpeg(signature) || BunnyFile.isPng(signature)) {
                        valid();
                    } else {
                        invalid({ signature: signature });
                    }
                }).catch(function (e) {
                    invalid(e);
                });
            } else {
                valid();
            }
        });
    }
922018
function Stream( options ) {
	var args = arguments,
		opts = {},
		err;
	if ( args.length ) {
		opts = options;
	}
	if ( !( this instanceof Stream ) ) {
		return new Stream( opts );
	}
	err = validate( opts );
	if ( err ) {
		throw err;
	}
	Transform.call( this, opts );
	this._readableState.objectMode = true;
	this._data = '';

	return this;
}
870031
def pull(client, revision, auto_login):
    """"""
    registry_url = detect_registry_url(client, auto_login=auto_login)

    repo = client.repo
    sha = repo.rev_parse(revision).hexsha
    short_sha = repo.git.rev_parse(sha, short=7)

    image = '{registry}:{short_sha}'.format(
        registry=registry_url.image, short_sha=short_sha
    )

    result = subprocess.run(['docker', 'image', 'pull', image])
    if result.returncode != 0:
        raise click.ClickException(
            'The image "{image}" was not pulled.\n\n'
            'Push the repository to the server or build the image manually:\n'
            '\n\tdocker build -t {image} .'.format(image=image)
        )
611271
function toDataURL (image, options) {
  var src = '';
  var async, callback;

  options = options || {};

  async = typeof options.callback === 'function';

  callback = async ? options.callback : function (err, data) {
    if (err) {
      throw err;
    }
    return data;
  };

  function _convert (err, img) {
    if (err) {
      return callback(err);
    }
    var result;
    cors(img);
    result = convert(img, options.width, options.height);
    return callback(null, (options.purify ? purify(result) : result));
  }

  if (isImage(image)) {
    src = image.src || '';
  } else if (typeof image === 'string') {
    if (!async) {
      return callback(new Error('the url mode should be called with a callback'));
    }
    src = image;
  } else {
    return callback(new Error('image should be an Image Object or a string'));
  }

  return async ? createImage(src, _convert) : _convert(null, image);
}
314208
function getRawBody (stream, options, callback) {
  var done = callback
  var opts = options || {}

  if (options === true || typeof options === 'string') {
    // short cut for encoding
    opts = {
      encoding: options
    }
  }

  if (typeof options === 'function') {
    done = options
    opts = {}
  }

  // validate callback is a function, if provided
  if (done !== undefined && typeof done !== 'function') {
    throw new TypeError('argument callback must be a function')
  }

  // require the callback without promises
  if (!done && !global.Promise) {
    throw new TypeError('argument callback is required')
  }

  // get encoding
  var encoding = opts.encoding !== true
    ? opts.encoding
    : 'utf-8'

  // convert the limit to an integer
  var limit = bytes.parse(opts.limit)

  // convert the expected length to an integer
  var length = opts.length != null && !isNaN(opts.length)
    ? parseInt(opts.length, 10)
    : null

  if (done) {
    // classic callback style
    return readStream(stream, encoding, length, limit, done)
  }

  return new Promise(function executor (resolve, reject) {
    readStream(stream, encoding, length, limit, function onRead (err, buf) {
      if (err) return reject(err)
      resolve(buf)
    })
  })
}
422072
function(tag, confImage, callback) {

      grunt.log.subhead(actioning[action] + ' image [' + tag + ']');

      async.waterfall([

      // Step 1: search for a running container with the same image
      function(cb) {
        docker.listContainers({
          all : 1,
        // filters: (action !== 'unpause') ? '{"status":["running"]}' : null
        }, function(err, containers) {

          if (err) {
            return cb(err);
          }

          var container = null;

          for (var c = 0; c < containers.length; c++) {
            if (containers[c].Image.indexOf(utils.qualifiedImageName(tag,
                  options.registry, null)) === 0) {
              container = containers[c];
              break;
            }
          }

          cb(null, container);
        });
      },

      // Step 2: stop it
      function(container, cb) {
        if (container) {
          grunt.log.writeln("Found a matched container, " + action + " it.");

          var dockcontainer = docker.getContainer(container.Id);

          var opts = confImage.options && confImage.options[action] || {};
          dockcontainer[action](opts, function(e, stream) {
            if (stream && stream.readable) {
              stream.setEncoding('utf8');
              stream.on('error', cb);
              stream.on('end', cb);
              stream.on('data', grunt.log.write);
            } else {
              cb(e);
            }

          });
        } else {
          grunt.log.writeln("No matched container with this image.");
          cb(null);
        }
      }, ], callback);

    }
997121
function(fileId, imgOrCanvas, maxSize, fromServer, customResizeFunction) {
            var promiseToReturn = new qq.Promise(),
                fileOrUrl, options;

            if (this._imageGenerator) {
                fileOrUrl = this._thumbnailUrls[fileId];
                options = {
                    customResizeFunction: customResizeFunction,
                    maxSize: maxSize > 0 ? maxSize : null,
                    scale: maxSize > 0
                };

                // If client-side preview generation is possible
                // and we are not specifically looking for the image URl returned by the server...
                if (!fromServer && qq.supportedFeatures.imagePreviews) {
                    fileOrUrl = this.getFile(fileId);
                }

                /* jshint eqeqeq:false,eqnull:true */
                if (fileOrUrl == null) {
                    promiseToReturn.failure({container: imgOrCanvas, error: "File or URL not found."});
                }
                else {
                    this._imageGenerator.generate(fileOrUrl, imgOrCanvas, options).then(
                        function success(modifiedContainer) {
                            promiseToReturn.success(modifiedContainer);
                        },

                        function failure(container, reason) {
                            promiseToReturn.failure({container: container, error: reason || "Problem generating thumbnail"});
                        }
                    );
                }
            }
            else {
                promiseToReturn.failure({container: imgOrCanvas, error: "Missing image generator module"});
            }

            return promiseToReturn;
        }
7460
function download(source, { verbose, output, onStart, onProgress } = {}) {
  return new Promise(function(y, n) {
    if (typeof output === 'undefined') {
      output = path.basename(url.parse(source).pathname) || 'unknown';
    }

    /**
     * Parse the source url into parts
     */
    const sourceUrl = url.parse(source);

    /**
     * Determine to use https or http request depends on source url
     */
    let request = null;
    if (sourceUrl.protocol === 'https:') {
      request = https.request;
    } else if (sourceUrl.protocol === 'http:') {
      request = http.request;
    } else {
      throw new Error('protocol should be http or https');
    }

    /**
     * Issue the request
     */
    const req = request(
      {
        method: 'GET',
        protocol: sourceUrl.protocol,
        host: sourceUrl.hostname,
        port: sourceUrl.port,
        path: sourceUrl.pathname + (sourceUrl.search || '')
      },
      function(res) {
        if (res.statusCode === 200) {
          const fileSize = Number.isInteger(res.headers['content-length'] - 0)
            ? parseInt(res.headers['content-length'])
            : 0;
          let downloadedSize = 0;

          /**
           * Create write stream
           */
          var writeStream = fs.createWriteStream(output, {
            flags: 'w+',
            encoding: 'binary'
          });

          res.pipe(writeStream);

          /**
           * Invoke `onStartCallback` function
           */
          if (onStart) {
            onStart(res.headers);
          }

          res.on('data', function(chunk) {
            downloadedSize += chunk.length;
            if (onProgress) {
              onProgress({
                fileSize,
                downloadedSize,
                percentage: fileSize > 0 ? downloadedSize / fileSize : 0
              });
            }
          });

          res.on('error', function(err) {
            writeStream.end();
            n(err);
          });

          writeStream.on('finish', function() {
            writeStream.end();
            req.end('finished');
            y({ headers: res.headers, fileSize });
          });
        } else if (
          res.statusCode === 301 ||
          res.statusCode === 302 ||
          res.statusCode === 307
        ) {
          const redirectLocation = res.headers.location;

          if (verbose) {
            console.log('node-wget-promise: Redirected to:', redirectLocation);
          }

          /**
           * Call download function recursively
           */
          download(redirectLocation, {
            output,
            onStart,
            onProgress
          })
            .then(y)
            .catch(n);
        } else {
          n('Server responded with unhandled status: ' + res.statusCode);
        }
      }
    );

    req.end('done');
    req.on('error', err => n(err));
  });
}
597365
function (platform, splash) {
  var deferred = Q.defer();
  var srcPath = settings.SPLASH_FILE;
  var platformPath = srcPath.replace(/\.png$/, '-' + platform.name + '.png');
  if (fs.existsSync(platformPath)) {
    srcPath = platformPath;
  }
  var dstPath = platform.splashPath + splash.name;
  var dst = path.dirname(dstPath);
  if (!fs.existsSync(dst)) {
    fs.mkdirsSync(dst);
  }
  ig.crop({
    srcPath: srcPath,
    dstPath: dstPath,
    quality: 1,
    format: 'png',
    width: splash.width,
    height: splash.height
  } , function(err, stdout, stderr){
    if (err) {
      deferred.reject(err);
    } else {
      deferred.resolve();
      display.success(splash.name + ' created');
    }
  });
  return deferred.promise;
}
1313901
function(data) {
    return Promise.retry(function() {
      return Promise.all(_.map(normalizer(data), function(datum) {

        // docker-compose run requires stdin to be a tty which causes
        // all sorts of chaos when you are running this through nodewebkit
        //
        // Until we can do this directly we compose run to get docker
        // config and then hit up dockerode for analogous run activity

        // can inspect a started container
        var winOpts = {
          background: true,
          rm: false,
          entrypoint: 'tail',
          cmd: ['-f', '/dev/null']
        };

        // Do the run and return the ID
        return compose.run(
          datum.compose,
          datum.project,
          _.extend({}, datum.opts, winOpts)
        )

        // Inspect
        .then(function(output) {
          // @todo: a better way to do this?
          var splitter = (process.platform === 'win32') ? '\r\n' : '\n';
          var parts = output.split(splitter);
          parts.pop();
          var id = _.last(parts);
          return docker.inspect(id);
        })

        // Remove the container and tap the data
        .tap(function(data) {
          return docker.remove(data.Id, {force: true, v: true});
        })

        // Now for the crazy shit
        .then(function(data) {

          // Parse commandy data
          var c = datum.opts.cmd;
          var e = datum.opts.entrypoint;
          var command = (_.isArray(e)) ? [c.join(' ')] : (c || []);
          var entrypoint = (!_.isArray(e)) ? [e] : e;

          // Refactor our create options
          // Handle opts.mode?
          var createOpts = data.Config;
          createOpts.Cmd = _.flatten(command);
          createOpts.name = _.trimLeft(data.Name, '/');
          createOpts.AttachStdin = true;
          createOpts.AttachStdout = true;
          createOpts.AttachStderr = true;
          createOpts.Mounts = data.Mounts;
          createOpts.HostConfig = data.HostConfig;
          createOpts.Tty = true;
          createOpts.OpenStdin = true;
          createOpts.StdinOnce = true;
          createOpts.Entrypoint = entrypoint;

          // Try to do the run
          return docker.run(createOpts, datum.opts);

        });
      }));
    });
  }
129112
function(url, callback) {
        if (isBrowser) {
            // Browser environments can't pipe, so download the file and add it
            return this.getImageDataFromUrl(url, function(err, data) {
                if (err) {
                    return callback(err);
                }

                this.addImageFromBuffer(data, callback);
            }.bind(this));
        }

        // Pipe the source URL into a POST-request
        request({ uri: url }).pipe(request({
            method: 'POST',
            uri: this.getSignedResourceUrl('POST', this.getImagesUrl()),
            json: true,
            headers: {
                'Accept': 'application/json',
                'User-Agent': 'imboclient-js'
            },
            onComplete: function(err, res, body) {
                callback(err, body ? body.imageIdentifier : null, body, res);
            }
        }));

        return this;
    }
43481
function stream (env) {
    let filter = parseFilter(env)

    filter.promise
      .then(data => {
        env.logger.log('Sass sources successfully parsed.')
        env.data = data
        onEmpty(data, env)
      })

    /**
     * Returned Promise await the full sequence,
     * instead of just the parsing step.
     */
    filter.promise = new Promise((resolve, reject) => {

      async function documentize () {
        try {
          init(env)
          await refresh(env)
          await theme(env)
          okay(env)
          resolve()
        } catch (err) {
          reject(err)
          env.emit('error', err)
          throw err
        }
      }

      filter
        .on('end', documentize)
        .on('error', err => env.emit('error', err))
        .resume() // Drain.

    })

    return filter
  }
446708
function stream (env) {
    let parseStream = parseFilter(env)

    let filter = through.obj((file, enc, cb) => cb(), function (cb) {
      parseStream.promise.then(data => {
        this.push(data)
        cb()
      }, cb)
    })

    return pipe(parseStream, filter)
  }
1260654
function dockerCommand(options) {
  const cmd = 'docker';
  const ps = spawnSync(cmd, options, { encoding: 'utf-8' });
  if (ps.error) {
    if (ps.error.code === 'ENOENT') {
      throw new Error('docker not found! Please install it.');
    }
    throw new Error(ps.error);
  } else if (ps.status !== 0) {
    throw new Error(ps.stderr);
  }
  return ps;
}