view hgext3rd/topic/common.py @ 6237:0b9042408809

topic: formatting branch, namespace and topic into fully qualified branch name
author Anton Shestakov <av6@dwimlabs.net>
date Tue, 03 May 2022 21:46:23 +0400
parents 7ad8107d953a
children 945d27da146c
line wrap: on
line source

# Copyright 2019 Pierre-Yves David <pierre-yves.david@octobus.net>
#
# This software may be used and distributed according to the terms of the
# GNU General Public License version 2 or any later version.

def hastopicext(repo):
    """True if the repo use the topic extension"""
    return getattr(repo, 'hastopicext', False)

def parsefqbn(string):
    """parse branch//namespace/topic string into branch, namespace and topic

    >>> parsefqbn(b'branch//topic')
    ('branch', 'default', 'topic')
    >>> parsefqbn(b'//namespace/topic')
    ('default', 'namespace', 'topic')
    >>> parsefqbn(b'branch//')
    ('branch', 'default', '')
    >>> parsefqbn(b'//namespace/')
    ('default', 'namespace', '')
    >>> parsefqbn(b'/topic')
    ('/topic', 'default', '')
    >>> parsefqbn(b'//topic')
    ('default', 'default', 'topic')
    >>> parsefqbn(b'branch//namespace/topic')
    ('branch', 'namespace', 'topic')
    >>> parsefqbn(b'file:///tmp/branch//')
    ('file:///tmp/branch', 'default', '')
    >>> parsefqbn(b'http://example.com/branch//namespace/topic')
    ('http://example.com/branch', 'namespace', 'topic')
    """
    branch, sep, other = string.rpartition(b'//')
    if not sep:
        # when there's no // anywhere in the string, rpartition returns
        # untouched string as the 3rd element, and the first two are empty
        branch, other = other, b''
    if not branch:
        branch = b'default'
    tns, sep, topic = other.partition(b'/')
    if not sep:
        # when there's no / in the rest of the string, there can only be topic
        tns, topic = b'default', tns
    return branch, tns, topic

def formatfqbn(branch=b'', namespace=b'', topic=b''):
    """format branch, namespace and topic into branch//namespace/topic string

    >>> formatfqbn(branch=b'branch', topic=b'topic')
    'branch//topic'
    >>> formatfqbn(namespace=b'namespace', topic=b'topic')
    '//namespace/topic'
    >>> formatfqbn(branch=b'branch')
    'branch'
    >>> formatfqbn(namespace=b'namespace')
    '//namespace/'
    >>> formatfqbn(branch=b'/topic')
    '/topic'
    >>> formatfqbn(topic=b'topic')
    '//topic'
    >>> formatfqbn(branch=b'branch', namespace=b'namespace', topic=b'topic')
    'branch//namespace/topic'
    >>> formatfqbn(branch=b'foo/bar', namespace=b'user26', topic=b'feature')
    'foo/bar//user26/feature'
    """
    result = b''
    if branch:
        result += branch
    if namespace or topic:
        result += b'//'
    if namespace:
        result += namespace + b'/'
    result += topic
    return result