summaryrefslogtreecommitdiffstats
path: root/git.py
blob: fd827f932342d673ab7e2ff4fddfea0edf31c927 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
# Copyright (C) 2023 The Qt Company Ltd.
# SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
import os
from typing import Optional, Union

import common

COMMAND_TIMEOUT = 5 * 60


class Remote:
    """A remote repository."""

    def __init__(self, url: str) -> None:
        self.url = url


class Repository:
    """
    A local repository cloned from a remote repository.
    """

    def __init__(self, directory: str) -> None:
        self.directory = directory

    @staticmethod
    async def clone(
        remote: Remote,
        parent_directory: str,
        log_directory: str,
    ) -> Union["Repository", common.Error]:
        try:
            name = remote.url.rsplit("/", maxsplit=1)[1]
        except IndexError:
            return common.Error("Failed to extract repository name from remote URL")

        directory = os.path.join(parent_directory, name)
        error = await common.Command.run(
            arguments=["git", "clone", "--", remote.url, directory],
            output_file=os.path.join(log_directory, "clone.log"),
            timeout=COMMAND_TIMEOUT,
        )
        match error:
            case common.Error() as error:
                return error

        return Repository(directory)

    async def reset(self, revision: str, log_directory: str) -> Optional[common.Error]:
        error = await common.Command.run(
            arguments=["git", "fetch", "origin", revision],
            output_file=os.path.join(log_directory, "fetch.log"),
            timeout=COMMAND_TIMEOUT,
            cwd=self.directory,
        )
        if error:
            return error

        error = await common.Command.run(
            arguments=["git", "clean", "-dfx"],
            output_file=os.path.join(log_directory, "clean.log"),
            timeout=COMMAND_TIMEOUT,
            cwd=self.directory,
        )
        if error:
            return error

        error = await common.Command.run(
            arguments=["git", "reset", "--hard", revision],
            output_file=os.path.join(log_directory, "reset.log"),
            timeout=COMMAND_TIMEOUT,
            cwd=self.directory,
        )
        if error:
            return error

        return None