├── .gitignore
├── .gitlab-ci.yml
├── .travis.yml
├── LICENSE
├── Makefile
├── README.md
├── examples
├── basic.py
├── gutenberg.py
└── newspapers.py
├── gluish
├── __init__.py
├── common.py
├── format.py
├── intervals.py
├── parameter.py
├── task.py
└── utils.py
├── requirements.txt
├── setup.py
├── test
├── fixtures
│ ├── l-1.txt
│ ├── l-100.txt
│ └── sample_dnb_oai_response.xml
├── format_test.py
├── intervals_test.py
├── parameter_test.py
├── task_test.py
└── utils_test.py
└── tox.ini
/.gitignore:
--------------------------------------------------------------------------------
1 | # Byte-compiled / optimized / DLL files
2 | __pycache__/
3 | *.py[cod]
4 |
5 | # C extensions
6 | *.so
7 |
8 | # Distribution / packaging
9 | .Python
10 | env/
11 | bin/
12 | build/
13 | develop-eggs/
14 | dist/
15 | eggs/
16 | lib/
17 | lib64/
18 | parts/
19 | sdist/
20 | var/
21 | *.egg-info/
22 | .installed.cfg
23 | *.egg
24 |
25 | # Installer logs
26 | pip-log.txt
27 | pip-delete-this-directory.txt
28 |
29 | # Unit test / coverage reports
30 | htmlcov/
31 | .tox/
32 | .coverage
33 | .cache
34 | nosetests.xml
35 | coverage.xml
36 |
37 | # Translations
38 | *.mo
39 |
40 | # Mr Developer
41 | .mr.developer.cfg
42 | .project
43 | .pydevproject
44 |
45 | # Rope
46 | .ropeproject
47 |
48 | # Django stuff:
49 | *.log
50 | *.pot
51 |
52 | # Sphinx documentation
53 | docs/_build/
54 | /.vscode/
55 |
--------------------------------------------------------------------------------
/.gitlab-ci.yml:
--------------------------------------------------------------------------------
1 | # In GitLab set environment variables -- .../-/settings/ci_cd
2 | #
3 | # NEXUS_USERNAME
4 | # NEXUS_PASSWORD
5 | # NEXUS_REPOSITORY_URL (where to upload artifacts, permissions required)
6 | # PYPI_PROXY_URL (take load off pypi.org)
7 | #
8 | image: python:3.6.9-buster
9 |
10 | stages:
11 | - test
12 | - deploy
13 |
14 | before_script:
15 | - pip install pytest twine
16 |
17 | tests:
18 | stage: test
19 | script:
20 | - python setup.py develop --index-url $PYPI_PROXY_URL # faster, less load for pypi
21 | - pytest -k 'not test_short_intervals'
22 | tags: [docker]
23 | except:
24 | - tags
25 |
26 | upload_to_nexus:
27 | stage: deploy
28 | variables:
29 | TWINE_USERNAME: $NEXUS_USERNAME
30 | TWINE_PASSWORD: $NEXUS_PASSWORD
31 | script:
32 | - python setup.py sdist
33 | - twine upload --repository-url $NEXUS_REPOSITORY_URL dist/*
34 | only:
35 | - tags
36 | tags: [docker]
37 |
--------------------------------------------------------------------------------
/.travis.yml:
--------------------------------------------------------------------------------
1 | language: python
2 | python:
3 | - "3.6"
4 | - "3.8"
5 | install: "pip install -r requirements.txt"
6 | # command to run tests
7 | script: nosetests -a '!notravis'
8 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 3, 29 June 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU General Public License is a free, copyleft license for
11 | software and other kinds of works.
12 |
13 | The licenses for most software and other practical works are designed
14 | to take away your freedom to share and change the works. By contrast,
15 | the GNU General Public License is intended to guarantee your freedom to
16 | share and change all versions of a program--to make sure it remains free
17 | software for all its users. We, the Free Software Foundation, use the
18 | GNU General Public License for most of our software; it applies also to
19 | any other work released this way by its authors. You can apply it to
20 | your programs, too.
21 |
22 | When we speak of free software, we are referring to freedom, not
23 | price. Our General Public Licenses are designed to make sure that you
24 | have the freedom to distribute copies of free software (and charge for
25 | them if you wish), that you receive source code or can get it if you
26 | want it, that you can change the software or use pieces of it in new
27 | free programs, and that you know you can do these things.
28 |
29 | To protect your rights, we need to prevent others from denying you
30 | these rights or asking you to surrender the rights. Therefore, you have
31 | certain responsibilities if you distribute copies of the software, or if
32 | you modify it: responsibilities to respect the freedom of others.
33 |
34 | For example, if you distribute copies of such a program, whether
35 | gratis or for a fee, you must pass on to the recipients the same
36 | freedoms that you received. You must make sure that they, too, receive
37 | or can get the source code. And you must show them these terms so they
38 | know their rights.
39 |
40 | Developers that use the GNU GPL protect your rights with two steps:
41 | (1) assert copyright on the software, and (2) offer you this License
42 | giving you legal permission to copy, distribute and/or modify it.
43 |
44 | For the developers' and authors' protection, the GPL clearly explains
45 | that there is no warranty for this free software. For both users' and
46 | authors' sake, the GPL requires that modified versions be marked as
47 | changed, so that their problems will not be attributed erroneously to
48 | authors of previous versions.
49 |
50 | Some devices are designed to deny users access to install or run
51 | modified versions of the software inside them, although the manufacturer
52 | can do so. This is fundamentally incompatible with the aim of
53 | protecting users' freedom to change the software. The systematic
54 | pattern of such abuse occurs in the area of products for individuals to
55 | use, which is precisely where it is most unacceptable. Therefore, we
56 | have designed this version of the GPL to prohibit the practice for those
57 | products. If such problems arise substantially in other domains, we
58 | stand ready to extend this provision to those domains in future versions
59 | of the GPL, as needed to protect the freedom of users.
60 |
61 | Finally, every program is threatened constantly by software patents.
62 | States should not allow patents to restrict development and use of
63 | software on general-purpose computers, but in those that do, we wish to
64 | avoid the special danger that patents applied to a free program could
65 | make it effectively proprietary. To prevent this, the GPL assures that
66 | patents cannot be used to render the program non-free.
67 |
68 | The precise terms and conditions for copying, distribution and
69 | modification follow.
70 |
71 | TERMS AND CONDITIONS
72 |
73 | 0. Definitions.
74 |
75 | "This License" refers to version 3 of the GNU General Public License.
76 |
77 | "Copyright" also means copyright-like laws that apply to other kinds of
78 | works, such as semiconductor masks.
79 |
80 | "The Program" refers to any copyrightable work licensed under this
81 | License. Each licensee is addressed as "you". "Licensees" and
82 | "recipients" may be individuals or organizations.
83 |
84 | To "modify" a work means to copy from or adapt all or part of the work
85 | in a fashion requiring copyright permission, other than the making of an
86 | exact copy. The resulting work is called a "modified version" of the
87 | earlier work or a work "based on" the earlier work.
88 |
89 | A "covered work" means either the unmodified Program or a work based
90 | on the Program.
91 |
92 | To "propagate" a work means to do anything with it that, without
93 | permission, would make you directly or secondarily liable for
94 | infringement under applicable copyright law, except executing it on a
95 | computer or modifying a private copy. Propagation includes copying,
96 | distribution (with or without modification), making available to the
97 | public, and in some countries other activities as well.
98 |
99 | To "convey" a work means any kind of propagation that enables other
100 | parties to make or receive copies. Mere interaction with a user through
101 | a computer network, with no transfer of a copy, is not conveying.
102 |
103 | An interactive user interface displays "Appropriate Legal Notices"
104 | to the extent that it includes a convenient and prominently visible
105 | feature that (1) displays an appropriate copyright notice, and (2)
106 | tells the user that there is no warranty for the work (except to the
107 | extent that warranties are provided), that licensees may convey the
108 | work under this License, and how to view a copy of this License. If
109 | the interface presents a list of user commands or options, such as a
110 | menu, a prominent item in the list meets this criterion.
111 |
112 | 1. Source Code.
113 |
114 | The "source code" for a work means the preferred form of the work
115 | for making modifications to it. "Object code" means any non-source
116 | form of a work.
117 |
118 | A "Standard Interface" means an interface that either is an official
119 | standard defined by a recognized standards body, or, in the case of
120 | interfaces specified for a particular programming language, one that
121 | is widely used among developers working in that language.
122 |
123 | The "System Libraries" of an executable work include anything, other
124 | than the work as a whole, that (a) is included in the normal form of
125 | packaging a Major Component, but which is not part of that Major
126 | Component, and (b) serves only to enable use of the work with that
127 | Major Component, or to implement a Standard Interface for which an
128 | implementation is available to the public in source code form. A
129 | "Major Component", in this context, means a major essential component
130 | (kernel, window system, and so on) of the specific operating system
131 | (if any) on which the executable work runs, or a compiler used to
132 | produce the work, or an object code interpreter used to run it.
133 |
134 | The "Corresponding Source" for a work in object code form means all
135 | the source code needed to generate, install, and (for an executable
136 | work) run the object code and to modify the work, including scripts to
137 | control those activities. However, it does not include the work's
138 | System Libraries, or general-purpose tools or generally available free
139 | programs which are used unmodified in performing those activities but
140 | which are not part of the work. For example, Corresponding Source
141 | includes interface definition files associated with source files for
142 | the work, and the source code for shared libraries and dynamically
143 | linked subprograms that the work is specifically designed to require,
144 | such as by intimate data communication or control flow between those
145 | subprograms and other parts of the work.
146 |
147 | The Corresponding Source need not include anything that users
148 | can regenerate automatically from other parts of the Corresponding
149 | Source.
150 |
151 | The Corresponding Source for a work in source code form is that
152 | same work.
153 |
154 | 2. Basic Permissions.
155 |
156 | All rights granted under this License are granted for the term of
157 | copyright on the Program, and are irrevocable provided the stated
158 | conditions are met. This License explicitly affirms your unlimited
159 | permission to run the unmodified Program. The output from running a
160 | covered work is covered by this License only if the output, given its
161 | content, constitutes a covered work. This License acknowledges your
162 | rights of fair use or other equivalent, as provided by copyright law.
163 |
164 | You may make, run and propagate covered works that you do not
165 | convey, without conditions so long as your license otherwise remains
166 | in force. You may convey covered works to others for the sole purpose
167 | of having them make modifications exclusively for you, or provide you
168 | with facilities for running those works, provided that you comply with
169 | the terms of this License in conveying all material for which you do
170 | not control copyright. Those thus making or running the covered works
171 | for you must do so exclusively on your behalf, under your direction
172 | and control, on terms that prohibit them from making any copies of
173 | your copyrighted material outside their relationship with you.
174 |
175 | Conveying under any other circumstances is permitted solely under
176 | the conditions stated below. Sublicensing is not allowed; section 10
177 | makes it unnecessary.
178 |
179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180 |
181 | No covered work shall be deemed part of an effective technological
182 | measure under any applicable law fulfilling obligations under article
183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184 | similar laws prohibiting or restricting circumvention of such
185 | measures.
186 |
187 | When you convey a covered work, you waive any legal power to forbid
188 | circumvention of technological measures to the extent such circumvention
189 | is effected by exercising rights under this License with respect to
190 | the covered work, and you disclaim any intention to limit operation or
191 | modification of the work as a means of enforcing, against the work's
192 | users, your or third parties' legal rights to forbid circumvention of
193 | technological measures.
194 |
195 | 4. Conveying Verbatim Copies.
196 |
197 | You may convey verbatim copies of the Program's source code as you
198 | receive it, in any medium, provided that you conspicuously and
199 | appropriately publish on each copy an appropriate copyright notice;
200 | keep intact all notices stating that this License and any
201 | non-permissive terms added in accord with section 7 apply to the code;
202 | keep intact all notices of the absence of any warranty; and give all
203 | recipients a copy of this License along with the Program.
204 |
205 | You may charge any price or no price for each copy that you convey,
206 | and you may offer support or warranty protection for a fee.
207 |
208 | 5. Conveying Modified Source Versions.
209 |
210 | You may convey a work based on the Program, or the modifications to
211 | produce it from the Program, in the form of source code under the
212 | terms of section 4, provided that you also meet all of these conditions:
213 |
214 | a) The work must carry prominent notices stating that you modified
215 | it, and giving a relevant date.
216 |
217 | b) The work must carry prominent notices stating that it is
218 | released under this License and any conditions added under section
219 | 7. This requirement modifies the requirement in section 4 to
220 | "keep intact all notices".
221 |
222 | c) You must license the entire work, as a whole, under this
223 | License to anyone who comes into possession of a copy. This
224 | License will therefore apply, along with any applicable section 7
225 | additional terms, to the whole of the work, and all its parts,
226 | regardless of how they are packaged. This License gives no
227 | permission to license the work in any other way, but it does not
228 | invalidate such permission if you have separately received it.
229 |
230 | d) If the work has interactive user interfaces, each must display
231 | Appropriate Legal Notices; however, if the Program has interactive
232 | interfaces that do not display Appropriate Legal Notices, your
233 | work need not make them do so.
234 |
235 | A compilation of a covered work with other separate and independent
236 | works, which are not by their nature extensions of the covered work,
237 | and which are not combined with it such as to form a larger program,
238 | in or on a volume of a storage or distribution medium, is called an
239 | "aggregate" if the compilation and its resulting copyright are not
240 | used to limit the access or legal rights of the compilation's users
241 | beyond what the individual works permit. Inclusion of a covered work
242 | in an aggregate does not cause this License to apply to the other
243 | parts of the aggregate.
244 |
245 | 6. Conveying Non-Source Forms.
246 |
247 | You may convey a covered work in object code form under the terms
248 | of sections 4 and 5, provided that you also convey the
249 | machine-readable Corresponding Source under the terms of this License,
250 | in one of these ways:
251 |
252 | a) Convey the object code in, or embodied in, a physical product
253 | (including a physical distribution medium), accompanied by the
254 | Corresponding Source fixed on a durable physical medium
255 | customarily used for software interchange.
256 |
257 | b) Convey the object code in, or embodied in, a physical product
258 | (including a physical distribution medium), accompanied by a
259 | written offer, valid for at least three years and valid for as
260 | long as you offer spare parts or customer support for that product
261 | model, to give anyone who possesses the object code either (1) a
262 | copy of the Corresponding Source for all the software in the
263 | product that is covered by this License, on a durable physical
264 | medium customarily used for software interchange, for a price no
265 | more than your reasonable cost of physically performing this
266 | conveying of source, or (2) access to copy the
267 | Corresponding Source from a network server at no charge.
268 |
269 | c) Convey individual copies of the object code with a copy of the
270 | written offer to provide the Corresponding Source. This
271 | alternative is allowed only occasionally and noncommercially, and
272 | only if you received the object code with such an offer, in accord
273 | with subsection 6b.
274 |
275 | d) Convey the object code by offering access from a designated
276 | place (gratis or for a charge), and offer equivalent access to the
277 | Corresponding Source in the same way through the same place at no
278 | further charge. You need not require recipients to copy the
279 | Corresponding Source along with the object code. If the place to
280 | copy the object code is a network server, the Corresponding Source
281 | may be on a different server (operated by you or a third party)
282 | that supports equivalent copying facilities, provided you maintain
283 | clear directions next to the object code saying where to find the
284 | Corresponding Source. Regardless of what server hosts the
285 | Corresponding Source, you remain obligated to ensure that it is
286 | available for as long as needed to satisfy these requirements.
287 |
288 | e) Convey the object code using peer-to-peer transmission, provided
289 | you inform other peers where the object code and Corresponding
290 | Source of the work are being offered to the general public at no
291 | charge under subsection 6d.
292 |
293 | A separable portion of the object code, whose source code is excluded
294 | from the Corresponding Source as a System Library, need not be
295 | included in conveying the object code work.
296 |
297 | A "User Product" is either (1) a "consumer product", which means any
298 | tangible personal property which is normally used for personal, family,
299 | or household purposes, or (2) anything designed or sold for incorporation
300 | into a dwelling. In determining whether a product is a consumer product,
301 | doubtful cases shall be resolved in favor of coverage. For a particular
302 | product received by a particular user, "normally used" refers to a
303 | typical or common use of that class of product, regardless of the status
304 | of the particular user or of the way in which the particular user
305 | actually uses, or expects or is expected to use, the product. A product
306 | is a consumer product regardless of whether the product has substantial
307 | commercial, industrial or non-consumer uses, unless such uses represent
308 | the only significant mode of use of the product.
309 |
310 | "Installation Information" for a User Product means any methods,
311 | procedures, authorization keys, or other information required to install
312 | and execute modified versions of a covered work in that User Product from
313 | a modified version of its Corresponding Source. The information must
314 | suffice to ensure that the continued functioning of the modified object
315 | code is in no case prevented or interfered with solely because
316 | modification has been made.
317 |
318 | If you convey an object code work under this section in, or with, or
319 | specifically for use in, a User Product, and the conveying occurs as
320 | part of a transaction in which the right of possession and use of the
321 | User Product is transferred to the recipient in perpetuity or for a
322 | fixed term (regardless of how the transaction is characterized), the
323 | Corresponding Source conveyed under this section must be accompanied
324 | by the Installation Information. But this requirement does not apply
325 | if neither you nor any third party retains the ability to install
326 | modified object code on the User Product (for example, the work has
327 | been installed in ROM).
328 |
329 | The requirement to provide Installation Information does not include a
330 | requirement to continue to provide support service, warranty, or updates
331 | for a work that has been modified or installed by the recipient, or for
332 | the User Product in which it has been modified or installed. Access to a
333 | network may be denied when the modification itself materially and
334 | adversely affects the operation of the network or violates the rules and
335 | protocols for communication across the network.
336 |
337 | Corresponding Source conveyed, and Installation Information provided,
338 | in accord with this section must be in a format that is publicly
339 | documented (and with an implementation available to the public in
340 | source code form), and must require no special password or key for
341 | unpacking, reading or copying.
342 |
343 | 7. Additional Terms.
344 |
345 | "Additional permissions" are terms that supplement the terms of this
346 | License by making exceptions from one or more of its conditions.
347 | Additional permissions that are applicable to the entire Program shall
348 | be treated as though they were included in this License, to the extent
349 | that they are valid under applicable law. If additional permissions
350 | apply only to part of the Program, that part may be used separately
351 | under those permissions, but the entire Program remains governed by
352 | this License without regard to the additional permissions.
353 |
354 | When you convey a copy of a covered work, you may at your option
355 | remove any additional permissions from that copy, or from any part of
356 | it. (Additional permissions may be written to require their own
357 | removal in certain cases when you modify the work.) You may place
358 | additional permissions on material, added by you to a covered work,
359 | for which you have or can give appropriate copyright permission.
360 |
361 | Notwithstanding any other provision of this License, for material you
362 | add to a covered work, you may (if authorized by the copyright holders of
363 | that material) supplement the terms of this License with terms:
364 |
365 | a) Disclaiming warranty or limiting liability differently from the
366 | terms of sections 15 and 16 of this License; or
367 |
368 | b) Requiring preservation of specified reasonable legal notices or
369 | author attributions in that material or in the Appropriate Legal
370 | Notices displayed by works containing it; or
371 |
372 | c) Prohibiting misrepresentation of the origin of that material, or
373 | requiring that modified versions of such material be marked in
374 | reasonable ways as different from the original version; or
375 |
376 | d) Limiting the use for publicity purposes of names of licensors or
377 | authors of the material; or
378 |
379 | e) Declining to grant rights under trademark law for use of some
380 | trade names, trademarks, or service marks; or
381 |
382 | f) Requiring indemnification of licensors and authors of that
383 | material by anyone who conveys the material (or modified versions of
384 | it) with contractual assumptions of liability to the recipient, for
385 | any liability that these contractual assumptions directly impose on
386 | those licensors and authors.
387 |
388 | All other non-permissive additional terms are considered "further
389 | restrictions" within the meaning of section 10. If the Program as you
390 | received it, or any part of it, contains a notice stating that it is
391 | governed by this License along with a term that is a further
392 | restriction, you may remove that term. If a license document contains
393 | a further restriction but permits relicensing or conveying under this
394 | License, you may add to a covered work material governed by the terms
395 | of that license document, provided that the further restriction does
396 | not survive such relicensing or conveying.
397 |
398 | If you add terms to a covered work in accord with this section, you
399 | must place, in the relevant source files, a statement of the
400 | additional terms that apply to those files, or a notice indicating
401 | where to find the applicable terms.
402 |
403 | Additional terms, permissive or non-permissive, may be stated in the
404 | form of a separately written license, or stated as exceptions;
405 | the above requirements apply either way.
406 |
407 | 8. Termination.
408 |
409 | You may not propagate or modify a covered work except as expressly
410 | provided under this License. Any attempt otherwise to propagate or
411 | modify it is void, and will automatically terminate your rights under
412 | this License (including any patent licenses granted under the third
413 | paragraph of section 11).
414 |
415 | However, if you cease all violation of this License, then your
416 | license from a particular copyright holder is reinstated (a)
417 | provisionally, unless and until the copyright holder explicitly and
418 | finally terminates your license, and (b) permanently, if the copyright
419 | holder fails to notify you of the violation by some reasonable means
420 | prior to 60 days after the cessation.
421 |
422 | Moreover, your license from a particular copyright holder is
423 | reinstated permanently if the copyright holder notifies you of the
424 | violation by some reasonable means, this is the first time you have
425 | received notice of violation of this License (for any work) from that
426 | copyright holder, and you cure the violation prior to 30 days after
427 | your receipt of the notice.
428 |
429 | Termination of your rights under this section does not terminate the
430 | licenses of parties who have received copies or rights from you under
431 | this License. If your rights have been terminated and not permanently
432 | reinstated, you do not qualify to receive new licenses for the same
433 | material under section 10.
434 |
435 | 9. Acceptance Not Required for Having Copies.
436 |
437 | You are not required to accept this License in order to receive or
438 | run a copy of the Program. Ancillary propagation of a covered work
439 | occurring solely as a consequence of using peer-to-peer transmission
440 | to receive a copy likewise does not require acceptance. However,
441 | nothing other than this License grants you permission to propagate or
442 | modify any covered work. These actions infringe copyright if you do
443 | not accept this License. Therefore, by modifying or propagating a
444 | covered work, you indicate your acceptance of this License to do so.
445 |
446 | 10. Automatic Licensing of Downstream Recipients.
447 |
448 | Each time you convey a covered work, the recipient automatically
449 | receives a license from the original licensors, to run, modify and
450 | propagate that work, subject to this License. You are not responsible
451 | for enforcing compliance by third parties with this License.
452 |
453 | An "entity transaction" is a transaction transferring control of an
454 | organization, or substantially all assets of one, or subdividing an
455 | organization, or merging organizations. If propagation of a covered
456 | work results from an entity transaction, each party to that
457 | transaction who receives a copy of the work also receives whatever
458 | licenses to the work the party's predecessor in interest had or could
459 | give under the previous paragraph, plus a right to possession of the
460 | Corresponding Source of the work from the predecessor in interest, if
461 | the predecessor has it or can get it with reasonable efforts.
462 |
463 | You may not impose any further restrictions on the exercise of the
464 | rights granted or affirmed under this License. For example, you may
465 | not impose a license fee, royalty, or other charge for exercise of
466 | rights granted under this License, and you may not initiate litigation
467 | (including a cross-claim or counterclaim in a lawsuit) alleging that
468 | any patent claim is infringed by making, using, selling, offering for
469 | sale, or importing the Program or any portion of it.
470 |
471 | 11. Patents.
472 |
473 | A "contributor" is a copyright holder who authorizes use under this
474 | License of the Program or a work on which the Program is based. The
475 | work thus licensed is called the contributor's "contributor version".
476 |
477 | A contributor's "essential patent claims" are all patent claims
478 | owned or controlled by the contributor, whether already acquired or
479 | hereafter acquired, that would be infringed by some manner, permitted
480 | by this License, of making, using, or selling its contributor version,
481 | but do not include claims that would be infringed only as a
482 | consequence of further modification of the contributor version. For
483 | purposes of this definition, "control" includes the right to grant
484 | patent sublicenses in a manner consistent with the requirements of
485 | this License.
486 |
487 | Each contributor grants you a non-exclusive, worldwide, royalty-free
488 | patent license under the contributor's essential patent claims, to
489 | make, use, sell, offer for sale, import and otherwise run, modify and
490 | propagate the contents of its contributor version.
491 |
492 | In the following three paragraphs, a "patent license" is any express
493 | agreement or commitment, however denominated, not to enforce a patent
494 | (such as an express permission to practice a patent or covenant not to
495 | sue for patent infringement). To "grant" such a patent license to a
496 | party means to make such an agreement or commitment not to enforce a
497 | patent against the party.
498 |
499 | If you convey a covered work, knowingly relying on a patent license,
500 | and the Corresponding Source of the work is not available for anyone
501 | to copy, free of charge and under the terms of this License, through a
502 | publicly available network server or other readily accessible means,
503 | then you must either (1) cause the Corresponding Source to be so
504 | available, or (2) arrange to deprive yourself of the benefit of the
505 | patent license for this particular work, or (3) arrange, in a manner
506 | consistent with the requirements of this License, to extend the patent
507 | license to downstream recipients. "Knowingly relying" means you have
508 | actual knowledge that, but for the patent license, your conveying the
509 | covered work in a country, or your recipient's use of the covered work
510 | in a country, would infringe one or more identifiable patents in that
511 | country that you have reason to believe are valid.
512 |
513 | If, pursuant to or in connection with a single transaction or
514 | arrangement, you convey, or propagate by procuring conveyance of, a
515 | covered work, and grant a patent license to some of the parties
516 | receiving the covered work authorizing them to use, propagate, modify
517 | or convey a specific copy of the covered work, then the patent license
518 | you grant is automatically extended to all recipients of the covered
519 | work and works based on it.
520 |
521 | A patent license is "discriminatory" if it does not include within
522 | the scope of its coverage, prohibits the exercise of, or is
523 | conditioned on the non-exercise of one or more of the rights that are
524 | specifically granted under this License. You may not convey a covered
525 | work if you are a party to an arrangement with a third party that is
526 | in the business of distributing software, under which you make payment
527 | to the third party based on the extent of your activity of conveying
528 | the work, and under which the third party grants, to any of the
529 | parties who would receive the covered work from you, a discriminatory
530 | patent license (a) in connection with copies of the covered work
531 | conveyed by you (or copies made from those copies), or (b) primarily
532 | for and in connection with specific products or compilations that
533 | contain the covered work, unless you entered into that arrangement,
534 | or that patent license was granted, prior to 28 March 2007.
535 |
536 | Nothing in this License shall be construed as excluding or limiting
537 | any implied license or other defenses to infringement that may
538 | otherwise be available to you under applicable patent law.
539 |
540 | 12. No Surrender of Others' Freedom.
541 |
542 | If conditions are imposed on you (whether by court order, agreement or
543 | otherwise) that contradict the conditions of this License, they do not
544 | excuse you from the conditions of this License. If you cannot convey a
545 | covered work so as to satisfy simultaneously your obligations under this
546 | License and any other pertinent obligations, then as a consequence you may
547 | not convey it at all. For example, if you agree to terms that obligate you
548 | to collect a royalty for further conveying from those to whom you convey
549 | the Program, the only way you could satisfy both those terms and this
550 | License would be to refrain entirely from conveying the Program.
551 |
552 | 13. Use with the GNU Affero General Public License.
553 |
554 | Notwithstanding any other provision of this License, you have
555 | permission to link or combine any covered work with a work licensed
556 | under version 3 of the GNU Affero General Public License into a single
557 | combined work, and to convey the resulting work. The terms of this
558 | License will continue to apply to the part which is the covered work,
559 | but the special requirements of the GNU Affero General Public License,
560 | section 13, concerning interaction through a network will apply to the
561 | combination as such.
562 |
563 | 14. Revised Versions of this License.
564 |
565 | The Free Software Foundation may publish revised and/or new versions of
566 | the GNU General Public License from time to time. Such new versions will
567 | be similar in spirit to the present version, but may differ in detail to
568 | address new problems or concerns.
569 |
570 | Each version is given a distinguishing version number. If the
571 | Program specifies that a certain numbered version of the GNU General
572 | Public License "or any later version" applies to it, you have the
573 | option of following the terms and conditions either of that numbered
574 | version or of any later version published by the Free Software
575 | Foundation. If the Program does not specify a version number of the
576 | GNU General Public License, you may choose any version ever published
577 | by the Free Software Foundation.
578 |
579 | If the Program specifies that a proxy can decide which future
580 | versions of the GNU General Public License can be used, that proxy's
581 | public statement of acceptance of a version permanently authorizes you
582 | to choose that version for the Program.
583 |
584 | Later license versions may give you additional or different
585 | permissions. However, no additional obligations are imposed on any
586 | author or copyright holder as a result of your choosing to follow a
587 | later version.
588 |
589 | 15. Disclaimer of Warranty.
590 |
591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599 |
600 | 16. Limitation of Liability.
601 |
602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610 | SUCH DAMAGES.
611 |
612 | 17. Interpretation of Sections 15 and 16.
613 |
614 | If the disclaimer of warranty and limitation of liability provided
615 | above cannot be given local legal effect according to their terms,
616 | reviewing courts shall apply local law that most closely approximates
617 | an absolute waiver of all civil liability in connection with the
618 | Program, unless a warranty or assumption of liability accompanies a
619 | copy of the Program in return for a fee.
620 |
621 | END OF TERMS AND CONDITIONS
622 |
623 | How to Apply These Terms to Your New Programs
624 |
625 | If you develop a new program, and you want it to be of the greatest
626 | possible use to the public, the best way to achieve this is to make it
627 | free software which everyone can redistribute and change under these terms.
628 |
629 | To do so, attach the following notices to the program. It is safest
630 | to attach them to the start of each source file to most effectively
631 | state the exclusion of warranty; and each file should have at least
632 | the "copyright" line and a pointer to where the full notice is found.
633 |
634 |
635 | Copyright (C)
636 |
637 | This program is free software: you can redistribute it and/or modify
638 | it under the terms of the GNU General Public License as published by
639 | the Free Software Foundation, either version 3 of the License, or
640 | (at your option) any later version.
641 |
642 | This program is distributed in the hope that it will be useful,
643 | but WITHOUT ANY WARRANTY; without even the implied warranty of
644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
645 | GNU General Public License for more details.
646 |
647 | You should have received a copy of the GNU General Public License
648 | along with this program. If not, see .
649 |
650 | Also add information on how to contact you by electronic and paper mail.
651 |
652 | If the program does terminal interaction, make it output a short
653 | notice like this when it starts in an interactive mode:
654 |
655 | Copyright (C)
656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657 | This is free software, and you are welcome to redistribute it
658 | under certain conditions; type `show c' for details.
659 |
660 | The hypothetical commands `show w' and `show c' should show the appropriate
661 | parts of the General Public License. Of course, your program's commands
662 | might be different; for a GUI interface, you would use an "about box".
663 |
664 | You should also get your employer (if you work as a programmer) or school,
665 | if any, to sign a "copyright disclaimer" for the program, if necessary.
666 | For more information on this, and how to apply and follow the GNU GPL, see
667 | .
668 |
669 | The GNU General Public License does not permit incorporating your program
670 | into proprietary programs. If your program is a subroutine library, you
671 | may consider it more useful to permit linking proprietary applications with
672 | the library. If this is what you want to do, use the GNU Lesser General
673 | Public License instead of this License. But first, please read
674 | .
675 |
--------------------------------------------------------------------------------
/Makefile:
--------------------------------------------------------------------------------
1 | dist:
2 | python setup.py sdist
3 |
4 | clean:
5 | find . -name "*.pyc" -exec rm -rf {} \;
6 | rm -rf build/ dist/ gluish.egg-info/ .tox/
7 | rm -rf .pytest_cache/
8 |
9 | coverage:
10 | nosetests --with-coverage --cover-package=gluish
11 |
12 | imports:
13 | isort -rc --atomic .
14 |
15 | pylint:
16 | pylint siskin
17 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Gluish
2 |
3 | Note: v0.2.X cleans up some cruft from v0.1.X. v0.2.X still passes the same
4 | tests as v0.1.X, but removes a lot of functionality unrelated to luigi. Please
5 | check, before you upgrade.
6 |
7 | Luigi 2.0 compatibility: gluish 0.2.3 or higher.
8 |
9 | Note that luigi dropped Python 2 support, and so does this package, starting with 0.3.0.
10 |
11 | ----
12 |
13 | [](https://travis-ci.org/miku/gluish)
14 | [](https://pypi.python.org/pypi/gluish)
15 | [](https://zenodo.org/badge/latestdoi/17902915)
16 | [](https://www.repostatus.org/#active)
17 |
18 | Some glue around [luigi](https://github.com/spotify/luigi).
19 |
20 | Provides a base class, that autogenerates its output filenames based on
21 | * some base path,
22 | * a tag,
23 | * the task id (the classname and the significant parameters)
24 |
25 | Additionally, this package provides a few smaller utilities, like a TSV format,
26 | a benchmarking decorator and some task templates.
27 |
28 | This project has been developed for [Project finc](https://finc.info) at [Leipzig University Library](https://ub.uni-leipzig.de).
29 |
30 | ## A basic task that knows its place
31 |
32 | `gluish.task.BaseTask` is intended to be used as a supertask.
33 |
34 | ```python
35 | from gluish.task import BaseTask
36 | import datetime
37 | import luigi
38 | import tempfile
39 |
40 | class DefaultTask(BaseTask):
41 | """ Some default abstract task for your tasks. BASE and TAG determine
42 | the paths, where the artefacts will be stored. """
43 | BASE = tempfile.gettempdir()
44 | TAG = 'just-a-test'
45 |
46 | class RealTask(DefaultTask):
47 | """ Note that this task has a `self.path()`, that figures out the full
48 | path for this class' output. """
49 | date = luigi.DateParameter(default=datetime.date(1970, 1, 1))
50 | def run(self):
51 | with self.output().open('w') as output:
52 | output.write('Hello World!')
53 |
54 | def output(self):
55 | return luigi.LocalTarget(path=self.path())
56 | ```
57 |
58 | When instantiating a `RealTask` instance, it will automatically be assigned a
59 | structured output path, consisting of `BASE`, `TAG`, task name and a slugified
60 | version of the significant parameters.
61 |
62 | ```python
63 |
64 | task = RealTask()
65 | task.output().path
66 | # would be something like this on OS X:
67 | # /var/folders/jy/g_b2kpwx0850/T/just-a-test/RealTask/date-1970-01-01.tsv
68 |
69 | ```
70 |
71 | ## A TSV format
72 |
73 | Was started on the
74 | [mailing list](https://groups.google.com/forum/#!searchin/luigi-user/TSV/luigi-user/F813st16xqw/xErC6pXR8zEJ).
75 | Continuing the example from above, lets create a task, that generates TSV
76 | files, named `TabularSource`.
77 |
78 | ```python
79 |
80 | from gluish.format import TSV
81 |
82 | class TabularSource(DefaultTask):
83 | date = luigi.DateParameter(default=datetime.date(1970, 1, 1))
84 | def run(self):
85 | with self.output().open('w') as output:
86 | for i in range(10):
87 | output.write_tsv(i, 'Hello', 'World')
88 |
89 | def output(self):
90 | return luigi.LocalTarget(path=self.path(), format=TSV)
91 | ```
92 |
93 | Another class, `TabularConsumer` can use `iter_tsv` on the handle obtained
94 | by opening the file. The `row` will be a tuple, or - if `cols` is specified -
95 | a `collections.namedtuple`.
96 |
97 | ```python
98 | class TabularConsumer(DefaultTask):
99 | date = luigi.DateParameter(default=datetime.date(1970, 1, 1))
100 | def requires(self):
101 | return TabularSource()
102 |
103 | def run(self):
104 | with self.input().open() as handle:
105 | for row in handle.iter_tsv(cols=('id', 'greeting', 'greetee'))
106 | print('{0} {1}!'.format(row.greeting, row.greetee))
107 |
108 | def complete(self):
109 | return False
110 | ```
111 |
112 | ## Easy shell calls
113 |
114 | Leverage command line tools with [`gluish.utils.shellout`](https://github.com/miku/gluish/blob/943993d29fe88d352d110620a717303b19897577/gluish/utils.py#L199). `shellout` will
115 | take a string argument and will format it according to the keyword arguments.
116 | The `{output}` placeholder is special, since it will be automatically assigned
117 | a path to a temporary file, if it is not specified as a keyword argument.
118 |
119 | The return value of `shellout` is the path to the `{output}` file.
120 |
121 | Spaces in the given string are normalized, unless `preserve_whitespace=True` is
122 | passed. A literal curly brace can be inserted by `{{` and `}}` respectively.
123 |
124 | An exception is raised, whenever the commands exit with a non-zero return value.
125 |
126 | Note: If you want to make sure an executable is available on you system before the task runs,
127 | you *can* use a [`gluish.common.Executable`](https://github.com/miku/gluish/blob/943993d29fe88d352d110620a717303b19897577/gluish/common.py#L106) task as requirement.
128 |
129 | ```python
130 | from gluish.common import Executable
131 | from gluish.utils import shellout
132 | import luigi
133 |
134 | class GIFScreencast(DefaultTask):
135 | """ Given a path to a screencast .mov, generate a GIF
136 | which is funnier by definition. """
137 | filename = luigi.Parameter(description='Path to a .mov screencast')
138 | delay = luigi.IntParameter(default=3)
139 |
140 | def requires(self):
141 | return [Executable(name='ffmpg'),
142 | Executable(name='gifsicle', message='http://www.lcdf.org/gifsicle/')]
143 |
144 | def run(self):
145 | output = shellout("""ffmpeg -i {infile} -s 600x400
146 | -pix_fmt rgb24 -r 10 -f gif - |
147 | gifsicle --optimize=3 --delay={delay} > {output} """,
148 | infile=self.filename, delay=self.delay)
149 | luigi.LocalTarget(output).move(self.output().path)
150 |
151 | def output(self):
152 | return luigi.LocalTarget(path=self.path())
153 | ```
154 |
155 | ## Dynamic date parameter
156 |
157 | Sometimes the *effective* date for a task needs to be determined dynamically.
158 |
159 | Consider for example a workflow involving an FTP server.
160 |
161 | A data source is fetched from FTP, but it is not known, when updates are
162 | supplied. So the FTP server needs to be checked in regular intervals.
163 | Dependent tasks do not need to be updated as long as there is nothing new
164 | on the FTP server.
165 |
166 | To map an arbitrary date to the *closest* date in the past, where an update
167 | occured, you can use a `gluish.parameter.ClosestDateParameter`, which is just an ordinary
168 | `DateParameter` but will invoke `task.closest()` behind the scene, to
169 | figure out the *effective date*.
170 |
171 | ```python
172 |
173 | from gluish.parameter import ClosestDateParameter
174 | import datetime
175 | import luigi
176 |
177 | class SimpleTask(DefaultTask):
178 | """ Reuse DefaultTask from above """
179 | date = ClosestDateParameter(default=datetime.date.today())
180 |
181 | def closest(self):
182 | # invoke dynamic checks here ...
183 | # for simplicity, map this task to the last monday
184 | return self.date - datetime.timedelta(days=self.date.weekday())
185 |
186 | def run(self):
187 | with self.output().open('w') as output:
188 | output.write("It's just another manic Monday!")
189 |
190 | def output(self):
191 | return luigi.LocalTarget(path=self.path())
192 |
193 | ```
194 |
195 | A short, self contained example can be found in [this gist](https://gist.github.com/miku/e72628ee54fce9f06a34).
196 |
--------------------------------------------------------------------------------
/examples/basic.py:
--------------------------------------------------------------------------------
1 | # coding: utf-8
2 | #
3 | # Copyright 2015 by Leipzig University Library, http://ub.uni-leipzig.de
4 | # by The Finc Authors, http://finc.info
5 | # by Martin Czygan,
6 | #
7 | # This file is part of some open source application.
8 | #
9 | # Some open source application is free software: you can redistribute
10 | # it and/or modify it under the terms of the GNU General Public
11 | # License as published by the Free Software Foundation, either
12 | # version 3 of the License, or (at your option) any later version.
13 | #
14 | # Some open source application is distributed in the hope that it will
15 | # be useful, but WITHOUT ANY WARRANTY; without even the implied warranty
16 | # of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 | # GNU General Public License for more details.
18 | #
19 | # You should have received a copy of the GNU General Public License
20 | # along with Foobar. If not, see .
21 | #
22 | # @license GPL-3.0+
23 | #
24 |
25 | """
26 | Basic usage of BaseTask.
27 | """
28 |
29 | import datetime
30 | import tempfile
31 |
32 | import luigi
33 | from gluish.task import BaseTask
34 |
35 |
36 | class ProjectBaseTask(BaseTask):
37 | """ Some overarching task, that only defines the root directory in BASE. """
38 | BASE = tempfile.gettempdir()
39 |
40 |
41 | class GroupOne(ProjectBaseTask):
42 | """ A group of related tasks. """
43 | TAG = 'group-1'
44 |
45 |
46 | class GroupTwo(ProjectBaseTask):
47 | """ A group of related tasks. """
48 | TAG = 'group-2'
49 |
50 |
51 | class SomeTask(GroupOne):
52 | """ Some concrete task from group one. """
53 | priority = luigi.IntParameter(default=10)
54 |
55 | def output(self):
56 | return luigi.LocalTarget(path=self.path())
57 |
58 |
59 | class AnotherTask(GroupTwo):
60 | """ Some concrete task from group two. """
61 | priority = luigi.IntParameter(default=10)
62 | date = luigi.DateParameter(default=datetime.date.today())
63 | name = luigi.Parameter(default='No', significant=False)
64 |
65 | def output(self):
66 | return luigi.LocalTarget(path=self.path())
67 |
68 |
69 | if __name__ == '__main__':
70 | task1 = SomeTask()
71 | task2 = AnotherTask()
72 |
73 | print(task1.output().path)
74 | print(task2.output().path)
75 |
--------------------------------------------------------------------------------
/examples/gutenberg.py:
--------------------------------------------------------------------------------
1 | # coding: utf-8
2 | #
3 | # Copyright 2015 by Leipzig University Library, http://ub.uni-leipzig.de
4 | # by The Finc Authors, http://finc.info
5 | # by Martin Czygan,
6 | #
7 | # This file is part of some open source application.
8 | #
9 | # Some open source application is free software: you can redistribute
10 | # it and/or modify it under the terms of the GNU General Public
11 | # License as published by the Free Software Foundation, either
12 | # version 3 of the License, or (at your option) any later version.
13 | #
14 | # Some open source application is distributed in the hope that it will
15 | # be useful, but WITHOUT ANY WARRANTY; without even the implied warranty
16 | # of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 | # GNU General Public License for more details.
18 | #
19 | # You should have received a copy of the GNU General Public License
20 | # along with Foobar. If not, see .
21 | #
22 | # @license GPL-3.0+
23 | #
24 |
25 | """
26 | Example of a small pipeline that downloads a Project Gutenberg dump,
27 | extracts the index terms and builds a top list of those terms.
28 |
29 | $ cd gluish
30 | $ python ./examples/gutenberg.py GutenbergTopIndexTerms --local-scheduler
31 |
32 | There is no quick way to see, where the files have gone, since we use
33 | `tempfile.gettempdir()`, which varies from system to sytem. Workaround is to
34 | use a python shell:
35 |
36 | $ cd examples
37 | $ python
38 | >>> import gutenberg
39 | >>> gutenberg.GutenbergTopIndexTerms().output().path
40 | u'/tmp/gutenberg/GutenbergTopIndexTerms/date-2014-03-17.tsv'
41 |
42 | The file should look like this:
43 |
44 | $ head -10 /tmp/gutenberg/GutenbergTopIndexTerms/date-2014-03-17.tsv
45 | 17419 Fiction
46 | 6892 Juvenile fiction
47 | 4511 History
48 | 2526 Periodicals
49 | 2404 United States
50 | 2040 19th century
51 | 1902 Great Britain
52 | 1810 Drama
53 | 1649 Biography
54 | 1616 Social life and customs
55 | """
56 |
57 | import tempfile
58 |
59 | import luigi
60 | from gluish import TSV, BaseTask, Executable, shellout, weekly
61 |
62 |
63 | class GutenbergTask(BaseTask):
64 | BASE = tempfile.gettempdir()
65 | TAG = 'gutenberg'
66 |
67 |
68 | class GutenbergDump(GutenbergTask):
69 | """
70 | Download dump.
71 |
72 | Updated usually every four days. These lists include the basic information
73 | about each eBook.
74 | """
75 | date = luigi.DateParameter(default=weekly())
76 |
77 | def requires(self):
78 | return [Executable(name='wget'), Executable(name='bunzip2')]
79 |
80 | def run(self):
81 | url = "http://gutenberg.readingroo.ms/cache/generated/feeds/catalog.marc.bz2"
82 | output = shellout('wget -q "{url}" -O {output}', url=url)
83 | output = shellout('bunzip2 {input} -c > {output}', input=output)
84 | luigi.LocalTarget(output).move(self.output().path)
85 |
86 | def output(self):
87 | return luigi.LocalTarget(path=self.path(ext='mrc'))
88 |
89 |
90 | class GutenbergIndexTerms(GutenbergTask):
91 | """ Extract all 653 a index terms. """
92 | date = luigi.DateParameter(default=weekly())
93 |
94 | def requires(self):
95 | return {'dump': GutenbergDump(date=self.date),
96 | 'apps': Executable(name='marctotsv',
97 | message='https://github.com/ubleipzig/marctools')}
98 |
99 | def run(self):
100 | output = shellout('marctotsv -k -s "|" {input} 001 653.a > {output}',
101 | input=self.input().get('dump').path)
102 | with luigi.LocalTarget(output, format=TSV).open() as handle:
103 | with self.output().open('w') as output:
104 | for row in handle.iter_tsv(cols=('id', 'terms')):
105 | for subfield in row.terms.split('|'):
106 | for term in subfield.split('--'):
107 | term = term.strip()
108 | output.write_tsv(row.id, term)
109 |
110 | def output(self):
111 | return luigi.LocalTarget(path=self.path(), format=TSV)
112 |
113 |
114 | class GutenbergTopIndexTerms(GutenbergTask):
115 | """ Sort and count top index terms. """
116 | date = luigi.DateParameter(default=weekly())
117 |
118 | def requires(self):
119 | return GutenbergIndexTerms(date=self.date)
120 |
121 | def run(self):
122 | output = shellout("cut -f 2- {input}| sort | uniq -c | sort -nr > {output}",
123 | input=self.input().path)
124 | luigi.LocalTarget(output).move(self.output().path)
125 |
126 | def output(self):
127 | return luigi.LocalTarget(path=self.path(), format=TSV)
128 |
129 |
130 | if __name__ == '__main__':
131 | luigi.run()
132 |
--------------------------------------------------------------------------------
/examples/newspapers.py:
--------------------------------------------------------------------------------
1 | # coding: utf-8
2 | # pylint: disable=F0401,E1101
3 | #
4 | # Copyright 2015 by Leipzig University Library, http://ub.uni-leipzig.de
5 | # by The Finc Authors, http://finc.info
6 | # by Martin Czygan,
7 | #
8 | # This file is part of some open source application.
9 | #
10 | # Some open source application is free software: you can redistribute
11 | # it and/or modify it under the terms of the GNU General Public
12 | # License as published by the Free Software Foundation, either
13 | # version 3 of the License, or (at your option) any later version.
14 | #
15 | # Some open source application is distributed in the hope that it will
16 | # be useful, but WITHOUT ANY WARRANTY; without even the implied warranty
17 | # of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 | # GNU General Public License for more details.
19 | #
20 | # You should have received a copy of the GNU General Public License
21 | # along with Foobar. If not, see .
22 | #
23 | # @license GPL-3.0+
24 | #
25 |
26 | """
27 | Example of a small pipeline that downloads a couple of newspaper frontpages,
28 | creates a newline delimited json and indexes it into elasticsearch (version 1.0+).
29 | """
30 |
31 | import hashlib
32 | import json
33 | import tempfile
34 |
35 | import elasticsearch
36 | import luigi
37 | from gluish import BaseTask, Executable, daily, random_string, shellout
38 |
39 | NEWSPAPERS = (
40 | 'http://bild.de/',
41 | 'http://faz.net/',
42 | 'http://spiegel.de/',
43 | 'http://sueddeutsche.de/',
44 | 'http://www.fr-online.de/',
45 | 'http://www.lvz-online.de/',
46 | 'http://www.nzz.ch/',
47 | )
48 |
49 |
50 | class FrontpageTask(BaseTask):
51 | """ Just a base class for out newspaper example. """
52 | BASE = tempfile.gettempdir()
53 | TAG = 'frontpage'
54 |
55 |
56 | class DownloadPage(FrontpageTask):
57 | """
58 | Download a frontpage.
59 | """
60 | date = luigi.DateParameter(default=daily())
61 | url = luigi.Parameter()
62 |
63 | def requires(self):
64 | """ Outsource the download. """
65 | return Executable(name='wget')
66 |
67 | def run(self):
68 | """ Just run wget quietly. """
69 | output = shellout('wget -q "{url}" -O {output}', url=self.url)
70 | luigi.LocalTarget(output).move(self.output().path)
71 |
72 | def output(self):
73 | """ Use the digest version, since URL can be ugly. """
74 | return luigi.LocalTarget(path=self.path(digest=True, ext='html'))
75 |
76 |
77 | class JsonPage(FrontpageTask):
78 | """ Convert the page to Json, adding some metadata. """
79 | date = luigi.DateParameter(default=daily())
80 | url = luigi.Parameter()
81 |
82 | def requires(self):
83 | """ Page needs to be already there. """
84 | return DownloadPage(date=self.date, url=self.url)
85 |
86 | def run(self):
87 | """ Construct the document id from the date and the url. """
88 | document = {}
89 | document['_id'] = hashlib.sha1('%s:%s' % (
90 | self.date, self.url)).hexdigest()
91 | with self.input().open() as handle:
92 | document['content'] = handle.read().decode('utf-8', 'ignore')
93 | document['url'] = self.url
94 | document['date'] = unicode(self.date)
95 | with self.output().open('w') as output:
96 | output.write(json.dumps(document))
97 |
98 | def output(self):
99 | """ Output a file with a single Json doc. """
100 | return luigi.LocalTarget(path=self.path(digest=True, ext='json'))
101 |
102 |
103 | class IndexPage(FrontpageTask):
104 | """ Index the Json document into an ES index. """
105 | date = luigi.DateParameter(default=daily())
106 | url = luigi.Parameter()
107 |
108 | doc_type = 'page'
109 | index = 'frontpage'
110 |
111 | def requires(self):
112 | """ We need the Json. """
113 | return JsonPage(date=self.date, url=self.url)
114 |
115 | def run(self):
116 | """ Index the document. Since ids are predictable,
117 | we won't index anything twice. """
118 | with self.input().open() as handle:
119 | body = json.loads(handle.read())
120 | es = elasticsearch.Elasticsearch()
121 | id = body.get('_id')
122 | es.index(index='frontpage', doc_type='html', id=id, body=body)
123 |
124 | def complete(self):
125 | """ Check, if out hashed date:url id is already in the index. """
126 | id = hashlib.sha1('%s:%s' % (self.date, self.url)).hexdigest()
127 | es = elasticsearch.Elasticsearch()
128 | try:
129 | es.get(index='frontpage', doc_type='html', id=id)
130 | except elasticsearch.NotFoundError:
131 | return False
132 | return True
133 |
134 | # Wrapper tasks
135 | # =============
136 |
137 | class DailyDownload(FrontpageTask, luigi.WrapperTask):
138 | """ Wraps a couple of downloads, so they can be parallelized. """
139 | date = luigi.DateParameter(default=daily())
140 |
141 | def requires(self):
142 | """ Download all pages. """
143 | for url in NEWSPAPERS:
144 | yield DownloadPage(url=url)
145 |
146 | def output(self):
147 | """ This is just a wrapper task. """
148 | return self.input()
149 |
150 |
151 | class DailyIndex(FrontpageTask, luigi.WrapperTask):
152 | """ Wraps a couple of downloads, so they can be parallelized. """
153 | date = luigi.DateParameter(default=daily())
154 | indicator = luigi.Parameter(default=random_string())
155 |
156 | def requires(self):
157 | """ Index all pages. """
158 | for url in NEWSPAPERS:
159 | yield IndexPage(url=url, date=self.date)
160 |
161 | def output(self):
162 | """ This is just a wrapper task. """
163 | return self.input()
164 |
165 |
166 | if __name__ == '__main__':
167 | luigi.run()
168 |
--------------------------------------------------------------------------------
/gluish/__init__.py:
--------------------------------------------------------------------------------
1 | # coding: utf-8
2 | # pylint: disable=W0401
3 | #
4 | # Copyright 2015 by Leipzig University Library, http://ub.uni-leipzig.de
5 | # by The Finc Authors, http://finc.info
6 | # by Martin Czygan,
7 | #
8 | # This file is part of some open source application.
9 | #
10 | # Some open source application is free software: you can redistribute
11 | # it and/or modify it under the terms of the GNU General Public
12 | # License as published by the Free Software Foundation, either
13 | # version 3 of the License, or (at your option) any later version.
14 | #
15 | # Some open source application is distributed in the hope that it will
16 | # be useful, but WITHOUT ANY WARRANTY; without even the implied warranty
17 | # of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 | # GNU General Public License for more details.
19 | #
20 | # You should have received a copy of the GNU General Public License
21 | # along with Foobar. If not, see .
22 | #
23 | # @license GPL-3.0+
24 | #
25 |
26 | """
27 | Gluish - few utils for luigi.
28 | """
29 |
30 | __version__ = '0.3.0'
31 |
32 | from gluish.common import *
33 | from gluish.format import *
34 | from gluish.intervals import *
35 | from gluish.parameter import *
36 | from gluish.task import *
37 | from gluish.utils import *
38 |
--------------------------------------------------------------------------------
/gluish/common.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # coding: utf-8
3 | #
4 | # Copyright 2015 by Leipzig University Library, http://ub.uni-leipzig.de
5 | # by The Finc Authors, http://finc.info
6 | # by Martin Czygan,
7 | #
8 | # This file is part of some open source application.
9 | #
10 | # Some open source application is free software: you can redistribute
11 | # it and/or modify it under the terms of the GNU General Public
12 | # License as published by the Free Software Foundation, either
13 | # version 3 of the License, or (at your option) any later version.
14 | #
15 | # Some open source application is distributed in the hope that it will
16 | # be useful, but WITHOUT ANY WARRANTY; without even the implied warranty
17 | # of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 | # GNU General Public License for more details.
19 | #
20 | # You should have received a copy of the GNU General Public License
21 | # along with Foobar. If not, see .
22 | #
23 | # @license GPL-3.0+
24 | #
25 |
26 | import datetime
27 | import logging
28 | import os
29 |
30 | import luigi
31 | import requests
32 |
33 | from gluish.parameter import ClosestDateParameter
34 | from gluish.utils import shellout, which
35 |
36 | __all__ = ['Executable', 'Available', 'GitCloneRepository', 'GitUpdateRepository', 'FillSolrIndex']
37 |
38 | logger = logging.getLogger('gluish')
39 |
40 |
41 | def service_is_up(service):
42 | """
43 | Return `False` if HTTP services returns status code != 200.
44 | """
45 | try:
46 | return requests.get(service).status_code == 200
47 | except:
48 | return False
49 |
50 |
51 | def getfirstline(file, default):
52 | """
53 | Returns the first line of a file.
54 | """
55 | with open(file, 'rb') as fh:
56 | content = fh.readlines()
57 | if len(content) == 1:
58 | return content[0].decode('utf-8').strip('\n')
59 |
60 | return default
61 |
62 |
63 | class chdir(object):
64 | """
65 | Change directory temporarily.
66 | """
67 |
68 | def __init__(self, path):
69 | self.wd = os.getcwd()
70 | self.dir = path
71 |
72 | def __enter__(self):
73 | os.chdir(self.dir)
74 |
75 | def __exit__(self, *args):
76 | os.chdir(self.wd)
77 |
78 |
79 | class Executable(luigi.Task):
80 | """
81 | Checks, whether an external executable is available. This task will consider
82 | itself complete, only if the executable `name` is found in $PATH.
83 | """
84 | name = luigi.Parameter()
85 | message = luigi.Parameter(default="")
86 |
87 | def run(self):
88 | """ Only run if, task is not complete. """
89 | raise RuntimeError('external program required: %s (%s)' % (self.name, self.message))
90 |
91 | def complete(self):
92 | return which(self.name) is not None
93 |
94 |
95 | class Available(luigi.Task):
96 | """
97 | Checks, whether an HTTP service is available or not. This task will consider
98 | itself complete, only if the HTTP service return a 200.
99 | """
100 | service = luigi.Parameter()
101 | message = luigi.Parameter(default="")
102 |
103 | def run(self):
104 | """ Only run if, task is not complete. """
105 | raise RuntimeError('HTTP service %s is not available (%s)' % (self.service, self.message))
106 |
107 | def complete(self):
108 | return service_is_up(self.service)
109 |
110 |
111 | class GitCloneRepository(luigi.Task):
112 | """
113 | Checks, whether a certain directory already exists (that should contain a Git repository) - otherwise it will be cloned.
114 | """
115 | gitrepository = luigi.Parameter()
116 | repositorydirectory = luigi.Parameter()
117 | basedirectory = luigi.Parameter()
118 |
119 | def requires(self):
120 | return Executable(name='git')
121 |
122 | def run(self):
123 | self.output().makedirs()
124 | with chdir(str(self.basedirectory)):
125 | shellout("""git clone {gitrepository}""", gitrepository=self.gitrepository)
126 |
127 | def output(self):
128 | return luigi.LocalTarget(path=os.path.join(self.basedirectory, str(self.repositorydirectory)))
129 |
130 |
131 | class GitUpdateRepository(luigi.Task):
132 | """
133 | Updates an existing Git repository
134 | """
135 | gitrepository = luigi.Parameter()
136 | repositorydirectory = luigi.Parameter()
137 | basedirectory = luigi.Parameter()
138 | branch = luigi.Parameter(default="master", significant=False)
139 |
140 | def requires(self):
141 | return [
142 | GitCloneRepository(gitrepository=self.gitrepository,
143 | repositorydirectory=self.repositorydirectory,
144 | basedirectory=self.basedirectory),
145 | Executable(name='git')
146 | ]
147 |
148 | def run(self):
149 | with chdir(str(self.output().path)):
150 | shellout("""git checkout {branch}""", branch=self.branch)
151 | shellout("""git pull origin {branch}""", branch=self.branch)
152 |
153 | def complete(self):
154 | if not self.output().exists():
155 | return False
156 |
157 | with chdir(str(self.output().path)):
158 | output = shellout("""git fetch origin {branch} > {output} 2>&1""", branch=self.branch)
159 |
160 | result = True
161 |
162 | with open(output, 'rb') as fh:
163 | content = fh.readlines()
164 | if len(content) >= 3:
165 | result = False
166 |
167 | revparseoutput = shellout("""git rev-parse {branch} > {output} 2>&1""", branch=self.branch)
168 | originrevparseoutput = shellout("""git rev-parse origin/{branch} > {output} 2>&1""", branch=self.branch)
169 |
170 | revparse = getfirstline(revparseoutput, "0")
171 | originrevparse = getfirstline(originrevparseoutput, "1")
172 |
173 | if revparse != originrevparse:
174 | result = False
175 |
176 | return result
177 |
178 | def output(self):
179 | return luigi.LocalTarget(path=os.path.join(str(self.basedirectory), str(self.repositorydirectory)))
180 |
181 |
182 | class FillSolrIndex(luigi.Task):
183 | # TODO: define proper complete criteria (?)
184 | # e.g. check, whether the amount of records that should be loaded into the index is index (if not, then index load is not successfully)
185 | """
186 | Loads processed data of a data package into a given Solr index (with help of solrbulk)
187 | """
188 | date = ClosestDateParameter(default=datetime.date.today())
189 | solruri = luigi.Parameter()
190 | solrcore = luigi.Parameter()
191 | purge = luigi.BoolParameter(default=False, significant=False)
192 | purgequery = luigi.Parameter(default="", significant=False)
193 | size = luigi.IntParameter(default=1000, significant=False)
194 | worker = luigi.IntParameter(default=2, significant=False)
195 | commitlimit = luigi.IntParameter(default=1000, significant=False)
196 | input = luigi.Parameter()
197 | taskdir = luigi.Parameter()
198 | outputfilename = luigi.Parameter()
199 | salt = luigi.Parameter()
200 |
201 | def determineprefix(self, purge=None, purgequery=None):
202 | solrbulk = 'solrbulk'
203 |
204 | if purge and purgequery is not None:
205 | return solrbulk + ' -purge -purge-query "' + purgequery + '"'
206 | if purge:
207 | return solrbulk + ' -purge'
208 |
209 | return solrbulk
210 |
211 | def requires(self):
212 | return [
213 | Available(service=self.solruri,
214 | message="provide a running Solr, please"),
215 | Executable(name='solrbulk',
216 | message='solrbulk command is missing on your system, you can, e.g., install it as a deb package on your Debian-based linux system (see https://github.com/miku/solrbulk#installation)'),
217 | ]
218 |
219 | def run(self):
220 | prefix = self.determineprefix(self.purge, self.purgequery)
221 | server = str(self.solruri) + str(self.solrcore)
222 | chunksize = self.size
223 | cores = self.worker
224 | inputpath = self.input
225 | commit = self.commitlimit
226 | output = shellout(
227 | """{prefix} -verbose -server {server} -size {size} -w {worker} -commit {commit} < {input}""",
228 | prefix=prefix,
229 | server=server,
230 | size=chunksize,
231 | worker=cores,
232 | commit=commit,
233 | input=inputpath)
234 |
235 | luigi.LocalTarget(output).move(self.output().path)
236 |
237 | def output(self):
238 | return luigi.LocalTarget(path=os.path.join(self.taskdir, str(self.outputfilename)))
239 |
--------------------------------------------------------------------------------
/gluish/format.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # coding: utf-8
3 | #
4 | # Copyright 2015 by Leipzig University Library, http://ub.uni-leipzig.de
5 | # by The Finc Authors, http://finc.info
6 | # by Martin Czygan,
7 | #
8 | # This file is part of some open source application.
9 | #
10 | # Some open source application is free software: you can redistribute
11 | # it and/or modify it under the terms of the GNU General Public
12 | # License as published by the Free Software Foundation, either
13 | # version 3 of the License, or (at your option) any later version.
14 | #
15 | # Some open source application is distributed in the hope that it will
16 | # be useful, but WITHOUT ANY WARRANTY; without even the implied warranty
17 | # of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 | # GNU General Public License for more details.
19 | #
20 | # You should have received a copy of the GNU General Public License
21 | # along with Foobar. If not, see .
22 | #
23 | # @license GPL-3.0+
24 | #
25 |
26 | """
27 | Format add-ons
28 | ==============
29 |
30 | Format related functions and classes. Highlights: A TSV class, that helps
31 | to work with tabular data.
32 |
33 | Example:
34 |
35 | def run(self):
36 | with self.output().open('w') as output:
37 | output.write_tsv('Ubik', '1969', '67871286')
38 |
39 | def output(self):
40 | return luigi.LocalTarget(path=self.path(), format=TSV)
41 |
42 | """
43 |
44 | from __future__ import unicode_literals
45 |
46 | import collections
47 | import functools
48 |
49 | import luigi
50 | from gluish.utils import random_string, which
51 | from six import string_types
52 |
53 | __all__ = ['TSV', 'Gzip', 'Zstd']
54 |
55 |
56 | def write_tsv(output_stream, *tup, **kwargs):
57 | """
58 | Write argument list in `tup` out as a tab-separeated row to the stream.
59 | """
60 | encoding = kwargs.get('encoding') or 'utf-8'
61 | value = u'\t'.join([s for s in tup]) + '\n'
62 | if encoding is None:
63 | if isinstance(value, string_types):
64 | output_stream.write(value.encode('utf-8'))
65 | else:
66 | output_stream.write(value)
67 | else:
68 | output_stream.write(value.encode(encoding))
69 |
70 |
71 | def iter_tsv(input_stream, cols=None, encoding='utf-8'):
72 | """
73 | If a tuple is given in cols, use the elements as names to construct
74 | a namedtuple.
75 |
76 | Columns can be marked as ignored by using ``X`` or ``0`` as column name.
77 |
78 | Example (ignore the first four columns of a five column TSV):
79 |
80 | ::
81 |
82 | def run(self):
83 | with self.input().open() as handle:
84 | for row in handle.iter_tsv(cols=('X', 'X', 'X', 'X', 'iln')):
85 | print(row.iln)
86 | """
87 | if cols:
88 | cols = [c if not c in ('x', 'X', 0, None) else random_string(length=5)
89 | for c in cols]
90 | Record = collections.namedtuple('Record', cols)
91 | for line in input_stream:
92 | yield Record._make(line.decode(encoding).rstrip('\n').split('\t'))
93 | else:
94 | for line in input_stream:
95 | yield tuple(line.decode(encoding).rstrip('\n').split('\t'))
96 |
97 |
98 | class TSVFormat(luigi.format.Format):
99 | """
100 | A basic CSV/TSV format.
101 | Discussion: https://groups.google.com/forum/#!topic/luigi-user/F813st16xqw
102 | """
103 |
104 | def hdfs_reader(self, input_pipe):
105 | raise NotImplementedError()
106 |
107 | def hdfs_writer(self, output_pipe):
108 | raise NotImplementedError()
109 |
110 | def pipe_reader(self, input_pipe):
111 | input_pipe.iter_tsv = functools.partial(iter_tsv, input_pipe)
112 | return input_pipe
113 |
114 | def pipe_writer(self, output_pipe):
115 | output_pipe.write_tsv = functools.partial(write_tsv, output_pipe)
116 | return output_pipe
117 |
118 |
119 | class GzipFormat(luigi.format.Format):
120 | """
121 | A gzip format, that upgrades itself to pigz, if it's installed.
122 | """
123 | input = 'bytes'
124 | output = 'bytes'
125 |
126 | def __init__(self, compression_level=None):
127 | self.compression_level = compression_level
128 | self.gzip = ["gzip"]
129 | self.gunzip = ["gunzip"]
130 |
131 | if which('pigz'):
132 | self.gzip = ["pigz"]
133 | self.gunzip = ["unpigz"]
134 |
135 | def pipe_reader(self, input_pipe):
136 | return luigi.format.InputPipeProcessWrapper(self.gunzip, input_pipe)
137 |
138 | def pipe_writer(self, output_pipe):
139 | args = self.gzip
140 | if self.compression_level is not None:
141 | args.append('-' + str(int(self.compression_level)))
142 | return luigi.format.OutputPipeProcessWrapper(args, output_pipe)
143 |
144 | class ZstdFormat(luigi.format.Format):
145 | """
146 | The zstandard format.
147 | """
148 | input = 'bytes'
149 | output = 'bytes'
150 |
151 | def __init__(self, compression_level=None):
152 | self.compression_level = compression_level
153 | self.zstd = ["zstd"]
154 | self.unzstd = ["unzstd"]
155 |
156 | def pipe_reader(self, input_pipe):
157 | return luigi.format.InputPipeProcessWrapper(self.unzstd, input_pipe)
158 |
159 | def pipe_writer(self, output_pipe):
160 | args = self.zstd
161 | if self.compression_level is not None:
162 | args.append('-' + str(int(self.compression_level)))
163 | return luigi.format.OutputPipeProcessWrapper(args, output_pipe)
164 |
165 | TSV = TSVFormat()
166 | Gzip = GzipFormat()
167 | Zstd = ZstdFormat()
168 |
--------------------------------------------------------------------------------
/gluish/intervals.py:
--------------------------------------------------------------------------------
1 | # coding: utf-8
2 | #
3 | # Copyright 2015 by Leipzig University Library, http://ub.uni-leipzig.de
4 | # by The Finc Authors, http://finc.info
5 | # by Martin Czygan,
6 | #
7 | # This file is part of some open source application.
8 | #
9 | # Some open source application is free software: you can redistribute
10 | # it and/or modify it under the terms of the GNU General Public
11 | # License as published by the Free Software Foundation, either
12 | # version 3 of the License, or (at your option) any later version.
13 | #
14 | # Some open source application is distributed in the hope that it will
15 | # be useful, but WITHOUT ANY WARRANTY; without even the implied warranty
16 | # of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 | # GNU General Public License for more details.
18 | #
19 | # You should have received a copy of the GNU General Public License
20 | # along with Foobar. If not, see .
21 | #
22 | # @license GPL-3.0+
23 | #
24 |
25 | """
26 | Various intervals.
27 | """
28 |
29 | import datetime
30 |
31 | __all__ = [
32 | 'biweekly',
33 | 'daily',
34 | 'every_minute',
35 | 'hourly',
36 | 'monthly',
37 | 'quarterly',
38 | 'semiyearly',
39 | 'weekly',
40 | 'yearly',
41 | ]
42 |
43 | def every_minute(dt=datetime.datetime.utcnow(), fmt=None):
44 | """
45 | Just pass on the given date.
46 | """
47 | date = datetime.datetime(dt.year, dt.month, dt.day, dt.hour, dt.minute, 1, 0, dt.tzinfo)
48 | if fmt is not None:
49 | return date.strftime(fmt)
50 | return date
51 |
52 | def hourly(dt=datetime.datetime.utcnow(), fmt=None):
53 | """
54 | Get a new datetime object every hour.
55 | """
56 | date = datetime.datetime(dt.year, dt.month, dt.day, dt.hour, 1, 1, 0, dt.tzinfo)
57 | if fmt is not None:
58 | return date.strftime(fmt)
59 | return date
60 |
61 | def daily(date=datetime.date.today()):
62 | """
63 | Just pass on the given date.
64 | """
65 | return date
66 |
67 | def weekly(date=datetime.date.today()):
68 | """
69 | Weeks start are fixes at Monday for now.
70 | """
71 | return date - datetime.timedelta(days=date.weekday())
72 |
73 | def biweekly(date=datetime.date.today()):
74 | """
75 | Every two weeks.
76 | """
77 | return datetime.date(date.year, date.month, 1 if date.day < 15 else 15)
78 |
79 | def monthly(date=datetime.date.today()):
80 | """
81 | Take a date object and return the first day of the month.
82 | """
83 | return datetime.date(date.year, date.month, 1)
84 |
85 | def quarterly(date=datetime.date.today()):
86 | """
87 | Fixed at: 1/1, 4/1, 7/1, 10/1.
88 | """
89 | return datetime.date(date.year, ((date.month - 1)//3) * 3 + 1, 1)
90 |
91 | def semiyearly(date=datetime.date.today()):
92 | """
93 | Twice a year.
94 | """
95 | return datetime.date(date.year, 1 if date.month < 7 else 7, 1)
96 |
97 | def yearly(date=datetime.date.today()):
98 | """
99 | Once a year.
100 | """
101 | return datetime.date(date.year, 1, 1)
102 |
--------------------------------------------------------------------------------
/gluish/parameter.py:
--------------------------------------------------------------------------------
1 | # coding: utf-8
2 | # pylint: disable=F0401,C0103,R0921,E1101,W0232,R0201,R0903,E1002
3 | #
4 | # Copyright 2015 by Leipzig University Library, http://ub.uni-leipzig.de
5 | # by The Finc Authors, http://finc.info
6 | # by Martin Czygan,
7 | #
8 | # This file is part of some open source application.
9 | #
10 | # Some open source application is free software: you can redistribute
11 | # it and/or modify it under the terms of the GNU General Public
12 | # License as published by the Free Software Foundation, either
13 | # version 3 of the License, or (at your option) any later version.
14 | #
15 | # Some open source application is distributed in the hope that it will
16 | # be useful, but WITHOUT ANY WARRANTY; without even the implied warranty
17 | # of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 | # GNU General Public License for more details.
19 | #
20 | # You should have received a copy of the GNU General Public License
21 | # along with Foobar. If not, see .
22 | #
23 | # @license GPL-3.0+
24 | #
25 |
26 | """
27 | Custom luigi parameters.
28 | """
29 |
30 | import luigi
31 |
32 | __all__ = ['ClosestDateParameter']
33 |
34 | class ClosestDateParameter(luigi.DateParameter):
35 | """
36 | A marker parameter to replace date parameter value with whatever
37 | self.closest() returns. Use in conjunction with `gluish.task.BaseTask`.
38 | """
39 | use_closest_date = True
40 |
--------------------------------------------------------------------------------
/gluish/task.py:
--------------------------------------------------------------------------------
1 | # coding: utf-8
2 | # pylint: disable=F0401,E1101,E1103
3 | #
4 | # Copyright 2015 by Leipzig University Library, http://ub.uni-leipzig.de
5 | # by The Finc Authors, http://finc.info
6 | # by Martin Czygan,
7 | #
8 | # This file is part of some open source application.
9 | #
10 | # Some open source application is free software: you can redistribute
11 | # it and/or modify it under the terms of the GNU General Public
12 | # License as published by the Free Software Foundation, either
13 | # version 3 of the License, or (at your option) any later version.
14 | #
15 | # Some open source application is distributed in the hope that it will
16 | # be useful, but WITHOUT ANY WARRANTY; without even the implied warranty
17 | # of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 | # GNU General Public License for more details.
19 | #
20 | # You should have received a copy of the GNU General Public License
21 | # along with Foobar. If not, see .
22 | #
23 | # @license GPL-3.0+
24 | #
25 |
26 | """
27 | Default task
28 | ============
29 |
30 | A default task, that covers file system layout.
31 | """
32 |
33 | import datetime
34 | import hashlib
35 | import os
36 | import tempfile
37 |
38 | import luigi
39 | from gluish.parameter import ClosestDateParameter
40 |
41 | __all__ = [
42 | 'BaseTask',
43 | 'MockTask'
44 | ]
45 |
46 | def is_closest_date_parameter(task, param_name):
47 | """ Return the parameter class of param_name on task. """
48 | for name, obj in task.get_params():
49 | if name == param_name:
50 | return hasattr(obj, 'use_closest_date')
51 | return False
52 |
53 | def delistify(x):
54 | """ A basic slug version of a given parameter list. """
55 | if isinstance(x, list):
56 | x = [e.replace("'", "") for e in x]
57 | return '-'.join(sorted(x))
58 | return x
59 |
60 | class BaseTask(luigi.Task):
61 | """
62 | A base task with a `path` method. BASE should be set to the root
63 | directory of all tasks. TAG is a shard for a group of related tasks.
64 | """
65 | BASE = os.environ.get('GLUISH_DATA', tempfile.gettempdir())
66 | TAG = 'default'
67 |
68 | def closest(self):
69 | """ Return the closest date for a given date.
70 | Defaults to the same date. """
71 | if not hasattr(self, 'date'):
72 | raise AttributeError('Task has no date attribute.')
73 | return self.date
74 |
75 | def effective_task_id(self):
76 | """ Replace date in task id with closest date. """
77 | params = self.param_kwargs
78 | if 'date' in params and is_closest_date_parameter(self, 'date'):
79 | params['date'] = self.closest()
80 | task_id_parts = sorted(['%s=%s' % (k, str(v)) for k, v in params.items()])
81 | return '%s(%s)' % (self.task_family, ', '.join(task_id_parts))
82 | else:
83 | return self.task_id
84 |
85 | def taskdir(self):
86 | """ Return the directory under which all artefacts are stored. """
87 | return os.path.join(self.BASE, self.TAG, self.task_family)
88 |
89 | def path(self, filename=None, ext='tsv', digest=False, shard=False, encoding='utf-8'):
90 | """
91 | Return the path for this class with a certain set of parameters.
92 | `ext` sets the extension of the file.
93 | If `hash` is true, the filename (w/o extenstion) will be hashed.
94 | If `shard` is true, the files are placed in shards, based on the first
95 | two chars of the filename (hashed).
96 | """
97 | if self.BASE is NotImplemented:
98 | raise RuntimeError('BASE directory must be set.')
99 |
100 | params = dict(self.get_params())
101 |
102 | if filename is None:
103 | parts = []
104 |
105 | for name, param in self.get_params():
106 | if not param.significant:
107 | continue
108 | if name == 'date' and is_closest_date_parameter(self, 'date'):
109 | parts.append('date-%s' % self.closest())
110 | continue
111 | if hasattr(param, 'is_list') and param.is_list:
112 | es = '-'.join([str(v) for v in getattr(self, name)])
113 | parts.append('%s-%s' % (name, es))
114 | continue
115 |
116 | val = getattr(self, name)
117 |
118 | if isinstance(val, datetime.datetime):
119 | val = val.strftime('%Y-%m-%dT%H%M%S')
120 | elif isinstance(val, datetime.date):
121 | val = val.strftime('%Y-%m-%d')
122 |
123 | parts.append('%s-%s' % (name, val))
124 |
125 | name = '-'.join(sorted(parts))
126 | if len(name) == 0:
127 | name = 'output'
128 | if digest:
129 | name = hashlib.sha1(name.encode(encoding)).hexdigest()
130 | if not ext:
131 | filename = '{fn}'.format(ext=ext, fn=name)
132 | else:
133 | filename = '{fn}.{ext}'.format(ext=ext, fn=name)
134 | if shard:
135 | prefix = hashlib.sha1(filename.encode(encoding)).hexdigest()[:2]
136 | return os.path.join(self.BASE, self.TAG, self.task_family, prefix, filename)
137 |
138 | return os.path.join(self.BASE, self.TAG, self.task_family, filename)
139 |
140 | class MockTask(BaseTask):
141 | """ A mock task object. Read fixture from path and that's it. """
142 | fixture = luigi.Parameter()
143 |
144 | def content(self):
145 | """ Return the content of the file in path. """
146 | with open(self.fixture) as handle:
147 | return handle.read()
148 |
149 | def run(self):
150 | """ Just copy the fixture, so we have some output. """
151 | luigi.LocalTarget(path=self.fixture).copy(self.output().path)
152 |
153 | def output(self):
154 | """ Mock output. """
155 | return luigi.LocalTarget(path=self.path(digest=True))
156 |
--------------------------------------------------------------------------------
/gluish/utils.py:
--------------------------------------------------------------------------------
1 | # coding: utf-8
2 | # pylint: disable=C0301
3 | #
4 | # Copyright 2015 by Leipzig University Library, http://ub.uni-leipzig.de
5 | # by The Finc Authors, http://finc.info
6 | # by Martin Czygan,
7 | #
8 | # This file is part of some open source application.
9 | #
10 | # Some open source application is free software: you can redistribute
11 | # it and/or modify it under the terms of the GNU General Public
12 | # License as published by the Free Software Foundation, either
13 | # version 3 of the License, or (at your option) any later version.
14 | #
15 | # Some open source application is distributed in the hope that it will
16 | # be useful, but WITHOUT ANY WARRANTY; without even the implied warranty
17 | # of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 | # GNU General Public License for more details.
19 | #
20 | # You should have received a copy of the GNU General Public License
21 | # along with Foobar. If not, see .
22 | #
23 | # @license GPL-3.0+
24 | #
25 |
26 | """
27 | A few utilities.
28 | """
29 |
30 | import logging
31 | import os
32 | import random
33 | import re
34 | import string
35 | import subprocess
36 | import tempfile
37 |
38 | from dateutil import relativedelta
39 |
40 | __all__ = [
41 | 'date_range',
42 | 'random_string',
43 | 'shellout',
44 | ]
45 |
46 | logger = logging.getLogger('gluish')
47 |
48 | def random_string(length=16):
49 | """
50 | Return a random string (upper and lowercase letters) of length `length`,
51 | defaults to 16.
52 | """
53 | return ''.join(random.choice(string.ascii_letters) for _ in range(length))
54 |
55 | def date_range(start_date, end_date, increment, period):
56 | """
57 | Generate `date` objects between `start_date` and `end_date` in `increment`
58 | `period` intervals.
59 | """
60 | next = start_date
61 | delta = relativedelta.relativedelta(**{period:increment})
62 | while next <= end_date:
63 | yield next
64 | next += delta
65 |
66 | def which(program):
67 | """
68 | Search for program in PATH.
69 | """
70 | def is_exe(fpath):
71 | return os.path.isfile(fpath) and os.access(fpath, os.X_OK)
72 |
73 | fpath, fname = os.path.split(program)
74 | if fpath:
75 | if is_exe(program):
76 | return program
77 | else:
78 | for path in os.environ["PATH"].split(os.pathsep):
79 | path = path.strip('"')
80 | exe_file = os.path.join(path, program)
81 | if is_exe(exe_file):
82 | return exe_file
83 |
84 | return None
85 |
86 | def shellout(template, preserve_whitespace=False, executable='/bin/bash',
87 | ignoremap=None, encoding=None, pipefail=True, **kwargs):
88 | """
89 |
90 | Takes a shell command template and executes it. The template must use the
91 | new (2.6+) format mini language. `kwargs` must contain any defined
92 | placeholder, only `output` is optional and will be autofilled with a
93 | temporary file if it used, but not specified explicitly.
94 |
95 | If `pipefail` is `False` no subshell environment will be spawned, where a
96 | failed pipe will cause an error as well. If `preserve_whitespace` is `True`,
97 | no whitespace normalization is performed. A custom shell executable name can
98 | be passed in `executable` and defaults to `/bin/bash`.
99 |
100 | Raises RuntimeError on nonzero exit codes. To ignore certain errors, pass a
101 | dictionary in `ignoremap`, with the error code to ignore as key and a string
102 | message as value.
103 |
104 | Simple template:
105 |
106 | wc -l < {input} > {output}
107 |
108 | Quoted curly braces:
109 |
110 | ps ax|awk '{{print $1}}' > {output}
111 |
112 | Usage with luigi:
113 |
114 | ...
115 | tmp = shellout('wc -l < {input} > {output}', input=self.input().path)
116 | luigi.LocalTarget(tmp).move(self.output().path)
117 | ....
118 |
119 | """
120 | if not 'output' in kwargs:
121 | kwargs.update({'output': tempfile.mkstemp(prefix='gluish-')[1]})
122 | if ignoremap is None:
123 | ignoremap = {}
124 | if encoding:
125 | command = template.decode(encoding).format(**kwargs)
126 | else:
127 | command = template.format(**kwargs)
128 | if not preserve_whitespace:
129 | command = re.sub('[ \t\n]+', ' ', command)
130 | if pipefail:
131 | command = '(set -o pipefail && %s)' % command
132 | logger.debug(command)
133 | code = subprocess.call([command], shell=True, executable=executable)
134 | if not code == 0:
135 | if code in ignoremap:
136 | logger.info("Ignoring error via ignoremap: %s" % ignoremap.get(code))
137 | else:
138 | logger.error('%s: %s' % (command, code))
139 | error = RuntimeError('%s exitcode: %s' % (command, code))
140 | error.code = code
141 | raise error
142 | return kwargs.get('output')
143 |
--------------------------------------------------------------------------------
/requirements.txt:
--------------------------------------------------------------------------------
1 | luigi>=1.0.20
2 | python-dateutil==2.2
3 | pytz==2014.4
4 | six==1.9.0
5 | future==0.16.0 # TODO(miku): get rid of this soon.
6 | requests>=2.18.4
7 |
--------------------------------------------------------------------------------
/setup.py:
--------------------------------------------------------------------------------
1 | # coding: utf-8
2 | #
3 | # Copyright 2015 by Leipzig University Library, http://ub.uni-leipzig.de
4 | # by The Finc Authors, http://finc.info
5 | # by Martin Czygan,
6 | #
7 | # This file is part of some open source application.
8 | #
9 | # Some open source application is free software: you can redistribute
10 | # it and/or modify it under the terms of the GNU General Public
11 | # License as published by the Free Software Foundation, either
12 | # version 3 of the License, or (at your option) any later version.
13 | #
14 | # Some open source application is distributed in the hope that it will
15 | # be useful, but WITHOUT ANY WARRANTY; without even the implied warranty
16 | # of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 | # GNU General Public License for more details.
18 | #
19 | # You should have received a copy of the GNU General Public License
20 | # along with Foobar. If not, see .
21 | #
22 | # @license GPL-3.0+
23 | #
24 |
25 | """
26 | Some glue around luigi.
27 |
28 | Provides a base class, that autogenerates its output filenames based on some
29 | tag, classname and parameters.
30 |
31 | Additionally, provide some smaller utilities, like a TSV format.
32 | """
33 |
34 | from setuptools import setup
35 |
36 | setup(name='gluish',
37 | version='0.3.0',
38 | description='Luigi helper.',
39 | url='https://github.com/miku/gluish',
40 | author='Martin Czygan',
41 | author_email='martin.czygan@gmail.com',
42 | packages=[
43 | 'gluish',
44 | ],
45 | package_dir={'gluish': 'gluish'},
46 | install_requires=[
47 | 'luigi>=1.0.20',
48 | 'python-dateutil>=2.2',
49 | 'pytz>=2014.4',
50 | 'requests>=2.18.4',
51 | 'six>=1.9.0',
52 | ],
53 | )
54 |
--------------------------------------------------------------------------------
/test/fixtures/l-1.txt:
--------------------------------------------------------------------------------
1 | 1
2 |
--------------------------------------------------------------------------------
/test/fixtures/l-100.txt:
--------------------------------------------------------------------------------
1 | 1
2 | 1
3 | 1
4 | 1
5 | 1
6 | 1
7 | 1
8 | 1
9 | 1
10 | 1
11 | 1
12 | 1
13 | 1
14 | 1
15 | 1
16 | 1
17 | 1
18 | 1
19 | 1
20 | 1
21 | 1
22 | 1
23 | 1
24 | 1
25 | 1
26 | 1
27 | 1
28 | 1
29 | 1
30 | 1
31 | 1
32 | 1
33 | 1
34 | 1
35 | 1
36 | 1
37 | 1
38 | 1
39 | 1
40 | 1
41 | 1
42 | 1
43 | 1
44 | 1
45 | 1
46 | 1
47 | 1
48 | 1
49 | 1
50 | 1
51 | 1
52 | 1
53 | 1
54 | 1
55 | 1
56 | 1
57 | 1
58 | 1
59 | 1
60 | 1
61 | 1
62 | 1
63 | 1
64 | 1
65 | 1
66 | 1
67 | 1
68 | 1
69 | 1
70 | 1
71 | 1
72 | 1
73 | 1
74 | 1
75 | 1
76 | 1
77 | 1
78 | 1
79 | 1
80 | 1
81 | 1
82 | 1
83 | 1
84 | 1
85 | 1
86 | 1
87 | 1
88 | 1
89 | 1
90 | 1
91 | 1
92 | 1
93 | 1
94 | 1
95 | 1
96 | 1
97 | 1
98 | 1
99 | 1
100 | 1
101 |
--------------------------------------------------------------------------------
/test/format_test.py:
--------------------------------------------------------------------------------
1 | # coding: utf-8
2 | #
3 | # Copyright 2015 by Leipzig University Library, http://ub.uni-leipzig.de
4 | # by The Finc Authors, http://finc.info
5 | # by Martin Czygan,
6 | #
7 | # This file is part of some open source application.
8 | #
9 | # Some open source application is free software: you can redistribute
10 | # it and/or modify it under the terms of the GNU General Public
11 | # License as published by the Free Software Foundation, either
12 | # version 3 of the License, or (at your option) any later version.
13 | #
14 | # Some open source application is distributed in the hope that it will
15 | # be useful, but WITHOUT ANY WARRANTY; without even the implied warranty
16 | # of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 | # GNU General Public License for more details.
18 | #
19 | # You should have received a copy of the GNU General Public License
20 | # along with Foobar. If not, see .
21 | #
22 | # @license GPL-3.0+
23 | #
24 |
25 | import gzip
26 | import hashlib
27 | import os
28 | import tempfile
29 | import unittest
30 |
31 | import luigi
32 | from gluish.format import TSV, iter_tsv, write_tsv, Gzip
33 |
34 |
35 | class FormatTest(unittest.TestCase):
36 |
37 | def test_write_tsv(self):
38 | path = tempfile.mktemp()
39 | with open(path, 'wb') as handle:
40 | write_tsv(handle, 'A', 'B', 'C')
41 | with open(path, 'rb') as handle:
42 | self.assertEqual(b'A\tB\tC\n', handle.read())
43 |
44 | def test_iter_tsv(self):
45 | path = tempfile.mktemp()
46 |
47 | with open(path, 'wb') as handle:
48 | write_tsv(handle, 'A', 'B', 'C')
49 |
50 | with open(path, 'rb') as handle:
51 | row = next(iter_tsv(handle))
52 | self.assertEqual(3, len(row))
53 |
54 | with open(path, 'rb') as handle:
55 | row = next(iter_tsv(handle, cols=('a', 'b', 'c')))
56 | self.assertEqual(3, len(row))
57 | self.assertEqual(row.a, 'A')
58 | self.assertEqual(row.b, 'B')
59 | self.assertEqual(row.c, 'C')
60 |
61 | with open(path, 'rb') as handle:
62 | exception_raised = False
63 | try:
64 | row = next(iter_tsv(handle, cols=('a', 'b')))
65 | except TypeError:
66 | exception_raised = True
67 | self.assertTrue(exception_raised)
68 |
69 | with open(path, 'rb') as handle:
70 | row = next(iter_tsv(handle, cols=('a', 0, 0)))
71 | self.assertEqual(3, len(row))
72 | self.assertEqual(row.a, 'A')
73 | self.assertFalse(hasattr(row, 'b'))
74 | self.assertFalse(hasattr(row, 'c'))
75 |
76 | with open(path, 'rb') as handle:
77 | row = next(iter_tsv(handle, cols=('X', 'b', 'X')))
78 | self.assertEqual(3, len(row))
79 | self.assertEqual(row.b, 'B')
80 | self.assertFalse(hasattr(row, 'a'))
81 | self.assertFalse(hasattr(row, 'c'))
82 |
83 |
84 | class TSVFormatTest(unittest.TestCase):
85 |
86 | def test_target(self):
87 | path = tempfile.mktemp()
88 | target = luigi.LocalTarget(path=path, format=TSV)
89 | with target.open('wb') as handle:
90 | self.assertTrue(hasattr(handle, 'write_tsv'))
91 | with target.open('rb') as handle:
92 | self.assertTrue(hasattr(handle, 'iter_tsv'))
93 |
94 | DUMMY_GZIP_FILENAME = '/tmp/gluish-DummyGzipTask-test'
95 |
96 | class DummyGzipTask(luigi.Task):
97 | def run(self):
98 | with self.output().open('wb') as output:
99 | output.write(b"hello")
100 | def output(self):
101 | return luigi.LocalTarget(path=DUMMY_GZIP_FILENAME, format=Gzip)
102 |
103 | class GzipFormatTest(unittest.TestCase):
104 |
105 | def test_decompress(self):
106 | try:
107 | os.remove(DUMMY_GZIP_FILENAME)
108 | except FileNotFoundError:
109 | pass
110 |
111 | task = DummyGzipTask()
112 | luigi.build([task], local_scheduler=True)
113 |
114 | self.assertTrue(os.path.exists(DUMMY_GZIP_FILENAME))
115 | with gzip.open(DUMMY_GZIP_FILENAME) as f:
116 | self.assertEqual(f.read(), b'hello')
117 |
118 | if __name__ == '__main__':
119 | unittest.main()
120 |
--------------------------------------------------------------------------------
/test/intervals_test.py:
--------------------------------------------------------------------------------
1 | # coding: utf-8
2 | # pylint: disable=C0103
3 | #
4 | # Copyright 2015 by Leipzig University Library, http://ub.uni-leipzig.de
5 | # by The Finc Authors, http://finc.info
6 | # by Martin Czygan,
7 | #
8 | # This file is part of some open source application.
9 | #
10 | # Some open source application is free software: you can redistribute
11 | # it and/or modify it under the terms of the GNU General Public
12 | # License as published by the Free Software Foundation, either
13 | # version 3 of the License, or (at your option) any later version.
14 | #
15 | # Some open source application is distributed in the hope that it will
16 | # be useful, but WITHOUT ANY WARRANTY; without even the implied warranty
17 | # of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 | # GNU General Public License for more details.
19 | #
20 | # You should have received a copy of the GNU General Public License
21 | # along with Foobar. If not, see .
22 | #
23 | # @license GPL-3.0+
24 | #
25 |
26 | """
27 | Test intervals.
28 | """
29 |
30 | import datetime
31 | import unittest
32 |
33 | import pytz
34 | from dateutil.tz import tzlocal
35 | from gluish.intervals import (biweekly, daily, every_minute, hourly, monthly,
36 | quarterly, semiyearly, weekly, yearly)
37 |
38 |
39 | class IntervalsTest(unittest.TestCase):
40 | """ Test intervals. """
41 |
42 | def test_short_intervals(self):
43 | dt = datetime.datetime(2000, 12, 3, 10, 10, 10, 0, pytz.utc)
44 | self.assertEqual('975834601', every_minute(dt, fmt='%s'))
45 |
46 | dt = datetime.datetime(2014, 6, 24, 13, 57, 59, 0, pytz.utc)
47 | self.assertEqual('1403611261', hourly(dt, fmt='%s'))
48 |
49 | dt = datetime.datetime(2014, 6, 24, 13, 1, 1, 0, pytz.utc)
50 | self.assertEqual('1403611261', hourly(dt, fmt='%s'))
51 |
52 | dt = datetime.datetime(2014, 6, 24, 12, 59, 59, 0, pytz.utc)
53 | self.assertEqual('1403607661', hourly(dt, fmt='%s'))
54 |
55 | test_short_intervals.notravis = 1
56 |
57 | def test_intervals(self):
58 | """ Basic intervals tests. """
59 |
60 | self.assertEqual(
61 | datetime.datetime(2000, 12, 3, 10, 10, 1, 0, pytz.utc),
62 | every_minute(datetime.datetime(2000, 12, 3, 10, 10, 10, 0, pytz.utc)))
63 |
64 | self.assertEqual(
65 | datetime.datetime(2000, 12, 3, 10, 1, 1, 0, pytz.utc),
66 | hourly(datetime.datetime(2000, 12, 3, 10, 10, 10, 0, pytz.utc)))
67 |
68 | #
69 | # Daily or less often
70 | #
71 | self.assertEqual(
72 | datetime.date(2000, 12, 3),
73 | daily(datetime.date(2000, 12, 3)))
74 |
75 | self.assertEqual(
76 | # 2000-11-27 was a Monday
77 | datetime.date(2000, 11, 27),
78 | weekly(datetime.date(2000, 12, 3)))
79 |
80 | self.assertEqual(
81 | datetime.date(2000, 12, 1),
82 | biweekly(datetime.date(2000, 12, 12)))
83 |
84 | self.assertEqual(
85 | datetime.date(2000, 12, 15),
86 | biweekly(datetime.date(2000, 12, 16)))
87 |
88 | self.assertEqual(
89 | datetime.date(2000, 12, 1),
90 | monthly(datetime.date(2000, 12, 12)))
91 |
92 | self.assertEqual(
93 | datetime.date(2000, 12, 1),
94 | monthly(datetime.date(2000, 12, 12)))
95 |
96 | self.assertEqual(
97 | datetime.date(2000, 10, 1),
98 | quarterly(datetime.date(2000, 12, 12)))
99 |
100 | self.assertEqual(
101 | datetime.date(2000, 7, 1),
102 | semiyearly(datetime.date(2000, 12, 12)))
103 |
104 | self.assertEqual(
105 | datetime.date(2000, 1, 1),
106 | yearly(datetime.date(2000, 12, 12)))
107 |
--------------------------------------------------------------------------------
/test/parameter_test.py:
--------------------------------------------------------------------------------
1 | # coding: utf-8
2 | #
3 | # Copyright 2015 by Leipzig University Library, http://ub.uni-leipzig.de
4 | # by The Finc Authors, http://finc.info
5 | # by Martin Czygan,
6 | #
7 | # This file is part of some open source application.
8 | #
9 | # Some open source application is free software: you can redistribute
10 | # it and/or modify it under the terms of the GNU General Public
11 | # License as published by the Free Software Foundation, either
12 | # version 3 of the License, or (at your option) any later version.
13 | #
14 | # Some open source application is distributed in the hope that it will
15 | # be useful, but WITHOUT ANY WARRANTY; without even the implied warranty
16 | # of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 | # GNU General Public License for more details.
18 | #
19 | # You should have received a copy of the GNU General Public License
20 | # along with Foobar. If not, see .
21 | #
22 | # @license GPL-3.0+
23 | #
24 |
25 | import unittest
26 |
27 |
28 | class ParameterTest(unittest.TestCase):
29 | """ Test parameters. """
30 |
31 | def test_closest_date_parameter(self):
32 | """
33 | Closest date parameter.
34 | """
35 | pass
36 |
--------------------------------------------------------------------------------
/test/task_test.py:
--------------------------------------------------------------------------------
1 | # coding: utf-8
2 | # pylint: disable=R0201,E1101,W0232,R0904
3 | #
4 | # Copyright 2015 by Leipzig University Library, http://ub.uni-leipzig.de
5 | # by The Finc Authors, http://finc.info
6 | # by Martin Czygan,
7 | #
8 | # This file is part of some open source application.
9 | #
10 | # Some open source application is free software: you can redistribute
11 | # it and/or modify it under the terms of the GNU General Public
12 | # License as published by the Free Software Foundation, either
13 | # version 3 of the License, or (at your option) any later version.
14 | #
15 | # Some open source application is distributed in the hope that it will
16 | # be useful, but WITHOUT ANY WARRANTY; without even the implied warranty
17 | # of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 | # GNU General Public License for more details.
19 | #
20 | # You should have received a copy of the GNU General Public License
21 | # along with Foobar. If not, see .
22 | #
23 | # @license GPL-3.0+
24 | #
25 |
26 | """
27 | Test tasks.
28 | """
29 |
30 | import datetime
31 | import os
32 | import shutil
33 | import tempfile
34 | import unittest
35 |
36 | import luigi
37 | from gluish.parameter import ClosestDateParameter
38 | from gluish.task import BaseTask, MockTask, is_closest_date_parameter
39 | from gluish.utils import shellout
40 |
41 | FIXTURES = os.path.join(os.path.dirname(__file__), 'fixtures')
42 |
43 | class TestTask(BaseTask):
44 | """ A base class for test tasks. """
45 | BASE = tempfile.gettempdir()
46 | TAG = 'gluish-testtasks'
47 |
48 | class TaskA(TestTask):
49 | """ Plain vanilla task, that does nothing. """
50 |
51 | def output(self):
52 | """ output """
53 | return luigi.LocalTarget(path=self.path())
54 |
55 | class TaskB(TestTask):
56 | """ Task with a date param. """
57 | date = luigi.DateParameter(default=datetime.date(1970, 1, 1))
58 |
59 | def output(self):
60 | """ output """
61 | return luigi.LocalTarget(path=self.path())
62 |
63 | class TaskC(TestTask):
64 | """ Task with a date param and an float param. """
65 | date = luigi.DateParameter(default=datetime.date(1970, 1, 1))
66 | threshold = luigi.FloatParameter(default=0.1)
67 |
68 | def output(self):
69 | """ output """
70 | return luigi.LocalTarget(path=self.path())
71 |
72 | class TaskD(TestTask):
73 | """ Task with a date param and an float param. And a closest method. """
74 | date = ClosestDateParameter(default=datetime.date(1970, 1, 1))
75 | threshold = luigi.FloatParameter(default=0.1)
76 |
77 | def closest(self):
78 | """ some dynamic attribute """
79 | return self.date
80 |
81 | def output(self):
82 | """ output """
83 | return luigi.LocalTarget(path=self.path())
84 |
85 | class TaskE(TestTask):
86 | """ Task with a date param and an float param. And a closest method. """
87 | date = ClosestDateParameter(default=datetime.date(2000, 1, 1))
88 | threshold = luigi.FloatParameter(default=0.1)
89 |
90 | def closest(self):
91 | """ some dynamic attribute """
92 | return self.date - datetime.timedelta(days=365)
93 |
94 | def output(self):
95 | """ output """
96 | return luigi.LocalTarget(path=self.path())
97 |
98 | class TaskF(TestTask):
99 | """ Task with a date param and an float param. And a closest method. """
100 | date = ClosestDateParameter(default=datetime.date(2000, 1, 1))
101 | threshold = luigi.FloatParameter(default=0.1, significant=False)
102 |
103 | def closest(self):
104 | """ some dynamic attribute """
105 | return self.date - datetime.timedelta(days=1)
106 |
107 | def output(self):
108 | """ output """
109 | return luigi.LocalTarget(path=self.path())
110 |
111 | class TaskG(TestTask):
112 | """ Task with a date param and an float param. And a closest method. """
113 | date = luigi.DateParameter(default=datetime.date(2000, 1, 1))
114 |
115 | def output(self):
116 | """ output """
117 | return luigi.LocalTarget(path=self.path())
118 |
119 | class TaskH(TestTask):
120 | """ Task with a date param and an float param. And a closest method. """
121 | closest = luigi.DateParameter(default=datetime.date(2000, 1, 1))
122 |
123 | def output(self):
124 | """ output """
125 | return luigi.LocalTarget(path=self.path())
126 |
127 | class TaskI(TestTask):
128 | """ Task with a date param and an float param. And a closest method. """
129 | closest = ClosestDateParameter(default=datetime.date(2000, 1, 1))
130 |
131 | def closest(self):
132 | """ some dynamic attribute """
133 | return self.date - datetime.timedelta(days=1)
134 |
135 | def output(self):
136 | """ output """
137 | return luigi.LocalTarget(path=self.path())
138 |
139 | class TaskJ(TestTask):
140 | """ Task with some exception in closest. """
141 | date = ClosestDateParameter(default=datetime.date(2000, 1, 1))
142 |
143 | def closest(self):
144 | raise ValueError()
145 |
146 | def output(self):
147 | """ output """
148 | return luigi.LocalTarget(path=self.path())
149 |
150 | class TaskK(TestTask):
151 | """ Task that returns a float from closest. """
152 | date = ClosestDateParameter(default=datetime.date(2000, 1, 1))
153 |
154 | def closest(self):
155 | return 10.10
156 |
157 | def output(self):
158 | """ output """
159 | return luigi.LocalTarget(path=self.path())
160 |
161 | class TaskL(TestTask):
162 | """ Task that returns some custom object from closest. """
163 | date = ClosestDateParameter(default=datetime.date(2000, 1, 1))
164 |
165 | def closest(self):
166 | class X(object):
167 | def __str__(self):
168 | return 'ABC'
169 | return X()
170 |
171 | def output(self):
172 | """ output """
173 | return luigi.LocalTarget(path=self.path())
174 |
175 | class TaskM(TestTask):
176 | """ Task that returns a float from closest. """
177 | a = luigi.IntParameter(default=1)
178 | b = luigi.IntParameter(default=2)
179 | c = luigi.Parameter(default='hello')
180 | date = ClosestDateParameter(default=datetime.date(2000, 1, 1))
181 |
182 | def closest(self):
183 | return 10.10
184 |
185 | def output(self):
186 | """ output """
187 | return luigi.LocalTarget(path=self.path())
188 |
189 | class TaskN(TestTask):
190 |
191 | def run(self):
192 | """ Simulate touch. """
193 | luigi.LocalTarget(path=self.output().path).open('w')
194 |
195 | def output(self):
196 | """ output """
197 | return luigi.LocalTarget(path=self.path())
198 |
199 | class ShardedTask(TestTask):
200 | """ Example task, that shards its outputs. """
201 | param = luigi.Parameter(default='Hello')
202 |
203 | def run(self):
204 | """ Dummy run. """
205 |
206 | def output(self):
207 | """ Use shard=True """
208 | return luigi.LocalTarget(path=self.path(shard=True))
209 |
210 | class TaskTest(unittest.TestCase):
211 | """ Test tasks. """
212 |
213 | @classmethod
214 | def tearDownClass(cls):
215 | base_dir = os.path.join(TestTask.BASE, TestTask.TAG)
216 | if os.path.exists(base_dir):
217 | shutil.rmtree(base_dir)
218 |
219 | def test_is_closest_date_parameter(self):
220 | self.assertEqual(is_closest_date_parameter(TaskL, 'date'), True)
221 | self.assertEqual(is_closest_date_parameter(TaskG, 'date'), False)
222 |
223 | def test_generic_task(self):
224 | """ Only output tests. """
225 | prefix = os.path.join(TestTask.BASE, TestTask.TAG)
226 |
227 | task = TaskA()
228 | self.assertEqual(task.output().path,
229 | os.path.join(prefix, 'TaskA', 'output.tsv'))
230 |
231 | task = TaskB()
232 | self.assertEqual(task.output().path,
233 | os.path.join(prefix, 'TaskB', 'date-1970-01-01.tsv'))
234 |
235 | task = TaskC()
236 | self.assertEqual(task.output().path,
237 | os.path.join(prefix, 'TaskC', 'date-1970-01-01-threshold-0.1.tsv'))
238 |
239 | task = TaskD()
240 | self.assertEqual(task.output().path,
241 | os.path.join(prefix, 'TaskD', 'date-1970-01-01-threshold-0.1.tsv'))
242 |
243 | task = TaskE()
244 | self.assertEqual(task.output().path,
245 | os.path.join(prefix, 'TaskE', 'date-1999-01-01-threshold-0.1.tsv'))
246 |
247 | task = TaskF()
248 | self.assertEqual(task.closest(), datetime.date(1999, 12, 31))
249 | self.assertEqual(task.output().path,
250 | os.path.join(prefix, 'TaskF', 'date-1999-12-31.tsv'))
251 |
252 | task = TaskG()
253 | self.assertEqual(task.closest(), datetime.date(2000, 1, 1))
254 | self.assertEqual(task.output().path,
255 | os.path.join(prefix, 'TaskG', 'date-2000-01-01.tsv'))
256 |
257 | task = TaskH()
258 | self.assertEqual(task.closest, datetime.date(2000, 1, 1))
259 | self.assertEqual(task.output().path,
260 | os.path.join(prefix, 'TaskH', 'closest-2000-01-01.tsv'))
261 |
262 | task = TaskI()
263 | self.assertRaises(AttributeError, task.closest)
264 |
265 | self.assertEqual(task.output().path,
266 | os.path.join(prefix, 'TaskI', 'output.tsv'))
267 |
268 | task = TaskJ()
269 | self.assertRaises(ValueError, task.closest)
270 | self.assertRaises(ValueError, task.output)
271 |
272 | task = TaskK()
273 | self.assertEqual(task.output().path,
274 | os.path.join(prefix, 'TaskK', 'date-10.1.tsv'))
275 |
276 | task = TaskL()
277 | self.assertEqual(task.output().path,
278 | os.path.join(prefix, 'TaskL', 'date-ABC.tsv'))
279 |
280 | task = TaskL()
281 | self.assertEqual(task.output().path,
282 | os.path.join(prefix, 'TaskL', 'date-ABC.tsv'))
283 |
284 | def test_mock_task(self):
285 | """ Test the mock class. """
286 | task = MockTask(fixture=os.path.join(FIXTURES, 'l-1.txt'))
287 | self.assertEqual(task.content(), '1\n')
288 | luigi.build([task], local_scheduler=True)
289 | self.assertEqual(task.output().open().read(), '1\n')
290 |
291 | def test_effective_id(self):
292 | """ Test effective_task_id """
293 | task = TaskK()
294 | self.assertTrue(task.task_id.startswith('TaskK_2000_01_01'))
295 | self.assertEqual('TaskK(date=10.1)', task.effective_task_id())
296 |
297 | task = TaskM()
298 | self.assertTrue(task.task_id.startswith('TaskM_1_2_hello_'))
299 | self.assertEqual('TaskM(a=1, b=2, c=hello, date=10.1)',
300 | task.effective_task_id())
301 |
302 | task = TaskG()
303 | self.assertTrue(task.task_id.startswith('TaskG_2000_01_01_'))
304 | self.assertTrue(task.effective_task_id().startswith('TaskG_2000_01_01_'))
305 |
306 | def test_sharded_task(self):
307 | """ Test, if task output is sharded. """
308 | task = ShardedTask(param="Hello")
309 | self.assertTrue(task.output().path.endswith("62/param-Hello.tsv"))
310 | task = ShardedTask(param="Hi")
311 | self.assertTrue(task.output().path.endswith("1c/param-Hi.tsv"))
312 |
313 | def test_task_dir(self):
314 | task = TaskN()
315 | self.assertFalse(os.path.exists(task.taskdir()))
316 | luigi.build([task], local_scheduler=True)
317 | self.assertTrue(os.path.isdir(task.taskdir()))
318 | self.assertTrue(task.taskdir().endswith('TaskN'))
319 |
--------------------------------------------------------------------------------
/test/utils_test.py:
--------------------------------------------------------------------------------
1 | # coding: utf-8
2 | # pylint: disable=C0103
3 | #
4 | # Copyright 2015 by Leipzig University Library, http://ub.uni-leipzig.de
5 | # by The Finc Authors, http://finc.info
6 | # by Martin Czygan,
7 | #
8 | # This file is part of some open source application.
9 | #
10 | # Some open source application is free software: you can redistribute
11 | # it and/or modify it under the terms of the GNU General Public
12 | # License as published by the Free Software Foundation, either
13 | # version 3 of the License, or (at your option) any later version.
14 | #
15 | # Some open source application is distributed in the hope that it will
16 | # be useful, but WITHOUT ANY WARRANTY; without even the implied warranty
17 | # of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 | # GNU General Public License for more details.
19 | #
20 | # You should have received a copy of the GNU General Public License
21 | # along with Foobar. If not, see .
22 | #
23 | # @license GPL-3.0+
24 | #
25 |
26 | """
27 | Test mixed utils.
28 | """
29 |
30 | import datetime
31 | import os
32 | import sys
33 | import tempfile
34 | import unittest
35 |
36 | from gluish.utils import date_range, shellout
37 |
38 |
39 | class UtilsTest(unittest.TestCase):
40 | """ Test various utility functions. """
41 | def test_date_range(self):
42 | """ Test date ranges. """
43 | start_date = datetime.date(1970, 1, 1)
44 | end_date = datetime.date(1970, 10, 1)
45 | dates = [date for date in date_range(start_date, end_date, 2, 'months')]
46 | self.assertEqual(5, len(dates))
47 |
48 | start_date = datetime.date(1970, 1, 1)
49 | end_date = datetime.date(1970, 1, 3)
50 | dates = [date for date in date_range(start_date, end_date, 1, 'days')]
51 | self.assertEqual(3, len(dates))
52 | self.assertEqual(dates, [datetime.date(1970, 1, 1),
53 | datetime.date(1970, 1, 2),
54 | datetime.date(1970, 1, 3)])
55 |
56 | def test_shellout(self):
57 | """ Test external command calls. """
58 | output = shellout('ls 1> /dev/null && echo {output} 1> /dev/null',
59 | output='hello')
60 | self.assertEqual('hello', output)
61 |
62 | path = tempfile.mktemp()
63 | with open(path, 'w') as handle:
64 | handle.write('Hello World!\n')
65 |
66 | output = shellout('wc -l < {input} > {output}', input=handle.name)
67 | self.assertTrue(os.path.exists(output))
68 | with open(output) as handle:
69 | self.assertEqual('1', handle.read().strip())
70 |
71 | @unittest.skipIf(sys.version_info.major > 2, 'skip on Python 3 for now.')
72 | def test_shellout_encoding(self):
73 | """ Test shellout encoding. """
74 | word = u'Catégorie'
75 | self.assertRaises(UnicodeEncodeError, shellout, 'echo {word}', word=word)
76 |
77 | output = shellout('echo {word} > {output}', word=word, encoding='utf-8')
78 | self.assertTrue(os.path.exists(output))
79 | with open(output) as handle:
80 | content = handle.read().strip()
81 | self.assertEqual('Cat\xc3\xa9gorie', content)
82 | self.assertEqual(u'Catégorie', content.decode('utf-8'))
83 |
--------------------------------------------------------------------------------
/tox.ini:
--------------------------------------------------------------------------------
1 | # Tox (http://tox.testrun.org/) is a tool for running tests
2 | # in multiple virtualenvs. This configuration file will run the
3 | # test suite on all supported python versions. To use it, "pip install tox"
4 | # and then run "tox" from this directory.
5 |
6 | [tox]
7 | envlist = py38, flake8
8 |
9 | [testenv]
10 | commands = pytest
11 | deps =
12 | pytest
13 |
--------------------------------------------------------------------------------