zhold_core/model/
command.rs1use serde::{Deserialize, Serialize};
2
3#[derive(Clone, Copy, Debug, Default, Deserialize, Eq, Hash, PartialEq, Serialize)]
5#[serde(rename_all = "snake_case")]
6pub enum CargoCommandClass {
7 Build,
9 Check,
11 Test,
13 Run,
15 Bench,
17 Doc,
19 #[default]
21 Other,
22}
23
24#[derive(Clone, Debug, Default, Deserialize, Eq, PartialEq, Serialize)]
26pub struct CommandDescriptor {
27 pub command_class: CargoCommandClass,
29 pub arguments_fingerprint: String,
31}
32
33impl CommandDescriptor {
34 pub fn from_arguments(arguments: &[String], fingerprint_key: &[u8; 32]) -> Self {
36 Self {
37 command_class: Self::classify(arguments),
38 arguments_fingerprint: keyed_fingerprint(arguments, fingerprint_key),
39 }
40 }
41
42 pub fn classify(arguments: &[String]) -> CargoCommandClass {
44 command_class(arguments)
45 }
46}
47
48fn keyed_fingerprint(arguments: &[String], key: &[u8; 32]) -> String {
49 let mut hasher = blake3::Hasher::new_keyed(key);
50 hasher.update(b"zhold-cargo-arguments-v2\0");
51 for argument in arguments {
52 let bytes = argument.as_bytes();
53 hasher.update(&u64::try_from(bytes.len()).unwrap_or(u64::MAX).to_le_bytes());
54 hasher.update(bytes);
55 }
56 hasher.finalize().to_hex()[..32].to_owned()
57}
58
59fn command_class(arguments: &[String]) -> CargoCommandClass {
60 let mut index = usize::from(
61 arguments
62 .first()
63 .is_some_and(|value| value.starts_with('+')),
64 );
65 while let Some(argument) = arguments.get(index) {
66 if argument == "--" {
67 return CargoCommandClass::Other;
68 }
69 if option_takes_value(argument) {
70 index = index.saturating_add(2);
71 continue;
72 }
73 if argument.starts_with('-') {
74 index = index.saturating_add(1);
75 continue;
76 }
77 return match argument.as_str() {
78 "build" => CargoCommandClass::Build,
79 "check" => CargoCommandClass::Check,
80 "test" => CargoCommandClass::Test,
81 "run" => CargoCommandClass::Run,
82 "bench" => CargoCommandClass::Bench,
83 "doc" => CargoCommandClass::Doc,
84 _ => CargoCommandClass::Other,
85 };
86 }
87 CargoCommandClass::Other
88}
89
90fn option_takes_value(argument: &str) -> bool {
91 matches!(argument, "--color" | "--config" | "-C" | "-Z")
92}