summary refs log tree commit diff stats
path: root/ganarchy/git.py
blob: a88a97971e7176d42cd5834a0540212a7392a3e8 (plain) (blame)
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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
# This file is part of GAnarchy - decentralized project hub
# Copyright (C) 2020  Soni L.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program.  If not, see <https://www.gnu.org/licenses/>.

"""Git abstraction.
"""

# Errors are raised when we can't provide an otherwise valid result.
# For example, we return 0 for counts instead of raising, but raise
# instead of returning empty strings for commit hashes and messages.

import shutil
import subprocess

class GitError(Exception):
    """Raised when a git operation fails, generally due to a
    missing commit or branch, or network connection issues.
    """
    pass

class Git:
    """A git repo.

    Takes a ``pathlib.Path`` as argument.
    """

    def __init__(self, path):
        self.path = path

    #########################################
    # Operations supported on any git repo. #
    #########################################

    def check_branchname(self, branchname):
        """Checks if the given branchname is a valid branch name.
        Raises if it isn't.

        Args:
            branchname (str): Name of branch.

        Raises:
            GitError: If an error occurs.
        """
        try:
            if branchname.startswith("-"):
                raise GitError("check branchname", branchname)
            out = self._cmd(
                "check-ref-format", "--branch", branchname
            ).stdout.decode("utf-8")
            # protect against @{-1}/@{-n} ("previous checkout operation")
            # is also fairly future-proofed, I hope?
            if (not out.startswith(branchname)) or (
                out.removeprefix(branchname) not in ('\r\n', '\n', '')
            ):
                raise GitError("check branchname", out, branchname)
        except subprocess.CalledProcessError as e:
            raise GitError("check branchname") from e

    def get_hash(self, target):
        """Returns the commit hash for a given target.

        Args:
            target (str): a refspec.

        Raises:
            GitError: If an error occurs.
        """
        try:
            return self._cmd(
                "show", target, "-s", "--format=format:%H", "--"
            ).stdout.decode("utf-8")
        except subprocess.CalledProcessError as e:
            raise GitError("get hash") from e

    def get_commit_message(self, target):
        """Returns the commit message for a given target.

        Args:
            target (str): a refspec.

        Raises:
            GitError: If an error occurs.
        """
        try:
            return self._cmd(
                "show", target, "-s", "--format=format:%B", "--"
            ).stdout.decode("utf-8", "replace")
        except subprocess.CalledProcessError as e:
            raise GitError("get commit message") from e

    def check_history(self, local_head, commit):
        """Checks if the local head contains commit in its history.
        Raises if it doesn't.

        Args:
            local_head (str): Name of local head.
            commit (str): Commit hash.

        Raises:
            GitError: If an error occurs.
        """
        try:
            self._cmd("merge-base", "--is-ancestor", commit, local_head)
        except subprocess.CalledProcessError as e:
            raise GitError("check history") from e

    ########################
    # Low-level operations #
    ########################

    def _cmd_init(self, *args):
        """Runs a command for initializing this git repo.

        Always uses ``--bare``.

        Returns:
            subprocess.CompletedProcess: The results of running the command.

        Raises:
            subprocess.CalledProcessError: If the command exited with a non-zero
            status.
        """
        return self._cmd_common('init', '--bare', *args, self.path)

    def _cmd_clone_from(self, from_, *args):
        """Runs a command for cloning into this git repo.

        Always uses ``--bare``.

        Returns:
            subprocess.CompletedProcess: The results of running the command.

        Raises:
            subprocess.CalledProcessError: If the command exited with a non-zero
            status.
        """
        return self._cmd_common('clone', '--bare', *args, from_, self.path)

    def _cmd(self, *args):
        """Runs a command for operating on this git repo.

        Note: Doesn't work for git init and git clone operations. Use
        ``_cmd_init`` and ``_cmd_clone_from`` instead.

        Always uses ``--bare``.

        Returns:
            subprocess.CompletedProcess: The results of running the command.

        Raises:
            subprocess.CalledProcessError: If the command exited with a non-zero
            status.
        """
        return self._cmd_common('-C', self.path, '--bare', *args)

    def _cmd_common(self, *args):
        """Runs a git command with the given args.

        This is a simple wrapper around ``subprocess.run``.

        Returns:
            subprocess.CompletedProcess: The results of running the command.

        Raises:
            subprocess.CalledProcessError: If the command exited with a non-zero
            status.
        """
        return subprocess.run(
            ('git',) + args,
            check=True,
            stdout=subprocess.PIPE,
            stderr=subprocess.PIPE
        )

class GitCache(Git):
    """A permanent repository used to cache remote objects.
    """

    #####################
    # Public operations #
    #####################

    def create(self):
        """Creates the local repo.

        Can safely be called on an existing repo.
        """
        try:
            return self._cmd_init()
        except subprocess.CalledProcessError as e:
            raise GitError("create") from e

    def with_work_repos(self, count):
        """Creates a context manager for managing work repos.

        Args:
            count (int): The number of work repos.
        """
        """From Rust:
        /// Creates the given number of work repos, and calls the closure to run
        /// operations on them.
        ///
        /// The operations can be done on the individual repos, and they'll be
        /// merged into the main repo as this function returns.
        ///
        /// If the callback fails, the work repos will be deleted. If the function
        /// succeeds, the work repos will be merged back into the main repo.
        ///
        /// # Panics
        ///
        /// Panics if a merge conflict is detected. Specifically, if two work repos
        /// modify the same work branch.
        ///
        /// # "Poisoning"
        ///
        /// If this method unwinds, the underlying git repos, if any, will not be
        /// deleted. Instead, future calls to this method will return a GitError.
        """
        work_repos = []
        for i in range(0, count):
            new_path = self.path.with_name('ganarchy-fetch-{}.git'.format(i))
            work_repos.append(GitFetch(new_path))
        physical_work_repos = []
        for repo in work_repos:
            self._fork(repo)
            physical_work_repos.append(repo)
        return _WithWorkRepos(self, physical_work_repos)

    #######################
    # Internal operations #
    #######################

    def _fetch_work(self, from_, branch, from_branch):
        try:
            self._cmd(
                "fetch", from_.path, "+{}:{}".format(from_branch, branch)
            )
        except subprocess.CalledProcessError as e:
            raise GitError("fetch work") from e

    def _replace(self, old_name, new_name):
        try:
            self._cmd(
                "branch", "-M", old_name, new_name
            )
        except subprocess.CalledProcessError as e:
            raise GitError("replace") from e

    def _fork(self, into):
        """Makes a shared clone of this local repo into the given work repo.

        Equivalent to ``git clone --bare --shared``, which is very dangerous!
        """
        try:
            return into._cmd_clone_from(self.path, '--shared')
        except subprocess.CalledProcessError as e:
            raise GitError("fork") from e

class GitFetch(Git):
    """A temporary repository used to fetch remote objects.
    """
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.pending_branches = set()

    #####################
    # Public operations #
    #####################

    def force_fetch(self, url, remote_head, local_head):
        """Fetches a remote head into a local head.
        
        If the local head already exists, it is replaced.

        Args:
            url (str): Remote url.
            remote_head (str): Name of remote head.
            local_head (str): Name of local head.

        Raises:
            GitError: If an error occurs.
        """
        try:
            self._cmd(
                "fetch", url, "+" + remote_head + ":" + local_head
            )
            self.pending_branches.add(local_head)
        except subprocess.CalledProcessError as e:
            raise GitError("fetch source") from e

    def get_count(self, first_hash, last_hash):
        """Returns a count of the commits added since ``first_hash``
        up to ``last_hash``.

        Args:
            first_hash (str): A commit.
            last_hash (str): Another commit.

        Returns:
            int: A count of commits added between the hashes, or 0
            if an error occurs.
        """
        try:
            res = self._cmd(
                "rev-list", "--count", first_hash + ".." + last_hash, "--"
            ).stdout.decode("utf-8").strip()
            return int(res)
        except subprocess.CalledProcessError as e:
            return 0

    #######################
    # Internal operations #
    #######################

    def _rm_branch(self, branch):
        try:
            self._cmd("branch", "-D", branch)
        except subprocess.CalledProcessError as e:
            raise GitError("rm branch") from e

    def _delete(self):
        try:
            shutil.rmtree(self.path)
        except IOError as e:
            raise GitError("delete", self.path) from e

class _WithWorkRepos:
    """Context manager for merging forked repos in ``with_work_repos``.
    """
    def __init__(self, cache_repo, work_repos):
        self.cache_repo = cache_repo
        self.work_repos = work_repos

    def __enter__(self):
        return self.work_repos

    def __exit__(self, exc_type, exc_val, exc_tb):
        if exc_type is None:
            branches = set()
            for work in self.work_repos:
                for branch in work.pending_branches:
                    if branch in branches:
                        raise GitError("Branch {} is in conflict!".format(branch))
                    branches.add(branch)
            del branches
            del work
            del branch

            for i, repo in enumerate(self.work_repos):
                for branch in repo.pending_branches:
                    fetch_head = "{}-{}".format(branch, i)
                    # First collect the work branch into a fetch head
                    self.cache_repo._fetch_work(repo, fetch_head, branch)
                    # If that succeeds, delete the work branch to free up disk
                    repo._rm_branch(branch)
                    # We have all the objects in the main repo and we probably
                    # have enough disk, so just replace the fetch head into
                    # the main branch and hope nothing errors.
                    self.cache_repo._replace(fetch_head, branch)
                repo._delete()