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::__staged::__deps::*;
264                use #root::prelude::*;
265                use #root::runtime_support::dfir_rs as __root_dfir_rs;
266                pub use #trybuild_crate_name_ident::__staged;
267
268                #[#root::runtime_support::tokio::main(crate = #tokio_main_ident, flavor = "current_thread")]
269                async fn main() {
270                    #root::telemetry::initialize_tracing();
271
272                    #( #extra_stmts )*
273
274                    let mut #dfir_ident = #dfir_expr;
275
276                    let local_set = #root::runtime_support::tokio::task::LocalSet::new();
277                    #(
278                        let _ = local_set.spawn_local( #sidecars ); // Uses #dfir_ident
279                    )*
280
281                    let _ = local_set.run_until(#dfir_ident.run()).await;
282                }
283            }
284        }
285        #[cfg(feature = "deploy")]
286        DeployMode::HydroDeploy => {
287            syn::parse_quote! {
288                #![allow(unused_imports, unused_crate_dependencies, missing_docs, non_snake_case)]
289                use #trybuild_crate_name_ident::__root as #orig_crate_name;
290                use #trybuild_crate_name_ident::__staged::__deps::*;
291                use #root::prelude::*;
292                use #root::runtime_support::dfir_rs as __root_dfir_rs;
293                pub use #trybuild_crate_name_ident::__staged;
294
295                #[#root::runtime_support::tokio::main(crate = #tokio_main_ident, flavor = "current_thread")]
296                async fn main() {
297                    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;
298                    let __hydro_lang_trybuild_cli = &__hydro_lang_trybuild_cli_owned;
299
300                    #( #extra_stmts )*
301
302                    let mut #dfir_ident = #dfir_expr;
303                    println!("ack start");
304
305                    // TODO(mingwei): initialize `tracing` at this point in execution.
306                    // After "ack start" is when we can print whatever we want.
307
308                    let local_set = #root::runtime_support::tokio::task::LocalSet::new();
309                    #(
310                        let _ = local_set.spawn_local( #sidecars ); // Uses #dfir_ident
311                    )*
312
313                    let _ = local_set.run_until(#root::runtime_support::launch::run_stdin_commands(
314                        async move {
315                            #dfir_ident.run().await
316                        }
317                    )).await;
318                }
319            }
320        }
321        #[cfg(feature = "maelstrom")]
322        DeployMode::Maelstrom => {
323            syn::parse_quote! {
324                #![allow(unused_imports, unused_crate_dependencies, missing_docs, non_snake_case)]
325                use #trybuild_crate_name_ident::__root as #orig_crate_name;
326                use #trybuild_crate_name_ident::__staged::__deps::*;
327                use #root::prelude::*;
328                use #root::runtime_support::dfir_rs as __root_dfir_rs;
329                pub use #trybuild_crate_name_ident::__staged;
330
331                #[allow(unused)]
332                fn __hydro_runtime<'a>(
333                    __hydro_lang_maelstrom_meta: &'a #root::__staged::deploy::maelstrom::deploy_runtime_maelstrom::MaelstromMeta
334                )
335                    -> #root::runtime_support::dfir_rs::scheduled::context::Dfir<impl #root::runtime_support::dfir_rs::scheduled::context::TickClosure + 'a>
336                {
337                    #( #extra_stmts )*
338
339                    #dfir_expr
340                }
341
342                #[#root::runtime_support::tokio::main(crate = #tokio_main_ident, flavor = "current_thread")]
343                async fn main() {
344                    #root::telemetry::initialize_tracing();
345
346                    // Initialize Maelstrom protocol - read init message and send init_ok
347                    let __hydro_lang_maelstrom_meta = #root::__staged::deploy::maelstrom::deploy_runtime_maelstrom::maelstrom_init();
348
349                    let mut #dfir_ident = __hydro_runtime(&__hydro_lang_maelstrom_meta);
350
351                    __hydro_lang_maelstrom_meta.start_receiving(); // start receiving messages after initializing subscribers
352
353                    let local_set = #root::runtime_support::tokio::task::LocalSet::new();
354                    #(
355                        let _ = local_set.spawn_local( #sidecars ); // Uses #dfir_ident
356                    )*
357
358                    let _ = local_set.run_until(#dfir_ident.run()).await;
359                }
360            }
361        }
362    };
363    source_ast
364}
365
366pub fn create_trybuild()
367-> Result<(PathBuf, PathBuf, Option<Vec<String>>), trybuild_internals_api::error::Error> {
368    let Metadata {
369        target_directory: target_dir,
370        workspace_root: workspace,
371        packages,
372    } = cargo::metadata()?;
373
374    let source_dir = cargo::manifest_dir()?;
375    let mut source_manifest = dependencies::get_manifest(&source_dir)?;
376
377    let mut dev_dependency_features = vec![];
378    source_manifest.dev_dependencies.retain(|k, v| {
379        if source_manifest.dependencies.contains_key(k) {
380            // already a non-dev dependency, so drop the dep and put the features under the test flag
381            for feat in &v.features {
382                dev_dependency_features.push(format!("{}/{}", k, feat));
383            }
384
385            false
386        } else {
387            // only enable this in test mode, so make it optional otherwise
388            dev_dependency_features.push(format!("dep:{k}"));
389
390            v.optional = true;
391            true
392        }
393    });
394
395    let mut features = features::find();
396
397    let path_dependencies = source_manifest
398        .dependencies
399        .iter()
400        .filter_map(|(name, dep)| {
401            let path = dep.path.as_ref()?;
402            if packages.iter().any(|p| &p.name == name) {
403                // Skip path dependencies coming from the workspace itself
404                None
405            } else {
406                Some(PathDependency {
407                    name: name.clone(),
408                    normalized_path: path.canonicalize().ok()?,
409                })
410            }
411        })
412        .collect();
413
414    let crate_name = source_manifest.package.name.clone();
415    let project_dir = path!(target_dir / "hydro_trybuild" / crate_name /);
416    fs::create_dir_all(&project_dir)?;
417
418    let project_name = format!("{}-hydro-trybuild", crate_name);
419    let mut manifest = Runner::make_manifest(
420        &workspace,
421        &project_name,
422        &source_dir,
423        &packages,
424        &[],
425        source_manifest,
426    )?;
427
428    if let Some(enabled_features) = &mut features {
429        enabled_features
430            .retain(|feature| manifest.features.contains_key(feature) || feature == "default");
431    }
432
433    for runtime_feature in HYDRO_RUNTIME_FEATURES {
434        manifest.features.insert(
435            format!("hydro___feature_{runtime_feature}"),
436            vec![format!("hydro_lang/{runtime_feature}")],
437        );
438    }
439
440    manifest
441        .dependencies
442        .get_mut("hydro_lang")
443        .unwrap()
444        .features
445        .push("runtime_support".to_owned());
446
447    manifest
448        .features
449        .insert("hydro___test".to_owned(), dev_dependency_features);
450
451    if manifest
452        .workspace
453        .as_ref()
454        .is_some_and(|w| w.dependencies.is_empty())
455    {
456        manifest.workspace = None;
457    }
458
459    let project = Project {
460        dir: project_dir,
461        source_dir,
462        target_dir,
463        name: project_name.clone(),
464        update: Update::env()?,
465        has_pass: false,
466        has_compile_fail: false,
467        features,
468        workspace,
469        path_dependencies,
470        manifest,
471        keep_going: false,
472    };
473
474    {
475        let _concurrent_test_lock = CONCURRENT_TEST_LOCK.lock().unwrap();
476
477        let project_lock = File::create(path!(project.dir / ".hydro-trybuild-lock"))?;
478        project_lock.lock()?;
479
480        fs::create_dir_all(path!(project.dir / "src"))?;
481        fs::create_dir_all(path!(project.dir / "examples"))?;
482
483        let crate_name_ident = syn::Ident::new(
484            &crate_name.replace("-", "_"),
485            proc_macro2::Span::call_site(),
486        );
487
488        write_atomic(
489            prettyplease::unparse(&syn::parse_quote! {
490                #![allow(unused_imports, unused_crate_dependencies, missing_docs, non_snake_case)]
491
492                pub use #crate_name_ident as __root;
493
494                #[cfg(feature = "hydro___test")]
495                pub mod __staged;
496
497                #[cfg(not(feature = "hydro___test"))]
498                pub use #crate_name_ident::__staged;
499            })
500            .as_bytes(),
501            &path!(project.dir / "src" / "lib.rs"),
502        )
503        .unwrap();
504
505        let base_manifest = toml::to_string(&project.manifest)?;
506
507        // Collect feature names for forwarding to dylib and dylib-examples crates
508        let feature_names: Vec<_> = project.manifest.features.keys().cloned().collect();
509
510        // Create dylib crate directory
511        let dylib_dir = path!(project.dir / "dylib");
512        fs::create_dir_all(path!(dylib_dir / "src"))?;
513
514        let trybuild_crate_name_ident = syn::Ident::new(
515            &project_name.replace("-", "_"),
516            proc_macro2::Span::call_site(),
517        );
518        write_atomic(
519            prettyplease::unparse(&syn::parse_quote! {
520                #![allow(unused_imports, unused_crate_dependencies, missing_docs, non_snake_case)]
521                pub use #trybuild_crate_name_ident::*;
522            })
523            .as_bytes(),
524            &path!(dylib_dir / "src" / "lib.rs"),
525        )?;
526
527        let serialized_edition = toml::to_string(
528            &vec![("edition", &project.manifest.package.edition)]
529                .into_iter()
530                .collect::<std::collections::HashMap<_, _>>(),
531        )
532        .unwrap();
533
534        // Dylib crate Cargo.toml - only dylib crate-type, no features needed
535        // Features are enabled on the base crate directly from dylib-examples
536        // On Windows, we currently disable dylib compilation due to https://github.com/bevyengine/bevy/pull/2016
537        let dylib_manifest = format!(
538            r#"[package]
539name = "{project_name}-dylib"
540version = "0.0.0"
541{}
542
543[lib]
544crate-type = ["{}"]
545
546[dependencies]
547{project_name} = {{ path = "..", default-features = false }}
548"#,
549            serialized_edition,
550            if cfg!(target_os = "windows") {
551                "rlib"
552            } else {
553                "dylib"
554            }
555        );
556        write_atomic(dylib_manifest.as_ref(), &path!(dylib_dir / "Cargo.toml"))?;
557
558        let dylib_examples_dir = path!(project.dir / "dylib-examples");
559        fs::create_dir_all(path!(dylib_examples_dir / "src"))?;
560        fs::create_dir_all(path!(dylib_examples_dir / "examples"))?;
561
562        write_atomic(
563            b"#![allow(unused_crate_dependencies)]\n",
564            &path!(dylib_examples_dir / "src" / "lib.rs"),
565        )?;
566
567        // Build feature forwarding for dylib-examples - forward directly to base crate
568        let features_section = feature_names
569            .iter()
570            .map(|f| format!("{f} = [\"{project_name}/{f}\"]"))
571            .collect::<Vec<_>>()
572            .join("\n");
573
574        // Dylib-examples crate Cargo.toml - has dylib as dev-dependency, features go to base crate
575        let dylib_examples_manifest = format!(
576            r#"[package]
577name = "{project_name}-dylib-examples"
578version = "0.0.0"
579{}
580
581[dev-dependencies]
582{project_name} = {{ path = "..", default-features = false }}
583{project_name}-dylib = {{ path = "../dylib", default-features = false }}
584
585[features]
586{features_section}
587
588[[example]]
589name = "sim-dylib"
590crate-type = ["cdylib"]
591"#,
592            serialized_edition
593        );
594        write_atomic(
595            dylib_examples_manifest.as_ref(),
596            &path!(dylib_examples_dir / "Cargo.toml"),
597        )?;
598
599        // sim-dylib.rs for the base crate and dylib-examples crate
600        let sim_dylib_contents = prettyplease::unparse(&syn::parse_quote! {
601            #![allow(unused_imports, unused_crate_dependencies, missing_docs, non_snake_case)]
602            include!(std::concat!(env!("TRYBUILD_LIB_NAME"), ".rs"));
603        });
604        write_atomic(
605            sim_dylib_contents.as_bytes(),
606            &path!(project.dir / "examples" / "sim-dylib.rs"),
607        )?;
608        write_atomic(
609            sim_dylib_contents.as_bytes(),
610            &path!(dylib_examples_dir / "examples" / "sim-dylib.rs"),
611        )?;
612
613        let workspace_manifest = format!(
614            r#"{}
615[[example]]
616name = "sim-dylib"
617crate-type = ["cdylib"]
618
619[workspace]
620members = ["dylib", "dylib-examples"]
621"#,
622            base_manifest,
623        );
624
625        write_atomic(
626            workspace_manifest.as_ref(),
627            &path!(project.dir / "Cargo.toml"),
628        )?;
629
630        // Compute hash for cache invalidation (dylib and dylib-examples are functions of workspace_manifest)
631        let manifest_hash = format!("{:X}", Sha256::digest(&workspace_manifest))
632            .chars()
633            .take(8)
634            .collect::<String>();
635
636        let workspace_cargo_lock = path!(project.workspace / "Cargo.lock");
637        let workspace_cargo_lock_contents_and_hash = if workspace_cargo_lock.exists() {
638            let cargo_lock_contents = fs::read_to_string(&workspace_cargo_lock)?;
639
640            let hash = format!("{:X}", Sha256::digest(&cargo_lock_contents))
641                .chars()
642                .take(8)
643                .collect::<String>();
644
645            Some((cargo_lock_contents, hash))
646        } else {
647            None
648        };
649
650        let trybuild_hash = format!(
651            "{}-{}",
652            manifest_hash,
653            workspace_cargo_lock_contents_and_hash
654                .as_ref()
655                .map(|(_contents, hash)| &**hash)
656                .unwrap_or_default()
657        );
658
659        if !check_contents(
660            trybuild_hash.as_bytes(),
661            &path!(project.dir / ".hydro-trybuild-manifest"),
662        )
663        .is_ok_and(|b| b)
664        {
665            // this is expensive, so we only do it if the manifest changed
666            if let Some((cargo_lock_contents, _)) = workspace_cargo_lock_contents_and_hash {
667                // only overwrite when the hash changed, because writing Cargo.lock must be
668                // immediately followed by a local `cargo update -w`
669                write_atomic(
670                    cargo_lock_contents.as_ref(),
671                    &path!(project.dir / "Cargo.lock"),
672                )?;
673            } else {
674                let _ = cargo::cargo(&project).arg("generate-lockfile").status();
675            }
676
677            // not `--offline` because some new runtime features may be enabled
678            std::process::Command::new("cargo")
679                .current_dir(&project.dir)
680                .args(["update", "-w"]) // -w to not actually update any versions
681                .stdout(std::process::Stdio::null())
682                .stderr(std::process::Stdio::null())
683                .status()
684                .unwrap();
685
686            write_atomic(
687                trybuild_hash.as_bytes(),
688                &path!(project.dir / ".hydro-trybuild-manifest"),
689            )?;
690        }
691
692        // Create examples folder for base crate (static linking)
693        let examples_folder = path!(project.dir / "examples");
694        fs::create_dir_all(&examples_folder)?;
695
696        let workspace_dot_cargo_config_toml = path!(project.workspace / ".cargo" / "config.toml");
697        if workspace_dot_cargo_config_toml.exists() {
698            let dot_cargo_folder = path!(project.dir / ".cargo");
699            fs::create_dir_all(&dot_cargo_folder)?;
700
701            write_atomic(
702                fs::read_to_string(&workspace_dot_cargo_config_toml)?.as_ref(),
703                &path!(dot_cargo_folder / "config.toml"),
704            )?;
705        }
706
707        let vscode_folder = path!(project.dir / ".vscode");
708        fs::create_dir_all(&vscode_folder)?;
709        write_atomic(
710            include_bytes!("./vscode-trybuild.json"),
711            &path!(vscode_folder / "settings.json"),
712        )?;
713    }
714
715    Ok((
716        project.dir.as_ref().into(),
717        project.target_dir.as_ref().into(),
718        project.features,
719    ))
720}
721
722fn check_contents(contents: &[u8], path: &Path) -> Result<bool, std::io::Error> {
723    let mut file = File::options()
724        .read(true)
725        .write(false)
726        .create(false)
727        .truncate(false)
728        .open(path)?;
729    file.lock()?;
730
731    let mut existing_contents = Vec::new();
732    file.read_to_end(&mut existing_contents)?;
733    Ok(existing_contents == contents)
734}
735
736pub(crate) fn write_atomic(contents: &[u8], path: &Path) -> Result<(), std::io::Error> {
737    let mut file = File::options()
738        .read(true)
739        .write(true)
740        .create(true)
741        .truncate(false)
742        .open(path)?;
743
744    let mut existing_contents = Vec::new();
745    file.read_to_end(&mut existing_contents)?;
746    if existing_contents != contents {
747        file.lock()?;
748        file.seek(SeekFrom::Start(0))?;
749        file.set_len(0)?;
750        file.write_all(contents)?;
751    }
752
753    Ok(())
754}