├── .github
└── workflows
│ └── main.yml
├── .gitignore
├── .readthedocs.yml
├── LICENSE
├── MANIFEST.in
├── README.md
├── docs
├── Makefile
└── source
│ ├── api.rst
│ ├── conf.py
│ └── index.rst
├── lib50
├── __init__.py
├── _api.py
├── _errors.py
├── authentication.py
├── config.py
├── crypto.py
└── locale
│ └── es
│ └── LC_MESSAGES
│ └── lib50.po
├── setup.cfg
├── setup.py
└── tests
├── __init__.py
├── __main__.py
├── api_tests.py
├── config_tests.py
├── crypto
├── private.pem
└── public.pem
├── crypto_tests.py
└── lib50_tests.py
/.github/workflows/main.yml:
--------------------------------------------------------------------------------
1 | on: push
2 | jobs:
3 | test-and-deploy:
4 | runs-on: ubuntu-latest
5 | steps:
6 | - uses: actions/checkout@v4
7 | - uses: actions/setup-python@v5
8 | with:
9 | python-version: "3.13"
10 | - name: Run tests
11 | run: |
12 | pip install babel
13 | pip install .
14 | python setup.py compile_catalog
15 | python -m tests
16 | - name: Install pypa/build
17 | run: python -m pip install build --user
18 | - name: Build a binary wheel and a source tarball
19 | run: python -m build --sdist --wheel --outdir dist/ .
20 | - name: Deploy to PyPI
21 | if: ${{ github.ref == 'refs/heads/main' }}
22 | uses: pypa/gh-action-pypi-publish@release/v1
23 | with:
24 | user: __token__
25 | password: ${{ secrets.PYPI_API_TOKEN }}
26 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | .DS_store
2 |
3 | # Byte-compiled / optimized / DLL files
4 | __pycache__/
5 | *.py[cod]
6 | *$py.class
7 |
8 | # C extensions
9 | *.so
10 |
11 | # Distribution / packaging
12 | .Python
13 | build/
14 | develop-eggs/
15 | dist/
16 | downloads/
17 | eggs/
18 | .eggs/
19 | lib/
20 | lib64/
21 | parts/
22 | sdist/
23 | var/
24 | wheels/
25 | *.egg-info/
26 | .installed.cfg
27 | *.egg
28 | MANIFEST
29 |
30 | # PyInstaller
31 | # Usually these files are written by a python script from a template
32 | # before PyInstaller builds the exe, so as to inject date/other infos into it.
33 | *.manifest
34 | *.spec
35 |
36 | # Installer logs
37 | pip-log.txt
38 | pip-delete-this-directory.txt
39 |
40 | # Unit test / coverage reports
41 | htmlcov/
42 | .tox/
43 | .coverage
44 | .coverage.*
45 | .cache
46 | nosetests.xml
47 | coverage.xml
48 | *.cover
49 | .hypothesis/
50 | .pytest_cache/
51 |
52 | # Translations
53 | *.mo
54 | *.pot
55 |
56 | # Django stuff:
57 | *.log
58 | local_settings.py
59 | db.sqlite3
60 |
61 | # Flask stuff:
62 | instance/
63 | .webassets-cache
64 |
65 | # Scrapy stuff:
66 | .scrapy
67 |
68 | # Sphinx documentation
69 | docs/_build/
70 |
71 | # PyBuilder
72 | target/
73 |
74 | # Jupyter Notebook
75 | .ipynb_checkpoints
76 |
77 | # pyenv
78 | .python-version
79 |
80 | # celery beat schedule file
81 | celerybeat-schedule
82 |
83 | # SageMath parsed files
84 | *.sage.py
85 |
86 | # Environments
87 | .env
88 | .venv
89 | env/
90 | venv/
91 | ENV/
92 | env.bak/
93 | venv.bak/
94 |
95 | # Spyder project settings
96 | .spyderproject
97 | .spyproject
98 |
99 | # Rope project settings
100 | .ropeproject
101 |
102 | # mkdocs documentation
103 | /site
104 |
105 | # mypy
106 | .mypy_cache/
107 |
--------------------------------------------------------------------------------
/.readthedocs.yml:
--------------------------------------------------------------------------------
1 | build:
2 | image: latest
3 |
4 | python:
5 | version: 3.7
6 | install:
7 | - method: pip
8 | path: .
9 | extra_requirements:
10 | - develop
11 |
12 | sphinx:
13 | builder: dirhtml
14 |
15 | version: 2
16 |
--------------------------------------------------------------------------------
/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 |
--------------------------------------------------------------------------------
/MANIFEST.in:
--------------------------------------------------------------------------------
1 | recursive-include lib50/locale *
2 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # lib50
2 |
--------------------------------------------------------------------------------
/docs/Makefile:
--------------------------------------------------------------------------------
1 | # Minimal makefile for Sphinx documentation
2 | #
3 |
4 | # You can set these variables from the command line.
5 | SPHINXOPTS =
6 | SPHINXBUILD = sphinx-build
7 | SPHINXPROJ = lib50
8 | SOURCEDIR = source
9 | BUILDDIR = build
10 |
11 | # Put it first so that "make" without argument is like "make help".
12 | help:
13 | @$(SPHINXBUILD) -M help "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O)
14 |
15 | .PHONY: help Makefile
16 |
17 | # Catch-all target: route all unknown targets to Sphinx using the new
18 | # "make mode" option. $(O) is meant as a shortcut for $(SPHINXOPTS).
19 | %: Makefile
20 | @$(SPHINXBUILD) -M $@ "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O)
21 |
--------------------------------------------------------------------------------
/docs/source/api.rst:
--------------------------------------------------------------------------------
1 | .. _api:
2 |
3 | API docs
4 | ========
5 |
6 | .. _lib50:
7 |
8 | lib50
9 | *******
10 |
11 | .. automodule:: lib50
12 | :members:
13 | :imported-members:
14 |
15 | lib50.config
16 | ************
17 |
18 | .. automodule:: lib50.config
19 | :members:
20 |
21 | lib50.crypto
22 | ************
23 |
24 | .. automodule:: lib50.crypto
25 | :members:
26 |
--------------------------------------------------------------------------------
/docs/source/conf.py:
--------------------------------------------------------------------------------
1 | import os
2 | import sys
3 | import time
4 |
5 | _tool = "lib50"
6 |
7 | # Add path to module for autodoc
8 | sys.path.insert(0, os.path.abspath(f'../../{_tool}'))
9 |
10 | # Include __init__ in autodoc
11 | # Source: https://stackoverflow.com/questions/5599254/how-to-use-sphinxs-autodoc-to-document-a-classs-init-self-method
12 | def skip(app, what, name, obj, would_skip, options):
13 | if name == "__init__":
14 | return False
15 | return would_skip
16 |
17 | def setup(app):
18 | app.connect("autodoc-skip-member", skip)
19 |
20 | extensions = ['sphinx.ext.autodoc']
21 |
22 | html_css_files = ["https://cs50.readthedocs.io/_static/custom.css?" + str(round(time.time()))]
23 | html_js_files = ["https://cs50.readthedocs.io/_static/custom.js?" + str(round(time.time()))]
24 | html_theme = "sphinx_rtd_theme"
25 | html_theme_options = {
26 | "display_version": False,
27 | "prev_next_buttons_location": False,
28 | "sticky_navigation": False
29 | }
30 | html_title = f'{_tool} Docs'
31 |
32 | project = f'{_tool}'
33 |
--------------------------------------------------------------------------------
/docs/source/index.rst:
--------------------------------------------------------------------------------
1 | ``lib50``
2 | ===========
3 |
4 | .. toctree::
5 | :hidden:
6 | :maxdepth: 3
7 | :caption: Contents:
8 |
9 | api
10 |
11 | .. Indices and tables
12 | .. ==================
13 |
14 | .. * :ref:`genindex`
15 | .. * :ref:`api`
16 | .. * :ref:`modindex`
17 | .. * :ref:`search`
18 |
19 |
20 | lib50 is CS50's library for common functionality shared between its tools. The library is, like most of CS50's projects, open-source, but its intention is to serve as an internal library for CS50's own tools. As such it is our current recommendation to not use lib50 as a dependency of one's own projects.
21 |
22 | The following concepts live primarily in lib50:
23 |
24 | * CS50 slugs
25 | * git
26 | * GitHub
27 | * ``.cs50.yml`` config files
28 | * signing and verification of payloads
29 |
30 |
31 | Design
32 | ******
33 |
34 | To promote reuse of functionality across CS50 tools, lib50 is designed to be tool agnostic. lib50 provides just the core functionality, but the semantics of that functionality are left up to the tool. For instance, submit50 adds the notion of a submission to a push, whereas it is the ``lib50.push`` function that ultimately handles the workflow with git and GitHub. Or per another example, lib50 provides the functionality to parse and validate ``.cs50.yml`` configuration files, but each individual tool (check50, submit50 and lab50) specifies their own options and handles their own logic.
35 |
36 | With the overarching design goal to make it easy to add to or to change implementation choices, lib50 abstracts away from implementation details for other CS50 tools. Concepts such as slugs, git, GitHub, and ``.cs50.yml`` live only in lib50. Tools such as check50 interact only with lib50's API at a higher level of abstraction, such as ``lib50.push`` and ``lib50.config.Loader``. The idea being, that there is now a single point of change. For instance, one could add support for another host, such as GitLab perhaps, to ``lib50.push`` and all of CS50's tools could instantly make use of the new host.
37 |
38 |
39 | Installation
40 | ************
41 |
42 | First make sure you have Python 3.6 or higher installed. You can download Python |download_python|.
43 |
44 | .. |download_python| raw:: html
45 |
46 | here
47 |
48 | lib50 has a dependency on git, please make sure to |install_git| if git is not already installed.
49 |
50 | .. |install_git| raw:: html
51 |
52 | install git
53 |
54 | To install lib50 under Linux / OS X:
55 |
56 | .. code-block:: bash
57 |
58 | pip install lib50
59 |
60 | Under Windows, please |install_windows_sub|. Then install lib50 within the subsystem.
61 |
62 | .. |install_windows_sub| raw:: html
63 |
64 | install the Linux subsystem
65 |
--------------------------------------------------------------------------------
/lib50/__init__.py:
--------------------------------------------------------------------------------
1 | import pathlib as _pathlib
2 | import gettext as _gettext
3 | from importlib.resources import files
4 |
5 | # Internationalization
6 | _ = _gettext.translation("lib50", str(files("lib50").joinpath("locale")), fallback=True).gettext
7 |
8 | _LOCAL_PATH = _pathlib.Path("~/.local/share/lib50").expanduser().absolute()
9 |
10 |
11 | def get_local_path():
12 | return _LOCAL_PATH
13 |
14 |
15 | def set_local_path(path):
16 | global _LOCAL_PATH
17 | _LOCAL_PATH = _pathlib.Path(path).expanduser().absolute()
18 |
19 |
20 | from ._api import *
21 | from ._errors import *
22 | from . import config, crypto
23 |
--------------------------------------------------------------------------------
/lib50/_api.py:
--------------------------------------------------------------------------------
1 | import contextlib
2 | import fnmatch
3 | import glob
4 | import logging
5 | import os
6 | from pathlib import Path
7 | from packaging import version
8 | import re
9 | import shutil
10 | import shlex
11 | import subprocess
12 | import sys
13 | import tempfile
14 | import threading
15 | import time
16 | import functools
17 |
18 | import jellyfish
19 | import pexpect
20 | import requests
21 | import termcolor
22 |
23 | from . import _, get_local_path
24 | from ._errors import *
25 | from .authentication import authenticate, logout, run_authenticated
26 | from . import config as lib50_config
27 |
28 | __all__ = ["push", "local", "working_area", "files", "connect",
29 | "prepare", "authenticate", "upload", "logout", "ProgressBar",
30 | "fetch_config", "get_local_slugs", "check_github_status", "Slug", "cd"]
31 |
32 | logger = logging.getLogger(__name__)
33 | logger.addHandler(logging.NullHandler())
34 |
35 | DEFAULT_PUSH_ORG = "me50"
36 | AUTH_URL = "https://submit.cs50.io"
37 |
38 |
39 | DEFAULT_FILE_LIMIT = 10000
40 |
41 |
42 | def push(tool, slug, config_loader, repo=None, data=None, prompt=lambda question, included, excluded: True, file_limit=DEFAULT_FILE_LIMIT):
43 | """
44 | Pushes to Github in name of a tool.
45 | What should be pushed is configured by the tool and its configuration in the .cs50.yml file identified by the slug.
46 | By default, this function pushes to https://github.com/org=me50/repo=/branch=.
47 |
48 | ``lib50.push`` executes the workflow: ``lib50.connect``, ``lib50.authenticate``, ``lib50.prepare`` and ``lib50.upload``.
49 |
50 | :param tool: name of the tool that initialized the push
51 | :type tool: str
52 | :param slug: the slug identifying a .cs50.yml config file in a GitHub repo. This slug is also the branch in the student's repo to which this will push.
53 | :type slug: str
54 | :param config_loader: a config loader for the tool that is able to parse the .cs50.yml config file for the tool.
55 | :type config_loader: lib50.config.Loader
56 | :param repo: an alternative repo to push to, otherwise the default is used: github.com/me50/
57 | :type repo: str, optional
58 | :param data: key value pairs that end up in the commit message. This can be used to communicate data with a backend.
59 | :type data: dict of strings, optional
60 | :param prompt: a prompt shown just before the push. In case this prompt returns false, the push is aborted. This lambda function has access to an honesty prompt configured in .cs50,yml, and all files that will be included and excluded in the push.
61 | :type prompt: lambda str, list, list => bool, optional
62 | :param file_limit: maximum number of files to be matched by any globbing pattern.
63 | :type file_limit: int
64 | :return: GitHub username and the commit hash
65 | :type: tuple(str, str)
66 |
67 | Example usage::
68 |
69 | from lib50 import push
70 | import submit50
71 |
72 | name, hash = push("submit50", "cs50/problems/2019/x/hello", submit50.CONFIG_LOADER)
73 | print(name)
74 | print(hash)
75 |
76 | """
77 | if data is None:
78 | data = {}
79 |
80 | language = os.environ.get("LANGUAGE")
81 | if language:
82 | data.setdefault("lang", language)
83 |
84 | slug = Slug.normalize_case(slug)
85 |
86 | check_dependencies()
87 |
88 | # Connect to GitHub and parse the config files
89 | remote, (honesty, included, excluded) = connect(slug, config_loader, file_limit=DEFAULT_FILE_LIMIT)
90 |
91 | # Authenticate the user with GitHub, and prepare the submission
92 | with authenticate(remote["org"], repo=repo) as user, prepare(tool, slug, user, included):
93 |
94 | # Show any prompt if specified
95 | if prompt(honesty, included, excluded):
96 | username, commit_hash = upload(slug, user, tool, data)
97 | format_dict = {"username": username, "slug": slug, "commit_hash": commit_hash}
98 | message = remote["message"].format(results=remote["results"].format(**format_dict), **format_dict)
99 | return username, commit_hash, message
100 | else:
101 | raise RejectedHonestyPromptError(_("No files were submitted."))
102 |
103 |
104 | def local(slug, offline=False, remove_origin=False, github_token=None):
105 | """
106 | Create/update local copy of the GitHub repo indentified by slug.
107 | The local copy is shallow and single branch, it contains just the last commit on the branch identified by the slug.
108 |
109 | :param slug: the slug identifying a GitHub repo.
110 | :type slug: str
111 | :param offline: a flag that indicates whether the user is offline. If so, then the local copy is only checked, but not updated.
112 | :type offline: bool, optional
113 | :param remove_origin: a flag, that when set to True, will remove origin as a remote of the git repo.
114 | :type remove_origin: bool, optional
115 | :param github_token: a GitHub authentication token used to verify the slug, only needed if the slug identifies a private repo.
116 | :type github_token: str, optional
117 | :return: path to local copy
118 | :type: pathlib.Path
119 |
120 | Example usage::
121 |
122 | from lib50 import local
123 |
124 | path = local("cs50/problems/2019/x/hello")
125 | print(list(path.glob("**/*")))
126 |
127 | """
128 |
129 | # Parse slug
130 | slug = Slug(slug, offline=offline, github_token=github_token)
131 |
132 | local_path = get_local_path() / slug.org / slug.repo
133 |
134 | git = Git().set("-C {path}", path=str(local_path))
135 | if not local_path.exists():
136 | run(Git()("init {path}", path=str(local_path)))
137 | run(git(f"remote add origin {slug.origin}"))
138 |
139 | if not offline:
140 | # Get latest version of checks
141 | run(git("fetch origin --depth 1 {branch}", branch=slug.branch))
142 |
143 | # Tolerate checkout failure (e.g., when origin doesn't exist)
144 | try:
145 | run(git("checkout -f -B {branch} origin/{branch}", branch=slug.branch))
146 | except Error:
147 | pass
148 |
149 | # Ensure that local copy of the repo is identical to remote copy
150 | run(git("reset --hard HEAD"))
151 |
152 | if remove_origin:
153 | run(git(f"remote remove origin"))
154 |
155 | problem_path = (local_path / slug.problem).absolute()
156 |
157 | if not problem_path.exists():
158 | raise InvalidSlugError(_("{} does not exist at {}/{}").format(slug.problem, slug.org, slug.repo))
159 |
160 | return problem_path
161 |
162 |
163 | @contextlib.contextmanager
164 | def working_area(files, name=""):
165 | """
166 | A contextmanager that copies all files to a temporary directory (the working area)
167 |
168 | :param files: all files to copy to the temporary directory
169 | :type files: list of string(s) or pathlib.Path(s)
170 | :param name: name of the temporary directory
171 | :type name: str, optional
172 | :return: path to the working area
173 | :type: pathlib.Path
174 |
175 | Example usage::
176 |
177 | from lib50 import working_area
178 |
179 | with working_area(["foo.c", "bar.py"], name="baz") as area:
180 | print(list(area.glob("**/*")))
181 |
182 | """
183 | with tempfile.TemporaryDirectory() as dir:
184 | dir = Path(Path(dir) / name)
185 | dir.mkdir(exist_ok=True)
186 |
187 | for f in files:
188 | dest = (dir / f).absolute()
189 | dest.parent.mkdir(parents=True, exist_ok=True)
190 | shutil.copy(f, dest)
191 | yield dir
192 |
193 |
194 | @contextlib.contextmanager
195 | def cd(dest):
196 | """
197 | A contextmanager for temporarily changing directory.
198 |
199 | :param dest: the path to the directory
200 | :type dest: str or pathlib.Path
201 | :return: dest unchanged
202 | :type: str or pathlib.Path
203 |
204 | Example usage::
205 |
206 | from lib50 import cd
207 | import os
208 |
209 | with cd("foo") as current_dir:
210 | print(os.getcwd())
211 |
212 | """
213 | origin = os.getcwd()
214 | try:
215 | os.chdir(dest)
216 | yield dest
217 | finally:
218 | os.chdir(origin)
219 |
220 |
221 | def files(patterns,
222 | require_tags=("require",),
223 | include_tags=("include",),
224 | exclude_tags=("exclude",),
225 | root=".",
226 | limit=DEFAULT_FILE_LIMIT):
227 | """
228 | Based on a list of patterns (``lib50.config.TaggedValue``) determine which files should be included and excluded.
229 | Any pattern tagged with a tag:
230 |
231 | * from ``include_tags`` will be included
232 | * from ``require_tags`` can only be a file, that will then be included. ``MissingFilesError`` is raised if missing.
233 | * from ``exclude_tags`` will be excluded
234 |
235 | :param patterns: patterns that are processed in order, to determine which files should be included and excluded.
236 | :type patterns: list of lib50.config.TaggedValue
237 | :param require_tags: tags that mark a file as required and through that included
238 | :type require_tags: list of strings, optional
239 | :param include_tags: tags that mark a pattern as included
240 | :type include_tags: list of strings, optional
241 | :param exclude_tags: tags that mark a pattern as excluded
242 | :type exclude_tags: list of strings, optional
243 | :param root: the root directory from which to look for files. Defaults to the current directory.
244 | :type root: str or pathlib.Path, optional
245 | :param limit: Maximum number of files that can be globbed.
246 | :type limit: int
247 | :return: all included files and all excluded files
248 | :type: tuple(set of strings, set of strings)
249 |
250 | Example usage::
251 |
252 | from lib50 import files
253 | from lib50.config import TaggedValue
254 |
255 | open("foo.py", "w").close()
256 | open("bar.c", "w").close()
257 | open("baz.h", "w").close()
258 |
259 | patterns = [TaggedValue("*", "exclude"),
260 | TaggedValue("*.c", "include"),
261 | TaggedValue("baz.h", "require")]
262 |
263 | print(files(patterns)) # prints ({'bar.c', 'baz.h'}, {'foo.py'})
264 |
265 | """
266 | require_tags = list(require_tags)
267 | include_tags = list(include_tags)
268 | exclude_tags = list(exclude_tags)
269 |
270 | # Ensure tags do not start with !
271 | for tags in [require_tags, include_tags, exclude_tags]:
272 | for i, tag in enumerate(tags):
273 | tags[i] = tag[1:] if tag.startswith("!") else tag
274 |
275 | with cd(root):
276 | # Include everything but hidden paths by default
277 | included = _glob("*", limit=limit)
278 | excluded = set()
279 |
280 | if patterns:
281 | missing_files = []
282 |
283 | # For each pattern
284 | for pattern in patterns:
285 | if not _is_relative_to(Path(pattern.value).expanduser().resolve(), Path.cwd()):
286 | raise Error(_("Cannot include/exclude paths outside the current directory, but such a path ({}) was specified.")
287 | .format(pattern.value))
288 |
289 | # Include all files that are tagged with !require
290 | if pattern.tag in require_tags:
291 | file = str(Path(pattern.value))
292 | if not Path(file).exists():
293 | missing_files.append(file)
294 | else:
295 | try:
296 | excluded.remove(file)
297 | except KeyError:
298 | pass
299 | else:
300 | included.add(file)
301 | # Include all files that are tagged with !include
302 | elif pattern.tag in include_tags:
303 | new_included = _glob(pattern.value, limit=limit)
304 | excluded -= new_included
305 | included.update(new_included)
306 | # Exclude all files that are tagged with !exclude
307 | elif pattern.tag in exclude_tags:
308 | new_excluded = _glob(pattern.value, limit=limit)
309 | included -= new_excluded
310 | excluded.update(new_excluded)
311 |
312 | if missing_files:
313 | raise MissingFilesError(missing_files)
314 |
315 | # Exclude any files that are not valid utf8
316 | invalid = set()
317 | for file in included:
318 | try:
319 | file.encode("utf8")
320 | except UnicodeEncodeError:
321 | excluded.add(file.encode("utf8", "replace").decode())
322 | invalid.add(file)
323 | included -= invalid
324 |
325 | return included, excluded
326 |
327 |
328 | def connect(slug, config_loader, file_limit=DEFAULT_FILE_LIMIT):
329 | """
330 | Connects to a GitHub repo indentified by slug.
331 | Then parses the ``.cs50.yml`` config file with the ``config_loader``.
332 | If not all required files are present, per the ``files`` tag in ``.cs50.yml``, an ``Error`` is raised.
333 |
334 | :param slug: the slug identifying a GitHub repo.
335 | :type slug: str
336 | :param config_loader: a config loader that is able to parse the .cs50.yml config file for a tool.
337 | :type config_loader: lib50.config.Loader
338 | :param file_limit: The maximum number of files that are allowed to be included.
339 | :type file_limit: int
340 | :return: the remote configuration (org, message, callback, results), and the input for a prompt (honesty question, included files, excluded files)
341 | :type: tuple(dict, tuple(str, set, set))
342 | :raises lib50.InvalidSlugError: if the slug is invalid for the tool
343 | :raises lib50.Error: if no files are staged. For instance the slug expects .c files, but there are only .py files present.
344 |
345 | Example usage::
346 |
347 | from lib50 import connect
348 | import submit50
349 |
350 | open("hello.c", "w").close()
351 |
352 | remote, (honesty, included, excluded) = connect("cs50/problems/2019/x/hello", submit50.CONFIG_LOADER)
353 |
354 | """
355 | with ProgressBar(_("Connecting")):
356 | # Get the config from GitHub at slug
357 | config_yaml = fetch_config(slug)
358 |
359 | # Load config file
360 | try:
361 | config = config_loader.load(config_yaml)
362 | except MissingToolError:
363 | raise InvalidSlugError(_("Invalid slug for {}. Did you mean something else?").format(config_loader.tool))
364 |
365 | # If config of tool is just a truthy value, config should be empty
366 | if not isinstance(config, dict):
367 | config = {}
368 |
369 | # By default send check50/style50 results back to submit.cs50.io
370 | remote = {
371 | "org": DEFAULT_PUSH_ORG,
372 | "message": _("Go to {results} to see your results."),
373 | "callback": "https://submit.cs50.io/hooks/results",
374 | "results": "https://submit.cs50.io/users/{username}/{slug}"
375 | }
376 |
377 | remote.update(config.get("remote", {}))
378 | honesty = config.get("honesty", True)
379 |
380 | # Figure out which files to include and exclude
381 | included, excluded = files(config.get("files"), limit=file_limit)
382 |
383 | # Check that at least 1 file is staged
384 | if not included:
385 | raise Error(_("No files in this directory are expected by {}.".format(slug)))
386 |
387 | return remote, (honesty, included, excluded)
388 |
389 |
390 | @contextlib.contextmanager
391 | def prepare(tool, branch, user, included):
392 | """
393 | A contextmanager that prepares git for pushing:
394 |
395 | * Check that there are no permission errors
396 | * Add necessities to git config
397 | * Stage files
398 | * Stage files via lfs if necessary
399 | * Check that atleast one file is staged
400 |
401 | :param tool: name of the tool that started the push
402 | :type tool: str
403 | :param branch: git branch to switch to
404 | :type branch: str
405 | :param user: the user who has access to the repo, and will ultimately author a commit
406 | :type user: lib50.User
407 | :param included: a list of files that are to be staged in git
408 | :type included: list of string(s) or pathlib.Path(s)
409 | :return: None
410 | :type: None
411 |
412 | Example usage::
413 |
414 | from lib50 import authenticate, prepare, upload
415 |
416 | with authenticate("me50") as user:
417 | tool = "submit50"
418 | branch = "cs50/problems/2019/x/hello"
419 | with prepare(tool, branch, user, ["hello.c"]):
420 | upload(branch, user, tool, {})
421 |
422 | """
423 | with working_area(included) as area:
424 | with ProgressBar(_("Verifying")):
425 | Git.working_area = f"-C {shlex.quote(str(area))}"
426 | git = Git().set(Git.working_area)
427 |
428 | # Clone just .git folder
429 | try:
430 | clone_command = f"clone --bare --single-branch {user.repo} .git"
431 | try:
432 | run_authenticated(user, git.set(Git.cache)(f"{clone_command} --branch {branch}"))
433 | except Error:
434 | run_authenticated(user, git.set(Git.cache)(clone_command))
435 | except Error:
436 | msg = _("Make sure your username and/or personal access token are valid and {} is enabled for your account. To enable {}, ").format(tool, tool)
437 | if user.org != DEFAULT_PUSH_ORG:
438 | msg += _("please contact your instructor.")
439 | else:
440 | msg += _("please go to {} in your web browser and try again.").format(AUTH_URL)
441 |
442 | if not os.environ.get("CODESPACES"):
443 | msg += _((" For instructions on how to set up a personal access token, please visit https://cs50.readthedocs.io/github"))
444 |
445 | raise Error(msg)
446 |
447 | with ProgressBar(_("Preparing")) as progress_bar:
448 | run(git("config --bool core.bare false"))
449 | run(git("config --path core.worktree {area}", area=str(area)))
450 |
451 | try:
452 | run(git("checkout --force {branch} .gitattributes", branch=branch))
453 | except Error:
454 | pass
455 |
456 | # Set user name/email in repo config
457 | run(git("config user.email {email}", email=user.email))
458 | run(git("config user.name {name}", name=user.name))
459 |
460 | # Switch to branch without checkout
461 | run(git("symbolic-ref HEAD {ref}", ref=f"refs/heads/{branch}"))
462 |
463 | # Git add all included files
464 | run(git(f"add -f {' '.join(shlex.quote(f) for f in included)}"))
465 |
466 | # Remove gitattributes from included
467 | if Path(".gitattributes").exists() and ".gitattributes" in included:
468 | included.remove(".gitattributes")
469 |
470 | # Add any oversized files through git-lfs
471 | _lfs_add(included, git)
472 |
473 | progress_bar.stop()
474 | yield
475 |
476 |
477 | def upload(branch, user, tool, data):
478 | """
479 | Commit + push to a branch
480 |
481 | :param branch: git branch to commit and push to
482 | :type branch: str
483 | :param user: authenticated user who can push to the repo and branch
484 | :type user: lib50.User
485 | :param tool: name of the tool that started the push
486 | :type tool: str
487 | :param data: key value pairs that end up in the commit message. This can be used to communicate data with a backend.
488 | :type data: dict of strings
489 | :return: username and commit hash
490 | :type: tuple(str, str)
491 |
492 | Example usage::
493 |
494 | from lib50 import authenticate, prepare, upload
495 |
496 | with authenticate("me50") as user:
497 | tool = "submit50"
498 | branch = "cs50/problems/2019/x/hello"
499 | with prepare(tool, branch, user, ["hello.c"]):
500 | upload(branch, user, tool, {tool:True})
501 |
502 | """
503 | with ProgressBar(_("Uploading")):
504 | commit_message = _("automated commit by {}").format(tool)
505 |
506 | data_str = " ".join(f"[{key}={val}]" for key, val in data.items())
507 |
508 | commit_message = f"{commit_message} {data_str}"
509 |
510 | # Commit + push
511 | git = Git().set(Git.working_area)
512 | run(git("commit -m {msg} --allow-empty", msg=commit_message))
513 | run_authenticated(user, git.set(Git.cache)("push origin {branch}", branch=branch))
514 | commit_hash = run(git("rev-parse HEAD"))
515 | return user.name, commit_hash
516 |
517 |
518 | def fetch_config(slug):
519 | """
520 | Fetch the config file at slug from GitHub.
521 |
522 | :param slug: a slug identifying a location on GitHub to fetch the config from.
523 | :type slug: str
524 | :return: the config in the form of unparsed json
525 | :type: str
526 | :raises lib50.InvalidSlugError: if there is no config file at slug.
527 |
528 | Example usage::
529 |
530 | from lib50 import fetch_config
531 |
532 | config = fetch_config("cs50/problems/2019/x/hello")
533 | print(config)
534 |
535 | """
536 | # Parse slug
537 | slug = Slug(slug)
538 |
539 | # Get config file (.cs50.yaml)
540 | try:
541 | yaml_content = get_content(slug.org, slug.repo, slug.branch, slug.problem / ".cs50.yaml")
542 | except InvalidSlugError:
543 | yaml_content = None
544 |
545 | # Get config file (.cs50.yml)
546 | try:
547 | yml_content = get_content(slug.org, slug.repo, slug.branch, slug.problem / ".cs50.yml")
548 | except InvalidSlugError:
549 | yml_content = None
550 |
551 | # If neither exists, error
552 | if not yml_content and not yaml_content:
553 | # Check if GitHub outage may be the source of the issue
554 | check_github_status()
555 |
556 | # Otherwise raise an InvalidSlugError
557 | raise InvalidSlugError(_("Invalid slug: {}. Did you mean something else?").format(slug))
558 |
559 | # If both exists, error
560 | if yml_content and yaml_content:
561 | raise InvalidSlugError(_("Invalid slug: {}. Multiple configurations (both .yaml and .yml) found.").format(slug))
562 |
563 | return yml_content or yaml_content
564 |
565 |
566 | def get_local_slugs(tool, similar_to=""):
567 | """
568 | Get all slugs for tool of which lib50 has a local copy.
569 | If similar_to is given, ranks and sorts local slugs by similarity to similar_to.
570 |
571 | :param tool: tool for which to get the local slugs
572 | :type tool: str
573 | :param similar_to: ranks and sorts local slugs by similarity to this slug
574 | :type similar_to: str, optional
575 | :return: list of slugs
576 | :type: list of strings
577 |
578 | Example usage::
579 |
580 | from lib50 import get_local_slugs
581 |
582 | slugs = get_local_slugs("check50", similar_to="cs50/problems/2019/x/hllo")
583 | print(slugs)
584 |
585 | """
586 | # Extract org and repo from slug to limit search
587 | similar_to = similar_to.strip("/")
588 | parts = Path(similar_to).parts
589 | entered_org = parts[0] if len(parts) >= 1 else ""
590 | entered_repo = parts[1] if len(parts) >= 2 else ""
591 |
592 | # Find path of local repo's
593 | local_path = get_local_path()
594 | local_repo = local_path / entered_org / entered_repo
595 |
596 | if not local_repo.exists():
597 | local_repo = local_path
598 |
599 | # Find all local config files within local_path
600 | config_paths = []
601 | for root, dirs, files in os.walk(local_repo):
602 | try:
603 | config_paths.append(lib50_config.get_config_filepath(root))
604 | except Error:
605 | pass
606 |
607 | # Filter out all local config files that do not contain tool
608 | config_loader = lib50_config.Loader(tool)
609 | valid_paths = []
610 | for config_path in config_paths:
611 | with open(config_path) as f:
612 | if config_loader.load(f.read(), validate=False):
613 | valid_paths.append(config_path.relative_to(local_path))
614 |
615 | # Find branch for every repo
616 | branch_map = {}
617 | for path in valid_paths:
618 | org, repo = path.parts[0:2]
619 | if (org, repo) not in branch_map:
620 | git = Git().set("-C {path}", path=str(local_path / path.parent))
621 | branch = run(git("rev-parse --abbrev-ref HEAD"))
622 | branch_map[(org, repo)] = branch
623 |
624 | # Reconstruct slugs for each config file
625 | slugs = []
626 | for path in valid_paths:
627 | org, repo = path.parts[0:2]
628 | branch = branch_map[(org, repo)]
629 | problem = "/".join(path.parts[2:-1])
630 | slugs.append("/".join((org, repo, branch, problem)))
631 |
632 | return _rank_similar_slugs(similar_to, slugs) if similar_to else slugs
633 |
634 |
635 | def _rank_similar_slugs(target_slug, other_slugs):
636 | """
637 | Rank other_slugs by their similarity to target_slug.
638 | Returns a list of other_slugs in order (most similar -> least similar).
639 | """
640 | if len(Path(target_slug).parts) >= 2:
641 | other_slugs_filtered = [slug for slug in other_slugs if Path(slug).parts[0:2] == Path(target_slug).parts[0:2]]
642 | if other_slugs_filtered:
643 | other_slugs = other_slugs_filtered
644 |
645 | scores = {}
646 | for other_slug in other_slugs:
647 | scores[other_slug] = jellyfish.jaro_winkler(target_slug, other_slug)
648 |
649 | return sorted(scores, key=lambda k: scores[k], reverse=True)
650 |
651 |
652 | def check_dependencies():
653 | """
654 | Check that dependencies are installed:
655 | - require git 2.7+, so that credential-cache--daemon ignores SIGHUP
656 | https://github.com/git/git/blob/v2.7.0/credential-cache--daemon.c
657 | """
658 |
659 | # Check that git is installed
660 | if not shutil.which("git"):
661 | raise Error(_("You don't have git. Install git, then re-run!"))
662 |
663 | # Check that git --version > 2.7
664 | _version = subprocess.check_output(["git", "--version"]).decode("utf-8")
665 | matches = re.search(r"^git version (\d+\.\d+\.\d+).*$", _version)
666 | if not matches or version.parse(matches.group(1)) < version.parse("2.7.0"):
667 | raise Error(_("You have an old version of git. Install version 2.7 or later, then re-run!"))
668 |
669 |
670 | class Git:
671 | """
672 | A stateful helper class for formatting git commands.
673 |
674 | To avoid confusion, and because these are not directly relevant to users,
675 | the class variables ``cache`` and ``working_area`` are excluded from logs.
676 |
677 | Example usage::
678 |
679 | command = Git().set("-C {folder}", folder="foo")("git clone {repo}", repo="foo")
680 | print(command)
681 | """
682 | cache = ""
683 | working_area = ""
684 |
685 | def __init__(self):
686 | self._args = []
687 |
688 | def set(self, git_arg, **format_args):
689 | """git = Git().set("-C {folder}", folder="foo")"""
690 | format_args = {name: shlex.quote(arg) for name, arg in format_args.items()}
691 | git = Git()
692 | git._args = self._args[:]
693 | git._args.append(git_arg.format(**format_args))
694 | return git
695 |
696 | def __call__(self, command, **format_args):
697 | """Git()("git clone {repo}", repo="foo")"""
698 | git = self.set(command, **format_args)
699 |
700 | git_command = f"git {' '.join(git._args)}"
701 |
702 | # Format to show in git info
703 | logged_command = f"git {' '.join(arg for arg in git._args if arg not in [str(git.cache), str(Git.working_area)])}"
704 |
705 | # Log pretty command in info
706 | logger.info(termcolor.colored(logged_command, attrs=["bold"]))
707 |
708 | return git_command
709 |
710 |
711 | class Slug:
712 | """
713 | A CS50 slug that uniquely identifies a location on GitHub.
714 |
715 | A slug is formatted as follows: ///
716 | Both the branch and the problem can have an arbitrary number of slashes.
717 | ``lib50.Slug`` performs validation on the slug, by querrying GitHub,
718 | pulling in all branches, and then by finding a branch and problem that matches the slug.
719 |
720 | :ivar str org: the GitHub organization
721 | :ivar str repo: the GitHub repo
722 | :ivar str branch: the branch in the repo
723 | :ivar str problem: path to the problem, the directory containing ``.cs50.yml``
724 | :ivar str slug: string representation of the slug
725 | :ivar bool offline: flag signalling whether the user is offline. If set to True, the slug is parsed locally.
726 | :ivar str origin: GitHub url for org/repo including authentication.
727 |
728 | Example usage::
729 |
730 | from lib50._api import Slug
731 |
732 | slug = Slug("cs50/problems/2019/x/hello")
733 | print(slug.org)
734 | print(slug.repo)
735 | print(slug.branch)
736 | print(slug.problem)
737 |
738 | """
739 |
740 | def __init__(self, slug, offline=False, github_token=None):
741 | """Parse /// from slug."""
742 | self.slug = self.normalize_case(slug)
743 | self.offline = offline
744 |
745 | # Assert begin/end of slug are correct
746 | self._check_endings()
747 |
748 | # Find third "/" in identifier
749 | idx = self.slug.find("/", self.slug.find("/") + 1)
750 | if idx == -1:
751 | raise InvalidSlugError(_("Invalid slug"))
752 |
753 | # Split slug in //
754 | remainder = self.slug[idx + 1:]
755 | self.org, self.repo = self.slug.split("/")[:2]
756 |
757 | credentials = f"{github_token}:x-oauth-basic@" if github_token else ""
758 | self.origin = f"https://{credentials}github.com/{self.org}/{self.repo}"
759 |
760 | # Gather all branches
761 | try:
762 | branches = self._get_branches()
763 | except TimeoutError:
764 | if not offline:
765 | raise ConnectionError("Could not connect to GitHub, it seems you are offline.")
766 | branches = []
767 | except ConnectionError:
768 | raise
769 | except Error:
770 | branches = []
771 |
772 | # Find a matching branch
773 | for branch in branches:
774 | if remainder.startswith(f"{branch}"):
775 | self.branch = branch
776 | self.problem = Path(remainder[len(branch) + 1:])
777 | break
778 | else:
779 | raise InvalidSlugError(_("Invalid slug: {}").format(self.slug))
780 |
781 | def _check_endings(self):
782 | """Check begin/end of slug, raises Error if malformed."""
783 | if self.slug.startswith("/") and self.slug.endswith("/"):
784 | raise InvalidSlugError(
785 | _("Invalid slug. Did you mean {}, without the leading and trailing slashes?").format(self.slug.strip("/")))
786 | elif self.slug.startswith("/"):
787 | raise InvalidSlugError(
788 | _("Invalid slug. Did you mean {}, without the leading slash?").format(self.slug.strip("/")))
789 | elif self.slug.endswith("/"):
790 | raise InvalidSlugError(
791 | _("Invalid slug. Did you mean {}, without the trailing slash?").format(self.slug.strip("/")))
792 |
793 | def _get_branches(self):
794 | """Get branches from org/repo."""
795 | if self.offline:
796 | local_path = get_local_path() / self.org / self.repo
797 | output = run(f"git -C {shlex.quote(str(local_path))} show-ref --heads").split("\n")
798 | else:
799 | cmd = f"git ls-remote --heads {self.origin}"
800 | try:
801 | with spawn(cmd, timeout=3) as child:
802 | output = child.read().strip().split("\r\n")
803 | except pexpect.TIMEOUT:
804 | if "Username for" in child.buffer:
805 | return []
806 | else:
807 | raise TimeoutError(3)
808 | except Error:
809 | if "Could not resolve host" in child.before + child.buffer:
810 | raise ConnectionError
811 | raise
812 |
813 | # Parse get_refs output for the actual branch names
814 | return (line.split()[1].replace("refs/heads/", "") for line in output)
815 |
816 | @staticmethod
817 | def normalize_case(slug):
818 | """Normalize the case of a slug in string form"""
819 | parts = slug.split("/")
820 | if len(parts) < 3:
821 | raise InvalidSlugError(_("Invalid slug"))
822 | parts[0] = parts[0].lower()
823 | parts[1] = parts[1].lower()
824 | return "/".join(parts)
825 |
826 | def __str__(self):
827 | return self.slug
828 |
829 |
830 | class ProgressBar:
831 | """
832 | A contextmanager that shows a progress bar starting with message.
833 |
834 | Example usage::
835 |
836 | from lib50 import ProgressBar
837 | import time
838 |
839 | with ProgressBar("uploading") as bar:
840 | time.sleep(5)
841 | bar.stop()
842 | time.sleep(5)
843 |
844 | """
845 | DISABLED = False
846 | TICKS_PER_SECOND = 2
847 |
848 | def __init__(self, message, output_stream=None):
849 | """
850 | :param message: the message of the progress bar, what the user is waiting on
851 | :type message: str
852 | :param output_stream: a stream to write the progress bar to
853 | :type output_stream: a stream or file-like object
854 | """
855 |
856 | if output_stream is None:
857 | output_stream = sys.stderr
858 |
859 | self._message = message
860 | self._progressing = False
861 | self._thread = None
862 | self._print = functools.partial(print, file=output_stream)
863 |
864 | def stop(self):
865 | """Stop the progress bar."""
866 | if self._progressing:
867 | self._progressing = False
868 | self._thread.join()
869 |
870 | def __enter__(self):
871 | def progress_runner():
872 | self._print(f"{self._message}...", end="", flush=True)
873 | while self._progressing:
874 | self._print(".", end="", flush=True)
875 | time.sleep(1 / ProgressBar.TICKS_PER_SECOND if ProgressBar.TICKS_PER_SECOND else 0)
876 | self._print()
877 |
878 | if not ProgressBar.DISABLED:
879 | self._progressing = True
880 | self._thread = threading.Thread(target=progress_runner)
881 | self._thread.start()
882 | else:
883 | self._print(f"{self._message}...")
884 |
885 | return self
886 |
887 | def __exit__(self, exc_type, exc_val, exc_tb):
888 | self.stop()
889 |
890 |
891 | class _StreamToLogger:
892 | """Send all that enters the stream to log-function."""
893 |
894 | def __init__(self, log):
895 | self._log = log
896 |
897 | def write(self, message):
898 | message = message.strip()
899 | if message:
900 | self._log(message)
901 |
902 | def flush(self):
903 | pass
904 |
905 |
906 | @contextlib.contextmanager
907 | def spawn(command, quiet=False, timeout=None):
908 | """Run (spawn) a command with `pexpect.spawn`"""
909 | # Spawn command
910 | child = pexpect.spawn(
911 | command,
912 | encoding="utf-8",
913 | env=dict(os.environ),
914 | timeout=timeout)
915 |
916 | try:
917 | if not quiet:
918 | # Log command output to logger
919 | child.logfile_read = _StreamToLogger(logger.debug)
920 | yield child
921 | except BaseException:
922 | child.close()
923 | raise
924 | else:
925 | if child.isalive():
926 | try:
927 | child.expect(pexpect.EOF, timeout=timeout)
928 | except pexpect.TIMEOUT:
929 | raise Error()
930 | child.close(force=True)
931 | if child.signalstatus is None and child.exitstatus != 0:
932 | logger.debug("{} exited with {}".format(command, child.exitstatus))
933 | raise Error()
934 |
935 |
936 | def run(command, quiet=False, timeout=None):
937 | """Run a command, returns command output."""
938 | try:
939 | with spawn(command, quiet, timeout) as child:
940 | command_output = child.read().strip().replace("\r\n", "\n")
941 | except pexpect.TIMEOUT:
942 | logger.info(f"command {command} timed out")
943 | raise TimeoutError(timeout)
944 |
945 | return command_output
946 |
947 |
948 | def _glob(pattern, skip_dirs=False, limit=DEFAULT_FILE_LIMIT):
949 | """
950 | Glob pattern, expand directories, return iterator over matching files.
951 | Throws ``lib50.TooManyFilesError`` if more than ``limit`` files are globbed.
952 | """
953 | # Implicit recursive iff no / in pattern and starts with *
954 | files = glob.iglob(f"**/{pattern}" if "/" not in pattern and pattern.startswith("*")
955 | else pattern, recursive=True)
956 |
957 | all_files = set()
958 |
959 | def add_file(f):
960 | fname = str(Path(f))
961 | all_files.add(fname)
962 | if len(all_files) > limit:
963 | raise TooManyFilesError(limit)
964 |
965 | # Expand dirs
966 | for file in files:
967 | if os.path.isdir(file) and not skip_dirs:
968 | for f in _glob(f"{file}/**/*", skip_dirs=True):
969 | if not os.path.isdir(f):
970 | add_file(f)
971 | else:
972 | add_file(file)
973 |
974 | return all_files
975 |
976 |
977 | def _match_files(universe, pattern):
978 | """From a universe of files, get just those files that match the pattern."""
979 | # Implicit recursive iff no / in pattern and starts with *
980 | if "/" not in pattern and pattern.startswith("*"):
981 | pattern = f"**/{pattern}"
982 | pattern = re.compile(fnmatch.translate(pattern))
983 | return set(file for file in universe if pattern.match(file))
984 |
985 |
986 | def get_content(org, repo, branch, filepath):
987 | """Get all content from org/repo/branch/filepath at GitHub."""
988 | url = "https://github.com/{}/{}/raw/{}/{}".format(org, repo, branch, filepath)
989 | try:
990 | r = requests.get(url)
991 | if not r.ok:
992 | if r.status_code == 404:
993 | raise InvalidSlugError(_("Invalid slug. Did you mean to submit something else?"))
994 | else:
995 | # Check if GitHub outage may be the source of the issue
996 | check_github_status()
997 |
998 | # Otherwise raise a ConnectionError
999 | raise ConnectionError(_("Could not connect to GitHub. Do make sure you are connected to the internet."))
1000 |
1001 | except requests.exceptions.SSLError as e:
1002 | raise ConnectionError(_(f"Could not connect to GitHub due to a SSL error.\nPlease check GitHub's status at githubstatus.com.\nError: {e}"))
1003 |
1004 | return r.content
1005 |
1006 |
1007 | def check_github_status():
1008 | """
1009 | Pings the githubstatus API. Raises a ConnectionError if the Git Operations and/or
1010 | API requests components show an increase in errors.
1011 |
1012 | :return: None
1013 | :type: None
1014 | :raises lib50.ConnectionError: if the Git Operations and/or API requests components show an increase in errors.
1015 | """
1016 | # https://www.githubstatus.com/api
1017 | status_result = requests.get("https://kctbh9vrtdwd.statuspage.io/api/v2/components.json")
1018 |
1019 | # If status check failed
1020 | if not status_result.ok:
1021 | raise ConnectionError(_("Could not connect to GitHub. Do make sure you are connected to the internet."))
1022 |
1023 | # Get the components lib50 uses
1024 | components = status_result.json()["components"]
1025 | relevant_components = [c for c in components if c["name"] in ("Git Operations", "API Requests")]
1026 |
1027 | # If there is an indication of errors on GitHub's side
1028 | for component in components:
1029 | if component["status"] != "operational":
1030 | raise ConnectionError(
1031 | _("Could not connect to GitHub. "
1032 | "It looks like GitHub is having some issues with {}. "
1033 | "Do check on https://www.githubstatus.com and try again later.").format(component['name']))
1034 |
1035 |
1036 | def _lfs_add(files, git):
1037 | """
1038 | Add any oversized files with lfs.
1039 | Throws error if a file is bigger than 2GB or git-lfs is not installed.
1040 | """
1041 | # Check for large files > 100 MB (and huge files > 2 GB)
1042 | # https://help.github.com/articles/conditions-for-large-files/
1043 | # https://help.github.com/articles/about-git-large-file-storage/
1044 | larges, huges = [], []
1045 | for file in files:
1046 | size = os.path.getsize(file)
1047 | if size > (100 * 1024 * 1024):
1048 | larges.append(file)
1049 | elif size > (2 * 1024 * 1024 * 1024):
1050 | huges.append(file)
1051 |
1052 | # Raise Error if a file is >2GB
1053 | if huges:
1054 | raise Error(_("These files are too large to be submitted:\n{}\n"
1055 | "Remove these files from your directory "
1056 | "and then re-run!").format("\n".join(huges)))
1057 |
1058 | # Add large files (>100MB) with git-lfs
1059 | if larges:
1060 | # Raise Error if git-lfs not installed
1061 | if not shutil.which("git-lfs"):
1062 | raise Error(_("These files are too large to be submitted:\n{}\n"
1063 | "Install git-lfs (or remove these files from your directory) "
1064 | "and then re-run!").format("\n".join(larges)))
1065 |
1066 | # Install git-lfs for this repo
1067 | run(git("lfs install --local"))
1068 |
1069 | # For pre-push hook
1070 | run(git("config credential.helper cache"))
1071 |
1072 | # Rm previously added file, have lfs track file, add file again
1073 | for large in larges:
1074 | run(git("rm --cached {large}", large=large))
1075 | run(git("lfs track {large}", large=large))
1076 | run(git("add {large}", large=large))
1077 | run(git("add --force .gitattributes"))
1078 |
1079 |
1080 | def _is_relative_to(path, *others):
1081 | """The is_relative_to method for Paths is Python 3.9+ so we implement it here."""
1082 | try:
1083 | path.relative_to(*others)
1084 | return True
1085 | except ValueError:
1086 | return False
1087 |
1088 |
--------------------------------------------------------------------------------
/lib50/_errors.py:
--------------------------------------------------------------------------------
1 | import os
2 | from . import _
3 |
4 | __all__ = [
5 | "Error",
6 | "InvalidSlugError",
7 | "MissingFilesError",
8 | "TooManyFilesError",
9 | "InvalidConfigError",
10 | "MissingToolError",
11 | "TimeoutError",
12 | "ConnectionError",
13 | "RejectedHonestyPromptError"
14 | ]
15 |
16 |
17 | class Error(Exception):
18 | """
19 | A generic lib50 Error.
20 |
21 | :ivar dict payload: arbitrary data
22 |
23 | """
24 |
25 | def __init__(self, *args, **kwargs):
26 | """"""
27 | super().__init__(*args, **kwargs)
28 | self.payload = {}
29 |
30 |
31 | class InvalidSlugError(Error):
32 | """A ``lib50.Error`` signalling that a slug is invalid."""
33 | pass
34 |
35 |
36 | class MissingFilesError(Error):
37 | """
38 | A ``lib50.Error`` signaling that files are missing.
39 | This error's payload has a ``files`` and ``dir`` key.
40 | ``MissingFilesError.payload["files"]`` are all the missing files in a list of strings.
41 | ``MissingFilesError.payload["dir"]`` is the current working directory (cwd) from when this error was raised.
42 | """
43 |
44 | def __init__(self, files, dir=None):
45 | """
46 | :param files: the missing files that caused the error
47 | :type files: list of string(s) or Pathlib.path(s)
48 | """
49 | if dir is None:
50 | dir = os.path.expanduser(os.getcwd())
51 |
52 | super().__init__("{}\n{}\n{}".format(
53 | _("You seem to be missing these required files:"),
54 | "\n".join(files),
55 | _("You are currently in: {}, did you perhaps intend another directory?".format(dir))
56 | ))
57 | self.payload.update(files=files, dir=dir)
58 |
59 |
60 | class TooManyFilesError(Error):
61 | """
62 | A ``lib50.Error`` signaling that too many files were attempted to be included.
63 | The error's payload has a ``dir`` and a ``limit`` key.
64 | ``TooManyFilesError.payload["dir"]`` is the directory in which the attempted submission occured.
65 | ``TooManyFilesError.payload["limit"]`` is the max number of files allowed
66 | """
67 |
68 | def __init__(self, limit, dir=None):
69 |
70 | if dir is None:
71 | dir = os.path.expanduser(os.getcwd())
72 |
73 | super().__init__("{}\n{}".format(
74 | _("Looks like you are in a directory with too many (> {}) files.").format(limit),
75 | _("You are currently in: {}, did you perhaps intend another directory?".format(dir))
76 | ))
77 | self.payload.update(limit=limit, dir=dir)
78 |
79 |
80 | class InvalidConfigError(Error):
81 | """A ``lib50.Error`` signalling that a config is invalid."""
82 | pass
83 |
84 |
85 | class MissingToolError(InvalidConfigError):
86 | """A more specific ``lib50.InvalidConfigError`` signalling that an entry for a tool is missing in the config."""
87 | pass
88 |
89 |
90 | class TimeoutError(Error):
91 | """A ``lib50.Error`` signalling a timeout has occured."""
92 | pass
93 |
94 |
95 | class ConnectionError(Error):
96 | """A ``lib50.Error`` signalling a connection has errored."""
97 | pass
98 |
99 |
100 | class InvalidSignatureError(Error):
101 | """A ``lib50.Error`` signalling the signature of a payload is invalid."""
102 | pass
103 |
104 |
105 | class RejectedHonestyPromptError(Error):
106 | """A ``lib50.Error`` signalling the honesty prompt was rejected by the user."""
107 | pass
--------------------------------------------------------------------------------
/lib50/authentication.py:
--------------------------------------------------------------------------------
1 | import attr
2 | import contextlib
3 | import enum
4 | import os
5 | import pexpect
6 | import sys
7 | import termcolor
8 | import termios
9 | import tty
10 |
11 | from pathlib import Path
12 |
13 | from . import _
14 | from . import _api as api
15 | from ._errors import ConnectionError, RejectedHonestyPromptError
16 |
17 | __all__ = ["User", "authenticate", "logout"]
18 |
19 | _CREDENTIAL_SOCKET = Path("~/.git-credential-cache/lib50").expanduser()
20 |
21 |
22 | @attr.s(slots=True)
23 | class User:
24 | """An authenticated GitHub user that has write access to org/repo."""
25 | name = attr.ib()
26 | repo = attr.ib()
27 | org = attr.ib()
28 | passphrase = attr.ib(default=str)
29 | email = attr.ib(default=attr.Factory(lambda self: f"{self.name}@users.noreply.github.com",
30 | takes_self=True),
31 | init=False)
32 |
33 | @contextlib.contextmanager
34 | def authenticate(org, repo=None):
35 | """
36 | A contextmanager that authenticates a user with GitHub via SSH if possible, otherwise via HTTPS.
37 |
38 | :param org: GitHub organisation to authenticate with
39 | :type org: str
40 | :param repo: GitHub repo (part of the org) to authenticate with. Default is the user's GitHub login.
41 | :type repo: str, optional
42 | :return: an authenticated user
43 | :type: lib50.User
44 |
45 | Example usage::
46 |
47 | from lib50 import authenticate
48 |
49 | with authenticate("me50") as user:
50 | print(user.name)
51 |
52 | """
53 | with api.ProgressBar(_("Authenticating")) as progress_bar:
54 | # Both authentication methods can require user input, best stop the bar
55 | progress_bar.stop()
56 |
57 | # Try auth through SSH
58 | user = _authenticate_ssh(org, repo=repo)
59 |
60 | # SSH auth failed, fallback to HTTPS
61 | if user is None:
62 | with _authenticate_https(org, repo=repo) as user:
63 | yield user
64 | # yield SSH user
65 | else:
66 | yield user
67 |
68 |
69 | def logout():
70 | """
71 | Log out from git.
72 |
73 | :return: None
74 | :type: None
75 | """
76 | api.run(f"git credential-cache --socket {_CREDENTIAL_SOCKET} exit")
77 |
78 |
79 | def run_authenticated(user, command, quiet=False, timeout=None):
80 | """Run a command as a authenticated user. Returns command output."""
81 | try:
82 | with api.spawn(command, quiet, timeout) as child:
83 | match = child.expect([
84 | "Enter passphrase for key",
85 | "Password for",
86 | pexpect.EOF
87 | ])
88 |
89 | # In case "Enter passphrase for key" appears, send user's passphrase
90 | if match == 0:
91 | child.sendline(user.passphrase)
92 | pass
93 | # In case "Password for" appears, https authentication failed
94 | elif match == 1:
95 | raise ConnectionError
96 |
97 | command_output = child.read().strip().replace("\r\n", "\n")
98 |
99 | except pexpect.TIMEOUT:
100 | api.logger.info(f"command {command} timed out")
101 | raise TimeoutError(timeout)
102 |
103 | return command_output
104 |
105 |
106 | def _authenticate_ssh(org, repo=None):
107 | """Try authenticating via ssh, if succesful yields a User, otherwise raises Error."""
108 |
109 | class State(enum.Enum):
110 | FAIL = 0
111 | SUCCESS = 1
112 | PASSPHRASE_PROMPT = 2
113 | NEW_KEY = 3
114 |
115 | # Require ssh-agent
116 | child = pexpect.spawn("ssh -p443 -T git@ssh.github.com", encoding="utf8")
117 |
118 | # GitHub prints 'Hi {username}!...' when attempting to get shell access
119 | try:
120 | state = State(child.expect([
121 | "Permission denied",
122 | "Hi (.+)! You've successfully authenticated",
123 | "Enter passphrase for key",
124 | "Are you sure you want to continue connecting"
125 | ]))
126 | except (pexpect.EOF, pexpect.TIMEOUT):
127 | return None
128 |
129 | passphrase = ""
130 |
131 | try:
132 | # New SSH connection
133 | if state == State.NEW_KEY:
134 | # yes to Continue connecting
135 | child.sendline("yes")
136 |
137 | state = State(child.expect([
138 | "Permission denied",
139 | "Hi (.+)! You've successfully authenticated",
140 | "Enter passphrase for key"
141 | ]))
142 |
143 | # while passphrase is needed, prompt and enter
144 | while state == State.PASSPHRASE_PROMPT:
145 |
146 | # Prompt passphrase
147 | passphrase = _prompt_password("Enter passphrase for SSH key: ")
148 |
149 | # Enter passphrase
150 | child.sendline(passphrase)
151 |
152 | state = State(child.expect([
153 | "Permission denied",
154 | "Hi (.+)! You've successfully authenticated",
155 | "Enter passphrase for key"
156 | ]))
157 |
158 | # In case of a re-prompt, warn the user
159 | if state == State.PASSPHRASE_PROMPT:
160 | print("Looks like that passphrase is incorrect, please try again.")
161 |
162 | # In case of failed auth and no re-prompt, warn user and fall back on https
163 | if state == State.FAIL:
164 | print("Looks like that passphrase is incorrect, trying authentication with"\
165 | " username and Personal Access Token instead.")
166 |
167 | # Succesfull authentication, done
168 | if state == State.SUCCESS:
169 | username = child.match.groups()[0]
170 | # Failed authentication, nothing to be done
171 | else:
172 | if not os.environ.get("CODESPACES"):
173 | _show_gh_changes_warning()
174 |
175 | return None
176 | finally:
177 | child.close()
178 |
179 | return User(name=username,
180 | repo=f"ssh://git@ssh.github.com:443/{org}/{username if repo is None else repo}",
181 | org=org,
182 | passphrase=passphrase)
183 |
184 |
185 | @contextlib.contextmanager
186 | def _authenticate_https(org, repo=None):
187 | """Try authenticating via HTTPS, if succesful yields User, otherwise raises Error."""
188 | _CREDENTIAL_SOCKET.parent.mkdir(mode=0o700, exist_ok=True)
189 | api.Git.cache = f"-c credential.helper= -c credential.helper='cache --socket {_CREDENTIAL_SOCKET}'"
190 | git = api.Git().set(api.Git.cache)
191 |
192 | # Get username/PAT from environment variables if possible
193 | username = os.environ.get("CS50_GH_USER")
194 | password = os.environ.get("CS50_TOKEN")
195 |
196 | # If in codespaces, check for missing environment variables and prompt user to re-login
197 | if os.environ.get("CODESPACES"):
198 | missing_env_vars = False
199 | for env_var in ("CS50_GH_USER", "CS50_TOKEN"):
200 | if os.environ.get(env_var) is None:
201 | missing_env_vars = True
202 | error = f"Missing environment variable {env_var}"
203 | print(termcolor.colored(error, color="red", attrs=["bold"]))
204 | if missing_env_vars:
205 | prompt = "Please visit https://cs50.dev/restart to restart your codespace."
206 | print(termcolor.colored(prompt, color="yellow", attrs=["bold"]))
207 | logout()
208 | sys.exit(1)
209 |
210 | # Otherwise, get credentials from cache if possible
211 | if username is None or password is None:
212 | try:
213 | with api.spawn(git("credential fill"), quiet=True) as child:
214 | child.sendline("protocol=https")
215 | child.sendline("host=github.com")
216 | child.sendline("")
217 | i = child.expect([
218 | "Username for '.+'",
219 | "Password for '.+'",
220 | "username=([^\r]+)\r\npassword=([^\r]+)\r\n"
221 | ])
222 | if i == 2:
223 | cached_username, cached_password = child.match.groups()
224 |
225 | # if cached credentials differ from existing env variables, don't use cache
226 | same_username = username is None or username == cached_username
227 | same_password = password is None or password == cached_password
228 | if same_username and same_password:
229 | username, password = cached_username, cached_password
230 | else:
231 | child.close()
232 | child.exitstatus = 0
233 | except pexpect.exceptions.EOF as e:
234 | pass
235 |
236 | # Prompt for username if not in env vars or cache
237 | if username is None:
238 | if not os.environ.get("CODESPACES"):
239 | _show_gh_changes_warning()
240 |
241 | username = _prompt_username(_("Enter username for GitHub: "))
242 |
243 | # Prompt for PAT if not in env vars or cache
244 | if password is None:
245 | if not os.environ.get("CODESPACES"):
246 | _show_gh_changes_warning()
247 |
248 | password = _prompt_password(_("Enter personal access token for GitHub: "))
249 |
250 | try:
251 | # Credentials are correct, best cache them
252 | with api.spawn(git("-c credentialcache.ignoresighup=true credential approve"), quiet=True) as child:
253 | child.sendline("protocol=https")
254 | child.sendline("host=github.com")
255 | child.sendline(f"path={org}/{username}")
256 | child.sendline(f"username={username}")
257 | child.sendline(f"password={password}")
258 | child.sendline("")
259 |
260 | yield User(name=username,
261 | repo=f"https://{username}@github.com/{org}/{username if repo is None else repo}",
262 | org=org)
263 | except Exception as e:
264 |
265 | # Do not prompt message if user rejects the honesty prompt
266 | if not isinstance(e, RejectedHonestyPromptError):
267 | msg = _("You might be using your GitHub password to log in," \
268 | " but that's no longer possible. But you can still use" \
269 | " check50 and submit50! See https://cs50.readthedocs.io/github for instructions.")
270 | print(termcolor.colored(msg, color="yellow", attrs=["bold"]))
271 |
272 | # Some error occured while this context manager is active, best forget credentials.
273 | logout()
274 | raise
275 | except BaseException:
276 | # Some special error (like SIGINT) occured while this context manager is active, best forget credentials.
277 | logout()
278 | raise
279 |
280 |
281 | def _show_gh_changes_warning():
282 | """Only once show a warning on the no password change at GitHub."""
283 | if not hasattr(_show_gh_changes_warning, "showed"):
284 | warning = "GitHub now requires that you use SSH or a personal access token"\
285 | " instead of a password to log in, but you can still use check50 and submit50!"\
286 | " See https://cs50.readthedocs.io/github for instructions if you haven't already!"
287 | print(termcolor.colored(warning, color="yellow", attrs=["bold"]))
288 | _show_gh_changes_warning.showed = True
289 |
290 |
291 | def _prompt_username(prompt="Username: "):
292 | """Prompt the user for username."""
293 | try:
294 | while True:
295 | username = input(prompt).strip()
296 | if not username:
297 | print("Username cannot be empty, please try again.")
298 | elif "@" in username:
299 | print("Please enter your GitHub username, not email.")
300 | else:
301 | return username
302 | except EOFError:
303 | print()
304 |
305 |
306 | def _prompt_password(prompt="Password: "):
307 | """Prompt the user for password, printing asterisks for each character"""
308 | print(prompt, end="", flush=True)
309 | password_bytes = []
310 | password_string = ""
311 |
312 | with _no_echo_stdin():
313 | while True:
314 | # Read one byte
315 | ch = sys.stdin.buffer.read(1)[0]
316 | # If user presses Enter or ctrl-d
317 | if ch in (ord("\r"), ord("\n"), 4):
318 | print("\r")
319 | break
320 | # Del
321 | elif ch == 127:
322 | if len(password_string) > 0:
323 | print("\b \b", end="", flush=True)
324 | # Remove last char and its corresponding bytes
325 | password_string = password_string[:-1]
326 | password_bytes = list(password_string.encode("utf8"))
327 | # Ctrl-c
328 | elif ch == 3:
329 | print("^C", end="", flush=True)
330 | raise KeyboardInterrupt
331 | else:
332 | password_bytes.append(ch)
333 |
334 | # If byte added concludes a utf8 char, print *
335 | try:
336 | password_string = bytes(password_bytes).decode("utf8")
337 | except UnicodeDecodeError:
338 | pass
339 | else:
340 | print("*", end="", flush=True)
341 |
342 | if not password_string:
343 | print("Password cannot be empty, please try again.")
344 | return _prompt_password(prompt)
345 |
346 | return password_string
347 |
348 |
349 | @contextlib.contextmanager
350 | def _no_echo_stdin():
351 | """
352 | On Unix only, have stdin not echo input.
353 | https://stackoverflow.com/questions/510357/python-read-a-single-character-from-the-user
354 | """
355 | fd = sys.stdin.fileno()
356 | old_settings = termios.tcgetattr(fd)
357 | tty.setraw(fd)
358 | try:
359 | yield
360 | finally:
361 | termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)
362 |
--------------------------------------------------------------------------------
/lib50/config.py:
--------------------------------------------------------------------------------
1 | """An API for retrieving and parsing ``.cs50.yml`` configs."""
2 |
3 | import collections
4 | import enum
5 |
6 | import yaml
7 | import os
8 | import pathlib
9 | from ._errors import InvalidConfigError, Error, MissingToolError
10 | from . import _
11 |
12 | try:
13 | from yaml import CSafeLoader as SafeLoader
14 | except ImportError:
15 | from yaml import SafeLoader
16 |
17 |
18 | def get_config_filepath(path):
19 | """
20 | Looks for the following files in order at path:
21 |
22 | * ``.cs50.yaml``
23 | * ``.cs50.yml``
24 |
25 | If only one exists, returns path to that file (i.e. ``/.cs50.yaml`` or ``/.cs50.yml``)
26 | Raises ``lib50.Error`` otherwise.
27 |
28 | :param path: local path to a ``.cs50.yml`` config file
29 | :type path: str or pathlib.Path
30 | :return: path to the config file
31 | :type: pathlib.Path
32 | :raises lib50.Error: if zero or more than one config files exist
33 |
34 | Example usage::
35 |
36 | from lib50 import local
37 | from lib50.config import get_config_filepath
38 |
39 | path = local("cs50/problems/2019/x/hello")
40 | config_path = get_config_filepath(path)
41 | print(config_path)
42 |
43 | """
44 | path = pathlib.Path(path)
45 |
46 | yaml_path = path / ".cs50.yaml" if (path / ".cs50.yaml").exists() else None
47 | yml_path = path / ".cs50.yml" if (path / ".cs50.yml").exists() else None
48 |
49 | if yaml_path and yml_path:
50 | raise Error(_("Two config files (.cs50.yaml and .cs50.yml) found at {}").format(path))
51 |
52 | if not yaml_path and not yml_path:
53 | raise Error(_("No config file (.cs50.yaml or .cs50.yml) found at {}".format(path)))
54 |
55 | return yml_path or yaml_path
56 |
57 |
58 | class TaggedValue:
59 | """A value tagged in a ``.yml`` file"""
60 | def __init__(self, value, tag):
61 | """
62 | :param value: the tagged value
63 | :type value: str
64 | :param tag: the yaml tag, with or without the syntactically required ``!``
65 | :type tag: str
66 | """
67 | self.value = value
68 | self.tag = tag[1:] if tag.startswith("!") else tag
69 |
70 | def __repr__(self):
71 | return f"TaggedValue(value={self.value}, tag={self.tag})"
72 |
73 |
74 | class Loader:
75 | """
76 | A config loader (parser) that can parse a tools section of ``.cs50.yml`` config files.
77 |
78 | The loader can be configured to parse and validate custom yaml tags.
79 | These tags can be global, in which case they can occur anywhere in a tool's section.
80 | Or scoped to a top level key within a tool's section, in which case these tags can only occur there.
81 |
82 | Tags can also have defaults.
83 | In which case there does not need to be a value next to the tag in the config file.
84 |
85 | Example usage::
86 |
87 | from lib50 import local
88 | from lib50.config import Loader, get_config_filepath
89 |
90 | # Get a local config file
91 | path = local("cs50/problems/2019/x/hello")
92 | config_path = get_config_filepath(path)
93 |
94 | # Create a loader for the tool submit50
95 | loader = Loader("submit50")
96 |
97 | # Allow the tags include/exclude/require to exist only within the files key of submit50
98 | loader.scope("files", "include", "exclude", "require")
99 |
100 | # Load, parse and validate the config file
101 | with open(config_path) as f:
102 | config = loader.load(f.read())
103 |
104 | print(config)
105 |
106 | """
107 |
108 | class _TaggedYamlValue:
109 | """
110 | A value tagged in a .yaml file.
111 | This is effectively an extension of TaggedValue that keeps track of all possible tags.
112 | This only exists for purposes of validation within ``Loader``.
113 | """
114 | def __init__(self, value, tag, *tags):
115 | """
116 | value - the actual value
117 | tag - the yaml tag
118 | tags - all possible valid tags for this value
119 | """
120 | tag = tag if tag.startswith("!") else "!" + tag
121 |
122 | tags = list(tags)
123 | for i, t in enumerate(tags):
124 | tags[i] = t if t.startswith("!") else "!" + t
125 | setattr(self, t[1:], False)
126 | setattr(self, tag[1:], True)
127 |
128 | self.tag = tag
129 | self.tags = set(tags)
130 | self.value = value
131 |
132 | def __repr__(self):
133 | return f"_TaggedYamlValue(tag={self.tag}, tags={self.tags})"
134 |
135 |
136 | def __init__(self, tool, *global_tags, default=None):
137 | """
138 | :param tool: the tool for which to load
139 | :type tool: str
140 | :param global_tags: any tags that can be applied globally (within the tool's section)
141 | :type global_tags: str
142 | :param default: a default value for global tags
143 | :type default: anything, optional
144 | """
145 | self._global_tags = self._ensure_exclamation(global_tags)
146 | self._global_default = default if not default or default.startswith("!") else "!" + default
147 | self._scopes = collections.defaultdict(list)
148 | self.tool = tool
149 |
150 | def scope(self, key, *tags, default=None):
151 | """
152 | Only apply tags and default for top-level key of the tool's section.
153 | This effectively scopes the tags to just that top-level key.
154 |
155 | :param key: the top-level key
156 | :type key: str
157 | :param tags: any tags that can be applied within the top-level key
158 | :type tags: str
159 | :param default: a default value for these tags
160 | :type default: anything, optional
161 | :return: None
162 | :type: None
163 | """
164 | scope = self._scopes[key]
165 | tags = self._ensure_exclamation(tags)
166 | default = default if not default or default.startswith("!") else "!" + default
167 |
168 | if scope:
169 | scope[0] = scope[0] + tags
170 | scope[1] = default if default else scope[1]
171 | else:
172 | scope.append(tags)
173 | scope.append(default)
174 |
175 | def load(self, content, validate=True):
176 | """
177 | Parse yaml content.
178 |
179 | :param content: the content of a config file
180 | :type content: str
181 | :param validate: if set to ``False``, no validation will be performed. Tags can then occur anywhere.
182 | :type validate: bool
183 | :return: the parsed config
184 | :type: dict
185 | :raises lib50.InvalidConfigError: in case a tag is misplaced, or the content is not valid yaml.
186 | :raises lib50.MissingToolError: in case the tool does not occur in the content.
187 | """
188 | # Try parsing the YAML with global tags
189 | try:
190 | config = yaml.load(content, Loader=self._loader(self._global_tags))
191 | except yaml.YAMLError:
192 | raise InvalidConfigError(_("Config is not valid yaml."))
193 |
194 | # Try extracting just the tool portion
195 | try:
196 | config = config[self.tool]
197 | assert config
198 | except (TypeError, KeyError, AssertionError):
199 | raise MissingToolError("{} is not enabled by this config file.".format(self.tool))
200 |
201 | # If no scopes, just apply global default
202 | if not isinstance(config, dict):
203 | config = self._apply_default(config, self._global_default)
204 | else:
205 | # Figure out what scopes exist
206 | scoped_keys = set(key for key in self._scopes)
207 |
208 | # For every scope
209 | for key in config:
210 | # If scope has custom tags, apply
211 | if key in scoped_keys:
212 | # local tags, and local default
213 | tags, default = self._scopes[key]
214 |
215 | # Inherit global default if no local default
216 | if not default:
217 | default = self._global_default
218 |
219 | config[key] = self._apply_default(config[key], default)
220 | self._apply_scope(config[key], tags)
221 | # Otherwise just apply global default
222 | else:
223 | config[key] = self._apply_default(config[key], self._global_default)
224 |
225 | if validate:
226 | self._validate_tags(config)
227 |
228 | config = self._simplify(config)
229 |
230 | return config
231 |
232 | def _loader(self, tags):
233 | """Create a yaml Loader."""
234 | class ConfigLoader(SafeLoader):
235 | pass
236 | ConfigLoader.add_multi_constructor("", lambda loader, prefix, node: Loader._TaggedYamlValue(node.value, node.tag, *tags))
237 | return ConfigLoader
238 |
239 | def _simplify(self, config):
240 | """Replace all Loader._TaggedYamlValue with TaggedValue (a simpler datastructure)"""
241 | if isinstance(config, dict):
242 | # Recursively simplify for each item in the config
243 | for key, val in config.items():
244 | config[key] = self._simplify(val)
245 |
246 | elif isinstance(config, list):
247 | # Recursively simplify for each item in the config
248 | for i, val in enumerate(config):
249 | config[i] = self._simplify(val)
250 |
251 | elif isinstance(config, Loader._TaggedYamlValue):
252 | # Replace Loader._TaggedYamlValue with TaggedValue
253 | config = TaggedValue(config.value, config.tag)
254 |
255 | return config
256 |
257 | def _validate_tags(self, config):
258 | """Check whether every _TaggedYamlValue has a valid tag, otherwise raise InvalidConfigError"""
259 | if isinstance(config, dict):
260 | # Recursively validate each item in the config
261 | for val in config.values():
262 | self._validate_tags(val)
263 |
264 | elif isinstance(config, list):
265 | # Recursively validate each item in the config
266 | for item in config:
267 | self._validate_tags(item)
268 |
269 | elif isinstance(config, Loader._TaggedYamlValue):
270 | tagged_value = config
271 |
272 | # if tagged_value is invalid, error
273 | if tagged_value.tag not in tagged_value.tags:
274 | raise InvalidConfigError(_("{} is not a valid tag for {}".format(tagged_value.tag, self.tool)))
275 |
276 | def _apply_default(self, config, default):
277 | """
278 | Apply default value to every str in config.
279 | Also ensure every _TaggedYamlValue has default in .tags
280 | """
281 | # No default, nothing to be done here
282 | if not default:
283 | return config
284 |
285 | # If the entire config is just a string, return default _TaggedYamlValue
286 | if isinstance(config, str):
287 | return Loader._TaggedYamlValue(config, default, default, *self._global_tags)
288 |
289 | if isinstance(config, dict):
290 | # Recursively apply defaults for each item in the config
291 | for key, val in config.items():
292 | config[key] = self._apply_default(val, default)
293 |
294 | elif isinstance(config, list):
295 | # Recursively apply defaults for each item in the config
296 | for i, val in enumerate(config):
297 | config[i] = self._apply_default(val, default)
298 |
299 | elif isinstance(config, Loader._TaggedYamlValue):
300 | # Make sure each _TaggedYamlValue knows about the default tag
301 | config.tags.add(default)
302 |
303 | return config
304 |
305 | def _apply_scope(self, config, tags):
306 | """Add locally scoped tags to config"""
307 | if isinstance(config, dict):
308 | # Recursively _apply_scope for each item in the config
309 | for val in config.values():
310 | self._apply_scope(val, tags)
311 |
312 | elif isinstance(config, list):
313 | # Recursively _apply_scope for each item in the config
314 | for item in config:
315 | self._apply_scope(item, tags)
316 |
317 | elif isinstance(config, Loader._TaggedYamlValue):
318 | tagged_value = config
319 |
320 | # add all local tags
321 | tagged_value.tags |= set(tags)
322 | for tag in tags:
323 | if not hasattr(tagged_value, tag):
324 | setattr(tagged_value, tag, False)
325 |
326 | @staticmethod
327 | def _ensure_exclamation(tags):
328 | """Places an exclamation mark for each tag that does not already have one"""
329 | return [tag if tag.startswith("!") else "!" + tag for tag in tags]
330 |
--------------------------------------------------------------------------------
/lib50/crypto.py:
--------------------------------------------------------------------------------
1 | """An API for verifying signed payloads such as check50 results."""
2 |
3 | import base64
4 |
5 | from cryptography.exceptions import InvalidSignature
6 | from cryptography.hazmat.primitives import serialization, hashes
7 | from cryptography.hazmat.primitives.asymmetric import padding
8 | from cryptography.hazmat.backends import default_backend
9 |
10 | from ._errors import InvalidSignatureError
11 |
12 | def load_public_key(pem_str):
13 | """
14 | Load a public key from a PEM string.
15 |
16 | "PEM is an encapsulation format, meaning keys in it can actually be any of several different key types.
17 | However these are all self-identifying, so you don’t need to worry about this detail.
18 | PEM keys are recognizable because they all begin with
19 | ``-----BEGIN {format}-----`` and end with ``-----END {format}-----``."
20 |
21 | - source: https://cryptography.io/en/latest/hazmat/primitives/asymmetric/serialization/#pem
22 |
23 | :param pem_str: the public key to load in PEM format
24 | :type pem_str: str
25 | :return: a key from ``cryptography.hazmat``
26 | :type: One of RSAPrivateKey, DSAPrivateKey, DHPrivateKey, or EllipticCurvePrivateKey
27 | """
28 | return serialization.load_pem_public_key(pem_str, backend=default_backend())
29 |
30 |
31 | def load_private_key(pem_str, password=None):
32 | """
33 | Load a private key from a PEM string.
34 |
35 | "PEM is an encapsulation format, meaning keys in it can actually be any of several different key types.
36 | However these are all self-identifying, so you don’t need to worry about this detail.
37 | PEM keys are recognizable because they all begin with
38 | ``-----BEGIN {format}-----`` and end with ``-----END {format}-----``."
39 |
40 | - source: https://cryptography.io/en/latest/hazmat/primitives/asymmetric/serialization/#pem
41 |
42 | :param pem_str: the private key to load in PEM format
43 | :type pem_str: str
44 | :param password: a password to decode the pem_str
45 | :type password: str, optional
46 | :return: a key from ``cryptography.hazmat``
47 | :type: One of RSAPrivateKey, DSAPrivateKey, DHPrivateKey, or EllipticCurvePrivateKey
48 | """
49 | return serialization.load_pem_private_key(pem_str, password=password, backend=default_backend())
50 |
51 |
52 | def verify(payload, signature, public_key):
53 | """
54 | Verify payload using (base64 encoded) signature and verification key. public_key should be obtained from load_public_key
55 | Uses RSA-PSS with SHA-512 and maximum salt length.
56 | The corresponding openssl command to create signatures that this function can verify is:
57 |
58 | ::
59 |
60 | openssl dgst -sha512 -sigopt rsa_padding_mode:pss -sigopt rsa_pss_saltlen:-2 -sign | openssl base64 -A
61 |
62 | :param payload: the payload
63 | :type payload: str
64 | :param signature: base64 encoded signature
65 | :type signature: bytes
66 | :param public_key: a public key from ``lib50.crypto.load_public_key``
67 | :return: True iff the payload could be verified
68 | :type: bool
69 | """
70 | try:
71 | public_key.verify(signature=base64.b64decode(signature),
72 | data=payload,
73 | padding=padding.PSS(
74 | mgf=padding.MGF1(hashes.SHA512()),
75 | salt_length=padding.PSS.MAX_LENGTH),
76 | algorithm=hashes.SHA512())
77 | except InvalidSignature:
78 | return False
79 |
80 | return True
81 |
82 |
83 | def sign(payload, private_key):
84 | """
85 | Sign a payload with a private key.
86 |
87 | :param payload: the payload
88 | :type payload: str
89 | :param private_key: a private key from ``lib50.crypto.load_private_key``
90 | :return: base64 encoded signature
91 | :type: bytes
92 | """
93 | return base64.b64encode(
94 | private_key.sign(data=payload,
95 | padding=padding.PSS(
96 | mgf=padding.MGF1(hashes.SHA512()),
97 | salt_length=padding.PSS.MAX_LENGTH),
98 | algorithm=hashes.SHA512()))
99 |
--------------------------------------------------------------------------------
/lib50/locale/es/LC_MESSAGES/lib50.po:
--------------------------------------------------------------------------------
1 |
2 | msgid ""
3 | msgstr ""
4 | "Project-Id-Version: PROJECT VERSION\n"
5 | "Report-Msgid-Bugs-To: \n"
6 | "POT-Creation-Date: 2020-01-09 16:00+0000\n"
7 | "PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n"
8 | "Last-Translator: FULL NAME \n"
9 | "Language: es\n"
10 | "Language-Team: es \n"
11 | "Plural-Forms: nplurals=2; plural=(n != 1)\n"
12 | "MIME-Version: 1.0\n"
13 | "Content-Type: text/plain; charset=utf-8\n"
14 | "Content-Transfer-Encoding: 8bit\n"
15 | "Generated-By: Babel 2.8.0\n"
16 |
17 | #: lib50/_api.py:76
18 | msgid "No files were submitted."
19 | msgstr "No se ha entregado ningún archivo."
20 |
21 | #: lib50/_api.py:106
22 | msgid "{} does not exist at {}/{}"
23 | msgstr "{} no existe en {}/{}"
24 |
25 | #: lib50/_api.py:217
26 | msgid "Connecting"
27 | msgstr "Conectando"
28 |
29 | #: lib50/_api.py:225
30 | msgid "Invalid slug for {}. Did you mean something else?"
31 | msgstr "El slug no es válido para {}. ¿Quisiste entregar algo más?"
32 |
33 | #: lib50/_api.py:234
34 | msgid "Go to {results} to see your results."
35 | msgstr "Vaya a {results} para ver sus resultados."
36 |
37 | #: lib50/_api.py:246
38 | msgid "No files in this directory are expected for submission."
39 | msgstr "Ningún archivo en este directorio se espera para la entrega."
40 |
41 | #: lib50/_api.py:258
42 | msgid "Authenticating"
43 | msgstr "Autenticando"
44 |
45 | #: lib50/_api.py:280
46 | msgid "Verifying"
47 | msgstr "Verificando"
48 |
49 | #: lib50/_api.py:287
50 | msgid ""
51 | "Make sure your username and/or password are valid and {} is enabled for "
52 | "your account. To enable {}, "
53 | msgstr ""
54 | "Asegúrese de que su nombre de usuario y/o contraseña sean válidos y {} "
55 | "esté habilitado para su cuenta. Para permitir {}, "
56 |
57 | #: lib50/_api.py:289
58 | msgid "please contact your instructor."
59 | msgstr "por favor contacte a su instructor."
60 |
61 | #: lib50/_api.py:291
62 | msgid "please go to {} in your web browser and try again."
63 | msgstr "por favor vaya a {} en su navegador de web e intente nuevamente."
64 |
65 | #: lib50/_api.py:298
66 | msgid "Preparing"
67 | msgstr "Preparando"
68 |
69 | #: lib50/_api.py:334
70 | msgid "Uploading"
71 | msgstr "Subiendo"
72 |
73 | #: lib50/_api.py:335
74 | msgid "automated commit by {}"
75 | msgstr "confirmación automatizada por {}"
76 |
77 | #: lib50/_api.py:376
78 | #, fuzzy
79 | msgid "Invalid slug: {}. Did you mean something else?"
80 | msgstr "El slug no es válido: {}. ¿Quisiste entregar otra cosa?"
81 |
82 | #: lib50/_api.py:380
83 | msgid "Invalid slug: {}. Multiple configurations (both .yaml and .yml) found."
84 | msgstr ""
85 | "El slug no es válido: {}. Se encontraron múltiples configuraciones "
86 | "(tanto .yaml como .yml)."
87 |
88 | #: lib50/_api.py:465
89 | msgid "You don't have git. Install git, then re-run!"
90 | msgstr "No tienes git. ¡Instala git, y luego vuelve a ejecutar!"
91 |
92 | #: lib50/_api.py:471
93 | msgid "You have an old version of git. Install version 2.7 or later, then re-run!"
94 | msgstr ""
95 | "Tienes una versión antigua de git. ¡Instala la versión 2.7 o superior, y "
96 | "vuelve a ejecutar!"
97 |
98 | #: lib50/_api.py:534 lib50/_api.py:594
99 | msgid "Invalid slug"
100 | msgstr "El slug no es válido"
101 |
102 | #: lib50/_api.py:557
103 | msgid "Invalid slug: {}"
104 | msgstr "El slug no es válido: {}"
105 |
106 | #: lib50/_api.py:563
107 | msgid "Invalid slug. Did you mean {}, without the leading and trailing slashes?"
108 | msgstr ""
109 | "El slug no es válido. ¿Querías decir {}, sin las barras la barra diagonal"
110 | " principal y la barra diagonal final?"
111 |
112 | #: lib50/_api.py:566
113 | msgid "Invalid slug. Did you mean {}, without the leading slash?"
114 | msgstr "El slug no es válido. ¿Querías decir {}, sin la barra diagonal principal?"
115 |
116 | #: lib50/_api.py:569
117 | msgid "Invalid slug. Did you mean {}, without the trailing slash?"
118 | msgstr "El slug no es válido. ¿Querías decir {}, sin la barra diagonal al final?"
119 |
120 | #: lib50/_api.py:736
121 | msgid "Invalid slug. Did you mean to submit something else?"
122 | msgstr "El slug no es válido. ¿Quisiste entregar algo más?"
123 |
124 | #: lib50/_api.py:742 lib50/_api.py:757
125 | msgid ""
126 | "Could not connect to GitHub. Do make sure you are connected to the "
127 | "internet."
128 | msgstr "No se pudo conectar a GitHub. Asegúrate de estar conectado al internet."
129 |
130 | #: lib50/_api.py:767
131 | msgid ""
132 | "Could not connect to GitHub. It looks like GitHub is having some issues "
133 | "with {}. Do check on https://www.githubstatus.com and try again later."
134 | msgstr ""
135 | "No se pudo conectar a GitHub. Parece que GitHub está teniendo algunos problemas "
136 | "con {}. Verifique en https://www.githubstatus.com e intente nuevamente más tarde."
137 |
138 | #: lib50/_api.py:790
139 | msgid ""
140 | "These files are too large to be submitted:\n"
141 | "{}\n"
142 | "Remove these files from your directory and then re-run!"
143 | msgstr ""
144 | "Estos archivos son demasiado grandes para ser entregados:\n"
145 | "{}\n"
146 | "¡Quita estos archivos de tu directorio y luego vuelve a ejecutar!"
147 |
148 | #: lib50/_api.py:798
149 | msgid ""
150 | "These files are too large to be submitted:\n"
151 | "{}\n"
152 | "Install git-lfs (or remove these files from your directory) and then re-"
153 | "run!"
154 | msgstr ""
155 | "Estos archivos son demasiado grandes para ser entregados:\n"
156 | "{}\n"
157 | "Instala git-lfs (o quita estos archivos de tu directorio) y luego vuelve "
158 | "a ejecutar!"
159 |
160 | #: lib50/_api.py:866
161 | msgid "GitHub username: "
162 | msgstr "Nombre de usuario de GitHub: "
163 |
164 | #: lib50/_api.py:867
165 | #, fuzzy
166 | msgid "GitHub password: "
167 | msgstr "Contraseña de GitHub for {}: "
168 |
169 | #: lib50/_errors.py:18
170 | msgid "You seem to be missing these required files:"
171 | msgstr "Parece que faltan estos archivos:"
172 |
173 | #: lib50/_errors.py:20
174 | msgid "You are currently in: {}, did you perhaps intend another directory?"
175 | msgstr "Estás actualmente en: {}. ¿Tal vez quisiste otro directorio?"
176 |
177 | #: lib50/config.py:31
178 | #, fuzzy
179 | msgid "Two config files (.cs50.yaml and .cs50.yml) found at {}"
180 | msgstr "No se encontró un archivo de configuración (.cs50.yaml o .cs50.yml) en {}"
181 |
182 | #: lib50/config.py:34
183 | msgid "No config file (.cs50.yaml or .cs50.yml) found at {}"
184 | msgstr "No se encontró un archivo de configuración (.cs50.yaml o .cs50.yml) en {}"
185 |
186 | #: lib50/config.py:100
187 | msgid "Config is not valid yaml."
188 | msgstr "El archivo de configuración no es yaml válido."
189 |
190 | #: lib50/config.py:182
191 | msgid "{} is not a valid tag for {}"
192 | msgstr "{} no es una etiqueta válida para {}"
193 |
194 | #~ msgid ""
195 | #~ "Looks like {} isn't enabled for "
196 | #~ "your account yet. Go to {} and "
197 | #~ "make sure you accept any pending "
198 | #~ "invitations!"
199 | #~ msgstr ""
200 | #~ "Parece que {} todavia no esta "
201 | #~ "habilitado en tu cuenta. Visita {} "
202 | #~ "y asegúrate de aceptar las invitaciones"
203 | #~ " pendientes!"
204 |
205 | #~ msgid "Could not connect to GitHub."
206 | #~ msgstr "No se pudo conectar a GitHub."
207 |
208 | #~ msgid "Failed to connect to GitHub"
209 | #~ msgstr "No se pudo conectar a GitHub"
210 |
211 | #~ msgid ""
212 | #~ "Looks like you have two-factor "
213 | #~ "authentication enabled! Please generate a "
214 | #~ "personal access token and use it "
215 | #~ "as your password. See "
216 | #~ "https://help.github.com/articles/creating-a-personal-access-"
217 | #~ "token-for-the-command-line for "
218 | #~ "more info."
219 | #~ msgstr ""
220 | #~ "¡Parece que tienes habilitada la autenticación de dos factores! "
221 | #~ "Por favor, genere un token de acceso personal y úselo como contraseña. "
222 | #~ "Consulte https://help.github.com/articles/creating-a-personal-access-"
223 | #~ "token-for-the-command-line para obtener más información."
224 |
225 | #~ msgid "Invalid username and/or password."
226 | #~ msgstr "Nombre de usuario y/o contraseña es inválido."
227 |
228 | #~ msgid "Could not authenticate user."
229 | #~ msgstr "No se pudo autenticar usuario."
230 |
--------------------------------------------------------------------------------
/setup.cfg:
--------------------------------------------------------------------------------
1 | [compile_catalog]
2 | domain = lib50
3 | directory = lib50/locale/
4 |
5 | [extract_messages]
6 | keywords = _ gettext ngettext
7 | width = 100
8 | output_file = lib50/locale/lib50.pot
9 |
10 | [update_catalog]
11 | input_file = lib50/locale/lib50.pot
12 | domain = lib50
13 | output_dir = lib50/locale/
14 |
15 | [init_catalog]
16 | input_file = lib50/locale/lib50.pot
17 | domain = lib50
18 | output_dir = lib50/locale/
19 |
--------------------------------------------------------------------------------
/setup.py:
--------------------------------------------------------------------------------
1 | if __import__("os").name == "nt":
2 | raise RuntimeError("lib50 does not support Windows directly. Instead, you should install the Windows Subsystem for Linux (https://docs.microsoft.com/en-us/windows/wsl/install-win10) and then install lib50 within that.")
3 |
4 | from setuptools import setup
5 |
6 | setup(
7 | author="CS50",
8 | author_email="sysadmins@cs50.harvard.edu",
9 | classifiers=[
10 | "Intended Audience :: Education",
11 | "Programming Language :: Python :: 3",
12 | "Topic :: Education",
13 | "Topic :: Utilities"
14 | ],
15 | message_extractors = {
16 | 'lib50': [('**.py', 'python', None),],
17 | },
18 | license="GPLv3",
19 | description="This is lib50, CS50's own internal library used in many of its tools.",
20 | long_description="This is lib50, CS50's own internal library used in many of its tools.",
21 | install_requires=["attrs>=18.1,<21", "packaging", "pexpect>=4.6,<5", "pyyaml<7", "requests>=2.13,<3", "setuptools", "termcolor>=1.1,<2", "jellyfish>=0.7,<1", "cryptography>=2.7"],
22 | extras_require = {
23 | "develop": ["sphinx", "sphinx-autobuild", "sphinx_rtd_theme"]
24 | },
25 | keywords=["lib50"],
26 | name="lib50",
27 | python_requires=">= 3.6",
28 | packages=["lib50"],
29 | url="https://github.com/cs50/lib50",
30 | version="3.0.12",
31 | include_package_data=True
32 | )
33 |
--------------------------------------------------------------------------------
/tests/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/cs50/lib50/7894dd3b9ffbcbf96c6ddc65345f5c32faaecf40/tests/__init__.py
--------------------------------------------------------------------------------
/tests/__main__.py:
--------------------------------------------------------------------------------
1 | import logging
2 | import unittest
3 | import sys
4 | import termcolor
5 |
6 | from . import *
7 |
8 | import lib50._api as api
9 |
10 | class ColoredFormatter(logging.Formatter):
11 | COLORS = {
12 | "ERROR": "red",
13 | "WARNING": "yellow",
14 | "DEBUG": "cyan",
15 | "INFO": "magenta",
16 | }
17 |
18 | def __init__(self, fmt, use_color=True):
19 | super().__init__(fmt=fmt)
20 | self.use_color = use_color
21 |
22 | def format(self, record):
23 | msg = super().format(record)
24 | return msg if not self.use_color else termcolor.colored(msg, getattr(record, "color", self.COLORS.get(record.levelname)))
25 |
26 | api.logger.setLevel("DEBUG")
27 | handler = logging.StreamHandler(sys.stderr)
28 | handler.setFormatter(ColoredFormatter("(%(levelname)s) %(message)s", use_color=sys.stderr.isatty()))
29 | api.logger.addHandler(handler)
30 |
31 | suite = unittest.TestLoader().discover("tests", pattern="*_tests.py")
32 | result = unittest.TextTestRunner(verbosity=2).run(suite)
33 | sys.exit(bool(result.errors or result.failures))
34 |
--------------------------------------------------------------------------------
/tests/api_tests.py:
--------------------------------------------------------------------------------
1 | import unittest
2 | import os
3 | import sys
4 | import contextlib
5 | import pathlib
6 | import tempfile
7 | import io
8 | import re
9 | import logging
10 | import subprocess
11 | import time
12 | import termcolor
13 | import pexpect
14 |
15 | import lib50._api
16 | import lib50.authentication
17 |
18 | class TestGit(unittest.TestCase):
19 | def setUp(self):
20 | self.info_output = []
21 |
22 | self.old_info = lib50._api.logger.info
23 | self.old_debug = logging.debug
24 |
25 | lib50._api.logger.info = lambda msg : self.info_output.append(msg)
26 |
27 | def tearDown(self):
28 | lib50._api.logger.info = self.old_info
29 | lib50._api.logger.debug = self.old_debug
30 |
31 | def test_no_args(self):
32 | self.assertEqual(lib50._api.Git()("foo"), "git foo")
33 | self.assertEqual(self.info_output, [termcolor.colored("git foo", attrs=["bold"])])
34 |
35 | def test_arg(self):
36 | self.assertEqual(lib50._api.Git().set("bar")("foo"), "git bar foo")
37 | self.assertEqual(self.info_output, [termcolor.colored("git bar foo", attrs=["bold"])])
38 |
39 | def test_args(self):
40 | self.assertEqual(lib50._api.Git().set("baz")("foo"), "git baz foo")
41 | self.assertEqual(self.info_output, [termcolor.colored("git baz foo", attrs=["bold"])])
42 |
43 | def test_special_args_not_set(self):
44 | try:
45 | lib50._api.Git.work_tree = "bar"
46 | lib50._api.Git.git_dir = "baz"
47 | lib50._api.Git.cache = "qux"
48 |
49 | self.assertEqual(lib50._api.Git()("foo"), "git foo")
50 | self.assertEqual(self.info_output, [termcolor.colored("git foo", attrs=["bold"])])
51 | finally:
52 | lib50._api.Git.work_tree = ""
53 | lib50._api.Git.git_dir = ""
54 | lib50._api.Git.cache = ""
55 |
56 | def test_special_args(self):
57 | try:
58 | lib50._api.Git.working_area = "bar"
59 | lib50._api.Git.cache = "baz"
60 |
61 | git = lib50._api.Git().set(lib50._api.Git.working_area).set(lib50._api.Git.cache)
62 | self.assertEqual(git("foo"), "git bar baz foo")
63 | self.assertEqual(self.info_output, [termcolor.colored("git foo", attrs=["bold"])])
64 | finally:
65 | lib50._api.Git.working_area = ""
66 | lib50._api.Git.cache = ""
67 |
68 | class TestSlug(unittest.TestCase):
69 | def test_wrong_format(self):
70 | with self.assertRaises(lib50._api.InvalidSlugError):
71 | lib50._api.Slug("/cs50/lib50/tests/bar")
72 |
73 | with self.assertRaises(lib50._api.InvalidSlugError):
74 | lib50._api.Slug("cs50/lib50/tests/bar/")
75 |
76 | with self.assertRaises(lib50._api.InvalidSlugError):
77 | lib50._api.Slug("/cs50/lib50/tests/bar/")
78 |
79 | with self.assertRaises(lib50._api.InvalidSlugError):
80 | lib50._api.Slug("cs50/problems2")
81 |
82 | def test_case(self):
83 | with self.assertRaises(lib50._api.InvalidSlugError):
84 | lib50._api.Slug("cs50/lib50/TESTS/bar")
85 | self.assertEqual(lib50._api.Slug("CS50/LiB50/tests/bar").slug, "cs50/lib50/tests/bar")
86 |
87 | def test_online(self):
88 | if os.environ.get("TRAVIS") == "true":
89 | self.skipTest("Cannot test online in travis.")
90 |
91 | slug = lib50._api.Slug("cs50/lib50/tests/bar")
92 | self.assertEqual(slug.slug, "cs50/lib50/tests/bar")
93 | self.assertEqual(slug.org, "cs50")
94 | self.assertEqual(slug.repo, "lib50")
95 | self.assertEqual(slug.branch, "tests")
96 | self.assertEqual(slug.problem, pathlib.Path("bar"))
97 |
98 | def test_wrong_slug_online(self):
99 | with self.assertRaises(lib50._api.InvalidSlugError):
100 | lib50._api.Slug("cs50/does/not/exist")
101 |
102 | def test_offline(self):
103 | try:
104 | old_local_path = lib50.get_local_path()
105 | old_wd = os.getcwd()
106 | temp_dir = tempfile.TemporaryDirectory()
107 | lib50.set_local_path(temp_dir.name)
108 | path = pathlib.Path(lib50.get_local_path()) / "foo" / "bar" / "baz"
109 | os.makedirs(path)
110 |
111 | os.chdir(pathlib.Path(lib50.get_local_path()) / "foo" / "bar")
112 | subprocess.check_output(["git", "init"])
113 | subprocess.check_output(["git", "config", "user.name", '"foo"'])
114 | subprocess.check_output(["git", "config", "user.email", '"bar@baz.com"'])
115 | subprocess.check_output(["git", "checkout", "-b", "main"])
116 |
117 | os.chdir(path)
118 |
119 | with open(".cs50.yaml", "w") as f:
120 | pass
121 | subprocess.check_output(["git", "add", ".cs50.yaml"])
122 | out = subprocess.check_output(["git", "commit", "-m", "\"qux\""])
123 |
124 | slug = lib50._api.Slug("foo/bar/main/baz", offline=True)
125 | self.assertEqual(slug.slug, "foo/bar/main/baz")
126 | self.assertEqual(slug.org, "foo")
127 | self.assertEqual(slug.repo, "bar")
128 | self.assertEqual(slug.branch, "main")
129 | self.assertEqual(slug.problem, pathlib.Path("baz"))
130 | finally:
131 | lib50.set_local_path(old_local_path)
132 | temp_dir.cleanup()
133 | os.chdir(old_wd)
134 |
135 | def test_wrong_slug_offline(self):
136 | with self.assertRaises(lib50._api.InvalidSlugError):
137 | lib50._api.Slug("cs50/does/not/exist", offline=True)
138 |
139 | class TestProgressBar(unittest.TestCase):
140 | def test_progress(self):
141 | f = io.StringIO()
142 | with contextlib.redirect_stdout(f):
143 | with lib50._api.ProgressBar("foo", output_stream=sys.stdout):
144 | pass
145 | self.assertTrue("foo..." in f.getvalue())
146 |
147 | def test_progress_moving(self):
148 | f = io.StringIO()
149 | with contextlib.redirect_stdout(f):
150 | try:
151 | old_ticks_per_second = lib50._api.ProgressBar.TICKS_PER_SECOND
152 | lib50._api.ProgressBar.TICKS_PER_SECOND = 100
153 | with lib50._api.ProgressBar("foo", output_stream=sys.stdout):
154 | time.sleep(.5)
155 | finally:
156 | lib50._api.ProgressBar.TICKS_PER_SECOND = old_ticks_per_second
157 |
158 | self.assertTrue("foo...." in f.getvalue())
159 |
160 | def test_disabled(self):
161 | f = io.StringIO()
162 | with contextlib.redirect_stdout(f):
163 | try:
164 | old_disabled = lib50._api.ProgressBar.DISABLED
165 | lib50._api.ProgressBar.DISABLED = True
166 | old_ticks_per_second = lib50._api.ProgressBar.TICKS_PER_SECOND
167 | lib50._api.ProgressBar.TICKS_PER_SECOND = 100
168 | with lib50._api.ProgressBar("foo", output_stream=sys.stdout):
169 | time.sleep(.5)
170 | finally:
171 | lib50._api.ProgressBar.DISABLED = old_disabled
172 | lib50._api.ProgressBar.TICKS_PER_SECOND = old_ticks_per_second
173 |
174 | self.assertEqual("foo...\n", f.getvalue())
175 |
176 | class TestPromptPassword(unittest.TestCase):
177 | @contextlib.contextmanager
178 | def replace_stdin(self):
179 | old = sys.stdin
180 | try:
181 | with tempfile.TemporaryFile() as stdin_f:
182 | sys.stdin = stdin_f
183 | sys.stdin.buffer = sys.stdin
184 | yield sys.stdin
185 | finally:
186 | sys.stdin = old
187 |
188 | @contextlib.contextmanager
189 | def mock_no_echo_stdin(self):
190 | @contextlib.contextmanager
191 | def mock():
192 | yield
193 |
194 | old = lib50.authentication._no_echo_stdin
195 | try:
196 | lib50.authentication._no_echo_stdin = mock
197 | yield mock
198 | finally:
199 | lib50._api.authentication = old
200 |
201 | def test_ascii(self):
202 | f = io.StringIO()
203 | with self.mock_no_echo_stdin(), self.replace_stdin(), contextlib.redirect_stdout(f):
204 | sys.stdin.write(bytes("foo\n".encode("utf8")))
205 | sys.stdin.seek(0)
206 | password = lib50.authentication._prompt_password()
207 |
208 | self.assertEqual(password, "foo")
209 | self.assertEqual(f.getvalue().count("*"), 3)
210 |
211 | def test_unicode(self):
212 | f = io.StringIO()
213 | with self.mock_no_echo_stdin(), self.replace_stdin(), contextlib.redirect_stdout(f):
214 | sys.stdin.write(bytes("↔♣¾€\n".encode("utf8")))
215 | sys.stdin.seek(0)
216 | password = lib50.authentication._prompt_password()
217 |
218 | self.assertEqual(password, "↔♣¾€")
219 | self.assertEqual(f.getvalue().count("*"), 4)
220 |
221 | def test_unicode_del(self):
222 | def resolve_backspaces(str):
223 | while True:
224 | temp = re.sub('.\b', '', str, count=1)
225 | if len(str) == len(temp):
226 | return re.sub('\b+', '', temp)
227 | str = temp
228 |
229 | f = io.StringIO()
230 | with self.mock_no_echo_stdin(), self.replace_stdin(), contextlib.redirect_stdout(f):
231 | sys.stdin.write(bytes(f"↔{chr(127)}♣¾{chr(127)}€\n".encode("utf8")))
232 | sys.stdin.seek(0)
233 | password = lib50.authentication._prompt_password()
234 |
235 | self.assertEqual(password, "♣€")
236 | self.assertEqual(resolve_backspaces(f.getvalue()).count("*"), 2)
237 |
238 |
239 | class TestGetLocalSlugs(unittest.TestCase):
240 | def setUp(self):
241 | self.old_path = lib50.get_local_path()
242 | self.temp_dir = tempfile.TemporaryDirectory()
243 | lib50.set_local_path(self.temp_dir.name)
244 | path = lib50.get_local_path() / "foo" / "bar" / "baz"
245 | os.makedirs(path)
246 | with open(path / ".cs50.yml", "w") as f:
247 | f.write("foo50: true\n")
248 | pexpect.run(f"git -C {path.parent.parent} init")
249 | pexpect.run(f'git -C {path.parent.parent} config user.name "foo"')
250 | pexpect.run(f'git -C {path.parent.parent} config user.email "bar@baz.com"')
251 | pexpect.run(f"git -C {path.parent.parent} checkout -b main")
252 | pexpect.run(f"git -C {path.parent.parent} add .")
253 | pexpect.run(f"git -C {path.parent.parent} commit -m \"message\"")
254 |
255 | def tearDown(self):
256 | self.temp_dir.cleanup()
257 | lib50.set_local_path(self.old_path)
258 |
259 | def test_one_local_slug(self):
260 | slugs = list(lib50.get_local_slugs("foo50"))
261 | self.assertEqual(len(slugs), 1)
262 | self.assertEqual(slugs[0], "foo/bar/main/baz")
263 |
264 |
265 | if __name__ == '__main__':
266 | unittest.main()
267 |
--------------------------------------------------------------------------------
/tests/config_tests.py:
--------------------------------------------------------------------------------
1 | import sys
2 | import unittest
3 | import tempfile
4 | import os
5 | import pathlib
6 |
7 | import lib50._errors
8 | import lib50.config
9 |
10 | class TestLoader(unittest.TestCase):
11 | def test_no_tool(self):
12 | content = ""
13 | with self.assertRaises(lib50._errors.MissingToolError):
14 | config = lib50.config.Loader("check50").load(content)
15 |
16 | def test_falsy_tool(self):
17 | content = "check50: false"
18 | with self.assertRaises(lib50._errors.MissingToolError):
19 | config = lib50.config.Loader("check50").load(content)
20 |
21 | def test_truthy_tool(self):
22 | content = "check50: true"
23 | config = lib50.config.Loader("check50").load(content)
24 | self.assertTrue(config)
25 |
26 | def test_no_files(self):
27 | content = \
28 | "check50:\n" \
29 | " dependencies:\n" \
30 | " - foo"
31 | config = lib50.config.Loader("check50").load(content)
32 | self.assertEqual(config, {"dependencies" : ["foo"]})
33 |
34 | def test_no_validation(self):
35 | content = \
36 | "check50:\n" \
37 | " bar:\n" \
38 | " - !include foo"
39 | config = lib50.config.Loader("check50").load(content, validate=False)
40 | self.assertEqual(config["bar"][0].tag, "include")
41 | self.assertEqual(config["bar"][0].value, "foo")
42 |
43 | def test_global_tag(self):
44 | content = \
45 | "check50:\n" \
46 | " foo:\n" \
47 | " - !include baz\n" \
48 | " bar:\n" \
49 | " - !include qux"
50 | config = lib50.config.Loader("check50", "include").load(content)
51 | self.assertEqual(config["foo"][0].tag, "include")
52 | self.assertEqual(config["foo"][0].value, "baz")
53 | self.assertEqual(config["bar"][0].tag, "include")
54 | self.assertEqual(config["bar"][0].value, "qux")
55 |
56 | def test_local_tag(self):
57 | content = \
58 | "check50:\n" \
59 | " files:\n" \
60 | " - !include foo"
61 | loader = lib50.config.Loader("check50")
62 | loader.scope("files", "include")
63 | config = loader.load(content)
64 | self.assertEqual(config["files"][0].tag, "include")
65 | self.assertEqual(config["files"][0].value, "foo")
66 |
67 | content = \
68 | "check50:\n" \
69 | " bar:\n" \
70 | " - !include foo"
71 | loader = lib50.config.Loader("check50")
72 | loader.scope("files", "include", default=False)
73 | with self.assertRaises(lib50._errors.InvalidConfigError):
74 | config = loader.load(content)
75 |
76 | def test_no_default(self):
77 | content = \
78 | "check50:\n" \
79 | " files:\n" \
80 | " - !INVALID foo"
81 | loader = lib50.config.Loader("check50")
82 | loader.scope("files", "include", default=False)
83 | with self.assertRaises(lib50._errors.InvalidConfigError):
84 | config = loader.load(content)
85 |
86 | def test_local_default(self):
87 | content = \
88 | "check50:\n" \
89 | " files:\n" \
90 | " - foo"
91 | loader = lib50.config.Loader("check50")
92 | loader.scope("files", default="bar")
93 | config = loader.load(content)
94 | self.assertEqual(config["files"][0].tag, "bar")
95 | self.assertEqual(config["files"][0].value, "foo")
96 |
97 | def test_global_default(self):
98 | content = \
99 | "check50:\n" \
100 | " files:\n" \
101 | " - foo"
102 | config = lib50.config.Loader("check50", default="bar").load(content)
103 | self.assertEqual(config["files"][0].tag, "bar")
104 | self.assertEqual(config["files"][0].value, "foo")
105 |
106 | def test_multiple_defaults(self):
107 | content = \
108 | "check50:\n" \
109 | " foo:\n" \
110 | " - baz\n" \
111 | " bar:\n" \
112 | " - qux"
113 | loader = lib50.config.Loader("check50", default="include")
114 | loader.scope("bar", default="exclude")
115 | config = loader.load(content)
116 | self.assertEqual(config["foo"][0].tag, "include")
117 | self.assertEqual(config["foo"][0].value, "baz")
118 | self.assertEqual(config["bar"][0].tag, "exclude")
119 | self.assertEqual(config["bar"][0].value, "qux")
120 |
121 | def test_same_tag_default(self):
122 | content = \
123 | "check50:\n" \
124 | " foo:\n" \
125 | " - !include bar\n" \
126 | " - baz"
127 | config = lib50.config.Loader("check50", "include", default="include").load(content)
128 | self.assertEqual(config["foo"][0].tag, "include")
129 | self.assertEqual(config["foo"][0].value, "bar")
130 | self.assertEqual(config["foo"][1].tag, "include")
131 | self.assertEqual(config["foo"][1].value, "baz")
132 |
133 | def test_multiple_tools(self):
134 | content = \
135 | "check50:\n" \
136 | " files:\n" \
137 | " - !require foo\n" \
138 | "lab50:\n" \
139 | " files:\n" \
140 | " - !open bar"
141 |
142 | check50_loader = lib50.config.Loader("check50")
143 | check50_loader.scope("files", "require")
144 | config = check50_loader.load(content)
145 | self.assertEqual(config["files"][0].tag, "require")
146 | self.assertEqual(config["files"][0].value, "foo")
147 |
148 | lab50_loader = lib50.config.Loader("lab50")
149 | lab50_loader.scope("files", "open")
150 | config = lab50_loader.load(content)
151 | self.assertEqual(config["files"][0].tag, "open")
152 | self.assertEqual(config["files"][0].value, "bar")
153 |
154 |
155 | class TestGetConfigFilepath(unittest.TestCase):
156 | def setUp(self):
157 | self.working_directory = tempfile.TemporaryDirectory()
158 | self.old_cwd = os.getcwd()
159 | os.chdir(self.working_directory.name)
160 |
161 | def tearDown(self):
162 | self.working_directory.cleanup()
163 | os.chdir(self.old_cwd)
164 |
165 | def test_no_config(self):
166 | with self.assertRaises(lib50._errors.Error):
167 | lib50.config.get_config_filepath(os.getcwd())
168 |
169 | with open("foo.txt", "w"):
170 | pass
171 |
172 | with self.assertRaises(lib50._errors.Error):
173 | lib50.config.get_config_filepath(os.getcwd())
174 |
175 | def test_config_yml(self):
176 | with open(".cs50.yml", "w"):
177 | pass
178 |
179 | config_file = lib50.config.get_config_filepath(os.getcwd())
180 |
181 | self.assertEqual(config_file, pathlib.Path(os.getcwd()) / ".cs50.yml")
182 |
183 | def test_config_yaml(self):
184 | with open(".cs50.yaml", "w"):
185 | pass
186 |
187 | config_file = lib50.config.get_config_filepath(os.getcwd())
188 |
189 | self.assertEqual(config_file, pathlib.Path(os.getcwd()) / ".cs50.yaml")
190 |
191 | def test_multiple_configs(self):
192 | with open(".cs50.yaml", "w"):
193 | pass
194 |
195 | with open(".cs50.yml", "w"):
196 | pass
197 |
198 | with self.assertRaises(lib50.Error):
199 | config_file = lib50.config.get_config_filepath(os.getcwd())
200 |
201 |
202 | if __name__ == '__main__':
203 | suite = unittest.TestLoader().loadTestsFromModule(sys.modules[__name__])
204 | unittest.TextTestRunner(verbosity=2).run(suite)
205 |
--------------------------------------------------------------------------------
/tests/crypto/private.pem:
--------------------------------------------------------------------------------
1 | -----BEGIN RSA PRIVATE KEY-----
2 | MIIJKAIBAAKCAgEAoLSyHBpFDW9CA5b7Pbz4UONP4yoT/HtuevarplWeegfRDkdU
3 | pv8ElMQK3lzkwEbzqBI/zxyJg0Pqm7OfRKbf1xERPXSy+6EWraQTPSjUir4/y68c
4 | iGEI8GGmJWwVju0D9w9zfCffZygI7M3xqp6Datv1xgwFH9ChwZKaauPMISwwYOeV
5 | nfhtNG+4VqzRwLoWJROpBb4sFsba2j1/cawaPpmcZDdEYOf7wxL5jjf4KDNKzSPo
6 | DUFu5rtP7hbwUMbvNHdb0YhfShP/KfxHMYPBwH3zoUK2qC2cITC0g9NGdZffRWpA
7 | QnjC9gowY1jolzOsFDddFOvTGllh2dcDqVEu6l1QalSMxsJU8CiRwNDxAoX268xd
8 | LiBuEv1t9VvLdUbAgd7yLTGqmyFaB3mxpz7QBUhFP06/f0KP4xRGDc+EAQQAFSiy
9 | ttvaf3cgf7sFUgz7Pm6Q/hr3Su9GKbwDB3ecwvd7tubeT3Gm/qlCx8alTsL9sAn2
10 | 5zYbbcmqhmAVUiOd44Wz9MCoUXeldId7+Su9er5VAiAN/h0m3xLJp4wymcAjh5lf
11 | HScp+OV2lwhQf4ZzY2CsjVDy+9e1C6NzLLloGtvDske+d4lopgqdH7jUFAX5TZMt
12 | yY+XLQKzcVPlQhSsVpVWzkW+iTAY6ekum7DONFGpMAcMa+FbTuvChuZVapkCAwEA
13 | AQKCAgBROsSEW+rnXYM6mUgo7ql9CUjKA+zSQ/mWAbTFgKV3/Rd4Zimtt10zbNwp
14 | hT7CyZpDK+ZA46XGSb/+L46jfs3JwYC7VY9ajRQPdM2crlSwRHWumLaNYK7KAjGe
15 | 3MEQ21CTwqWW7fiIBb5tI7OxkCnRC5lxH4Y/jI8WbunKeZYmdlWFxcjkbjuUs5uz
16 | g+sJxYWH/CYFFxjl8mGQymDurhUd6zsXlK/lY5zn/2FQt42hlDuM8UdL2/UYfzlp
17 | mQKjccpa9LHeeVXg9baWHERIDNcUWxWYP0ZgP52ZUSsNLu+AZOGgDpKohq3U+1V2
18 | Aeye8KlcFpfgCUtNGDzThVD+dmCFnM7yuKPhMBEA+eMghFLCkqDdvtBJ4B8T1BJy
19 | 2qyAJp3BrXb785haQC6mLpRyqstohxfNS3MJyGubBf++oqy+NtqOJhgbaWB7zy2c
20 | si+kbC+X6qZWjgZcQB4jHR7QALkQQsRfTZ5lUvIT++mHnS2gEEahTuYFm6bHoZOu
21 | NDDU/CB9ddJ0+ugZEmSvXHexrNY5l/zGSRitewwQlbjds8DTGH7jB6dhzWUymawM
22 | VSA0JwWj6xhdl6jeCN6bIQfV8GHVHSbYrajN2helbBoPe8Hh4ZbDJtcH/PAV1VqF
23 | qDPzVJsta0PA6eyKTWhxet4vqR0EgwdenaFImymkvZcQcJ1euQKCAQEAzed5Zvcm
24 | E4IepU+17yGLjnzeTAw98rH4+ijL6B8zFgsZRlvjpdRyUl12fXl3wUAC7lxu16/7
25 | wnafYclw3aCcDu+TYclO8g1/cNWNfEaheW1chWZAGvQeJZiXBNmOYR6sS+6//ZTc
26 | XhYTl3x0KBAJn8y3N25jY4HSq46s3xXkcOAZeQmZDjNz8BWQZQui4uKyCAnXs/Sc
27 | epc2NAX0mpDrAj7hKWlT43MGK3XZ/F7O3RZScpZkoi0ijmgEksR9U9kB8048ENOU
28 | QlnOWGbraQ8mzTaWU9RvR2Q94aAksSFR+T/HowgGmjlstD9ZwNYw9tf+x1K87e3z
29 | MYkK8rZF2HiR5wKCAQEAx84W+ANCZqBcjJuvWuY9eX+FdXNCzdJzmmXr+V+a7kdj
30 | t8my6/S3pmhDC79+jfIJiND2ZnVIZnol1smMfw3QiP09qCL36Bn2ZeS4aOgXj9wu
31 | teGr9b4RhPzqV5D9UZar8mGYEo6fuAYlVtIvZne9P3SIsRdjNnWJbttiPs58PCp6
32 | 4XdYw+3XODpEG7UNzoEudUw28VbMs6i/cBJkAS0m9wD0OVHJCsguiPyIy7wztGac
33 | WqnqDeLonvA6nTunMBUfEUNqhpkRGRxa39OownF3X21ItU8RZCCsqBznv3xlIv5f
34 | E1AfjlvDrFhviPbaiqE79E5OlT9/1uxnEG88KDOPfwKCAQAwinNKXNVzH+fNnP8N
35 | AuF9k95sGy63elFx2BBKBqDqf29T8PG39F+HH1WBuxMKUebe/pd67ZfyfjiQuwaK
36 | mQRxWPVrxiOAWMJEfXO/an9Cuw9mu3Y9ZHN+9XwUvp0cNDj2JbDJPUC+RYIU4lgX
37 | 4cADFiXTQYjYupBJtXb3mJekLJCUwjh86pBYdxz1VUrvJfZGgtuBJxeEpwU2Onkx
38 | vxxICT7XnmcSZdl8gWoEXu1xnYOOU/ohaXaOD+OUHhJVpAEbtMPgS6DWC4njuU+i
39 | EtpY4peJ57jcIbuc5z3/LBXBJtIPkyLLVOJVk+G63kPozX7Yyp6TkNcWRHJ6SZIp
40 | uDLdAoIBABISqjE02kS+LKDrVCk8ukLLLh85lclYR+ynW3jrFPCItJRjQjPlptb+
41 | h1IAuEnOot4lSKRr52idk96hzHuRnFNH1NPoldQAxTDiR2v10mvI1tDM4OkRkDQf
42 | THMvQjqnDlaWTVMgY4IZzDbWPENggVXEDLk4DFlYuF22qmRT+RjYHtVWHklasiT7
43 | 4D1BW0ZamQEzK6UY3NtDYE2a3EDe/K9K/sxQgYbgJJVvglArbeHbhjkNNYacB76Y
44 | rDScuLq4rl65YmFaZxmGXxHv60vrR4jyMal0xXXxHqz2MGA5uEw6Bg+RJ8mQs1pb
45 | hXs2GP6BJxMqIiGN5Npj986cwSxBvbECggEBAJC1a1/mAB+4bOh7VYqhXi+dc9+X
46 | 32wF7svrba7O34gNQj6+emCQHnbUzejJV/BQGybZsq2QLbXTFSe+x8ubA/IMGrlI
47 | JZQGpC4kqxT1dZf5lp3aTYeLslAuTjxmOVtITQJE6qYS5O+LPkx8xajFOXURv6tq
48 | uXBqGy4rW2JB3h8sS9vk/qC+1Bd8V/I4p+NYgbAUvcZw/EGsv3G/vLn9cM1O/uQ3
49 | Ysu+eq1WGtxweVopmrjcoxF1im8cxzLYvmzqrG3pDN3ONyPCJh8YKyrzCl78lwtG
50 | ok6gFQkERxxiwOMW+X1Pis5EwdHKGhQ3S2kZ7uYEtTPLdJUZpWRIuHQby2s=
51 | -----END RSA PRIVATE KEY-----
52 |
--------------------------------------------------------------------------------
/tests/crypto/public.pem:
--------------------------------------------------------------------------------
1 | -----BEGIN PUBLIC KEY-----
2 | MIICIjANBgkqhkiG9w0BAQEFAAOCAg8AMIICCgKCAgEAoLSyHBpFDW9CA5b7Pbz4
3 | UONP4yoT/HtuevarplWeegfRDkdUpv8ElMQK3lzkwEbzqBI/zxyJg0Pqm7OfRKbf
4 | 1xERPXSy+6EWraQTPSjUir4/y68ciGEI8GGmJWwVju0D9w9zfCffZygI7M3xqp6D
5 | atv1xgwFH9ChwZKaauPMISwwYOeVnfhtNG+4VqzRwLoWJROpBb4sFsba2j1/cawa
6 | PpmcZDdEYOf7wxL5jjf4KDNKzSPoDUFu5rtP7hbwUMbvNHdb0YhfShP/KfxHMYPB
7 | wH3zoUK2qC2cITC0g9NGdZffRWpAQnjC9gowY1jolzOsFDddFOvTGllh2dcDqVEu
8 | 6l1QalSMxsJU8CiRwNDxAoX268xdLiBuEv1t9VvLdUbAgd7yLTGqmyFaB3mxpz7Q
9 | BUhFP06/f0KP4xRGDc+EAQQAFSiyttvaf3cgf7sFUgz7Pm6Q/hr3Su9GKbwDB3ec
10 | wvd7tubeT3Gm/qlCx8alTsL9sAn25zYbbcmqhmAVUiOd44Wz9MCoUXeldId7+Su9
11 | er5VAiAN/h0m3xLJp4wymcAjh5lfHScp+OV2lwhQf4ZzY2CsjVDy+9e1C6NzLLlo
12 | GtvDske+d4lopgqdH7jUFAX5TZMtyY+XLQKzcVPlQhSsVpVWzkW+iTAY6ekum7DO
13 | NFGpMAcMa+FbTuvChuZVapkCAwEAAQ==
14 | -----END PUBLIC KEY-----
15 |
--------------------------------------------------------------------------------
/tests/crypto_tests.py:
--------------------------------------------------------------------------------
1 | import pathlib
2 | import unittest
3 | import uuid
4 |
5 | import lib50.crypto
6 |
7 | KEY_DIRECTORY = pathlib.Path(__file__).absolute().parent / "crypto"
8 |
9 | class TestCrypt(unittest.TestCase):
10 | def setUp(self):
11 | with open(KEY_DIRECTORY / "public.pem", "rb") as f:
12 | self.public_key = lib50.crypto.load_public_key(f.read())
13 |
14 | with open(KEY_DIRECTORY / "private.pem", "rb") as f:
15 | self.private_key = lib50.crypto.load_private_key(f.read())
16 |
17 | def test_sign_then_verify(self):
18 | payload = uuid.uuid4().hex.encode()
19 | signature = lib50.crypto.sign(payload, self.private_key)
20 | self.assertTrue(lib50.crypto.verify(payload, signature, self.public_key))
21 |
22 | def test_invalid_verify(self):
23 | payload1 = uuid.uuid4().hex.encode()
24 | payload2 = uuid.uuid4().hex.encode()
25 |
26 | # The probability that this loop even iterates once is basically 0
27 | while payload1 == payload2:
28 | payload2 = uuid.uuid4().hex.encode()
29 |
30 | signature1 = lib50.crypto.sign(payload1, self.private_key)
31 | self.assertFalse(lib50.crypto.verify(payload2, signature1, self.public_key))
32 |
--------------------------------------------------------------------------------
/tests/lib50_tests.py:
--------------------------------------------------------------------------------
1 | import unittest
2 | import os
3 | import io
4 | import time
5 | import pathlib
6 | import contextlib
7 | import shutil
8 | import sys
9 | import tempfile
10 | import logging
11 | import termcolor
12 | import subprocess
13 | import lib50
14 | import lib50.config
15 |
16 | class TestConnect(unittest.TestCase):
17 | def setUp(self):
18 | self.loader = lib50.config.Loader("check50")
19 | self.loader.scope("files", "exclude", "include", "require")
20 |
21 | self.working_directory = tempfile.TemporaryDirectory()
22 | self._wd = os.getcwd()
23 | os.chdir(self.working_directory.name)
24 |
25 | def tearDown(self):
26 | self.working_directory.cleanup()
27 | os.chdir(self._wd)
28 |
29 | def test_connect(self):
30 | f = io.StringIO()
31 | open("hello.py", "w").close()
32 | with contextlib.redirect_stdout(f):
33 | remote, (honesty, included, excluded) = lib50.connect("cs50/lib50/tests/bar", self.loader)
34 | self.assertEqual(excluded, set())
35 |
36 | self.assertEqual(remote["org"], lib50._api.DEFAULT_PUSH_ORG)
37 |
38 | f = io.StringIO()
39 | loader = lib50.config.Loader("submit50")
40 | loader.scope("files", "exclude", "include", "require")
41 | with contextlib.redirect_stdout(f):
42 | remote, (honesty, included, excluded) = lib50.connect("cs50/lib50/tests/bar", loader)
43 | self.assertEqual(included, {"hello.py"})
44 |
45 | def test_missing_problem(self):
46 | f = io.StringIO()
47 | with contextlib.redirect_stdout(f):
48 | with self.assertRaises(lib50.InvalidSlugError):
49 | lib50.connect("cs50/lib50/tests/i_do_not_exist", self.loader)
50 |
51 | def test_no_tool_in_config(self):
52 | f = io.StringIO()
53 | loader = lib50.config.Loader("i_do_not_exist")
54 | with contextlib.redirect_stdout(f):
55 | with self.assertRaises(lib50.InvalidSlugError):
56 | lib50.connect("cs50/lib50/tests/bar", loader)
57 |
58 | def test_no_config(self):
59 | f = io.StringIO()
60 | with contextlib.redirect_stdout(f):
61 | with self.assertRaises(lib50.InvalidSlugError):
62 | lib50.connect("cs50/lib50/tests/no_config", self.loader)
63 |
64 | class TestFiles(unittest.TestCase):
65 | def setUp(self):
66 | self.loader = lib50.config.Loader("check50")
67 | self.loader.scope("files", "include", "exclude", "require")
68 |
69 | self.working_directory = tempfile.TemporaryDirectory()
70 | self._wd = os.getcwd()
71 | os.chdir(self.working_directory.name)
72 |
73 | def tearDown(self):
74 | self.working_directory.cleanup()
75 | os.chdir(self._wd)
76 |
77 | def test_exclude_only_one(self):
78 | content = \
79 | "check50:\n" \
80 | " files:\n" \
81 | " - !exclude foo.py\n"
82 |
83 | config = self.loader.load(content)
84 |
85 | open("foo.py", "w").close()
86 | open("bar.py", "w").close()
87 |
88 | included, excluded = lib50.files(config.get("files"))
89 | self.assertEqual(set(included), {"bar.py"})
90 | self.assertEqual(set(excluded), {"foo.py"})
91 |
92 | def test_exclude_all(self):
93 | content = \
94 | "check50:\n" \
95 | " files:\n" \
96 | " - !exclude \"*\"\n"
97 |
98 | config = self.loader.load(content)
99 |
100 | included, excluded = lib50.files(config.get("files"))
101 | self.assertEqual(included, set())
102 | self.assertEqual(excluded, set())
103 |
104 | open("foo.py", "w").close()
105 |
106 | included, excluded = lib50.files(config.get("files"))
107 | self.assertEqual(set(included), set())
108 | self.assertEqual(set(excluded), {"foo.py"})
109 |
110 | def test_include_only_one(self):
111 | content = \
112 | "check50:\n" \
113 | " files:\n" \
114 | " - !exclude \"*\"\n" \
115 | " - !include foo.py\n"
116 |
117 | config = self.loader.load(content)
118 |
119 | open("foo.py", "w").close()
120 | open("bar.py", "w").close()
121 |
122 | included, excluded = lib50.files(config.get("files"))
123 | self.assertEqual(set(included), {"foo.py"})
124 | self.assertEqual(set(excluded), {"bar.py"})
125 |
126 | def test_include_all(self):
127 | config = {}
128 |
129 | open("foo.py", "w").close()
130 | open("bar.c", "w").close()
131 |
132 | included, excluded = lib50.files(config.get("files"))
133 | self.assertEqual(set(included), {"foo.py", "bar.c"})
134 | self.assertEqual(set(excluded), set())
135 |
136 | content = \
137 | "check50:\n" \
138 | " files:\n" \
139 | " - !include \"*\"\n"
140 |
141 | config = self.loader.load(content)
142 |
143 | included, excluded = lib50.files(config.get("files"))
144 | self.assertEqual(set(included), {"foo.py", "bar.c"})
145 | self.assertEqual(set(excluded), set())
146 |
147 | def test_required(self):
148 | content = \
149 | "check50:\n" \
150 | " files:\n" \
151 | " - !require foo.py\n"
152 |
153 | config = self.loader.load(content)
154 |
155 | open("foo.py", "w").close()
156 |
157 | included, excluded = lib50.files(config.get("files"))
158 | self.assertEqual(set(included), {"foo.py"})
159 | self.assertEqual(set(excluded), set())
160 |
161 | open("bar.c", "w").close()
162 |
163 | included, excluded = lib50.files(config.get("files"))
164 | self.assertEqual(set(included), {"foo.py", "bar.c"})
165 | self.assertEqual(set(excluded), set())
166 |
167 | def test_required_overwrite_exclude(self):
168 | content = \
169 | "check50:\n" \
170 | " files:\n" \
171 | " - !exclude \"*\"\n" \
172 | " - !require foo.py\n"
173 |
174 | config = self.loader.load(content)
175 |
176 | open("foo.py", "w").close()
177 |
178 | included, excluded = lib50.files(config.get("files"))
179 | self.assertEqual(set(included), {"foo.py"})
180 | self.assertEqual(set(excluded), set())
181 |
182 | open("bar.c", "w").close()
183 |
184 | included, excluded = lib50.files(config.get("files"))
185 | self.assertEqual(set(included), {"foo.py"})
186 | self.assertEqual(set(excluded), {"bar.c"})
187 |
188 | def test_exclude_folder_include_file(self):
189 | content = \
190 | "check50:\n" \
191 | " files:\n" \
192 | " - !exclude foo\n" \
193 | " - !include foo/bar\n"
194 |
195 | config = self.loader.load(content)
196 |
197 | os.mkdir("foo")
198 | open("foo/bar", "w").close()
199 |
200 | included, excluded = lib50.files(config.get("files"))
201 | self.assertEqual(set(included), {"foo/bar"})
202 | self.assertEqual(set(excluded), set())
203 |
204 | def test_include_file_exclude_folder(self):
205 | content = \
206 | "check50:\n" \
207 | " files:\n" \
208 | " - !include foo/bar.py\n" \
209 | " - !exclude foo\n"
210 |
211 | config = self.loader.load(content)
212 |
213 | os.mkdir("foo")
214 | open("foo/bar.py", "w").close()
215 |
216 | included, excluded = lib50.files(config.get("files"))
217 | self.assertEqual(set(included), set())
218 | self.assertEqual(set(excluded), {"foo/bar.py"})
219 |
220 | def test_exclude_extension_include_folder(self):
221 | content = \
222 | "check50:\n" \
223 | " files:\n" \
224 | " - !exclude \"*.py\"\n" \
225 | " - !include foo\n"
226 |
227 | config = self.loader.load(content)
228 |
229 | os.mkdir("foo")
230 | open("foo/bar.py", "w").close()
231 |
232 | included, excluded = lib50.files(config.get("files"))
233 | self.assertEqual(set(included), {"foo/bar.py"})
234 | self.assertEqual(set(excluded), set())
235 |
236 | def test_exclude_extension_include_everything_from_folder(self):
237 | content = \
238 | "check50:\n" \
239 | " files:\n" \
240 | " - !exclude \"*.py\"\n" \
241 | " - !include \"foo/*\"\n"
242 |
243 | config = self.loader.load(content)
244 |
245 | os.mkdir("foo")
246 | open("foo/bar.py", "w").close()
247 |
248 | included, excluded = lib50.files(config.get("files"))
249 | self.assertEqual(set(included), {"foo/bar.py"})
250 | self.assertEqual(set(excluded), set())
251 |
252 | def test_exclude_everything_include_folder(self):
253 | content = \
254 | "check50:\n" \
255 | " files:\n" \
256 | " - !exclude \"*\"\n" \
257 | " - !include foo\n"
258 |
259 | config = self.loader.load(content)
260 |
261 | os.mkdir("foo")
262 | open("foo/bar.py", "w").close()
263 |
264 | included, excluded = lib50.files(config.get("files"))
265 | self.assertEqual(set(included), {"foo/bar.py"})
266 | self.assertEqual(set(excluded), set())
267 |
268 | def test_implicit_recursive(self):
269 | os.mkdir("foo")
270 | open("foo/bar.py", "w").close()
271 | open("qux.py", "w").close()
272 |
273 | content = \
274 | "check50:\n" \
275 | " files:\n" \
276 | " - !exclude \"*.py\"\n"
277 |
278 | config = self.loader.load(content)
279 |
280 | included, excluded = lib50.files(config.get("files"))
281 | self.assertEqual(set(included), set())
282 | self.assertEqual(set(excluded), {"qux.py", "foo/bar.py"})
283 |
284 | content = \
285 | "check50:\n" \
286 | " files:\n" \
287 | " - !exclude \"./*.py\"\n"
288 |
289 | config = self.loader.load(content)
290 |
291 | included, excluded = lib50.files(config.get("files"))
292 | self.assertEqual(set(included), {"foo/bar.py"})
293 | self.assertEqual(set(excluded), {"qux.py"})
294 |
295 | def test_implicit_recursive_with_slash(self):
296 | content = \
297 | "check50:\n" \
298 | " files:\n" \
299 | " - !exclude \"*/*.py\"\n"
300 |
301 | config = self.loader.load(content)
302 |
303 | os.mkdir("foo")
304 | os.mkdir("foo/bar")
305 | open("foo/bar/baz.py", "w").close()
306 | open("foo/qux.py", "w").close()
307 |
308 | included, excluded = lib50.files(config.get("files"))
309 | self.assertEqual(set(included), {"foo/bar/baz.py"})
310 | self.assertEqual(set(excluded), {"foo/qux.py"})
311 |
312 | def test_explicit_recursive(self):
313 | content = \
314 | "check50:\n" \
315 | " files:\n" \
316 | " - !exclude \"foo/**/*.py\"\n"
317 |
318 | config = self.loader.load(content)
319 |
320 | os.mkdir("foo")
321 | os.mkdir("foo/bar")
322 | os.mkdir("foo/bar/baz")
323 | open("foo/bar/baz/qux.py", "w").close()
324 | open("hello.py", "w").close()
325 |
326 | included, excluded = lib50.files(config.get("files"))
327 | self.assertEqual(set(included), {"hello.py"})
328 | self.assertEqual(set(excluded), {"foo/bar/baz/qux.py"})
329 |
330 | def test_requires_no_exclude(self):
331 | content = \
332 | "check50:\n" \
333 | " files:\n" \
334 | " - !require does_not_exist.py\n"
335 |
336 | config = self.loader.load(content)
337 |
338 | with self.assertRaises(lib50.MissingFilesError):
339 | lib50.files(config.get("files"))
340 |
341 | def test_invalid_utf8_filename(self):
342 | try:
343 | open(b"\xc3\x28", "w").close()
344 | except OSError:
345 | self.skipTest("can't create invalid utf8 filename")
346 | else:
347 | included, excluded = lib50.files({})
348 | self.assertEqual(included, set())
349 | self.assertEqual(excluded, {"?("})
350 |
351 | def test_from_root(self):
352 | os.mkdir("foo")
353 | os.mkdir("foo/bar")
354 | os.mkdir("foo/bar/baz")
355 | open("foo/bar/baz/qux.py", "w").close()
356 | open("foo/hello.py", "w").close()
357 |
358 | included, excluded = lib50.files([], root="foo")
359 | self.assertEqual(included, {"bar/baz/qux.py", "hello.py"})
360 | self.assertEqual(excluded, set())
361 |
362 | def test_no_tags(self):
363 | open("foo.py", "w").close()
364 | open("bar.py", "w").close()
365 | open("baz.py", "w").close()
366 |
367 | content = \
368 | "check50:\n" \
369 | " files:\n" \
370 | " - !include \"foo.py\"\n" \
371 | " - !exclude \"bar.py\"\n" \
372 | " - !require \"baz.py\"\n"
373 | config = self.loader.load(content)
374 |
375 | included, excluded = lib50.files(config.get("files"), exclude_tags=[], include_tags=[], require_tags=[])
376 |
377 | self.assertEqual(included, {"foo.py", "bar.py", "baz.py"})
378 | self.assertEqual(excluded, set())
379 |
380 | def test_custom_tags(self):
381 | open("foo.py", "w").close()
382 | open("bar.py", "w").close()
383 | open("baz.py", "w").close()
384 |
385 | content = \
386 | "foo50:\n" \
387 | " files:\n" \
388 | " - !open \"foo.py\"\n" \
389 | " - !close \"bar.py\"\n" \
390 | " - !exclude \"baz.py\"\n"
391 |
392 | loader = lib50.config.Loader("foo50")
393 | loader.scope("files", "open", "close", "exclude")
394 | config = loader.load(content)
395 |
396 | included, excluded = lib50.files(config.get("files"),
397 | exclude_tags=["exclude"],
398 | include_tags=[""],
399 | require_tags=["open", "close"])
400 |
401 | self.assertEqual(included, {"foo.py", "bar.py"})
402 | self.assertEqual(excluded, {"baz.py"})
403 |
404 | def test_non_file_require(self):
405 | open("foo.py", "w").close()
406 |
407 | content = \
408 | "check50:\n" \
409 | " files:\n" \
410 | " - !require \"*.py\"\n"
411 |
412 | config = self.loader.load(content)
413 |
414 | with self.assertRaises(lib50.MissingFilesError):
415 | included, excluded = lib50.files(config.get("files"))
416 |
417 | def test_lab50_tags(self):
418 | # Four dummy files
419 | open("foo.py", "w").close()
420 | open("bar.py", "w").close()
421 | open("baz.py", "w").close()
422 | open("qux.py", "w").close()
423 |
424 | # Dummy config file (.cs50.yml)
425 | content = \
426 | "lab50:\n" \
427 | " files:\n" \
428 | " - !open \"foo.py\"\n" \
429 | " - !include \"bar.py\"\n" \
430 | " - !exclude \"baz.py\"\n" \
431 | " - \"qux.py\"\n"
432 |
433 | # Create a config Loader for a tool called lab50
434 | loader = lib50.config.Loader("lab50")
435 |
436 | # Scope the files section of lab50 with the tags: open, include and exclude
437 | loader.scope("files", "open", "include", "exclude", default="include")
438 |
439 | # Load the config
440 | config = loader.load(content)
441 |
442 | # Figure out which files have an open tag
443 | opened_files = [tagged_value.value for tagged_value in config["files"] if tagged_value.tag == "open"]
444 |
445 | # Have lib50.files figure out which files should be included and excluded
446 | # Simultaneously ensure all open files exist
447 | included, excluded = lib50.files(config["files"], require_tags=["open"])
448 |
449 | # Make sure that files tagged with open are also included
450 | opened_files = [file for file in opened_files if file in included]
451 |
452 | # Assert
453 | self.assertEqual(included, {"foo.py", "bar.py", "qux.py"})
454 | self.assertEqual(excluded, {"baz.py"})
455 | self.assertEqual(set(opened_files), {"foo.py"})
456 |
457 |
458 | class TestLocal(unittest.TestCase):
459 | def setUp(self):
460 | self.loader = lib50.config.Loader("check50")
461 | self.loader.scope("files", "include", "exclude", "require")
462 |
463 | self.working_directory = tempfile.TemporaryDirectory()
464 | self._wd = os.getcwd()
465 | os.chdir(self.working_directory.name)
466 |
467 | def tearDown(self):
468 | self.working_directory.cleanup()
469 | os.chdir(self._wd)
470 |
471 | def test_local(self):
472 | local_dir = lib50.local("cs50/lib50/tests/bar")
473 |
474 | self.assertTrue(local_dir.is_dir())
475 | self.assertTrue((local_dir / "__init__.py").is_file())
476 | self.assertTrue((local_dir / ".cs50.yaml").is_file())
477 |
478 | local_dir = lib50.local("cs50/lib50/tests/bar")
479 |
480 | self.assertTrue(local_dir.is_dir())
481 | self.assertTrue((local_dir / "__init__.py").is_file())
482 | self.assertTrue((local_dir / ".cs50.yaml").is_file())
483 |
484 | shutil.rmtree(local_dir)
485 |
486 | local_dir = lib50.local("cs50/lib50/tests/bar")
487 |
488 | self.assertTrue(local_dir.is_dir())
489 | self.assertTrue((local_dir / "__init__.py").is_file())
490 | self.assertTrue((local_dir / ".cs50.yaml").is_file())
491 |
492 | shutil.rmtree(local_dir)
493 |
494 | class TestWorkingArea(unittest.TestCase):
495 | def setUp(self):
496 | self.working_directory = tempfile.TemporaryDirectory()
497 | self._wd = os.getcwd()
498 | os.chdir(self.working_directory.name)
499 | with open("foo.py", "w") as f:
500 | pass
501 |
502 | with open("bar.c", "w") as f:
503 | pass
504 |
505 | with open("qux.java", "w") as f:
506 | pass
507 |
508 | def tearDown(self):
509 | self.working_directory.cleanup()
510 | os.chdir(self._wd)
511 |
512 | def test_empty(self):
513 | with lib50.working_area([]) as working_area:
514 | contents = os.listdir(working_area)
515 |
516 | self.assertEqual(contents, [])
517 |
518 | def test_one_file(self):
519 | with lib50.working_area(["foo.py"]) as working_area:
520 | contents = os.listdir(working_area)
521 |
522 | self.assertEqual(contents, ["foo.py"])
523 |
524 | def test_multiple_files(self):
525 | with lib50.working_area(["foo.py", "bar.c"]) as working_area:
526 | contents = os.listdir(working_area)
527 |
528 | self.assertEqual(set(contents), {"foo.py", "bar.c"})
529 |
530 | def test_include_missing_file(self):
531 | with self.assertRaises(FileNotFoundError):
532 | with lib50.working_area(["i_do_not_exist"]) as working_area:
533 | pass
534 |
535 | if __name__ == '__main__':
536 | unittest.main()
537 |
--------------------------------------------------------------------------------