Exemplo n.º 1
0
def setup_repo(url):
  try:
    myui=ui.ui(interactive=False)
  except TypeError:
    myui=ui.ui()
    myui.setconfig('ui', 'interactive', 'off')
  return myui,hg.repository(myui,url)
Exemplo n.º 2
0
def setup_repo(url):
    try:
        myui = ui.ui(interactive=False)
    except TypeError:
        myui = ui.ui()
        myui.setconfig("ui", "interactive", "off")
    return myui, hg.repository(myui, url)
Exemplo n.º 3
0
def _upgrade(ui, repo):
    ext_dir = os.path.dirname(os.path.abspath(__file__))
    ui.debug(_('kiln: checking for extensions upgrade for %s\n') % ext_dir)

    try:
        r = localrepo.localrepository(hgui.ui(), ext_dir)
    except RepoError:
        commands.init(hgui.ui(), dest=ext_dir)
        r = localrepo.localrepository(hgui.ui(), ext_dir)

    r.ui.setconfig('kiln', 'autoupdate', False)
    r.ui.pushbuffer()
    try:
        source = 'https://developers.kilnhg.com/Repo/Kiln/Group/Kiln-Extensions'
        if commands.incoming(r.ui, r, bundle=None, force=False, source=source) != 0:
            # no incoming changesets, or an error. Don't try to upgrade.
            ui.debug('kiln: no extensions upgrade available\n')
            return
        ui.write(_('updating Kiln Extensions at %s... ') % ext_dir)
        # pull and update return falsy values on success
        if commands.pull(r.ui, r, source=source) or commands.update(r.ui, r, clean=True):
            url = urljoin(repo.url()[:repo.url().lower().index('/repo')], 'Tools')
            ui.write(_('unable to update\nvisit %s to download the newest extensions\n') % url)
        else:
            ui.write(_('complete\n'))
    except Exception, e:
        ui.debug(_('kiln: error updating extensions: %s\n') % e)
        ui.debug(_('kiln: traceback: %s\n') % traceback.format_exc())
Exemplo n.º 4
0
    def pull(self, source=None, target=None):
        from mercurial import commands, hg, ui, error
        log.debug("Clone or update HG repository.")

        source = source or self.source
        target = target or self.target

        # Folders need to be manually created
        if not os.path.exists(target):
            os.makedirs(target)

        # Doesn't work with unicode type
        url = str(source)
        path = str(target)

        try:
            repo = hg.repository(ui.ui(), path)
            commands.pull(ui.ui(), repo, source=url)
            commands.update(ui.ui(), repo)
            log.debug("Mercurial: repository at " + url + " updated.")
        except error.RepoError, e:
            log.debug("Mercurial: " + str(e))
            try:
                commands.clone(ui.ui(), url, path)
                log.debug("Mercurial: repository at " + url + " cloned.")
            except Exception, e:
                log.debug("Mercurial: " + str(e))
                raise PullFromRepositoryException(unicode(e))
Exemplo n.º 5
0
def main(argv):
    # Find destination directory based on current file location
    destdir = os.path.abspath(os.path.join(
            os.path.dirname(__file__), '..', '..'))

    # Read the configuration file for the shared repository to get the pull path
    repo = hg.repository(
        ui.ui(), os.path.join(os.path.dirname(__file__), '..'))
    sharedpath = repo.ui.config('paths', 'default', None)
    if sharedpath is None:
        raise Exception('no default path in the shared directory!')

    unstable = sharedpath.endswith('-unstable')
    path = os.path.dirname(sharedpath)
    print 'using %s as remote repository path' % path

    for module in reduce(lambda x, y: x + y.split(','), argv, []):
        if module.endswith('-unstable'):
            module = module[:-len('-unstable')]

        if not os.path.exists(os.path.join(destdir, module)):
            # Attempt to clone the repository to the destination
            if module == "GUIRipper-Plugin-JFC" or module == "GUIRipper-Core" or module == "GUITARModel-Plugin-JFC" or module == "GUITARModel-Core" or module == "GUIReplayer-Plugin-JFC" or module == "GUIReplayer-Core":
				call("git clone git://github.com/cmsc435sikuli/" + module + ".git " + destdir + "/" +  module, shell=True)
            else:
                url = '%s/%s%s' % (path, module, '-unstable' if unstable else '')
                print 'checking out %s to %s' % (url, destdir)
                commands.clone(ui.ui(), url, os.path.join(destdir, module))
        else:
            # Repository already exists, skip
            print '%s already exists (skipping)' % module
Exemplo n.º 6
0
    def __init__(self, repoPath, local_site):
        from mercurial import hg, ui
        from mercurial.__version__ import version

        version = version.replace("+", ".")
        version_parts = [int(x) for x in version.split(".")]

        if version_parts[0] == 1 and version_parts[1] <= 2:
            hg_ui = ui.ui(interactive=False)
        else:
            hg_ui = ui.ui()
            hg_ui.setconfig('ui', 'interactive', 'off')

        # Check whether ssh is configured for mercurial. Assume that any
        # configured ssh is set up correctly for this repository.
        hg_ssh = hg_ui.config('ui', 'ssh')

        if not hg_ssh:
            logging.debug('Using rbssh for mercurial')
            hg_ui.setconfig('ui', 'ssh', 'rbssh --rb-local-site=%s'
                            % local_site)
        else:
            logging.debug('Found configured ssh for mercurial: %s' % hg_ssh)

        self.repo = hg.repository(hg_ui, path=repoPath)
Exemplo n.º 7
0
def repository(_ui=None, path='', bundle=None):
    '''Returns a subclassed Mercurial repository to which new
    THG-specific methods have been added. The repository object
    is obtained using mercurial.hg.repository()'''
    if bundle:
        if _ui is None:
            _ui = uimod.ui()
        repo = bundlerepo.bundlerepository(_ui, path, bundle)
        repo.__class__ = _extendrepo(repo)
        agent = RepoAgent(repo)
        return agent.rawRepo()
    if path not in _repocache:
        if _ui is None:
            _ui = uimod.ui()
        try:
            repo = hg.repository(_ui, path)
            # get unfiltered repo in version safe manner
            repo = getattr(repo, 'unfiltered', lambda: repo)()
            repo.__class__ = _extendrepo(repo)
            agent = RepoAgent(repo)
            _repocache[path] = agent.rawRepo()
            return agent.rawRepo()
        except EnvironmentError:
            raise error.RepoError('Cannot open repository at %s' % path)
    if not os.path.exists(os.path.join(path, '.hg/')):
        del _repocache[path]
        # this error must be in local encoding
        raise error.RepoError('%s is not a valid repository' % path)
    return _repocache[path]
Exemplo n.º 8
0
def hg_push_update(repo):
    u = ui.ui()
    repo = hg.repository(u, repo)
    repo.ui.pushbuffer()
    commands.update(ui.ui(), repo)
    hg_log.debug("updating repo: %s" % repo)
    hg_log.debug(repo.ui.popbuffer().split('\n')[0])
Exemplo n.º 9
0
def repository(_ui=None, path='', create=False, bundle=None):
    '''Returns a subclassed Mercurial repository to which new
    THG-specific methods have been added. The repository object
    is obtained using mercurial.hg.repository()'''
    if bundle:
        if _ui is None:
            _ui = uimod.ui()
        repo = bundlerepo.bundlerepository(_ui, path, bundle)
        repo.__class__ = _extendrepo(repo)
        repo._pyqtobj = ThgRepoWrapper(repo)
        return repo
    if create or path not in _repocache:
        if _ui is None:
            _ui = uimod.ui()
        try:
            repo = hg.repository(_ui, path, create)
            repo.__class__ = _extendrepo(repo)
            repo._pyqtobj = ThgRepoWrapper(repo)
            _repocache[path] = repo
            return repo
        except EnvironmentError:
            raise error.RepoError('Cannot open repository at %s' % path)
    if not os.path.exists(os.path.join(path, '.hg/')):
        del _repocache[path]
        # this error must be in local encoding
        raise error.RepoError('%s is not a valid repository' % path)
    return _repocache[path]
def get_latest_repo_rev( url ):
    """
        look up the latest mercurial tip revision
    """
    hexfunc = ui.ui().debugflag and hex or short
    repo = hg.repository( ui.ui(), url )
    tip = hexfunc( repo.lookup( 'tip' ) )
    return tip
Exemplo n.º 11
0
    def clone(self, destination=None):
        """ Clone the repository to the local disk. """

        if destination is not None:
            self.destination = destination

        hg.clone(ui.ui(), dict(), self.url, self.destination, True)
        self._repository = hg.repository(ui.ui(), self.destination)
Exemplo n.º 12
0
    def update(self, branch=None):
        """ Update the local repository for recent changes. """
        if branch is None:
            branch = self.branch

        print "*** Updating to branch '%s'" % branch
        commands.pull(ui.ui(), self._repository, self.url)
        commands.update(ui.ui(), self._repository, None, branch, True)
Exemplo n.º 13
0
def get_repo_for_repository(app, repository=None, repo_path=None):
    # Import from mercurial here to let Galaxy start under Python 3
    from mercurial import (
        hg,
        ui
    )
    if repository is not None:
        return hg.repository(ui.ui(), repository.repo_path(app))
    if repo_path is not None:
        return hg.repository(ui.ui(), repo_path)
Exemplo n.º 14
0
def update_repos(rev):

	try:
		print >> OUTPUT_FILE, 'accessing repository: %s' % PORTAL_HOME
		repos = hg.repository(ui.ui(), PORTAL_HOME)
		print >> OUTPUT_FILE, 'updating to revision: %s' % rev
		commands.update(ui.ui(), repos, rev=rev, check=True)
	except Exception, e:
		print >> ERROR_FILE, "Error: %s" % e
		print >> ERROR_FILE, "Aborting."
		sys.exit(1)
Exemplo n.º 15
0
    def hg_add(self, single=None):
        """Adds all files to Mercurial when the --watch options is passed
        This only happens one time. All consequent files are not auto added
        to the watch list."""
        repo = hg.repository(ui.ui(), self.path)
        if single is None:
            commands.add(ui.ui(), repo=repo)
            hg_log.debug('added files to repo %s' % self.path)

        else:
            commands.add(ui.ui(), repo, single) 
            hg_log.debug('added files to repo %s' % self.path)
Exemplo n.º 16
0
	def update(self):
		"""
		Pull updates from the upstream repository.

		If ``newest`` is set to False in the recipe or in the buildout
		configuration, no action is taken.
		"""
		if self.newest:
			self.logger.info("Pulling repository %s and updating %s" % (
				self.repository, self.directory
			))
			commands.pull(ui.ui(), hg.repository(ui.ui(), self.directory),
				self.repository, update=True)
Exemplo n.º 17
0
    def __init__(self, repoPath):
        from mercurial import hg, ui
        from mercurial.__version__ import version

        version_parts = [int(x) for x in version.split(".")]

        if version_parts[0] == 1 and version_parts[1] <= 2:
            hg_ui = ui.ui(interactive=False)
        else:
            hg_ui = ui.ui()
            hg_ui.setconfig('ui', 'interactive', 'off')

        self.repo = hg.repository(hg_ui, path=repoPath)
Exemplo n.º 18
0
    def __init__(self, repoPath, local_site):
        from mercurial import hg, ui, error

        # We've encountered problems getting the Mercurial version number.
        # Originally, we imported 'version' from mercurial.__version__,
        # which would sometimes return None.
        #
        # We are now trying to go through their version() function, if
        # available. That is likely the most reliable.
        try:
            from mercurial.util import version
            hg_version = version()
        except ImportError:
            # If version() wasn't available, we'll try to import __version__
            # ourselves, and then get 'version' from that.
            try:
                from mercurial import __version__
                hg_version = __version__.version
            except ImportError:
                # If that failed, we'll hard-code an empty string. This will
                # trigger the "<= 1.2" case below.
                hg_version = ''

        # If something gave us None, convert it to an empty string so
        # parse_version can accept it.
        if hg_version is None:
            hg_version = ''

        if parse_version(hg_version) <= parse_version("1.2"):
            hg_ui = ui.ui(interactive=False)
        else:
            hg_ui = ui.ui()
            hg_ui.setconfig('ui', 'interactive', 'off')

        # Check whether ssh is configured for mercurial. Assume that any
        # configured ssh is set up correctly for this repository.
        hg_ssh = hg_ui.config('ui', 'ssh')

        if not hg_ssh:
            logging.debug('Using rbssh for mercurial')
            hg_ui.setconfig('ui', 'ssh', 'rbssh --rb-local-site=%s'
                            % local_site)
        else:
            logging.debug('Found configured ssh for mercurial: %s' % hg_ssh)

        try:
            self.repo = hg.repository(hg_ui, path=repoPath)
        except error.RepoError, e:
            logging.error('Error connecting to Mercurial repository %s: %s'
                          % (repoPath, e))
            raise RepositoryNotFoundError
Exemplo n.º 19
0
    def clone(self, destination=None):
        """ Clone the repository to the local disk. """
        if destination is not None:
            self.destination = destination

        print "*** Cloning repository to '%s'" % self.destination

        # Bug 676793: Due to an API change in 1.9 the order of parameters has
        #             been changed.
        if __version__.version >= "1.9":
            hg.clone(ui.ui(), dict(), self.url, self.destination, True)
        else:
            hg.clone(ui.ui(), self.url, self.destination, True)
        self._repository = hg.repository(ui.ui(), self.destination)
 def checkout_hg(self):
     return 'hg', 'st'
     # pull new version of project from perository
     if not self.repo_path:
         # may be need to find repo recursively from this dir to up, but it's only may be.
         self.repo_path = os.path.abspath(os.path.join(os.path.dirname(__file__), '..', '..',))
     repo = hg.repository(
         ui.ui(),
         self.repo_path
     )
     url = dict(repo.ui.configitems('paths', 'default'))['default']
     commands.pull(ui.ui(), repo, url)
     # and update it
     commands.update(ui.ui(), repo)
     return
Exemplo n.º 21
0
    def __init__(self, repo, name=None, baseui=None):
        if isinstance(repo, str):
            if baseui:
                u = baseui.copy()
            else:
                u = ui.ui()
            self.repo = hg.repository(u, repo)
        else:
            self.repo = repo

        self.repo = self._getview(self.repo)
        self.repo.ui.setconfig("ui", "report_untrusted", "off")
        self.repo.baseui.setconfig("ui", "report_untrusted", "off")
        self.repo.ui.setconfig("ui", "nontty", "true")
        self.repo.baseui.setconfig("ui", "nontty", "true")
        hook.redirect(True)
        self.mtime = -1
        self.size = -1
        self.reponame = name
        self.archives = "zip", "gz", "bz2"
        self.stripecount = 1
        # a repo owner may set web.templates in .hg/hgrc to get any file
        # readable by the user running the CGI script
        self.templatepath = self.config("web", "templates")
        self.websubtable = self.loadwebsub()
Exemplo n.º 22
0
 def __init__(self, rev = 'tip', path = '/home/calixte/dev/mozilla/mozilla-central.hg'):
     self.root = path
     self.ui = ui.ui()
     self.rev = rev
     self.repo = hg.repository(self.ui, path)
     self.ctx = self.repo[self.rev]
     self.haspushlog = hasattr(self.repo, 'pushlog')
Exemplo n.º 23
0
Arquivo: hgshelve.py Projeto: dpla/zen
 def __init__(self, repopath):
     self.ui = ui.ui(quiet=True, interactive=False)
     self.repopath = os.path.abspath(repopath)
     self.repo = self.open_or_create_repo(self.repopath)
     if self.hg_book_re is None:
         self.hg_book_re = re.compile('^%s-(.+)-(.{40})$' % self.hg_book_prefix)
     self._keys = self.get_persisted_objects_keys()
Exemplo n.º 24
0
 def set_destination(self, value):
     """ Sets the location destination of the repository. """
     try:
         self._destination = value
         self._repository = hg.repository(ui.ui(), self._destination)
     except:
         self._repository = None
Exemplo n.º 25
0
 def __init__(self, repo, ufiles, minpct, copies):
     super(RenameSearchThread, self).__init__()
     self.repo = hg.repository(ui.ui(), repo.root)
     self.ufiles = ufiles
     self.minpct = minpct
     self.copies = copies
     self.stopped = False
Exemplo n.º 26
0
def _do_case(self, name, layout):
    subdir = test_util.subdir.get(name, '')
    self._load_fixture_and_fetch(name, subdir=subdir, stupid=False, layout=layout)
    assert len(self.repo) > 0, 'Repo had no changes, maybe you need to add a subdir entry in test_util?'
    wc2_path = self.wc_path + '_stupid'
    u = ui.ui()
    checkout_path = self.repo_path
    if subdir:
        checkout_path += '/' + subdir
    u.setconfig('hgsubversion', 'stupid', '1')
    u.setconfig('hgsubversion', 'layout', layout)
    hg.clone(u, test_util.fileurl(checkout_path), wc2_path, update=False)
    if layout == 'single':
        self.assertEqual(len(self.repo.heads()), 1)
    self.repo2 = hg.repository(ui.ui(), wc2_path)
    self.assertEqual(self.repo.heads(), self.repo2.heads())
Exemplo n.º 27
0
def main():
    rootdir = os.path.realpath(__file__ + '/../..')
    os.chdir(rootdir)

    if not os.path.isdir(NEWSDIR):
        sys.exit("Can't find news directory")

    repo = hg.repository(ui.ui(), '.')

    args = sys.argv[1:]
    if args:
        command = args.pop(0)
    else:
        command = 'preview'

    if command == 'generate':
        generate(repo)
    elif command == 'preview':
        out, htmlOut, _ = preview(repo)
        print 'Text Version:\n'
        for line in out:
            print line
        print 'Html Version:\n'
        for line in htmlOut:
            print line
    else:
        sys.exit("Usage: %s <preview|generate>" % sys.argv[0])
Exemplo n.º 28
0
def run(hgcmd='add', root='', cwd='', files=[], **opts):
    u = ui.ui()
    u.updateopts(debug=False, traceback=False)
    repo = hg.repository(u, path=root)

    cmdoptions = {
        'all':False, 'clean':False, 'ignored':False, 'modified':False,
        'added':True, 'removed':True, 'deleted':True, 'unknown':False, 'rev':[],
        'exclude':[], 'include':[], 'debug':True,'verbose':True
    }
    
    if hgcmd == 'add':
        cmdoptions['unknown'] = True        
    elif hgcmd == 'remove':
        cmdoptions['clean'] = True
    else:
        raise "Invalid command '%s'" % hgcmd
        
    dialog = GStatus(u, repo, cwd, files, cmdoptions, True)

    gtk.gdk.threads_init()
    gtk.gdk.threads_enter()
    dialog.display()
    gtk.main()
    gtk.gdk.threads_leave()
Exemplo n.º 29
0
Arquivo: hg.py Projeto: pombreda/bob
 def getTip(self):
     hg_ui = ui.ui()
     if hasattr(hg, 'peer'):
         repo = hg.peer(hg_ui, {}, self.uri)
     else:
         repo = hg.repository(hg_ui, self.uri)
     return short(repo.heads()[0])
def get_repo_changelog_tuples( repo_path ):
    repo = hg.repository( ui.ui(), repo_path )
    changelog_tuples = []
    for changeset in repo.changelog:
        ctx = repo.changectx( changeset )
        changelog_tuples.append( ( ctx.rev(), str( ctx ) ) )
    return changelog_tuples
Exemplo n.º 31
0
 def installable_revisions(self, app, sort_revisions=True):
     return metadata_util.get_metadata_revisions(
         self,
         hg.repository(ui.ui(), self.repo_path(app)),
         sort_revisions=sort_revisions)
Exemplo n.º 32
0
 def revision(self, app):
     repo = hg.repository(ui.ui(), self.repo_path(app))
     tip_ctx = repo.changectx(repo.changelog.tip())
     return "%s:%s" % (str(
         tip_ctx.rev()), str(repo.changectx(repo.changelog.tip())))
Exemplo n.º 33
0
 def tip(self, app):
     repo = hg.repository(ui.ui(), self.repo_path(app))
     return str(repo.changectx(repo.changelog.tip()))
Exemplo n.º 34
0
 def is_new(self, app):
     repo = hg.repository(ui.ui(), self.repo_path(app))
     tip_ctx = repo.changectx(repo.changelog.tip())
     return tip_ctx.rev() < 0
Exemplo n.º 35
0
    def appendSubrepos(self, repo=None):
        invalidRepoList = []

        # Mercurial repos are the only ones that can have subrepos
        if self.repotype() == 'hg':
            try:
                sri = None
                if repo is None:
                    if not os.path.exists(self._root):
                        self._valid = False
                        return [self._root]
                    elif not os.path.exists(os.path.join(self._root, '.hgsub')):
                        return []  # skip repo creation, which is expensive
                    repo = hg.repository(ui.ui(), self._root)
                wctx = repo['.']
                sortkey = lambda x: os.path.basename(util.normpath(repo.wjoin(x)))
                for subpath in sorted(wctx.substate, key=sortkey):
                    sri = None
                    abssubpath = repo.wjoin(subpath)
                    subtype = wctx.substate[subpath][2]
                    sriIsValid = os.path.isdir(abssubpath)
                    sri = SubrepoItem(abssubpath, subtype=subtype)
                    sri._valid = sriIsValid
                    self.appendChild(sri)

                    if not sriIsValid:
                        self._valid = False
                        sri._valid = False
                        invalidRepoList.append(repo.wjoin(subpath))
                        return invalidRepoList
                        continue

                    if subtype == 'hg':
                        # Only recurse into mercurial subrepos
                        sctx = wctx.sub(subpath)
                        invalidSubrepoList = sri.appendSubrepos(sctx._repo)
                        if invalidSubrepoList:
                            self._valid = False
                            invalidRepoList += invalidSubrepoList

            except (EnvironmentError, error.RepoError, util.Abort), e:
                # Add the repo to the list of repos/subrepos
                # that could not be open
                self._valid = False
                if sri:
                    sri._valid = False
                    invalidRepoList.append(abssubpath)
                invalidRepoList.append(self._root)
            except Exception, e:
                # If any other sort of exception happens, show the corresponding
                # error message, but do not crash!
                # Note that we _also_ will mark the offending repos as invalid
                # It is unfortunate that Python 2.4, which we target does not
                # support combined try/except/finally clauses, forcing us
                # to duplicate some code here
                self._valid = False
                if sri:
                    sri._valid = False
                    invalidRepoList.append(abssubpath)
                invalidRepoList.append(self._root)

                # Show a warning message indicating that there was an error
                if repo:
                    rootpath = repo.root
                else:
                    rootpath = self._root
                warningMessage = (_('An exception happened while loading the ' \
                    'subrepos of:<br><br>"%s"<br><br>') + \
                    _('The exception error message was:<br><br>%s<br><br>') +\
                    _('Click OK to continue or Abort to exit.')) \
                    % (rootpath, e.message)
                res = qtlib.WarningMsgBox(_('Error loading subrepos'),
                                    warningMessage,
                                    buttons = QMessageBox.Ok | QMessageBox.Abort)
                # Let the user abort so that he gets the full exception info
                if res == QMessageBox.Abort:
                    raise
Exemplo n.º 36
0
 def __init__(self, repository_url):
     self.ui = ui.ui()
     self.repository = hg.repository(self.ui, repository_url)
Exemplo n.º 37
0
 def __init__(self, directory, create_watcher):
     self.directory = os.path.abspath(directory)
     self.ui = ui.ui()
     self.create_watcher = create_watcher
Exemplo n.º 38
0
if __name__ == "__main__":
    from mercurial import ui, hg
    repo = hg.repository(ui.ui(), "klayge-slimmed-hg")
    rev_map = []
    total_revs = len(repo)
    for i in range(total_revs - 1, 0, -1):
        print("Revision %d/%d" % (i, total_revs - 1))
        change_ctx = repo[i]
        rev_map.append([
            i,
            change_ctx.extra().get("convert_revision", "")[0:12], "",
            int(change_ctx.date()[0]),
            change_ctx.description()
        ])

    git_revs = []
    git_id_file = open("GitID.txt", "r")
    for line in git_id_file:
        git_revs.append((line[0:40], int(line[41:51]), line[52:len(line) - 1]))
    git_id_file.close()

    rev_map_file = open("SlimRevMap.txt", "w")
    for rev in rev_map:
        rev[4] = rev[4].replace("\n", " ")
        match_git_revs = []
        for git_rev in git_revs:
            if ((0 == rev[4].find(git_rev[2])) and (git_rev[1] == rev[3])):
                match_git_revs.append(git_rev)
        if 1 == len(match_git_revs):
            rev[2] = match_git_revs[0][0]
        else:
Exemplo n.º 39
0
                    s = "%-*s  %s" % (opts_len, optstr, desc)
                else:
                    s = optstr
                ui.write("%s\n" % s)
                if optstr.endswith("[+]>"):
                    multioccur = True
            if multioccur:
                ui.write(
                    _("\n[+] marked option can be specified"
                      " multiple times\n"))
            ui.write("\n")
        # aliases
        if d['aliases']:
            ui.write(_("    aliases: %s\n\n") % " ".join(d['aliases']))


def allextensionnames():
    return extensions.enabled().keys() + extensions.disabled().keys()


if __name__ == "__main__":
    doc = 'hg.1.gendoc'
    if len(sys.argv) > 1:
        doc = sys.argv[1]

    ui = uimod.ui()
    if doc == 'hg.1.gendoc':
        showdoc(ui)
    else:
        showtopic(ui, sys.argv[1])
Exemplo n.º 40
0
                      metavar="OUTPUT_PATH",
                      help="Path to build into (default 'dist')")
    parser.add_option("-b",
                      "--backup",
                      dest="backup",
                      metavar="BACKUP_PATH",
                      help="Path to preserve old version to")
    parser.add_option("-i",
                      "--ignore",
                      action="append",
                      dest="ignore",
                      metavar="IGNORE_PATH",
                      help="Ignore files in this path")
    parser.add_option("-c",
                      "--cache",
                      action="store_true",
                      dest="cache",
                      default=False,
                      help="use cached test suite and specification data only")
    (options, args) = parser.parse_args()

    ui = ui.ui()
    ui.setconfig('ui', 'debug', str(options.debug))
    ui.setconfig('ui', 'quiet', str(options.quiet))
    ui.setconfig('ui', 'verbose', str(options.verbose))

    builder = Builder(ui, options.output, options.backup, options.ignore,
                      options.cache)
    result = builder.build(args)
    quit(result)
Exemplo n.º 41
0
def _hgrepofound(p):
    ui = ui_.ui()
    repo = hg.repository(ui, p)
    return MercurialGuessRenames(ui, repo)
Exemplo n.º 42
0
def setup_ui():
    u = ui.ui()
    u.setconfig('ui', 'report_untrusted', 'off')
    u.setconfig('ui', 'interactive', 'off')
    return u
Exemplo n.º 43
0
    def __init__(self, args=None, opts={}, parent=None):
        super(CloneDialog, self).__init__(parent)
        f = self.windowFlags()
        self.setWindowFlags(f & ~Qt.WindowContextHelpButtonHint)
        self.ui = ui.ui()
        self.ret = None

        dest = src = cwd = os.getcwd()
        if args:
            if len(args) > 1:
                src = args[0]
                dest = args[1]
            else:
                src = args[0]
        udest = hglib.tounicode(dest)
        usrc = hglib.tounicode(src)
        ucwd = hglib.tounicode(cwd)

        self.prev_dest = None

        # base layout box
        box = QVBoxLayout()
        box.setSpacing(6)

        ## main layout grid
        grid = QGridLayout()
        grid.setSpacing(6)
        box.addLayout(grid)

        ### source combo and button
        self.src_combo = QComboBox()
        self.src_combo.setEditable(True)
        self.src_combo.setMinimumWidth(310)
        self.src_btn = QPushButton(_('Browse...'))
        self.src_btn.setAutoDefault(False)
        self.src_btn.clicked.connect(self.browse_src)
        grid.addWidget(QLabel(_('Source:')), 0, 0)
        grid.addWidget(self.src_combo, 0, 1)
        grid.addWidget(self.src_btn, 0, 2)

        ### destination combo and button
        self.dest_combo = QComboBox()
        self.dest_combo.setEditable(True)
        self.dest_combo.setMinimumWidth(310)
        self.dest_btn = QPushButton(_('Browse...'))
        self.dest_btn.setAutoDefault(False)
        self.dest_btn.clicked.connect(self.browse_dest)
        grid.addWidget(QLabel(_('Destination:')), 1, 0)
        grid.addWidget(self.dest_combo, 1, 1)
        grid.addWidget(self.dest_btn, 1, 2)

        for combo in (self.src_combo, self.dest_combo):
            qtlib.allowCaseChangingInput(combo)

        s = QSettings()
        self.shist = s.value('clone/source').toStringList()
        for path in self.shist:
            if path: self.src_combo.addItem(path)
        self.src_combo.setCurrentIndex(-1)
        self.src_combo.setEditText(usrc)

        self.dhist = s.value('clone/dest').toStringList()
        for path in self.dhist:
            if path: self.dest_combo.addItem(path)
        self.dest_combo.setCurrentIndex(-1)
        self.dest_combo.setEditText(udest)

        ### options
        expander = qtlib.ExpanderLabel(_('Options'), False)
        expander.expanded.connect(self.show_options)
        grid.addWidget(expander, 2, 0, Qt.AlignLeft | Qt.AlignTop)

        optbox = QVBoxLayout()
        optbox.setSpacing(6)
        grid.addLayout(optbox, 2, 1, 1, 2)

        def chktext(chklabel, btnlabel=None, btnslot=None, stretch=None):
            hbox = QHBoxLayout()
            hbox.setSpacing(0)
            optbox.addLayout(hbox)
            chk = QCheckBox(chklabel)
            text = QLineEdit(enabled=False)
            hbox.addWidget(chk)
            hbox.addWidget(text)
            if stretch is not None:
                hbox.addStretch(stretch)
            if btnlabel:
                btn = QPushButton(btnlabel)
                btn.setEnabled(False)
                btn.setAutoDefault(False)
                btn.clicked.connect(btnslot)
                hbox.addSpacing(6)
                hbox.addWidget(btn)
                chk.toggled.connect(
                    lambda e: self.toggle_enabled(e, text, target2=btn))
                return chk, text, btn
            else:
                chk.toggled.connect(lambda e: self.toggle_enabled(e, text))
                return chk, text

        self.rev_chk, self.rev_text = chktext(_('Clone to revision:'),
                                              stretch=40)

        self.noupdate_chk = QCheckBox(
            _('Do not update the new working directory'))
        self.pproto_chk = QCheckBox(_('Use pull protocol to copy metadata'))
        self.uncomp_chk = QCheckBox(_('Use uncompressed transfer'))
        optbox.addWidget(self.noupdate_chk)
        optbox.addWidget(self.pproto_chk)
        optbox.addWidget(self.uncomp_chk)

        self.qclone_chk, self.qclone_txt, self.qclone_btn = \
                chktext(_('Include patch queue'), btnlabel=_('Browse...'),
                        btnslot=self.onBrowseQclone)

        self.proxy_chk = QCheckBox(_('Use proxy server'))
        optbox.addWidget(self.proxy_chk)
        useproxy = bool(self.ui.config('http_proxy', 'host'))
        self.proxy_chk.setEnabled(useproxy)
        self.proxy_chk.setChecked(useproxy)

        self.insecure_chk = QCheckBox(_('Do not verify host certificate'))
        optbox.addWidget(self.insecure_chk)
        self.insecure_chk.setEnabled(False)

        self.remote_chk, self.remote_text = chktext(_('Remote command:'))

        # allow to specify start revision for p4 & svn repos.
        self.startrev_chk, self.startrev_text = chktext(_('Start revision:'),
                                                        stretch=40)

        self.hgcmd_lbl = QLabel(_('Hg command:'))
        self.hgcmd_lbl.setAlignment(Qt.AlignRight)
        self.hgcmd_txt = QLineEdit()
        self.hgcmd_txt.setReadOnly(True)
        grid.addWidget(self.hgcmd_lbl, 3, 0)
        grid.addWidget(self.hgcmd_txt, 3, 1)
        self.hgcmd_txt.setMinimumWidth(400)

        ## command widget
        self.cmd = cmdui.Widget(True, True, self)
        self.cmd.commandStarted.connect(self.command_started)
        self.cmd.commandFinished.connect(self.command_finished)
        self.cmd.commandFinished.connect(self.cmdfinished)
        self.cmd.commandCanceling.connect(self.command_canceling)
        box.addWidget(self.cmd)

        ## bottom buttons
        buttons = QDialogButtonBox()
        self.cancel_btn = buttons.addButton(QDialogButtonBox.Cancel)
        self.cancel_btn.clicked.connect(self.cmd.cancel)
        self.close_btn = buttons.addButton(QDialogButtonBox.Close)
        self.close_btn.clicked.connect(self.onCloseClicked)
        self.close_btn.setAutoDefault(False)
        self.clone_btn = buttons.addButton(_('&Clone'),
                                           QDialogButtonBox.ActionRole)
        self.clone_btn.clicked.connect(self.clone)
        self.detail_btn = buttons.addButton(_('Detail'),
                                            QDialogButtonBox.ResetRole)
        self.detail_btn.setAutoDefault(False)
        self.detail_btn.setCheckable(True)
        self.detail_btn.toggled.connect(self.detail_toggled)
        box.addWidget(buttons)

        # dialog setting
        self.setLayout(box)
        self.layout().setSizeConstraint(QLayout.SetFixedSize)
        self.setWindowTitle(_('Clone - %s') % ucwd)
        self.setWindowIcon(qtlib.geticon('hg-clone'))

        # connect extra signals
        self.src_combo.editTextChanged.connect(self.composeCommand)
        self.src_combo.editTextChanged.connect(self.onUrlHttps)
        self.src_combo.editTextChanged.connect(self.onResetDefault)
        self.src_combo.currentIndexChanged.connect(self.onResetDefault)
        self.dest_combo.editTextChanged.connect(self.composeCommand)
        self.rev_chk.toggled.connect(self.composeCommand)
        self.rev_text.textChanged.connect(self.composeCommand)
        self.noupdate_chk.toggled.connect(self.composeCommand)
        self.pproto_chk.toggled.connect(self.composeCommand)
        self.uncomp_chk.toggled.connect(self.composeCommand)
        self.qclone_chk.toggled.connect(self.composeCommand)
        self.qclone_txt.textChanged.connect(self.composeCommand)
        self.proxy_chk.toggled.connect(self.composeCommand)
        self.insecure_chk.toggled.connect(self.composeCommand)
        self.remote_chk.toggled.connect(self.composeCommand)
        self.remote_text.textChanged.connect(self.composeCommand)
        self.startrev_chk.toggled.connect(self.composeCommand)

        # prepare to show
        self.cmd.setHidden(True)
        self.cancel_btn.setHidden(True)
        self.detail_btn.setHidden(True)
        self.show_options(False)

        rev = opts.get('rev')
        if rev:
            self.rev_chk.setChecked(True)
            self.rev_text.setText(hglib.tounicode(rev))
        self.noupdate_chk.setChecked(bool(opts.get('noupdate')))
        self.pproto_chk.setChecked(bool(opts.get('pull')))
        self.uncomp_chk.setChecked(bool(opts.get('uncompressed')))

        self.src_combo.setFocus()
        self.src_combo.lineEdit().selectAll()

        self.composeCommand()
Exemplo n.º 44
0
                    help='Do not check repository state')
parser.add_argument(
    '--num_files_per_load',
    type=int,
    default=-1,
    help='Number of files loaded to gpu each time (-1 for all)')
parser.add_argument('dbn_def_file', help='Path to nn definition file')
parser.add_argument('param_def_file', help='Path to run params file')
parser.add_argument('db_name', help='Name of training database')
parser.add_argument('dev_db_name', help='Name of validation database')
parser.add_argument('db_path', help='Path to database')
parser.add_argument('output_fldr', type=str, help='output folder')

arguments = parser.parse_args()
if not arguments.skip_repo:
    rep = localrepo.instance(ui.ui(), '.', False)
    if sum([len(x) for x in rep.status()]) != 0:
        print "Please commit changes to repository before running program"
        sys.exit(1)

if not os.path.exists(arguments.output_fldr):
    os.makedirs(arguments.output_fldr)
logPath = os.path.join(arguments.output_fldr, "log.txt")
if os.path.exists(logPath): os.remove(logPath)
rep = localrepo.instance(ui.ui(), '.', False)
revision_num = rep.changelog.headrevs()[0]

# create logger
logging.basicConfig(
    filename=logPath,
    level=logging.INFO,
Exemplo n.º 45
0
 def __init__(self, repo_path):
     self._repo_path = repo_path.encode('utf-8')
     self._ui = ui.ui()
     self._repo = hg.repository(self._ui, self._repo_path)
     self._ctx = self._repo[self.revision_id]
     self.revno = self._ctx.rev()
Exemplo n.º 46
0
 def __init__(self, dir=None):
     self.dir = dir
     self.repo = hg.repository(ui.ui(), dir)
Exemplo n.º 47
0
 def globalLatestRevison(self):
     repo = hg.repository(ui.ui(), self.BASEDIR)
     cctx = repo['tip']
     return cctx.rev()
Exemplo n.º 48
0
yt scripts can be a bit intimidating, and at times a bit obtuse.  But there's a
lot you can do, and this section of the manual will assist with figuring out
how to do some fairly common tasks -- which can lead to combining these, with
other Python code, into more complicated and advanced tasks.

.. note::
   All of these scripts are located in the mercurial repository at
   http://hg.yt-project.org/cookbook/

"""
footer = """ """

import cStringIO, sys, glob, os
from mercurial import hg, ui, commands
uii = ui.ui()

if "--index" in sys.argv:
    recipes = open("source/cookbook/recipes.rst", "w")
else:
    recipes = cStringIO.StringIO()
recipes.write(header)

url = "here: http://hg.yt-project.org/cookbook/raw/tip/%s ."


def cond_output(f, v):
    if not v:
        f.write(".. rubric:: Sample Output\n\n")
    return True
Exemplo n.º 49
0
def setup_repo(url):
    myui = ui.ui()
    return myui, hg.repository(myui, url)
Exemplo n.º 50
0
def get_repos(sa_session, file_path, hgweb_config_dir, **kwargs):
    """
    Load repos from DB and included tools from .xml configs.
    """
    hgwcm = HgWebConfigManager()
    hgwcm.hgweb_config_dir = hgweb_config_dir
    # Do not index deleted, deprecated, or "tool_dependency_definition" type repositories.
    q = sa_session.query(model.Repository).filter_by(deleted=False).filter_by(
        deprecated=False).order_by(model.Repository.update_time.desc())
    q = q.filter(model.Repository.type != 'tool_dependency_definition')
    for repo in q:
        category_names = []
        for rca in sa_session.query(
                model.RepositoryCategoryAssociation
        ).filter(model.RepositoryCategoryAssociation.repository_id == repo.id):
            for category in sa_session.query(model.Category).filter(
                    model.Category.id == rca.category.id):
                category_names.append(category.name.lower())
        categories = (",").join(category_names)
        repo_id = repo.id
        name = repo.name
        description = repo.description
        long_description = repo.long_description
        homepage_url = repo.homepage_url
        remote_repository_url = repo.remote_repository_url

        times_downloaded = repo.times_downloaded or 0

        repo_owner_username = ''
        if repo.user_id is not None:
            user = sa_session.query(
                model.User).filter(model.User.id == repo.user_id).one()
            repo_owner_username = user.username.lower()

        approved = 'no'
        for review in repo.reviews:
            if review.approved == 'yes':
                approved = 'yes'
                break

        last_updated = pretty_print_time_interval(repo.update_time)
        full_last_updated = repo.update_time.strftime("%Y-%m-%d %I:%M %p")

        # Load all changesets of the repo for lineage.
        repo_path = os.path.join(
            hgweb_config_dir,
            hgwcm.get_entry(
                os.path.join("repos", repo.user.username, repo.name)))
        hg_repo = hg.repository(ui.ui(), repo_path.encode('utf-8'))
        lineage = []
        for changeset in hg_repo.changelog:
            lineage.append(
                unicodify(changeset) + ":" + unicodify(hg_repo[changeset]))
        repo_lineage = str(lineage)

        #  Parse all the tools within repo for a separate index.
        tools_list = []
        path = os.path.join(file_path, *directory_hash_id(repo.id))
        path = os.path.join(path, "repo_%d" % repo.id)
        if os.path.exists(path):
            tools_list.extend(load_one_dir(path))
            for root, dirs, files in os.walk(path):
                if '.hg' in dirs:
                    dirs.remove('.hg')
                for dirname in dirs:
                    tools_in_dir = load_one_dir(os.path.join(root, dirname))
                    tools_list.extend(tools_in_dir)

        yield (dict(id=unicodify(repo_id),
                    name=unicodify(name),
                    description=unicodify(description),
                    long_description=unicodify(long_description),
                    homepage_url=unicodify(homepage_url),
                    remote_repository_url=unicodify(remote_repository_url),
                    repo_owner_username=unicodify(repo_owner_username),
                    times_downloaded=unicodify(times_downloaded),
                    approved=unicodify(approved),
                    last_updated=unicodify(last_updated),
                    full_last_updated=unicodify(full_last_updated),
                    tools_list=tools_list,
                    repo_lineage=unicodify(repo_lineage),
                    categories=unicodify(categories)))
Exemplo n.º 51
0
def _get_release():
    """ Get the release of the package.

    :return:
        A tuple of the full release name, the version number, the hexadecimal
        version number and a list of changelog entries (all as strings).
    """

    # The root directory should contain dot files that tell us what sort of
    # package we are.

    release_suffix = ''

    if os.path.exists(os.path.join(_RootDir, '.hg')):
        # Handle a Mercurial repository.

        from mercurial import hg, ui

        # Get the repository.
        repo = hg.repository(ui.ui(), _RootDir)

        # The last changeset is the "parent" of the working directory.
        ctx = repo[None].parents()[0]

        # If the one before the last changeset has a release tag then the last
        # changeset refers to the tagging and not a genuine change.
        before = ctx.parents()[0]

        version = _release_tag(before)

        if version is not None:
            ctx = before
        else:
            release_suffix = '-snapshot-' + str(ctx)

        changelog = [_format_changelog(ctx)]

        # Go back through the line of the first parent to find the last
        # release.
        parent_version = None

        parents = ctx.parents()
        while len(parents) != 0:
            parent_ctx = parents[0]

            changelog.append(_format_changelog(parent_ctx))

            parent_version = _release_tag(parent_ctx)
            if parent_version is not None:
                break

            parents = parent_ctx.parents()

        if version is None and parent_version is not None:
            # This is a snapshot so work out what the next version will be
            # based on the previous version.
            major, minor, micro = parent_version

            if ctx.branch() == 'default':
                minor += 1

                # This should be 0 anyway.
                micro = 0
            else:
                micro += 1

            version = (major, minor, micro)
    else:
        # Handle a Mercurial archive.

        changelog = None
        name = os.path.basename(_RootDir)

        release_suffix = "-unknown"
        version = None

        parts = name.split('-')
        if len(parts) > 1:
            name = parts[-1]

            if len(name) == 12:
                # This is the best we can do without access to the repository.
                release_suffix = '-' + name

    # Format the results.
    if version is None:
        version = (0, 1, 0)

    major, minor, micro = version

    if micro == 0:
        version = '%d.%d' % (major, minor)
    else:
        version = '%d.%d.%d' % (major, minor, micro)

    release = '%s%s' % (version, release_suffix)
    hex_version = '%02x%02x%02x' % (major, minor, micro)

    return release, version, hex_version, changelog
Exemplo n.º 52
0
def build_changelog(docs_path, package_name="mezzanine"):
    """
    Converts Mercurial commits into a changelog in RST format.
    """

    project_path = os.path.join(docs_path, "..")
    version_file = os.path.join(package_name, "__init__.py")
    version_var = "__version__"
    changelog_filename = "CHANGELOG"
    changelog_file = os.path.join(project_path, changelog_filename)
    versions = SortedDict()
    repo = None
    ignore = ("AUTHORS", "formatting", "typo", "pep8", "whitespace",
              "README", "trans", "print debug", "debugging", "tabs",
              "style", "sites", "ignore", "tweak", "cleanup", "minor")
    hotfixes = {
        "40cbc47b8d8a": "1.0.9",
        "a25749986abc": "1.0.10",
    }

    # Load the repo.
    try:
        from mercurial import ui, hg, error
    except ImportError:
        pass
    else:
        try:
            repo = hg.repository(ui.ui(), project_path)
        except error.RepoError:
            return
    if repo is None:
        return

    # Go through each changeset and assign it to the versions dict.
    changesets = [repo.changectx(changeset) for changeset in repo.changelog]
    for cs in sorted(changesets, reverse=True, key=_changeset_date):
        # Check if the file with the version number is in this changeset
        # and if it is, pull it out and assign it as a variable.
        files = cs.files()
        new_version = False
        # Commit message cleanup hacks.
        description = cs.description().rstrip(".").replace("\n", ". ")
        while "  " in description:
            description = description.replace("  ", " ")
        description = description.replace(". . ", ". ").replace("...", ",")
        while ".." in description:
            description = description.replace("..", ".")
        description = description.replace(":.", ":").replace("n'. t", "n't")
        words = description.split()
        # Format var names in commit.
        for i, word in enumerate(words):
            if (set("._") & set(word[:-1]) and set(letters) & set(word)
                and "`" not in word and not word[0].isdigit()):
                last = ""
                if word[-1] in ",.":
                    last, word = word[-1], word[:-1]
                words[i] = "``%s``%s" % (word, last)
        description = " ".join(words)
        if version_file in files:
            for line in cs[version_file].data().split("\n"):
                if line.startswith(version_var):
                    exec line
                    if locals()[version_var] == "0.1.0":
                        locals()[version_var] = "1.0.0"
                        break
                    versions[locals()[version_var]] = {
                        "changes": [],
                        "date": _changeset_date(cs).strftime("%b %d, %Y")
                    }
                    new_version = len(files) == 1
        # Ignore changesets that are merges, bumped the version, closed
        # a branch, regenerated the changelog itself, contain an ignore
        # word, or are one word long.
        merge = len(cs.parents()) > 1
        branch_closed = len(files) == 0
        changelog_update = changelog_filename in files
        ignored = [w for w in ignore if w.lower() in description.lower()]
        one_word = len(description.split()) == 1
        if (merge or new_version or branch_closed or changelog_update or
            ignored or one_word):
            continue
        # Ensure we have a current version and if so, add this changeset's
        # description to it.
        hotfix = hotfixes.get(cs.hex()[:12])
        version = None
        try:
            version = locals()[version_var]
        except KeyError:
            if not hotfix:
                continue
        user = cs.user().split("<")[0].strip()
        entry = "%s - %s" % (description, user)
        if hotfix or entry not in versions[version]["changes"]:
            if hotfix:
                versions[hotfix] = {
                    "changes": [entry],
                    "date": _changeset_date(cs).strftime("%b %d, %Y"),
                }
            else:
                versions[version]["changes"].insert(0, entry)

    # Write out the changelog.
    with open(changelog_file, "w") as f:
        for version, version_info in versions.items():
            header = "Version %s (%s)" % (version, version_info["date"])
            f.write("%s\n" % header)
            f.write("%s\n" % ("-" * len(header)))
            f.write("\n")
            if version_info["changes"]:
                for change in version_info["changes"]:
                    f.write("  * %s\n" % change)
            else:
                f.write("  * No changes listed.\n")
            f.write("\n")
Exemplo n.º 53
0
 def get_build_number(self, repo_path):
     repo = hg.repository(ui.ui(), repo_path)
     return len(repo.changelog)
Exemplo n.º 54
0
 def allow_push(self, app):
     repo = hg.repository(ui.ui(), self.repo_path(app))
     return repo.ui.config('web', 'allow_push')
Exemplo n.º 55
0
    wspath = None
    outputfile = None

    for opt, arg in opts:
        if opt == '-w':
            wspath = arg
        elif opt == '-o':
            outputfile = arg
        elif opt == '-p':
            parentpath = arg

    if not wspath:
        usage()

    try:
        repository = hg.repository(ui.ui(), wspath)
    except error.RepoError, e:
        sys.stderr.write("failed to open repository: %s\n" % e)
        sys.exit(1)

    ws = WorkSpace(repository)
    act = ws.active(parentpath)

    node = act.parenttip.node()
    parenttip = binascii.hexlify(node)

    fh = None
    if outputfile:
        try:
            fh = open(outputfile, 'w')
        except EnvironmentError, e:
Exemplo n.º 56
0
def build_changelog(docs_path, package_name="mezzanine"):
    """
    Converts Mercurial commits into a changelog in RST format.
    """

    project_path = os.path.join(docs_path, "..")
    version_file = os.path.join(package_name, "__init__.py")
    version_var = "__version__"
    changelog_filename = "CHANGELOG"
    changelog_file = os.path.join(project_path, changelog_filename)
    versions = SortedDict()
    repo = None

    # Load the repo.
    try:
        from mercurial import ui, hg, error
    except ImportError:
        pass
    else:
        try:
            repo = hg.repository(ui.ui(), project_path)
        except error.RepoError:
            return
    if repo is None:
        return

    # Go through each changeset and assign it to the versions dict.
    changesets = [repo.changectx(changeset) for changeset in repo.changelog]
    for changeset in sorted(changesets, reverse=True, key=_changeset_date):
        # Check if the file with the version number is in this changeset
        # and if it is, pull it out and assign it as a variable.
        files = changeset.files()
        new_version = False
        if version_file in files:
            for line in changeset[version_file].data().split("\n"):
                if line.startswith(version_var):
                    exec line
                    if locals()[version_var] == "0.1.0":
                        locals()[version_var] = "1.0.0"
                        break
                    date = _changeset_date(changeset)
                    versions[locals()[version_var]] = {
                        "changes": [], "date": date.strftime("%b %d, %Y")}
                    new_version = len(files) == 1
        # Ignore changesets that are merges, bumped the version, closed
        # a branch or regenerated the changelog itself.
        merge = len(changeset.parents()) > 1
        branch_closed = len(files) == 0
        changelog_update = changelog_filename in files
        if merge or new_version or branch_closed or changelog_update:
            continue
        # Ensure we have a current version and if so, add this changeset's
        # description to it.
        try:
            version = locals()[version_var]
        except KeyError:
            continue
        else:
            description = changeset.description().rstrip(".").replace("\n", "")
            user = changeset.user().split("<")[0].strip()
            entry = "%s - %s" % (description, user)
            if entry not in versions[version]["changes"]:
                versions[version]["changes"].insert(0, entry)

    # Write out the changelog.
    with open(changelog_file, "w") as f:
        for version, version_info in versions.items():
            header = "Version %s (%s)" % (version, version_info["date"])
            f.write("%s\n" % header)
            f.write("%s\n" % ("-" * len(header)))
            f.write("\n")
            if version_info["changes"]:
                for change in version_info["changes"]:
                    f.write("  * %s\n" % change)
            else:
                f.write("  * No changes listed.\n")
            f.write("\n")
Exemplo n.º 57
0
 def setUp(self):
     # create a test repo location.
     self.tmpdir = tempfile.mkdtemp('hg-git_url-test').encode('utf-8')
     commands.init(ui.ui(), self.tmpdir)
     repo = hg.repository(ui.ui(), self.tmpdir)
     self.handler = GitHandler(repo, ui.ui())
Exemplo n.º 58
0
import os
from mercurial import hg, ui

u = ui.ui()

repo = hg.repository(u, 'test1', create=1)
os.chdir('test1')

# create 'foo' with fixed time stamp
f = open('foo', 'w')
f.write('foo\n')
f.close()
os.utime('foo', (1000, 1000))

# add+commit 'foo'
repo.add(['foo'])
repo.commit(text='commit1', date="0 0")

print "workingfilectx.date =", repo[None]['foo'].date()
Exemplo n.º 59
0
import os

version_info = (1, 3, 0, 'devel')

_verpart = ''
if version_info[3] != 'final':
    _verpart = version_info[3]

version = '.'.join(str(v) for v in version_info[:3]) + _verpart

try:
    from mercurial import hg, ui
    # Take the revision of the updated/working none/changeset
    revision = 'r%s' % hg.repository(
        ui.ui(),
        __file__.split('/transifex/txcommon')[0])[None].parents()[0].rev()
except Exception:
    revision = ''

# A 'final' version should have its revision hidden even in the full version
if revision and _verpart:
    version_full = version + '-' + revision
else:
    version_full = version

del _verpart


def import_to_python(import_str):
    """Given a string 'a.b.c' return object c from a.b module."""
    mod_name, obj_name = import_str.rsplit('.', 1)
Exemplo n.º 60
0
#!/usr/bin/python
import sys

from mercurial import ui, hg

repo = hg.repository(ui.ui(), '..')
changes = [d for d in repo[sys.argv[1]].descendants()]
for c in changes:
    description = c.description()
    if description != 'merge' and description != 'Merge':
        print description