├── .gitignore ├── LICENSE ├── README.md ├── bin └── sedlex ├── docs └── format.md ├── requirements.txt ├── sedlex ├── AddArcheoLexFilenameVisitor.py ├── AddCocoricoVoteVisitor.py ├── AddCommitMessageVisitor.py ├── AddDiffVisitor.py ├── AddGitHubHistoryLinkVisitor.py ├── AddGitHubIssueVisitor.py ├── AddGitLabHistoryLinkVisitor.py ├── AddGitLabIssueVisitor.py ├── CreateGitBookVisitor.py ├── GitCommitVisitor.py ├── GitPushVisitor.py ├── InitializeGitRepositoryVisitor.py ├── __init__.py ├── diff.py └── template │ ├── __init__.py │ ├── git │ ├── .travis.yml │ └── provisioning │ │ ├── provision.yml.j2 │ │ ├── requirements.yml │ │ └── roles │ │ ├── duralex-sedlex │ │ └── tasks │ │ │ └── main.yml │ │ └── pages │ │ └── tasks │ │ └── main.yml │ ├── gitbook │ ├── README.md.j2 │ ├── SUMMARY.md.j2 │ ├── amendment.md.j2 │ ├── article.md.j2 │ ├── book.json.j2 │ ├── html.j2 │ ├── law.md.j2 │ ├── styles │ │ └── website.css.j2 │ └── text.md.j2 │ ├── github │ ├── commit_message.j2 │ ├── issue_body.j2 │ └── issue_title.j2 │ └── gitlab │ ├── commit_message.j2 │ ├── issue_description.j2 │ └── issue_title.j2 └── setup.py /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | env/ 12 | build/ 13 | develop-eggs/ 14 | dist/ 15 | downloads/ 16 | eggs/ 17 | .eggs/ 18 | lib/ 19 | lib64/ 20 | parts/ 21 | sdist/ 22 | var/ 23 | *.egg-info/ 24 | .installed.cfg 25 | *.egg 26 | 27 | # PyInstaller 28 | # Usually these files are written by a python script from a template 29 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 30 | *.manifest 31 | *.spec 32 | 33 | # Installer logs 34 | pip-log.txt 35 | pip-delete-this-directory.txt 36 | 37 | # Unit test / coverage reports 38 | htmlcov/ 39 | .tox/ 40 | .coverage 41 | .coverage.* 42 | .cache 43 | nosetests.xml 44 | coverage.xml 45 | *,cover 46 | .hypothesis/ 47 | 48 | # Translations 49 | *.mo 50 | *.pot 51 | 52 | # Django stuff: 53 | *.log 54 | local_settings.py 55 | 56 | # Flask stuff: 57 | instance/ 58 | .webassets-cache 59 | 60 | # Scrapy stuff: 61 | .scrapy 62 | 63 | # Sphinx documentation 64 | docs/_build/ 65 | 66 | # PyBuilder 67 | target/ 68 | 69 | # IPython Notebook 70 | .ipynb_checkpoints 71 | 72 | # pyenv 73 | .python-version 74 | 75 | # celery beat schedule file 76 | celerybeat-schedule 77 | 78 | # dotenv 79 | .env 80 | 81 | # virtualenv 82 | venv/ 83 | ENV/ 84 | 85 | # Spyder project settings 86 | .spyderproject 87 | 88 | # Rope project settings 89 | .ropeproject 90 | 91 | # Pip installed dependencies 92 | src 93 | 94 | data 95 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU AFFERO GENERAL PUBLIC LICENSE 2 | Version 3, 19 November 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 Affero General Public License is a free, copyleft license for 11 | software and other kinds of works, specifically designed to ensure 12 | cooperation with the community in the case of network server software. 13 | 14 | The licenses for most software and other practical works are designed 15 | to take away your freedom to share and change the works. By contrast, 16 | our General Public Licenses are intended to guarantee your freedom to 17 | share and change all versions of a program--to make sure it remains free 18 | software for all its users. 19 | 20 | When we speak of free software, we are referring to freedom, not 21 | price. Our General Public Licenses are designed to make sure that you 22 | have the freedom to distribute copies of free software (and charge for 23 | them if you wish), that you receive source code or can get it if you 24 | want it, that you can change the software or use pieces of it in new 25 | free programs, and that you know you can do these things. 26 | 27 | Developers that use our General Public Licenses protect your rights 28 | with two steps: (1) assert copyright on the software, and (2) offer 29 | you this License which gives you legal permission to copy, distribute 30 | and/or modify the software. 31 | 32 | A secondary benefit of defending all users' freedom is that 33 | improvements made in alternate versions of the program, if they 34 | receive widespread use, become available for other developers to 35 | incorporate. Many developers of free software are heartened and 36 | encouraged by the resulting cooperation. However, in the case of 37 | software used on network servers, this result may fail to come about. 38 | The GNU General Public License permits making a modified version and 39 | letting the public access it on a server without ever releasing its 40 | source code to the public. 41 | 42 | The GNU Affero General Public License is designed specifically to 43 | ensure that, in such cases, the modified source code becomes available 44 | to the community. It requires the operator of a network server to 45 | provide the source code of the modified version running there to the 46 | users of that server. Therefore, public use of a modified version, on 47 | a publicly accessible server, gives the public access to the source 48 | code of the modified version. 49 | 50 | An older license, called the Affero General Public License and 51 | published by Affero, was designed to accomplish similar goals. This is 52 | a different license, not a version of the Affero GPL, but Affero has 53 | released a new version of the Affero GPL which permits relicensing under 54 | this license. 55 | 56 | The precise terms and conditions for copying, distribution and 57 | modification follow. 58 | 59 | TERMS AND CONDITIONS 60 | 61 | 0. Definitions. 62 | 63 | "This License" refers to version 3 of the GNU Affero General Public License. 64 | 65 | "Copyright" also means copyright-like laws that apply to other kinds of 66 | works, such as semiconductor masks. 67 | 68 | "The Program" refers to any copyrightable work licensed under this 69 | License. Each licensee is addressed as "you". "Licensees" and 70 | "recipients" may be individuals or organizations. 71 | 72 | To "modify" a work means to copy from or adapt all or part of the work 73 | in a fashion requiring copyright permission, other than the making of an 74 | exact copy. The resulting work is called a "modified version" of the 75 | earlier work or a work "based on" the earlier work. 76 | 77 | A "covered work" means either the unmodified Program or a work based 78 | on the Program. 79 | 80 | To "propagate" a work means to do anything with it that, without 81 | permission, would make you directly or secondarily liable for 82 | infringement under applicable copyright law, except executing it on a 83 | computer or modifying a private copy. Propagation includes copying, 84 | distribution (with or without modification), making available to the 85 | public, and in some countries other activities as well. 86 | 87 | To "convey" a work means any kind of propagation that enables other 88 | parties to make or receive copies. Mere interaction with a user through 89 | a computer network, with no transfer of a copy, is not conveying. 90 | 91 | An interactive user interface displays "Appropriate Legal Notices" 92 | to the extent that it includes a convenient and prominently visible 93 | feature that (1) displays an appropriate copyright notice, and (2) 94 | tells the user that there is no warranty for the work (except to the 95 | extent that warranties are provided), that licensees may convey the 96 | work under this License, and how to view a copy of this License. If 97 | the interface presents a list of user commands or options, such as a 98 | menu, a prominent item in the list meets this criterion. 99 | 100 | 1. Source Code. 101 | 102 | The "source code" for a work means the preferred form of the work 103 | for making modifications to it. "Object code" means any non-source 104 | form of a work. 105 | 106 | A "Standard Interface" means an interface that either is an official 107 | standard defined by a recognized standards body, or, in the case of 108 | interfaces specified for a particular programming language, one that 109 | is widely used among developers working in that language. 110 | 111 | The "System Libraries" of an executable work include anything, other 112 | than the work as a whole, that (a) is included in the normal form of 113 | packaging a Major Component, but which is not part of that Major 114 | Component, and (b) serves only to enable use of the work with that 115 | Major Component, or to implement a Standard Interface for which an 116 | implementation is available to the public in source code form. A 117 | "Major Component", in this context, means a major essential component 118 | (kernel, window system, and so on) of the specific operating system 119 | (if any) on which the executable work runs, or a compiler used to 120 | produce the work, or an object code interpreter used to run it. 121 | 122 | The "Corresponding Source" for a work in object code form means all 123 | the source code needed to generate, install, and (for an executable 124 | work) run the object code and to modify the work, including scripts to 125 | control those activities. However, it does not include the work's 126 | System Libraries, or general-purpose tools or generally available free 127 | programs which are used unmodified in performing those activities but 128 | which are not part of the work. For example, Corresponding Source 129 | includes interface definition files associated with source files for 130 | the work, and the source code for shared libraries and dynamically 131 | linked subprograms that the work is specifically designed to require, 132 | such as by intimate data communication or control flow between those 133 | subprograms and other parts of the work. 134 | 135 | The Corresponding Source need not include anything that users 136 | can regenerate automatically from other parts of the Corresponding 137 | Source. 138 | 139 | The Corresponding Source for a work in source code form is that 140 | same work. 141 | 142 | 2. Basic Permissions. 143 | 144 | All rights granted under this License are granted for the term of 145 | copyright on the Program, and are irrevocable provided the stated 146 | conditions are met. This License explicitly affirms your unlimited 147 | permission to run the unmodified Program. The output from running a 148 | covered work is covered by this License only if the output, given its 149 | content, constitutes a covered work. This License acknowledges your 150 | rights of fair use or other equivalent, as provided by copyright law. 151 | 152 | You may make, run and propagate covered works that you do not 153 | convey, without conditions so long as your license otherwise remains 154 | in force. You may convey covered works to others for the sole purpose 155 | of having them make modifications exclusively for you, or provide you 156 | with facilities for running those works, provided that you comply with 157 | the terms of this License in conveying all material for which you do 158 | not control copyright. Those thus making or running the covered works 159 | for you must do so exclusively on your behalf, under your direction 160 | and control, on terms that prohibit them from making any copies of 161 | your copyrighted material outside their relationship with you. 162 | 163 | Conveying under any other circumstances is permitted solely under 164 | the conditions stated below. Sublicensing is not allowed; section 10 165 | makes it unnecessary. 166 | 167 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 168 | 169 | No covered work shall be deemed part of an effective technological 170 | measure under any applicable law fulfilling obligations under article 171 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 172 | similar laws prohibiting or restricting circumvention of such 173 | measures. 174 | 175 | When you convey a covered work, you waive any legal power to forbid 176 | circumvention of technological measures to the extent such circumvention 177 | is effected by exercising rights under this License with respect to 178 | the covered work, and you disclaim any intention to limit operation or 179 | modification of the work as a means of enforcing, against the work's 180 | users, your or third parties' legal rights to forbid circumvention of 181 | technological measures. 182 | 183 | 4. Conveying Verbatim Copies. 184 | 185 | You may convey verbatim copies of the Program's source code as you 186 | receive it, in any medium, provided that you conspicuously and 187 | appropriately publish on each copy an appropriate copyright notice; 188 | keep intact all notices stating that this License and any 189 | non-permissive terms added in accord with section 7 apply to the code; 190 | keep intact all notices of the absence of any warranty; and give all 191 | recipients a copy of this License along with the Program. 192 | 193 | You may charge any price or no price for each copy that you convey, 194 | and you may offer support or warranty protection for a fee. 195 | 196 | 5. Conveying Modified Source Versions. 197 | 198 | You may convey a work based on the Program, or the modifications to 199 | produce it from the Program, in the form of source code under the 200 | terms of section 4, provided that you also meet all of these conditions: 201 | 202 | a) The work must carry prominent notices stating that you modified 203 | it, and giving a relevant date. 204 | 205 | b) The work must carry prominent notices stating that it is 206 | released under this License and any conditions added under section 207 | 7. This requirement modifies the requirement in section 4 to 208 | "keep intact all notices". 209 | 210 | c) You must license the entire work, as a whole, under this 211 | License to anyone who comes into possession of a copy. This 212 | License will therefore apply, along with any applicable section 7 213 | additional terms, to the whole of the work, and all its parts, 214 | regardless of how they are packaged. This License gives no 215 | permission to license the work in any other way, but it does not 216 | invalidate such permission if you have separately received it. 217 | 218 | d) If the work has interactive user interfaces, each must display 219 | Appropriate Legal Notices; however, if the Program has interactive 220 | interfaces that do not display Appropriate Legal Notices, your 221 | work need not make them do so. 222 | 223 | A compilation of a covered work with other separate and independent 224 | works, which are not by their nature extensions of the covered work, 225 | and which are not combined with it such as to form a larger program, 226 | in or on a volume of a storage or distribution medium, is called an 227 | "aggregate" if the compilation and its resulting copyright are not 228 | used to limit the access or legal rights of the compilation's users 229 | beyond what the individual works permit. Inclusion of a covered work 230 | in an aggregate does not cause this License to apply to the other 231 | parts of the aggregate. 232 | 233 | 6. Conveying Non-Source Forms. 234 | 235 | You may convey a covered work in object code form under the terms 236 | of sections 4 and 5, provided that you also convey the 237 | machine-readable Corresponding Source under the terms of this License, 238 | in one of these ways: 239 | 240 | a) Convey the object code in, or embodied in, a physical product 241 | (including a physical distribution medium), accompanied by the 242 | Corresponding Source fixed on a durable physical medium 243 | customarily used for software interchange. 244 | 245 | b) Convey the object code in, or embodied in, a physical product 246 | (including a physical distribution medium), accompanied by a 247 | written offer, valid for at least three years and valid for as 248 | long as you offer spare parts or customer support for that product 249 | model, to give anyone who possesses the object code either (1) a 250 | copy of the Corresponding Source for all the software in the 251 | product that is covered by this License, on a durable physical 252 | medium customarily used for software interchange, for a price no 253 | more than your reasonable cost of physically performing this 254 | conveying of source, or (2) access to copy the 255 | Corresponding Source from a network server at no charge. 256 | 257 | c) Convey individual copies of the object code with a copy of the 258 | written offer to provide the Corresponding Source. This 259 | alternative is allowed only occasionally and noncommercially, and 260 | only if you received the object code with such an offer, in accord 261 | with subsection 6b. 262 | 263 | d) Convey the object code by offering access from a designated 264 | place (gratis or for a charge), and offer equivalent access to the 265 | Corresponding Source in the same way through the same place at no 266 | further charge. You need not require recipients to copy the 267 | Corresponding Source along with the object code. If the place to 268 | copy the object code is a network server, the Corresponding Source 269 | may be on a different server (operated by you or a third party) 270 | that supports equivalent copying facilities, provided you maintain 271 | clear directions next to the object code saying where to find the 272 | Corresponding Source. Regardless of what server hosts the 273 | Corresponding Source, you remain obligated to ensure that it is 274 | available for as long as needed to satisfy these requirements. 275 | 276 | e) Convey the object code using peer-to-peer transmission, provided 277 | you inform other peers where the object code and Corresponding 278 | Source of the work are being offered to the general public at no 279 | charge under subsection 6d. 280 | 281 | A separable portion of the object code, whose source code is excluded 282 | from the Corresponding Source as a System Library, need not be 283 | included in conveying the object code work. 284 | 285 | A "User Product" is either (1) a "consumer product", which means any 286 | tangible personal property which is normally used for personal, family, 287 | or household purposes, or (2) anything designed or sold for incorporation 288 | into a dwelling. In determining whether a product is a consumer product, 289 | doubtful cases shall be resolved in favor of coverage. For a particular 290 | product received by a particular user, "normally used" refers to a 291 | typical or common use of that class of product, regardless of the status 292 | of the particular user or of the way in which the particular user 293 | actually uses, or expects or is expected to use, the product. A product 294 | is a consumer product regardless of whether the product has substantial 295 | commercial, industrial or non-consumer uses, unless such uses represent 296 | the only significant mode of use of the product. 297 | 298 | "Installation Information" for a User Product means any methods, 299 | procedures, authorization keys, or other information required to install 300 | and execute modified versions of a covered work in that User Product from 301 | a modified version of its Corresponding Source. The information must 302 | suffice to ensure that the continued functioning of the modified object 303 | code is in no case prevented or interfered with solely because 304 | modification has been made. 305 | 306 | If you convey an object code work under this section in, or with, or 307 | specifically for use in, a User Product, and the conveying occurs as 308 | part of a transaction in which the right of possession and use of the 309 | User Product is transferred to the recipient in perpetuity or for a 310 | fixed term (regardless of how the transaction is characterized), the 311 | Corresponding Source conveyed under this section must be accompanied 312 | by the Installation Information. But this requirement does not apply 313 | if neither you nor any third party retains the ability to install 314 | modified object code on the User Product (for example, the work has 315 | been installed in ROM). 316 | 317 | The requirement to provide Installation Information does not include a 318 | requirement to continue to provide support service, warranty, or updates 319 | for a work that has been modified or installed by the recipient, or for 320 | the User Product in which it has been modified or installed. Access to a 321 | network may be denied when the modification itself materially and 322 | adversely affects the operation of the network or violates the rules and 323 | protocols for communication across the network. 324 | 325 | Corresponding Source conveyed, and Installation Information provided, 326 | in accord with this section must be in a format that is publicly 327 | documented (and with an implementation available to the public in 328 | source code form), and must require no special password or key for 329 | unpacking, reading or copying. 330 | 331 | 7. Additional Terms. 332 | 333 | "Additional permissions" are terms that supplement the terms of this 334 | License by making exceptions from one or more of its conditions. 335 | Additional permissions that are applicable to the entire Program shall 336 | be treated as though they were included in this License, to the extent 337 | that they are valid under applicable law. If additional permissions 338 | apply only to part of the Program, that part may be used separately 339 | under those permissions, but the entire Program remains governed by 340 | this License without regard to the additional permissions. 341 | 342 | When you convey a copy of a covered work, you may at your option 343 | remove any additional permissions from that copy, or from any part of 344 | it. (Additional permissions may be written to require their own 345 | removal in certain cases when you modify the work.) You may place 346 | additional permissions on material, added by you to a covered work, 347 | for which you have or can give appropriate copyright permission. 348 | 349 | Notwithstanding any other provision of this License, for material you 350 | add to a covered work, you may (if authorized by the copyright holders of 351 | that material) supplement the terms of this License with terms: 352 | 353 | a) Disclaiming warranty or limiting liability differently from the 354 | terms of sections 15 and 16 of this License; or 355 | 356 | b) Requiring preservation of specified reasonable legal notices or 357 | author attributions in that material or in the Appropriate Legal 358 | Notices displayed by works containing it; or 359 | 360 | c) Prohibiting misrepresentation of the origin of that material, or 361 | requiring that modified versions of such material be marked in 362 | reasonable ways as different from the original version; or 363 | 364 | d) Limiting the use for publicity purposes of names of licensors or 365 | authors of the material; or 366 | 367 | e) Declining to grant rights under trademark law for use of some 368 | trade names, trademarks, or service marks; or 369 | 370 | f) Requiring indemnification of licensors and authors of that 371 | material by anyone who conveys the material (or modified versions of 372 | it) with contractual assumptions of liability to the recipient, for 373 | any liability that these contractual assumptions directly impose on 374 | those licensors and authors. 375 | 376 | All other non-permissive additional terms are considered "further 377 | restrictions" within the meaning of section 10. If the Program as you 378 | received it, or any part of it, contains a notice stating that it is 379 | governed by this License along with a term that is a further 380 | restriction, you may remove that term. If a license document contains 381 | a further restriction but permits relicensing or conveying under this 382 | License, you may add to a covered work material governed by the terms 383 | of that license document, provided that the further restriction does 384 | not survive such relicensing or conveying. 385 | 386 | If you add terms to a covered work in accord with this section, you 387 | must place, in the relevant source files, a statement of the 388 | additional terms that apply to those files, or a notice indicating 389 | where to find the applicable terms. 390 | 391 | Additional terms, permissive or non-permissive, may be stated in the 392 | form of a separately written license, or stated as exceptions; 393 | the above requirements apply either way. 394 | 395 | 8. Termination. 396 | 397 | You may not propagate or modify a covered work except as expressly 398 | provided under this License. Any attempt otherwise to propagate or 399 | modify it is void, and will automatically terminate your rights under 400 | this License (including any patent licenses granted under the third 401 | paragraph of section 11). 402 | 403 | However, if you cease all violation of this License, then your 404 | license from a particular copyright holder is reinstated (a) 405 | provisionally, unless and until the copyright holder explicitly and 406 | finally terminates your license, and (b) permanently, if the copyright 407 | holder fails to notify you of the violation by some reasonable means 408 | prior to 60 days after the cessation. 409 | 410 | Moreover, your license from a particular copyright holder is 411 | reinstated permanently if the copyright holder notifies you of the 412 | violation by some reasonable means, this is the first time you have 413 | received notice of violation of this License (for any work) from that 414 | copyright holder, and you cure the violation prior to 30 days after 415 | your receipt of the notice. 416 | 417 | Termination of your rights under this section does not terminate the 418 | licenses of parties who have received copies or rights from you under 419 | this License. If your rights have been terminated and not permanently 420 | reinstated, you do not qualify to receive new licenses for the same 421 | material under section 10. 422 | 423 | 9. Acceptance Not Required for Having Copies. 424 | 425 | You are not required to accept this License in order to receive or 426 | run a copy of the Program. Ancillary propagation of a covered work 427 | occurring solely as a consequence of using peer-to-peer transmission 428 | to receive a copy likewise does not require acceptance. However, 429 | nothing other than this License grants you permission to propagate or 430 | modify any covered work. These actions infringe copyright if you do 431 | not accept this License. Therefore, by modifying or propagating a 432 | covered work, you indicate your acceptance of this License to do so. 433 | 434 | 10. Automatic Licensing of Downstream Recipients. 435 | 436 | Each time you convey a covered work, the recipient automatically 437 | receives a license from the original licensors, to run, modify and 438 | propagate that work, subject to this License. You are not responsible 439 | for enforcing compliance by third parties with this License. 440 | 441 | An "entity transaction" is a transaction transferring control of an 442 | organization, or substantially all assets of one, or subdividing an 443 | organization, or merging organizations. If propagation of a covered 444 | work results from an entity transaction, each party to that 445 | transaction who receives a copy of the work also receives whatever 446 | licenses to the work the party's predecessor in interest had or could 447 | give under the previous paragraph, plus a right to possession of the 448 | Corresponding Source of the work from the predecessor in interest, if 449 | the predecessor has it or can get it with reasonable efforts. 450 | 451 | You may not impose any further restrictions on the exercise of the 452 | rights granted or affirmed under this License. For example, you may 453 | not impose a license fee, royalty, or other charge for exercise of 454 | rights granted under this License, and you may not initiate litigation 455 | (including a cross-claim or counterclaim in a lawsuit) alleging that 456 | any patent claim is infringed by making, using, selling, offering for 457 | sale, or importing the Program or any portion of it. 458 | 459 | 11. Patents. 460 | 461 | A "contributor" is a copyright holder who authorizes use under this 462 | License of the Program or a work on which the Program is based. The 463 | work thus licensed is called the contributor's "contributor version". 464 | 465 | A contributor's "essential patent claims" are all patent claims 466 | owned or controlled by the contributor, whether already acquired or 467 | hereafter acquired, that would be infringed by some manner, permitted 468 | by this License, of making, using, or selling its contributor version, 469 | but do not include claims that would be infringed only as a 470 | consequence of further modification of the contributor version. For 471 | purposes of this definition, "control" includes the right to grant 472 | patent sublicenses in a manner consistent with the requirements of 473 | this License. 474 | 475 | Each contributor grants you a non-exclusive, worldwide, royalty-free 476 | patent license under the contributor's essential patent claims, to 477 | make, use, sell, offer for sale, import and otherwise run, modify and 478 | propagate the contents of its contributor version. 479 | 480 | In the following three paragraphs, a "patent license" is any express 481 | agreement or commitment, however denominated, not to enforce a patent 482 | (such as an express permission to practice a patent or covenant not to 483 | sue for patent infringement). To "grant" such a patent license to a 484 | party means to make such an agreement or commitment not to enforce a 485 | patent against the party. 486 | 487 | If you convey a covered work, knowingly relying on a patent license, 488 | and the Corresponding Source of the work is not available for anyone 489 | to copy, free of charge and under the terms of this License, through a 490 | publicly available network server or other readily accessible means, 491 | then you must either (1) cause the Corresponding Source to be so 492 | available, or (2) arrange to deprive yourself of the benefit of the 493 | patent license for this particular work, or (3) arrange, in a manner 494 | consistent with the requirements of this License, to extend the patent 495 | license to downstream recipients. "Knowingly relying" means you have 496 | actual knowledge that, but for the patent license, your conveying the 497 | covered work in a country, or your recipient's use of the covered work 498 | in a country, would infringe one or more identifiable patents in that 499 | country that you have reason to believe are valid. 500 | 501 | If, pursuant to or in connection with a single transaction or 502 | arrangement, you convey, or propagate by procuring conveyance of, a 503 | covered work, and grant a patent license to some of the parties 504 | receiving the covered work authorizing them to use, propagate, modify 505 | or convey a specific copy of the covered work, then the patent license 506 | you grant is automatically extended to all recipients of the covered 507 | work and works based on it. 508 | 509 | A patent license is "discriminatory" if it does not include within 510 | the scope of its coverage, prohibits the exercise of, or is 511 | conditioned on the non-exercise of one or more of the rights that are 512 | specifically granted under this License. You may not convey a covered 513 | work if you are a party to an arrangement with a third party that is 514 | in the business of distributing software, under which you make payment 515 | to the third party based on the extent of your activity of conveying 516 | the work, and under which the third party grants, to any of the 517 | parties who would receive the covered work from you, a discriminatory 518 | patent license (a) in connection with copies of the covered work 519 | conveyed by you (or copies made from those copies), or (b) primarily 520 | for and in connection with specific products or compilations that 521 | contain the covered work, unless you entered into that arrangement, 522 | or that patent license was granted, prior to 28 March 2007. 523 | 524 | Nothing in this License shall be construed as excluding or limiting 525 | any implied license or other defenses to infringement that may 526 | otherwise be available to you under applicable patent law. 527 | 528 | 12. No Surrender of Others' Freedom. 529 | 530 | If conditions are imposed on you (whether by court order, agreement or 531 | otherwise) that contradict the conditions of this License, they do not 532 | excuse you from the conditions of this License. If you cannot convey a 533 | covered work so as to satisfy simultaneously your obligations under this 534 | License and any other pertinent obligations, then as a consequence you may 535 | not convey it at all. For example, if you agree to terms that obligate you 536 | to collect a royalty for further conveying from those to whom you convey 537 | the Program, the only way you could satisfy both those terms and this 538 | License would be to refrain entirely from conveying the Program. 539 | 540 | 13. Remote Network Interaction; Use with the GNU General Public License. 541 | 542 | Notwithstanding any other provision of this License, if you modify the 543 | Program, your modified version must prominently offer all users 544 | interacting with it remotely through a computer network (if your version 545 | supports such interaction) an opportunity to receive the Corresponding 546 | Source of your version by providing access to the Corresponding Source 547 | from a network server at no charge, through some standard or customary 548 | means of facilitating copying of software. This Corresponding Source 549 | shall include the Corresponding Source for any work covered by version 3 550 | of the GNU General Public License that is incorporated pursuant to the 551 | following paragraph. 552 | 553 | Notwithstanding any other provision of this License, you have 554 | permission to link or combine any covered work with a work licensed 555 | under version 3 of the GNU General Public License into a single 556 | combined work, and to convey the resulting work. The terms of this 557 | License will continue to apply to the part which is the covered work, 558 | but the work with which it is combined will remain governed by version 559 | 3 of the GNU General Public License. 560 | 561 | 14. Revised Versions of this License. 562 | 563 | The Free Software Foundation may publish revised and/or new versions of 564 | the GNU Affero General Public License from time to time. Such new versions 565 | will be similar in spirit to the present version, but may differ in detail to 566 | address new problems or concerns. 567 | 568 | Each version is given a distinguishing version number. If the 569 | Program specifies that a certain numbered version of the GNU Affero General 570 | Public License "or any later version" applies to it, you have the 571 | option of following the terms and conditions either of that numbered 572 | version or of any later version published by the Free Software 573 | Foundation. If the Program does not specify a version number of the 574 | GNU Affero General Public License, you may choose any version ever published 575 | by the Free Software Foundation. 576 | 577 | If the Program specifies that a proxy can decide which future 578 | versions of the GNU Affero General Public License can be used, that proxy's 579 | public statement of acceptance of a version permanently authorizes you 580 | to choose that version for the Program. 581 | 582 | Later license versions may give you additional or different 583 | permissions. However, no additional obligations are imposed on any 584 | author or copyright holder as a result of your choosing to follow a 585 | later version. 586 | 587 | 15. Disclaimer of Warranty. 588 | 589 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 590 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 591 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 592 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 593 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 594 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 595 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 596 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 597 | 598 | 16. Limitation of Liability. 599 | 600 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 601 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 602 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 603 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 604 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 605 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 606 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 607 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 608 | SUCH DAMAGES. 609 | 610 | 17. Interpretation of Sections 15 and 16. 611 | 612 | If the disclaimer of warranty and limitation of liability provided 613 | above cannot be given local legal effect according to their terms, 614 | reviewing courts shall apply local law that most closely approximates 615 | an absolute waiver of all civil liability in connection with the 616 | Program, unless a warranty or assumption of liability accompanies a 617 | copy of the Program in return for a fee. 618 | 619 | END OF TERMS AND CONDITIONS 620 | 621 | How to Apply These Terms to Your New Programs 622 | 623 | If you develop a new program, and you want it to be of the greatest 624 | possible use to the public, the best way to achieve this is to make it 625 | free software which everyone can redistribute and change under these terms. 626 | 627 | To do so, attach the following notices to the program. It is safest 628 | to attach them to the start of each source file to most effectively 629 | state the exclusion of warranty; and each file should have at least 630 | the "copyright" line and a pointer to where the full notice is found. 631 | 632 | 633 | Copyright (C) 634 | 635 | This program is free software: you can redistribute it and/or modify 636 | it under the terms of the GNU Affero General Public License as published 637 | by the Free Software Foundation, either version 3 of the License, or 638 | (at your option) any later version. 639 | 640 | This program is distributed in the hope that it will be useful, 641 | but WITHOUT ANY WARRANTY; without even the implied warranty of 642 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 643 | GNU Affero General Public License for more details. 644 | 645 | You should have received a copy of the GNU Affero General Public License 646 | along with this program. If not, see . 647 | 648 | Also add information on how to contact you by electronic and paper mail. 649 | 650 | If your software can interact with users remotely through a computer 651 | network, you should also make sure that it provides a way for users to 652 | get its source. For example, if your program is a web application, its 653 | interface could display a "Source" link that leads users to an archive 654 | of the code. There are many ways you could offer source, and different 655 | solutions will be better for different programs; see section 13 for the 656 | specific requirements. 657 | 658 | You should also get your employer (if you work as a programmer) or school, 659 | if any, to sign a "copyright disclaimer" for the program, if necessary. 660 | For more information on this, and how to apply and follow the GNU AGPL, see 661 | . 662 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # SedLex 2 | 3 | SedLex is a frontend generator for French bills compiled using [DuraLex](https://github.com/Legilibre/DuraLex). 4 | 5 | ## Installation 6 | 7 | ### Installing dependencies 8 | 9 | ```bash 10 | pip install -r requirements.txt 11 | ``` 12 | 13 | ### Fetching the original law texts 14 | 15 | If you want to generate diffs, you will need to have the corresponding original law texts in the `data` directory. 16 | This original data is expected to be a Git repositories created using [Archeo-Lex](https://github.com/Legilibre/Archeo-Lex). 17 | 18 | ## Generating patch files 19 | 20 | **Before generating patch files, you must fetch the corresponding original law texts. In order to do so, please read the ["Fetching the original law texts"](#fetching-the-original-law-texts) section.** 21 | 22 | By default, the intermediary representation will not compute/feature the diff of each edit. 23 | You must add the `--diff` switch to the command line: 24 | 25 | ```bash 26 | duralex --file bill.html | ./bin/sedlex --diff 27 | ``` 28 | 29 | ```json 30 | { 31 | "children": [ 32 | { 33 | "children": [ 34 | { 35 | "children": [ 36 | { 37 | "children": [ 38 | { 39 | "type": "quote", 40 | "words": "autorisé" 41 | } 42 | ], 43 | "type": "words" 44 | }, 45 | { 46 | "children": [ 47 | { 48 | "children": [ 49 | { 50 | "children": [ 51 | { 52 | "children": [ 53 | { 54 | "type": "quote", 55 | "words": "défendu" 56 | } 57 | ], 58 | "type": "words-reference" 59 | } 60 | ], 61 | "order": 1, 62 | "type": "sentence-reference" 63 | } 64 | ], 65 | "filename": "data/code des instruments monétaires et des médailles/9.md", 66 | "id": "9", 67 | "type": "article-reference" 68 | } 69 | ], 70 | "id": "code des instruments monétaires et des médailles", 71 | "type": "code-reference" 72 | } 73 | ], 74 | "diff": "--- \"data/code des instruments monétaires et des médailles/9.md\"\n+++ \"data/code des instruments monétaires et des médailles/9.md\"\n@@ -1,6 +1,6 @@\n # titre 1\n \n-Il est expressément défendu à toutes personnes, quelles que soient les professions qu'elles exercent, de frapper ou de faire frapper des médailles, jetons ou pièces de plaisir, d'or, d'argent et autres métaux, ailleurs que dans les ateliers de la monnaie, à moins d'être munies d'une autorisation spéciale du ministre de l'économie et des finances.\n+Il est expressément autorisé à toutes personnes, quelles que soient les professions qu'elles exercent, de frapper ou de faire frapper des médailles, jetons ou pièces de plaisir, d'or, d'argent et autres métaux, ailleurs que dans les ateliers de la monnaie, à moins d'être munies d'une autorisation spéciale du ministre de l'économie et des finances.\n \n # titre 2\n ", 75 | "editType": "replace", 76 | "type": "edit" 77 | } 78 | ], 79 | "isNew": false, 80 | "order": 1, 81 | "type": "article" 82 | } 83 | ] 84 | } 85 | ``` 86 | 87 | Then, using [jq](https://stedolan.github.io/jq/), it is easy to extract only the `diff` fields: 88 | 89 | ```bash 90 | duralex --file bill.html | ./bin/sedlex --diff | jq -r '.. | .diff? | strings' 91 | ``` 92 | 93 | ```patch 94 | --- "data/code des instruments monétaires et des médailles/9.md" 95 | +++ "data/code des instruments monétaires et des médailles/9.md" 96 | @@ -1,6 +1,6 @@ 97 | # titre 1 98 | 99 | -Il est expressément défendu à toutes personnes, quelles que soient les professions qu'elles exercent, de frapper ou de faire frapper des médailles, jetons ou pièces de plaisir, d'or, d'argent et autres métaux, ailleurs que dans les ateliers de la monnaie, à moins d'être munies d'une autorisation spéciale du ministre de l'économie et des finances. 100 | +Il est expressément autorisé à toutes personnes, quelles que soient les professions qu'elles exercent, de frapper ou de faire frapper des médailles, jetons ou pièces de plaisir, d'or, d'argent et autres métaux, ailleurs que dans les ateliers de la monnaie, à moins d'être munies d'une autorisation spéciale du ministre de l'économie et des finances. 101 | 102 | # titre 2 103 | ``` 104 | 105 | Such output can be written in a patch file to be applied later: 106 | 107 | ```bash 108 | duralex --file bill.html | ./bin/sedlex --diff | jq -r '.. | .diff? | strings' > articles.patch 109 | ``` 110 | 111 | or it can be piped to apply the patch directly: 112 | 113 | ```bash 114 | duralex --file bill.html | ./bin/sedlex --diff | jq -r '.. | .diff? | strings' | patch -p0 115 | ``` 116 | 117 | ## Git integration 118 | 119 | SedLex can automagically apply each `edit` node into an actual Git commit by passing the `--git-commit` flag. 120 | 121 | Passing the `--git-push` flag will effectively push those commits. 122 | 123 | SedLex can also generate meaningful commit messages by passing the `--commit-message` flag. 124 | For example, the following `edit` node: 125 | 126 | ```json 127 | { 128 | "children": [ 129 | { 130 | "children": [ 131 | { 132 | "type": "quote", 133 | "words": "autorisé" 134 | } 135 | ], 136 | "type": "words" 137 | }, 138 | { 139 | "children": [ 140 | { 141 | "children": [ 142 | { 143 | "children": [ 144 | { 145 | "children": [ 146 | { 147 | "type": "quote", 148 | "words": "défendu" 149 | } 150 | ], 151 | "type": "words-reference" 152 | } 153 | ], 154 | "order": 1, 155 | "type": "sentence-reference" 156 | } 157 | ], 158 | "filename": "data/code des instruments monétaires et des médailles/9.md", 159 | "id": "9", 160 | "type": "article-reference" 161 | } 162 | ], 163 | "id": "code des instruments monétaires et des médailles", 164 | "type": "code-reference" 165 | } 166 | ], 167 | "editType": "replace", 168 | "type": "edit" 169 | } 170 | ``` 171 | 172 | will generate the following commit message: 173 | 174 | > Remplacer les mots "défendu" dans l'article 9 par les mots "autorisé" (Article 1). 175 | 176 | Each commit message is added as a `commitMessage` field on the corresponding `edit` node: 177 | 178 | ```json 179 | { 180 | "type": "edit", 181 | "editType": "replace", 182 | "commitMessage": "Remplacer les mots \"défendu\" dans l'article 9 par les mots \"autorisé\" (Article 1).", 183 | } 184 | ``` 185 | 186 | ## GitHub integration 187 | 188 | SedLex can automagically create a [GitHub](https://github.com) issue for each `article` node by passing the 189 | `--github-repository` and `--github-token` flags. As a result, each edit/commit will reference the corresponding 190 | article/issue (and vice versa). Each article from the original bill will become a GitHub issue with: 191 | 192 | * a title of the form "Article {{ article.order }}" (ex: "Article 42"); 193 | * a description containing the original content of the corresponding article. 194 | 195 | Such issue will also be referenced by the commit message of all the `edit` nodes that are descendants of the 196 | corresponding `article` node. For example, this commit message: 197 | 198 | > Remplacer les mots "défendu" dans l'article 9 par les mots "autorisé" (Article 1). 199 | 200 | would become: 201 | 202 | > Remplacer les mots "défendu" dans l'article 9 par les mots "autorisé" (Article 1). 203 | > 204 | > GitHub: https://github.com/Legilibre/CIMM-articles/issues/1 205 | 206 | *In the example above, proper meaningful commit messages are generated by adding the `--commit-message` flag, cf 207 | [Git integration](#git-integration).* 208 | 209 | All the generated content is templated by the following jinja2 templates: 210 | 211 | * the title of the issue: `template/github/issue_title.j2` 212 | * the body of the issue: `template/github/issue_body.j2` 213 | * the commit message: `template/github/commit_message.j2` 214 | 215 | The following command line will effectively compute diffs, create commit messages, apply and commit and push the changes on Git and create all the relevant content on GitHub: 216 | 217 | ```bash 218 | duralex --file bill.html | sedlex \ 219 | --github-token your_api_token_here --github-repository namespace/repository \ 220 | --diff \ 221 | --commit-message \ 222 | --git-commit \ 223 | --git-push 224 | ``` 225 | 226 | ## GitLab integration 227 | 228 | The GitLab integration works exactly like [the GitHub integration](#github-integration) except it's configured using the 229 | `--gitlab-repository` and `--gitlab-token` flags. 230 | 231 | All the generated content is templated by the following jinja2 templates: 232 | 233 | * the title of the issue: `template/gitlab/issue_title.j2` 234 | * the body of the issue: `template/gitlab/issue_description.j2` 235 | * the commit message: `template/gitlab/commit_message.j2` 236 | 237 | The following command line will effectively compute diffs, create commit messages, apply and commit and push the changes on Git and create all the relevant content on GitLab: 238 | 239 | ```bash 240 | duralex --file bill.html | sedlex \ 241 | --gitlab-token your_api_token_here --gitlab-repository namespace/repository \ 242 | --diff \ 243 | --commit-message \ 244 | --git-commit \ 245 | --git-push 246 | ``` 247 | 248 | ## GitBook integration 249 | 250 | SedLex can automagically create a [GitBook](https://www.gitbook.com) by passing the `--gitbook` option. This option 251 | must be set to the output directory for the GitBook Markdown files (SUMMARY.md, README.md, ...). 252 | 253 | The `--gitbook-format` option can be used to specify the desired GitBook output. It can be `html`, `markdown` or both. 254 | The default output format is `markdown`. 255 | 256 | To generate the most comprehensive GitBook, it is recommended to also use the `--commit-message` and `--diff` flags: 257 | 258 | ```bash 259 | duralex --file bill.html | sedlex \ 260 | --gitbook /path/to/the/gitbook \ 261 | --diff \ 262 | --commit-message 263 | ``` 264 | -------------------------------------------------------------------------------- /bin/sedlex: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # -*- coding=utf-8 -*- 3 | 4 | import codecs 5 | import os 6 | import json 7 | import sys 8 | import argparse 9 | import urllib 10 | 11 | sys.path.insert(0, os.path.join(os.path.realpath(os.path.dirname(__file__)), '..')) 12 | sys.path.insert(0, os.path.join(os.path.realpath(os.path.dirname(__file__)), '../src')) 13 | 14 | from duralex.AddParentVisitor import AddParentVisitor 15 | from duralex.DeleteParentVisitor import DeleteParentVisitor 16 | 17 | from sedlex.AddCommitMessageVisitor import AddCommitMessageVisitor 18 | from sedlex.AddArcheoLexFilenameVisitor import AddArcheoLexFilenameVisitor 19 | from sedlex.AddDiffVisitor import AddDiffVisitor 20 | from sedlex.AddGitHubIssueVisitor import AddGitHubIssueVisitor 21 | from sedlex.AddGitLabIssueVisitor import AddGitLabIssueVisitor 22 | from sedlex.GitCommitVisitor import GitCommitVisitor 23 | from sedlex.CreateGitBookVisitor import CreateGitBookVisitor 24 | from sedlex.AddCocoricoVoteVisitor import AddCocoricoVoteVisitor 25 | from sedlex.AddGitHubHistoryLinkVisitor import AddGitHubHistoryLinkVisitor 26 | from sedlex.AddGitLabHistoryLinkVisitor import AddGitLabHistoryLinkVisitor 27 | from sedlex.InitializeGitRepositoryVisitor import InitializeGitRepositoryVisitor 28 | 29 | def decode(data): 30 | try: 31 | data = data.decode('utf-8') 32 | except: 33 | try: 34 | data = data.decode('iso-8859-1') 35 | except: 36 | pass 37 | 38 | return data 39 | 40 | def handle_data(data, args): 41 | tree = json.loads(data) 42 | 43 | AddParentVisitor().visit(tree) 44 | 45 | if args.git_init: 46 | InitializeGitRepositoryVisitor(args).visit(tree) 47 | 48 | if args.commit_message: 49 | AddCommitMessageVisitor().visit(tree) 50 | 51 | if args.diff: 52 | AddArcheoLexFilenameVisitor(args.repository).visit(tree) 53 | AddDiffVisitor().visit(tree) 54 | 55 | if args.github_token and args.github_repository: 56 | AddGitHubHistoryLinkVisitor(args).visit(tree) 57 | AddGitHubIssueVisitor(args).visit(tree) 58 | 59 | if args.gitlab_token and args.gitlab_repository: 60 | AddGitLabHistoryLinkVisitor(args).visit(tree) 61 | AddGitLabIssueVisitor(args).visit(tree) 62 | 63 | if args.git_commit: 64 | GitCommitVisitor().visit(tree) 65 | 66 | if args.git_push: 67 | GitPushVisitor().visit(tree) 68 | 69 | if args.gitbook: 70 | CreateGitBookVisitor(args).visit(tree) 71 | 72 | if args.cocorico_app_id and args.cocorico_secret: 73 | AddCocoricoVoteVisitor(args).visit(tree) 74 | 75 | if not args.quiet: 76 | DeleteParentVisitor().visit(tree) 77 | json_data = json.dumps(tree, sort_keys=True, indent=2, ensure_ascii=False) 78 | sys.stdout.write(json_data) 79 | 80 | def main(argv=None): 81 | parser = argparse.ArgumentParser(prog='sedlex') 82 | parser.add_argument('--file', help='the path of the bill to process', default='-') 83 | parser.add_argument('--url', help='the URL of the bill to process') 84 | parser.add_argument('--quiet', action='store_true', help='no stdout output') 85 | parser.add_argument('--diff', action='store_true', help='compute a diff for each edit') 86 | parser.add_argument('--repository', help='') 87 | parser.add_argument('--commit-message', action='store_true', help='generate a commit message for each edit') 88 | parser.add_argument('--git-init', action='store_true', help='initialize the git repository (if needed) in the directory specified by --repository') 89 | parser.add_argument('--git-commit', action='store_true', help='git commit each edit') 90 | parser.add_argument('--git-push', action='store_true', help='git push all the referenced repositories') 91 | parser.add_argument('--github-token', help='the GitHub API token') 92 | parser.add_argument('--github-repository', help='the target GitHub repository') 93 | parser.add_argument('--gitlab-token', help='the GitLab API token') 94 | parser.add_argument('--gitlab-repository', help='the target GitLab repository') 95 | parser.add_argument('--gitbook', help='create a GitBook') 96 | parser.add_argument('--gitbook-format', choices=['html', 'markdown'], nargs='+', default=['markdown'], help='the comma-separated list of GitBook export formats') 97 | parser.add_argument('--cocorico-app-id', help='the Cocorico App ID to create the vote') 98 | parser.add_argument('--cocorico-secret', help='the Cocorico secret to create the vote') 99 | parser.add_argument('--cocorico-url', help='the URL of Cocorico backend') 100 | 101 | args = parser.parse_args() 102 | 103 | if args.url: 104 | data = urllib.urlopen(args.url).read() 105 | elif args.file: 106 | if args.file == '-': 107 | data = decode(sys.stdin.buffer.read()) 108 | else: 109 | f = open(args.file, 'rb') 110 | data = decode(f.read()) 111 | f.close() 112 | 113 | handle_data(data, args) 114 | 115 | return 0 116 | 117 | if __name__ == "__main__": 118 | sys.exit(main()) 119 | -------------------------------------------------------------------------------- /docs/format.md: -------------------------------------------------------------------------------- 1 | Data format 2 | =========== 3 | 4 | To compute the diff of an amendment on some amended text (e.g. an article of law proposal), the DuraLex tree passed to AddDiffVisitor should be: 5 | 6 | ``` 7 | { 8 | "children": [ 9 | { 10 | "children": [ 11 | { 12 | "children": [ 13 | { 14 | … 15 | } 16 | ], 17 | "content": "Au premier alinéa, les mots \"quarante députés ou quarante sénateurs\" sont remplacés par les mots \"trente députés ou trente sénateurs\".", 18 | "type": "amendment" 19 | } 20 | ], 21 | "content": "Au sixième alinéa de l'article 16 de la Constitution, les mots : \"soixante députés ou soixante sénateurs\" sont remplacés par les mots : \"quarante députés ou quarante sénateurs\".", 22 | "order": 11, 23 | "type": "bill-article" 24 | } 25 | ], 26 | "type": "law-proposal" 27 | } 28 | ``` 29 | 30 | If the DuraLex tree was already computed as `tree` and the root node has no type, it can be attached to its content: 31 | ```python 32 | bill = duralex.tree.create_node(None, {'type': duralex.tree.TYPE_LAW_PROPOSAL}) 33 | bill_article = duralex.tree.create_node(bill, {'type': duralex.tree.TYPE_BILL_ARTICLE, 'content': 'Au sixième alinéa…', 'order': 11}) 34 | tree['type'] = duralex.tree.TYPE_AMENDMENT 35 | tree['content'] = 'Au premier alinéa…' 36 | duralex.tree.push_node(bill_article, tree) 37 | amendment = tree 38 | ``` 39 | 40 | To compute the diff of the bill article or any in-force article (of type “modifying text”/“amendment”), it can be done similarly one level above. Or, if all texts modified by the bill article are available through Archéo Lex, it is not needed to encapsulate the DuraLex tree of the bill article in higher-level tree. 41 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | html5lib 2 | beautifulsoup4 3 | requests 4 | jinja2 5 | python-gitlab 6 | PyGithub 7 | -e git+git://github.com/Legilibre/DuraLex.git#egg=duralex 8 | -------------------------------------------------------------------------------- /sedlex/AddArcheoLexFilenameVisitor.py: -------------------------------------------------------------------------------- 1 | import os 2 | import codecs 3 | import re 4 | 5 | from duralex.AbstractVisitor import AbstractVisitor 6 | import duralex.tree as tree 7 | 8 | class AddArcheoLexFilenameVisitor(AbstractVisitor): 9 | def __init__(self, repositoryArticles=None, repositoryFile=None): 10 | self.base = repositoryArticles 11 | self.baseFile = repositoryFile 12 | self.content = {} 13 | super(AddArcheoLexFilenameVisitor, self).__init__() 14 | 15 | def visit_article_reference_node(self, node, post): 16 | if post: 17 | return 18 | 19 | node_law = node 20 | while 'parent' in node_law and node_law['type'] != tree.TYPE_CODE_REFERENCE and node_law['type'] != tree.TYPE_LAW_REFERENCE: 21 | node_law = node_law['parent'] 22 | if 'repository' in node_law: 23 | node['filename'] = os.path.join(node_law['repository'], 'Article_' + node['id'].replace(' ', '_') + '.md') 24 | if 'filename' in node_law and node_law['filename'] in self.content: 25 | content = re.search(r'\n\n#+ Article ' + node['id'] + '\n\n([^\n]*(\n([^\n]+|(\n[^#]*)))*)', '\n\n' + self.content[node_law['filename']]) 26 | if content: 27 | node['content'] = content.group(1).strip() 28 | 29 | def visit_article_definition_node(self, node, post): 30 | if post: 31 | return 32 | 33 | node_law = node 34 | while 'parent' in node_law and node_law['type'] != tree.TYPE_CODE_REFERENCE and node_law['type'] != tree.TYPE_LAW_REFERENCE: 35 | node_law = node_law['parent'] 36 | # TODO: ugly: add an article but code/law only specified in reference, a visitor should previously wrap this article-def in a code-def 37 | if 'repository' not in node_law: 38 | node_law = node 39 | while 'parent' in node_law and node_law['type'] != tree.TYPE_EDIT: 40 | node_law = node_law['parent'] 41 | node_law = tree.filter_nodes(node_law, lambda x: x['type'] in [tree.TYPE_CODE_REFERENCE, tree.TYPE_LAW_REFERENCE]) 42 | if len(node_law): 43 | node_law = node_law[0] 44 | else: 45 | node_law = None 46 | if node_law and 'repository' in node_law: 47 | node['filename'] = os.path.join(node_law['repository'], 'Article_' + node['id'].replace(' ', '_') + '.md') 48 | if node_law and 'filename' in node_law and node_law['filename'] in self.content: 49 | content = re.search(r'\n\n#+ Article ' + node['id'] + '\n\n([^\n]*(\n([^\n]+|(\n[^#]*)))*)', '\n\n' + self.content[node_law['filename']]) 50 | if content: 51 | node['content'] = content.group(1).strip() 52 | 53 | def visit_code_reference_node(self, node, post): 54 | if post: 55 | return 56 | 57 | if self.base: 58 | node['repository'] = os.path.join(self.base, node['id'].replace(' ', '_')) 59 | if self.baseFile: 60 | node['filename'] = os.path.join(self.baseFile, node['id'].replace(' ', '_'), node['id'].replace(' ', '_') + '.md') 61 | if 'filename' in node and node['filename'] not in self.content: 62 | try: 63 | input_file = codecs.open(node['filename'], mode='r', encoding='utf-8').read() 64 | self.content[node['filename']] = input_file 65 | except FileNotFoundError: 66 | pass 67 | 68 | def visit_law_reference_node(self, node, post): 69 | if post: 70 | return 71 | 72 | node['repository'] = os.path.join(self.base, 'loi_' + node['id'].replace(' ', '_')) 73 | if self.baseFile: 74 | node['filename'] = os.path.join(self.baseFile, node['id'].replace(' ', '_'), node['id'].replace(' ', '_') + '.md') 75 | if 'filename' in node and node['filename'] not in self.content: 76 | try: 77 | input_file = codecs.open(node['filename'], mode='r', encoding='utf-8').read() 78 | self.content[node['filename']] = input_file 79 | except FileNotFoundError: 80 | pass 81 | 82 | # vim: set ts=4 sw=4 sts=4 et: 83 | -------------------------------------------------------------------------------- /sedlex/AddCocoricoVoteVisitor.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | from duralex.AbstractVisitor import AbstractVisitor 4 | 5 | from duralex.alinea_parser import * 6 | 7 | import requests 8 | 9 | class AddCocoricoVoteVisitor(AbstractVisitor): 10 | def __init__(self, args): 11 | self.url = args.cocorico_url 12 | if not self.url: 13 | self.url = 'https://cocorico.cc' 14 | 15 | r = requests.post( 16 | self.url + '/api/oauth/token', 17 | auth=(args.cocorico_app_id, args.cocorico_secret), 18 | data={ 'grant_type': 'client_credentials' }, 19 | verify=self.url != 'https://local.cocorico.cc' 20 | ) 21 | self.access_token = r.json()['access_token'] 22 | 23 | super(AddCocoricoVoteVisitor, self).__init__() 24 | 25 | def visit_node(self, node): 26 | if not self.access_token: 27 | return 28 | 29 | # if on root node 30 | if 'parent' not in node and 'type' not in node: 31 | r = requests.post( 32 | self.url + '/api/vote', 33 | headers={'Authorization': 'Bearer ' + self.access_token}, 34 | data={ 35 | 'title': 'test de vote', 36 | 'description': 'ceci est un test', 37 | 'url': 'https://legilibre.fr/?test=49' 38 | }, 39 | verify=self.url != 'https://local.cocorico.cc' 40 | ) 41 | node['cocoricoVote'] = r.json()['vote']['id'] 42 | -------------------------------------------------------------------------------- /sedlex/AddCommitMessageVisitor.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | from duralex.AbstractVisitor import AbstractVisitor 4 | 5 | from duralex.alinea_parser import * 6 | 7 | import duralex.tree 8 | 9 | import re 10 | 11 | def int_to_roman(integer): 12 | string = '' 13 | table = [ 14 | ['M',1000], ['CM',900], ['D',500], ['CD',400], ['C',100], ['XC',90], ['L',50], ['XL',40], ['X',10], ['IX',9], 15 | ['V',5], ['IV',4], ['I',1] 16 | ] 17 | 18 | for pair in table: 19 | while integer - pair[1] >= 0: 20 | integer -= pair[1] 21 | string += pair[0] 22 | 23 | return string 24 | 25 | class AddCommitMessageVisitor(AbstractVisitor): 26 | def __init__(self): 27 | self.ref_parts = [] 28 | self.def_parts = [] 29 | 30 | super(AddCommitMessageVisitor, self).__init__() 31 | 32 | def visit_law_reference_node(self, node, post): 33 | if post: 34 | return 35 | 36 | self.ref_parts.append(u'de la loi N°' + node['id']) 37 | 38 | def visit_article_reference_node(self, node, post): 39 | if post: 40 | return 41 | 42 | if 'children' in node and len(node['children']) > 0: 43 | self.ref_parts.append(u'de l\'article ' + node['id']) 44 | else: 45 | self.ref_parts.append(u'l\'article ' + node['id']) 46 | if 'position' in node and node['position'] == 'after': 47 | self.ref_parts.append(u'après') 48 | 49 | def visit_bill_article_reference_node(self, node, post): 50 | if post: 51 | return 52 | 53 | if duralex.tree.get_root(node)['type'] == duralex.tree.TYPE_LAW_PROJECT: 54 | self.ref_parts.append(u'du projet de loi') 55 | elif duralex.tree.get_root(node)['type'] == duralex.tree.TYPE_LAW_PROPOSAL: 56 | self.ref_parts.append(u'de la proposition de loi') 57 | 58 | if 'children' in node and len(node['children']) > 0: 59 | self.ref_parts.append(u'de l\'article ' + str(node['order'])) 60 | else: 61 | self.ref_parts.append(u'l\'article ' + str(node['order'])) 62 | if 'position' in node and node['position'] == 'after': 63 | self.ref_parts.append(u'après') 64 | 65 | def visit_alinea_reference_node(self, node, post): 66 | if post: 67 | return 68 | 69 | if 'children' in node and len(node['children']) > 0: 70 | if node['order'] == -1: 71 | self.ref_parts.append(u'du dernier alinéa') 72 | elif node['order'] == -2: 73 | self.ref_parts.append(u'de l\'avant-dernier alinéa') 74 | else: 75 | self.ref_parts.append(u'de l\'alinéa ' + str(node['order'])) 76 | else: 77 | if node['order'] == -1: 78 | self.ref_parts.append(u'le dernier alinéa') 79 | elif node['order'] == -2: 80 | self.ref_parts.append(u'l\'avant-dernier alinéa') 81 | else: 82 | self.ref_parts.append(u'l\'alinéa ' + str(node['order'])) 83 | 84 | def visit_sentence_reference_node(self, node, post): 85 | if post: 86 | return 87 | 88 | if node['order'] == 1: 89 | number_word = u'la 1ère' 90 | elif node['order'] == -1: 91 | number_word = u'la dernière' 92 | elif node['order'] == -1: 93 | number_word = u'l\'avant-dernière' 94 | else: 95 | number_word = u'la ' + node['order'] + u'ème' 96 | 97 | if 'children' in node and len(node['children']) > 0: 98 | self.ref_parts.append(u'de ' + number_word + ' phrase') 99 | else: 100 | self.ref_parts.append(number_word + ' phrase') 101 | 102 | def visit_words_reference_node(self, node, post): 103 | if post: 104 | return 105 | 106 | quotes = filter_nodes(node, lambda n: n['type'] == 'quote') 107 | quotes = ''.join([n['words'] for n in quotes]) 108 | num_words = len(re.findall(r'\S+', quotes)) 109 | 110 | if num_words == 1: 111 | self.ref_parts.append(u'le mot "' + quotes + '"') 112 | else: 113 | self.ref_parts.append(u'les mots "' + quotes + '"') 114 | 115 | def visit_header1_reference_node(self, node, post): 116 | if post: 117 | return 118 | 119 | # FIXME 120 | 121 | def visit_words_definition_node(self, node, post): 122 | if post: 123 | return 124 | 125 | quotes = filter_nodes(node, lambda n: n['type'] == 'quote') 126 | quotes = ''.join([n['words'] for n in quotes]) 127 | num_words = len(re.findall(r'\S+', quotes)) 128 | 129 | if num_words == 1: 130 | self.def_parts.append(u'le mot "' + quotes + '"') 131 | else: 132 | self.def_parts.append(u'les mots "' + quotes + '"') 133 | 134 | def visit_article_definition_node(self, node, post): 135 | if post: 136 | return 137 | 138 | self.def_parts.append(u'un article ' + node['id']) 139 | 140 | def visit_edit_node(self, node, post): 141 | if not post: 142 | self.ref_parts = [] 143 | self.def_parts = [] 144 | return 145 | 146 | edit_desc = '' 147 | if node['editType'] == 'delete': 148 | edit_desc = 'supprimer ' + ' '.join(self.ref_parts[::-1]) 149 | elif node['editType'] == 'edit' or node['editType'] == 'replace': 150 | edit_desc = 'remplacer ' + ' '.join(self.ref_parts[::-1]) + ' par ' + ', '.join(self.def_parts) 151 | elif node['editType'] == 'add': 152 | edit_desc = ' '.join(self.ref_parts[::-1]) + ' ajouter ' + ' '.join(self.def_parts[::-1]) 153 | 154 | origin = [] 155 | ancestors = get_node_ancestors(node) 156 | for ancestor in ancestors: 157 | if 'type' not in ancestor: 158 | continue; 159 | 160 | if ancestor['type'] == duralex.tree.TYPE_AMENDMENT: 161 | origin.append('Amendement ' + ancestor['id']) 162 | if ancestor['type'] == duralex.tree.TYPE_BILL_ARTICLE: 163 | origin.append('Article ' + str(ancestor['order'])) 164 | if ancestor['type'] == duralex.tree.TYPE_HEADER1: 165 | origin.append(int_to_roman(ancestor['order'])) 166 | if ancestor['type'] == duralex.tree.TYPE_HEADER2: 167 | origin.append(unicode(ancestor['order']) + u'°') 168 | # FIXME: handle duralex.tree.TYPE_HEADER3 169 | origin = ', '.join(origin[::-1]) 170 | 171 | node['commitMessage'] = edit_desc[0].upper() + edit_desc[1:] + ' (' + origin + ').' 172 | -------------------------------------------------------------------------------- /sedlex/AddDiffVisitor.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | import codecs 4 | import re 5 | import difflib 6 | import sys 7 | import os 8 | 9 | import duralex.alinea_parser as parser 10 | from . import diff 11 | 12 | from duralex.AbstractVisitor import AbstractVisitor 13 | 14 | import duralex.tree as tree 15 | 16 | class AddDiffVisitor(AbstractVisitor): 17 | REGEXP = { 18 | tree.TYPE_HEADER1_REFERENCE : re.compile(r'([IVXCLDM]+\. - (?:(?:.|\n)(?![IVXCLDM]+\. - ))*)', re.UNICODE), 19 | tree.TYPE_HEADER2_REFERENCE : re.compile(r'(\d+\. (?:(?:.|\n)(?!\d+\. ))*)', re.UNICODE), 20 | tree.TYPE_HEADER3_REFERENCE : re.compile(r'([a-z]+\) (?:(?:.|\n)(?![a-z]+\) ))*)', re.UNICODE), 21 | tree.TYPE_ALINEA_REFERENCE : re.compile(r'^(.+)$', re.UNICODE | re.MULTILINE), 22 | tree.TYPE_SENTENCE_REFERENCE : re.compile(r'([A-ZÀÀÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏ].*?(?= 0 or content == None else self.end + len(content)+1 46 | match = list(re.finditer(AddDiffVisitor.REGEXP[type], content[self.begin:end])) 47 | if type == tree.TYPE_SENTENCE_REFERENCE: 48 | s = re.match('^(" *|« *)?((Art\. (.*?)\.?|[IVXCLDM]+ *(bis|ter|quater|quinquies|sexies|septies|octies|nonies)?\.?) +[-‐‑‒–—―] +|[a-z]+\) *|\d+° *\)? *)', content[self.begin:end]) 49 | if s != None: 50 | self.begin += len(s.group(0)) 51 | match = list(re.finditer(AddDiffVisitor.REGEXP[type], content[self.begin:end])) 52 | if len(match) == 0: 53 | match = list(re.finditer('(.*)', content[self.begin:end])) 54 | order = node['order'] 55 | if order < 0: 56 | order += len(match)+1 57 | if 'position' in node and node['position'] == 'after': 58 | if order == len(match): 59 | self.begin = self.end 60 | return 61 | elif order > len(match): 62 | node['error'] = '[SedLex] visit_alinea_reference_node: node[\'order\'] == '+str(order)+' >= len(match) == '+str(len(match)) 63 | return 64 | match = match[order] 65 | self.begin += match.start() 66 | if node['type'] in [tree.TYPE_WORD_REFERENCE, tree.TYPE_SENTENCE_REFERENCE]: 67 | self.end = self.begin 68 | else: 69 | if order - 1 == len(match): 70 | self.begin = self.end 71 | return 72 | elif order - 1 > len(match): 73 | node['error'] = '[SedLex] visit_'+typestring+'_node: node[\'order\']-1 == '+str(order)+'-1 >= len(match) == '+str(len(match)) 74 | return 75 | match = match[order - 1] 76 | self.begin += match.start() 77 | self.end = self.begin + len(match.group(1)) 78 | 79 | def visit_alinea_reference_node(self, node, post): 80 | if post: 81 | return 82 | self.compute_location(tree.TYPE_ALINEA_REFERENCE, 'alinea_reference', node) 83 | 84 | def visit_sentence_reference_node(self, node, post): 85 | if post: 86 | return 87 | self.compute_location(tree.TYPE_SENTENCE_REFERENCE, 'sentence_reference', node) 88 | 89 | def visit_header1_reference_node(self, node, post): 90 | if post: 91 | return 92 | self.compute_location(tree.TYPE_HEADER1_REFERENCE, 'header1_reference', node) 93 | 94 | def visit_header2_reference_node(self, node, post): 95 | if post: 96 | return 97 | self.compute_location(tree.TYPE_HEADER2_REFERENCE, 'header2_reference', node) 98 | 99 | def visit_header3_reference_node(self, node, post): 100 | if post: 101 | return 102 | self.compute_location(tree.TYPE_HEADER2_REFERENCE, 'header3_reference', node) 103 | 104 | def visit_words_reference_node(self, node, post): 105 | if post: 106 | return 107 | 108 | if len(self.content.values()) == 1: 109 | content = list(self.content.values())[0] 110 | else: 111 | if len(self.content.values()) == 0: 112 | node['error'] = '[SedLex] missing text in visit_words_reference_node' 113 | raise Exception('missing text of the article') 114 | else: 115 | raise ValueError 116 | end = self.end if self.end >= 0 or content == None else self.end + len(content)+1 117 | 118 | if 'children' in node and node['children'][0]['type'] == 'quote': 119 | words = node['children'][0]['words'].strip() 120 | location = content[self.begin:end].lower().find(words.lower()) 121 | if location == -1: 122 | if end-self.begin < 21: 123 | raise Exception('words not found in "'+content[self.begin:end]+'"') 124 | else: 125 | raise Exception('words not found in "'+content[self.begin:self.begin+10]+'…'+content[end-10:end]+'"') 126 | if 'position' in node and node['position'] == 'after': 127 | self.begin += content[self.begin:end].lower().find(words.lower()) + len(words) 128 | self.end = self.begin 129 | else: 130 | self.begin += content[self.begin:end].lower().find(words.lower()) 131 | self.end = self.begin + len(words) 132 | 133 | def visit_article_reference_node(self, node, post): 134 | if post: 135 | return 136 | if 'filename' in node: 137 | if 'content' in node: 138 | self.set_content(node['filename'], node['content']) 139 | else: 140 | self.set_content_from_file(node['filename'], node) 141 | 142 | def visit_bill_article_node(self, node, post): 143 | if post: 144 | self.bill_article = None 145 | else: 146 | self.bill_article = (node['order'], node['content']) 147 | 148 | def visit_amendment_node(self, node, post): 149 | if post: 150 | self.is_amendment = False 151 | else: 152 | self.is_amendment = True 153 | 154 | def visit_bill_article_reference_node(self, node, post): 155 | bill_article = tree.filter_nodes( 156 | tree.get_root(node), 157 | lambda n: n['type'] == tree.TYPE_BILL_ARTICLE and n['order'] == node['order'] 158 | ) 159 | if len(bill_article) == 1: 160 | self.set_content(bill_article[0]['order'], bill_article[0]['content']) 161 | 162 | def visit_article_definition_node(self, node, post): 163 | if post: 164 | return 165 | if 'filename' in node: 166 | if 'content' in node: 167 | self.set_content(node['filename'], node['content']) 168 | else: 169 | self.set_content_from_file(node['filename'], node) 170 | 171 | def set_content_from_file(self, filename, node): 172 | if filename not in self.content: 173 | if os.path.isfile(filename): 174 | input_file = codecs.open(filename, mode="r", encoding="utf-8") 175 | self.set_content(filename, input_file.read()) 176 | else: 177 | node['error'] = '[SedLex] file not found' 178 | self.set_content(filename, '') 179 | 180 | def set_content(self, key, content): 181 | self.content[key] = content 182 | self.begin = 0 183 | self.end = -1 184 | 185 | def visit_edit_node(self, node, post): 186 | if not post: 187 | self.content = {} 188 | self.begin = 0 189 | self.end = -1 190 | if self.is_amendment and self.bill_article: 191 | self.set_content(self.bill_article[0], self.bill_article[1]) 192 | return 193 | 194 | article_reference_node = parser.filter_nodes(node, lambda x: x['type'] == tree.TYPE_ARTICLE_REFERENCE) 195 | article_definition_node = parser.filter_nodes(node, lambda x: x['type'] == tree.TYPE_ARTICLE_DEFINITION) 196 | editTypeArticle = 'edit' 197 | if node['editType'] == 'add' and len(article_definition_node): 198 | editTypeArticle = 'add' 199 | if not article_reference_node and len(self.content.values()) == 0 and editTypeArticle == 'edit': 200 | node['error'] = '[SedLex] visit_edit_node: no article reference node' 201 | return 202 | if len(article_reference_node) > 1: 203 | node['error'] = '[SedLex] visit_edit_node: multiple article reference nodes' 204 | return 205 | 206 | filename = 'unnamed article' 207 | if article_reference_node and 'filename' in article_reference_node[0]: 208 | filename = article_reference_node[0]['filename'] 209 | id = article_reference_node[0]['id'] 210 | elif article_definition_node and 'filename' in article_definition_node[0]: 211 | filename = article_definition_node[0]['filename'] 212 | id = article_definition_node[0]['id'] 213 | 214 | if editTypeArticle == 'edit': 215 | if len(self.content.values()) == 1: 216 | old_content = list(self.content.values())[0] 217 | else: 218 | if len(self.content.values()) == 0: 219 | node['error'] = '[SedLex] missing text in visit_edit_node' 220 | raise Exception('missing text of the article') 221 | else: 222 | raise ValueError 223 | else: 224 | old_content = None 225 | 226 | new_content = old_content 227 | new_words = None 228 | diff = (None, None, None) 229 | end = self.end if self.end >= 0 or old_content == None else self.end + len(old_content)+1 230 | 231 | try: 232 | if node['editType'] in ['replace', 'edit']: 233 | # replace words 234 | def_node = parser.filter_nodes(node, tree.is_definition) 235 | if not def_node: 236 | node['error'] = '[SedLex] visit_edit_node: no definition node found in editType in [\'replace\', \'edit\']' 237 | return 238 | def_node = def_node[-1] 239 | new_words = def_node['children'][0]['words'] 240 | diff = (self.begin, old_content[self.begin:end], new_words) 241 | elif node['editType'] == 'delete': 242 | art_ref_node = parser.filter_nodes(node, lambda x: x['type'] in [tree.TYPE_ARTICLE_REFERENCE, tree.TYPE_BILL_ARTICLE_REFERENCE]) 243 | other_ref_nodes = parser.filter_nodes(node, lambda x: x['type'] not in [tree.TYPE_EDIT, tree.TYPE_ARTICLE_REFERENCE, tree.TYPE_CODE_REFERENCE, tree.TYPE_LAW_REFERENCE, tree.TYPE_LAW_PROJECT, tree.TYPE_LAW_PROPOSAL, tree.TYPE_BILL_ARTICLE_REFERENCE]) 244 | if art_ref_node and not other_ref_nodes: 245 | new_content = None 246 | else: 247 | new_words = '' 248 | diff = (self.begin, old_content[self.begin:end], None) 249 | elif node['editType'] == 'add': 250 | def_node = parser.filter_nodes(node, lambda x: x['type'] == tree.TYPE_QUOTE)[-1] 251 | if not def_node['words']: 252 | raise Exception('Empty words to be added') 253 | # add a word 254 | if node['children'][1]['type'] == tree.TYPE_WORD_DEFINITION: 255 | # typography: add the new words before the full stop 256 | if old_content[self.begin:end] and old_content[end-1:end] == '.': 257 | new_words = old_content[self.begin:end-1] + def_node['words'] + old_content[end-1] 258 | diff = (end-1, None, def_node['words']) 259 | else: 260 | new_words = old_content[self.begin:end] + def_node['words'] 261 | diff = (end, None, def_node['words']) 262 | elif node['children'][1]['type'] == tree.TYPE_SENTENCE_DEFINITION: 263 | # typography: ensure the sentence is terminated by a full stop 264 | if def_node['words'][-1] != '.': 265 | def_node['words'] += '.' 266 | new_words = old_content[self.begin:end] + ' ' + def_node['words'] 267 | diff = (end, None, def_node['words']) 268 | # add an alinea 269 | elif node['children'][1]['type'] in [tree.TYPE_ALINEA_DEFINITION, tree.TYPE_HEADER1_DEFINITION, tree.TYPE_HEADER2_DEFINITION, tree.TYPE_HEADER3_DEFINITION]: 270 | art_ref_node = parser.filter_nodes(node, lambda x: x['type'] in [tree.TYPE_ARTICLE_REFERENCE, tree.TYPE_BILL_ARTICLE_REFERENCE]) 271 | other_ref_nodes = parser.filter_nodes(node, lambda x: tree.is_reference(x) and x['type'] not in [tree.TYPE_ARTICLE_REFERENCE, tree.TYPE_CODE_REFERENCE, tree.TYPE_LAW_REFERENCE, tree.TYPE_LAW_PROJECT, tree.TYPE_LAW_PROPOSAL, tree.TYPE_BILL_ARTICLE_REFERENCE]) 272 | if art_ref_node and not other_ref_nodes: 273 | self.begin = end 274 | new_words = '\n' + '\n'.join([ 275 | n['words'] for n in parser.filter_nodes(node, lambda x: x['type'] == tree.TYPE_QUOTE) 276 | ]).strip() 277 | diff = (self.begin, None, new_words) 278 | if self.begin < end: 279 | new_words += '\n' + old_content[self.begin:end] 280 | # add an article 281 | elif node['children'][1]['type'] == tree.TYPE_ARTICLE_DEFINITION: 282 | new_words = '\n'.join([ 283 | n['words'] for n in parser.filter_nodes(node, lambda x: x['type'] == tree.TYPE_QUOTE) 284 | ]) 285 | self.begin = 0 286 | self.end = -1 287 | diff = (self.begin, None, new_words) 288 | # Note the following instructions are a specific case when an article-ref is replaced by a new article-def, it would not work if there is no article-ref 289 | if 'id' in node['children'][1] and node['children'][1]['id'] != id: 290 | id = node['children'][1]['id'] 291 | filename = re.sub(r'Article_(.*)\.md$', 'Article_'+id+'.md', filename) 292 | old_content = None 293 | if new_words != None: 294 | new_content, left, new_words, right, self.begin, self.end = typography(old_content, new_words, self.begin, end) 295 | if diff[1]: 296 | diff = (self.begin, old_content[self.begin:self.end], new_words) 297 | elif old_content != None: 298 | new_content_bis, left_bis, new_words_bis, right_bis, begin_bis, end_bis = typography(old_content, diff[2], diff[0], diff[0]) 299 | diff = (begin_bis, old_content[begin_bis:end_bis], new_words_bis) 300 | 301 | if self.computeDiff: 302 | old_content_list = old_content.splitlines() if old_content else [] 303 | new_content_list = new_content.splitlines() if new_content else [] 304 | unified_diff = difflib.unified_diff( 305 | old_content_list, 306 | new_content_list, 307 | tofile='\"' + filename + '\"' if new_content != None else '/dev/null', 308 | fromfile='\"' + filename + '\"' if old_content != None else '/dev/null' 309 | ) 310 | unified_diff = list(unified_diff) 311 | if len(unified_diff) > 0: 312 | node['diff'] = ('\n'.join(unified_diff)).replace('\n\n', '\n') # investigate why double newlines 313 | #node['htmlDiff'] = diff.make_html_rich_diff(old_content, new_content, self.filename) 314 | if self.computeExactDiff and (diff[1] or diff[2]): 315 | node['exactDiff'] = '--- ' + ('"' + filename + '"' if old_content != None else '/dev/null') + '\n' + \ 316 | '+++ ' + ('"' + filename + '"' if new_content != None else '/dev/null') + '\n' 317 | if diff[0] < 0: 318 | diff = (diff[0]+len(old_content), diff[1], diff[2]) 319 | # Modify a part of the text 320 | if diff[1] != None and diff[2] != None: 321 | node['exactDiff'] += '@@ -%d,%d +%d,%d @@' %(diff[0]+1,len(diff[1]),diff[0]+1,len(diff[2])) 322 | # Remove the entire article 323 | elif diff[1] != None and diff[2] == None: 324 | if diff[0] != 0: 325 | raise Exception('Article removed but index was not at the beginning') 326 | node['exactDiff'] += '@@ -1,%d +0,0 @@' %(len(diff[1])) 327 | # Add an entire article 328 | elif diff[1] == None and diff[2] != None: 329 | if diff[0] != 0: 330 | raise Exception('Article added but index was not at the beginning') 331 | node['exactDiff'] += '@@ -0,0 +1,%d @@' %(len(diff[2])) 332 | else: 333 | raise Exception('Empty diff, should not happen') 334 | if diff[1]: 335 | node['exactDiff'] += '\n-' + diff[1].replace('\n','\n-') 336 | if diff[2]: 337 | node['exactDiff'] += '\n+' + diff[2].replace('\n','\n+') 338 | node['text'] = old_content 339 | 340 | # See issue #1: it seems that the source text for each verb is the original text and not the text already modified in earlier changes 341 | #if node['parent']['type'] != tree.TYPE_AMENDMENT or node['parent']['status'] == 'approved': 342 | # self.set_content(self.filename, new_content) 343 | except Exception as e: 344 | # FIXME: proper error message 345 | raise e 346 | 347 | def typography(old_content, new_words, begin, end): 348 | 349 | if not new_words: 350 | if begin > 0 and old_content[begin-1:begin] == ' ' and (end == len(old_content) or old_content[end:end+1] in [' ', '\n']): 351 | return old_content[:begin-1] + old_content[end:], old_content[:begin-1], '', old_content[end:], begin-1, end 352 | elif (begin == 0 or old_content[begin-1:begin] == '\n') and old_content[end:end+1] == ' ': 353 | return old_content[:begin] + old_content[end+1:], old_content[:begin], '', old_content[end+1:], begin, end+1 354 | return old_content[:begin] + old_content[end:], old_content[:begin], '', old_content[end:], begin, end 355 | 356 | # Replace simple newlines by double newlines (Markdown syntax for new paragraphs) 357 | new_words = re.sub(r'(^|[^\n])\n([^\n]|$)', r'\1\n\n\2', new_words.strip(' ')) 358 | new_words = re.sub(r'(^|[^\n])\n{3,}([^\n]|$)', r'\1\n\n\2', new_words) 359 | 360 | if not old_content: 361 | return new_words, '', new_words, '', begin, end 362 | 363 | right = old_content[end:] 364 | left = old_content[:begin] 365 | 366 | # Remove orphan spaces before or after the introduced words 367 | left_spaces = '' 368 | right_spaces = '' 369 | if right: 370 | right_re = re.search(r'^( *)[^ ]', right) 371 | if right_re: 372 | right_spaces = right_re.group(1) 373 | end += len(right_spaces) 374 | right = old_content[end:] 375 | if left: 376 | left_re = re.search(r'[^ ]( *)$', left) 377 | if left_re: 378 | left_spaces = left_re.group(1) 379 | begin -= len(left_spaces) 380 | left = old_content[:begin] 381 | 382 | # Add a sigle space before or after the introduced words depending if we have two letters or point/comma/colon/semicolon + letter 383 | if new_words and right and re.match(r'^[.,:;!?]?[0-9a-záàâäéèêëíìîïóòôöøœúùûüýỳŷÿ°«»)!?‐‑‒–—―-]+$', new_words[-1]+right[0], flags=re.IGNORECASE): 384 | new_words = new_words+' ' 385 | if new_words and left and re.match(r'^[.,:;!?]?[0-9a-záàâäéèêëíìîïóòôöøœúùûüýỳŷÿ°«»)!?‐‑‒–—―-]+$', left[-1]+new_words[0], flags=re.IGNORECASE): 386 | new_words = ' '+new_words 387 | if not new_words and right and left and re.match(r'^[.,:;!?]?[0-9a-záàâäéèêëíìîïóòôöøœúùûüýỳŷÿ°«»)!?‐‑‒–—―-]+$', left[-1]+right[0], flags=re.IGNORECASE): 388 | new_words = ' '+new_words 389 | 390 | # Transfer spaces to old_content if common with the new_words to minimise the length of new_words 391 | if new_words and new_words[0] == ' ' and left_spaces: 392 | new_words = new_words[1:] 393 | begin += 1 394 | left = old_content[:begin] 395 | if new_words and new_words[-1] == ' ' and right_spaces: 396 | new_words = new_words[:-1] 397 | end -= 1 398 | right = old_content[end:] 399 | 400 | # Remove empty alineas 401 | if not new_words: 402 | left_re = re.search(r'[^\n](\n{2,})$', left) 403 | right_re = re.search(r'^(\n{2,})[^\n]', right) 404 | # Do not invert these two if: the specific case of the last alinea removed would not work 405 | if left_re and (right_re or re.search(r'^\n*$', right)): 406 | begin -= len(left_re.group(1)) 407 | left = old_content[:begin] 408 | elif right_re and (left_re or not left): 409 | end += len(right_re.group(1)) 410 | right = old_content[end:] 411 | 412 | return left+new_words+right, left, new_words, right, begin, end 413 | 414 | # vim: set ts=4 sw=4 sts=4 et: 415 | -------------------------------------------------------------------------------- /sedlex/AddGitHubHistoryLinkVisitor.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | from duralex.AbstractVisitor import AbstractVisitor 4 | 5 | class AddGitHubHistoryLinkVisitor(AbstractVisitor): 6 | def __init__(self, args): 7 | self.repo = args.github_repository 8 | self.law_id = None 9 | 10 | super(AddGitHubHistoryLinkVisitor, self).__init__() 11 | 12 | def visit_law_reference_node(self, node, post): 13 | if post: 14 | return 15 | 16 | self.law_id = node['id'] 17 | 18 | def visit_article_reference_node(self, node, post): 19 | if post: 20 | return 21 | 22 | node['githubHistory'] = ( 23 | 'https://github.com/' 24 | + self.repo + 25 | '/commits/' + self.law_id + '/' 26 | + 'Article_' + node['id'] + '.md' 27 | ) 28 | -------------------------------------------------------------------------------- /sedlex/AddGitHubIssueVisitor.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | from duralex.AbstractVisitor import AbstractVisitor 4 | 5 | from duralex.alinea_parser import * 6 | 7 | from github import Github 8 | 9 | from . import template 10 | 11 | class AddGitHubIssueVisitor(AbstractVisitor): 12 | def __init__(self, args): 13 | self.github = Github(args.github_token) 14 | self.repo = self.github.get_repo(args.github_repository) 15 | self.issues = list(self.repo.get_issues()) 16 | self.current_issue_number = -1 17 | self.current_issue_link = None 18 | 19 | super(AddGitHubIssueVisitor, self).__init__() 20 | 21 | def visit_edit_node(self, node, post): 22 | if post: 23 | return 24 | node['githubIssue'] = self.current_issue_link 25 | node['commitMessage'] = template.template_string('github/commit_message.j2', {'edit': node}) 26 | 27 | def visit_node(self, node): 28 | if 'type' in node and node['type'] == 'article': 29 | title = template.template_string('github/issue_title.j2', { 'article': node }) 30 | body = template.template_string('github/issue_body.j2', { 'article': node }) 31 | found = False 32 | for issue in self.issues: 33 | if issue.title == title: 34 | found = True 35 | self.current_issue_link = issue.html_url 36 | node['githubIssue'] = self.current_issue_link 37 | self.current_issue_number = issue.number 38 | if issue.body != body: 39 | issue.edit(title=title, body=body) 40 | if not found: 41 | issue = self.repo.create_issue(title=title, body=body) 42 | self.current_issue_link = issue.html_url 43 | node['githubIssue'] = self.current_issue_link 44 | self.current_issue_number = issue.number 45 | 46 | super(AddGitHubIssueVisitor, self).visit_node(node) 47 | -------------------------------------------------------------------------------- /sedlex/AddGitLabHistoryLinkVisitor.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | from duralex.AbstractVisitor import AbstractVisitor 4 | 5 | import os 6 | 7 | class AddGitLabHistoryLinkVisitor(AbstractVisitor): 8 | def __init__(self, args): 9 | self.repo = args.gitlab_repository 10 | self.law_id = None 11 | 12 | super(AddGitLabHistoryLinkVisitor, self).__init__() 13 | 14 | def visit_law_reference_node(self, node, post): 15 | if post: 16 | return 17 | self.law_id = node['id'] 18 | 19 | def visit_article_reference_node(self, node, post): 20 | if post: 21 | return 22 | 23 | node['gitlabHistory'] = ('https://gitlab.com/' 24 | + self.repo + '/commits/master/' 25 | + 'loi_' + self.law_id + '/' 26 | + 'Article_' + node['id'] + '.md') 27 | -------------------------------------------------------------------------------- /sedlex/AddGitLabIssueVisitor.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | from duralex.AbstractVisitor import AbstractVisitor 4 | from . import template 5 | 6 | from duralex.alinea_parser import * 7 | 8 | import gitlab 9 | 10 | class AddGitLabIssueVisitor(AbstractVisitor): 11 | def __init__(self, args): 12 | self.gitlab = gitlab.Gitlab('https://gitlab.com', args.gitlab_token) 13 | self.repo_name = args.gitlab_repository 14 | self.repo = self.gitlab.projects.get(self.repo_name) 15 | self.issues = self.repo.issues.list(state='opened') 16 | self.current_issue_number = -1 17 | self.current_issue_link = None 18 | 19 | super(AddGitLabIssueVisitor, self).__init__() 20 | 21 | def visit_edit_node(self, node, post): 22 | if post: 23 | return 24 | node['gitlabIssue'] = self.current_issue_link 25 | node['commitMessage'] = template.template_string('gitlab/commit_message.j2', {'edit': node}) 26 | 27 | def visit_node(self, node): 28 | if 'type' in node and node['type'] == 'article': 29 | title = template.template_string('gitlab/issue_title.j2', {'article': node}) 30 | description = template.template_string('gitlab/issue_description.j2', {'article': node}) 31 | found = False 32 | for issue in self.issues: 33 | if issue.title == title: 34 | found = True 35 | self.current_issue_number = issue.iid 36 | if issue.description != description: 37 | issue.save(title=title, description=description) 38 | if not found: 39 | issue = self.gitlab.project_issues.create( 40 | { 41 | 'title': title, 42 | 'description': description 43 | }, 44 | project_id=self.repo.id 45 | ) 46 | self.current_issue_number = issue.iid 47 | self.current_issue_link = 'https://gitlab.com/' + self.repo_name + '/issues/' + str(self.current_issue_number) 48 | node['gitlabIssue'] = self.current_issue_link 49 | 50 | super(AddGitLabIssueVisitor, self).visit_node(node) 51 | -------------------------------------------------------------------------------- /sedlex/CreateGitBookVisitor.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | from duralex.AbstractVisitor import AbstractVisitor 4 | from .AddCommitMessageVisitor import int_to_roman 5 | from . import template 6 | from . import diff 7 | 8 | from duralex.alinea_parser import * 9 | import duralex.tree as tree 10 | 11 | from bs4 import BeautifulSoup 12 | import jinja2 13 | 14 | import os 15 | import subprocess 16 | import tempfile 17 | from distutils.dir_util import copy_tree 18 | 19 | class CreateGitBookVisitor(AbstractVisitor): 20 | def __init__(self, args): 21 | self.gitbook_dir = args.gitbook 22 | self.tmp_dir = tempfile.mkdtemp() 23 | self.formats = args.gitbook_format 24 | 25 | super(CreateGitBookVisitor, self).__init__() 26 | 27 | def write_file(self, filename, data): 28 | f = open(self.tmp_dir + '/' + filename, 'w') 29 | f.write(data.encode('utf-8')) 30 | f.close() 31 | 32 | def get_article_commit_title(self, node): 33 | ancestors = get_node_ancestors(node) 34 | messages = [] 35 | for ancestor in ancestors: 36 | if 'type' not in ancestor: 37 | continue; 38 | if ancestor['type'] == tree.TYPE_BILL_ARTICLE: 39 | messages.append('Article ' + str(ancestor['order'])) 40 | elif ancestor['type'] == tree.TYPE_AMENDMENT: 41 | messages.append('Amendement ' + str(ancestor['id'])) 42 | elif ancestor['type'] == tree.TYPE_HEADER1: 43 | messages.append(int_to_roman(ancestor['order'])) 44 | elif ancestor['type'] == tree.TYPE_HEADER2: 45 | messages.append(unicode(ancestor['order']) + u'°') 46 | elif ancestor['type'] == tree.TYPE_HEADER3: 47 | messages.append(unicode(chr(ord('a') + ancestor['order'])) + u')') 48 | return ', '.join(messages[::-1]) 49 | 50 | def get_article_commit_diff(self, edit, target_title, target_href): 51 | if 'htmlDiff' in edit: 52 | soup = BeautifulSoup(edit['htmlDiff'], "html5lib") 53 | filename_div = soup.find('div', {'class': 'diff-filename'}) 54 | a_tag = soup.new_tag('a', href=target_href) 55 | a_tag.string = target_title 56 | filename_div.string = '' 57 | filename_div.append(a_tag) 58 | return unicode(soup.body.div) 59 | elif 'diff' in edit: 60 | process = subprocess.Popen( 61 | 'diff2html -i stdin -d word -o stdout --su hidden -s line', 62 | shell=True, 63 | stdout=subprocess.PIPE, 64 | stdin=subprocess.PIPE, 65 | stderr=subprocess.PIPE 66 | ) 67 | out, err = process.communicate(input=edit['diff'].encode('utf-8') + '\n') 68 | soup = BeautifulSoup(out, "html5lib") 69 | return (str(list(soup.find_all('style'))[0]) + '\n\n' 70 | + unicode(soup.find('div', {'id': 'diff'}))) 71 | 72 | def get_commits(self, node): 73 | edit_nodes = filter_nodes(node, lambda n: 'type' in n and n['type'] == tree.TYPE_EDIT) 74 | commits = [] 75 | for edit_node in edit_nodes: 76 | article_refs = filter_nodes(edit_node, lambda n: n['type'] == tree.TYPE_ARTICLE_REFERENCE) 77 | # FIXME: amendment that targets a bill article and not a law/code article 78 | if len(article_refs) == 0: 79 | continue 80 | article_ref = article_refs[0] 81 | target_title, target_href = self.get_deep_link(self.get_edit_target_nodes(article_ref)) 82 | commits.append({ 83 | 'title': self.get_article_commit_title(edit_node), 84 | # remove the " ({reference list})" from the commit message since its already printed 85 | # in the header above 86 | 'description': re.sub(r' \(.*\)', '', edit_node['commitMessage'].splitlines()[0]) if 'commitMessage' in edit_node else None, 87 | 'diff': self.get_article_commit_diff(edit_node, target_title, target_href), 88 | 'target': { 89 | 'title': target_title, 90 | 'link': target_href 91 | } 92 | }) 93 | return commits 94 | 95 | def get_articles(self, node): 96 | articles = [] 97 | article_nodes = filter_nodes(node, lambda n: n['type'] == tree.TYPE_BILL_ARTICLE) 98 | for article_node in article_nodes: 99 | articles.append({ 100 | 'order': article_node['order'], 101 | 'content': article_node['content'], 102 | 'commits': self.get_commits(article_node), 103 | 'githubIssue': article_node['githubIssue'] if 'githubIssue' in article_node else None, 104 | 'gitlabIssue': article_node['gitlabIssue'] if 'gitlabIssue' in article_node else None 105 | }) 106 | return articles 107 | 108 | def get_amendments(self, node): 109 | amendments = [] 110 | amendment_nodes = filter_nodes(node, lambda n: n['type'] == tree.TYPE_AMENDMENT) 111 | for amendment_node in amendment_nodes: 112 | amendments.append({ 113 | 'id': amendment_node['id'], 114 | 'content': amendment_node['content'], 115 | 'commits': self.get_commits(amendment_node), 116 | 'signatories': amendment_node['signatories'], 117 | 'description': amendment_node['description'], 118 | }) 119 | return amendments 120 | 121 | def merge_dicts(self, *dict_args): 122 | """ 123 | Given any number of dicts, shallow copy and merge into a new dict, 124 | precedence goes to key value pairs in latter dicts. 125 | """ 126 | result = {} 127 | for dictionary in dict_args: 128 | result.update(dictionary) 129 | return result 130 | 131 | def visit_node(self, node): 132 | super(CreateGitBookVisitor, self).visit_node(node) 133 | 134 | if tree.is_root(node): 135 | edits = self.build_edit_matrix(node) 136 | articles = self.get_articles(node) 137 | amendments = self.get_amendments(node) 138 | modified_texts = self.get_modified_texts(edits) 139 | template_data = { 140 | 'title': self.get_book_title(node), 141 | 'url': node['url'], 142 | 'type': node['type'], 143 | 'description': node['description'], 144 | 'modified': modified_texts, 145 | 'articles': articles, 146 | 'amendments': amendments, 147 | 'tree': node, 148 | } 149 | 150 | if 'cocoricoVote' in node: 151 | template_data['cocorico_vote'] = node['cocoricoVote'] 152 | 153 | template.template_file( 154 | 'gitbook/book.json.j2', 155 | template_data, 156 | os.path.join(self.tmp_dir, 'book.json') 157 | ) 158 | template.template_file( 159 | 'gitbook/styles/website.css.j2', 160 | template_data, 161 | os.path.join(self.tmp_dir, 'styles/website.css') 162 | ) 163 | template.template_file( 164 | 'gitbook/SUMMARY.md.j2', 165 | template_data, 166 | os.path.join(self.tmp_dir, 'SUMMARY.md') 167 | ) 168 | template.template_file( 169 | 'gitbook/README.md.j2', 170 | template_data, 171 | os.path.join(self.tmp_dir, 'README.md') 172 | ) 173 | current_article = 0 174 | for article in articles: 175 | template.template_file( 176 | 'gitbook/article.md.j2', 177 | self.merge_dicts(template_data, {'current_article': current_article}), 178 | os.path.join(self.tmp_dir, 'article-' + str(article['order']) + '.md') 179 | ) 180 | current_article += 1 181 | 182 | current_amendment = 0 183 | for amendment in amendments: 184 | template.template_file( 185 | 'gitbook/amendment.md.j2', 186 | self.merge_dicts(template_data, {'current_amendment': current_amendment}), 187 | os.path.join(self.tmp_dir, 'amendment-' + str(amendment['id']) + '.md') 188 | ) 189 | current_amendment += 1 190 | 191 | current_article = 0 192 | current_law = 0 193 | for modified in modified_texts: 194 | template.template_file( 195 | 'gitbook/law.md.j2', 196 | self.merge_dicts(template_data, { 197 | 'current_law': current_law, 198 | }), 199 | os.path.join(self.tmp_dir, modified['law'] + '.md') 200 | ) 201 | for article in modified['articles']: 202 | template.template_file( 203 | 'gitbook/text.md.j2', 204 | self.merge_dicts(template_data, { 205 | 'current_law': current_law, 206 | 'current_article': current_article 207 | }), 208 | os.path.join(self.tmp_dir, modified['law'] + '-' + article['id'] + '.md') 209 | ) 210 | current_article += 1 211 | current_law += 1 212 | 213 | if 'html' in self.formats: 214 | self.cmd('gitbook install') 215 | self.cmd('gitbook build') 216 | 217 | if 'markdown' in self.formats: 218 | copy_tree(self.tmp_dir, self.gitbook_dir) 219 | else: 220 | copy_tree(os.path.join(self.tmp_dir, '_book'), self.gitbook_dir) 221 | else: 222 | copy_tree(self.tmp_dir, self.gitbook_dir) 223 | 224 | def cmd(self, command): 225 | process = subprocess.Popen( 226 | command, 227 | cwd=self.tmp_dir, 228 | shell=True, 229 | stdout=subprocess.PIPE, 230 | stdin=subprocess.PIPE, 231 | stderr=subprocess.PIPE 232 | ) 233 | return process.communicate() 234 | 235 | def get_book_title(self, root_node): 236 | title = '' 237 | 238 | if root_node['type'] == tree.TYPE_LAW_PROJECT: 239 | title = 'Projet De Loi' 240 | elif root_node['type'] == tree.TYPE_LAW_PROPOSAL: 241 | title = 'Proposition De Loi' 242 | 243 | if 'id' in root_node: 244 | title += u' N°' + str(root_node['id']) 245 | if 'legislature' in root_node: 246 | title += ', ' + str(root_node['legislature']) + u'ème législature' 247 | return title 248 | 249 | def patch(self, original, unified_diff): 250 | fd, filename = input_file = tempfile.mkstemp() 251 | os.write(fd, original.encode('utf-8')) 252 | process = subprocess.Popen( 253 | 'patch -r - -p0 --output=- ' + filename, 254 | shell=True, 255 | stdout=subprocess.PIPE, 256 | stdin=subprocess.PIPE, 257 | stderr=subprocess.PIPE 258 | ) 259 | out, err = process.communicate(input=unified_diff.encode('utf-8') + '\n') 260 | return ''.join(out).decode('utf-8') 261 | 262 | def get_deep_link(self, nodes): 263 | href = [] 264 | title = [] 265 | for node in nodes: 266 | if node['type'] == tree.TYPE_LAW_REFERENCE: 267 | title.append(u'Loi N°' + node['id']) 268 | href.append(node['id']) 269 | elif node['type'] == tree.TYPE_BILL_ARTICLE: 270 | title.append(u'Article ' + str(node['order'])) 271 | href.append(u'article-' + str(node['order']) + '.md#article-' + str(node['order'])) 272 | elif node['type'] == tree.TYPE_AMENDMENT: 273 | title.append(u'Amendment ' + node['id']) 274 | href.append(u'amendment-' + node['id'] + '.md#amendment-' + node['id']) 275 | elif node['type'] == tree.TYPE_ARTICLE_REFERENCE: 276 | title.append(u'Article ' + node['id']) 277 | href.append(node['id'] + '.md') 278 | elif node['type'] == tree.TYPE_HEADER1: 279 | title.append(int_to_roman(node['order'])) 280 | href.append(int_to_roman(node['order'])) 281 | elif node['type'] == tree.TYPE_HEADER2: 282 | title.append(unicode(node['order']) + u'°') 283 | href.append(str(node['order']) + u'°') 284 | elif ancestor['type'] == tree.TYPE_HEADER3: 285 | title.append(unicode(chr(ord('a') + ancestor['order'])) + u')') 286 | href.append(unicode(chr(ord('a') + ancestor['order'])) + u')') 287 | return (', '.join(title), '-'.join(href)) 288 | 289 | def get_edit_target_nodes(self, node): 290 | nodes = [] 291 | 292 | if tree.is_reference(node): 293 | nodes.append(node) 294 | 295 | nodes += filter( 296 | lambda n: tree.is_reference(n), 297 | get_node_ancestors(node) 298 | ) 299 | 300 | return sorted( 301 | nodes, 302 | key=lambda n: tree.TYPE_REFERENCE.index(n['type']) 303 | ) 304 | 305 | def get_edit_source_nodes(self, node): 306 | edit_source_types = [ 307 | tree.TYPE_AMENDMENT, 308 | tree.TYPE_BILL_ARTICLE, 309 | tree.TYPE_HEADER1, 310 | tree.TYPE_HEADER2, 311 | tree.TYPE_HEADER3, 312 | ] 313 | 314 | return sorted( 315 | filter( 316 | lambda n: 'type' in n and n['type'] in edit_source_types, 317 | get_node_ancestors(node) 318 | ), 319 | key=lambda n: edit_source_types.index(n['type']) 320 | ) 321 | 322 | def get_original_content(self, ref): 323 | if ref['type'] == tree.TYPE_BILL_ARTICLE_REFERENCE: 324 | bill_article = tree.filter_nodes( 325 | tree.get_root(ref), 326 | lambda n: n['type'] == tree.TYPE_BILL_ARTICLE and n['order'] == ref['order'] 327 | ) 328 | if len(bill_article) == 1: 329 | return bill_article[0]['content'] 330 | elif ref['type'] == tree.TYPE_ARTICLE_REFERENCE: 331 | f = open(ref['filename'], 'r') 332 | text = f.read().decode('utf-8') 333 | f.close() 334 | return text 335 | 336 | def get_modified_texts(self, edits): 337 | modified = [] 338 | edits = edits[tree.TYPE_BILL_ARTICLE] 339 | law_ids = set([i[0] for i in edits.keys()]) 340 | for law_id in law_ids: 341 | law_edits = {k: v for k, v in edits.iteritems() if k[0] == law_id} 342 | articles = [] 343 | for k, v in edits.iteritems(): 344 | law_ref = filter_nodes(v[0][-1], lambda n: n['type'] in [tree.TYPE_LAW_REFERENCE, tree.TYPE_CODE_REFERENCE] and n['id'] == k[0])[0] 345 | article_ref = filter_nodes(law_ref, lambda n: n['type'] == tree.TYPE_ARTICLE_REFERENCE and n['id'] == k[1])[0] 346 | 347 | original_text = self.get_original_content(article_ref) 348 | text = original_text 349 | 350 | commits = [] 351 | for edit_source in v: 352 | title, href = self.get_deep_link(edit_source) 353 | commits.append({'title': title, 'link': href}) 354 | edit_refs = filter_nodes(edit_source[-1], lambda n: n['type'] == tree.TYPE_EDIT) 355 | for edit_ref in edit_refs: 356 | if 'diff' in edit_ref: 357 | text = self.patch(text, edit_ref['diff']) 358 | article = { 359 | 'id': k[1], 360 | 'diff': diff.make_html_rich_diff(original_text, text), 361 | 'commits': commits 362 | } 363 | if 'gitlabHistory' in article_ref: 364 | article['gitlabHistory'] = article_ref['gitlabHistory'] 365 | if 'githubHistory' in article_ref: 366 | article['githubHistory'] = article_ref['githubHistory'] 367 | articles.append(article) 368 | articles = sorted(articles, key=lambda x: x['id'].replace('-', ' ')) 369 | modified.append({'law': law_id, 'articles': articles}) 370 | return modified 371 | 372 | def build_edit_matrix(self, node): 373 | edits = { 374 | tree.TYPE_BILL_ARTICLE: {}, 375 | tree.TYPE_AMENDMENT: {}, 376 | } 377 | 378 | # fetch bill articles targeting law articles 379 | self.build_edit_matrix_for_types( 380 | node, 381 | edits[tree.TYPE_BILL_ARTICLE], 382 | [tree.TYPE_BILL_ARTICLE], 383 | [tree.TYPE_ARTICLE_REFERENCE], 384 | [tree.TYPE_LAW_REFERENCE, tree.TYPE_CODE_REFERENCE] 385 | ) 386 | self.build_edit_matrix_for_types( 387 | node, 388 | edits[tree.TYPE_AMENDMENT], 389 | [tree.TYPE_AMENDMENT], 390 | [tree.TYPE_ARTICLE_REFERENCE], 391 | [tree.TYPE_LAW_REFERENCE, tree.TYPE_CODE_REFERENCE] 392 | ) 393 | 394 | # fetch amendments targeting bill articles 395 | # self.build_edit_matrix_for_types( 396 | # node, 397 | # edits, 398 | # [tree.TYPE_AMENDMENT], 399 | # [tree.TYPE_BILL_ARTICLE_REFERENCE], 400 | # None 401 | # ) 402 | 403 | return edits 404 | 405 | def build_edit_matrix_for_types(self, node, edits, source_type, target_type, repo_types): 406 | article_refs = [] 407 | sources = filter_nodes( 408 | node, 409 | lambda n: 'type' in n and n['type'] in source_type 410 | ) 411 | for source in sources: 412 | article_refs += filter_nodes( 413 | source, 414 | lambda n: 'type' in n and n['type'] in target_type 415 | ) 416 | for article_ref in article_refs: 417 | repo_refs = filter( 418 | lambda n: 'type' in n and n['type'] in repo_types, 419 | get_node_ancestors(article_ref) 420 | ) 421 | if len(repo_refs) != 0: 422 | key = (repo_refs[0]['id'], article_ref['id']) 423 | if key not in edits: 424 | edits[key] = [] 425 | edits[key].append(self.get_edit_source_nodes(article_ref)) 426 | -------------------------------------------------------------------------------- /sedlex/GitCommitVisitor.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | from duralex.AbstractVisitor import AbstractVisitor 4 | 5 | from duralex.alinea_parser import * 6 | 7 | import subprocess 8 | import os 9 | 10 | class GitCommitVisitor(AbstractVisitor): 11 | def __init__(self): 12 | self.repository = None 13 | self.commitMessage = None 14 | super(GitCommitVisitor, self).__init__() 15 | 16 | def visit_edit_node(self, node, post): 17 | if post: 18 | return 19 | 20 | if 'commitMessage' in node: 21 | self.commitMessage = node['commitMessage'] 22 | else: 23 | self.commitMessage = None 24 | 25 | if 'diff' in node: 26 | process = subprocess.Popen( 27 | 'patch -r - -p0 --remove-empty-files --ignore-whitespace', 28 | shell=True, 29 | stdout=subprocess.PIPE, 30 | stdin=subprocess.PIPE, 31 | stderr=subprocess.PIPE 32 | ) 33 | out, err = process.communicate(input=node['diff'].encode('utf-8') + '\n') 34 | 35 | def visit_article_reference_node(self, node, post): 36 | if post: 37 | return 38 | 39 | if self.commitMessage and self.repository: 40 | process = subprocess.Popen( 41 | [ 42 | 'git', 43 | '-C', self.repository, 44 | 'commit', 45 | os.path.basename(node['filename']), 46 | '-m', self.commitMessage, 47 | '--author="SedLex "' 48 | ], 49 | # shell=True, 50 | stdout=subprocess.PIPE, 51 | stderr=subprocess.PIPE, 52 | universal_newlines=True 53 | ) 54 | out, err = process.communicate() 55 | 56 | def visit_node(self, node): 57 | if 'repository' in node: 58 | self.repository = node['repository'] 59 | 60 | super(GitCommitVisitor, self).visit_node(node) 61 | -------------------------------------------------------------------------------- /sedlex/GitPushVisitor.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | from duralex.AbstractVisitor import AbstractVisitor 4 | 5 | import subprocess 6 | import os 7 | 8 | class GitPushVisitor(AbstractVisitor): 9 | 10 | def __init__(self): 11 | self.repositories = [] 12 | super(GitPushVisitor, self).__init__() 13 | 14 | def visit_node(self, node): 15 | if 'repository' in node: 16 | self.repositories.append(node['repository']) 17 | 18 | super(GitPushVisitor, self).visit_node(node) 19 | 20 | if 'parent' not in node: 21 | for repository in self.repositories: 22 | process = subprocess.Popen( 23 | [ 24 | 'git', 25 | '-C', repository, 26 | 'push', '--all', 'origin' 27 | ], 28 | stdout=subprocess.PIPE, 29 | stderr=subprocess.PIPE, 30 | universal_newlines=True 31 | ) 32 | out, err = process.communicate() 33 | -------------------------------------------------------------------------------- /sedlex/InitializeGitRepositoryVisitor.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | from duralex.AbstractVisitor import AbstractVisitor 4 | 5 | import duralex.tree 6 | 7 | from . import template 8 | 9 | import subprocess 10 | import os 11 | import json 12 | import tempfile 13 | 14 | class InitializeGitRepositoryVisitor(AbstractVisitor): 15 | def __init__(self, args): 16 | self.repository = args.repository 17 | self.github_repository = args.github_repository 18 | self.num_subtrees = 0 19 | self.rev_date = None 20 | 21 | super(InitializeGitRepositoryVisitor, self).__init__() 22 | 23 | def repository_is_initialized(self): 24 | return os.path.isdir(os.path.join(self.repository, '.git')) 25 | 26 | def initialize_repository(self, node): 27 | if not self.repository_is_initialized(): 28 | self.git('init') 29 | if self.github_repository: 30 | self.git('remote add github ' + self.github_repository) 31 | files = template.template_dir( 32 | 'git', 33 | { 34 | 'url': node['url'] 35 | }, 36 | self.repository 37 | ) 38 | self.git('add ' + ' '.join(files).replace(self.repository + '/', '')) 39 | self.git('commit -m "Initialisation du projet de loi." --author "SedLex "') 40 | # The "debug" branch will be used to store debug files with stdin, stdout, argv... 41 | self.git('branch debug') 42 | # The "pages" branch will be used to store the static HTML files for GitHub pages. 43 | self.git('branch gh-pages') 44 | 45 | def visit_node(self, node): 46 | if duralex.tree.is_root(node): 47 | self.rev_date = node['date'] 48 | if not os.path.isdir(self.repository): 49 | os.mkdir(self.repository) 50 | if not self.repository_is_initialized(): 51 | self.initialize_repository(node) 52 | 53 | super(InitializeGitRepositoryVisitor, self).visit_node(node) 54 | 55 | def visit_code_reference_node(self, node, post): 56 | if post: 57 | return 58 | 59 | if os.path.isdir(os.path.join(self.repository, node['id'])): 60 | return 61 | 62 | self.git_subtree( 63 | 'https://github.com/Assemblee-Citoyenne/' + node['id'], 64 | node['id'], 65 | u'Ajout du ' + node['id'] + '.' 66 | ) 67 | 68 | def visit_law_reference_node(self, node, post): 69 | if post: 70 | return 71 | 72 | slug = 'loi_' + node['id'] 73 | 74 | if os.path.isdir(os.path.join(self.repository, slug)): 75 | return 76 | 77 | self.git_subtree( 78 | 'https://github.com/Assemblee-Citoyenne/' + slug, 79 | slug, 80 | u'Ajout de la loi N°' + node['id'] + '.' 81 | ) 82 | 83 | def visit_bill_article_node(self, node, post): 84 | if not post: 85 | return 86 | 87 | git_filename = u'Article_' + unicode(node['order']) + u'.md' 88 | 89 | node['filename'] = os.path.join(self.repository, git_filename) 90 | article_file = open(node['filename'], 'w') 91 | article_file.write(node['content'].replace('\n', '\n\n').encode('utf-8')) 92 | article_file.truncate() 93 | article_file.close() 94 | 95 | self.git('add ' + git_filename) 96 | self.git( 97 | 'commit ' + git_filename 98 | + ' -m "Ajout de l\'article ' + unicode(node['order']) + '."' 99 | + ' --author "SedLex "' 100 | ) 101 | 102 | # https://stackoverflow.com/questions/33855701/git-read-tree-removed-all-the-history#33856740 103 | def git_subtree(self, repo, prefix, message): 104 | self.git('remote add ' + prefix + ' ' + repo) 105 | self.git('fetch ' + prefix) 106 | rev_hash, err, rc = self.git('rev-list -n1 --before=' + self.rev_date + ' ' + prefix + '/master') 107 | rev_hash = rev_hash.strip() 108 | self.git('branch ' + prefix + ' ' + rev_hash) 109 | self.git('merge -sours --no-commit --allow-unrelated-histories --squash ' + prefix) 110 | self.git('read-tree --prefix=' + prefix + ' -u ' + prefix) 111 | self.git('commit -m "' + message + '" --author="SedLex "') 112 | # self.git('branch -d ' + prefix) 113 | 114 | def git(self, command, path=None): 115 | # print('git ' + command) 116 | process = subprocess.Popen( 117 | 'git ' + command, 118 | cwd=path or self.repository, 119 | shell=True, 120 | stdout=subprocess.PIPE, 121 | stdin=subprocess.PIPE, 122 | stderr=subprocess.PIPE 123 | ) 124 | out, err = process.communicate() 125 | return out, err, process.returncode 126 | -------------------------------------------------------------------------------- /sedlex/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Legilibre/SedLex/8838a6687d64ef3cb5c8515883e4a28d3eb39532/sedlex/__init__.py -------------------------------------------------------------------------------- /sedlex/diff.py: -------------------------------------------------------------------------------- 1 | import difflib 2 | 3 | def make_html_rich_diff(a, b, filename = None): 4 | html = ['
'] 5 | if filename: 6 | html.append('
' + filename + '
') 7 | 8 | a = a.splitlines() if a != '' else [] 9 | b = b.splitlines() if b != '' else [] 10 | 11 | html.append('
') 12 | for i in range(0, max(len(a), len(b))): 13 | line_a = a[i] if i < len(a) else '' 14 | line_b = b[i] if i < len(b) else '' 15 | s = difflib.SequenceMatcher(a=line_a, b=line_b) 16 | ops = s.get_opcodes() 17 | changed = False 18 | for op in ops: 19 | if op[0] == 'equal': 20 | html.append('' + line_a[op[1]:op[2]] + '') 21 | elif op[0] == 'delete': 22 | html.append( 23 | '' 24 | + line_a[op[1]:op[2]] + line_b[op[3]:op[4]] 25 | + '' 26 | ) 27 | changed = True 28 | elif op[0] == 'insert': 29 | html.append( 30 | '' 31 | + line_a[op[1]:op[2]] + line_b[op[3]:op[4]] 32 | + '' 33 | ) 34 | changed = True 35 | elif op[0] == 'replace': 36 | html.append( 37 | '' 38 | + line_a[op[1]:op[2]] 39 | + '' 40 | ) 41 | html.append( 42 | '' 43 | + line_b[op[3]:op[4]] 44 | + '' 45 | ) 46 | changed = True 47 | # html.append(tag + content + '') 48 | html.append('
') 49 | html.append('
') 50 | return ''.join(html)#.encode('utf-8') 51 | -------------------------------------------------------------------------------- /sedlex/template/__init__.py: -------------------------------------------------------------------------------- 1 | import jinja2 2 | import os 3 | import shutil 4 | 5 | _ROOT = os.path.abspath(os.path.dirname(__file__)) 6 | 7 | def template_string(template, values): 8 | template = os.path.join(_ROOT, template) 9 | f = open(template, 'r') 10 | e = jinja2.Environment( 11 | loader=jinja2.FileSystemLoader(os.path.dirname(template)) 12 | ) 13 | t = e.from_string(f.read().decode('utf-8')) 14 | f.close() 15 | 16 | return t.render(values) 17 | 18 | def template_file(template, values, out): 19 | template = os.path.join(_ROOT, template) 20 | r = template_string(template, values) 21 | 22 | path = os.path.dirname(out) 23 | if not os.path.exists(path): 24 | os.makedirs(path) 25 | f = open(out, 'w') 26 | f.write(r.encode('utf-8') + "\n") 27 | f.truncate() 28 | f.close() 29 | 30 | def template_dir(dir, values, out): 31 | dir = os.path.join(_ROOT, dir) 32 | templated_files = [] 33 | for root, dirs, files in os.walk(dir): 34 | for name in files: 35 | path = os.path.join(root, name) 36 | out_path = out + path.replace(dir, '') 37 | out_dir = os.path.dirname(out_path) 38 | if not os.path.exists(out_dir): 39 | os.makedirs(out_dir) 40 | if name.endswith(".j2"): 41 | out_path = out_path.replace('.j2', '') 42 | template_file(path, values, out_path) 43 | else: 44 | if os.path.exists(out_path): 45 | os.remove(out_path) 46 | shutil.copy(path, out_path) 47 | templated_files.append(out_path) 48 | return templated_files 49 | -------------------------------------------------------------------------------- /sedlex/template/git/.travis.yml: -------------------------------------------------------------------------------- 1 | sudo: required 2 | dist: trusty 3 | language: python 4 | 5 | install: 6 | - pip install ansible 7 | - ansible-galaxy install -r requirements.yml 8 | 9 | script: 10 | - ansible-playbook -i "localhost," -c local provision.yml 11 | -------------------------------------------------------------------------------- /sedlex/template/git/provisioning/provision.yml.j2: -------------------------------------------------------------------------------- 1 | --- 2 | 3 | - hosts: localhost 4 | vars: 5 | duralex_project_url: "{{ url }}" 6 | project_repository: "{{ '{{' }} playbook_dir | dirname {{ '}}' }}" 7 | roles: 8 | - { role: geerlingguy.git } 9 | - { role: bobbyrenwick.pip } 10 | - { role: geerlingguy.nodejs, nodejs_version: "7.x", nodejs_npm_global_packages: gitbook-cli } 11 | - { role: duralex-sedlex } 12 | - { role: pages } 13 | -------------------------------------------------------------------------------- /sedlex/template/git/provisioning/requirements.yml: -------------------------------------------------------------------------------- 1 | --- 2 | 3 | - src: geerlingguy.git 4 | version: 1.4.0 5 | 6 | - src: bobbyrenwick.pip 7 | version: v2.1.1 8 | 9 | - src: geerlingguy.nodejs 10 | version: 4.1.1 11 | -------------------------------------------------------------------------------- /sedlex/template/git/provisioning/roles/duralex-sedlex/tasks/main.yml: -------------------------------------------------------------------------------- 1 | --- 2 | 3 | - name: Install DuraLex. 4 | pip: 5 | name: git+git://github.com/Legilibre/DuraLex.git#egg=duralex 6 | state: present 7 | 8 | - name: Install SedLex. 9 | pip: 10 | name: git+git://github.com/Legilibre/SedLex.git#egg=sedlex 11 | state: present 12 | 13 | - name: Fetch DuraLex data. 14 | shell: duralex --url "{{ duralex_project_url }}" > /tmp/duralex.json 15 | -------------------------------------------------------------------------------- /sedlex/template/git/provisioning/roles/pages/tasks/main.yml: -------------------------------------------------------------------------------- 1 | --- 2 | 3 | - name: Generate HTML pages. 4 | shell: cat /tmp/duralex.json | sedlex --gitbook --gitbook-format html --repository {{ project_repository }} 5 | -------------------------------------------------------------------------------- /sedlex/template/gitbook/README.md.j2: -------------------------------------------------------------------------------- 1 | {%- import 'html.j2' as html -%} 2 | 3 | # {{ html.icon('university" aria-hidden="true') }} {{ title | title }} 4 | 5 | {{ description[0].upper() }}{{ description[1:] }}. 6 | 7 | [{{ html.icon('external-link" aria-hidden="true') }} Texte original]({{ url }}) 8 | 9 | ## {{ html.icon('bookmark-o') }} Articles 10 | 11 | {% if type == 'law-proposal' %} 12 | La proposition de loi est constituée des articles suivants : 13 | {% elif type == 'law-project' %} 14 | Le projet de loi est constituée des articles suivants : 15 | {% endif %} 16 | 17 | {% for article in articles %} 18 | * [Article {{ article.order }}](article-{{ article.order }}.md) 19 | {%- endfor %} 20 | 21 | {% if amendments | length > 0 %} 22 | et des amendements suivants : 23 | 24 | {% for amendment in amendments %} 25 | * [Amendement {{ amendment.id }}](amendment-{{ amendment.id }}.md) 26 | {%- endfor %} 27 | 28 | {% endif %} 29 | 30 | {% if modified is defined and modified | length > 0 %} 31 | ## {{ html.icon('file-text-o') }} Textes modifiés 32 | 33 | {% if type == 'law-proposal' %} 34 | La proposition de loi modifie les textes suivants : 35 | {% elif type == 'law-project' %} 36 | Le projet de loi modifie les textes suivants : 37 | {% endif %} 38 | 39 | {% for m in modified %} 40 | * [Loi N°{{ m.law }}]({{ m.law }}.md) 41 | {%- for article in m.articles %} 42 | * [Article {{ article.id }}]({{ m.law }}-{{ article.id }}.md) 43 | {%- endfor %} 44 | {%- endfor %} 45 | 46 | {%- endif %} 47 | 48 | {% if cocorico_vote is defined %} 49 | ## Vote 50 | 51 | * [Voter](https://cocorico.cc/embed/vote-widget/{{ cocorico_vote }}) 52 | * [Résultats du vote](https://cocorico.cc/ballot-box/{{ cocorico_vote }}) 53 | {% endif %} 54 | -------------------------------------------------------------------------------- /sedlex/template/gitbook/SUMMARY.md.j2: -------------------------------------------------------------------------------- 1 | # Summary 2 | 3 | {% if type == 'law-proposal' %} 4 | ## Proposition de loi 5 | {% elif type == 'law-project' %} 6 | ## Projet de loi 7 | {% endif %} 8 | {% for article in articles %} 9 | * [Article {{ article.order }}](article-{{ article.order }}.md) 10 | {%- endfor %} 11 | 12 | {% for amendment in amendments %} 13 | ## Amendements 14 | * [Amendement {{ amendment.id }}](amendment-{{ amendment.id }}.md) 15 | {%- endfor %} 16 | 17 | {% if modified is defined and modified | length > 0 %} 18 | ## Textes modifiés 19 | {% for m in modified %} 20 | * [Loi N°{{ m.law }}]({{ m.law }}.md) 21 | {%- for article in m.articles %} 22 | * [Article {{ article.id }}]({{ m.law }}-{{ article.id }}.md) 23 | {%- endfor %} 24 | {%- endfor %} 25 | 26 | {%- endif %} 27 | 28 | {% if cocorico_vote is defined %} 29 | ## Vote 30 | 31 | * [Voter](https://cocorico.cc/embed/vote-widget/{{ cocorico_vote }}) 32 | * [Résultats du vote](https://cocorico.cc/ballot-box/{{ cocorico_vote }}) 33 | {% endif %} 34 | -------------------------------------------------------------------------------- /sedlex/template/gitbook/amendment.md.j2: -------------------------------------------------------------------------------- 1 | {%- import 'html.j2' as html -%} 2 | 3 | # {{ html.icon('bookmark-o') }} {{ title | title }}, Amendement {{ amendments[current_amendment].id }} 4 | 5 | ## {{ html.icon('lightbulb-o') }} Exposé 6 | 7 | {{ amendments[current_amendment].description }} 8 | 9 | ## {{ html.icon('file-text-o') }} Texte 10 | 11 | {{ amendments[current_amendment].content.replace('\n', '\n\n') }} 12 | 13 | ## {{ html.icon('users') }} Signataires 14 | 15 | {% for signatory in amendments[current_amendment].signatories -%} 16 | * {{ signatory.name }} 17 | {% endfor %} 18 | 19 | {% if amendments[current_amendment].commits | length %} 20 | ## {{ html.icon('pencil-square-o') }} Suivi des modifications 21 | 22 | L'amendement {{ amendments[current_amendment].order }} apporte les modifications suivantes : 23 | 24 | {% for commit in amendments[current_amendment].commits %} 25 | ### {{ commit.title }} 26 | 27 | {{ commit.description | default('') }} 28 | 29 | {{ commit.diff }} 30 | {% endfor %} 31 | 32 | {% endif %} 33 | -------------------------------------------------------------------------------- /sedlex/template/gitbook/article.md.j2: -------------------------------------------------------------------------------- 1 | {%- import 'html.j2' as html -%} 2 | 3 | # {{ html.icon('bookmark-o') }} {{ title | title }}, Article {{ articles[current_article].order }} 4 | 5 | ## {{ html.icon('file-text-o') }} Texte 6 | 7 | {{ articles[current_article].content.replace('\n', '\n\n') }} 8 | 9 | ## {{ html.icon('pencil-square-o') }} Suivi des modifications 10 | 11 | {% if articles[current_article].gitlabIssue %} 12 | [{{ html.icon('code-fork') }} Voir dans le système de gestion de versions (expert)]({{ articles[current_article].gitlabIssue }}) 13 | {% elif articles[current_article].githubIssue %} 14 | [{{ html.icon('code-fork') }} Voir dans le système de gestion de versions (expert)]({{ articles[current_article].githubIssue }}) 15 | {% endif %} 16 | 17 | {% if type == 'law-proposal' %} 18 | L'article {{ articles[current_article].order }} de la proposition de loi apporte les modifications suivantes : 19 | {% elif type == 'law-project' %} 20 | L'article {{ articles[current_article].order }} du projet de loi apporte les modifications suivantes : 21 | {% endif %} 22 | 23 | {% for commit in articles[current_article].commits %} 24 | ### {{ commit.title }} 25 | 26 | {{ commit.description | default('') }} 27 | 28 | {{ commit.diff }} 29 | {% endfor %} 30 | -------------------------------------------------------------------------------- /sedlex/template/gitbook/book.json.j2: -------------------------------------------------------------------------------- 1 | { 2 | "language": "fr", 3 | "plugins": [ 4 | "heading-anchors" 5 | ], 6 | "title": "{{ title }}" 7 | } 8 | -------------------------------------------------------------------------------- /sedlex/template/gitbook/html.j2: -------------------------------------------------------------------------------- 1 | {%- macro icon(name) -%} 2 | 3 | {%- endmacro -%} 4 | -------------------------------------------------------------------------------- /sedlex/template/gitbook/law.md.j2: -------------------------------------------------------------------------------- 1 | {%- import 'html.j2' as html -%} 2 | 3 | # {{ html.icon('balance-scale') }} Loi N°{{ modified[current_law].law }} 4 | 5 | ## {{ html.icon('pencil-square-o') }} Articles modifiés 6 | 7 | {% if type == 'law-proposal' %} 8 | La proposition de loi modifie les articles de la loi N°{{ modified[current_law].law }} suivants : 9 | {% elif type == 'law-project' %} 10 | Le projet de loi modifie les articles de la loi N°{{ modified[current_law].law }} suivants : 11 | {% endif %} 12 | 13 | {%- for article in modified[current_law].articles %} 14 | * [Article {{ article.id }}]({{ modified[current_law].law }}-{{ article.id }}.md) 15 | {%- endfor %} 16 | -------------------------------------------------------------------------------- /sedlex/template/gitbook/styles/website.css.j2: -------------------------------------------------------------------------------- 1 | .divider, 2 | .gitbook-link { 3 | display : none!important; 4 | } 5 | 6 | .diff .diff-delete { 7 | color : #a33; 8 | background : #ffeaea; 9 | text-decoration : line-through; 10 | } 11 | 12 | .diff .diff-insert { 13 | background : #eaffea; 14 | } 15 | 16 | .diff { 17 | margin-bottom : 20px; 18 | border : 1px solid rgba(0,0,0,.15); 19 | border-radius : 3px; 20 | } 21 | 22 | .diff .diff-content { 23 | padding : 10px; 24 | background : #fcfcfc; 25 | } 26 | 27 | .diff .diff-filename { 28 | padding : 10px; 29 | border-bottom : 1px solid rgba(0,0,0,.15); 30 | background : #f6f6f6; 31 | } 32 | 33 | .diff .diff-filename:before { 34 | content : "\f0f6"; 35 | padding-right : 10px; 36 | font : normal normal normal 14px/1 FontAwesome; 37 | } 38 | -------------------------------------------------------------------------------- /sedlex/template/gitbook/text.md.j2: -------------------------------------------------------------------------------- 1 | {%- import 'html.j2' as html -%} 2 | 3 | # {{ html.icon('balance-scale') }} Loi N°{{ modified[current_law].law }}, Article {{ modified[current_law].articles[current_article].id }} 4 | 5 | ## {{ html.icon('file-text-o') }} Texte 6 | 7 | {{ modified[current_law].articles[current_article].diff }} 8 | 9 | ## {{ html.icon('pencil-square-o') }} Modifications 10 | 11 | {% if modified[current_law].articles[current_article].gitlabHistory %} 12 | [{{ html.icon('code-fork') }} Voir l'historique complet de cet article (expert)]({{ modified[current_law].articles[current_article].gitlabHistory }}) 13 | {% elif modified[current_law].articles[current_article].githubHistory %} 14 | [{{ html.icon('code-fork') }} Voir l'historique complet de cet article (expert)]({{ modified[current_law].articles[current_article].githubHistory }}) 15 | {% endif %} 16 | 17 | {% if type == 'law-proposal' %} 18 | Cet article est modifié par les articles de la proposition de loi suivants : 19 | {% elif type == 'law-project' %} 20 | Cet article est modifié par les articles du projet de loi suivants : 21 | {% endif %} 22 | 23 | {%- for commit in modified[current_law].articles[current_article].commits %} 24 | * [{{ commit.title }}]({{ commit.link }}) 25 | {%- endfor %} 26 | -------------------------------------------------------------------------------- /sedlex/template/github/commit_message.j2: -------------------------------------------------------------------------------- 1 | {% if edit.commitMessage is defined -%} 2 | {{ edit.commitMessage }} 3 | {% endif -%} 4 | GitHub: {{ edit.githubIssue }} 5 | -------------------------------------------------------------------------------- /sedlex/template/github/issue_body.j2: -------------------------------------------------------------------------------- 1 | {{ article.content }} 2 | -------------------------------------------------------------------------------- /sedlex/template/github/issue_title.j2: -------------------------------------------------------------------------------- 1 | 🏛 Article {{ article.order }} 2 | -------------------------------------------------------------------------------- /sedlex/template/gitlab/commit_message.j2: -------------------------------------------------------------------------------- 1 | {% if edit.commitMessage is defined -%} 2 | {{ edit.commitMessage }} 3 | {% endif -%} 4 | GitLab: {{ edit.gitlabIssue }} 5 | -------------------------------------------------------------------------------- /sedlex/template/gitlab/issue_description.j2: -------------------------------------------------------------------------------- 1 | {{ article.content.replace('\n', '\n\n') }} 2 | -------------------------------------------------------------------------------- /sedlex/template/gitlab/issue_title.j2: -------------------------------------------------------------------------------- 1 | 🏛 Article {{ article.order }} 2 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | from setuptools import setup 2 | 3 | import os 4 | 5 | template_files = [] 6 | for root, dirs, files in os.walk('sedlex/template'): 7 | for f in files: 8 | template_files.append(os.path.join(root, f).replace('sedlex/', '')) 9 | 10 | setup( 11 | name='SedLex', 12 | version='0.1', 13 | install_requires=[ 14 | 'html5lib', 15 | 'beautifulsoup4', 16 | 'requests', 17 | 'jinja2', 18 | 'python-gitlab', 19 | 'PyGithub' 20 | ], 21 | package_dir={ 22 | 'sedlex': 'sedlex' 23 | }, 24 | package_data={ 25 | 'sedlex': template_files 26 | }, 27 | packages=[ 28 | 'sedlex' 29 | ], 30 | # data_files=[('template', template_files)], 31 | scripts=[ 32 | 'bin/sedlex' 33 | ] 34 | ) 35 | --------------------------------------------------------------------------------