dotenv コードリーディング
下記のコードリーディングを行う
使用方法
-
.env
ファイルを用意する
-
env::vars()
で.env
を環境変数として読み込める
- 下記が出力される
CODEGEN_TEST_VAR1: hello!
CODEGEN_TEST_VAR2: 'quotes within quotes'
[[bin]]
は何をしているのだろう
Cargo.toml
の [[bin]]
をコメントアウトしても cargo run --bin dotenv --features="cli"
で呼び出せる
# [[bin]]
# name = "dotenv"
# required-features = ["cli"]
A binary’s source can be src/main.rs and/or stored in the src/bin/ directory. For src/main.rs, the default binary name is the package name. The settings for each binary can be customized in the[[bin]] tables in Cargo.toml.
[[bin]]
を使うことで実行するバイナリの設定をカスタマイズできる
今回の場合だと cargo run --bin dotenv
を実行した時の動作は下記のようになる
[[bin]]
なし
cargo run --bin dotenv
Compiling dotenv v0.15.0 (/xxxx/oss_reading/dotenv_reading/dotenv/dotenv)
error[E0463]: can't find crate for `clap`
--> dotenv/src/bin/dotenv.rs:1:1
|
1 | extern crate clap;
| ^^^^^^^^^^^^^^^^^^ can't find crate
For more information about this error, try `rustc --explain E0463`.
error: could not compile `dotenv` (bin "dotenv") due to 1 previous error
[[bin]]
あり
cargo run --bin dotenv
error: target `dotenv` in package `dotenv` requires the features: `cli`
Consider enabling them by passing, e.g., `--features="cli"`
dependencies
に clap
があるが、自動でインストールされないのは optional = true
があるから
Dependencies can be marked “optional”, which means they will not be compiled by default.
[features]
に設定を追加することでインストールしたい依存関係を明示できる
Features are defined in the [features] table in Cargo.toml. Each feature specifies an array of other features or optional dependencies that it enables.
[dev-dependencies]
に書かれた依存関係はビルド時にはインストールされない
Dev-dependencies are not used when compiling a package for building, but are used for compiling tests, examples, and benchmarks.
以前は crate を読み込むのに extern crate
が必要だった
This one is quite straightforward: you no longer need to write extern crate to import a crate into your project. Before:
[dependencies]
に追加すると src/lib.rs
を利用出来るようになる
Cargo.toml の中身を見ても、src/main.rs については何も書いてありません。これは、Cargoは src/main.rs が、パッケージと同じ名前を持つバイナリクレートのクレートルートであるという慣習に従っているためです。 同じように、Cargoはパッケージディレクトリに src/lib.rs が含まれていたら、パッケージにはパッケージと同じ名前のライブラリクレートが含まれており、src/lib.rs がそのクレートルートなのだと判断します。 Cargoはクレートルートファイルを rustcに渡し、ライブラリやバイナリをビルドします。
call_once
に渡されたクロージャーは一度しか実行されなくなる
初期化処理などに使用される
Performs an initialization routine once and only once. The given closure will be executed if this is the first time call_once has been called, and otherwise the routine will not be invoked.
動作例
use std::sync::Once;
static INIT: Once = Once::new();
fn init() {
INIT.call_once(|| {
println!("init");
});
}
fn once_example() {
init();
init();
init();
}
fn main() {
once_example();
}
init
PathBuf
はファイルシステムのパスを表すことが出来る
ファイル操作の時に使用する
An owned, mutable path (akin to String).
This type provides methods like push and set_extension that mutate the path in place.
構造体Pathは、ファイルシステム中のパスを表します。
Pathはイミュータブルです。Pathの所有権ありのバージョンがPathBufです。
Finder
は別ファイルで定義されている
構造体のフィールドに参照を指定した場合、<'a>
のようにライフタイムの指定が必須になる
構造体に、他の何かに所有されたデータへの参照を保持させることもできますが、 そうするにはライフタイムという第10章で議論するRustの機能を使用しなければなりません。 ライフタイムのおかげで構造体に参照されたデータが、構造体自体が有効な間、ずっと有効であることを保証してくれるのです。 ライフタイムを指定せずに構造体に参照を保持させようとしたとしましょう。以下の通りですが、これは動きません:
filename
フィールドを Path::new(".env")
で初期化
Iter
は別ファイルで定義されている
env::current_dir
で現在のディレクトリ名を取得できる
アクセス権限がない場合などには Err
が返る
Returns the current working directory as a PathBuf
Returns an Err if the current working directory value is invalid. Possible cases:
- Current directory does not exist.
- There are insufficient permissions to access the current directory.
map_err
メソッドにより Result
型が返した Err
を任意の Err
に変換することが出来る
これの Ok
バージョンとして map
が存在する
Maps a Result<T, E> to Result<T, F> by applying a function to a contained Err value, leaving an Ok value untouched.
find
メソッドは下記で定義されている
ルートディレクトリ(ビルド結果である target
ディレクトリが作成されるディレクトリ)にある .env
への絶対パスが candidate
変数に束縛される
fs::metadata
メソッドにより引数のファイルが存在するかなどの処理を行える
Given a path, queries the file system to get information about a file, directory, etc.
This function will return an error in the following situations, but is not limited to just these cases:
- The user lacks permissions to perform metadata call on path.
- path does not exist.
ファイルが存在する場合はファイルの絶対パスを返す
ファイルが存在しないかつ NotFound
エラー以外の場合はエラーを返す
std::io::Error
の kind
メソッドによりエラーの詳細を取得できる
Returns the corresponding ErrorKind for this error.
親ディレクトリが存在する場合は再帰的に find
メソッドを呼び出す
親ディレクトリが存在しない場合はエラーを返す
path
変数には .env
ファイルへの絶対パスが束縛されている
file
変数を引数にして Iter
構造体を初期化する
lines
メソッドによりファイルの行単位での操作が可能になる
Returns an iterator over the lines of this reader.
(path, iter)
によって .env
ファイルへの絶対パスと Iter
構造体のインスタンスが返る
find
メソッドにより Iter
構造体のインスタンスを iter
変数に束縛する
load
メソッドでエラーが発生しなければ .env
ファイルへの絶対パスを返す
for in
構文を呼び出している
for in構文はIteratorとさまざまな方法でやり取りできます。
Rust では Iterator
トレイトを実装することで繰り返し処理を行えるようになる
Iteratorトレイトは、例えば配列のような、要素の集合に対してイテレータを実装するためのトレイトです。
このトレイトはnextの要素に相当するものを決定するためのメソッドのみを要求します。このメソッドはimplブロック内で手動で実装するか、あるいは(配列やrangeのように)自動で定義されます。
行が存在する場合はその値が line
変数に束縛される
parse_line
メソッドは下記に定義されている