Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(158)

Side by Side Diff: infra_libs/time_functions/parser.py

Issue 2059833002: Add master_cleaner tool. (Closed) Base URL: https://chromium.googlesource.com/infra/infra.git@master
Patch Set: Comments. Created 4 years, 6 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch
« no previous file with comments | « infra/tools/master_cleaner/__main__.py ('k') | no next file » | no next file with comments »
Toggle Intra-line Diffs ('i') | Expand Comments ('e') | Collapse Comments ('c') | Show Comments Hide Comments ('s')
OLDNEW
(Empty)
1 # Copyright 2016 The Chromium Authors. All rights reserved.
2 # Use of this source code is governed by a BSD-style license that can be
3 # found in the LICENSE file.
4
5 """Utility functions to parse time/duration arguments."""
6
7
8 import argparse
9 import datetime
10 import re
11
12
13 _TIMEDELTA_CONV = {
14 'us': datetime.timedelta(microseconds=1),
15 'ms': datetime.timedelta(milliseconds=1),
16 's': datetime.timedelta(seconds=1),
17 'm': datetime.timedelta(minutes=1),
18 'h': datetime.timedelta(hours=1),
19 'd': datetime.timedelta(days=1),
20 }
21 _TIMEDELTA_RE = re.compile(r'(\d+)(\w+)')
22
23
24 def parse_timedelta(v):
25 """Returns (datetime.timedelta) The parsed timedelta.
26
27 Args:
28 v (str): The time delta string, a comma-delimited set of <count><unit>
29 tokens comprising the timedelta (e.g., 10d,2h is 10 days, 2 hours).
30
31 Raises:
32 ValueError: If parsing failed.
33 """
34 result = datetime.timedelta()
35 for comp in v.split(','):
36 match = _TIMEDELTA_RE.match(comp)
37 if match is None:
38 raise ValueError('Invalid timedelta token (%s)' % (comp,))
39 count, unit = int(match.group(1)), match.group(2)
40 unit_value = _TIMEDELTA_CONV.get(unit)
41 if unit_value is None:
42 raise ValueError('Invalid timedelta token unit (%s)' % (unit,))
43 result += (unit_value * count)
44 return result
45
46
47 def argparse_timedelta_type(v):
48 """Returns (datetime.timedelta) The parsed timedelta.
49
50 This is an argparse-compatible version of `parse_timedelta` that raises an
51 argparse.ArgumentTypeError on failure instead of a ValueError.
52
53 Raises:
54 argparse.ArgumentTypeError: If parsing failed.
55 """
56 try:
57 return parse_timedelta(v)
58 except ValueError as e:
59 raise argparse.ArgumentTypeError(e.message)
OLDNEW
« no previous file with comments | « infra/tools/master_cleaner/__main__.py ('k') | no next file » | no next file with comments »

Powered by Google App Engine
This is Rietveld 408576698