Set up Git, push to Heroku, and launch the app.
966866
def deploy_sandbox_shared_setup(log, verbose=True, app=None, exp_config=None):
    """"""
    if verbose:
        out = None
    else:
        out = open(os.devnull, "w")

    config = get_config()
    if not config.ready:
        config.load()
    heroku.sanity_check(config)

    (id, tmp) = setup_experiment(log, debug=False, app=app, exp_config=exp_config)

    # Register the experiment using all configured registration services.
    if config.get("mode") == "live":
        log("Registering the experiment on configured services...")
        registration.register(id, snapshot=None)

    # Log in to Heroku if we aren't already.
    log("Making sure that you are logged in to Heroku.")
    heroku.log_in()
    config.set("heroku_auth_token", heroku.auth_token())
    log("", chevrons=False)

    # Change to temporary directory.
    cwd = os.getcwd()
    os.chdir(tmp)

    # Commit Heroku-specific files to tmp folder's git repo.
    git = GitClient(output=out)
    git.init()
    git.add("--all")
    git.commit('"Experiment {}"'.format(id))

    # Initialize the app on Heroku.
    log("Initializing app on Heroku...")
    team = config.get("heroku_team", None)
    heroku_app = HerokuApp(dallinger_uid=id, output=out, team=team)
    heroku_app.bootstrap()
    heroku_app.buildpack("https://github.com/stomita/heroku-buildpack-phantomjs")

    # Set up add-ons and AWS environment variables.
    database_size = config.get("database_size")
    redis_size = config.get("redis_size")
    addons = [
        "heroku-postgresql:{}".format(quote(database_size)),
        "heroku-redis:{}".format(quote(redis_size)),
        "papertrail",
    ]
    if config.get("sentry"):
        addons.append("sentry")

    for name in addons:
        heroku_app.addon(name)

    heroku_config = {
        "aws_access_key_id": config["aws_access_key_id"],
        "aws_secret_access_key": config["aws_secret_access_key"],
        "aws_region": config["aws_region"],
        "auto_recruit": config["auto_recruit"],
        "smtp_username": config["smtp_username"],
        "smtp_password": config["smtp_password"],
        "whimsical": config["whimsical"],
    }

    heroku_app.set_multiple(**heroku_config)

    # Wait for Redis database to be ready.
    log("Waiting for Redis...")
    ready = False
    while not ready:
        try:
            r = redis.from_url(heroku_app.redis_url)
            r.set("foo", "bar")
            ready = True
        except (ValueError, redis.exceptions.ConnectionError):
            time.sleep(2)

    log("Saving the URL of the postgres database...")
    # Set the notification URL and database URL in the config file.
    config.extend(
        {
            "notification_url": heroku_app.url + "/notifications",
            "database_url": heroku_app.db_url,
        }
    )
    config.write()
    git.add("config.txt")
    time.sleep(0.25)
    git.commit("Save URLs for database and notifications")
    time.sleep(0.25)

    # Launch the Heroku app.
    log("Pushing code to Heroku...")
    git.push(remote="heroku", branch="HEAD:master")

    log("Scaling up the dynos...")
    size = config.get("dyno_type")
    for process in ["web", "worker"]:
        qty = config.get("num_dynos_" + process)
        heroku_app.scale_up_dyno(process, qty, size)
    if config.get("clock_on"):
        heroku_app.scale_up_dyno("clock", 1, size)

    time.sleep(8)

    # Launch the experiment.
    log("Launching the experiment on the remote server and starting recruitment...")
    launch_data = _handle_launch_data("{}/launch".format(heroku_app.url), error=log)
    result = {
        "app_name": heroku_app.name,
        "app_home": heroku_app.url,
        "recruitment_msg": launch_data.get("recruitment_msg", None),
    }
    log("Experiment details:")
    log("App home: {}".format(result["app_home"]), chevrons=False)
    log("Recruiter info:")
    log(result["recruitment_msg"], chevrons=False)

    # Return to the branch whence we came.
    os.chdir(cwd)

    log("Completed deployment of experiment " + id + ".")
    return result
355202
def set
      unless stack = Codex.in(shift_argument)
        error("Usage: heroku stack:set STACK.\nMust specify target stack.")
      end

      api.put_stack(app, stack)
      display "Stack set. Next release on #{app} will use #{Codex.out(stack)}."
      display "Run `git push heroku master` to create a new release on #{Codex.out(stack)}."
    end
69088
def run_app(self):
        """"""
        # Update system arguments
        sys.argv[0] = sys.executable
        sys.argv[1] = '{}.py'.format(sys.argv[1])

        # Make sure to exit with the return value from the subprocess call
        self._app_process = subprocess.Popen(sys.argv)
        return self._app_process.wait()
1083444
def run(self):
        
        try:
            if self.should_fetch:
                self.fetch()

            self.rebase_all_branches()

            if self.with_bundler():
                self.check_bundler()

            if self.settings['push.auto']:
                self.push()

        except GitError as error:
            self.print_error(error)

            # Used for test cases
            if self.testing:
                raise
            else:  # pragma: no cover
                sys.exit(1)
319920
def setup_app(command, conf, vars):
    """"""
    load_environment(conf.global_conf, conf.local_conf)
    setup_schema(command, conf, vars)
    bootstrap.bootstrap(command, conf, vars)
1054617
def run():
    """"""
    _parser_options()
    set_verbose(args["verbose"])
    
    if _check_global_settings():
        _load_db()
    else:
        exit(-1)

    #Check the server configuration against the script arguments passed in.
    _setup_server()

    if args["rollback"]:
        _server_rollback()
        okay("The server rollback appears to have been successful.")
        exit(0)

    _server_enable()    
    _list_repos()
    _handle_install()
    
    #This is the workhorse once a successful installation has happened.
    _do_cron()
116999
async function deploy() {
  // By default deploy to the staging deployment slot
  const remote = getRemote(process.argv.includes('--production') ? null : 'staging');

  // Initialize a new Git repository inside the `/build` folder
  // if it doesn't exist yet
  const repo = await GitRepo.open('build', { init: true });
  await repo.setRemote(remote.name, remote.url);

  // Fetch the remote repository if it exists
  if ((await repo.hasRef(remote.url, 'master'))) {
    await repo.fetch(remote.name);
    await repo.reset(`${remote.name}/master`, { hard: true });
    await repo.clean({ force: true });
  }

  // Build the project in RELEASE mode which
  // generates optimized and minimized bundles
  process.argv.push('--release');
  await run(require('./build'));

  // Push the contents of the build folder to the remote server via Git
  await repo.add('--all .');
  await repo.commit('Update');
  await repo.push(remote.name, 'master');

  // Check if the site was successfully deployed
  const response = await fetch(remote.website);
  console.log(`${remote.website} -> ${response.statusCode}`);
}
1190606
def run(self):
        """"""
        if os.system('git add .'):
            sys.exit(1)
        if self.message is not None:
            os.system('git commit -a -m "' + self.message + '"')
        else:
            os.system('git commit -a')
624100
def prepare_app_pipeline():
    """"""
    runner = ForemastRunner()
    runner.write_configs()
    runner.create_app()
    runner.create_pipeline()
    runner.cleanup()
624096
def run(self, args):
        '''
        
        '''
        command = args[0]
        try:
            if command == 'install':
                self._install(args)
            elif command == 'local':
                self._local(args)
            elif command == 'repo':
                self._repo(args)
            elif command == 'remove':
                self._remove(args)
            elif command == 'build':
                self._build(args)
            elif command == 'update_repo':
                self._download_repo_metadata(args)
            elif command == 'create_repo':
                self._create_repo(args)
            elif command == 'files':
                self._list_files(args)
            elif command == 'info':
                self._info(args)
            elif command == 'list':
                self._list(args)
            elif command == 'close':
                self._close()
            else:
                raise SPMInvocationError('Invalid command \'{0}\''.format(command))
        except SPMException as exc:
            self.ui.error(six.text_type(exc))
1185322
def run():
    

    setup_file = os.path.join(package_root, 'setup.py')

    git_wc_proc = subprocess.Popen(
        ['git', 'status', '--porcelain', '-uno'],
        stdout=subprocess.PIPE,
        stderr=subprocess.STDOUT,
        cwd=package_root
    )
    git_wc_status, _ = git_wc_proc.communicate()

    if len(git_wc_status) > 0:
        print(git_wc_status.decode('utf-8').rstrip(), file=sys.stderr)
        print('Unable to perform release since working copy is not clean', file=sys.stderr)
        return False

    git_tag_proc = subprocess.Popen(
        ['git', 'tag', '-l', '--contains', 'HEAD'],
        stdout=subprocess.PIPE,
        stderr=subprocess.PIPE,
        cwd=package_root
    )
    tag, tag_error = git_tag_proc.communicate()

    if len(tag_error) > 0:
        print(tag_error.decode('utf-8').rstrip(), file=sys.stderr)
        print('Error looking for current git tag', file=sys.stderr)
        return False

    if len(tag) == 0:
        print('No git tag found on HEAD', file=sys.stderr)
        return False

    tag = tag.decode('ascii').strip()

    setuptools.sandbox.run_setup(
        setup_file,
        ['sdist', 'bdist_wheel', '--universal']
    )

    twine.cli.dispatch(['upload', 'dist/%s-%s*' % (package_name, tag)])

    setuptools.sandbox.run_setup(
        setup_file,
        ['clean']
    )
602107
async function deploy() {
  // Initialize a new repository
  await makeDir('build');
  await spawn('git', ['init', '--quiet'], options);

  // Changing a remote's URL
  let isRemoteExists = false;
  try {
    await spawn(
      'git',
      ['config', '--get', `remote.${remote.name}.url`],
      options,
    );
    isRemoteExists = true;
  } catch (error) {
    /* skip */
  }
  await spawn(
    'git',
    ['remote', isRemoteExists ? 'set-url' : 'add', remote.name, remote.url],
    options,
  );

  // Fetch the remote repository if it exists
  let isRefExists = false;
  try {
    await spawn(
      'git',
      ['ls-remote', '--quiet', '--exit-code', remote.url, remote.branch],
      options,
    );
    isRefExists = true;
  } catch (error) {
    await spawn('git', ['update-ref', '-d', 'HEAD'], options);
  }
  if (isRefExists) {
    await spawn('git', ['fetch', remote.name], options);
    await spawn(
      'git',
      ['reset', `${remote.name}/${remote.branch}`, '--hard'],
      options,
    );
    await spawn('git', ['clean', '--force'], options);
  }

  // Build the project in RELEASE mode which
  // generates optimized and minimized bundles
  process.argv.push('--release');
  if (remote.static) process.argv.push('--static');
  await run(require('./build').default); // eslint-disable-line global-require
  if (process.argv.includes('--static')) {
    await cleanDir('build/*', {
      nosort: true,
      dot: true,
      ignore: ['build/.git', 'build/public'],
    });
    await moveDir('build/public', 'build');
  }

  // Push the contents of the build folder to the remote server via Git
  await spawn('git', ['add', '.', '--all'], options);
  try {
    await spawn('git', ['diff', '--cached', '--exit-code', '--quiet'], options);
  } catch (error) {
    await spawn(
      'git',
      ['commit', '--message', `Update ${new Date().toISOString()}`],
      options,
    );
  }
  await spawn(
    'git',
    ['push', remote.name, `master:${remote.branch}`, '--set-upstream'],
    options,
  );

  // Check if the site was successfully deployed
  const response = await fetch(remote.website);
  console.info(
    `${remote.website} => ${response.status} ${response.statusText}`,
  );
}
1034286
def run(prefix, cmd, postfix, options, args, &block)
      timeout  = options.delete(:timeout) rescue nil
      timeout  = true if timeout.nil?

      base     = options.delete(:base) rescue nil
      base     = true if base.nil?

      if input = options.delete(:input)
        block = lambda { |stdin| stdin.write(input) }
      end

      opt_args = transform_options(options)

      if RUBY_PLATFORM.downcase =~ /mswin(?!ce)|mingw|bccwin/
        ext_args = args.reject { |a| a.empty? }.map { |a| (a == '--' || a[0].chr == '|' || Grit.no_quote) ? a : "\"#{e(a)}\"" }
        gitdir = base ? "--git-dir=\"#{self.git_dir}\"" : ""
        call = "#{prefix}#{Git.git_binary} #{gitdir} #{cmd.to_s.gsub(/_/, '-')} #{(opt_args + ext_args).join(' ')}#{e(postfix)}"
      else
        ext_args = args.reject { |a| a.empty? }.map { |a| (a == '--' || a[0].chr == '|' || Grit.no_quote) ? a : "'#{e(a)}'" }
        gitdir = base ? "--git-dir='#{self.git_dir}'" : ""
        call = "#{prefix}#{Git.git_binary} #{gitdir} #{cmd.to_s.gsub(/_/, '-')} #{(opt_args + ext_args).join(' ')}#{e(postfix)}"
      end

      Grit.log(call) if Grit.debug
      response, err = timeout ? sh(call, &block) : wild_sh(call, &block)
      Grit.log(response) if Grit.debug
      Grit.log(err) if Grit.debug
      response
    end
834249
def main():
    
    logging.basicConfig(
        format='[%(asctime)s] %(levelname)s -- %(message)s',
        level=logging.DEBUG)

    parser = argparse.ArgumentParser(description='')
    parser.add_argument('git_url', help='Url of the repo to sync')
    parser.add_argument('branch_name', default='master', help='Branch of repo to sync', nargs='?')
    parser.add_argument('repo_dir', default='.', help='Path to clone repo under', nargs='?')
    args = parser.parse_args()

    for line in GitPuller(
        args.git_url,
        args.branch_name,
        args.repo_dir
    ).pull():
        print(line)
117393
def main():
    """"""

    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument(
        'githubtoken',
        help="Github OAuth token, see https://developer.github.com/v3/oauth/")
    parser.add_argument('destination', help="location of the downloaded repos")
    parser.add_argument(
        '-n', '--nbrepo', help="number of repositories per language",
        type=int, default=1000)
    parser.add_argument(
        '-d', '--debug', default=False, action='store_true',
        help="show debug messages")

    args = parser.parse_args()
    config_logging(args.debug)

    destination = Path(args.destination)
    nb_repos = args.nbrepo
    token = args.githubtoken

    languages = config_dict('languages.json')
    destination.mkdir(exist_ok=True)

    for pos, language in enumerate(sorted(languages), 1):
        LOGGER.info("Step %.2f%%, %s", 100 * pos / len(languages), language)
        LOGGER.info("Fetch %d repos infos for language %s", nb_repos, language)
        repos = _retrieve_repo_details(language, nb_repos, token)
        LOGGER.info("%d repos details kept. Downloading", len(repos))
        _download_repos(language, repos, destination)
        LOGGER.info("Language %s repos downloaded", language)

    LOGGER.debug("Exit OK")
324134
def push(self):
        
        self.github_repo.create_and_push()
        self._repo = self.github_repo.repo
        return self._repo
909356
def init(ctx, client, directory, name, force, use_external_storage):
    """"""
    if not client.use_external_storage:
        use_external_storage = False

    ctx.obj = client = attr.evolve(
        client,
        path=directory,
        use_external_storage=use_external_storage,
    )

    msg = 'Initialized empty project in {path}'
    branch_name = None

    stack = contextlib.ExitStack()

    if force and client.repo:
        msg = 'Initialized project in {path} (branch {branch_name})'
        merge_args = ['--no-ff', '-s', 'recursive', '-X', 'ours']

        try:
            commit = client.find_previous_commit(
                str(client.renku_metadata_path),
            )
            branch_name = 'renku/init/' + str(commit)
        except KeyError:
            from git import NULL_TREE
            commit = NULL_TREE
            branch_name = 'renku/init/root'
            merge_args.append('--allow-unrelated-histories')

        ctx.obj = client = stack.enter_context(
            client.worktree(
                branch_name=branch_name,
                commit=commit,
                merge_args=merge_args,
            )
        )

    try:
        with client.lock:
            path = client.init_repository(name=name, force=force)
    except FileExistsError:
        raise click.UsageError(
            'Renku repository is not empty. '
            'Please use --force flag to use the directory as Renku '
            'repository.'
        )

    stack.enter_context(client.commit())

    with stack:
        # Install Git hooks.
        from .githooks import install
        ctx.invoke(install, force=force)

        # Create all necessary template files.
        from .runner import template
        ctx.invoke(template, force=force)

    click.echo(msg.format(path=path, branch_name=branch_name))