0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

プライベートレポジトリのCrateを使う

Last updated at Posted at 2024-02-09

プライベートなgithubのレポジトリにあまり公開したくないcrateを登録して利用する。

Cargo.tomlでdependenciesにプライベートなレポジトリを git="" で指定して利用することで人には見られたくないけど管理が大変なCrateの管理を他に投げられて便利だね、というお話です。

Crate(ライブラリ)をつくる

cargo new --lib my_crate
cd my_crate

このようにしてプロジェクトを作成、続いて src/lib.rsを編集します。

pub fn say() -> String {
    "Hello, world!".to_string()
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn it_works() {
        let result = say();
        assert_eq!(result, "Hello, world!");
    }
}

say() というファンクションを作りました。呼ぶと Hello, world! がStringで返ります。
ついでにテストコードも修正しました。

テスト実行

cargo test

このようにテストを実行します。

running 1 test
test tests::it_works ... ok

test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s

   Doc-tests my_crate

running 0 tests

test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s

it_works ... ok といっているのでOKです。
何かfailedみたいなニュアンスのことを言われたらエラーが直るまで踏ん張ります。

githubでプライベートなレポジトリを作りCrateを登録する

ss

プライベートなので違うアカウントからは見えません。
完璧です。

テストプログラムを作る

ではこのプライベートレポジトリのCrateが本当に使えるのかテストします。

cargo new my_crate_test
cd my_crate_test

Cargo.tomlのdependenciesでgitのアドレスを指定してcrateの利用を宣言するには次のように記述します。

[dependencies]
my_crate = { git = "https://github.com/<account_name>/my_crate.git" }

そして、src/main.rsです。

fn main() {
    let msg = my_crate::say();
    println!("{}", msg);
}

ではいざ実行

cargo run

ここでgithubへのログインを促されると思いますのでログインします(もしかしたらすでにログインしたことになっていて尋ねられないこともあるかもしれないですが)

スクリーンショット 2024-02-09 214514

ログインが出来るとこのように表示されてビルドが開始されます。
そして・・・

    Finished dev [unoptimized + debuginfo] target(s) in 0.03s
     Running `target\debug\my_crate_test.exe`
Hello, world!

まとめ

無事にプライベートなレポジトリからcrateを取り込んでコンパイルすることが出来ました。
簡単な機能であればmodとかで参照しても良いのですが「複雑ないつものアイツ」みたいなのを多用するようになってくるとcrateの管理が大変、どれが最新だっけ?みたいな悩みなんかも尽きない、そんな苦労をしない為にも積極的にgitを利用して行きたいところです。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?