1
0
Fork 0
mirror of https://github.com/Luzifer/worktime.git synced 2024-12-22 14:01:17 +00:00

Initial version

This commit is contained in:
Knut Ahlers 2016-09-24 14:59:16 +02:00
commit ff6a6f694e
Signed by: luzifer
GPG key ID: DC2729FDD34BE99E
15 changed files with 1216 additions and 0 deletions

1
.gitignore vendored Normal file
View file

@ -0,0 +1 @@
worktime

202
LICENSE Normal file
View file

@ -0,0 +1,202 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

55
cmd/add.go Normal file
View file

@ -0,0 +1,55 @@
package cmd
import (
"crypto/sha1"
"fmt"
"time"
"github.com/Luzifer/worktime/schema"
"github.com/spf13/cobra"
)
// addCmd represents the add command
var addCmd = &cobra.Command{
Use: "add <day> <start> <end> [tag [tag...]]",
Short: "Add a time frame to the given day",
RunE: func(cmd *cobra.Command, args []string) error {
if len(args) < 3 {
return fmt.Errorf("Please supply required arguments")
}
day, err := time.Parse("2006-01-02", args[0])
if err != nil {
return fmt.Errorf("'day' parameter seems to have a wrong format: %s", err)
}
doc, err := schema.LoadDay(cfg.couchDB, day, true)
if err != nil {
return err
}
doc.Times = append(doc.Times, &schema.Time{
ID: fmt.Sprintf("%x", sha1.Sum([]byte(time.Now().String()))),
Start: args[1],
End: args[2],
Tags: args[3:],
})
return doc.Save(cfg.couchDB)
},
}
func init() {
timeCmd.AddCommand(addCmd)
// Here you will define your flags and configuration settings.
// Cobra supports Persistent Flags which will work for this command
// and all subcommands, e.g.:
// addCmd.PersistentFlags().String("foo", "", "A help for foo")
// Cobra supports local flags which will only run when this command
// is called directly, e.g.:
// addCmd.Flags().BoolP("toggle", "t", false, "Help message for toggle")
}

39
cmd/overtime.go Normal file
View file

@ -0,0 +1,39 @@
package cmd
import (
"fmt"
"time"
"github.com/Luzifer/worktime/schema"
"github.com/spf13/cobra"
)
// overtimeCmd represents the overtime command
var overtimeCmd = &cobra.Command{
Use: "overtime",
Short: "Shows total overtime over all time",
RunE: func(cmd *cobra.Command, args []string) error {
overtime, err := schema.GetOvertime(cfg.couchDB, time.Time{})
if err != nil {
return err
}
fmt.Printf("Total overtime: %s\n", time.Duration(overtime.Value*float64(time.Hour)))
return nil
},
}
func init() {
RootCmd.AddCommand(overtimeCmd)
// Here you will define your flags and configuration settings.
// Cobra supports Persistent Flags which will work for this command
// and all subcommands, e.g.:
// overtimeCmd.PersistentFlags().String("foo", "", "A help for foo")
// Cobra supports local flags which will only run when this command
// is called directly, e.g.:
// overtimeCmd.Flags().BoolP("toggle", "t", false, "Help message for toggle")
}

64
cmd/patch.go Normal file
View file

@ -0,0 +1,64 @@
package cmd
import (
"errors"
"fmt"
"strings"
"time"
"github.com/Luzifer/worktime/schema"
"github.com/spf13/cobra"
)
// patchCmd represents the patch command
var patchCmd = &cobra.Command{
Use: "patch <day> <time id> <start> <end> [[+/-]tag [[+/-]tag]]",
Short: "A brief description of your command",
RunE: func(cmd *cobra.Command, args []string) error {
if len(args) < 4 {
return fmt.Errorf("Please supply required arguments")
}
day, err := time.Parse("2006-01-02", args[0])
if err != nil {
return fmt.Errorf("'day' parameter seems to have a wrong format: %s", err)
}
doc, err := schema.LoadDay(cfg.couchDB, day, false)
if err != nil {
return err
}
for _, t := range doc.Times {
if strings.HasPrefix(t.ID, args[1]) {
if args[2] != "=" {
t.Start = args[2]
}
if args[3] != "=" {
t.End = args[3]
}
for _, tag := range args[4:] {
t.Tag(tag)
}
return doc.Save(cfg.couchDB)
}
}
return errors.New("No time frame with the given ID was found")
},
}
func init() {
timeCmd.AddCommand(patchCmd)
// Here you will define your flags and configuration settings.
// Cobra supports Persistent Flags which will work for this command
// and all subcommands, e.g.:
// patchCmd.PersistentFlags().String("foo", "", "A help for foo")
// Cobra supports local flags which will only run when this command
// is called directly, e.g.:
// patchCmd.Flags().BoolP("toggle", "t", false, "Help message for toggle")
}

66
cmd/remove.go Normal file
View file

@ -0,0 +1,66 @@
package cmd
import (
"fmt"
"strings"
"time"
"github.com/Luzifer/worktime/schema"
"github.com/spf13/cobra"
)
// removeCmd represents the remove command
var removeCmd = &cobra.Command{
Use: "remove [day] <id>",
Short: "Deletes a time frame from the given day",
Aliases: []string{"rm"},
RunE: func(cmd *cobra.Command, args []string) error {
var inDay, inID string
switch len(args) {
case 2:
inDay = args[0]
inID = args[1]
case 1:
inDay = time.Now().Format("2006-01-02")
inID = args[0]
default:
return fmt.Errorf("Please supply required arguments")
}
day, err := time.Parse("2006-01-02", inDay)
if err != nil {
return fmt.Errorf("'day' parameter seems to have a wrong format: %s", err)
}
doc, err := schema.LoadDay(cfg.couchDB, day, false)
if err != nil {
return err
}
nt := []*schema.Time{}
for i := range doc.Times {
if !strings.HasPrefix(doc.Times[i].ID, inID) {
nt = append(nt, doc.Times[i])
}
}
doc.Times = nt
return doc.Save(cfg.couchDB)
},
}
func init() {
timeCmd.AddCommand(removeCmd)
// Here you will define your flags and configuration settings.
// Cobra supports Persistent Flags which will work for this command
// and all subcommands, e.g.:
// removeCmd.PersistentFlags().String("foo", "", "A help for foo")
// Cobra supports local flags which will only run when this command
// is called directly, e.g.:
// removeCmd.Flags().BoolP("toggle", "t", false, "Help message for toggle")
}

83
cmd/root.go Normal file
View file

@ -0,0 +1,83 @@
package cmd
import (
"fmt"
"net/url"
"os"
couch "github.com/lancecarlson/couchgo"
"github.com/spf13/cobra"
"github.com/spf13/viper"
)
var cfg = struct {
CfgFile string
couchDB *couch.Client
}{}
// RootCmd represents the base command when called without any subcommands
var RootCmd = &cobra.Command{
Use: "worktime",
Short: "Manage worktimes in CouchDB",
// Uncomment the following line if your bare application
// has an action associated with it:
// Run: func(cmd *cobra.Command, args []string) { },
PersistentPreRunE: func(cmd *cobra.Command, args []string) error {
var err error
if viper.GetString("couchdb") == "" {
return fmt.Errorf("couchdb url needs to be set")
}
u, err := url.Parse(viper.GetString("couchdb"))
if err != nil {
return err
}
cfg.couchDB = couch.NewClient(u)
return nil
},
}
// Execute adds all child commands to the root command sets flags appropriately.
// This is called by main.main(). It only needs to happen once to the rootCmd.
func Execute() {
if err := RootCmd.Execute(); err != nil {
fmt.Println(err)
os.Exit(-1)
}
}
func init() {
cobra.OnInitialize(initConfig)
// Here you will define your flags and configuration settings.
// Cobra supports Persistent Flags, which, if defined here,
// will be global for your application.
RootCmd.PersistentFlags().String("couchdb", "", "URL to access couchdb (http://user:pass@host:port/database)")
viper.BindPFlag("couchdb", RootCmd.PersistentFlags().Lookup("couchdb"))
RootCmd.PersistentFlags().StringVar(&cfg.CfgFile, "config", "", "config file (default is $HOME/.worktime.yaml)")
// Cobra also supports local flags, which will only run
// when this action is called directly.
//RootCmd.Flags().BoolP("toggle", "t", false, "Help message for toggle")
}
// initConfig reads in config file and ENV variables if set.
func initConfig() {
if cfg.CfgFile != "" { // enable ability to specify config file via flag
viper.SetConfigFile(cfg.CfgFile)
}
viper.SetConfigName(".worktime") // name of config file (without extension)
viper.AddConfigPath("$HOME") // adding home directory as first search path
viper.AutomaticEnv() // read in environment variables that match
// If a config file is found, read it in.
if err := viper.ReadInConfig(); err == nil {
fmt.Println("Using config file:", viper.ConfigFileUsed())
}
}

68
cmd/show.go Normal file
View file

@ -0,0 +1,68 @@
package cmd
import (
"fmt"
"os"
"text/template"
"time"
"github.com/Luzifer/worktime/schema"
"github.com/spf13/cobra"
)
// showCmd represents the show command
var showCmd = &cobra.Command{
Use: "show [day]",
Short: "Display a summary of the given / current day",
RunE: func(cmd *cobra.Command, args []string) error {
if len(args) != 1 {
args = []string{time.Now().Format("2006-01-02")}
}
day, err := time.Parse("2006-01-02", args[0])
if err != nil {
return fmt.Errorf("'day' parameter seems to have a wrong format: %s", err)
}
doc, err := schema.LoadDay(cfg.couchDB, day, false)
if err != nil {
return err
}
overtime, err := schema.GetOvertime(cfg.couchDB, day)
if err != nil {
return err
}
tplSrc, err := Asset("templates/show.tpl")
if err != nil {
return err
}
tpl, err := template.New("show").Parse(string(tplSrc))
if err != nil {
return err
}
return tpl.Execute(os.Stdout, map[string]interface{}{
"day": doc,
"overtime": time.Duration(overtime.Value * float64(time.Hour)),
})
},
}
func init() {
RootCmd.AddCommand(showCmd)
// Here you will define your flags and configuration settings.
// Cobra supports Persistent Flags which will work for this command
// and all subcommands, e.g.:
// showCmd.PersistentFlags().String("foo", "", "A help for foo")
// Cobra supports local flags which will only run when this command
// is called directly, e.g.:
// showCmd.Flags().BoolP("toggle", "t", false, "Help message for toggle")
}

66
cmd/tag.go Normal file
View file

@ -0,0 +1,66 @@
package cmd
import (
"fmt"
"strings"
"time"
"github.com/Luzifer/worktime/schema"
"github.com/spf13/cobra"
)
// tagCmd represents the tag command
var tagCmd = &cobra.Command{
Use: "tag <day> [time-id] <[+/-]tag>",
Short: "Adds or removes a tag from the day or time entry inside the day",
RunE: func(cmd *cobra.Command, args []string) error {
var timeId, tag string
switch len(args) {
case 2:
tag = args[1]
case 3:
timeId = args[1]
tag = args[2]
default:
return fmt.Errorf("Please supply required arguments")
}
day, err := time.Parse("2006-01-02", args[0])
if err != nil {
return fmt.Errorf("'day' parameter seems to have a wrong format: %s", err)
}
doc, err := schema.LoadDay(cfg.couchDB, day, true)
if err != nil {
return err
}
if timeId != "" {
for _, t := range doc.Times {
if strings.HasPrefix(t.ID, timeId) {
t.Tag(tag)
return doc.Save(cfg.couchDB)
}
}
return fmt.Errorf("Could not find time with ID '%s'", timeId)
}
doc.Tag(tag)
return doc.Save(cfg.couchDB)
},
}
func init() {
RootCmd.AddCommand(tagCmd)
// Here you will define your flags and configuration settings.
// Cobra supports Persistent Flags which will work for this command
// and all subcommands, e.g.:
// tagCmd.PersistentFlags().String("foo", "", "A help for foo")
// Cobra supports local flags which will only run when this command
// is called directly, e.g.:
// tagCmd.Flags().BoolP("toggle", "t", false, "Help message for toggle")
}

237
cmd/templates.go Normal file
View file

@ -0,0 +1,237 @@
// Code generated by go-bindata.
// sources:
// templates/show.tpl
// DO NOT EDIT!
package cmd
import (
"bytes"
"compress/gzip"
"fmt"
"io"
"io/ioutil"
"os"
"path/filepath"
"strings"
"time"
)
func bindataRead(data []byte, name string) ([]byte, error) {
gz, err := gzip.NewReader(bytes.NewBuffer(data))
if err != nil {
return nil, fmt.Errorf("Read %q: %v", name, err)
}
var buf bytes.Buffer
_, err = io.Copy(&buf, gz)
clErr := gz.Close()
if err != nil {
return nil, fmt.Errorf("Read %q: %v", name, err)
}
if clErr != nil {
return nil, err
}
return buf.Bytes(), nil
}
type asset struct {
bytes []byte
info os.FileInfo
}
type bindataFileInfo struct {
name string
size int64
mode os.FileMode
modTime time.Time
}
func (fi bindataFileInfo) Name() string {
return fi.name
}
func (fi bindataFileInfo) Size() int64 {
return fi.size
}
func (fi bindataFileInfo) Mode() os.FileMode {
return fi.mode
}
func (fi bindataFileInfo) ModTime() time.Time {
return fi.modTime
}
func (fi bindataFileInfo) IsDir() bool {
return false
}
func (fi bindataFileInfo) Sys() interface{} {
return nil
}
var _templatesShowTpl = []byte("\x1f\x8b\x08\x00\x00\x09\x6e\x88\x00\xff\x84\x90\xb1\x8a\xc3\x30\x10\x44\x7b\x7d\xc5\x60\xb8\xf2\x74\xe5\xc1\x81\x3a\xbb\x70\x75\x85\xf3\x03\x0b\x96\x8d\x20\x92\x83\xa4\x04\x8c\xd8\x7f\x0f\x2b\x39\x90\xa4\x89\xab\x9d\xf5\xcc\xec\x43\xc6\x18\x83\xe9\xea\x3d\xc5\x1d\xdb\x82\x52\xa0\x67\xda\x75\x4f\xfb\xd8\x83\x19\x62\x50\x27\x5a\xd3\x9f\xfc\x8b\x14\x56\xdb\x1c\xb2\x03\xb3\x04\xc4\x57\x0a\xec\x39\x59\x30\x87\x1f\x12\x11\x66\x30\x2b\x55\x0a\xdc\x72\x24\x9c\xb7\x09\xdf\xcc\x6a\xec\xd1\xbe\x29\x53\xcc\x75\x1a\xc2\x7c\xec\xa4\xf8\xed\x54\x0d\x32\x4b\xd9\x25\xba\x90\x17\x74\x5f\xfa\x37\x75\xd0\x0d\xb2\x62\xb7\xae\x87\x1a\xea\x7d\x3c\x41\x4b\xef\x27\xde\x57\x70\x19\x05\xf7\xff\x66\x63\x76\xde\xd6\x27\xd0\xdb\xa1\xc4\x75\x0f\x00\x00\xff\xff\x0d\x5c\x07\xed\x3f\x01\x00\x00")
func templatesShowTplBytes() ([]byte, error) {
return bindataRead(
_templatesShowTpl,
"templates/show.tpl",
)
}
func templatesShowTpl() (*asset, error) {
bytes, err := templatesShowTplBytes()
if err != nil {
return nil, err
}
info := bindataFileInfo{name: "templates/show.tpl", size: 319, mode: os.FileMode(436), modTime: time.Unix(1474552026, 0)}
a := &asset{bytes: bytes, info: info}
return a, nil
}
// Asset loads and returns the asset for the given name.
// It returns an error if the asset could not be found or
// could not be loaded.
func Asset(name string) ([]byte, error) {
cannonicalName := strings.Replace(name, "\\", "/", -1)
if f, ok := _bindata[cannonicalName]; ok {
a, err := f()
if err != nil {
return nil, fmt.Errorf("Asset %s can't read by error: %v", name, err)
}
return a.bytes, nil
}
return nil, fmt.Errorf("Asset %s not found", name)
}
// MustAsset is like Asset but panics when Asset would return an error.
// It simplifies safe initialization of global variables.
func MustAsset(name string) []byte {
a, err := Asset(name)
if err != nil {
panic("asset: Asset(" + name + "): " + err.Error())
}
return a
}
// AssetInfo loads and returns the asset info for the given name.
// It returns an error if the asset could not be found or
// could not be loaded.
func AssetInfo(name string) (os.FileInfo, error) {
cannonicalName := strings.Replace(name, "\\", "/", -1)
if f, ok := _bindata[cannonicalName]; ok {
a, err := f()
if err != nil {
return nil, fmt.Errorf("AssetInfo %s can't read by error: %v", name, err)
}
return a.info, nil
}
return nil, fmt.Errorf("AssetInfo %s not found", name)
}
// AssetNames returns the names of the assets.
func AssetNames() []string {
names := make([]string, 0, len(_bindata))
for name := range _bindata {
names = append(names, name)
}
return names
}
// _bindata is a table, holding each asset generator, mapped to its name.
var _bindata = map[string]func() (*asset, error){
"templates/show.tpl": templatesShowTpl,
}
// AssetDir returns the file names below a certain
// directory embedded in the file by go-bindata.
// For example if you run go-bindata on data/... and data contains the
// following hierarchy:
// data/
// foo.txt
// img/
// a.png
// b.png
// then AssetDir("data") would return []string{"foo.txt", "img"}
// AssetDir("data/img") would return []string{"a.png", "b.png"}
// AssetDir("foo.txt") and AssetDir("notexist") would return an error
// AssetDir("") will return []string{"data"}.
func AssetDir(name string) ([]string, error) {
node := _bintree
if len(name) != 0 {
cannonicalName := strings.Replace(name, "\\", "/", -1)
pathList := strings.Split(cannonicalName, "/")
for _, p := range pathList {
node = node.Children[p]
if node == nil {
return nil, fmt.Errorf("Asset %s not found", name)
}
}
}
if node.Func != nil {
return nil, fmt.Errorf("Asset %s not found", name)
}
rv := make([]string, 0, len(node.Children))
for childName := range node.Children {
rv = append(rv, childName)
}
return rv, nil
}
type bintree struct {
Func func() (*asset, error)
Children map[string]*bintree
}
var _bintree = &bintree{nil, map[string]*bintree{
"templates": &bintree{nil, map[string]*bintree{
"show.tpl": &bintree{templatesShowTpl, map[string]*bintree{}},
}},
}}
// RestoreAsset restores an asset under the given directory
func RestoreAsset(dir, name string) error {
data, err := Asset(name)
if err != nil {
return err
}
info, err := AssetInfo(name)
if err != nil {
return err
}
err = os.MkdirAll(_filePath(dir, filepath.Dir(name)), os.FileMode(0755))
if err != nil {
return err
}
err = ioutil.WriteFile(_filePath(dir, name), data, info.Mode())
if err != nil {
return err
}
err = os.Chtimes(_filePath(dir, name), info.ModTime(), info.ModTime())
if err != nil {
return err
}
return nil
}
// RestoreAssets restores an asset under the given directory recursively
func RestoreAssets(dir, name string) error {
children, err := AssetDir(name)
// File
if err != nil {
return RestoreAsset(dir, name)
}
// Dir
for _, child := range children {
err = RestoreAssets(dir, filepath.Join(name, child))
if err != nil {
return err
}
}
return nil
}
func _filePath(dir, name string) string {
cannonicalName := strings.Replace(name, "\\", "/", -1)
return filepath.Join(append([]string{dir}, strings.Split(cannonicalName, "/")...)...)
}

38
cmd/time.go Normal file
View file

@ -0,0 +1,38 @@
// Copyright © 2016 NAME HERE <EMAIL ADDRESS>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package cmd
import "github.com/spf13/cobra"
// timeCmd represents the time command
var timeCmd = &cobra.Command{
Use: "time",
Short: "manipulate times of a day",
}
func init() {
RootCmd.AddCommand(timeCmd)
// Here you will define your flags and configuration settings.
// Cobra supports Persistent Flags which will work for this command
// and all subcommands, e.g.:
// timeCmd.PersistentFlags().String("foo", "", "A help for foo")
// Cobra supports local flags which will only run when this command
// is called directly, e.g.:
// timeCmd.Flags().BoolP("toggle", "t", false, "Help message for toggle")
}

59
cmd/track.go Normal file
View file

@ -0,0 +1,59 @@
package cmd
import (
"crypto/sha1"
"fmt"
"os"
"os/signal"
"syscall"
"time"
"github.com/Luzifer/worktime/schema"
"github.com/spf13/cobra"
)
// trackCmd represents the track command
var trackCmd = &cobra.Command{
Use: "track [tag [tag]]",
Short: "Track a time frame from the command start until interruption",
RunE: func(cmd *cobra.Command, args []string) error {
start := time.Now()
fmt.Println("Press Ctrl+C to stop time tracking...")
c := make(chan os.Signal, 1)
signal.Notify(c, os.Interrupt, syscall.SIGTERM)
<-c // Blocks until a signal arrives
end := time.Now()
doc, err := schema.LoadDay(cfg.couchDB, start, true)
if err != nil {
return err
}
doc.Times = append(doc.Times, &schema.Time{
ID: fmt.Sprintf("%x", sha1.Sum([]byte(time.Now().String()))),
Start: start.Format("15:04:05"),
End: end.Format("15:04:05"),
Tags: args,
})
return doc.Save(cfg.couchDB)
},
}
func init() {
timeCmd.AddCommand(trackCmd)
// Here you will define your flags and configuration settings.
// Cobra supports Persistent Flags which will work for this command
// and all subcommands, e.g.:
// trackCmd.PersistentFlags().String("foo", "", "A help for foo")
// Cobra supports local flags which will only run when this command
// is called directly, e.g.:
// trackCmd.Flags().BoolP("toggle", "t", false, "Help message for toggle")
}

9
main.go Normal file
View file

@ -0,0 +1,9 @@
package main
//go:generate go-bindata -pkg cmd -o cmd/templates.go templates/
import "github.com/Luzifer/worktime/cmd"
func main() {
cmd.Execute()
}

220
schema/schema.go Normal file
View file

@ -0,0 +1,220 @@
package schema
import (
"fmt"
"net/url"
"sort"
"strings"
"time"
"github.com/Luzifer/go_helpers/str"
couch "github.com/lancecarlson/couchgo"
)
const (
TagIll = "ill"
TagVacation = "vacation"
TagWeekend = "weekend"
TagHoliday = "holiday"
TagEvent = "event"
TagHomeoffice = "homeoffice"
TagBreak = "break"
TagAutotrack = "autotrack"
TagOnCall = "on-call"
)
func evalTags(tags []string, tag string) []string {
rawTag := strings.TrimLeft(tag, "+-")
out := tags
switch tag[0] {
default:
fallthrough
case '+':
if !str.StringInSlice(rawTag, tags) {
out = append(tags, rawTag)
}
case '-':
if str.StringInSlice(rawTag, tags) {
out = []string{}
for _, t := range tags {
if t != rawTag {
out = append(out, t)
}
}
}
}
sort.Strings(out)
return out
}
type Day struct {
DayID string `json:"_id"`
Revision string `json:"_rev,omitempty"`
Times []*Time `json:"times"`
Tags []string `json:"tags,omitempty"`
// deprecated tags, have auto-migration
IsIll bool `json:"is_ill,omitempty"`
IsVacation bool `json:"is_vacation,omitempty"`
IsWeekend bool `json:"is_weekend,omitempty"`
IsHoliday bool `json:"is_holiday,omitempty"`
IsEvent bool `json:"is_event,omitempty"`
Homeoffice bool `json:"homeoffice,omitempty"`
}
func (d *Day) Tag(tag string) {
d.Tags = evalTags(d.Tags, tag)
}
func (d *Day) migrate() {
if d.IsIll {
d.Tag(TagIll)
}
if d.IsVacation {
d.Tag(TagVacation)
}
if d.IsWeekend {
d.Tag(TagWeekend)
}
if d.IsHoliday {
d.Tag(TagHoliday)
}
if d.IsEvent {
d.Tag(TagEvent)
}
if d.Homeoffice {
d.Tag(TagHomeoffice)
}
d.IsIll = false
d.IsEvent = false
d.IsVacation = false
d.IsWeekend = false
d.IsHoliday = false
d.Homeoffice = false
for _, t := range d.Times {
t.migrate()
}
}
func (d *Day) validate() error {
for _, t := range d.Times {
if err := t.validate(); err != nil {
return err
}
}
return nil
}
func LoadDay(db *couch.Client, date time.Time, mayCreate bool) (*Day, error) {
id := date.Format("2006-01-02")
doc := &Day{}
if err := db.Get(id, doc); err != nil {
if strings.Contains(err.Error(), "not_found") && mayCreate {
doc = &Day{DayID: id}
} else {
return nil, err
}
}
doc.migrate()
return doc, nil
}
func (d *Day) Save(db *couch.Client) error {
if err := d.validate(); err != nil {
return err
}
res, err := db.Save(d)
if err != nil {
return err
}
d.Revision = res.Rev
return nil
}
type Time struct {
ID string `json:"id"`
Start string `json:"start"`
End string `json:"end"`
Tags []string `json:"tags,omitempty"`
// deprecated tags, have auto-migration
IsBreak bool `json:"is_break,omitempty"`
IsAutotrack bool `json:"is_autotrack,omitempty"`
IsOnCall bool `json:"is_on_call,omitempty"`
}
func (w *Time) Tag(tag string) {
w.Tags = evalTags(w.Tags, tag)
}
func (w *Time) migrate() {
if w.IsBreak {
w.Tag(TagBreak)
}
if w.IsAutotrack {
w.Tag(TagAutotrack)
}
if w.IsOnCall {
w.Tag(TagOnCall)
}
w.IsBreak = false
w.IsAutotrack = false
w.IsOnCall = false
}
func (t *Time) validate() error {
now := time.Now().Format("15:04:05")
if t.Start == "now" {
t.Start = now
}
if t.End == "now" {
t.End = now
}
if _, err := time.Parse("15:04:05", t.Start); err != nil {
return fmt.Errorf("Time %.7s has invalid start date: %s", t.ID, err)
}
if _, err := time.Parse("15:04:05", t.End); err != nil {
return fmt.Errorf("Time %.7s has invalid end date: %s", t.ID, err)
}
return nil
}
type Overtime struct {
Value float64 `json:"value"`
}
func GetOvertime(db *couch.Client, day time.Time) (Overtime, error) {
var opts *url.Values
if !day.IsZero() {
opts = &url.Values{}
opts.Set("reduce", "false")
opts.Set("startkey", fmt.Sprintf("\"%s\"", day.Format("2006-01-02")))
opts.Set("endkey", fmt.Sprintf("\"%s\"", day.Format("2006-01-02")))
}
mdr, err := db.View("analysis", "overtime", opts, nil)
if err != nil {
return Overtime{}, err
}
if len(mdr.Rows) == 0 {
return Overtime{}, fmt.Errorf("Did not find any results in view")
}
result := Overtime{}
return result, couch.Remarshal(mdr.Rows[0], &result)
}

9
templates/show.tpl Normal file
View file

@ -0,0 +1,9 @@
==== Summary of {{ .day.DayID }} ====
Tags: {{ range .day.Tags }}{{ . }} {{ else }}n/a{{ end }}
{{ if .day.Times -}}
ID Start End Tags{{ range .day.Times }}
{{ printf "%.7s" .ID }} {{ .Start }} {{ .End }} {{ range .Tags}}{{ . }} {{ else }}n/a{{ end }}{{ end }}
{{ end -}}
Overtime: {{ .overtime }}