forked from aws/amazon-q-developer-cli
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathbuild.rs
More file actions
386 lines (333 loc) · 13.1 KB
/
build.rs
File metadata and controls
386 lines (333 loc) · 13.1 KB
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
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
use convert_case::{
Case,
Casing,
};
use quote::{
format_ident,
quote,
};
// TODO(brandonskiser): update bundle identifier for signed builds
#[cfg(target_os = "macos")]
const MACOS_BUNDLE_IDENTIFIER: &str = "com.amazon.codewhisperer";
const DEF: &str = include_str!("./telemetry_definitions.json");
#[derive(Debug, Clone, serde::Deserialize)]
#[serde(rename_all = "camelCase")]
struct TypeDef {
name: String,
r#type: Option<String>,
allowed_values: Option<Vec<String>>,
description: String,
}
#[derive(Debug, Clone, serde::Deserialize)]
struct MetricDef {
name: String,
description: String,
metadata: Option<Vec<MetricMetadata>>,
passive: Option<bool>,
unit: Option<String>,
}
#[derive(Debug, Clone, serde::Deserialize)]
struct MetricMetadata {
r#type: String,
required: Option<bool>,
}
#[derive(Debug, Clone, serde::Deserialize)]
struct Def {
types: Vec<TypeDef>,
metrics: Vec<MetricDef>,
}
/// Writes a generated Info.plist for the qchat executable under src/.
///
/// This is required for signing the executable since we must embed the Info.plist directly within
/// the binary.
#[cfg(target_os = "macos")]
fn write_plist() {
let plist = format!(
r#"<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>CFBundlePackageType</key>
<string>APPL</string>
<key>CFBundleIdentifier</key>
<string>{}</string>
<key>CFBundleName</key>
<string>{}</string>
<key>CFBundleVersion</key>
<string>{}</string>
<key>CFBundleShortVersionString</key>
<string>{}</string>
<key>CFBundleInfoDictionaryVersion</key>
<string>6.0</string>
<key>NSHumanReadableCopyright</key>
<string>Copyright © 2022 Amazon Q CLI Team (q-cli@amazon.com):Chay Nabors (nabochay@amazon.com):Brandon Kiser (bskiser@amazon.com) All rights reserved.</string>
</dict>
</plist>
"#,
MACOS_BUNDLE_IDENTIFIER,
option_env!("AMAZON_Q_BUILD_HASH").unwrap_or("unknown"),
option_env!("AMAZON_Q_BUILD_DATETIME").unwrap_or("unknown"),
env!("CARGO_PKG_VERSION")
);
std::fs::write("src/Info.plist", plist).expect("writing the Info.plist should not fail");
}
fn main() {
println!("cargo:rerun-if-changed=def.json");
// Download feed.json if FETCH_FEED environment variable is set
if std::env::var("FETCH_FEED").is_ok() {
download_feed_json();
}
#[cfg(target_os = "macos")]
write_plist();
let outdir = std::env::var("OUT_DIR").unwrap();
let data = serde_json::from_str::<Def>(DEF).unwrap();
let mut out = "
#[allow(rustdoc::invalid_html_tags)]
#[allow(rustdoc::bare_urls)]
mod inner {
"
.to_string();
out.push_str("pub mod types {");
for t in data.types {
let name = format_ident!("{}", t.name.to_case(Case::Pascal));
let rust_type = match t.allowed_values {
// enum
Some(allowed_values) => {
let mut variants = vec![];
let mut variant_as_str = vec![];
for v in allowed_values {
let ident = format_ident!("{}", v.replace('.', "").to_case(Case::Pascal));
variants.push(quote!(
#[doc = concat!("`", #v, "`")]
#ident
));
variant_as_str.push(quote!(
#name::#ident => #v
));
}
let description = t.description;
quote::quote!(
#[doc = #description]
#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
#[non_exhaustive]
pub enum #name {
#(
#variants,
)*
}
impl #name {
pub fn as_str(&self) -> &'static str {
match self {
#( #variant_as_str, )*
}
}
}
impl ::std::fmt::Display for #name {
fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result {
f.write_str(self.as_str())
}
}
)
.to_string()
},
// struct
None => {
let r#type = match t.r#type.as_deref() {
Some("string") | None => quote!(::std::string::String),
Some("int") => quote!(::std::primitive::i64),
Some("double") => quote!(::std::primitive::f64),
Some("boolean") => quote!(::std::primitive::bool),
Some(other) => panic!("{}", other),
};
let description = t.description;
quote::quote!(
#[doc = #description]
#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
#[serde(transparent)]
pub struct #name(pub #r#type);
impl #name {
pub fn new(t: #r#type) -> Self {
Self(t)
}
pub fn value(&self) -> &#r#type {
&self.0
}
pub fn into_value(self) -> #r#type {
self.0
}
}
impl ::std::fmt::Display for #name {
fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result {
write!(f, "{}", self.0)
}
}
impl From<#r#type> for #name {
fn from(t: #r#type) -> Self {
Self(t)
}
}
)
.to_string()
},
};
out.push_str(&rust_type);
}
out.push('}');
out.push_str("pub mod metrics {");
for m in data.metrics.clone() {
let raw_name = m.name;
let name = format_ident!("{}", raw_name.to_case(Case::Pascal));
let description = m.description;
let passive = m.passive.unwrap_or_default();
let unit = match m.unit.map(|u| u.to_lowercase()).as_deref() {
Some("bytes") => quote!(::amzn_toolkit_telemetry_client::types::Unit::Bytes),
Some("count") => quote!(::amzn_toolkit_telemetry_client::types::Unit::Count),
Some("milliseconds") => quote!(::amzn_toolkit_telemetry_client::types::Unit::Milliseconds),
Some("percent") => quote!(::amzn_toolkit_telemetry_client::types::Unit::Percent),
Some("none") | None => quote!(::amzn_toolkit_telemetry_client::types::Unit::None),
Some(unknown) => {
panic!("unknown unit: {:?}", unknown);
},
};
let metadata = m.metadata.unwrap_or_default();
let mut fields = Vec::new();
for field in &metadata {
let field_name = format_ident!("{}", &field.r#type.to_case(Case::Snake));
let ty_name = format_ident!("{}", field.r#type.to_case(Case::Pascal));
let ty = if field.required.unwrap_or_default() {
quote!(crate::telemetry::definitions::types::#ty_name)
} else {
quote!(::std::option::Option<crate::telemetry::definitions::types::#ty_name>)
};
fields.push(quote!(
#field_name: #ty
));
}
let metadata_entries = metadata.iter().map(|m| {
let raw_name = &m.r#type;
let key = format_ident!("{}", m.r#type.to_case(Case::Snake));
let value = if m.required.unwrap_or_default() {
quote!(.value(self.#key.to_string()))
} else {
quote!(.value(self.#key.map(|v| v.to_string()).unwrap_or_default()))
};
quote!(
::amzn_toolkit_telemetry_client::types::MetadataEntry::builder()
.key(#raw_name)
#value
.build()
)
});
let rust_type = quote::quote!(
#[doc = #description]
#[derive(Debug, Clone, PartialEq, ::serde::Serialize, ::serde::Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct #name {
/// The time that the event took place,
pub create_time: ::std::option::Option<::std::time::SystemTime>,
/// Value based on unit and call type,
pub value: ::std::option::Option<f64>,
#( pub #fields, )*
}
impl #name {
const NAME: &'static ::std::primitive::str = #raw_name;
const PASSIVE: ::std::primitive::bool = #passive;
const UNIT: ::amzn_toolkit_telemetry_client::types::Unit = #unit;
}
impl crate::telemetry::definitions::IntoMetricDatum for #name {
fn into_metric_datum(self) -> ::amzn_toolkit_telemetry_client::types::MetricDatum {
let metadata_entries = vec![
#(
#metadata_entries,
)*
];
let epoch_timestamp = self.create_time
.map_or_else(
|| ::std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_millis() as ::std::primitive::i64,
|t| t.duration_since(std::time::UNIX_EPOCH).unwrap().as_millis() as ::std::primitive::i64
);
::amzn_toolkit_telemetry_client::types::MetricDatum::builder()
.metric_name(#name::NAME)
.passive(#name::PASSIVE)
.unit(#name::UNIT)
.epoch_timestamp(epoch_timestamp)
.value(self.value.unwrap_or(1.0))
.set_metadata(Some(metadata_entries))
.build()
.unwrap()
}
}
);
out.push_str(&rust_type.to_string());
}
out.push('}');
// enum of all metrics
let mut metrics = Vec::new();
for m in data.metrics {
let name = format_ident!("{}", m.name.to_case(Case::Pascal));
metrics.push(quote!(
#name
));
}
out.push_str("#[derive(Debug, Clone, PartialEq, ::serde::Serialize, ::serde::Deserialize)]\n#[serde(tag = \"type\", content = \"content\")]\npub enum Metric {\n");
for m in metrics {
out.push_str(&format!("{m}(crate::telemetry::definitions::metrics::{m}),\n"));
}
out.push('}');
out.push_str("}\npub use inner::*;");
let file: syn::File = syn::parse_str(&out).unwrap();
let pp = prettyplease::unparse(&file);
// write an empty file to the output directory
std::fs::write(format!("{}/mod.rs", outdir), pp).unwrap();
}
/// Downloads the latest feed.json from the autocomplete repository.
/// This ensures official builds have the most up-to-date changelog information.
///
/// # Errors
///
/// Prints cargo warnings if:
/// - `curl` command is not available
/// - Network request fails
/// - File write operation fails
fn download_feed_json() {
use std::process::Command;
println!("cargo:warning=Downloading latest feed.json from autocomplete repo...");
// Check if curl is available first
let curl_check = Command::new("curl").arg("--version").output();
if curl_check.is_err() {
panic!(
"curl command not found. Cannot download latest feed.json. Please install curl or build without FETCH_FEED=1 to use existing feed.json."
);
}
let output = Command::new("curl")
.args([
"-H",
"Accept: application/vnd.github.v3.raw",
"-f", // fail on HTTP errors
"-s", // silent
"-v", // verbose output printed to stderr
"--show-error", // print error message to stderr (since -s is used)
"https://api.github.com/repos/aws/amazon-q-developer-cli-autocomplete/contents/feed.json",
])
.output();
match output {
Ok(result) if result.status.success() => {
if let Err(e) = std::fs::write("src/cli/feed.json", result.stdout) {
panic!("Failed to write feed.json: {}", e);
} else {
println!("cargo:warning=Successfully downloaded latest feed.json");
}
},
Ok(result) => {
let error_msg = if !result.stderr.is_empty() {
format!("{}", String::from_utf8_lossy(&result.stderr))
} else {
"An unknown error occurred".to_string()
};
panic!("Failed to download feed.json: {}", error_msg);
},
Err(e) => {
panic!("Failed to execute curl: {}", e);
},
}
}