Software /
code /
prosody
Comparison
util/human/io.lua @ 10870:3f1889608f3e
util.human.io: New central place for UI helpers
author | Matthew Wild <mwild1@gmail.com> |
---|---|
date | Tue, 02 Jun 2020 08:00:37 +0100 |
child | 10872:a3f3f42736f2 |
comparison
equal
deleted
inserted
replaced
10869:c91697b81349 | 10870:3f1889608f3e |
---|---|
1 local function getchar(n) | |
2 local stty_ret = os.execute("stty raw -echo 2>/dev/null"); | |
3 local ok, char; | |
4 if stty_ret == true or stty_ret == 0 then | |
5 ok, char = pcall(io.read, n or 1); | |
6 os.execute("stty sane"); | |
7 else | |
8 ok, char = pcall(io.read, "*l"); | |
9 if ok then | |
10 char = char:sub(1, n or 1); | |
11 end | |
12 end | |
13 if ok then | |
14 return char; | |
15 end | |
16 end | |
17 | |
18 local function getline() | |
19 local ok, line = pcall(io.read, "*l"); | |
20 if ok then | |
21 return line; | |
22 end | |
23 end | |
24 | |
25 local function getpass() | |
26 local stty_ret, _, status_code = os.execute("stty -echo 2>/dev/null"); | |
27 if status_code then -- COMPAT w/ Lua 5.1 | |
28 stty_ret = status_code; | |
29 end | |
30 if stty_ret ~= 0 then | |
31 io.write("\027[08m"); -- ANSI 'hidden' text attribute | |
32 end | |
33 local ok, pass = pcall(io.read, "*l"); | |
34 if stty_ret == 0 then | |
35 os.execute("stty sane"); | |
36 else | |
37 io.write("\027[00m"); | |
38 end | |
39 io.write("\n"); | |
40 if ok then | |
41 return pass; | |
42 end | |
43 end | |
44 | |
45 local function show_yesno(prompt) | |
46 io.write(prompt, " "); | |
47 local choice = getchar():lower(); | |
48 io.write("\n"); | |
49 if not choice:match("%a") then | |
50 choice = prompt:match("%[.-(%U).-%]$"); | |
51 if not choice then return nil; end | |
52 end | |
53 return (choice == "y"); | |
54 end | |
55 | |
56 local function read_password() | |
57 local password; | |
58 while true do | |
59 io.write("Enter new password: "); | |
60 password = getpass(); | |
61 if not password then | |
62 print("No password - cancelled"); | |
63 return; | |
64 end | |
65 io.write("Retype new password: "); | |
66 if getpass() ~= password then | |
67 if not show_yesno [=[Passwords did not match, try again? [Y/n]]=] then | |
68 return; | |
69 end | |
70 else | |
71 break; | |
72 end | |
73 end | |
74 return password; | |
75 end | |
76 | |
77 local function show_prompt(prompt) | |
78 io.write(prompt, " "); | |
79 local line = getline(); | |
80 line = line and line:gsub("\n$",""); | |
81 return (line and #line > 0) and line or nil; | |
82 end | |
83 | |
84 local function printf(fmt, ...) | |
85 print(msg:format(...)); | |
86 end | |
87 | |
88 return { | |
89 getchar = getchar; | |
90 getline = getline; | |
91 getpass = getpass; | |
92 show_yesno = show_yesno; | |
93 read_password = read_password; | |
94 show_prompt = show_prompt; | |
95 printf = printf; | |
96 }; |