Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Rust] flatc build script wrapper #6453

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -120,6 +120,7 @@ dart/pubspec.lock
dart/.dart_tool/
dart/build/
dart/doc/api/
!rust/flatc
Cargo.lock
.corpus**
.seed**
Expand Down
15 changes: 15 additions & 0 deletions rust/flatc/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
[package]
name = "flatc"
version = "0.1.0"
edition = "2018"
authors = ["Richard Berry <rjsberry@pm.me>", "FlatBuffers Maintainers"]
license = "Apache-2.0"
build = "build.rs"
description = "Companion package to flatbuffers to generate code at compile time."
homepage = "https://google.github.io/flatbuffers/"
repository = "https://github.com/google/flatbuffers"
keywords = ["flatbuffers", "serialization", "zero-copy"]
categories = ["encoding", "data-structures", "memory-management"]

[build-dependencies]
cmake = "0.1"
61 changes: 61 additions & 0 deletions rust/flatc/build.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
/*
* Copyright 2018 Google Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

use std::{env, fs, path::Path, process::Command};

fn main() {
let git_sha = if let Ok(output) = Command::new("git")
.args(&["rev-parse", "--short=7", "HEAD"])
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

no need to make it short imo

.output()
{
String::from_utf8(output.stdout).expect("utf8 sha")
} else {
"unavailable".to_owned()
};

println!("cargo:rustc-env=FLATBUFFERS_COMMIT_SHA={}", git_sha.trim());

if let Ok(output) = Command::new("cmake").arg("--version").output() {
println!("\n\n{:?}\n\n", output);
}

let flatc_root = Path::new(&env::var("CARGO_MANIFEST_DIR").unwrap())
.join("..")
.join("..");

// CI workaround
let cmake_cache = flatc_root.join("CMakeCache.txt");
if cmake_cache.exists() {
fs::remove_file(cmake_cache).expect("remove cmake cache");
}

let mut cmake = ::cmake::Config::new(flatc_root);

cmake.define("CMAKE_BUILD_TYPE", "Release");
cmake.define("CMAKE_INSTALL_BINDIR", "bin");
cmake.define("FLATBUFFERS_BUILD_TESTS", "OFF");
cmake.define("FLATBUFFERS_BUILD_FLATLIB", "OFF");
cmake.define("FLATBUFFERS_BUILD_FLATHASH", "OFF");
#[cfg(windows)]
cmake.cxxflag("/EHsc");

#[cfg(windows)]
let _ = if let Ok(cmake_vs_version) = env::var("CMAKE_VS_VERSION") {
cmake.generator(format!("Visual Studio {}", cmake_vs_version));
};

cmake.build();
}
303 changes: 303 additions & 0 deletions rust/flatc/src/lib.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,303 @@
/*
* Copyright 2018 Google Inc. All rights reserved.
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

2021

*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

//! # flatc
//!
//! Companion package to [`flatbuffers`] to generate code using `flatc` (the
//! FlatBuffers schema compiler) at compile time.
//!
//! This library is intended to be used as a `build-dependencies` entry in
//! `Cargo.toml`:
//!
//! ```toml
//! [dependencies]
//! flatbuffers = "0.5"
//!
//! [build-dependencies]
//! flatc = "0.1"
//! ```
//!
//! # Examples
//!
//! Use the `Build` structure to compile schema files:
//!
//! ```no_run
//! extern crate flatc;
//!
//! fn main() {
//! flatc::Build::new()
//! .schema("schema/foo.fbs")
//! .compile();
//! }
//! ```
//!
//! Include the generated Rust code:
//!
//! ```ignore
//! mod foo_generated {
//! include!(concat!(env!("OUT_DIR"), "/foo_generated.rs"));
//! }
//! ```
//!
//! [`flatbuffers`]: https://docs.rs/flatbuffers/latest

#![cfg_attr(feature = "cargo-clippy", allow(new_without_default_derive))]

use std::{env, fmt, io, iter::once, process::Command, path::{Path, PathBuf}};

/// The commit SHA of [google/flatbuffers.git] that the crate-supplied copy of
/// `flatc` was compiled with.
///
/// [google/flatbuffers.git]: https://github.com/google/flatbuffers
const FLATBUFFERS_COMMIT_SHA: &str = env!("FLATBUFFERS_COMMIT_SHA");

/// The location of the copy of the `flatc` executable compiled by this crate.
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I really like the idea of packaging flatc with this crate... I wonder if we can use it to couple the flatbuffers library with the flatc version somehow.

Related: #6149

@krojew might have opinions on this

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We already are aiming at unifying versions across languages, so packaging flatc can be a nice feautre to have.

const FLATC_EXECUTABLE: &str = concat!(env!("OUT_DIR"), "/bin/flatc");

/// An internal error that occured.
struct Error {
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

consider using this_error to ease the boilerplate

/// The kind of error.
kind: ErrorKind,
/// A helpful message.
message: String,
}

impl Error {
/// Create a new instance of an `Error`.
fn new<S: AsRef<str>>(kind: ErrorKind, message: S) -> Self {
Self {
kind,
message: message.as_ref().to_owned(),
}
}
}

impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self.kind {
ErrorKind::IO => {
writeln!(
f,
"An I/O error occured during FlatBuffers compilation: {}\n",
self.message,
)?;
}
ErrorKind::FlatC => {
writeln!(
f,
"A flatc error occurred during schema compilation with the crate-supplied executable\n",
)?;
}
}

writeln!(f, "Error message: {}", self.message)?;
writeln!(f, "flatc executable: {}", FLATC_EXECUTABLE)?;
writeln!(f, "flatbuffers commit: {}", FLATBUFFERS_COMMIT_SHA)?;

Ok(())
}
}

impl From<io::Error> for Error {
fn from(error: io::Error) -> Self {
Self::new(ErrorKind::IO, format!("{}", error))
}
}

/// The type of errors that can occur when using `flatc`.
enum ErrorKind {
/// An I/O error occured.
IO,
/// An error occurred while using the schema compiler.
FlatC,
}

/// A builder for compilation of one or multiple FlatBuffers schemas.
///
/// This is the core type of `flatc`. For further documentation, see the
/// individual methods for this structure.
pub struct Build {
/// The path that compiled schema files will be written into.
output_path: Option<PathBuf>,
/// The paths that will be tried in `include` statements in schemas.
include_paths: Vec<PathBuf>,
/// The schema files that will be compiled.
schema: Vec<PathBuf>,
/// Whether or not --gen-all is passed.
gen_all: bool,
}

impl Build {
/// Create a new instance of a `flatc` compilation with no configuration.
///
/// This is finished with the [`compile`](struct.Build.html#method.compile)
/// function.
pub fn new() -> Self {
Self {
output_path: None,
include_paths: Vec::new(),
schema: Vec::new(),
gen_all: false,
}
}

/// Add a schema file to the files which will be compiled.
///
/// ## Shell Command
///
/// ```text
/// $ flatc -r foo.fbs bar.fbs baz.fbs
/// ```
///
/// ## Rust Equivalent
///
/// ```no_run
/// extern crate flatc;
///
/// fn main() {
/// flatc::Build::new()
/// .schema("foo.fbs")
/// .schema("bar.fbs")
/// .schema("baz.fbs")
/// .compile();
/// }
/// ```
pub fn schema<P: AsRef<Path>>(&mut self, file: P) -> &mut Self {
self.schema.push(file.as_ref().to_path_buf());
self
}

/// Add include directories to the flatc compilation.
///
/// The order in which directories are added will be preserved.
///
/// ## Shell Command
///
/// ```text
/// $ flatc -r -I dir1 -I dir2 foo.fbs
/// ```
///
/// ## Rust equivalent
///
/// ```no_run
/// extern crate flatc;
///
/// fn main() {
/// flatc::Build::new()
/// .schema("foo.fbs")
/// .include("dir1")
/// .include("dir2")
/// .compile();
/// }
/// ```
pub fn include<P: AsRef<Path>>(&mut self, dir: P) -> &mut Self {
self.include_paths.push(dir.as_ref().to_path_buf());
self
}

/// This tells flatc to put all the code for includes into the same
/// generated file. This helps mitigate issue flatbuffers#5589.
/// It is set to `false` by default, but for Rust it is currently
/// necessary for significant usage of flatbuffers.
///
/// ## Shell Command
///
/// ```text
/// $ flatc -r --gen-all -I dir1 -I dir2 foo.fbs
/// ```
///
/// ## Rust equivalent
///
/// ```no_run
/// fn main() {
/// flatc::Build::new()
/// .gen_all(true)
/// .schema("foo.fbs")
/// .include("dir1")
/// .include("dir2")
/// .compile();
/// }
/// ```
pub fn gen_all(&mut self, gen_all: bool) -> &mut Self {
self.gen_all = gen_all;
self
}

/// Run the FlatBuffer schema compiler, generating one file for each of the
/// schemas added to the `Build` with the
/// [`schema`](struct.Build.html#method.schema) method.
///
/// Output filenames are postfixed with "*_generated*", and the extension is
/// set to "*.rs*". These files are placed in `OUT_DIR`. They can be
/// included in your crate using compile time macros.
///
/// # Example
///
/// For a compilation of `foo.fbs`, you would include it in your main crate
/// with:
///
/// ```ignore
/// mod foo_generated {
/// include!(concat!(env!("OUT_DIR"), "/foo_generated.rs"));
/// }
/// ```
///
/// # Panics
///
/// This function will panic if it encounters any error. This will be
/// emitted as a compilation error when compiling your crate.
pub fn compile(&self) {
if let Err(e) = self.try_compile() {
panic!("\n\n{}\n\n", e);
}
}
}

impl Build {
fn try_compile(&self) -> Result<(), Error> {
let output_path = self.output_path.as_ref().map_or_else(
|| env::var("OUT_DIR").unwrap(),
|path| format!("{}", path.display()),
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think this can be done in new. the None variant isn't actually used

);

let include_paths = self
.include_paths
.iter()
.flat_map(|path| once("-I".to_string()).chain(once(path.display().to_string())));

let fbs_files = self.schema.iter();

Command::new(FLATC_EXECUTABLE)
.current_dir(env::var("CARGO_MANIFEST_DIR").unwrap())
.arg("-r")
.args(if self.gen_all { &["--gen-all"][..] } else { &[] })
.args(&["-o", &output_path])
.args(include_paths)
.args(fbs_files)
.output()
.map_err(Error::from)
.and_then(|output| {
if output.status.success() {
Ok(())
} else {
Err(Error::new(
ErrorKind::FlatC,
String::from_utf8(output.stdout).unwrap().trim(),
))
}
})
}
}
Loading