33# This file is part of Checkmk (https://checkmk.com). It is subject to the terms and
44# conditions defined in the file COPYING, which is part of this source code package.
55
6-
7- from __future__ import annotations
8-
96import re
10- from typing import Any
11-
12- from pydantic import GetCoreSchemaHandler
13- from pydantic_core import core_schema
7+ from typing import Self
148
159
1610class UserId (str ):
@@ -57,19 +51,7 @@ class UserId(str):
5751 # Note: livestatus.py duplicates the regex to validate incoming UserIds!
5852 USER_ID_REGEX = re .compile (r"^[\w$][-@.+\w$]*$" , re .UNICODE )
5953
60- @classmethod
61- def __get_pydantic_core_schema__ (
62- cls , source_type : Any , _handler : GetCoreSchemaHandler
63- ) -> core_schema .CoreSchema :
64- return core_schema .no_info_after_validator_function (
65- cls ,
66- core_schema .union_schema (
67- [core_schema .str_schema (), core_schema .is_instance_schema (cls )]
68- ),
69- serialization = core_schema .to_string_ser_schema (),
70- )
71-
72- def __new__ (cls , text : str ) -> UserId :
54+ def __new__ (cls , text : str ) -> Self :
7355 """Construct a new UserId object
7456
7557 UserIds are used in a variety of contexts, including HTML, file paths and other external
@@ -154,7 +136,15 @@ def __new__(cls, text: str) -> UserId:
154136 return super ().__new__ (cls , text )
155137
156138 @classmethod
157- def builtin (cls ) -> UserId :
139+ def parse (cls , x : object ) -> Self :
140+ if isinstance (x , cls ):
141+ return x
142+ if isinstance (x , str ):
143+ return cls (x )
144+ raise ValueError (f"invalid username: { x !r} " )
145+
146+ @classmethod
147+ def builtin (cls ) -> Self :
158148 """A special UserId signifying something is owned or created not by a real user but shipped
159149 as a built in functionality.
160150 This is mostly used in cmk.gui.visuals.
@@ -163,4 +153,4 @@ def builtin(cls) -> UserId:
163153 Moreover, be aware that it is very possible that some parts of the code use the UserId ""
164154 with a different meaning.
165155 """
166- return UserId ("" )
156+ return cls ("" )
0 commit comments