/*
Cli container def
505194
function() {
    return {
      compose: self.app.composeCore,
      project: self.app.name,
      opts: {
        services: ['terminus'],
        mode: 'collect',
        app: self.app
      }
    };
  }
378981
def run_container(self, conf, images, **kwargs):
        """"""
        with self._run_container(conf, images, **kwargs):
            pass
908495
function() {
    return {
      compose: app.composeCore,
      project: app.name,
      opts: {
        mode: kbox.core.deps.get('mode') === 'gui' ? 'collect' : 'attach',
        services: ['cli'],
        app: app
      }
    };
  }
418276
function Container(parent) {
      this.parent = parent;
      this.children = [];

      this.resolver = parent && parent.resolver || function() {};

      this.registry       = dictionary(parent ? parent.registry : null);
      this.cache          = dictionary(parent ? parent.cache : null);
      this.factoryCache   = dictionary(parent ? parent.factoryCache : null);
      this.resolveCache   = dictionary(parent ? parent.resolveCache : null);
      this.typeInjections = dictionary(parent ? parent.typeInjections : null);
      this.injections     = dictionary(null);
      this.normalizeCache = dictionary(null);

      this.factoryTypeInjections = dictionary(parent ? parent.factoryTypeInjections : null);
      this.factoryInjections     = dictionary(null);

      this._options     = dictionary(parent ? parent._options : null);
      this._typeOptions = dictionary(parent ? parent._typeOptions : null);
    }
34849
def handle_basic_container_args(options, parser=None):
    
    dir_modes = {}
    error_fn = parser.error if parser else sys.exit

    def handle_dir_mode(path, mode):
        path = os.path.abspath(path)
        if not os.path.isdir(path):
            error_fn(
                "Cannot specify directory mode for '{}' because it does not exist or is no directory."
                .format(path))
        if path in dir_modes:
            error_fn("Cannot specify multiple directory modes for '{}'.".format(path))
        dir_modes[path] = mode

    for path in options.hidden_dir:
        handle_dir_mode(path, DIR_HIDDEN)
    for path in options.read_only_dir:
        handle_dir_mode(path, DIR_READ_ONLY)
    for path in options.overlay_dir:
        handle_dir_mode(path, DIR_OVERLAY)
    for path in options.full_access_dir:
        handle_dir_mode(path, DIR_FULL_ACCESS)

    if options.keep_tmp:
        if "/tmp" in dir_modes and not dir_modes["/tmp"] == DIR_FULL_ACCESS:
            error_fn("Cannot specify both --keep-tmp and --hidden-dir /tmp.")
        dir_modes["/tmp"] = DIR_FULL_ACCESS
    elif not "/tmp" in dir_modes:
        dir_modes["/tmp"] = DIR_HIDDEN

    if not "/" in dir_modes:
        dir_modes["/"] = DIR_OVERLAY
    if not "/run" in dir_modes:
        dir_modes["/run"] = DIR_HIDDEN

    if options.container_system_config:
        if options.network_access:
            logging.warning("The container configuration disables DNS, "
                "host lookups will fail despite --network-access. "
                "Consider using --keep-system-config.")
    else:
        # /etc/resolv.conf is necessary for DNS lookups and on many systems is a symlink
        # to either /run/resolvconf/resolv.conf or /run/systemd/resolve/sub-resolve.conf,
        # so we keep that directory accessible as well.
        if not "/run/resolvconf" in dir_modes and os.path.isdir("/run/resolvconf"):
            dir_modes["/run/resolvconf"] = DIR_READ_ONLY
        if not "/run/systemd/resolve" in dir_modes and os.path.isdir("/run/systemd/resolve"):
            dir_modes["/run/systemd/resolve"] = DIR_READ_ONLY

    return {
        'network_access': options.network_access,
        'container_tmpfs': options.tmpfs,
        'container_system_config': options.container_system_config,
        'dir_modes': dir_modes,
        }
1008278
def cli():
    """"""
    parser = argparse.ArgumentParser()
    parser.add_argument('api', help="""
        API to call.
        One one of 'article', 'frontpage', 'product', 'image', 'analyze', or
        'discussion'.
    """)
    parser.add_argument('url', help="""
        URL to pass as the 'url' parameter.
    """)
    parser.add_argument('token', help="""
        API key (token).
        Get one at https://www.diffbot.com/.
    """)
    parser.add_argument('-a', '--all', help="""
        Request all fields.
    """, action='store_true')
    parser.add_argument('-f', '--file', help="""
        File to read data from.
        Use '-' to read from STDIN.
    """)
    fields = text = html = None
    _args = parser.parse_args()
    if _args.all:
        fields = '*'
    if _args.file == '-':
        text = sys.stdin.read()
    elif _args.file:
        with open(_args.file, 'rb') as src:
            if os.path.splitext(_args.file)[1] in ('.html', '.htm'):
                html = src.read().decode(ENCODING)
            else:
                text = src.read().decode(ENCODING)
    print(json.dumps((api(_args.api, _args.url, _args.token,
                          html=html or None,
                          text=text or None,
                          fields=fields)),
                     sort_keys=True,
                     indent=2))
717338
def container(self, cls, **kwargs):
        """"""
        self.start_container(cls, **kwargs)
        yield
        self.end_container()
834686
def get_cli():
    """"""
    parser = argparse.ArgumentParser(
        prog="auto_version",
        description="auto version v%s: a tool to control version numbers" % __version__,
    )
    parser.add_argument(
        "--target",
        action="append",
        default=[],
        help="Files containing version info. "
        "Assumes unique variable names between files. (default: %s)."
        % (config.targets,),
    )
    parser.add_argument(
        "--bump",
        choices=SemVerSigFig,
        help="Bumps the specified part of SemVer string. "
        "Use this locally to correctly modify the version file.",
    )
    parser.add_argument(
        "--news",
        "--file-triggers",
        action="store_true",
        dest="file_triggers",
        help="Detects need to bump based on presence of files (as specified in config).",
    )
    parser.add_argument(
        "--set",
        help="Set the SemVer string. Use this locally to set the project version explicitly.",
    )
    parser.add_argument(
        "--set-patch-count",
        action="store_true",
        help="Sets the patch number to the commit count.",
    )
    parser.add_argument(
        "--lock",
        action="store_true",
        help="Locks the SemVer string. "
        "Lock will remain for another call to autoversion before being cleared.",
    )
    parser.add_argument(
        "--release",
        action="store_true",
        default=False,
        help="Marks as a release build, which flags the build as released.",
    )
    parser.add_argument(
        "--version",
        action="store_true",
        default=False,
        help="Prints the version of auto_version itself (self-version).",
    )
    parser.add_argument("--config", help="Configuration file path.")
    parser.add_argument(
        "-v",
        "--verbosity",
        action="count",
        default=0,
        help="increase output verbosity. " "can be specified multiple times",
    )
    return parser.parse_known_args()
1302922
public function container($container = null, Closure $callback = null)
    {
        $container = is_null($container) ? $this->defaultContainer : $container;

        if (!isset($this->containers[$container])) {
            $this->addContainer(
                $container,
                $this->getContainerTypes($container),
                $this->getContainerFormat($container),
                $this->getContainerFormats($container)
            );
        }

        if (is_callable($callback)) {
            $callback($this->containers[$container]);
        }

        return $this->containers[$container];
    }
42889
def cli(ctx, file, quote):
    ''''''
    ctx.obj = {}
    ctx.obj['FILE'] = file
    ctx.obj['QUOTE'] = quote
698476
protected function cmdExport() /*: void*/
    {
        /**
         * @see simplecomplex_locale_text_cli()
         */
        $container = Dependency::container();
        // Validate input. ---------------------------------------------
        $language = '';
        if (empty($this->command->arguments['language'])) {
            $this->command->inputErrors[] = !isset($this->command->arguments['language']) ?
                'Missing \'language\' argument.' : 'Empty \'language\' argument.';
        } else {
            $language = $this->command->arguments['language'];
            if (!LocaleCode::validate($language)) {
                $this->command->inputErrors[] = 'Invalid \'language\' argument.';
            }
        }
        $target_file = '';
        if (empty($this->command->arguments['target-file'])) {
            $this->command->inputErrors[] = !isset($this->command->arguments['target-file']) ?
                'Missing \'target-file\' argument.' : 'Empty \'target-file\' argument.';
        } else {
            $target_file = $this->command->arguments['target-file'];
        }

        $from_sources = !empty($this->command->options['from-sources']);
        $format = !empty($this->command->options['format']) ? $this->command->options['format'] : 'JSON';
        $unescaped = !empty($this->command->options['unescaped']);
        $pretty = !empty($this->command->options['pretty']);

        // Pre-confirmation --yes/-y ignored for this command.
        if ($this->environment->riskyCommandRequireConfirm && $this->command->preConfirmed) {
            $this->command->inputErrors[] = 'Pre-confirmation \'yes\'/-y option not supported for this command,'
                . "\n" . 'unless env var PHP_LIB_SIMPLECOMPLEX_UTILS_CLI_SKIP_CONFIRM'
                . "\n" . 'or .risky_command_skip_confirm file in document root.';
        }
        if ($this->command->inputErrors) {
            foreach ($this->command->inputErrors as $msg) {
                $this->environment->echoMessage(
                    $this->environment->format($msg, 'hangingIndent'),
                    'notice'
                );
            }
            // This command's help text.
            $this->environment->echoMessage("\n" . $this->command);
            exit;
        }
        // Check if the command is doable.------------------------------
        if ($container->has('config')) {
            /** @var \SimpleComplex\Config\IniSectionedConfig $config */
            $config = $container->get('config');
        } else {
            $config_class = static::CLASS_CONFIG;
            /** @var \SimpleComplex\Config\IniSectionedConfig $config */
            $config = new $config_class('global');
        }
        $locale_text_paths = $config->get('lib_simplecomplex_locale', 'localeTextPaths');
        if (!$locale_text_paths) {
            $this->environment->echoMessage(
                'Global config misses item section[lib_simplecomplex_locale] key[localeTextPaths].',
                'warning'
            );
            exit;
        }
        if (!is_array($locale_text_paths)) {
            $this->environment->echoMessage(
                'Global config item section[lib_simplecomplex_locale] key[localeTextPaths] is not array.',
                'error'
            );
            exit;
        }
        // localeTextPaths are relative to vendor dir, unless absolute.
        $vendor_dir = Utils::getInstance()->vendorDir();
        foreach ($locale_text_paths as &$path) {
            if ($path{0} !== '/' && strpos($path, $vendor_dir . '/') !== 0) {
                $path = $vendor_dir . '/' . $path;
            }
        }
        unset($path);
        // Do it.
        $locale_text_class = static::CLASS_LOCALE_TEXT;
        /** @var LocaleText $locale_text */
        $locale_text = new $locale_text_class($language, $locale_text_paths);
        // Display command and the arg values used.---------------------
        if ($this->environment->riskyCommandRequireConfirm || !$this->command->preConfirmed) {
            $this->environment->echoMessage(
                $this->environment->format(
                    $this->environment->format($this->command->name, 'emphasize')
                    . "\n" . 'language: ' . $language
                    . "\n" . 'target-file: ' . $target_file
                    . (!$this->command->options ? '' : ("\n--" . join(' --', array_keys($this->command->options)))),
                    'hangingIndent'
                )
            );
        }
        // Request confirmation, ignore --yes/-y pre-confirmation option;
        // unless .risky_command_skip_confirm file placed in document root.
        if ($this->environment->riskyCommandRequireConfirm) {
            if (!$this->environment->confirm(
                'Export that locale-text language from ' . (!$from_sources ? 'cache' : 'sources')
                . ' - will overwrite the target file (if exists)?'
                . "\n" . 'Type \'yes\' to continue:',
                ['yes'],
                '',
                'Aborted exporting locale-text language.'
            )) {
                exit;
            }
        } elseif (!$this->command->preConfirmed && !$this->environment->confirm(
                'Export that locale-text language from ' . (!$from_sources ? 'cache' : 'sources')
                . ' - will overwrite the target file (if exists)?'
                . "\n" . 'Type \'yes\' or \'y\' to continue:',
                ['yes', 'y'],
                '',
                'Aborted exporting locale-text language.'
            )) {
            exit;
        }
        // Do it.
        if (!$locale_text->export(
            $target_file,
            [
                'fromSources' => $from_sources,
                'format' => strtoupper($format),
                'unescaped' => $unescaped,
                'pretty' => $pretty,
            ]
        )) {
            $this->environment->echoMessage('Failed to export locale-text language[' . $language . '].', 'error');
        } elseif (!$this->command->silent) {
            $this->environment->echoMessage(
                'Exported locale-text language[' . $language . '] from ' . (!$from_sources ? 'cache' : 'sources')
                . ' to target file[' . $target_file . '].',
                'success'
            );
        }
        exit;
    }
1320252
private function cliIO()
    {
        $services = [
            'Cli\Input'  => 'input',
            'Cli\Output' => 'output',
        ];

        foreach ($services as $className => $classOffset) {
            $this->services->load($className, $classOffset);
        }
    }
548560
function getDockerUid(bindPath) {
  const options = [
    'run',
    '--rm',
    '-v',
    `${bindPath}:/test`,
    'alpine',
    'stat',
    '-c',
    '%u',
    '/bin/sh'
  ];
  const ps = dockerCommand(options);
  return ps.stdout.trim();
}
308297
def rm(self, container_alias):

        '''
            
        '''

        title = '%s.rm' % self.__class__.__name__

    # validate inputs
        input_fields = {
            'container_alias': container_alias
        }
        for key, value in input_fields.items():
            object_title = '%s(%s=%s)' % (title, key, str(value))
            self.fields.validate(value, '.%s' % key, object_title)

    # run remove command
        sys_cmd = 'docker rm -f %s' % container_alias
        output_lines = self.command(sys_cmd).split('\n')

        return output_lines[0]
1004699
def cli():
    """"""
    parser = argparse.ArgumentParser(prog="sphinx-serve",
                                     formatter_class=argparse.ArgumentDefaultsHelpFormatter,
                                     conflict_handler="resolve",
                                     description=__doc__
                                     )

    parser.add_argument("-v", "--version", action="version",
                        version="%(prog)s {0}".format(__version__)
                        )

    parser.add_argument("-h", "--host", action="store",
                        default="0.0.0.0",
                        help="Listen to the given hostname"
                        )

    parser.add_argument("-p", "--port", action="store",
                        type=int, default=8081,
                        help="Listen to given port"
                        )

    parser.add_argument("-b", "--build", action="store",
                        default="_build",
                        help="Build folder name"
                        )

    parser.add_argument("-s", "--single", action="store_true",
                        help="Serve the single-html documentation version"
                        )

    return parser.parse_args()
499353
function CliDispatch (action, dir, baseDir) {
  this.action = action
  this.dir = dir
  this.baseDir = baseDir
}
1184106
function (file) {
  let port = program.port,
    host = program.host || '127.0.0.1',
    dbname = program.dbname || '-deployd',
    mongoPort = program.mongoPort ? Number(program.mongoPort) : '27017',
    env = program.environment || process.env.DPD_ENV || 'development',
    retries = 0,
    credentials = {};


  if (!port) {
    port = 2403;
    retries = env === 'development' && 5;
  }

  if (file) {
    process.chdir(path.dirname(file));
  }
  if (test('-f', 'app.dpd')) {
    console.log(`deployd CLI version ${packageInfo.version}`);
    console.log('starting deployd');

    if (fs.existsSync(latestversionFile)) {
      const latest = fs.readFileSync(latestversionFile, 'utf-8');
      if (latest && semver.gt(latest, packageInfo.version)) {
        console.log(`deployd CLI v${latest} is available.`);
        console.log();
      }
    }
    checkForUpdates();

    if (!test('-d', './.dpd')) mkdir('-p', './.dpd');
    if (!test('-d', './.dpd/pids')) mkdir('-p', './.dpd/pids');
    if (!test('-d', './data')) mkdir('-p', './data');

    if (program.auth && program.host === undefined) {
      console.error("Authentication requires the '-h' host flag... exiting.");
      process.exit();
    }

    function setCredentials(username, password) { // eslint-disable-line no-inner-declarations
      Step(function () {
        const next = this;
        if (username && username !== '') {
          credentials.username = username;
          next();
        } else {
          console.error('Username cannot be blank.');
          process.exit();
        }
      },
        function () {
          const next = this;
          if (password && password !== '') {
            credentials.password = password;
            next();
          } else {
            console.error('Password cannot be blank.');
            process.exit();
          }
        },
        startup
      );
    }

    if (program.host) {
      if (program.auth) {
        const auth = program.auth.split(':'),
          username = auth[0],
          password = auth[1];
        setCredentials(username, password);
      } else if (program.username || program.password) {
        setCredentials(program.username, program.password);
      } else {
        startup();
      }
    } else {
      mongod.restart(program.mongod || 'mongod', env, mongoPort, startup);
    }
  } else {
    console.log('This directory does not contain a Deployd app!');
    console.log('Use "dpd create <appname>" to create a new app');
    console.log('or use "dpd path/to/app.dpd" to start an app in another directory');
    stop(1);
  }

  function startup(err) {
    if (err) {
      console.log("Failed to start MongoDB (Make sure 'mongod' are in your $PATH or use dpd --mongod option. Ref: http://docs.deployd.com/docs/basics/cli.html)");
      return stop(1);
    }

    const options = { port, env: 'development', db: { host, port: mongoPort, name: dbname } };

    options.env = program.environment || process.env.DPD_ENV || options.env;
    if (options.env !== 'development') console.log('starting in %s mode', options.env);

    if (credentials && credentials.length > 0) options.db.credentials = credentials;

    let dpd = createServer(options);
    dpd.on('listening', onListening);
    dpd.on('error', onError);
    dpd.listen();
    dpd.deploydPath = program.deploydPath;

    function onListening() {
      console.info('listening on port', options.port);
      const commands = repl(dpd);
      if (program.dashboard) {
        commands.dashboard();
      } else if (program.open) {
        commands.open();
      }
    }

    function onError(err2) {
      if (err2.code === 'EADDRINUSE') {
        console.error();
        console.error(`ERROR: port ${options.port} is already in use`);
        if (retries > 0) {
          options.port += 1;
          console.log(`Trying again on port ${options.port}...`);
          console.log();
          retries -= 1;
          dpd = createServer(options);
          dpd.on('listening', onListening);
          dpd.on('error', onError);
          dpd.listen();
        } else {
          process.exit();
        }
      } else {
        console.error(err2);
        process.exit();
      }
    }
  }
}