submit change to remote repository

	Submits change to remote repository.
	Bails out if the local repository is not in sync with the remote one.
160899
def submit(ui, repo, *pats, **opts):
	
	if codereview_disabled:
		raise hg_util.Abort(codereview_disabled)

	# We already called this on startup but sometimes Mercurial forgets.
	set_mercurial_encoding_to_utf8()

	if not opts["no_incoming"] and hg_incoming(ui, repo):
		need_sync()

	cl, err = CommandLineCL(ui, repo, pats, opts, op="submit", defaultcc=defaultcc)
	if err != "":
		raise hg_util.Abort(err)

	user = None
	if cl.copied_from:
		user = cl.copied_from
	userline = CheckContributor(ui, repo, user)
	typecheck(userline, str)

	about = ""
	if cl.reviewer:
		about += "R=" + JoinComma([CutDomain(s) for s in cl.reviewer]) + "\n"
	if opts.get('tbr'):
		tbr = SplitCommaSpace(opts.get('tbr'))
		cl.reviewer = Add(cl.reviewer, tbr)
		about += "TBR=" + JoinComma([CutDomain(s) for s in tbr]) + "\n"
	if cl.cc:
		about += "CC=" + JoinComma([CutDomain(s) for s in cl.cc]) + "\n"

	if not cl.reviewer:
		raise hg_util.Abort("no reviewers listed in CL")

	if not cl.local:
		raise hg_util.Abort("cannot submit non-local CL")

	# upload, to sync current patch and also get change number if CL is new.
	if not cl.copied_from:
		cl.Upload(ui, repo, gofmt_just_warn=True)

	# check gofmt for real; allowed upload to warn in order to save CL.
	cl.Flush(ui, repo)
	CheckFormat(ui, repo, cl.files)

	about += "%s%s\n" % (server_url_base, cl.name)

	if cl.copied_from:
		about += "\nCommitter: " + CheckContributor(ui, repo, None) + "\n"
	typecheck(about, str)

	if not cl.mailed and not cl.copied_from:		# in case this is TBR
		cl.Mail(ui, repo)

	# submit changes locally
	message = cl.desc.rstrip() + "\n\n" + about
	typecheck(message, str)

	set_status("pushing " + cl.name + " to remote server")

	if hg_outgoing(ui, repo):
		raise hg_util.Abort("local repository corrupt or out-of-phase with remote: found outgoing changes")
	
	old_heads = len(hg_heads(ui, repo).split())

	global commit_okay
	commit_okay = True
	ret = hg_commit(ui, repo, *['path:'+f for f in cl.files], message=message, user=userline)
	commit_okay = False
	if ret:
		raise hg_util.Abort("nothing changed")
	node = repo["-1"].node()
	# push to remote; if it fails for any reason, roll back
	try:
		new_heads = len(hg_heads(ui, repo).split())
		if old_heads != new_heads and not (old_heads == 0 and new_heads == 1):
			# Created new head, so we weren't up to date.
			need_sync()

		# Push changes to remote.  If it works, we're committed.  If not, roll back.
		try:
			if hg_push(ui, repo):
				raise hg_util.Abort("push error")
		except hg_error.Abort, e:
			if e.message.find("push creates new heads") >= 0:
				# Remote repository had changes we missed.
				need_sync()
			raise
		except urllib2.HTTPError, e:
			print >>sys.stderr, "pushing to remote server failed; do you have commit permissions?"
			raise
	except:
		real_rollback()
		raise

	# We're committed. Upload final patch, close review, add commit message.
	changeURL = hg_node.short(node)
	url = ui.expandpath("default")
	m = re.match("(^https?://([^@/]+@)?([^.]+)\.googlecode\.com/hg/?)" + "|" +
		"(^https?://([^@/]+@)?code\.google\.com/p/([^/.]+)(\.[^./]+)?/?)", url)
	if m:
		if m.group(1): # prj.googlecode.com/hg/ case
			changeURL = "https://code.google.com/p/%s/source/detail?r=%s" % (m.group(3), changeURL)
		elif m.group(4) and m.group(7): # code.google.com/p/prj.subrepo/ case
			changeURL = "https://code.google.com/p/%s/source/detail?r=%s&repo=%s" % (m.group(6), changeURL, m.group(7)[1:])
		elif m.group(4): # code.google.com/p/prj/ case
			changeURL = "https://code.google.com/p/%s/source/detail?r=%s" % (m.group(6), changeURL)
		else:
			print >>sys.stderr, "URL: ", url
	else:
		print >>sys.stderr, "URL: ", url
	pmsg = "*** Submitted as " + changeURL + " ***\n\n" + message

	# When posting, move reviewers to CC line,
	# so that the issue stops showing up in their "My Issues" page.
	PostMessage(ui, cl.name, pmsg, reviewers="", cc=JoinComma(cl.reviewer+cl.cc))

	if not cl.copied_from:
		EditDesc(cl.name, closed=True, private=cl.private)
	cl.Delete(ui, repo)

	c = repo[None]
	if c.branch() == releaseBranch and not c.modified() and not c.added() and not c.removed():
		ui.write("switching from %s to default branch.\n" % releaseBranch)
		err = hg_clean(repo, "default")
		if err:
			return err
	return 0
596262
def _sync_repo(self, repo_url: str, revision: str or None = None) -> Path:
        '''
        '''

        repo_name = repo_url.split('/')[-1].rsplit('.', maxsplit=1)[0]
        repo_path = (self._cache_path / repo_name).resolve()

        self.logger.debug(f'Synchronizing with repo; URL: {repo_url}, revision: {revision}')

        try:
            self.logger.debug(f'Cloning repo {repo_url} to {repo_path}')

            run(
                f'git clone {repo_url} {repo_path}',
                shell=True,
                check=True,
                stdout=PIPE,
                stderr=STDOUT
            )

        except CalledProcessError as exception:
            if repo_path.exists():
                self.logger.debug('Repo already cloned; pulling from remote')

                try:
                    run(
                        'git pull',
                        cwd=repo_path,
                        shell=True,
                        check=True,
                        stdout=PIPE,
                        stderr=STDOUT
                    )

                except CalledProcessError as exception:
                    self.logger.warning(str(exception))

            else:
                self.logger.error(str(exception))

        if revision:
            run(
                f'git checkout {revision}',
                cwd=repo_path,
                shell=True,
                check=True,
                stdout=PIPE,
                stderr=STDOUT
            )

        return repo_path
622034
def publish(self):
        '''
        
        '''

        self.cleanup

        remote = self.remote
        branch = self.branch
        return self.m(
            'pushing changes to %s/%s' % (remote, branch),
            cmdd=dict(
                cmd='git push -u %s %s' % (remote, branch),
                cwd=self.local
            ),
            more=dict(remote=remote, branch=branch)
        )
1089270
def _pull(self):
        '''
        
        '''

        pull = self.m(
            'pulling remote changes',
            cmdd=dict(cmd='git pull --tags', cwd=self.local),
            critical=False
        )
        if 'CONFLICT' in pull.get('out'):
            self.m(
                'Congratulations! You have merge conflicts in the repository!',
                state=True,
                more=pull
            )
        return pull
557746
def commit(self, revision, is_amend=False):
        
        if not isinstance(revision, Revision):
            raise InvalidArgType()

        if not self.current_client:
            raise ClientNotSpecified()

        if is_amend:
            self.current_client.save(revision)
        else:
            self.current_client.write()
            self.current_client.save(revision)

        return self
60888
def sync(ctx, scm, to_branch, verbose, fake):
    
    scm.fake = fake
    scm.verbose = fake or verbose

    scm.repo_check(require_remote=True)

    if to_branch:
        # Optional branch specifier.
        branch = scm.fuzzy_match_branch(to_branch)
        if branch:
            is_external = True
            original_branch = scm.get_current_branch_name()
        else:
            raise click.BadArgumentUsage(
                "Branch {0} does not exist. Use an existing branch."
                .format(crayons.yellow(branch)))
    else:
        # Sync current branch.
        branch = scm.get_current_branch_name()
        is_external = False

    if branch in scm.get_branch_names(local=False):
        if is_external:
            ctx.invoke(switch, to_branch=branch, verbose=verbose, fake=fake)
        scm.stash_log(sync=True)
        status_log(scm.smart_pull, 'Pulling commits from the server.')
        status_log(scm.push, 'Pushing commits to the server.', branch)
        scm.unstash_log(sync=True)
        if is_external:
            ctx.invoke(switch, to_branch=original_branch, verbose=verbose, fake=fake)
    else:
        raise click.BadArgumentUsage(
            "Branch {0} is not published. Publish before syncing."
            .format(crayons.yellow(branch)))
141552
protected synchronized void submit() {
    try {
      if (theJobConf.getBoolean("create.empty.dir.if.nonexist", false)) {
        FileSystem fs = FileSystem.get(theJobConf);
        Path inputPaths[] = FileInputFormat.getInputPaths(theJobConf);
        for (int i = 0; i < inputPaths.length; i++) {
          if (!fs.exists(inputPaths[i])) {
            try {
              fs.mkdirs(inputPaths[i]);
            } catch (IOException e) {

            }
          }
        }
      }
      RunningJob running = jc.submitJob(theJobConf);
      this.mapredJobID = running.getID();
      this.state = Job.RUNNING;
    } catch (IOException ioe) {
      this.state = Job.FAILED;
      this.message = StringUtils.stringifyException(ioe);
    }
  }
145465
public function makeChangelog($repository) {
      $repoPrefix = 'remotes/upstream/';
      $parentRevision = 'master';
      $currentRevision = 'develop';

      $changelog = $this->taskChangelog();
      $command = 'git describe --abbrev=0 --tags';
      $lastTag = $this->_exec($command)->getMessage();
      if ($lastTag) {
         // if tags exist check against the last one
         $parentRevision = 'tags/' . trim($lastTag);
      } else if (!$this->_exec("git ls-remote upstream $parentRevision")->getMessage()) {
         // master branch does not exist, let's go against first parent as first time ever revision check
         $message = $this->_exec("git rev-list --max-parents=0 HEAD")->getMessage();
         $parentRevision = trim($message);
         $currentRevision = 'HEAD';
      }

      // default revision range
      $fromRev = $repoPrefix . $parentRevision;
      $toRev = $repoPrefix . $currentRevision;
      if ($currentRevision == 'HEAD') {
         // first time ever revision check fix, prefix can't be used.
         $fromRev = $parentRevision;
         $toRev = $currentRevision;
      }

      $this->stopOnFail(true);
      $command = 'git log --pretty=" * %s ([%h](https://github.com/' . $repository . '/commit/%h))"  ' . $fromRev . '..' . $toRev . ' --grep="^fix" --grep="^feat" --grep=="^perf"';
      $result = $this->_exec($command)->getMessage();
      if (empty($result)) {
         return Robo\Result::cancelled('No new commits for release an update');
      }
      if (preg_match('/(BREAKING CHANGE:)|(^ \* feat)/m', $result, $regs)) {
         switch ($regs[0]) {
            case 'BREAKING CHANGE:':
               $this->releaseType = 'major';
               break;
            case ' * feat':
               $this->releaseType = 'minor';
               break;
            // by default is patch
         }
      }
      $this->setVersionFromComposer('composer.json');
      $newVersion = $this->newVersion = $this->generateNextVersion($this->version);
      $result = ($result) ? $result : ' * Minor changes, for more details see our [commit history](https://github.com/' . $repository . '/compare/master...' . $newVersion . '/bugfixes)';
      $changelog->filename('CHANGELOG.md')
         ->version("[" . $newVersion . "](https://github.com/$repository/tree/" . $newVersion . ") (" . date('Y-m-d') . ")")
         ->setBody($result)
         ->run();
   }
519474
def submit
      submit!
    rescue Exception => e
      if e.respond_to?(:record)
        inherit_errors(e.record) unless e.record == self
        false
      else
        raise
      end
    end
469870
def update(self):
        
        # Fetch remotes, so we know we're dealing with latest remote
        yield from self.update_remotes()

        # Rename local untracked files that might be overwritten by pull
        yield from self.rename_local_untracked()

        # Reset local files that have been deleted. We don't actually expect users to
        # delete something that's present upstream and expect to keep it. This prevents
        # unnecessary conflicts, and also allows users to click the link again to get
        # a fresh copy of a file they might have screwed up.
        yield from self.reset_deleted_files()

        # If there are local changes, make a commit so we can do merges when pulling
        # We also allow empty commits. On NFS (at least), sometimes repo_is_dirty returns a false
        # positive, returning True even when there are no local changes (git diff-files seems to return
        # bogus output?). While ideally that would not happen, allowing empty commits keeps us
        # resilient to that issue.
        if self.repo_is_dirty():
            yield from self.ensure_lock()
            yield from execute_cmd(['git', 'commit', '-am', 'WIP', '--allow-empty'], cwd=self.repo_dir)

        # Merge master into local!
        yield from self.ensure_lock()
        yield from execute_cmd(['git', 'merge', '-Xours', 'origin/{}'.format(self.branch_name)], cwd=self.repo_dir)
381831
void undoLocalChanges() {

        workspaceProvider.synchronizedOperation(new Callable<Void>() {
            @Override
            public Void call() {
                try {
                    LOGGER.info("Undo local changes due to failure of git operations");
                    try {
                        git.rebase().setOperation(RebaseCommand.Operation.ABORT).call();
                    } catch (WrongRepositoryStateException e) {
                        // ignore rebasing exception when in wrong state
                    }
                    final String remoteBranch = Constants.R_REMOTES + Constants.DEFAULT_REMOTE_NAME + '/' + git.getRepository().getBranch();
                    git.reset().setMode(ResetType.HARD).setRef(remoteBranch).call();
                    git.clean().setCleanDirectories(true).call();
                    try {
                        final ObjectId head = git.getRepository().resolve(Constants.HEAD);
                        LOGGER.info("Undo local changes completed. HEAD is " + head.getName());
                    } catch (final Exception e) {
                        LOGGER.warn("Failed to fetch HEAD", e);
                    }
                } catch (final Exception e) {
                    LOGGER.error("Unable to undo changes", e);
                }
                return null;
            }
        });
    }
339376
def commit():
    

    session_token = request.headers['session_token']
    repository    = request.headers['repository']

    #===
    current_user = have_authenticated_user(request.environ['REMOTE_ADDR'], repository, session_token)
    if current_user is False: return fail(user_auth_fail_msg)

    #===
    repository_path = config['repositories'][repository]['path']

    def with_exclusive_lock():
        if not varify_user_lock(repository_path, session_token): return fail(lock_fail_msg)

        #===
        data_store = versioned_storage(repository_path)
        if not data_store.have_active_commit(): return fail(no_active_commit_msg)

        result = {}
        if request.headers['mode'] == 'commit':
            new_head = data_store.commit(request.headers['commit_message'], current_user['username'])
            result = {'head' : new_head}
        else:
            data_store.rollback()

        # Release the user lock
        update_user_lock(repository_path, None)
        return success(result)
    return lock_access(repository_path, with_exclusive_lock)
917976
def upload(ui, repo, name, **opts):
	
	if codereview_disabled:
		raise hg_util.Abort(codereview_disabled)

	repo.ui.quiet = True
	cl, err = LoadCL(ui, repo, name, web=True)
	if err != "":
		raise hg_util.Abort(err)
	if not cl.local:
		raise hg_util.Abort("cannot upload non-local change")
	cl.Upload(ui, repo)
	print "%s%s\n" % (server_url_base, cl.name)
	return 0
769611
void submit() {

        try {
            CmsProject project = m_context.getCms().readProject((CmsUUID)m_projectComboBox.getValue());
            if (!m_context.getCms().getRequestContext().getCurrentProject().equals(project)) {
                A_CmsUI.get().changeProject(project);
            } else {
                project = null;
            }
            String siteRoot = (String)m_siteComboBox.getValue();
            if (!m_context.getCms().getRequestContext().getSiteRoot().equals(siteRoot)) {
                A_CmsUI.get().changeSite(siteRoot);
            } else {
                siteRoot = null;
            }
            if ((siteRoot != null) && CmsFileExplorerConfiguration.APP_ID.equals(m_context.getAppId())) {
                I_CmsWorkplaceAppConfiguration editorConf = OpenCms.getWorkplaceAppManager().getAppConfiguration(
                    CmsPageEditorConfiguration.APP_ID);
                if (editorConf.getVisibility(m_context.getCms()).isActive()) {
                    ((I_CmsHasAppLaunchCommand)editorConf).getAppLaunchCommand().run();
                    return;
                }
            }
            m_context.finish(project, siteRoot);
        } catch (CmsException e) {
            m_context.error(e);
        }
    }
77189
@Override
	public void commit() throws RemoteException {
		tx.commit();
		try {
			tx = VanillaDb.txMgr().newTransaction(isolationLevel, readOnly);
		} catch (Exception e) {
			throw new RemoteException("error creating transaction ", e);
		}
	}
934343
protected void gitCommit(String message, Map<String, String> messageProperties)
            throws MojoFailureException, CommandLineException {
        message = replaceProperties(message, messageProperties);

        if (gpgSignCommit) {
            getLog().info("Committing changes. GPG-signed.");

            executeGitCommand("commit", "-a", "-S", "-m", message);
        } else {
            getLog().info("Committing changes.");

            executeGitCommand("commit", "-a", "-m", message);
        }
    }
1235596
def sync_local_to_remote(force="no"):
    

    _check_requirements()

    if force != "yes":
        message = "This will replace the remote database '%s' with your "\
            "local '%s', are you sure [y/n]" % (env.psql_db, env.local_psql_db)
        answer = prompt(message, "y")

        if answer != "y":
            logger.info("Sync stopped")
            return

    init_tasks()  # Bootstrap fabrik

    # Create database dump
    local_file = "sync_%s.sql.tar.gz" % int(time.time()*1000)
    local_path = "/tmp/%s" % local_file

    with context_managers.shell_env(PGPASSWORD=env.local_psql_password):
        elocal("pg_dump -h localhost -Fc -f %s -U %s %s -x -O" % (
            local_path, env.local_psql_user, env.local_psql_db
        ))

    remote_path = "/tmp/%s" % local_file

    # Upload sync file
    put(remote_path, local_path)

    # Import sync file by performing the following task (drop, create, import)
    with context_managers.shell_env(PGPASSWORD=env.psql_password):
        env.run("pg_restore --clean -h localhost -d %s -U %s '%s'" % (
            env.psql_db,
            env.psql_user,
            remote_path)
        )

    # Cleanup
    env.run("rm %s" % remote_path)
    elocal("rm %s" % local_path)

    # Trigger hook
    run_hook("postgres.after_sync_local_to_remote")

    logger.info("Sync complete")