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
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
use std::path::PathBuf;
use anyhow::{Context, Result, bail};
use clap::Args;
use libsail::collection::Indexable;
use libsail::format::Format;
use regex::bytes::Regex;
use crate::cli::FormatArg;
use crate::input::Inputs;
use crate::output::{emit, writer};
#[derive(Args)]
pub struct RenameArgs {
/// file to read, or - for stdin
#[arg(default_value = "-")]
pub input: PathBuf,
/// put this in front of every name
#[arg(long)]
pub prefix: Option<String>,
/// put this after every name
#[arg(long)]
pub suffix: Option<String>,
/// replace what this pattern matches, with --with
#[arg(long, requires = "with")]
pub replace: Option<String>,
/// what --replace puts in place of a match; ${1} is the first group
#[arg(long, requires = "replace")]
pub with: Option<String>,
/// number the records, replacing each name with this stem plus its position
#[arg(long)]
pub number: Option<String>,
/// assert the input is this format, and fail if it is not
#[arg(long, value_enum)]
pub format: Option<FormatArg>,
/// where to write [default: stdout]
#[arg(short, long)]
pub output: Option<PathBuf>,
}
impl RenameArgs {
pub fn run(self) -> Result<()> {
let rules = self.rules()?;
let inputs = Inputs::read(std::slice::from_ref(&self.input), self.format)?;
let entry = &inputs.entries()[0];
let out = writer(self.output.as_deref())?;
// not through dispatch!: renaming writes to a record
// rather than reading one, and where a name is stored
// is the one thing the three formats do not share --
// a Vec<u8> field, a #=GF line, and a header string
match inputs.format() {
Format::Fasta => {
let collection = libsail::seq::fasta::Fasta::new(entry.reader()?)?;
let renamed = (0..collection.len())
.map(|n| {
let mut record = collection.cloned(n).expect("a counted record");
record.name = rules.apply(&record.name, n);
record
})
.collect::<Vec<_>>();
emit(renamed, crate::output::write::fasta, out)
}
Format::Stockholm => {
let collection = libsail::seq::stockholm::Stockholm::new(entry.reader()?)?;
let renamed = (0..collection.len())
.map(|n| {
let mut record = collection.cloned(n).expect("a counted record");
let was = record.id().unwrap_or_default().to_vec();
let now = rules.apply(&was, n);
set_id(&mut record, &now)?;
Ok(record)
})
.collect::<Result<Vec<_>>>()?;
emit(renamed, crate::output::write::stockholm, out)
}
Format::Hmm => {
let collection = libsail::seq::p7hmm::Hmm::new(entry.reader()?)?;
let renamed = (0..collection.len())
.map(|n| {
let mut record = collection.cloned(n).expect("a counted record");
record.header.name = rules.apply(&record.header.name, n);
Ok(record)
})
.collect::<Result<Vec<_>>>()?;
emit(renamed, crate::output::write::hmm, out)
}
}
}
fn rules(&self) -> Result<Rules> {
if self.prefix.is_none()
&& self.suffix.is_none()
&& self.replace.is_none()
&& self.number.is_none()
{
bail!("rename needs --prefix, --suffix, --replace or --number")
}
let replace = match (&self.replace, &self.with) {
(Some(pattern), Some(with)) => Some((
Regex::new(pattern).with_context(|| format!("the pattern {pattern:?}"))?,
with.as_bytes().to_vec(),
)),
_ => None,
};
Ok(Rules {
prefix: self.prefix.clone().unwrap_or_default().into_bytes(),
suffix: self.suffix.clone().unwrap_or_default().into_bytes(),
replace,
number: self.number.clone().map(String::into_bytes),
})
}
}
// ---
/// What each rewrite does to one name.
struct Rules {
prefix: Vec<u8>,
suffix: Vec<u8>,
replace: Option<(Regex, Vec<u8>)>,
number: Option<Vec<u8>>,
}
impl Rules {
/// The new name for the record at position `n`.
fn apply(&self, name: &[u8], n: usize) -> Vec<u8> {
// the order is fixed and is what makes the flags
// combinable: --number replaces the name outright,
// then --replace rewrites it, then --prefix and
// --suffix wrap what is left
let mut now = match &self.number {
// 1-based, and zero-padded to four so the names
// sort into record order
Some(stem) => {
let mut numbered = stem.clone();
numbered.extend_from_slice(format!("{:04}", n + 1).as_bytes());
numbered
}
None => name.to_vec(),
};
if let Some((pattern, with)) = &self.replace {
now = pattern.replace_all(&now, &with[..]).into_owned();
}
// after --replace, so a pattern cannot match the
// prefix this same call just added
let mut out = self.prefix.clone();
out.extend_from_slice(&now);
out.extend_from_slice(&self.suffix);
out
}
}
/// Rewrite an alignment's `#=GF ID`, adding one where it had none.
fn set_id(record: &mut libsail::seq::stockholm::StockholmRecord, name: &[u8]) -> Result<()> {
let name = name.to_vec();
// the record reads its id back out of gf rather than
// storing it, so renaming means editing that line --
// nothing else in the record would be written out
match record.gf.iter_mut().find(|(feature, _)| feature == b"ID") {
Some((_, value)) => *value = name,
// in front, because Pfam writes ID first and a reader
// scanning for it should not have to pass the rest
None => record.gf.insert(0, (b"ID".to_vec(), name)),
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
fn rules(args: RenameArgs) -> Rules {
args.rules().unwrap()
}
fn args() -> RenameArgs {
RenameArgs {
input: PathBuf::from("-"),
prefix: None,
suffix: None,
replace: None,
with: None,
number: None,
format: None,
output: None,
}
}
#[test]
fn a_prefix_and_a_suffix_wrap_the_name_they_are_given() {
let r = rules(RenameArgs {
prefix: Some("x_".into()),
suffix: Some("_y".into()),
..args()
});
assert_eq!(r.apply(b"AB", 0), b"x_AB_y");
}
#[test]
fn numbering_counts_from_one_and_pads_so_the_names_sort() {
// seq10 sorting before seq2 is the whole reason for
// the padding
let r = rules(RenameArgs {
number: Some("seq".into()),
..args()
});
assert_eq!(r.apply(b"anything", 0), b"seq0001");
assert_eq!(r.apply(b"anything", 9), b"seq0010");
}
#[test]
fn a_replacement_runs_before_the_prefix_it_would_otherwise_match() {
// order is what makes the flags combinable: a pattern
// must not match the prefix this same call just added
let r = rules(RenameArgs {
prefix: Some("HUMAN_".into()),
replace: Some("HUMAN".into()),
with: Some("H".into()),
..args()
});
assert_eq!(r.apply(b"DLG4_HUMAN", 0), b"HUMAN_DLG4_H");
}
#[test]
fn a_replacement_reaches_a_captured_group_through_the_braced_form() {
let braced = rules(RenameArgs {
replace: Some("(.+)_(.+)".into()),
with: Some("${2}_${1}".into()),
..args()
});
assert_eq!(braced.apply(b"DLG4_HUMAN", 0), b"HUMAN_DLG4");
}
#[test]
fn a_bare_group_reference_swallows_an_underscore_after_it() {
// **note: the trap this records is the regex crate's,
// not this command's: $2_ reads as a group
// *named* "2_", which does not exist and
// expands to nothing. the name comes out
// wrong in silence, so --with documents the
// braced form and this pins the behaviour
// against a future regex release changing it
let bare = rules(RenameArgs {
replace: Some("(.+)_(.+)".into()),
with: Some("$2_$1".into()),
..args()
});
assert_eq!(bare.apply(b"DLG4_HUMAN", 0), b"DLG4");
}
#[test]
fn renaming_with_no_rule_at_all_is_refused() {
// silently emitting the input unchanged would look
// like the rename worked
assert!(args().rules().is_err());
}
}