Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

CMD: Time-based UUID Generator & Parser #85

Open
wants to merge 12 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
Copyright (c) 2009,2014 Google Inc. All rights reserved.
Copyright (c) 2021 Pedro Albanese. All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
Expand Down
54 changes: 54 additions & 0 deletions cmd/uuid/main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
// Package main is the main package for the UUID generator application.
package main

import (
"bytes"
"flag"
"fmt"
"io"
"os"
"strings"
"time"

"github.com/google/uuid"
)

// parse is a command-line flag to parse the given UUID. ('-' for STDIN)
var (
parse = flag.String("d", "", "Parse given UUID. ('-' for STDIN)")
)

func main() {
flag.Parse()
var lreader io.Reader

// If no UUID is given as input, generate a new UUID and print it.
if *parse == "" {
u, _ := uuid.NewUUID()
fmt.Printf("%s\n", u)
} else if *parse != "" { // If a UUID is provided as input, parse and process it.
if *parse == "-" { // If input is "-", read from STDIN.
lreader = os.Stdin
} else { // Otherwise, read from the provided input string.
lreader = strings.NewReader(*parse)
}

buf := new(bytes.Buffer)
buf.ReadFrom(lreader)
s := buf.String()
s = strings.TrimSuffix(s, "\n")

// Parse the UUID string to a UUID object.
uuid, _ := uuid.Parse(s)
fmt.Printf("UUID= %s\n", uuid)

// Get the timestamp information from the parsed UUID.
id := uuid
t := id.Time()
sec, nsec := t.UnixTime()
timeStamp := time.Unix(sec, nsec)

// Print the timestamp in a formatted date string.
fmt.Printf("DATE= %v \n", timeStamp.Format("2006-01-02 Mon 15:04:05.00000Z -0700"))
}
}
2 changes: 1 addition & 1 deletion go.mod
Original file line number Diff line number Diff line change
@@ -1 +1 @@
module github.com/google/uuid
module github.com/pedroalbanese/uuid