This file is indexed.

/usr/share/pyshared/DITrack/DB/Common.py is in ditrack 0.8-1.2.

This file is owned by root:root, with mode 0o644.

The actual contents of the file can be viewed below.

  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
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
#
# Common.py - common database classes and functions
#
# Copyright (c) 2006-2007 The DITrack Project, www.ditrack.org.
#
# $Id: Common.py 2439 2008-01-21 16:17:21Z gli $
# $HeadURL: https://svn.xiolabs.com/ditrack/src/tags/0.8/DITrack/DB/Common.py $
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
#  * Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
#  * Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
#

import copy
import os.path
import pprint
import re
import string
import errno
import shelve
import sys

# DITrack modules
import DITrack.DB.Configuration
import DITrack.DB.Issue
import DITrack.DB.Exceptions
import DITrack.DB.LMA
import DITrack.DB.WC
from DITrack.Logging import DEBUG, get_caller
import DITrack.SVN
import DITrack.ThirdParty.Python.string
import DITrack.Util.Locking

# Root database directory property containing format version.
VERSION_PROP = "ditrack:format"

# Current database format version.
FORMAT_VERSION = "4"

# File with database format version
DATABASE_VERSION_FILE = "format"

# Local modifications area directory and file name
LOCAL_DT_DIR = ".ditrack"

# Lock file
LOCK_FILE = "LOCK"

def next_entity_name(names):
    """
    Generates next entity name, given the set of existing ones.

    The sequence is A, B .. Z, AA, AB, .. AZ, BA, BB, ... ZZ
    """

    if names:
        names = copy.copy(names)
        names.sort()
        prev = names[-1]
    else:
        return "A"

    assert(len(prev))

    res = ""
    carry = True
    for c in prev[::-1]:
        assert(c >= "A")
        assert(c <= "Z")

        was_carry = carry
        carry = False

        if was_carry:
            if c == "Z":
                res = "A" + res
                carry = True
            else:
                res = chr(ord(c) + 1) + res
        else:
            res = c + res

    if carry:
        res = "A" + res

    return res

def open_local_dt_shelve(path, filename):
    """
    Opens a shelve in local DITrack directory (LOCAL_DT_DIR) which is created
    as needed. The name of the shelve to open is passed in FILENAME. Returns
    the shelve handle.
    """

    datadir = os.path.join(path, LOCAL_DT_DIR)

    if not os.path.exists(datadir):
        os.mkdir(datadir, 0755)

    return shelve.open(os.path.join(datadir, filename))

#
# Classes
#

class Database:
    """
    Class representing complete database object.
    """

    def __init__(self, path, username, svn_path, mode="r", timeout=0):
        """
        XXX: rework this description, document the 'timeout' parameter.

        Opens a DITrack database at PATH. USERNAME is a username which is used
        to expand variables in filter definitions. SVN_PATH is a path to the
        Subversion command line client executable. MODE is the open mode,
        either "r" (for read-only operations) or "w" (for modifications).

        May raise the following exceptions:

        DITrack.DB.Exceptions.InvalidVersionError
            Invalid database format version.

        DITrack.DB.Exceptions.NotDatabaseError
            The directory pointed to by PATH doesn't look like a DITrack
            database.

        DITrack.DB.Exceptions.NotDirectoryError
            The PATH is not a directory.
        """

        self.lock = None
        assert (mode == "r") or (mode == "w"), mode

        # Check that it's a directory.
        if not os.path.isdir(path):
            raise DITrack.DB.Exceptions.NotDirectoryError

        # Get database version
        try:
            v = open(os.path.join(path, DATABASE_VERSION_FILE), 
                "r").readline().split()[0]
        except IOError:
            v = None

        if not v or not len(v):
            raise DITrack.DB.Exceptions.NotDatabaseError

        # Check if this is supported version.
        if v != FORMAT_VERSION:
            raise DITrack.DB.Exceptions.InvalidVersionError

        # Creating local ditrack dir
        datadir = os.path.join(path, LOCAL_DT_DIR)
        if not os.path.exists(datadir):
            os.mkdir(datadir, 0755)

        # Lock database
        try:
            self.lock = DITrack.Util.Locking.lock(
                open(os.path.join(path, LOCAL_DT_DIR, LOCK_FILE), "w"),
                mode, timeout)
        except DITrack.Util.Locking.FileIsLockedError:
            raise DITrack.DB.Exceptions.DBIsLockedError

        # Read up the configuration.
        self.cfg = DITrack.DB.Configuration.Configuration(path, username)

        if mode != "r":
            if username not in self.cfg.users:
                raise DITrack.DB.Exceptions.InvalidUserError

        # Set up local modifications area.
        self.lma = DITrack.DB.LMA.LocalModsArea(path)

        # Working copy interface.
        self.wc = DITrack.DB.WC.WorkingCopy(path, svn_path)

    def __getitem__(self, key):
        """
        Return an issue by KEY (string id). Raises KeyError is the issue is
        neither in the WC, nor in the LMA.
        """

        # XXX: make sure the key is a string.

        DEBUG("Retrieving issue '%s' (called from %s)" % (key, get_caller()))

        try:
            issue = self.wc[key]
        except KeyError:
            issue = None

        local = None

        try:
            local = self.lma[key]
        except KeyError:
            if not issue:
                raise

        assert(issue or local)

        if issue:
            if local:
                issue.merge_local_comments(local)
                issue.update_info()
        else:
            issue = local

        return issue

    def commit_comment(self, issue_number, comment_name):
        """
        Commits comment COMMENT_NAME of issue ISSUE_NUMBER from the LMA. An
        assertion will fail if the ISSUE_NUMBER is not a firm one. Returns
        simple newly assigned comment number as a string.
        """

        DEBUG("Committing comment '%s' of issue '%s' (called from %s)" %
            (comment_name, issue_number, get_caller()))

        # XXX: use is_valid_*()
        assert issue_number.isdigit()

        lma_issue = self.lma[issue_number]
        comment = lma_issue[comment_name]

        number, changes = self.wc.new_comment(issue_number, comment)

        # XXX: if the commit has failed, we need to revert the changes back.
        self.wc.commit(changes, "i#%s: %s\n%s" %
            (issue_number, self.wc[issue_number].info["Title"],
            comment.logmsg))

        # Now, when the changes are committed, remove the comment from the LMA.
        self.lma.remove_comment(issue_number, comment_name)

        return number

    def commit_issue(self, name):
        """
        Commits issue NAME from LMA. Returns newly assigned issue number.
        """

        DEBUG("Committing issue '%s' (called from %s)" % (name, get_caller()))

        for x in name:
            assert(x in string.uppercase)

        issue = self.lma[name]
        number, changes = self.wc.new_issue(issue)

        # XXX: if the commit has failed, we need to revert the changes back.
        self.wc.commit(
            changes, 
            "i#%d added: %s\n" 
            "(assigned to %s, due in %s)" % (
                number, issue.info["Title"], issue.info["Owned-by"], 
                issue.info["Due-in"]
            )
        )

        # Now, when the changes are committed, remove the issue from the LMA.
        self.lma.remove_issue(name)

        return number

    def issue_by_id(self, id, err=True):
        """
        Fetches an issue by ID from the database, checking if 1) the identifier
        is valid; 2) the issue actually exists. If either of these checks
        fails, raises DITrack.DB.Exceptions.IssueIdSyntaxError or KeyError
        respectively. If ERR is true, prints out diagnostics before raising the
        exception.
        """

        if not self.is_valid_issue_id(id):
            if err:
                DITrack.Util.common.err("Invalid identifier: '%s'" % id)
            raise DITrack.DB.Exceptions.IssueIdSyntaxError, id

        try:
            issue = self[id]
        except KeyError:
            if err:
                DITrack.Util.common.err("No such entity: '%s'" % id)
            raise KeyError, id

        return issue

    def issues(self, from_wc=True, from_lma=True):
        """
        Return a list of tuples (ID, ISSUE) for issues present in the database.

        Issues from working copy and LMA are included as prescribed by FROM_WC
        and FROM_LMA parameters respectively. The list returned is sorted. All
        WC issues precede LMA issues.
        """

        DEBUG("from_wc=%s, from_lma=%s" % (from_wc, from_lma))

        res = {}
        if from_wc:
            for id, issue in self.wc.issues():
                res[id] = issue

        DEBUG("Firm issues: %s" % pprint.pformat(res))
        if from_lma:
            for id, issue in self.lma.issues():
                DEBUG("LMA issue entity: %s" % pprint.pformat(id))
                if self.is_valid_issue_name(id):
                    # It's a local issue, just store it.
                    res[id] = issue
                else:

                    # We are asked to return local issues only, don't bother
                    # merging comments to firm ones.
                    if not from_wc:
                        continue

                    # It's a local comment to a firm issue. We need to merge
                    # issue headers.
                    id = int(id)
                    assert id in res, pprint.pformat(id)

                    DEBUG("Merging local comments for issue '%s'" % id)
                    res[id].merge_local_comments(issue)
                    res[id].update_info()

        keys = res.keys()
        keys.sort()
        return [(k, res[k]) for k in keys]

    def is_valid_issue_number(self, id):

        issue_number_re = re.compile("^\\d+$")
        if issue_number_re.match(id):
            return int(id) != 0
        else:
            return False

    def is_valid_issue_name(self, id):
        """
        XXX: rename into valid_simple_name()
        XXX: move out of the class

        Checks if the ID passed is a syntactically valid simple entity name.

        'Simple' means 'not compound', e.g. "A" is simple, "A.B" is not.
        """

        issue_name_re = re.compile("^[A-Z]+$")
        return issue_name_re.match(id)

    def is_valid_issue_id(self, id):
        """
        Checks if the passed identifier ID is a syntactically correct
        identifier (i.e. a valid number or name).
        """

        return self.is_valid_issue_number(id) or self.is_valid_issue_name(id)

    def lma_issues(self, firm=True, local=True):
        """
        Returns a list of tuples (ID, ISSUE) for all issue entities present
        in the LMA. The FIRM and LOCAL parameters control which kind of issues
        to include into the resulting list (either FIRM or LOCAL should be
        True; or both). The returned list is sorted, firm issues always precede
        local ones.
        """

        assert (firm or local), "firm=%s, local=%s" % (firm, local)

        return self.lma.issues(firm=firm, local=local)

    def new_comment(self, issue_num, issue_before, issue_after, text, added_by,
        added_on):
        """
        Add a new comment reflecting the change in issue ISSUE_NUM from
        ISSUE_BEFORE to ISSUE_AFTER with specified TEXT to the LMA. Returns
        tuple (NAME, COMMENT). ADDED_BY and ADDED_ON are the comment's author
        and addition date respectively.

        If there is no difference and the TEXT passed is empty, raises
        DITrack.DB.Exceptions.NoDifferenceCondition.

        XXX: reflect attachments logic
        """

        delta = issue_before.diff(issue_after)
        attachment_delta = issue_before.diff_attachments(issue_after)

        if (not delta) and (not text) and (not attachment_delta):
            raise DITrack.DB.Exceptions.NoDifferenceCondition

        delta_map = {}
        for h, o, n in delta:
            delta_map[h] = (o, n)

        logmsg = []

        for (name, (old_value, new_value)) in delta_map.iteritems():
            if name == "Status":
                if new_value == "closed":
                    s = "closed"
                    if "Resolution" in delta_map:
                        s += " as %s" % delta_map["Resolution"][1]
                    logmsg.append(s)
                elif new_value == "open":
                    logmsg.append("reopened")

            elif name == "Owned-by":
                logmsg.append("reassigned to %s" % new_value)

            elif name == "Due-in":
                logmsg.append("moved to %s" % new_value)

            elif name == "Resolution":
                # Used in "Status" condition.
                continue  
            elif name == "Attachments":
                # Handled below (see attachment_delta).
                continue 

            else:
                if old_value is None:
                    old_value = ""
                if new_value is None:
                    new_value = ""
                logmsg.append("headers changed: '%s': '%s' -> '%s'" %
                        (name, old_value, new_value))



        if attachment_delta:
            for action in ("added", "removed"):
                if (action in attachment_delta) and attachment_delta[action]:
                    logmsg.append(
                        "attachment(s) %s: %s"
                        % (
                            action,
                            ", ".join(
                                map(
                                    lambda x: x.name,
                                    attachment_delta[action]
                                )
                            )
                        )
                    )

        logmsg_str = "".join ([" * %s\n" % k for k in logmsg])

        if len(text):
            logmsg_str += "\n%s\n" % text

        comment = DITrack.DB.Issue.Comment.create(text, added_on=added_on,
            added_by=added_by, delta=delta, logmsg=logmsg_str,
            attachment_delta=attachment_delta)

        name = self.lma.new_comment(issue_num, comment)

        return name, comment

    def new_issue(self, title, opened_by, opened_on, owned_by, category,
        version_reported, version_due, description):
        """
        Add a new issue to LMA of the database.

        Returns tuple (name, issue), where NAME is newly assigned name and
        ISSUE is newly created issue object.
        """

        if not owned_by:
            owned_by = self.cfg.category[category].default_owner

        issue = DITrack.DB.Issue.Issue.create(
            title=title,
            opened_by=opened_by,
            opened_on=opened_on,
            owned_by=owned_by,
            category=category,
            version_reported=version_reported,
            version_due=version_due,
            description=description
            )

        name = self.lma.new_issue(issue)

        return name, issue

    def remove_comment(self, issue_id, comment_name):
        """
        Removes local comment from the database (e.g. from the LMA).

        ValueError is raised if the ISSUE_ID is not a syntactically valid
        issue number of if COMMENT_NAME is not a syntactically valid name.

        The COMMENT_NAME parameter should refer to an existing LMA entity
        (e.g. a comment of an existing issue), otherwise KeyError is raised.
        """

        if not self.is_valid_issue_id(issue_id):
            raise ValueError

        if not self.is_valid_issue_name(comment_name):
            raise ValueError

        if not issue_id in self.lma:
            raise KeyError

        # XXX: check that KeyError will be raised if COMMENT_NAME is not
        # contained in the LMA issue
        self.lma.remove_comment(issue_id, comment_name)

    def update(self, maxage=None):
        """
        Update the working copy (sync from the repository).

        If MAXAGE is None, update the database. If the database was updated
        more than MAXAGE seconds back, update the database. Otherwise return
        taking no action.

        XXX: return values are described in WC.update()
        """
        return self.wc.update(maxage)

class Filter:
    def __init__(self, str, username=None):
        """
        Initialize the filter by parsing string expression STR. USERNAME is
        the user name to be set as the value for 'DT:USER' variable.
        """

        # Remember the way the filter was defined
        self._expression = str

        # Is it a predefined filter name?
        inplace_re = re.compile("[,=]")

        if not inplace_re.search(str):
            # This looks like a predefined filter name
            raise DITrack.DB.Exceptions.FilterIsPredefinedError(str)

        vars = dict(os.environ)
        if username is not None:
            vars["DT:USER"] = username

        # Split into subclauses.
        clauses = filter(lambda x: len(x), str.split(","))

        self.conditions = []
        condition_re = re.compile(
            "^(?P<param>[^!=]*)(?P<condition>!?=)(?P<value>.*)$"
        )

        for c in clauses:
            m = condition_re.match(c)
            if not m:
                raise DITrack.DB.Exceptions.FilterExpressionError(c)

            condition = m.groupdict()

            if len(condition) != 3:
                raise DITrack.DB.Exceptions.FilterExpressionError(c)

            if condition['value'] == '""' or condition['value'] == "''":
                condition['value'] = ""
            # Perform substitutions.
            t = DITrack.ThirdParty.Python.string.Template(condition['value'])
            try:
                condition['value'] = t.substitute(vars)
            except KeyError, var:
               sys.stderr.write(
                   "Warning. Unknown variable in filters: %s\n" % var)
               condition['value'] = t.safe_substitute(vars)

            self.conditions.append(condition)


    def __str__(self):
        return self._expression

    def matches(self, issue):
        for c in self.conditions:
            assert len(c) == 3

            if c['param'] not in issue.info:
                if c['value'] != "":
                    return False
                else:
                    info_value = ""
            else:
                info_value = issue.info[c['param']]

            if c['condition'] == "=":
                if info_value != c['value']:
                    return False
            elif c['condition'] == "!=":
                if info_value == c['value']:
                    return False
            else:
                raise DITrack.DB.Exceptions.NotImplemented, c['condition']

        return True