Commit 9674812b34e360f6e28fb7fc808688313bf1c1f0
1 parent
6e4d5a71
Exists in
master
and in
68 other branches
ADD: next_copy_name function, for duplicating items
Showing
1 changed file
with
51 additions
and
0 deletions
Show diff stats
invesalius/utils.py
@@ -25,11 +25,62 @@ import sys | @@ -25,11 +25,62 @@ import sys | ||
25 | 25 | ||
26 | 26 | ||
27 | def debug(error_str): | 27 | def debug(error_str): |
28 | + """ | ||
29 | + Redirects output to file, or to the terminal | ||
30 | + This should be used in the place of "print" | ||
31 | + """ | ||
28 | from session import Session | 32 | from session import Session |
29 | session = Session() | 33 | session = Session() |
30 | if session.debug: | 34 | if session.debug: |
31 | print >> sys.stderr, error_str | 35 | print >> sys.stderr, error_str |
32 | 36 | ||
37 | +def next_copy_name(original_name, names_list): | ||
38 | + """ | ||
39 | + Given original_name of an item and a list of existing names, | ||
40 | + builds up the name of a copy, keeping the pattern: | ||
41 | + original_name | ||
42 | + original_name copy | ||
43 | + original_name copy#1 | ||
44 | + """ | ||
45 | + # is there only one copy, unnumbered? | ||
46 | + if original_name.endswith(" copy"): | ||
47 | + first_copy = original_name | ||
48 | + last_index = -1 | ||
49 | + else: | ||
50 | + parts = original_name.rpartition(" copy#") | ||
51 | + # is there any copy, might be numbered? | ||
52 | + if parts[0] and parts[-1]: | ||
53 | + # yes, lets check if it ends with a number | ||
54 | + if isinstance(eval(parts[-1]), int): | ||
55 | + last_index = int(parts[-1]) - 1 | ||
56 | + first_copy="%s copy"%parts[0] | ||
57 | + # no... well, so will build the copy name from zero | ||
58 | + else: | ||
59 | + last_index = -1 | ||
60 | + first_copy = "%s copy"%original_name | ||
61 | + # apparently this isthe new copy name, check it | ||
62 | + if not (first_copy in names_list): | ||
63 | + return first_copy | ||
64 | + | ||
65 | + else: | ||
66 | + # no, apparently there are no copies, as | ||
67 | + # separator was not found -- returned ("", " copy#", "") | ||
68 | + last_index = -1 | ||
69 | + first_copy = "%s copy"%original_name | ||
70 | + | ||
71 | + # apparently this isthe new copy name, check it | ||
72 | + if not (first_copy in names_list): | ||
73 | + return first_copy | ||
74 | + | ||
75 | + # lets build up the new name based on last pattern value | ||
76 | + got_new_name = False | ||
77 | + while not got_new_name: | ||
78 | + last_index += 1 | ||
79 | + next_copy = "%s#%d"%(first_copy, last_index+1) | ||
80 | + if not (next_copy in names_list): | ||
81 | + got_new_name = True | ||
82 | + return next_copy | ||
83 | + | ||
33 | 84 | ||
34 | #http://www.garyrobinson.net/2004/03/python_singleto.html | 85 | #http://www.garyrobinson.net/2004/03/python_singleto.html |
35 | # Gary Robinson | 86 | # Gary Robinson |