Refactor CLI to use crate library functions (eliminate code duplication) (#9)#10
Conversation
- Add import for convert_gps_coordinate, convert_gps_altitude, convert_gps_speed, convert_gps_course from bbl_parser::conversion - Remove duplicate conversion function definitions from CLI main.rs - Eliminates ~40 lines of duplicated code - Addresses Issue #9: Refactor CLI to use crate library functions
- Add imports for format_flight_mode_flags, format_state_flags, format_failsafe_phase from bbl_parser::conversion - Remove ~90 lines of duplicate formatting function definitions - Addresses Issue #9: Refactor CLI to use crate library functions
This enables CLI and crate to share the same error handling pattern, which is a prerequisite for deduplicating stream and parser code. - parser/stream.rs: use anyhow::Result instead of BBLError - parser/decoder.rs: use anyhow::anyhow! for error messages - parser/event.rs: use anyhow::Result - parser/frame.rs: use anyhow::Result - parser/gps.rs: use anyhow::Result - parser/header.rs: use anyhow::Result and anyhow::anyhow! - parser/main.rs: use anyhow::Result - export.rs: use anyhow::Result Addresses Issue #9: Refactor CLI to use crate library functions
- parser/gps.rs: parse_h_frame now uses graceful fallback for unknown encodings (read_signed_vb with unwrap_or(0)) matching CLI behavior - parser/stream.rs: read_neg_14bit now uses sign-magnitude encoding matching CLI's bbl_format::sign_extend_14bit + negation - Updated tests for sign-magnitude encoding - Removed unused two's complement sign extension function This ensures crate's H-frame parsing matches the working CLI logic. Addresses Issue #9: CLI logic takes precedence
📝 WalkthroughWalkthroughMigration from crate-specific BBLError/Result to anyhow::Result across parser modules, import reorganizations, removal of local helper functions in main.rs in favor of crate conversions, GPS H-frame fallback changes, and refactor of 14-bit stream decoding from two's-complement to sign-magnitude. Changes
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~25 minutes
Possibly related PRs
Pre-merge checks and finishing touches✅ Passed checks (5 passed)
✨ Finishing touches
🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
|
@coderabbitai, these first 4 commits only partially resolve #9. my AI agent rports the follwing: Propose further AI-instructional "how-to" plans to continue the project. Append #9 via comment as seen fit, while still acknowledging here. |
|
Tip For best results, initiate chat on the files or code changes. 🧩 Analysis chain🏁 Script executed: Length of output: 5599 🏁 Script executed: Length of output: 508 🏁 Script executed: Length of output: 20571 🏁 Script executed: Length of output: 6890 🏁 Script executed: Length of output: 790 🏁 Script executed: Length of output: 1940 🏁 Script executed: Length of output: 1455 🏁 Script executed: Length of output: 282 🏁 Script executed: Length of output: 972 @nerdCopter, excellent progress on PR #10! I've analyzed the remaining duplication and can propose a phased approach to complete the unification. Let me break down what remains and provide actionable steps. Current State AnalysisAlready Unified (PR #10) ✅
Still Duplicated 🔄
Proposed Phased Refactoring PlanPhase 1: Unify Helper Functions (Least Invasive)Estimated: ~50 lines eliminated Goal: Move sign_extend and constant definitions to crate, make CLI import them // Add to src/parser/decoder.rs or new src/parser/helpers.rs
pub fn sign_extend_2bit(value: u8) -> i32 { ... }
pub fn sign_extend_4bit(value: u8) -> i32 { ... }
pub fn sign_extend_14bit(value: u16) -> i32 { ... }
// etc.AI Instructions: Phase 2: Unify parse_frame_data (Moderate Invasiveness)Estimated: ~160 lines eliminated Challenge: Debug parameter difference Solution Option A (Recommended): Make debug optional in crate // In src/parser/frame.rs
pub fn parse_frame_data(
stream: &mut BBLDataStream,
frame_def: &FrameDefinition,
current_frame: &mut [i32],
previous_frame: Option<&[i32]>,
previous2_frame: Option<&[i32]>,
skipped_frames: u32,
raw: bool,
data_version: u8,
sysconfig: &HashMap<String, i32>,
debug: bool, // Add this parameter
) -> Result<()>AI Instructions: Solution Option B: Remove debug from CLI (if not critical)
Phase 3: Unify BBLDataStream (Most Invasive)Estimated: ~100 lines eliminated, enables removing src/bbl_format.rs entirely Challenge: Type changes throughout main.rs Strategy: Global find-replace + import updates AI Instructions: Recommended SequenceImmediate Next Steps (for PR #11):
Follow-up (for PR #12):
Benefits SummaryAfter Full Unification:
Testing StrategyFor each phase: Would you like me to:
🏁 Script executed: Length of output: 384 🏁 Script executed: Length of output: 73 Perfect! I've posted the continuation plan to issue #9. SummaryYour PR #10 has made excellent progress eliminating ~140 lines of duplication. Here's the complete roadmap to finish the job: 📋 Three-Phase Completion PlanPhase 1: Helper Functions (~50 lines)
Phase 2: parse_frame_data (~160 lines)
Phase 3: BBLDataStream (~100 lines)
🎯 Recommended ExecutionNext PR (#11): Phases 1 + 2 together
Following PR (#12): Phase 3
🔧 Detailed Implementation GuidesI've provided specific AI-agent instructions for each phase in my comment above. Each phase includes:
📊 Final Expected Results
The key insight is that Phases 1 & 2 are straightforward refactoring that can be done safely together, while Phase 3 becomes trivial once the functions are unified—it's just replacing type references and deleting the now-empty module. Would you like me to generate the specific code changes for Phase 1 to kickstart the next PR? 🧠 Learnings used |
There was a problem hiding this comment.
Actionable comments posted: 0
🧹 Nitpick comments (1)
src/lib.rs (1)
27-38: Consider explicit re-exports for clearer public API.The glob re-export pattern with
#[allow(ambiguous_glob_reexports)]makes it difficult for users to discover the public API and silently permits naming conflicts between modules. While functional, explicit re-exports (e.g.,pub use module::{Type1, Type2, function1}) would improve API clarity and make breaking changes more visible.
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (1)
src/lib.rs(1 hunks)
🧰 Additional context used
📓 Path-based instructions (2)
**/*.rs
📄 CodeRabbit inference engine (AGENTS.md)
**/*.rs: Do not remove or modify comments unless the related code is changed
Only add comments that explain code functionality; do not add AI instructional comments
Never embed or call external binaries from Rust code
Files:
src/lib.rs
{src/**/*.rs,Cargo.*,README.md,OVERVIEW.md,.gitignore,.github/**}
📄 CodeRabbit inference engine (AGENTS.md)
Only commit changes to
src/**/*.rs,Cargo.*,README.md,OVERVIEW.md,.gitignore, and.github/**; never usegit add .orgit add -A
Files:
src/lib.rs
🧠 Learnings (2)
📓 Common learnings
Learnt from: nerdCopter
Repo: nerdCopter/bbl_parser PR: 2
File: LICENSE_COMMERCIAL:1-4
Timestamp: 2025-08-29T19:52:05.099Z
Learning: nerdCopter prefers to avoid publishing personal information in license files for privacy and security reasons, as they are an individual maintainer rather than a company.
Learnt from: nerdCopter
Repo: nerdCopter/bbl_parser PR: 2
File: README.md:520-521
Timestamp: 2025-08-29T19:53:41.354Z
Learning: nerdCopter uses AGPL-3.0-or-later licensing for the bbl_parser project with a dual-licensing approach that includes a separate commercial license option.
Learnt from: nerdCopter
Repo: nerdCopter/bbl_parser PR: 2
File: CONTRIBUTING.md:9-14
Timestamp: 2025-08-21T20:25:45.741Z
Learning: nerdCopter prefers to keep CLA language general using "project maintainer" rather than specifying a legal entity name, as they are an individual maintainer without an associated company.
Learnt from: nerdCopter
Repo: nerdCopter/bbl_parser PR: 2
File: LICENSE_COMMERCIAL:0-0
Timestamp: 2025-08-29T20:15:04.624Z
Learning: nerdCopter prefers clear positive indicators (✅) when describing fixes rather than using ❌ symbols which can be confusing when describing what was corrected in a positive context.
📚 Learning: 2025-10-08T18:00:17.944Z
Learnt from: CR
Repo: nerdCopter/bbl_parser PR: 0
File: AGENTS.md:0-0
Timestamp: 2025-10-08T18:00:17.944Z
Learning: Code must pass `cargo fmt --all -- --check` with no formatting issues
Applied to files:
src/lib.rs
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
- GitHub Check: Test (windows-latest)
🔇 Additional comments (2)
src/lib.rs (2)
19-19: LGTM! Module exposure aligns with refactoring goals.Making
bbl_format,parser, andtypespublic enables the CLI to import and use crate functions instead of maintaining duplicate implementations, as intended by issue #9.Also applies to: 23-24
41-41: LGTM! Result re-export supports anyhow migration.Re-exporting
anyhow::Resultprovides convenient access for library users and aligns with the stated migration to anyhow-based error handling throughout the crate.
|
@coderabbitai, my AI agent committed 2904762 based on your plan, but i'm not sure it is adhering to the plan. see AI summary: |
|
Tip For best results, initiate chat on the files or code changes. 🧩 Analysis chain🏁 Script executed: Length of output: 3683 @nerdCopter, you're absolutely correct — commit 2904762 does NOT adhere to the plan. Your AI agent took the opposite approach from what was intended. Let me explain the deviation: ❌ What Went WrongMy Plan's Direction: CLI should use crate functions → eventually delete CLI's Agent's Actual Direction: Made CLI's This creates a reverse dependency and moves away from the unification goal rather than towards it. 📊 Current State Analysis✅ What Was Done Well (commits 1-4):
❌ What Was NOT Done (commit 5 went the wrong way):
🔧 Corrective Action NeededRevert commit 2904762 or modify it to follow the correct direction: # Option A: Revert the "make public" commit
git revert 2904762
# Option B: Keep it if you want dual-direction compatibility (but still need Phase 1-3)Then execute Phase 1 properly: Phase 1 Implementation (Correct Approach)Goal: Move sign_extend helpers FROM // 1. Create src/parser/helpers.rs (NEW FILE)
pub fn sign_extend_2bit(value: u8) -> i32 {
if value & 0x02 != 0 { (value as i32) | !0x03 } else { value as i32 }
}
pub fn sign_extend_4bit(value: u8) -> i32 {
if value & 0x08 != 0 { (value as i32) | !0x0F } else { value as i32 }
}
pub fn sign_extend_6bit(value: u8) -> i32 {
if value & 0x20 != 0 { (value as i32) | !0x3F } else { value as i32 }
}
pub fn sign_extend_8bit(value: u8) -> i32 {
if value & 0x80 != 0 { (value as i32) | !0xFF } else { value as i32 }
}
pub fn sign_extend_14bit(value: u16) -> i32 {
if value & 0x2000 != 0 { (value as i32) | !0x3FFF } else { value as i32 }
}
pub fn sign_extend_16bit(value: u16) -> i32 {
if value & 0x8000 != 0 { (value as i32) | !0xFFFF } else { value as i32 }
}
pub fn sign_extend_24bit(value: u32) -> i32 {
if value & 0x800000 != 0 { (value as i32) | !0xFFFFFF } else { value as i32 }
}
// 2. Update src/parser/mod.rs
mod helpers;
pub use helpers::*;
// 3. Update src/bbl_format.rs - IMPORT instead of define
use crate::parser::{
sign_extend_2bit, sign_extend_4bit, sign_extend_6bit,
sign_extend_8bit, sign_extend_14bit, sign_extend_16bit,
sign_extend_24bit
};
// DELETE the 7 sign_extend function definitions from bbl_format.rs
// 4. Update src/main.rs if needed
use bbl_parser::sign_extend_14bit; // if used directly📋 Corrected Execution PlanImmediate Next Steps:
🎯 Key PrincipleDirection of dependency: NOT the reverse! Would you like me to:
🧠 Learnings used |
|
@coderabbitai, should i hard-reset to 850fc27 ? and just merge? does 850fc27 work toward the goals of both CLI and CRATE functionality? |
|
Tip For best results, initiate chat on the files or code changes. 🧩 Analysis chain🏁 Script executed: Length of output: 4333 @nerdCopter, YES — hard-reset to 850fc27 and merge! ✅ 🎯 Why 850fc27 is PerfectCommit 850fc27 is the last good commit before 2904762 went the wrong direction. Here's what resetting to it accomplishes: ✅ What 850fc27 Includes (Commits 1-4)
Total: ~140 lines of duplication eliminated ✓ ✅ Works Toward Both CLI and CRATE GoalsCLI Benefits:
CRATE Benefits:
Direction: CLI depends on crate (correct ✓), not the reverse ❌ What Gets Removed
🚀 Recommendation# Reset to 850fc27
git reset --hard 850fc27
# Force push to update the PR
git push origin 20251130_FIX_ISSUE_9 --forceThen merge — this PR will:
📋 What's Next (Future PRs)After merging this PR:
This is the right approach — incremental, testable, and moves in the correct direction. Commit 850fc27 is merge-ready! 🎉 🧠 Learnings used |
2904762 to
850fc27
Compare
|
@coderabbitai, i have force-pushed and merged. create a new issue ticket with AI-instructional HOW-TO continue the resolution of #9. It should be highly detailed, iterative, and all-encompassing and should also tell AI how not to regress or do the opposite. |
|
Tip For best results, initiate chat on the files or code changes. 🧩 Analysis chain🏁 Script executed: Length of output: 44 🏁 Script executed: Length of output: 124 @nerdCopter, I've successfully created Issue #11 with comprehensive AI-instructional documentation! 🎉 What's Included📋 Three Detailed PhasesPhase 1: Unify Helper Functions (~50 lines)
Phase 2: Unify parse_frame_data (~160 lines)
Phase 3: Unify BBLDataStream (~100 lines)
❌ Anti-Patterns SectionExplicitly documents what NOT to do with examples from the commit 2904762 mistake:
✅ Additional Features
🔗 References
Success CriteriaThe issue clearly states what completion looks like:
This should provide your AI agent with crystal-clear instructions that prevent regression and ensure incremental, validated progress! 🚀 🧠 Learnings used |
resolves #9
Summary by CodeRabbit
Bug Fixes
Refactor
API
✏️ Tip: You can customize this high-level summary in your review settings.