aboutsummaryrefslogtreecommitdiff
path: root/src/main.rs
blob: a2de0e101d0ae779c55596bb42eda40fc925fb21 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
use std::path::PathBuf;
use std::ops::Deref;

use anyhow::Result;

use rustyline::error::ReadlineError;
use rustyline::Editor;

use structopt::StructOpt;

use sled::IVec;

#[derive(StructOpt, Debug)]
#[structopt(name = "sledcli")]
struct Opt {
	/// Path to Sled database
	#[structopt(name="path")]
	path: PathBuf,
}

enum DisplayMode {
	TryString,
	HexDump,
	Mixed,
}

struct State {
	db: sled::Db,
	tree: sled::Tree,
	displaymode: DisplayMode,
}

fn main() {
	let opt = Opt::from_args();
	let db = sled::Config::default()
		.path(&opt.path)
		.open()
		.expect("Unable to open database");

	let tree: sled::Tree = db.deref().clone();
	let mut state = State {
		db,
		tree,
		displaymode: DisplayMode::Mixed,
	};

	let mut readline = Editor::<()>::new();
    loop {
        let lineread = readline.readline(&format!("{}> ", try_string(&state.tree.name())));
        match lineread {
            Ok(line) => {
                readline.add_history_entry(line.as_str());
				if let Err(e) = do_command(&line, &mut state) {
					println!("Error: {}", e);
				}
            },
            Err(ReadlineError::Interrupted) => {
				println!("^C");
				continue;
            },
            Err(ReadlineError::Eof) => {
                break
            },
            Err(err) => {
                println!("Readline error: {:?}", err);
                break
            }
        }
    }
}

fn try_string(input: &sled::IVec) -> String {
    let mut string = String::new();
	utf8::LossyDecoder::new(|s| string.push_str(s)).feed(input);
	string
}

fn do_command(line: &str, state: &mut State) -> Result<()> {
	let parts = line.split(' ').filter(|part| part.len() > 0).collect::<Vec<_>>();
	if parts.is_empty() {
		return Ok(());
	}

	match &parts[..] {
		["ls"] => {
			let mut names = state.db.tree_names();
			names.sort();
			for name in names {
				println!("{}", try_string(&name));
			}
		}
		["cd", treename] => {
			if state.db.tree_names().iter().any(|t| t == treename.as_bytes()) {
				state.tree = state.db.open_tree(treename.as_bytes())?;
			} else {
				println!("Tree {} does not exist", treename);
			}
		}
		["hex"] => {
			state.displaymode = DisplayMode::HexDump;
		}
		["str"] => {
			state.displaymode = DisplayMode::TryString;
		}
		["mix"] => {
			state.displaymode = DisplayMode::Mixed;
		}
		["keys"] => {
			for (i, pair) in state.tree.iter().enumerate() {
				if i >= 20 {
					println!("...");
					break;
				}
				let (k, _v) = pair?;
				state.displaymode.print_key(&k);
			}
		}
		["pairs"] => {
			for (i, pair) in state.tree.iter().enumerate() {
				if i >= 20 {
					println!("...");
					break;
				}
				let (k, v) = pair?;
				state.displaymode.print_pair(&k, &v);
			}
		}
		bad_cmd => println!("Unrecognized command: {:?}", bad_cmd),
	}
	Ok(())
}

impl DisplayMode {
	fn print_key(&self, k: &IVec) {
		match *self {
			DisplayMode::HexDump => {
				hexdump::hexdump(k);
			}
			_ => {
				println!("{}", try_string(k));
			}
		}
	}

	fn print_pair(&self, k: &IVec, v: &IVec) {
		match *self {
			DisplayMode::HexDump => {
				hexdump::hexdump(k);
				hexdump::hexdump(v);
				println!();
			}
			DisplayMode::Mixed => {
				println!("{}", try_string(k));
				hexdump::hexdump(v);
				println!();
			}
			DisplayMode::TryString => {
				println!("{}\t{}", try_string(k), try_string(v));
			}
		}
	}
}