Skip to main content

hydro_lang/compile/trybuild/
generate.rs

1use std::fs::{self, File};
2use std::io::{Read, Seek, SeekFrom, Write};
3use std::path::{Path, PathBuf};
4
5#[cfg(any(feature = "deploy", feature = "maelstrom"))]
6use dfir_lang::diagnostic::Diagnostics;
7#[cfg(any(feature = "deploy", feature = "maelstrom"))]
8use dfir_lang::graph::DfirGraph;
9use sha2::{Digest, Sha256};
10#[cfg(any(feature = "deploy", feature = "maelstrom"))]
11use stageleft::internal::quote;
12#[cfg(any(feature = "deploy", feature = "maelstrom"))]
13use syn::visit_mut::VisitMut;
14use trybuild_internals_api::cargo::{self, Metadata};
15use trybuild_internals_api::env::Update;
16use trybuild_internals_api::run::{PathDependency, Project};
17use trybuild_internals_api::{Runner, dependencies, features, path};
18
19#[cfg(any(feature = "deploy", feature = "maelstrom"))]
20use super::rewriters::UseTestModeStaged;
21
22pub const HYDRO_RUNTIME_FEATURES: &[&str] = &[
23    "deploy_integration",
24    "runtime_measure",
25    "docker_runtime",
26    "ecs_runtime",
27    "maelstrom_runtime",
28];
29
30#[cfg(any(feature = "deploy", feature = "maelstrom"))]
31/// Whether to use dynamic linking for the generated binary.
32/// - `Static`: Place in base crate examples (for remote/containerized deploys)
33/// - `Dynamic`: Place in dylib crate examples (for sim and localhost deploys)
34#[derive(Debug, Clone, Copy, PartialEq, Eq)]
35pub enum LinkingMode {
36    Static,
37    #[cfg(feature = "deploy")]
38    Dynamic,
39}
40
41#[cfg(any(feature = "deploy", feature = "maelstrom"))]
42/// The deployment mode for code generation.
43#[derive(Debug, Clone, Copy, PartialEq, Eq)]
44pub enum DeployMode {
45    #[cfg(feature = "deploy")]
46    /// Standard HydroDeploy
47    HydroDeploy,
48    #[cfg(any(feature = "docker_deploy", feature = "ecs_deploy"))]
49    /// Containerized deployment (Docker/ECS)
50    Containerized,
51    #[cfg(feature = "maelstrom")]
52    /// Maelstrom deployment with stdin/stdout JSON protocol
53    Maelstrom,
54}
55
56pub(crate) static IS_TEST: std::sync::atomic::AtomicBool =
57    std::sync::atomic::AtomicBool::new(false);
58
59pub(crate) static CONCURRENT_TEST_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
60
61/// Enables "test mode" for Hydro, which makes it possible to compile Hydro programs written
62/// inside a `#[cfg(test)]` module. This should be enabled in a global [`ctor`] hook.
63///
64/// # Example
65/// ```ignore
66/// #[cfg(test)]
67/// mod test_init {
68///    #[ctor::ctor]
69///    fn init() {
70///        hydro_lang::compile::init_test();
71///    }
72/// }
73/// ```
74pub fn init_test() {
75    IS_TEST.store(true, std::sync::atomic::Ordering::Relaxed);
76}
77
78#[cfg(any(feature = "deploy", feature = "maelstrom"))]
79fn clean_bin_name_prefix(bin_name_prefix: &str) -> String {
80    bin_name_prefix
81        .replace("::", "__")
82        .replace(" ", "_")
83        .replace(",", "_")
84        .replace("<", "_")
85        .replace(">", "")
86        .replace("(", "")
87        .replace(")", "")
88        .replace("{", "_")
89        .replace("}", "_")
90}
91
92#[derive(Debug, Clone)]
93pub struct TrybuildConfig {
94    pub project_dir: PathBuf,
95    pub target_dir: PathBuf,
96    pub features: Option<Vec<String>>,
97    #[cfg(feature = "deploy")]
98    /// Which crate within the workspace to use for examples.
99    /// - `Static`: base crate (for remote/containerized deploys)
100    /// - `Dynamic`: dylib-examples crate (for sim and localhost deploys)
101    pub linking_mode: LinkingMode,
102}
103
104#[cfg(any(feature = "deploy", feature = "maelstrom"))]
105pub fn create_graph_trybuild(
106    graph: DfirGraph,
107    extra_stmts: &[syn::Stmt],
108    sidecars: &[syn::Expr],
109    bin_name_prefix: Option<&str>,
110    deploy_mode: DeployMode,
111    linking_mode: LinkingMode,
112) -> (String, TrybuildConfig) {
113    let source_dir = cargo::manifest_dir().unwrap();
114    let source_manifest = dependencies::get_manifest(&source_dir).unwrap();
115    let crate_name = source_manifest.package.name.replace("-", "_");
116
117    let is_test = IS_TEST.load(std::sync::atomic::Ordering::Relaxed);
118
119    let generated_code = compile_graph_trybuild(
120        graph,
121        extra_stmts,
122        sidecars,
123        &crate_name,
124        is_test,
125        deploy_mode,
126    );
127
128    let inlined_staged = if is_test {
129        let raw_toml_manifest = toml::from_str::<toml::Value>(
130            &fs::read_to_string(path!(source_dir / "Cargo.toml")).unwrap(),
131        )
132        .unwrap();
133
134        let maybe_custom_lib_path = raw_toml_manifest
135            .get("lib")
136            .and_then(|lib| lib.get("path"))
137            .and_then(|path| path.as_str());
138
139        let mut gen_staged = stageleft_tool::gen_staged_trybuild(
140            &maybe_custom_lib_path
141                .map(|s| path!(source_dir / s))
142                .unwrap_or_else(|| path!(source_dir / "src" / "lib.rs")),
143            &path!(source_dir / "Cargo.toml"),
144            &crate_name,
145            Some("hydro___test".to_owned()),
146        );
147
148        gen_staged.attrs.insert(
149            0,
150            syn::parse_quote! {
151                #![allow(
152                    unused,
153                    ambiguous_glob_reexports,
154                    clippy::suspicious_else_formatting,
155                    unexpected_cfgs,
156                    reason = "generated code"
157                )]
158            },
159        );
160
161        Some(prettyplease::unparse(&gen_staged))
162    } else {
163        None
164    };
165
166    let source = prettyplease::unparse(&generated_code);
167
168    let hash = format!("{:X}", Sha256::digest(&source))
169        .chars()
170        .take(8)
171        .collect::<String>();
172
173    let bin_name = if let Some(bin_name_prefix) = &bin_name_prefix {
174        format!("{}_{}", clean_bin_name_prefix(bin_name_prefix), &hash)
175    } else {
176        hash
177    };
178
179    let (project_dir, target_dir, mut cur_bin_enabled_features) = create_trybuild().unwrap();
180
181    // Determine which crate's examples folder to use based on linking mode
182    let examples_dir = match linking_mode {
183        LinkingMode::Static => path!(project_dir / "examples"),
184        #[cfg(feature = "deploy")]
185        LinkingMode::Dynamic => path!(project_dir / "dylib-examples" / "examples"),
186    };
187
188    // TODO(shadaj): garbage collect this directory occasionally
189    fs::create_dir_all(&examples_dir).unwrap();
190
191    let out_path = path!(examples_dir / format!("{bin_name}.rs"));
192    {
193        let _concurrent_test_lock = CONCURRENT_TEST_LOCK.lock().unwrap();
194        write_atomic(source.as_ref(), &out_path).unwrap();
195    }
196
197    if let Some(inlined_staged) = inlined_staged {
198        let staged_path = path!(project_dir / "src" / "__staged.rs");
199        {
200            let _concurrent_test_lock = CONCURRENT_TEST_LOCK.lock().unwrap();
201            write_atomic(inlined_staged.as_bytes(), &staged_path).unwrap();
202        }
203    }
204
205    if is_test {
206        if cur_bin_enabled_features.is_none() {
207            cur_bin_enabled_features = Some(vec![]);
208        }
209
210        cur_bin_enabled_features
211            .as_mut()
212            .unwrap()
213            .push("hydro___test".to_owned());
214    }
215
216    (
217        bin_name,
218        TrybuildConfig {
219            project_dir,
220            target_dir,
221            features: cur_bin_enabled_features,
222            #[cfg(feature = "deploy")]
223            linking_mode,
224        },
225    )
226}
227
228#[cfg(any(feature = "deploy", feature = "maelstrom"))]
229pub fn compile_graph_trybuild(
230    partitioned_graph: DfirGraph,
231    extra_stmts: &[syn::Stmt],
232    sidecars: &[syn::Expr],
233    crate_name: &str,
234    is_test: bool,
235    deploy_mode: DeployMode,
236) -> syn::File {
237    use crate::staging_util::get_this_crate;
238
239    let mut diagnostics = Diagnostics::new();
240    let mut dfir_expr: syn::Expr = syn::parse2(
241        partitioned_graph
242            .as_code(&quote! { __root_dfir_rs }, true, quote!(), &mut diagnostics)
243            .expect("DFIR code generation failed with diagnostics."),
244    )
245    .unwrap();
246
247    if is_test {
248        UseTestModeStaged { crate_name }.visit_expr_mut(&mut dfir_expr);
249    }
250
251    let orig_crate_name = quote::format_ident!("{}", crate_name);
252    let trybuild_crate_name_ident = quote::format_ident!("{}_hydro_trybuild", crate_name);
253    let root = get_this_crate();
254    let tokio_main_ident = format!("{}::runtime_support::tokio", root);
255    let dfir_ident = quote::format_ident!("{}", crate::compile::DFIR_IDENT);
256
257    let source_ast: syn::File = match deploy_mode {
258        #[cfg(any(feature = "docker_deploy", feature = "ecs_deploy"))]
259        DeployMode::Containerized => {
260            syn::parse_quote! {
261                #![allow(unused_imports, unused_crate_dependencies, missing_docs, non_snake_case)]
262                use #trybuild_crate_name_ident::__root as #orig_crate_name;
263                use #trybuild_crate_name_ident::__root::*;
264                use #trybuild_crate_name_ident::__staged::__deps::*;
265                use #root::prelude::*;
266                use #root::runtime_support::dfir_rs as __root_dfir_rs;
267                pub use #trybuild_crate_name_ident::__staged;
268
269                #[#root::runtime_support::tokio::main(crate = #tokio_main_ident, flavor = "current_thread")]
270                async fn main() {
271                    #root::telemetry::initialize_tracing();
272
273                    #( #extra_stmts )*
274
275                    let mut #dfir_ident = #dfir_expr;
276
277                    let local_set = #root::runtime_support::tokio::task::LocalSet::new();
278                    #(
279                        let _ = local_set.spawn_local( #sidecars ); // Uses #dfir_ident
280                    )*
281
282                    let _ = local_set.run_until(#dfir_ident.run()).await;
283                }
284            }
285        }
286        #[cfg(feature = "deploy")]
287        DeployMode::HydroDeploy => {
288            syn::parse_quote! {
289                #![allow(unused_imports, unused_crate_dependencies, missing_docs, non_snake_case)]
290                use #trybuild_crate_name_ident::__root as #orig_crate_name;
291                use #trybuild_crate_name_ident::__root::*;
292                use #trybuild_crate_name_ident::__staged::__deps::*;
293                use #root::prelude::*;
294                use #root::runtime_support::dfir_rs as __root_dfir_rs;
295                pub use #trybuild_crate_name_ident::__staged;
296
297                #[#root::runtime_support::tokio::main(crate = #tokio_main_ident, flavor = "current_thread")]
298                async fn main() {
299                    let __hydro_lang_trybuild_cli_owned: #root::runtime_support::hydro_deploy_integration::DeployPorts<#root::__staged::deploy::deploy_runtime::HydroMeta> = #root::runtime_support::launch::init_no_ack_start().await;
300                    let __hydro_lang_trybuild_cli = &__hydro_lang_trybuild_cli_owned;
301
302                    #( #extra_stmts )*
303
304                    let mut #dfir_ident = #dfir_expr;
305                    println!("ack start");
306
307                    // TODO(mingwei): initialize `tracing` at this point in execution.
308                    // After "ack start" is when we can print whatever we want.
309
310                    let local_set = #root::runtime_support::tokio::task::LocalSet::new();
311                    #(
312                        let _ = local_set.spawn_local( #sidecars ); // Uses #dfir_ident
313                    )*
314
315                    let _ = local_set.run_until(#root::runtime_support::launch::run_stdin_commands(
316                        async move {
317                            #dfir_ident.run().await
318                        }
319                    )).await;
320                }
321            }
322        }
323        #[cfg(feature = "maelstrom")]
324        DeployMode::Maelstrom => {
325            syn::parse_quote! {
326                #![allow(unused_imports, unused_crate_dependencies, missing_docs, non_snake_case)]
327                use #trybuild_crate_name_ident::__root as #orig_crate_name;
328                use #trybuild_crate_name_ident::__root::*;
329                use #trybuild_crate_name_ident::__staged::__deps::*;
330                use #root::prelude::*;
331                use #root::runtime_support::dfir_rs as __root_dfir_rs;
332                pub use #trybuild_crate_name_ident::__staged;
333
334                #[allow(unused)]
335                fn __hydro_runtime<'a>(
336                    __hydro_lang_maelstrom_meta: &'a #root::__staged::deploy::maelstrom::deploy_runtime_maelstrom::MaelstromMeta
337                )
338                    -> #root::runtime_support::dfir_rs::scheduled::context::Dfir<impl #root::runtime_support::dfir_rs::scheduled::context::TickClosure + 'a>
339                {
340                    #( #extra_stmts )*
341
342                    #dfir_expr
343                }
344
345                #[#root::runtime_support::tokio::main(crate = #tokio_main_ident, flavor = "current_thread")]
346                async fn main() {
347                    #root::telemetry::initialize_tracing();
348
349                    // Initialize Maelstrom protocol - read init message and send init_ok
350                    let __hydro_lang_maelstrom_meta = #root::__staged::deploy::maelstrom::deploy_runtime_maelstrom::maelstrom_init();
351
352                    let mut #dfir_ident = __hydro_runtime(&__hydro_lang_maelstrom_meta);
353
354                    __hydro_lang_maelstrom_meta.start_receiving(); // start receiving messages after initializing subscribers
355
356                    let local_set = #root::runtime_support::tokio::task::LocalSet::new();
357                    #(
358                        let _ = local_set.spawn_local( #sidecars ); // Uses #dfir_ident
359                    )*
360
361                    let _ = local_set.run_until(#dfir_ident.run()).await;
362                }
363            }
364        }
365    };
366    source_ast
367}
368
369pub fn create_trybuild()
370-> Result<(PathBuf, PathBuf, Option<Vec<String>>), trybuild_internals_api::error::Error> {
371    let Metadata {
372        target_directory: target_dir,
373        workspace_root: workspace,
374        packages,
375    } = cargo::metadata()?;
376
377    let source_dir = cargo::manifest_dir()?;
378    let mut source_manifest = dependencies::get_manifest(&source_dir)?;
379
380    let mut dev_dependency_features = vec![];
381    source_manifest.dev_dependencies.retain(|k, v| {
382        if source_manifest.dependencies.contains_key(k) {
383            // already a non-dev dependency, so drop the dep and put the features under the test flag
384            for feat in &v.features {
385                dev_dependency_features.push(format!("{}/{}", k, feat));
386            }
387
388            false
389        } else {
390            // only enable this in test mode, so make it optional otherwise
391            dev_dependency_features.push(format!("dep:{k}"));
392
393            v.optional = true;
394            true
395        }
396    });
397
398    let mut features = features::find();
399
400    let path_dependencies = source_manifest
401        .dependencies
402        .iter()
403        .filter_map(|(name, dep)| {
404            let path = dep.path.as_ref()?;
405            if packages.iter().any(|p| &p.name == name) {
406                // Skip path dependencies coming from the workspace itself
407                None
408            } else {
409                Some(PathDependency {
410                    name: name.clone(),
411                    normalized_path: path.canonicalize().ok()?,
412                })
413            }
414        })
415        .collect();
416
417    let crate_name = source_manifest.package.name.clone();
418    let project_dir = path!(target_dir / "hydro_trybuild" / crate_name /);
419    fs::create_dir_all(&project_dir)?;
420
421    let project_name = format!("{}-hydro-trybuild", crate_name);
422    let mut manifest = Runner::make_manifest(
423        &workspace,
424        &project_name,
425        &source_dir,
426        &packages,
427        &[],
428        source_manifest,
429    )?;
430
431    if let Some(enabled_features) = &mut features {
432        enabled_features
433            .retain(|feature| manifest.features.contains_key(feature) || feature == "default");
434    }
435
436    for runtime_feature in HYDRO_RUNTIME_FEATURES {
437        manifest.features.insert(
438            format!("hydro___feature_{runtime_feature}"),
439            vec![format!("hydro_lang/{runtime_feature}")],
440        );
441    }
442
443    manifest
444        .dependencies
445        .get_mut("hydro_lang")
446        .unwrap()
447        .features
448        .push("runtime_support".to_owned());
449
450    manifest
451        .features
452        .insert("hydro___test".to_owned(), dev_dependency_features);
453
454    if manifest
455        .workspace
456        .as_ref()
457        .is_some_and(|w| w.dependencies.is_empty())
458    {
459        manifest.workspace = None;
460    }
461
462    let project = Project {
463        dir: project_dir,
464        source_dir,
465        target_dir,
466        name: project_name.clone(),
467        update: Update::env()?,
468        has_pass: false,
469        has_compile_fail: false,
470        features,
471        workspace,
472        path_dependencies,
473        manifest,
474        keep_going: false,
475    };
476
477    {
478        let _concurrent_test_lock = CONCURRENT_TEST_LOCK.lock().unwrap();
479
480        let project_lock = File::create(path!(project.dir / ".hydro-trybuild-lock"))?;
481        project_lock.lock()?;
482
483        fs::create_dir_all(path!(project.dir / "src"))?;
484        fs::create_dir_all(path!(project.dir / "examples"))?;
485
486        let crate_name_ident = syn::Ident::new(
487            &crate_name.replace("-", "_"),
488            proc_macro2::Span::call_site(),
489        );
490
491        write_atomic(
492            prettyplease::unparse(&syn::parse_quote! {
493                #![allow(unused_imports, unused_crate_dependencies, missing_docs, non_snake_case)]
494
495                pub use #crate_name_ident as __root;
496
497                #[cfg(feature = "hydro___test")]
498                pub mod __staged;
499
500                #[cfg(not(feature = "hydro___test"))]
501                pub use #crate_name_ident::__staged;
502            })
503            .as_bytes(),
504            &path!(project.dir / "src" / "lib.rs"),
505        )
506        .unwrap();
507
508        let base_manifest = toml::to_string(&project.manifest)?;
509
510        // Collect feature names for forwarding to dylib and dylib-examples crates
511        let feature_names: Vec<_> = project.manifest.features.keys().cloned().collect();
512
513        // Create dylib crate directory
514        let dylib_dir = path!(project.dir / "dylib");
515        fs::create_dir_all(path!(dylib_dir / "src"))?;
516
517        let trybuild_crate_name_ident = syn::Ident::new(
518            &project_name.replace("-", "_"),
519            proc_macro2::Span::call_site(),
520        );
521        write_atomic(
522            prettyplease::unparse(&syn::parse_quote! {
523                #![allow(unused_imports, unused_crate_dependencies, missing_docs, non_snake_case)]
524                pub use #trybuild_crate_name_ident::*;
525            })
526            .as_bytes(),
527            &path!(dylib_dir / "src" / "lib.rs"),
528        )?;
529
530        let serialized_edition = toml::to_string(
531            &vec![("edition", &project.manifest.package.edition)]
532                .into_iter()
533                .collect::<std::collections::HashMap<_, _>>(),
534        )
535        .unwrap();
536
537        // Dylib crate Cargo.toml - only dylib crate-type, no features needed
538        // Features are enabled on the base crate directly from dylib-examples
539        // On Windows, we currently disable dylib compilation due to https://github.com/bevyengine/bevy/pull/2016
540        let dylib_manifest = format!(
541            r#"[package]
542name = "{project_name}-dylib"
543version = "0.0.0"
544{}
545
546[lib]
547crate-type = ["{}"]
548
549[dependencies]
550{project_name} = {{ path = "..", default-features = false }}
551"#,
552            serialized_edition,
553            if cfg!(target_os = "windows") {
554                "rlib"
555            } else {
556                "dylib"
557            }
558        );
559        write_atomic(dylib_manifest.as_ref(), &path!(dylib_dir / "Cargo.toml"))?;
560
561        let dylib_examples_dir = path!(project.dir / "dylib-examples");
562        fs::create_dir_all(path!(dylib_examples_dir / "src"))?;
563        fs::create_dir_all(path!(dylib_examples_dir / "examples"))?;
564
565        write_atomic(
566            b"#![allow(unused_crate_dependencies)]\n",
567            &path!(dylib_examples_dir / "src" / "lib.rs"),
568        )?;
569
570        // Build feature forwarding for dylib-examples - forward directly to base crate
571        let features_section = feature_names
572            .iter()
573            .map(|f| format!("{f} = [\"{project_name}/{f}\"]"))
574            .collect::<Vec<_>>()
575            .join("\n");
576
577        // Dylib-examples crate Cargo.toml - has dylib as dev-dependency, features go to base crate
578        let dylib_examples_manifest = format!(
579            r#"[package]
580name = "{project_name}-dylib-examples"
581version = "0.0.0"
582{}
583
584[dev-dependencies]
585{project_name} = {{ path = "..", default-features = false }}
586{project_name}-dylib = {{ path = "../dylib", default-features = false }}
587
588[features]
589{features_section}
590
591[[example]]
592name = "sim-dylib"
593crate-type = ["cdylib"]
594"#,
595            serialized_edition
596        );
597        write_atomic(
598            dylib_examples_manifest.as_ref(),
599            &path!(dylib_examples_dir / "Cargo.toml"),
600        )?;
601
602        // sim-dylib.rs for the base crate and dylib-examples crate
603        let sim_dylib_contents = prettyplease::unparse(&syn::parse_quote! {
604            #![allow(unused_imports, unused_crate_dependencies, missing_docs, non_snake_case)]
605            include!(std::concat!(env!("TRYBUILD_LIB_NAME"), ".rs"));
606        });
607        write_atomic(
608            sim_dylib_contents.as_bytes(),
609            &path!(project.dir / "examples" / "sim-dylib.rs"),
610        )?;
611        write_atomic(
612            sim_dylib_contents.as_bytes(),
613            &path!(dylib_examples_dir / "examples" / "sim-dylib.rs"),
614        )?;
615
616        let workspace_manifest = format!(
617            r#"{}
618[[example]]
619name = "sim-dylib"
620crate-type = ["cdylib"]
621
622[workspace]
623members = ["dylib", "dylib-examples"]
624"#,
625            base_manifest,
626        );
627
628        write_atomic(
629            workspace_manifest.as_ref(),
630            &path!(project.dir / "Cargo.toml"),
631        )?;
632
633        // Compute hash for cache invalidation (dylib and dylib-examples are functions of workspace_manifest)
634        let manifest_hash = format!("{:X}", Sha256::digest(&workspace_manifest))
635            .chars()
636            .take(8)
637            .collect::<String>();
638
639        let workspace_cargo_lock = path!(project.workspace / "Cargo.lock");
640        let workspace_cargo_lock_contents_and_hash = if workspace_cargo_lock.exists() {
641            let cargo_lock_contents = fs::read_to_string(&workspace_cargo_lock)?;
642
643            let hash = format!("{:X}", Sha256::digest(&cargo_lock_contents))
644                .chars()
645                .take(8)
646                .collect::<String>();
647
648            Some((cargo_lock_contents, hash))
649        } else {
650            None
651        };
652
653        let trybuild_hash = format!(
654            "{}-{}",
655            manifest_hash,
656            workspace_cargo_lock_contents_and_hash
657                .as_ref()
658                .map(|(_contents, hash)| &**hash)
659                .unwrap_or_default()
660        );
661
662        if !check_contents(
663            trybuild_hash.as_bytes(),
664            &path!(project.dir / ".hydro-trybuild-manifest"),
665        )
666        .is_ok_and(|b| b)
667        {
668            // this is expensive, so we only do it if the manifest changed
669            if let Some((cargo_lock_contents, _)) = workspace_cargo_lock_contents_and_hash {
670                // only overwrite when the hash changed, because writing Cargo.lock must be
671                // immediately followed by a local `cargo update -w`
672                write_atomic(
673                    cargo_lock_contents.as_ref(),
674                    &path!(project.dir / "Cargo.lock"),
675                )?;
676            } else {
677                let _ = cargo::cargo(&project).arg("generate-lockfile").status();
678            }
679
680            // not `--offline` because some new runtime features may be enabled
681            std::process::Command::new("cargo")
682                .current_dir(&project.dir)
683                .args(["update", "-w"]) // -w to not actually update any versions
684                .stdout(std::process::Stdio::null())
685                .stderr(std::process::Stdio::null())
686                .status()
687                .unwrap();
688
689            write_atomic(
690                trybuild_hash.as_bytes(),
691                &path!(project.dir / ".hydro-trybuild-manifest"),
692            )?;
693        }
694
695        // Create examples folder for base crate (static linking)
696        let examples_folder = path!(project.dir / "examples");
697        fs::create_dir_all(&examples_folder)?;
698
699        let workspace_dot_cargo_config_toml = path!(project.workspace / ".cargo" / "config.toml");
700        if workspace_dot_cargo_config_toml.exists() {
701            let dot_cargo_folder = path!(project.dir / ".cargo");
702            fs::create_dir_all(&dot_cargo_folder)?;
703
704            write_atomic(
705                fs::read_to_string(&workspace_dot_cargo_config_toml)?.as_ref(),
706                &path!(dot_cargo_folder / "config.toml"),
707            )?;
708        }
709
710        let vscode_folder = path!(project.dir / ".vscode");
711        fs::create_dir_all(&vscode_folder)?;
712        write_atomic(
713            include_bytes!("./vscode-trybuild.json"),
714            &path!(vscode_folder / "settings.json"),
715        )?;
716    }
717
718    Ok((
719        project.dir.as_ref().into(),
720        project.target_dir.as_ref().into(),
721        project.features,
722    ))
723}
724
725fn check_contents(contents: &[u8], path: &Path) -> Result<bool, std::io::Error> {
726    let mut file = File::options()
727        .read(true)
728        .write(false)
729        .create(false)
730        .truncate(false)
731        .open(path)?;
732    file.lock()?;
733
734    let mut existing_contents = Vec::new();
735    file.read_to_end(&mut existing_contents)?;
736    Ok(existing_contents == contents)
737}
738
739pub(crate) fn write_atomic(contents: &[u8], path: &Path) -> Result<(), std::io::Error> {
740    let mut file = File::options()
741        .read(true)
742        .write(true)
743        .create(true)
744        .truncate(false)
745        .open(path)?;
746
747    let mut existing_contents = Vec::new();
748    file.read_to_end(&mut existing_contents)?;
749    if existing_contents != contents {
750        file.lock()?;
751        file.seek(SeekFrom::Start(0))?;
752        file.set_len(0)?;
753        file.write_all(contents)?;
754    }
755
756    Ok(())
757}