Skip to content

Commit

Permalink
refactor: clarify how HeaderSource loaded (#140)
Browse files Browse the repository at this point in the history
This closes #138.

Signed-off-by: tison <wander4096@gmail.com>
  • Loading branch information
tisonkun authored Mar 31, 2024
1 parent 6a159b1 commit ee20c4b
Showing 1 changed file with 29 additions and 30 deletions.
59 changes: 29 additions & 30 deletions fmt/src/license/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,13 +12,9 @@
// See the License for the specific language governing permissions and
// limitations under the License.

use snafu::ResultExt;
use snafu::OptionExt;

use crate::{
config::Config,
error::{InvalidConfigSnafu, LoadConfigSnafu},
Result,
};
use crate::{config::Config, error::InvalidConfigSnafu, Result};

#[derive(Debug, Clone)]
pub struct HeaderSource {
Expand All @@ -27,39 +23,42 @@ pub struct HeaderSource {

impl HeaderSource {
pub fn from_config(config: &Config) -> Result<Self> {
if let Some(inline_header) = &config.inline_header {
return Ok(HeaderSource {
content: inline_header.clone(),
});
// 1. inline_header takes priority.
if let Some(content) = config.inline_header.as_ref().cloned() {
return Ok(HeaderSource { content });
}

if let Some(header_path) = &config.header_path {
if let Some(content) = bundled_headers(header_path) {
return Ok(content);
}

// 2. Then, header_path tries to load from base_dir.
let header_path = config.header_path.as_ref().context(InvalidConfigSnafu {
message: "no header source found (both inline_header and header_path are None)",
})?;
let path = {
let mut path = config.base_dir.clone();
path.push(header_path);
let content = std::fs::read_to_string(header_path)
.context(LoadConfigSnafu { name: header_path })?;
path
};
if let Ok(content) = std::fs::read_to_string(path) {
return Ok(HeaderSource { content });
}

InvalidConfigSnafu {
message: "no header source found in config",
}
.fail()
// 3. Finally, fallback to try bundled headers.
bundled_headers(header_path).context(InvalidConfigSnafu {
message: format!("no header source found (header_path is invalid: {header_path})"),
})
}
}

pub fn bundled_headers(name: &str) -> Option<HeaderSource> {
match name {
"Apache-2.0.txt" => Some(HeaderSource {
content: include_str!("Apache-2.0.txt").to_string(),
}),
"Apache-2.0-ASF.txt" => Some(HeaderSource {
content: include_str!("Apache-2.0-ASF.txt").to_string(),
}),
_ => None,
macro_rules! match_bundled_headers {
($name:expr, $($file:expr),*) => {
match $name {
$(
$file => Some(HeaderSource { content: include_str!($file).to_string() }),
)*
_ => None,
}
}
}

fn bundled_headers(name: &str) -> Option<HeaderSource> {
match_bundled_headers!(name, "Apache-2.0.txt", "Apache-2.0-ASF.txt")
}

0 comments on commit ee20c4b

Please sign in to comment.