Debian Codegraph @

cylc/flow/id.py

raw
1 # THIS FILE IS PART OF THE CYLC WORKFLOW ENGINE.
2 # Copyright (C) NIWA & British Crown (Met Office) & Contributors.
3 #
4 # This program is free software: you can redistribute it and/or modify
5 # it under the terms of the GNU General Public License as published by
6 # the Free Software Foundation, either version 3 of the License, or
7 # (at your option) any later version.
8 #
9 # This program is distributed in the hope that it will be useful,
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 # GNU General Public License for more details.
13 #
14 # You should have received a copy of the GNU General Public License
15 # along with this program. If not, see <http://www.gnu.org/licenses/>.
16
17 """Cylc univeral identifier system for referencing Cylc "objects".
18
19 This module contains the abstract ID tokenising/detokenising code.
20 """
21
22 from enum import Enum
23 import re
24 from typing import (
25 TYPE_CHECKING,
26 Any,
27 Iterable,
28 List,
29 Literal,
30 Optional,
31 Set,
32 Tuple,
33 Union,
34 cast,
35 overload,
36 )
37
38 from cylc.flow import LOG
39
40
41 if TYPE_CHECKING:
42 from cylc.flow.cycling import PointBase
43
44
45 class IDTokens(Enum):
46 """Cylc object identifier tokens."""
47
48 User = 'user'
49 Workflow = 'workflow'
50 Cycle = 'cycle'
51 Task = 'task'
52 Job = 'job'
53
54
55 class Tokens(dict):
56 """A parsed representation of a Cylc universal identifier (UID).
57
58 Examples:
59 Parse tokens:
60 >>> tokens = Tokens('~u/w//c/t/01')
61 >>> tokens
62 <id: ~u/w//c/t/01>
63
64 Parse back to a string ID:
65 >>> tokens.id
66 '~u/w//c/t/01'
67 >>> tokens.workflow_id
68 '~u/w'
69 >>> tokens.relative_id
70 'c/t/01'
71
72 Inspect the tokens:
73 >>> tokens['user']
74 'u'
75 >>> tokens['task']
76 't'
77 >>> tokens['task_sel'] # task selector
78 >>> list(tokens.values()) # Note the None values are selectors
79 ['u', 'w', None, 'c', None, 't', None, '01', None]
80
81 Construct tokens:
82 >>> Tokens(workflow='w', cycle='c')
83 <id: w//c>
84 >>> Tokens(workflow='w', cycle='c')['job']
85
86 # Make a copy (note Tokens are immutable):
87 >>> tokens.duplicate()
88 <id: ~u/w//c/t/01>
89 >>> tokens.duplicate(job='02') # make changes at the same time
90 <id: ~u/w//c/t/02>
91
92 """
93 _REGULAR_KEYS: Set[str] = {token.value for token in IDTokens}
94 _SELECTOR_KEYS = {
95 f'{token.value}_sel'
96 for token in IDTokens
97 if token != IDTokens.User
98 }
99
100 # all valid dictionary keys
101 _KEYS = _REGULAR_KEYS | _SELECTOR_KEYS
102
103 _TASK_LIKE_KEYS = {
104 key for key in _KEYS if not (
105 key.startswith(IDTokens.User.value)
106 or key.startswith(IDTokens.Workflow.value)
107 )
108 }
109
110 def __init__(
111 self,
112 *args: 'Union[str, Tokens]',
113 relative: bool = False,
114 **kwargs: Optional[str]
115 ):
116 if args:
117 if len(args) > 1:
118 raise ValueError()
119 if isinstance(args[0], str):
120 kwargs = tokenise(args[0], relative)
121 else:
122 kwargs = dict(args[0])
123 else:
124 for key in kwargs:
125 if key not in self._KEYS:
126 raise ValueError(f'Invalid token: {key}')
127 dict.__init__(self, **kwargs)
128
129 def __setitem__(self, key, value):
130 raise Exception('Tokens objects are not mutable')
131
132 def update(self, other):
133 raise Exception('Tokens objects are not mutable')
134
135 def __getitem__(self, key):
136 try:
137 return dict.__getitem__(self, key)
138 except KeyError:
139 if key not in self._KEYS:
140 raise ValueError(f'Invalid token: {key}') from None
141 return None
142
143 def __str__(self):
144 return self.id
145
146 def __repr__(self):
147 """Python internal representation.
148
149 Examples:
150 >>> Tokens('a//1')
151 <id: a//1>
152 >>> Tokens('//1', relative=True)
153 <id: //1>
154 >>> Tokens()
155 <id: >
156
157 """
158 if self.is_null:
159 id_ = ''
160 else:
161 id_ = self.id
162 return f'<id: {id_}>'
163
164 def __hash__(self):
165 # generate the __hash__ from the non None items in the dictionary
166 return hash(tuple(sorted(((k, v) for k, v in self.items() if v))))
167
168 def __eq__(self, other):
169 if not isinstance(other, Tokens):
170 return False
171 return all(
172 self[key] == other[key]
173 for key in self._KEYS
174 )
175
176 def __lt__(self, other):
177 return self.id < other.id
178
179 def __gt__(self, other):
180 return self.id > other.id
181
182 def __ne__(self, other):
183 if not isinstance(other, Tokens):
184 return True
185 return any(
186 self[key] != other[key]
187 for key in self._KEYS
188 )
189
190 @property # noqa A003 (not shadowing id built-in)
191 def id(self) -> str: # noqa A003 (not shadowing id built-in)
192 """The full ID these tokens represent.
193
194 Examples:
195 >>> Tokens('~u/w//c/t/01').id
196 '~u/w//c/t/01'
197 >>> Tokens().id
198 Traceback (most recent call last):
199 ValueError: No tokens provided
200
201 """
202 return detokenise(self)
203
204 @property
205 def relative_id(self) -> str:
206 """The relative ID (without the workflow part).
207
208 Examples:
209 >>> Tokens('~u/w//c/t/01').relative_id
210 'c/t/01'
211 >>> Tokens('~u/w').relative_id
212 Traceback (most recent call last):
213 ValueError: No tokens provided
214
215 """
216 return detokenise(self.task, relative=True)
217
218 @property
219 def relative_id_with_selectors(self) -> str:
220 """The relative ID (without the workflow part), with selectors.
221
222 Examples:
223 >>> Tokens('~u/w//c/t:failed/01').relative_id
224 'c/t/01'
225 >>> Tokens('~u/w//c/t:failed/01').relative_id_with_selectors
226 'c/t:failed/01'
227
228 """
229 return detokenise(self.task, relative=True, selectors=True)
230
231 @property
232 def workflow_id(self) -> str:
233 """The workflow id (without the relative part).
234
235 Examples:
236 >>> Tokens('~u/w//c/t/01').workflow_id
237 '~u/w'
238 >>> Tokens('c/t/01', relative=True).workflow_id
239 Traceback (most recent call last):
240 ValueError: No tokens provided
241
242 """
243 return detokenise(self.workflow)
244
245 @property
246 def lowest_token(self) -> str:
247 """Return the lowest token present in a tokens dictionary.
248
249 Examples:
250 >>> Tokens('~u/w//c/t/01').lowest_token
251 'job'
252 >>> Tokens('~u/w//c/t').lowest_token
253 'task'
254 >>> Tokens('~u/w//c').lowest_token
255 'cycle'
256 >>> Tokens('~u/w//').lowest_token
257 'workflow'
258 >>> Tokens('~u').lowest_token
259 'user'
260 >>> Tokens().lowest_token({})
261 Traceback (most recent call last):
262 ValueError: No tokens defined
263
264 """
265 for token in reversed(IDTokens):
266 if token.value in self and self[token.value]:
267 return token.value
268 raise ValueError('No tokens defined')
269
270 def pop_token(self) -> Tuple[str, str]:
271 """Pop the lowest token.
272
273 Examples:
274 >>> tokens = Tokens('~u/w//c/t/01')
275 >>> tokens.pop_token()
276 ('job', '01')
277 >>> tokens.pop_token()
278 ('task', 't')
279 >>> tokens.pop_token()
280 ('cycle', 'c')
281 >>> tokens.pop_token()
282 ('workflow', 'w')
283 >>> tokens.pop_token()
284 ('user', 'u')
285 >>> tokens
286 <id: >
287 >>> tokens.pop_token()
288 Traceback (most recent call last):
289 KeyError: 'No defined tokens.'
290
291 """
292 for token in reversed(IDTokens):
293 token_name = token.value
294 value = self[token_name]
295 if value:
296 self.pop(token_name)
297 return (token_name, value)
298 raise KeyError('No defined tokens.')
299
300 @property
301 def is_task_like(self) -> bool:
302 """Returns True if any task-like objects are present in the ID.
303
304 Task like == cycles or tasks or jobs.
305
306 Examples:
307 >>> Tokens('workflow//').is_task_like
308 False
309 >>> Tokens('workflow//1').is_task_like
310 True
311
312 """
313 return any(
314 self[key] for key in self._TASK_LIKE_KEYS
315 )
316
317 @property
318 def task(self) -> 'Tokens':
319 """The task portion of the tokens.
320
321 Examples:
322 >>> Tokens('~user/workflow//cycle/task/01').task
323 <id: //cycle/task/01>
324
325 """
326 return Tokens(
327 **{
328 key: value
329 for key, value in self.items()
330 if key in self._TASK_LIKE_KEYS
331 }
332 )
333
334 @property
335 def workflow(self) -> 'Tokens':
336 """The workflow portion of the tokens.
337
338 Examples:
339 >>> Tokens('~user/workflow//cycle/task/01').workflow
340 <id: ~user/workflow>
341
342 """
343 return Tokens(
344 **{
345 key: value
346 for key, value in self.items()
347 if key not in self._TASK_LIKE_KEYS
348 }
349 )
350
351 @property
352 def is_null(self) -> bool:
353 """Returns True if no tokens are set.
354
355 Examples:
356 >>> tokens = Tokens()
357 >>> tokens.is_null
358 True
359 >>> tokens.duplicate(job_sel='x').is_null
360 True
361 >>> tokens.duplicate(job='01').is_null
362 False
363
364 """
365 return not any(
366 self[key] for key in self._REGULAR_KEYS
367 )
368
369 @property
370 def submit_num(self) -> int | None:
371 """The job submit number as an integer, or None if not set.
372
373 Examples:
374 >>> Tokens('//c/t/01').submit_num
375 1
376 >>> Tokens('//c/t').submit_num is None
377 True
378 """
379 return int(self['job']) if self['job'] else None
380
381 @overload
382 def duplicate(
383 self,
384 *,
385 cycle: str,
386 task: str,
387 **kwargs,
388 ) -> 'TaskTokens':
389 ...
390
391 @overload
392 def duplicate(
393 self,
394 *tokens_list: 'Tokens',
395 **kwargs,
396 ) -> 'Tokens':
397 ...
398
399 def duplicate(
400 self,
401 *tokens_list: 'Tokens',
402 **kwargs,
403 ) -> 'Tokens':
404 """Duplicate a tokens object.
405
406 Can be used to change the values of the new object at the same time.
407
408 Examples:
409 Duplicate tokens:
410 >>> tokens1 = Tokens('~u/w')
411 >>> tokens2 = tokens1.duplicate()
412
413 The copy is equal but a different object:
414 >>> tokens1 == tokens2
415 True
416 >>> id(tokens1) == id(tokens2)
417 False
418
419 Make a copy with a modification:
420 >>> tokens1.duplicate(cycle='1').id
421 '~u/w//1'
422
423 The Original is not changed:
424 >>> tokens1.id
425 '~u/w'
426
427 Arguments override in definition order:
428 >>> Tokens.duplicate(
429 ... tokens1,
430 ... Tokens(cycle='c', task='a', job='01'),
431 ... task='b'
432 ... ).id
433 '~u/w//c/b/01'
434
435 """
436 _kwargs: dict[str, Any] = {}
437 for tokens in (self, *tokens_list):
438 _kwargs.update(tokens)
439 _kwargs.update(kwargs)
440 return Tokens(**_kwargs)
441
442
443 class TaskTokens(Tokens):
444 """A Tokens object where the cycle and task are compulsory."""
445
446 def __init__(self, cycle: str, task: str, **kwargs):
447 Tokens.__init__(self, cycle=cycle, task=task, **kwargs)
448
449 @overload
450 def __getitem__(self, key: "Literal['cycle']") -> str:
451 ...
452
453 @overload
454 def __getitem__(self, key: "Literal['task']") -> str:
455 ...
456
457 def __getitem__(self, key: str) -> Optional[str]:
458 return Tokens.__getitem__(self, key)
459
460 def duplicate(self, *tokens_list, **kwargs) -> 'TaskTokens':
461 return cast(
462 'TaskTokens', Tokens.duplicate(self, *tokens_list, **kwargs)
463 )
464
465 @property
466 def task(self) -> 'TaskTokens':
467 return cast('TaskTokens', Tokens.task.fget(self)) # type: ignore
468
469 @property
470 def is_task_like(self) -> 'Literal[True]':
471 return True
472
473
474 # //cycle[:sel][/task[:sel][/job[:sel]]]
475 RELATIVE_PATTERN = rf'''
476 //
477 (?P<{IDTokens.Cycle.value}>[^~\/:\n][^~\/\n]*?)
478 (?:
479 :
480 (?P<{IDTokens.Cycle.value}_sel>[^\/:\n]+)
481 )?
482 (?:
483 /
484 (?:
485 (?P<{IDTokens.Task.value}>[^\/:\n]+)
486 (?:
487 :
488 (?P<{IDTokens.Task.value}_sel>[^\/:\n]+)
489 )?
490 (?:
491 /
492 (?:
493 (?P<{IDTokens.Job.value}>[^\/:\n]+)
494 (?:
495 :
496 (?P<{IDTokens.Job.value}_sel>[^\/:\n]+)
497 )?
498 )?
499 )?
500 )?
501 )?
502 '''
503
504 RELATIVE_ID = re.compile(
505 r'^' + RELATIVE_PATTERN + r'$',
506 re.X
507 )
508
509 # ~user[/workflow[:sel][//cycle[:sel][/task[:sel][/job[:sel]]]]]
510 UNIVERSAL_ID = re.compile(
511 rf'''
512 # don't match an empty string
513 (?=.)
514 # either match a user or the start of the line
515 (?:
516 (?:
517 ~
518 (?P<{IDTokens.User.value}>[^\/:\n~]+)
519 # allow the match to end here
520 (\/|$)
521 )
522 |^
523 )
524 (?:
525 (?P<{IDTokens.Workflow.value}>
526 # can't begin with //
527 (?!//)
528 # workflow ID (flat)
529 [^:~\n\/]+
530 # workflow ID (hierarchical)
531 (?:
532 (?:
533 \/
534 [^:~\n\/]+
535 )+
536 )?
537
538 )
539 (?:
540 :
541 (?P<{IDTokens.Workflow.value}_sel>[^\/:\n]+)
542 )?
543 (?:
544 (?:
545 # can't end ///
546 //(?!/)
547 )?
548 (?:
549 # cycle/task/job
550 {RELATIVE_PATTERN}
551 )?
552 )?
553 )?
554 $
555 ''',
556 re.X
557 )
558
559 # task.cycle[:sel]
560 LEGACY_TASK_DOT_CYCLE = re.compile(
561 rf'''
562 ^
563 # NOTE: task names can contain "."
564 (?P<{IDTokens.Task.value}>[^~\:\/\n]+)
565 \.
566 # NOTE: legacy cycles always start with a number
567 (?P<{IDTokens.Cycle.value}>\d[^~\.\:\/\n]*)
568 # NOTE: the task selector applied to the cycle in this legacy format
569 # (not a mistake)
570 (?:
571 :
572 (?P<{IDTokens.Task.value}_sel>[^\:\/\n]+)
573 )?
574 $
575 ''',
576 re.X
577 )
578
579 # cycle/task[:sel]
580 LEGACY_CYCLE_SLASH_TASK = re.compile(
581 rf'''
582 ^
583 # NOTE: legacy cycles always start with a number
584 (?P<{IDTokens.Cycle.value}>\d[^~\.\:\/\n]+)
585 \/
586 # NOTE: task names can contain "."
587 (?P<{IDTokens.Task.value}>[^~\:\/\n]+)
588 (?:
589 :
590 (?P<{IDTokens.Task.value}_sel>[^\:\/\n]+)
591 )?
592 $
593 ''',
594 re.X
595 )
596
597
598 def quick_relative_id(
599 cycle: Union[str, int, 'PointBase'],
600 task: str,
601 task_sel: Optional[str] = None
602 ) -> str:
603 """Generate a relative ID for a task, with optional selector.
604
605 This is a more efficient solution to `Tokens` for cases where
606 you only want the ID string and don't have any use for a Tokens object.
607
608 Example:
609 >>> q = quick_relative_id
610 >>> q('1', 'a') == Tokens(cycle='1', task='a').relative_id
611 True
612
613 >>> q('1', 'a', 'succeeded')
614 '1/a:succeeded'
615
616 >>> q('1', 'a', 'succeeded') == (
617 ... detokenise(
618 ... Tokens(cycle='1', task='a', task_sel="succeeded"),
619 ... selectors=True,
620 ... relative=True
621 ... )
622 ... )
623 True
624
625 """
626 if task_sel is None:
627 return f'{cycle}/{task}'
628 else:
629 return f'{cycle}/{task}:{task_sel}'
630
631
632 def _dict_strip(dictionary):
633 """Run str.strip against dictionary values.
634
635 Examples:
636 >>> _dict_strip({'a': ' x ', 'b': 'x', 'c': None})
637 {'a': 'x', 'b': 'x', 'c': None}
638
639 """
640 return {
641 key: value.strip() if value else None
642 for key, value in dictionary.items()
643 }
644
645
646 def legacy_tokenise(identifier: str) -> Tokens:
647 """Convert a legacy string identifier into Cylc tokens.
648
649 Supports the two legacy Cylc7 formats:
650
651 * task.cycle[:task_status]
652 * cycle/task[:task_status]
653
654 Args:
655 identifier (str):
656 The namespace to tokenise.
657
658 Returns:
659 dict - {token: value}
660
661 Warning:
662 The tokenise() function will parse a legacy token as a Workflow.
663
664 Raises:
665 ValueError:
666 For invalid identifiers.
667
668 Examples:
669 # task.cycle[:task_status]
670 >>> legacy_tokenise('task.123')
671 {'task': 'task', 'cycle': '123', 'task_sel': None}
672 >>> legacy_tokenise('task.123:task_sel')
673 {'task': 'task', 'cycle': '123', 'task_sel': 'task_sel'}
674
675 # cylc/task[:task_status]
676 >>> legacy_tokenise('123/task')
677 {'cycle': '123', 'task': 'task', 'task_sel': None}
678 >>> legacy_tokenise('123/task:task_sel')
679 {'cycle': '123', 'task': 'task', 'task_sel': 'task_sel'}
680
681 """
682 for pattern in (
683 LEGACY_TASK_DOT_CYCLE,
684 LEGACY_CYCLE_SLASH_TASK
685 ):
686 match = pattern.match(identifier)
687 if match:
688 return _dict_strip(match.groupdict())
689 raise ValueError(f'Invalid legacy Cylc identifier: {identifier}')
690
691
692 def tokenise(
693 identifier: str,
694 relative: bool = False,
695 ) -> Tokens:
696 """Convert a string identifier into Cylc tokens.
697
698 Args:
699 identifier (str):
700 The namespace to tokenise.
701 relative (bool):
702 If True the prefix // is implicit if omitted.
703
704 Returns:
705 dict - {token: value}
706
707 Warning:
708 Will parse a legacy (task and or cycle) token as a Workflow.
709
710 Raises:
711 ValueError:
712 For invalid identifiers.
713
714 Examples:
715 # absolute identifiers
716 >>> tokenise(
717 ... '~user/workflow:workflow_sel//'
718 ... 'cycle:cycle_sel/task:task_sel/01:job_sel'
719 ... ) # doctest: +NORMALIZE_WHITESPACE
720 <id: ~user/workflow//cycle/task/01>
721
722 >>> def _(tokens):
723 ... return {
724 ... token: value for token, value in tokens.items() if value}
725
726 # "full" identifiers
727 >>> _(tokenise('workflow//cycle'))
728 {'workflow': 'workflow', 'cycle': 'cycle'}
729
730 # "partial" identifiers:
731 >>> _(tokenise('~user'))
732 {'user': 'user'}
733 >>> _(tokenise('~user/workflow'))
734 {'user': 'user', 'workflow': 'workflow'}
735 >>> _(tokenise('workflow'))
736 {'workflow': 'workflow'}
737
738 # "relative" identifiers (new syntax):
739 >>> _(tokenise('//cycle'))
740 {'cycle': 'cycle'}
741 >>> _(tokenise('cycle', relative=True))
742 {'cycle': 'cycle'}
743 >>> _(tokenise('//cycle/task/job'))
744 {'cycle': 'cycle', 'task': 'task', 'job': 'job'}
745
746 # whitespace stripping is employed on all values:
747 >>> _(tokenise(' workflow // cycle '))
748 {'workflow': 'workflow', 'cycle': 'cycle'}
749
750 # illegal identifiers:
751 >>> tokenise('a///')
752 Traceback (most recent call last):
753 ValueError: Invalid Cylc identifier: a///
754
755 """
756 patterns = [UNIVERSAL_ID, RELATIVE_ID]
757 if relative and not identifier.startswith('//'):
758 identifier = f'//{identifier}'
759 for pattern in patterns:
760 match = pattern.match(identifier)
761 if match:
762 return Tokens(**_dict_strip(match.groupdict()))
763 raise ValueError(f'Invalid Cylc identifier: {identifier}')
764
765
766 def detokenise(
767 tokens: Tokens,
768 selectors: bool = False,
769 relative: bool = False,
770 ) -> str:
771 """Convert Cylc tokens into a string identifier.
772
773 Args:
774 tokens (dict):
775 IDTokens as returned by tokenise.
776 selectors (bool):
777 If true selectors (i.e. :sel) will be included in the output.
778 relative (bool):
779 If true relative references are not given the `//` prefix.
780
781 Returns:
782 str - Identifier i.e. ~user/workflow//cycle/task/job
783
784 Raises:
785 ValueError:
786 For invalid or empty tokens.
787
788 Examples:
789 # absolute references:
790 >>> detokenise(tokenise('~user'))
791 '~user'
792 >>> detokenise(tokenise('~user/workflow'))
793 '~user/workflow'
794 >>> detokenise(tokenise('~user/workflow//cycle'))
795 '~user/workflow//cycle'
796 >>> detokenise(tokenise('~user/workflow//cycle/task'))
797 '~user/workflow//cycle/task'
798 >>> detokenise(tokenise('~user/workflow//cycle/task/4'))
799 '~user/workflow//cycle/task/04'
800
801 # relative references:
802 >>> detokenise(tokenise('//cycle/task/4'))
803 '//cycle/task/04'
804 >>> detokenise(tokenise('//cycle/task/4'), relative=True)
805 'cycle/task/04'
806
807 # selectors are enabled using the selectors kwarg:
808 >>> detokenise(tokenise('workflow:a//cycle:b/task:c/01:d'))
809 'workflow//cycle/task/01'
810 >>> detokenise(tokenise('workflow:a//cycle:b/task:c/01:d'), True)
811 'workflow:a//cycle:b/task:c/01:d'
812
813 # missing tokens expand to '*' (absolute):
814 >>> tokens = tokenise('~user/workflow//cycle/task/01')
815 >>> tokens.pop('task')
816 'task'
817 >>> detokenise(tokens)
818 '~user/workflow//cycle/*/01'
819
820 # missing tokens expand to '*' (relative):
821 >>> tokens = tokenise('//cycle/task/01')
822 >>> tokens.pop('task')
823 'task'
824 >>> detokenise(tokens)
825 '//cycle/*/01'
826
827 # empty tokens result in traceback:
828 >>> detokenise({})
829 Traceback (most recent call last):
830 ValueError: No tokens provided
831
832 """
833 keys = {
834 key for key in Tokens._REGULAR_KEYS
835 if tokens.get(key)
836 }
837 is_relative = keys.isdisjoint(('user', 'workflow'))
838 is_partial = keys.isdisjoint(('cycle', 'task', 'job'))
839 if is_relative and is_partial:
840 raise ValueError('No tokens provided')
841
842 # determine the lowest token
843 for lowest_token in reversed(IDTokens):
844 if lowest_token.value in keys:
845 break
846
847 highest_token: Optional[IDTokens]
848 identifier = []
849 if is_relative:
850 highest_token = IDTokens.Cycle
851 if not relative:
852 identifier = ['/']
853 else:
854 highest_token = IDTokens.User
855
856 for token in IDTokens:
857 if highest_token:
858 if token != highest_token:
859 continue
860 highest_token = None
861 value: Optional[str] = tokens.get(token.value)
862 if not value and token == IDTokens.User:
863 continue
864 elif token == IDTokens.User:
865 value = f'~{value}'
866 elif token == IDTokens.Job and value != 'NN':
867 value = f'{int(value):02}' # type: ignore[arg-type]
868 value = value or '*'
869 if selectors and tokens.get(token.value + '_sel'):
870 # include selectors
871 value = f'{value}:{tokens[token.value + "_sel"]}'
872 if token == IDTokens.Workflow and not is_partial:
873 value += '/'
874 identifier.append(value)
875
876 if token == lowest_token:
877 break
878
879 return '/'.join(identifier)
880
881
882 def upgrade_legacy_ids(*ids: str, relative=False) -> List[str]:
883 """Reformat IDs from legacy to contemporary format:
884
885 If no upgrading is required it returns the identifiers unchanged.
886
887 Args:
888 *ids:
889 Identifier list.
890 relative:
891 If `False` then `ids` must describe absolute ID(s) e.g:
892 workflow task1.cycle1 task2.cycle2
893 If `True` then `ids` should be relative e.g:
894 task1.cycle1 task2.cycle2
895
896 Returns:
897 tuple/list - Identifier list.
898
899 # do nothing to contemporary ids:
900 >>> upgrade_legacy_ids('workflow')
901 ['workflow']
902
903 >>> upgrade_legacy_ids('workflow', '//cycle')
904 ['workflow', '//cycle']
905
906 # upgrade legacy task.cycle ids:
907 >>> upgrade_legacy_ids('workflow', 'task.123', 'task.234')
908 ['workflow', '//123/task', '//234/task']
909
910 # upgrade legacy cycle/task ids:
911 >>> upgrade_legacy_ids('workflow', '123/task', '234/task')
912 ['workflow', '//123/task', '//234/task']
913
914 # upgrade mixed legacy ids:
915 >>> upgrade_legacy_ids('workflow', 'task.123', '234/task')
916 ['workflow', '//123/task', '//234/task']
917
918 # upgrade legacy task states:
919 >>> upgrade_legacy_ids('workflow', 'task.123:abc', '234/task:def')
920 ['workflow', '//123/task:abc', '//234/task:def']
921
922 # upgrade relative IDs:
923 >>> upgrade_legacy_ids('x.1', relative=True)
924 ['1/x']
925 >>> upgrade_legacy_ids('x.1', 'x.2', 'x.3:s', relative=True)
926 ['1/x', '2/x', '3/x:s']
927
928 """
929 if not relative and len(ids) < 2:
930 # only legacy relative references require upgrade => abort
931 return list(ids)
932
933 legacy_ids: List[str]
934 _ids: Iterable[str]
935 if relative:
936 legacy_ids = []
937 _ids = ids
938 else:
939 legacy_ids = [ids[0]]
940 _ids = ids[1:]
941
942 for id_ in _ids:
943 try:
944 tokens = legacy_tokenise(id_)
945 except ValueError:
946 # not a valid legacy token => abort
947 return list(ids)
948 else:
949 # upgrade this token
950 legacy_ids.append(
951 detokenise(tokens, selectors=True, relative=relative)
952 )
953
954 LOG.warning(
955 f'Cylc7 format is deprecated, using: {" ".join(legacy_ids)}'
956 ' (see "cylc help id")'
957 )
958 return legacy_ids
959
960
961 def contains_multiple_workflows(tokens_list: List[Tokens]) -> bool:
962 """Returns True if multiple workflows are contained in the tokens list.
963
964 Examples:
965 >>> a_1 = tokenise('a//1')
966 >>> a_2 = tokenise('a//2')
967 >>> b_1 = tokenise('b//1')
968
969 >>> contains_multiple_workflows([a_1])
970 False
971 >>> contains_multiple_workflows([a_1, a_2])
972 False
973 >>> contains_multiple_workflows([a_1, b_1])
974 True
975
976 """
977 return len({
978 (tokens['user'], tokens['workflow'])
979 for tokens in tokens_list
980 }) > 1