├── .editorconfig ├── .github ├── FUNDING.yml └── workflows │ └── release.yml ├── .gitignore ├── .goreleaser.yaml ├── CHANGES.md ├── LICENSE ├── Makefile ├── README.md ├── _config.yml ├── documentation ├── header.jpg ├── tyme3json.png ├── zeit.png └── zeit_stats.jpg ├── extras ├── test-parsing.sh ├── zeit-sketchybar.sh ├── zeit-waybar-bemenu.sh ├── zeit-waybar-wofi.sh └── zeit.1m.sh ├── go.mod ├── go.sum ├── z ├── calendar.go ├── constants.go ├── database.go ├── entry.go ├── entryCmd.go ├── eraseCmd.go ├── exportCmd.go ├── finishCmd.go ├── helpers.go ├── importCmd.go ├── listCmd.go ├── project.go ├── projectCmd.go ├── reportCmd.go ├── resumeCmd.go ├── rootCmd.go ├── statsCmd.go ├── switchBackCmd.go ├── switchCmd.go ├── task.go ├── taskCmd.go ├── trackCmd.go ├── trackingCmd.go ├── tui.go ├── tyme.go ├── util.go └── versionCmd.go └── zeit.go /.editorconfig: -------------------------------------------------------------------------------- 1 | root = true 2 | 3 | [*] 4 | end_of_line = lf 5 | charset = utf-8 6 | trim_trailing_whitespace = true 7 | insert_final_newline = true 8 | max_line = 80 9 | 10 | [*.{md,markdown}] 11 | trim_trailing_whitespace = false 12 | 13 | [{Makefile,Makefile.*}] 14 | indent_style = tab 15 | indent_size = 2 16 | -------------------------------------------------------------------------------- /.github/FUNDING.yml: -------------------------------------------------------------------------------- 1 | custom: ["https://github.com/mrusme#support"] 2 | -------------------------------------------------------------------------------- /.github/workflows/release.yml: -------------------------------------------------------------------------------- 1 | name: Release 2 | 3 | on: 4 | push: 5 | tags: 6 | - '*' 7 | 8 | jobs: 9 | 10 | release: 11 | runs-on: ubuntu-latest 12 | steps: 13 | - uses: actions/checkout@v4 14 | 15 | - name: Set up Go 16 | uses: actions/setup-go@v5 17 | with: 18 | go-version: 1.22 19 | 20 | - name: Run GoReleaser 21 | uses: goreleaser/goreleaser-action@v6 22 | with: 23 | distribution: goreleaser 24 | version: '~> v2' 25 | args: release --clean --timeout 80m 26 | env: 27 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} 28 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Binaries for programs and plugins 2 | *.exe 3 | *.exe~ 4 | *.dll 5 | *.so 6 | *.dylib 7 | 8 | # Test binary, built with `go test -c` 9 | *.test 10 | 11 | # Output of the go coverage tool, specifically when used with LiteIDE 12 | *.out 13 | 14 | # Dependency directories (remove the comment below to include it) 15 | # vendor/ 16 | 17 | /zeit 18 | /db 19 | /db.demo 20 | /charts.txt 21 | .DS_Store 22 | -------------------------------------------------------------------------------- /.goreleaser.yaml: -------------------------------------------------------------------------------- 1 | # .goreleaser.yaml 2 | builds: 3 | - 4 | env: 5 | - CGO_ENABLED=0 6 | goos: 7 | - darwin 8 | - linux 9 | - netbsd 10 | - openbsd 11 | - freebsd 12 | - plan9 13 | - windows 14 | goarch: 15 | - 386 16 | - amd64 17 | - arm 18 | - arm64 19 | goarm: 20 | - 6 21 | - 7 22 | ignore: 23 | - goos: darwin 24 | goarch: 386 25 | - goos: darwin 26 | goarch: arm 27 | - goos: netbsd 28 | goarch: arm64 29 | - goos: freebsd 30 | goarm: arm64 31 | - goos: plan9 32 | goarm: arm64 33 | 34 | -------------------------------------------------------------------------------- /CHANGES.md: -------------------------------------------------------------------------------- 1 | ## Command structure 2 | 3 | | Root | Sub | short-opt | long-opt | Time Option | New | 4 | | ---- | ---------- | --------- | --------------------------- | ----------- | --- | 5 | | zeit | | -h | --help | | | 6 | | | | | --no-colors | | | 7 | | | | | --config | | X | 8 | | | | -d | --debug | | | 9 | | | completion | -h | --help | | | 10 | | | | | --no-descriptions | | | 11 | | | entry | -b | --begin | X | | 12 | | | | | --decimal | | | 13 | | | | -s | --finish | X | | 14 | | | | -h | --help | | | 15 | | | | -n | --notes | | | 16 | | | | -p | --project | | | 17 | | | | -t | --task | | | 18 | | | erase | -h | --help | | | 19 | | | export | -h | --help | | | 20 | | | | | --format | | | 21 | | | | -p | --project | | | 22 | | | | | --range | | X | 23 | | | | | --since | X | | 24 | | | | -t | --task | | | 25 | | | | | --until | X | | 26 | | | finish | -b | --begin | X | | 27 | | | | -s | --finish | X | | 28 | | | | -h | --help | | | 29 | | | | -n | --notes | | | 30 | | | | -p | --project | | | 31 | | | | -t | --task | | | 32 | | | help | -h | --help | | | 33 | | | import | | --format | | | 34 | | | | -h | --help | | | 35 | | | list | | --append-project-id-to-task | | | 36 | | | | | --decimal | | | 37 | | | | -h | --help | | | 38 | | | | | --only-projects-and-tasks | | | 39 | | | | | --only-tasks | | | 40 | | | | -p | --project | | | 41 | | | | | --range | | X | 42 | | | | | --since | X | | 43 | | | | -t | --task | | | 44 | | | | | --total | | | 45 | | | | | --until | X | | 46 | | | project | -c | --color | | | 47 | | | | -h | --help | | | 48 | | | report | -h | --help | | X | 49 | | | | -p | --project | | X | 50 | | | | | --range | | X | 51 | | | | | --since | X | X | 52 | | | | -t | --task | | X | 53 | | | | | --until | X | X | 54 | | | resume | -h | --help | | X | 55 | | | | -b | --begin | X | X | 56 | | | | -s | --finish | X | X | 57 | | | sketchy | -h | --help | | X | 58 | | | stats | | --decimal | | | 59 | | | | -h | --help | | | 60 | | | switch | -h | --help | | X | 61 | | | | -b | --begin | X | X | 62 | | | | -n | --notes | | X | 63 | | | | -p | --project | | X | 64 | | | | -t | --task | | X | 65 | | | switchback | -h | --help | | X | 66 | | | | -b | --begin | X | X | 67 | | | task | -g | --git | | | 68 | | | | -h | --help | | | 69 | | | track | -b | --begin | X | | 70 | | | | -s | --finish | X | | 71 | | | | -f | --force | | | 72 | | | | -n | --notes | | | 73 | | | | -p | --project | | | 74 | | | | -t | --task | | | 75 | | | | -h | --help | | | 76 | | | tracking | -h | --help | | | 77 | | | version | -h | --help | | | 78 | 79 | ## Changes 80 | 81 | ### Extension Viper and Cobra 82 | 83 | The extension of Cobra with Viper opens up the possibility of persisting time settings in a configuration file. This configuration file is optional, all default settings are chosen so that the behaviour of time does not change if this file does not exist. 84 | 85 | By default, this file is searched for in $XDG_CONFIG_HOME/zeit/zeit.yaml (XDG_CONFIG_HOME => $HOME/.config), can also be overwritten with --config. 86 | 87 | ``` 88 | db: /Users/schretzi/OneDrive/Zeit/zeit.db 89 | debug: false 90 | firstWeekDayMonday: true 91 | ``` 92 | 93 | ### Linting 94 | 95 | I also use GO professionally and as a result I have linter and style checking software running on my system, which report masses of warnings and errors wih the current code. I have cleaned up the code and adapted it according to SolarLint and GO best practices so that my IDE and build tools are clear again and new, real errors are visible. 96 | 97 | ### Time Parsing 98 | 99 | Different places use different parsing of time - track vs. entry. This always leads to errors during entry or some entries have to be unnecessarily long. 100 | I have now combined these processes: I have incorporated dateparse from entryCmd into the helper/parseTime function and then adapted entryCmd so that this function is used via the struct method. This means that all -b and -s parameters now process the time entered in the same way. In my opinion, this should also solve issue #29 in Github. 101 | 102 | #### now Library vs. DataParse 103 | 104 | Elsewhere, the now library is used to parse time. I did not succeed in deduplicating the two libraries to one, as now does not successfully master most of the test cases. Therefore, I still use DataParse for the inputs and now for the list selection 105 | 106 | #### Test Cases 107 | 108 | ``` 109 | go run . track -p "TESTS" -t "Zeit-Test" -b '10:00' -s '11:00' 110 | go run . track -p "TESTS" -t "Zeit-Test" -b '01:00pm' -s '02:00pm' 111 | go run . track -p "TESTS" -t "Zeit-Test" -b '-04:00' -s '-03:00' 112 | go run . track -p "TESTS" -t "Zeit-Test" -b '-02:00' -s '+01:00' 113 | go run . track -p "TESTS" -t "Zeit-Test" -b '2023-09-11 10:00 +0300' -s '2023-09-11 12:00 +0400' 114 | go run . track -p "TESTS" -t "Zeit-Test" -b '2023-09-11 20:00' -s '2023-09-11 21:00' 115 | go run . track -p "TESTS" -t "Zeit-Test" -b '2023-09-11T20:00' -s '2023-09-11T21:00' 116 | go run . track -p "TESTS" -t "Zeit-Test" -b '2023-09-11T20:00:00' -s '2023-09-11T21:00:00' 117 | go run . track -p "TESTS" -t "Zeit-Test" -b '2023-09-11T20:00:00+02:00' -s '2023-09-11T21:00:00+02:00' 118 | ``` 119 | 120 | ### Relative Time 121 | 122 | Relative time entries are always calculated by time.Now. In the context of tracking new entries this also makes sense, when editing existing entries I would expect the changes to be applied to the existing time, this has now been changed. 123 | 124 | ``` 125 | go run . track -p TESTS -t Rel-Tests -b -01:00 -s +01:00 126 | 127 | go run . list 128 | f4297201-c5d9-415b-a7f2-5f39f4fbf19b Rel-Tests on TESTS from 2024-05-18 20:52 +0200 to 2024-05-18 22:52 +0200 (2:00h) 129 | 130 | go run . entry f4297201-c5d9-415b-a7f2-5f39f4fbf19b -b -01:00 -s +01:00 131 | 132 | go run . list 133 | f4297201-c5d9-415b-a7f2-5f39f4fbf19b Rel-Tests on TESTS from 2024-05-18 19:52 +0200 to 2024-05-18 23:52 +0200 (4:00h) 134 | ``` 135 | 136 | ### Round to Minute 137 | 138 | My applications do not require billing to the second, minutes are sufficient. At the moment, however, there may be deviations or ambiguities due to rounding. I have added an optional setting which always rounds to the full minute 139 | 140 | ``` 141 | time: 142 | no-seconds: true 143 | ``` 144 | 145 | ``` 146 | {"begin":"2024-05-18T21:14:06.74637+02:00","finish":"2024-05-18T23:14:06.746393+02:00","project":"TESTS","task":"Rel-Tests","user":"schretzi"} 147 | {"begin":"2024-05-18T21:14:00+02:00","finish":"2024-05-18T23:14:00+02:00","project":"TESTS","task":"Rel-Tests","user":"schretzi"} 148 | ``` 149 | 150 | ### Project and Task mandatory with default Project 151 | 152 | For my use case, entries without project and task make no sense, most of the time is booked to a project (job). I therefore have the following optional settings: 153 | 154 | - Project and task are required, no entry can be created without them 155 | - If no project is passed as a parameter, a default value can be used 156 | 157 | ``` 158 | project: 159 | mandatory: true 160 | default: TESTS 161 | task: 162 | mandatory: true 163 | ``` 164 | 165 | ### since/until/range 166 | 167 | I always need the same relative time ranges for the list view or the report, setting --since and --until for this is time consuming, so I added the optional --range parameter.If this is set, --since and --until are set to the corresponding values via the now library: 168 | 169 | - today 170 | - yesterday 171 | - thisWeek 172 | - lastWeek 173 | - thisMonth 174 | - lastMonth 175 | 176 | #### Testcases 177 | 178 | ``` 179 | MONTH=4 180 | YEAR=2024 181 | for i in $(seq 1 30) 182 | do 183 | go run . track -p "TESTS" -t "RangeTests" -b "2024-${MONTH}-${i} 10:00" -s "2024-${MONTH}-${i} 17:00" 184 | done 185 | 186 | MONTH=5 187 | YEAR=2024 188 | for i in $(seq 1 19) 189 | do 190 | go run . track -p "TESTS" -t "RangeTests" -b "2024-${MONTH}-${i} 10:00" -s "2024-${MONTH}-${i} 17:00" 191 | done 192 | 193 | go run . list --range today 194 | go run . list --range thisWeek 195 | ``` 196 | 197 | ### FmtDuration Bug - Open: 198 | 199 | fmt.Println(trackDiff) 200 | 201 | taskDuration := fmtDuration(trackDiff) 202 | 203 | fmt.Println(taskDuration) 204 | 205 | 1h20m0s 206 | 1:19 207 | 208 | ### New Functions resume / switch / switchback 209 | 210 | Some processes that occur in my everyday work have required several steps or entries that can be avoided, so there are three new functions: 211 | 212 | - resume: The last task (last entry in the list sorted by start time) is resumed - only the times are provided as parameters, otherwise it would not be the last task 213 | - switch: I always have to interrupt my work due to meetings or operational activities. The switch is used to end the current task at the specified time (-b or now()) and start a new one with the specified parameters 214 | - switchback: After the meeting, I want to resume the previous activity using -b to set the time of the switch 215 | 216 | Example procedure: I work on the development of the new functions until the end of the previous day, in the morning I resume work, at 09.00 there is the daily with my team colleagues, then the development is continued: 217 | 218 | ``` 219 | zeit track -p "TESTS" -t "Develop new features" -b "2024-05-18 15:00" -s "2024-05-18 19:00" 220 | ▶ tracked Develop new features on TESTS 221 | 222 | zeit list 223 | 38cdcc16-eb58-4b5b-b564-dbfb979f537c Develop new features on TESTS from 2024-05-18 15:00 +0200 to 2024-05-18 19:00 +0200 (4:00h) 224 | 225 | zeit resume -b "2024-05-19 07:40" 226 | ▶ began tracking Develop new features on TESTS 227 | 228 | zeit list 229 | 38cdcc16-eb58-4b5b-b564-dbfb979f537c Develop new features on TESTS from 2024-05-18 15:00 +0200 to 2024-05-18 19:00 +0200 (4:00h) 230 | 7461cdf8-efc9-4468-9f7c-8990ab1a62df Develop new features on TESTS from 2024-05-19 07:40 +0200 to 2024-05-19 10:32 +0200 (2:52h) [running] 231 | 232 | 233 | zeit switch -b 09:00 -t "Daily" 234 | ■ finished tracking Develop new features on TESTS for 1:20h 235 | ▶ began tracking Daily on TESTS 236 | 237 | zeit switchback -b 09:20 238 | ■ finished tracking Daily on TESTS for 0:20h 239 | ▶ began tracking Develop new features on TESTS 240 | 241 | zeit list 242 | 38cdcc16-eb58-4b5b-b564-dbfb979f537c Develop new features on TESTS from 2024-05-18 15:00 +0200 to 2024-05-18 19:00 +0200 (4:00h) 243 | 7461cdf8-efc9-4468-9f7c-8990ab1a62df Develop new features on TESTS from 2024-05-19 07:40 +0200 to 2024-05-19 09:00 +0200 (1:20h) 244 | 421f65b2-291a-47d0-a1b4-4e344ea52731 Daily on TESTS from 2024-05-19 09:00 +0200 to 2024-05-19 09:20 +0200 (0:20h) 245 | 81e2ca0f-6de7-4550-ab0b-fc9e3e576544 Develop new features on TESTS from 2024-05-19 09:20 +0200 to 2024-05-19 10:41 +0200 (1:21h) [running] 246 | 247 | ``` 248 | 249 | ### New Function report 250 | 251 | To be able to easily transfer my accumulated times to the time reports of my employer and my private projects, I need a clearer overview than list, but more detailed than stats. Therefore I have created a new function report that totals per day / project / task. 252 | 253 | ``` 254 |  zeit report -h 255 | Reporting summaries on daily, project, task level for a given range 256 | 257 | Usage: 258 | zeit report [flags] 259 | 260 | Flags: 261 | -h, --help help for report 262 | -p, --project string Project to be listed 263 | --range string shortcut to set since/until for a given range (today, yesterday, thisWeek, lastWeek, thisMonth, lastMonth) 264 | --since string Date/time to start the list from 265 | -t, --task string Task to be listed 266 | --until string Date/time to list until 267 | 268 | Global Flags: 269 | --config string config file (default is $XDG_CONFIG_HOME/zeit/zeit.yaml) 270 | -d, --debug Display debugging output in the console. (default: false) 271 | --no-colors Do not use colors in output 272 | ``` 273 | 274 | For a quick overview, there is the option in the configuration file to define a period as the default, in my case the current week 275 | 276 | ``` 277 | report: 278 | default: thisWeek 279 | ``` 280 | 281 | ``` 282 |  zeit report 283 | Reporting for Timerange: thisWeek / 2024-05-27 - 2024-06-02 284 | 285 | 2024-05-27 : 3h0m0s 286 | TESTS : 2h0m0s 287 | Testing actual status : 2h0m0s 288 | ZEIT : 1h0m0s 289 | Creating Switch function : 1h0m0s 290 | 291 | 2024-05-28 : 1h23m0s 292 | ZEIT : 1h23m0s 293 | Creating Report function : 40m0s 294 | Daily : 30m0s 295 | Documentation : 13m0s 296 | 297 | ``` 298 | 299 | ### New Function sketchy 300 | 301 | I work on a Macbook with the Sketchybar as an additional menu bar. In this I would like to display the current status of the time recording. The output of tracking cannot be used 1:1 and I am still considering adding the total hours per day or something similar in the future. Therefore a new function ‘sketchy’ which has no parameters and calls the sketchbar function to set the label. The path to sketchybar must be set in the configuration file: 302 | 303 | ``` 304 | sketchybar: 305 | path: /opt/homebrew/bin/sketchybar 306 | ``` 307 | 308 | The following paragraph must be added to the sketchbarrc: 309 | 310 | ``` 311 | ##### Show actual Zeit tracking 312 | 313 | sketchybar --add item zeit e \ 314 | --set zeit icon=󱏁 \ 315 | script="/zeit sketchy" \ 316 | update_freq=15 317 | ``` 318 | 319 | This means that the current tracking in the form \|\ is displayed in the sketch bar to the right of the notch (e): \ 320 | 321 | ### Custom Completions for Tasks 322 | 323 | After entering ‘-task’, \\ displays the list of tasks in the database. 324 | Future topics on this: 325 | 326 | - Filter by tasks from projects 327 | - Performance when there are large numbers of entries in the database (it is unclear to me how the performance develops anyway) 328 | 329 | ## Future Ideas if I find time 330 | 331 | - Listing Project (with tasks) 332 | - Listing Tasks 333 | - Archiving Tasks (in sense that autocompletion only shows active tasks) 334 | - UI (report, edit existing tasks) 335 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | VERSION=0.0 2 | 3 | all: 4 | go build -ldflags "-X github.com/mrusme/zeit/z.VERSION=$(VERSION)" 5 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | Zeit 2 | ---- 3 | 4 | ![zeit](documentation/zeit.png) 5 | 6 | [![Static 7 | Badge](https://img.shields.io/badge/Join_on_Matrix-green?style=for-the-badge&logo=element&logoColor=%23ffffff&label=Chat&labelColor=%23333&color=%230DBD8B&link=https%3A%2F%2Fmatrix.to%2F%23%2F%2521PHlbgZTdrhjkCJrfVY%253Amatrix.org)](https://matrix.to/#/%21PHlbgZTdrhjkCJrfVY%3Amatrix.org) 8 | 9 | Zeit, erfassen. A command line tool for tracking time spent on tasks & projects. 10 | 11 | [Get some more info on why I build this 12 | here](https://マリウス.com/zeit-erfassen-a-cli-activity-time-tracker/). 13 | 14 | [Download the latest version for macOS, Linux, FreeBSD, NetBSD, OpenBSD & Plan9 15 | here](https://github.com/mrusme/zeit/releases/latest). 16 | 17 | 18 | ## Build 19 | 20 | ```sh 21 | make 22 | ``` 23 | 24 | **Info**: This will build using the version 0.0.0. You can prefix the `make` 25 | command with `VERSION=x.y.z` and set `x`, `y` and `z` accordingly if you want 26 | the version in `zeit --help` to be a different one. 27 | 28 | 29 | ## Usage 30 | 31 | ![zeit](documentation/header.jpg) 32 | 33 | Please make sure to `export ZEIT_DB=~/.config/zeit.db` (or whatever location 34 | you would like to have the zeit database at). 35 | 36 | *zeit*'s data structure contains of the following key entities: `project`, 37 | `task` and `entry`. An `entry` consists of a `project` and a `task`. These 38 | don't have to pre-exist and can be created on-the-fly inside a new `entry` using 39 | e.g. `zeit track --project "New Project" --task "New Task"`. In order to 40 | configure them, the `zeit project` and the `zeit task` commands can be utilised. 41 | 42 | 43 | ### Projects 44 | 45 | A project can be configured using `zeit project`: 46 | 47 | ```sh 48 | zeit project --help 49 | ``` 50 | 51 | #### Examples: 52 | 53 | Set the project color to a hex color code, allowing `zeit stats` to display 54 | information in that color (if your terminal supports colours): 55 | 56 | ```sh 57 | zeit project --color '#d3d3d3' "cool project" 58 | ``` 59 | 60 | 61 | ### Task 62 | 63 | A task can be configured using `zeit task`: 64 | 65 | ```sh 66 | zeit task --help 67 | ``` 68 | 69 | #### Examples: 70 | 71 | Setting up a Git repository to have commit messages automatically imported 72 | into the activity notes when an activity is finished: 73 | 74 | ```sh 75 | zeit task --git ~/my/git/repository "development" 76 | ``` 77 | 78 | **Info:** You will have to have the `git` binary available in your `PATH` for 79 | this to work. *zeit* automatically limits the commit log to the exact time of 80 | the activity's beginning- and finish-time. Commit messages before or after these 81 | times won't be imported. 82 | 83 | 84 | ### Track activity 85 | 86 | ```sh 87 | zeit track --help 88 | ``` 89 | 90 | #### Examples: 91 | 92 | Begin tracking a new activity and reset the start time to 15 minutes ago: 93 | 94 | ```sh 95 | zeit track --project project --task task --begin -0:15 96 | ``` 97 | 98 | 99 | ### Show current activity 100 | 101 | ```sh 102 | zeit tracking 103 | ``` 104 | 105 | 106 | ### Finish tracking activity 107 | 108 | ```sh 109 | zeit finish --help 110 | ``` 111 | 112 | #### Examples: 113 | 114 | Finish tracking the currently tracked activity without adding any further info: 115 | 116 | ```sh 117 | zeit finish 118 | ``` 119 | 120 | Finish tracking the currently tracked activity and change its task: 121 | 122 | ```sh 123 | zeit finish --task other-task 124 | ``` 125 | 126 | Finish tracking the currently tracked activity and adjust its start time to 127 | 4 PM: 128 | 129 | ```sh 130 | zeit finish --begin 16:00 131 | ``` 132 | 133 | 134 | ### List tracked activity 135 | 136 | ```sh 137 | zeit list --help 138 | ``` 139 | 140 | #### Examples: 141 | 142 | List all tracked activities: 143 | 144 | ```sh 145 | zeit list 146 | ``` 147 | 148 | List all tracked activities since a specific date/time: 149 | 150 | ```sh 151 | zeit list --since "2020-10-14T00:00:01+01:00" 152 | ``` 153 | 154 | List all tracked activities and add the total hours: 155 | 156 | ```sh 157 | zeit list --total 158 | ``` 159 | 160 | List only projects and tasks (relational): 161 | 162 | ```sh 163 | zeit list --only-projects-and-tasks 164 | ``` 165 | 166 | List only projects and tasks (relational) that were tracked since a specific 167 | date/time: 168 | 169 | ```sh 170 | zeit list --only-projects-and-tasks --since "2020-10-14T00:00:01+01:00" 171 | ``` 172 | 173 | 174 | ### Display/update activity 175 | 176 | ```sh 177 | zeit entry --help 178 | ``` 179 | 180 | #### Examples: 181 | 182 | Display a tracked activity: 183 | 184 | ```sh 185 | zeit entry 14037730-5c2d-44ff-b70e-81f1dcd4eb5f 186 | ``` 187 | 188 | Update a tracked activity: 189 | 190 | ```sh 191 | zeit entry --finish "2020-09-02T18:16:00+01:00" 14037730-5c2d-44ff-b70e-81f1dcd4eb5f 192 | ``` 193 | 194 | 195 | ### Erase tracked activity 196 | 197 | ```sh 198 | zeit erase --help 199 | ``` 200 | 201 | #### Examples: 202 | 203 | Erase a tracked activity by its internal ID: 204 | 205 | ```sh 206 | zeit erase 14037730-5c2d-44ff-b70e-81f1dcd4eb5f 207 | ``` 208 | 209 | 210 | ### Statistics 211 | 212 | ![zeit stats](documentation/zeit_stats.jpg) 213 | 214 | ```sh 215 | zeit stats 216 | ``` 217 | 218 | 219 | ### Import tracked activities 220 | 221 | ```sh 222 | zeit import --help 223 | ``` 224 | 225 | The following formats are supported as of right now: 226 | 227 | #### `tyme`: Tyme 3 JSON 228 | 229 | It is possible to import JSON exports from [Tyme 3](https://www.tyme-app.com). 230 | It is important that the JSON is exported with the following options set/unset: 231 | 232 | ![Tyme 3 JSON export](documentation/tyme3json.png) 233 | 234 | - `Start`/`End` can be set as required 235 | - `Format` has to be `JSON` 236 | - `Export only unbilled entries` can be set as required 237 | - `Mark exported entries as billed` can be set as required 238 | - `Include non-billable tasks` can be set as required 239 | - `Filter Projects & Tasks` can be set as required 240 | - `Combine times by day & task` **must** be unchecked 241 | 242 | During import, *zeit* will create SHA1 sums for every Tyme 3 entry, which 243 | allows it to identify every imported activity. This way *zeit* won't import the 244 | exact same entry twice. Keep this in mind if you change entries in Tyme and 245 | then import them again into *zeit*. 246 | 247 | #### Examples: 248 | 249 | Import a Tyme 3 JSON export: 250 | 251 | ```sh 252 | zeit import --format tyme ./tyme.export.json 253 | ``` 254 | 255 | 256 | ### Export tracked activities 257 | 258 | ```sh 259 | zeit export --help 260 | ``` 261 | 262 | The following formats are supported as of right now: 263 | 264 | #### `zeit`: *zeit* JSON 265 | 266 | The *zeit* internal JSON format. Basically a dump of the database including 267 | only tracked activities. 268 | 269 | #### `tyme`: Tyme 3 JSON 270 | 271 | It is possible to export JSON compatible to the Tyme 3 JSON format. Fields that 272 | are not available in *zeit* will be filled with dummy values, e.g. 273 | `Billing: "UNBILLED"`. 274 | 275 | #### Examples: 276 | 277 | Export a Tyme 3 JSON: 278 | 279 | ```sh 280 | zeit export --format tyme --project "my project" --since "2020-04-01T15:04:05+07:00" --until "2020-04-04T15:04:05+07:00" 281 | ``` 282 | 283 | ## Integrations 284 | 285 | Here are a few integrations and extensions built by myself as well as other 286 | people that make use of `zeit`: 287 | 288 | - [`zeit-waybar-bemenu.sh`](https://github.com/mrusme/zeit/blob/main/extras/zeit-waybar-bemenu.sh), 289 | a script for integrating `zeit` into 290 | [waybar](https://github.com/Alexays/Waybar), using 291 | [bemenu](https://github.com/Cloudef/bemenu) 292 | - [`zeit-waybar-wofi.sh`](https://github.com/mrusme/zeit/blob/main/extras/zeit-waybar-wofi.sh), 293 | a script for integrating `zeit` into 294 | [waybar](https://github.com/Alexays/Waybar), using 295 | [wofi](https://hg.sr.ht/~scoopta/wofi) 296 | - [`zeit.1m.sh`](https://github.com/mrusme/zeit/blob/main/extras/zeit.1m.sh), 297 | an [`xbar`](https://github.com/matryer/xbar) plugin for `zeit` 298 | - [`zeit-status.sh`](https://github.com/khughitt/dotfiles/blob/master/polybar/scripts/zeit-status.sh), 299 | a [Polybar](https://github.com/polybar/polybar) integration for `zeit` by 300 | [@khughitt](https://github.com/khughitt) 301 | (see [#1](https://github.com/mrusme/zeit/issues/1)) 302 | - your link here, feel free to PR! :-) 303 | -------------------------------------------------------------------------------- /_config.yml: -------------------------------------------------------------------------------- 1 | theme: jekyll-theme-minimal -------------------------------------------------------------------------------- /documentation/header.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mrusme/zeit/2bf1ab1181f8712708e7facaab79d7ee2899c8fb/documentation/header.jpg -------------------------------------------------------------------------------- /documentation/tyme3json.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mrusme/zeit/2bf1ab1181f8712708e7facaab79d7ee2899c8fb/documentation/tyme3json.png -------------------------------------------------------------------------------- /documentation/zeit.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mrusme/zeit/2bf1ab1181f8712708e7facaab79d7ee2899c8fb/documentation/zeit.png -------------------------------------------------------------------------------- /documentation/zeit_stats.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mrusme/zeit/2bf1ab1181f8712708e7facaab79d7ee2899c8fb/documentation/zeit_stats.jpg -------------------------------------------------------------------------------- /extras/test-parsing.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | ############################################################ 4 | # Help # 5 | ############################################################ 6 | Help() 7 | { 8 | echo "Run Parsing test suite for zeit" 9 | echo 10 | echo "Syntax: test-parsing.sh [-t ZEIT_DB_PATH] [-c CMD]" 11 | echo "options:" 12 | echo "h Print this Help." 13 | echo "t overwrite default ZEIT_DB Path for test (default: /tmp/zeit_test_parsing.db" 14 | echo "c define command to test (default: zeit from Path)" 15 | echo "v Verbose" 16 | echo 17 | } 18 | 19 | ############################################################ 20 | # Process the input options. Add options as needed. # 21 | ############################################################ 22 | # Get the options 23 | while getopts ":t:c:" option; do 24 | case $option in 25 | h) # display Help 26 | Help 27 | exit;; 28 | t) # Overwrite tmp path for test DB 29 | INPUT_PATH=$OPTARG;; 30 | c) # Set command to test 31 | CMD=$OPTARG;; 32 | \?) # Invalid option 33 | echo "Error: Invalid option" 34 | exit;; 35 | esac 36 | done 37 | 38 | 39 | if [[ -z $INPUT_PATH ]]; then 40 | DB_PATH=/tmp/zeit_test_parsing.db 41 | else 42 | if [[ -d $INPUT_PATH ]]; then 43 | DB_PATH="${INPUT_PATH}/zeit_test_parsing.db" 44 | else 45 | echo "ERROR: The Path entered for -t is either not existing or not a directory. Valid input is only an existing directory" 46 | exit 1 47 | fi 48 | fi 49 | 50 | if [[ -f $DB_PATH ]]; then 51 | rm $DB_PATH 52 | fi 53 | 54 | echo "PATH: $DB_PATH" 55 | 56 | if [[ -z $CMD ]]; then 57 | CMD=$(command -v -- zeit) 58 | else 59 | if [[ -z $CMD ]]; then 60 | echo "ERROR: No Executable found to test, zeit not in path and set with -c" 61 | exit 1 62 | fi 63 | fi 64 | 65 | 66 | echo "CMD: $CMD" 67 | 68 | declare -a tests 69 | tests+=('1;10:00;11:00') 70 | tests+=('2;01:00pm;02:00pm') 71 | tests+=('3;-04:00;-03:00') 72 | tests+=('4;-02:00;+01:00') 73 | tests+=('5;2023-09-11 10:00 +0300;2023-09-11 12:00 +0400') 74 | tests+=('6;2023-09-11 20:00;2023-09-11 21:00') 75 | tests+=('7;2023-09-11T20:00;2023-09-11T21:00') 76 | tests+=('8;2023-09-11T20:00:00;2023-09-11T21:00:00') 77 | tests+=('9;2023-09-11T20:00:00+03:00;2023-09-11T21:00:00+03:00') 78 | tests+=('10;01.04.2025 10:00;01.04.2025 12:00') 79 | tests+=('11;25.05. 10:00;25.05. 12:00') 80 | tests+=('12;04-01 10:00;04-01 12:00') 81 | tests+=('13;01.04. 10:00;01.04. 12:00') 82 | tests+=('14;01.04 10:00;01.04 12:00') # Will not work but parse to today without dot after month 83 | tests+=('15;1 hour ago;in 2 hours') 84 | 85 | for ((i = 0; i < ${#tests[@]}; i++)) 86 | do 87 | test_line=${tests[$i]} 88 | # echo "LINE: $test_line)" 89 | 90 | mapfile -td \; test < <(printf "%s\0" "$test_line") 91 | 92 | # echo ${test[1]} 93 | # echo ${test[2]} 94 | 95 | echo "$CMD track -p "TESTS" -t "Zeit-Test ${test[0]}" -b ${test[1]} -s ${test[2]}" 96 | $CMD track -p "TESTS" -t "Zeit-Test ${test[0]}" -b "${test[1]}" -s "${test[2]}" 97 | $CMD list | grep "Zeit-Test ${test[0]}" 98 | echo -e "\n" 99 | done 100 | -------------------------------------------------------------------------------- /extras/zeit-sketchybar.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | ## Skeytchybar configuration: 4 | # sketchybar --add item zeit e \ 5 | # --set zeit icon=󱏁 \ 6 | # script="$HOME/bin/zeit-sketchybar.sh" \ 7 | # update_freq=15 8 | 9 | 10 | ZEIT_BIN=$HOME/bin/zeit 11 | SKETCHY_BIN=/opt/homebrew/bin/sketchybar 12 | 13 | line_identifier='^ ▶ tracking' 14 | 15 | tracking=$($ZEIT_BIN tracking --no-colors | grep "$line_identifier" | sed -e "s/$line_identifier//") 16 | 17 | echo $tracking 18 | $SKETCHY_BIN --set zeit label="$tracking" 19 | -------------------------------------------------------------------------------- /extras/zeit-waybar-bemenu.sh: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | # 3 | # Example waybar configuration: 4 | # 5 | # "custom/zeit": { 6 | # "format": "{}", 7 | # "exec": "zeit-waybar-bemenu.sh", 8 | # "on-click": "zeit-waybar-bemenu.sh click", 9 | # "interval": 10 10 | # }, 11 | # 12 | 13 | ZEIT_BIN=zeit 14 | 15 | tracking=$($ZEIT_BIN tracking --no-colors) 16 | 17 | if [[ "$1" == "click" ]] 18 | then 19 | if echo "$tracking" | grep -q '^ ▶ tracking' 20 | then 21 | $ZEIT_BIN finish 22 | exit 0 23 | fi 24 | 25 | selection=$($ZEIT_BIN list \ 26 | --only-tasks \ 27 | --append-project-id-to-task \ 28 | | bemenu -p ' ' -P '▶' 29 | ) 30 | 31 | task=$(echo $selection | pcregrep -io1 '(.+) \[.+') 32 | project=$(echo $selection | pcregrep -io1 '.+\[(.+)\]') 33 | 34 | if [[ "$task" == "" ]] || [[ "$project" == "" ]] 35 | then 36 | exit 1 37 | fi 38 | 39 | $ZEIT_BIN track -p "$project" -t "$task" 40 | exit 0 41 | fi 42 | 43 | echo -n $tracking 44 | 45 | -------------------------------------------------------------------------------- /extras/zeit-waybar-wofi.sh: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | # 3 | # Example waybar configuration: 4 | # 5 | # "custom/zeit": { 6 | # "format": "{}", 7 | # "exec": "zeit-waybar-wofi.sh", 8 | # "on-click": "zeit-waybar-wofi.sh click", 9 | # "interval": 10 10 | # }, 11 | # 12 | 13 | ZEIT_BIN=zeit 14 | 15 | tracking=$($ZEIT_BIN tracking --no-colors) 16 | 17 | if [[ "$1" == "click" ]] 18 | then 19 | if echo "$tracking" | grep -q '^ ▶ tracking' 20 | then 21 | $ZEIT_BIN finish 22 | exit 0 23 | fi 24 | 25 | selection=$($ZEIT_BIN list \ 26 | --only-tasks \ 27 | --append-project-id-to-task \ 28 | | wofi \ 29 | --dmenu \ 30 | --sort-order default \ 31 | --cache-file /dev/null\ 32 | ) 33 | 34 | task=$(echo $selection | pcregrep -io1 '(.+) \[.+') 35 | project=$(echo $selection | pcregrep -io1 '.+\[(.+)\]') 36 | 37 | if [[ "$task" == "" ]] || [[ "$project" == "" ]] 38 | then 39 | exit 1 40 | fi 41 | 42 | $ZEIT_BIN track -p "$project" -t "$task" 43 | exit 0 44 | fi 45 | 46 | echo -n $tracking 47 | 48 | -------------------------------------------------------------------------------- /extras/zeit.1m.sh: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | 3 | # zeit 4 | # Marius 5 | # mrusme 6 | # Control `zeit` (https://github.com/mrusme/zeit) from the macOS menu bar. 7 | # https://github.com/mrusme/zeit/raw/main/documentation/zeit.png 8 | # https://マリウス.com/zeit-erfassen-a-cli-activity-time-tracker/ 9 | # 1.0 10 | # 11 | # string(ZEIT_BIN="/usr/local/bin/zeit"): Your zeit binary location 12 | # string(ZEIT_DB="$HOME/.zeit.db"): Your zeit database location 13 | # 14 | # Control `zeit` (https://github.com/mrusme/zeit) from the macOS menu bar. 15 | # 16 | # by Marius (marius@xn--gckvb8fzb.com) 17 | # 18 | 19 | PLACEHOLDER_NO_PROJECT='[no project]' 20 | PLACEHOLDER_NO_TASK='[no task]' 21 | 22 | if [ -z "$ZEIT_BIN" ] 23 | then 24 | ZEIT_BIN=$1 25 | fi 26 | 27 | if [ -z "$ZEIT_DB" ] 28 | then 29 | export ZEIT_DB=$2 30 | fi 31 | 32 | case $3 in 33 | "track") 34 | flag_p=$4 35 | flag_t=$5 36 | 37 | $ZEIT_BIN --no-colors finish 38 | 39 | if [ "$flag_p" = "$PLACEHOLDER_NO_PROJECT" ] 40 | then 41 | flag_p='' 42 | fi 43 | if [ "$flag_t" = "$PLACEHOLDER_NO_TASK" ] 44 | then 45 | flag_t='' 46 | fi 47 | 48 | $ZEIT_BIN --no-colors track -p "$flag_p" -t "$flag_t" 49 | # exit 0 50 | ;; 51 | "finish") 52 | $ZEIT_BIN --no-colors finish 53 | # exit 0 54 | ;; 55 | esac 56 | 57 | trackingProject='' 58 | trackingTask='' 59 | trackingDuration='' 60 | tracking=$($ZEIT_BIN --no-colors tracking) 61 | 62 | if echo "$tracking" | grep -q '^ ▶ tracking' 63 | then 64 | if echo "$tracking" | grep -q '^ ▶ tracking task for' 65 | then 66 | trackingProject=$PLACEHOLDER_NO_PROJECT 67 | trackingTask=$PLACEHOLDER_NO_TASK 68 | trackingDuration=$(echo "$tracking" | sed -E 's/.*tracking task for (.+)/\1/g') 69 | else 70 | trackingProject=$(echo "$tracking" | sed -E 's/.*tracking (.+) on (.+) for (.+)/\2/g') 71 | trackingTask=$(echo "$tracking" | sed -E 's/.*tracking (.+) on (.+) for (.+)/\1/g') 72 | trackingDuration=$(echo "$tracking" | sed -E 's/.*tracking (.+) on (.+) for (.+)/\3/g') 73 | fi 74 | tracking=$trackingDuration 75 | fi 76 | 77 | echo "$tracking" 78 | echo '---' 79 | echo 'Projects' 80 | 81 | project='' 82 | $ZEIT_BIN --no-colors list --only-projects-and-tasks | while read -r line 83 | do 84 | if echo "$line" | grep -q '^◆' 85 | then 86 | project=$(echo "$line" | sed 's/◆[[:space:]]\{0,3\}//g') 87 | if [ "$project" = "" ] 88 | then 89 | project=$PLACEHOLDER_NO_PROJECT 90 | fi 91 | 92 | if [ "$project" = "$trackingProject" ] 93 | then 94 | echo "-- ▶ $project" 95 | else 96 | echo "-- $project" 97 | fi 98 | elif echo "$line" | grep -q '^└──' 99 | then 100 | task=$(echo "$line" | sed 's/└──[[:space:]]\{0,3\}//g') 101 | 102 | if [ "$task" = "" ] 103 | then 104 | task=$PLACEHOLDER_NO_TASK 105 | fi 106 | 107 | if [ "$project" = "$trackingProject" ] && [ "$task" = "$trackingTask" ] 108 | then 109 | echo "---- ▶ $task | shell='$0' param1='$ZEIT_BIN' param2='$ZEIT_DB' param3=finish param4='$project' param5='$task' terminal=false refresh=true" 110 | else 111 | echo "---- $task | shell='$0' param1='$ZEIT_BIN' param2='$ZEIT_DB' param3=track param4='$project' param5='$task' terminal=false refresh=true" 112 | fi 113 | fi 114 | done 115 | exit 116 | -------------------------------------------------------------------------------- /go.mod: -------------------------------------------------------------------------------- 1 | module github.com/mrusme/zeit 2 | 3 | go 1.24.1 4 | 5 | toolchain go1.24.3 6 | 7 | require ( 8 | github.com/cnf/structhash v0.0.0-20250313080605-df4c6cc74a9a 9 | github.com/google/uuid v1.6.0 10 | github.com/gookit/color v1.5.4 11 | github.com/jinzhu/now v1.1.5 12 | github.com/markusmobius/go-dateparser v1.2.4 13 | github.com/shopspring/decimal v1.4.0 14 | github.com/spf13/cobra v1.9.1 15 | github.com/spf13/viper v1.20.1 16 | github.com/tidwall/buntdb v1.3.2 17 | ) 18 | 19 | require ( 20 | github.com/fsnotify/fsnotify v1.9.0 // indirect 21 | github.com/go-viper/mapstructure/v2 v2.2.1 // indirect 22 | github.com/hablullah/go-hijri v1.0.2 // indirect 23 | github.com/hablullah/go-juliandays v1.0.0 // indirect 24 | github.com/inconshreveable/mousetrap v1.1.0 // indirect 25 | github.com/jalaali/go-jalaali v0.0.0-20250521085720-bf793ab67800 // indirect 26 | github.com/pelletier/go-toml/v2 v2.2.4 // indirect 27 | github.com/sagikazarmark/locafero v0.9.0 // indirect 28 | github.com/sourcegraph/conc v0.3.0 // indirect 29 | github.com/spf13/afero v1.14.0 // indirect 30 | github.com/spf13/cast v1.8.0 // indirect 31 | github.com/spf13/pflag v1.0.6 // indirect 32 | github.com/subosito/gotenv v1.6.0 // indirect 33 | github.com/tetratelabs/wazero v1.9.0 // indirect 34 | github.com/tidwall/btree v1.7.0 // indirect 35 | github.com/tidwall/gjson v1.18.0 // indirect 36 | github.com/tidwall/grect v0.1.4 // indirect 37 | github.com/tidwall/match v1.1.1 // indirect 38 | github.com/tidwall/pretty v1.2.1 // indirect 39 | github.com/tidwall/rtred v0.1.2 // indirect 40 | github.com/tidwall/tinyqueue v0.1.1 // indirect 41 | github.com/wasilibs/go-re2 v1.10.0 // indirect 42 | github.com/wasilibs/wazero-helpers v0.0.0-20250123031827-cd30c44769bb // indirect 43 | github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e // indirect 44 | go.uber.org/multierr v1.11.0 // indirect 45 | golang.org/x/exp v0.0.0-20250408133849-7e4ce0ab07d0 // indirect 46 | golang.org/x/sys v0.33.0 // indirect 47 | golang.org/x/text v0.25.0 // indirect 48 | gopkg.in/yaml.v3 v3.0.1 // indirect 49 | ) 50 | -------------------------------------------------------------------------------- /go.sum: -------------------------------------------------------------------------------- 1 | github.com/cnf/structhash v0.0.0-20250313080605-df4c6cc74a9a h1:Ohw57yVY2dBTt+gsC6aZdteyxwlxfbtgkFEMTEkwgSw= 2 | github.com/cnf/structhash v0.0.0-20250313080605-df4c6cc74a9a/go.mod h1:pCxVEbcm3AMg7ejXyorUXi6HQCzOIBf7zEDVPtw0/U4= 3 | github.com/cpuguy83/go-md2man/v2 v2.0.6/go.mod h1:oOW0eioCTA6cOiMLiUPZOpcVxMig6NIQQ7OS05n1F4g= 4 | github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc h1:U9qPSI2PIWSS1VwoXQT9A3Wy9MM3WgvqSxFWenqJduM= 5 | github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= 6 | github.com/frankban/quicktest v1.14.6 h1:7Xjx+VpznH+oBnejlPUj8oUpdxnVs4f8XU8WnHkI4W8= 7 | github.com/frankban/quicktest v1.14.6/go.mod h1:4ptaffx2x8+WTWXmUCuVU6aPUX1/Mz7zb5vbUoiM6w0= 8 | github.com/fsnotify/fsnotify v1.9.0 h1:2Ml+OJNzbYCTzsxtv8vKSFD9PbJjmhYF14k/jKC7S9k= 9 | github.com/fsnotify/fsnotify v1.9.0/go.mod h1:8jBTzvmWwFyi3Pb8djgCCO5IBqzKJ/Jwo8TRcHyHii0= 10 | github.com/go-viper/mapstructure/v2 v2.2.1 h1:ZAaOCxANMuZx5RCeg0mBdEZk7DZasvvZIxtHqx8aGss= 11 | github.com/go-viper/mapstructure/v2 v2.2.1/go.mod h1:oJDH3BJKyqBA2TXFhDsKDGDTlndYOZ6rGS0BRZIxGhM= 12 | github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI= 13 | github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY= 14 | github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0= 15 | github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= 16 | github.com/gookit/color v1.5.4 h1:FZmqs7XOyGgCAxmWyPslpiok1k05wmY3SJTytgvYFs0= 17 | github.com/gookit/color v1.5.4/go.mod h1:pZJOeOS8DM43rXbp4AZo1n9zCU2qjpcRko0b6/QJi9w= 18 | github.com/hablullah/go-hijri v1.0.2 h1:drT/MZpSZJQXo7jftf5fthArShcaMtsal0Zf/dnmp6k= 19 | github.com/hablullah/go-hijri v1.0.2/go.mod h1:OS5qyYLDjORXzK4O1adFw9Q5WfhOcMdAKglDkcTxgWQ= 20 | github.com/hablullah/go-juliandays v1.0.0 h1:A8YM7wIj16SzlKT0SRJc9CD29iiaUzpBLzh5hr0/5p0= 21 | github.com/hablullah/go-juliandays v1.0.0/go.mod h1:0JOYq4oFOuDja+oospuc61YoX+uNEn7Z6uHYTbBzdGc= 22 | github.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8= 23 | github.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw= 24 | github.com/jalaali/go-jalaali v0.0.0-20250521085720-bf793ab67800 h1:lvIuaX7hO0eO3Rlev+cVnlsoExR3i/JXxu88zt4JHPg= 25 | github.com/jalaali/go-jalaali v0.0.0-20250521085720-bf793ab67800/go.mod h1:Wqfu7mjUHj9WDzSSPI5KfBclTTEnLveRUFr/ujWnTgE= 26 | github.com/jinzhu/now v1.1.5 h1:/o9tlHleP7gOFmsnYNz3RGnqzefHA47wQpKrrdTIwXQ= 27 | github.com/jinzhu/now v1.1.5/go.mod h1:d3SSVoowX0Lcu0IBviAWJpolVfI5UJVZZ7cO71lE/z8= 28 | github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE= 29 | github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk= 30 | github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= 31 | github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= 32 | github.com/markusmobius/go-dateparser v1.2.4 h1:2e8XJozaERVxGwsRg72coi51L2aiYqE2gukkdLc85ck= 33 | github.com/markusmobius/go-dateparser v1.2.4/go.mod h1:CBAUADJuMNhJpyM6IYaWAoFhtKaqnUcznY2cL7gNugY= 34 | github.com/pelletier/go-toml/v2 v2.2.4 h1:mye9XuhQ6gvn5h28+VilKrrPoQVanw5PMw/TB0t5Ec4= 35 | github.com/pelletier/go-toml/v2 v2.2.4/go.mod h1:2gIqNv+qfxSVS7cM2xJQKtLSTLUE9V8t9Stt+h56mCY= 36 | github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 h1:Jamvg5psRIccs7FGNTlIRMkT8wgtp5eCXdBlqhYGL6U= 37 | github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= 38 | github.com/rogpeppe/go-internal v1.9.0 h1:73kH8U+JUqXU8lRuOHeVHaa/SZPifC7BkcraZVejAe8= 39 | github.com/rogpeppe/go-internal v1.9.0/go.mod h1:WtVeX8xhTBvf0smdhujwtBcq4Qrzq/fJaraNFVN+nFs= 40 | github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM= 41 | github.com/sagikazarmark/locafero v0.9.0 h1:GbgQGNtTrEmddYDSAH9QLRyfAHY12md+8YFTqyMTC9k= 42 | github.com/sagikazarmark/locafero v0.9.0/go.mod h1:UBUyz37V+EdMS3hDF3QWIiVr/2dPrx49OMO0Bn0hJqk= 43 | github.com/shopspring/decimal v1.4.0 h1:bxl37RwXBklmTi0C79JfXCEBD1cqqHt0bbgBAGFp81k= 44 | github.com/shopspring/decimal v1.4.0/go.mod h1:gawqmDU56v4yIKSwfBSFip1HdCCXN8/+DMd9qYNcwME= 45 | github.com/sourcegraph/conc v0.3.0 h1:OQTbbt6P72L20UqAkXXuLOj79LfEanQ+YQFNpLA9ySo= 46 | github.com/sourcegraph/conc v0.3.0/go.mod h1:Sdozi7LEKbFPqYX2/J+iBAM6HpqSLTASQIKqDmF7Mt0= 47 | github.com/spf13/afero v1.14.0 h1:9tH6MapGnn/j0eb0yIXiLjERO8RB6xIVZRDCX7PtqWA= 48 | github.com/spf13/afero v1.14.0/go.mod h1:acJQ8t0ohCGuMN3O+Pv0V0hgMxNYDlvdk+VTfyZmbYo= 49 | github.com/spf13/cast v1.8.0 h1:gEN9K4b8Xws4EX0+a0reLmhq8moKn7ntRlQYgjPeCDk= 50 | github.com/spf13/cast v1.8.0/go.mod h1:ancEpBxwJDODSW/UG4rDrAqiKolqNNh2DX3mk86cAdo= 51 | github.com/spf13/cobra v1.9.1 h1:CXSaggrXdbHK9CF+8ywj8Amf7PBRmPCOJugH954Nnlo= 52 | github.com/spf13/cobra v1.9.1/go.mod h1:nDyEzZ8ogv936Cinf6g1RU9MRY64Ir93oCnqb9wxYW0= 53 | github.com/spf13/pflag v1.0.6 h1:jFzHGLGAlb3ruxLB8MhbI6A8+AQX/2eW4qeyNZXNp2o= 54 | github.com/spf13/pflag v1.0.6/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg= 55 | github.com/spf13/viper v1.20.1 h1:ZMi+z/lvLyPSCoNtFCpqjy0S4kPbirhpTMwl8BkW9X4= 56 | github.com/spf13/viper v1.20.1/go.mod h1:P9Mdzt1zoHIG8m2eZQinpiBjo6kCmZSKBClNNqjJvu4= 57 | github.com/stretchr/testify v1.10.0 h1:Xv5erBjTwe/5IxqUQTdXv5kgmIvbHo3QQyRwhJsOfJA= 58 | github.com/stretchr/testify v1.10.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY= 59 | github.com/subosito/gotenv v1.6.0 h1:9NlTDc1FTs4qu0DDq7AEtTPNw6SVm7uBMsUCUjABIf8= 60 | github.com/subosito/gotenv v1.6.0/go.mod h1:Dk4QP5c2W3ibzajGcXpNraDfq2IrhjMIvMSWPKKo0FU= 61 | github.com/tetratelabs/wazero v1.9.0 h1:IcZ56OuxrtaEz8UYNRHBrUa9bYeX9oVY93KspZZBf/I= 62 | github.com/tetratelabs/wazero v1.9.0/go.mod h1:TSbcXCfFP0L2FGkRPxHphadXPjo1T6W+CseNNY7EkjM= 63 | github.com/tidwall/assert v0.1.0 h1:aWcKyRBUAdLoVebxo95N7+YZVTFF/ASTr7BN4sLP6XI= 64 | github.com/tidwall/assert v0.1.0/go.mod h1:QLYtGyeqse53vuELQheYl9dngGCJQ+mTtlxcktb+Kj8= 65 | github.com/tidwall/btree v1.7.0 h1:L1fkJH/AuEh5zBnnBbmTwQ5Lt+bRJ5A8EWecslvo9iI= 66 | github.com/tidwall/btree v1.7.0/go.mod h1:twD9XRA5jj9VUQGELzDO4HPQTNJsoWWfYEL+EUQ2cKY= 67 | github.com/tidwall/buntdb v1.3.2 h1:qd+IpdEGs0pZci37G4jF51+fSKlkuUTMXuHhXL1AkKg= 68 | github.com/tidwall/buntdb v1.3.2/go.mod h1:lZZrZUWzlyDJKlLQ6DKAy53LnG7m5kHyrEHvvcDmBpU= 69 | github.com/tidwall/gjson v1.12.1/go.mod h1:/wbyibRr2FHMks5tjHJ5F8dMZh3AcwJEMf5vlfC0lxk= 70 | github.com/tidwall/gjson v1.18.0 h1:FIDeeyB800efLX89e5a8Y0BNH+LOngJyGrIWxG2FKQY= 71 | github.com/tidwall/gjson v1.18.0/go.mod h1:/wbyibRr2FHMks5tjHJ5F8dMZh3AcwJEMf5vlfC0lxk= 72 | github.com/tidwall/grect v0.1.4 h1:dA3oIgNgWdSspFzn1kS4S/RDpZFLrIxAZOdJKjYapOg= 73 | github.com/tidwall/grect v0.1.4/go.mod h1:9FBsaYRaR0Tcy4UwefBX/UDcDcDy9V5jUcxHzv2jd5Q= 74 | github.com/tidwall/lotsa v1.0.2 h1:dNVBH5MErdaQ/xd9s769R31/n2dXavsQ0Yf4TMEHHw8= 75 | github.com/tidwall/lotsa v1.0.2/go.mod h1:X6NiU+4yHA3fE3Puvpnn1XMDrFZrE9JO2/w+UMuqgR8= 76 | github.com/tidwall/match v1.1.1 h1:+Ho715JplO36QYgwN9PGYNhgZvoUSc9X2c80KVTi+GA= 77 | github.com/tidwall/match v1.1.1/go.mod h1:eRSPERbgtNPcGhD8UCthc6PmLEQXEWd3PRB5JTxsfmM= 78 | github.com/tidwall/pretty v1.2.0/go.mod h1:ITEVvHYasfjBbM0u2Pg8T2nJnzm8xPwvNhhsoaGGjNU= 79 | github.com/tidwall/pretty v1.2.1 h1:qjsOFOWWQl+N3RsoF5/ssm1pHmJJwhjlSbZ51I6wMl4= 80 | github.com/tidwall/pretty v1.2.1/go.mod h1:ITEVvHYasfjBbM0u2Pg8T2nJnzm8xPwvNhhsoaGGjNU= 81 | github.com/tidwall/rtred v0.1.2 h1:exmoQtOLvDoO8ud++6LwVsAMTu0KPzLTUrMln8u1yu8= 82 | github.com/tidwall/rtred v0.1.2/go.mod h1:hd69WNXQ5RP9vHd7dqekAz+RIdtfBogmglkZSRxCHFQ= 83 | github.com/tidwall/tinyqueue v0.1.1 h1:SpNEvEggbpyN5DIReaJ2/1ndroY8iyEGxPYxoSaymYE= 84 | github.com/tidwall/tinyqueue v0.1.1/go.mod h1:O/QNHwrnjqr6IHItYrzoHAKYhBkLI67Q096fQP5zMYw= 85 | github.com/wasilibs/go-re2 v1.10.0 h1:vQZEBYZOCA9jdBMmrO4+CvqyCj0x4OomXTJ4a5/urQ0= 86 | github.com/wasilibs/go-re2 v1.10.0/go.mod h1:k+5XqO2bCJS+QpGOnqugyfwC04nw0jaglmjrrkG8U6o= 87 | github.com/wasilibs/wazero-helpers v0.0.0-20250123031827-cd30c44769bb h1:gQ+ZV4wJke/EBKYciZ2MshEouEHFuinB85dY3f5s1q8= 88 | github.com/wasilibs/wazero-helpers v0.0.0-20250123031827-cd30c44769bb/go.mod h1:jMeV4Vpbi8osrE/pKUxRZkVaA0EX7NZN0A9/oRzgpgY= 89 | github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e h1:JVG44RsyaB9T2KIHavMF/ppJZNG9ZpyihvCd0w101no= 90 | github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e/go.mod h1:RbqR21r5mrJuqunuUZ/Dhy/avygyECGrLceyNeo4LiM= 91 | go.uber.org/multierr v1.11.0 h1:blXXJkSxSSfBVBlC76pxqeO+LN3aDfLQo+309xJstO0= 92 | go.uber.org/multierr v1.11.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y= 93 | golang.org/x/exp v0.0.0-20250408133849-7e4ce0ab07d0 h1:R84qjqJb5nVJMxqWYb3np9L5ZsaDtB+a39EqjV0JSUM= 94 | golang.org/x/exp v0.0.0-20250408133849-7e4ce0ab07d0/go.mod h1:S9Xr4PYopiDyqSyp5NjCrhFrqg6A5zA2E/iPHPhqnS8= 95 | golang.org/x/sys v0.33.0 h1:q3i8TbbEz+JRD9ywIRlyRAQbM0qF7hu24q3teo2hbuw= 96 | golang.org/x/sys v0.33.0/go.mod h1:BJP2sWEmIv4KK5OTEluFJCKSidICx8ciO85XgH3Ak8k= 97 | golang.org/x/text v0.25.0 h1:qVyWApTSYLk/drJRO5mDlNYskwQznZmkpV2c8q9zls4= 98 | golang.org/x/text v0.25.0/go.mod h1:WEdwpYrmk1qmdHvhkSTNPm3app7v4rsT8F2UD6+VHIA= 99 | gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= 100 | gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15 h1:YR8cESwS4TdDjEe65xsg0ogRM/Nc3DYOhEAlW+xobZo= 101 | gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= 102 | gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= 103 | gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= 104 | -------------------------------------------------------------------------------- /z/calendar.go: -------------------------------------------------------------------------------- 1 | package z 2 | 3 | import ( 4 | "fmt" 5 | "strings" 6 | "time" 7 | 8 | "github.com/jinzhu/now" 9 | "github.com/shopspring/decimal" 10 | // "github.com/gookit/color" 11 | ) 12 | 13 | type Statistic struct { 14 | Hours decimal.Decimal 15 | Project string 16 | Color (func(...interface{}) string) 17 | } 18 | 19 | type WeekStatistics map[string][]Statistic 20 | 21 | type Week struct { 22 | Statistics WeekStatistics 23 | } 24 | 25 | type Month struct { 26 | Name string 27 | Weeks [5]Week 28 | } 29 | 30 | type Calendar struct { 31 | Months [12]Month 32 | Distribution map[string]Statistic 33 | TotalHours decimal.Decimal 34 | } 35 | 36 | func NewCalendar(entries []Entry) (Calendar, error) { 37 | cal := Calendar{} 38 | 39 | cal.Distribution = make(map[string]Statistic) 40 | 41 | projects := make(map[string]Project) 42 | 43 | for _, entry := range entries { 44 | var entryFinish time.Time 45 | endOfBeginDay := now.With(entry.Begin).EndOfDay() 46 | sameDayHours := decimal.NewFromInt(0) 47 | nextDayHours := decimal.NewFromInt(0) 48 | 49 | projectId := GetIdFromName(entry.Project) 50 | 51 | if projects[projectId].Name == "" { 52 | project, err := database.GetProject(entry.User, entry.Project) 53 | if err != nil { 54 | return cal, err 55 | } 56 | 57 | projects[projectId] = project 58 | } 59 | 60 | if entry.Finish.IsZero() { 61 | entryFinish = time.Now() 62 | } else { 63 | entryFinish = entry.Finish 64 | } 65 | 66 | /* 67 | * Apparently the activity end is on a new day. 68 | * This means we have to split the activity across two days. 69 | */ 70 | if endOfBeginDay.Before(entryFinish) == true { 71 | startOfFinishDay := now.With(entryFinish).BeginningOfDay() 72 | 73 | sameDayDuration := endOfBeginDay.Sub(entry.Begin) 74 | sameDay := sameDayDuration.Hours() 75 | sameDayHours = decimal.NewFromFloat(sameDay) 76 | 77 | nextDayDuration := entryFinish.Sub(startOfFinishDay) 78 | nextDay := nextDayDuration.Hours() 79 | nextDayHours = decimal.NewFromFloat(nextDay) 80 | 81 | } else { 82 | sameDayDuration := entryFinish.Sub(entry.Begin) 83 | sameDay := sameDayDuration.Hours() 84 | sameDayHours = decimal.NewFromFloat(sameDay) 85 | } 86 | 87 | if sameDayHours.GreaterThan(decimal.NewFromInt(0)) { 88 | month, weeknumber := GetISOWeekInMonth(entry.Begin) 89 | month0 := month - 1 90 | weeknumber0 := weeknumber - 1 91 | weekday := entry.Begin.Weekday() 92 | weekdayName := weekday.String()[:2] 93 | 94 | stat := Statistic{ 95 | Hours: sameDayHours, 96 | Project: entry.Project, 97 | Color: GetColorFnFromHex(projects[projectId].Color), 98 | } 99 | 100 | if cal.Months[month0].Weeks[weeknumber0].Statistics == nil { 101 | cal.Months[month0].Weeks[weeknumber0].Statistics = make(WeekStatistics) 102 | } 103 | 104 | cal.Months[month0].Weeks[weeknumber0].Statistics[weekdayName] = append(cal.Months[month0].Weeks[weeknumber0].Statistics[weekdayName], stat) 105 | } 106 | 107 | if nextDayHours.GreaterThan(decimal.NewFromInt(0)) { 108 | month, weeknumber := GetISOWeekInMonth(entryFinish) 109 | month0 := month - 1 110 | weeknumber0 := weeknumber - 1 111 | weekday := entry.Begin.Weekday() 112 | weekdayName := weekday.String()[:2] 113 | 114 | stat := Statistic{ 115 | Hours: nextDayHours, 116 | Project: entry.Project, 117 | Color: GetColorFnFromHex(projects[projectId].Color), 118 | } 119 | 120 | if cal.Months[month0].Weeks[weeknumber0].Statistics == nil { 121 | cal.Months[month0].Weeks[weeknumber0].Statistics = make(WeekStatistics) 122 | } 123 | 124 | cal.Months[month0].Weeks[weeknumber0].Statistics[weekdayName] = append(cal.Months[month0].Weeks[weeknumber0].Statistics[weekdayName], stat) 125 | } 126 | 127 | dist := cal.Distribution[entry.Project] 128 | dist.Project = entry.Project 129 | dist.Hours = dist.Hours.Add(sameDayHours) 130 | dist.Hours = dist.Hours.Add(nextDayHours) 131 | dist.Color = GetColorFnFromHex(projects[projectId].Color) 132 | cal.Distribution[entry.Project] = dist 133 | 134 | // fmt.Printf("Same Day: %s \n Next Day: %s \n Project Hours: %s\n", sameDayHours.String(), nextDayHours.String(), dist.Hours.String()) 135 | cal.TotalHours = cal.TotalHours.Add(sameDayHours) 136 | cal.TotalHours = cal.TotalHours.Add(nextDayHours) 137 | } 138 | 139 | return cal, nil 140 | } 141 | 142 | func (calendar *Calendar) GetOutputForWeekCalendar(date time.Time, month int, week int) string { 143 | var output string = "" 144 | var bars [][]string 145 | totalHours := decimal.NewFromInt(0) 146 | 147 | days := []string{"Mo", "Tu", "We", "Th", "Fr", "Sa", "Su"} 148 | for _, day := range days { 149 | dayHours := decimal.NewFromInt(0) 150 | 151 | for _, stat := range calendar.Months[month].Weeks[week].Statistics[day] { 152 | dayHours = dayHours.Add(stat.Hours) 153 | totalHours = totalHours.Add(stat.Hours) 154 | } 155 | 156 | if dayHours.GreaterThan(decimal.NewFromInt(24)) { 157 | fmt.Printf("%s %s of week %d in month %d has more than 24h tracked; cutting at 24h now\n", CharError, day, (month + 1), (week + 1)) 158 | dayHours = decimal.NewFromInt(24) 159 | } 160 | 161 | bar := GetOutputBarForHours(dayHours, calendar.Months[month].Weeks[week].Statistics[day]) 162 | bars = append(bars, bar) 163 | } 164 | 165 | output = fmt.Sprintf("CW %02d %s H\n", GetISOCalendarWeek(date), fmtHours(totalHours)) 166 | for row := 0; row < len(bars[0]); row++ { 167 | output = fmt.Sprintf("%s%2d │", output, ((6 - row) * 4)) 168 | for col := 0; col < len(bars); col++ { 169 | output = fmt.Sprintf("%s%s", output, bars[col][row]) 170 | } 171 | output = fmt.Sprintf("%s\n", output) 172 | } 173 | output = fmt.Sprintf("%s └────────────────────────────\n %s %s %s %s %s %s %s\n", 174 | output, days[0], days[1], days[2], days[3], days[4], days[5], days[6]) 175 | 176 | return output 177 | } 178 | 179 | func (calendar *Calendar) GetOutputForDistribution() string { 180 | var output string = "" 181 | 182 | // fmt.Printf("%s\n", calendar.TotalHours.String()) 183 | 184 | var bar string = "" 185 | for _, stat := range calendar.Distribution { 186 | divided := stat.Hours.Div(calendar.TotalHours) 187 | percentage := divided.Mul(decimal.NewFromInt(100)) 188 | hoursStr := fmtHours(stat.Hours) 189 | percentageStr := percentage.StringFixed(2) 190 | 191 | dividedByBarLength := percentage.Div(decimal.NewFromInt(100)) 192 | percentageForBar := dividedByBarLength.Mul(decimal.NewFromInt(80)) 193 | percentageForBarInt := int(percentageForBar.Round(0).IntPart()) 194 | 195 | bar = fmt.Sprintf("%s%s", bar, stat.Color(strings.Repeat("█", percentageForBarInt))) 196 | 197 | output = fmt.Sprintf("%s%s%*s H / %*s %%\n", output, stat.Color(stat.Project), (68 - len(stat.Project)), hoursStr, 5, percentageStr) 198 | } 199 | 200 | output = fmt.Sprintf("DISTRIBUTION\n\n%s\n\n%s\n", bar, output) 201 | return output 202 | } 203 | -------------------------------------------------------------------------------- /z/constants.go: -------------------------------------------------------------------------------- 1 | package z 2 | 3 | const ( 4 | FlagNoColors string = "no-colors" 5 | FlagDebug string = "debug" 6 | ) 7 | 8 | const ( 9 | TFAbsTwelveHour int = 0 10 | TFAbsTwentyfourHour int = 1 11 | TFRelHourMinute int = 2 12 | TFRelHourFraction int = 3 13 | ) 14 | 15 | const ( 16 | FinishWithMetadata int = 0 17 | FinishOnlyTime int = 1 18 | ) 19 | 20 | const DateFormat string = "2006-01-02" 21 | -------------------------------------------------------------------------------- /z/database.go: -------------------------------------------------------------------------------- 1 | package z 2 | 3 | import ( 4 | "encoding/json" 5 | "errors" 6 | "log" 7 | "sort" 8 | "strings" 9 | 10 | "github.com/google/uuid" 11 | "github.com/spf13/viper" 12 | "github.com/tidwall/buntdb" 13 | ) 14 | 15 | type Database struct { 16 | DB *buntdb.DB 17 | } 18 | 19 | func InitDatabase() (*Database, error) { 20 | dbfile := viper.GetString("db") 21 | if dbfile == "" { 22 | return nil, errors.New("please `export ZEIT_DB` to the location the zeit database should be stored at") 23 | } 24 | 25 | db, err := buntdb.Open(dbfile) 26 | if err != nil { 27 | return nil, err 28 | } 29 | 30 | db.CreateIndex("task", "*", buntdb.IndexJSON("task")) 31 | db.CreateIndex("project", "*", buntdb.IndexJSON("project")) 32 | 33 | database := Database{db} 34 | return &database, nil 35 | } 36 | 37 | func (database *Database) NewID() string { 38 | id, err := uuid.NewRandom() 39 | if err != nil { 40 | log.Fatalln("could not generate UUID: %+v", err) 41 | } 42 | return id.String() 43 | } 44 | 45 | func (database *Database) AddEntry(user string, entry Entry, setRunning bool) (string, error) { 46 | id := database.NewID() 47 | 48 | entryJson, jsonerr := json.Marshal(entry) 49 | if jsonerr != nil { 50 | return id, jsonerr 51 | } 52 | 53 | dberr := database.DB.Update(func(tx *buntdb.Tx) error { 54 | if setRunning == true { 55 | _, _, seterr := tx.Set(user+":status:running", id, nil) 56 | if seterr != nil { 57 | return seterr 58 | } 59 | } 60 | _, _, seterr := tx.Set(user+":entry:"+id, string(entryJson), nil) 61 | if seterr != nil { 62 | return seterr 63 | } 64 | 65 | return nil 66 | }) 67 | 68 | return id, dberr 69 | } 70 | 71 | func (database *Database) GetEntry(user string, entryId string) (Entry, error) { 72 | var entry Entry 73 | 74 | dberr := database.DB.View(func(tx *buntdb.Tx) error { 75 | value, err := tx.Get(user + ":entry:" + entryId) 76 | if err != nil { 77 | return err 78 | } 79 | json.Unmarshal([]byte(value), &entry) 80 | 81 | entry.ID = entryId 82 | return nil 83 | }) 84 | 85 | return entry, dberr 86 | } 87 | 88 | func (database *Database) UpdateEntry(user string, entry Entry) (string, error) { 89 | entryJson, jsonerr := json.Marshal(entry) 90 | if jsonerr != nil { 91 | return entry.ID, jsonerr 92 | } 93 | 94 | dberr := database.DB.Update(func(tx *buntdb.Tx) error { 95 | _, _, seerr := tx.Set(user+":entry:"+entry.ID, string(entryJson), nil) 96 | if seerr != nil { 97 | return seerr 98 | } 99 | 100 | return nil 101 | }) 102 | 103 | return entry.ID, dberr 104 | } 105 | 106 | func (database *Database) FinishEntry(user string, entry Entry) (string, error) { 107 | entryJson, jsonerr := json.Marshal(entry) 108 | if jsonerr != nil { 109 | return entry.ID, jsonerr 110 | } 111 | 112 | dberr := database.DB.Update(func(tx *buntdb.Tx) error { 113 | runningEntryId, grerr := tx.Get(user + ":status:running") 114 | if grerr != nil { 115 | return errors.New("no currently running entry found!") 116 | } 117 | 118 | if runningEntryId != entry.ID { 119 | return errors.New("specified entry is not currently running!") 120 | } 121 | 122 | _, _, srerr := tx.Set(user+":status:running", "", nil) 123 | if srerr != nil { 124 | return srerr 125 | } 126 | 127 | _, _, seerr := tx.Set(user+":entry:"+entry.ID, string(entryJson), nil) 128 | if seerr != nil { 129 | return seerr 130 | } 131 | 132 | return nil 133 | }) 134 | 135 | return entry.ID, dberr 136 | } 137 | 138 | func (database *Database) EraseEntry(user string, id string) error { 139 | runningEntryId, err := database.GetRunningEntryId(user) 140 | if err != nil { 141 | return err 142 | } 143 | 144 | dberr := database.DB.Update(func(tx *buntdb.Tx) error { 145 | if runningEntryId == id { 146 | _, _, seterr := tx.Set(user+":status:running", "", nil) 147 | if seterr != nil { 148 | return seterr 149 | } 150 | } 151 | 152 | _, delerr := tx.Delete(user + ":entry:" + id) 153 | if delerr != nil { 154 | return delerr 155 | } 156 | 157 | return nil 158 | }) 159 | 160 | return dberr 161 | } 162 | 163 | func (database *Database) GetRunningEntryId(user string) (string, error) { 164 | var runningId string = "" 165 | 166 | dberr := database.DB.View(func(tx *buntdb.Tx) error { 167 | value, err := tx.Get(user + ":status:running") 168 | if errors.Is(err, buntdb.ErrNotFound) { 169 | return nil 170 | } 171 | if err != nil { 172 | return err 173 | } 174 | runningId = value 175 | return nil 176 | }) 177 | 178 | return runningId, dberr 179 | } 180 | 181 | func (database *Database) ListEntries(user string) ([]Entry, error) { 182 | var entries []Entry 183 | 184 | dberr := database.DB.View(func(tx *buntdb.Tx) error { 185 | tx.AscendKeys(user+":entry:*", func(key, value string) bool { 186 | var entry Entry 187 | json.Unmarshal([]byte(value), &entry) 188 | 189 | entry.SetIDFromDatabaseKey(key) 190 | 191 | entries = append(entries, entry) 192 | return true 193 | }) 194 | 195 | return nil 196 | }) 197 | 198 | sort.Slice(entries, func(i, j int) bool { return entries[i].Begin.Before(entries[j].Begin) }) 199 | return entries, dberr 200 | } 201 | 202 | func (database *Database) GetImportsSHA1List(user string) (map[string]string, error) { 203 | sha1List := make(map[string]string) 204 | 205 | dberr := database.DB.View(func(tx *buntdb.Tx) error { 206 | value, err := tx.Get(user+":imports:sha1", false) 207 | if err != nil { 208 | return nil 209 | } 210 | 211 | sha1Entries := strings.Split(value, ",") 212 | 213 | for _, sha1Entry := range sha1Entries { 214 | sha1EntrySplit := strings.Split(sha1Entry, ":") 215 | sha1 := sha1EntrySplit[0] 216 | id := sha1EntrySplit[1] 217 | sha1List[sha1] = id 218 | } 219 | 220 | return nil 221 | }) 222 | 223 | return sha1List, dberr 224 | } 225 | 226 | func (database *Database) UpdateImportsSHA1List(user string, sha1List map[string]string) error { 227 | var sha1Entries []string 228 | 229 | for sha1, id := range sha1List { 230 | sha1Entries = append(sha1Entries, sha1+":"+id) 231 | } 232 | 233 | value := strings.Join(sha1Entries, ",") 234 | 235 | dberr := database.DB.Update(func(tx *buntdb.Tx) error { 236 | _, _, seterr := tx.Set(user+":imports:sha1", value, nil) 237 | if seterr != nil { 238 | return seterr 239 | } 240 | 241 | return nil 242 | }) 243 | 244 | return dberr 245 | } 246 | 247 | func (database *Database) UpdateProject(user string, projectName string, project Project) error { 248 | projectJson, jsonerr := json.Marshal(project) 249 | if jsonerr != nil { 250 | return jsonerr 251 | } 252 | 253 | projectId := GetIdFromName(projectName) 254 | 255 | dberr := database.DB.Update(func(tx *buntdb.Tx) error { 256 | _, _, sperr := tx.Set(user+":project:"+projectId, string(projectJson), nil) 257 | if sperr != nil { 258 | return sperr 259 | } 260 | 261 | return nil 262 | }) 263 | 264 | return dberr 265 | } 266 | 267 | func (database *Database) GetProject(user string, projectName string) (Project, error) { 268 | var project Project 269 | projectId := GetIdFromName(projectName) 270 | 271 | dberr := database.DB.View(func(tx *buntdb.Tx) error { 272 | value, err := tx.Get(user+":project:"+projectId, false) 273 | if err != nil { 274 | return nil 275 | } 276 | 277 | json.Unmarshal([]byte(value), &project) 278 | 279 | return nil 280 | }) 281 | 282 | return project, dberr 283 | } 284 | 285 | func (database *Database) UpdateTask(user string, taskName string, task Task) error { 286 | taskJson, jsonerr := json.Marshal(task) 287 | if jsonerr != nil { 288 | return jsonerr 289 | } 290 | 291 | taskId := GetIdFromName(taskName) 292 | 293 | dberr := database.DB.Update(func(tx *buntdb.Tx) error { 294 | _, _, sperr := tx.Set(user+":task:"+taskId, string(taskJson), nil) 295 | if sperr != nil { 296 | return sperr 297 | } 298 | 299 | return nil 300 | }) 301 | 302 | return dberr 303 | } 304 | 305 | func (database *Database) GetTask(user string, taskName string) (Task, error) { 306 | var task Task 307 | taskId := GetIdFromName(taskName) 308 | 309 | dberr := database.DB.View(func(tx *buntdb.Tx) error { 310 | value, err := tx.Get(user+":task:"+taskId, false) 311 | if err != nil { 312 | return nil 313 | } 314 | 315 | json.Unmarshal([]byte(value), &task) 316 | 317 | return nil 318 | }) 319 | 320 | return task, dberr 321 | } 322 | -------------------------------------------------------------------------------- /z/entry.go: -------------------------------------------------------------------------------- 1 | package z 2 | 3 | import ( 4 | "errors" 5 | "fmt" 6 | "strings" 7 | "time" 8 | 9 | "github.com/gookit/color" 10 | "github.com/shopspring/decimal" 11 | "github.com/spf13/viper" 12 | ) 13 | 14 | type Entry struct { 15 | ID string `json:"-"` 16 | Begin time.Time `json:"begin,omitempty"` 17 | Finish time.Time `json:"finish,omitempty"` 18 | Project string `json:"project,omitempty"` 19 | Task string `json:"task,omitempty"` 20 | Notes string `json:"notes,omitempty"` 21 | User string `json:"user,omitempty"` 22 | 23 | SHA1 string `json:"-"` 24 | } 25 | 26 | func NewEntry( 27 | id string, 28 | begin string, 29 | finish string, 30 | project string, 31 | task string, 32 | user string, 33 | ) (Entry, error) { 34 | var err error 35 | 36 | newEntry := Entry{} 37 | 38 | newEntry.ID = id 39 | newEntry.Project = project 40 | newEntry.Task = task 41 | newEntry.User = user 42 | 43 | _, err = newEntry.SetBeginFromString(begin, time.Time{}) 44 | if err != nil { 45 | return Entry{}, err 46 | } 47 | 48 | _, err = newEntry.SetFinishFromString(finish, time.Time{}) 49 | if err != nil { 50 | return Entry{}, err 51 | } 52 | 53 | if id == "" && newEntry.IsFinishedAfterBegan() == false { 54 | return Entry{}, errors.New("beginning time of tracking cannot be after finish time") 55 | } 56 | 57 | return newEntry, nil 58 | } 59 | 60 | func (entry *Entry) SetIDFromDatabaseKey(key string) error { 61 | splitKey := strings.Split(key, ":") 62 | 63 | if len(splitKey) < 3 || len(splitKey) > 3 { 64 | return errors.New("not a valid database key") 65 | } 66 | 67 | entry.ID = splitKey[2] 68 | return nil 69 | } 70 | 71 | func (entry *Entry) SetBeginFromString(begin string, contextTime time.Time) (time.Time, error) { 72 | var beginTime time.Time 73 | var err error 74 | 75 | if begin == "" { 76 | beginTime = time.Now() 77 | } else { 78 | beginTime, err = ParseTime(begin, contextTime) 79 | if err != nil { 80 | return beginTime, err 81 | } 82 | } 83 | 84 | entry.Begin = beginTime 85 | entry.secondsBegin() 86 | return entry.Begin, nil 87 | } 88 | 89 | func (entry *Entry) SetFinishFromString(finish string, contextTime time.Time) (time.Time, error) { 90 | var finishTime time.Time 91 | var err error 92 | 93 | if finish != "" { 94 | finishTime, err = ParseTime(finish, contextTime) 95 | if err != nil { 96 | return finishTime, err 97 | } 98 | } 99 | 100 | entry.Finish = finishTime 101 | entry.secondsFinish() 102 | return entry.Finish, nil 103 | } 104 | 105 | func (entry *Entry) IsFinishedAfterBegan() bool { 106 | return (entry.Finish.IsZero() || entry.Begin.Before(entry.Finish) || entry.Begin.Equal(entry.Finish)) 107 | } 108 | 109 | func (entry *Entry) GetOutputForTrack(isRunning bool, wasRunning bool) string { 110 | var outputPrefix string = "" 111 | var outputSuffix string = "" 112 | 113 | now := time.Now() 114 | trackDiffNow := now.Sub(entry.Begin) 115 | durationString := fmtDuration(trackDiffNow) 116 | 117 | if isRunning == true && wasRunning == false { 118 | outputPrefix = "began tracking" 119 | } else if isRunning == true && wasRunning == true { 120 | outputPrefix = "tracking" 121 | outputSuffix = fmt.Sprintf(" for %sh", color.FgLightWhite.Render(durationString)) 122 | } else if isRunning == false && wasRunning == false { 123 | outputPrefix = "tracked" 124 | } 125 | 126 | if entry.Task != "" && entry.Project != "" { 127 | return fmt.Sprintf("%s %s %s on %s%s\n", CharTrack, outputPrefix, color.FgLightWhite.Render(entry.Task), color.FgLightWhite.Render(entry.Project), outputSuffix) 128 | } else if entry.Task != "" && entry.Project == "" { 129 | return fmt.Sprintf("%s %s %s%s\n", CharTrack, outputPrefix, color.FgLightWhite.Render(entry.Task), outputSuffix) 130 | } else if entry.Task == "" && entry.Project != "" { 131 | return fmt.Sprintf("%s %s task on %s%s\n", CharTrack, outputPrefix, color.FgLightWhite.Render(entry.Project), outputSuffix) 132 | } 133 | 134 | return fmt.Sprintf("%s %s task%s\n", CharTrack, outputPrefix, outputSuffix) 135 | } 136 | 137 | func (entry *Entry) GetDuration() decimal.Decimal { 138 | duration := entry.Finish.Sub(entry.Begin) 139 | if duration < 0 { 140 | duration = time.Now().Sub(entry.Begin) 141 | } 142 | return decimal.NewFromFloat(duration.Hours()) 143 | } 144 | 145 | func (entry *Entry) GetOutputForFinish() string { 146 | var outputSuffix string = "" 147 | 148 | trackDiff := entry.Finish.Sub(entry.Begin) 149 | taskDuration := fmtDuration(trackDiff) 150 | 151 | outputSuffix = fmt.Sprintf(" for %sh", color.FgLightWhite.Render(taskDuration)) 152 | 153 | if entry.Task != "" && entry.Project != "" { 154 | return fmt.Sprintf("%s finished tracking %s on %s%s\n", CharFinish, color.FgLightWhite.Render(entry.Task), color.FgLightWhite.Render(entry.Project), outputSuffix) 155 | } else if entry.Task != "" && entry.Project == "" { 156 | return fmt.Sprintf("%s finished tracking %s%s\n", CharFinish, color.FgLightWhite.Render(entry.Task), outputSuffix) 157 | } else if entry.Task == "" && entry.Project != "" { 158 | return fmt.Sprintf("%s finished tracking task on %s%s\n", CharFinish, color.FgLightWhite.Render(entry.Project), outputSuffix) 159 | } 160 | 161 | return fmt.Sprintf("%s finished tracking task%s\n", CharFinish, outputSuffix) 162 | } 163 | 164 | func (entry *Entry) GetOutput(full bool) string { 165 | var output string = "" 166 | var entryFinish time.Time 167 | var isRunning string = "" 168 | 169 | if entry.Finish.IsZero() { 170 | entryFinish = time.Now() 171 | isRunning = "[running]" 172 | } else { 173 | entryFinish = entry.Finish 174 | } 175 | 176 | trackDiff := entryFinish.Sub(entry.Begin) 177 | taskDuration := fmtDuration(trackDiff) 178 | if full == false { 179 | output = fmt.Sprintf("%s %s on %s from %s to %s (%sh) %s", 180 | color.FgGray.Render(entry.ID), 181 | color.FgLightWhite.Render(entry.Task), 182 | color.FgLightWhite.Render(entry.Project), 183 | color.FgLightWhite.Render(entry.Begin.Format("2006-01-02 15:04 -0700")), 184 | color.FgLightWhite.Render(entryFinish.Format("2006-01-02 15:04 -0700")), 185 | color.FgLightWhite.Render(taskDuration), 186 | color.FgLightYellow.Render(isRunning), 187 | ) 188 | } else { 189 | output = fmt.Sprintf("%s\n %s on %s\n %sh from %s to %s %s\n\n Notes:\n %s\n", 190 | color.FgGray.Render(entry.ID), 191 | color.FgLightWhite.Render(entry.Task), 192 | color.FgLightWhite.Render(entry.Project), 193 | color.FgLightWhite.Render(taskDuration), 194 | color.FgLightWhite.Render(entry.Begin.Format("2006-01-02 15:04 -0700")), 195 | color.FgLightWhite.Render(entryFinish.Format("2006-01-02 15:04 -0700")), 196 | color.FgLightYellow.Render(isRunning), 197 | color.FgLightWhite.Render(strings.Replace(entry.Notes, "\n", "\n ", -1)), 198 | ) 199 | } 200 | 201 | return output 202 | } 203 | 204 | func GetFilteredEntries(entries []Entry, project string, task string, since time.Time, until time.Time) ([]Entry, error) { 205 | var filteredEntries []Entry 206 | 207 | for _, entry := range entries { 208 | if project != "" && GetIdFromName(entry.Project) != GetIdFromName(project) { 209 | continue 210 | } 211 | 212 | if task != "" && GetIdFromName(entry.Task) != GetIdFromName(task) { 213 | continue 214 | } 215 | 216 | if since.IsZero() == false && since.Before(entry.Begin) == false && since.Equal(entry.Begin) == false { 217 | continue 218 | } 219 | 220 | if until.IsZero() == false && until.After(entry.Finish) == false && until.Equal(entry.Finish) == false { 221 | continue 222 | } 223 | 224 | if until.IsZero() == false && entry.Finish.IsZero() && !entry.Begin.Before(until) { 225 | continue 226 | } 227 | 228 | filteredEntries = append(filteredEntries, entry) 229 | } 230 | 231 | return filteredEntries, nil 232 | } 233 | 234 | func (entry *Entry) secondsBegin() { 235 | if viper.GetBool("time.no-seconds") { 236 | entry.Begin = entry.Begin.Truncate(time.Duration(time.Minute)) 237 | } 238 | } 239 | 240 | func (entry *Entry) secondsFinish() { 241 | if viper.GetBool("time.no-seconds") { 242 | entry.Finish = entry.Finish.Truncate(time.Duration(time.Minute)) 243 | } 244 | } 245 | -------------------------------------------------------------------------------- /z/entryCmd.go: -------------------------------------------------------------------------------- 1 | package z 2 | 3 | import ( 4 | "fmt" 5 | "os" 6 | "strings" 7 | 8 | "github.com/spf13/cobra" 9 | ) 10 | 11 | var entryCmd = &cobra.Command{ 12 | Use: "entry ([flags]) [id]", 13 | Short: "Display or update activity", 14 | Long: "Display or update tracked activity.", 15 | Args: cobra.ExactArgs(1), 16 | Run: func(cmd *cobra.Command, args []string) { 17 | user := GetCurrentUser() 18 | id := args[0] 19 | 20 | entry, err := database.GetEntry(user, id) 21 | if err != nil { 22 | fmt.Printf("%s %+v\n", CharError, err) 23 | os.Exit(1) 24 | } 25 | 26 | if begin != "" || finish != "" || project != "" || notes != "" || task != "" { 27 | if begin != "" { 28 | entry.Begin, err = entry.SetBeginFromString(begin, entry.Begin) 29 | if err != nil { 30 | fmt.Printf("%s %+v\n", CharError, err) 31 | os.Exit(1) 32 | } 33 | } 34 | 35 | if finish != "" { 36 | entry.Finish, err = entry.SetFinishFromString(finish, entry.Finish) 37 | if err != nil { 38 | fmt.Printf("%s %+v\n", CharError, err) 39 | os.Exit(1) 40 | } 41 | } 42 | 43 | if project != "" { 44 | entry.Project = project 45 | } 46 | 47 | if task != "" { 48 | entry.Task = task 49 | } 50 | 51 | if notes != "" { 52 | entry.Notes = strings.Replace(notes, "\\n", "\n", -1) 53 | } 54 | 55 | _, err = database.UpdateEntry(user, entry) 56 | if err != nil { 57 | fmt.Printf("%s %+v\n", CharError, err) 58 | os.Exit(1) 59 | } 60 | } 61 | 62 | fmt.Printf("%s %s\n", CharInfo, entry.GetOutput(true)) 63 | return 64 | }, 65 | } 66 | 67 | func init() { 68 | rootCmd.AddCommand(entryCmd) 69 | entryCmd.Flags().StringVarP(&begin, "begin", "b", "", "Update date/time the activity began at") 70 | entryCmd.Flags().StringVarP(&finish, "finish", "s", "", "Update date/time the activity finished at") 71 | entryCmd.Flags().StringVarP(&project, "project", "p", "", "Update activity project") 72 | entryCmd.Flags().StringVarP(¬es, "notes", "n", "", "Update activity notes") 73 | entryCmd.Flags().StringVarP(&task, "task", "t", "", "Update activity task") 74 | entryCmd.Flags().BoolVar(&fractional, "decimal", false, "Show fractional hours in decimal format instead of minutes") 75 | 76 | flagName := "task" 77 | entryCmd.RegisterFlagCompletionFunc(flagName, func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) { 78 | user := GetCurrentUser() 79 | entries, _ := database.ListEntries(user) 80 | _, tasks := listProjectsAndTasks(entries) 81 | return tasks, cobra.ShellCompDirectiveDefault 82 | }) 83 | } 84 | -------------------------------------------------------------------------------- /z/eraseCmd.go: -------------------------------------------------------------------------------- 1 | package z 2 | 3 | import ( 4 | "fmt" 5 | "os" 6 | 7 | "github.com/gookit/color" 8 | "github.com/spf13/cobra" 9 | ) 10 | 11 | var eraseCmd = &cobra.Command{ 12 | Use: "erase ([flags]) [id]", 13 | Short: "Erase activity", 14 | Long: "Erase tracked activity.", 15 | Args: cobra.ExactArgs(1), 16 | Run: func(cmd *cobra.Command, args []string) { 17 | user := GetCurrentUser() 18 | id := args[0] 19 | 20 | err := database.EraseEntry(user, id) 21 | if err != nil { 22 | fmt.Printf("%s %+v\n", CharError, err) 23 | os.Exit(1) 24 | } 25 | 26 | fmt.Printf("%s erased %s\n", CharInfo, color.FgLightWhite.Render(id)) 27 | return 28 | }, 29 | } 30 | 31 | func init() { 32 | rootCmd.AddCommand(eraseCmd) 33 | } 34 | -------------------------------------------------------------------------------- /z/exportCmd.go: -------------------------------------------------------------------------------- 1 | package z 2 | 3 | import ( 4 | "encoding/json" 5 | "fmt" 6 | "os" 7 | "strings" 8 | 9 | "github.com/spf13/cobra" 10 | ) 11 | 12 | func exportZeitJson(user string, entries []Entry) (string, error) { 13 | stringified, err := json.Marshal(entries) 14 | if err != nil { 15 | return "", err 16 | } 17 | 18 | return string(stringified), nil 19 | } 20 | 21 | func exportTymeJson(user string, entries []Entry) (string, error) { 22 | tyme := Tyme{} 23 | err := tyme.FromEntries(entries) 24 | if err != nil { 25 | return "", err 26 | } 27 | 28 | return tyme.Stringify(), nil 29 | } 30 | 31 | var exportCmd = &cobra.Command{ 32 | Use: "export ([flags])", 33 | Short: "Export tracked activities", 34 | Long: "Export tracked activities to various formats.", 35 | // Args: cobra.ExactArgs(1), 36 | Run: func(cmd *cobra.Command, args []string) { 37 | var entries []Entry 38 | var err error 39 | 40 | user := GetCurrentUser() 41 | 42 | entries, err = database.ListEntries(user) 43 | if err != nil { 44 | fmt.Printf("%s %+v\n", CharError, err) 45 | os.Exit(1) 46 | } 47 | sinceTime, untilTime := ParseSinceUntil(since, until, listRange) 48 | 49 | var filteredEntries []Entry 50 | filteredEntries, err = GetFilteredEntries(entries, project, task, sinceTime, untilTime) 51 | if err != nil { 52 | fmt.Printf("%s %+v\n", CharError, err) 53 | os.Exit(1) 54 | } 55 | 56 | var output string = "" 57 | switch format { 58 | case "zeit": 59 | output, err = exportZeitJson(user, filteredEntries) 60 | if err != nil { 61 | fmt.Printf("%s %+v\n", CharError, err) 62 | os.Exit(1) 63 | } 64 | case "tyme": 65 | output, err = exportTymeJson(user, filteredEntries) 66 | if err != nil { 67 | fmt.Printf("%s %+v\n", CharError, err) 68 | os.Exit(1) 69 | } 70 | default: 71 | fmt.Printf("%s specify an export format; see `zeit export --help` for more info\n", CharError) 72 | os.Exit(1) 73 | } 74 | 75 | fmt.Printf("%s\n", output) 76 | return 77 | }, 78 | } 79 | 80 | func init() { 81 | rootCmd.AddCommand(exportCmd) 82 | exportCmd.Flags().StringVar(&format, "format", "zeit", "Format to export, possible values: zeit, tyme") 83 | exportCmd.Flags().StringVar(&since, "since", "", "Date/time to start the export from") 84 | exportCmd.Flags().StringVar(&until, "until", "", "Date/time to export until") 85 | exportCmd.Flags().StringVar(&listRange, "range", "", "Shortcut for --since and --until that accepts: "+strings.Join(Ranges(), ", ")) 86 | exportCmd.Flags().StringVarP(&project, "project", "p", "", "Project to be exported") 87 | exportCmd.Flags().StringVarP(&task, "task", "t", "", "Task to be exported") 88 | 89 | flagName := "task" 90 | exportCmd.RegisterFlagCompletionFunc(flagName, func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) { 91 | user := GetCurrentUser() 92 | entries, _ := database.ListEntries(user) 93 | _, tasks := listProjectsAndTasks(entries) 94 | return tasks, cobra.ShellCompDirectiveDefault 95 | }) 96 | } 97 | -------------------------------------------------------------------------------- /z/finishCmd.go: -------------------------------------------------------------------------------- 1 | package z 2 | 3 | import ( 4 | "github.com/spf13/cobra" 5 | ) 6 | 7 | var finishCmd = &cobra.Command{ 8 | Use: "finish", 9 | Short: "Finish currently running activity", 10 | Long: "Finishing tracking of currently running activity.", 11 | Run: func(cmd *cobra.Command, args []string) { 12 | finishTask(FinishWithMetadata) 13 | }, 14 | } 15 | 16 | func init() { 17 | rootCmd.AddCommand(finishCmd) 18 | finishCmd.Flags().StringVarP(&begin, "begin", "b", "", "Time the activity should begin at\n\nEither in the formats 16:00 / 4:00PM \nor relative to the current time, \ne.g. -0:15 (now minus 15 minutes), +1.50 (now plus 1:30h).") 19 | finishCmd.Flags().StringVarP(&finish, "finish", "s", "", "Time the activity should finish at\n\nEither in the formats 16:00 / 4:00PM \nor relative to the current time, \ne.g. -0:15 (now minus 15 minutes), +1.50 (now plus 1:30h).\nMust be after --begin time.") 20 | finishCmd.Flags().StringVarP(&project, "project", "p", "", "Project to be assigned") 21 | finishCmd.Flags().StringVarP(¬es, "notes", "n", "", "Activity notes") 22 | finishCmd.Flags().StringVarP(&task, "task", "t", "", "Task to be assigned") 23 | 24 | flagName := "task" 25 | finishCmd.RegisterFlagCompletionFunc(flagName, func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) { 26 | user := GetCurrentUser() 27 | entries, _ := database.ListEntries(user) 28 | _, tasks := listProjectsAndTasks(entries) 29 | return tasks, cobra.ShellCompDirectiveDefault 30 | }) 31 | } 32 | -------------------------------------------------------------------------------- /z/helpers.go: -------------------------------------------------------------------------------- 1 | package z 2 | 3 | import ( 4 | "bytes" 5 | "errors" 6 | "fmt" 7 | "math" 8 | "os" 9 | "os/exec" 10 | "os/user" 11 | "regexp" 12 | "strconv" 13 | "strings" 14 | "time" 15 | 16 | "github.com/jinzhu/now" 17 | "github.com/markusmobius/go-dateparser" 18 | "github.com/spf13/viper" 19 | ) 20 | 21 | func TimeFormats() []string { 22 | return []string{ 23 | `^\d{1,2}:\d{1,2}(am|pm)$`, // Absolute twelve hour format 24 | `^\d{1,2}:\d{1,2}$`, // Absolute twenty four hour format 25 | `^([+-])(\d{1,2}):(\d{1,2})$`, // Relative hour:minute format 26 | `^([+-])(\d{1,2})\.(\d{1,2})$`, // Relative hour.fraction format 27 | } 28 | } 29 | 30 | func GetCurrentUser() string { 31 | user, err := user.Current() 32 | if err != nil { 33 | return "unknown" 34 | } 35 | 36 | return user.Username 37 | } 38 | 39 | func GetTimeFormat(timeStr string) int { 40 | var matched bool 41 | var regerr error 42 | 43 | for timeFormatId, timeFormat := range TimeFormats() { 44 | matched, regerr = regexp.MatchString(timeFormat, timeStr) 45 | if regerr != nil { 46 | return -1 47 | } 48 | 49 | if matched == true { 50 | return timeFormatId 51 | } 52 | } 53 | 54 | return -1 55 | } 56 | 57 | // TODO: Use https://golang.org/pkg/time/#ParseDuration 58 | func RelToTime(timeStr string, ftId int, contextTime time.Time) (time.Time, error) { 59 | re := regexp.MustCompile(TimeFormats()[ftId]) 60 | gm := re.FindStringSubmatch(timeStr) 61 | 62 | if len(gm) < 4 { 63 | return time.Now(), errors.New("No match") 64 | } 65 | 66 | var hours int = 0 67 | var minutes int = 0 68 | 69 | if ftId == TFRelHourFraction { 70 | f, _ := strconv.ParseFloat(gm[2]+"."+gm[3], 32) 71 | minutes = int(f * 60.0) 72 | } else { 73 | hours, _ = strconv.Atoi(gm[2]) 74 | minutes, _ = strconv.Atoi(gm[3]) 75 | } 76 | 77 | var t time.Time 78 | 79 | if viper.IsSet("time.relative") && viper.GetString("time.relative") == "context" && !contextTime.IsZero() { 80 | switch gm[1] { 81 | case "+": 82 | t = contextTime.Add(time.Hour*time.Duration(hours) + time.Minute*time.Duration(minutes)) 83 | case "-": 84 | t = contextTime.Add((time.Hour*time.Duration(hours) + time.Minute*time.Duration(minutes)) * -1) 85 | } 86 | 87 | return t, nil 88 | } 89 | 90 | switch gm[1] { 91 | case "+": 92 | t = time.Now().Local().Add(time.Hour*time.Duration(hours) + time.Minute*time.Duration(minutes)) 93 | case "-": 94 | t = time.Now().Local().Add((time.Hour*time.Duration(hours) + time.Minute*time.Duration(minutes)) * -1) 95 | } 96 | 97 | return t, nil 98 | } 99 | 100 | func ParseTime(timeStr string, contextTime time.Time) (time.Time, error) { 101 | loc, err := time.LoadLocation("Local") 102 | if err != nil { 103 | return time.Now(), errors.New("could not load location") 104 | } 105 | 106 | cfg := dateparser.Configuration{ 107 | DefaultTimezone: loc, 108 | } 109 | 110 | tfId := GetTimeFormat(timeStr) 111 | 112 | switch tfId { 113 | case TFRelHourMinute, TFRelHourFraction: 114 | return RelToTime(timeStr, tfId, contextTime) 115 | default: 116 | tnew, err := dateparser.Parse(&cfg, timeStr) 117 | if err != nil { 118 | return time.Now(), errors.New("could not match passed time") 119 | } 120 | 121 | return tnew.Time, err 122 | } 123 | } 124 | 125 | func GetIdFromName(name string) string { 126 | reg, regerr := regexp.Compile("[^a-zA-Z0-9]+") 127 | if regerr != nil { 128 | return "" 129 | } 130 | 131 | id := strings.ToLower(reg.ReplaceAllString(name, "")) 132 | 133 | return id 134 | } 135 | 136 | func GetISOCalendarWeek(date time.Time) int { 137 | _, cw := date.ISOWeek() 138 | return cw 139 | } 140 | 141 | func GetISOWeekInMonth(date time.Time) (month int, weeknumber int) { 142 | if date.IsZero() { 143 | return -1, -1 144 | } 145 | 146 | newDay := (date.Day() - int(date.Weekday()) + 1) 147 | addDay := (date.Day() - newDay) * -1 148 | changedDate := date.AddDate(0, 0, addDay) 149 | 150 | return int(changedDate.Month()), int(math.Ceil(float64(changedDate.Day()) / 7.0)) 151 | } 152 | 153 | func GetGitLog(repo string, since time.Time, until time.Time) (string, string, error) { 154 | var stdout, stderr bytes.Buffer 155 | cmd := exec.Command("git", "-C", repo, "config", "user.name") 156 | cmd.Stdout = &stdout 157 | cmd.Stderr = &stderr 158 | err := cmd.Run() 159 | if err != nil { 160 | return "", "", err 161 | } 162 | gitUserStr, gitUserErrStr := string(stdout.Bytes()), string(stderr.Bytes()) 163 | if gitUserStr == "" && gitUserErrStr != "" { 164 | return gitUserStr, gitUserErrStr, errors.New(gitUserErrStr) 165 | } 166 | 167 | stdout.Reset() 168 | stderr.Reset() 169 | 170 | cmd = exec.Command("git", "-C", repo, "log", "--author", gitUserStr, "--since", since.Format("2006-01-02T15:04:05-0700"), "--until", until.Format("2006-01-02T15:04:05-0700"), "--pretty=oneline") 171 | cmd.Stdout = &stdout 172 | cmd.Stderr = &stderr 173 | err = cmd.Run() 174 | if err != nil { 175 | return "", "", err 176 | } 177 | 178 | stdoutStr, stderrStr := string(stdout.Bytes()), string(stderr.Bytes()) 179 | return stdoutStr, stderrStr, nil 180 | } 181 | 182 | func Ranges() []string { 183 | return []string{ 184 | "today", 185 | "yesterday", 186 | "thisWeek", 187 | "lastWeek", 188 | "thisMonth", 189 | "lastMonth", 190 | } 191 | } 192 | 193 | func ParseSinceUntil(since string, until string, listRange string) (time.Time, time.Time) { 194 | var sinceTime time.Time 195 | var untilTime time.Time 196 | var err error 197 | 198 | if since != "" { 199 | sinceTime, err = now.Parse(since) 200 | if err != nil { 201 | fmt.Printf("%s %+v\n", CharError, err) 202 | os.Exit(1) 203 | } 204 | } 205 | 206 | if until != "" { 207 | untilTime, err = now.Parse(until) 208 | if err != nil { 209 | fmt.Printf("%s %+v\n", CharError, err) 210 | os.Exit(1) 211 | } 212 | } 213 | 214 | if listRange != "" { 215 | if since != "" || until != "" { 216 | fmt.Println("Range and since/until can't be used together, select one of them") 217 | os.Exit(1) 218 | } 219 | 220 | if viper.GetBool("firstWeekDayMonday") { 221 | now.WeekStartDay = time.Monday 222 | } 223 | 224 | loc, _ := time.LoadLocation("Local") 225 | time.Local = loc 226 | switch strings.ToLower(listRange) { 227 | case "today": 228 | sinceTime = now.BeginningOfDay() 229 | untilTime = now.EndOfDay() 230 | case "yesterday": 231 | sinceTime = now.BeginningOfDay().AddDate(0, 0, -1) 232 | untilTime = now.EndOfDay().AddDate(0, 0, -1) 233 | case "thisweek": 234 | sinceTime = now.BeginningOfWeek() 235 | untilTime = now.EndOfWeek() 236 | case "lastweek": 237 | lastWeekDay := time.Now().AddDate(0, 0, -7) 238 | sinceTime = now.With(lastWeekDay).BeginningOfWeek() 239 | untilTime = now.With(lastWeekDay).EndOfWeek() 240 | case "thismonth": 241 | sinceTime = now.BeginningOfMonth() 242 | untilTime = now.EndOfMonth() 243 | case "lastmonth": 244 | lastMonthDay := time.Now().AddDate(0, -1, 0) 245 | sinceTime = now.With(lastMonthDay).BeginningOfMonth() 246 | untilTime = now.With(lastMonthDay).EndOfMonth() 247 | default: 248 | fmt.Println("Unknown range selection, possible options: ", strings.Join(Ranges(), " ")) 249 | os.Exit(1) 250 | } 251 | } 252 | 253 | return sinceTime, untilTime 254 | } 255 | -------------------------------------------------------------------------------- /z/importCmd.go: -------------------------------------------------------------------------------- 1 | package z 2 | 3 | import ( 4 | "fmt" 5 | "os" 6 | "time" 7 | 8 | "github.com/cnf/structhash" 9 | "github.com/gookit/color" 10 | "github.com/spf13/cobra" 11 | ) 12 | 13 | func importTymeJson(user string, file string) ([]Entry, error) { 14 | var entries []Entry 15 | 16 | tyme := Tyme{} 17 | tyme.Load(file) 18 | 19 | for _, tymeEntry := range tyme.Data { 20 | tymeEntrySHA1 := structhash.Sha1(tymeEntry, 1) 21 | tymeStart, err := time.Parse("2006-01-02T15:04:05-07:00", tymeEntry.Start) 22 | if err != nil { 23 | fmt.Printf("%s %+v\n", CharError, err) 24 | continue 25 | } 26 | 27 | tymeEnd, err := time.Parse("2006-01-02T15:04:05-07:00", tymeEntry.End) 28 | if err != nil { 29 | fmt.Printf("%s %+v\n", CharError, err) 30 | continue 31 | } 32 | 33 | entry, err := NewEntry("", "", "", tymeEntry.Project, tymeEntry.Task, user) 34 | if err != nil { 35 | fmt.Printf("%s %+v\n", CharError, err) 36 | continue 37 | } 38 | 39 | entry.Begin = tymeStart 40 | entry.Finish = tymeEnd 41 | 42 | entry.SHA1 = fmt.Sprintf("%x", tymeEntrySHA1) 43 | 44 | entries = append(entries, entry) 45 | } 46 | 47 | return entries, nil 48 | } 49 | 50 | var importCmd = &cobra.Command{ 51 | Use: "import ([flags]) [file]", 52 | Short: "Import tracked activities", 53 | Long: "Import tracked activities from various formats.", 54 | Args: cobra.ExactArgs(1), 55 | Run: func(cmd *cobra.Command, args []string) { 56 | var entries []Entry 57 | var err error 58 | 59 | user := GetCurrentUser() 60 | 61 | switch format { 62 | case "zeit": 63 | // TODO: 64 | fmt.Printf("%s not yet implemented\n", CharError) 65 | os.Exit(1) 66 | case "tyme": 67 | entries, err = importTymeJson(user, args[0]) 68 | if err != nil { 69 | fmt.Printf("%s %+v\n", CharError, err) 70 | os.Exit(1) 71 | } 72 | default: 73 | fmt.Printf("%s specify an import format; see `zeit import --help` for more info\n", CharError) 74 | os.Exit(1) 75 | } 76 | 77 | sha1List, sha1Err := database.GetImportsSHA1List(user) 78 | if sha1Err != nil { 79 | fmt.Printf("%s %+v\n", CharError, sha1Err) 80 | os.Exit(1) 81 | } 82 | 83 | for _, entry := range entries { 84 | if id, ok := sha1List[entry.SHA1]; ok { 85 | fmt.Printf("%s %s was previously imported as %s; not importing again\n", CharInfo, color.FgLightWhite.Render(entry.SHA1), color.FgLightWhite.Render(id)) 86 | continue 87 | } 88 | 89 | importedId, err := database.AddEntry(user, entry, false) 90 | if err != nil { 91 | fmt.Printf("%s %s could not be imported: %+v\n", CharError, color.FgLightWhite.Render(entry.SHA1), color.FgRed.Render(err)) 92 | continue 93 | } 94 | 95 | fmt.Printf("%s %s was imported as %s\n", CharInfo, color.FgLightWhite.Render(entry.SHA1), color.FgLightWhite.Render(importedId)) 96 | sha1List[entry.SHA1] = importedId 97 | } 98 | 99 | err = database.UpdateImportsSHA1List(user, sha1List) 100 | if err != nil { 101 | fmt.Printf("%s %+v\n", CharError, err) 102 | os.Exit(1) 103 | } 104 | 105 | return 106 | }, 107 | } 108 | 109 | func init() { 110 | rootCmd.AddCommand(importCmd) 111 | importCmd.Flags().StringVar(&format, "format", "zeit", "Format to import, possible values: zeit, tyme") 112 | } 113 | -------------------------------------------------------------------------------- /z/listCmd.go: -------------------------------------------------------------------------------- 1 | package z 2 | 3 | import ( 4 | "fmt" 5 | "strings" 6 | 7 | "github.com/shopspring/decimal" 8 | "github.com/spf13/cobra" 9 | ) 10 | 11 | var ( 12 | listTotalTime bool 13 | listOnlyProjectsAndTasks bool 14 | listOnlyTasks bool 15 | appendProjectIDToTask bool 16 | ) 17 | 18 | var listCmd = &cobra.Command{ 19 | Use: "list", 20 | Short: "List activities", 21 | Long: "List all tracked activities.", 22 | Run: func(cmd *cobra.Command, args []string) { 23 | filteredEntries := listEntries() 24 | 25 | totalHours := decimal.NewFromInt(0) 26 | for _, entry := range filteredEntries { 27 | totalHours = totalHours.Add(entry.GetDuration()) 28 | fmt.Printf("%s\n", entry.GetOutput(false)) 29 | } 30 | 31 | if listTotalTime == true { 32 | fmt.Printf("\nTOTAL: %s H\n\n", fmtHours(totalHours)) 33 | } 34 | return 35 | }, 36 | } 37 | 38 | func init() { 39 | rootCmd.AddCommand(listCmd) 40 | listCmd.Flags().StringVar(&since, "since", "", "Date/time to start the list from") 41 | listCmd.Flags().StringVar(&until, "until", "", "Date/time to list until") 42 | listCmd.Flags().StringVar(&listRange, "range", "", "Shortcut for --since and --until that accepts: "+strings.Join(Ranges(), ", ")) 43 | listCmd.Flags().StringVarP(&project, "project", "p", "", "Project to be listed") 44 | listCmd.Flags().StringVarP(&task, "task", "t", "", "Task to be listed") 45 | listCmd.Flags().BoolVar(&fractional, "decimal", false, "Show fractional hours in decimal format instead of minutes") 46 | listCmd.Flags().BoolVar(&listTotalTime, "total", false, "Show total time of hours for listed activities") 47 | listCmd.Flags().BoolVar(&listOnlyProjectsAndTasks, "only-projects-and-tasks", false, "Only list projects and their tasks, no entries") 48 | listCmd.Flags().BoolVar(&listOnlyTasks, "only-tasks", false, "Only list tasks, no projects nor entries") 49 | listCmd.Flags().BoolVar(&appendProjectIDToTask, "append-project-id-to-task", false, "Append project ID to tasks in the list") 50 | 51 | flagName := "task" 52 | listCmd.RegisterFlagCompletionFunc(flagName, func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) { 53 | user := GetCurrentUser() 54 | entries, _ := database.ListEntries(user) 55 | _, tasks := listProjectsAndTasks(entries) 56 | return tasks, cobra.ShellCompDirectiveDefault 57 | }) 58 | } 59 | -------------------------------------------------------------------------------- /z/project.go: -------------------------------------------------------------------------------- 1 | package z 2 | 3 | type Project struct { 4 | Name string `json:"name,omitempty"` 5 | Color string `json:"color,omitempty"` 6 | } 7 | -------------------------------------------------------------------------------- /z/projectCmd.go: -------------------------------------------------------------------------------- 1 | package z 2 | 3 | import ( 4 | "fmt" 5 | "os" 6 | // "time" 7 | "github.com/spf13/cobra" 8 | // "github.com/gookit/color" 9 | ) 10 | 11 | var projectColor string 12 | 13 | var projectCmd = &cobra.Command{ 14 | Use: "project ([flags]) [project]", 15 | Short: "Project settings", 16 | Long: "Configure project settings.", 17 | Args: cobra.ExactArgs(1), 18 | Run: func(cmd *cobra.Command, args []string) { 19 | user := GetCurrentUser() 20 | projectName := args[0] 21 | 22 | project, err := database.GetProject(user, projectName) 23 | if err != nil { 24 | fmt.Printf("%s %+v\n", CharError, err) 25 | os.Exit(1) 26 | } 27 | 28 | project.Name = projectName 29 | 30 | if projectColor != "" { 31 | project.Color = projectColor 32 | } 33 | 34 | err = database.UpdateProject(user, projectName, project) 35 | if err != nil { 36 | fmt.Printf("%s %+v\n", CharError, err) 37 | os.Exit(1) 38 | } 39 | 40 | fmt.Printf("%s project updated\n", CharInfo) 41 | return 42 | }, 43 | } 44 | 45 | func init() { 46 | rootCmd.AddCommand(projectCmd) 47 | projectCmd.Flags().StringVarP(&projectColor, "color", "c", "", "Set the color of the project (hex code, e.g. #121212)") 48 | } 49 | -------------------------------------------------------------------------------- /z/reportCmd.go: -------------------------------------------------------------------------------- 1 | package z 2 | 3 | import ( 4 | "fmt" 5 | "sort" 6 | "time" 7 | 8 | "github.com/gookit/color" 9 | "github.com/spf13/cobra" 10 | "github.com/spf13/viper" 11 | ) 12 | 13 | type reportEntry struct { 14 | Date string 15 | Project string 16 | Task string 17 | Duration float64 18 | Notes string 19 | Running bool 20 | } 21 | 22 | type reportLine struct { 23 | Duration float64 24 | Notes []string 25 | Running bool 26 | } 27 | 28 | var ( 29 | weeklyFlag bool 30 | monthlyFlag bool 31 | notesFlag bool 32 | noTasksFlag bool 33 | ) 34 | var dailyReport map[string]map[string]map[string]reportLine 35 | 36 | var reportCmd = &cobra.Command{ 37 | Use: "report", 38 | Short: "report times an day / project / task level", 39 | Long: "Reporting summaries on daily, project, task level for a given range", 40 | Run: func(cmd *cobra.Command, args []string) { 41 | if since == "" && until == "" && listRange == "" { 42 | listRange = viper.GetString("report.default") 43 | } 44 | 45 | dailyReport = make(map[string]map[string]map[string]reportLine) 46 | 47 | if weeklyFlag { 48 | viper.Set("report.weeklySum", true) 49 | } 50 | if monthlyFlag { 51 | viper.Set("report.monthlySum", true) 52 | } 53 | if notesFlag { 54 | viper.Set("report.notes", true) 55 | } 56 | if noTasksFlag { 57 | viper.Set("report.no-tasks", true) 58 | } 59 | 60 | filteredEntries := listEntries() 61 | sinceTime, untilTime := ParseSinceUntil(since, until, listRange) 62 | if listRange != "" { 63 | fmt.Println("Reporting for Timerange:", listRange, "/", sinceTime.Format(DateFormat), "-", untilTime.Format(DateFormat)) 64 | } 65 | var reportEntries []reportEntry 66 | for _, fe := range filteredEntries { 67 | var entryDuration float64 68 | running := false 69 | if fe.Finish.IsZero() { 70 | entryDuration = time.Duration(time.Since(fe.Begin)).Seconds() 71 | running = true 72 | } else { 73 | entryDuration = time.Duration(fe.Finish.Sub(fe.Begin)).Seconds() 74 | } 75 | dateString := fe.Begin.Format(DateFormat) 76 | reportEntries = append(reportEntries, reportEntry{dateString, fe.Project, fe.Task, entryDuration, fe.Notes, running}) 77 | } 78 | 79 | for _, re := range reportEntries { 80 | dailyReporting(re) 81 | } 82 | 83 | output() 84 | }, 85 | } 86 | 87 | func init() { 88 | rootCmd.AddCommand(reportCmd) 89 | 90 | reportCmd.Flags().StringVar(&since, "since", "", "Date/time to start the list from") 91 | reportCmd.Flags().StringVar(&until, "until", "", "Date/time to list until") 92 | reportCmd.Flags().StringVar(&listRange, "range", "", "shortcut to set since/until for a given range (today, yesterday, thisWeek, lastWeek, thisMonth, lastMonth)") 93 | reportCmd.Flags().StringVarP(&project, "project", "p", "", "Project to be listed") 94 | reportCmd.Flags().StringVarP(&task, "task", "t", "", "Task to be listed") 95 | reportCmd.PersistentFlags().BoolVar(&weeklyFlag, "weekly", false, "Print summary of weekly hours") 96 | reportCmd.PersistentFlags().BoolVar(&monthlyFlag, "monthly", false, "Print summary of monthly hours") 97 | reportCmd.PersistentFlags().BoolVar(¬esFlag, "notes", false, "Print notes for the task") 98 | reportCmd.PersistentFlags().BoolVar(&noTasksFlag, "no-tasks", false, "Print only summary bot no task details") 99 | 100 | flagName := "task" 101 | reportCmd.RegisterFlagCompletionFunc(flagName, func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) { 102 | user := GetCurrentUser() 103 | entries, _ := database.ListEntries(user) 104 | _, tasks := listProjectsAndTasks(entries) 105 | return tasks, cobra.ShellCompDirectiveDefault 106 | }) 107 | } 108 | 109 | func dailyReporting(re reportEntry) { 110 | _, ok := dailyReport[re.Date] 111 | if !ok { 112 | dailyReport[re.Date] = make(map[string]map[string]reportLine) 113 | dailyReport[re.Date][re.Project] = make(map[string]reportLine) 114 | dailyReport[re.Date][re.Project][re.Task] = reportLine{Duration: re.Duration, Notes: []string{re.Notes}, Running: re.Running} 115 | return 116 | } 117 | 118 | _, ok = dailyReport[re.Date][re.Project] 119 | if !ok { 120 | dailyReport[re.Date][re.Project] = make(map[string]reportLine) 121 | dailyReport[re.Date][re.Project][re.Task] = reportLine{Duration: re.Duration, Notes: []string{re.Notes}, Running: re.Running} 122 | return 123 | } 124 | 125 | _, ok = dailyReport[re.Date][re.Project][re.Task] 126 | if !ok { 127 | dailyReport[re.Date][re.Project][re.Task] = reportLine{Duration: re.Duration, Notes: []string{re.Notes}, Running: re.Running} 128 | return 129 | } 130 | 131 | workEntry := dailyReport[re.Date][re.Project][re.Task] 132 | if workEntry.Running || re.Running { 133 | workEntry.Running = true 134 | } 135 | workEntry.Duration += re.Duration 136 | workEntry.Notes = append(workEntry.Notes, re.Notes) 137 | dailyReport[re.Date][re.Project][re.Task] = workEntry 138 | } 139 | 140 | func output() { 141 | lastWeek := "" 142 | weekSum := 0.0 143 | lastMonth := "" 144 | monthSum := 0.0 145 | for _, dateKey := range dialyKeys() { 146 | dailySum := 0.0 147 | fmt.Println(" ") 148 | for _, projectKey := range projectKeys(dateKey) { 149 | projectSum := 0.0 150 | for _, taskKey := range taskKeys(dateKey, projectKey) { 151 | t, _ := time.Parse("2006-01-02", dateKey) 152 | year, week := t.ISOWeek() 153 | thisWeek := fmt.Sprintf("%04d-%02d", year, week) 154 | if lastWeek != "" && lastWeek != thisWeek { 155 | if viper.GetBool("report.weeklySum") { 156 | color.FgGray.Println(" Week: ", lastWeek, ":", fmtDuration(time.Duration(weekSum*float64(time.Second))), "\n-------------------\n") 157 | } 158 | lastWeek = thisWeek 159 | weekSum = 0.0 160 | } 161 | if lastWeek == "" { 162 | lastWeek = thisWeek 163 | } 164 | 165 | month := t.Month() 166 | thisMonth := fmt.Sprintf("%04d-%02d", year, month) 167 | if lastMonth != "" && lastMonth != thisMonth { 168 | if viper.GetBool("report.monthlySum") { 169 | color.FgGray.Println(" Month: ", lastMonth, ":", fmtDuration(time.Duration(monthSum*float64(time.Second))), "\n=====================\n") 170 | } 171 | lastMonth = thisMonth 172 | monthSum = 0.0 173 | } 174 | if lastMonth == "" { 175 | lastMonth = thisMonth 176 | } 177 | 178 | if !viper.GetBool("report.no-tasks") { 179 | color.FgLightWhite.Print(" ", fmtDuration(time.Duration(dailyReport[dateKey][projectKey][taskKey].Duration*float64(time.Second))), " ", taskKey) 180 | if dailyReport[dateKey][projectKey][taskKey].Running { 181 | color.FgLightYellow.Println(" (running)") 182 | } else { 183 | fmt.Println() 184 | } 185 | if viper.GetBool("report.notes") { 186 | for _, note := range dailyReport[dateKey][projectKey][taskKey].Notes[1:] { 187 | if len(note) > 0 { 188 | color.FgLightBlue.Println(" ", note) 189 | } 190 | } 191 | } 192 | } 193 | projectSum += dailyReport[dateKey][projectKey][taskKey].Duration 194 | dailySum += dailyReport[dateKey][projectKey][taskKey].Duration 195 | weekSum += dailyReport[dateKey][projectKey][taskKey].Duration 196 | monthSum += dailyReport[dateKey][projectKey][taskKey].Duration 197 | } 198 | fmt.Println(" ", projectKey, ":", fmtDuration(time.Duration(projectSum*float64(time.Second)))) 199 | } 200 | fmt.Println(" ", dateKey, ":", fmtDuration(time.Duration(dailySum*float64(time.Second)))) 201 | } 202 | if viper.GetBool("report.weeklySum") { 203 | fmt.Println("\n Week: ", lastWeek, ":", fmtDuration(time.Duration(weekSum*float64(time.Second)))) 204 | } 205 | if viper.GetBool("report.monthlySUm") { 206 | fmt.Println("\n Month: ", lastMonth, ":", fmtDuration(time.Duration(monthSum*float64(time.Second)))) 207 | } 208 | } 209 | 210 | func dialyKeys() []string { 211 | keys := make([]string, 0, len(dailyReport)) 212 | 213 | for k := range dailyReport { 214 | keys = append(keys, k) 215 | } 216 | 217 | sort.Strings(keys) 218 | 219 | return keys 220 | } 221 | 222 | func projectKeys(daily string) []string { 223 | keys := make([]string, 0, len(dailyReport[daily])) 224 | 225 | for k := range dailyReport[daily] { 226 | keys = append(keys, k) 227 | } 228 | 229 | sort.Strings(keys) 230 | 231 | return keys 232 | } 233 | 234 | func taskKeys(daily string, project string) []string { 235 | keys := make([]string, 0, len(dailyReport[daily][project])) 236 | 237 | for k := range dailyReport[daily][project] { 238 | keys = append(keys, k) 239 | } 240 | 241 | sort.Strings(keys) 242 | 243 | return keys 244 | } 245 | -------------------------------------------------------------------------------- /z/resumeCmd.go: -------------------------------------------------------------------------------- 1 | package z 2 | 3 | import ( 4 | "github.com/spf13/cobra" 5 | ) 6 | 7 | var resumeCmd = &cobra.Command{ 8 | Use: "resume", 9 | Short: "Resume last task", 10 | Long: "Track new activity with all parameters of the last task (based on begin time)", 11 | Run: func(cmd *cobra.Command, args []string) { 12 | resumeTask(1) 13 | }, 14 | } 15 | 16 | func init() { 17 | rootCmd.AddCommand(resumeCmd) 18 | 19 | resumeCmd.Flags().StringVarP(&begin, "begin", "b", "", "Time the activity should begin at\n\nEither in the formats 16:00 / 4:00PM \nor relative to the current time, \ne.g. -0:15 (now minus 15 minutes), +1.50 (now plus 1:30h).") 20 | resumeCmd.Flags().StringVarP(&finish, "finish", "s", "", "Time the activity should finish at\n\nEither in the formats 16:00 / 4:00PM \nor relative to the current time, \ne.g. -0:15 (now minus 15 minutes), +1.50 (now plus 1:30h).\nMust be after --begin time.") 21 | } 22 | -------------------------------------------------------------------------------- /z/rootCmd.go: -------------------------------------------------------------------------------- 1 | package z 2 | 3 | import ( 4 | "fmt" 5 | "os" 6 | 7 | "github.com/gookit/color" 8 | "github.com/spf13/cobra" 9 | "github.com/spf13/viper" 10 | ) 11 | 12 | var database *Database 13 | 14 | var ( 15 | begin string 16 | finish string 17 | switchString string 18 | project string 19 | task string 20 | notes string 21 | ) 22 | 23 | var ( 24 | since string 25 | until string 26 | listRange string 27 | ) 28 | 29 | var ( 30 | format string 31 | force bool 32 | ) 33 | 34 | var ( 35 | noColors bool 36 | debug bool 37 | cfgFile string 38 | ) 39 | 40 | const ( 41 | CharTrack = " ▶" 42 | CharFinish = " ■" 43 | CharErase = " ◀" 44 | CharError = " ▲" 45 | CharInfo = " ●" 46 | CharMore = " ◆" 47 | ) 48 | 49 | var rootCmd = &cobra.Command{ 50 | Use: "zeit", 51 | Short: "Command line Zeiterfassung", 52 | Long: `A command line time tracker.`, 53 | } 54 | 55 | func Execute() { 56 | if err := rootCmd.Execute(); err != nil { 57 | fmt.Printf("%s %+v\n", CharError, err) 58 | os.Exit(-1) 59 | } 60 | } 61 | 62 | func init() { 63 | cobra.OnInitialize(initConfig) 64 | 65 | rootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "config file (default is $XDG_CONFIG_HOME/zeit.[yaml|toml") 66 | 67 | rootCmd.PersistentFlags().BoolVar(&noColors, FlagNoColors, false, "Do not use colors in output") 68 | viper.BindPFlag(FlagNoColors, rootCmd.PersistentFlags().Lookup(FlagNoColors)) 69 | 70 | rootCmd.PersistentFlags().BoolVarP(&debug, FlagDebug, "d", false, "Display debugging output in the console. (default: false)") 71 | viper.BindPFlag(FlagDebug, rootCmd.PersistentFlags().Lookup(FlagDebug)) 72 | } 73 | 74 | func initConfig() { 75 | if noColors == true { 76 | color.Disable() 77 | } 78 | 79 | viper.SetEnvPrefix("zeit") 80 | viper.BindEnv("db") 81 | 82 | if cfgFile != "" { 83 | // Use config file from the flag. 84 | viper.SetConfigFile(cfgFile) 85 | } else { 86 | // Find home directory. 87 | home, err := os.UserHomeDir() 88 | cobra.CheckErr(err) 89 | 90 | viper.AddConfigPath("$XDG_CONFIG_HOME") 91 | viper.AddConfigPath("$XDG_CONFIG_HOME/zeit") 92 | viper.AddConfigPath(home + "/.config") 93 | viper.AddConfigPath(home + "/.config/zeit") 94 | viper.SetConfigName("zeit") 95 | } 96 | 97 | if err := viper.ReadInConfig(); err != nil { 98 | // Set default values for parameters 99 | viper.Set("debug", false) 100 | } 101 | 102 | if viper.GetBool("debug") { 103 | fmt.Fprintln(os.Stderr, "Using config file:", viper.ConfigFileUsed()) 104 | fmt.Fprintln(os.Stderr, "Using Database file:", viper.GetString("db")) 105 | } 106 | 107 | var err error 108 | database, err = InitDatabase() 109 | if err != nil { 110 | fmt.Printf("%s %+v\n", CharError, err) 111 | os.Exit(1) 112 | } 113 | } 114 | -------------------------------------------------------------------------------- /z/statsCmd.go: -------------------------------------------------------------------------------- 1 | package z 2 | 3 | import ( 4 | "fmt" 5 | "os" 6 | "strings" 7 | "time" 8 | 9 | "github.com/spf13/cobra" 10 | // "github.com/shopspring/decimal" 11 | // "github.com/gookit/color" 12 | ) 13 | 14 | var statsCmd = &cobra.Command{ 15 | Use: "stats", 16 | Short: "Display activity statistics", 17 | Long: "Display statistics on all tracked activities.", 18 | Run: func(cmd *cobra.Command, args []string) { 19 | user := GetCurrentUser() 20 | 21 | entries, err := database.ListEntries(user) 22 | if err != nil { 23 | fmt.Printf("%s %+v\n", CharError, err) 24 | os.Exit(1) 25 | } 26 | 27 | cal, _ := NewCalendar(entries) 28 | 29 | weekMinus0 := time.Now() 30 | monthMinus0, weeknumberMinus0 := GetISOWeekInMonth(weekMinus0) 31 | monthMinus00 := monthMinus0 - 1 32 | weeknumberMinus00 := weeknumberMinus0 - 1 33 | thisWeek := cal.GetOutputForWeekCalendar(weekMinus0, monthMinus00, weeknumberMinus00) 34 | 35 | weekMinus1 := weekMinus0.AddDate(0, 0, -7) 36 | monthMinus1, weeknumberMinus1 := GetISOWeekInMonth(weekMinus1) 37 | monthMinus10 := monthMinus1 - 1 38 | weeknumberMinus10 := weeknumberMinus1 - 1 39 | previousWeek := cal.GetOutputForWeekCalendar(weekMinus1, monthMinus10, weeknumberMinus10) 40 | 41 | if monthMinus00 == monthMinus10 { 42 | fmt.Printf("\n%s\n\n", strings.ToUpper(weekMinus0.Month().String())) 43 | } else { 44 | fmt.Printf("\n%s / %s\n\n", strings.ToUpper(weekMinus0.Month().String()), strings.ToUpper(weekMinus1.Month().String())) 45 | } 46 | fmt.Printf("%s\n\n\n", OutputAppendRight(thisWeek, previousWeek, 16)) 47 | fmt.Printf("%s\n", cal.GetOutputForDistribution()) 48 | 49 | return 50 | }, 51 | } 52 | 53 | func init() { 54 | rootCmd.AddCommand(statsCmd) 55 | statsCmd.Flags().BoolVar(&fractional, "decimal", false, "Show fractional hours in decimal format instead of minutes") 56 | } 57 | -------------------------------------------------------------------------------- /z/switchBackCmd.go: -------------------------------------------------------------------------------- 1 | package z 2 | 3 | import ( 4 | "github.com/spf13/cobra" 5 | ) 6 | 7 | var switchBackCmd = &cobra.Command{ 8 | Use: "switchback", 9 | Short: "switchback to the task before the last one", 10 | Long: "End running activity and resume the task which was before, which can either be kept running until 'finish' is being called or parameterized to be a finished activity.", 11 | Run: func(cmd *cobra.Command, args []string) { 12 | finish = switchString 13 | finishTask(FinishOnlyTime) 14 | 15 | finish = "" 16 | begin = switchString 17 | resumeTask(2) 18 | }, 19 | } 20 | 21 | func init() { 22 | rootCmd.AddCommand(switchBackCmd) 23 | 24 | switchBackCmd.Flags().StringVarP(&switchString, "begin", "b", "", "Time the new activity should begin at and the old one ends\n\nEither in the formats 16:00 / 4:00PM \nor relative to the current time, \ne.g. -0:15 (now minus 15 minutes), +1.50 (now plus 1:30h).") 25 | } 26 | -------------------------------------------------------------------------------- /z/switchCmd.go: -------------------------------------------------------------------------------- 1 | package z 2 | 3 | import ( 4 | "github.com/spf13/cobra" 5 | ) 6 | 7 | var switchCmd = &cobra.Command{ 8 | Use: "switch", 9 | Short: "switch to another task", 10 | Long: "End running activity and track new activity, which can either be kept running until 'finish' is being called or parameterized to be a finished activity.", 11 | Run: func(cmd *cobra.Command, args []string) { 12 | finish = switchString 13 | finishTask(FinishOnlyTime) 14 | 15 | finish = "" 16 | begin = switchString 17 | trackTask() 18 | }, 19 | } 20 | 21 | func init() { 22 | rootCmd.AddCommand(switchCmd) 23 | 24 | switchCmd.Flags().StringVarP(&switchString, "begin", "b", "", "Time the new activity should begin at and the old one ends\n\nEither in the formats 16:00 / 4:00PM \nor relative to the current time, \ne.g. -0:15 (now minus 15 minutes), +1.50 (now plus 1:30h).") 25 | switchCmd.Flags().StringVarP(&project, "project", "p", "", "Project to be assigned") 26 | switchCmd.Flags().StringVarP(&task, "task", "t", "", "Task to be assigned") 27 | switchCmd.Flags().StringVarP(¬es, "notes", "n", "", "Activity notes") 28 | 29 | flagName := "task" 30 | switchCmd.RegisterFlagCompletionFunc(flagName, func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) { 31 | user := GetCurrentUser() 32 | entries, _ := database.ListEntries(user) 33 | _, tasks := listProjectsAndTasks(entries) 34 | return tasks, cobra.ShellCompDirectiveDefault 35 | }) 36 | } 37 | -------------------------------------------------------------------------------- /z/task.go: -------------------------------------------------------------------------------- 1 | package z 2 | 3 | import ( 4 | "fmt" 5 | "os" 6 | "time" 7 | 8 | "github.com/spf13/viper" 9 | ) 10 | 11 | type Task struct { 12 | Name string `json:"name,omitempty"` 13 | GitRepository string `json:"gitRepository,omitempty"` 14 | } 15 | 16 | func listEntries() []Entry { 17 | user := GetCurrentUser() 18 | 19 | entries, err := database.ListEntries(user) 20 | if err != nil { 21 | fmt.Printf("%s %+v\n", CharError, err) 22 | os.Exit(1) 23 | } 24 | 25 | sinceTime, untilTime := ParseSinceUntil(since, until, listRange) 26 | 27 | var filteredEntries []Entry 28 | filteredEntries, err = GetFilteredEntries(entries, project, task, sinceTime, untilTime) 29 | if err != nil { 30 | fmt.Printf("%s %+v\n", CharError, err) 31 | os.Exit(1) 32 | } 33 | 34 | if listOnlyProjectsAndTasks || listOnlyTasks { 35 | printProjects(filteredEntries) 36 | return nil 37 | } 38 | return filteredEntries 39 | } 40 | 41 | func printProjects(entries []Entry) { 42 | projectsAndTasks, _ := listProjectsAndTasks(entries) 43 | for project := range projectsAndTasks { 44 | if listOnlyProjectsAndTasks && !listOnlyTasks { 45 | fmt.Printf("%s %s\n", CharMore, project) 46 | } 47 | 48 | for task := range projectsAndTasks[project] { 49 | if listOnlyProjectsAndTasks && !listOnlyTasks { 50 | fmt.Printf("%*s└── ", 1, " ") 51 | } 52 | 53 | if appendProjectIDToTask { 54 | fmt.Printf("%s [%s]\n", task, project) 55 | } else { 56 | fmt.Printf("%s\n", task) 57 | } 58 | } 59 | } 60 | } 61 | 62 | func listProjectsAndTasks(entries []Entry) (map[string]map[string]bool, []string) { 63 | projectsAndTasks := make(map[string]map[string]bool) 64 | var allTasks []string 65 | 66 | for _, filteredEntry := range entries { 67 | taskMap, ok := projectsAndTasks[filteredEntry.Project] 68 | 69 | if !ok { 70 | taskMap = make(map[string]bool) 71 | projectsAndTasks[filteredEntry.Project] = taskMap 72 | } 73 | 74 | taskMap[filteredEntry.Task] = true 75 | projectsAndTasks[filteredEntry.Project] = taskMap 76 | allTasks = append(allTasks, filteredEntry.Task) 77 | } 78 | 79 | return projectsAndTasks, allTasks 80 | } 81 | 82 | func trackTask() { 83 | user := GetCurrentUser() 84 | 85 | runningEntryId, err := database.GetRunningEntryId(user) 86 | if err != nil { 87 | fmt.Printf("%s %+v\n", CharError, err) 88 | os.Exit(1) 89 | } 90 | 91 | if runningEntryId != "" { 92 | fmt.Printf("%s a task is already running\n", CharTrack) 93 | os.Exit(1) 94 | } 95 | 96 | if project == "" && viper.GetString("project.default") != "" { 97 | project = viper.GetString("project.default") 98 | } 99 | 100 | if project == "" && viper.GetBool("project.mandatory") { 101 | fmt.Println("project is mandatory but missing") 102 | os.Exit(1) 103 | } 104 | 105 | if task == "" && viper.GetBool("task.mandatory") { 106 | fmt.Println("task is mandatory but missing") 107 | os.Exit(1) 108 | } 109 | 110 | newEntry, err := NewEntry("", begin, finish, project, task, user) 111 | if err != nil { 112 | fmt.Printf("%s %+v\n", CharError, err) 113 | os.Exit(1) 114 | } 115 | 116 | if notes != "" { 117 | newEntry.Notes = notes 118 | } 119 | 120 | isRunning := newEntry.Finish.IsZero() 121 | 122 | _, err = database.AddEntry(user, newEntry, isRunning) 123 | if err != nil { 124 | fmt.Printf("%s %+v\n", CharError, err) 125 | os.Exit(1) 126 | } 127 | 128 | fmt.Print(newEntry.GetOutputForTrack(isRunning, false)) 129 | } 130 | 131 | func finishTask(mode int) { 132 | user := GetCurrentUser() 133 | 134 | runningEntryId, err := database.GetRunningEntryId(user) 135 | if err != nil { 136 | fmt.Printf("%s %+v\n", CharError, err) 137 | os.Exit(1) 138 | } 139 | 140 | if runningEntryId == "" { 141 | fmt.Printf("%s not running\n", CharFinish) 142 | os.Exit(1) 143 | } 144 | 145 | runningEntry, err := database.GetEntry(user, runningEntryId) 146 | if err != nil { 147 | fmt.Printf("%s %+v\n", CharError, err) 148 | os.Exit(1) 149 | } 150 | 151 | tmpEntry, err := NewEntry(runningEntry.ID, begin, finish, project, task, user) 152 | if err != nil { 153 | fmt.Printf("%s %+v\n", CharError, err) 154 | os.Exit(1) 155 | } 156 | 157 | if begin != "" { 158 | runningEntry.Begin = tmpEntry.Begin 159 | } 160 | 161 | if finish != "" { 162 | runningEntry.Finish = tmpEntry.Finish 163 | } else { 164 | runningEntry.Finish = time.Now() 165 | } 166 | 167 | if mode == FinishWithMetadata { 168 | finishTaskMetadata(user, &runningEntry, &tmpEntry) 169 | } 170 | 171 | if !runningEntry.IsFinishedAfterBegan() { 172 | fmt.Printf("%s %+v\n", CharError, "beginning time of tracking cannot be after finish time") 173 | os.Exit(1) 174 | } 175 | 176 | _, err = database.FinishEntry(user, runningEntry) 177 | if err != nil { 178 | fmt.Printf("%s %+v\n", CharError, err) 179 | os.Exit(1) 180 | } 181 | 182 | fmt.Print(runningEntry.GetOutputForFinish()) 183 | } 184 | 185 | func finishTaskMetadata(user string, runningEntry *Entry, tmpEntry *Entry) { 186 | if project != "" { 187 | runningEntry.Project = tmpEntry.Project 188 | } 189 | 190 | if task != "" { 191 | runningEntry.Task = tmpEntry.Task 192 | } 193 | 194 | if notes != "" { 195 | runningEntry.Notes = fmt.Sprintf("%s\n%s", runningEntry.Notes, notes) 196 | } 197 | 198 | if runningEntry.Task != "" { 199 | task, err := database.GetTask(user, runningEntry.Task) 200 | if err != nil { 201 | fmt.Printf("%s %+v\n", CharError, err) 202 | os.Exit(1) 203 | } 204 | 205 | taskGit(&task, runningEntry) 206 | } 207 | } 208 | 209 | func taskGit(task *Task, runningEntry *Entry) { 210 | if task.GitRepository != "" && task.GitRepository != "-" { 211 | stdout, stderr, err := GetGitLog(task.GitRepository, runningEntry.Begin, runningEntry.Finish) 212 | if err != nil { 213 | fmt.Printf("%s %+v\n", CharError, err) 214 | os.Exit(1) 215 | } 216 | 217 | if stderr == "" { 218 | runningEntry.Notes = fmt.Sprintf("%s\n%s", runningEntry.Notes, stdout) 219 | } else { 220 | fmt.Printf("%s notes were not imported: %+v\n", CharError, stderr) 221 | } 222 | } 223 | } 224 | 225 | func resumeTask(index int) { 226 | user := GetCurrentUser() 227 | 228 | entries, err := database.ListEntries(user) 229 | if err != nil { 230 | fmt.Printf("%s %+v\n", CharError, err) 231 | os.Exit(1) 232 | } 233 | lastEntry := entries[len(entries)-index] 234 | 235 | runningEntryId, err := database.GetRunningEntryId(user) 236 | if err != nil { 237 | fmt.Printf("%s %+v\n", CharError, err) 238 | os.Exit(1) 239 | } 240 | 241 | if runningEntryId != "" { 242 | fmt.Printf("%s a task is already running\n", CharTrack) 243 | os.Exit(1) 244 | } 245 | 246 | project = lastEntry.Project 247 | task = lastEntry.Task 248 | 249 | newEntry, err := NewEntry("", begin, finish, project, task, user) 250 | if err != nil { 251 | fmt.Printf("%s %+v\n", CharError, err) 252 | os.Exit(1) 253 | } 254 | 255 | if lastEntry.Notes != "" { 256 | newEntry.Notes = lastEntry.Notes 257 | } 258 | 259 | isRunning := newEntry.Finish.IsZero() 260 | 261 | _, err = database.AddEntry(user, newEntry, isRunning) 262 | if err != nil { 263 | fmt.Printf("%s %+v\n", CharError, err) 264 | os.Exit(1) 265 | } 266 | 267 | fmt.Print(newEntry.GetOutputForTrack(isRunning, false)) 268 | } 269 | -------------------------------------------------------------------------------- /z/taskCmd.go: -------------------------------------------------------------------------------- 1 | package z 2 | 3 | import ( 4 | "fmt" 5 | "os" 6 | // "time" 7 | "github.com/spf13/cobra" 8 | // "github.com/gookit/color" 9 | ) 10 | 11 | var taskGitRepository string 12 | 13 | var taskCmd = &cobra.Command{ 14 | Use: "task ([flags]) [task]", 15 | Short: "Task settings", 16 | Long: "Configure task settings.", 17 | Args: cobra.ExactArgs(1), 18 | Run: func(cmd *cobra.Command, args []string) { 19 | user := GetCurrentUser() 20 | taskName := args[0] 21 | 22 | task, err := database.GetTask(user, taskName) 23 | if err != nil { 24 | fmt.Printf("%s %+v\n", CharError, err) 25 | os.Exit(1) 26 | } 27 | 28 | task.Name = taskName 29 | 30 | if taskGitRepository != "-" { 31 | task.GitRepository = taskGitRepository 32 | } 33 | 34 | err = database.UpdateTask(user, taskName, task) 35 | if err != nil { 36 | fmt.Printf("%s %+v\n", CharError, err) 37 | os.Exit(1) 38 | } 39 | 40 | fmt.Printf("%s task updated\n", CharInfo) 41 | return 42 | }, 43 | } 44 | 45 | func init() { 46 | rootCmd.AddCommand(taskCmd) 47 | taskCmd.Flags().StringVarP(&taskGitRepository, "git", "g", "-", "Set the task's Git repository to enable commit message importing into activity notes.\nSet to an empty string '' to remove a previously set repository and disable git log imports.") 48 | } 49 | -------------------------------------------------------------------------------- /z/trackCmd.go: -------------------------------------------------------------------------------- 1 | package z 2 | 3 | import ( 4 | "fmt" 5 | "os" 6 | 7 | "github.com/spf13/cobra" 8 | "github.com/spf13/viper" 9 | ) 10 | 11 | var trackCmd = &cobra.Command{ 12 | Use: "track", 13 | Short: "Tracking time", 14 | Long: "Track new activity, which can either be kept running until 'finish' is being called or parameterized to be a finished activity.", 15 | Run: func(cmd *cobra.Command, args []string) { 16 | user := GetCurrentUser() 17 | 18 | runningEntryId, err := database.GetRunningEntryId(user) 19 | if err != nil { 20 | fmt.Printf("%s %+v\n", CharError, err) 21 | os.Exit(1) 22 | } 23 | 24 | if runningEntryId != "" { 25 | fmt.Printf("%s a task is already running\n", CharTrack) 26 | os.Exit(1) 27 | } 28 | 29 | if project == "" && viper.GetString("project.default") != "" { 30 | project = viper.GetString("project.default") 31 | } 32 | 33 | if project == "" && viper.GetBool("project.mandatory") { 34 | fmt.Println("project is mandatory but missing") 35 | os.Exit(1) 36 | } 37 | 38 | if task == "" && viper.GetBool("task.mandatory") { 39 | fmt.Println("task is mandatory but missing") 40 | os.Exit(1) 41 | } 42 | 43 | newEntry, err := NewEntry("", begin, finish, project, task, user) 44 | if err != nil { 45 | fmt.Printf("%s %+v\n", CharError, err) 46 | os.Exit(1) 47 | } 48 | 49 | if notes != "" { 50 | newEntry.Notes = notes 51 | } 52 | 53 | isRunning := newEntry.Finish.IsZero() 54 | 55 | _, err = database.AddEntry(user, newEntry, isRunning) 56 | if err != nil { 57 | fmt.Printf("%s %+v\n", CharError, err) 58 | os.Exit(1) 59 | } 60 | 61 | fmt.Printf(newEntry.GetOutputForTrack(isRunning, false)) 62 | return 63 | }, 64 | } 65 | 66 | func init() { 67 | rootCmd.AddCommand(trackCmd) 68 | trackCmd.Flags().StringVarP(&begin, "begin", "b", "", "Time the activity should begin at\n\nEither in the formats 16:00 / 4:00PM \nor relative to the current time, \ne.g. -0:15 (now minus 15 minutes), +1.50 (now plus 1:30h).") 69 | trackCmd.Flags().StringVarP(&finish, "finish", "s", "", "Time the activity should finish at\n\nEither in the formats 16:00 / 4:00PM \nor relative to the current time, \ne.g. -0:15 (now minus 15 minutes), +1.50 (now plus 1:30h).\nMust be after --begin time.") 70 | trackCmd.Flags().StringVarP(&project, "project", "p", "", "Project to be assigned") 71 | trackCmd.Flags().StringVarP(&task, "task", "t", "", "Task to be assigned") 72 | trackCmd.Flags().StringVarP(¬es, "notes", "n", "", "Activity notes") 73 | trackCmd.Flags().BoolVarP(&force, "force", "f", false, "Force begin tracking of a new task \neven though another one is still running \n(ONLY IF YOU KNOW WHAT YOU'RE DOING!)") 74 | 75 | flagName := "task" 76 | trackCmd.RegisterFlagCompletionFunc(flagName, func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) { 77 | user := GetCurrentUser() 78 | entries, _ := database.ListEntries(user) 79 | _, tasks := listProjectsAndTasks(entries) 80 | return tasks, cobra.ShellCompDirectiveDefault 81 | }) 82 | } 83 | -------------------------------------------------------------------------------- /z/trackingCmd.go: -------------------------------------------------------------------------------- 1 | package z 2 | 3 | import ( 4 | "fmt" 5 | "os" 6 | 7 | "github.com/spf13/cobra" 8 | ) 9 | 10 | var trackingCmd = &cobra.Command{ 11 | Use: "tracking", 12 | Short: "Currently tracking activity", 13 | Long: "Show currently tracking activity.", 14 | Run: func(cmd *cobra.Command, args []string) { 15 | user := GetCurrentUser() 16 | 17 | runningEntryId, err := database.GetRunningEntryId(user) 18 | if err != nil { 19 | fmt.Printf("%s %+v\n", CharError, err) 20 | os.Exit(1) 21 | } 22 | 23 | if runningEntryId == "" { 24 | fmt.Printf("%s not running\n", CharFinish) 25 | os.Exit(1) 26 | } 27 | 28 | runningEntry, err := database.GetEntry(user, runningEntryId) 29 | if err != nil { 30 | fmt.Printf("%s %+v\n", CharError, err) 31 | os.Exit(1) 32 | } 33 | 34 | fmt.Printf(runningEntry.GetOutputForTrack(true, true)) 35 | return 36 | }, 37 | } 38 | 39 | func init() { 40 | rootCmd.AddCommand(trackingCmd) 41 | } 42 | -------------------------------------------------------------------------------- /z/tui.go: -------------------------------------------------------------------------------- 1 | package z 2 | 3 | import ( 4 | "fmt" 5 | "math" 6 | 7 | "github.com/gookit/color" 8 | "github.com/shopspring/decimal" 9 | ) 10 | 11 | func GetOutputBoxForNumber(number int, clr func(...interface{}) string) string { 12 | switch number { 13 | case 0: 14 | return clr(" ") 15 | case 1: 16 | return clr(" ▄") 17 | case 2: 18 | return clr("▄▄") 19 | case 3: 20 | return clr("▄█") 21 | case 4: 22 | return clr("██") 23 | } 24 | 25 | return clr(" ") 26 | } 27 | 28 | func GetOutputBarForHours(hours decimal.Decimal, stats []Statistic) []string { 29 | bar := []string{ 30 | color.FgGray.Render("····"), 31 | color.FgGray.Render("····"), 32 | color.FgGray.Render("····"), 33 | color.FgGray.Render("····"), 34 | color.FgGray.Render("····"), 35 | color.FgGray.Render("····"), 36 | } 37 | 38 | hoursInt := int((hours.Round(0)).IntPart()) 39 | rest := ((hours.Round(0)).Mod(decimal.NewFromInt(4))).Round(0) 40 | restInt := int(rest.IntPart()) 41 | 42 | divisible := hoursInt - restInt 43 | fullparts := divisible / 4 44 | 45 | colorsFull := make(map[int](func(...interface{}) string)) 46 | colorsFullIdx := 0 47 | 48 | colorFraction := color.FgWhite.Render 49 | colorFractionPrevAmount := 0.0 50 | 51 | for _, stat := range stats { 52 | statHoursInt, _ := stat.Hours.Float64() 53 | statRest := (stat.Hours.Round(0)).Mod(decimal.NewFromInt(4)) 54 | statRestFloat, _ := statRest.Float64() 55 | 56 | if statRestFloat > colorFractionPrevAmount { 57 | colorFractionPrevAmount = statRestFloat 58 | colorFraction = stat.Color 59 | } 60 | 61 | fullColoredParts := int(math.Round(statHoursInt) / 4) 62 | 63 | if fullColoredParts == 0 && statHoursInt > colorFractionPrevAmount { 64 | colorFractionPrevAmount = statHoursInt 65 | colorFraction = stat.Color 66 | } 67 | 68 | for i := 0; i < fullColoredParts; i++ { 69 | colorsFull[colorsFullIdx] = stat.Color 70 | colorsFullIdx++ 71 | } 72 | } 73 | 74 | iColor := 0 75 | for i := (len(bar) - 1); i > (len(bar) - 1 - fullparts); i-- { 76 | if iColor < colorsFullIdx { 77 | bar[i] = " " + GetOutputBoxForNumber(4, colorsFull[iColor]) + " " 78 | iColor++ 79 | } else { 80 | bar[i] = " " + GetOutputBoxForNumber(4, colorFraction) + " " 81 | } 82 | } 83 | 84 | if restInt > 0 { 85 | bar[(len(bar) - 1 - fullparts)] = " " + GetOutputBoxForNumber(restInt, colorFraction) + " " 86 | } 87 | 88 | return bar 89 | } 90 | 91 | func OutputAppendRight(leftStr string, rightStr string, pad int) string { 92 | var output string = "" 93 | var rpos int = 0 94 | 95 | left := []rune(leftStr) 96 | leftLen := len(left) 97 | right := []rune(rightStr) 98 | rightLen := len(right) 99 | 100 | for lpos := 0; lpos < leftLen; lpos++ { 101 | if left[lpos] == '\n' || lpos == (leftLen-1) { 102 | output = fmt.Sprintf("%s%*s", output, pad, "") 103 | for rpos = rpos; rpos < rightLen; rpos++ { 104 | output = fmt.Sprintf("%s%c", output, right[rpos]) 105 | if right[rpos] == '\n' { 106 | rpos++ 107 | break 108 | } 109 | } 110 | continue 111 | } 112 | output = fmt.Sprintf("%s%c", output, left[lpos]) 113 | } 114 | 115 | return output 116 | } 117 | 118 | func GetColorFnFromHex(colorHex string) func(...interface{}) string { 119 | if colorHex == "" { 120 | colorHex = "#dddddd" 121 | } 122 | return color.NewRGBStyle(color.HEX(colorHex)).Sprint 123 | } 124 | -------------------------------------------------------------------------------- /z/tyme.go: -------------------------------------------------------------------------------- 1 | package z 2 | 3 | import ( 4 | "encoding/json" 5 | "os" 6 | "time" 7 | 8 | // "fmt" 9 | "github.com/shopspring/decimal" 10 | ) 11 | 12 | type TymeEntry struct { 13 | Billing string `json:"billing"` // "UNBILLED", 14 | Category string `json:"category"` // "Client", 15 | Distance string `json:"distance"` // "0", 16 | Duration string `json:"duration"` // "15", 17 | Start string `json:"start"` // "2020-09-01T08:45:00+01:00", 18 | End string `json:"end"` // "2020-09-01T08:57:00+01:00", 19 | Note string `json:"note"` // "", 20 | Project string `json:"project"` // "Project", 21 | Quantity string `json:"quantity"` // "0", 22 | Rate string `json:"rate"` // "140", 23 | RoundingMethod string `json:"rounding_method"` // "NEAREST", 24 | RoundingMinutes int `json:"rounding_minutes"` // 15, 25 | Subtask string `json:"subtask"` // "", 26 | Sum string `json:"sum"` // "35", 27 | Task string `json:"task"` // "Development", 28 | Type string `json:"type"` // "timed", 29 | User string `json:"user"` // "" 30 | } 31 | 32 | type Tyme struct { 33 | Data []TymeEntry `json:"data"` 34 | } 35 | 36 | func (tyme *Tyme) Load(filename string) error { 37 | file, err := os.Open(filename) 38 | if err != nil { 39 | return err 40 | } 41 | defer file.Close() 42 | 43 | decoder := json.NewDecoder(file) 44 | 45 | if err = decoder.Decode(&tyme); err != nil { 46 | return err 47 | } 48 | 49 | return nil 50 | } 51 | 52 | func (tyme *Tyme) FromEntries(entries []Entry) error { 53 | for _, entry := range entries { 54 | duration := decimal.NewFromFloat(entry.Finish.Sub(entry.Begin).Minutes()) 55 | 56 | tymeEntry := TymeEntry{ 57 | Billing: "UNBILLED", 58 | Category: "", 59 | Distance: "0", 60 | Duration: duration.StringFixed(0), 61 | Start: entry.Begin.Format(time.RFC3339), 62 | End: entry.Finish.Format(time.RFC3339), 63 | Note: entry.Notes, 64 | Project: entry.Project, 65 | Quantity: "0", 66 | Rate: "0", 67 | RoundingMethod: "NEAREST", 68 | RoundingMinutes: 15, 69 | Subtask: "", 70 | Sum: "0", 71 | Task: entry.Task, 72 | Type: "timed", 73 | User: "", 74 | } 75 | 76 | tyme.Data = append(tyme.Data, tymeEntry) 77 | } 78 | 79 | return nil 80 | } 81 | 82 | func (tyme *Tyme) Stringify() string { 83 | stringified, err := json.Marshal(tyme) 84 | if err != nil { 85 | return "" 86 | } 87 | 88 | return string(stringified) 89 | } 90 | -------------------------------------------------------------------------------- /z/util.go: -------------------------------------------------------------------------------- 1 | package z 2 | 3 | import ( 4 | "fmt" 5 | "time" 6 | 7 | "github.com/shopspring/decimal" 8 | ) 9 | 10 | var fractional bool 11 | 12 | func fmtDuration(dur time.Duration) string { 13 | return fmtHours(decimal.NewFromFloat(dur.Hours())) 14 | } 15 | 16 | func fmtHours(hours decimal.Decimal) string { 17 | if fractional { 18 | return hours.StringFixed(2) 19 | } else { 20 | return fmt.Sprintf( 21 | "%s:%02s", 22 | hours.Floor(), // hours 23 | hours.Sub(hours.Floor()). 24 | Mul(decimal.NewFromFloat(.6)). 25 | Mul(decimal.NewFromInt(100)). 26 | Floor()) 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /z/versionCmd.go: -------------------------------------------------------------------------------- 1 | package z 2 | 3 | import ( 4 | "fmt" 5 | 6 | "github.com/spf13/cobra" 7 | ) 8 | 9 | var VERSION string 10 | 11 | func init() { 12 | rootCmd.AddCommand(versionCmd) 13 | } 14 | 15 | var versionCmd = &cobra.Command{ 16 | Use: "version", 17 | Short: "Display what Zeit it is", 18 | Long: `The version of Zeit.`, 19 | Run: func(cmd *cobra.Command, args []string) { 20 | fmt.Println("zeit", VERSION) 21 | }, 22 | } 23 | -------------------------------------------------------------------------------- /zeit.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "github.com/mrusme/zeit/z" 5 | ) 6 | 7 | func main() { 8 | z.Execute() 9 | } 10 | --------------------------------------------------------------------------------