├── .editorconfig ├── .gitignore ├── .travis.yml ├── AUTHORS.rst ├── CONTRIBUTING.rst ├── HISTORY.rst ├── LICENSE ├── MANIFEST.in ├── Makefile ├── README.rst ├── docs ├── Makefile ├── authors.rst ├── conf.py ├── contributing.rst ├── hamster_cli.rst ├── history.rst ├── index.rst ├── installation.rst ├── make.bat ├── modules.rst ├── notes.rst ├── readme.rst └── usage.rst ├── hamster_cli ├── __init__.py ├── hamster_cli.py └── help_strings.py ├── requirements ├── dev.pip ├── docs.pip └── test.pip ├── setup.cfg ├── setup.py ├── tests ├── __init__.py ├── conftest.py ├── factories.py ├── test_hamster_cli.py └── test_integration_tests.py └── tox.ini /.editorconfig: -------------------------------------------------------------------------------- 1 | # http://editorconfig.org 2 | 3 | root = true 4 | 5 | [*] 6 | indent_style = space 7 | indent_size = 4 8 | trim_trailing_whitespace = true 9 | insert_final_newline = true 10 | charset = utf-8 11 | end_of_line = lf 12 | 13 | [*.bat] 14 | indent_style = tab 15 | end_of_line = crlf 16 | 17 | [LICENSE] 18 | insert_final_newline = false 19 | 20 | [Makefile] 21 | indent_style = tab 22 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | env/ 12 | build/ 13 | develop-eggs/ 14 | dist/ 15 | downloads/ 16 | eggs/ 17 | .eggs/ 18 | lib/ 19 | lib64/ 20 | parts/ 21 | sdist/ 22 | var/ 23 | *.egg-info/ 24 | .installed.cfg 25 | *.egg 26 | 27 | # PyInstaller 28 | # Usually these files are written by a python script from a template 29 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 30 | *.manifest 31 | *.spec 32 | 33 | # Installer logs 34 | pip-log.txt 35 | pip-delete-this-directory.txt 36 | 37 | # Unit test / coverage reports 38 | htmlcov/ 39 | .tox/ 40 | .coverage 41 | .coverage.* 42 | .cache 43 | nosetests.xml 44 | coverage.xml 45 | *,cover 46 | .hypothesis/ 47 | 48 | # Translations 49 | *.mo 50 | *.pot 51 | 52 | # Django stuff: 53 | *.log 54 | 55 | # Sphinx documentation 56 | docs/_build/ 57 | 58 | # PyBuilder 59 | target/ 60 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | # Config file for automatic testing at travis-ci.org 2 | # This file will be regenerated if you run travis_pypi_setup.py 3 | 4 | language: python 5 | 6 | env: 7 | - TOXENV=py34 8 | - TOXENV=py27 9 | - TOXENV=flake8 10 | - TOXENV=isort 11 | 12 | before_install: 13 | - pip install codecov 14 | 15 | # command to install dependencies, e.g. pip install -r requirements.txt --use-mirrors 16 | install: 17 | - pip install -U tox codecov 18 | 19 | # command to run tests, e.g. python setup.py test 20 | script: 21 | - make test-all 22 | 23 | after_success: 24 | - codecov 25 | -------------------------------------------------------------------------------- /AUTHORS.rst: -------------------------------------------------------------------------------- 1 | ======= 2 | Credits 3 | ======= 4 | 5 | Development Lead 6 | ---------------- 7 | 8 | * Eric Goller 9 | 10 | Contributors 11 | ------------ 12 | 13 | None yet. Why not be the first? 14 | -------------------------------------------------------------------------------- /CONTRIBUTING.rst: -------------------------------------------------------------------------------- 1 | ============ 2 | Contributing 3 | ============ 4 | 5 | Contributions are welcome, and they are greatly appreciated! Every 6 | little bit helps, and credit will always be given. 7 | 8 | You can contribute in many ways: 9 | 10 | Types of Contributions 11 | ---------------------- 12 | 13 | Report Bugs 14 | ~~~~~~~~~~~ 15 | 16 | Report bugs at https://github.com/elbenfreund/hamster_cli/issues. 17 | 18 | If you are reporting a bug, please include: 19 | 20 | * Your operating system name and version. 21 | * Any details about your local setup that might be helpful in troubleshooting. 22 | * Detailed steps to reproduce the bug. 23 | 24 | Fix Bugs 25 | ~~~~~~~~ 26 | 27 | Look through the GitHub issues for bugs. Anything tagged with "bug" 28 | is open to whoever wants to implement it. 29 | 30 | Implement Features 31 | ~~~~~~~~~~~~~~~~~~ 32 | 33 | Look through the GitHub issues for features. Anything tagged with "feature" 34 | is open to whoever wants to implement it. 35 | 36 | Write Documentation 37 | ~~~~~~~~~~~~~~~~~~~ 38 | 39 | hamster_cli could always use more documentation, whether as part of the 40 | official hamster_cli docs, in docstrings, or even on the web in blog posts, 41 | articles, and such. 42 | 43 | Submit Feedback 44 | ~~~~~~~~~~~~~~~ 45 | 46 | The best way to send feedback is to file an issue at https://github.com/elbenfreund/hamster_cli/issues. 47 | 48 | If you are proposing a feature: 49 | 50 | * Explain in detail how it would work. 51 | * Keep the scope as narrow as possible, to make it easier to implement. 52 | * Remember that this is a volunteer-driven project, and that contributions 53 | are welcome :) 54 | 55 | Get Started! 56 | ------------ 57 | 58 | Ready to contribute? Here's how to set up `hamster_cli` for local development. 59 | 60 | 1. Fork the `hamster_cli` repo on GitHub. 61 | 2. Clone your fork locally:: 62 | 63 | $ git clone git@github.com:your_name_here/hamster_cli.git 64 | 65 | 3. Install your local copy into a virtualenv. Assuming you have virtualenvwrapper installed, this is how you set up your fork for local development:: 66 | 67 | $ mkvirtualenv hamster_cli 68 | $ cd hamster_cli/ 69 | $ make develop 70 | 71 | 4. Create a branch for local development:: 72 | 73 | $ git checkout -b name-of-your-bugfix-or-feature 74 | 75 | Now you can make your changes locally. 76 | 77 | 5. When you're done making changes, check that your changes pass flake8 and the tests, including testing other Python versions with tox:: 78 | 79 | $ make test-all 80 | 81 | To get flake8 and tox, just pip install them into your virtualenv. 82 | 83 | 6. Commit your changes and push your branch to GitHub:: 84 | 85 | $ git add . 86 | $ git commit -m "Your detailed description of your changes." 87 | $ git push origin name-of-your-bugfix-or-feature 88 | 89 | 7. Submit a pull request through the GitHub website. 90 | 91 | Pull Request Guidelines 92 | ----------------------- 93 | 94 | Before you submit a pull request, check that it meets these guidelines: 95 | 96 | 1. The pull request should include tests. 97 | 2. If the pull request adds functionality, the docs should be updated. Put 98 | your new functionality into a function with a docstring, and add the 99 | feature to the list in README.rst. 100 | 3. The pull request should work for Python 2.6, 2.7, 3.3, and 3.4, and for 101 | PyPy. Check https://travis-ci.org/elbenfreund/hamster_cli/pull_requests 102 | and make sure that the tests pass for all supported Python versions. 103 | 104 | Tips 105 | ---- 106 | 107 | To run a subset of tests:: 108 | 109 | $ make test TEST_ARGS="-k NAME_OF_TEST_OR_SUB_MODULE" 110 | 111 | or if you just want to run a particular tox environment:: 112 | 113 | $ tox -e NAMEOVENVORONMENT 114 | 115 | If you want to play around with an executeable version of you modified client:: 116 | 117 | $ cd PATH_TO_CLONED_REPOSITORY 118 | $ mkvirtualenv NAME_OF_SANDBOX_ENV 119 | $ pip install -e . 120 | 121 | This will install your WIP hamster-cli in a wroking state into your sandbox. 122 | Any changes to the codebase will be applied by that version right away. Please 123 | not that any files created by the client will persist even if you uninstall it 124 | or delete the virtualenv. 125 | -------------------------------------------------------------------------------- /HISTORY.rst: -------------------------------------------------------------------------------- 1 | .. :changelog: 2 | 3 | History 4 | ------- 5 | 6 | 0.12.0 (2016-04-25) 7 | ------------------- 8 | * ``stop`` now shows detail on the fact saved. 9 | * ``current`` now shows how much time was accumulated so far. 10 | * Remove standalone script block. You are expected to utilize pip/setuptools to 11 | setup ``hamster_cli``. ``virtualenvs`` FTW! 12 | * Testenvironment now uses linkchecks and ``doc8`` for validating the 13 | documentation. 14 | * Removed 'GTK window' related pseudo methods. Until the functionality is 15 | actually here. 16 | * Added ``manifest`` validation to testenvironment. 17 | * Added ``pep257`` validation to testsuite. 18 | * Vastly improved docstring, docstringcoverage and frontend helptexts. 19 | * Use ``hamsterlib 0.10.0`` new improved config layout. 20 | * Add GPL boilerplate and frontend information. 21 | * ``release`` make target now uses ``twine``. 22 | * Provide new ``details`` command to list basic runtime environment details. 23 | 24 | 0.11.0 (2016-04-16) 25 | -------------------- 26 | * New, solid config handling. 27 | * Switch to `semantic versioning `_. 28 | * Move CI from codeship to Travis-CI. 29 | * First batch of very basic integration tests. 30 | * Several fixes to packaging. 31 | 32 | 0.1.0 (2016-04-09) 33 | --------------------- 34 | * First release on PyPI. 35 | * Prove-of-concept release. 36 | * Most of the basic functionality is there. 37 | * Provides basic test coverage. 38 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Copyright (c) 2015, Eric Goller 2 | All rights reserved. 3 | 4 | 5 | GNU GENERAL PUBLIC LICENSE 6 | Version 3, 29 June 2007 7 | 8 | Copyright (C) 2007 Free Software Foundation, Inc. 9 | Everyone is permitted to copy and distribute verbatim copies 10 | of this license document, but changing it is not allowed. 11 | 12 | Preamble 13 | 14 | The GNU General Public License is a free, copyleft license for 15 | software and other kinds of works. 16 | 17 | The licenses for most software and other practical works are designed 18 | to take away your freedom to share and change the works. By contrast, 19 | the GNU General Public License is intended to guarantee your freedom to 20 | share and change all versions of a program--to make sure it remains free 21 | software for all its users. We, the Free Software Foundation, use the 22 | GNU General Public License for most of our software; it applies also to 23 | any other work released this way by its authors. You can apply it to 24 | your programs, too. 25 | 26 | When we speak of free software, we are referring to freedom, not 27 | price. Our General Public Licenses are designed to make sure that you 28 | have the freedom to distribute copies of free software (and charge for 29 | them if you wish), that you receive source code or can get it if you 30 | want it, that you can change the software or use pieces of it in new 31 | free programs, and that you know you can do these things. 32 | 33 | To protect your rights, we need to prevent others from denying you 34 | these rights or asking you to surrender the rights. Therefore, you have 35 | certain responsibilities if you distribute copies of the software, or if 36 | you modify it: responsibilities to respect the freedom of others. 37 | 38 | For example, if you distribute copies of such a program, whether 39 | gratis or for a fee, you must pass on to the recipients the same 40 | freedoms that you received. You must make sure that they, too, receive 41 | or can get the source code. And you must show them these terms so they 42 | know their rights. 43 | 44 | Developers that use the GNU GPL protect your rights with two steps: 45 | (1) assert copyright on the software, and (2) offer you this License 46 | giving you legal permission to copy, distribute and/or modify it. 47 | 48 | For the developers' and authors' protection, the GPL clearly explains 49 | that there is no warranty for this free software. For both users' and 50 | authors' sake, the GPL requires that modified versions be marked as 51 | changed, so that their problems will not be attributed erroneously to 52 | authors of previous versions. 53 | 54 | Some devices are designed to deny users access to install or run 55 | modified versions of the software inside them, although the manufacturer 56 | can do so. This is fundamentally incompatible with the aim of 57 | protecting users' freedom to change the software. The systematic 58 | pattern of such abuse occurs in the area of products for individuals to 59 | use, which is precisely where it is most unacceptable. Therefore, we 60 | have designed this version of the GPL to prohibit the practice for those 61 | products. If such problems arise substantially in other domains, we 62 | stand ready to extend this provision to those domains in future versions 63 | of the GPL, as needed to protect the freedom of users. 64 | 65 | Finally, every program is threatened constantly by software patents. 66 | States should not allow patents to restrict development and use of 67 | software on general-purpose computers, but in those that do, we wish to 68 | avoid the special danger that patents applied to a free program could 69 | make it effectively proprietary. To prevent this, the GPL assures that 70 | patents cannot be used to render the program non-free. 71 | 72 | The precise terms and conditions for copying, distribution and 73 | modification follow. 74 | 75 | TERMS AND CONDITIONS 76 | 77 | 0. Definitions. 78 | 79 | "This License" refers to version 3 of the GNU General Public License. 80 | 81 | "Copyright" also means copyright-like laws that apply to other kinds of 82 | works, such as semiconductor masks. 83 | 84 | "The Program" refers to any copyrightable work licensed under this 85 | License. Each licensee is addressed as "you". "Licensees" and 86 | "recipients" may be individuals or organizations. 87 | 88 | To "modify" a work means to copy from or adapt all or part of the work 89 | in a fashion requiring copyright permission, other than the making of an 90 | exact copy. The resulting work is called a "modified version" of the 91 | earlier work or a work "based on" the earlier work. 92 | 93 | A "covered work" means either the unmodified Program or a work based 94 | on the Program. 95 | 96 | To "propagate" a work means to do anything with it that, without 97 | permission, would make you directly or secondarily liable for 98 | infringement under applicable copyright law, except executing it on a 99 | computer or modifying a private copy. Propagation includes copying, 100 | distribution (with or without modification), making available to the 101 | public, and in some countries other activities as well. 102 | 103 | To "convey" a work means any kind of propagation that enables other 104 | parties to make or receive copies. Mere interaction with a user through 105 | a computer network, with no transfer of a copy, is not conveying. 106 | 107 | An interactive user interface displays "Appropriate Legal Notices" 108 | to the extent that it includes a convenient and prominently visible 109 | feature that (1) displays an appropriate copyright notice, and (2) 110 | tells the user that there is no warranty for the work (except to the 111 | extent that warranties are provided), that licensees may convey the 112 | work under this License, and how to view a copy of this License. If 113 | the interface presents a list of user commands or options, such as a 114 | menu, a prominent item in the list meets this criterion. 115 | 116 | 1. Source Code. 117 | 118 | The "source code" for a work means the preferred form of the work 119 | for making modifications to it. "Object code" means any non-source 120 | form of a work. 121 | 122 | A "Standard Interface" means an interface that either is an official 123 | standard defined by a recognized standards body, or, in the case of 124 | interfaces specified for a particular programming language, one that 125 | is widely used among developers working in that language. 126 | 127 | The "System Libraries" of an executable work include anything, other 128 | than the work as a whole, that (a) is included in the normal form of 129 | packaging a Major Component, but which is not part of that Major 130 | Component, and (b) serves only to enable use of the work with that 131 | Major Component, or to implement a Standard Interface for which an 132 | implementation is available to the public in source code form. A 133 | "Major Component", in this context, means a major essential component 134 | (kernel, window system, and so on) of the specific operating system 135 | (if any) on which the executable work runs, or a compiler used to 136 | produce the work, or an object code interpreter used to run it. 137 | 138 | The "Corresponding Source" for a work in object code form means all 139 | the source code needed to generate, install, and (for an executable 140 | work) run the object code and to modify the work, including scripts to 141 | control those activities. However, it does not include the work's 142 | System Libraries, or general-purpose tools or generally available free 143 | programs which are used unmodified in performing those activities but 144 | which are not part of the work. For example, Corresponding Source 145 | includes interface definition files associated with source files for 146 | the work, and the source code for shared libraries and dynamically 147 | linked subprograms that the work is specifically designed to require, 148 | such as by intimate data communication or control flow between those 149 | subprograms and other parts of the work. 150 | 151 | The Corresponding Source need not include anything that users 152 | can regenerate automatically from other parts of the Corresponding 153 | Source. 154 | 155 | The Corresponding Source for a work in source code form is that 156 | same work. 157 | 158 | 2. Basic Permissions. 159 | 160 | All rights granted under this License are granted for the term of 161 | copyright on the Program, and are irrevocable provided the stated 162 | conditions are met. This License explicitly affirms your unlimited 163 | permission to run the unmodified Program. The output from running a 164 | covered work is covered by this License only if the output, given its 165 | content, constitutes a covered work. This License acknowledges your 166 | rights of fair use or other equivalent, as provided by copyright law. 167 | 168 | You may make, run and propagate covered works that you do not 169 | convey, without conditions so long as your license otherwise remains 170 | in force. You may convey covered works to others for the sole purpose 171 | of having them make modifications exclusively for you, or provide you 172 | with facilities for running those works, provided that you comply with 173 | the terms of this License in conveying all material for which you do 174 | not control copyright. Those thus making or running the covered works 175 | for you must do so exclusively on your behalf, under your direction 176 | and control, on terms that prohibit them from making any copies of 177 | your copyrighted material outside their relationship with you. 178 | 179 | Conveying under any other circumstances is permitted solely under 180 | the conditions stated below. Sublicensing is not allowed; section 10 181 | makes it unnecessary. 182 | 183 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 184 | 185 | No covered work shall be deemed part of an effective technological 186 | measure under any applicable law fulfilling obligations under article 187 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 188 | similar laws prohibiting or restricting circumvention of such 189 | measures. 190 | 191 | When you convey a covered work, you waive any legal power to forbid 192 | circumvention of technological measures to the extent such circumvention 193 | is effected by exercising rights under this License with respect to 194 | the covered work, and you disclaim any intention to limit operation or 195 | modification of the work as a means of enforcing, against the work's 196 | users, your or third parties' legal rights to forbid circumvention of 197 | technological measures. 198 | 199 | 4. Conveying Verbatim Copies. 200 | 201 | You may convey verbatim copies of the Program's source code as you 202 | receive it, in any medium, provided that you conspicuously and 203 | appropriately publish on each copy an appropriate copyright notice; 204 | keep intact all notices stating that this License and any 205 | non-permissive terms added in accord with section 7 apply to the code; 206 | keep intact all notices of the absence of any warranty; and give all 207 | recipients a copy of this License along with the Program. 208 | 209 | You may charge any price or no price for each copy that you convey, 210 | and you may offer support or warranty protection for a fee. 211 | 212 | 5. Conveying Modified Source Versions. 213 | 214 | You may convey a work based on the Program, or the modifications to 215 | produce it from the Program, in the form of source code under the 216 | terms of section 4, provided that you also meet all of these conditions: 217 | 218 | a) The work must carry prominent notices stating that you modified 219 | it, and giving a relevant date. 220 | 221 | b) The work must carry prominent notices stating that it is 222 | released under this License and any conditions added under section 223 | 7. This requirement modifies the requirement in section 4 to 224 | "keep intact all notices". 225 | 226 | c) You must license the entire work, as a whole, under this 227 | License to anyone who comes into possession of a copy. This 228 | License will therefore apply, along with any applicable section 7 229 | additional terms, to the whole of the work, and all its parts, 230 | regardless of how they are packaged. This License gives no 231 | permission to license the work in any other way, but it does not 232 | invalidate such permission if you have separately received it. 233 | 234 | d) If the work has interactive user interfaces, each must display 235 | Appropriate Legal Notices; however, if the Program has interactive 236 | interfaces that do not display Appropriate Legal Notices, your 237 | work need not make them do so. 238 | 239 | A compilation of a covered work with other separate and independent 240 | works, which are not by their nature extensions of the covered work, 241 | and which are not combined with it such as to form a larger program, 242 | in or on a volume of a storage or distribution medium, is called an 243 | "aggregate" if the compilation and its resulting copyright are not 244 | used to limit the access or legal rights of the compilation's users 245 | beyond what the individual works permit. Inclusion of a covered work 246 | in an aggregate does not cause this License to apply to the other 247 | parts of the aggregate. 248 | 249 | 6. Conveying Non-Source Forms. 250 | 251 | You may convey a covered work in object code form under the terms 252 | of sections 4 and 5, provided that you also convey the 253 | machine-readable Corresponding Source under the terms of this License, 254 | in one of these ways: 255 | 256 | a) Convey the object code in, or embodied in, a physical product 257 | (including a physical distribution medium), accompanied by the 258 | Corresponding Source fixed on a durable physical medium 259 | customarily used for software interchange. 260 | 261 | b) Convey the object code in, or embodied in, a physical product 262 | (including a physical distribution medium), accompanied by a 263 | written offer, valid for at least three years and valid for as 264 | long as you offer spare parts or customer support for that product 265 | model, to give anyone who possesses the object code either (1) a 266 | copy of the Corresponding Source for all the software in the 267 | product that is covered by this License, on a durable physical 268 | medium customarily used for software interchange, for a price no 269 | more than your reasonable cost of physically performing this 270 | conveying of source, or (2) access to copy the 271 | Corresponding Source from a network server at no charge. 272 | 273 | c) Convey individual copies of the object code with a copy of the 274 | written offer to provide the Corresponding Source. This 275 | alternative is allowed only occasionally and noncommercially, and 276 | only if you received the object code with such an offer, in accord 277 | with subsection 6b. 278 | 279 | d) Convey the object code by offering access from a designated 280 | place (gratis or for a charge), and offer equivalent access to the 281 | Corresponding Source in the same way through the same place at no 282 | further charge. You need not require recipients to copy the 283 | Corresponding Source along with the object code. If the place to 284 | copy the object code is a network server, the Corresponding Source 285 | may be on a different server (operated by you or a third party) 286 | that supports equivalent copying facilities, provided you maintain 287 | clear directions next to the object code saying where to find the 288 | Corresponding Source. Regardless of what server hosts the 289 | Corresponding Source, you remain obligated to ensure that it is 290 | available for as long as needed to satisfy these requirements. 291 | 292 | e) Convey the object code using peer-to-peer transmission, provided 293 | you inform other peers where the object code and Corresponding 294 | Source of the work are being offered to the general public at no 295 | charge under subsection 6d. 296 | 297 | A separable portion of the object code, whose source code is excluded 298 | from the Corresponding Source as a System Library, need not be 299 | included in conveying the object code work. 300 | 301 | A "User Product" is either (1) a "consumer product", which means any 302 | tangible personal property which is normally used for personal, family, 303 | or household purposes, or (2) anything designed or sold for incorporation 304 | into a dwelling. In determining whether a product is a consumer product, 305 | doubtful cases shall be resolved in favor of coverage. For a particular 306 | product received by a particular user, "normally used" refers to a 307 | typical or common use of that class of product, regardless of the status 308 | of the particular user or of the way in which the particular user 309 | actually uses, or expects or is expected to use, the product. A product 310 | is a consumer product regardless of whether the product has substantial 311 | commercial, industrial or non-consumer uses, unless such uses represent 312 | the only significant mode of use of the product. 313 | 314 | "Installation Information" for a User Product means any methods, 315 | procedures, authorization keys, or other information required to install 316 | and execute modified versions of a covered work in that User Product from 317 | a modified version of its Corresponding Source. The information must 318 | suffice to ensure that the continued functioning of the modified object 319 | code is in no case prevented or interfered with solely because 320 | modification has been made. 321 | 322 | If you convey an object code work under this section in, or with, or 323 | specifically for use in, a User Product, and the conveying occurs as 324 | part of a transaction in which the right of possession and use of the 325 | User Product is transferred to the recipient in perpetuity or for a 326 | fixed term (regardless of how the transaction is characterized), the 327 | Corresponding Source conveyed under this section must be accompanied 328 | by the Installation Information. But this requirement does not apply 329 | if neither you nor any third party retains the ability to install 330 | modified object code on the User Product (for example, the work has 331 | been installed in ROM). 332 | 333 | The requirement to provide Installation Information does not include a 334 | requirement to continue to provide support service, warranty, or updates 335 | for a work that has been modified or installed by the recipient, or for 336 | the User Product in which it has been modified or installed. Access to a 337 | network may be denied when the modification itself materially and 338 | adversely affects the operation of the network or violates the rules and 339 | protocols for communication across the network. 340 | 341 | Corresponding Source conveyed, and Installation Information provided, 342 | in accord with this section must be in a format that is publicly 343 | documented (and with an implementation available to the public in 344 | source code form), and must require no special password or key for 345 | unpacking, reading or copying. 346 | 347 | 7. Additional Terms. 348 | 349 | "Additional permissions" are terms that supplement the terms of this 350 | License by making exceptions from one or more of its conditions. 351 | Additional permissions that are applicable to the entire Program shall 352 | be treated as though they were included in this License, to the extent 353 | that they are valid under applicable law. If additional permissions 354 | apply only to part of the Program, that part may be used separately 355 | under those permissions, but the entire Program remains governed by 356 | this License without regard to the additional permissions. 357 | 358 | When you convey a copy of a covered work, you may at your option 359 | remove any additional permissions from that copy, or from any part of 360 | it. (Additional permissions may be written to require their own 361 | removal in certain cases when you modify the work.) You may place 362 | additional permissions on material, added by you to a covered work, 363 | for which you have or can give appropriate copyright permission. 364 | 365 | Notwithstanding any other provision of this License, for material you 366 | add to a covered work, you may (if authorized by the copyright holders of 367 | that material) supplement the terms of this License with terms: 368 | 369 | a) Disclaiming warranty or limiting liability differently from the 370 | terms of sections 15 and 16 of this License; or 371 | 372 | b) Requiring preservation of specified reasonable legal notices or 373 | author attributions in that material or in the Appropriate Legal 374 | Notices displayed by works containing it; or 375 | 376 | c) Prohibiting misrepresentation of the origin of that material, or 377 | requiring that modified versions of such material be marked in 378 | reasonable ways as different from the original version; or 379 | 380 | d) Limiting the use for publicity purposes of names of licensors or 381 | authors of the material; or 382 | 383 | e) Declining to grant rights under trademark law for use of some 384 | trade names, trademarks, or service marks; or 385 | 386 | f) Requiring indemnification of licensors and authors of that 387 | material by anyone who conveys the material (or modified versions of 388 | it) with contractual assumptions of liability to the recipient, for 389 | any liability that these contractual assumptions directly impose on 390 | those licensors and authors. 391 | 392 | All other non-permissive additional terms are considered "further 393 | restrictions" within the meaning of section 10. If the Program as you 394 | received it, or any part of it, contains a notice stating that it is 395 | governed by this License along with a term that is a further 396 | restriction, you may remove that term. If a license document contains 397 | a further restriction but permits relicensing or conveying under this 398 | License, you may add to a covered work material governed by the terms 399 | of that license document, provided that the further restriction does 400 | not survive such relicensing or conveying. 401 | 402 | If you add terms to a covered work in accord with this section, you 403 | must place, in the relevant source files, a statement of the 404 | additional terms that apply to those files, or a notice indicating 405 | where to find the applicable terms. 406 | 407 | Additional terms, permissive or non-permissive, may be stated in the 408 | form of a separately written license, or stated as exceptions; 409 | the above requirements apply either way. 410 | 411 | 8. Termination. 412 | 413 | You may not propagate or modify a covered work except as expressly 414 | provided under this License. Any attempt otherwise to propagate or 415 | modify it is void, and will automatically terminate your rights under 416 | this License (including any patent licenses granted under the third 417 | paragraph of section 11). 418 | 419 | However, if you cease all violation of this License, then your 420 | license from a particular copyright holder is reinstated (a) 421 | provisionally, unless and until the copyright holder explicitly and 422 | finally terminates your license, and (b) permanently, if the copyright 423 | holder fails to notify you of the violation by some reasonable means 424 | prior to 60 days after the cessation. 425 | 426 | Moreover, your license from a particular copyright holder is 427 | reinstated permanently if the copyright holder notifies you of the 428 | violation by some reasonable means, this is the first time you have 429 | received notice of violation of this License (for any work) from that 430 | copyright holder, and you cure the violation prior to 30 days after 431 | your receipt of the notice. 432 | 433 | Termination of your rights under this section does not terminate the 434 | licenses of parties who have received copies or rights from you under 435 | this License. If your rights have been terminated and not permanently 436 | reinstated, you do not qualify to receive new licenses for the same 437 | material under section 10. 438 | 439 | 9. Acceptance Not Required for Having Copies. 440 | 441 | You are not required to accept this License in order to receive or 442 | run a copy of the Program. Ancillary propagation of a covered work 443 | occurring solely as a consequence of using peer-to-peer transmission 444 | to receive a copy likewise does not require acceptance. However, 445 | nothing other than this License grants you permission to propagate or 446 | modify any covered work. These actions infringe copyright if you do 447 | not accept this License. Therefore, by modifying or propagating a 448 | covered work, you indicate your acceptance of this License to do so. 449 | 450 | 10. Automatic Licensing of Downstream Recipients. 451 | 452 | Each time you convey a covered work, the recipient automatically 453 | receives a license from the original licensors, to run, modify and 454 | propagate that work, subject to this License. You are not responsible 455 | for enforcing compliance by third parties with this License. 456 | 457 | An "entity transaction" is a transaction transferring control of an 458 | organization, or substantially all assets of one, or subdividing an 459 | organization, or merging organizations. If propagation of a covered 460 | work results from an entity transaction, each party to that 461 | transaction who receives a copy of the work also receives whatever 462 | licenses to the work the party's predecessor in interest had or could 463 | give under the previous paragraph, plus a right to possession of the 464 | Corresponding Source of the work from the predecessor in interest, if 465 | the predecessor has it or can get it with reasonable efforts. 466 | 467 | You may not impose any further restrictions on the exercise of the 468 | rights granted or affirmed under this License. For example, you may 469 | not impose a license fee, royalty, or other charge for exercise of 470 | rights granted under this License, and you may not initiate litigation 471 | (including a cross-claim or counterclaim in a lawsuit) alleging that 472 | any patent claim is infringed by making, using, selling, offering for 473 | sale, or importing the Program or any portion of it. 474 | 475 | 11. Patents. 476 | 477 | A "contributor" is a copyright holder who authorizes use under this 478 | License of the Program or a work on which the Program is based. The 479 | work thus licensed is called the contributor's "contributor version". 480 | 481 | A contributor's "essential patent claims" are all patent claims 482 | owned or controlled by the contributor, whether already acquired or 483 | hereafter acquired, that would be infringed by some manner, permitted 484 | by this License, of making, using, or selling its contributor version, 485 | but do not include claims that would be infringed only as a 486 | consequence of further modification of the contributor version. For 487 | purposes of this definition, "control" includes the right to grant 488 | patent sublicenses in a manner consistent with the requirements of 489 | this License. 490 | 491 | Each contributor grants you a non-exclusive, worldwide, royalty-free 492 | patent license under the contributor's essential patent claims, to 493 | make, use, sell, offer for sale, import and otherwise run, modify and 494 | propagate the contents of its contributor version. 495 | 496 | In the following three paragraphs, a "patent license" is any express 497 | agreement or commitment, however denominated, not to enforce a patent 498 | (such as an express permission to practice a patent or covenant not to 499 | sue for patent infringement). To "grant" such a patent license to a 500 | party means to make such an agreement or commitment not to enforce a 501 | patent against the party. 502 | 503 | If you convey a covered work, knowingly relying on a patent license, 504 | and the Corresponding Source of the work is not available for anyone 505 | to copy, free of charge and under the terms of this License, through a 506 | publicly available network server or other readily accessible means, 507 | then you must either (1) cause the Corresponding Source to be so 508 | available, or (2) arrange to deprive yourself of the benefit of the 509 | patent license for this particular work, or (3) arrange, in a manner 510 | consistent with the requirements of this License, to extend the patent 511 | license to downstream recipients. "Knowingly relying" means you have 512 | actual knowledge that, but for the patent license, your conveying the 513 | covered work in a country, or your recipient's use of the covered work 514 | in a country, would infringe one or more identifiable patents in that 515 | country that you have reason to believe are valid. 516 | 517 | If, pursuant to or in connection with a single transaction or 518 | arrangement, you convey, or propagate by procuring conveyance of, a 519 | covered work, and grant a patent license to some of the parties 520 | receiving the covered work authorizing them to use, propagate, modify 521 | or convey a specific copy of the covered work, then the patent license 522 | you grant is automatically extended to all recipients of the covered 523 | work and works based on it. 524 | 525 | A patent license is "discriminatory" if it does not include within 526 | the scope of its coverage, prohibits the exercise of, or is 527 | conditioned on the non-exercise of one or more of the rights that are 528 | specifically granted under this License. You may not convey a covered 529 | work if you are a party to an arrangement with a third party that is 530 | in the business of distributing software, under which you make payment 531 | to the third party based on the extent of your activity of conveying 532 | the work, and under which the third party grants, to any of the 533 | parties who would receive the covered work from you, a discriminatory 534 | patent license (a) in connection with copies of the covered work 535 | conveyed by you (or copies made from those copies), or (b) primarily 536 | for and in connection with specific products or compilations that 537 | contain the covered work, unless you entered into that arrangement, 538 | or that patent license was granted, prior to 28 March 2007. 539 | 540 | Nothing in this License shall be construed as excluding or limiting 541 | any implied license or other defenses to infringement that may 542 | otherwise be available to you under applicable patent law. 543 | 544 | 12. No Surrender of Others' Freedom. 545 | 546 | If conditions are imposed on you (whether by court order, agreement or 547 | otherwise) that contradict the conditions of this License, they do not 548 | excuse you from the conditions of this License. If you cannot convey a 549 | covered work so as to satisfy simultaneously your obligations under this 550 | License and any other pertinent obligations, then as a consequence you may 551 | not convey it at all. For example, if you agree to terms that obligate you 552 | to collect a royalty for further conveying from those to whom you convey 553 | the Program, the only way you could satisfy both those terms and this 554 | License would be to refrain entirely from conveying the Program. 555 | 556 | 13. Use with the GNU Affero General Public License. 557 | 558 | Notwithstanding any other provision of this License, you have 559 | permission to link or combine any covered work with a work licensed 560 | under version 3 of the GNU Affero General Public License into a single 561 | combined work, and to convey the resulting work. The terms of this 562 | License will continue to apply to the part which is the covered work, 563 | but the special requirements of the GNU Affero General Public License, 564 | section 13, concerning interaction through a network will apply to the 565 | combination as such. 566 | 567 | 14. Revised Versions of this License. 568 | 569 | The Free Software Foundation may publish revised and/or new versions of 570 | the GNU General Public License from time to time. Such new versions will 571 | be similar in spirit to the present version, but may differ in detail to 572 | address new problems or concerns. 573 | 574 | Each version is given a distinguishing version number. If the 575 | Program specifies that a certain numbered version of the GNU General 576 | Public License "or any later version" applies to it, you have the 577 | option of following the terms and conditions either of that numbered 578 | version or of any later version published by the Free Software 579 | Foundation. If the Program does not specify a version number of the 580 | GNU General Public License, you may choose any version ever published 581 | by the Free Software Foundation. 582 | 583 | If the Program specifies that a proxy can decide which future 584 | versions of the GNU General Public License can be used, that proxy's 585 | public statement of acceptance of a version permanently authorizes you 586 | to choose that version for the Program. 587 | 588 | Later license versions may give you additional or different 589 | permissions. However, no additional obligations are imposed on any 590 | author or copyright holder as a result of your choosing to follow a 591 | later version. 592 | 593 | 15. Disclaimer of Warranty. 594 | 595 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 596 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 597 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 598 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 599 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 600 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 601 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 602 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 603 | 604 | 16. Limitation of Liability. 605 | 606 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 607 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 608 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 609 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 610 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 611 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 612 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 613 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 614 | SUCH DAMAGES. 615 | 616 | 17. Interpretation of Sections 15 and 16. 617 | 618 | If the disclaimer of warranty and limitation of liability provided 619 | above cannot be given local legal effect according to their terms, 620 | reviewing courts shall apply local law that most closely approximates 621 | an absolute waiver of all civil liability in connection with the 622 | Program, unless a warranty or assumption of liability accompanies a 623 | copy of the Program in return for a fee. 624 | 625 | END OF TERMS AND CONDITIONS 626 | 627 | How to Apply These Terms to Your New Programs 628 | 629 | If you develop a new program, and you want it to be of the greatest 630 | possible use to the public, the best way to achieve this is to make it 631 | free software which everyone can redistribute and change under these terms. 632 | 633 | To do so, attach the following notices to the program. It is safest 634 | to attach them to the start of each source file to most effectively 635 | state the exclusion of warranty; and each file should have at least 636 | the "copyright" line and a pointer to where the full notice is found. 637 | 638 | 639 | Copyright (C) 640 | 641 | This program is free software: you can redistribute it and/or modify 642 | it under the terms of the GNU General Public License as published by 643 | the Free Software Foundation, either version 3 of the License, or 644 | (at your option) any later version. 645 | 646 | This program is distributed in the hope that it will be useful, 647 | but WITHOUT ANY WARRANTY; without even the implied warranty of 648 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 649 | GNU General Public License for more details. 650 | 651 | You should have received a copy of the GNU General Public License 652 | along with this program. If not, see . 653 | 654 | Also add information on how to contact you by electronic and paper mail. 655 | 656 | If the program does terminal interaction, make it output a short 657 | notice like this when it starts in an interactive mode: 658 | 659 | Copyright (C) 660 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 661 | This is free software, and you are welcome to redistribute it 662 | under certain conditions; type `show c' for details. 663 | 664 | The hypothetical commands `show w' and `show c' should show the appropriate 665 | parts of the General Public License. Of course, your program's commands 666 | might be different; for a GUI interface, you would use an "about box". 667 | 668 | You should also get your employer (if you work as a programmer) or school, 669 | if any, to sign a "copyright disclaimer" for the program, if necessary. 670 | For more information on this, and how to apply and follow the GNU GPL, see 671 | . 672 | 673 | The GNU General Public License does not permit incorporating your program 674 | into proprietary programs. If your program is a subroutine library, you 675 | may consider it more useful to permit linking proprietary applications with 676 | the library. If this is what you want to do, use the GNU Lesser General 677 | Public License instead of this License. But first, please read 678 | . 679 | -------------------------------------------------------------------------------- /MANIFEST.in: -------------------------------------------------------------------------------- 1 | include AUTHORS.rst 2 | include CONTRIBUTING.rst 3 | include HISTORY.rst 4 | include LICENSE 5 | include README.rst 6 | include Makefile 7 | include tox.ini 8 | 9 | 10 | recursive-include tests * 11 | recursive-include requirements *.txt 12 | recursive-include docs *.rst conf.py Makefile make.bat 13 | 14 | 15 | exclude .editorconfig 16 | recursive-exclude * __pycache__ 17 | recursive-exclude * *.py[co] 18 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | BUILDDIR = _build 2 | 3 | .PHONY: clean-pyc clean-build docs clean 4 | 5 | define BROWSER_PYSCRIPT 6 | import os, webbrowser, sys 7 | try: 8 | from urllib import pathname2url 9 | except: 10 | from urllib.request import pathname2url 11 | 12 | webbrowser.open("file://" + pathname2url(os.path.abspath(sys.argv[1]))) 13 | endef 14 | export BROWSER_PYSCRIPT 15 | 16 | BROWSER := python -c "$$BROWSER_PYSCRIPT" 17 | 18 | help: 19 | @echo "Please use 'make ' where is one of" 20 | @echo " clean to remove all build, test, coverage and Python artifacts" 21 | @echo " clean-build to remove build artifacts" 22 | @echo " clean-pyc to remove Python file artifacts" 23 | @echo " clean-docs" 24 | @echo " clean-test to remove test and coverage artifacts" 25 | @echo " lint to check style with flake8" 26 | @echo " test to run tests quickly with the default Python" 27 | @echo " test-all to run tests on every Python version with tox" 28 | @echo " coverage to check code coverage quickly with the default Python" 29 | @echo " coverage-html" 30 | @echo " develop to install (or update) all packages required for development" 31 | @echo " docs to generate Sphinx HTML documentation, including API docs" 32 | @echo " isort to run isort on the whole project." 33 | @echo " release to package and upload a release" 34 | @echo " dist to package" 35 | @echo " install to install the package to the active Python's site-packages" 36 | 37 | clean: clean-build clean-pyc clean-test 38 | 39 | clean-build: 40 | rm -fr build/ 41 | rm -fr dist/ 42 | rm -fr .eggs/ 43 | find . -name '*.egg-info' -exec rm -fr {} + 44 | find . -name '*.egg' -exec rm -f {} + 45 | 46 | clean-pyc: 47 | find . -name '*.pyc' -exec rm -f {} + 48 | find . -name '*.pyo' -exec rm -f {} + 49 | find . -name '*~' -exec rm -f {} + 50 | find . -name '__pycache__' -exec rm -fr {} + 51 | 52 | clean-docs: 53 | $(MAKE) -C docs clean BUILDDIR=$(BUILDDIR) 54 | 55 | clean-test: 56 | rm -fr .tox/ 57 | rm -f .coverage 58 | rm -fr htmlcov/ 59 | 60 | develop: 61 | pip install -U pip setuptools wheel 62 | pip install -U -e . 63 | pip install -U -r requirements/dev.txt 64 | 65 | lint: 66 | flake8 hamster_cli tests 67 | 68 | test: 69 | py.test $(TEST_ARGS) tests/ 70 | 71 | test-all: 72 | tox 73 | 74 | coverage: 75 | coverage run -m pytest $(TEST_ARGS) tests 76 | coverage report 77 | 78 | coverage-html: coverage 79 | coverage html 80 | $(BROWSER) htmlcov/index.html 81 | 82 | docs: 83 | rm -f docs/hamster_cli.rst 84 | rm -f docs/modules.rst 85 | sphinx-apidoc -o docs/ hamster_cli 86 | $(MAKE) -C docs clean 87 | $(MAKE) -C docs html 88 | $(BROWSER) docs/_build/html/index.html 89 | 90 | isort: 91 | isort --recursive setup.py hamster_cli/ tests/ 92 | 93 | 94 | servedocs: docs 95 | watchmedo shell-command -p '*.rst' -c '$(MAKE) -C docs html' -R -D . 96 | 97 | release: clean 98 | python setup.py sdist bdist_wheel 99 | twine upload -r pypi -s dist/* 100 | 101 | dist: clean 102 | python setup.py sdist 103 | python setup.py bdist_wheel 104 | ls -l dist 105 | 106 | install: clean 107 | python setup.py install 108 | -------------------------------------------------------------------------------- /README.rst: -------------------------------------------------------------------------------- 1 | =============================== 2 | hamster_cli 3 | =============================== 4 | 5 | .. image:: https://img.shields.io/pypi/v/hamster_cli.svg 6 | :target: https://pypi.python.org/pypi/hamster_cli 7 | 8 | .. image:: https://img.shields.io/travis/elbenfreund/hamster_cli/master.svg 9 | :target: https://travis-ci.org/elbenfreund/hamster_cli 10 | 11 | .. image:: https://img.shields.io/codecov/c/gh/projecthamster/hamster_cli/master.svg 12 | :target: https://codecov.io/gh/projecthamster/hamster-cli 13 | 14 | .. image:: https://readthedocs.org/projects/hamst-cli/badge/?version=master 15 | :target: https://readthedocs.org/projects/hamst-cli/badge/?version=master 16 | :alt: Documentation Status 17 | 18 | .. image:: https://badge.waffle.io/elbenfreund/hamster_cli.png?label=ready&title=Ready 19 | :target: https://waffle.io/elbenfreund/hamster_cli 20 | :alt: 'Stories in Ready' 21 | 22 | .. image:: https://requires.io/github/elbenfreund/hamster_cli/requirements.svg?branch=master 23 | :target: https://requires.io/github/elbenfreund/hamster_cli/requirements/?branch=master 24 | :alt: Requirements Status 25 | 26 | 27 | 28 | A basic CLI for the hamster time tracker. 29 | 30 | *WARNING* 31 | This is still pre-alpha software. Altough we are reaching apoint were most 32 | things work as intended we make no promisse about your data as well as any 33 | commitment. In particular there is no intension to migrate any databases from 34 | this version to any future more mature release. 35 | 36 | News (2016-04-25) 37 | ----------------- 38 | Version 0.12.0 is out! With this version we feel confident that you may be able 39 | to actually play with ``hamster-cli`` in a somewhat productive way. Whilst we 40 | are still far from being production ready and miss a significant amount of 41 | legacy feature this release may give you quite the idea where we are heading. 42 | For the first time we were able to give the frontend some love whilst further 43 | beefin up our QA toolchain, introducing even more tests and new test 44 | environments. The documentation has been vastly improved, digging into the code 45 | never was easier. 46 | 47 | Happy hacking; Eric. 48 | 49 | Features 50 | -------- 51 | * High test coverage. 52 | * Well documented. 53 | * Lightweight. 54 | * Free software: GPL3 55 | * Uses ``hamsterlib``, which supports a wide array of databases. 56 | * Few dependencies 57 | * Active development. 58 | 59 | Resources 60 | ----------- 61 | * `Documentation `_ 62 | 63 | Credits 64 | --------- 65 | Tools used in rendering this package: 66 | 67 | * Cookiecutter_ 68 | * `cookiecutter-pypackage`_ 69 | 70 | .. _Cookiecutter: https://github.com/audreyr/cookiecutter 71 | .. _`cookiecutter-pypackage`: https://github.com/audreyr/cookiecutter-pypackage 72 | -------------------------------------------------------------------------------- /docs/Makefile: -------------------------------------------------------------------------------- 1 | # Makefile for Sphinx documentation 2 | # 3 | 4 | # You can set these variables from the command line. 5 | SPHINXOPTS = 6 | SPHINXBUILD = sphinx-build 7 | PAPER = 8 | BUILDDIR = _build 9 | 10 | # User-friendly check for sphinx-build 11 | ifeq ($(shell which $(SPHINXBUILD) >/dev/null 2>&1; echo $$?), 1) 12 | $(error The '$(SPHINXBUILD)' command was not found. Make sure you have Sphinx installed, then set the SPHINXBUILD environment variable to point to the full path of the '$(SPHINXBUILD)' executable. Alternatively you can add the directory with the executable to your PATH. If you don't have Sphinx installed, grab it from http://sphinx-doc.org/) 13 | endif 14 | 15 | # Internal variables. 16 | PAPEROPT_a4 = -D latex_paper_size=a4 17 | PAPEROPT_letter = -D latex_paper_size=letter 18 | ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . 19 | # the i18n builder cannot share the environment and doctrees with the others 20 | I18NSPHINXOPTS = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . 21 | 22 | .PHONY: help clean html dirhtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest gettext 23 | 24 | help: 25 | @echo "Please use \`make ' where is one of" 26 | @echo " html to make standalone HTML files" 27 | @echo " dirhtml to make HTML files named index.html in directories" 28 | @echo " singlehtml to make a single large HTML file" 29 | @echo " pickle to make pickle files" 30 | @echo " json to make JSON files" 31 | @echo " htmlhelp to make HTML files and a HTML help project" 32 | @echo " qthelp to make HTML files and a qthelp project" 33 | @echo " devhelp to make HTML files and a Devhelp project" 34 | @echo " epub to make an epub" 35 | @echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter" 36 | @echo " latexpdf to make LaTeX files and run them through pdflatex" 37 | @echo " latexpdfja to make LaTeX files and run them through platex/dvipdfmx" 38 | @echo " text to make text files" 39 | @echo " man to make manual pages" 40 | @echo " texinfo to make Texinfo files" 41 | @echo " info to make Texinfo files and run them through makeinfo" 42 | @echo " gettext to make PO message catalogs" 43 | @echo " changes to make an overview of all changed/added/deprecated items" 44 | @echo " xml to make Docutils-native XML files" 45 | @echo " pseudoxml to make pseudoxml-XML files for display purposes" 46 | @echo " linkcheck to check all external links for integrity" 47 | @echo " doctest to run all doctests embedded in the documentation (if enabled)" 48 | 49 | clean: 50 | rm -rf $(BUILDDIR)/* 51 | 52 | html: 53 | $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html 54 | @echo 55 | @echo "Build finished. The HTML pages are in $(BUILDDIR)/html." 56 | 57 | dirhtml: 58 | $(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml 59 | @echo 60 | @echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml." 61 | 62 | singlehtml: 63 | $(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml 64 | @echo 65 | @echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml." 66 | 67 | pickle: 68 | $(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle 69 | @echo 70 | @echo "Build finished; now you can process the pickle files." 71 | 72 | json: 73 | $(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json 74 | @echo 75 | @echo "Build finished; now you can process the JSON files." 76 | 77 | htmlhelp: 78 | $(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp 79 | @echo 80 | @echo "Build finished; now you can run HTML Help Workshop with the" \ 81 | ".hhp project file in $(BUILDDIR)/htmlhelp." 82 | 83 | qthelp: 84 | $(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp 85 | @echo 86 | @echo "Build finished; now you can run "qcollectiongenerator" with the" \ 87 | ".qhcp project file in $(BUILDDIR)/qthelp, like this:" 88 | @echo "# qcollectiongenerator $(BUILDDIR)/qthelp/hamster_cli.qhcp" 89 | @echo "To view the help file:" 90 | @echo "# assistant -collectionFile $(BUILDDIR)/qthelp/hamster_cli.qhc" 91 | 92 | devhelp: 93 | $(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp 94 | @echo 95 | @echo "Build finished." 96 | @echo "To view the help file:" 97 | @echo "# mkdir -p $$HOME/.local/share/devhelp/hamster_cli" 98 | @echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/hamster_cli" 99 | @echo "# devhelp" 100 | 101 | epub: 102 | $(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub 103 | @echo 104 | @echo "Build finished. The epub file is in $(BUILDDIR)/epub." 105 | 106 | latex: 107 | $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex 108 | @echo 109 | @echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex." 110 | @echo "Run \`make' in that directory to run these through (pdf)latex" \ 111 | "(use \`make latexpdf' here to do that automatically)." 112 | 113 | latexpdf: 114 | $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex 115 | @echo "Running LaTeX files through pdflatex..." 116 | $(MAKE) -C $(BUILDDIR)/latex all-pdf 117 | @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." 118 | 119 | latexpdfja: 120 | $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex 121 | @echo "Running LaTeX files through platex and dvipdfmx..." 122 | $(MAKE) -C $(BUILDDIR)/latex all-pdf-ja 123 | @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." 124 | 125 | text: 126 | $(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text 127 | @echo 128 | @echo "Build finished. The text files are in $(BUILDDIR)/text." 129 | 130 | man: 131 | $(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man 132 | @echo 133 | @echo "Build finished. The manual pages are in $(BUILDDIR)/man." 134 | 135 | texinfo: 136 | $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo 137 | @echo 138 | @echo "Build finished. The Texinfo files are in $(BUILDDIR)/texinfo." 139 | @echo "Run \`make' in that directory to run these through makeinfo" \ 140 | "(use \`make info' here to do that automatically)." 141 | 142 | info: 143 | $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo 144 | @echo "Running Texinfo files through makeinfo..." 145 | make -C $(BUILDDIR)/texinfo info 146 | @echo "makeinfo finished; the Info files are in $(BUILDDIR)/texinfo." 147 | 148 | gettext: 149 | $(SPHINXBUILD) -b gettext $(I18NSPHINXOPTS) $(BUILDDIR)/locale 150 | @echo 151 | @echo "Build finished. The message catalogs are in $(BUILDDIR)/locale." 152 | 153 | changes: 154 | $(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes 155 | @echo 156 | @echo "The overview file is in $(BUILDDIR)/changes." 157 | 158 | linkcheck: 159 | $(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck 160 | @echo 161 | @echo "Link check complete; look for any errors in the above output " \ 162 | "or in $(BUILDDIR)/linkcheck/output.txt." 163 | 164 | doctest: 165 | $(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest 166 | @echo "Testing of doctests in the sources finished, look at the " \ 167 | "results in $(BUILDDIR)/doctest/output.txt." 168 | 169 | xml: 170 | $(SPHINXBUILD) -b xml $(ALLSPHINXOPTS) $(BUILDDIR)/xml 171 | @echo 172 | @echo "Build finished. The XML files are in $(BUILDDIR)/xml." 173 | 174 | pseudoxml: 175 | $(SPHINXBUILD) -b pseudoxml $(ALLSPHINXOPTS) $(BUILDDIR)/pseudoxml 176 | @echo 177 | @echo "Build finished. The pseudo-XML files are in $(BUILDDIR)/pseudoxml." 178 | -------------------------------------------------------------------------------- /docs/authors.rst: -------------------------------------------------------------------------------- 1 | .. include:: ../AUTHORS.rst 2 | -------------------------------------------------------------------------------- /docs/conf.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # 4 | # hamster_cli documentation build configuration file, created by 5 | # sphinx-quickstart on Tue Jul 9 22:26:36 2013. 6 | # 7 | # This file is execfile()d with the current directory set to its 8 | # containing dir. 9 | # 10 | # Note that not all possible configuration values are present in this 11 | # autogenerated file. 12 | # 13 | # All configuration values have a default; values that are commented out 14 | # serve to show the default. 15 | 16 | import sys 17 | import os 18 | import datetime 19 | import shlex 20 | import alabaster 21 | 22 | 23 | 24 | # If extensions (or modules to document with autodoc) are in another 25 | # directory, add these directories to sys.path here. If the directory is 26 | # relative to the documentation root, use os.path.abspath to make it 27 | # absolute, like shown here. 28 | #sys.path.insert(0, os.path.abspath('.')) 29 | 30 | # Get the project root dir, which is the parent dir of this 31 | cwd = os.getcwd() 32 | project_root = os.path.dirname(cwd) 33 | 34 | # Insert the project root dir as the first element in the PYTHONPATH. 35 | # This lets us ensure that the source package is imported, and that its 36 | # version is used. 37 | sys.path.insert(0, project_root) 38 | 39 | import hamster_cli 40 | 41 | # -- General configuration --------------------------------------------- 42 | 43 | # If your documentation needs a minimal Sphinx version, state it here. 44 | #needs_sphinx = '1.0' 45 | 46 | # Add any Sphinx extension module names here, as strings. They can be 47 | # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom ones. 48 | extensions = [ 49 | 'sphinx.ext.autodoc', 50 | 'sphinx.ext.viewcode', 51 | 'sphinx.ext.todo', 52 | 'sphinx.ext.coverage', 53 | 'alabaster', 54 | ] 55 | 56 | # Add any paths that contain templates here, relative to this directory. 57 | templates_path = ['_templates'] 58 | 59 | # The suffix of source filenames. 60 | source_suffix = '.rst' 61 | 62 | # The encoding of source files. 63 | #source_encoding = 'utf-8-sig' 64 | 65 | # The master toctree document. 66 | master_doc = 'index' 67 | 68 | # General information about the project. 69 | project = u'hamster_cli' 70 | copyright = '2015, Eric Goller' 71 | author = 'Eric Goller' 72 | 73 | # The version info for the project you're documenting, acts as replacement 74 | # for |version| and |release|, also used in various other places throughout 75 | # the built documents. 76 | # 77 | # The short X.Y version. 78 | version = '0.12.0' 79 | # The full version, including alpha/beta/rc tags. 80 | release = '0.12.0' 81 | 82 | # The language for content autogenerated by Sphinx. Refer to documentation 83 | # for a list of supported languages. 84 | #language = None 85 | 86 | # There are two options for replacing |today|: either, you set today to 87 | # some non-false value, then it is used: 88 | #today = '' 89 | # Else, today_fmt is used as the format for a strftime call. 90 | #today_fmt = '%B %d, %Y' 91 | 92 | # List of patterns, relative to source directory, that match files and 93 | # directories to ignore when looking for source files. 94 | exclude_patterns = ['_build'] 95 | 96 | # The reST default role (used for this markup: `text`) to use for all 97 | # documents. 98 | #default_role = None 99 | 100 | # If true, '()' will be appended to :func: etc. cross-reference text. 101 | #add_function_parentheses = True 102 | 103 | # If true, the current module name will be prepended to all description 104 | # unit titles (such as .. function::). 105 | #add_module_names = True 106 | 107 | # If true, sectionauthor and moduleauthor directives will be shown in the 108 | # output. They are ignored by default. 109 | #show_authors = False 110 | 111 | # The name of the Pygments (syntax highlighting) style to use. 112 | pygments_style = 'sphinx' 113 | 114 | # A list of ignored prefixes for module index sorting. 115 | #modindex_common_prefix = [] 116 | 117 | # If true, keep warnings as "system message" paragraphs in the built 118 | # documents. 119 | #keep_warnings = False 120 | 121 | 122 | # -- Options for HTML output ------------------------------------------- 123 | 124 | # The theme to use for HTML and HTML Help pages. See the documentation for 125 | # a list of builtin themes. 126 | html_theme = 'alabaster' 127 | 128 | # Theme options are theme-specific and customize the look and feel of a 129 | # theme further. For a list of options available for each theme, see the 130 | # documentation. 131 | html_theme_options = { 132 | # Relative path (from $PROJECT/_static/) to a logo image, which will appear 133 | # in the upper left corner above the name of the project. 134 | # 'logo': 'logo.png', 135 | 'logo_name': True, 136 | 'description': 'A command line timetracker.', 137 | 'github_user': 'elbenfreund', 138 | 'github_repo': 'hamstser_cli', 139 | 'github_button': True, 140 | 'github_banner': False, 141 | 'travis_button': False, 142 | 'extra_nav_links': { 143 | 'Build Status': 'https://travis-ci.org/elbenfreund/hamster_cli', 144 | 'Coverage Status': 'https://codecov.io/github/elbenfreund/hamsster_cli?branch=master', 145 | 'Requirements Status': 'https://requires.io/github/elbenfreund/hamster_cli/requirements/?branch=master', 146 | 'Project Management': 'https://waffle.io/elbenfreund/hamster_cli', 147 | }, 148 | 'analytics_id': '', 149 | 'show_related': False, 150 | 'show_powered_by': True, 151 | } 152 | 153 | # Add any paths that contain custom themes here, relative to this directory. 154 | #html_theme_path = [] 155 | 156 | # The name for this set of Sphinx documents. If None, it defaults to 157 | # " v documentation". 158 | #html_title = None 159 | 160 | # A shorter title for the navigation bar. Default is the same as 161 | # html_title. 162 | #html_short_title = None 163 | 164 | # The name of an image file (relative to this directory) to place at the 165 | # top of the sidebar. 166 | #html_logo = None 167 | 168 | # The name of an image file (within the static path) to use as favicon 169 | # of the docs. This file should be a Windows icon file (.ico) being 170 | # 16x16 or 32x32 pixels large. 171 | #html_favicon = None 172 | 173 | # Add any paths that contain custom static files (such as style sheets) 174 | # here, relative to this directory. They are copied after the builtin 175 | # static files, so a file named "default.css" will overwrite the builtin 176 | # "default.css". 177 | html_static_path = ['_static'] 178 | 179 | # If not '', a 'Last updated on:' timestamp is inserted at every page 180 | # bottom, using the given strftime format. 181 | #html_last_updated_fmt = '%b %d, %Y' 182 | 183 | # If true, SmartyPants will be used to convert quotes and dashes to 184 | # typographically correct entities. 185 | #html_use_smartypants = True 186 | 187 | # Custom sidebar templates, maps document names to template names. 188 | html_sidebars = { 189 | '**': [ 190 | 'about.html', 191 | 'navigation.html', 192 | 'relations.html', 193 | 'searchbox.html', 194 | 'donate.html', 195 | ] 196 | } 197 | 198 | # Additional templates that should be rendered to pages, maps page names 199 | # to template names. 200 | #html_additional_pages = {} 201 | 202 | # If false, no module index is generated. 203 | #html_domain_indices = True 204 | 205 | # If false, no index is generated. 206 | #html_use_index = True 207 | 208 | # If true, the index is split into individual pages for each letter. 209 | #html_split_index = False 210 | 211 | # If true, links to the reST sources are added to the pages. 212 | #html_show_sourcelink = True 213 | 214 | # If true, "Created using Sphinx" is shown in the HTML footer. 215 | # Default is True. 216 | #html_show_sphinx = True 217 | 218 | # If true, "(C) Copyright ..." is shown in the HTML footer. 219 | # Default is True. 220 | #html_show_copyright = True 221 | 222 | # If true, an OpenSearch description file will be output, and all pages 223 | # will contain a tag referring to it. The value of this option 224 | # must be the base URL from which the finished HTML is served. 225 | #html_use_opensearch = '' 226 | 227 | # This is the file name suffix for HTML files (e.g. ".xhtml"). 228 | #html_file_suffix = None 229 | 230 | # Output file base name for HTML help builder. 231 | htmlhelp_basename = 'hamster_clidoc' 232 | 233 | 234 | # -- Options for LaTeX output ------------------------------------------ 235 | 236 | latex_elements = { 237 | # The paper size ('letterpaper' or 'a4paper'). 238 | #'papersize': 'letterpaper', 239 | 240 | # The font size ('10pt', '11pt' or '12pt'). 241 | #'pointsize': '10pt', 242 | 243 | # Additional stuff for the LaTeX preamble. 244 | #'preamble': '', 245 | } 246 | 247 | # Grouping the document tree into LaTeX files. List of tuples 248 | # (source start file, target name, title, author, documentclass 249 | # [howto/manual]). 250 | latex_documents = [ 251 | ('index', 'hamster_cli.tex', 252 | u'hamster_cli Documentation', 253 | u'Eric Goller', 'manual'), 254 | ] 255 | 256 | # The name of an image file (relative to this directory) to place at 257 | # the top of the title page. 258 | #latex_logo = None 259 | 260 | # For "manual" documents, if this is true, then toplevel headings 261 | # are parts, not chapters. 262 | #latex_use_parts = False 263 | 264 | # If true, show page references after internal links. 265 | #latex_show_pagerefs = False 266 | 267 | # If true, show URL addresses after external links. 268 | #latex_show_urls = False 269 | 270 | # Documents to append as an appendix to all manuals. 271 | #latex_appendices = [] 272 | 273 | # If false, no module index is generated. 274 | #latex_domain_indices = True 275 | 276 | 277 | # -- Options for manual page output ------------------------------------ 278 | 279 | # One entry per manual page. List of tuples 280 | # (source start file, name, description, authors, manual section). 281 | man_pages = [ 282 | ('index', 'hamster_cli', 283 | u'hamster_cli Documentation', 284 | [u'Eric Goller'], 1) 285 | ] 286 | 287 | # If true, show URL addresses after external links. 288 | #man_show_urls = False 289 | 290 | 291 | # -- Options for Texinfo output ---------------------------------------- 292 | 293 | # Grouping the document tree into Texinfo files. List of tuples 294 | # (source start file, target name, title, author, 295 | # dir menu entry, description, category) 296 | texinfo_documents = [ 297 | ('index', 'hamster_cli', 298 | u'hamster_cli Documentation', 299 | u'Eric Goller', 300 | 'hamster_cli', 301 | 'One line description of project.', 302 | 'Miscellaneous'), 303 | ] 304 | 305 | # Documents to append as an appendix to all manuals. 306 | #texinfo_appendices = [] 307 | 308 | # If false, no module index is generated. 309 | #texinfo_domain_indices = True 310 | 311 | # How to display URL addresses: 'footnote', 'no', or 'inline'. 312 | #texinfo_show_urls = 'footnote' 313 | 314 | # If true, do not generate a @detailmenu in the "Top" node's menu. 315 | #texinfo_no_detailmenu = False 316 | -------------------------------------------------------------------------------- /docs/contributing.rst: -------------------------------------------------------------------------------- 1 | .. include:: ../CONTRIBUTING.rst 2 | -------------------------------------------------------------------------------- /docs/hamster_cli.rst: -------------------------------------------------------------------------------- 1 | hamster_cli package 2 | =================== 3 | 4 | Submodules 5 | ---------- 6 | 7 | hamster_cli.hamster_cli module 8 | ------------------------------ 9 | 10 | .. automodule:: hamster_cli.hamster_cli 11 | :members: 12 | :undoc-members: 13 | :show-inheritance: 14 | 15 | hamster_cli.help_strings module 16 | ------------------------------- 17 | 18 | .. automodule:: hamster_cli.help_strings 19 | :members: 20 | :undoc-members: 21 | :show-inheritance: 22 | 23 | 24 | Module contents 25 | --------------- 26 | 27 | .. automodule:: hamster_cli 28 | :members: 29 | :undoc-members: 30 | :show-inheritance: 31 | -------------------------------------------------------------------------------- /docs/history.rst: -------------------------------------------------------------------------------- 1 | .. include:: ../HISTORY.rst 2 | -------------------------------------------------------------------------------- /docs/index.rst: -------------------------------------------------------------------------------- 1 | .. hamster_cli documentation master file, created by 2 | sphinx-quickstart on Tue Jul 9 22:26:36 2013. 3 | You can adapt this file completely to your liking, but it should at least 4 | contain the root `toctree` directive. 5 | 6 | Welcome to hamster_cli's documentation! 7 | ======================================== 8 | 9 | Contents: 10 | 11 | .. toctree:: 12 | :maxdepth: 2 13 | 14 | readme 15 | installation 16 | usage 17 | API reference 18 | contributing 19 | authors 20 | history 21 | 22 | Indices and tables 23 | ================== 24 | 25 | * :ref:`genindex` 26 | * :ref:`modindex` 27 | * :ref:`search` 28 | 29 | -------------------------------------------------------------------------------- /docs/installation.rst: -------------------------------------------------------------------------------- 1 | ============ 2 | Installation 3 | ============ 4 | 5 | At the command line:: 6 | 7 | $ easy_install hamster_cli 8 | 9 | Or, if you have virtualenvwrapper installed:: 10 | 11 | $ mkvirtualenv hamster_cli 12 | $ pip install hamster_cli 13 | -------------------------------------------------------------------------------- /docs/make.bat: -------------------------------------------------------------------------------- 1 | @ECHO OFF 2 | 3 | REM Command file for Sphinx documentation 4 | 5 | if "%SPHINXBUILD%" == "" ( 6 | set SPHINXBUILD=sphinx-build 7 | ) 8 | set BUILDDIR=_build 9 | set ALLSPHINXOPTS=-d %BUILDDIR%/doctrees %SPHINXOPTS% . 10 | set I18NSPHINXOPTS=%SPHINXOPTS% . 11 | if NOT "%PAPER%" == "" ( 12 | set ALLSPHINXOPTS=-D latex_paper_size=%PAPER% %ALLSPHINXOPTS% 13 | set I18NSPHINXOPTS=-D latex_paper_size=%PAPER% %I18NSPHINXOPTS% 14 | ) 15 | 16 | if "%1" == "" goto help 17 | 18 | if "%1" == "help" ( 19 | :help 20 | echo.Please use `make ^` where ^ is one of 21 | echo. html to make standalone HTML files 22 | echo. dirhtml to make HTML files named index.html in directories 23 | echo. singlehtml to make a single large HTML file 24 | echo. pickle to make pickle files 25 | echo. json to make JSON files 26 | echo. htmlhelp to make HTML files and a HTML help project 27 | echo. qthelp to make HTML files and a qthelp project 28 | echo. devhelp to make HTML files and a Devhelp project 29 | echo. epub to make an epub 30 | echo. latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter 31 | echo. text to make text files 32 | echo. man to make manual pages 33 | echo. texinfo to make Texinfo files 34 | echo. gettext to make PO message catalogs 35 | echo. changes to make an overview over all changed/added/deprecated items 36 | echo. xml to make Docutils-native XML files 37 | echo. pseudoxml to make pseudoxml-XML files for display purposes 38 | echo. linkcheck to check all external links for integrity 39 | echo. doctest to run all doctests embedded in the documentation if enabled 40 | goto end 41 | ) 42 | 43 | if "%1" == "clean" ( 44 | for /d %%i in (%BUILDDIR%\*) do rmdir /q /s %%i 45 | del /q /s %BUILDDIR%\* 46 | goto end 47 | ) 48 | 49 | 50 | %SPHINXBUILD% 2> nul 51 | if errorlevel 9009 ( 52 | echo. 53 | echo.The 'sphinx-build' command was not found. Make sure you have Sphinx 54 | echo.installed, then set the SPHINXBUILD environment variable to point 55 | echo.to the full path of the 'sphinx-build' executable. Alternatively you 56 | echo.may add the Sphinx directory to PATH. 57 | echo. 58 | echo.If you don't have Sphinx installed, grab it from 59 | echo.http://sphinx-doc.org/ 60 | exit /b 1 61 | ) 62 | 63 | if "%1" == "html" ( 64 | %SPHINXBUILD% -b html %ALLSPHINXOPTS% %BUILDDIR%/html 65 | if errorlevel 1 exit /b 1 66 | echo. 67 | echo.Build finished. The HTML pages are in %BUILDDIR%/html. 68 | goto end 69 | ) 70 | 71 | if "%1" == "dirhtml" ( 72 | %SPHINXBUILD% -b dirhtml %ALLSPHINXOPTS% %BUILDDIR%/dirhtml 73 | if errorlevel 1 exit /b 1 74 | echo. 75 | echo.Build finished. The HTML pages are in %BUILDDIR%/dirhtml. 76 | goto end 77 | ) 78 | 79 | if "%1" == "singlehtml" ( 80 | %SPHINXBUILD% -b singlehtml %ALLSPHINXOPTS% %BUILDDIR%/singlehtml 81 | if errorlevel 1 exit /b 1 82 | echo. 83 | echo.Build finished. The HTML pages are in %BUILDDIR%/singlehtml. 84 | goto end 85 | ) 86 | 87 | if "%1" == "pickle" ( 88 | %SPHINXBUILD% -b pickle %ALLSPHINXOPTS% %BUILDDIR%/pickle 89 | if errorlevel 1 exit /b 1 90 | echo. 91 | echo.Build finished; now you can process the pickle files. 92 | goto end 93 | ) 94 | 95 | if "%1" == "json" ( 96 | %SPHINXBUILD% -b json %ALLSPHINXOPTS% %BUILDDIR%/json 97 | if errorlevel 1 exit /b 1 98 | echo. 99 | echo.Build finished; now you can process the JSON files. 100 | goto end 101 | ) 102 | 103 | if "%1" == "htmlhelp" ( 104 | %SPHINXBUILD% -b htmlhelp %ALLSPHINXOPTS% %BUILDDIR%/htmlhelp 105 | if errorlevel 1 exit /b 1 106 | echo. 107 | echo.Build finished; now you can run HTML Help Workshop with the ^ 108 | .hhp project file in %BUILDDIR%/htmlhelp. 109 | goto end 110 | ) 111 | 112 | if "%1" == "qthelp" ( 113 | %SPHINXBUILD% -b qthelp %ALLSPHINXOPTS% %BUILDDIR%/qthelp 114 | if errorlevel 1 exit /b 1 115 | echo. 116 | echo.Build finished; now you can run "qcollectiongenerator" with the ^ 117 | .qhcp project file in %BUILDDIR%/qthelp, like this: 118 | echo.^> qcollectiongenerator %BUILDDIR%\qthelp\hamster_cli.qhcp 119 | echo.To view the help file: 120 | echo.^> assistant -collectionFile %BUILDDIR%\qthelp\hamster_cli.ghc 121 | goto end 122 | ) 123 | 124 | if "%1" == "devhelp" ( 125 | %SPHINXBUILD% -b devhelp %ALLSPHINXOPTS% %BUILDDIR%/devhelp 126 | if errorlevel 1 exit /b 1 127 | echo. 128 | echo.Build finished. 129 | goto end 130 | ) 131 | 132 | if "%1" == "epub" ( 133 | %SPHINXBUILD% -b epub %ALLSPHINXOPTS% %BUILDDIR%/epub 134 | if errorlevel 1 exit /b 1 135 | echo. 136 | echo.Build finished. The epub file is in %BUILDDIR%/epub. 137 | goto end 138 | ) 139 | 140 | if "%1" == "latex" ( 141 | %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex 142 | if errorlevel 1 exit /b 1 143 | echo. 144 | echo.Build finished; the LaTeX files are in %BUILDDIR%/latex. 145 | goto end 146 | ) 147 | 148 | if "%1" == "latexpdf" ( 149 | %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex 150 | cd %BUILDDIR%/latex 151 | make all-pdf 152 | cd %BUILDDIR%/.. 153 | echo. 154 | echo.Build finished; the PDF files are in %BUILDDIR%/latex. 155 | goto end 156 | ) 157 | 158 | if "%1" == "latexpdfja" ( 159 | %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex 160 | cd %BUILDDIR%/latex 161 | make all-pdf-ja 162 | cd %BUILDDIR%/.. 163 | echo. 164 | echo.Build finished; the PDF files are in %BUILDDIR%/latex. 165 | goto end 166 | ) 167 | 168 | if "%1" == "text" ( 169 | %SPHINXBUILD% -b text %ALLSPHINXOPTS% %BUILDDIR%/text 170 | if errorlevel 1 exit /b 1 171 | echo. 172 | echo.Build finished. The text files are in %BUILDDIR%/text. 173 | goto end 174 | ) 175 | 176 | if "%1" == "man" ( 177 | %SPHINXBUILD% -b man %ALLSPHINXOPTS% %BUILDDIR%/man 178 | if errorlevel 1 exit /b 1 179 | echo. 180 | echo.Build finished. The manual pages are in %BUILDDIR%/man. 181 | goto end 182 | ) 183 | 184 | if "%1" == "texinfo" ( 185 | %SPHINXBUILD% -b texinfo %ALLSPHINXOPTS% %BUILDDIR%/texinfo 186 | if errorlevel 1 exit /b 1 187 | echo. 188 | echo.Build finished. The Texinfo files are in %BUILDDIR%/texinfo. 189 | goto end 190 | ) 191 | 192 | if "%1" == "gettext" ( 193 | %SPHINXBUILD% -b gettext %I18NSPHINXOPTS% %BUILDDIR%/locale 194 | if errorlevel 1 exit /b 1 195 | echo. 196 | echo.Build finished. The message catalogs are in %BUILDDIR%/locale. 197 | goto end 198 | ) 199 | 200 | if "%1" == "changes" ( 201 | %SPHINXBUILD% -b changes %ALLSPHINXOPTS% %BUILDDIR%/changes 202 | if errorlevel 1 exit /b 1 203 | echo. 204 | echo.The overview file is in %BUILDDIR%/changes. 205 | goto end 206 | ) 207 | 208 | if "%1" == "linkcheck" ( 209 | %SPHINXBUILD% -b linkcheck %ALLSPHINXOPTS% %BUILDDIR%/linkcheck 210 | if errorlevel 1 exit /b 1 211 | echo. 212 | echo.Link check complete; look for any errors in the above output ^ 213 | or in %BUILDDIR%/linkcheck/output.txt. 214 | goto end 215 | ) 216 | 217 | if "%1" == "doctest" ( 218 | %SPHINXBUILD% -b doctest %ALLSPHINXOPTS% %BUILDDIR%/doctest 219 | if errorlevel 1 exit /b 1 220 | echo. 221 | echo.Testing of doctests in the sources finished, look at the ^ 222 | results in %BUILDDIR%/doctest/output.txt. 223 | goto end 224 | ) 225 | 226 | if "%1" == "xml" ( 227 | %SPHINXBUILD% -b xml %ALLSPHINXOPTS% %BUILDDIR%/xml 228 | if errorlevel 1 exit /b 1 229 | echo. 230 | echo.Build finished. The XML files are in %BUILDDIR%/xml. 231 | goto end 232 | ) 233 | 234 | if "%1" == "pseudoxml" ( 235 | %SPHINXBUILD% -b pseudoxml %ALLSPHINXOPTS% %BUILDDIR%/pseudoxml 236 | if errorlevel 1 exit /b 1 237 | echo. 238 | echo.Build finished. The pseudo-XML files are in %BUILDDIR%/pseudoxml. 239 | goto end 240 | ) 241 | 242 | :end 243 | -------------------------------------------------------------------------------- /docs/modules.rst: -------------------------------------------------------------------------------- 1 | hamster_cli 2 | =========== 3 | 4 | .. toctree:: 5 | :maxdepth: 4 6 | 7 | hamster_cli 8 | -------------------------------------------------------------------------------- /docs/notes.rst: -------------------------------------------------------------------------------- 1 | Implementation and Development Notes 2 | ===================================== 3 | 4 | To promote cleanness and seperation of concens we split the actual command 5 | invocation and its click-integration from the logic ctriggered by that 6 | that command. This has the added benefit of a clear seperation of unit and 7 | integration tests. 8 | 9 | * For information about unicode handling, see: 10 | http://click.pocoo.org/5/python3/#python3-surrogates This should be alright 11 | for our usecase, as any properly user environment should have its unicode 12 | locale declared. And if not, its acceptable to bully the user to do so. 13 | 14 | * Click commands deal only with strings. So quite often, the first thing our 15 | custom command-functions will do is provide some basic type conversion and 16 | error checking. before calling the corresponding lib method. 17 | * Whilst the backend usualy either returns results or Errors, the client should 18 | always try to handle those errors which are predictable and turn them into 19 | user relevant command line output. Only actual errors that are not part of 20 | the expected user interaction shall get through as exceptions. 21 | 22 | Propably better as subcommands: 23 | * ``categories`` (list) 24 | * ``activities`` (list) 25 | -------------------------------------------------------------------------------- /docs/readme.rst: -------------------------------------------------------------------------------- 1 | .. include:: ../README.rst 2 | -------------------------------------------------------------------------------- /docs/usage.rst: -------------------------------------------------------------------------------- 1 | ======== 2 | Usage 3 | ======== 4 | 5 | To use hamster_cli simply imvoke it:: 6 | 7 | hamster-cli 8 | 9 | Incompabilities 10 | --------------- 11 | 12 | We tries hard to stay compatible with *legacy hamster-cli* but there are some 13 | aspects where we could not do so without make to huge tradeoffs to what we feel 14 | is the proper way to do so. For transparency and you to evaluate if those 15 | breaking points affect you we list them here: 16 | 17 | * Only one *ongoing fact* at a time. You will not be able to start more than 18 | one fact without providing an endtime. If you do you will be presented with 19 | an error and either have to cancel or stop the current *ongoing fact*. 20 | * Argument values that contain whitespaces need to be wrapped in quoteation 21 | marks. This is established practice and needed to stay POSIX compatible. In 22 | particular this affects: 23 | * start/end - datetimes; As date and time aspects are seperatetd by a 24 | whitespace. 25 | * ``raw_fact`` arguments; As they contain various whitespaces. 26 | * search terms 27 | -------------------------------------------------------------------------------- /hamster_cli/__init__.py: -------------------------------------------------------------------------------- 1 | # This file is part of 'hamster_cli'. 2 | # 3 | # 'hamster_cli' is free software: you can redistribute it and/or modify 4 | # it under the terms of the GNU General Public License as published by 5 | # the Free Software Foundation, either version 3 of the License, or 6 | # (at your option) any later version. 7 | # 8 | # 'hamster_cli' is distributed in the hope that it will be useful, 9 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 10 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 11 | # GNU General Public License for more details. 12 | # 13 | # You should have received a copy of the GNU General Public License 14 | # along with 'hamster_cli'. If not, see . 15 | 16 | """``hamster_cli``, a command line time tracker utilizing the power of ``hamsterlib``.""" 17 | 18 | 19 | __author__ = 'Eric Goller' 20 | __email__ = 'Elbenfreund@DenkenInEchtzeit.net' 21 | __version__ = '0.12.0' 22 | __appname__ = 'hamster_cli' 23 | -------------------------------------------------------------------------------- /hamster_cli/hamster_cli.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | # This file is part of 'hamster_cli'. 4 | # 5 | # 'hamster_cli' is free software: you can redistribute it and/or modify 6 | # it under the terms of the GNU General Public License as published by 7 | # the Free Software Foundation, either version 3 of the License, or 8 | # (at your option) any later version. 9 | # 10 | # 'hamster_cli' is distributed in the hope that it will be useful, 11 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | # GNU General Public License for more details. 14 | # 15 | # You should have received a copy of the GNU General Public License 16 | # along with 'hamster_cli'. If not, see . 17 | 18 | """A time tracker for the command line. Utilizing the power of hamster-lib.""" 19 | 20 | 21 | from __future__ import absolute_import, unicode_literals 22 | 23 | import datetime 24 | import logging 25 | import os 26 | from collections import namedtuple 27 | from gettext import gettext as _ 28 | 29 | import appdirs 30 | import click 31 | import hamster_lib 32 | # Once we drop py2 support, we can use the builtin again but unicode support 33 | # under python 2 is practicly non existing and manual encoding is not easily 34 | # possible. 35 | from backports.configparser import SafeConfigParser 36 | from hamster_lib import Fact, HamsterControl, reports 37 | from hamster_lib.helpers import time as time_helpers 38 | from tabulate import tabulate 39 | 40 | from . import help_strings 41 | 42 | 43 | class HamsterAppDirs(appdirs.AppDirs): 44 | """Custom class that ensure appdirs exist.""" 45 | 46 | def __init__(self, *args, **kwargs): 47 | """Add create flag value to instance.""" 48 | super(HamsterAppDirs, self).__init__(*args, **kwargs) 49 | self.create = True 50 | 51 | @property 52 | def user_data_dir(self): 53 | """Return ``user_data_dir``.""" 54 | directory = appdirs.user_data_dir(self.appname, self.appauthor, 55 | version=self.version, roaming=self.roaming) 56 | if self.create: 57 | self._ensure_directory_exists(directory) 58 | return directory 59 | 60 | @property 61 | def site_data_dir(self): 62 | """Return ``site_data_dir``.""" 63 | directory = appdirs.site_data_dir(self.appname, self.appauthor, 64 | version=self.version, multipath=self.multipath) 65 | if self.create: 66 | self._ensure_directory_exists(directory) 67 | return directory 68 | 69 | @property 70 | def user_config_dir(self): 71 | """Return ``user_config_dir``.""" 72 | directory = appdirs.user_config_dir(self.appname, self.appauthor, 73 | version=self.version, roaming=self.roaming) 74 | if self.create: 75 | self._ensure_directory_exists(directory) 76 | return directory 77 | 78 | @property 79 | def site_config_dir(self): 80 | """Return ``site_config_dir``.""" 81 | directory = appdirs.site_config_dir(self.appname, self.appauthor, 82 | version=self.version, multipath=self.multipath) 83 | if self.create: 84 | self._ensure_directory_exists(directory) 85 | return directory 86 | 87 | @property 88 | def user_cache_dir(self): 89 | """Return ``user_cache_dir``.""" 90 | directory = appdirs.user_cache_dir(self.appname, self.appauthor, 91 | version=self.version) 92 | if self.create: 93 | self._ensure_directory_exists(directory) 94 | return directory 95 | 96 | @property 97 | def user_log_dir(self): 98 | """Return ``user_log_dir``.""" 99 | directory = appdirs.user_log_dir(self.appname, self.appauthor, 100 | version=self.version) 101 | if self.create: 102 | self._ensure_directory_exists(directory) 103 | return directory 104 | 105 | def _ensure_directory_exists(self, directory): 106 | """Ensure that the passed path exists.""" 107 | if not os.path.lexists(directory): 108 | os.makedirs(directory) 109 | return directory 110 | 111 | 112 | class Controler(HamsterControl): 113 | """A custom controler that adds config handling on top of its regular functionality.""" 114 | 115 | def __init__(self): 116 | """Instantiate controler instance and adding client_config to it.""" 117 | lib_config, client_config = _get_config(_get_config_instance()) 118 | super(Controler, self).__init__(lib_config) 119 | self.client_config = client_config 120 | 121 | 122 | LOG_LEVELS = { 123 | 'info': logging.INFO, 124 | 'debug': logging.DEBUG, 125 | 'warning': logging.WARNING, 126 | 'error': logging.ERROR, 127 | } 128 | 129 | 130 | AppDirs = HamsterAppDirs('hamster_cli') 131 | 132 | 133 | pass_controler = click.make_pass_decorator(Controler, ensure=True) 134 | 135 | 136 | @click.group(help=help_strings.RUN_HELP) 137 | @pass_controler 138 | def run(controler): 139 | """General context run right before any of the commands.""" 140 | click.clear() 141 | _show_greeting() 142 | _run(controler) 143 | 144 | 145 | def _run(controler): 146 | """Make sure that loggers are setup properly.""" 147 | _setup_logging(controler) 148 | 149 | 150 | @run.command(help=help_strings.SEARCH_HELP) 151 | @click.argument('search_term') 152 | @click.argument('time_range', default='') 153 | @pass_controler 154 | def search(controler, search_term, time_range): 155 | """Fetch facts matching certain criteria.""" 156 | # [FIXME] 157 | # Check what we actually match against. 158 | _search(controler, search_term, time_range) 159 | 160 | 161 | def _search(controler, search_term, time_range): 162 | """ 163 | Search facts machting given timerange and search term. Both are optional. 164 | 165 | Matching facts will be printed in a tabular representation. 166 | 167 | Make sure that arguments are converted into apropiate types before passing 168 | them on to the backend. 169 | 170 | We leave it to the backend to first parse the timeinfo and then complete any 171 | missing data based on the passed config settings. 172 | 173 | Args: 174 | search_term: Term that need to be matched by the fact in order to be considered a hit. 175 | time_range: Only facts within this timerange will be considered. 176 | """ 177 | # [FIXME] 178 | # As far as our backend is concerned search_term as well as time range are 179 | # optional. If the same is true for legacy hamster-cli needs to be checked. 180 | if not time_range: 181 | start, end = (None, None) 182 | else: 183 | # [FIXME] 184 | # This is a rather crude fix. Recent versions of ``hamster-lib`` do not 185 | # provide a dedicated helper to parse *just* time(ranges) but expect a 186 | # ``raw_fact`` text. In order to work around this we just append 187 | # whitespaces to our time range argument which will qualify for the 188 | # desired parsing. 189 | # Once raw_fact/time parsing has been refactored in hamster-lib, this 190 | # should no longer be needed. 191 | time_range = time_range + ' ' 192 | timeinfo = time_helpers.extract_time_info(time_range)[0] 193 | start, end = time_helpers.complete_timeframe(timeinfo, controler.config) 194 | 195 | results = controler.facts.get_all(filter_term=search_term, start=start, end=end) 196 | 197 | table, headers = _generate_facts_table(results) 198 | click.echo(tabulate(table, headers=headers)) 199 | 200 | 201 | @run.command(help=help_strings.LIST_HELP) 202 | @click.argument('time_range', default='') 203 | @pass_controler 204 | def list(controler, time_range): 205 | """List all facts within a timerange.""" 206 | _search(controler, search_term='', time_range=time_range) 207 | 208 | 209 | @run.command(help=help_strings.START_HELP) 210 | @click.argument('raw_fact') 211 | @click.argument('start', default='') 212 | @click.argument('end', default='') 213 | @pass_controler 214 | def start(controler, raw_fact, start, end): 215 | """Start or add a fact.""" 216 | # [FIXME] 217 | # The original semantics do not work anymore. As we make a clear difference 218 | # between *adding* a (complete) fact and *starting* a (ongoing) fact. 219 | # This needs to be reflected in this command. 220 | _start(controler, raw_fact, start, end) 221 | 222 | 223 | def _start(controler, raw_fact, start, end): 224 | """ 225 | Start or add a fact. 226 | 227 | Args: 228 | raw_fact: ``raw_fact`` containing information about the Fact to be started. As an absolute 229 | minimum this must be a string representing the 'activityname'. 230 | start (optional): When does the fact start? 231 | end (optional): When does the fact end? 232 | 233 | Returns: 234 | None: If everything went alright. 235 | 236 | Note: 237 | * Whilst it is possible to pass timeinformation as part of the ``raw_fact`` as 238 | well as dedicated ``start`` and ``end`` arguments only the latter will be represented 239 | in the resulting fact in such a case. 240 | """ 241 | fact = Fact.create_from_raw_fact(raw_fact) 242 | # Explicit trumps implicit! 243 | if start: 244 | fact.start = time_helpers.parse_time(start) 245 | if end: 246 | fact.end = time_helpers.parse_time(end) 247 | 248 | if not fact.end: 249 | # We seem to want to start a new tmp fact 250 | # Neither the raw fact string nor an additional optional end time have 251 | # been passed. 252 | # Until we decide wether to split this into start/add command we use the 253 | # presence of any 'end' information as indication of the users intend. 254 | tmp_fact = True 255 | else: 256 | tmp_fact = False 257 | 258 | # We complete the facts times in both cases as even an new 'ongoing' fact 259 | # may be in need of some time-completion for its start information. 260 | 261 | # Complete missing fields with default values. 262 | # legacy hamster_cli seems to have a different fallback behaviour than 263 | # our regular backend, in particular the way 'day_start' is handled. 264 | # For maximum consistency we use the backends unified ``complete_timeframe`` 265 | # helper instead. If behaviour similar to the legacy hamster-cli is desired, 266 | # all that seems needed is to change ``day_start`` to '00:00'. 267 | 268 | # The following is needed becauses start and end may be ``None``. 269 | if not fact.start: 270 | # No time information has been passed at all. 271 | fact.start = datetime.datetime.now() 272 | 273 | else: 274 | # We got some time information, which may be incomplete however. 275 | if not fact.end: 276 | end_date = None 277 | end_time = None 278 | else: 279 | end_date = fact.end.date() 280 | end_time = fact.end.time() 281 | 282 | timeframe = time_helpers.TimeFrame( 283 | fact.start.date(), fact.start.time(), end_date, end_time, None) 284 | fact.start, fact.end = time_helpers.complete_timeframe(timeframe, controler.config) 285 | 286 | if tmp_fact: 287 | # Quick fix for tmp facts. that way we can use the default helper 288 | # function which will autocomplete the end info as well. 289 | # Because of our use of ``complete timeframe our 'ongoing fact' may have 290 | # recieved an ``end`` value now. In that case we reset it to ``None``. 291 | fact.end = None 292 | 293 | controler.client_logger.debug(_( 294 | "New fact instance created: {fact}".format(fact=fact) 295 | )) 296 | fact = controler.facts.save(fact) 297 | 298 | 299 | @run.command(help=help_strings.STOP_HELP) 300 | @pass_controler 301 | def stop(controler): 302 | """Stop tracking current fact. Saving the result.""" 303 | _stop(controler) 304 | 305 | 306 | def _stop(controler): 307 | """ 308 | Stop cucrrent 'ongoing fact' and save it to the backend. 309 | 310 | Returns: 311 | None: If successful. 312 | 313 | Raises: 314 | ValueError: If no *ongoing fact* can be found. 315 | """ 316 | try: 317 | fact = controler.facts.stop_tmp_fact() 318 | except ValueError: 319 | message = _( 320 | "Unable to continue temporary fact. Are you sure there is one?" 321 | "Try running *current*." 322 | ) 323 | raise click.ClickException(message) 324 | else: 325 | message = '{fact} ({duration} minutes)'.format(fact=fact, duration=fact.get_string_delta()) 326 | controler.client_logger.info(_(message)) 327 | click.echo(_(message)) 328 | 329 | 330 | @run.command(help=help_strings.CANCEL_HELP) 331 | @pass_controler 332 | def cancel(controler): 333 | """Cancel 'ongoing fact'. E.g stop it without storing in the backend.""" 334 | _cancel(controler) 335 | 336 | 337 | def _cancel(controler): 338 | """ 339 | Cancel tracking current temporary fact, discaring the result. 340 | 341 | Returns: 342 | None: If success. 343 | 344 | Raises: 345 | KeyErŕor: No *ongoing fact* can be found. 346 | """ 347 | try: 348 | controler.facts.cancel_tmp_fact() 349 | except KeyError: 350 | message = _("Nothing tracked right now. Not doing anything.") 351 | controler.client_logger.info(message) 352 | raise click.ClickException(message) 353 | else: 354 | message = _("Tracking canceled.") 355 | click.echo(message) 356 | controler.client_logger.debug(message) 357 | 358 | 359 | @run.command(help=help_strings.EXPORT_HELP) 360 | @click.argument('format', nargs=1, default='csv') 361 | @click.argument('start', nargs=1, default='') 362 | @click.argument('end', nargs=1, default='') 363 | @pass_controler 364 | def export(controler, format, start, end): 365 | """Export all facts of within a given timewindow to a file of specified format.""" 366 | _export(controler, format, start, end) 367 | 368 | 369 | def _export(controler, format, start, end): 370 | """ 371 | Export all facts in the given timeframe in the format specified. 372 | 373 | Args: 374 | format (str): Format to export to. Valid options are: ``csv``, ``xml`` and ``ical``. 375 | start (datetime.datetime): Consider only facts starting at this time or later. 376 | end (datetime.datetime): Consider only facts starting no later than this time. 377 | 378 | Returns: 379 | None: If everything went alright. 380 | 381 | Raises: 382 | click.Exception: If format is not recognized. 383 | """ 384 | accepted_formats = ['csv', 'ical', 'xml'] 385 | # [TODO] 386 | # Once hamster_lib has a proper 'export' register available we should be able 387 | # to streamline this. 388 | if format not in accepted_formats: 389 | message = _("Unrecocgnized export format recieved") 390 | controler.client_logger.info(message) 391 | raise click.ClickException(message) 392 | if not start: 393 | start = None 394 | if not end: 395 | end = None 396 | 397 | filepath = controler.client_config['export_path'] 398 | facts = controler.facts.get_all(start=start, end=end) 399 | if format == 'csv': 400 | writer = reports.TSVWriter(filepath) 401 | writer.write_report(facts) 402 | click.echo(_("Facts have been exported to: {path}".format(path=filepath))) 403 | elif format == 'ical': 404 | writer = reports.ICALWriter(filepath) 405 | writer.write_report(facts) 406 | click.echo(_("Facts have been exported to: {path}".format(path=filepath))) 407 | elif format == 'xml': 408 | writer = reports.XMLWriter(filepath) 409 | writer.write_report(facts) 410 | click.echo(_("Facts have been exported to: {path}".format(path=filepath))) 411 | 412 | 413 | @run.command(help=help_strings.CATEGORIES_HELP) 414 | @pass_controler 415 | def categories(controler): 416 | """List all existing categories, ordered by name.""" 417 | _categories(controler) 418 | 419 | 420 | def _categories(controler): 421 | """ 422 | List all existing categories, ordered by name. 423 | 424 | Returns: 425 | None: If success. 426 | """ 427 | result = controler.categories.get_all() 428 | # [TODO] 429 | # Provide nicer looking tabulated output. 430 | for category in result: 431 | click.echo(category.name) 432 | 433 | 434 | @run.command(help=help_strings.CURRENT_HELP) 435 | @pass_controler 436 | def current(controler): 437 | """Display current *ongoing fact*.""" 438 | _current(controler) 439 | 440 | 441 | def _current(controler): 442 | """ 443 | Return current *ongoing fact*. 444 | 445 | Returns: 446 | None: If everything went alright. 447 | 448 | Raises: 449 | click.ClickException: If we fail to fetch any *ongoing fact*. 450 | """ 451 | try: 452 | fact = controler.facts.get_tmp_fact() 453 | except KeyError: 454 | message = _( 455 | "There seems no be no activity beeing tracked right now." 456 | " maybe you want to *start* tracking one right now?" 457 | ) 458 | raise click.ClickException(message) 459 | else: 460 | fact.end = datetime.datetime.now() 461 | string = '{fact} ({duration} minutes)'.format(fact=fact, duration=fact.get_string_delta()) 462 | click.echo(string) 463 | 464 | 465 | @run.command(help=help_strings.ACTIVITIES_HELP) 466 | @click.argument('search_term', default='') 467 | @pass_controler 468 | def activities(controler, search_term): 469 | """List all activities. Provide optional filtering by name.""" 470 | _activities(controler, search_term) 471 | 472 | 473 | def _activities(controler, search_term): 474 | """ 475 | List all activities. Provide optional filtering by name. 476 | 477 | Args: 478 | search_term (str): String to match ``Activity.name`` against. 479 | 480 | Returns: 481 | None: If success. 482 | """ 483 | result = controler.activities.get_all(search_term=search_term) 484 | table = [] 485 | headers = (_("Activity"), _("Category")) 486 | for activity in result: 487 | if activity.category: 488 | category = activity.category.name 489 | else: 490 | category = None 491 | table.append((activity.name, category)) 492 | 493 | click.echo(tabulate(table, headers=headers)) 494 | 495 | 496 | @run.command(help=help_strings.LICENSE_HELP) 497 | def license(): 498 | """Show license information.""" 499 | _license() 500 | 501 | 502 | def _license(): 503 | """Show license information.""" 504 | license = """ 505 | 'hamster_cli' is free software: you can redistribute it and/or modify 506 | it under the terms of the GNU General Public License as published by 507 | the Free Software Foundation, either version 3 of the License, or 508 | (at your option) any later version. 509 | 510 | 'hamster_cli' is distributed in the hope that it will be useful, 511 | but WITHOUT ANY WARRANTY; without even the implied warranty of 512 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 513 | GNU General Public License for more details. 514 | 515 | You should have received a copy of the GNU General Public License 516 | along with . If not, see . 517 | """ 518 | click.echo(license) 519 | 520 | 521 | @run.command(help=help_strings.DETAILS_HELP) 522 | @pass_controler 523 | def details(controler): 524 | """List details about the runtime environment.""" 525 | _details(controler) 526 | 527 | 528 | def _details(controler): 529 | """List details about the runtime environment.""" 530 | def get_db_info(): 531 | result = None 532 | 533 | def get_sqlalchemy_info(): 534 | engine = controler.config['db_engine'] 535 | if engine == 'sqlite': 536 | sqlalchemy_string = _("Using 'sqlite' with database stored under: {}".format( 537 | controler.config['db_path'])) 538 | else: 539 | port = controler.config.get('db_port', '') 540 | if port: 541 | port = ':{}'.format(port) 542 | 543 | sqlalchemy_string = _( 544 | "Using '{engine}' connecting to database {name} on {host}{port}" 545 | " as user {username}.".format( 546 | engine=engine, host=controler.config['db_host'], port=port, 547 | username=controler.config['db_user'], name=controler.config['db_name']) 548 | ) 549 | return sqlalchemy_string 550 | 551 | # For now we do not need to check for various store option as we allow 552 | # only one anyway. 553 | result = get_sqlalchemy_info() 554 | return result 555 | 556 | from hamster_cli import __version__, __appname__ 557 | click.echo(_("You are running {name} version {version}.".format( 558 | name=__appname__, version=__version__))) 559 | click.echo("Configuration found under: {}.".format(_get_config_path())) 560 | click.echo("Logfile stored under: {}.".format(controler.client_config['logfile_path'])) 561 | click.echo("Reports exported to: {}.".format(controler.client_config['export_path'])) 562 | click.echo(get_db_info()) 563 | 564 | 565 | # Helper functions 566 | def _setup_logging(controler): 567 | """Setup logging for the lib_logger as well as client specific logging.""" 568 | formatter = logging.Formatter( 569 | '[%(levelname)s] %(asctime)s %(name)s %(funcName)s: %(message)s') 570 | 571 | lib_logger = controler.lib_logger 572 | client_logger = logging.getLogger('hamster_cli') 573 | # Clear any existing (null)Handlers 574 | lib_logger.handlers = [] 575 | client_logger.handlers = [] 576 | client_logger.setLevel(controler.client_config['log_level']) 577 | lib_logger.setLevel(controler.client_config['log_level']) 578 | controler.client_logger = client_logger 579 | 580 | if controler.client_config['log_console']: 581 | console_handler = logging.StreamHandler() 582 | console_handler.setFormatter(formatter) 583 | lib_logger.addHandler(console_handler) 584 | client_logger.addHandler(console_handler) 585 | 586 | if controler.client_config['logfile_path']: 587 | filename = controler.client_config['logfile_path'] 588 | file_handler = logging.FileHandler(filename, encoding='utf-8') 589 | file_handler.setFormatter(formatter) 590 | lib_logger.addHandler(file_handler) 591 | client_logger.addHandler(file_handler) 592 | 593 | 594 | def _get_config(config_instance): 595 | """ 596 | Rertrieve config dictionaries for backend and client setup. 597 | 598 | Raises: 599 | ValueError: Raised if we fail to process the user supplied config information. 600 | Please note that there will be no log entry as at this point, logging has not 601 | been set up yet. 602 | 603 | Returns: 604 | tuple: ``backend_config, client_config)`` tuple, where each element is a 605 | dictionary storing relevant config data. 606 | """ 607 | # [TODO] 608 | # We propably can make better use of configparsers default config optionn, 609 | # but for now this will do. 610 | 611 | def get_client_config(config): 612 | """ 613 | Process client section of provided config and turn it into proper config dictionary. 614 | 615 | Make sure config values are of proper type and provide basic 616 | sanity checks (e.g. make sure we got a filename if we want to log to 617 | file and such..). 618 | 619 | Not all key/values returned here need to be user configurable! 620 | 621 | It is worth noting that this is where we turn our user provided config information 622 | into the actual dictionaries to be consumed by our backend and client objects. 623 | A particular consequence is that the division of "Client/Backend" in the config 624 | file is purely cosmetic. Another consequence is that not all user provided config 625 | information has to be processed at all. We just take what we need and can safely 626 | ignore the rest. That way we can improve the config file layout without having to 627 | adjust our code all the time. It also means our main code does not have to deal with 628 | turning ``path`` plus ``name`` into a full location and such. 629 | """ 630 | def get_logfile_path(): 631 | log_dir = AppDirs.user_log_dir 632 | return os.path.join(log_dir, config.get('Client', 'log_filename')) 633 | 634 | def get_log_level(): 635 | try: 636 | log_level = LOG_LEVELS[config.get('Client', 'log_level').lower()] 637 | except KeyError: 638 | raise ValueError(_("Unrecognized log level value in config")) 639 | return log_level 640 | 641 | def get_log_console(): 642 | return config.getboolean('Client', 'log_console') 643 | 644 | def get_export_dir(): 645 | """Return path to save exports to. Filenextension will be added by export method.""" 646 | return os.path.join(AppDirs.user_data_dir, 'export') 647 | 648 | return { 649 | 'log_level': get_log_level(), 650 | 'log_console': get_log_console(), 651 | 'logfile_path': get_logfile_path(), 652 | 'export_path': get_export_dir(), 653 | } 654 | 655 | def get_backend_config(config): 656 | """ 657 | Return properly populated config dictionaries for consumption by our application. 658 | 659 | Make sure config values are of proper type and provide basic 660 | sanity checks (e.g. make sure we got a filename if we want to log to 661 | file and such..). 662 | 663 | Setting of config values that are not actually derived from our config file but by 664 | inspecting our runtime environment (e.g. path information) happens here as well. 665 | 666 | Note: 667 | At least the validation code/sanity checks may be relevant to other 668 | clients as well. So mabe this qualifies for inclusion into 669 | hammsterlib? 670 | """ 671 | def get_day_start(): 672 | try: 673 | day_start = datetime.datetime.strptime(config.get('Backend', 674 | 'daystart'), '%H:%M:%S').time() 675 | except ValueError: 676 | raise ValueError(_("We encountered an error when parsing configs" 677 | "'day_start' value! Aborting ...")) 678 | return day_start 679 | 680 | def get_store(): 681 | store = config.get('Backend', 'store') 682 | if store not in hamster_lib.lib.REGISTERED_BACKENDS.keys(): 683 | raise ValueError(_("Unrecognized store option.")) 684 | return store 685 | 686 | def get_db_path(): 687 | return config.get('Backend', 'db_path') 688 | 689 | def get_fact_min_delta(): 690 | return config.get('Backend', 'fact_min_delta') 691 | 692 | def get_tmpfile_path(): 693 | """Return path to file used to store *ongoing fact*.""" 694 | return os.path.join(AppDirs.user_data_dir, 'hamster_cli.fact') 695 | 696 | def get_db_config(): 697 | """Provide a dict with db-specifiy key/value to be added to the backend config.""" 698 | result = {} 699 | engine = config.get('Backend', 'db_engine') 700 | result = {'db_engine': engine} 701 | if engine == 'sqlite': 702 | result.update({'db_path': config.get('Backend', 'db_path')}) 703 | else: 704 | try: 705 | result.update({'db_port': config.get('Backend', 'db_port')}) 706 | except KeyError: 707 | pass 708 | 709 | result.update({ 710 | 'db_host': config.get('Backend', 'db_host'), 711 | 'db_name': config.get('Backend', 'db_name'), 712 | 'db_user': config.get('Backend', 'db_user'), 713 | 'db_password': config.get('Backend', 'db_password'), 714 | }) 715 | return result 716 | 717 | backend_config = { 718 | 'store': get_store(), 719 | 'day_start': get_day_start(), 720 | 'fact_min_delta': get_fact_min_delta(), 721 | 'tmpfile_path': get_tmpfile_path(), 722 | } 723 | backend_config.update(get_db_config()) 724 | return backend_config 725 | 726 | return (get_backend_config(config_instance), get_client_config(config_instance)) 727 | 728 | 729 | def _get_config_instance(): 730 | """ 731 | Return a SafeConfigParser instance. 732 | 733 | If we can not find a config file under its expected location, we trigger creation 734 | of a new default file and return its instance. 735 | 736 | Returns: 737 | SafeConfigParser: Either the config loaded from file or an instance representing 738 | the content of our newly creating default config. 739 | """ 740 | config = SafeConfigParser() 741 | configfile_path = _get_config_path() 742 | if not config.read(configfile_path): 743 | click.echo(_("No valid config file found. Trying to create a new default config" 744 | " at: '{}'.".format(configfile_path))) 745 | config = _write_config_file(configfile_path) 746 | click.echo(_("A new default config file has been successfully created.")) 747 | return config 748 | 749 | 750 | def _get_config_path(): 751 | """Show general information upon client launch.""" 752 | config_dir = AppDirs.user_config_dir 753 | config_filename = 'hamster_cli.conf' 754 | return os.path.join(config_dir, config_filename) 755 | 756 | 757 | def _write_config_file(file_path): 758 | """ 759 | Write a default config file to the specified location. 760 | 761 | Returns: 762 | SafeConfigParser: Instace written to file. 763 | """ 764 | # [FIXME] 765 | # This may be usefull to turn into a proper command, so users can restore to 766 | # factory settings easily. 767 | 768 | def get_db_path(): 769 | return os.path.join(str(AppDirs.user_data_dir), 'hamster_cli.sqlite') 770 | 771 | def get_tmp_file_path(): 772 | return os.path.join(str(AppDirs.user_data_dir), 'hamster_cli.fact') 773 | 774 | config = SafeConfigParser() 775 | 776 | # Backend 777 | config.add_section('Backend') 778 | config.set('Backend', 'store', 'sqlalchemy') 779 | config.set('Backend', 'daystart', '00:00:00') 780 | config.set('Backend', 'fact_min_delta', '60') 781 | config.set('Backend', 'db_engine', 'sqlite') 782 | config.set('Backend', 'db_host', '') 783 | config.set('Backend', 'db_port', '') 784 | config.set('Backend', 'db_name', '') 785 | config.set('Backend', 'db_path', get_db_path()) 786 | config.set('Backend', 'db_user', '') 787 | config.set('Backend', 'db_password', '') 788 | 789 | # Client 790 | config.add_section('Client') 791 | config.set('Client', 'unsorted_localized', 'Unsorted') 792 | config.set('Client', 'log_level', 'debug') 793 | config.set('Client', 'log_console', 'False') 794 | config.set('Client', 'log_filename', 'hamster_cli.log') 795 | 796 | configfile_path = os.path.dirname(file_path) 797 | if not os.path.lexists(configfile_path): 798 | os.makedirs(configfile_path) 799 | with open(file_path, 'w') as fobj: 800 | config.write(fobj) 801 | 802 | return config 803 | 804 | 805 | def _generate_facts_table(facts): 806 | """ 807 | Create a nice looking table representing a set of fact instances. 808 | 809 | Returns a (table, header) tuple. 'table' is a list of ``TableRow`` 810 | instances representing a single fact. 811 | """ 812 | # If you want to change the order just adjust the dict. 813 | headers = { 814 | 'start': _("Start"), 815 | 'end': _("End"), 816 | 'activity': _("Activity"), 817 | 'category': _("Category"), 818 | 'description': _("Description"), 819 | 'delta': _("Duration") 820 | } 821 | 822 | columns = ('start', 'end', 'activity', 'category', 'description', 823 | 'delta') 824 | 825 | header = [headers[column] for column in columns] 826 | 827 | TableRow = namedtuple('TableRow', columns) 828 | 829 | table = [] 830 | for fact in facts: 831 | if fact.category: 832 | category = fact.category.name 833 | else: 834 | category = '' 835 | 836 | table.append(TableRow( 837 | activity=fact.activity.name, 838 | category=category, 839 | description=fact.description, 840 | start=fact.start.strftime('%Y-%m-%d %H:%M'), 841 | end=fact.end.strftime('%Y-%m-%d %H:%M'), 842 | # [TODO] 843 | # Use ``Fact.get_string_delta`` instead! 844 | delta='{minutes} min.'.format(minutes=(int(fact.delta.total_seconds() / 60))), 845 | )) 846 | 847 | return (table, header) 848 | 849 | 850 | def _show_greeting(): 851 | """Display a greeting message providing basic set of information.""" 852 | click.echo(_("Welcome to 'hamster_cli', your friendly time tracker for the command line.")) 853 | click.echo("Copyright (C) 2015-2016, Eric Goller ") 854 | click.echo(_( 855 | "'hamster_cli' is published under the terms of the GPL3, for details please use" 856 | "the 'license' command." 857 | )) 858 | click.echo() 859 | -------------------------------------------------------------------------------- /hamster_cli/help_strings.py: -------------------------------------------------------------------------------- 1 | """Module to provide u18n friendly help text strings for our CLI commands.""" 2 | 3 | 4 | from gettext import gettext as _ 5 | 6 | RUN_HELP = _( 7 | """ 8 | 'hamster-cli' is a time tracker for the command line. 9 | 10 | You can use it to track how you spend your time as well as have it export your 11 | collected data into various output formats. Below you find a list of available 12 | commands. If you call them with the '--help' option you will be shown details 13 | on how to use the command and its supported arguments and parameters. 14 | In general and as usual: if you want to pass any arguments or options that 15 | contain whitespace, you will need to wrap them in quotation marks. 16 | """ 17 | ) 18 | 19 | 20 | SEARCH_HELP = _( 21 | """ 22 | Search facts machting given timerange and search term. 23 | 24 | 'search_term': May be an arbitrary string that will be matched against 25 | existing facts activity names. 26 | 27 | 'time_range': Limit returned facts to those starting within the given time 28 | window. This invormation may be specified in the following format: 29 | '%Y-%m-%d %H:%M - %Y-%m-%d %H:%M'. 30 | 31 | {time_range_info} 32 | \b 33 | About timerange formats: 34 | You may omit any date and/or time portion of that format, in which case we 35 | will complete the missing information as described further down. 36 | Alternativly you can just pass start time offset from now in minutes such 37 | as ' -XX' (where X are 'minutes before now) which will also apply our 38 | 'completion strategy' to the end time related values. Please note that you 39 | if you specify a relative starting time you need to wrap it in quoteation 40 | marks as well as lead with a whitespace in front of the '-' sign. 41 | 42 | \b 43 | How missing date/time information is completed: 44 | * Missing *start date* will fall back to 'today'. 45 | * Misisng *start time* will fall back to your configured 'day_start' 46 | setting. 47 | * Missing *end date* will be the day after today if 'day_start' is not 48 | '00:00', else it will be today. 49 | * Missing *end time* will be one second before your configured 50 | 'day_start' value. 51 | """ 52 | ) 53 | 54 | 55 | LIST_HELP = _( 56 | """ 57 | List facts within a date range. 58 | 59 | Matching facts will be printed in a tabular representation. 60 | 61 | TIME_RANGE: Only fact within this timerange will be considered. 62 | """ 63 | ) 64 | 65 | 66 | START_HELP = _( 67 | """ 68 | Start or add a fact. 69 | 70 | If you add a fact without providing sufficent informaiton about its end a 71 | *ongoing fac* will be created to capture you current work. Only one such 72 | fact can be present at any given time. Please refer to *stop*, *cancel* 73 | and *current* commands for further information. 74 | 75 | \b 76 | RAW_FACT: 77 | 'raw_fact'-string containing information about the Fact to be started. 78 | 'raw_fact' may have the following components: 79 | @ # #, ' 80 | 81 | \b 82 | 83 | May have one of the following three formats: 'HH:MM', 'HH:MM-HH:MM' or 84 | ' -MM'. 85 | * 'HH:MM': Starttime in hours an minutes. 86 | * 'HH:MM-HH:MM' Start and endtime given in ours and minutes. 87 | * ' -MM' Starttime given as 'minutes before *now*. Please be advised: 88 | You need to lead with a whitespace before the '-' sign or put ' -- ' 89 | before the start of your raw_fact. For details refer to 90 | https://github.com/elbenfreund/hamster_cli/issues/108 91 | All times specified refer to *today*. 92 | 93 | \b 94 | 95 | Name of the activity. This is the name of the (potentially recurring) 96 | action you want to track. As an absolute minimum this needs to be 97 | present. 98 | 99 | \b 100 | 101 | You assign activities to categories to group them together. Each 102 | activity/category combination is allowed only once. If you have to 103 | activitynames in two distinct categories however, they will be treated 104 | totaly independent however. 105 | 106 | \b 107 | , , etc 108 | Tags are currently unsupported. 109 | 110 | \b 111 | 112 | A detailed description of that particular instance of performing this 113 | activity. Please note that that is not a description of the category or 114 | the activity in general but a way to provide additional context to this 115 | instance. 116 | 117 | \b 118 | START: 119 | When does the fact start? When specified this will override any start 120 | information present in the *raw fact*. This is usefull if you want to add 121 | a fact with a different date than today. 122 | 123 | \b 124 | END: 125 | When does the fact end? When specified this will override any end information 126 | present in the *raw fact*. 127 | """ 128 | ) 129 | 130 | 131 | STOP_HELP = _( 132 | """Stop tracking current fact saving the result.""" 133 | ) 134 | 135 | 136 | CANCEL_HELP = _( 137 | """Cancel *ongoing fact*. E.g stop it without storing in the backend.""" 138 | ) 139 | 140 | 141 | EXPORT_HELP = _( 142 | """ 143 | Export all facts of within a given timewindow to a file of specified format. 144 | 145 | FORMAT: Export format. Currently supported options are: 'csv', 'xml' and 146 | 'ical'. Defaults to ``csv``. 147 | 148 | START: Start of timewindow. 149 | 150 | END: End of timewindow. 151 | """ 152 | ) 153 | 154 | 155 | CATEGORIES_HELP = _( 156 | """List all existing categories, ordered by name.""" 157 | ) 158 | 159 | 160 | CURRENT_HELP = _( 161 | """Display current tmp fact.""" 162 | ) 163 | 164 | 165 | ACTIVITIES_HELP = _( 166 | """ 167 | List all activities. Provide optional filtering by name. 168 | 169 | Prints all matching activities one per line. 170 | 171 | SEARCH: String to be matched against activity name. 172 | """ 173 | ) 174 | 175 | 176 | LICENSE_HELP = _( 177 | """Show license information.""" 178 | ) 179 | 180 | 181 | DETAILS_HELP = _( 182 | """List details about the runtime environment.""" 183 | ) 184 | -------------------------------------------------------------------------------- /requirements/dev.pip: -------------------------------------------------------------------------------- 1 | # This file specifies all packages required for local development 2 | 3 | -r ./docs.pip 4 | -r ./test.pip 5 | 6 | bumpversion==0.5.3 7 | ipython==4.2.0 8 | wheel==0.29.0 9 | watchdog==0.8.3 10 | -------------------------------------------------------------------------------- /requirements/docs.pip: -------------------------------------------------------------------------------- 1 | # This file specifies all packages required to build the documentation. 2 | 3 | Sphinx==1.4.1 4 | -------------------------------------------------------------------------------- /requirements/test.pip: -------------------------------------------------------------------------------- 1 | # This file is used for local testing with and without tox as well as for 2 | # testing on the CI servers. 3 | 4 | coverage==4.0.3 5 | fauxfactory==2.0.9 6 | isort==4.2.5 7 | pytest==2.9.1 8 | pytest_faker==1.1.0 9 | pytest-factoryboy==1.1.6 10 | tox==2.3.1 11 | future==0.15.2 12 | freezegun==0.3.7 13 | pytest-mock==0.11.0 14 | -------------------------------------------------------------------------------- /setup.cfg: -------------------------------------------------------------------------------- 1 | [bumpversion] 2 | current_version = 0.12.0 3 | commit = True 4 | tag = False 5 | 6 | [bumpversion:file:setup.py] 7 | 8 | [bumpversion:file:hamster_cli/__init__.py] 9 | 10 | [bumpversion:file:docs/conf.py] 11 | 12 | [coverage:run] 13 | branch = True 14 | source = hamster_cli 15 | omit = hamster_cli/cli_client.py 16 | 17 | [coverage:report] 18 | exclude_lines = 19 | if __name__ == .__main__.: 20 | 21 | [isort] 22 | not_skip = __init__.py 23 | known_third_party = appdirs, backports, click, faker, factory, fauxfactory, freezegun, future, 24 | hamster_lib, past, pytest, pytest_factoryboy, six, tabulate 25 | 26 | [pytest] 27 | addopt = 28 | --tb=short 29 | --strict 30 | --rsx 31 | 32 | [flake8] 33 | exclude = build/*.py,docs/*.py,*/.ropeproject/* 34 | ignore = E128 35 | max-line-length = 99 36 | 37 | [doc8] 38 | ignore-path = *.egg-info/,.tox/,docs/_build/ 39 | 40 | [wheel] 41 | universal = 1 42 | 43 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | """Packing metadata for setuptools.""" 4 | 5 | 6 | try: 7 | from setuptools import setup 8 | except ImportError: 9 | from distutils.core import setup 10 | 11 | 12 | with open('README.rst') as readme_file: 13 | readme = readme_file.read() 14 | 15 | with open('HISTORY.rst') as history_file: 16 | history = history_file.read().replace('.. :changelog:', '') 17 | 18 | requirements = [ 19 | 'appdirs', 20 | 'Click', 21 | 'hamster-lib', 22 | 'tabulate', 23 | # py27 compatibility related 24 | 'six', 25 | 'future', 26 | 'configparser >= 3.5.0b2', 27 | ] 28 | 29 | setup( 30 | name='hamster_cli', 31 | version='0.12.0', 32 | description="A basic CLI for the hamster time tracker.", 33 | long_description=readme + '\n\n' + history, 34 | author="Eric Goller", 35 | author_email='Elbenfreund@DenkenInEchtzeit.net', 36 | url='https://github.com/elbenfreund/hamster_cli', 37 | packages=[ 38 | 'hamster_cli', 39 | ], 40 | package_dir={'hamster_cli': 41 | 'hamster_cli'}, 42 | install_requires=requirements, 43 | license="GPL3", 44 | zip_safe=False, 45 | keywords='hamster_cli', 46 | classifiers=[ 47 | 'Development Status :: 2 - Pre-Alpha', 48 | 'Intended Audience :: End Users/Desktop', 49 | 'License :: OSI Approved :: GNU General Public License v3 (GPLv3)', 50 | 'Natural Language :: English', 51 | "Programming Language :: Python :: 2", 52 | 'Programming Language :: Python :: 2.7', 53 | 'Programming Language :: Python :: 3', 54 | 'Programming Language :: Python :: 3.4', 55 | ], 56 | entry_points=''' 57 | [console_scripts] 58 | hamster-cli=hamster_cli.hamster_cli:run 59 | ''' 60 | ) 61 | -------------------------------------------------------------------------------- /tests/__init__.py: -------------------------------------------------------------------------------- 1 | """Testsuite for ``hamster_cli``.""" 2 | -------------------------------------------------------------------------------- /tests/conftest.py: -------------------------------------------------------------------------------- 1 | """ 2 | Fixtures available in our tests. 3 | 4 | In general fixtures shoudl return a single instance. If a fixture is a factory its name should 5 | reflect that. Fixtures that are parametrized should be suffixed with ``_parametrized`` to indicate 6 | the potentially increased costs to it. 7 | """ 8 | 9 | from __future__ import absolute_import, unicode_literals 10 | 11 | import codecs 12 | import datetime 13 | import os 14 | import pickle as pickle 15 | 16 | import fauxfactory 17 | import hamster_lib 18 | import pytest 19 | # Once we drop py2 support, we can use the builtin again but unicode support 20 | # under python 2 is practicly non existing and manual encoding is not easily 21 | # possible. 22 | from backports.configparser import SafeConfigParser 23 | from click.testing import CliRunner 24 | from pytest_factoryboy import register 25 | from six import text_type 26 | 27 | import hamster_cli.hamster_cli as hamster_cli 28 | 29 | from . import factories 30 | 31 | register(factories.CategoryFactory) 32 | register(factories.ActivityFactory) 33 | register(factories.FactFactory) 34 | 35 | 36 | @pytest.fixture 37 | def filename(): 38 | """Provide a filename string.""" 39 | return fauxfactory.gen_utf8() 40 | 41 | 42 | @pytest.fixture 43 | def filepath(tmpdir, filename): 44 | """Provide a fully qualified pathame within our tmp-dir.""" 45 | return os.path.join(tmpdir.strpath, filename) 46 | 47 | 48 | @pytest.fixture 49 | def appdirs(mocker, tmpdir): 50 | """Provide mocked version specific user dirs using a tmpdir.""" 51 | def ensure_directory_exists(directory): 52 | if not os.path.lexists(directory): 53 | os.makedirs(directory) 54 | return directory 55 | 56 | hamster_cli.AppDirs = mocker.MagicMock() 57 | hamster_cli.AppDirs.user_config_dir = ensure_directory_exists(os.path.join( 58 | tmpdir.mkdir('config').strpath, 'hamster_cli/')) 59 | hamster_cli.AppDirs.user_data_dir = ensure_directory_exists(os.path.join( 60 | tmpdir.mkdir('data').strpath, 'hamster_cli/')) 61 | hamster_cli.AppDirs.user_cache_dir = ensure_directory_exists(os.path.join( 62 | tmpdir.mkdir('cache').strpath, 'hamster_cli/')) 63 | hamster_cli.AppDirs.user_log_dir = ensure_directory_exists(os.path.join( 64 | tmpdir.mkdir('log').strpath, 'hamster_cli/')) 65 | return hamster_cli.AppDirs 66 | 67 | 68 | @pytest.fixture 69 | def runner(appdirs, get_config_file): 70 | """Provide a convenient fixture to simulate execution of (sub-) commands.""" 71 | def runner(args=[], **kwargs): 72 | return CliRunner().invoke(hamster_cli.run, args, **kwargs) 73 | return runner 74 | 75 | 76 | @pytest.fixture 77 | def base_config(): 78 | """Provide a generic baseline configuration.""" 79 | return lib_config, client_config 80 | 81 | 82 | @pytest.fixture 83 | def lib_config(tmpdir): 84 | """ 85 | Provide a backend config fixture. This can be passed to a controler directly. 86 | 87 | That means this fixture represents the the result of all typechecks and 88 | type conversions. 89 | """ 90 | return { 91 | 'store': 'sqlalchemy', 92 | 'day_start': datetime.time(hour=0, minute=0, second=0), 93 | 'db_engine': 'sqlite', 94 | 'db_path': ':memory:', 95 | 'tmpfile_path': os.path.join(tmpdir.mkdir('cache2').strpath, 'test.pickle'), 96 | 'fact_min_delta': 60, 97 | } 98 | 99 | 100 | @pytest.fixture 101 | def client_config(tmpdir): 102 | """ 103 | Provide a client config fixture. This can be passed to a controler directly. 104 | 105 | That means this fixture represents the the result of all typechecks and 106 | type conversions. 107 | """ 108 | return { 109 | 'unsorted_localized': 'Unsorted', 110 | 'log_level': 10, 111 | 'log_console': False, 112 | 'logfile_path': False, 113 | 'export_path': os.path.join(tmpdir.mkdir('export').strpath, 'export'), 114 | 'logging_path': os.path.join(tmpdir.mkdir('log2').strpath, 'hamster_cli.log'), 115 | } 116 | 117 | 118 | @pytest.fixture 119 | def config_instance(tmpdir, faker): 120 | """Provide a (dynamicly generated) SafeConfigParser instance.""" 121 | def generate_config(**kwargs): 122 | config = SafeConfigParser() 123 | # Backend 124 | config.add_section('Backend') 125 | config.set('Backend', 'store', kwargs.get('store', 'sqlalchemy')) 126 | config.set('Backend', 'daystart', kwargs.get('daystart', '00:00:00')) 127 | config.set('Backend', 'fact_min_delta', kwargs.get('fact_min_delta', '60')) 128 | config.set('Backend', 'db_engine', kwargs.get('db_engine', 'sqlite')) 129 | config.set('Backend', 'db_path', kwargs.get('db_path', os.path.join( 130 | tmpdir.strpath, 'hamster_db.sqlite'))) 131 | config.set('Backend', 'db_host', kwargs.get('db_host', '')) 132 | config.set('Backend', 'db_name', kwargs.get('db_name', '')) 133 | config.set('Backend', 'db_port', kwargs.get('db_port', '')) 134 | config.set('Backend', 'db_user', kwargs.get('db_user', '')), 135 | config.set('Backend', 'db_password', kwargs.get('db_password', '')) 136 | 137 | # Client 138 | config.add_section('Client') 139 | config.set('Client', 'unsorted_localized', kwargs.get( 140 | 'unsorted_localized', 'Unsorted')) 141 | config.set('Client', 'log_level', kwargs.get('log_level', 'debug')) 142 | config.set('Client', 'log_console', kwargs.get('log_console', '0')) 143 | config.set('Client', 'log_filename', kwargs.get('log_filename', faker.file_name())) 144 | return config 145 | return generate_config 146 | 147 | 148 | @pytest.fixture 149 | def config_file(config_instance, appdirs): 150 | """Provide a config file store under our fake config dir.""" 151 | with codecs.open(os.path.join(appdirs.user_config_dir, 'hamster_cli.conf'), 152 | 'w', encoding='utf-8') as fobj: 153 | config_instance().write(fobj) 154 | 155 | 156 | @pytest.fixture 157 | def get_config_file(config_instance, appdirs): 158 | """Provide a dynamic config file store under our fake config dir.""" 159 | def generate(**kwargs): 160 | instance = config_instance(**kwargs) 161 | with codecs.open(os.path.join(appdirs.user_config_dir, 'hamster_cli.conf'), 162 | 'w', encoding='utf-8') as fobj: 163 | instance.write(fobj) 164 | return instance 165 | return generate 166 | 167 | 168 | # Various config settings 169 | @pytest.fixture 170 | def db_name(request): 171 | """Return a randomized database name.""" 172 | return fauxfactory.gen_utf8() 173 | 174 | 175 | @pytest.fixture 176 | def db_user(request): 177 | """Return a randomized database username.""" 178 | return fauxfactory.gen_utf8() 179 | 180 | 181 | @pytest.fixture 182 | def db_password(request): 183 | """Return a randomized database password.""" 184 | return fauxfactory.gen_utf8() 185 | 186 | 187 | @pytest.fixture(params=(fauxfactory.gen_latin1(), fauxfactory.gen_ipaddr())) 188 | def db_host(request): 189 | """Return a randomized database username.""" 190 | return request.param 191 | 192 | 193 | @pytest.fixture 194 | def db_port(request): 195 | """Return a randomized database port.""" 196 | return text_type(fauxfactory.gen_integer(min_value=0, max_value=65535)) 197 | 198 | 199 | @pytest.fixture 200 | def tmp_fact(controler_with_logging, fact): 201 | """Fixture that ensures there is a ``ongoing fact`` file present at the expected place.""" 202 | fact.end = None 203 | fact = controler_with_logging.facts.save(fact) 204 | return fact 205 | 206 | 207 | @pytest.fixture 208 | def invalid_tmp_fact(tmpdir, client_config): 209 | """Fixture to provide a *ongoing fact* file that contains an invalid object instance.""" 210 | with open(client_config['tmp_filename'], 'wb') as fobj: 211 | pickle.dump(None, fobj) 212 | 213 | 214 | @pytest.yield_fixture 215 | def controler(lib_config, client_config): 216 | """Provide a pseudo controler instance.""" 217 | controler = hamster_lib.HamsterControl(lib_config) 218 | controler.client_config = client_config 219 | yield controler 220 | controler.store.cleanup() 221 | 222 | 223 | @pytest.yield_fixture 224 | def controler_with_logging(lib_config, client_config): 225 | """Provide a pseudo controler instance with logging setup.""" 226 | controler = hamster_lib.HamsterControl(lib_config) 227 | controler.client_config = client_config 228 | # [FIXME] 229 | # We souldn't shortcut like this! 230 | hamster_cli._setup_logging(controler) 231 | yield controler 232 | controler.store.cleanup() 233 | 234 | 235 | @pytest.fixture(params=[ 236 | ('', '', { 237 | 'filter_term': '', 238 | 'start': None, 239 | 'end': None, 240 | }), 241 | ('', '2015-12-12 18:00 - 2015-12-12 19:30', { 242 | 'filter_term': '', 243 | 'start': datetime.datetime(2015, 12, 12, 18, 0, 0), 244 | 'end': datetime.datetime(2015, 12, 12, 19, 30, 0) 245 | }), 246 | ('', '2015-12-12 18:00', { 247 | 'filter_term': '', 248 | 'start': datetime.datetime(2015, 12, 12, 18, 0, 0), 249 | 'end': datetime.datetime(2015, 12, 12, 23, 59, 59) 250 | }), 251 | ('', '2015-12-12', { 252 | 'filter_term': '', 253 | 'start': datetime.datetime(2015, 12, 12, 0, 0, 0), 254 | 'end': datetime.datetime(2015, 12, 12, 23, 59, 59) 255 | }), 256 | ('', '13:00', { 257 | 'filter_term': '', 258 | 'start': datetime.datetime(2015, 12, 12, 13, 0, 0), 259 | 'end': datetime.datetime(2015, 12, 12, 23, 59, 59), 260 | }), 261 | ]) 262 | def search_parameter_parametrized(request): 263 | """Provide a parametrized set of arguments for the ``search`` command.""" 264 | return request.param 265 | -------------------------------------------------------------------------------- /tests/factories.py: -------------------------------------------------------------------------------- 1 | """Factories to provide easy to use randomized instances of our main objects.""" 2 | 3 | import datetime 4 | 5 | import factory 6 | import faker 7 | import hamster_lib 8 | 9 | 10 | class CategoryFactory(factory.Factory): 11 | """Provide a factory for randomized ``hamster_lib.Category`` instances.""" 12 | 13 | pk = None 14 | name = factory.Faker('word') 15 | 16 | class Meta: 17 | model = hamster_lib.Category 18 | 19 | 20 | class ActivityFactory(factory.Factory): 21 | """Provide a factory for randomized ``hamster_lib.Activity`` instances.""" 22 | 23 | pk = None 24 | name = factory.Faker('word') 25 | category = factory.SubFactory(CategoryFactory) 26 | deleted = False 27 | 28 | class Meta: 29 | model = hamster_lib.Activity 30 | 31 | 32 | class FactFactory(factory.Factory): 33 | """Provide a factory for randomized ``hamster_lib.Fact`` instances.""" 34 | 35 | pk = None 36 | activity = factory.SubFactory(ActivityFactory) 37 | start = faker.Faker().date_time() 38 | end = start + datetime.timedelta(hours=3) 39 | description = factory.Faker('paragraph') 40 | 41 | class Meta: 42 | model = hamster_lib.Fact 43 | -------------------------------------------------------------------------------- /tests/test_hamster_cli.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | import datetime 4 | import logging 5 | import os 6 | 7 | import fauxfactory 8 | import hamster_lib 9 | import pytest 10 | # Once we drop py2 support, we can use the builtin again but unicode support 11 | # under python 2 is practicly non existing and manual encoding is not easily 12 | # possible. 13 | from backports.configparser import SafeConfigParser 14 | from click import ClickException 15 | from freezegun import freeze_time 16 | 17 | from hamster_cli import __appname__, __version__, hamster_cli 18 | 19 | 20 | class TestSearch(object): 21 | """Unit tests for search command.""" 22 | 23 | @freeze_time('2015-12-12 18:00') 24 | def test_search(self, controler, mocker, fact, search_parameter_parametrized): 25 | """Ensure that your search parameters get passed on to the apropiate backend function.""" 26 | search_term, time_range, expectation = search_parameter_parametrized 27 | controler.facts.get_all = mocker.MagicMock(return_value=[fact]) 28 | hamster_cli._search(controler, search_term, time_range) 29 | controler.facts.get_all.assert_called_with(**expectation) 30 | 31 | 32 | class TestStart(object): 33 | """Unit test related to starting a new fact.""" 34 | 35 | @freeze_time('2015-12-25 18:00') 36 | @pytest.mark.parametrize(('raw_fact', 'start', 'end', 'expectation'), [ 37 | ('foo@bar', '2015-12-12 13:00', '2015-12-12 16:30', { 38 | 'activity': 'foo', 39 | 'category': 'bar', 40 | 'start': datetime.datetime(2015, 12, 12, 13, 0, 0), 41 | 'end': datetime.datetime(2015, 12, 12, 16, 30, 0), 42 | }), 43 | ('10:00 - 18:00 foo@bar', '2015-12-12 13:00', '', { 44 | 'activity': 'foo', 45 | 'category': 'bar', 46 | 'start': datetime.datetime(2015, 12, 12, 13, 0, 0), 47 | 'end': datetime.datetime(2015, 12, 25, 18, 00, 0), 48 | }), 49 | # 'ongoing fact's 50 | ('foo@bar', '2015-12-12 13:00', '', { 51 | 'activity': 'foo', 52 | 'category': 'bar', 53 | 'start': datetime.datetime(2015, 12, 12, 13, 0, 0), 54 | 'end': None, 55 | }), 56 | ('11:00 foo@bar', '2015-12-12 13:00', '', { 57 | 'activity': 'foo', 58 | 'category': 'bar', 59 | 'start': datetime.datetime(2015, 12, 12, 13, 0, 0), 60 | 'end': None, 61 | }), 62 | ]) 63 | def test_start_add_new_fact(self, controler_with_logging, mocker, raw_fact, 64 | start, end, expectation): 65 | """ 66 | Test that inpul validation and assignment of start/endtime works is done as expected. 67 | """ 68 | controler = controler_with_logging 69 | controler.facts.save = mocker.MagicMock() 70 | hamster_cli._start(controler, raw_fact, start, end) 71 | assert controler.facts.save.called 72 | args, kwargs = controler.facts.save.call_args 73 | fact = args[0] 74 | assert fact.start == expectation['start'] 75 | assert fact.end == expectation['end'] 76 | assert fact.activity.name == expectation['activity'] 77 | assert fact.category.name == expectation['category'] 78 | 79 | 80 | class TestStop(object): 81 | """Unit test concerning the stop command.""" 82 | 83 | def test_stop_existing_tmp_fact(self, tmp_fact, controler_with_logging, mocker): 84 | """Make sure stoping an ongoing fact works as intended.""" 85 | controler_with_logging.facts.stop_tmp_fact = mocker.MagicMock() 86 | hamster_cli._stop(controler_with_logging) 87 | assert controler_with_logging.facts.stop_tmp_fact.called 88 | 89 | def test_stop_no_existing_tmp_fact(self, controler_with_logging, capsys): 90 | """Make sure that stop without actually an ongoing fact leads to an error.""" 91 | controler = controler_with_logging 92 | with pytest.raises(ClickException): 93 | hamster_cli._stop(controler) 94 | out, err = capsys.readouterr() 95 | assert 'Unable to continue' in err 96 | 97 | 98 | class TestCancel(object): 99 | """Unit tests related to cancelation of an ongoing fact.""" 100 | 101 | def test_cancel_existing_tmp_fact(self, tmp_fact, controler_with_logging, mocker, 102 | capsys): 103 | """Test cancelation in case there is an ongoing fact.""" 104 | controler = controler_with_logging 105 | controler.facts.cancel_tmp_fact = mocker.MagicMock(return_value=None) 106 | hamster_cli._cancel(controler) 107 | out, err = capsys.readouterr() 108 | assert controler.facts.cancel_tmp_fact.called 109 | assert 'canceled' in out 110 | 111 | def test_cancel_no_existing_tmp_fact(self, controler_with_logging, capsys): 112 | """Test cancelation in case there is no actual ongoing fact.""" 113 | with pytest.raises(ClickException): 114 | hamster_cli._cancel(controler_with_logging) 115 | out, err = capsys.readouterr() 116 | assert 'Nothing tracked right now' in err 117 | 118 | 119 | class TestExport(object): 120 | """Unittests related to data export.""" 121 | @pytest.mark.parametrize('format', ['html', fauxfactory.gen_latin1()]) 122 | def test_invalid_format(self, controler_with_logging, format, mocker): 123 | """Make sure that passing an invalid format exits prematurely.""" 124 | controler = controler_with_logging 125 | with pytest.raises(ClickException): 126 | hamster_cli._export(controler, format, None, None) 127 | 128 | def test_csv(self, controler, controler_with_logging, mocker): 129 | """Make sure that a valid format returns the apropiate writer class.""" 130 | hamster_lib.reports.TSVWriter = mocker.MagicMock() 131 | hamster_cli._export(controler, 'csv', None, None) 132 | assert hamster_lib.reports.TSVWriter.called 133 | 134 | def test_ical(self, controler, controler_with_logging, mocker): 135 | """Make sure that a valid format returns the apropiate writer class.""" 136 | hamster_lib.reports.ICALWriter = mocker.MagicMock() 137 | hamster_cli._export(controler, 'ical', None, None) 138 | assert hamster_lib.reports.ICALWriter.called 139 | 140 | def test_xml(self, controler, controler_with_logging, mocker): 141 | """Make sure that passing 'xml' as format parameter returns the apropiate writer class.""" 142 | hamster_lib.reports.XMLWriter = mocker.MagicMock() 143 | hamster_cli._export(controler, 'xml', None, None) 144 | assert hamster_lib.reports.XMLWriter.called 145 | 146 | def test_with_start(self, controler, controler_with_logging, tmpdir, mocker): 147 | """Make sure that passing a end date is passed to the fact gathering method.""" 148 | controler.facts.get_all = mocker.MagicMock() 149 | path = os.path.join(tmpdir.mkdir('report').strpath, 'report.csv') 150 | hamster_lib.reports.TSVWriter = mocker.MagicMock( 151 | return_value=hamster_lib.reports.TSVWriter(path) 152 | ) 153 | start = fauxfactory.gen_datetime() 154 | hamster_cli._export(controler, 'csv', start, None) 155 | args, kwargs = controler.facts.get_all.call_args 156 | assert kwargs['start'] == start 157 | 158 | def test_with_end(self, controler, controler_with_logging, tmpdir, mocker): 159 | """Make sure that passing a end date is passed to the fact gathering method.""" 160 | controler.facts.get_all = mocker.MagicMock() 161 | path = os.path.join(tmpdir.mkdir('report').strpath, 'report.csv') 162 | hamster_lib.reports.TSVWriter = mocker.MagicMock( 163 | return_value=hamster_lib.reports.TSVWriter(path) 164 | ) 165 | end = fauxfactory.gen_datetime() 166 | hamster_cli._export(controler, 'csv', None, end) 167 | args, kwargs = controler.facts.get_all.call_args 168 | assert kwargs['end'] == end 169 | 170 | 171 | class TestCategories(object): 172 | """Unittest related to category listings.""" 173 | 174 | def test_categories(self, controler_with_logging, category, mocker, capsys): 175 | """Make sure the categories get displayed to the user.""" 176 | controler = controler_with_logging 177 | controler.categories.get_all = mocker.MagicMock(return_value=[category]) 178 | hamster_cli._categories(controler) 179 | out, err = capsys.readouterr() 180 | assert category.name in out 181 | assert controler.categories.get_all.called 182 | 183 | 184 | class TestCurrent(object): 185 | """Unittest for dealing with 'ongoing facts'.""" 186 | 187 | def test_tmp_fact(self, controler, tmp_fact, controler_with_logging, capsys, fact, mocker): 188 | """Make sure the current fact is displayed if there is one.""" 189 | controler = controler_with_logging 190 | controler.facts.get_tmp_fact = mocker.MagicMock(return_value=fact) 191 | hamster_cli._current(controler) 192 | out, err = capsys.readouterr() 193 | assert controler.facts.get_tmp_fact 194 | assert str(fact) in out 195 | 196 | def test_no_tmp_fact(self, controler_with_logging, capsys): 197 | """Make sure we display proper feedback if there is no current 'ongoing fact.""" 198 | controler = controler_with_logging 199 | with pytest.raises(ClickException): 200 | hamster_cli._current(controler) 201 | out, err = capsys.readouterr() 202 | assert 'There seems no be no activity beeing tracked right now' in err 203 | 204 | 205 | class TestActivities(object): 206 | """Unittests for the ``activities`` command.""" 207 | 208 | def test_activities_no_category(self, controler, activity, mocker, capsys): 209 | """Make sure command works if activities do not have a category associated.""" 210 | activity.category = None 211 | controler.activities.get_all = mocker.MagicMock( 212 | return_value=[activity]) 213 | mocker.patch('hamster_cli.hamster_cli.tabulate') 214 | hamster_cli.tabulate = mocker.MagicMock( 215 | return_value='{}, {}'.format(activity.name, None)) 216 | hamster_cli._activities(controler, '') 217 | out, err = capsys.readouterr() 218 | assert activity.name in out 219 | hamster_cli.tabulate.call_args[0] == [(activity.name, None)] 220 | 221 | def test_activities_with_category(self, controler, activity, mocker, 222 | capsys): 223 | """Make sure activity name and category are displayed if present.""" 224 | controler.activities.get_all = mocker.MagicMock( 225 | return_value=[activity]) 226 | hamster_cli._activities(controler, '') 227 | out, err = capsys.readouterr() 228 | assert activity.name in out 229 | assert activity.category.name in out 230 | 231 | def test_activities_with_search_term(self, controler, activity, mocker, 232 | capsys): 233 | """Make sure the search term is passed on.""" 234 | controler.activities.get_all = mocker.MagicMock( 235 | return_value=[activity]) 236 | hamster_cli._activities(controler, 'foobar') 237 | out, err = capsys.readouterr() 238 | assert controler.activities.get_all.called 239 | controler.activities.get_all.assert_called_with(search_term='foobar') 240 | assert activity.name in out 241 | assert activity.category.name in out 242 | 243 | 244 | class TestDetails(object): 245 | """Unittests for the ``details`` command.""" 246 | 247 | def test_details_general_data_is_shown(self, controler, capsys): 248 | """Make sure user recieves the desired output.""" 249 | hamster_cli._details(controler) 250 | out, err = capsys.readouterr() 251 | strings = (__appname__, __version__, 'Configuration', 'Logfile', 'Reports') 252 | for string in strings: 253 | assert string in out 254 | 255 | def test_details_sqlite(self, controler, appdirs, mocker, capsys): 256 | """Make sure database details for sqlite are shown properly.""" 257 | controler._get_store = mocker.MagicMock() 258 | engine, path = 'sqlite', appdirs.user_data_dir 259 | controler.config['db_engine'] = engine 260 | controler.config['db_path'] = path 261 | hamster_cli._details(controler) 262 | out, err = capsys.readouterr() 263 | for item in (engine, path): 264 | assert item in out 265 | 266 | def test_details_non_sqlite(self, controler, capsys, db_port, db_host, db_name, 267 | db_user, db_password, mocker): 268 | """ 269 | Make sure database details for non-sqlite are shown properly. 270 | 271 | We need to mock the backend Controler because it would try to setup a 272 | database connection right away otherwise. 273 | """ 274 | controler._get_store = mocker.MagicMock() 275 | controler.config['db_engine'] = 'postgres' 276 | controler.config['db_name'] = db_name 277 | controler.config['db_host'] = db_host 278 | controler.config['db_user'] = db_user 279 | controler.config['db_password'] = db_password 280 | controler.config['db_port'] = db_port 281 | hamster_cli._details(controler) 282 | out, err = capsys.readouterr() 283 | for item in ('postgres', db_host, db_name, db_user): 284 | assert item in out 285 | if db_port: 286 | assert db_port in out 287 | assert db_password not in out 288 | 289 | 290 | class TestLicense(object): 291 | """Unittests for ``license`` command.""" 292 | 293 | def test_license_is_shown(self, capsys): 294 | """Make sure the license text is actually displayed.""" 295 | hamster_cli._license() 296 | out, err = capsys.readouterr() 297 | assert "'hamster_cli' is free software" in out 298 | assert "GNU General Public License" in out 299 | assert "version 3" in out 300 | 301 | 302 | class TestSetupLogging(object): 303 | """Make sure that our logging setup is executed as expected.""" 304 | 305 | def test_setup_logging(self, controler, client_config, lib_config): 306 | """Test that library and client logger have log level set according to config.""" 307 | hamster_cli._setup_logging(controler) 308 | assert controler.lib_logger.level == ( 309 | controler.client_config['log_level']) 310 | assert controler.client_logger.level == ( 311 | controler.client_config['log_level']) 312 | 313 | def test_setup_logging_log_console_true(self, controler): 314 | """Make sure that if console loggin is on lib and client logger have a streamhandler.""" 315 | controler.client_config['log_console'] = True 316 | hamster_cli._setup_logging(controler) 317 | assert isinstance(controler.client_logger.handlers[0], 318 | logging.StreamHandler) 319 | assert isinstance(controler.lib_logger.handlers[0], 320 | logging.StreamHandler) 321 | assert controler.client_logger.handlers[0].formatter 322 | 323 | def test_setup_logging_no_logging(self, controler): 324 | """Make sure that if no logging enabled, our loggers don't have any handlers.""" 325 | hamster_cli._setup_logging(controler) 326 | assert controler.lib_logger.handlers == [] 327 | assert controler.client_logger.handlers == [] 328 | 329 | def test_setup_logging_log_file_true(self, controler, appdirs): 330 | """Make sure that if we enable a logfile_path, both loggers recieve a ``FileHandler``.""" 331 | controler.client_config['logfile_path'] = os.path.join(appdirs.user_log_dir, 'foobar.log') 332 | hamster_cli._setup_logging(controler) 333 | assert isinstance(controler.lib_logger.handlers[0], 334 | logging.FileHandler) 335 | assert isinstance(controler.client_logger.handlers[0], 336 | logging.FileHandler) 337 | 338 | 339 | class TestGetConfig(object): 340 | """Make sure that turning a config instance into proper config dictionaries works.""" 341 | 342 | @pytest.mark.parametrize('log_level', ['debug']) 343 | def test_log_levels_valid(self, log_level, config_instance): 344 | """Make sure that *string loglevels* translate to their respective integers properly.""" 345 | backend, client = hamster_cli._get_config( 346 | config_instance(log_level=log_level)) 347 | assert client['log_level'] == 10 348 | 349 | @pytest.mark.parametrize('log_level', ['foobar']) 350 | def test_log_levels_invalid(self, log_level, config_instance): 351 | """Test that invalid *string loglevels* raise ``ValueError``.""" 352 | with pytest.raises(ValueError): 353 | backend, client = hamster_cli._get_config( 354 | config_instance(log_level=log_level)) 355 | 356 | @pytest.mark.parametrize('day_start', ['05:00:00']) 357 | def test_daystart_valid(self, config_instance, day_start): 358 | """Test that ``day_start`` string translate to proper ``datetime.time`` instances.""" 359 | backend, client = hamster_cli._get_config(config_instance( 360 | daystart=day_start)) 361 | assert backend['day_start'] == datetime.datetime.strptime( 362 | '05:00:00', '%H:%M:%S').time() 363 | 364 | @pytest.mark.parametrize('day_start', ['foobar']) 365 | def test_daystart_invalid(self, config_instance, day_start): 366 | """Test that invalid ``day_start`` strings raises ``ValueError``.""" 367 | with pytest.raises(ValueError): 368 | backend, client = hamster_cli._get_config( 369 | config_instance(daystart=day_start)) 370 | 371 | def test_invalid_store(self, config_instance): 372 | """Make sure that encountering an unsupportet store will raise an exception.""" 373 | with pytest.raises(ValueError): 374 | backend, client = hamster_cli._get_config(config_instance(store='foobar')) 375 | 376 | def test_non_sqlite(self, config_instance): 377 | """Make sure that passing a store other than 'sqlalchemy' raises exception.""" 378 | config_instance = config_instance(db_engine='postgres') 379 | backend, client = hamster_cli._get_config(config_instance) 380 | assert backend['db_host'] == config_instance.get('Backend', 'db_host') 381 | assert backend['db_port'] == config_instance.get('Backend', 'db_port') 382 | assert backend['db_name'] == config_instance.get('Backend', 'db_name') 383 | assert backend['db_user'] == config_instance.get('Backend', 'db_user') 384 | assert backend['db_password'] == config_instance.get('Backend', 'db_password') 385 | 386 | 387 | class TestGetConfigInstance(object): 388 | def test_no_file_present(self, appdirs, mocker): 389 | """Make sure a new vanilla config is written if no config is found.""" 390 | mocker.patch('hamster_cli.hamster_cli._write_config_file') 391 | hamster_cli._get_config_instance() 392 | assert hamster_cli._write_config_file.called 393 | 394 | def test_file_present(self, config_instance, config_file, mocker): 395 | """Make sure we try parsing a found config file.""" 396 | result = hamster_cli._get_config_instance() 397 | assert result.get('Backend', 'store') == config_instance().get('Backend', 'store') 398 | 399 | def test_get_config_path(self, appdirs, mocker): 400 | """Make sure the config target path is constructed to our expectations.""" 401 | mocker.patch('hamster_cli.hamster_cli._write_config_file') 402 | hamster_cli._get_config_instance() 403 | expectation = os.path.join(appdirs.user_config_dir, 'hamster_cli.conf') 404 | assert hamster_cli._write_config_file.called_with(expectation) 405 | 406 | 407 | class TestGenerateTable(object): 408 | def test_generate_table(self, fact): 409 | """Make sure the table contains all expected fact data.""" 410 | table, header = hamster_cli._generate_facts_table([fact]) 411 | assert table[0].start == fact.start.strftime('%Y-%m-%d %H:%M') 412 | assert table[0].activity == fact.activity.name 413 | 414 | def test_header(self): 415 | """Make sure the tables header matches our expectation.""" 416 | table, header = hamster_cli._generate_facts_table([]) 417 | assert len(header) == 6 418 | 419 | 420 | class TestWriteConfigFile(object): 421 | def test_file_is_written(self, filepath): 422 | """Make sure the file is written. Content is not checked, this is ConfigParsers job.""" 423 | hamster_cli._write_config_file(filepath) 424 | assert os.path.lexists(filepath) 425 | 426 | def test_return_config_instance(self, filepath): 427 | """Make sure we return a ``SafeConfigParser`` instance.""" 428 | result = hamster_cli._write_config_file(filepath) 429 | assert isinstance(result, SafeConfigParser) 430 | 431 | def test_non_existing_path(self, tmpdir, filename): 432 | """Make sure that the path-parents are created ifnot present.""" 433 | filepath = os.path.join(tmpdir.strpath, 'foobar') 434 | assert os.path.lexists(filepath) is False 435 | hamster_cli._write_config_file(filepath) 436 | assert os.path.lexists(filepath) 437 | 438 | 439 | class TestHamsterAppDirs(object): 440 | """Make sure that our custom AppDirs works as intended.""" 441 | 442 | def test_user_data_dir_returns_directoy(self, tmpdir, mocker): 443 | """Make sure method returns directory.""" 444 | path = tmpdir.strpath 445 | mocker.patch('hamster_cli.hamster_cli.appdirs.user_data_dir', return_value=path) 446 | appdir = hamster_cli.HamsterAppDirs('hamster_cli') 447 | assert appdir.user_data_dir == path 448 | 449 | @pytest.mark.parametrize('create', [True, False]) 450 | def test_user_data_dir_creates_file(self, tmpdir, mocker, create, faker): 451 | """Make sure that path creation depends on ``create`` attribute.""" 452 | path = os.path.join(tmpdir.strpath, '{}/'.format(faker.word())) 453 | mocker.patch('hamster_cli.hamster_cli.appdirs.user_data_dir', return_value=path) 454 | appdir = hamster_cli.HamsterAppDirs('hamster_cli') 455 | appdir.create = create 456 | assert os.path.exists(appdir.user_data_dir) is create 457 | 458 | def test_site_data_dir_returns_directoy(self, tmpdir, mocker): 459 | """Make sure method returns directory.""" 460 | path = tmpdir.strpath 461 | mocker.patch('hamster_cli.hamster_cli.appdirs.site_data_dir', return_value=path) 462 | appdir = hamster_cli.HamsterAppDirs('hamster_cli') 463 | assert appdir.site_data_dir == path 464 | 465 | @pytest.mark.parametrize('create', [True, False]) 466 | def test_site_data_dir_creates_file(self, tmpdir, mocker, create, faker): 467 | """Make sure that path creation depends on ``create`` attribute.""" 468 | path = os.path.join(tmpdir.strpath, '{}/'.format(faker.word())) 469 | mocker.patch('hamster_cli.hamster_cli.appdirs.site_data_dir', return_value=path) 470 | appdir = hamster_cli.HamsterAppDirs('hamster_cli') 471 | appdir.create = create 472 | assert os.path.exists(appdir.site_data_dir) is create 473 | 474 | def test_user_config_dir_returns_directoy(self, tmpdir, mocker): 475 | """Make sure method returns directory.""" 476 | path = tmpdir.strpath 477 | mocker.patch('hamster_cli.hamster_cli.appdirs.user_config_dir', return_value=path) 478 | appdir = hamster_cli.HamsterAppDirs('hamster_cli') 479 | assert appdir.user_config_dir == path 480 | 481 | @pytest.mark.parametrize('create', [True, False]) 482 | def test_user_config_dir_creates_file(self, tmpdir, mocker, create, faker): 483 | """Make sure that path creation depends on ``create`` attribute.""" 484 | path = os.path.join(tmpdir.strpath, '{}/'.format(faker.word())) 485 | mocker.patch('hamster_cli.hamster_cli.appdirs.user_config_dir', return_value=path) 486 | appdir = hamster_cli.HamsterAppDirs('hamster_cli') 487 | appdir.create = create 488 | assert os.path.exists(appdir.user_config_dir) is create 489 | 490 | def test_site_config_dir_returns_directoy(self, tmpdir, mocker): 491 | """Make sure method returns directory.""" 492 | path = tmpdir.strpath 493 | mocker.patch('hamster_cli.hamster_cli.appdirs.site_config_dir', return_value=path) 494 | appdir = hamster_cli.HamsterAppDirs('hamster_cli') 495 | assert appdir.site_config_dir == path 496 | 497 | @pytest.mark.parametrize('create', [True, False]) 498 | def test_site_config_dir_creates_file(self, tmpdir, mocker, create, faker): 499 | """Make sure that path creation depends on ``create`` attribute.""" 500 | path = os.path.join(tmpdir.strpath, '{}/'.format(faker.word())) 501 | mocker.patch('hamster_cli.hamster_cli.appdirs.site_config_dir', return_value=path) 502 | appdir = hamster_cli.HamsterAppDirs('hamster_cli') 503 | appdir.create = create 504 | assert os.path.exists(appdir.site_config_dir) is create 505 | 506 | def test_user_cache_dir_returns_directoy(self, tmpdir, mocker): 507 | """Make sure method returns directory.""" 508 | path = tmpdir.strpath 509 | mocker.patch('hamster_cli.hamster_cli.appdirs.user_cache_dir', return_value=path) 510 | appdir = hamster_cli.HamsterAppDirs('hamster_cli') 511 | assert appdir.user_cache_dir == path 512 | 513 | @pytest.mark.parametrize('create', [True, False]) 514 | def test_user_cache_dir_creates_file(self, tmpdir, mocker, create, faker): 515 | """Make sure that path creation depends on ``create`` attribute.""" 516 | path = os.path.join(tmpdir.strpath, '{}/'.format(faker.word())) 517 | mocker.patch('hamster_cli.hamster_cli.appdirs.user_cache_dir', return_value=path) 518 | appdir = hamster_cli.HamsterAppDirs('hamster_cli') 519 | appdir.create = create 520 | assert os.path.exists(appdir.user_cache_dir) is create 521 | 522 | def test_user_log_dir_returns_directoy(self, tmpdir, mocker): 523 | """Make sure method returns directory.""" 524 | path = tmpdir.strpath 525 | mocker.patch('hamster_cli.hamster_cli.appdirs.user_log_dir', return_value=path) 526 | appdir = hamster_cli.HamsterAppDirs('hamster_cli') 527 | assert appdir.user_log_dir == path 528 | 529 | @pytest.mark.parametrize('create', [True, False]) 530 | def test_user_log_dir_creates_file(self, tmpdir, mocker, create, faker): 531 | """Make sure that path creation depends on ``create`` attribute.""" 532 | path = os.path.join(tmpdir.strpath, '{}/'.format(faker.word())) 533 | mocker.patch('hamster_cli.hamster_cli.appdirs.user_log_dir', return_value=path) 534 | appdir = hamster_cli.HamsterAppDirs('hamster_cli') 535 | appdir.create = create 536 | assert os.path.exists(appdir.user_log_dir) is create 537 | 538 | 539 | class TestShowGreeting(object): 540 | """Make shure our greeting function behaves as expected.""" 541 | 542 | def test_shows_welcome(self, capsys): 543 | """Make sure we welcome our users properly.""" 544 | hamster_cli._show_greeting() 545 | out, err = capsys.readouterr() 546 | assert "Welcome to 'hamster_cli'" in out 547 | 548 | def test_shows_copyright(self, capsys): 549 | """Make sure we show basic copyright information.""" 550 | hamster_cli._show_greeting() 551 | out, err = capsys.readouterr() 552 | assert "Copyright" in out 553 | 554 | def test_shows_license(self, capsys): 555 | """Make sure we display a brief reference to the license.""" 556 | hamster_cli._show_greeting() 557 | out, err = capsys.readouterr() 558 | assert "GPL3" in out 559 | assert "'license' command" in out 560 | -------------------------------------------------------------------------------- /tests/test_integration_tests.py: -------------------------------------------------------------------------------- 1 | from __future__ import unicode_literals 2 | 3 | 4 | class TestBasicRun(object): 5 | def test_basic_run(self, runner): 6 | """Make sure that invoking the command passes without exception.""" 7 | result = runner() 8 | assert result.exit_code == 0 9 | 10 | 11 | class TestSearch(object): 12 | def test_search(self, runner): 13 | """Make sure that invoking the command passes without exception.""" 14 | result = runner(['search', 'foobar']) 15 | assert result.exit_code == 0 16 | 17 | 18 | class TestList(object): 19 | def test_list(self, runner): 20 | """Make sure that invoking the command passes without exception.""" 21 | result = runner(['list']) 22 | assert result.exit_code == 0 23 | 24 | 25 | class TestStart(object): 26 | def test_start(self, runner): 27 | """Make sure that invoking the command passes without exception.""" 28 | result = runner(['start', 'coding', '', '']) 29 | assert result.exit_code == 0 30 | 31 | 32 | class TestStop(object): 33 | def test_stop(self, runner): 34 | """ 35 | Make sure that invoking the command passes without exception. 36 | 37 | As we don't have a ``ongoing fact`` by default, we expect an expectation to be raised. 38 | """ 39 | result = runner(['stop']) 40 | assert result.exit_code == 1 41 | 42 | 43 | class TestCancel(object): 44 | def test_cancel(self, runner): 45 | """ 46 | Make sure that invoking the command passes without exception. 47 | 48 | As we don't have a ``ongoing fact`` by default, we expect an expectation to be raised. 49 | """ 50 | result = runner(['cancel']) 51 | assert result.exit_code == 1 52 | 53 | 54 | class TestCurrent(object): 55 | def test_current(self, runner): 56 | """ 57 | Make sure that invoking the command passes without exception. 58 | 59 | As we don't have a ``ongoing fact`` by default, we expect an expectation to be raised. 60 | """ 61 | result = runner(['current']) 62 | assert result.exit_code == 1 63 | 64 | 65 | class TestExport(object): 66 | def test_export(self, runner): 67 | """Make sure that invoking the command passes without exception.""" 68 | result = runner(['export']) 69 | assert result.exit_code == 0 70 | 71 | 72 | class TestCategories(object): 73 | def test_categories(self, runner): 74 | """Make sure that invoking the command passes without exception.""" 75 | result = runner(['categories']) 76 | assert 'Error' not in result.output 77 | assert result.exit_code == 0 78 | 79 | 80 | class TestActivities(object): 81 | def test_activities(self, runner): 82 | """Make sure that invoking the command passes without exception.""" 83 | result = runner(['activities']) 84 | assert 'Error' not in result.output 85 | assert result.exit_code == 0 86 | 87 | 88 | class TestLicense(object): 89 | """Make sure command works as expected.""" 90 | 91 | def test_license(self, runner): 92 | """Make sure command launches without exception.""" 93 | result = runner(['license']) 94 | assert result.exit_code == 0 95 | 96 | 97 | class TestDetails(object): 98 | """Make sure command works as expected.""" 99 | 100 | def test_details(self, runner): 101 | """Make sure command launches without exception.""" 102 | result = runner(['details']) 103 | assert result.exit_code == 0 104 | -------------------------------------------------------------------------------- /tox.ini: -------------------------------------------------------------------------------- 1 | [tox] 2 | envlist = py27, py34, flake8, isort, pep257, docs, manifest 3 | 4 | [testenv] 5 | setenv = 6 | PYTHONPATH = {toxinidir}:{toxinidir}/hamster_cli 7 | whitelist_externals = make 8 | passenv = 9 | SPHINXOPTS_BUILD 10 | SPHINXOPTS_LINKCHECK 11 | commands = 12 | pip install -r requirements/dev.pip 13 | make coverage 14 | 15 | [testenv:flake8] 16 | basepython = python3.4 17 | deps = 18 | flake8==2.5.4 19 | flake8-debugger==1.4.0 20 | flake8-print==2.0.2 21 | pep8-naming==0.3.3 22 | skip_install = True 23 | commands = flake8 setup.py hamster_cli/ tests/ 24 | 25 | [testenv:pep257] 26 | basepython = python3.4 27 | skip_install = True 28 | deps = 29 | pep257==0.7.0 30 | commands = 31 | pep257 setup.py hamster_cli/ tests/ 32 | 33 | [testenv:isort] 34 | basepython = python3.4 35 | deps = isort==4.2.5 36 | skip_install = True 37 | commands = 38 | isort --check-only --recursive --verbose setup.py hamster_cli/ tests/ 39 | 40 | [testenv:manifest] 41 | basepython = python3.4 42 | deps = check-manifest==0.31 43 | skip_install = True 44 | commands = 45 | check-manifest -v 46 | 47 | [testenv:docs] 48 | basepython = python3.4 49 | deps = doc8==0.7.0 50 | commands = 51 | pip install -r requirements/docs.pip 52 | make docs BUILDDIR={envtmpdir} SPHINXOPTS={env:SPHINXOPTS_BUILD:''} 53 | make --directory=docs linkcheck BUILDDIR={envtmpdir} SPHINXOPTS={env:SPHINXOPTS_LINKCHECK:} 54 | doc8 55 | --------------------------------------------------------------------------------