summaryrefslogtreecommitdiff
path: root/tools/tai64dec
diff options
context:
space:
mode:
Diffstat (limited to 'tools/tai64dec')
-rw-r--r--tools/tai64dec/default.nix18
-rw-r--r--tools/tai64dec/setup.py10
-rw-r--r--tools/tai64dec/tai64dec/__main__.py46
3 files changed, 74 insertions, 0 deletions
diff --git a/tools/tai64dec/default.nix b/tools/tai64dec/default.nix
new file mode 100644
index 00000000..380c22bf
--- /dev/null
+++ b/tools/tai64dec/default.nix
@@ -0,0 +1,18 @@
1{ system, self, mach-nix, leapseconds, ... }:
2let
3 pkgs = self.legacyPackages.${system};
4in mach-nix.lib.${system}.buildPythonPackage {
5 pname = "tai64dec";
6 src = pkgs.lib.sourceByRegex ./. ["^setup\.py$" "^tai64dec(/[^/]+.*)?$"];
7 version = "0.0.0";
8 ignoreDataOutdated = true;
9
10 requirements = ''
11 leapseconddata
12 '';
13
14 postInstall = ''
15 wrapProgram $out/bin/tai64dec \
16 --set-default LEAPSECONDS_FILE ${leapseconds}
17 '';
18}
diff --git a/tools/tai64dec/setup.py b/tools/tai64dec/setup.py
new file mode 100644
index 00000000..d936796b
--- /dev/null
+++ b/tools/tai64dec/setup.py
@@ -0,0 +1,10 @@
1from setuptools import setup
2
3setup(name='tai64dec',
4 packages=['tai64dec'],
5 entry_points={
6 'console_scripts': [
7 'tai64dec=tai64dec.__main__:main'
8 ],
9 },
10)
diff --git a/tools/tai64dec/tai64dec/__main__.py b/tools/tai64dec/tai64dec/__main__.py
new file mode 100644
index 00000000..a8854523
--- /dev/null
+++ b/tools/tai64dec/tai64dec/__main__.py
@@ -0,0 +1,46 @@
1import sys, os
2
3import argparse
4
5from leapseconddata import LeapSecondData
6from math import ldexp
7from pathlib import Path
8from datetime import datetime, timezone
9import secrets
10
11
12class BooleanAction(argparse.Action):
13 def __init__(self, option_strings, dest, nargs=None, **kwargs):
14 super(BooleanAction, self).__init__(option_strings, dest, nargs=0, **kwargs)
15
16 def __call__(self, parser, namespace, values, option_string=None):
17 setattr(namespace, self.dest, False if option_string.startswith('--no') else True)
18
19
20def main():
21 parser = argparse.ArgumentParser(prog='tai64dec', formatter_class=argparse.ArgumentDefaultsHelpFormatter)
22 parser.add_argument('--random', '--no-random', action=BooleanAction, default=False)
23 parser.add_argument('--ns', '--no-ns', action=BooleanAction, default=True)
24 args = parser.parse_args()
25
26
27 leapsecond_data = LeapSecondData.from_file(Path(os.getenv('LEAPSECONDS_FILE')))
28
29 now = datetime.now(tz=timezone.utc)
30
31 tai_dt = leapsecond_data.to_tai(now)
32 seconds = int(tai_dt.timestamp())
33 seconds += int(ldexp(1, 62))
34 out = seconds
35
36 if args.ns:
37 nanoseconds = int((tai_dt.timestamp() - seconds) / 1e-9)
38 out = out << 32 | nanoseconds
39
40 if args.random:
41 out = out << 24 | int.from_bytes(secrets.token_bytes(3), byteorder='little', signed=False)
42
43 print('{:d}'.format(out), file=sys.stdout)
44
45if __name__ == '__main__':
46 sys.exit(main())