├── .gitignore ├── Gemfile ├── LICENSE ├── README.md ├── archives └── .gitkeep ├── controllers ├── archiv_controller.rb ├── repotask_controller.rb ├── task_controller.rb └── tasklist_controller.rb ├── data ├── answers │ └── .gitkeep ├── repos │ └── .gitkeep └── starters │ └── .gitkeep ├── deleteme.txt ├── lib ├── date_prettifier.rb ├── help_helper.rb ├── help_repotask.rb ├── helpers.rb ├── repotask_factory.rb ├── settings_helper.rb ├── task_factory.rb └── wrapping_helper.rb ├── models ├── archiv.rb ├── lang.rb ├── repotask.rb ├── task.rb └── task_list.rb ├── revuu.rb ├── sample_data ├── .gitkeep ├── sample_archive_20181127.tar └── sample_archive_20181221.tar ├── tmp └── .gitkeep └── views ├── archiv_view.rb ├── repotask_view.rb ├── task_view.rb └── tasklist_view.rb /.gitignore: -------------------------------------------------------------------------------- 1 | tmp/* 2 | !tmp/.gitkeep 3 | node_modules/ 4 | node_modules/* 5 | \#* 6 | package-lock.json 7 | Gemfile.lock 8 | package-lock.json 9 | planning.txt 10 | planning.md 11 | repotask_planning.md 12 | talk_outline.md 13 | minitar.txt 14 | archives/*.tar 15 | !archives/.gitkeep 16 | data/eliminator.rb 17 | data/*.json 18 | data/answers/* 19 | data/starters/* 20 | data/repos/* 21 | !data/answers/.gitkeep 22 | !data/starters/.gitkeep 23 | !data/repos/.gitkeep 24 | less 25 | history 26 | nohup.out 27 | models/helpers.js 28 | *.DS_Store* 29 | color_exper.rb 30 | randomkeys.rb 31 | -------------------------------------------------------------------------------- /Gemfile: -------------------------------------------------------------------------------- 1 | source "https://rubygems.org" 2 | gem "json", "~> 2.1" 3 | gem "date", "~> 1.0" 4 | gem "chronic", "~> 0.10.2" 5 | gem "minitar", "~> 0.6.1" 6 | gem "git", "~> 1.5" 7 | gem "colorize", "~> 0.8.1" 8 | gem "minitest", "~> 5.11" 9 | gem "rake", "~> 12.3" 10 | 11 | gem "railties", "~> 5.2" 12 | 13 | gem "bootsnap", "~> 1.3" 14 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # revuu 2 | A new kind of learning tool for programming, Revuu makes it unusually easy and 3 | fun to review coding tasks. You can create practical (how-to) programming 4 | questions, auto-creating and keeping track of answer files, running your 5 | answers in-app, scheduling reviews automatically, etc. 6 | 7 | ## User introduction 8 | 9 | See https://www.youtube.com/watch?v=Mgrdg1uwDeA for the how and why of Revuu. 10 | 11 | This is the only tool we know of that makes it easy to drill your own hand-made, 12 | complex web development tasks (such as Rails tasks) repeatedly, handling all the 13 | set-up, scheduling, file naming, retrieving, opening with your text editor, 14 | opening a console at the right place, saving, git branch management, and running 15 | for you. You can focus on the coding challenge you want to learn. 16 | 17 | The basic functions of the program are adding tasks, opening the needed files 18 | with your favorite text editor, running the script and seeing the results, and 19 | recording that you've done a review and that the next review should be done on a 20 | certain date. 21 | 22 | Currently, we support Ruby, Rails, JavaScript (and Node), HTML, CSS, Python, 23 | Java, C, C++, Rust, and Bash scripting. We support not just one-file scripting 24 | tasks but also complex, directory-based tasks (which Revuu calls "repotasks"), 25 | coordinating both edits to multiple files and also with console commands. 26 | 27 | Add copious, well-chosen tags in order to be able to sort tasks. Sort tasks in 28 | different ways. Change all task dates at once. Easily import (load) and export 29 | (archive, back up, share) your data. 30 | 31 | Try it! You can experiment with some included sample data. 32 | 33 | ## Install and requirements 34 | Clone the repo (instructions should be clear enough from Github). A recent 35 | version of Ruby (>2.2) is installed. Execute `bundle install` to install the 36 | gem requirements. If you want to run a console automatically, you'll need xterm. 37 | 38 | Only tested on Ubuntu and modern Macs, but should work in any \*nix-based 39 | system. Won't work in Windows (sorry). 40 | 41 | ## Run and Use 42 | Once Ruby, the app, and the gem dependencies are installed, you should be able 43 | to start the app from the directory you installed it in just by typing `ruby revuu.rb` on the command line. 44 | 45 | Revuu ships with a bunch of pre-made questions (in the "sample data" folder) and 46 | answers by way of demonstration. Load by pressing 'a' to go to the archive 47 | system, and then 'sa' to copy the sample data. Then press 'l' to load, and 48 | choose the sample data. 49 | 50 | To learn how to use the system, press '?' for help. It's pretty easy to learn, 51 | and we have extensive help files. 52 | 53 | ## Author 54 | Larry Sanger (email is domain sanger.io, username larry) 55 | 56 | I'd love to have some detailed feedback. I've had very little so far (as of 57 | January 2019). 58 | 59 | ## Development to do list 60 | 61 | * Full text search with sorting by relevance score. 62 | * Make various archive safety improvements/clarifications. 63 | * Add statistics (number of questions, average review interval, average score, 64 | average score per language, number to do today, etc.). 65 | 66 | ## Programmer notes 67 | 68 | If Rubyists want to help out, I'd be very happy. 69 | 70 | ## Version notes 71 | 72 | ### 1.0 (September 27, 2018) 73 | First published version: 74 | 75 | Features include new tasks, list all tasks, delete task, sort by tags, and 76 | various user and programmer documentation. There are several features related 77 | to answering/reviewing tasks: saving a new review (including date and score), 78 | writing an answer using a (one supported) text editor, running the answer 79 | (using at the options of Ruby, Node.js, Java, C, Bash scripting, and text; 80 | including both compiled and interpreted languages), archiving old answers, and 81 | running old answers. From the same screen, the user can edit task instructions, 82 | tags, date of next review, and user's current score. Task, review, and settings 83 | data are all saved in JSON files. 84 | 85 | ### 1.1 (September 28, 2018) 86 | Text editor support: 87 | 88 | Added support for Atom, Eclipse, Pico, Nano, Vi, Vim, and other text editors. 89 | This checks the user's system to see which are available and shows only those. 90 | The app now checks that the settings file exists, pre-populates it with 91 | defaults if not, and makes some other improvements to settings. Also added a 92 | simple 'refresh' function for the task review and edit screen. 93 | 94 | ### 1.2 (October 1, 2018) 95 | Navigation: 96 | 97 | Added pagination and page navigation. Data about any persisted tag searches 98 | and navigation page was added as attributes to the global TaskList object. So 99 | the user can navigate to the second page of tasks, view one, quit that view, 100 | and then be placed back on the second page of tasks. If the user starts from 101 | tag search results (even the second page of them), he is returned to that page. 102 | That means users can search for one particular language (or method) without 103 | having to redo the search in between tasks. 104 | 105 | ### 1.3 (October 6, 2018) 106 | Lots of little improvements: 107 | 108 | Automatically inserts language name and variants into tag list. Similarly, 109 | inserts language name in parentheses before the page title, not in the data, 110 | but when the task is rendered to the user. 'x' command shows the "next due" 111 | task to the user. Let user abandon task instead of inputting instructions or 112 | tags. Changed 'Node.js' to 'JavaScript'. Fixed several bugs; now pretty 113 | stable, but badly needs refactoring; started adding notes for doing that. 114 | Now, when a task list is the result of filtering, there is a green message 115 | at the top of the list saying "Filtered by {language name}". Moved gems to 116 | Gemfile and required them via `Bundler.require(:default)`. 117 | 118 | ### 2.0 (October 10, 2018) 119 | Refactoring and instructions: 120 | 121 | The biggest change that justifies the major version number change is that 122 | the code has been completely rearranged into /models, /controllers, and 123 | /views folders, on analogy with web-based MVC development. There is still 124 | quite a bit of refactoring to do, but this is a big enough change to warrant 125 | the new number. In addition, there is now a large, detailed help system 126 | accessible from both task list and task views. There are also a number of 127 | smaller improvements. 128 | 129 | ### 2.1 (October 15, 2018) 130 | Added spaced repetition and refactored with Lang class: 131 | 132 | Added spaced repetition method (which semi-intelligently suggests a next date 133 | for review). Along with other refactoring, surgically extracted the 134 | language-related methods and structures and placed them carefully within a 135 | brand new Lang class. Consequently, user can now change default language, and 136 | it is now a real default. Stopped calling many accessor methods on named 137 | objects in favor of just using instance variables, after confirming that 138 | controllers and views are adequately self-contained; hence the analogy to MVC 139 | code structure is almost complete. Fixed bugs including a problem with the 140 | "date prettifier." 141 | 142 | ### 2.2 (October 18, 2018) 143 | Added starter code and Python: 144 | 145 | Code that a task writer wants the user to use in solving a problem is dubbed 146 | "starter code"; this code was included in the task instructions, but has now 147 | been separated out, so the user doesn't have to copy and paste it from the 148 | question. Also, added Python support. Fixed various bugs, especially a tag bug. 149 | 150 | ### 2.3 (October 26, 2018) 151 | Archive system and autowrap: 152 | 153 | Added fully-functional data archive system with full CRUD functionality, such 154 | as creating new tarballs, loading old ones, showing them, and deleting them. 155 | I make my data available via a new `sample_data/` folder that won't interfere 156 | with your data, if and when you want to pull down the latest, greatest version. 157 | Autowrap overwide text fields and tags (without autowrapping code, hopefully); 158 | debugged this. Made introductory video to get people using Revuu! Moved 159 | `answers/` to `data/answers` (so all data is in the same place now) and renamed 160 | `data/revuu.json` to `data/tasks.json` (so now all data is ready to copy in one 161 | folder). Prepared codebase for clean start (and safe `git pull`ing) by cleaning 162 | out the content of `data/` and encouraging user to use sample data. Also, 163 | experimentally changed (shortened) the spaced repetition intervals, since they 164 | had been too long for me. 165 | 166 | ### 2.4 (November 1, 2018) 167 | Misc bug fixes and improvements: 168 | 169 | Adjusted spaced repetition intervals again. Cleaned up datafile (`tasks.json`), 170 | which had been needlessly saving calculated attributes, reducing file size by 171 | 22%. Improvements to UX when adding tasks (allowing user to quit). Finally 172 | fixed three bugs with the wrapping method. Added time to the last reviewed 173 | date. Added # of tags to task view screen. Since my task IDs have entered three 174 | digits, I hid them and replaced them with 0-9 in the task list view. 175 | 176 | ### 2.5 (November 8, 2018) 177 | Refactored TaskList and new TaskFactory: 178 | 179 | Started major refactoring in preparation for the big "directory-based tasks" 180 | feature. Moved main dispatch table to class `TaskList`; removed `$tasks` 181 | references from within `TaskList` class and modules; included 182 | `TasklistController` and `TasklistView` in `TaskList` class; removed global 183 | inclusion from revuu.rb. Fixed very bad (inadvertantly deleted tasks!) bug 184 | introduced when switching to 0-9 in task list view. Thoroughly refactored 185 | `revuu.rb`, settings methods (now located in settings_helper.rb), and added 186 | edge case logic for missing settings. Also refactored `TaskList` class and 187 | both modules, fixing bugs, thereby loading the tasklist instantly (as before), 188 | making the tasklist UX more consistent, etc. Consolidated `Task` class methods, 189 | as well as all methods used in creating new tasks, in a brand new 190 | `task_factory.rb` helper); also, refactored all task-creation methods. 191 | 192 | ### 3.0 (November 13, 2018) 193 | Finished big refactoring of Task and TaskList classes: 194 | 195 | Finished refactoring class `Task`. Renamed `helpers/` to `lib/`. Included 196 | `TaskController` and `TaskView` in class `Task`, so they're no longer globals. 197 | Fixed bugs and rendered UX more consistent. Should be ready to start work on 198 | directory-based tasks! 199 | 200 | ### 3.1 (November 19, 2018) 201 | Added Repotasks: 202 | 203 | Big update. Introduced the rather massive new Repotask feature. Created 204 | RepotaskFactory, the model, controller, and view files for Repotasks, and in 205 | general made it possible to make questions based on entire directory-based 206 | repositories, and git branches thereof. Also made instructions for repotask 207 | system. Fixed various bugs; there are probably still a few, but the new 208 | feature is pretty stable. 209 | 210 | ### 3.2 (November 23, 2018) 211 | Colorize and migrate files to deep locations: 212 | 213 | Added color-coding of languages. Added HTML, CSS, C++, and Rust. Moved answers, 214 | old answers, and starter code into sub-sub-etc.-folders that support up to 215 | 100,000 different tasks in the same collection. Changed the logic to create 216 | these new folders as needed and locate the files where they are buried deep. 217 | Created a data migration script for people who have existing data; this was 218 | extensively tested and should work flawlessly (worked flawlessly for me) behind 219 | the scenes. Replaced Colorize gem (with the help of our first pull request, 220 | thanks to githubcyclist!) with a few methods now at the end of `helpers.rb`. 221 | Squashed many bugs associated with all these changes; few left. 222 | 223 | ### 3.3 (November 29, 2018) 224 | Review history, view/run old repotask code, new video: 225 | 226 | Added review history, making it easy to find tasks you reviewed recently. 227 | Added the ability to view and run old, archived repotask code--very complex. 228 | Deciding it was easy to support less colorful terminals, I made the code use 229 | the more limited Colorize gem (which I had briefly removed) for terminals of 230 | which `$COLORTERM` != 'truecolor'. Let user review deleted task before deleting. 231 | Made and uploaded new helper video: https://www.youtube.com/watch?v=Mgrdg1uwDeA 232 | 233 | ### 3.4 (December 15, 2018) 234 | Improved sorting and searching: 235 | 236 | Added sorting of tasks by ID (date added) and average score. Display history of 237 | reviews (in task view). Allowed partial (and regex) search of tags. Added 238 | Bootstrap to supported tech. Small bug fixes. 239 | 240 | ### 3.5 (January 6, 2019) 241 | Server running support and auto-advance: 242 | 243 | In this extensive update, incredibly (to Revuu's author), a major bug was fixed. 244 | Now the user can run Sinatra servers from within Revuu. This is a major step 245 | toward enabling spaced repetition review of questions about complex web 246 | frameworks--enabling the user to efficiently drill harder methods while Revuu 247 | handles the complex setup. Be sure to add 248 | 249 | BUNDLE_GEMFILE='./Gemfile' && 250 | 251 | before the `ruby ` Sinatra command. (Still need to update help 252 | file with these instructions.) 253 | 254 | Also we now automatically move the user to the next question to review (after 255 | prompt) after recording a review; also, add an 'x' shortcut to do that directly. 256 | Added search/sort for tasks without tags (other than default tags); type 257 | 'notags'. Added simple fix to end-of-year "unknown" date bug. We also added 258 | functionality to ensure that spaced repetition recommendations do not cluster 259 | together on any one day (if there's a cluster building, they fall to one side or 260 | the other depending on which days have the fewest). 261 | 262 | ### 3.6 (January 22, 2019) 263 | Added Rails, open terminal, and "change dates" feature: 264 | 265 | We can now say that it is possible to add Rails repotasks. All Bash commands are 266 | now to be typed in by the user in a special xterm console that pops up when the 267 | user types 'co' (although you can still use "commands to run" if you like). The 268 | console opens in the correct repo directory, at the correct branch, and reset 269 | with the correct environment. Also added "change dates" feature, which edits all 270 | task review dates by a day offset. Now, if you get behind, you can use this 271 | feature to catch yourself up. 272 | 273 | ### 3.7 274 | 275 | Add option to open terminal in all regular tasks (not just repotasks). 276 | -------------------------------------------------------------------------------- /archives/.gitkeep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/globewalldesk/revuu/7f118434e12a96c8165c32748323c55402f5224a/archives/.gitkeep -------------------------------------------------------------------------------- /controllers/archiv_controller.rb: -------------------------------------------------------------------------------- 1 | module ArchivController 2 | # Wrapper look for Archive-related commands. 3 | def archive_loop 4 | command = nil 5 | until command == 'q' 6 | command = get_user_command('a') 7 | dispatch_table(command) 8 | end 9 | end 10 | 11 | def dispatch_table(command) 12 | case command 13 | when 'c' 14 | archive = Archiv.new # Since no argument, a name is created for 'archive'. 15 | archive.create_archive # Uses the new name. 16 | when 'l' 17 | choose_archive_and_load 18 | when 's' 19 | display_archives; puts ''; 20 | when 'd' 21 | delete_archive 22 | when 'f' 23 | welcome_to_archive 24 | when 'sa' 25 | copy_sample_data 26 | when 'help', '?' 27 | launch_instructions_system 28 | welcome_to_archive 29 | when 'q' 30 | return 31 | else 32 | puts 'Huh?' 33 | end 34 | end 35 | 36 | def choose_archive_and_load 37 | # User must choose one of the existing archives to load. 38 | archive_name = choose_archive 39 | # Backup existing data, if it exists; then delete; then unpack named archive; 40 | # then copy unpacked directories and files into data/. 41 | if archive_name 42 | archive = Archiv.new(archive: archive_name) # With argument, a name is saved. 43 | msg = archive.load_archive 44 | puts "Nothing new loaded; escaping." if msg == nil 45 | else 46 | puts "Escaping; didn't load anything.\n\n" 47 | end 48 | end 49 | 50 | def load_archive 51 | unless $tasks.list.empty? 52 | puts "\nDo you want to save an archive of the currently-loaded data first?" 53 | puts "\nNOTE! Be sure before proceeding. Don't overwrite new data with old!" 54 | puts "NOTE!! The currently-loaded data does have unsaved changes." if $unsaved_changes 55 | puts '' 56 | save_first = nil 57 | until save_first && (save_first == '' || 'ynq'.include?(save_first) ) 58 | puts "Press for [y], [n], or [q]uit (escape)." 59 | save_first = get_user_command("l") 60 | end 61 | return nil if save_first == 'q' 62 | if save_first == '' || save_first == 'y' 63 | Archiv.new(archive: affix_date_and_ext('')).create_archive # Does as it tells the user... 64 | end 65 | end 66 | system('rm -rf data/') 67 | puts "Unpacking archive..." 68 | # Actually copy from zip file to data folder, reconstructing the data folder! 69 | Minitar.unpack(self.archive, "./") 70 | # Reload the goods, just as App.new does. But REFACTORING PROBLEM: do I really 71 | # want to be calling #new here? 72 | puts "Done! Quit the archive system to see the newly-loaded archive." 73 | return true # indicating to #choose_archive_and_load that loading went fine. 74 | end 75 | 76 | def delete_archive 77 | # Show archives and solicit number. 78 | puts "OK, ready to delete. Choose wisely!" 79 | archive_name = choose_archive 80 | puts "Escaping without deleting." unless archive_name 81 | begin 82 | # Delete that archive. 83 | system("rm #{archive_name}") 84 | rescue "Couldn't delete, for some reason." 85 | ensure 86 | display_archives 87 | puts '' 88 | end 89 | end 90 | 91 | def copy_sample_data 92 | puts "\nThis simple function just makes a sample data set available in your" 93 | puts "list of archives. It's already done: " 94 | system('cp sample_data/* archives/') 95 | display_archives 96 | puts "You can now [l]oad this data and check it out.\n\n" 97 | end 98 | 99 | end 100 | -------------------------------------------------------------------------------- /controllers/repotask_controller.rb: -------------------------------------------------------------------------------- 1 | module RepotaskController 2 | 3 | # Launches repotask display for user and prompts for input (e.g., open files, 4 | # save review, run answer, edit instructions, etc.). 5 | def launch_repotask_interface 6 | display_info # Different display from class Task. 7 | command = '' 8 | until command == 'q' or $auto_next 9 | command = get_user_command('+').downcase 10 | # Dispatch table returns command, which in at least one case might be 11 | # changed by the dispatch table. 12 | command = process_repotask_input(command) 13 | end 14 | nil # No tasklist dispatch table message. 15 | end 16 | 17 | # Given a user command in the Repotask view, dispatch as appropriate. 18 | def process_repotask_input(command) 19 | case command 20 | when /\A(\d+)\Z/ 21 | open_file($1.to_i) 22 | when 'a' 23 | puts "Interpreting 'a' as '1'." 24 | open_file(1) 25 | when 'o' 26 | open_repo 27 | when 's' # Same as Task method. 28 | review_result = record_review 29 | # See TaskView#prompt_for_autonext. 30 | return command if review_result == 'done' 31 | if $auto_next and branch_reset_confirmed?(true) # true = exiting 32 | # Needed when leaving, to avoid git errors. 33 | reset_current_branch('skip_notice') 34 | else 35 | puts "Branch reset not confirmed; not quitting.\n\n" 36 | command = '' # Prevents quitting. 37 | end 38 | when 'r' # Execute the repotask's run_commands. 39 | run_answer 40 | when 'help', '?' # Launch help. 41 | launch_instructions_system 42 | display_info # Display the task after returning from help. 43 | when 'oo' # Switch to backup/archive repo and open. 44 | open_repo('old') 45 | when 'rr' # Run archived repo code. 46 | run_answer('old') 47 | when 'h' 48 | review_history 49 | when 'co' 50 | open_console 51 | when 'l' # Same as Task method. 52 | self.change_language 53 | when 'i' # Same as Task method. 54 | edit_field('instructions') 55 | when 'c' 56 | edit_run_commands # User will often have to tweak @run_commands. 57 | when 'fi' 58 | edit_files_to_edit 59 | when 't' # Same as Task method. 60 | edit_field('tags') 61 | when 'd' # Same as Task method. 62 | date = get_next_review_date('d') 63 | save_review_date(date) if date 64 | when 'sc' # Same as Task method. 65 | prep_new_score 66 | when 'f' 67 | display_info 68 | when 'q', 'x' # Quit task view and return to tasklist. 69 | cache_answer_in_archive_branch 70 | if branch_reset_confirmed?(true) # true = exiting 71 | # Needed when leaving, to avoid git errors. 72 | reset_current_branch 73 | else 74 | puts "Branch reset not confirmed; not quitting.\n\n" 75 | command = '' # Prevents quitting. 76 | end 77 | $auto_next = true if command == 'x' 78 | else 79 | puts 'Huh?' 80 | end 81 | return command 82 | end 83 | 84 | def open_file(file) 85 | unless @files 86 | print "No files to open. Add some with 'fi'.\n\n" 87 | return 88 | end 89 | return unless checkout_before_open_or_run 90 | unless file.between?(1, @files.length) 91 | print "\nSorry, but (#{file}) is not the number of a file. You can add " + 92 | "a file to open\nwith the [fi]les command.\n\n" 93 | return 94 | end 95 | file = @files[file-1] 96 | system("#{$textedcmd} data/repos/#{@repo}/#{file}") 97 | puts "When you're done, don't forget to press 'r' to run." 98 | end 99 | 100 | def open_repo(old=false) 101 | return unless checkout_before_open_or_run(old) 102 | system("#{$textedcmd} data/repos/#{@repo}") 103 | puts "When you're done, don't forget to press 'r' to run." 104 | end 105 | 106 | def checkout_before_open_or_run(old=false) 107 | if old # We're switching to the task's old (archive) branch. 108 | # Check out the archive before launching the archive branch. 109 | return false unless safely_check_out_branch(@old_branch, 'oo') 110 | else # We're switching to the task's main branch. 111 | # Check out the branch (and reset the previous branch) if we're not on it. 112 | return false unless safely_check_out_branch 113 | # If we're on the task branch, it might be unclean. Double-check and 114 | # reset if necessary. 115 | return false unless branch_reset_confirmed? 116 | end 117 | return true 118 | end 119 | 120 | # This prompts the user for an "OK" to hard reset the branch (rolling back 121 | # the files); if so, resets and returns true; if not, returns false. 122 | # Automatically returns true if branch already reset this session, or if 123 | # a reset was not needed. 124 | def branch_reset_confirmed?(exiting = false) 125 | return true if @reset_this_session and ! exiting 126 | g = Git.open("data/repos/#{@repo}") 127 | # This will make the following status query correct. 128 | system("cd data/repos/#{@repo}&&git status -s") 129 | unless g.status.changed.empty? 130 | if exiting 131 | puts <<~EXITCONFIRMATION 132 | 133 | Whenever you exit a repotask, we need to reset (delete changes made to) 134 | this branch. Please confirm to quit. 135 | 136 | EXITCONFIRMATION 137 | else 138 | puts <<~CONFIRMRESET 139 | 140 | WARNING: 141 | There are uncommitted (unsaved) changes to this branch. They could be 142 | from another answer that uses this branch that you never reset, or 143 | something else. You might (or might not) want to make sure it's not 144 | something you want to save before proceeding with reset; these 145 | changes will be deleted. 146 | 147 | CONFIRMRESET 148 | end 149 | confirm = nil 150 | until ['y', 'n', ''].include? confirm 151 | puts "Confirm reset? (Enter for [y]es, or [n]o)" 152 | confirm = get_user_command('o') 153 | end 154 | if confirm == 'n' 155 | print "OK, branch not reset.\n\n" 156 | return false 157 | end 158 | reset_current_branch # Returns true. 159 | else 160 | @reset_this_session = true 161 | end 162 | end 163 | 164 | def reset_current_branch(skip_notice = false) 165 | g = Git.open("data/repos/#{repo}") 166 | g.reset_hard 167 | # Remove untracked files (hard reset leaves them behind). 168 | system("cd data/repos/#{repo}&&git clean -qfdx -f") 169 | puts "\nBranch (#{@branch}) reset: files restored to original state." unless 170 | skip_notice 171 | @reset_this_session = true 172 | end 173 | 174 | def run_answer(old=false) 175 | return unless checkout_before_open_or_run(old) 176 | # If running the old (archive) repo, first check if the branch exists and 177 | # is different from the unedited starter version. 178 | if old 179 | g = Git.open("data/repos/#{@repo}") 180 | branches = g.branches.local.map {|b| b.full} 181 | if ! branches.include? @old_branch 182 | print "\nNo old branch to view. You haven't saved a solution to this " + 183 | "task yet.\n\n" 184 | return nil 185 | elsif system("cd data/repos/#{@repo}&&git diff #{branch} #{@old_branch} --quiet") 186 | print "\nNothing to run. The old (archived) task code is unchanged. " + 187 | "Maybe the task\nhas never been done?\n\n" 188 | return nil 189 | end 190 | end 191 | # OLD: commands = @run_commands.split("\n").join("&&") 192 | commands = @run_commands.split("\n") 193 | # OLD: commands = `cd data/repos/#{@repo}&&#{commands}` 194 | archive_msg = " " + "archive".colorize(background: @langhash.color) if old 195 | puts "\nRunning commands from ##{@id}#{archive_msg}:" 196 | puts ("=" * 75).colorize(@langhash.color) 197 | puts '' 198 | run_command_list(commands) 199 | puts '' 200 | puts ("=" * 75).colorize(@langhash.color) 201 | end 202 | 203 | def run_command_list(commands) 204 | pid = nil 205 | commands.each do |command| 206 | if command.split(': ')[0] == 'fork' 207 | pid = Process.fork do 208 | system("cd data/repos/#{@repo}&&#{command.split(': ')[1]}") 209 | end 210 | Process.wait(pid) if pid 211 | else 212 | # if command =~ /\Aruby/ 213 | # puts "Running:" 214 | # puts "cd data/repos/#{@repo}&&bundle exec #{command}" 215 | # system("cd data/repos/#{@repo}&&bundle exec #{command}") 216 | # else 217 | # puts "Running:" 218 | # puts "cd data/repos/#{@repo}&&#{command}" 219 | system("cd data/repos/#{@repo}&&#{command}") 220 | # end 221 | end 222 | end 223 | end 224 | 225 | # If not already done, check out a git branch (the task's or the archive). 226 | # This is skipped if we're already on the branch we want. (The latter doesn't 227 | # guarantee that the tree is clean, as we might want it to be.) 228 | def safely_check_out_branch(branch=@branch, prompt='o') 229 | #puts "branch = #{branch}" 230 | #puts "@reset_this_session = #{@reset_this_session}" 231 | #puts "@reset_archive_this_session = #{@reset_archive_this_session}" 232 | # The task's branch is already checked out and it's the one we want? 233 | # Skip checkout. 234 | return true if @reset_this_session and branch == @branch 235 | # The archive's branch is already checked out and it's the one we want? 236 | # Skip checkout. 237 | return true if @reset_archive_this_session and branch == @old_branch 238 | # If you got here, then either another branch is checked out, and we 239 | # want the task's branch; OR the task's branch is checked out, and we 240 | # want the archive branch. 241 | g = Git.open("data/repos/#{@repo}") 242 | # Is the currently checked-out git branch the branch we want? No... 243 | if g.current_branch != branch 244 | # This will make the following status query correct. 245 | system("cd data/repos/#{@repo}&&git status -s") 246 | # Give scary warning if there are uncommitted changes. 247 | if branch == @branch 248 | unless g.status.changed.empty? 249 | if ! external_branch_reset_confirmed?(g.current_branch) 250 | puts "Not running. Branch #{g.current_branch} unchanged." 251 | # Escape if permission not granted by user. 252 | return nil 253 | else 254 | @reset_this_session = true # It soon will be... 255 | g.reset_hard # RESET!!! 256 | # Remove untracked files (hard reset leaves them behind). 257 | system("cd data/repos/#{repo}&&git clean -qfdx") 258 | end 259 | end 260 | # Forget the archive session regardless of reset. 261 | @reset_archive_this_session = false 262 | elsif branch == @old_branch 263 | # If I want the archive branch, the task branch is checked out and 264 | # clean, groovy--ready to switch. 265 | if g.status.changed.empty? and g.current_branch == @branch 266 | puts "Current branch of the #{@repo} repo is clean, so" 267 | puts "you're ready to switch to the archive branch for task #{@id}." 268 | # If I want the archive branch, the task branch is checked out but 269 | # NOT clean, make sure the user is OK with it. 270 | elsif ! g.status.changed.empty? and g.current_branch == @branch 271 | puts "The main branch of the #{@repo} repo has edits. If you want" 272 | puts "to view the archive, you can, but you'll lose all your changes." 273 | return nil unless old_checkout_confirmed?(prompt) 274 | g.reset_hard # RESET!!! 275 | # Remove untracked files (hard reset leaves them behind). 276 | system("cd data/repos/#{repo}&&git clean -qfdx") 277 | end 278 | # Regardless of whether the task's main branch was clean, it's been 279 | # reset (cleaned). 280 | @reset_this_session = false # Going away from maybe-dirty main branch. 281 | @reset_archive_this_session = true 282 | # If I want the archive branch, and another branch is checked out and 283 | # IT is clean, groovy--ready to switch. No need of comment. 284 | end 285 | # Check out needed branch in any case. 286 | g.branch(branch).checkout 287 | end 288 | true # We have the branch we want now. 289 | end 290 | 291 | # Get confirmation, if necessary, from user to switch to the archive branch. 292 | def old_checkout_confirmed?(prompt) 293 | # Return true if no changes yet to the current branch AND the user is on 294 | # the task's branch 295 | confirm = nil 296 | until ['y', 'n', ''].include? confirm 297 | puts "Confirm reset? (Enter for [y]es, or [n]o)" 298 | confirm = get_user_command(prompt) 299 | end 300 | if confirm == 'n' 301 | print "OK, branch not reset.\n\n" 302 | return false 303 | else 304 | return true 305 | # I.e., the user has confirmed that he's ready to switch from this 306 | # repo's current unclean branch to the archive branch. The actual switch 307 | # is performed in #safely_check_out_branch. 308 | end 309 | end 310 | 311 | # Asks user to confirm hard resetting changes to an external branch. 312 | def external_branch_reset_confirmed?(current) 313 | warning = external_branch_reset_warning(current) 314 | puts wrap_overlong_paragraphs(warning) 315 | confirm = nil 316 | until ['y', 'n', ''].include? confirm 317 | puts "Enter for [y]es, or [n]o to escape (and take care of the changes)." 318 | confirm = get_user_command('r') 319 | end 320 | confirm != 'n' # Returns true if 'y' or '', false if 'n'. 321 | end 322 | 323 | def external_branch_reset_warning(current) 324 | <<~EXTBRANCHWARNING 325 | WARNING: 326 | 327 | We need to switch to the "#{@branch}" branch before running. There are 328 | uncommitted changes to the currently checked-out branch, 329 | "#{current}". These changes could be an answer to a question, 330 | set-up of a new branch that was never saved (by being committed), or some 331 | random editing you might or might not want. First make sure, then answer: 332 | 333 | Do you want to hard reset (delete) the changes to #{current}? 334 | 335 | EXTBRANCHWARNING 336 | end 337 | 338 | def edit_run_commands 339 | # Write @run_commands to temp file. 340 | file = 'tmp/run_commands.tmp' 341 | File.write(file, @run_commands) 342 | # Load with pico. 343 | system("pico #{file}") 344 | # Capture contents to @run_commands. 345 | @run_commands = File.read(file) 346 | # Delete temp file. 347 | File.delete(file) 348 | # Save tasks 349 | $tasks.save_tasklist 350 | puts "New run commands loaded." 351 | end 352 | 353 | def edit_files_to_edit 354 | response = self.class.get_files(@repo, @branch, @files) 355 | if response == 'q' 356 | display_info 357 | puts "Quit files interface. No changes made." 358 | else 359 | @files = response 360 | $tasks.save_tasklist 361 | display_info 362 | puts "Files loaded." 363 | end 364 | end 365 | 366 | # We'll cause errors when checking out other branches (when either creating 367 | # or answering other repotasks) if our changes to this branch aren't either 368 | # committed or reset. We don't want to commit them (that ruins the branch 369 | # for purposes of this question). So we must reset the branch. But if the 370 | # user wants to see his answer again later (as an answer reference, e.g.), 371 | # we need to give him a place to see it. We do so by caching his answer in 372 | # a special archive branch (one per task), which is always overwritten by 373 | # this method. Specially named so they don't show up as options to base new 374 | # repotasks on. 375 | def cache_answer_in_archive_branch 376 | g = Git.open("data/repos/#{@repo}") 377 | # This will make the following status queries correct. 378 | system("cd data/repos/#{@repo}&&git status -s") 379 | # Skip making an archive if (1) we're in the archive branch, or (2) no 380 | # changes were made to the main task branch and we're in the main branch, 381 | # or (3) another branch is checked out already. 382 | # If we're in the archive branch, the main task branch was already reset. 383 | # If we're in another branch, we don't want to overwrite this one. 384 | return if ( (g.status.changed.empty? && 385 | g.current_branch == @branch) or # Covers case (2). 386 | g.current_branch != @branch) # Covers cases (1) and (3). 387 | # Delete any existing archive branch. 388 | branches = g.branches.local.map {|b| b.full} 389 | g.branch(@old_branch).delete if branches.include? @old_branch 390 | # Create archive branch (again, maybe). 391 | g.branch(@old_branch).checkout 392 | g.add 393 | g.commit("standard archive") 394 | # Finally, checkout the main repotask branch. 395 | g.branch(@branch).checkout 396 | end 397 | 398 | end 399 | -------------------------------------------------------------------------------- /controllers/task_controller.rb: -------------------------------------------------------------------------------- 1 | module TaskController 2 | 3 | # Launches task display for user and prompts for input (e.g., write answer, 4 | # save review, run answer, edit instructions, etc.). RF 5 | def launch_task_interface 6 | display_info 7 | command = '' 8 | until command == 'q' or $auto_next 9 | command = get_user_command('+').downcase 10 | process_edit_input(command) 11 | end 12 | nil # No tasklist dispatch table message. 13 | end 14 | 15 | # Given a user command in the Task view, dispatch as appropriate. RF 16 | def process_edit_input(command) 17 | case command 18 | when 's' # Record information about review. 19 | record_review 20 | when 'a' # Opens file in your text editor so you can write answer. 21 | write_answer 22 | when 'r' # Execute the file you wrote. 23 | run_answer 24 | when 'co' # Open a console in the task's directory 25 | open_console 26 | when 'help', '?' # Launch help. 27 | launch_instructions_system 28 | display_info # Display the task after returning from help. 29 | when 'o' # Open file containing old/archived answers for this task. 30 | view_old_answers 31 | when 'rr' # Run old answer. No guarantee it will work. 32 | run_answer('old') 33 | when 'h' 34 | review_history 35 | when 'i' # Edit instructions for this task. 36 | edit_field('instructions') 37 | when 't' # Edit tags for this task. 38 | edit_field('tags') 39 | when 'd' # Edit date of next review (spaced repetition algorithm suggests). 40 | date = get_next_review_date('d') 41 | save_review_date(date) if date 42 | when 'sc' # Edit score of personal knowledge of this task. 43 | prep_new_score 44 | when 'st' # Open starter code file in text editor & load it when done. 45 | edit_starter 46 | when 'f' # Re[f]resh task page. Maybe should be done automatically. 47 | display_info 48 | when 'l' # Change language setting for this task. 49 | self.change_language 50 | when 'x' 51 | $auto_next = true 52 | when 'q' # Quit task view and return to tasklist. 53 | return 54 | else 55 | puts 'Huh?' 56 | end 57 | end 58 | 59 | # User records that he performed a review; updates score and next date. RF 60 | def record_review 61 | puts "Good, you completed a review." 62 | # Get @score from user. 63 | score = get_score('r') # User gets one chance; abandons attempt otherwise. 64 | return unless score 65 | # Get @next_review_date from user (might be based on spaced repetition algorithm). 66 | date = get_next_review_date('s', score) 67 | return unless date 68 | # Update current @score only after date is acceptable. 69 | @score = score 70 | # Update @next_review_date. 71 | @next_review_date = date 72 | # Save review date and score to @all_reviews. 73 | @all_reviews << {'score' => @score, 'review_date' => DateTime.now.to_s} 74 | # Save updated task data to JSON file. 75 | $tasks.save_tasklist 76 | # Refresh view. 77 | display_info 78 | # Show review history since typically it's of interest at this point. 79 | review_history 80 | # Ask user if he wants to go immediately to the next question; returns 'true' 81 | # if the answer is yes. 82 | return prompt_for_autonext 83 | end 84 | 85 | # Used only in the "date of next review" command. RF 86 | def save_review_date(date) 87 | @next_review_date = date 88 | $tasks.save_tasklist 89 | display_info 90 | end 91 | 92 | # User inputs new rating of own ability to solve task. Used only in the 93 | # "edit score" command. RF 94 | def prep_new_score 95 | score = get_score('s') 96 | if score 97 | @score = score 98 | # Edit data from most recent review 99 | @all_reviews[-1]['score'] = score 100 | else 101 | return nil 102 | end 103 | $tasks.save_tasklist 104 | display_info 105 | end 106 | 107 | # Save old answer to archive file (e.g., 'answer_old_23.rb'). Used by module 108 | # TaskView#write_answer. (Not the same as archiving all data.) RF 109 | def archive_old_answer 110 | # Create a folder for this archive if one doesn't exist yet. 111 | create_folder_if_necessary(@old_location_dir) 112 | # Load existing answer archive, if any. 113 | old_archive = File.exist?(@old_location) ? File.read(@old_location) : '' 114 | # Load current answer file contents. 115 | contents = File.read(@location) 116 | # Prepare new archive contents. 117 | # If C, Java, etc., then completely overwrite old answer file. 118 | if @langhash.one_main_per_file 119 | new_archive = contents 120 | # If Java, the main class needs to be renamed to be runnable. 121 | if @lang == 'Java' 122 | new_archive.gsub!('public class answer', 'public class answer_old') 123 | end 124 | else # Else the usual case: append newer answer to top of old_archive. 125 | # Separate different archived answers with a line of comments. 126 | # Use $cmnt2 for /* ... */ style comments. 127 | comment_separator = (@langhash.cmnt2 ? ((@langhash.cmnt*37) + 128 | @langhash.cmnt2) : (@langhash.cmnt*37) ) 129 | # Concatenate current contents with archive file contents. 130 | new_archive = 131 | contents + ("\n\n\n" + @langhash.spacer + "\n" + comment_separator + 132 | + "\n\n\n") + old_archive 133 | end 134 | # Write concatenated contents to the location of the archive. 135 | File.write(@old_location, new_archive) 136 | save_change_timestamp_to_settings # Whenever a change is made... 137 | end 138 | 139 | # Pre-populates the task answer file with starter code. RF 140 | def add_starter_code_to_answer_file 141 | if @starter 142 | File.write(@location, @starter) 143 | save_change_timestamp_to_settings 144 | elsif @lang == 'Java' 145 | File.write(@location, java_starter) 146 | save_change_timestamp_to_settings 147 | end 148 | end 149 | 150 | # Opens a new xterm (user must have) console located in the repotask's working 151 | # directory. 152 | def open_console 153 | check_for_xterm 154 | # This is a rather complicated command that required a fair bit of research. 155 | # "env -i HOME=$HOME" resets the environment variables (to blank), while 156 | # "bash -l" starts a new bash session and "-c" plus the command executes a 157 | # command in that bash session. 'cd #{Dir.pwd}', etc., changes to the working 158 | # directory of the repotask, "DISPLAY=:0" tells Bash which computer display 159 | # to use (because you cleared all environment variables earlier), while 160 | # finally "xterm -fa 'Monospace' -fs 12'" opens xterm and sets it to run in 161 | # a readable font size. 162 | if @repo 163 | system("env -i HOME=\"$HOME\" bash -l -c 'cd #{Dir.pwd}/data/repos/#{@repo} && DISPLAY=:0 xterm -fa 'Monospace' -fs 11'") 164 | else 165 | system("env -i HOME=\"$HOME\" bash -l -c 'cd #{Dir.pwd}/#{@location_dir} && DISPLAY=:0 xterm -fa 'Monospace' -fs 11'") 166 | end 167 | end 168 | 169 | def check_for_xterm 170 | unless system("which xterm > /dev/null") 171 | puts "\nSorry, you need to install xterm. Try 'sudo apt-get install xterm'." 172 | puts "This might or might not work on your system. You can do it yourself;" 173 | puts "or do you want me to try running this for you? [y]/n" 174 | answer = get_user_command('co') 175 | unless answer == 'y' or answer == '' 176 | return 177 | end 178 | unless system("sudo apt-get install xterm") 179 | return 180 | end 181 | end 182 | end 183 | 184 | end 185 | -------------------------------------------------------------------------------- /controllers/tasklist_controller.rb: -------------------------------------------------------------------------------- 1 | module TasklistController 2 | 3 | private 4 | 5 | # This is the top-level app loop. It's here rather than in App because most 6 | # of its functions concern the Tasklist. RF 7 | def app_loop 8 | command = nil 9 | until command == 'q' 10 | # The 'auto next' system loads the next task automatically if the user 11 | # so chooses. 12 | command = $auto_next ? 'x' : get_user_command('=').downcase 13 | $auto_next = false 14 | process_tasklist_input(command) 15 | next if $auto_next 16 | # Escape from TaskList when user requests archive or deletes all data. 17 | return if $view_archive or $destroyed_data 18 | end 19 | puts '' 20 | puts ($unsaved_changes ? 21 | "You have unarchived (un-backed up) changes, but your data is saved." 22 | : "Your data is saved.") 23 | puts "Goodbye until next time!" 24 | end 25 | 26 | # Dispatch table for tasklist (and options, archive, and task view launch). 27 | # Typically (not always) redisplays tasks after executing some function. RF 28 | def process_tasklist_input(command) 29 | # A 'message' (or nil) is returned by most of these functions, and then 30 | # passed off to TasklistView::display_tasks. 31 | message = case command 32 | when '>', '.' 33 | nav('next') 34 | when '<', ',' 35 | nav('back') 36 | when '>>', '..' 37 | nav('end') 38 | when '<<', ',,' 39 | nav('top') 40 | when 'n' 41 | task = Task.generate_new_task 42 | task ? "New task saved." : "Task input abandoned." 43 | when 'r' 44 | repotask = Repotask.generate_new_repotask 45 | repotask ? "New repotask saved." : "Repotask input abandoned." 46 | when /\A(\d+)\Z/ 47 | task = fetch_task_from_displayed_number($1.to_i) 48 | if task 49 | if task.class == Task 50 | task.launch_task_interface 51 | else 52 | task.launch_repotask_interface 53 | end 54 | else 55 | "Task not found." 56 | end 57 | when 'l' 58 | prep_to_show_all_tasks # Clears @default_tag and stops filtering. 59 | when 'x' 60 | edit_next_item 61 | when 'd' 62 | confirm_delete 63 | when 't' 64 | tag_search 65 | when 'a' 66 | $view_archive = true # Used in revuu.rb. Exits TaskList. 67 | return 68 | when 'e' 69 | choose_text_editor 70 | when 'p' 71 | choose_default_language 72 | when 'de' 73 | destroy_all 74 | return if $destroyed_data # Used in revuu.rb. Exits TaskList. 75 | when 'h' 76 | display_history 77 | when 's' 78 | display_sorting_commands 79 | when 'id' 80 | sort_by_id 81 | when 'sc' 82 | sort_by_avg_score 83 | when 'notags' 84 | display_tasks_without_tags 85 | when 'c' 86 | prompt_to_change_all_review_dates 87 | when '?', 'help' 88 | launch_instructions_system 89 | when 'q' 90 | return 91 | else 92 | puts 'Huh?' 93 | no_refresh = true 94 | end 95 | # Note, no_refresh is declared only after 'else' just above. 96 | clear_screen unless no_refresh 97 | # Note, 'message' is the return value of the 'case' block above. 98 | display_tasks(false, message) unless no_refresh 99 | end 100 | 101 | # Given where to navigate, set the page num to reflect the change. RF 102 | def nav(where) 103 | # Decide whether to use all tasks or a filtered subset. 104 | list = @filter_tag ? @tag_filtered_list : @list 105 | return '' if list.length < 10 # Nav not possible; too few tasks. 106 | last_pg = calculate_last_page_number(list) 107 | on_first = (@page_num == 1) 108 | on_last = (@page_num == last_pg) 109 | case where 110 | when 'top' 111 | @page_num = 1 112 | when 'back' 113 | @page_num = (on_first ? 1 : @page_num - 1 ) 114 | when 'next' 115 | @page_num = (on_last ? last_pg : @page_num + 1) 116 | when 'end' 117 | @page_num = last_pg 118 | end 119 | nil # No dispatch table message. 120 | end 121 | 122 | # Given a task list, calculate and return the # of last page to display. RF 123 | def calculate_last_page_number(list) 124 | last_pg = (list.length/10.0).floor + 1 125 | # This gets rid of an empty page when user has multiples of 10. 126 | last_pg -= 1 if (list.length/10.0) == (list.length/10) 127 | last_pg 128 | end 129 | 130 | # Simply clears the filter tag and tag-filtered list; will cause the whole 131 | # list to be displayed on re-display of tasks. RF 132 | def prep_to_show_all_tasks 133 | if @filter_tag 134 | @filter_tag = nil 135 | @tag_filtered_list = [] 136 | @page_num = 1 137 | end 138 | nil # No dispatch table message. 139 | end 140 | 141 | # Simply opens the item with the earliest review date to edit. RF 142 | def edit_next_item 143 | list = @filter_tag ? @tag_filtered_list : @list 144 | item = list[0] 145 | item.class == Task ? item.launch_task_interface : 146 | item.launch_repotask_interface 147 | nil # No dispatch table message. 148 | end 149 | 150 | # Get user input for searching tasks by tag; return just matching tasks. RF 151 | def tag_search 152 | # Prepare arrays of tasks containing tags. 153 | tag_hash = prepare_hash_of_tag_arrays 154 | if tag_hash.empty? 155 | return "No tags found." 156 | end 157 | tag = get_search_tag_from_user 158 | # If default tag exists and user hit alone, use default tag. 159 | if (!@default_tag.nil? && tag == '') 160 | tag = @default_tag 161 | end 162 | tag_matches = get_tag_matches(tag.downcase, tag_hash) 163 | # Display results. If not found, say so. 164 | unless tag_matches.empty? 165 | # Assign default tag to input. This does double duty as boolean 166 | # indicating whether the current tasklist display is filtered or not. 167 | @filter_tag = tag 168 | @default_tag = @filter_tag.dup unless 169 | @filter_tag == 'history' or @filter_tag == 'sort_by_id' or 170 | @filter_tag == 'reverse_sort_by_id' or @filter_tag == 'sort_by_avg_score' or 171 | @filter_tag == 'reverse_sort_by_avg_score' or @filter_tag == 'notags' 172 | @page_num = 1 173 | # Save sorted array of tasks filtered by this tag. 174 | @tag_filtered_list = match_tasks(tag: tag, tag_hash: tag_hash, 175 | tag_matches: tag_matches) 176 | return "Filtering by '#{tag}'. Press 'l' to clear filter." 177 | else 178 | return "'#{tag}' not found." 179 | end 180 | end 181 | 182 | # Basically uses the same logic as #tag_search. 183 | def display_history 184 | return "No history yet. Make and review a task first." if @history.empty? 185 | @filter_tag = 'history' 186 | @page_num = 1 187 | @tag_filtered_list = @history.map{|h| h[1]}.uniq 188 | return "Showing history. Press 'l' to show tasklist." 189 | end 190 | 191 | def sort_by_id 192 | return "No tasks to sort." if @list.empty? 193 | @page_num = 1 194 | if @filter_tag and @filter_tag == 'sort_by_id' 195 | @filter_tag = 'reverse_sort_by_id' 196 | @tag_filtered_list = @list.sort_by{|t| t.id}.reverse 197 | return "Showing tasks *reverse* sorted by ID (date created)." 198 | else 199 | @filter_tag = 'sort_by_id' 200 | @tag_filtered_list = @list.sort_by{|t| t.id} 201 | return "Showing tasks sorted by ID (date created)." 202 | end 203 | end 204 | 205 | def prep_array_of_tasks_by_avg_score 206 | @list.sort_by do |t| 207 | scores = t.all_reviews.map {|r| r['score']} 208 | (scores.reduce(:+) / scores.count.to_f) 209 | end 210 | end 211 | 212 | def sort_by_avg_score 213 | return "No tasks to sort." if @list.empty? 214 | @page_num = 1 215 | score_ordered_tasks = prep_array_of_tasks_by_avg_score 216 | if @filter_tag and @filter_tag == 'sort_by_avg_score' 217 | @filter_tag = 'reverse_sort_by_avg_score' 218 | @tag_filtered_list = score_ordered_tasks.reverse 219 | return "Showing tasks *reverse* sorted by average score." 220 | else 221 | @filter_tag = 'sort_by_avg_score' 222 | @tag_filtered_list = score_ordered_tasks 223 | return "Showing tasks sorted by average score." 224 | end 225 | end 226 | 227 | def display_tasks_without_tags 228 | return "No tasks." if @list.empty? 229 | @filter_tag = 'notags' 230 | @page_num = 1 231 | @tag_filtered_list = @list.find_all do |t| 232 | # Find all tasks that have no tags other than the language defaults. 233 | x = t.tags 234 | y = t.langhash.lang_alts + [t.langhash.name] 235 | nondefault_tags = (x + y) - (x & y) 236 | nondefault_tags.empty? # If there no nondefault tags, return this item. 237 | end 238 | return "Showing all tasks with no (non-default) tags." 239 | end 240 | 241 | # For use in tag search: a hash where keys = tags while values = tasks. RF 242 | def prepare_hash_of_tag_arrays 243 | tag_hash = {} 244 | list.each do |task| 245 | next unless task.tags 246 | task.tags.each do |tag| 247 | tag_hash[tag] = [] unless tag_hash[tag] 248 | tag_hash[tag] << task unless tag_hash[tag].include? task 249 | end 250 | end 251 | tag_hash 252 | end 253 | 254 | # Given an integer, return a task from the tasklist. RF 255 | def fetch_task_from_displayed_number(num) 256 | @displayed_tasks[num] 257 | end 258 | 259 | end 260 | -------------------------------------------------------------------------------- /data/answers/.gitkeep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/globewalldesk/revuu/7f118434e12a96c8165c32748323c55402f5224a/data/answers/.gitkeep -------------------------------------------------------------------------------- /data/repos/.gitkeep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/globewalldesk/revuu/7f118434e12a96c8165c32748323c55402f5224a/data/repos/.gitkeep -------------------------------------------------------------------------------- /data/starters/.gitkeep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/globewalldesk/revuu/7f118434e12a96c8165c32748323c55402f5224a/data/starters/.gitkeep -------------------------------------------------------------------------------- /deleteme.txt: -------------------------------------------------------------------------------- 1 | Make a new Rails app! 2 | 3 | Do this in a separate repo terminal. 4 | 5 | Install a new Rails instance with (1) some clever name, (2) *without* a 6 | copy of the Rails framework within the local directory, and (3) 7 | specifying PostgreSQL. Then (4) start the server and see if it's working. 8 | 9 | You should probably double-check that the command is correct before 10 | running it. 11 | -------------------------------------------------------------------------------- /lib/date_prettifier.rb: -------------------------------------------------------------------------------- 1 | require 'date' 2 | 3 | module DatePrettifier 4 | 5 | # From timestamp, output a human-friendly date 6 | def prettify_timestamp(ts) 7 | now = DateTime.now 8 | ts = DateTime.parse(ts) if ts.class == String 9 | sec_diff = (ts.to_time.to_i - now.to_time.to_i).abs 10 | # Longer than one year 11 | if ! ts.between?(now - 365, now + 365) 12 | diff = (sec_diff/(60*60*24*365.0)).round 13 | s = pl(diff) 14 | ago_from_now(ts, now, 'year', diff, s) 15 | # One month to a year: '2 months ago', '5 months from now' 16 | elsif ! ts.between?(now - 56, now + 56) 17 | diff = ((sec_diff * 12)/(60*60*24*365.0)).round 18 | s = pl(diff) 19 | ago_from_now(ts, now, 'month', diff, s) 20 | # If 7-27 days ahead or behind, e.g.: '1 week ago', '3 weeks from now' 21 | elsif ! ts.between?(now - 6, now + 6) 22 | diff = ((sec_diff/7)/(60*60*24.0)).round 23 | s = pl(diff) 24 | ago_from_now(ts, now, 'week', diff, s) 25 | # If yesterday or tomorrow: 'yesterday', 'tomorrow'. NOTE: "out of order". 26 | elsif ts.yday == now.yday - 1 || ts.yday == now.yday + 1 27 | (ts.yday - now.yday).positive? ? 'tomorrow' : 'yesterday' 28 | elsif ts.yday == 1 and now.yday == 365 29 | 'tomorrow' 30 | elsif ts.yday == 365 and now.yday == 1 31 | 'yesterday' 32 | # If today! NOTE: Also "out of order" 33 | elsif ts.yday == now.yday 34 | 'today' 35 | # If 2-6 days ahead or behind, e.g.: '3 days ago', '4 days from now' 36 | elsif ! ts.between?(now - 1, now + 1) 37 | diff = (sec_diff/(60*60*24.0)).ceil 38 | s = pl(diff) 39 | ago_from_now(ts, now, 'day', diff, s) 40 | else 41 | 'unknown' 42 | end 43 | end 44 | 45 | # Simple pluralizer 46 | def pl(diff) 47 | diff > 1 ? 's' : '' 48 | end 49 | 50 | def ago_from_now(ts, now, unit, diff, s) 51 | ts > now ? "#{diff} #{unit}#{s} from now" : "#{diff} #{unit}#{s} ago" 52 | end 53 | 54 | end 55 | 56 | =begin 57 | # Testing data 58 | 59 | long_ago = DateTime.new(1970) 60 | few_months = DateTime.new(2018, 2) 61 | few_weeks = DateTime.new(2018, 9, 3) 62 | few_days = DateTime.new(2018, 9, 20) 63 | yesterday = DateTime.new(2018, 9, 22) 64 | tomorrow = DateTime.new(2018, 9, 24) 65 | today = DateTime.new(2018,9,23) 66 | future = DateTime.new(2020,1,1) 67 | 68 | puts "Long ago, it was #{prettify_timestamp(long_ago)}." 69 | puts "Earlier this year, it was #{prettify_timestamp(few_months)}." 70 | puts "Earlier this month, it was #{prettify_timestamp(few_weeks)}." 71 | puts "Some days ago, it was #{prettify_timestamp(few_days)}." 72 | puts "No, it was #{prettify_timestamp(yesterday)}." 73 | puts "No, #{prettify_timestamp(tomorrow)}!" 74 | puts "Too late, it's #{prettify_timestamp(today)}!!!" 75 | puts "In the future it'll be #{prettify_timestamp(future)}." 76 | =end 77 | -------------------------------------------------------------------------------- /lib/help_helper.rb: -------------------------------------------------------------------------------- 1 | module HelpHelper 2 | # Note, passes along a copy of the launching object in order to return there. 3 | def launch_instructions_system(options = nil) 4 | clear_screen 5 | skip_list = false 6 | instr_choice = '' 7 | options ||= { 8 | instructions: big_instruction_array, 9 | title: 'REVUU HELP TOPICS:', 10 | qualifier: '' 11 | } 12 | until instr_choice == 'q' 13 | unless skip_list 14 | display_instruction_choices(options) 15 | puts "Type a number above to learn how to use the " + 16 | "#{options[:qualifier]}system, or [q]uit: " 17 | end 18 | instr_choice = get_user_command('i') 19 | next if instr_choice == 'q' 20 | instr_choice = instr_choice.to_i 21 | if validate_instr_choice(instr_choice, options) 22 | # Repotasks have a whole nother instruction system. 23 | unless options[:instructions][instr_choice-1][:title] == 24 | "SUBSECTION: how to use the repotask system" 25 | display_instruction(instr_choice, options) 26 | skip_list = false 27 | else 28 | launch_repotask_instructions_system 29 | end 30 | else 31 | puts "Not a valid option.\n\n" 32 | skip_list = true 33 | end 34 | end 35 | return "You can type '?' to get back to help." 36 | end 37 | 38 | def display_instruction_choices(options) 39 | instructions = options[:instructions] 40 | # Prepare string containing big_instruction_array titles. 41 | title = options[:title] 42 | title_string = '=+' * (title.length/2).round 43 | title_string += "\n#{title}\n" 44 | title_string += ('=+' * (title.length/2).round) + "\n" 45 | line_counter = 0 46 | new_line = '' 47 | instructions.each_with_index do |instr, i| 48 | this_addition = "(#{i + 1}) #{instr[:title]} " 49 | # If addition this addition to the string would make it 50 | # over 75 characters, then add a newline to the string 51 | # and reset line_counter 52 | if (line_counter + this_addition.length) > 75 53 | title_string << new_line + "\n" 54 | new_line = this_addition 55 | if (instructions.length - 1 == i) 56 | title_string << new_line 57 | end 58 | line_counter = this_addition.length 59 | else 60 | new_line << this_addition 61 | if (instructions.length - 1 == i) 62 | title_string << new_line 63 | end 64 | line_counter += this_addition.length 65 | end 66 | end 67 | # Print the string. 68 | puts title_string + "\n\n" 69 | end 70 | 71 | def validate_instr_choice(i, options) 72 | # i is valid iff it (-1) is an index of $big_instruction_array 73 | (i-1).between?(0, options[:instructions].length - 1) 74 | end 75 | 76 | # Given an index number, print out the corresponding content from $big_instruction_array. 77 | def display_instruction(i, options) 78 | instructions = options[:instructions] 79 | clear_screen 80 | print("(" + i.to_s + ") ") 81 | print instructions[i-1][:title].capitalize + ":\n" 82 | puts('=' * 75) 83 | puts "#{instructions[i-1][:content]}" 84 | puts('=' * 75) 85 | end 86 | 87 | def big_instruction_array 88 | [ { 89 | title: "introduction", 90 | content: <<-ENDINTRO 91 | Welcome to Revuu! 92 | 93 | This app will help you review programming tasks, improving understanding 94 | and keeping your skills fresh. It was written with the notion that 95 | programmers (and others) need repetition of not declarative but 96 | procedural knowledge. 97 | 98 | So when you perform a review, you don't try to answer a question in 99 | words. Instead, you try to perform a task. Essentially, to use Revuu, 100 | you'd add complex, not simple, tasks. Probably the ideal Revuu task 101 | would require 2-10 minutes to complete. 102 | 103 | The basic functions of the program are adding tasks, using the handy 104 | answer filing and editing system (which probably works with your 105 | favorite text editor), running the script and seeing the results, and 106 | recording that you've done a review and that the next review should be 107 | done on a certain date. The two basic views of the app are a paginated 108 | list of tasks and an individual task view. 109 | 110 | Currently, we support Ruby, JavaScript (Node.js), Python, Java, C, and 111 | Bash scripting. We also support many commonly-used text editors and 112 | IDEs. 113 | 114 | Add copious, well-chosen tags in order to be able to sort tasks. 115 | 116 | Revuu ships with a bunch of pre-made questions and answers by way of 117 | demonstration. You can delete these and make your own, if you like. The 118 | questions are mostly Ruby and JavaScript right now. 119 | ENDINTRO 120 | }, 121 | { 122 | title: "getting started", 123 | content: <<-GETTINGSTARTED 124 | Basically, Revuu is all about (1) giving yourself programming tasks that 125 | drill skills you want to learn, (2) making it super-easy to write (with 126 | your text editor of choice) and run scripts from within Revuu, and 127 | (3) keeping track of how confident you feel and, consequently, when your 128 | next review for an skill should be. 129 | 130 | The first thing you'll want to do is to check (and probably change) the 131 | default text editor: from the task list view (the one you see when you 132 | first start the program), press 'e' for editor. 133 | 134 | Since Revuu ships with a lot of ready-made questions, you should 135 | probably delete a lot of questions. You can delete all of them simply by 136 | navigating to /data and there deleting tasks.json (don't delete revuu.rb 137 | --that's the app). If you want to delete them one at a time, you can do 138 | so by pressing 'd' and then typing the number next to the question you 139 | want to delete. 140 | 141 | If you retain any questions, you'll want to change the "next review" 142 | dates on them. You have to do that one at a time (or I can write a 143 | method to do that automatically--let me know if you want me to). 144 | 145 | To *really* get started, you'll want to add questions based on your 146 | studies or by examining how you solved problems in your own code (you 147 | want to commit that stuff to memory, right?). To get started, just press 148 | 'n' for new and follow the instructions. 149 | 150 | After you write a task, you should answer it ('a' on the task view) and 151 | then make sure the answer is correct by running your script ('r'). 152 | GETTINGSTARTED 153 | }, 154 | { 155 | title: 'create a task', 156 | content: <<-CREATEATASK 157 | To write a new task for regular review, press 'n'. The app will lead you 158 | through what you need to do. 159 | 160 | I recommend that you keep the tasks fairly simple--enough to accomplish 161 | in, say, two to 10 minutes. It is also a good idea to make sure the 162 | outcome is objective, so you can check up on yourself easily. 163 | 164 | If you don't like the default text editor, you can switch it by going to 165 | the task list (the one you see when you first start the program) and 166 | pressing 'e'. 167 | 168 | Right now, Revuu supports Ruby, JavaScript, Python, Java, C, and Bash 169 | (and text files). I can easily add more languages; just let me know. 170 | There's no reason to think your language of choice can't be supported. 171 | 172 | As to tags, a key tip to bear in mind is to add any unusual methods, 173 | keywords, techniques, and concepts (that have clear names) to the tag 174 | list. Tags are separated by commas, although if you enter them one to a 175 | line, they'll be rendered in the correct format. 176 | 177 | DO add tags, because otherwise you won't be able to search or filter. 178 | 179 | Set an initial score for yourself based on how confident you are in 180 | doing the task. I don't think you have to have everything memorized to 181 | get a 5, but that's up to you. Your first review is scheduled for the 182 | same day. (See 'review a task' for more details.) 183 | CREATEATASK 184 | }, 185 | { 186 | title: 'how do I add a title?', 187 | content: <<-ADDTITLE 188 | It's simple to add a title to your task: the first line of the task 189 | instructions serves as a title. Revuu's author skips down a line or two 190 | after the title just for clarity to the reader. 191 | ADDTITLE 192 | }, 193 | { 194 | title: 'review (practice, answer) a task', 195 | content: <<-REVIEWATASK 196 | Revuu makes it really easy to review a task, i.e., writing a script that 197 | follows the instructions for a task. Just go to the task view (by 198 | entering the number next to it) and press 'a'. 199 | 200 | This will open up a file, with a well-chosen filename based on the task 201 | ID and programming language, using your text editor of choice (remember, 202 | you can change the default by choosing 'e' for editor from the top-level 203 | task list). 204 | 205 | To run your script, whether it is in progress or finished, simply save 206 | and press 'r'. If the language is compiled, the command to compile will 207 | be run first automatically before executing the file. 208 | 209 | Be sure to press 's' for save a review after you're done. See the 210 | separate help items about this and also about how spaced repetition 211 | works. 212 | 213 | Note, if you have already written an answer before, the script prompts 214 | you to save/archive your old answer; this is done automatically for you 215 | just by pressing 'y'. It can be a great resource for your later review 216 | to see your earlier solutions. Note that programs that have a single 217 | main function (e.g., C and Java) overwrite rather than append the 218 | answer. Ruby and JavaScript, by contrast, simply append answers to the 219 | top of the list. You can actually read your old answers with 'o' and 220 | re-run your old scripts with 'rr'. 221 | REVIEWATASK 222 | }, 223 | { 224 | title: 'save (record) a review', 225 | content: <<-SAVEAREVIEW 226 | After you have successfully finished a task, you should press 's' for 227 | save (or record) the information that a review was performed. This 228 | prompts you to do two things: first, to judge your level of mastery of 229 | the material. Mastery doesn't necessarily mean your total memorization 230 | of every little thing; sometimes, we have mastered something that we 231 | still have to look up information to finish. 232 | 233 | Second, Revuu asks you to either (1) accept the date that the spaced 234 | repetition algorithm recommends for your next review, simply by pressing 235 | "Enter", or (2) enter the date yourself (or, rather, a plain English 236 | string such as "two weeks from now" or "next Tuesday"). 237 | 238 | Bear in mind that your judgment about when you should review the 239 | material is probably more reliable than the algorithm. Please look at 240 | the help item titled "how the spaced repetition algorithm works." 241 | SAVEAREVIEW 242 | }, 243 | { 244 | title: 'how the spaced repetition algorithm works', 245 | content: <<-SPACEDREPETITION 246 | In general, spaced repetition is the learning technique of spacing out 247 | reviews of learned information in ever-increasing increments, unless 248 | more frequent repetitions prove to be necessary. 249 | 250 | Here are the rules that Revuu's simple version of this algorithm follows 251 | (note, "interval" means the interval between today and the most recent 252 | review): 253 | 254 | Score First review All later reviews 255 | 1 tomorrow tomorrow 256 | 2 tomorrow greater of 0.25 the interval or in 2 days 257 | 3 in 2 days greater of 0.5 of the interval or in 4 days 258 | 4 in 4 days in 1.5 times the interval 259 | 5 in 1 week in 2 times the interval 260 | 261 | Please DO NOT rely religiously on this algorithm. Your judgment is 262 | probably considerably more reliable than the algorithm. Sometimes you 263 | might benefit from frequent repetition of material that you are 264 | confident of; sometimes you might not want to see some material that is 265 | shaky for months to come, may because it isn't important. 266 | SPACEDREPETITION 267 | }, 268 | { 269 | title: 'run an answer/script', 270 | content: <<-RUNANANSWER 271 | One of the coolest things about Revuu is that you can run your scripts 272 | right from within the app. After you've written your answer, simply type 273 | 'r' for run. You can also re-run archived answers with 'rr'. Any error 274 | messages or stack traces that you'd see on the command line will appear 275 | in the window. 276 | 277 | It can be a handy way to remind yourself what you're expecting out of 278 | an answer by re-running an archived answer. 279 | RUNANANSWER 280 | }, 281 | { 282 | title: 'edit task information', 283 | content: <<-EDITOTHERTASKINFO 284 | Almost everything about a task can be edited after it has been created, 285 | regardless of whether it's been answered before: 286 | 287 | Type 'i' to edit instructions (i.e., the task text that appears at the 288 | top of the task page). 289 | 290 | Type 't' to edit tags. (Note, language tags are autogenerated.) 291 | 292 | Type 'd' to edit/schedule the date of next review. Simply type such 293 | words as "tomorrow" or "in 2 weeks" or "4 months anon". Past dates and 294 | exact dates work too. 295 | 296 | Type 'sc' to edit the score. This doesn't do much yet but it will in the 297 | future. 298 | EDITOTHERTASKINFO 299 | }, 300 | { 301 | title: 'save, run, and view old answers', 302 | content: <<-OLDANSWERS 303 | Another cool feature of Revuu is that the app automatically archives old 304 | answers for you (this is done when you press 'a' and then choose 'y' to 305 | archive), and then allows you view them again with 'o' for old answer 306 | and to run them again with 'rr' for re-run. Note that while languages 307 | like JavaScript and Ruby append newer answers to the top of the archive 308 | file, languages that permit only one main function like C and Java 309 | entirely overwrite the old answer, which will be lost forever. 310 | OLDANSWERS 311 | }, 312 | { 313 | title: 'delete a task', 314 | content: <<-DELETEATASK 315 | To delete a task, first you have to be on the task list view (the top 316 | level). Then press 'd' and enter the number next to the task you want to 317 | delete. WARNING: there is no "are you sure?"-type prompt, so be careful 318 | about what number you enter. The deleted task and its data will be gone 319 | forever; be careful. 320 | 321 | If you just don't want to see a task for a long time, you can always 322 | view the task and then press 'd' for date and put in something like 323 | "in 100 years". 324 | DELETEATASK 325 | }, 326 | { 327 | title: 'refresh the view', 328 | content: <<-REFRESHTASKS 329 | Sometimes Revuu gets to be rather messy, and important stuff has 330 | scrolled off the top of the screen. You can refresh your view, though. 331 | 332 | If you're on the task list (the top level), press 'l' to list the tasks 333 | --to clear the screen and redisplay the task list. 334 | 335 | If you're viewing a particular task, press 'f' to refresh the task 336 | instructions and data. 337 | REFRESHTASKS 338 | }, 339 | { 340 | title: 'search and filter tasks', 341 | content: <<-SEARCHFILTER 342 | First, make sure you have a decent system of tags to search and filter 343 | on. Just type 't' for tag and type in a tag. It must closely match a 344 | tag to get any results. 345 | 346 | The search and filter feature is not sophisticated yet. It is not 347 | possible to search the text of task instructions. 348 | 349 | Mainly the tag feature is useful to search on language tags. Language 350 | tags are added (and edited) automatically by Revuu. (If you try to 351 | delete them, they'll be re-added.) 352 | SEARCHFILTER 353 | }, 354 | { 355 | title: 'change text editor', 356 | content: <<-CHANGEEDITOR 357 | To change the default text editor (for editing your answers), simply go 358 | to the task list (top level) and type 'e' for editor. Revuu examines 359 | your system to see what editors you have installed (that run from the 360 | command line) and gives you the option to pick from those. Unless you 361 | use a relatively unpopular text editor, yours is probably supported. If 362 | not, write me and I can add it. 363 | CHANGEEDITOR 364 | }, 365 | { 366 | title: 'change programming language', 367 | content: <<-CHANGELANGUAGE 368 | Each task has its own associated programming language, so you can use 369 | several different languages at the same time on Revuu. To set the 370 | default language (which you accept by hitting "Enter" when you're 371 | creating a new task), go to the task list (top level) and type 'p' for 372 | programming language. 373 | 374 | As to the language of an individual task, you set it when you create the 375 | task. But this can be changed at any time from the view page for a 376 | particular task (if you're not there, just type the number next to it 377 | from the task list). The command is 'c' for configure language. 378 | CHANGELANGUAGE 379 | }, 380 | { 381 | title: 'navigation', 382 | content: <<-NAVIGATE 383 | To open a task, type the number next to it; to get back to the task 384 | list, press 'q'. 385 | 386 | To view the next task (the one with the earliest due date), press 'x' 387 | from the task list (top level) view. 388 | 389 | To go to the next page of tasks (assuming you have over 10), press '>' 390 | (or '.'). To go back, press '<' (or ','). To go to the end of several 391 | pages, type '>>' (or '..'); to go to the beginning, '<<' (or ',,'). 392 | NAVIGATE 393 | }, 394 | { 395 | title: 'how do I delete all loaded data and start afresh?', 396 | content: <<-DESTROY 397 | Simply press 'de'. If you really don't care about your data and want it 398 | erased forever, this is a good option. It's also how you'd get rid of 399 | the sample data after you looked it over. It's also how you'd start a 400 | new data collection with a specific topic after properly archiving 401 | another collection with a different topic. 402 | DESTROY 403 | }, 404 | { 405 | title: 'can I save different data repositories separately?', 406 | content: <<-DIFFREPOS 407 | Revuu's archive system allows you to manage questions from different 408 | topics (or people) separately. You can restrict a review session to one 409 | language or another by searching on a language tag. 410 | 411 | To make different data repos for different topics (or people), 412 | (1) Press 'a' from the task list to go to the archive system, and with 413 | 'c', for 'create archive', save the current data set *using a tag*. 414 | (2) Back in the task view, press 'de' to destroy all the questions. 415 | (3) Start a new repo. When you're ready to archive it, return to the 416 | archive system and use a *different* tag from the first. 417 | 418 | Whenever you want to switch from data set to data set, then: 419 | (4) Go to the archive system with 'a'. 420 | (5) Press 'c' to create an archive of your latest data and be sure to 421 | use the CORRECT tag, i.e., the one of the one you're saving. 422 | (6) Then press 'l' to load the archive you want to switch to. 423 | DIFFREPOS 424 | }, 425 | { 426 | title: 'back up, share, and import data', 427 | content: <<-ARCHIVESYSTEM 428 | Revuu has a fairly extensive archive system. Press 'a' from the tasklist 429 | to launch it. 430 | 431 | Your live data is saved in the data/ folder, not the archives/ folder. 432 | When you archive (with 'c' for create archive) your data, you are simply 433 | making a tarball, a copy, of the data/ folder and placing the copy in 434 | archives/. Grab it from there to share with others. 435 | 436 | When you press 'l' for load archive, you are getting ready to use an 437 | existing archive (tarball); you'll overwrite your currently live data. 438 | 439 | If you're new to Revuu, you can check out some sample data by 440 | (1) pressing 'sa', (2) pressing 'l' and then choosing the sample data 441 | archive you just imported, then (3) 'q' to quit the archive system. 442 | From the task list, you can always delete this data en mass with 'de'. 443 | 444 | WARNING 1: Please be aware that this will first ERASE any existing live 445 | data in data/. You can make an archive of your live data with 'c'. 446 | 447 | WARNING 2: Overwriting your most recent archive, and permanently losing 448 | it, is possible if you accidentally load some old data into your data/ 449 | folder (i.e., make it live) and then archive that. So be careful not to 450 | re-archive old data. 451 | 452 | That said, it is possible (using tags) to work with and switch between 453 | different archives. Just be sure, always, to use tagged names for your 454 | archive files rather than the default plain "archive_YYYYMMDD.tar" name. 455 | ARCHIVESYSTEM 456 | }, 457 | { 458 | title: 'SUBSECTION: how to use the repotask system' 459 | } 460 | ] 461 | end 462 | end 463 | -------------------------------------------------------------------------------- /lib/help_repotask.rb: -------------------------------------------------------------------------------- 1 | module HelpRepotask 2 | def launch_repotask_instructions_system 3 | options = { 4 | instructions: repotask_instructions, 5 | title: 'REPOTASK HELP TOPICS:', 6 | qualifier: 'repotask ' 7 | 8 | } 9 | launch_instructions_system(options) 10 | clear_screen 11 | end 12 | 13 | def repotask_instructions 14 | [ { 15 | title: "what's a repotask?", 16 | content: <<-WHATSAREPOTASK 17 | A regular task can be performed using a single file. 18 | 19 | A repotask is a task that can be performed only using at least two files 20 | that interact. They might have many files, contained in a directory, and 21 | are typically maintained in a repository (repo) that is managed by a 22 | version control system--usually Git. 23 | 24 | Revuu's Repotask system allows you to make and review tasks that are based 25 | on potentially big, complex systems. Crazy, maybe, but true. 26 | 27 | NOTE: You'll have to know a bit (not too much) about Git in order to make 28 | repotasks. If you don't know about it yet and you're serious about coding, 29 | then learn the basics--it's worth it. 30 | WHATSAREPOTASK 31 | }, 32 | { 33 | title: "how to set up a repo for a repotask", 34 | content: <<-REPOSETUP 35 | To make a repotask, first you have to set up a repo. Here's how: 36 | 37 | (1) Create or move a repo (a directory with two or more files and possibly 38 | some subdirectories) into data/repos/. 39 | (2) If the directory hasn't been initialized with git already, type 40 | "git init" on the command line of the top folder of your directory. 41 | (3) Get your files exactly as you'll like them, ideally for several 42 | different questions. 43 | (4) Add and commit your files: from the top folder again, execute 44 | "git add ." followed by "git commit -m 'a description'". Voila! Your 45 | "master" git branch is ready for repotasks! 46 | (5) If you need a slightly changed set of files for another repotask, you 47 | should check out a new branch. To do that, execute: 48 | 'git checkout -b branch_name'. Then repeat steps (3) and (4). 49 | 50 | Repeat as needed. Remember to commit your changes (as in (4) above) if you 51 | many any further changes; or if you want to reject them and go back to 52 | your most recent commit, execute "git reset --hard". 53 | REPOSETUP 54 | }, 55 | { 56 | title: "how to create a repotask", 57 | content: <<-NEWREPOTASK 58 | To start a new repotask, from the task list, press 'r'. You'll be shown a 59 | list of your repos; you'll have to choose one. Then you'll have to choose 60 | from the branches of that repo. HINT: If you have trouble remembering 61 | exactly how a branch looks, you can navigate (on the command line) to the 62 | repo and execute "git checkout ". When you do this, you might 63 | have to commit or reset some changes if your tree is "unclean." 64 | 65 | The rest of the procedure is similar to that for regular tasks, except for 66 | the "Input Run Commands" screen; here, you will have to input whatever 67 | commands you'll need in order to run your program. This might include such 68 | things as opening a web page in a browser, starting a server, or migrating 69 | a database. (Note, you'll have to migrate down any database changes after 70 | answering a question.) Basically, whatever commands you'd have to execute 71 | if you were simply doing the task in a development context, list them. 72 | 73 | Note that you can edit all of this information within the task view page. 74 | 75 | It might seem like a bit of work to add a repotask, but it's not too bad 76 | after you've learned how. And it's really, really worth it! 77 | NEWREPOTASK 78 | }, 79 | { 80 | title: "how to do (answer) a repotask", 81 | content: <<-DOREPOTASK 82 | Doing a repotask is similar to doing a regular task. The main difference 83 | is that you have to choose which file to edit, and you might have to work 84 | with a few different languages to do the task (e.g., HTML and CSS). To 85 | edit a particular file, simply press the number from the "FILES TO EDIT 86 | FOR THIS TASK" list. If the file isn't there, you can always press 'o' to 87 | open the repo or 'fi' to add files to the "FILES TO EDIT" list. 88 | 89 | The only other things that are quite different are (1) your work is 90 | deleted from the repo (Revuu executes 'git reset --hard' for you) so that 91 | you maintain a "clean tree," something needed for Git to work properly. A 92 | copy of your most recent attempt is, however, saved in an archive. Also, 93 | (2) when you press 'r' to run, Revuu runs whatever commands you told it 94 | to run in setting up the repotask. If you need to edit those commands (not 95 | an uncommon thing), press 'c' for commands. 96 | 97 | Doing everything else--saving a review, configuring language, editing 98 | instructions, etc.--works the same as with regular tasks. 99 | DOREPOTASK 100 | }, 101 | { 102 | title: "why are repotasks (and Git) necessary?", 103 | content: <<-REPOSNEC 104 | Repotasks are necessary because most of the more advanced programming 105 | tasks involve multiple interacting files (and media and databases and 106 | APIs). The most obvious example of this are modern websites, which use 107 | HTML, CSS, and JavaScript. 108 | 109 | The cool thing about Revuu and repotasks is that they actually enable you 110 | to repeatedly practice relatively complex tasks without setting up a 111 | complex context again and again--Revuu does that for you, once you've set 112 | up the question once. Now you have a way to ensure you won't forget the 113 | fiddly little details of CSS and other complex programming tasks. 114 | 115 | Git is necessary to manage the many versions of a repo that you'll want to 116 | add in order to make many questions about some tech. Revuu handles all the 117 | complexity of managing Git branches for you; all you have to do is make 118 | sure you keep your tree "clean," i.e., decide whether to commit a change 119 | to a branch or else reset it. 120 | REPOSNEC 121 | } 122 | ] 123 | end 124 | end 125 | -------------------------------------------------------------------------------- /lib/helpers.rb: -------------------------------------------------------------------------------- 1 | module Helpers 2 | 3 | # NOTE: move some methods to settings_helper.rb and some to help_helper.rg 4 | 5 | # Clear screen and print header. Used throughout the app. RF 6 | def clear_screen 7 | system("clear") 8 | header 9 | end 10 | 11 | # Used in clear_screen above. RF 12 | def header 13 | puts sprintf("%-69s%s", " * R * E * V * U * U *", "v. 3.6"). 14 | colorize(:black).colorize(background: :white) 15 | puts '' 16 | end 17 | 18 | def get_user_command(leader) 19 | extra_space = ( ("=+a".include? (leader)) ? "" : " ") 20 | print "#{extra_space}#{leader}> " 21 | gets.chomp 22 | end 23 | 24 | # This is copied into new Java answers. Used throughout class Task. RF 25 | def java_starter 26 | return <<~JAVASTARTER 27 | public class answer_#{@id} { 28 | public static void main(String[] args) { 29 | /* do not edit 'answer_' */ 30 | } 31 | } 32 | JAVASTARTER 33 | end 34 | 35 | # Given an array, show it with numbers (separate method) and solicit and 36 | # return the element corresponding to the user choice (or nil if user quits). 37 | def wrap_items_with_numbers(arr, args = {}) 38 | args[:enter_OK] ||= false 39 | args[:minus_mode] ||= false 40 | show_array_with_numbers(arr, args) 41 | choice = 0 42 | minus = false # Allows user to use this interface to delete from list. 43 | until ( choice.between?(1,arr.length) || (choice =~ /(\-)(\d+)/ && 44 | $2.between?(1,arr.length)) 45 | ) do 46 | or_enter = args[:enter_OK] ? 'or Enter ' : '' 47 | or_minus = args[:minus_mode] ? '; -# to remove' : '' 48 | puts "Choose a number (#{or_enter}or 'q' to quit#{or_minus}):" 49 | choice = get_user_command('r') 50 | return '' if choice == '' && args[:enter_OK] 51 | return 'q' if choice == 'q' 52 | # If user inputs something of the form '-#' (e.g., '-2') then handle 53 | # specially. 54 | if choice =~ /(\-)(\d+)/ 55 | choice = $2.to_i 56 | return choice, true # true = This is a removal. 57 | else 58 | choice = choice.to_i 59 | end 60 | end 61 | chosen_item = arr[choice-1] 62 | end 63 | 64 | # Display an array in (1) format (2) like (3) this, wrapped. 65 | def show_array_with_numbers(arr, args = {}) 66 | args[:colored] ||= false # Used in color-coding file names. 67 | # FOR LATER: EITHER PUT THE MOST RECENT ON THE TOP OR MAKE DEFAULT with *. 68 | # Actually do the displaying. Note, available_editors is a method. 69 | width = 0 70 | arr.each_with_index do |element,i| 71 | item = "(#{i+1}) #{element} " # Works with paths... 72 | # Decide whether to wrap (add newline). 73 | if item.length + width >= 75 74 | puts('') 75 | width = 0 76 | item = ' ' + item # Add padding to wrapped item. 77 | end 78 | # Add padding to first item. 79 | (item = ' ' + item) if i == 0 80 | # Always adds to line length and prints item. 81 | width += item.length 82 | item = args[:colored] ? colored(item) : item 83 | print item 84 | end 85 | print "\n\n" 86 | end 87 | 88 | # Takes a string from #show_array_with_numbers and colors it, if it 89 | # corresponds to a language type. 90 | def colored(item) 91 | Lang.defined_langs.each do |lang| 92 | ext = lang[:ext] 93 | if item =~ /( ?\(\d+\) )([\w\s\/]+\.#{ext} )$/ 94 | return $1 + $2.colorize(lang[:color]) 95 | end 96 | lname = lang[:name] 97 | if item =~ /( ?\(\d+\) )(#{lname} )$/ 98 | return $1 + $2.colorize(lang[:color]) 99 | end 100 | end 101 | return item # If no color matches. 102 | end 103 | 104 | # New, important method determines the directory within data/answers/ and 105 | # data/starters that a file goes in. 106 | # # Given an ID (string), return the directory (string) it goes in. 107 | # Returns in the form '00000/0000/000/00'. 108 | def determine_directory(id) 109 | id = id.to_s.split('').reverse.join 110 | # Supports up to ten thousands of answers. 111 | id =~ /^(\d)(\d?)(\d?)(\d?)(\d?)/ 112 | tens = $2 == '' ? '0' : $2 113 | huns = $3 == '' ? '0' : $3 114 | thous = $4 == '' ? '0' : $4 115 | tthous = $5 == '' ? '0' : $5 116 | "#{tthous}0000/#{thous}000/#{huns}00/#{tens}0" 117 | end 118 | 119 | ############################################################################## 120 | # DATA MIGRATION 121 | # Until Revuu 3.2, all answers were held in a single directory, data/answers. 122 | # Now we are putting them all into nested folders based on thousands, 123 | # hundreds, and tens. Thus the user's answer for #32 will go in 124 | # data/answers/0000/000/30; answer #2485 in data/answers/2000/400/80. 125 | 126 | # Updates file locations for those few people who saved data from 127 | def update_file_locations 128 | # Make array of answer files. 129 | answers = Dir["data/answers/*"] 130 | starters = Dir["data/starters/*"] 131 | files = answers + starters 132 | files.each do |f| 133 | # Skip it if it doesn't match; if it does, extract its ID. 134 | next unless f =~ /(answer_|answer_old_|starter_)(\d+)\./ 135 | # For each answer file, concatenate its proper directory. 136 | inner_location = determine_directory($2) 137 | # If the directory doesn't exist, create it. 138 | dir = if (f =~ /\/starter_/) 139 | "data/starters/#{inner_location}" 140 | else 141 | "data/answers/#{inner_location}" 142 | end 143 | p dir 144 | `mkdir -p #{dir}` unless File.directory?(dir) 145 | # Move the answer file to the directory. 146 | `mv #{f} #{dir}` 147 | end 148 | end 149 | 150 | end 151 | 152 | module Colorize::InstanceMethods 153 | alias :old_colorize :colorize 154 | end 155 | 156 | class String 157 | def color_text(r, g, b) 158 | "\033[38;2;#{r};#{g};#{b}m#{self}\u001b[0m" 159 | end 160 | 161 | def color_bg(r, g, b) 162 | "\033[48;2;#{r};#{g};#{b}m#{self}\u001b[0m" 163 | end 164 | 165 | # Takes symbol with English color name, returns colored string. 166 | # Examples: "foo".colorize(:red) => returns red string. 167 | # "foo".colorize(background: :blue) => returns blue background string. 168 | def colorize(color) 169 | return self unless color # If nil color is passed, return uncolored string. 170 | if ENV["COLORTERM"] 171 | color.class == Symbol ? 172 | self.color_text(*RGB_CODES[color]) : 173 | self.color_bg(*RGB_CODES[color[:background]]) 174 | else 175 | if color.class == Symbol 176 | color = COLOR_MAPPER.has_key?(color) ? COLOR_MAPPER[color] : color 177 | self.old_colorize(color) 178 | else 179 | color[:background] = COLOR_MAPPER.has_key?(color[:background]) ? 180 | COLOR_MAPPER[color[:background]] : color[:background] 181 | self.old_colorize(color) 182 | end 183 | end 184 | end 185 | 186 | RGB_CODES = { 187 | # Original "Colorize" gem colors, for backwards-compatibility. 188 | black: [46, 52, 54], 189 | red: [204, 0, 0], 190 | green: [78, 154, 6], 191 | yellow: [205, 176, 48], 192 | blue: [52, 101, 164], 193 | magenta:[117, 80, 123], 194 | cyan: [6, 152, 154], 195 | white: [211, 215, 207], 196 | light_black: [85, 87, 83], 197 | light_red: [239, 41, 41], 198 | light_green: [158, 229, 90], 199 | light_yellow: [252, 233, 79], 200 | light_blue: [114, 159, 207], 201 | light_magenta:[173, 127, 168], 202 | light_cyan: [52, 226, 226], 203 | light_white: [238, 238, 236], 204 | # New colors. 205 | free_speech_red: [169, 16, 0], # Ruby 206 | festival: [233, 212, 77], # JavaScript 207 | denim: [27, 132, 193], # CSS 208 | tahiti_gold: [233, 98, 40], # HTML 209 | chateau_green: [69, 181, 80], # Bash 210 | malibu: [93, 164, 221], # SQL/PSQL 211 | echo_blue: [163, 179, 198], # C 212 | med_aquamarine: [98, 202, 175], # C++ 213 | carrot_orange: [240, 148, 33], # Java 214 | saffron: [247, 191, 48], # Python 215 | brown: [165, 42, 42], # Rust 216 | medium_purple: [139, 87, 217], # Bootstrap 217 | mandarian_orange: [154, 37, 42] # Rails 218 | } 219 | 220 | # Mapping new color names to old names for use by Colorize gem. 221 | COLOR_MAPPER = { 222 | free_speech_red: :red, # Ruby 223 | festival: :light_yellow, # JavaScript 224 | denim: :blue, # CSS 225 | tahiti_gold: :light_red, # HTML 226 | chateau_green: :white, # Bash 227 | malibu: :cyan, # SQL/PSQL 228 | echo_blue: :light_blue, # C 229 | med_aquamarine: :blue, # C++ 230 | carrot_orange: :magenta, # Java 231 | saffron: :yellow, # Python 232 | brown: :red, # Rust 233 | medium_purple: :light_magenta, # Bootstrap 234 | mandarian_orange: :red # Rails 235 | } 236 | end 237 | -------------------------------------------------------------------------------- /lib/repotask_factory.rb: -------------------------------------------------------------------------------- 1 | # "Factory module" that prepares the data needed to initialize a Task of the 2 | # RepoTask variety. 3 | module RepotaskFactory 4 | 5 | # Cf. TaskFactory#generate_new_task; uncommented items might be commented 6 | # there. 7 | def generate_new_repotask 8 | clear_screen 9 | task_data = {saved: false} 10 | lang = '' 11 | repo = '' # Used by get_branch & get_files. 12 | branch = '' # Used by get_files. 13 | new_task_lambdas = [ 14 | # Get repo for this task. 15 | { repo: -> { get_repo } }, 16 | # Get git branch. 17 | { branch: -> { get_branch(repo) } }, 18 | # Get list of files user will have to edit in order to do task. 19 | { files: -> { puts "CHOOSE FILES:"; get_files(repo, branch) } }, 20 | # The next three are the same as TaskFactory. 21 | { lang: -> { get_initial_language_from_user('r') } }, # In TaskFactory. 22 | { instructions: -> { get_instructions_from_user(lang) } }, # Ditto. 23 | { tags: -> { get_tags_from_user(lang) } }, # Ditto. 24 | # Get command(s) needed to run the app. 25 | { run_commands: -> { get_run_commands } } 26 | ] 27 | new_task_lambdas.each do |lhash| 28 | lhash.each do |label, methd| 29 | value = methd.call 30 | return nil if value == 'q' # Quit abandons task-making. 31 | # This is the list of required values. 32 | if (value.nil? && [:repo, :branch, :lang, :instructions, 33 | :tags].include?(label)) 34 | return nil # Abandon task-making if a required value is missing. 35 | end 36 | task_data[label] = value 37 | repo = value if label == :repo # Needed for later lambdas. 38 | branch = value if label == :branch 39 | lang = value if label == :lang # Ditto. 40 | clear_screen 41 | end 42 | end 43 | Repotask.new(task_data) 44 | end 45 | 46 | ############################################################################ 47 | # REPO METHODS 48 | # Extracts and returns choice of repo or 'q' from user, or returns nil. 49 | def get_repo 50 | return nil unless repo_exists? 51 | puts "CHOOSE REPO:" 52 | repo = solicit_choice_of_repo_from_user 53 | end 54 | 55 | # Checks for an actual repo in repos/. Just needs to be a directory; could 56 | # be empty. 57 | def repo_exists? 58 | result = Dir["./data/repos/*"].any? do |item| 59 | File.directory?(item) 60 | end 61 | unless result 62 | puts "You have no repos. Please make some (get [h]elp if necessary)." 63 | print "Press Enter to continue..." 64 | gets 65 | end 66 | result 67 | end 68 | 69 | def solicit_choice_of_repo_from_user 70 | puts "Choose the repo that you'll be making the task about." 71 | puts "Your repos (in data/repos/):" 72 | # First, get a list of actual directories in data/repos/. 73 | repos = Dir["data/repos/*"].select{|r| File.directory?(r)} 74 | repos.map! {|r| r.split("/")[-1]} # Only want the folder names themselves. 75 | repo = wrap_items_with_numbers(repos) # Returns user choice. 76 | end 77 | 78 | ############################################################################ 79 | # GIT BRANCH METHODS 80 | # Extracts and returns choice of branch or 'q' from user, or returns nil. 81 | def get_branch(repo) 82 | return nil unless branch_exists?(repo) 83 | puts "CHOOSE GIT BRANCH:" 84 | branch = solicit_choice_of_branch_from_user(repo) 85 | end 86 | 87 | # Return boolean: does the repo have a git branch? 88 | def branch_exists?(repo) 89 | begin 90 | g = Git.open("data/repos/#{repo}") 91 | g.branches.local.find {|b| b.full} # A branch has a "full" name. 92 | rescue 93 | puts "NOTE!" 94 | puts "Directory '#{repo}' hasn't been initialized with git yet." 95 | puts "Please navigate to it and type 'git init'. Also, commit a branch," 96 | puts "at least the master branch. I.e., you will also have to add a " 97 | puts "commit, i.e., execute the commands \"git add .\" and" 98 | puts "\"git commit -m 'initial commit'\". If you want to make different" 99 | puts "versions of the repo (you probably will), you will have to make" 100 | puts "*and commit* a different git branch for each. If you don't know" 101 | puts "how to make git branches ('git branch -b ') and make" 102 | puts "commits, you won't be able to make repotasks.\n\n" 103 | print "Press Enter to continue..." 104 | gets 105 | nil 106 | end 107 | end 108 | 109 | def solicit_choice_of_branch_from_user(repo) 110 | g = Git.open("data/repos/#{repo}") 111 | branches = g.branches.local 112 | .map {|b| b.full} 113 | .reject {|b| b =~ /\d\_archive$/} 114 | puts "Choose the git branch your task is based on." 115 | puts "WARNING! Your latest commit, whatever it is, will be used." 116 | puts "Revuu never makes git commits for you, but will reset to the latest.\n\n" 117 | puts "Your branches:" 118 | branches = sort_branches_by_git_commit_order(repo, branches) 119 | branch = wrap_items_with_numbers(branches) 120 | end 121 | 122 | # I want the branches in order of most recent commit. ruby-git doesn't 123 | # seem to support this, so I had to do this hacky thing. 124 | def sort_branches_by_git_commit_order(repo, branches) 125 | branches_ordered = `cd data/repos/#{repo}&&git for-each-ref --sort=committerdate` 126 | branches_ordered = branches_ordered.split("\n") 127 | .reverse 128 | .map {|br| br.split('/')[-1]} 129 | # Now, re-order branches in the same order. 130 | branches.sort! do |x,y| 131 | branches_ordered.find_index(x) <=> branches_ordered.find_index(y) 132 | end 133 | branches 134 | end 135 | 136 | ########################################################################### 137 | # FILES METHODS 138 | # Extracts and returns an array of files (maybe just one long) that the 139 | # user will change in order to do the task. 140 | def get_files(repo, branch, existing_choices = []) 141 | begin 142 | checkout_branch(repo, branch) # Files might only be available on one branch. 143 | return nil unless any_files_exist?(repo) 144 | files = all_repo_files(repo) 145 | user_chosen_files = get_file_array_from_user(files, existing_choices) 146 | rescue Exception => e 147 | print "Sorry, you can't use that branch:\n\n" 148 | puts e 149 | print "\nPress any key to continue..." 150 | gets 151 | return 'q' 152 | end 153 | end 154 | 155 | # As the title says: given a repo and a branch, check it oooouuuuut! 156 | def checkout_branch(repo, branch) 157 | g = Git.open("data/repos/#{repo}") 158 | g.branch(branch).checkout 159 | end 160 | 161 | # Return boolean: does the repo have any files at all? 162 | def any_files_exist?(repo) 163 | all_repo_files(repo).length > 0 164 | end 165 | 166 | def all_repo_files(repo) 167 | Dir[ File.join("data/repos/#{repo}", '**', '*') ] 168 | .reject {|d| File.directory? d} 169 | .reject {|f| f =~ /tmp\// || f =~ /bin\//} 170 | .map {|f| f.gsub!("data/repos/#{repo}/", '') } 171 | #.sort 172 | end 173 | 174 | # existing_choices is a file array provided by the presently-existing 175 | # Repotask#files. Used when get_files is called from the Repotask view. 176 | def get_file_array_from_user(files, existing_choices) 177 | puts <<~GETFILES 178 | To do the task, the user will have to edit some files. Please specify 179 | which files. NOTE: Press Enter by itself to finish (or skip). 180 | GETFILES 181 | user_chosen_files = existing_choices 182 | files -= existing_choices 183 | ans = nil 184 | file = nil 185 | until file == '' 186 | # Show files with choice 187 | unless user_chosen_files.empty? 188 | puts "\nFiles you've chosen so far: " 189 | show_array_with_numbers(user_chosen_files) 190 | puts "Files remaining:" 191 | end 192 | # 'true' on next line allows user to return choice of ''. 193 | file, remove = 194 | wrap_items_with_numbers(files, 195 | {enter_OK: true, minus_mode: true, colored: true}) unless 196 | files.empty? 197 | return 'q' if file == 'q' 198 | break if file == '' 199 | # If wrap_items_with_numbers returns a removal, then it returns an 200 | # integer (the number of the file to remove from user_chosen_files). 201 | if remove 202 | file = user_chosen_files[file - 1] 203 | user_chosen_files -= [file] 204 | files << file 205 | file = nil # Because otherwise this will be added in again. This code sucks! 206 | end 207 | # If there are no more files choice, ask user to confirm or remove one. 208 | if files.empty? 209 | print " No files remaining.\n\n" 210 | user_chosen_files_copy = user_chosen_files.dup 211 | user_chosen_files, removed_file = 212 | remove_file_from_complete_list(user_chosen_files) 213 | return 'q' if removed_file == 'q' 214 | files = [removed_file] if removed_file 215 | end 216 | break if files.empty? # 'files' array might be no longer empty. 217 | files -= [file] 218 | (user_chosen_files << file) if file 219 | end 220 | user_chosen_files ? user_chosen_files : nil 221 | end 222 | 223 | def remove_file_from_complete_list(files) 224 | puts "You've included all files from the repo for editing. Press Enter" 225 | puts "to confirm or enter the number of a file to remove." 226 | response = wrap_items_with_numbers(files, {enter_OK: true, colored: true}) 227 | return 'q' if response == 'q' 228 | response = response == '' ? nil : response 229 | return (files - [response]), response 230 | end 231 | 232 | ############################################################################ 233 | # RUN COMMANDS METHOD 234 | def get_run_commands 235 | puts "INPUT RUN COMMANDS:\n" 236 | run_commands = launch_external_input_for_new_task( 237 | type: 'run_commands', 238 | prompt: "On the next screen, enter at least one command line\n" + 239 | "command needed to see the code in action. Required.", 240 | required: true ) 241 | end 242 | 243 | end 244 | -------------------------------------------------------------------------------- /lib/settings_helper.rb: -------------------------------------------------------------------------------- 1 | module SettingsHelper 2 | 3 | # Accepts a hash (e.g., {'lang' => 'C'}) & overwrites settings file. RF 4 | def update_settings_file(args) 5 | # Ensure a settings file exists. 6 | create_settings_file_if_necessary 7 | settings_hash = load_settings_into_hash 8 | # Merge new language info into hash. 9 | hash_to_write = settings_hash.merge(args) 10 | # Write new hash. 11 | File.write("./data/settings.json", hash_to_write.to_json) 12 | end 13 | 14 | # Checks if there is no data/settings.json file. Creates one and populates it 15 | # with some defaults, if not. RF 16 | def create_settings_file_if_necessary 17 | settings_file = "data/settings.json" 18 | if File.exist?(settings_file) && File.stat(settings_file).size > 0 19 | return 20 | else 21 | system("touch #{settings_file}") 22 | ur_settings = { 'lang' => 'Other', 23 | 'texted' => 'Pico', 24 | 'last_change' => DateTime.now.to_s, 25 | 'unsaved_changes' => true, 26 | 'last_archive' => DateTime.now.to_s } 27 | File.write(settings_file, ur_settings.to_json) 28 | end 29 | end 30 | 31 | # Loads JSON from settings.json into hash, or else returns {}. RF 32 | def load_settings_into_hash 33 | raw_settings = File.read("./data/settings.json") 34 | raw_settings = {} if raw_settings == "" 35 | settings_hash = ( raw_settings == {} ? {} : JSON.parse(raw_settings) ) 36 | end 37 | 38 | # Load the default language and other settings from file. RF 39 | def load_defaults_from_settings 40 | # Revuu doesn't assume a settings file exists, in case of user error. 41 | create_settings_file_if_necessary 42 | # Load settings from data/settings.json. 43 | settings_hash = load_settings_into_hash 44 | # Next, check settings for completeness, and fix if incomplete. 45 | # Does a language setting exist? 46 | ensure_language_setting_exists(settings_hash) 47 | # Does a text editor setting exist and is it still OK? 48 | ensure_text_editor_setting_kosher(settings_hash) 49 | # Does settings contain a last updated, last archive, unsaved changes boolean? 50 | ensure_archive_settings_kosher(settings_hash) 51 | end 52 | 53 | # Checks that the settings file has a language setting; if not, forces user 54 | # to pick one. RF 55 | def ensure_language_setting_exists(settings_hash) 56 | # Check if 'lang' key exists; if not, create and save. 57 | if settings_hash['lang'] 58 | # Given a programming language name, return a Lang object, stored in a global. 59 | $lang_defaults = Lang.new(settings_hash['lang']) 60 | else 61 | puts "LANGUAGE SETTING MISSING." 62 | message = choose_default_language # Saves the language if the user picks one. 63 | puts message, '' 64 | end 65 | end 66 | 67 | # Checks that the settings file has an available text editor setting; if not, 68 | # forces user to pick one. RF 69 | def ensure_text_editor_setting_kosher(settings_hash) 70 | if settings_hash['texted'] && 71 | ensure_text_editor_still_available(settings_hash['texted']) # Self-truthing. 72 | $texted = settings_hash['texted'] 73 | $textedcmd = text_editors[$texted] 74 | else # i.e., there is no 'texted' setting. 75 | puts "TEXT EDITOR SETTING MISSING." 76 | message = choose_text_editor(true) # i.e., a choice is required. 77 | puts message, '' 78 | update_settings_file({'lang': $lang_defaults.name}) 79 | end 80 | end 81 | 82 | # Checks whether a given text editor is available; if not, forces user to 83 | # pick one. RF 84 | def ensure_text_editor_still_available(texted) 85 | # Check if text editor in settings is still available. If not, choose new. 86 | unless available_editors.include? texted 87 | puts "YOUR OLD TEXT EDITOR (#{texted.upcase}) IS NO LONGER INSTALLED." 88 | message = choose_text_editor(true) # i.e., a choice is required. 89 | puts message, '' 90 | return true 91 | else 92 | return true 93 | end 94 | end 95 | 96 | # Checks and assigns archive settings (from setting file); if they don't 97 | # exist, populates with some defaults. RF 98 | def ensure_archive_settings_kosher(settings_hash) 99 | settings_to_merge = {} # Probably won't be any, but just in case... 100 | if settings_hash['last_change'] 101 | $last_change = settings_hash['last_change'] 102 | else 103 | # Pretend the last change was now. 104 | $last_change = DateTime.now.to_s 105 | settings_to_merge.merge!({'last_change' => $last_change}) 106 | end 107 | # defined? because the value is either 'true' or 'false', so testing the 108 | # value itself messes up the logic. 109 | if defined? settings_hash['unsaved_changes'] 110 | $unsaved_changes = settings_hash['unsaved_changes'] 111 | else 112 | # If there isn't an unsaved changes setting, prompt the user to save. 113 | $unsaved_changes = true 114 | settings_to_merge.merge!({'unsaved_changes' => $unsaved_changes}) 115 | end 116 | if settings_hash['last_archive'] 117 | $last_archive = settings_hash['last_archive'] 118 | else 119 | # No idea when last archive was, so just set it to now. 120 | $last_archive = DateTime.now.to_s 121 | settings_to_merge.merge!({'last_archive' => $last_archive}) 122 | end 123 | # If there was any missing data, write it to settings. 124 | update_settings_file(settings_to_merge) unless settings_to_merge.empty? 125 | end 126 | 127 | # Should be called whenever a task is created or changed. Generates a new 128 | # "last [most recent] change" timestamp as well as a "last archive" which is 129 | # set to an arbitrary time before the task is marked as created. These are 130 | # used to calculate whether there are unsaved changes. Finally, saves these 131 | # three values to settings. RF 132 | def save_change_timestamp_to_settings 133 | $last_change = DateTime.now.to_s 134 | $last_archive = (DateTime.now - 1).to_s unless $last_archive 135 | $unsaved_changes = DateTime.parse($last_change) > DateTime.parse($last_archive) 136 | update_settings_file( { 'last_change' => $last_change, 137 | 'last_archive' => $last_archive, 138 | 'unsaved_changes' => $unsaved_changes } ) 139 | end 140 | 141 | # Used both at startup and as a user option function, this both solicits and 142 | # sets a new text editor global, returning a message to the user. RF 143 | def choose_text_editor(choice_required = false) 144 | # Display text editors available on the user's system. 145 | display_list_of_editors_to_user 146 | editor_num = nil 147 | # Select new editor; two circumstances of doing so: 148 | # user is required to choose an editor if none is saved in settings... 149 | if choice_required 150 | until editor_num && editor_num.between?(0,available_editors.length-1) 151 | # Let user select new editor. 152 | puts "Please select which one you'll use to write answers." 153 | editor_num = get_user_command('e').to_i - 1 154 | puts "Choose a number between 1 and #{available_editors.length}." unless 155 | editor_num.between?(0,available_editors.length-1) 156 | end 157 | else # ...or user is simply switching editors. 158 | puts "Please select which one you'll use to write answers." 159 | editor_num = get_user_command('e').to_i - 1 160 | unless editor_num.between?(0,available_editors.length-1) 161 | return "Sticking with #{$texted}." 162 | end 163 | end 164 | # Reset text editor global ($texted). 165 | edname = available_editors[editor_num] 166 | $texted = edname 167 | $textedcmd = text_editors[edname] 168 | update_settings_file({'texted' => edname}) 169 | return "OK, you'll use #{edname}." 170 | end 171 | 172 | # Both compiles a list of available editors and displays them to the user. RF 173 | def display_list_of_editors_to_user 174 | default_msg = " (default = *)" if $texted 175 | puts "Text editors on your system#{default_msg}:" 176 | width = 0 177 | # Actually do the displaying. Note, available_editors is a method. 178 | available_editors.each_with_index do |editor,i| 179 | default_asterisk = '*' if defined? $texted and $texted == editor 180 | item = "(#{i+1}) #{editor}#{default_asterisk} " 181 | # Decide whether to wrap (add newline). 182 | if item.length + width >= 75 183 | puts('') 184 | width = 0 185 | end 186 | # Always adds to line length and prints item. 187 | width += item.length 188 | print item 189 | end 190 | puts '' 191 | end 192 | 193 | # Compares Revuu's list of text editors with what is available on the user's 194 | # system; returns sorted array of the names of available text editors. RF 195 | def available_editors 196 | # Given list of text editors, return those available on this system. 197 | available = text_editors.select do |name,command| 198 | `which #{command}`.length > 0 199 | end 200 | available.keys.sort # Alpha order names and return as array. 201 | end 202 | 203 | # Could be a variable and/or constant, and could be stored in a JSON file, 204 | # but for consistency with 'available_editors', I made it a global method. RF 205 | def text_editors 206 | { 'Sublime Text' => 'subl', 207 | 'Atom' => 'atom', 208 | 'Nano' => 'nano', 209 | 'Pico' => 'pico', 210 | 'Visual Studio Code' => 'code', 211 | 'vi' => 'vi', 212 | 'vim' => 'vim', 213 | 'Eclipse' => 'eclipse', 214 | 'IntelliJ' => 'idea', 215 | 'Android Studio' => 'studio', 216 | 'Xcode' => 'xcode', 217 | 'Netbeans' => 'netbeans', 218 | 'PhpStorm' => 'phpstorm', 219 | 'PyCharm' => 'pycharm', 220 | 'Emacs' => 'emacs', 221 | 'gedit' => 'gedit' } 222 | end 223 | 224 | # After getting a language from Lang::choose_default, saves to defaults. 225 | # Returns nil if language saved properly; returns language name otherwise. RF 226 | def choose_default_language 227 | puts "OK, let's choose a default language." 228 | default = $lang_defaults ? $lang_defaults.name : 'Other' 229 | new_default = Lang.solicit_languages_from_user('p', default) 230 | if (new_default && new_default != default && new_default != 'q') 231 | update_settings_file({'lang' => new_default}) 232 | $lang_defaults = Lang.new(new_default) 233 | message = "Saved #{$lang_defaults.name} as the default language." 234 | else 235 | # This is necessary because sometimes the setting won't be saved. 236 | update_settings_file({'lang' => default}) 237 | $lang_defaults = Lang.new(default) 238 | message = "Sticking with #{default}." 239 | end 240 | return message 241 | end 242 | 243 | end 244 | -------------------------------------------------------------------------------- /lib/task_factory.rb: -------------------------------------------------------------------------------- 1 | # This module has the main methods needed to compile the data needed to create 2 | # a new task. It is a mixin (extension) of class Task. 3 | module TaskFactory 4 | 5 | # Prepares data for new task. 6 | # Launched only by tasklist 'n' command. Compiles data needed to create a 7 | # task. At end, calls Task#new and returns the new task instance (or nil). 8 | # Note, this is basically just a series of user interfaces that prompt for 9 | # input and offer to skip (sometimes) or to quit. Quitting returns nil. RF 10 | def generate_new_task 11 | clear_screen 12 | # This is a hash we'll be passing to Task.new, which uses saved: false in 13 | # order to signal #initialize to populate 14 | new_task_data = {saved: false} 15 | lang = '' # Capture lang value when created; used in lambdas below. 16 | # Create methods array: these are the methods needed to generate task data. 17 | # Labels correspond to Task attributes. 18 | new_task_lambdas = [ 19 | { lang: -> { get_initial_language_from_user('n') } }, # n = prompt 20 | { instructions: -> { get_instructions_from_user(lang) } }, 21 | { starter: -> { starter_arg = (lang == 'Java' ? 'Java' : false); 22 | starter_code_sequence(starter_arg) } }, 23 | { tags: -> { get_tags_from_user(lang) } } 24 | ] 25 | # Iterate above lambdas; abandon task-making if 'q', or when nil if 26 | # required. Otherwise, use returned values in new_task_data hash. 27 | new_task_lambdas.each do |lhash| 28 | lhash.each do |label, methd| 29 | value = methd.call 30 | return nil if value == 'q' # Quit abandons task-making. 31 | # This is the list of required values. 32 | if [:lang, :instructions, :tags].include? label && value.nil? 33 | return nil # Abandon task-making if a required value is missing. 34 | end 35 | new_task_data[label] = value 36 | lang = value if label == :lang # Grab the lang; needed for later lambdas. 37 | clear_screen 38 | end 39 | end 40 | # Construct new task! 41 | Task.new(new_task_data) 42 | end # of ::generate_new_task 43 | 44 | # Get language from user; returns a canonical, approved name for saving. RF 45 | def get_initial_language_from_user(prompt) 46 | puts "CHOOSE LANGUAGE:" 47 | lang = Lang.solicit_languages_from_user(prompt, $lang_defaults.name) 48 | end 49 | 50 | # Just a wrapper for launch_external_input... and instructions. RF 51 | def get_instructions_from_user(lang) 52 | instructions = launch_external_input_for_new_task(type: 'Instructions', 53 | prompt: "INPUT INSTRUCTIONS:\nOn the next screen, you'll type in the " + 54 | "instructions for your new task. ", required: true) 55 | instructions = (instructions == 'q' || instructions.nil?) ? instructions : 56 | wrap_overlong_paragraphs(instructions, lang.length) 57 | end 58 | 59 | # Asks the user if he wants to write some starter code. If so, opens a temp 60 | # file in the text editor, then grabs the text when the user gives the OK, 61 | # deletes the file, and returns the text (or nil). RF 62 | def starter_code_sequence(java=nil) # Lang needed for file extension. 63 | starter_desired = get_starter_code? 64 | return 'q' if starter_desired == 'q' 65 | if starter_desired 66 | launch_external_input_for_new_task(type: 'Starter', required: false, prompt: 67 | "Edit the starter code on the next screen.", 68 | java: java) 69 | else 70 | nil 71 | end 72 | end 73 | 74 | # Ask user if he wants to edit starter code up front. RF 75 | def get_starter_code? 76 | puts "EDIT STARTER CODE:" 77 | starter_decision = nil 78 | loop do 79 | puts "Edit some starter code (you can do this later)?" 80 | puts " for [y]es, [n]o, or [q]uit." 81 | starter_decision = get_user_command('n') 82 | break if ('ynq'.include? starter_decision || starter_decision == '') 83 | end 84 | return 'q' if starter_decision == 'q' 85 | (starter_decision == 'y' || starter_decision == '') ? true : false 86 | end 87 | 88 | # Solicit tags from user (not required). RF 89 | def get_tags_from_user(lang) 90 | puts "INPUT TAGS:" 91 | tag_decision = nil 92 | loop do 93 | puts "Edit tags (you can do this later)?" 94 | puts " for [y]es, [n]o, or [q]uit." 95 | tag_decision = get_user_command('n') 96 | break if ('ynq'.include? tag_decision || tag_decision == '') 97 | end 98 | return 'q' if tag_decision == 'q' 99 | tag_decision = (tag_decision == 'y' || tag_decision == '') ? true : false 100 | if tag_decision 101 | tags = launch_external_input_for_new_task(type: 'Tags', prompt: 102 | "Edit tags on the next screen; language-related tags are added automatically.", 103 | required: false) 104 | else 105 | tags = nil 106 | end 107 | # Add standard tags and "massage" user-input tags. 108 | prep_tags(tags, lang) 109 | end 110 | 111 | # Massage user-input tags so they're standardized. Returns tag array. RF 112 | def prep_tags(tags, lang) 113 | # Convert newlines to commas. 114 | tags.gsub!("\n", ',') if tags 115 | # Convert user input string, which should be comma-separated, into array. 116 | # This also initializes a tag array if user didn't input any tags. 117 | tags = (tags ? tags.split(',').map!(&:strip) : []) 118 | # List = this language name + any alts 119 | lang_name_variants = Lang.all_lang_names_and_alts(lang) 120 | # Remove any tags that (case-insensitively) match langs to reject. 121 | tags.reject! {|tag| lang_name_variants.any? {|l| /\A#{l}\Z/i.match(tag) } } 122 | # Making use of an accessor of the Lang class variable 'defined_langs', 123 | # first 'find' the hash matching the param 'lang'; return [:alts] value. 124 | lang_alts = Lang.defined_langs.find {|l| l[:name] == lang }[:alts] 125 | # Put in canonical language tags; splat operators ensure that subarrays aren't created. 126 | lang_name_variants.concat(tags) 127 | end 128 | 129 | # Given a prompt and a test, wring an acceptable answer from the user or let 130 | # him abandon adding the new task. Returns input, nil, or 'q'. RF 131 | def launch_external_input_for_new_task(args) # :prompt, :type, :required, :java 132 | args[:prompt] = (args[:prompt] ? args[:prompt] : "\n") 133 | args[:prompt] += "\nPress Ctrl-W to save and Ctrl-X to submit. " + 134 | "\nPress now to continue or [q]uit." 135 | # Loop = solicit input in external file; verifies or else prompts again. 136 | loop do 137 | puts args[:prompt] 138 | choice = get_user_command('n') 139 | return 'q' if choice == 'q' # Quit to abandon task-creation. 140 | input = get_input_from_external_file(args) 141 | if args[:required] 142 | if input && input.length > 0 143 | puts "#{args[:type]} saved." 144 | return input 145 | else 146 | puts "\n\nPLEASE NOTE:\n#{args[:type]} required." 147 | end 148 | else # input not required 149 | pretty_type = args[:type].gsub(/\_/, " ").capitalize 150 | input ? (puts "#{pretty_type} saved."; return input) : (return nil) 151 | end 152 | end 153 | end 154 | 155 | # Given some arguments, prep and open a temporary file for user input; then 156 | # get input from it and return it. RF 157 | def get_input_from_external_file(args) 158 | tempfile = "tmp/#{args[:type].downcase}.tmp" 159 | system("rm #{tempfile}") if File.file?(tempfile) # Just to be safe. 160 | File.write(tempfile, java_starter) if args[:java] # java_starter in TaskView module. 161 | system("pico #{tempfile}") 162 | input = File.read(tempfile).strip if File.file?(tempfile) 163 | system("rm #{tempfile}") if File.file?(tempfile) 164 | return input 165 | end 166 | 167 | end 168 | -------------------------------------------------------------------------------- /lib/wrapping_helper.rb: -------------------------------------------------------------------------------- 1 | module WrappingHelper 2 | 3 | # Given a string representing the contents of a longish file, output a 4 | # similar string with newlines redistributed so that the likely paragraphs 5 | # are wrapped before n (=75) characters while the code bits are not wrapped. 6 | # Spacer is used when the first line will have, e.g., '(JavaScript) '. 7 | def wrap_overlong_paragraphs(para_string, spacer=0) 8 | # First, for instruction fields that feature e.g. '(Ruby)', insert a 9 | # placeholder into the text (temporarily) so wrapping looks good when 10 | # displayed with those prepended strings. 11 | spacer += 3 if spacer > 0 # for '(', ')', and ' ' 12 | para_string = ('x' * spacer) + para_string 13 | # Next, divide para (which is one long string with potentially many \n 14 | # in it) into an array of *likely* paragraphs. 15 | # Identify potential paragraphs (=two or more newlines). 16 | paras = para_string.split(/\n\n/) 17 | # Width at wrapping can be univerally set from here. 18 | width = 75 19 | # Iterate array and output hash with "is it an actual para' data. 20 | para_hashes = test_if_actual_paras(paras, width) 21 | # Then, wrap the likely paragraphs (those marked 'true'). 22 | paras = para_hashes.map do |para| 23 | if para[:is_wrappable] # Wrap if it's a wrappable paragraph. 24 | wrap(para[:text], width) 25 | else # Otherwise, return the unwrapped paragraph. 26 | para[:text] 27 | end 28 | end 29 | paras.join("\n\n")[spacer..-1] 30 | end 31 | 32 | # Output an array of hashes with data about whether a para is really a para. 33 | def test_if_actual_paras(paras, width) # 'paras' is an array of strings (=paras). 34 | para_hashes = [] 35 | paras.each do |para| 36 | is_wrappable = false 37 | # For each para, split on newlines. 38 | para_lines = para.split("\n") # This is another array of strings (lines). 39 | para_lines = [para_lines] unless para_lines.class == Array 40 | # If there is only one line in para, mark as a paragraph. 41 | if para_lines.length == 1 42 | is_wrappable = true 43 | # If 2 or more lines are under 50 in length, don't wrap. 44 | elsif ( para_lines.count {|line| line.length < 50} >= 2 ) 45 | is_wrappable = false 46 | # Otherwise, if there's a line over 75, wrap. 47 | elsif (para_lines.any? {|line| line.length >= width}) 48 | is_wrappable = true 49 | end 50 | # NOTE FOR LATER: doesn't handle edge cases where the author has a 51 | # paragraph that includes indented lines, using the indented lines as 52 | # paragraph separators. Those sorts of paragraphs will not be wrapped. 53 | para_hashes << {is_wrappable: is_wrappable, text: para} # para = string w/ \n 54 | end 55 | para_hashes 56 | end 57 | 58 | # Simply accepts a string paragraph with \n; wraps it at n characters wide. 59 | def wrap(text, width) 60 | # Strip newlines. 61 | text.gsub!("\n", " ") # 'text' is still a string paragraph, just lacks \n. 62 | # Add them in just before n words. 63 | newlines = [] 64 | line = '' 65 | word_array = text.split(/\s+/) 66 | word_array.each_with_index do |word,i| 67 | # See if this word can be added to a line. 68 | if (line + " " + word).length >= width # Too long! 69 | newlines << line # Add working line to array of lines (no space; end of line). 70 | line = word + " " # Start constructing new working line, with space. 71 | newlines << line if i + 1 == word_array.length # Last word gets own line! 72 | else # Not too long. 73 | line += word + " " # So go ahead and add word to line, with space. 74 | newlines << line if i + 1 == word_array.length # Last word gets own line! 75 | end 76 | end 77 | newlines.map{|l| l.strip}.join("\n") 78 | end 79 | 80 | end 81 | -------------------------------------------------------------------------------- /models/archiv.rb: -------------------------------------------------------------------------------- 1 | # Both logic and UI for creating, loading, and deleting archives of user data. 2 | class Archiv 3 | 4 | def self.launch_archive_system 5 | # Show welcome screen. 6 | welcome_to_archive 7 | # Launch archive loop (in controller). 8 | archive_loop 9 | end 10 | 11 | attr_accessor :archive 12 | 13 | def initialize(args={}) 14 | # Create a tar archive of the contents of data/. 15 | @archive = args[:archive] || set_archive_name # in ArchivView 16 | end 17 | 18 | # Makes a tarball of data/ and saves it in archives/. Returns a string 19 | # containing the name of the archive. 20 | def create_archive 21 | begin 22 | Dir.mkdir("archives") unless Dir.exists?("archives") 23 | Minitar.pack("./data", File.open("archives/#{@archive}", 'wb')) 24 | puts "Created #{@archive}." 25 | save_archive_timestamp_to_settings 26 | rescue StandardError => e 27 | puts "Oops, error: #{e}" 28 | puts "Archive not created." 29 | nil 30 | end 31 | end 32 | 33 | def save_archive_timestamp_to_settings 34 | $last_archive = DateTime.now.to_s 35 | $unsaved_changes = false 36 | update_settings_file({'last_archive' => $last_archive, 'unsaved_changes' => false}) 37 | end 38 | 39 | private 40 | 41 | # Validates a user-submitted string as a suitable archive name; returns 42 | # boolean. 43 | def is_valid?(nm) 44 | return false if nm.nil? 45 | return true if nm == '' 46 | # Name must be a word character 1-20 in length. 47 | unless nm =~ /\W/ 48 | # Don't let user put extension in name. 49 | if /(\.zip|\.gz|\.tar)/.match(nm) 50 | puts "Please don't include the file extension; just use a simple label." 51 | return false 52 | elsif nm[-1] == '_' 53 | puts "Please don't put _ at the end of your string." 54 | return false 55 | else 56 | return true 57 | end 58 | else 59 | puts "Please use only letters, numbers, and _, not over 20 characters." 60 | return false 61 | end 62 | end 63 | 64 | # Require pre-validated name string or ''; constructs and returns filename. 65 | def affix_date_and_ext(nm) 66 | date = DateTime.now.strftime("%Y%m%d") 67 | label = nm == '' ? 'archive' : nm + '_archive' 68 | return "#{label}_#{date}.tar".downcase 69 | end 70 | 71 | end 72 | -------------------------------------------------------------------------------- /models/lang.rb: -------------------------------------------------------------------------------- 1 | # The purpose of the Lang class is primarily to generate (and hold) data about 2 | # a language, given a particular programming language name such as 'Java' or 3 | # 'JavaScript'. Hence, all that is needed to initialize a Lang object is such a 4 | # language name. The class does double duty by exposing language-related class 5 | # methods that could, perhaps, live in a separate helper module. 6 | class Lang 7 | 8 | class << self 9 | # Extracts from user answers that result in the name of the task's language. 10 | # Requires a string identifying the current language. 11 | def solicit_languages_from_user(prompt, current) 12 | default = $lang_defaults ? $lang_defaults.name : 'Other' 13 | # Show user language. 14 | if default != current 15 | puts "Default language is #{default}; the current language is #{current}." 16 | else 17 | puts "Default language is #{default}." 18 | end 19 | # Check which languages are available on the system. 20 | available_langs = @@defined_langs.reject do |l| 21 | `which #{l[:cmd]}` == '' 22 | end 23 | # If, amazingly, there's only one language, say so and exit. 24 | if available_langs.length == 1 25 | puts "There's only one language available and you're using it." 26 | return default 27 | end 28 | # Show available languages to user and solicit a number. 29 | puts "Here are the languages we support that are on your system." 30 | puts "Enter the number of a language; for current; or [q]uit:" 31 | choice = wrap_items_with_numbers(available_langs.map{|l| l[:name]}, 32 | {colored: true, enter_OK: true}) 33 | puts '' 34 | return 'q' if choice == 'q' 35 | return current if (choice == '' || choice == current) 36 | return choice 37 | end 38 | 39 | # Read accessor for @@defined_langs; for use by Task::prep_tags. 40 | def defined_langs 41 | @@defined_langs 42 | end 43 | 44 | # An array of all the language names, plus the alternative names. 45 | # Used in the task_factory's tag massager method. 46 | def all_lang_names_and_alts(lang) 47 | all_names = [] 48 | l = @@defined_langs.find {|l| lang == l[:name]} 49 | all_names << l[:name] 50 | all_names.concat(l[:alts]) unless l[:alts].empty? 51 | all_names 52 | end 53 | 54 | end # of class methods 55 | 56 | # Language data hashes--now a new and improved class variable! 57 | @@defined_langs = 58 | [ 59 | {name: 'Ruby', ext: 'rb', cmd: 'ruby', cmnt: '#', alts: [], spacer: 60 | "puts ''", color: :free_speech_red }, 61 | 62 | {name: 'JavaScript', ext: 'js', cmd: 'node', cmnt: '//', alts: 63 | ['JS', 'Node', 'Node.js'], spacer: "console.log(' ')", color: 64 | :festival}, 65 | 66 | {name: 'HTML', ext: 'html', cmd: 'firefox', cmnt: '', 67 | alts: ['HTML5'], spacer: "

 

", one_main_per_file: true, 68 | color: :tahiti_gold}, 69 | 70 | {name: 'CSS', ext: 'css', cmd: 'firefox', cmnt: '/*', cmnt2: '*/', 71 | alts: ['CSS3'], spacer: '', color: :denim}, 72 | 73 | {name: 'Rails', ext: 'rb', cmd: 'ruby', cmnt: '#', alts: ['RoR', 74 | 'Ruby on Rails'], spacer: "puts", color: :mandarian_orange}, 75 | 76 | {name: 'Bash', ext: 'sh', cmd: '/bin/bash', cmnt: '#', alts: 77 | ['command line', 'shell', 'shell scripting', 'Bash scripting', 'Linux', 78 | 'Unix'], spacer: "echo '<--spacer-->'", color: :chateau_green}, 79 | 80 | {name: 'SQL', ext: 'rb', cmd: 'ruby', cmd2: 'psql tysql postgres', 81 | cmnt: '#', alts: ['postgresql', 'psql'], spacer: "puts ''", color: :malibu}, 82 | 83 | {name: 'C', ext: 'c', cmd: 'gcc', cmd2: './a.out', cmnt: '/*', 84 | cmnt2: '*/', one_main_per_file: true, alts: ['C language', 85 | 'C programming language'], color: :echo_blue}, 86 | 87 | {name: 'C++', ext: 'cpp', cmd: 'g++', cmd2: './a.out', alts: ['C plus plus'], 88 | cmnt: '//', spacer: 'cout<<"\n";', color: :med_aquamarine}, 89 | 90 | {name: 'Java', ext: 'java', cmd: 'javac', cmd2: 'java ', 91 | cmnt: '//', one_main_per_file: true, alts: [], color: :carrot_orange}, 92 | 93 | {name: 'Python', ext: 'py', cmd: 'python', cmnt: '#', alts: [], spacer: 94 | 'print("\n")', color: :saffron}, 95 | 96 | {name: 'Rust', ext: 'rs', cmd: 'rustc', cmd2: './', cmnt: '//', 97 | alts: ['Rust programming language'], one_main_per_file: true, color: :brown, 98 | spacer: 'println!("\n")'}, 99 | 100 | {name: 'Bootstrap', ext: 'html', cmd: 'firefox', cmnt: '', 101 | alts: ['Bootstrap.js'], one_main_per_file: true, color: :medium_purple}, 102 | 103 | {name: 'Other', ext: 'txt', cmd: 'more', cmnt: '#', alts: [], spacer: 104 | "\n<--spacer-->\n", color: :light_magenta} 105 | ] 106 | 107 | # Lang objects expose language data as in a hash. 108 | attr_accessor :name, :ext, :cmd, :cmnt, :cmd2, :cmnt2, :one_main_per_file, 109 | :alts, :lang_alts, :spacer, :color 110 | 111 | def initialize(lang_name) 112 | l = fetch_lang_hash_from_name_cmd(lang_name) 113 | # User changes these with Task#change_language. 114 | @name = l[:name] # Programming language. Get from/set to settings.json. 115 | @ext = l[:ext] # Filename extension. 116 | @cmd = l[:cmd] # Command to execute (or compile). 117 | @cmnt = l[:cmnt] # Comment char in language. 118 | @cmd2 = l[:cmd2] ? l[:cmd2] : false # Run after compiling in, e.g., C. 119 | @cmnt2 = l[:cmnt2] ? l[:cmnt2] : false # Comment-ender in, e.g., C. 120 | @one_main_per_file = l[:one_main_per_file] ? l[:one_main_per_file] : false 121 | @lang_alts = l[:alts] 122 | @spacer = l[:spacer] ? l[:spacer] : '' # String to append to archived file. 123 | @color = l[:color] 124 | return self 125 | end 126 | 127 | # Given a language name, return a language data hash. 128 | def fetch_lang_hash_from_name_cmd(lang_name) # Should be just 'lang' or 'lang_name'. 129 | @@defined_langs.find {|l| l[:name] == lang_name } 130 | end 131 | 132 | end 133 | -------------------------------------------------------------------------------- /models/repotask.rb: -------------------------------------------------------------------------------- 1 | class Repotask < Task 2 | extend RepotaskFactory 3 | include RepotaskController 4 | include RepotaskView 5 | 6 | # Attributes saved in tasks.json: 7 | attr_reader :repo, :branch, :files, :run_commands, :old_branch 8 | # All other attributes should be found in class Task. 9 | 10 | def initialize(args) 11 | super(args) 12 | @repo = args[:repo] 13 | @branch = args[:branch] 14 | @files = args[:files] 15 | @run_commands = args[:run_commands] 16 | # Step (2). (Step (1) is in Task#initialize.) 17 | if @saved # For use when loading old/existing tasks. 18 | @id = args[:id] 19 | @old_branch = calculate_old_branch 20 | else # For use when creating neqw tasks. 21 | @id = calculate_id 22 | @old_branch = calculate_old_branch 23 | # Step (3). 24 | save_change_timestamp_to_settings # (a) Save change timestamp. 25 | save_new_task # (b) Save task to tasks.json. 26 | launch_repotask_interface # Actually launch the task view for the new task. 27 | end 28 | # Eventually, save new "defaults" (most recent choices) to settings and 29 | # otherwise update settings file; incl. @repo, @branch, and associated 30 | # commands at least. 31 | end 32 | 33 | def calculate_old_branch 34 | "#{@branch}_#{@id}_archive" 35 | end 36 | 37 | end 38 | -------------------------------------------------------------------------------- /models/task.rb: -------------------------------------------------------------------------------- 1 | ############################################################################### 2 | # The Task class enables the user to input new tasks and do basic task manipulation. 3 | class Task 4 | extend TaskFactory # This prepares the data needed to start a new task. 5 | include TaskView 6 | include TaskController 7 | 8 | # Edited by Tasklist#change_all_review_dates 9 | attr_accessor :next_review_date 10 | 11 | # Attributes saved in tasks.json: 12 | attr_reader :id, :lang, :instructions, :tags, :score, :saved, :date_started, 13 | :all_reviews, 14 | # Attributes inferred from this saved data: 15 | :langhash, :file, :location, :old_file, :old_location, :starter, 16 | :starter_location, :location_dir, :old_location_dir, 17 | :starter_location_dir 18 | # The long Task attribute set is a function of how complex Tasks are. 19 | 20 | # Initialization is a three-step process and differs depending on whether an 21 | # existing task is being loaded from datafile or a new task is being created: 22 | # (1) Populate attributes by user input on startup; defaults; or datafile. 23 | # (2) Load or calculate ID and populate ID-dependent attributes. 24 | # (3) For new tasks, save data as needed. RF 25 | def initialize(args = {}) 26 | # Step (1). 27 | args = defaults.merge(args) 28 | @lang = args[:lang] 29 | @instructions = args[:instructions] 30 | @tags = args[:tags] 31 | @score = args[:score] 32 | @saved = args[:saved] 33 | @date_started = args[:date_started] 34 | @next_review_date = args[:next_review_date] 35 | @all_reviews = args[:all_reviews] 36 | @langhash = Lang.new(@lang) 37 | # Step (2). 38 | unless self.class == Repotask # See Repotask#initialize. 39 | if @saved # For use when loading old/existing tasks. 40 | @id = args[:id] 41 | load_locations_and_starter 42 | else # For use when creating new tasks. 43 | @id = calculate_id 44 | # Step (3). 45 | load_locations_and_starter(args) # (a) Load new starter & locations; save starter. 46 | save_change_timestamp_to_settings # (b) Save change timestamp. 47 | save_new_task # (c) Save task to tasks.json. 48 | launch_task_interface # Actually launch the task view for the new task. 49 | end 50 | end 51 | end 52 | 53 | # Converts task to hash for further conversion to JSON. Used only when 54 | # TaskList saves a list. Returns a hash of attributes-to-save. RF 55 | def to_hash 56 | hash = {} 57 | self.instance_variables.each do |var| 58 | # These attributes don't need to be saved in tasks.json. 59 | skip = %w|langhash starter file location old_file old_location 60 | starter_location saved reset_this_session location_dir 61 | old_location_dir starter_location_dir| 62 | next if skip.include? var.to_s[1..-1] 63 | hash[var.to_s[1..-1]] = self.instance_variable_get var 64 | end 65 | hash 66 | end 67 | 68 | # Change the language for this task. Rarely used. Doesn't delete old language 69 | # files if any were created. RT 70 | def change_language 71 | new_lang = Lang.solicit_languages_from_user('c', @lang) 72 | # Save if new, and tell user if he is now switching languages. 73 | if (new_lang && new_lang != 'q' && @lang != new_lang) 74 | puts "OK, switching from #{@lang} to #{new_lang}." 75 | # Save new language instance variables. 76 | @lang = new_lang 77 | @langhash = Lang.new(@lang) 78 | # Repopulate location attributes. 79 | get_file_locations 80 | # And save to tasks.json too. 81 | $tasks.save_tasklist 82 | else 83 | puts "Sticking with #{@lang}." 84 | end 85 | end 86 | 87 | private 88 | 89 | # Sandi Metz-recommended defaults method, merged w/ args in #initialize. RF 90 | def defaults 91 | { 92 | tags: [], 93 | score: 1, 94 | saved: true, # The 'args' passed when a new task is made include saved: false. 95 | lang: $lang_defaults.name, 96 | date_started: DateTime.now.to_s, 97 | next_review_date: DateTime.now.to_s, # First review is due immediately. 98 | all_reviews: [] 99 | } 100 | end 101 | 102 | # Finds the highest ID in the list and returns a number 1 higher. If no 103 | # tasks in list yet, returns 1. RF 104 | def calculate_id 105 | if ! $tasks.list.empty? 106 | max = $tasks.list.max_by { |t| t.id.to_i } 107 | max.id.to_i + 1 # Permits gaps; deliberately doesn't reuse IDs. 108 | else 109 | 1 110 | end 111 | end 112 | 113 | # This method loads file locations, @starter, and writes a new starter file, 114 | # depending on whether the task is new or saved. Bit convoluted. RF 115 | def load_locations_and_starter(args = {}) 116 | get_file_locations # This assigns @file, @location, @old_file, 117 | # @old_location, and @starter_location. 118 | if @saved 119 | @starter = load_starter 120 | else # i.e., if a new task... 121 | @starter = args[:starter] 122 | @starter = add_id_to_java_starter if @lang == 'Java' and @starter 123 | create_folder_if_necessary(@location_dir) 124 | create_folder_if_necessary(@starter_location_dir) 125 | File.write(@starter_location, @starter) unless @starter.nil? 126 | end 127 | end 128 | 129 | # Given an ID, load the task's file locations. RF 130 | def get_file_locations 131 | # Determine filename for answer for this task. 132 | ext = @langhash.ext 133 | dir = determine_directory(@id) 134 | @file = "answer_#{@id}.#{ext}" 135 | @location_dir = "data/answers/#{dir}/" 136 | @location = "data/answers/#{dir}/#{@file}" 137 | # Determine filename for old answers for this task. (Helper.) 138 | @old_file = "answer_old_#{@id}.#{ext}" 139 | @old_location_dir = "data/answers/#{dir}/" 140 | @old_location = "data/answers/#{dir}/#{@old_file}" 141 | @starter_location_dir = "data/starters/#{dir}/" 142 | @starter_location = "data/starters/#{dir}/starter_#{@id}.#{ext}" 143 | end 144 | 145 | # Tests if a folder is necessary to create for a particular answer, old 146 | # answer, or starter file. Creates the folder if so. Unused return. 147 | def create_folder_if_necessary(dir) 148 | return if File.directory?(dir) 149 | `mkdir -p #{dir}` 150 | end 151 | 152 | # If starter file exists, return contents (for @starter); else nil. RF 153 | def load_starter 154 | if File.exist?(@starter_location) && File.stat(@starter_location).size > 0 155 | File.read(@starter_location) 156 | else 157 | nil 158 | end 159 | end 160 | 161 | # Adding @id to the class name is necessary here if the code is to be 162 | # runnable and since the @id isn't assigned by the factory methods. (The 163 | # factory method, Task#generate_new_task, only prepares the values 164 | # necessary to initialize the object.) RF 165 | def add_id_to_java_starter 166 | @starter = @starter.gsub!('answer_ {', "answer_#{@id} {") 167 | end 168 | 169 | # Used only when creating a new task. Simply adds the task to @list, saves 170 | # the task by saving the whole @list, and toggles @saved to true. RF 171 | def save_new_task 172 | @saved = true 173 | # Add object to the front of the $tasks.list (where sorting would put it). 174 | $tasks.list.unshift(self) 175 | # Save the tasklist. 176 | $tasks.save_tasklist 177 | end 178 | 179 | # Expects score; return suggested timestamp of next review, according to a 180 | # simple spaced repetition algorithm. (User needn't accept this.) RF 181 | def calculate_spaced_repetition_date(score) 182 | adjust_by = 0 183 | # If first review, it's an easy return. 184 | if @all_reviews.length == 0 185 | adjust_by = case score 186 | when 1 187 | 1 188 | when 2 189 | 1 190 | when 3 191 | 2 192 | when 4 193 | 4 194 | when 5 195 | 7 196 | end 197 | else 198 | # Otherwise, it is the second or later review, and so we make some calculations. 199 | # Set interval (time between present and most recent review): 200 | interval = ( DateTime.now - DateTime.parse(@all_reviews[-1]['review_date']) ).round 201 | interval = 1 if interval < 1 # Minimum interval time = 1 day. 202 | adjust_by = case score 203 | when 1 204 | 1 205 | when 2 206 | [(interval * 0.25), 2].max.round 207 | when 3 208 | [(interval * 0.5), 4].max.round 209 | when 4 210 | (interval * 1.5) < 5 ? 5 : interval * 1.5 211 | when 5 212 | (interval * 2.0) < 7 ? 7 : interval * 2.0 213 | end 214 | end 215 | return_date = adjust_date_to_avoid_clumping(DateTime.now + adjust_by) 216 | end 217 | 218 | # Given a timestamp, return a timestamp that avoids clumping too many 219 | # tasks on a date. 220 | def adjust_date_to_avoid_clumping(ts) 221 | # Don't bother, if ts is within the next two days. 222 | return (ts) if ts.between?(DateTime.now, DateTime.now + 2) 223 | # (1) Count number of tasks now scheduled for the date of the timestamp, 224 | # as well as on the two surrounding dates. 225 | # (1.a) Assign calendar dates to tasks within 72 hrs of ts (YYYYMMDD). 226 | nearby_timestamps = find_tasks_nearby_in_date(ts) 227 | # (1.b) Calculate the number of tasks on the three days surrounding ts. 228 | pdc, dc, ndc = count_nearby_days(ts, nearby_timestamps) 229 | day_counts = [pdc, dc, ndc] 230 | p day_counts 231 | # (2) If ts is over 120% the average, or the other two counts are too 232 | # low, then propose to put it on the date with the lowest percentage. 233 | average = day_counts.reduce(:+) / 3.0 234 | if ( dc + 1 < (average * 1.2) ) and 235 | ! ( pdc < (average * 0.8) ) and 236 | ! ( ndc < (average * 0.8) ) 237 | return ts 238 | else 239 | # Seems klugy. Surely there's a more efficient way? 240 | least = day_counts.min 241 | index_of_least = day_counts.find_index(least) 242 | case index_of_least 243 | when 0 244 | puts "Recommend prev" 245 | return ts - 1 246 | when 1 247 | puts "Recommend staying put" 248 | return ts 249 | when 2 250 | puts "Recommend next" 251 | return ts + 1 252 | end 253 | end 254 | end 255 | 256 | # Given a timestamp (a DateTime object), return a subarray of $tasks that 257 | # are scheduled within two days of this one. 258 | def find_tasks_nearby_in_date(ts) 259 | nearby_timestamps = $tasks.list.find_all do |t| 260 | t = DateTime.parse(t.next_review_date) 261 | t.between?(ts-2, ts+2) 262 | end 263 | # Return just the timestamps (Date objects), not the whole Task objects. 264 | nearby_timestamps.map {|t| t.next_review_date} 265 | end 266 | 267 | 268 | def count_nearby_days(ts, timestamps) 269 | # Determine a calendar date for ts, for ts-24h, and ts+24h. 270 | prev_day = month_day_array(ts-1) # [month, day] 271 | day = month_day_array(ts) 272 | next_day = month_day_array(ts+1) 273 | prev_day_count = day_count = next_day_count = 0 274 | # Actually count up number of tasks falling on the three dates. 275 | timestamps.each do |timestamp| 276 | eval_day = month_day_array(timestamp) 277 | case eval_day 278 | when prev_day 279 | prev_day_count += 1 280 | when day 281 | day_count += 1 282 | when next_day 283 | next_day_count += 1 284 | end 285 | end 286 | return prev_day_count, day_count, next_day_count 287 | end 288 | 289 | # Given a timestamp, return an array of the form [month, day]. 290 | def month_day_array(date) 291 | date = DateTime.parse(date) unless date.class == DateTime 292 | [date.strftime("%-m"), date.strftime("%-d")] 293 | end 294 | 295 | end # of class Tasks 296 | -------------------------------------------------------------------------------- /models/task_list.rb: -------------------------------------------------------------------------------- 1 | ############################################################################### 2 | # TaskLists contain, most importantly, a sorted array of tasks and come with 3 | # various helpers for CRUD functions with respect to tasks, although the 4 | # actual display and editing of tasks is handled by class Task. RF 5 | class TaskList 6 | include TasklistController 7 | include TasklistView 8 | attr_accessor :list 9 | # These might not need accessors; I'm just listing them for clarity. 10 | attr_reader :displayed_tasks, :tag_filtered_list, :filter_tag, :default_tag, 11 | :page_num, :history 12 | def initialize 13 | @list = [] 14 | @tasklist_filter = 'all' 15 | @page_num = 1 16 | load_all_tasks 17 | $tasks = self # class Task & class Archiv need access for saving etc. 18 | @history = load_history 19 | display_tasks('first screen') 20 | app_loop 21 | end 22 | 23 | # Overwrites tasks.json datafile with the latest tasklist data. RF 24 | def save_tasklist 25 | # Sort @list before saving. 26 | @list.sort!{|x,y| DateTime.parse(x.next_review_date) <=> 27 | DateTime.parse(y.next_review_date)} 28 | # Convert @list to JSON. 29 | json = JSON.pretty_generate({"tasks": @list.map{|task| task.to_hash } }) 30 | # Overwrite datafile. 31 | File.open("./data/tasks.json", "w") do |f| 32 | f.write(json) 33 | end 34 | save_change_timestamp_to_settings 35 | load_history # RE-load history 36 | # If the user is currently filtering tasks, better add the new task to 37 | # the tag-filtered list. 38 | if @filter_tag && ! (@filter_tag == 'history' or @filter_tag == 'sort_by_id' or 39 | @filter_tag == 'reverse_sort_by_id' or @filter_tag == 'sort_by_avg_score' or 40 | @filter_tag == 'reverse_sort_by_avg_score' or @filter_tag == 'notags') 41 | tag_hash = prepare_hash_of_tag_arrays 42 | tag_matches = get_tag_matches(@filter_tag, tag_hash) 43 | @tag_filtered_list = match_tasks(tag: @filter_tag, tag_hash: tag_hash, 44 | tag_matches: tag_matches) 45 | end 46 | # NOTE FOR REFACTOR: badly need to resort after saving, in case the user 47 | # has deleted the task. 48 | end 49 | 50 | private 51 | # Loads contents of tasks.json into an array that is iterated in order to 52 | # output @list. RF 53 | def load_all_tasks 54 | # Let it work without the datafile existing. 55 | if (File.exist?("./data/tasks.json") && 56 | File.stat("./data/tasks.json").size > 0) 57 | file = File.read "./data/tasks.json" 58 | data = JSON.parse(file) 59 | task_array = data['tasks'] 60 | task_array.each do |task| 61 | task_with_symbols = {} 62 | task.each {|k,v| task_with_symbols[k.to_sym] = v } 63 | # It's a Repotask if it has a :repo key. 64 | task_with_symbols[:repo] ? 65 | @list << Repotask.new(task_with_symbols) : 66 | @list << Task.new(task_with_symbols) 67 | end 68 | @list = @list.sort!{|x,y| DateTime.parse(x.next_review_date) <=> 69 | DateTime.parse(y.next_review_date)} 70 | end 71 | end 72 | 73 | def load_history 74 | start = Time.now 75 | reviews = {} 76 | @list.each do |t| 77 | t.all_reviews.each {|r| reviews[r['review_date']] = t} 78 | end 79 | @history = reviews.sort_by {|timestamp,task| timestamp }.reverse 80 | end 81 | 82 | def get_tag_matches(tag, tag_hash) 83 | tag_hash.keys.find_all { |k| k.downcase =~ /#{tag}/ } 84 | end 85 | 86 | def match_tasks(args) 87 | tag = args[:tag] 88 | tag_hash = args[:tag_hash] 89 | tag_matches = args[:tag_matches] 90 | @tag_filtered_list = [] 91 | tag_matches.each do |tag| 92 | @tag_filtered_list = (@tag_filtered_list + tag_hash[tag]).uniq 93 | end 94 | return @tag_filtered_list 95 | end 96 | 97 | # Accepts the display number (NOT ID) of a task and attempts to delete it. 98 | # Return user message (whether successful or not). RF 99 | def delete_task(num) 100 | task = fetch_task_from_displayed_number(num) 101 | # Prepare info about the task deleted to send back to user. 102 | if @list.delete(task) # Recall that Array#delete returns nil if not found. 103 | delete_task_files(task) 104 | save_tasklist 105 | message = delete_message(task) 106 | return "Deleted:\n#{message}\n\n" 107 | else 108 | return "'#{num}' not found; nothing deleted.\n\n" 109 | end 110 | end 111 | 112 | def delete_message(task) 113 | message = "(#{task.lang}) ".colorize(task.langhash.color) 114 | message += task.instructions.split("\n")[0][0..20] 115 | message += '...' if task.instructions.split("\n")[0][0..20] != 116 | task.instructions.split("\n")[0] 117 | message += " (ID ##{task.id.to_s})" 118 | end 119 | 120 | # Delete any files associated with the task to delete. RF 121 | def delete_task_files(task) 122 | return nil unless defined?(task.id) 123 | ending = "#{task.id}.#{task.langhash.ext}" 124 | dir = determine_directory(task.id) 125 | # Delete current answer. 126 | system("rm data/answers/#{dir}/answer_#{ending}") if 127 | File.exist? "data/answers/#{dir}/answer_#{ending}" 128 | # Delete archive. 129 | system("rm data/answers/#{dir}/answer_old_#{ending}") if 130 | File.exist? "data/answers/#{dir}/answer_old_#{ending}" 131 | # Delete code starter. 132 | system("rm data/starters/#{dir}/starter_#{ending}") if 133 | File.exist? "data/starters/#{dir}/starter_#{ending}" 134 | end 135 | 136 | # Start over. Delete all data in tasks.json, starters/, and answers/. Results 137 | # in a clean install, ready to add new tasks. 138 | def destroy_all 139 | begin 140 | if user_confirms_destruction 141 | # Actually perform the file deletions. 142 | system("rm data/tasks.json") 143 | puts "tasks.json removed..." 144 | system("rm data/settings.json") 145 | puts "settings.json removed..." 146 | system("rm -f answers/*") 147 | puts "answers/ removed..." 148 | system("rm -f starters/*") 149 | puts "starters/ removed..." 150 | system("rm -rf repos/*") 151 | puts "repos/ removed..." 152 | # The following triggers exit from TaskList loop to App for reloading. 153 | $destroyed_data = true 154 | puts "All tasks destroyed." 155 | print "Press any key to continue..." 156 | gets 157 | clear_screen 158 | else 159 | return "Nothing destroyed. Remember, you can back up your data with [a]rchive." 160 | end 161 | rescue => err 162 | return "There was an error: #{err}" 163 | end 164 | end 165 | 166 | # Used when user presses 'c' from the tasklist, this edits and saves all 167 | # task @next_review_dates by the offset given, with positive numbers moving 168 | # dates into the future, and negative numbers into the past. Supports 169 | # fractional numbers. 170 | def change_all_review_dates(offset) 171 | offset = offset.to_f 172 | return "Unchanged; zero entered." if offset == 0 173 | # Actually change the dates 174 | @list.each do |task| 175 | date = DateTime.parse(task.next_review_date) 176 | date += offset # Actually do the magic. 177 | task.next_review_date = date.to_s 178 | end 179 | save_tasklist # Changed every task--need to save! 180 | direction_msg = offset > 0 ? "later" : "earlier" 181 | return "Moved all task review dates to #{offset.abs} days #{direction_msg}." 182 | end 183 | 184 | 185 | end # of class TaskList 186 | -------------------------------------------------------------------------------- /revuu.rb: -------------------------------------------------------------------------------- 1 | require 'rubygems' 2 | require 'bundler/setup' 3 | Bundler.require(:default) 4 | 5 | # LIBRARY/HELPERS 6 | Dir["./lib/*.rb"].each {|file| require file } 7 | include Helpers, DatePrettifier, HelpRepotask, HelpHelper, SettingsHelper, WrappingHelper 8 | # CONTROLLERS 9 | Dir["./controllers/*.rb"].each {|file| require file } 10 | include ArchivController # Need to make these included in class Archiv, not globally. 11 | # VIEWS 12 | Dir["./views/*.rb"].each {|file| require file } 13 | include ArchivView 14 | # MODELS (all are classes) 15 | Dir["./models/*.rb"].each {|file| require file unless file =~ /repotask/} 16 | require './models/repotask' 17 | 18 | update_file_locations unless File.directory?("data/answers/00000") 19 | 20 | puts ENV['BUNDLE_GEMFILE'] 21 | 22 | ############################################################################### 23 | # Program wrapper object 24 | class App 25 | 26 | def initialize 27 | system("clear") 28 | start_text 29 | # From here you always view the tasklist; if you exit the tasklist while 30 | # $view_archive is true, you enter the archive system; if you exit while 31 | # $destroyed_data is true, you reload the tasklist; otherwise, you quit 32 | # the app altogether. 33 | loop do 34 | # We reset globals that might have been set true by the user. 35 | $view_archive = false # Cf. TasklistController dispatch table. 36 | $destroyed_data = false # Cf. TaskList#destroy_all. 37 | $auto_next = false # Cf. TaskView#prompt_for_autonext. 38 | load_defaults_from_settings # Loads/assigns a number of settings globals. 39 | TaskList.new # Contains the main app loop. 40 | if $view_archive 41 | Archiv.launch_archive_system 42 | clear_screen 43 | elsif $destroyed_data 44 | redo # Since the data is now gone, restart. 45 | else 46 | break 47 | end 48 | end 49 | end 50 | 51 | def start_text 52 | wd = 75 # Standard line width, could be made into a global. 53 | logo = "* R * E * V * U * U *" 54 | start = logo.center(wd) 55 | # Center the logo. 56 | line = ('=' * logo.length).center(wd) 57 | # Introductory padding and text on startup. 58 | puts "\n\n\n" + line + "\n" + start + "\n" + line + "\n\n\n" 59 | puts intro unless File.exist?("./data/tasks.json") 60 | # NB if no tasks, orient user. Note, 'help' method is in tasklist_view.rb. 61 | puts (new_user_text + "\n") unless File.exist?("./data/tasks.json") 62 | end 63 | 64 | # Shown to everyone, only on startup. 65 | def intro 66 | intro = <<~ENDINST 67 | Revuu is a Ruby command line app to help you organize practical reviews of 68 | programming tasks that you want to learn. You can add problems, solve them 69 | with your favorite text editor, run the resulting script in Revuu, record 70 | that you've done a review, and schedule more for the future. The developer 71 | finds it to be a handy way to learn and solidify easy-to-forget skills. 72 | 73 | ENDINST 74 | end 75 | 76 | # Shown only if user has no tasks loaded. 77 | def new_user_text 78 | newbie = <<~NEWBIE 79 | No tasks are loaded! Press 'n' to add your first task or press 'a' to load 80 | a task list from the archive (where you can find some sample data to play 81 | with). Choose your text editor with 'e' and your default programming 82 | language with 'p'. For a general introduction and detailed instructions, 83 | press '?'. 84 | NEWBIE 85 | end 86 | 87 | end 88 | 89 | App.new 90 | -------------------------------------------------------------------------------- /sample_data/.gitkeep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/globewalldesk/revuu/7f118434e12a96c8165c32748323c55402f5224a/sample_data/.gitkeep -------------------------------------------------------------------------------- /sample_data/sample_archive_20181127.tar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/globewalldesk/revuu/7f118434e12a96c8165c32748323c55402f5224a/sample_data/sample_archive_20181127.tar -------------------------------------------------------------------------------- /sample_data/sample_archive_20181221.tar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/globewalldesk/revuu/7f118434e12a96c8165c32748323c55402f5224a/sample_data/sample_archive_20181221.tar -------------------------------------------------------------------------------- /tmp/.gitkeep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/globewalldesk/revuu/7f118434e12a96c8165c32748323c55402f5224a/tmp/.gitkeep -------------------------------------------------------------------------------- /views/archiv_view.rb: -------------------------------------------------------------------------------- 1 | module ArchivView 2 | # Intro user to archive screen; clears screen and shows introductory text. 3 | def welcome_to_archive 4 | clear_screen 5 | title = "REVUU ARCHIVE SYSTEM" 6 | puts '*-' * (title.length / 2).round 7 | puts title 8 | puts '*-' * (title.length / 2).round 9 | puts <<~ARCHIVEHEADER 10 | Here, you can [c]reate an archive (i.e., export) your data and [l]oad 11 | (i.e., import) data--such as the [sa]mple data. This is where to back up 12 | your data so it won't be lost, or to share a task set with others. Note, 13 | at present, old answers, starter code, and old review data are part of 14 | your archive. 15 | 16 | ARCHIVEHEADER 17 | puts archive_help 18 | end 19 | 20 | # List of dispatch_table commands for user. 21 | def archive_help 22 | <<~ARCHIVEHELP 23 | Archives: [c]reate/export [l]oad/import [s]how all [d]elete 24 | Also: re[f]resh view [sa]mple data [?] help [q]uit archive system 25 | 26 | ARCHIVEHELP 27 | end 28 | 29 | # Pesters user for a valid archive name; returns it. 30 | def set_archive_name 31 | puts <<~SETARCHIVENAME 32 | Press for a generic archive name or enter a brief label; 33 | this could be your last name, a company or project name, or the 34 | name of some technology you're learning. 35 | 36 | SETARCHIVENAME 37 | archive_name = nil 38 | until is_valid?(archive_name) 39 | archive_name = get_user_command('c') 40 | end 41 | affix_date_and_ext(archive_name) 42 | end 43 | 44 | # Pesters user for name (number) of archive; returns name. 45 | def choose_archive 46 | # Display archives and also output an array of archive locations. 47 | archives = display_archives 48 | load_num = nil 49 | until ([*(1..archives.length)].include?(load_num) || load_num == 'q') 50 | puts "\nWhich of the archives above (or [q]uit to escape)?" 51 | load_num = get_user_command('l') 52 | load_num = load_num.to_i unless load_num == 'q' 53 | end 54 | load_num.class == String ? false : archives[load_num-1] 55 | end 56 | 57 | # Loads list of archive names, then displays them in numbered fashion. 58 | def display_archives 59 | puts "\nYour archives:" 60 | archives = Dir["archives/*.tar"].sort 61 | # Construct string 62 | line = '' 63 | archives.each_with_index do |a,i| 64 | a =~ /^archives\/(\w+?)_(\d{8})\.tar$/ 65 | tag, date = $1, $2 66 | date = Time.parse(date).strftime("%Y/%-m/%-d") 67 | tag = tag == 'archive' ? '' : "#{tag.gsub!('_archive', '')}: " 68 | addition = "(#{i+1}) #{tag}#{date} " 69 | if (line + addition).length > 74 70 | puts line 71 | line = addition 72 | else 73 | line += addition 74 | end 75 | puts line if a == archives[-1] 76 | end 77 | archives 78 | end 79 | 80 | end 81 | -------------------------------------------------------------------------------- /views/repotask_view.rb: -------------------------------------------------------------------------------- 1 | module RepotaskView 2 | 3 | def display_info 4 | super("REPOTASK") 5 | display_files 6 | display_repotask_commands(@tag_str) 7 | end 8 | 9 | def display_files 10 | puts "\nFILES TO EDIT FOR REPOTASK" 11 | unless @files 12 | puts "No files specified. Press 'fi' to add some, if you like.\n\n" 13 | return 14 | end 15 | show_array_with_numbers(@files, {colored:true}) 16 | puts "GIT INFO Repo: #{@repo} Branch: #{@branch}\n\n" 17 | end 18 | 19 | def display_repotask_commands(tag_str) 20 | puts <<~DISPLAYREPOTASKCOMMANDS 21 | COMMANDS Review: [1] open file #1 [o]pen repo [r]un answer [s]ave review 22 | [co]nsole [oo]pen old [rr]un old [h]istory [?] help 23 | Edit: [i]nstructions [c]ommands to run [fi]les [t]ags#{tag_str} 24 | [d]ate of next review [sc]ore 25 | Also: re[f]resh config [l]anguage [q]uit review and editing 26 | 27 | DISPLAYREPOTASKCOMMANDS 28 | end 29 | 30 | end 31 | -------------------------------------------------------------------------------- /views/task_view.rb: -------------------------------------------------------------------------------- 1 | module TaskView 2 | 3 | # This actually shows the task data (instructions, etc.) to the user, then 4 | # shows the commands for interfacing with this data. RF 5 | def display_info(type_label = nil) # See below re type_label. 6 | clear_screen 7 | puts '=' * 75 8 | type_label ||= 'TASK' # # type_label is "REPOTASK" if self.class == Repotask 9 | puts "#{type_label} INSTRUCTIONS:" 10 | # Note, lib/wrapping_helper.rb has already accommodated the space needed for 11 | # the (@lang) bit. 12 | puts ('(' + @lang + ') ').colorize(@langhash.color) + @instructions 13 | puts '=' * 75 14 | # Prepare and print task data strings for line 1. 15 | date = DateTime.parse(@date_started).strftime("%-m/%-d/%Y") 16 | starter_string = @starter ? '*Yes*' : 'No' 17 | printf(" ID: %d Started: %-10s Reviews: %d Score: %s Starter: #{starter_string}\n", 18 | @id, date, @all_reviews.length, @score) 19 | # Prepare and print task data strings for line 2 + command list. 20 | last_date_timestamp = @all_reviews.empty? ? 21 | nil : @all_reviews.max_by {|r| r['review_date']}['review_date'] 22 | last_precise_date = last_date_timestamp ? 23 | DateTime.parse(last_date_timestamp).strftime("%-m/%-d/%Y") : 'none yet' 24 | last_time = last_date_timestamp ? DateTime.parse(last_date_timestamp). 25 | strftime(" %H:%M") : '' 26 | next_precise_date = DateTime.parse(@next_review_date). 27 | strftime("%-m/%-d/%Y") 28 | default_tag_count = @langhash.lang_alts.length + 1 # +1 for the lang name. 29 | @tag_str = "(#{@tags.length - default_tag_count})" 30 | puts " Review dates >> Last: #{last_precise_date}#{last_time} " + 31 | "Next: #{next_precise_date} (#{prettify_timestamp(@next_review_date)})" 32 | puts " Files directory: #{@location_dir}" if self.class == Task 33 | display_task_commands(@tag_str) if self.class == Task 34 | end 35 | 36 | def display_task_commands(tag_str) 37 | puts <<~DISPLAYTASKCOMMANDS 38 | 39 | COMMANDS Review: [s]ave review [a]nswer [r]un answer [co]nsole [?] help 40 | [o]ld answers [rr]un old answers review [h]istory 41 | Edit: [i]nstructions [t]ags#{tag_str} [d]ate of next review 42 | [sc]ore [st]arter code 43 | Also: re[f]resh config [l]anguage [q]uit review and editing 44 | 45 | DISPLAYTASKCOMMANDS 46 | end 47 | 48 | # Solicit and return a valid score or return nil if user fails to do so. RF 49 | def get_score(prompt) 50 | puts "Input score (5: mastered, 4: confident, 3: shaky, 2: barely recall, 1: blank)" 51 | score = get_user_command(prompt).to_i 52 | unless [1, 2, 3, 4, 5].include?(score) 53 | puts "Score must be between 1 and 5." 54 | return nil 55 | end 56 | score 57 | end 58 | 59 | # Prompt user to either accept spaced repetition-calculated date or else 60 | # enter own. Returns timestamp or, if can't parse user-entered date, nil. RF 61 | def get_next_review_date(prompt, score=@score) 62 | calculated_date = calculate_spaced_repetition_date(score) 63 | puts "\nSpaced repetition date: #{calculated_date.strftime("%-m/%-d/%Y")} " + 64 | "(#{prettify_timestamp(calculated_date)})" 65 | puts "Do next review when? Use regular English, or" 66 | puts "just press 'Enter' to accept date above or 'q' to escape.\n\n" 67 | date = get_user_command(prompt) 68 | return nil if date == 'q' 69 | # "Chronic" gem parses ordinary English input to Time obj. 70 | date = ( date == '' ? calculated_date.to_time : Chronic.parse(date) ) 71 | unless date.class == Time 72 | puts "ERROR: couldn't parse date." 73 | return nil 74 | end 75 | DateTime.parse(date.to_s).to_s # Convert Time to DateTime string. 76 | end 77 | 78 | # Given a task, opens its answer file with the default text editor. RF 79 | def write_answer 80 | # If answer file has content, ask user if he wants it archived first. 81 | if (File.exist?(@location) && File.stat(@location).size > 0 && 82 | File.read(@location) != java_starter && File.read(@location) != @starter) 83 | puts "An answer exists. Want to archive it before opening? ([y]/n)" 84 | ans = get_user_command(' a') 85 | # If yes, archive the old answer and blank the answer file. 86 | if (ans == 'y' || ans == '') 87 | archive_old_answer 88 | # Create a folder for this answer if one doesn't exist yet. 89 | create_folder_if_necessary(@location_dir) 90 | File.write(@location, '') # Erase old answer from answer file. 91 | # Creates file with starter code as necessary. 92 | add_starter_code_to_answer_file 93 | end 94 | else 95 | add_starter_code_to_answer_file 96 | end 97 | # Open with default editor. (Set default in #configure_answers. Helper.) 98 | system("#{$textedcmd} #{@location}") 99 | # Remind user to press 'r' to run. 100 | puts "When you're done, don't forget to press 'r' to run." 101 | end 102 | 103 | # Given a task (answer), run it (optionally, an archived task answer). 104 | # Long and complex but all devoted to running the answer. RF 105 | def run_answer(old = false) 106 | old ? (file = @old_file and location = @old_location and location_dir = @old_location_dir) : 107 | (file = @file and location = @location and location_dir = @location_dir) 108 | if ( File.exist?(location) && File.stat(location).size > 0 ) 109 | puts "\nRunning #{file}:" 110 | puts ("=" * 75).colorize(@langhash.color) 111 | puts '' 112 | system("cd #{location_dir} && #{@langhash.cmd} #{file}") 113 | # If the language is compiled, the latter line runs the compiler. 114 | # The following then runs the compiled executable. 115 | if @langhash.cmd2 116 | # Java, e.g., needs to remove the extension. Other rules can be 117 | # added here for new languages as needed. 118 | subbed_cmd = @langhash.cmd2.gsub('', 119 | file.gsub(".#{@langhash.ext}", '')) 120 | system("cd #{location_dir} && #{subbed_cmd}") 121 | end 122 | puts '' 123 | puts ("=" * 75).colorize(@langhash.color) 124 | # Find the last review performed. 125 | last_review = @all_reviews.max_by {|r| r['review_date']} 126 | # Decide whether to prompt user to press 's'. Skip if no reviews. 127 | if last_review 128 | date_of_last_review = last_review['review_date'] 129 | last_was_today = 130 | DateTime.parse(date_of_last_review).yday == DateTime.now.yday 131 | else 132 | last_was_today = false 133 | end 134 | puts (old || last_was_today) ? "\n" : 135 | "\nIf it's correct, press 's' to save a review." 136 | else 137 | puts "The #{old ? 'old answer archive' : 'answer'} file doesn't exist." 138 | end 139 | end 140 | 141 | # Open old answer file (with archived answers) in your text editor. RF 142 | def view_old_answers 143 | # If it exists and is nonzero, display archive with default text editor. 144 | if ( File.exist?(@old_location) && File.stat(@old_location).size > 0 ) 145 | system("#{$textedcmd} #{@old_location}") 146 | # Remind user to press 'rr' to run. 147 | puts "If you want, you can run the old answer archive with 'rr'." 148 | else # ...or else say it doesn't exist. 149 | puts "There is no old answer archive for this task yet." 150 | end 151 | end 152 | 153 | # Just display the dates and scores of previous reviews. 154 | def review_history 155 | puts 156 | puts "Review history for ##{@id}" 157 | header = "Score | Date | Time Ago" 158 | puts header, '=' * (header.length + 12) 159 | # Each review is a hash 160 | color = :green 161 | next_date = DateTime.parse(@next_review_date).strftime("%B %-d, %Y") 162 | future_time = prettify_timestamp(@next_review_date) 163 | puts sprintf("%-5s | %-18s | %-s", "Next>", next_date, future_time). 164 | colorize(:light_yellow) 165 | @all_reviews.reverse.each do |r| 166 | score = r['score'] 167 | raw_date = r['review_date'] 168 | full_date = DateTime.parse(raw_date).strftime("%B %-d, %Y") 169 | time_ago = prettify_timestamp(raw_date) 170 | str = sprintf("%-5s | %-18s | %-s", score, full_date, time_ago) 171 | puts str.colorize(color) 172 | color = color ? nil : :green 173 | end 174 | puts '=' * (header.length + 12) 175 | puts 176 | end 177 | 178 | # Used to edit both instructions and tags. RF 179 | def edit_field(field) 180 | # Load current attribute contents. 181 | contents = (field == 'tags' ? 182 | (self.instance_variable_get("@#{field}").join(', ') if 183 | self.instance_variable_get("@#{field}") ) : 184 | self.instance_variable_get("@#{field}") ) 185 | # Wraps tags (adds "\n") for user during editing; saved without. 186 | contents = wrap_overlong_paragraphs(contents) if field == 'tags' 187 | # Write contents to temp file. OK if nil. 188 | File.write("./tmp/#{field}.tmp", contents) 189 | # Open file for editing; uses Pico for simplicity of task-switching 190 | # (don't have to prompt the user to load after finishing). 191 | system("pico tmp/#{field}.tmp") 192 | # Save upon closing: grab text. 193 | attrib = File.read("./tmp/#{field}.tmp").strip 194 | # Strip newlines if tags (otherwise commas are introduced). 195 | attrib.gsub!("\n", '') if field == 'tags' 196 | if attrib.empty? && field == 'instructions' 197 | puts "ERROR: Instructions cannot be blank." 198 | return nil # Abandons (doesn't save) any attempt to blank instructions. 199 | # Use tag prep method if field type is tags. 200 | elsif field == 'tags' 201 | attrib = self.class.prep_tags(attrib, @lang) # In module TaskFactory. 202 | elsif field == 'instructions' 203 | # In lib/helpers.rb (used for both instructions and tags): 204 | attrib = wrap_overlong_paragraphs(attrib, @lang.length) if 205 | attrib.class == String 206 | end 207 | # Set instance variable to contents of edited temp file. 208 | self.instance_variable_set("@#{field}", attrib) 209 | # Save updated instructions to JSON file if you've made it this far. 210 | $tasks.save_tasklist 211 | # Refresh view. 212 | display_info 213 | end 214 | 215 | # Open starter code file with text editor; load and save when done. RF 216 | def edit_starter 217 | puts "Editing the starter code in #{$texted}." 218 | # Create a folder for this starter if one doesn't exist yet. 219 | create_folder_if_necessary(@starter_location_dir) 220 | system("#{$textedcmd} #{@starter_location}") 221 | print "Save your work, then press to load the starter code: " 222 | gets 223 | if ( File.exist?(@starter_location) && 224 | File.stat(@starter_location).size > 0 ) 225 | @starter = File.read(@starter_location) 226 | print "Starter text (last saved version) now loaded.\n\n" 227 | save_change_timestamp_to_settings 228 | elsif ( File.exist?(@starter_location) && 229 | File.stat(@starter_location).size == 0 ) 230 | @starter = '' 231 | print "The starter code is now blank.\n\n" 232 | save_change_timestamp_to_settings 233 | else 234 | print "Starter code not saved. Try saving first, then press 'st' again.\n\n" 235 | end 236 | end 237 | 238 | # This asks the user if he wants to skip immediately to the next task in the 239 | # list (i.e., always the first one in the list *after* saving a review, just 240 | # like hitting 'x' from the tasklist). 241 | def prompt_for_autonext 242 | # Figure out what the present list is. 243 | list = $tasks.filter_tag ? $tasks.tag_filtered_list : $tasks.list 244 | # First check if the user is done with all tasks for the day. 245 | now = DateTime.now 246 | this_midnight = now + 1 - (now.hour/24.0) - (now.min/(24.0*60)) 247 | # If the first-listed (next due) task is later than this midnight, done! 248 | if list[0].next_review_date > this_midnight.to_s 249 | puts "Good job! You've finished your review for the day!" 250 | return 'done' 251 | end 252 | num_left = list.count {|t| t.next_review_date < this_midnight.to_s} 253 | puts "You have #{num_left.to_s.colorize(:malibu)} to go. Skip to next task? ( for [y]es.)" 254 | autonext_answer = get_user_command('s') 255 | $auto_next = true if autonext_answer == '' or autonext_answer == 'y' 256 | end 257 | 258 | end 259 | -------------------------------------------------------------------------------- /views/tasklist_view.rb: -------------------------------------------------------------------------------- 1 | module TasklistView 2 | 3 | private 4 | 5 | # Displays a view of (part of) the task list to the user. Uses many methods 6 | # that only it calls. RF 7 | def display_tasks(first_screen=nil, message='') 8 | clear_screen unless first_screen 9 | print_header_for_tasklist_display 10 | list = prepare_tasklist_for_tasklist_display 11 | if ! list.empty? 12 | print_tasklist(list) 13 | else 14 | print "\nThere are no tasks yet. Press 'n' to add one or 'a'" + 15 | " to load archive.\n\n" 16 | end 17 | print_pagination_string_for_tasklist_display(list) 18 | print_help_text_for_tasklist_display 19 | puts message unless (message == '' || message == nil) 20 | end 21 | 22 | # Simply print the first couple lines of the task list (used only by 23 | # #display_tasks). RF 24 | def print_header_for_tasklist_display 25 | label_for_date_column = 'Due date' # By default except for history. 26 | if @filter_tag 27 | if @filter_tag == 'history' 28 | puts "> Review History <".center(75).colorize(:black) 29 | .colorize(background: :light_yellow) 30 | label_for_date_column = 'Last reviewed' 31 | elsif @filter_tag == 'sort_by_id' 32 | puts "> Sorted by ID <".center(75).colorize(:light_yellow) 33 | .colorize(background: :blue) 34 | elsif @filter_tag == 'reverse_sort_by_id' 35 | puts "> Reverse sorted by ID <".center(75).colorize(:light_yellow) 36 | .colorize(background: :blue) 37 | elsif @filter_tag == 'sort_by_avg_score' 38 | puts "> Sorted by average score <".center(75).colorize(:black) 39 | .colorize(background: :light_cyan) 40 | elsif @filter_tag == 'reverse_sort_by_avg_score' 41 | puts "> Reverse sorted by average score <".center(75).colorize(:black) 42 | .colorize(background: :light_cyan) 43 | elsif @filter_tag == 'notags' 44 | puts "> Tasks that need tags <".center(75).colorize(:black) 45 | .colorize(background: :white) 46 | else 47 | puts "> Filtered by '#{@filter_tag}' <".center(75) 48 | .colorize(background: :green) 49 | end 50 | puts 51 | end 52 | printf("%3s | %-49s| %-21s\n", ' #', 'Instructions (first line)', 53 | label_for_date_column) 54 | puts separator = '=' * 75 55 | end 56 | 57 | # Since #display_tasks can print different views of the user's task list, first 58 | # we must prepare a properly filtered, sorted tasklist. Returns list. RF 59 | def prepare_tasklist_for_tasklist_display 60 | # If the TaskList knows that the user has successfully searched for a tag, 61 | # then return the search results. 62 | @displayed_tasks = [] 63 | list = (@filter_tag ? @tag_filtered_list : @list) 64 | unless @filter_tag == 'history' or @filter_tag == 'sort_by_id' or 65 | @filter_tag == 'reverse_sort_by_id' or @filter_tag == 'sort_by_avg_score' or 66 | @filter_tag == 'reverse_sort_by_avg_score' or @filter_tag == 'notags' 67 | list.sort!{|x,y| DateTime.parse(x.next_review_date) <=> 68 | DateTime.parse(y.next_review_date)} 69 | end 70 | list 71 | end 72 | 73 | # Simply prints the tasklist. Requires tasklist; prints it for user. RF 74 | def print_tasklist(list) 75 | pindex = (@page_num - 1) * 10 # The list's array index to copy from. 76 | colored = true 77 | list = list[pindex, 10] 78 | list[0..10].each_with_index do |task, i| 79 | @displayed_tasks[i] = task # Used in switching to task view for a task. 80 | # Absolute insanity required to make the colors come out right. 81 | colorblock = " ".colorize(background: task.langhash.color) 82 | numstr = becolor(" #{i} | ", colored) 83 | lang_str = ('(' + task.lang + ') ').colorize(task.langhash.color) 84 | title_str = becolor(prepare_title_string(task, (task.lang.length+3)), colored) 85 | date_item = @filter_tag == 'history' ? task.all_reviews[-1]['review_date'] : 86 | task.next_review_date 87 | time_str = becolor(sprintf("| %-21s", 88 | prettify_timestamp(date_item)), colored) 89 | puts colorblock + numstr + lang_str + title_str + time_str 90 | # (colored ? line.colorize(:green) : line) + "\n" 91 | #puts line.colorize(task.langhash.color) 92 | colored = !colored # Toggle green and white colors with each line. 93 | end 94 | puts separator = '=' * 75 95 | end 96 | 97 | def becolor(str, colored) 98 | colored ? str.colorize(:green) : str 99 | end 100 | 101 | # Given a task, prepare the title string that is shown in the tasklist 102 | # display. Requires the task, returns the string (title_str). RT 103 | def prepare_title_string(task, lang_length) 104 | # Grab the first 47 characters of the first line of @instructions. 105 | # First, add the language in parens and calculate how much space is left. 106 | limit = 47 - lang_length # Subtract length of the addition from title. 107 | # Prepare '...' at end of string if nec. 108 | line_1 = task.instructions.split("\n")[0][0..limit] 109 | line_1_avec_dots = line_1 == task.instructions.split("\n")[0] ? 110 | line_1 : line_1[0..-4] + '...' 111 | line_1_avec_dots + (' ' * (49 - line_1_avec_dots.length - lang_length)) 112 | end 113 | 114 | # From a tasklist array, prepare (mostly) and show a string, e.g.: 115 | # [<<]top [<]back ...5 (6) 7... next[>] end[>>] RF 116 | def print_pagination_string_for_tasklist_display(list) 117 | # No pagination at all if list.length < 10. 118 | return '' if list.length < 10 119 | pnum = @page_num.dup # The page number the user is on. 120 | last_pg = calculate_last_page_number(list) 121 | on_first = (pnum == 1 ? true : false) 122 | on_last = (pnum == last_pg ? true : false) 123 | # Print page number plus surrounding pages; remove stuff from this as nec. 124 | str = "[<<]top [<]back #{pnum - 1} (#{pnum}) #{pnum + 1} next[>] end[>>]" 125 | # Remove top/end if list.length < 21. 126 | if list.length < 21 127 | str.slice!('[<<]top ') 128 | str.slice!(' end[>>]') 129 | end 130 | # Remove top and back if on first page (pnum < 10). 131 | if on_first 132 | str.slice!('[<<]top ') 133 | str.slice!('[<]back ') 134 | # Show third page in list if it exists 135 | str.gsub!('(1) 2 ', '(1) 2 3 ') if last_pg > 2 136 | str.slice!('0 ') 137 | end 138 | # Remove next and end if on last page. 139 | if on_last 140 | str.slice!(' next[>]') 141 | str.slice!(' end[>>]') 142 | # If you're on p. 3 or up, you'll need to add a page before the penultimate page. 143 | str.gsub!('[<]back ', "[<]back #{pnum - 2} ") unless pnum < 3 144 | # Delete the nonexistent "page" above the last page. 145 | str.gsub!(") #{pnum + 1}", ')') 146 | end 147 | str = "Nav: " + str 148 | tcl = 69 - str.length 149 | task_count = sprintf("%#{tcl}s tasks", list.length) 150 | puts str + task_count 151 | end 152 | 153 | # Prints the help text that goes underneath the tasklist display. RF 154 | def print_help_text_for_tasklist_display 155 | asterisk = $unsaved_changes ? '*' : '' 156 | puts <<~HELPTEXT 157 | 158 | Commands are: 159 | [n]ew task new [r]epo task [1] view #1 [l]ist all tasks show ne[x]t 160 | [t]ag search [h]istory [a]rchive#{asterisk} [s]ort [c]hange dates [d]elete task 161 | set text [e]ditor set [p]rogramming language [de]stroy [?] help 162 | 163 | HELPTEXT 164 | end 165 | 166 | def display_sorting_commands 167 | return "You can sort by:\n" + 168 | "[l] due date [h]istory (date of most recent reviews) [t]ag\n" + 169 | "[id] date added (earliest to latest) [id] again to reverse\n" + 170 | "average [sc]ores (low to high) average [sc]ores again to reverse\n" + 171 | "[notags] tasks with no (non-default) tags\n\n" 172 | end 173 | 174 | # Get search term (tag) from user. RF 175 | def get_search_tag_from_user 176 | default_text = @default_tag.nil? ? '' : 177 | " ( for '#{@default_tag}')" 178 | puts "Enter tag#{default_text}." 179 | get_user_command('t') 180 | end 181 | 182 | # Warns user & gets a number to delete from user; returns message. RF 183 | def confirm_delete 184 | print "WARNING! CANNOT UNDO!\nType number of task to delete or 'q' to escape: " 185 | num = gets.chomp 186 | # Do a bit of validation with user-input string first. 187 | return "'#{num}' entered so nothing deleted." if 188 | num.to_i.to_s != num # Catches 'q', '', and any non-integer. 189 | num = num.to_i # Convert to integer. 190 | # Double-check... 191 | task = fetch_task_from_displayed_number(num) 192 | puts "\nHere's the task you're about to delete:" 193 | puts delete_message(task) 194 | puts 195 | print "Press Enter to delete, 'q' to escape: " 196 | last_chance = gets.chomp 197 | return "Not deleting after all." unless last_chance == '' 198 | # Receives back a message for the user or false if delete not successful. 199 | message = delete_task(num) 200 | return message 201 | end 202 | 203 | # Simply prompts the user (twice if there's unsaved data) to confirm that 204 | # he indeed wants to destroy all task data. Returns boolean. RF 205 | def user_confirms_destruction 206 | # Explain what's happening. 207 | puts "\nTo \"destroy\" is to delete all tasks, i.e., erase the contents of data/." 208 | puts "This includes your loaded data, but does not include archives." 209 | # Get user confirmation or report status if there are unsaved changes. 210 | if $unsaved_changes 211 | puts "\nALERT! You have unarchived changes. Do you really want to do this?" 212 | puts 'Confirm with [y]es; all else quits this function.' 213 | command = get_user_command('de') 214 | return false unless command == 'y' 215 | else 216 | puts "\nLooks like you're ready; the currently-loaded data has been archived," 217 | puts "so it can be easily reloaded from the [a]rchive system." 218 | end 219 | # Final confirmation. 220 | puts "\nWARNING! Are you ready to delete all tasks? LAST WARNING! Press [y]es or [n]o." 221 | command = get_user_command('de') 222 | return command == 'y' # Returns boolean. 223 | end 224 | 225 | # Prompts user to edit all tasks at once. For now, the user can only change 226 | # all dates, and only by some offset number of days. 227 | def prompt_to_change_all_review_dates 228 | return "No tasks; can't change tasks." if @list.empty? 229 | puts "\nThis command allows you to change all task dates forward or back." 230 | puts "To move all review dates ahead by 5 days, type '5' without quotes." 231 | puts "To move all review dates to 9 days previous, type '-9'." 232 | puts "Fractional days, such as '1.5', are OK." 233 | puts "\nEnter days or 'q' to quit." 234 | offset = get_user_command('c') 235 | return "'q' entered; not changing dates." if offset == 'q' 236 | return "Number not entered; dates unchanged." unless offset =~ /^\-?\d+$/ 237 | change_all_review_dates(offset) 238 | end 239 | 240 | end 241 | --------------------------------------------------------------------------------