hanzi-sort 0.2.1

Sort Chinese text by pinyin or stroke count, with polyphonic overrides and terminal-friendly output
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
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
use std::fs;
use std::io::Write;
use std::path::{Path, PathBuf};
use std::process::{Command, Output, Stdio};
use std::time::{SystemTime, UNIX_EPOCH};

struct TempWorkspace {
    path: PathBuf,
}

impl TempWorkspace {
    fn new() -> Self {
        let unique = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .expect("system time should be after UNIX_EPOCH")
            .as_nanos();
        let path =
            std::env::temp_dir().join(format!("hanzi-sort-test-{}-{}", std::process::id(), unique));
        fs::create_dir_all(&path).expect("temporary directory should be created");
        Self { path }
    }

    fn path(&self) -> &Path {
        &self.path
    }
}

impl Drop for TempWorkspace {
    fn drop(&mut self) {
        let _ = fs::remove_dir_all(&self.path);
    }
}

fn binary_command() -> Command {
    Command::new(env!("CARGO_BIN_EXE_hanzi-sort"))
}

fn stdout(output: &Output) -> String {
    String::from_utf8(output.stdout.clone()).expect("stdout should be valid UTF-8")
}

fn stderr(output: &Output) -> String {
    String::from_utf8(output.stderr.clone()).expect("stderr should be valid UTF-8")
}

#[test]
fn empty_stdin_produces_empty_output_and_exits_successfully() {
    // Mimics `hanzi-sort < /dev/null`: stdin is non-TTY, empty.
    // Like `sort`, hanzi-sort should treat this as "no input, no output"
    // and exit 0 — matching Unix filter conventions.
    let mut command = binary_command();
    command.stdin(Stdio::null());
    command.stdout(Stdio::piped());
    command.stderr(Stdio::piped());
    let output = command.output().expect("CLI command should run");

    assert!(
        output.status.success(),
        "stderr: {}",
        stderr(&output)
    );
    assert_eq!(stdout(&output), "");
}

#[test]
fn reads_stdin_when_no_explicit_input_provided() {
    let mut command = binary_command();
    command.args(["--columns", "1", "--entry-width", "2", "--blank-every", "0"]);
    command.stdin(Stdio::piped());
    command.stdout(Stdio::piped());
    command.stderr(Stdio::piped());

    let mut child = command.spawn().expect("CLI command should spawn");
    {
        let stdin = child.stdin.as_mut().expect("stdin should be piped");
        stdin
            .write_all(b"\xe8\xb5\xb5\xe5\x9b\x9b\n\xe5\xbc\xa0\xe4\xb8\x89\n\xe6\xb1\x89\xe5\xad\x97\n")
            .expect("write stdin");
        // 赵四 / 张三 / 汉字 in UTF-8
    }
    let output = child.wait_with_output().expect("CLI command should finish");

    assert!(output.status.success(), "stderr: {}", stderr(&output));
    assert_eq!(stdout(&output), "汉字\n张三\n赵四");
}

#[test]
fn dash_file_arg_reads_stdin() {
    let mut command = binary_command();
    command.args(["-f", "-", "--columns", "1", "--entry-width", "2", "--blank-every", "0"]);
    command.stdin(Stdio::piped());
    command.stdout(Stdio::piped());
    command.stderr(Stdio::piped());

    let mut child = command.spawn().expect("CLI command should spawn");
    {
        let stdin = child.stdin.as_mut().expect("stdin should be piped");
        stdin
            .write_all("\n\n".as_bytes())
            .expect("write stdin");
    }
    let output = child.wait_with_output().expect("CLI command should finish");

    assert!(output.status.success(), "stderr: {}", stderr(&output));
    assert_eq!(stdout(&output), "\n");
}

#[test]
fn reverse_flag_inverts_sort_order() {
    let mut command = binary_command();
    command.args([
        "-t", "汉字", "张三", "赵四",
        "--reverse",
        "--columns", "1", "--entry-width", "2", "--blank-every", "0",
    ]);
    let output = command.output().expect("CLI command should run");

    assert!(output.status.success(), "stderr: {}", stderr(&output));
    assert_eq!(stdout(&output), "赵四\n张三\n汉字");
}

#[test]
fn unique_flag_removes_duplicates() {
    let mut command = binary_command();
    command.args([
        "-t", "张三", "汉字", "张三", "赵四", "张三",
        "--unique",
        "--columns", "1", "--entry-width", "2", "--blank-every", "0",
    ]);
    let output = command.output().expect("CLI command should run");

    assert!(output.status.success(), "stderr: {}", stderr(&output));
    assert_eq!(stdout(&output), "汉字\n张三\n赵四");
}

#[test]
fn unique_and_reverse_compose_correctly() {
    // -u removes duplicates first, then -r reverses the deduped output.
    let mut command = binary_command();
    command.args([
        "-t", "张三", "汉字", "张三", "赵四",
        "--unique", "--reverse",
        "--columns", "1", "--entry-width", "2", "--blank-every", "0",
    ]);
    let output = command.output().expect("CLI command should run");

    assert!(output.status.success(), "stderr: {}", stderr(&output));
    assert_eq!(stdout(&output), "赵四\n张三\n汉字");
}

#[test]
fn completions_subcommand_emits_bash_script() {
    let mut command = binary_command();
    command.args(["completions", "bash"]);
    let output = command.output().expect("CLI command should run");

    assert!(output.status.success(), "stderr: {}", stderr(&output));
    let body = stdout(&output);
    assert!(
        body.contains("_hanzi-sort()"),
        "bash completion should define _hanzi-sort function: {body}"
    );
    assert!(
        body.contains("--reverse") && body.contains("--unique"),
        "completion should mention all top-level flags"
    );
}

#[test]
fn completions_subcommand_emits_zsh_script() {
    let mut command = binary_command();
    command.args(["completions", "zsh"]);
    let output = command.output().expect("CLI command should run");

    assert!(output.status.success(), "stderr: {}", stderr(&output));
    let body = stdout(&output);
    assert!(
        body.contains("#compdef hanzi-sort"),
        "zsh completion should declare compdef header: {body}"
    );
}

#[test]
fn help_includes_examples_section() {
    let mut command = binary_command();
    command.arg("--help");
    let output = command.output().expect("CLI command should run");

    assert!(output.status.success());
    let help = stdout(&output);
    assert!(help.contains("EXAMPLES:"), "help should include examples section");
    assert!(
        help.contains("cat names.txt | hanzi-sort"),
        "help should show stdin example"
    );
    assert!(
        help.contains("hanzi-sort completions bash"),
        "help should advertise the completions subcommand"
    );
}

#[test]
fn reads_file_inputs_line_by_line_and_ignores_blank_lines() {
    let temp = TempWorkspace::new();
    let input_path = temp.path().join("names.txt");
    fs::write(&input_path, "赵四\n\n张三\n汉字\n").expect("input file should be written");

    let mut command = binary_command();
    command.args(["-f"]);
    command.arg(&input_path);
    command.args(["--columns", "1", "--entry-width", "2", "--blank-every", "0"]);
    let output = command.output().expect("CLI command should run");

    assert!(output.status.success());
    assert_eq!(stdout(&output), "汉字\n张三\n赵四");
}

#[test]
fn rejects_mixing_file_and_text_inputs() {
    let temp = TempWorkspace::new();
    let input_path = temp.path().join("names.txt");
    fs::write(&input_path, "张三\n").expect("input file should be written");

    let mut command = binary_command();
    command.args(["-f"]);
    command.arg(&input_path);
    command.args(["-t", "赵四"]);
    let output = command.output().expect("CLI command should run");

    assert!(!output.status.success());
    assert!(stderr(&output).contains("cannot be used with"));
}

#[test]
fn rejects_missing_input_file() {
    let temp = TempWorkspace::new();
    let missing_path = temp.path().join("missing.txt");

    let mut command = binary_command();
    command.args(["-f"]);
    command.arg(&missing_path);
    let output = command.output().expect("CLI command should run");

    assert!(!output.status.success());
    assert!(stderr(&output).contains("failed to inspect input path"));
}

#[test]
fn rejects_directory_input() {
    let temp = TempWorkspace::new();
    let input_dir = temp.path().join("folder");
    fs::create_dir_all(&input_dir).expect("directory input should be created");

    let mut command = binary_command();
    command.args(["-f"]);
    command.arg(&input_dir);
    let output = command.output().expect("CLI command should run");

    assert!(!output.status.success());
    assert!(stderr(&output).contains("directory inputs are not supported"));
}

#[test]
fn writes_output_to_file_when_requested() {
    let temp = TempWorkspace::new();
    let output_path = temp.path().join("sorted.txt");

    let mut command = binary_command();
    command.args([
        "-t",
        "",
        "",
        "--columns",
        "1",
        "--entry-width",
        "2",
        "--blank-every",
        "0",
        "-o",
    ]);
    command.arg(&output_path);
    let output = command.output().expect("CLI command should run");

    assert!(output.status.success());
    assert!(stdout(&output).is_empty());
    assert_eq!(
        fs::read_to_string(&output_path).expect("output file should be written"),
        "\n"
    );
}

#[test]
fn supports_stroke_sorting_from_cli() {
    let mut command = binary_command();
    command.args([
        "-t",
        "",
        "",
        "",
        "--sort-by",
        "strokes",
        "--columns",
        "1",
        "--entry-width",
        "2",
        "--blank-every",
        "0",
    ]);
    let output = command.output().expect("CLI command should run");

    assert!(output.status.success());
    assert_eq!(stdout(&output), "\n\n");
}

#[cfg(feature = "collator-radical")]
#[test]
fn radical_sort_works_via_cli() {
    let mut command = binary_command();
    command.args([
        "-t",
        "",
        "",
        "",
        "--sort-by",
        "radical",
        "--columns",
        "1",
        "--entry-width",
        "2",
        "--blank-every",
        "0",
    ]);
    let output = command.output().expect("CLI command should run");

    assert!(output.status.success(), "stderr: {}", stderr(&output));
    assert_eq!(stdout(&output), "\n\n");
}

#[cfg(feature = "collator-zhuyin")]
#[test]
fn supports_zhuyin_sorting_from_cli() {
    let mut command = binary_command();
    command.args([
        "-t",
        "",
        "",
        "",
        "--sort-by",
        "zhuyin",
        "--columns",
        "1",
        "--entry-width",
        "2",
        "--blank-every",
        "0",
    ]);
    let output = command.output().expect("CLI command should run");

    assert!(output.status.success(), "stderr: {}", stderr(&output));
    assert_eq!(stdout(&output), "\n\n");
}

#[cfg(feature = "collator-jyutping")]
#[test]
fn supports_jyutping_sorting_from_cli() {
    let mut command = binary_command();
    command.args([
        "-t",
        "",
        "",
        "",
        "--sort-by",
        "jyutping",
        "--columns",
        "1",
        "--entry-width",
        "2",
        "--blank-every",
        "0",
    ]);
    let output = command.output().expect("CLI command should run");

    assert!(output.status.success(), "stderr: {}", stderr(&output));
    assert_eq!(stdout(&output), "\n\n");
}

#[test]
fn rejects_output_path_that_is_a_directory() {
    let temp = TempWorkspace::new();
    let output_dir = temp.path().join("out");
    fs::create_dir_all(&output_dir).expect("output directory should be created");

    let mut command = binary_command();
    command.args(["-t", "", "", "-o"]);
    command.arg(&output_dir);
    let output = command.output().expect("CLI command should run");

    assert!(!output.status.success());
    assert!(stderr(&output).contains("failed to write output file"));
}

#[cfg(feature = "collator-jyutping")]
#[test]
fn jyutping_override_via_cli() {
    let temp = TempWorkspace::new();
    let override_path = temp.path().join("override.toml");
    fs::write(
        &override_path,
        "[char_override]\n'中' = 'zung3'\n",
    )
    .expect("override file should be written");

    let mut command = binary_command();
    command.args([
        "-t", "", "",
        "--sort-by", "jyutping",
        "--config",
    ]);
    command.arg(&override_path);
    command.args(["--columns", "1", "--entry-width", "2", "--blank-every", "0"]);
    let output = command.output().expect("CLI command should run");

    assert!(output.status.success(), "stderr: {}", stderr(&output));
    // 汉 (hon3) sorts before 中 (now zung3 via override) because 'h' < 'z'.
    assert_eq!(stdout(&output), "\n");
}

#[test]
fn rejects_invalid_override_config() {
    let temp = TempWorkspace::new();
    let override_path = temp.path().join("override.toml");
    fs::write(
        &override_path,
        "[phrase_override]\n\"重庆\" = [\"chong2\"]\n",
    )
    .expect("override file should be written");

    let mut command = binary_command();
    command.args(["-t", "重庆", "--config"]);
    command.arg(&override_path);
    let output = command.output().expect("CLI command should run");

    assert!(!output.status.success());
    assert!(
        stderr(&output)
            .contains("phrase_override entry '重庆' has 2 characters but 1 pinyin values")
    );
}

#[test]
fn rejects_missing_override_config_file() {
    let temp = TempWorkspace::new();
    let override_path = temp.path().join("missing.toml");

    let mut command = binary_command();
    command.args(["-t", "重庆", "--config"]);
    command.arg(&override_path);
    let output = command.output().expect("CLI command should run");

    assert!(!output.status.success());
    assert!(stderr(&output).contains("failed to read override config"));
}

#[test]
fn phrase_override_changes_sort_order() {
    let temp = TempWorkspace::new();
    let override_path = temp.path().join("override.toml");
    fs::write(
        &override_path,
        "[phrase_override]\n\"重庆\" = [\"chong2\", \"qing4\"]\n",
    )
    .expect("override file should be written");

    let mut command = binary_command();
    command.args(["-t", "重庆", "银行", "--config"]);
    command.arg(&override_path);
    command.args(["--columns", "1", "--entry-width", "2", "--blank-every", "0"]);
    let output = command.output().expect("CLI command should run");

    assert!(output.status.success());
    assert_eq!(stdout(&output), "重庆\n银行");
}

#[test]
fn char_override_changes_single_character_sort_order() {
    let temp = TempWorkspace::new();
    let override_path = temp.path().join("override.toml");
    fs::write(&override_path, "[char_override]\n'重' = 'chong2'\n")
        .expect("override file should be written");

    let mut command = binary_command();
    command.args(["-t", "重要", "银行", "--config"]);
    command.arg(&override_path);
    command.args(["--columns", "1", "--entry-width", "2", "--blank-every", "0"]);
    let output = command.output().expect("CLI command should run");

    assert!(output.status.success());
    assert_eq!(stdout(&output), "重要\n银行");
}