File: __main__.py

package info (click to toggle)
python-ulid 2.2.0-4
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 164 kB
  • sloc: python: 667; makefile: 14
file content (166 lines) | stat: -rw-r--r-- 5,290 bytes parent folder | download
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
import argparse
import shutil
import sys
import textwrap
from collections.abc import Callable
from collections.abc import Sequence
from datetime import datetime
from functools import partial
from typing import Any
from typing import Optional
from uuid import UUID

import ulid
from ulid import ULID


def make_parser(prog: str | None = None) -> argparse.ArgumentParser:
    parser = argparse.ArgumentParser(
        prog=prog,
        description=textwrap.indent(
            textwrap.dedent(
                """
            Create or inspect ULIDs

            A ULID is a universally unique lexicographically sortable identifier
            with the following structure

               01AN4Z07BY      79KA1307SR9X4MV3
              |----------|    |----------------|
               Timestamp          Randomness
                 48bits             80bits
            """
            ).strip(),
            "    ",
        ),
        formatter_class=partial(
            argparse.RawDescriptionHelpFormatter,
            # Prevent argparse from taking up the entire width of the terminal window
            # which impedes readability.
            width=min(shutil.get_terminal_size().columns - 2, 127),
        ),
    )
    parser.set_defaults(func=lambda _: parser.print_help())
    parser.add_argument("--version", "-V", action="version", version=ulid.__version__)

    subparsers = parser.add_subparsers(title="subcommands")
    b = subparsers.add_parser(
        "build",
        help="generate ULIDs from different sources",
    )
    b.add_argument(
        "--from-int",
        metavar="<int>",
        help="create from integer",
    )
    b.add_argument(
        "--from-hex",
        metavar="<str>",
        help="create from 32 character hex value",
    )
    b.add_argument(
        "--from-str",
        metavar="<str>",
        help="create from base32 encoded string of length 26",
    )
    b.add_argument(
        "--from-timestamp",
        metavar="<int|float>",
        help="create from timestamp either as float in secs or int as millis",
    )
    b.add_argument(
        "--from-datetime",
        metavar="<iso8601>",
        help="create from datetime. The timestamp part of the ULID will be taken from the datetime",
    )
    b.add_argument(
        "--from-uuid",
        metavar="<uuid>",
        help="create from given UUID. The timestamp part will be random.",
    )
    b.set_defaults(func=build)

    s = subparsers.add_parser("show", help="show properties of a ULID")
    s.add_argument("ulid", help="the ULID to inspect. The special value - reads from stdin")
    s.add_argument("--uuid", action="store_true", help="convert to fully random UUID")
    s.add_argument("--uuid4", action="store_true", help="convert to RFC 4122 compliant UUIDv4")
    s.add_argument("--hex", action="store_true", help="convert to hex")
    s.add_argument("--int", action="store_true", help="convert to int")
    s.add_argument("--timestamp", "--ts", action="store_true", help="show timestamp")
    s.add_argument("--datetime", "--dt", action="store_true", help="show datetime")
    s.set_defaults(func=show)
    return parser


def main(argv: Sequence[str], prog: str | None = None) -> None:
    args = make_parser(prog).parse_args(argv)
    args.func(args)


def from_value_or_stdin(value: str, convert: Optional[Callable[[str], Any]] = None) -> Any:
    value = sys.stdin.readline().strip() if value == "-" else value
    if convert is not None:
        return convert(value)
    return value


def parse_numeric(s: str) -> int | float:
    try:
        return int(s)
    except ValueError:
        return float(s)


def build(args: argparse.Namespace) -> None:
    ulid: ULID
    if args.from_int is not None:
        ulid = ULID.from_int(from_value_or_stdin(args.from_int, int))
    elif args.from_hex is not None:
        ulid = ULID.from_hex(from_value_or_stdin(args.from_hex))
    elif args.from_str is not None:
        ulid = ULID.from_str(from_value_or_stdin(args.from_str))
    elif args.from_timestamp is not None:
        ulid = ULID.from_timestamp(from_value_or_stdin(args.from_timestamp, parse_numeric))
    elif args.from_datetime is not None:
        ulid = ULID.from_datetime(from_value_or_stdin(args.from_datetime, datetime.fromisoformat))
    elif args.from_uuid is not None:
        ulid = ULID.from_uuid(from_value_or_stdin(args.from_uuid, UUID))
    else:
        ulid = ULID()
    print(ulid)


def show(args: argparse.Namespace) -> None:
    ulid: ULID = ULID.from_str(from_value_or_stdin(args.ulid))
    if args.uuid:
        print(ulid.to_uuid())
    elif args.uuid4:
        print(ulid.to_uuid4())
    elif args.hex:
        print(ulid.hex)
    elif args.int:
        print(int(ulid))
    elif args.timestamp:
        print(ulid.timestamp)
    elif args.datetime:
        print(ulid.datetime)
    else:
        print(
            textwrap.dedent(
                f"""
                ULID:      {ulid!s}
                Hex:       {ulid.hex}
                Int:       {int(ulid)}
                Timestamp: {ulid.timestamp}
                Datetime:  {ulid.datetime}
                """
            ).strip()
        )


def entrypoint() -> None:
    main(sys.argv[1:])


if __name__ == "__main__":
    main(sys.argv[1:], "python -m ulid")