File: submodules.py

package info (click to toggle)
python-pygit2 1.18.1-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 2,720 kB
  • sloc: ansic: 12,584; python: 9,337; sh: 205; makefile: 26
file content (378 lines) | stat: -rw-r--r-- 12,660 bytes parent folder | download
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
373
374
375
376
377
378
# Copyright 2010-2025 The pygit2 contributors
#
# This file is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License, version 2,
# as published by the Free Software Foundation.
#
# In addition to the permissions in the GNU General Public License,
# the authors give you unlimited permission to link the compiled
# version of this file into combinations with other programs,
# and to distribute those combinations without any restriction
# coming from the use of this file.  (The General Public License
# restrictions do apply in other respects; for example, they cover
# modification of the file, and distribution when not linked into
# a combined executable.)
#
# This file 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
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; see the file COPYING.  If not, write to
# the Free Software Foundation, 51 Franklin Street, Fifth Floor,
# Boston, MA 02110-1301, USA.

from __future__ import annotations
from typing import TYPE_CHECKING, Iterable, Iterator, Optional, Union

from ._pygit2 import Oid
from .callbacks import git_fetch_options, RemoteCallbacks
from .enums import SubmoduleIgnore, SubmoduleStatus
from .errors import check_error
from .ffi import ffi, C
from .utils import to_bytes, maybe_string

# Need BaseRepository for type hints, but don't let it cause a circular dependency
if TYPE_CHECKING:
    from .repository import BaseRepository


class Submodule:
    _repo: BaseRepository
    _subm: object

    @classmethod
    def _from_c(cls, repo: BaseRepository, cptr):
        subm = cls.__new__(cls)

        subm._repo = repo
        subm._subm = cptr

        return subm

    def __del__(self):
        C.git_submodule_free(self._subm)

    def open(self):
        """Open the repository for a submodule."""
        crepo = ffi.new('git_repository **')
        err = C.git_submodule_open(crepo, self._subm)
        check_error(err)

        return self._repo._from_c(crepo[0], True)

    def init(self, overwrite: bool = False):
        """
        Just like "git submodule init", this copies information about the submodule
        into ".git/config".

        Parameters:

        overwrite
            By default, existing submodule entries will not be overwritten,
            but setting this to True forces them to be updated.
        """
        err = C.git_submodule_init(self._subm, int(overwrite))
        check_error(err)

    def update(
        self,
        init: bool = False,
        callbacks: Optional[RemoteCallbacks] = None,
        depth: int = 0,
    ):
        """
        Update a submodule. This will clone a missing submodule and checkout
        the subrepository to the commit specified in the index of the
        containing repository. If the submodule repository doesn't contain the
        target commit (e.g. because fetchRecurseSubmodules isn't set), then the
        submodule is fetched using the fetch options supplied in options.

        Parameters:

        init
            If the submodule is not initialized, setting this flag to True will
            initialize the submodule before updating. Otherwise, this will raise
            an error if attempting to update an uninitialized repository.

        callbacks
            Optional RemoteCallbacks to clone or fetch the submodule.

        depth
            Number of commits to fetch.
            The default is 0 (full commit history).
        """

        opts = ffi.new('git_submodule_update_options *')
        C.git_submodule_update_options_init(
            opts, C.GIT_SUBMODULE_UPDATE_OPTIONS_VERSION
        )
        opts.fetch_opts.depth = depth

        with git_fetch_options(callbacks, opts=opts.fetch_opts) as payload:
            err = C.git_submodule_update(self._subm, int(init), opts)
            payload.check_error(err)

    def reload(self, force: bool = False):
        """
        Reread submodule info from config, index, and HEAD.

        Call this to reread cached submodule information for this submodule if
        you have reason to believe that it has changed.

        Parameters:

        force
            Force reload even if the data doesn't seem out of date
        """
        err = C.git_submodule_reload(self._subm, int(force))
        check_error(err)

    @property
    def name(self):
        """Name of the submodule."""
        name = C.git_submodule_name(self._subm)
        return ffi.string(name).decode('utf-8')

    @property
    def path(self):
        """Path of the submodule."""
        path = C.git_submodule_path(self._subm)
        return ffi.string(path).decode('utf-8')

    @property
    def url(self) -> Union[str, None]:
        """URL of the submodule."""
        url = C.git_submodule_url(self._subm)
        return maybe_string(url)

    @property
    def branch(self):
        """Branch that is to be tracked by the submodule."""
        branch = C.git_submodule_branch(self._subm)
        return ffi.string(branch).decode('utf-8')

    @property
    def head_id(self) -> Union[Oid, None]:
        """
        The submodule's HEAD commit id (as recorded in the superproject's
        current HEAD tree).
        Returns None if the superproject's HEAD doesn't contain the submodule.
        """

        head = C.git_submodule_head_id(self._subm)
        if head == ffi.NULL:
            return None
        return Oid(raw=bytes(ffi.buffer(head.id)[:]))


class SubmoduleCollection:
    """Collection of submodules in a repository."""

    def __init__(self, repository: BaseRepository):
        self._repository = repository

    def __getitem__(self, name: str) -> Submodule:
        """
        Look up submodule information by name or path.
        Raises KeyError if there is no such submodule.
        """
        csub = ffi.new('git_submodule **')
        cpath = ffi.new('char[]', to_bytes(name))

        err = C.git_submodule_lookup(csub, self._repository._repo, cpath)
        check_error(err)
        return Submodule._from_c(self._repository, csub[0])

    def __contains__(self, name: str) -> bool:
        return self.get(name) is not None

    def __iter__(self) -> Iterator[Submodule]:
        for s in self._repository.listall_submodules():
            yield self[s]

    def get(self, name: str) -> Union[Submodule, None]:
        """
        Look up submodule information by name or path.
        Unlike __getitem__, this returns None if the submodule is not found.
        """
        try:
            return self[name]
        except KeyError:
            return None

    def add(
        self,
        url: str,
        path: str,
        link: bool = True,
        callbacks: Optional[RemoteCallbacks] = None,
        depth: int = 0,
    ) -> Submodule:
        """
        Add a submodule to the index.
        The submodule is automatically cloned.

        Returns: the submodule that was added.

        Parameters:

        url
            The URL of the submodule.

        path
            The path within the parent repository to add the submodule

        link
            Should workdir contain a gitlink to the repo in `.git/modules` vs. repo directly in workdir.

        callbacks
            Optional RemoteCallbacks to clone the submodule.

        depth
            Number of commits to fetch.
            The default is 0 (full commit history).
        """
        csub = ffi.new('git_submodule **')
        curl = ffi.new('char[]', to_bytes(url))
        cpath = ffi.new('char[]', to_bytes(path))
        gitlink = 1 if link else 0

        err = C.git_submodule_add_setup(
            csub, self._repository._repo, curl, cpath, gitlink
        )
        check_error(err)

        submodule_instance = Submodule._from_c(self._repository, csub[0])

        # Prepare options
        opts = ffi.new('git_submodule_update_options *')
        C.git_submodule_update_options_init(
            opts, C.GIT_SUBMODULE_UPDATE_OPTIONS_VERSION
        )
        opts.fetch_opts.depth = depth

        with git_fetch_options(callbacks, opts=opts.fetch_opts) as payload:
            crepo = ffi.new('git_repository **')
            err = C.git_submodule_clone(crepo, submodule_instance._subm, opts)
            payload.check_error(err)

        # Clean up submodule repository
        from .repository import Repository

        Repository._from_c(crepo[0], True)

        err = C.git_submodule_add_finalize(submodule_instance._subm)
        check_error(err)
        return submodule_instance

    def init(self, submodules: Optional[Iterable[str]] = None, overwrite: bool = False):
        """
        Initialize submodules in the repository. Just like "git submodule init",
        this copies information about the submodules into ".git/config".

        Parameters:

        submodules
            Optional list of submodule paths or names to initialize.
            Default argument initializes all submodules.

        overwrite
            Flag indicating if initialization should overwrite submodule entries.
        """
        if submodules is None:
            submodules = self._repository.listall_submodules()

        instances = [self[s] for s in submodules]

        for submodule in instances:
            submodule.init(overwrite)

    def update(
        self,
        submodules: Optional[Iterable[str]] = None,
        init: bool = False,
        callbacks: Optional[RemoteCallbacks] = None,
        depth: int = 0,
    ):
        """
        Update submodules. This will clone a missing submodule and checkout
        the subrepository to the commit specified in the index of the
        containing repository. If the submodule repository doesn't contain the
        target commit (e.g. because fetchRecurseSubmodules isn't set), then the
        submodule is fetched using the fetch options supplied in options.

        Parameters:

        submodules
            Optional list of submodule paths or names. If you omit this parameter
            or pass None, all submodules will be updated.

        init
            If the submodule is not initialized, setting this flag to True will
            initialize the submodule before updating. Otherwise, this will raise
            an error if attempting to update an uninitialized repository.

        callbacks
            Optional RemoteCallbacks to clone or fetch the submodule.

        depth
            Number of commits to fetch.
            The default is 0 (full commit history).
        """
        if submodules is None:
            submodules = self._repository.listall_submodules()

        instances = [self[s] for s in submodules]

        for submodule in instances:
            submodule.update(init, callbacks, depth)

    def status(
        self, name: str, ignore: SubmoduleIgnore = SubmoduleIgnore.UNSPECIFIED
    ) -> SubmoduleStatus:
        """
        Get the status of a submodule.

        Returns: A combination of SubmoduleStatus flags.

        Parameters:

        name
            Submodule name or path.

        ignore
            A SubmoduleIgnore value indicating how deeply to examine the working directory.
        """
        cstatus = ffi.new('unsigned int *')
        err = C.git_submodule_status(
            cstatus, self._repository._repo, to_bytes(name), ignore
        )
        check_error(err)
        return SubmoduleStatus(cstatus[0])

    def cache_all(self):
        """
        Load and cache all submodules in the repository.

        Because the `.gitmodules` file is unstructured, loading submodules is an
        O(N) operation.  Any operation that requires accessing all submodules is O(N^2)
        in the number of submodules, if it has to look each one up individually.
        This function loads all submodules and caches them so that subsequent
        submodule lookups by name are O(1).
        """
        err = C.git_repository_submodule_cache_all(self._repository._repo)
        check_error(err)

    def cache_clear(self):
        """
        Clear the submodule cache populated by `submodule_cache_all`.
        If there is no cache, do nothing.

        The cache incorporates data from the repository's configuration, as well
        as the state of the working tree, the index, and HEAD. So any time any
        of these has changed, the cache might become invalid.
        """
        err = C.git_repository_submodule_cache_clear(self._repository._repo)
        check_error(err)