Completed
Push — develop ( cf43d3...e33935 )
by Jace
15s queued 10s
created

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

Complexity

Conditions 3

Size

Total Lines 10
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 3

Importance

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