Deploying A Data Source. Check If It Exists First, then update, if not create it.
433522
function deploy(connections, dataSource, cb) {

  async.waterfall([
    function validateParams(cb) {
      var dataSourceValidator = validate(dataSource);
      //The data source parameter should have an ID property.
      dataSourceValidator.has(CONSTANTS.DATA_SOURCE_ID, function(err) {
        if (err) {
          return cb(buildErrorResponse({error: new Error("An ID Parameter Is Required To Deploy A Data Source"), code: ERROR_CODES.FH_FORMS_INVALID_PARAMETERS}));
        }

        cb(undefined, dataSource);
      });
    },
    function findDataSource(dataSource, cb) {
      var query = {

      };

      //Searching By ID.
      query[CONSTANTS.DATA_SOURCE_ID] = dataSource[CONSTANTS.DATA_SOURCE_ID];

      //Looking up a full data source document as we are updating
      lookUpDataSources(connections, {
        query: query,
        lean: false
      }, function(err, dataSources) {
        if (err) {
          return cb(buildErrorResponse({
            error: err,
            userDetail: "Unexpected Error When Searching For A Data Source",
            code: ERROR_CODES.FH_FORMS_UNEXPECTED_ERROR
          }));
        }

        //If no data sources found create, otherwise update.
        if (dataSources.length === 0) {
          connections.deploy = true;
          create(connections, dataSource, cb);
        } else {
          update(connections, dataSource, cb);
        }
      });
    }
  ], cb);
}
902230
function(callback) {
      fs.exists(options.source, function(exists) {
        if(!exists) { callback(new Error('Source file do not exists!')); }
        else { callback(null, true); }
      });
    }
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}`,
  );
}
222723
def create(self, columns=None, type_map=None, overwrite=False):
        """"""
        # Check already exists #
        if self.count_bytes > 0:
            if overwrite: self.remove()
            else: raise Exception("File exists already at '%s'" % self)
        # If we want it empty #
        if columns is None:
            self.touch()
        # Make the table #
        else:
            self.add_table(self.main_table, columns=columns, type_map=type_map)
359034
def _upsert(context, params, data):
    """"""
    table = params.get("table")
    table = datastore.get_table(table, primary_id=False)
    unique_keys = ensure_list(params.get("unique"))
    data["__last_seen"] = datetime.datetime.utcnow()
    if len(unique_keys):
        updated = table.update(data, unique_keys, return_count=True)
        if updated:
            return
    data["__first_seen"] = data["__last_seen"]
    table.insert(data)
1324663
def create():
    
    # Generate project locale
    locale = env.locale.replace("UTF-8", "utf8")
    with hide("stdout"):
        if locale not in run("locale -a"):
            sudo("locale-gen %s" % env.locale)
            sudo("update-locale %s" % env.locale)
            sudo("service postgresql restart")
            run("exit")

    # Create project path
    run("mkdir -p %s" % env.proj_path)

    # Set up virtual env
    run("mkdir -p %s" % env.venv_home)
    with cd(env.venv_home):
        if exists(env.proj_name):
            if confirm("Virtualenv already exists in host server: %s"
                       "\nWould you like to replace it?" % env.proj_name):
                run("rm -rf %s" % env.proj_name)
            else:
                abort()
        run("virtualenv %s" % env.proj_name)

    # Upload project files
    if env.deploy_tool in env.vcs_tools:
        vcs_upload()
    else:
        rsync_upload()

    # Create DB and DB user
    pw = db_pass()
    user_sql_args = (env.proj_name, pw.replace("'", "\'"))
    user_sql = "CREATE USER %s WITH ENCRYPTED PASSWORD '%s';" % user_sql_args
    psql(user_sql, show=False)
    shadowed = "*" * len(pw)
    print_command(user_sql.replace("'%s'" % pw, "'%s'" % shadowed))
    psql("CREATE DATABASE %s WITH OWNER %s ENCODING = 'UTF8' "
         "LC_CTYPE = '%s' LC_COLLATE = '%s' TEMPLATE template0;" %
         (env.proj_name, env.proj_name, env.locale, env.locale))

    # Set up SSL certificate
    if not env.ssl_disabled:
        conf_path = "/etc/nginx/conf"
        if not exists(conf_path):
            sudo("mkdir %s" % conf_path)
        with cd(conf_path):
            crt_file = env.proj_name + ".crt"
            key_file = env.proj_name + ".key"
            if not exists(crt_file) and not exists(key_file):
                try:
                    crt_local, = glob(join("deploy", "*.crt"))
                    key_local, = glob(join("deploy", "*.key"))
                except ValueError:
                    parts = (crt_file, key_file, env.domains[0])
                    sudo("openssl req -new -x509 -nodes -out %s -keyout %s "
                         "-subj '/CN=%s' -days 3650" % parts)
                else:
                    upload_template(crt_local, crt_file, use_sudo=True)
                    upload_template(key_local, key_file, use_sudo=True)

    # Install project-specific requirements
    upload_template_and_reload("settings")
    with project():
        if env.reqs_path:
            pip("-r %s/%s" % (env.proj_path, env.reqs_path))
        pip("gunicorn setproctitle psycopg2 "
            "django-compressor python-memcached")
    # Bootstrap the DB
        manage("createdb --noinput --nodata")
        python("from django.conf import settings;"
               "from django.contrib.sites.models import Site;"
               "Site.objects.filter(id=settings.SITE_ID).update(domain='%s');"
               % env.domains[0])
        for domain in env.domains:
            python("from django.contrib.sites.models import Site;"
                   "Site.objects.get_or_create(domain='%s');" % domain)
        if env.admin_pass:
            pw = env.admin_pass
            user_py = ("from django.contrib.auth import get_user_model;"
                       "User = get_user_model();"
                       "u, _ = User.objects.get_or_create(username='admin');"
                       "u.is_staff = u.is_superuser = True;"
                       "u.set_password('%s');"
                       "u.save();" % pw)
            python(user_py, show=False)
            shadowed = "*" * len(pw)
            print_command(user_py.replace("'%s'" % pw, "'%s'" % shadowed))

    return True
910576
def create_or_update(options) #:nodoc:
                                  #      puts 'create_or_update'
      ret = true
      run_callbacks :save do
        result = new_record? ? create(options) : update(options)
#        puts 'save_callbacks result=' + result.inspect
        ret = result
      end
      ret
    end
721989
def upsert(self):
        
        if not self.jenkins_host.has_job(self.name):
            LOGGER.info("creating {0}...".format(self.name))
            self.jenkins_host.create_job(self.name, self.config_xml)
        else:
            jenkins_job = self.jenkins_host[self.name]
            LOGGER.info("updating {0}...".format(self.name))
            jenkins_job.update_config(self.config_xml)
185677
function syncDB(options) {
  var uri = options.uri || conf.db,
      entries = (options.drop ? scripts('drop') : []).concat(scripts('create')),
      progress = options.progress || noop,
      complete = options.complete || noop;

  connect(uri, function(err, client, done) {
    if(err) { throw err; }
    run(client, done);
  });

  function run(client, done) {
    var entry = entries.shift()
      , script
      , path;

    if(entry !== undefined) {
      script = entry[0];
      path = entry[1];

      progress(script, path);
      client.query(script, function (err) {
        if(err) {
          complete(err);
          done(err);
        } else {
          run(client, done);
        }
      });
    } else {
      complete();
      done();
    }
  }

}
1336532
def deploy(self, package=None):
        
        if package is None:
            package = deployment_package.default()
        package.deploy()
        if self.proper_name in installed_functions():
            self.update(package)
        else:
            self.install(package)
126794
function updateValidAndInvalidDataSources(dataSourcesToSplit, currentInvalidDataSources) {
  logger.debug("dataSourcesToSplit", dataSourcesToSplit);
  currentInvalidDataSources = currentInvalidDataSources || [];
  var validInvalid = _.partition(dataSourcesToSplit, function(dataSourceUpdateData) {
    if (dataSourceUpdateData) {
      return !dataSourceUpdateData.error;
    }
    return true;
  });

  var validDataSources = validInvalid[0];

  //Updating any data sources that are no longer valid
  var invalidDataSources = _.union(validInvalid[1], currentInvalidDataSources);

  return {
    valid: validDataSources,
    invalid: invalidDataSources
  };
}
708814
def check_if_exists(self):
        """"""
        if self.req is None:
            return False
        try:
            self.satisfied_by = pkg_resources.get_distribution(self.req)
        except pkg_resources.DistributionNotFound:
            return False
        except pkg_resources.VersionConflict:
            self.conflicts_with = pkg_resources.get_distribution(self.req.project_name)
        return True
828131
def _create_and_update(self):
        
        data_json = self._create_json()
        data_json.update(self.additional_params)
        request_url = self._artifactory.drive + '/api/{uri}/{x.name}'.format(uri=self._uri, x=self)
        r = self._session.put(
            request_url,
            json=data_json,
            headers={'Content-Type': 'application/json'},
            auth=self._auth,
        )
        r.raise_for_status()
        rest_delay()
        self.read()
789822
public function deploy()
    {
        $this->logger->notice('Deploying ' . $this->name . ' (' . $this->releaseIdentifier . ')');
        $this->workflow->run($this);
    }
911611
def create_source(srcdir, preload_image, datapusher=False):
    
    try:
        docker.web_command(
            command='/bin/cp -a /project/ckan /project_target/ckan',
            rw={srcdir: '/project_target'},
            image=preload_image)
        if datapusher:
            docker.web_command(
                command='/bin/cp -a /project/datapusher /project_target/datapusher',
                rw={srcdir: '/project_target'},
                image=preload_image)
        shutil.copy(
            srcdir + '/ckan/ckan/config/who.ini',
            srcdir)
        shutil.copy(
            srcdir + '/ckan/ckan/config/solr/schema.xml',
            srcdir)
    finally:
        # fix srcdir permissions
        docker.web_command(
            command='/bin/chown -R --reference=/project /project',
            rw={srcdir: '/project'},
            )
417440
def _get_or_create_run(build):
    """"""
    release_name, release_number = _get_release_params()
    run_name = request.form.get('run_name', type=str)
    utils.jsonify_assert(run_name, 'run_name required')

    release = (
        models.Release.query
        .filter_by(build_id=build.id, name=release_name, number=release_number)
        .first())
    utils.jsonify_assert(release, 'release does not exist')

    run = (
        models.Run.query
        .filter_by(release_id=release.id, name=run_name)
        .first())
    if not run:
        # Ignore re-reports of the same run name for this release.
        logging.info('Created run: build_id=%r, release_name=%r, '
                     'release_number=%d, run_name=%r',
                     build.id, release.name, release.number, run_name)
        run = models.Run(
            release_id=release.id,
            name=run_name,
            status=models.Run.DATA_PENDING)
        db.session.add(run)
        db.session.flush()

    return release, run
501127
function () {
    log();
    log('source', fss.baseRelative(config.source));
    log('target', fss.baseRelative(config.target));
    if (!fss.directoryExists(fss.baseRelative(config.appdir))) {
        log('error', 'no source directory at', config.appdir);
        process.exit(1);
    }
}