1// Copyright Materialize, Inc. and contributors. All rights reserved.
2//
3// Use of this software is governed by the Business Source License
4// included in the LICENSE file.
5//
6// As of the Change Date specified in that file, in accordance with
7// the Business Source License, use of this software will be governed
8// by the Apache License, Version 2.0.
910//! Helpers to generate the header of a Bazel file.
1112use crate::rules::LoadStatement;
13use crate::targets::RustTarget;
1415use super::ToBazelDefinition;
16use std::collections::BTreeMap;
1718use std::fmt;
1920static CODE_GENERATED_HEADER: &str = "# Code generated by cargo-gazelle DO NOT EDIT
2122# Copyright Materialize, Inc. and contributors. All rights reserved.
23#
24# Use of this software is governed by the Business Source License
25# included in the LICENSE file at the root of this repository.
26#
27# As of the Change Date specified in that file, in accordance with
28# the Business Source License, use of this software will be governed
29# by the Apache License, Version 2.0.
30";
3132/// Header to include on a BUILD.bazel file.
33///
34/// Includes special text to indicate this file is generated, and imports any necessary Rust rules.
35///
36/// TODO(parkmycar): This works for now but should surely be refactored.
37#[derive(Debug)]
38pub struct BazelHeader {
39 loads: Vec<LoadStatement>,
40}
4142impl BazelHeader {
43pub fn generate(targets: &[Box<dyn RustTarget>]) -> Self {
44let x = targets
45 .iter()
46 .flat_map(|t| t.rules().into_iter())
47 .map(|rule| (rule.module(), rule));
4849let mut rules = BTreeMap::new();
50for (module, rule) in x {
51let entry = rules.entry(module).or_insert(Vec::new());
52 entry.push(rule);
53 }
5455let loads = rules.into_iter().map(LoadStatement::from).collect();
5657 BazelHeader { loads }
58 }
59}
6061impl ToBazelDefinition for BazelHeader {
62fn format(&self, writer: &mut dyn fmt::Write) -> Result<(), fmt::Error> {
63writeln!(writer, "{CODE_GENERATED_HEADER}")?;
64writeln!(writer)?;
65writeln!(
66 writer,
67r#"package(default_visibility = ["//visibility:public"])"#
68)?;
69writeln!(writer)?;
7071// TODO(parkmcar): Handle differently named root repositories.
72writeln!(
73 writer,
74r#"load("@crates_io//:defs.bzl", "aliases", "all_crate_deps")"#
75)?;
7677for stmt in &self.loads {
78 stmt.format(writer)?;
79writeln!(writer)?;
80 }
8182Ok(())
83 }
84}