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

add CLI support: clippy and fmt + rename commands #452

Open
wants to merge 22 commits into
base: develop
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 20 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
5 changes: 4 additions & 1 deletion .cargo/config.toml
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
[alias]
bitcoin-indexer-install = "install --path components/cli --locked --force"
bitcoin-indexer-install = "install --path components/ordhook-cli --locked --force"
bitcoin-indexer-fmt = "fmt -- --config group_imports=StdExternalCrate,imports_granularity=Crate"
bitcoin-indexer-clippy = "clippy --tests --all-features --all-targets -- -A clippy::too_many_arguments -A clippy::needless_return -A clippy::type_complexity -A clippy::ptr_arg"
bitcoin-indexer-clippy-cli = "clippy --tests --all-features --all-targets --message-format=short -- -A clippy::too_many_arguments -A clippy::needless_return -A clippy::type_complexity -A clippy::ptr_arg -D warnings"

[env]
RUST_TEST_THREADS = "1"
102 changes: 101 additions & 1 deletion .github/workflows/ci.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -119,6 +119,102 @@ jobs:
run: npm run testenv:stop
if: always()

rustfmt:
name: rust-fmt
runs-on: ubuntu-latest
strategy:
fail-fast: false
matrix:
suite:
- cli
- chainhook-sdk
- chainhook-postgres
- ordhook-core
- runes
defaults:
run:
working-directory: ./components/${{ matrix.suite }}
steps:
- uses: actions/checkout@v4
with:
persist-credentials: false

- name: Rustfmt Job Summary
run: |
# Run cargo and store the original output
CARGO_STATUS=0
CARGO_OUTPUT=$(cargo fmt --all --manifest-path=Cargo.toml -- --config group_imports=StdExternalCrate,imports_granularity=Crate --color=always --check 2>/dev/null) || CARGO_STATUS=$?

if [ ${CARGO_STATUS} -eq 0 ]; then
cat <<MARKDOWN_INTRO >> $GITHUB_STEP_SUMMARY
# Rustfmt Results

The code is formatted perfectly!
MARKDOWN_INTRO
else
cat <<MARKDOWN_INTRO >> $GITHUB_STEP_SUMMARY
# Rustfmt Results

\`cargo fmt\` reported formatting errors in the following locations.
You can fix them by executing the following command and committing the changes.
\`\`\`bash
cargo bitcoin-indexer-fmt
\`\`\`
MARKDOWN_INTRO

echo "${CARGO_OUTPUT}" |
# Strip color codes
sed 's/\x1B\[[0-9;]*[A-Za-z]\x0f\?//g' |
# Strip (some) cursor movements
sed 's/\x1B.[A-G]//g' |
tr "\n" "\r" |
# Wrap each location into a HTML details
sed -E 's#Diff in ([^\r]*?)( at line |:)([[:digit:]]+):\r((:?[ +-][^\r]*\r)+)#<details>\n<summary>\1:\3</summary>\n\n```diff\n\4```\n\n</details>\n\n#g' |
tr "\r" "\n" >> $GITHUB_STEP_SUMMARY
fi

# Print the original cargo message
echo "${CARGO_OUTPUT}"
# Exit with the same status as cargo
exit "${CARGO_STATUS}"

clippy:
name: rust-clippy
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
with:
persist-credentials: false

- name: Run clippy
id: clippy
run: |
# Disable immediate exit on error
set +e

# Run clippy and capture output
cargo bitcoin-indexer-clippy-cli 2>&1 | tee /tmp/clippy_output.log
CLIPPY_EXIT_CODE=${PIPESTATUS[0]}

# Print output if clippy failed
if [ $CLIPPY_EXIT_CODE -ne 0 ]; then
echo "## ❌ Clippy Check Failed

To see and fix these issues, run:
\`\`\`bash
cargo bitcoin-indexer-clippy
\`\`\`

### Clippy Errors
\`\`\`
$(cat /tmp/clippy_output.log | grep -E '(error\:)|(warning\:)')
\`\`\`" >> $GITHUB_STEP_SUMMARY
fi

# Enable immediate exit on error again
set -e
exit $CLIPPY_EXIT_CODE

test:
strategy:
fail-fast: false
Expand Down Expand Up @@ -158,6 +254,10 @@ jobs:
- name: Install Rust
uses: actions-rust-lang/setup-rust-toolchain@v1

- name: Run doc tests
run: |
cargo test --doc

- name: Run tests
run: |
cargo install --force cargo-tarpaulin
Expand All @@ -178,7 +278,7 @@ jobs:

semantic-release:
runs-on: ubuntu-latest
needs: [api-lint, api-test, test]
needs: [api-lint, api-test, test, rustfmt, clippy]
outputs:
new_release_version: ${{ steps.semantic.outputs.new_release_version }}
new_release_published: ${{ steps.semantic.outputs.new_release_published }}
Expand Down
9 changes: 9 additions & 0 deletions .vscode/settings.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
{
"editor.defaultFormatter": "rust-lang.rust-analyzer",
"editor.formatOnSave": true,
"editor.formatOnSaveMode": "file",
"rust-analyzer.rustfmt.extraArgs": [
"--config",
"group_imports=StdExternalCrate,imports_granularity=Crate"
]
}
21 changes: 12 additions & 9 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,15 +2,18 @@
/ --- / Index Bitcoin meta-protocols like Ordinals, BRC-20, and Runes.
/ /

* [Features](#features)
* [Quick Start](#quick-start)
* [Installing](#installing)
* [Running the Indexer](#running-the-indexer)
* [Configuration](#configuration)
* [System Requirements](#system-requirements)
* [Postgres](#postgres)
* [Contribute](#contribute)
* [Community](#community)
- [Features](#features)
- [Quick Start](#quick-start)
- [Installing](#installing)
- [Running the Indexer](#running-the-indexer)
- [Running an API](#running-an-api)
- [Configuration](#configuration)
- [System Requirements](#system-requirements)
- [Postgres](#postgres)
- [Contribute](#contribute)
- [Code of Conduct](#code-of-conduct)
- [Contributing Guide](#contributing-guide)
- [Community](#community)

***

Expand Down
4 changes: 2 additions & 2 deletions components/chainhook-postgres/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -37,9 +37,9 @@
if let Some(size) = config.pool_max_size {
pool_builder = pool_builder.max_size(size);
}
Ok(pool_builder
pool_builder
.build()
.map_err(|e| format!("unable to build pg connection pool: {e}"))?)
.map_err(|e| format!("unable to build pg connection pool: {e}"))

Check warning on line 42 in components/chainhook-postgres/src/lib.rs

View check run for this annotation

Codecov / codecov/patch

components/chainhook-postgres/src/lib.rs#L42

Added line #L42 was not covered by tests
}

/// Returns a new pg connection client taken from a pool.
Expand Down
4 changes: 2 additions & 2 deletions components/chainhook-postgres/src/types/mod.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
mod pg_bigint_u32;
mod pg_numeric_u64;
mod pg_numeric_u128;
mod pg_numeric_u64;
mod pg_smallint_u8;

pub use pg_bigint_u32::PgBigIntU32;
pub use pg_numeric_u64::PgNumericU64;
pub use pg_numeric_u128::PgNumericU128;
pub use pg_numeric_u64::PgNumericU64;
pub use pg_smallint_u8::PgSmallIntU8;
3 changes: 1 addition & 2 deletions components/chainhook-postgres/src/types/pg_bigint_u32.rs
Original file line number Diff line number Diff line change
Expand Up @@ -57,9 +57,8 @@ impl Ord for PgBigIntU32 {
mod test {
use test_case::test_case;

use crate::pg_test_client;

use super::PgBigIntU32;
use crate::pg_test_client;

#[test_case(4294967295; "u32 max")]
#[test_case(0; "zero")]
Expand Down
5 changes: 2 additions & 3 deletions components/chainhook-postgres/src/types/pg_numeric_u128.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ use tokio_postgres::types::{to_sql_checked, FromSql, IsNull, ToSql, Type};

/// Transforms a u128 value into postgres' `numeric` wire format.
pub fn u128_into_pg_numeric_bytes(number: u128, out: &mut BytesMut) {
let mut num = number.clone();
let mut num = number;
let mut digits = vec![];
while !num.is_zero() {
let remainder = (num % 10000).to_i16().unwrap();
Expand Down Expand Up @@ -136,9 +136,8 @@ impl Ord for PgNumericU128 {
mod test {
use test_case::test_case;

use crate::pg_test_client;

use super::PgNumericU128;
use crate::pg_test_client;

#[test_case(340282366920938463463374607431768211455; "u128 max")]
#[test_case(80000000000000000; "with trailing zeros")]
Expand Down
3 changes: 1 addition & 2 deletions components/chainhook-postgres/src/types/pg_numeric_u64.rs
Original file line number Diff line number Diff line change
Expand Up @@ -53,9 +53,8 @@ impl Ord for PgNumericU64 {
mod test {
use test_case::test_case;

use crate::pg_test_client;

use super::PgNumericU64;
use crate::pg_test_client;

#[test_case(18446744073709551615; "u64 max")]
#[test_case(800000000000; "with trailing zeros")]
Expand Down
3 changes: 1 addition & 2 deletions components/chainhook-postgres/src/types/pg_smallint_u8.rs
Original file line number Diff line number Diff line change
Expand Up @@ -39,9 +39,8 @@ impl<'a> FromSql<'a> for PgSmallIntU8 {
mod test {
use test_case::test_case;

use crate::pg_test_client;

use super::PgSmallIntU8;
use crate::pg_test_client;

#[test_case(255; "u8 max")]
#[test_case(0; "zero")]
Expand Down
2 changes: 1 addition & 1 deletion components/chainhook-postgres/src/utils.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ pub fn multi_row_query_param_str(rows: usize, columns: usize) -> String {
let mut arg_num = 1;
let mut arg_str = String::new();
for _ in 0..rows {
arg_str.push_str("(");
arg_str.push('(');
for i in 0..columns {
arg_str.push_str(format!("${},", arg_num + i).as_str());
}
Expand Down
35 changes: 23 additions & 12 deletions components/chainhook-sdk/src/indexer/bitcoin/mod.rs
Original file line number Diff line number Diff line change
@@ -1,22 +1,22 @@
use std::time::Duration;

use crate::try_debug;
use crate::utils::Context;
use bitcoincore_rpc::bitcoin::hashes::Hash;
use bitcoincore_rpc::bitcoin::{self, Amount, BlockHash};
use bitcoincore_rpc::jsonrpc::error::RpcError;
use bitcoincore_rpc::{
bitcoin::{self, hashes::Hash, Amount, BlockHash},
jsonrpc::error::RpcError,
};
use bitcoincore_rpc_json::GetRawTransactionResultVoutScriptPubKey;
use chainhook_types::bitcoin::{OutPoint, TxIn, TxOut};
use chainhook_types::{
BitcoinBlockData, BitcoinBlockMetadata, BitcoinNetwork,
BitcoinTransactionData,BitcoinTransactionMetadata, BlockHeader, BlockIdentifier,
TransactionIdentifier,
bitcoin::{OutPoint, TxIn, TxOut},
BitcoinBlockData, BitcoinBlockMetadata, BitcoinNetwork, BitcoinTransactionData,
BitcoinTransactionMetadata, BlockHeader, BlockIdentifier, TransactionIdentifier,
};
use config::BitcoindConfig;
use hiro_system_kit::slog;
use reqwest::Client as HttpClient;
use serde::Deserialize;

use crate::{try_debug, utils::Context};

#[derive(Clone, PartialEq, Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct BitcoinBlockFullBreakdown {
Expand Down Expand Up @@ -213,7 +213,10 @@
});
let block_hash = http_client
.post(&bitcoin_config.rpc_url)
.basic_auth(&bitcoin_config.rpc_username, Some(&bitcoin_config.rpc_password))
.basic_auth(
&bitcoin_config.rpc_username,
Some(&bitcoin_config.rpc_password),
)
.header("Content-Type", "application/json")
.header("Host", &bitcoin_config.rpc_url[7..])
.json(&body)
Expand Down Expand Up @@ -283,7 +286,10 @@
});
let res = http_client
.post(&bitcoin_config.rpc_url)
.basic_auth(&bitcoin_config.rpc_username, Some(&bitcoin_config.rpc_password))
.basic_auth(
&bitcoin_config.rpc_username,
Some(&bitcoin_config.rpc_password),

Check warning on line 291 in components/chainhook-sdk/src/indexer/bitcoin/mod.rs

View check run for this annotation

Codecov / codecov/patch

components/chainhook-sdk/src/indexer/bitcoin/mod.rs#L290-L291

Added lines #L290 - L291 were not covered by tests
)
.header("Content-Type", "application/json")
.header("Host", &bitcoin_config.rpc_url[7..])
.json(&body)
Expand Down Expand Up @@ -344,7 +350,12 @@
let mut transactions = vec![];
let block_height = block.height as u64;

try_debug!(ctx, "Standardizing Bitcoin block #{} {}", block.height, block.hash);
try_debug!(
ctx,
"Standardizing Bitcoin block #{} {}",
block.height,
block.hash
);

for (tx_index, mut tx) in block.tx.into_iter().enumerate() {
let txid = tx.txid.to_string();
Expand Down
14 changes: 8 additions & 6 deletions components/chainhook-sdk/src/indexer/fork_scratch_pad.rs
Original file line number Diff line number Diff line change
@@ -1,14 +1,16 @@
use crate::{
indexer::{ChainSegment, ChainSegmentIncompatibility},
try_error, try_info, try_warn,
utils::Context,
};
use std::collections::{BTreeMap, BTreeSet, HashSet};

use chainhook_types::{
BlockHeader, BlockIdentifier, BlockchainEvent, BlockchainUpdatedWithHeaders,
BlockchainUpdatedWithReorg,
};
use hiro_system_kit::slog;
use std::collections::{BTreeMap, BTreeSet, HashSet};

use crate::{
indexer::{ChainSegment, ChainSegmentIncompatibility},
try_error, try_info, try_warn,
utils::Context,
};

pub struct ForkScratchPad {
canonical_fork_id: usize,
Expand Down
5 changes: 2 additions & 3 deletions components/chainhook-sdk/src/indexer/mod.rs
Original file line number Diff line number Diff line change
@@ -1,15 +1,14 @@
pub mod bitcoin;
pub mod fork_scratch_pad;

use crate::utils::{AbstractBlock, Context};
use std::collections::VecDeque;

use chainhook_types::{BlockHeader, BlockIdentifier, BlockchainEvent};
use config::BitcoindConfig;
use hiro_system_kit::slog;

use std::collections::VecDeque;

use self::fork_scratch_pad::ForkScratchPad;
use crate::utils::{AbstractBlock, Context};

#[derive(Deserialize, Debug, Clone, Default)]
pub struct AssetClassCache {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,10 +1,9 @@
use crate::utils::Context;

use super::super::BlockchainEventExpectation;
use super::bitcoin_blocks;
use chainhook_types::{BitcoinBlockData, BlockchainEvent};
use hiro_system_kit::slog;

use super::{super::BlockchainEventExpectation, bitcoin_blocks};
use crate::utils::Context;

pub fn expect_no_chain_update() -> BlockchainEventExpectation {
Box::new(move |chain_event_to_check: Option<BlockchainEvent>| {
assert!(
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
use base58::FromBase58;
use bitcoincore_rpc::bitcoin::blockdata::opcodes;
use bitcoincore_rpc::bitcoin::blockdata::script::Builder as BitcoinScriptBuilder;
use chainhook_types::{bitcoin::TxOut, BitcoinTransactionData, BitcoinTransactionMetadata, TransactionIdentifier};
use bitcoincore_rpc::bitcoin::blockdata::{opcodes, script::Builder as BitcoinScriptBuilder};
use chainhook_types::{
bitcoin::TxOut, BitcoinTransactionData, BitcoinTransactionMetadata, TransactionIdentifier,
};

pub fn generate_test_tx_bitcoin_p2pkh_transfer(
txid: u64,
Expand Down
Loading
Loading