capsid_database/
target.rs1use std::{fmt, str::FromStr};
2
3use capsid_model::{
4 BackupId, CheckpointId, InstanceId, JobGroupId, JobRunId, LedgerId, NetworkId, PoolId,
5 ProjectId, RequestId, RevisionId, TemplateId, TokenId, VolumeId, WorkloadId, WorkspaceId,
6};
7
8#[derive(Debug, Clone, PartialEq, Eq)]
9pub enum Target<Id> {
10 Id(Id),
11 Name(String),
14}
15
16impl<Id: FromStr> Target<Id> {
17 pub fn parse(target: &str) -> Self {
18 match target.parse() {
19 Ok(id) => Self::Id(id),
20 Err(_) => Self::Name(target.to_owned()),
21 }
22 }
23}
24
25impl<Id: PartialEq> Target<Id> {
26 pub fn matches(&self, id: &Id, original: &str) -> bool {
29 match self {
30 Self::Id(target) => target == id,
31 Self::Name(name) => name == original,
32 }
33 }
34}
35
36impl<Id: fmt::Display> fmt::Display for Target<Id> {
37 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
38 match self {
39 Self::Id(id) => id.fmt(formatter),
40 Self::Name(name) => formatter.write_str(name),
41 }
42 }
43}
44
45impl<Id: Clone> From<&Target<Id>> for Target<Id> {
46 fn from(target: &Target<Id>) -> Self {
47 target.clone()
48 }
49}
50
51macro_rules! target {
53 ($($id:ty),+ $(,)?) => {$(
54 impl From<$id> for Target<$id> {
55 fn from(id: $id) -> Self {
56 Self::Id(id)
57 }
58 }
59
60 impl From<&$id> for Target<$id> {
61 fn from(id: &$id) -> Self {
62 Self::Id(*id)
63 }
64 }
65
66 impl From<&str> for Target<$id> {
67 fn from(target: &str) -> Self {
68 Self::parse(target)
69 }
70 }
71
72 impl From<&String> for Target<$id> {
73 fn from(target: &String) -> Self {
74 Self::parse(target)
75 }
76 }
77
78 impl From<String> for Target<$id> {
79 fn from(target: String) -> Self {
80 Self::parse(&target)
81 }
82 }
83 )+};
84}
85
86target!(
87 BackupId,
88 CheckpointId,
89 InstanceId,
90 JobGroupId,
91 JobRunId,
92 LedgerId,
93 NetworkId,
94 PoolId,
95 ProjectId,
96 RequestId,
97 RevisionId,
98 TemplateId,
99 TokenId,
100 VolumeId,
101 WorkloadId,
102 WorkspaceId,
103);