Completed
Push — develop ( 8f6d27...fd7108 )
by
unknown
05:28 queued 11s
created

doorstop.core.item.Item.references()   A

Complexity

Conditions 2

Size

Total Lines 5
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 6
dl 0
loc 5
rs 10
c 0
b 0
f 0
cc 2
nop 2
1
# SPDX-License-Identifier: LGPL-3.0-only
2
3
"""Representation of an item in a document."""
4
5
import functools
6
import os
7
from typing import Any, List
8
9
import pyficache
10
11
from doorstop import common, settings
12
from doorstop.common import DoorstopError
13
from doorstop.core import editor
14
from doorstop.core.base import (
15
    BaseFileObject,
16
    add_item,
17
    auto_load,
18
    auto_save,
19
    delete_item,
20
    edit_item,
21
)
22
from doorstop.core.reference_finder import ReferenceFinder
23
from doorstop.core.types import UID, Level, Prefix, Stamp, Text, to_bool
24
from doorstop.core.yaml_validator import YamlValidator
25
26
log = common.logger(__name__)
27
28
29
def _convert_to_yaml(indent, prefix, value):
30
    """Convert value to YAML output format.
31
32
    :param indent: the indentation level
33
    :param prefix: the length of the prefix before the value, e.g. '- ' for
34
    lists or 'key: ' for keys
35
    :param value: the value to convert
36
37
    :return: the value converted to YAML output format
38
39
    """
40
    if isinstance(value, str):
41
        length = indent + prefix + len(value)
42
        if length > settings.MAX_LINE_LENGTH or '\n' in value:
43
            value = Text.save_text(value.strip())
44
        else:
45
            value = str(value)  # line is short enough as a string
46
    elif isinstance(value, list):
47
        value = [_convert_to_yaml(indent, 2, v) for v in value]
48
    elif isinstance(value, dict):
49
        value = {
50
            k: _convert_to_yaml(indent + 2, len(k) + 2, v) for k, v in value.items()
51
        }
52
    return value
53
54
55
def requires_tree(func):
56
    """Require a tree reference."""
57
58
    @functools.wraps(func)
59
    def wrapped(self, *args, **kwargs):
60
        if not self.tree:
61
            name = func.__name__
62
            log.critical("`{}` can only be called with a tree".format(name))
63
            return None
64
        return func(self, *args, **kwargs)
65
66
    return wrapped
67
68
69
class Item(BaseFileObject):  # pylint: disable=R0902
70
    """Represents an item file with linkable text."""
71
72
    EXTENSIONS = '.yml', '.yaml'
73
74
    DEFAULT_LEVEL = Level('1.0')
75
    DEFAULT_ACTIVE = True
76
    DEFAULT_NORMATIVE = True
77
    DEFAULT_DERIVED = False
78
    DEFAULT_REVIEWED = Stamp()
79
    DEFAULT_TEXT = Text()
80
    DEFAULT_REF = ""
81
    DEFAULT_HEADER = Text()
82
83
    def __init__(self, document, path, root=os.getcwd(), **kwargs):
84
        """Initialize an item from an existing file.
85
86
        :param path: path to Item file
87
        :param root: path to root of project
88
89
        """
90
        super().__init__()
91
        # Ensure the path is valid
92
        if not os.path.isfile(path):
93
            raise DoorstopError("item does not exist: {}".format(path))
94
        # Ensure the filename is valid
95
        filename = os.path.basename(path)
96
        name, ext = os.path.splitext(filename)
97
        try:
98
            UID(name).check()
99
        except DoorstopError:
100
            msg = "invalid item filename: {}".format(filename)
101
            raise DoorstopError(msg) from None
102
        # Ensure the file extension is valid
103
        if ext.lower() not in self.EXTENSIONS:
104
            msg = "'{0}' extension not in {1}".format(path, self.EXTENSIONS)
105
            raise DoorstopError(msg)
106
        # Initialize the item
107
        self.path = path
108
        self.root: str = root
109
        self.document = document
110
        self.tree = kwargs.get('tree')
111
        self.auto = kwargs.get('auto', Item.auto)
112
        self.reference_finder = ReferenceFinder()
113
        self.yaml_validator = YamlValidator()
114
        # Set default values
115
        self._data['level'] = Item.DEFAULT_LEVEL
116
        self._data['active'] = Item.DEFAULT_ACTIVE
117
        self._data['normative'] = Item.DEFAULT_NORMATIVE
118
        self._data['derived'] = Item.DEFAULT_DERIVED
119
        self._data['reviewed'] = Item.DEFAULT_REVIEWED
120
        self._data['text'] = Item.DEFAULT_TEXT
121
        self._data['ref'] = Item.DEFAULT_REF
122
        self._data['references'] = None
123
        self._data['links'] = set()
124
        if settings.ENABLE_HEADERS:
125
            self._data['header'] = Item.DEFAULT_HEADER
126
127
    def __repr__(self):
128
        return "Item('{}')".format(self.path)
129
130
    def __str__(self):
131
        if common.verbosity < common.STR_VERBOSITY:
132
            return str(self.uid)
133
        else:
134
            return "{} ({})".format(self.uid, self.relpath)
135
136
    def __lt__(self, other):
137
        if self.level == other.level:
138
            return self.uid < other.uid
139
        else:
140
            return self.level < other.level
141
142
    @staticmethod
143
    @add_item
144
    def new(
145
        tree, document, path, root, uid, level=None, auto=None
146
    ):  # pylint: disable=R0913
147
        """Create a new item.
148
149
        :param tree: reference to the tree that contains this item
150
        :param document: reference to document that contains this item
151
152
        :param path: path to directory for the new item
153
        :param root: path to root of the project
154
        :param uid: UID for the new item
155
156
        :param level: level for the new item
157
        :param auto: automatically save the item
158
159
        :raises: :class:`~doorstop.common.DoorstopError` if the item
160
            already exists
161
162
        :return: new :class:`~doorstop.core.item.Item`
163
164
        """
165
        UID(uid).check()
166
        filename = str(uid) + Item.EXTENSIONS[0]
167
        path2 = os.path.join(path, filename)
168
        # Create the initial item file
169
        log.debug("creating item file at {}...".format(path2))
170
        Item._create(path2, name='item')
171
        # Initialize the item
172
        item = Item(document, path2, root=root, tree=tree, auto=False)
173
        item.level = level if level is not None else item.level  # type: ignore
174
        if auto or (auto is None and Item.auto):
175
            item.save()
176
        # Return the item
177
        return item
178
179
    def _set_attributes(self, attributes):
180
        """Set the item's attributes."""
181
        self.yaml_validator.validate_item_yaml(attributes)
182
        for key, value in attributes.items():
183
            if key == 'level':
184
                value = Level(value)
185
            elif key == 'active':
186
                value = to_bool(value)
187
            elif key == 'normative':
188
                value = to_bool(value)
189
            elif key == 'derived':
190
                value = to_bool(value)
191
            elif key == 'reviewed':
192
                value = Stamp(value)
193
            elif key == 'text':
194
                value = Text(value)
195
            elif key == 'ref':
196
                value = value.strip()
197
            elif key == 'references':
198
                stripped_value = []
199
                for ref_dict in value:
200
                    ref_type = ref_dict['type']
201
                    ref_path = ref_dict['path']
202
203
                    stripped_ref_dict = {"type": ref_type, "path": ref_path.strip()}
204
                    if 'keyword' in ref_dict:
205
                        ref_keyword = ref_dict['keyword']
206
                        stripped_ref_dict['keyword'] = ref_keyword
207
208
                    stripped_value.append(stripped_ref_dict)
209
210
                value = stripped_value
211
            elif key == 'links':
212
                value = set(UID(part) for part in value)
213
            elif key == 'header':
214
                value = Text(value)
215
            self._data[key] = value
216
217
    def load(self, reload=False):
218
        """Load the item's properties from its file."""
219
        if self._loaded and not reload:
220
            return
221
        log.debug("loading {}...".format(repr(self)))
222
        # Read text from file
223
        text = self._read(self.path)
224
        # Parse YAML data from text
225
        data = self._load(text, self.path)
226
        # Store parsed data
227
        self._set_attributes(data)
228
        # Set meta attributes
229
        self._loaded = True
230
231
    @edit_item
232
    def save(self):
233
        """Format and save the item's properties to its file."""
234
        log.debug("saving {}...".format(repr(self)))
235
        # Format the data items
236
        data = self._yaml_data()
237
        # Dump the data to YAML
238
        text = self._dump(data)
239
        # Save the YAML to file
240
        self._write(text, self.path)
241
        # Set meta attributes
242
        self._loaded = True
243
        self.auto = True
244
245
    # properties #############################################################
246
247
    def _yaml_data(self):
248
        """Get all the item's data formatted for YAML dumping."""
249
        data = {}
250
        for key, value in self._data.items():
251
            if key == 'level':
252
                value = value.yaml
253
            elif key == 'text':
254
                value = value.yaml
255
            elif key == 'header':
256
                # Handle for case if the header is undefined in YAML
257
                if hasattr(value, 'yaml'):
258
                    value = value.yaml
259
                else:
260
                    value = ''
261
            elif key == 'ref':
262
                value = value.strip()
263
            elif key == 'references':
264
                if value is None:
265
                    continue
266
                stripped_value = []
267
                for el in value:
268
                    ref_dict = {"path": el["path"].strip(), "type": "file"}
269
270
                    if 'keyword' in el:
271
                        ref_dict['keyword'] = el['keyword']
272
273
                    stripped_value.append(ref_dict)
274
275
                value = stripped_value
276
            elif key == 'links':
277
                value = [{str(i): i.stamp.yaml} for i in sorted(value)]
278
            elif key == 'reviewed':
279
                value = value.yaml
280
            else:
281
                value = _convert_to_yaml(0, len(key) + 2, value)
282
            data[key] = value
283
        return data
284
285
    @property  # type: ignore
286
    @auto_load
287
    def data(self):
288
        """Load and get all the item's data formatted for YAML dumping."""
289
        return self._yaml_data()
290
291
    @property
292
    def uid(self):
293
        """Get the item's UID."""
294
        filename = os.path.basename(self.path)
295
        return UID(os.path.splitext(filename)[0])
296
297
    @property  # type: ignore
298
    @auto_load
299
    def level(self):
300
        """Get the item's level."""
301
        return self._data['level']
302
303
    @level.setter  # type: ignore
304
    @auto_save
305
    def level(self, value):
306
        """Set the item's level."""
307
        self._data['level'] = Level(value)
308
309
    @property
310
    def depth(self):
311
        """Get the item's heading order based on it's level."""
312
        return len(self.level)
313
314
    @property  # type: ignore
315
    @auto_load
316
    def active(self):
317
        """Get the item's active status.
318
319
        An inactive item will not be validated. Inactive items are
320
        intended to be used for:
321
322
        - future requirements
323
        - temporarily disabled requirements or tests
324
        - externally implemented requirements
325
        - etc.
326
327
        """
328
        return self._data['active']
329
330
    @active.setter  # type: ignore
331
    @auto_save
332
    def active(self, value):
333
        """Set the item's active status."""
334
        self._data['active'] = to_bool(value)
335
336
    @property  # type: ignore
337
    @auto_load
338
    def derived(self):
339
        """Get the item's derived status.
340
341
        A derived item does not have links to items in its parent
342
        document, but should still be linked to by items in its child
343
        documents.
344
345
        """
346
        return self._data['derived']
347
348
    @derived.setter  # type: ignore
349
    @auto_save
350
    def derived(self, value):
351
        """Set the item's derived status."""
352
        self._data['derived'] = to_bool(value)
353
354
    @property  # type: ignore
355
    @auto_load
356
    def normative(self):
357
        """Get the item's normative status.
358
359
        A non-normative item should not have or be linked to.
360
        Non-normative items are intended to be used for:
361
362
        - headings
363
        - comments
364
        - etc.
365
366
        """
367
        return self._data['normative']
368
369
    @normative.setter  # type: ignore
370
    @auto_save
371
    def normative(self, value):
372
        """Set the item's normative status."""
373
        self._data['normative'] = to_bool(value)
374
375
    @property
376
    def heading(self):
377
        """Indicate if the item is a heading.
378
379
        Headings have a level that ends in zero and are non-normative.
380
381
        """
382
        return self.level.heading and not self.normative
383
384
    @heading.setter  # type: ignore
385
    @auto_save
386
    def heading(self, value):
387
        """Set the item's heading status."""
388
        heading = to_bool(value)
389
        if heading and not self.heading:
390
            self.level.heading = True
391
            self.normative = False
392
        elif not heading and self.heading:
393
            self.level.heading = False
394
            self.normative = True
395
396
    @property  # type: ignore
397
    @auto_load
398
    def cleared(self):
399
        """Indicate if no links are suspect."""
400
        for uid, item in self._get_parent_uid_and_item():
401
            if uid.stamp != item.stamp():
402
                return False
403
        return True
404
405
    @property  # type: ignore
406
    @auto_load
407
    def reviewed(self):
408
        """Indicate if the item has been reviewed."""
409
        stamp = self.stamp(links=True)
410
        if self._data['reviewed'] == Stamp(True):
411
            self._data['reviewed'] = stamp
412
        return self._data['reviewed'] == stamp
413
414
    @reviewed.setter  # type: ignore
415
    @auto_save
416
    def reviewed(self, value):
417
        """Set the item's review status."""
418
        self._data['reviewed'] = Stamp(value)
419
420
    @property  # type: ignore
421
    @auto_load
422
    def text(self):
423
        """Get the item's text."""
424
        return self._data['text']
425
426
    @text.setter  # type: ignore
427
    @auto_save
428
    def text(self, value):
429
        """Set the item's text."""
430
        self._data['text'] = Text(value)
431
432
    @property  # type: ignore
433
    @auto_load
434
    def header(self):
435
        """Get the item's header."""
436
        if settings.ENABLE_HEADERS:
437
            return self._data['header']
438
        return None
439
440
    @header.setter  # type: ignore
441
    @auto_save
442
    def header(self, value):
443
        """Set the item's header."""
444
        if settings.ENABLE_HEADERS:
445
            self._data['header'] = Text(value)
446
447
    @property  # type: ignore
448
    @auto_load
449
    def ref(self):
450
        """Get the item's external file reference.
451
452
        An external reference can be part of a line in a text file or
453
        the filename of any type of file.
454
455
        """
456
        return self._data['ref']
457
458
    @ref.setter  # type: ignore
459
    @auto_save
460
    def ref(self, value):
461
        """Set the item's external file reference."""
462
        self._data['ref'] = str(value) if value else ""
463
464
    @property  # type: ignore
465
    @auto_load
466
    def references(self):
467
        """Get the item's external file references."""
468
        return self._data['references']
469
470
    @references.setter  # type: ignore
471
    @auto_save
472
    def references(self, value):
473
        """Set the item's external file references."""
474
        if value is not None:
475
            assert isinstance(value, list)
476
        self._data['references'] = value
477
478
    @property  # type: ignore
479
    @auto_load
480
    def links(self):
481
        """Get a list of the item UIDs this item links to."""
482
        return sorted(self._data['links'])
483
484
    @links.setter  # type: ignore
485
    @auto_save
486
    def links(self, value):
487
        """Set the list of item UIDs this item links to."""
488
        self._data['links'] = set(UID(v) for v in value)
489
490
    @property
491
    def parent_links(self):
492
        """Get a list of the item UIDs this item links to."""
493
        return self.links  # alias
494
495
    @parent_links.setter
496
    def parent_links(self, value):
497
        """Set the list of item UIDs this item links to."""
498
        self.links = value  # alias
499
500
    @requires_tree
501
    def _get_parent_uid_and_item(self):
502
        """Yield UID and item of all links of this item."""
503
        for uid in self.links:
504
            try:
505
                item = self.tree.find_item(uid)
506
            except DoorstopError:
507
                item = UnknownItem(uid)
508
                log.warning(item.exception)
509
            yield uid, item
510
511
    @property
512
    def parent_items(self):
513
        """Get a list of items that this item links to."""
514
        return [item for uid, item in self._get_parent_uid_and_item()]
515
516
    @property  # type: ignore
517
    @requires_tree
518
    def parent_documents(self):
519
        """Get a list of documents that this item's document should link to.
520
521
        .. note::
522
523
           A document only has one parent.
524
525
        """
526
        try:
527
            return [self.tree.find_document(self.document.prefix)]
528
        except DoorstopError:
529
            log.warning(Prefix.UNKNOWN_MESSAGE.format(self.document.prefix))
530
            return []
531
532
    # actions ################################################################
533
534
    @auto_save
535
    def set_attributes(self, attributes):
536
        """Set the item's attributes and save them."""
537
        self._set_attributes(attributes)
538
539
    def edit(self, tool=None, edit_all=True):
540
        """Open the item for editing.
541
542
        :param tool: path of alternate editor
543
        :param edit_all: True to edit the whole item,
544
            False to only edit the text.
545
546
        """
547
        # Lock the item
548
        if self.tree:
549
            self.tree.vcs.lock(self.path)
550
        # Edit the whole file in an editor
551
        if edit_all:
552
            self.save()
553
            editor.edit(self.path, tool=tool)
554
            self.load(True)
555
        # Edit only the text part in an editor
556
        else:
557
            # Edit the text in a temporary file
558
            edited_text = editor.edit_tmp_content(
559
                title=str(self.uid), original_content=str(self.text), tool=tool
560
            )
561
            # Save the text in the actual item file
562
            self.text = edited_text
563
564
    @auto_save
565
    def link(self, value):
566
        """Add a new link to another item UID.
567
568
        :param value: item or UID
569
570
        """
571
        uid = UID(value)
572
        log.info("linking to '{}'...".format(uid))
573
        self._data['links'].add(uid)
574
575
    @auto_save
576
    def unlink(self, value):
577
        """Remove an existing link by item UID.
578
579
        :param value: item or UID
580
581
        """
582
        uid = UID(value)
583
        try:
584
            self._data['links'].remove(uid)
585
        except KeyError:
586
            log.warning("link to {0} does not exist".format(uid))
587
588
    def is_reviewed(self):
589
        return self._data['reviewed']
590
591
    @requires_tree
592
    def find_ref(self):
593
        """Get the external file reference and line number.
594
595
        :raises: :class:`~doorstop.common.DoorstopError` when no
596
            reference is found
597
598
        :return: relative path to file or None (when no reference
599
            set),
600
            line number (when found in file) or None (when found as
601
            filename) or None (when no reference set)
602
603
        """
604
        # Return immediately if no external reference
605
        if not self.ref:
606
            log.debug("no external reference to search for")
607
            return None, None
608
        # Update the cache
609
        if not settings.CACHE_PATHS:
610
            pyficache.clear_file_cache()
611
        # Search for the external reference
612
        return self.reference_finder.find_ref(self.ref, self.tree, self.path)
613
614
    @requires_tree
615
    def find_references(self):
616
        """Get the array of references. Check each references before returning.
617
618
        :raises: :class:`~doorstop.common.DoorstopError` when no
619
            reference is found
620
621
        :return: Array of tuples:
622
            (
623
              relative path to file or None (when no reference set),
624
              line number (when found in file) or None (when found as
625
              filename) or None (when no reference set)
626
            )
627
628
        """
629
630
        if not self.references:
631
            log.debug("no external reference to search for")
632
            return []
633
        if not settings.CACHE_PATHS:
634
            pyficache.clear_file_cache()
635
636
        references = []
637
        for ref_item in self.references:
638
            path = ref_item["path"]
639
            keyword = ref_item["keyword"] if "keyword" in ref_item else None
640
641
            reference = self.reference_finder.find_file_reference(
642
                path, self.root, self.tree, path, keyword
643
            )
644
            references.append(reference)
645
        return references
646
647
    def find_child_links(self, find_all=True):
648
        """Get a list of item UIDs that link to this item (reverse links).
649
650
        :param find_all: find all items (not just the first) before returning
651
652
        :return: list of found item UIDs
653
654
        """
655
        items, _ = self.find_child_items_and_documents(find_all=find_all)
656
        identifiers = [item.uid for item in items]
657
        return identifiers
658
659
    child_links = property(find_child_links)
660
661
    def find_child_items(self, find_all=True):
662
        """Get a list of items that link to this item.
663
664
        :param find_all: find all items (not just the first) before returning
665
666
        :return: list of found items
667
668
        """
669
        items, _ = self.find_child_items_and_documents(find_all=find_all)
670
        return items
671
672
    child_items = property(find_child_items)
673
674
    def find_child_documents(self):
675
        """Get a list of documents that should link to this item's document.
676
677
        :return: list of found documents
678
679
        """
680
        _, documents = self.find_child_items_and_documents(find_all=False)
681
        return documents
682
683
    child_documents = property(find_child_documents)
684
685
    def find_child_items_and_documents(self, document=None, tree=None, find_all=True):
686
        """Get lists of child items and child documents.
687
688
        :param document: document containing the current item
689
        :param tree: tree containing the current item
690
        :param find_all: find all items (not just the first) before returning
691
692
        :return: list of found items, list of all child documents
693
694
        """
695
        child_items: List[Item] = []
696
        child_documents: List[Any] = []  # `List[Document]`` creats an import cycle
697
        document = document or self.document
698
        tree = tree or self.tree
699
        if not document or not tree:
700
            return child_items, child_documents
701
        # Find child objects
702
        log.debug("finding item {}'s child objects...".format(self))
703
        for document2 in tree:
704
            if document2.parent == document.prefix:
705
                child_documents.append(document2)
706
                # Search for child items unless we only need to find one
707
                if not child_items or find_all:
708
                    for item2 in document2:
709
                        if self.uid in item2.links:
710
                            if not item2.active:
711
                                item2 = UnknownItem(item2.uid)
712
                                log.warning(item2.exception)
713
                                child_items.append(item2)
714
                            else:
715
                                child_items.append(item2)
716
                                if not find_all and item2.active:
717
                                    break
718
        # Display found links
719
        if child_items:
720
            if find_all:
721
                joined = ', '.join(str(i) for i in child_items)
722
                msg = "child items: {}".format(joined)
723
            else:
724
                msg = "first child item: {}".format(child_items[0])
725
            log.debug(msg)
726
            joined = ', '.join(str(d) for d in child_documents)
727
            log.debug("child documents: {}".format(joined))
728
        return sorted(child_items), child_documents
729
730
    @auto_load
731
    def stamp(self, links=False):
732
        """Hash the item's key content for later comparison."""
733
        values = [self.uid, self.text, self.ref]
734
735
        if self.references:
736
            values.append(self.references)
737
738
        if links:
739
            values.extend(self.links)
740
        for key in self.document.extended_reviewed:
741
            if key in self._data:
742
                values.append(self._dump(self._data[key]))
743
            else:
744
                log.warning(
745
                    "{}: missing extended reviewed attribute: {}".format(self.uid, key)
746
                )
747
        return Stamp(*values)
748
749
    @auto_save
750
    def clear(self, parents=None):
751
        """Clear suspect links."""
752
        log.info("clearing suspect links...")
753
        for uid, item in self._get_parent_uid_and_item():
754
            if not parents or uid in parents:
755
                uid.stamp = item.stamp()
756
757
    @auto_save
758
    def review(self):
759
        """Mark the item as reviewed."""
760
        log.info("marking item as reviewed...")
761
        self._data['reviewed'] = self.stamp(links=True)
762
763
    @delete_item
764
    def delete(self, path=None):
765
        """Delete the item."""
766
767
768
class UnknownItem:
769
    """Represents an unknown item, which doesn't have a path."""
770
771
    UNKNOWN_PATH = '???'  # string to represent an unknown path
772
773
    normative = False  # do not include unknown items in traceability
774
    level = Item.DEFAULT_LEVEL
775
776
    def __init__(self, value, spec=Item):
777
        self._uid = UID(value)
778
        self._spec = dir(spec)  # list of attribute names for warnings
779
        msg = UID.UNKNOWN_MESSAGE.format(k='', u=self.uid)
780
        self.exception = DoorstopError(msg)
781
782
    def __str__(self):
783
        return Item.__str__(self)
784
785
    def __getattr__(self, name):
786
        if name in self._spec:
787
            log.debug(self.exception)
788
        return self.__getattribute__(name)
789
790
    def __lt__(self, other):
791
        return self.uid < other.uid
792
793
    @property
794
    def uid(self):
795
        """Get the item's UID."""
796
        return self._uid
797
798
    @property
799
    def relpath(self):
800
        """Get the unknown item's relative path string."""
801
        return "@{}{}".format(os.sep, self.UNKNOWN_PATH)
802
803
    def stamp(self):  # pylint: disable=R0201
804
        """Return an empty stamp."""
805
        return Stamp(None)
806