File: index.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 (562 lines) | stat: -rw-r--r-- 18,020 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
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
# 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.

import typing
import warnings
from dataclasses import dataclass

# Import from pygit2
from ._pygit2 import Oid, Tree, Diff
from .enums import DiffOption, FileMode
from .errors import check_error
from .ffi import ffi, C
from .utils import to_bytes, to_str
from .utils import GenericIterator, StrArray


class Index:
    # XXX Implement the basic features in C (_pygit2.Index) and make
    # pygit2.Index to inherit from _pygit2.Index? This would allow for
    # a proper implementation in some places: e.g. checking the index type
    # from C code (see Tree_diff_to_index)

    def __init__(self, path=None):
        """Create a new Index

        If path is supplied, the read and write methods will use that path
        to read from and write to.
        """
        cindex = ffi.new('git_index **')
        err = C.git_index_open(cindex, to_bytes(path))
        check_error(err)

        self._repo = None
        self._index = cindex[0]
        self._cindex = cindex

    @classmethod
    def from_c(cls, repo, ptr):
        index = cls.__new__(cls)
        index._repo = repo
        index._index = ptr[0]
        index._cindex = ptr

        return index

    @property
    def _pointer(self):
        return bytes(ffi.buffer(self._cindex)[:])

    def __del__(self):
        C.git_index_free(self._index)

    def __len__(self):
        return C.git_index_entrycount(self._index)

    def __contains__(self, path):
        err = C.git_index_find(ffi.NULL, self._index, to_bytes(path))
        if err == C.GIT_ENOTFOUND:
            return False

        check_error(err)
        return True

    def __getitem__(self, key):
        centry = ffi.NULL
        if isinstance(key, str) or hasattr(key, '__fspath__'):
            centry = C.git_index_get_bypath(self._index, to_bytes(key), 0)
        elif isinstance(key, int):
            if key >= 0:
                centry = C.git_index_get_byindex(self._index, key)
            else:
                raise ValueError(key)
        else:
            raise TypeError(f'Expected str or int, got {type(key)}')

        if centry == ffi.NULL:
            raise KeyError(key)

        return IndexEntry._from_c(centry)

    def __iter__(self):
        return GenericIterator(self)

    def read(self, force=True):
        """
        Update the contents of the Index by reading from a file.

        Parameters:

        force
            If True (the default) always reload. If False, only if the file
            has changed.
        """

        err = C.git_index_read(self._index, force)
        check_error(err, io=True)

    def write(self):
        """Write the contents of the Index to disk."""
        err = C.git_index_write(self._index)
        check_error(err, io=True)

    def clear(self):
        err = C.git_index_clear(self._index)
        check_error(err)

    def read_tree(self, tree):
        """Replace the contents of the Index with those of the given tree,
        expressed either as a <Tree> object or as an oid (string or <Oid>).

        The tree will be read recursively and all its children will also be
        inserted into the Index.
        """
        repo = self._repo
        if isinstance(tree, str):
            tree = repo[tree]

        if isinstance(tree, Oid):
            if repo is None:
                raise TypeError('id given but no associated repository')

            tree = repo[tree]
        elif not isinstance(tree, Tree):
            raise TypeError('argument must be Oid or Tree')

        tree_cptr = ffi.new('git_tree **')
        ffi.buffer(tree_cptr)[:] = tree._pointer[:]
        err = C.git_index_read_tree(self._index, tree_cptr[0])
        check_error(err)

    def write_tree(self, repo=None):
        """Create a tree out of the Index. Return the <Oid> object of the
        written tree.

        The contents of the index will be written out to the object
        database. If there is no associated repository, 'repo' must be
        passed. If there is an associated repository and 'repo' is
        passed, then that repository will be used instead.

        It returns the id of the resulting tree.
        """
        coid = ffi.new('git_oid *')

        repo = repo or self._repo

        if repo:
            err = C.git_index_write_tree_to(coid, self._index, repo._repo)
        else:
            err = C.git_index_write_tree(coid, self._index)

        check_error(err)
        return Oid(raw=bytes(ffi.buffer(coid)[:]))

    def remove(self, path, level=0):
        """Remove an entry from the Index."""
        err = C.git_index_remove(self._index, to_bytes(path), level)
        check_error(err, io=True)

    def remove_directory(self, path, level=0):
        """Remove a directory from the Index."""
        err = C.git_index_remove_directory(self._index, to_bytes(path), level)
        check_error(err, io=True)

    def remove_all(self, pathspecs):
        """Remove all index entries matching pathspecs."""
        with StrArray(pathspecs) as arr:
            err = C.git_index_remove_all(self._index, arr.ptr, ffi.NULL, ffi.NULL)
            check_error(err, io=True)

    def add_all(self, pathspecs=None):
        """Add or update index entries matching files in the working directory.

        If pathspecs are specified, only files matching those pathspecs will
        be added.
        """
        pathspecs = pathspecs or []
        with StrArray(pathspecs) as arr:
            err = C.git_index_add_all(self._index, arr.ptr, 0, ffi.NULL, ffi.NULL)
            check_error(err, io=True)

    def add(self, path_or_entry):
        """Add or update an entry in the Index.

        If a path is given, that file will be added. The path must be relative
        to the root of the worktree and the Index must be associated with a
        repository.

        If an IndexEntry is given, that entry will be added or update in the
        Index without checking for the existence of the path or id.
        """
        if isinstance(path_or_entry, IndexEntry):
            entry = path_or_entry
            centry, str_ref = entry._to_c()
            err = C.git_index_add(self._index, centry)
        elif isinstance(path_or_entry, str) or hasattr(path_or_entry, '__fspath__'):
            path = path_or_entry
            err = C.git_index_add_bypath(self._index, to_bytes(path))
        else:
            raise TypeError('argument must be string or IndexEntry')

        check_error(err, io=True)

    def add_conflict(self, ancestor, ours, theirs):
        """
        Add or update index entries to represent a conflict. Any staged entries that
        exist at the given paths will be removed.

        Parameters:

        ancestor
            ancestor of the conflict
        ours
            ours side of the conflict
        theirs
            their side of the conflict
        """

        if ancestor and not isinstance(ancestor, IndexEntry):
            raise TypeError('ancestor has to be an instance of IndexEntry or None')
        if ours and not isinstance(ours, IndexEntry):
            raise TypeError('ours has to be an instance of IndexEntry or None')
        if theirs and not isinstance(theirs, IndexEntry):
            raise TypeError('theirs has to be an instance of IndexEntry or None')

        centry_ancestor = centry_ours = centry_theirs = ffi.NULL
        if ancestor is not None:
            centry_ancestor, _ = ancestor._to_c()
        if ours is not None:
            centry_ours, _ = ours._to_c()
        if theirs is not None:
            centry_theirs, _ = theirs._to_c()
        err = C.git_index_conflict_add(
            self._index, centry_ancestor, centry_ours, centry_theirs
        )

        check_error(err, io=True)

    def diff_to_workdir(
        self,
        flags: DiffOption = DiffOption.NORMAL,
        context_lines: int = 3,
        interhunk_lines: int = 0,
    ) -> Diff:
        """
        Diff the index against the working directory. Return a <Diff> object
        with the differences between the index and the working copy.

        Parameters:

        flags
            A combination of enums.DiffOption constants.

        context_lines
            The number of unchanged lines that define the boundary of a hunk
            (and to display before and after).

        interhunk_lines
            The maximum number of unchanged lines between hunk boundaries
            before the hunks will be merged into a one.
        """
        repo = self._repo
        if repo is None:
            raise ValueError('diff needs an associated repository')

        copts = ffi.new('git_diff_options *')
        err = C.git_diff_options_init(copts, 1)
        check_error(err)

        copts.flags = int(flags)
        copts.context_lines = context_lines
        copts.interhunk_lines = interhunk_lines

        cdiff = ffi.new('git_diff **')
        err = C.git_diff_index_to_workdir(cdiff, repo._repo, self._index, copts)
        check_error(err)

        return Diff.from_c(bytes(ffi.buffer(cdiff)[:]), repo)

    def diff_to_tree(
        self,
        tree: Tree,
        flags: DiffOption = DiffOption.NORMAL,
        context_lines: int = 3,
        interhunk_lines: int = 0,
    ) -> Diff:
        """
        Diff the index against a tree.  Return a <Diff> object with the
        differences between the index and the given tree.

        Parameters:

        tree
            The tree to diff.

        flags
            A combination of enums.DiffOption constants.

        context_lines
            The number of unchanged lines that define the boundary of a hunk
            (and to display before and after).

        interhunk_lines
            The maximum number of unchanged lines between hunk boundaries
            before the hunks will be merged into a one.
        """
        repo = self._repo
        if repo is None:
            raise ValueError('diff needs an associated repository')

        if not isinstance(tree, Tree):
            raise TypeError('tree must be a Tree')

        copts = ffi.new('git_diff_options *')
        err = C.git_diff_options_init(copts, 1)
        check_error(err)

        copts.flags = int(flags)
        copts.context_lines = context_lines
        copts.interhunk_lines = interhunk_lines

        ctree = ffi.new('git_tree **')
        ffi.buffer(ctree)[:] = tree._pointer[:]

        cdiff = ffi.new('git_diff **')
        err = C.git_diff_tree_to_index(cdiff, repo._repo, ctree[0], self._index, copts)
        check_error(err)

        return Diff.from_c(bytes(ffi.buffer(cdiff)[:]), repo)

    #
    # Conflicts
    #

    @property
    def conflicts(self):
        """A collection of conflict information

        If there are no conflicts None is returned. Otherwise return an object
        that represents the conflicts in the index.

        This object presents a mapping interface with the paths as keys. You
        can use the ``del`` operator to remove a conflict from the Index.

        Each conflict is made up of three elements. Access or iteration
        of the conflicts returns a three-tuple of
        :py:class:`~pygit2.IndexEntry`. The first is the common
        ancestor, the second is the "ours" side of the conflict, and the
        third is the "theirs" side.

        These elements may be None depending on which sides exist for
        the particular conflict.
        """
        if not C.git_index_has_conflicts(self._index):
            return None

        return ConflictCollection(self)


@dataclass
class MergeFileResult:
    automergeable: bool
    'True if the output was automerged, false if the output contains conflict markers'

    path: typing.Union[str, None]
    'The path that the resultant merge file should use, or None if a filename conflict would occur'

    mode: FileMode
    'The mode that the resultant merge file should use'

    contents: str
    'Contents of the file, which might include conflict markers'

    def __repr__(self):
        t = type(self)
        contents = (
            self.contents if len(self.contents) <= 20 else f'{self.contents[:20]}...'
        )
        return (
            f'<{t.__module__}.{t.__qualname__} "'
            f'automergeable={self.automergeable} "'
            f'path={self.path} '
            f'mode={self.mode} '
            f'contents={contents}>'
        )

    @classmethod
    def _from_c(cls, centry):
        if centry == ffi.NULL:
            return None

        automergeable = centry.automergeable != 0
        path = to_str(ffi.string(centry.path)) if centry.path else None
        mode = FileMode(centry.mode)
        contents = ffi.string(centry.ptr, centry.len).decode('utf-8')

        return MergeFileResult(automergeable, path, mode, contents)


class IndexEntry:
    path: str
    'The path of this entry'

    id: Oid
    'The id of the referenced object'

    mode: FileMode
    'The mode of this entry, a FileMode value'

    def __init__(self, path, object_id: Oid, mode: FileMode):
        self.path = path
        self.id = object_id
        self.mode = mode

    @property
    def oid(self):
        # For backwards compatibility
        return self.id

    @property
    def hex(self):
        """The id of the referenced object as a hex string"""
        warnings.warn('Use str(entry.id)', DeprecationWarning)
        return str(self.id)

    def __str__(self):
        return f'<path={self.path} id={self.id} mode={self.mode}>'

    def __repr__(self):
        t = type(self)
        return f'<{t.__module__}.{t.__qualname__} path={self.path} id={self.id} mode={self.mode}>'

    def __eq__(self, other):
        if self is other:
            return True
        if not isinstance(other, IndexEntry):
            return NotImplemented
        return (
            self.path == other.path and self.id == other.id and self.mode == other.mode
        )

    def _to_c(self):
        """Convert this entry into the C structure

        The first returned arg is the pointer, the second is the reference to
        the string we allocated, which we need to exist past this function
        """
        centry = ffi.new('git_index_entry *')
        # basically memcpy()
        ffi.buffer(ffi.addressof(centry, 'id'))[:] = self.id.raw[:]
        centry.mode = int(self.mode)
        path = ffi.new('char[]', to_bytes(self.path))
        centry.path = path

        return centry, path

    @classmethod
    def _from_c(cls, centry):
        if centry == ffi.NULL:
            return None

        entry = cls.__new__(cls)
        entry.path = to_str(ffi.string(centry.path))
        entry.mode = FileMode(centry.mode)
        entry.id = Oid(raw=bytes(ffi.buffer(ffi.addressof(centry, 'id'))[:]))

        return entry


class ConflictCollection:
    def __init__(self, index):
        self._index = index

    def __getitem__(self, path):
        cancestor = ffi.new('git_index_entry **')
        cours = ffi.new('git_index_entry **')
        ctheirs = ffi.new('git_index_entry **')

        err = C.git_index_conflict_get(
            cancestor, cours, ctheirs, self._index._index, to_bytes(path)
        )
        check_error(err)

        ancestor = IndexEntry._from_c(cancestor[0])
        ours = IndexEntry._from_c(cours[0])
        theirs = IndexEntry._from_c(ctheirs[0])

        return ancestor, ours, theirs

    def __delitem__(self, path):
        err = C.git_index_conflict_remove(self._index._index, to_bytes(path))
        check_error(err)

    def __iter__(self):
        return ConflictIterator(self._index)

    def __contains__(self, path):
        cancestor = ffi.new('git_index_entry **')
        cours = ffi.new('git_index_entry **')
        ctheirs = ffi.new('git_index_entry **')

        err = C.git_index_conflict_get(
            cancestor, cours, ctheirs, self._index._index, to_bytes(path)
        )
        if err == C.GIT_ENOTFOUND:
            return False

        check_error(err)
        return True


class ConflictIterator:
    def __init__(self, index):
        citer = ffi.new('git_index_conflict_iterator **')
        err = C.git_index_conflict_iterator_new(citer, index._index)
        check_error(err)
        self._index = index
        self._iter = citer[0]

    def __del__(self):
        C.git_index_conflict_iterator_free(self._iter)

    def __iter__(self):
        return self

    def __next__(self):
        cancestor = ffi.new('git_index_entry **')
        cours = ffi.new('git_index_entry **')
        ctheirs = ffi.new('git_index_entry **')

        err = C.git_index_conflict_next(cancestor, cours, ctheirs, self._iter)
        if err == C.GIT_ITEROVER:
            raise StopIteration

        check_error(err)

        ancestor = IndexEntry._from_c(cancestor[0])
        ours = IndexEntry._from_c(cours[0])
        theirs = IndexEntry._from_c(ctheirs[0])

        return ancestor, ours, theirs