-
Notifications
You must be signed in to change notification settings - Fork 0
/
random-password.groovy
81 lines (64 loc) · 1.71 KB
/
random-password.groovy
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
// java -cp ".:$GROOVY_HOME/lib/groovy-3.0.6.jar:out/dev" random-password --help
String[] args = getProperty("args") as String[]
def usage = { ->
println """
usage: random_password -[has]
-h,--help Usage Information
-a,--alphabet <arg> A set of characters to generate the password
-s,--size <arg> set the size of the password 8 by default
"""
}
if (!args) {
println "Invalid arguments, please see the usage section: "
usage()
return
}
def generatePassword = { String alphabet, int size ->
StringBuilder password = new StringBuilder()
new Random().with {
size.times {
password.append(alphabet[ nextInt( alphabet.length() ) ])
}
}
password.toString()
}
def hasOption = { String... options ->
boolean result = false
options.each {option ->
if(args.contains(option)){
result = true
}
}
result
}
def findOptionIndex = { String... options ->
int index = 0
options.each { option ->
int indexOf = args.findIndexOf { it == option }
if (indexOf != -1) {
index = indexOf+1
}
}
index
}
// default values
def letters = (('a'..'z') + ('A'..'Z'))
def numbers = '0'..'9'
def special = '.;!$_-'
def size = 8
String alphabet = (letters+numbers+special).join('')
if (["-h", "--help"].contains(args[0])) {
usage()
return
}
if(hasOption("-a", "--alphabet")) {
alphabet = args[findOptionIndex("-a", "--alphabet")]
}
if(hasOption("-s", "--size")) {
size = Math.abs(args[findOptionIndex("-s", "--size")] as Integer)
}
println """*** Generating password using ***
Alphabet: $alphabet
Size: $size
"""
println generatePassword(alphabet, size)