Skip to content

Commit

Permalink
Support of '--prefix' option
Browse files Browse the repository at this point in the history
  • Loading branch information
moul committed Aug 3, 2015
1 parent 9d3b424 commit 7c55547
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 0 deletions.
27 changes: 27 additions & 0 deletions anonuuid.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,9 @@ type AnonUUID struct {

// Random flag will generate random fake UUIDs
Random bool

// Prefix will be the beginning of all the generated UUIDs
Prefix string
}

// Sanitize takes a string as input and return sanitized string
Expand All @@ -39,6 +42,13 @@ func (a *AnonUUID) Sanitize(input string) string {
func (a *AnonUUID) FakeUUID(realUUID string) string {
if _, ok := a.cache[realUUID]; !ok {

if a.Prefix != "" {
matched, err := regexp.MatchString("^[a-z0-9]+$", a.Prefix)
if err != nil || !matched {
a.Prefix = "invalidprefix"
}
}

var fakeUUID string
var err error
if a.Hexspeak {
Expand All @@ -54,6 +64,13 @@ func (a *AnonUUID) FakeUUID(realUUID string) string {
log.Fatalf("Test")
}

if a.Prefix != "" {
fakeUUID, err = PrefixUUID(a.Prefix, fakeUUID)
if err != nil {
panic(err)
}
}

// FIXME: check for duplicates and retry

a.cache[realUUID] = fakeUUID
Expand All @@ -74,6 +91,16 @@ func init() {
rand.Seed(time.Now().UTC().UnixNano())
}

// PrefixUUID returns a prefixed UUID
func PrefixUUID(prefix string, uuid string) (string, error) {
uuidLetters := uuid[:8] + uuid[9:13] + uuid[14:18] + uuid[19:23] + uuid[24:36]
prefixedUUID, err := FormatUUID(prefix + uuidLetters)
if err != nil {
return "", err
}
return prefixedUUID, nil
}

// FormatUUID takes a string in input and return an UUID formatted string by repeating the string and placing dashes if necessary
func FormatUUID(part string) (string, error) {
if len(part) < 32 {
Expand Down
5 changes: 5 additions & 0 deletions cmd/anonuuid/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,10 @@ func main() {
Name: "random, r",
Usage: "Generate random fake UUIDs",
},
cli.StringFlag{
Name: "prefix, p",
Usage: "Prefix generated UUIDs",
},
}

app.Action = action
Expand All @@ -41,6 +45,7 @@ func action(c *cli.Context) {

anonuuid.Hexspeak = c.Bool("hexspeak")
anonuuid.Random = c.Bool("random")
anonuuid.Prefix = c.String("prefix")

for scanner.Scan() {
line := scanner.Text()
Expand Down

0 comments on commit 7c55547

Please sign in to comment.