1# This file is part of Buildbot.  Buildbot is free software: you can
2# redistribute it and/or modify it under the terms of the GNU General Public
3# License as published by the Free Software Foundation, version 2.
4#
5# This program is distributed in the hope that it will be useful, but WITHOUT
6# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
7# FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more
8# details.
9#
10# You should have received a copy of the GNU General Public License along with
11# this program; if not, write to the Free Software Foundation, Inc., 51
12# Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
13#
14# Copyright Buildbot Team Members
15
16
17import re
18from collections import namedtuple
19
20# The regex is matching more than it should and is not intended to be an url validator.
21# It is intended to efficiently and reliably extract information from the various examples
22# that are described in the unit tests.
23
24_giturlmatcher = re.compile(
25    r'(?P<proto>(https?://|ssh://|git://|))'
26    r'((?P<user>.*)@)?'
27    r'(?P<domain>[^\/:]+)(:((?P<port>[0-9]+)/)?|/)'
28    r'((?P<owner>.+)/)?(?P<repo>[^/]+?)(\.git)?$')
29
30GitUrl = namedtuple('GitUrl', ['proto', 'user', 'domain', 'port', 'owner', 'repo'])
31
32
33def giturlparse(url):
34    res = _giturlmatcher.match(url)
35    if res is None:
36        return None
37
38    port = res.group("port")
39    if port is not None:
40        port = int(port)
41    proto = res.group("proto")
42    if proto:
43        proto = proto[:-3]
44    else:
45        proto = 'ssh'  # implicit proto is ssh
46    return GitUrl(proto, res.group('user'), res.group("domain"),
47                  port, res.group('owner'), res.group('repo'))
48