agcodex_execpolicy/
opt.rs

1#![allow(clippy::needless_lifetimes)]
2
3use crate::ArgType;
4use crate::starlark::values::ValueLike;
5use allocative::Allocative;
6use derive_more::derive::Display;
7use starlark::any::ProvidesStaticType;
8use starlark::values::AllocValue;
9use starlark::values::Heap;
10use starlark::values::NoSerialize;
11use starlark::values::StarlarkValue;
12use starlark::values::UnpackValue;
13use starlark::values::Value;
14use starlark::values::starlark_value;
15
16/// Command line option that takes a value.
17#[derive(Clone, Debug, Display, PartialEq, Eq, ProvidesStaticType, NoSerialize, Allocative)]
18#[display("opt({})", opt)]
19pub struct Opt {
20    /// The option as typed on the command line, e.g., `-h` or `--help`. If
21    /// it can be used in the `--name=value` format, then this should be
22    /// `--name` (though this is subject to change).
23    pub opt: String,
24    pub meta: OptMeta,
25    pub required: bool,
26}
27
28/// When defining an Opt, use as specific an OptMeta as possible.
29#[derive(Clone, Debug, Display, PartialEq, Eq, ProvidesStaticType, NoSerialize, Allocative)]
30#[display("{}", self)]
31pub enum OptMeta {
32    /// Option does not take a value.
33    Flag,
34
35    /// Option takes a single value matching the specified type.
36    Value(ArgType),
37}
38
39impl Opt {
40    pub const fn new(opt: String, meta: OptMeta, required: bool) -> Self {
41        Self {
42            opt,
43            meta,
44            required,
45        }
46    }
47
48    pub fn name(&self) -> &str {
49        &self.opt
50    }
51}
52
53#[starlark_value(type = "Opt")]
54impl<'v> StarlarkValue<'v> for Opt {
55    type Canonical = Opt;
56}
57
58impl<'v> UnpackValue<'v> for Opt {
59    type Error = starlark::Error;
60
61    fn unpack_value_impl(value: Value<'v>) -> starlark::Result<Option<Self>> {
62        // TODO(mbolin): It fels like this should be doable without cloning?
63        // Cannot simply consume the value?
64        Ok(value.downcast_ref::<Opt>().cloned())
65    }
66}
67
68impl<'v> AllocValue<'v> for Opt {
69    fn alloc_value(self, heap: &'v Heap) -> Value<'v> {
70        heap.alloc_simple(self)
71    }
72}
73
74#[starlark_value(type = "OptMeta")]
75impl<'v> StarlarkValue<'v> for OptMeta {
76    type Canonical = OptMeta;
77}