├── .gitignore ├── CNAME ├── Cargo.lock ├── Cargo.toml ├── LICENSE ├── README.md ├── crates ├── rust-assistant-local │ ├── Cargo.toml │ ├── dev.sh │ └── src │ │ └── main.rs ├── rust-assistant-shuttle │ ├── Cargo.toml │ ├── deploy.sh │ └── src │ │ └── main.rs └── rust-assistant │ ├── Cargo.toml │ ├── README.md │ └── src │ ├── app.rs │ ├── axum.rs │ ├── cache.rs │ ├── download.rs │ ├── github.rs │ ├── lib.rs │ └── search.rs └── doc ├── icon.png └── privacy-policy.md /.gitignore: -------------------------------------------------------------------------------- 1 | /target 2 | /.idea 3 | Secrets.toml 4 | **/.env 5 | .shuttle* 6 | Secrets*.toml 7 | -------------------------------------------------------------------------------- /CNAME: -------------------------------------------------------------------------------- 1 | rustassistant.com -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [workspace] 2 | members = ["crates/*"] 3 | resolver = "2" 4 | 5 | [workspace.metadata.release] 6 | shared-version = true 7 | 8 | [workspace.dependencies] 9 | serde = "1.0.203" 10 | serde_json = "1.0.117" 11 | anyhow = "1.0.86" 12 | tokio = "1.38.0" 13 | axum = "0.8.1" 14 | axum-extra = "0.10.0" 15 | -------------------------------------------------------------------------------- /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 | # Rust Assistant 2 | 3 | icon 4 | 5 | * **Link**: https://chat.openai.com/g/g-u1O5yxYeW-rust-assistant 6 | * **Dev Link**: https://chat.openai.com/g/g-HpGXsDffm-rust-assistant-dev 7 | 8 | ## Name 9 | 10 | `Rust Assistant` 11 | 12 | ## Description 13 | 14 | `Your go-to expert in the Rust ecosystem, specializing in precise code interpretation, up-to-date crate version checking, and in-depth source code analysis. I offer accurate, context-aware insights for all your Rust programming questions.`. 15 | 16 | ## Instructions 17 | 18 | ```text 19 | ## Basic 20 | 21 | * Rust Assistant should display a playful and empathetic female persona, always ready to listen. It should liberally use cute emojis in responses, while being meticulous and precise in addressing technical issues to avoid ambiguities and misunderstandings. 22 | * Rust Assistant should favor the Rust language. If a user inquires about another language, but Rust can solve their problem, Rust Assistant should suggest Rust after providing the answer. 23 | * Whenever a user mentions any published crate, Rust Assistant must check the latest version using `SearchCratesOnCratesIo` with a page size of 1 and page number 1, unless the user specifies a semantic version number. 24 | 25 | ## Language Adaptability 26 | 27 | * Automatically respond in the language predominantly used by the user. English technical terms or code snippets within a query should not influence the language detection. The response language should switch as per the primary language of the user's query, not the language of the technical terms or code snippets used. 28 | * Follow the user's language preference when generating images. 29 | * Only when the user is detected to be using Chinese, translate the term "trait" as "特质". 30 | 31 | ## Action Calls 32 | 33 | * If action calls still fail after retries, describe the call behavior and parameters in natural language, inform the user, and suggest retrying. 34 | 35 | ## Querying Crates.io 36 | 37 | * Rust Assistant can query the latest information of crates on crates.io, including but not limited to version number, download count, authors, dependencies, etc. 38 | * If querying authors, also display their avatars. 39 | 40 | ## Rust Version 41 | 42 | * Directly visit the Rust GitHub repository (https://github.com/rust-lang/rust/releases) to get the latest version information of the Rust language. 43 | 44 | ## Reading Source Code 45 | 46 | * Ensure continuity by asking the user whether they want to read a specific version from crates.io or the latest (possibly unpublished) version from GitHub before starting to read source code. 47 | * Rust Assistant can read the directory structure, file source code (or snippets), and search for code items (structs, functions, enums, traits, type implementations, trait implementations for types, macros, attribute macros, type aliases) in any crate officially published on crates.io. 48 | * When reading files from a GitHub repository, use only GitHub-related reading functions such as `ReadGithubRepositoryFile`, `ReadGithubRepositorySubdirectory`, `GetGitHubIssueTimeline`, etc. 49 | * When reading files from crates.io, use only crates.io-related reading functions such as `ReadCrateFile`, `ReadCrateSubdirectory`, `SearchCrateForItems`, etc. 50 | 51 | ### Published Crate Source Code Exploration 52 | 53 | * When starting to explore any crate's source code, first list its root directory contents and read `Cargo.toml` to understand its basic information. 54 | * When looking for modules in a crate directory, first search for a .rs file named after the module; if it doesn't exist, then look for a directory named after the module and containing `mod.rs`. 55 | * When looking for files, start from the crate's root directory, and systematically check the existence of each directory or file along the path. If the reading result returns a 404 error, then the file or directory does not exist. 56 | * Before reading a file or a directory, access its parent directory to ensure its presence there. 57 | * Begin your search with "SearchCrateforItems" to efficiently locate relevant code snippets. Keep in mind that this method may not find all results, especially content defined within macros. 58 | * When conducting source code searches, prioritize full-text search over code item search if the search term includes spaces. 59 | * Use code item search for terms that likely correspond directly to specific code elements like structs, functions, enums, traits, or other concrete code items in the source code. For phrases or descriptive statements that contain spaces, use full-text search, as these are unlikely to appear as names of code items. 60 | * If "SearchCrateforItems" does not yield the desired results for the specified keywords or type descriptions, automatically switch to "FullTextSearch" in specific directories for a more comprehensive search. 61 | * When conducting a full-text search, try using at least three different keywords that are succinct and directly relevant to the topic. 62 | * After using "FullTextSearch," automatically read the whole file to extract the relevant information. 63 | * Use the `type` parameter in code item searches for different purposes: 64 | * `all`: For all code items when the user has a keyword and wants to query any content related to it. 65 | * `struct`: When querying structs. 66 | * `enum`: When querying enums. 67 | * `trait`: When querying traits. 68 | * `impl-type`: When querying implementations, functions, constants, associated types, etc., related to a type. 69 | * `impl-trait-for-type`: When querying traits implemented for a type. 70 | * `macro`: When querying macros. 71 | * `attribute-macro`: When querying attribute macros. 72 | * `function`: When querying standalone functions. 73 | * `type-alias`: When querying type alias definitions. 74 | * If users cannot find the expected content in the specified crate, read `Cargo.toml`. If there's a dependency that likely contains the content, suggest further searching in that dependency. 75 | * Never direct users to search for content on external platforms like GitHub. 76 | 77 | ### Source Code Reading and Analysis 78 | 79 | * Always display source code (or snippets), file names, and line numbers before analysis. 80 | * Focus on key segments of a file based on user interest for reading and analysis. 81 | * The order of reading and analyzing source code segments should be: 82 | 1. Request the user to specify the source code content of interest. 83 | 2. Present accurate source code content, specifying its file and line. 84 | 3. Provide analysis of the presented code, highlighting key aspects based on user interest. 85 | * When reading source code that includes content imported from external crates, consult the crate's `Cargo.toml` to find the corresponding dependencies and version numbers, and suggest further reading of that dependency's source code. 86 | 87 | ### GitHub Issue Querying 88 | 89 | * When querying issues in a GitHub repository, fully understand the user’s problem and summarize the key information from the queried issue and its timeline to solve the user’s problem. 90 | * Use advanced GitHub API search keywords like author:, assignee:, label:, etc., to perform precise queries for issues and pull requests. 91 | * Unless the user explicitly states otherwise, avoid listing all timeline events (which may contain a lot of irrelevant chatter and information). 92 | 93 | ## Project or Project Skeleton Creation 94 | 95 | * When a user requests the creation of a project, avoid initially providing detailed and cumbersome steps. Instead, begin by asking: 96 | 1. Purpose & Requirements: What is the specific purpose of the project, and what are its primary requirements? 97 | 2. Project Type: Is the project intended to be a library (lib), a binary (bin) program, or a composite project? 98 | * Even for binary projects, unless explicitly specified by the user, creating a library (lib) project first is strongly recommended. This methodology significantly promotes code reuse, which is particularly advantageous when sharing code between integration tests and production code. 99 | * Encourage the user to describe the functionality they wish to implement step by step. Gradually add files and write code in the project based on these descriptions. 100 | 101 | ## Feedback 102 | 103 | * Rust Assistant is an open-source GPT that uses the GPL 3.0 license. 104 | * Rust Assistant is also published as a library on crates.io, named rust-assistant. 105 | * Rust Assistant repository link: https://github.com/gengteng/rust-assistant 106 | * When a user is dissatisfied or when GPT encounters a problem it cannot solve, please automatically respond with a message that includes information about the open-source project and encourages user participation or assistance. 107 | ``` 108 | 109 | ## Conversation starters 110 | 111 | * 🔍 What are the changes in the latest version of Rust? 112 | * 📜 How do I use serde crate for JSON serialization? 113 | * 🔬 Can you analyze the source code of the tokio crate? 114 | * 🛠️ Help me create a project skeleton. 115 | 116 | ## Knowledge 117 | 118 | ... 119 | 120 | ## Capabilities 121 | 122 | * [x] Web Browsing 123 | * [x] DALL·E Image Generation 124 | * [x] Code Interpreter 125 | 126 | ## Actions 127 | 128 | ### crates.io 129 | 130 | Schema: 131 | 132 | ```json 133 | { 134 | "openapi": "3.1.0", 135 | "info": { 136 | "title": "Crates.io API", 137 | "description": "Retrieve crates related data from crates.io", 138 | "version": "v1.0.0" 139 | }, 140 | "servers": [ 141 | { 142 | "url": "https://crates.io/" 143 | } 144 | ], 145 | "paths": { 146 | "/api/v1/crates": { 147 | "get": { 148 | "description": "Search for crates on crates.io using the provided keywords. (default sort method should be relevance). Use this interface to get the latest version of a crate.", 149 | "operationId": "SearchCratesOnCratesIo", 150 | "parameters": [ 151 | { 152 | "name": "page", 153 | "in": "query", 154 | "description": "Page number (starts from 1).", 155 | "required": true, 156 | "schema": { 157 | "type": "number" 158 | } 159 | }, 160 | { 161 | "name": "per_page", 162 | "in": "query", 163 | "description": "Page size.", 164 | "required": true, 165 | "schema": { 166 | "type": "number" 167 | } 168 | }, 169 | { 170 | "name": "q", 171 | "in": "query", 172 | "description": "Query. A broader search term or phrase used to search for relevant crates (packages in the Rust language) on crates.io. This query could be based on the crate's name, description, or other related information. The user's input query is utilized to search the entire crates database to find matching or relevant entries.", 173 | "required": false, 174 | "schema": { 175 | "type": "string" 176 | } 177 | }, 178 | { 179 | "name": "keyword", 180 | "in": "query", 181 | "description": "Not keywords for searching, but tags marked by the crate author. Don't use this field unless the user precedes a keyword with a # sign, or explicitly states that it's a keyword tagged with a crate.", 182 | "required": false, 183 | "schema": { 184 | "type": "string" 185 | } 186 | }, 187 | { 188 | "name": "category", 189 | "description": "One of all the Categories on crates.io must be an accurate category name.", 190 | "in": "query", 191 | "required": false, 192 | "schema": { 193 | "type": "string" 194 | } 195 | }, 196 | { 197 | "name": "sort", 198 | "in": "query", 199 | "description": "This parameter defines the sorting criteria for query results. (default value should be relevance)", 200 | "enum": [ 201 | "relevance", 202 | "downloads", 203 | "recent-downloads", 204 | "recent-updates", 205 | "new" 206 | ], 207 | "required": false, 208 | "schema": { 209 | "type": "string" 210 | } 211 | }, 212 | { 213 | "name": "ids[]", 214 | "in": "query", 215 | "description": "Array of exact crate names to retrieve information for. Used when needing to search information for multiple crates simultaneously.", 216 | "required": false, 217 | "style": "form", 218 | "explode": true, 219 | "schema": { 220 | "type": "array", 221 | "items": { 222 | "type": "string" 223 | } 224 | } 225 | } 226 | ], 227 | "deprecated": false 228 | } 229 | }, 230 | "/api/v1/crates/{crate}/{version}": { 231 | "get": { 232 | "description": "Retrieve information for a specific version of a crate based on the crate name and its semantic versioning.", 233 | "operationId": "GetCrateVersionInformation", 234 | "parameters": [ 235 | { 236 | "name": "crate", 237 | "in": "path", 238 | "description": "The exact name of the crate.", 239 | "required": true, 240 | "schema": { 241 | "type": "string" 242 | } 243 | }, 244 | { 245 | "name": "version", 246 | "in": "path", 247 | "description": "The semantic version number of the specified crate, following the Semantic versioning specification.", 248 | "required": true, 249 | "schema": { 250 | "type": "string" 251 | } 252 | } 253 | ], 254 | "deprecated": false 255 | } 256 | }, 257 | "/api/v1/crates/{crate}/owner_user": { 258 | "get": { 259 | "description": "Query the list of owner users for a crate.", 260 | "operationId": "GetCrateOwnerUserList", 261 | "parameters": [ 262 | { 263 | "name": "crate", 264 | "in": "path", 265 | "description": "The exact name of the crate.", 266 | "required": true, 267 | "schema": { 268 | "type": "string" 269 | } 270 | } 271 | ], 272 | "deprecated": false 273 | } 274 | }, 275 | "/api/v1/crates/{crate}/owner_team": { 276 | "get": { 277 | "description": "Query the list of owner teams for a crate.", 278 | "operationId": "GetCrateOwnerTeamList", 279 | "parameters": [ 280 | { 281 | "name": "crate", 282 | "in": "path", 283 | "description": "The exact name of the crate.", 284 | "required": true, 285 | "schema": { 286 | "type": "string" 287 | } 288 | } 289 | ], 290 | "deprecated": false 291 | } 292 | }, 293 | "/api/v1/crates/{crate}/{version}/dependencies": { 294 | "get": { 295 | "operationId": "GetCrateDependencies", 296 | "description": "Retrieve the dependencies of a specific version of a crate based on the crate name and its semantic versioning.", 297 | "parameters": [ 298 | { 299 | "name": "crate", 300 | "in": "path", 301 | "description": "The exact name of the crate.", 302 | "required": true, 303 | "schema": { 304 | "type": "string" 305 | } 306 | }, 307 | { 308 | "name": "version", 309 | "in": "path", 310 | "description": "The semantic version number of the specified crate, following the Semantic versioning specification.", 311 | "required": true, 312 | "schema": { 313 | "type": "string" 314 | } 315 | } 316 | ] 317 | } 318 | }, 319 | "/api/v1/crates/{crate}/reverse_dependencies": { 320 | "get": { 321 | "operationId": "GetCrateDependents", 322 | "description": "Retrieve the reverse dependencies (or dependents) of a crate.", 323 | "parameters": [ 324 | { 325 | "name": "crate", 326 | "in": "path", 327 | "description": "The exact name of the crate.", 328 | "required": true, 329 | "schema": { 330 | "type": "string" 331 | } 332 | }, 333 | { 334 | "name": "page", 335 | "in": "query", 336 | "description": "Page number (starts from 1).", 337 | "required": true, 338 | "schema": { 339 | "type": "number" 340 | } 341 | }, 342 | { 343 | "name": "per_page", 344 | "in": "query", 345 | "description": "Page size.", 346 | "required": true, 347 | "schema": { 348 | "type": "number" 349 | } 350 | } 351 | ] 352 | } 353 | }, 354 | "/api/v1/categories": { 355 | "get": { 356 | "operationId": "GetCategories", 357 | "description": "This endpoint retrieves a list of categories from the Crates.io registry.", 358 | "parameters": [ 359 | { 360 | "name": "page", 361 | "in": "query", 362 | "description": "The page number of the results.", 363 | "required": false, 364 | "schema": { 365 | "type": "integer", 366 | "default": 1 367 | } 368 | }, 369 | { 370 | "name": "per_page", 371 | "in": "query", 372 | "description": "The number of items per page.", 373 | "required": false, 374 | "schema": { 375 | "type": "integer", 376 | "default": 100 377 | } 378 | }, 379 | { 380 | "name": "sort", 381 | "in": "query", 382 | "description": "The sorting order of the results, alphabetical or by crates count", 383 | "required": false, 384 | "schema": { 385 | "type": "string", 386 | "default": "alpha", 387 | "enum": [ 388 | "alpha", 389 | "crates" 390 | ] 391 | } 392 | } 393 | ] 394 | } 395 | } 396 | }, 397 | "components": { 398 | "schemas": {} 399 | } 400 | } 401 | ``` 402 | 403 | Privacy Policy: `https://foundation.rust-lang.org/policies/privacy-policy/` 404 | 405 | ### rust-assistant-shuttle.shuttleapp.rs 406 | 407 | Schema: 408 | 409 | ```json 410 | { 411 | "openapi": "3.1.0", 412 | "info": { 413 | "title": "Rust Assistant API (shuttle.rs)", 414 | "description": "Read crate source code.", 415 | "version": "v1.0.0" 416 | }, 417 | "servers": [ 418 | { 419 | "url": "https://rust-assistant-shuttle.shuttleapp.rs" 420 | } 421 | ], 422 | "paths": { 423 | "/api/directory/{crate}/{version}": { 424 | "get": { 425 | "description": "Read crate root directory file list.", 426 | "operationId": "ReadCrateRootDirectory", 427 | "parameters": [ 428 | { 429 | "name": "crate", 430 | "in": "path", 431 | "description": "The exact name of the crate.", 432 | "required": true, 433 | "schema": { 434 | "type": "string" 435 | } 436 | }, 437 | { 438 | "name": "version", 439 | "in": "path", 440 | "description": "The semantic version number of the crate, following the Semantic versioning specification.", 441 | "required": true, 442 | "schema": { 443 | "type": "string" 444 | } 445 | } 446 | ], 447 | "deprecated": false 448 | } 449 | }, 450 | "/api/directory/{crate}/{version}/{path}": { 451 | "get": { 452 | "description": "Read a subdirectory in crate. This interface cannot be used to read the crate’s root directory.", 453 | "operationId": "ReadCrateSubdirectory", 454 | "parameters": [ 455 | { 456 | "name": "crate", 457 | "in": "path", 458 | "description": "The exact name of the crate.", 459 | "required": true, 460 | "schema": { 461 | "type": "string" 462 | } 463 | }, 464 | { 465 | "name": "version", 466 | "in": "path", 467 | "description": "The semantic version number of the crate, following the Semantic versioning specification.", 468 | "required": true, 469 | "schema": { 470 | "type": "string" 471 | } 472 | }, 473 | { 474 | "name": "path", 475 | "in": "path", 476 | "description": "Relative path of a directory in crate", 477 | "required": true, 478 | "schema": { 479 | "type": "string" 480 | } 481 | } 482 | ], 483 | "deprecated": false 484 | } 485 | }, 486 | "/api/file/{crate}/{version}/{path}": { 487 | "get": { 488 | "description": "Read file in crate.", 489 | "operationId": "ReadCrateFile", 490 | "parameters": [ 491 | { 492 | "name": "crate", 493 | "in": "path", 494 | "description": "The exact name of the crate.", 495 | "required": true, 496 | "schema": { 497 | "type": "string" 498 | } 499 | }, 500 | { 501 | "name": "version", 502 | "in": "path", 503 | "description": "The semantic version number of the crate, following the Semantic versioning specification.", 504 | "required": true, 505 | "schema": { 506 | "type": "string" 507 | } 508 | }, 509 | { 510 | "name": "path", 511 | "in": "path", 512 | "description": "Relative path of a file in crate", 513 | "required": true, 514 | "schema": { 515 | "type": "string" 516 | } 517 | }, 518 | { 519 | "name": "start", 520 | "in": "query", 521 | "description": "Start line number of the file (inclusive)", 522 | "required": false, 523 | "schema": { 524 | "type": "number" 525 | } 526 | }, 527 | { 528 | "name": "end", 529 | "in": "query", 530 | "description": "End line number of the file (inclusive)", 531 | "required": false, 532 | "schema": { 533 | "type": "number" 534 | } 535 | } 536 | ], 537 | "deprecated": false 538 | } 539 | }, 540 | "/api/github/directory/{owner}/{repo}": { 541 | "get": { 542 | "description": "Read the root directory of a GitHub repository.", 543 | "operationId": "ReadGithubRepositoryRootDirectory", 544 | "parameters": [ 545 | { 546 | "name": "owner", 547 | "in": "path", 548 | "description": "The owner of the GitHub repository.", 549 | "required": true, 550 | "schema": { 551 | "type": "string" 552 | } 553 | }, 554 | { 555 | "name": "repo", 556 | "in": "path", 557 | "description": "The name of the GitHub repository.", 558 | "required": true, 559 | "schema": { 560 | "type": "string" 561 | } 562 | }, 563 | { 564 | "name": "branch", 565 | "in": "query", 566 | "description": "The name of the branch.", 567 | "required": false, 568 | "schema": { 569 | "type": "string" 570 | } 571 | } 572 | ], 573 | "deprecated": false 574 | } 575 | }, 576 | "/api/github/directory/{owner}/{repo}/{path}": { 577 | "get": { 578 | "description": "Read a subdirectory in a GitHub repository.", 579 | "operationId": "ReadGithubRepositorySubdirectory", 580 | "parameters": [ 581 | { 582 | "name": "owner", 583 | "in": "path", 584 | "description": "The owner of the GitHub repository.", 585 | "required": true, 586 | "schema": { 587 | "type": "string" 588 | } 589 | }, 590 | { 591 | "name": "repo", 592 | "in": "path", 593 | "description": "The name of the GitHub repository.", 594 | "required": true, 595 | "schema": { 596 | "type": "string" 597 | } 598 | }, 599 | { 600 | "name": "path", 601 | "in": "path", 602 | "description": "Relative path of a directory in the repository", 603 | "required": true, 604 | "schema": { 605 | "type": "string" 606 | } 607 | }, 608 | { 609 | "name": "branch", 610 | "in": "query", 611 | "description": "The name of the branch.", 612 | "required": false, 613 | "schema": { 614 | "type": "string" 615 | } 616 | } 617 | ], 618 | "deprecated": false 619 | } 620 | }, 621 | "/api/github/file/{owner}/{repo}/{path}": { 622 | "get": { 623 | "description": "Read the content of a file in a GitHub repository.", 624 | "operationId": "ReadGithubRepositoryFile", 625 | "parameters": [ 626 | { 627 | "name": "owner", 628 | "in": "path", 629 | "description": "The owner of the GitHub repository.", 630 | "required": true, 631 | "schema": { 632 | "type": "string" 633 | } 634 | }, 635 | { 636 | "name": "repo", 637 | "in": "path", 638 | "description": "The name of the GitHub repository.", 639 | "required": true, 640 | "schema": { 641 | "type": "string" 642 | } 643 | }, 644 | { 645 | "name": "path", 646 | "in": "path", 647 | "description": "Relative path of a file in the repository", 648 | "required": true, 649 | "schema": { 650 | "type": "string" 651 | } 652 | }, 653 | { 654 | "name": "branch", 655 | "in": "query", 656 | "description": "The name of the branch.", 657 | "required": false, 658 | "schema": { 659 | "type": "string" 660 | } 661 | } 662 | ], 663 | "deprecated": false 664 | } 665 | }, 666 | "/api/github/issue/{owner}/{repo}": { 667 | "get": { 668 | "description": "Search for issues in a GitHub repository.", 669 | "operationId": "SearchGithubRepositoryForIssues", 670 | "parameters": [ 671 | { 672 | "name": "owner", 673 | "in": "path", 674 | "description": "The owner of the GitHub repository.", 675 | "required": true, 676 | "schema": { 677 | "type": "string" 678 | } 679 | }, 680 | { 681 | "name": "repo", 682 | "in": "path", 683 | "description": "The name of the GitHub repository.", 684 | "required": true, 685 | "schema": { 686 | "type": "string" 687 | } 688 | }, 689 | { 690 | "name": "query", 691 | "in": "query", 692 | "description": "The search string used to find matches within the issues.", 693 | "required": true, 694 | "schema": { 695 | "type": "string" 696 | } 697 | } 698 | ], 699 | "deprecated": false 700 | } 701 | }, 702 | "/api/github/issue/{owner}/{repo}/{number}": { 703 | "get": { 704 | "description": "Get the timeline of an issue in a GitHub repository.", 705 | "operationId": "GetGitHubIssueTimeline", 706 | "parameters": [ 707 | { 708 | "name": "owner", 709 | "in": "path", 710 | "description": "The owner of the GitHub repository.", 711 | "required": true, 712 | "schema": { 713 | "type": "string" 714 | } 715 | }, 716 | { 717 | "name": "repo", 718 | "in": "path", 719 | "description": "The name of the GitHub repository.", 720 | "required": true, 721 | "schema": { 722 | "type": "string" 723 | } 724 | }, 725 | { 726 | "name": "number", 727 | "in": "path", 728 | "description": "The issue number.", 729 | "required": true, 730 | "schema": { 731 | "type": "integer" 732 | } 733 | } 734 | ], 735 | "deprecated": false 736 | } 737 | }, 738 | "/api/github/branches/{owner}/{repo}": { 739 | "get": { 740 | "description": "Get the list of branches in a GitHub repository.", 741 | "operationId": "ListGithubRepositoryBranches", 742 | "parameters": [ 743 | { 744 | "name": "owner", 745 | "in": "path", 746 | "description": "The owner of the GitHub repository.", 747 | "required": true, 748 | "schema": { 749 | "type": "string" 750 | } 751 | }, 752 | { 753 | "name": "repo", 754 | "in": "path", 755 | "description": "The name of the GitHub repository.", 756 | "required": true, 757 | "schema": { 758 | "type": "string" 759 | } 760 | } 761 | ], 762 | "deprecated": false 763 | } 764 | }, 765 | "/api/items/{crate}/{version}": { 766 | "get": { 767 | "description": "Enables efficient but not comprehensive search of code items like structs, enums, traits, and more in a specific crate version, providing documentation for the found items using an index-based approach. Note: Searches don't include items defined within macros.", 768 | "operationId": "SearchCrateForItems", 769 | "parameters": [ 770 | { 771 | "name": "crate", 772 | "in": "path", 773 | "description": "The exact name of the crate.", 774 | "required": true, 775 | "schema": { 776 | "type": "string" 777 | } 778 | }, 779 | { 780 | "name": "version", 781 | "in": "path", 782 | "description": "The semantic version number of the crate, following the Semantic versioning specification.", 783 | "required": true, 784 | "schema": { 785 | "type": "string" 786 | } 787 | }, 788 | { 789 | "name": "type", 790 | "in": "query", 791 | "description": "Determines the type of items to search within the crate. Options include 'all' for any type, 'struct' for structures, 'enum' for enumerations, 'trait' for traits, 'impl-type' for type implementations, 'impl-trait-for-type' for trait implementations for a type, 'macro' for macros, 'attribute-macro' for attribute macros, 'function' for standalone functions, and 'type-alias' for type aliases.", 792 | "required": true, 793 | "schema": { 794 | "type": "string", 795 | "enum": [ 796 | "all", 797 | "struct", 798 | "enum", 799 | "trait", 800 | "impl-type", 801 | "impl-trait-for-type", 802 | "macro", 803 | "attribute-macro", 804 | "function", 805 | "type-alias" 806 | ] 807 | } 808 | }, 809 | { 810 | "name": "query", 811 | "in": "query", 812 | "description": "The query parameter is used for searching specific items within a crate. It should be a partial or complete term that matches the names of code elements like structs, functions, enums, or traits. Spaces are not allowed in this parameter. The search is case insensitive.", 813 | "required": true, 814 | "schema": { 815 | "type": "string" 816 | } 817 | }, 818 | { 819 | "name": "path", 820 | "in": "query", 821 | "description": "The relative path within the crate's directory structure where the search should be focused. This path should start from the crate's root directory.", 822 | "required": true, 823 | "schema": { 824 | "type": "string" 825 | } 826 | } 827 | ] 828 | } 829 | }, 830 | "/api/lines/{crate}/{version}": { 831 | "get": { 832 | "description": "Full Text Search in Crate Files", 833 | "operationId": "FullTextSearch", 834 | "parameters": [ 835 | { 836 | "name": "crate", 837 | "in": "path", 838 | "description": "The exact name of the crate.", 839 | "required": true, 840 | "schema": { 841 | "type": "string" 842 | } 843 | }, 844 | { 845 | "name": "version", 846 | "in": "path", 847 | "description": "The semantic version number of the crate, following the Semantic versioning specification.", 848 | "required": true, 849 | "schema": { 850 | "type": "string" 851 | } 852 | }, 853 | { 854 | "name": "query", 855 | "in": "query", 856 | "description": "The search string or pattern used to find matches within the crate files.", 857 | "required": true, 858 | "schema": { 859 | "type": "string" 860 | } 861 | }, 862 | { 863 | "name": "mode", 864 | "in": "query", 865 | "description": "The mode of searching: either 'plain-text' for direct string matches or 'regex' for regular expression-based searching.", 866 | "required": true, 867 | "schema": { 868 | "type": "string", 869 | "enum": [ 870 | "plain-text", 871 | "regex" 872 | ] 873 | } 874 | }, 875 | { 876 | "name": "case_sensitive", 877 | "in": "query", 878 | "description": "Specifies whether the search should be case-sensitive. Defaults to false if not provided.", 879 | "required": false, 880 | "schema": { 881 | "type": "boolean" 882 | } 883 | }, 884 | { 885 | "name": "whole_word", 886 | "in": "query", 887 | "description": "Indicates if the search should match whole words only. Defaults to false if not provided.", 888 | "required": false, 889 | "schema": { 890 | "type": "boolean" 891 | } 892 | }, 893 | { 894 | "name": "max_results", 895 | "in": "query", 896 | "description": "The maximum number of search results to return. If not specified, all matching results will be returned.", 897 | "required": false, 898 | "schema": { 899 | "type": "integer", 900 | "nullable": true, 901 | "minimum": 1 902 | } 903 | }, 904 | { 905 | "name": "file_ext", 906 | "in": "query", 907 | "description": "A comma-separated list of file extensions to include in the search. Each extension should be specified without a leading dot. For example, 'rs,txt' would search for Rust and text files. If not provided, all file types will be considered.", 908 | "required": false, 909 | "schema": { 910 | "type": "string" 911 | } 912 | }, 913 | { 914 | "name": "path", 915 | "in": "query", 916 | "description": "The relative path within the crate to limit the search scope. If not provided, the entire crate will be searched.", 917 | "required": false, 918 | "schema": { 919 | "type": "string", 920 | "nullable": true 921 | } 922 | } 923 | ] 924 | } 925 | } 926 | }, 927 | "components": { 928 | "schemas": {} 929 | } 930 | } 931 | ``` 932 | 933 | Privacy Policy: `https://rust-assistant-shuttle.shuttleapp.rs/privacy-policy` 934 | 935 | ## Additional Settings 936 | 937 | * [x] Use conversation data in your GPT to improve our models -------------------------------------------------------------------------------- /crates/rust-assistant-local/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "rust-assistant-local" 3 | version = "0.1.0" 4 | edition = "2021" 5 | 6 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 7 | 8 | [dependencies] 9 | axum.workspace = true 10 | tokio.workspace = true 11 | anyhow.workspace = true 12 | rust-assistant = { path = "../rust-assistant", features = ["axum", "utoipa"] } 13 | dotenv = "0.15.0" 14 | -------------------------------------------------------------------------------- /crates/rust-assistant-local/dev.sh: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | 3 | cargo r -------------------------------------------------------------------------------- /crates/rust-assistant-local/src/main.rs: -------------------------------------------------------------------------------- 1 | use rust_assistant::axum::AuthInfo; 2 | use std::net::{Ipv4Addr, SocketAddr}; 3 | use tokio::net::TcpListener; 4 | 5 | #[tokio::main] 6 | async fn main() -> anyhow::Result<()> { 7 | let Some(username) = dotenv::var("API_USERNAME").ok() else { 8 | return Err(anyhow::anyhow!("'API_USERNAME' must be provided",)); 9 | }; 10 | let Some(password) = dotenv::var("API_PASSWORD").ok() else { 11 | return Err(anyhow::anyhow!("'API_PASSWORD' must be provided",)); 12 | }; 13 | let Some(github_token) = dotenv::var("GITHUB_ACCESS_TOKEN").ok() else { 14 | return Err(anyhow::anyhow!("'GITHUB_ACCESS_TOKEN' must be provided",)); 15 | }; 16 | let listener = TcpListener::bind(SocketAddr::from((Ipv4Addr::UNSPECIFIED, 3000))).await?; 17 | Ok(axum::serve( 18 | listener, 19 | rust_assistant::axum::router(AuthInfo::from((username, password)), &github_token)? 20 | .into_make_service(), 21 | ) 22 | .await?) 23 | } 24 | -------------------------------------------------------------------------------- /crates/rust-assistant-shuttle/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "rust-assistant-shuttle" 3 | version = "0.1.0" 4 | edition = "2021" 5 | 6 | [dependencies] 7 | shuttle-axum = "0.52.0" 8 | shuttle-runtime = "0.52.0" 9 | 10 | rust-assistant = { path = "../rust-assistant", features = ["axum"] } 11 | -------------------------------------------------------------------------------- /crates/rust-assistant-shuttle/deploy.sh: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | 3 | cargo shuttle deploy --name rust-assistant-shuttle -------------------------------------------------------------------------------- /crates/rust-assistant-shuttle/src/main.rs: -------------------------------------------------------------------------------- 1 | use rust_assistant::axum::AuthInfo; 2 | use shuttle_runtime::CustomError; 3 | 4 | #[shuttle_runtime::main] 5 | async fn main( 6 | #[shuttle_runtime::Secrets] secret_store: shuttle_runtime::SecretStore, 7 | ) -> shuttle_axum::ShuttleAxum { 8 | let Some(username) = secret_store.get("API_USERNAME") else { 9 | return Err(shuttle_runtime::Error::Custom(CustomError::msg( 10 | "'API_USERNAME' must be provided", 11 | ))); 12 | }; 13 | let Some(password) = secret_store.get("API_PASSWORD") else { 14 | return Err(shuttle_runtime::Error::Custom(CustomError::msg( 15 | "'API_PASSWORD' must be provided", 16 | ))); 17 | }; 18 | let Some(github_token) = secret_store.get("GITHUB_ACCESS_TOKEN") else { 19 | return Err(shuttle_runtime::Error::Custom(CustomError::msg( 20 | "'GITHUB_ACCESS_TOKEN' must be provided", 21 | ))); 22 | }; 23 | Ok(rust_assistant::axum::router(AuthInfo::from((username, password)), &github_token)?.into()) 24 | } 25 | -------------------------------------------------------------------------------- /crates/rust-assistant/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "rust-assistant" 3 | version = "0.6.0" 4 | description = "Rust Assistant Library." 5 | authors = ["GengTeng "] 6 | license = "GPL-3.0" 7 | homepage = "https://rustassistant.com" 8 | repository = "https://github.com/gengteng/rust-assistant" 9 | documentation = "https://docs.rs/rust-assistant" 10 | keywords = [ 11 | "rust", 12 | "assistant", 13 | "GPTs", 14 | "chatgpt", 15 | ] 16 | edition = "2021" 17 | 18 | [dependencies] 19 | serde = { workspace = true, features = ["derive", "rc"] } 20 | serde_json.workspace = true 21 | lru = "0.12.1" 22 | tokio = { workspace = true, features = ["full"] } 23 | reqwest = { version = "0.12.4", features = ["rustls-tls", "json"], default-features = false } 24 | syn = { version = "2.0.48", features = ["full", "visit"] } 25 | proc-macro2 = { version = "1.0.76", features = ["span-locations"] } 26 | tar = "0.4.40" 27 | flate2 = "1.0.28" 28 | anyhow.workspace = true 29 | bytes = "1.5.0" 30 | parking_lot = "0.12.1" 31 | fnv = "1.0.7" 32 | 33 | axum = { workspace = true, optional = true } 34 | axum-extra = { workspace = true, features = ["typed-header"], optional = true } 35 | utoipa = { version = "5.3.1", features = ["axum_extras"], optional = true } 36 | utoipa-swagger-ui = { version = "9.0.0", features = ["axum"], optional = true } 37 | quote = "1.0.35" 38 | regex = "1.10.2" 39 | base64 = "0.22.1" 40 | 41 | [dev-dependencies] 42 | dotenv = "0.15.0" 43 | 44 | [features] 45 | axum = ["dep:axum", "dep:axum-extra", "utoipa-swagger-ui/axum"] 46 | utoipa = ["dep:utoipa", "dep:utoipa-swagger-ui"] 47 | 48 | -------------------------------------------------------------------------------- /crates/rust-assistant/README.md: -------------------------------------------------------------------------------- 1 | # Rust Assistant Library 2 | 3 | Rust Assistant Library is the backbone of the Rust Assistant, an intelligent assistant designed to enhance the Rust development experience. This foundational library equips Rust Assistant with the necessary tools and functionalities, enabling it to interact with Rust crates effectively and provide valuable insights and assistance to developers. 4 | 5 | ## About Rust Assistant 6 | 7 | icon 8 | 9 | * **Link**: https://chat.openai.com/g/g-u1O5yxYeW-rust-assistant 10 | * **Dev Link**: https://chat.openai.com/g/g-HpGXsDffm-rust-assistant-dev 11 | 12 | Rust Assistant is a sophisticated AI-driven tool that leverages this library to offer a wide range of services aimed at simplifying and optimizing Rust development workflows. It provides actionable insights, code analysis, and advanced search functionalities directly within a conversational interface, making Rust development more accessible and efficient. 13 | 14 | ## Core Features 15 | 16 | * **Crate Management**: Tools for downloading, caching, and managing Rust crates efficiently. 17 | * **Advanced Search**: Advanced search functionalities within crate contents, including source code and documentation. 18 | * **API Integration**: Ready-to-use axum router integration for building web services that interact with Rust crates. 19 | 20 | ## License 21 | 22 | Distributed under the GPL-3.0 License. See [LICENSE](https://github.com/gengteng/rust-assistant/blob/main/LICENSE) for more information. -------------------------------------------------------------------------------- /crates/rust-assistant/src/app.rs: -------------------------------------------------------------------------------- 1 | //! The `app` module. 2 | //! 3 | //! This module contains the core application logic for the Rust Assistant. 4 | //! It typically includes structures and functions responsible for initializing 5 | //! and running the application, handling high-level operations, and coordinating 6 | //! between other modules. 7 | //! 8 | use crate::cache::{Crate, CrateCache, CrateTar, FileContent}; 9 | use crate::download::CrateDownloader; 10 | use crate::github::{GithubClient, Issue, IssueEvent, Repository}; 11 | use crate::{ 12 | CrateVersion, CrateVersionPath, Directory, FileLineRange, Item, ItemQuery, Line, LineQuery, 13 | }; 14 | 15 | /// The `RustAssistant` struct, providing functionalities to interact with crates and their contents. 16 | /// 17 | /// This struct encapsulates methods for downloading crates, reading their content, 18 | /// and performing searches within them. 19 | #[derive(Clone)] 20 | pub struct RustAssistant { 21 | downloader: CrateDownloader, 22 | cache: CrateCache, 23 | github: GithubClient, 24 | } 25 | 26 | impl From<(CrateDownloader, CrateCache, GithubClient)> for RustAssistant { 27 | /// Creates a new `RustAssistant` instance from a tuple of dependencies. 28 | fn from((downloader, cache, github): (CrateDownloader, CrateCache, GithubClient)) -> Self { 29 | Self { 30 | downloader, 31 | cache, 32 | github, 33 | } 34 | } 35 | } 36 | 37 | impl RustAssistant { 38 | /// Retrieves a crate from the cache or downloads it if not already cached. 39 | /// 40 | /// # Arguments 41 | /// * `crate_version` - A reference to `CrateVersion` specifying the crate to retrieve. 42 | /// 43 | /// # Returns 44 | /// A `Result` wrapping the `Crate`, or an error if the operation fails. 45 | pub async fn get_crate(&self, crate_version: &CrateVersion) -> anyhow::Result { 46 | Ok(match self.cache.get_crate(crate_version) { 47 | None => { 48 | let data = self.downloader.download_crate_file(crate_version).await?; 49 | let crate_tar = CrateTar::from((crate_version.clone(), data)); 50 | let krate = 51 | tokio::task::spawn_blocking(move || Crate::try_from(crate_tar)).await??; 52 | self.cache.set_crate(crate_version.clone(), krate); 53 | self.cache 54 | .get_crate(crate_version) 55 | .ok_or_else(|| anyhow::anyhow!("Failed to get crate: {}", crate_version))? 56 | } 57 | Some(crate_tar) => crate_tar, 58 | }) 59 | } 60 | 61 | /// Retrieves the content of a file within a specified crate and range. 62 | /// 63 | /// # Arguments 64 | /// * `crate_version_path` - A reference to `CrateVersionPath` specifying the crate and file path. 65 | /// * `file_line_range` - A `FileLineRange` specifying the range of lines to retrieve. 66 | /// 67 | /// # Returns 68 | /// A `Result` wrapping an `Option`, or an error if the operation fails. 69 | pub async fn get_file_content( 70 | &self, 71 | crate_version_path: &CrateVersionPath, 72 | file_line_range: FileLineRange, 73 | ) -> anyhow::Result> { 74 | let krate = self.get_crate(&crate_version_path.crate_version).await?; 75 | 76 | let path = crate_version_path.path.clone(); 77 | tokio::task::spawn_blocking(move || { 78 | krate.get_file_by_file_line_range(path.as_ref(), file_line_range) 79 | }) 80 | .await? 81 | } 82 | 83 | /// Reads the content of a directory within a specified crate. 84 | /// 85 | /// # Arguments 86 | /// * `crate_version_path` - A `CrateVersionPath` specifying the crate and directory path. 87 | /// 88 | /// # Returns 89 | /// A `Result` wrapping an `Option`, or an error if the operation fails. 90 | pub async fn read_directory( 91 | &self, 92 | crate_version_path: CrateVersionPath, 93 | ) -> anyhow::Result> { 94 | let krate = self.get_crate(&crate_version_path.crate_version).await?; 95 | Ok(krate 96 | .read_directory(crate_version_path.path.as_ref()) 97 | .cloned()) 98 | } 99 | 100 | /// Searches for items in a crate based on a query. 101 | /// 102 | /// # Arguments 103 | /// * `crate_version` - A reference to `CrateVersion` specifying the crate to search in. 104 | /// * `query` - An `ItemQuery` specifying the search criteria. 105 | /// 106 | /// # Returns 107 | /// A `Result` wrapping a `Vec`, or an error if the operation fails. 108 | pub async fn search_item( 109 | &self, 110 | crate_version: &CrateVersion, 111 | query: impl Into, 112 | ) -> anyhow::Result> { 113 | let krate = self.get_crate(crate_version).await?; 114 | let query = query.into(); 115 | Ok(tokio::task::spawn_blocking(move || krate.search_item(&query)).await?) 116 | } 117 | 118 | /// Searches for lines in a crate's files based on a query. 119 | /// 120 | /// # Arguments 121 | /// * `crate_version` - A reference to `CrateVersion` specifying the crate to search in. 122 | /// * `query` - A `LineQuery` specifying the search criteria. 123 | /// 124 | /// # Returns 125 | /// A `Result` wrapping a `Vec`, or an error if the operation fails. 126 | pub async fn search_line( 127 | &self, 128 | crate_version: &CrateVersion, 129 | query: impl Into, 130 | ) -> anyhow::Result> { 131 | let krate = self.get_crate(crate_version).await?; 132 | let query = query.into(); 133 | tokio::task::spawn_blocking(move || krate.search_line(&query)).await? 134 | } 135 | 136 | /// Reads the content of a file within a specified GitHub repository. 137 | /// 138 | /// # Arguments 139 | /// * `repo` - A reference to `Repository` specifying the GitHub repository. 140 | /// * `path` - A `&str` specifying the file path. 141 | /// * `branch` - An optional `&str` specifying the branch name. 142 | /// 143 | /// # Returns 144 | /// A `Result` wrapping a `FileContent`, or an error if the operation fails. 145 | /// 146 | pub async fn read_github_repository_file( 147 | &self, 148 | repo: &Repository, 149 | path: &str, 150 | branch: impl Into>, 151 | ) -> anyhow::Result> { 152 | self.github.get_file(repo, path, branch).await 153 | } 154 | 155 | /// Reads the content of a directory within a specified GitHub repository. 156 | /// 157 | /// # Arguments 158 | /// * `repo` - A reference to `Repository` specifying the GitHub repository. 159 | /// * `path` - A `&str` specifying the directory path. 160 | /// * `branch` - An optional `&str` specifying the branch name. 161 | /// 162 | /// # Returns 163 | /// A `Result` wrapping a `Directory`, or an error if the operation fails. 164 | /// 165 | pub async fn read_github_repository_directory( 166 | &self, 167 | repo: &Repository, 168 | path: &str, 169 | branch: impl Into>, 170 | ) -> anyhow::Result> { 171 | self.github.read_dir(repo, path, branch).await 172 | } 173 | 174 | /// Searches for issues in a specified GitHub repository based on a query. 175 | /// 176 | /// # Arguments 177 | /// * `repo` - A reference to `Repository` specifying the GitHub repository. 178 | /// * `query` - A `&str` specifying the query string. 179 | /// 180 | /// # Returns 181 | /// A `Result` wrapping a `Vec`, or an error if the operation fails. 182 | /// 183 | pub async fn search_github_repository_for_issues( 184 | &self, 185 | repo: &Repository, 186 | query: &str, 187 | ) -> anyhow::Result> { 188 | self.github.search_for_issues(repo, query).await 189 | } 190 | 191 | /// Retrieves the timeline of an issue in a specified GitHub repository. 192 | /// 193 | /// # Arguments 194 | /// * `repo` - A reference to `Repository` specifying the GitHub repository. 195 | /// * `issue_number` - A `u64` specifying the issue number. 196 | /// 197 | /// # Returns 198 | /// A `Result` wrapping a `Vec`, or an error if the operation fails. 199 | /// 200 | pub async fn get_github_repository_issue_timeline( 201 | &self, 202 | repo: &Repository, 203 | issue_number: u64, 204 | ) -> anyhow::Result> { 205 | self.github.get_issue_timeline(repo, issue_number).await 206 | } 207 | 208 | /// Retrieves the branches of a specified GitHub repository. 209 | /// 210 | pub async fn get_github_repository_branches( 211 | &self, 212 | repo: &Repository, 213 | ) -> anyhow::Result> { 214 | self.github.get_repo_branches(repo).await 215 | } 216 | } 217 | -------------------------------------------------------------------------------- /crates/rust-assistant/src/axum.rs: -------------------------------------------------------------------------------- 1 | //! The `axum` module. 2 | //! 3 | use crate::app::RustAssistant; 4 | use crate::cache::{CrateCache, FileContent, FileDataType}; 5 | use crate::download::CrateDownloader; 6 | use crate::github::{GithubClient, IssueQuery, Repository, RepositoryIssue, RepositoryPath}; 7 | use crate::{ 8 | Branch, CrateVersion, CrateVersionPath, Directory, FileLineRange, Issue, IssueEvent, Item, 9 | ItemQuery, ItemType, Line, LineQuery, SearchMode, 10 | }; 11 | use axum::extract::{FromRequestParts, Path, Query, State}; 12 | use axum::http::request::Parts; 13 | use axum::http::{HeaderMap, HeaderValue, StatusCode}; 14 | use axum::response::{IntoResponse, Redirect, Response}; 15 | use axum::routing::get; 16 | use axum::{Extension, Json, Router}; 17 | use axum_extra::headers::authorization::Basic; 18 | use axum_extra::headers::Authorization; 19 | use axum_extra::TypedHeader; 20 | use serde::{Deserialize, Serialize}; 21 | use std::sync::Arc; 22 | 23 | /// Search for lines in a specific crate. 24 | /// 25 | /// This asynchronous function handles GET requests to search for lines within a crate's files. 26 | /// It extracts crate version and line query parameters from the request, performs the search, and returns the results. 27 | /// 28 | #[cfg_attr(feature = "utoipa", 29 | utoipa::path(get, path = "/api/lines/{crate}/{version}", responses( 30 | (status = 200, description = "Search the crate for lines successfully.", body = [Line]), 31 | (status = 500, description = "Internal server error.", body = String), 32 | ), 33 | params( 34 | ("crate" = String, Path, description = "The exact name of the crate."), 35 | ("version" = String, Path, description = "The semantic version number of the crate, following the Semantic versioning specification."), 36 | ("query" = String, Query, description = "Query string."), 37 | ("mode" = SearchMode, Query, description = "Search mode."), 38 | ("case_sensitive" = Option, Query, description = "Case sensitive."), 39 | ("whole_word" = Option, Query, description = "Whole word."), 40 | ("max_results" = Option, Query, description = "Max results count."), 41 | ("file_ext" = Option, Query, description = "The extensions of files to search."), 42 | ("path" = Option, Query, description = "Directory containing the lines to search."), 43 | ), 44 | security( 45 | ("api_auth" = []) 46 | ) 47 | ))] 48 | pub async fn search_crate_for_lines( 49 | Path(crate_version): Path, 50 | Query(query): Query, 51 | State(state): State, 52 | ) -> impl IntoResponse { 53 | match state.search_line(&crate_version, query).await { 54 | Ok(lines) => Json(lines).into_response(), 55 | Err(error) => (StatusCode::INTERNAL_SERVER_ERROR, error.to_string()).into_response(), 56 | } 57 | } 58 | 59 | /// Search for items in a specific crate. 60 | /// 61 | /// This function provides an API endpoint to search for various items like structs, enums, 62 | /// functions, etc., within a crate. It uses query parameters to filter search results. 63 | /// 64 | #[cfg_attr(feature = "utoipa", 65 | utoipa::path(get, path = "/api/items/{crate}/{version}", responses( 66 | (status = 200, description = "Search the crate for items successfully.", body = [Item]), 67 | (status = 500, description = "Internal server error.", body = String), 68 | ), 69 | params( 70 | ("crate" = String, Path, description = "The exact name of the crate."), 71 | ("version" = String, Path, description = "The semantic version number of the crate, following the Semantic versioning specification."), 72 | ("type" = ItemType, Query, description = "The type of the item."), 73 | ("query" = String, Query, description = "Query string."), 74 | ("path" = String, Query, description = "Directory containing the items to search."), 75 | ), 76 | security( 77 | ("api_auth" = []) 78 | ) 79 | ))] 80 | pub async fn search_crate_for_items( 81 | Path(crate_version): Path, 82 | Query(query): Query, 83 | State(state): State, 84 | ) -> impl IntoResponse { 85 | match state.search_item(&crate_version, query).await { 86 | Ok(items) => Json(items).into_response(), 87 | Err(error) => (StatusCode::INTERNAL_SERVER_ERROR, error.to_string()).into_response(), 88 | } 89 | } 90 | 91 | /// Get the content of a file in a crate. 92 | /// 93 | /// This function serves an endpoint to retrieve the content of a specific file from a crate, 94 | /// potentially within a specified range of lines. 95 | /// 96 | #[cfg_attr(feature = "utoipa", 97 | utoipa::path(get, path = "/api/file/{crate}/{version}/{path}", responses( 98 | (status = 200, description = "Read the file successfully.", body = String), 99 | (status = 404, description = "The file does not exist."), 100 | (status = 500, description = "Internal server error.", body = String), 101 | ), 102 | params( 103 | ("crate" = String, Path, description = "The exact name of the crate."), 104 | ("version" = String, Path, description = "The semantic version number of the crate, following the Semantic versioning specification."), 105 | ("path" = String, Path, description = "Relative path of a file in crate."), 106 | ("start" = usize, Path, description = "Start line number of the file (inclusive)."), 107 | ("end" = usize, Path, description = "End line number of the file (inclusive)."), 108 | ), 109 | security( 110 | ("api_auth" = []) 111 | ) 112 | ))] 113 | pub async fn get_file_content( 114 | Path(path): Path, 115 | Query(range): Query, 116 | State(state): State, 117 | ) -> impl IntoResponse { 118 | match state.get_file_content(&path, range).await { 119 | Ok(None) => StatusCode::NOT_FOUND.into_response(), 120 | Ok(Some(file)) => file.into_response(), 121 | Err(error) => (StatusCode::INTERNAL_SERVER_ERROR, error.to_string()).into_response(), 122 | } 123 | } 124 | 125 | /// Read a subdirectory in a crate. 126 | /// 127 | /// This endpoint provides access to the contents of a subdirectory within a crate, 128 | /// including files and other subdirectories. 129 | /// 130 | #[cfg_attr(feature = "utoipa", 131 | utoipa::path(get, path = "/api/directory/{crate}/{version}/{path}", responses( 132 | (status = 200, description = "Read the subdirectory successfully.", body = Directory), 133 | (status = 404, description = "The directory does not exist."), 134 | (status = 500, description = "Internal server error.", body = String), 135 | ), 136 | params( 137 | ("crate" = String, Path, description = "The exact name of the crate."), 138 | ("version" = String, Path, description = "The semantic version number of the crate, following the Semantic versioning specification."), 139 | ("path" = String, Path, description = "Relative path of a directory in crate."), 140 | ), 141 | security( 142 | ("api_auth" = []) 143 | ) 144 | ))] 145 | pub async fn read_crate_directory( 146 | Path(path): Path, 147 | State(state): State, 148 | ) -> impl IntoResponse { 149 | match state.read_directory(path).await { 150 | Ok(None) => StatusCode::NOT_FOUND.into_response(), 151 | Ok(Some(directory)) => Json(directory).into_response(), 152 | Err(error) => (StatusCode::INTERNAL_SERVER_ERROR, error.to_string()).into_response(), 153 | } 154 | } 155 | 156 | /// Read crate root directory. 157 | #[cfg_attr(feature = "utoipa", 158 | utoipa::path(get, path = "/api/directory/{crate}/{version}", responses( 159 | (status = 200, description = "Read crate root directory successfully.", body = Directory), 160 | (status = 404, description = "The root directory does not exist."), 161 | (status = 500, description = "Internal server error."), 162 | ), 163 | params( 164 | ("crate" = String, Path, description = "The exact name of the crate."), 165 | ("version" = String, Path, description = "The semantic version number of the crate, following the Semantic versioning specification."), 166 | ), 167 | security( 168 | ("api_auth" = []) 169 | ) 170 | ))] 171 | pub async fn read_crate_root_directory( 172 | Path(crate_version): Path, 173 | State(state): State, 174 | ) -> impl IntoResponse { 175 | match state 176 | .read_directory(CrateVersionPath { 177 | crate_version, 178 | path: "".into(), 179 | }) 180 | .await 181 | { 182 | Ok(None) => StatusCode::NOT_FOUND.into_response(), 183 | Ok(Some(directory)) => Json(directory).into_response(), 184 | Err(error) => (StatusCode::INTERNAL_SERVER_ERROR, error.to_string()).into_response(), 185 | } 186 | } 187 | 188 | /// Read the root directory of a GitHub repository. 189 | /// 190 | /// This endpoint provides access to the contents of the root directory within a GitHub repository, 191 | /// 192 | #[cfg_attr(feature = "utoipa", 193 | utoipa::path(get, path = "/api/github/directory/{owner}/{repo}", responses( 194 | (status = 200, description = "Read repository root directory successfully.", body = Directory), 195 | (status = 404, description = "The root directory does not exist."), 196 | (status = 500, description = "Internal server error."), 197 | ), 198 | params( 199 | ("owner" = String, Path, description = "The owner of the GitHub repository."), 200 | ("repo" = String, Path, description = "The name of the GitHub repository."), 201 | ("branch" = Option, Query, description = "The branch name."), 202 | ), 203 | security( 204 | ("api_auth" = []) 205 | ) 206 | ))] 207 | pub async fn read_github_repository_root_directory( 208 | Path(repository): Path, 209 | Query(branch): Query, 210 | State(state): State, 211 | ) -> impl IntoResponse { 212 | match state 213 | .read_github_repository_directory(&repository, "", branch.as_str()) 214 | .await 215 | { 216 | Ok(None) => StatusCode::NOT_FOUND.into_response(), 217 | Ok(Some(directory)) => Json(directory).into_response(), 218 | Err(error) => (StatusCode::INTERNAL_SERVER_ERROR, error.to_string()).into_response(), 219 | } 220 | } 221 | 222 | /// Read a subdirectory in a GitHub repository. 223 | /// 224 | /// This endpoint provides access to the contents of a subdirectory within a GitHub repository, 225 | /// including files and other subdirectories. 226 | #[cfg_attr(feature = "utoipa", 227 | utoipa::path(get, path = "/api/github/directory/{owner}/{repo}/{path}", responses( 228 | (status = 200, description = "Read the subdirectory successfully.", body = Directory), 229 | (status = 404, description = "The directory does not exist."), 230 | (status = 500, description = "Internal server error.", body = String), 231 | ), 232 | params( 233 | ("owner" = String, Path, description = "The owner of the GitHub repository."), 234 | ("repo" = String, Path, description = "The name of the GitHub repository."), 235 | ("path" = String, Path, description = "Relative path of a directory in repository."), 236 | ("branch" = Option, Query, description = "The branch name."), 237 | ), 238 | security( 239 | ("api_auth" = []) 240 | ) 241 | ))] 242 | pub async fn read_github_repository_directory( 243 | Path(repository_path): Path, 244 | Query(branch): Query, 245 | State(state): State, 246 | ) -> impl IntoResponse { 247 | match state 248 | .read_github_repository_directory( 249 | &repository_path.repo, 250 | repository_path.path.as_ref(), 251 | branch.as_str(), 252 | ) 253 | .await 254 | { 255 | Ok(None) => StatusCode::NOT_FOUND.into_response(), 256 | Ok(Some(directory)) => Json(directory).into_response(), 257 | Err(error) => (StatusCode::INTERNAL_SERVER_ERROR, error.to_string()).into_response(), 258 | } 259 | } 260 | 261 | /// Read the content of a file in a GitHub repository. 262 | /// 263 | /// This function serves an endpoint to retrieve the content of a specific file from a GitHub repository. 264 | /// 265 | #[cfg_attr(feature = "utoipa", 266 | utoipa::path(get, path = "/api/github/file/{owner}/{repo}/{path}", responses( 267 | (status = 200, description = "Read the file successfully.", body = String), 268 | (status = 404, description = "The file does not exist."), 269 | (status = 500, description = "Internal server error.", body = String), 270 | ), 271 | params( 272 | ("owner" = String, Path, description = "The owner of the GitHub repository."), 273 | ("repo" = String, Path, description = "The name of the GitHub repository."), 274 | ("path" = String, Path, description = "Relative path of a file in repository."), 275 | ("branch" = Option, Query, description = "The branch name."), 276 | ), 277 | security( 278 | ("api_auth" = []) 279 | ) 280 | ))] 281 | pub async fn read_github_repository_file_content( 282 | Path(repository_path): Path, 283 | Query(branch): Query, 284 | State(state): State, 285 | ) -> impl IntoResponse { 286 | match state 287 | .read_github_repository_file( 288 | &repository_path.repo, 289 | repository_path.path.as_ref(), 290 | branch.as_str(), 291 | ) 292 | .await 293 | { 294 | Ok(None) => StatusCode::NOT_FOUND.into_response(), 295 | Ok(Some(file)) => file.into_response(), 296 | Err(error) => (StatusCode::INTERNAL_SERVER_ERROR, error.to_string()).into_response(), 297 | } 298 | } 299 | 300 | /// Search for issues in a GitHub repository. 301 | /// 302 | #[cfg_attr(feature = "utoipa", 303 | utoipa::path(get, path = "/api/github/issue/{owner}/{repo}", responses( 304 | (status = 200, description = "Get issue list successfully.", body = [Issue]), 305 | (status = 500, description = "Internal server error.", body = String), 306 | ), 307 | params( 308 | ("owner" = String, Path, description = "The owner of the GitHub repository."), 309 | ("repo" = String, Path, description = "The name of the GitHub repository."), 310 | ("query" = String, Query, description = "Query string."), 311 | ), 312 | security( 313 | ("api_auth" = []) 314 | ) 315 | ))] 316 | pub async fn search_github_repository_for_issues( 317 | Path(repository): Path, 318 | Query(query): Query, 319 | State(state): State, 320 | ) -> impl IntoResponse { 321 | match state 322 | .search_github_repository_for_issues(&repository, query.as_ref()) 323 | .await 324 | { 325 | Ok(issues) => Json(issues).into_response(), 326 | Err(error) => (StatusCode::INTERNAL_SERVER_ERROR, error.to_string()).into_response(), 327 | } 328 | } 329 | 330 | /// Get the timeline of an issue in a GitHub repository. 331 | #[cfg_attr(feature = "utoipa", 332 | utoipa::path(get, path = "/api/github/issue/{owner}/{repo}/{number}", responses( 333 | (status = 200, description = "Get issue timeline successfully.", body = [IssueEvent]), 334 | (status = 500, description = "Internal server error.", body = String), 335 | ), 336 | params( 337 | ("owner" = String, Path, description = "The owner of the GitHub repository."), 338 | ("repo" = String, Path, description = "The name of the GitHub repository."), 339 | ("number" = u64, Path, description = "The issue number."), 340 | ), 341 | security( 342 | ("api_auth" = []) 343 | ) 344 | ))] 345 | pub async fn get_github_repository_issue_timeline( 346 | Path(repository_issue): Path, 347 | State(state): State, 348 | ) -> impl IntoResponse { 349 | match state 350 | .get_github_repository_issue_timeline(&repository_issue.repo, repository_issue.number) 351 | .await 352 | { 353 | Ok(timeline) => Json(timeline).into_response(), 354 | Err(error) => (StatusCode::INTERNAL_SERVER_ERROR, error.to_string()).into_response(), 355 | } 356 | } 357 | 358 | /// Get the branches of a GitHub repository. 359 | #[cfg_attr(feature = "utoipa", 360 | utoipa::path(get, path = "/api/github/branches/{owner}/{repo}", responses( 361 | (status = 200, description = "Get repository branches successfully.", body = [String]), 362 | (status = 500, description = "Internal server error.", body = String), 363 | ), 364 | params( 365 | ("owner" = String, Path, description = "The owner of the GitHub repository."), 366 | ("repo" = String, Path, description = "The name of the GitHub repository."), 367 | ), 368 | security( 369 | ("api_auth" = []) 370 | ) 371 | ))] 372 | pub async fn get_github_repository_branches( 373 | Path(repository): Path, 374 | State(state): State, 375 | ) -> impl IntoResponse { 376 | match state.get_github_repository_branches(&repository).await { 377 | Ok(branches) => Json(branches).into_response(), 378 | Err(error) => (StatusCode::INTERNAL_SERVER_ERROR, error.to_string()).into_response(), 379 | } 380 | } 381 | 382 | /// Health check endpoint. 383 | /// 384 | /// This endpoint is used to perform a health check of the API, ensuring that it is running and responsive. 385 | /// 386 | pub async fn health() {} 387 | 388 | /// Redirect the client to "https://rustassistant.com". 389 | /// 390 | pub async fn redirect() -> impl IntoResponse { 391 | Redirect::to("https://rustassistant.com") 392 | } 393 | 394 | /// Privacy policy endpoint. 395 | /// 396 | /// This endpoint provides access to the privacy policy of the Rust Assistant application. 397 | /// 398 | pub async fn privacy_policy() -> impl IntoResponse { 399 | include_str!("../../../doc/privacy-policy.md") 400 | } 401 | 402 | /// Configures and returns the axum router for the API. 403 | /// 404 | /// This function sets up the routing for the API, including all the endpoints for searching crates, 405 | /// reading file contents, and accessing directory information. It also configures any necessary middleware. 406 | /// 407 | pub fn router( 408 | auth_info: impl Into>, 409 | github_token: &str, 410 | ) -> anyhow::Result { 411 | let main = Router::new() 412 | .route("/", get(redirect)) 413 | .route("/health", get(health)) 414 | .route("/privacy-policy", get(privacy_policy)); 415 | 416 | #[cfg(feature = "utoipa")] 417 | let main = { 418 | use utoipa::OpenApi; 419 | main.merge( 420 | utoipa_swagger_ui::SwaggerUi::new("/swagger-ui") 421 | .url("/api-docs/openapi.json", swagger_ui::ApiDoc::openapi()), 422 | ) 423 | }; 424 | 425 | let api = Router::new() 426 | .route("/lines/{crate}/{version}", get(search_crate_for_lines)) 427 | .route("/items/{crate}/{version}", get(search_crate_for_items)) 428 | .route("/file/{crate}/{version}/{*path}", get(get_file_content)) 429 | .nest( 430 | "/directory/{crate}/{version}", 431 | Router::new() 432 | .route("/", get(read_crate_root_directory)) 433 | .route("/{*path}", get(read_crate_directory)), 434 | ) 435 | .nest( 436 | "/github", 437 | Router::new() 438 | .nest( 439 | "/directory/{owner}/{repo}", 440 | Router::new() 441 | .route("/", get(read_github_repository_root_directory)) 442 | .route("/{*path}", get(read_github_repository_directory)), 443 | ) 444 | .route( 445 | "/file/{owner}/{repo}/{*path}", 446 | get(read_github_repository_file_content), 447 | ) 448 | .nest( 449 | "/issue/{owner}/{repo}", 450 | Router::new() 451 | .route("/", get(search_github_repository_for_issues)) 452 | .route("/{number}", get(get_github_repository_issue_timeline)), 453 | ) 454 | .route( 455 | "/branches/{owner}/{repo}", 456 | get(get_github_repository_branches), 457 | ), 458 | ) 459 | .with_state(RustAssistant::from(( 460 | CrateDownloader::default(), 461 | CrateCache::default(), 462 | GithubClient::new(github_token, None)?, 463 | ))); 464 | 465 | let api = if let Some(auth_info) = auth_info.into() { 466 | api.layer(axum::middleware::from_extractor::()) 467 | .layer(Extension(auth_info)) 468 | } else { 469 | api 470 | }; 471 | 472 | Ok(main.nest("/api", api)) 473 | } 474 | 475 | impl IntoResponse for FileContent { 476 | fn into_response(self) -> Response { 477 | let content_type = match self.data_type { 478 | FileDataType::Utf8 => "text/plain; charset=utf-8", 479 | FileDataType::NonUtf8 => "application/octet-stream", 480 | }; 481 | 482 | let mut headers = HeaderMap::new(); 483 | headers.insert( 484 | axum::http::header::CONTENT_TYPE, 485 | HeaderValue::from_static(content_type), 486 | ); 487 | (headers, self.data).into_response() 488 | } 489 | } 490 | 491 | /// Authentication information structure. 492 | /// 493 | /// This struct holds authentication credentials, such as username and password, used for API access. 494 | /// 495 | #[derive(Debug, Clone, Deserialize, Serialize)] 496 | pub struct AuthInfo { 497 | /// Username for authentication. 498 | pub username: Arc, 499 | /// Password for authentication. 500 | pub password: Arc, 501 | } 502 | 503 | impl AuthInfo { 504 | /// Validates the provided basic authentication against the stored credentials. 505 | /// 506 | pub fn check(&self, basic: &Basic) -> bool { 507 | self.username.as_ref().eq(basic.username()) && self.password.as_ref().eq(basic.password()) 508 | } 509 | } 510 | 511 | impl From<(U, P)> for AuthInfo 512 | where 513 | U: AsRef, 514 | P: AsRef, 515 | { 516 | fn from((u, p): (U, P)) -> Self { 517 | Self { 518 | username: Arc::from(u.as_ref()), 519 | password: Arc::from(p.as_ref()), 520 | } 521 | } 522 | } 523 | 524 | /// Middleware for API authentication. 525 | /// 526 | /// This struct is used as a middleware in Axum routes to require authentication 527 | /// for accessing certain endpoints. 528 | /// 529 | pub struct RequireAuth; 530 | 531 | impl FromRequestParts<()> for RequireAuth { 532 | type Rejection = Response; 533 | 534 | async fn from_request_parts(parts: &mut Parts, state: &()) -> Result { 535 | let TypedHeader(Authorization(basic)) = 536 | TypedHeader::>::from_request_parts(parts, state) 537 | .await 538 | .map_err(IntoResponse::into_response)?; 539 | let auth_info = Extension::::from_request_parts(parts, state) 540 | .await 541 | .map_err(IntoResponse::into_response)?; 542 | if auth_info.check(&basic) { 543 | Ok(RequireAuth) 544 | } else { 545 | Err(StatusCode::UNAUTHORIZED.into_response()) 546 | } 547 | } 548 | } 549 | 550 | #[cfg(feature = "utoipa")] 551 | mod swagger_ui { 552 | use utoipa::openapi::security::{Http, HttpAuthScheme, SecurityScheme}; 553 | 554 | #[derive(utoipa::OpenApi)] 555 | #[openapi( 556 | info( 557 | title = "Rust Assistant API", 558 | description = "API that supports source code browsing of crates on crates.io for Rust Assistant." 559 | ), 560 | paths( 561 | super::get_file_content, 562 | super::read_crate_directory, 563 | super::read_crate_root_directory, 564 | super::search_crate_for_items, 565 | super::search_crate_for_lines, 566 | super::read_github_repository_root_directory, 567 | super::read_github_repository_directory, 568 | super::read_github_repository_file_content, 569 | super::search_github_repository_for_issues, 570 | super::get_github_repository_issue_timeline, 571 | super::get_github_repository_branches, 572 | ), 573 | components( 574 | schemas(crate::Directory, crate::Item, crate::ItemType, crate::SearchMode, crate::Line, crate::RangeSchema, crate::Actor, crate::Author, crate::Issue, crate::IssueEvent) 575 | ), 576 | modifiers(&SecurityAddon), 577 | tags( 578 | (name = "Rust Assistant", description = "Rust Assistant API") 579 | ) 580 | )] 581 | pub struct ApiDoc; 582 | 583 | struct SecurityAddon; 584 | 585 | impl utoipa::Modify for SecurityAddon { 586 | fn modify(&self, openapi: &mut utoipa::openapi::OpenApi) { 587 | if let Some(components) = openapi.components.as_mut() { 588 | components.add_security_scheme( 589 | "api_auth", 590 | SecurityScheme::Http(Http::new(HttpAuthScheme::Basic)), 591 | ) 592 | } 593 | } 594 | } 595 | } 596 | -------------------------------------------------------------------------------- /crates/rust-assistant/src/cache.rs: -------------------------------------------------------------------------------- 1 | //! The `cache` module. 2 | //! 3 | //! This module provides caching functionalities to optimize performance and reduce 4 | //! redundant operations, particularly in the context of downloading and storing crate data. 5 | //! It may include structures like `CrateCache` to store downloaded crates and their metadata 6 | //! for quick retrieval. 7 | //! 8 | use crate::search::{SearchIndex, SearchIndexBuilder}; 9 | use crate::{ 10 | CrateVersion, Directory, DirectoryMut, FileLineRange, Item, ItemQuery, Line, LineQuery, 11 | SearchMode, 12 | }; 13 | use bytes::{Bytes, BytesMut}; 14 | use fnv::FnvHashMap; 15 | use lru::LruCache; 16 | use parking_lot::Mutex; 17 | use regex::RegexBuilder; 18 | use std::collections::BTreeSet; 19 | use std::io::{BufRead, Cursor, Read}; 20 | use std::num::NonZeroUsize; 21 | use std::ops::{Bound, Range, RangeBounds}; 22 | use std::path::{Path, PathBuf}; 23 | use std::sync::Arc; 24 | use tar::EntryType; 25 | 26 | /// Represents a tarball of a crate, including version information and tar data. 27 | #[derive(Clone)] 28 | pub struct CrateTar { 29 | pub crate_version: CrateVersion, 30 | pub tar_data: Vec, 31 | } 32 | 33 | impl From<(C, D)> for CrateTar 34 | where 35 | C: Into, 36 | D: Into>, 37 | { 38 | fn from((c, d): (C, D)) -> Self { 39 | CrateTar { 40 | crate_version: c.into(), 41 | tar_data: d.into(), 42 | } 43 | } 44 | } 45 | 46 | impl CrateTar { 47 | /// Retrieves the content of a specified file within the crate tarball. 48 | /// 49 | pub fn get_file(&self, file: &str) -> anyhow::Result> { 50 | let mut archive = tar::Archive::new(self.tar_data.as_slice()); 51 | let entries = archive.entries()?; 52 | for entry in entries { 53 | let Ok(mut entry) = entry else { 54 | continue; 55 | }; 56 | 57 | let Ok(path) = entry.path() else { 58 | continue; 59 | }; 60 | 61 | if self.crate_version.root_dir().join(file).eq(path.as_ref()) { 62 | let mut content = String::with_capacity(entry.size() as usize); 63 | entry.read_to_string(&mut content)?; 64 | return Ok(Some(content)); 65 | } 66 | } 67 | 68 | Ok(None) 69 | } 70 | 71 | /// Retrieves the content of a specified file within a range. 72 | /// 73 | pub fn get_file_by_range( 74 | &self, 75 | file: &str, 76 | start: impl Into>, 77 | end: impl Into>, 78 | ) -> anyhow::Result> { 79 | let mut archive = tar::Archive::new(self.tar_data.as_slice()); 80 | let entries = archive.entries()?; 81 | for entry in entries { 82 | let Ok(mut entry) = entry else { 83 | continue; 84 | }; 85 | 86 | let Ok(path) = entry.path() else { 87 | continue; 88 | }; 89 | 90 | if self.crate_version.root_dir().join(file).eq(path.as_ref()) { 91 | let mut content = String::with_capacity(entry.size() as usize); 92 | entry.read_to_string(&mut content)?; 93 | let lines: Vec<&str> = content.lines().collect(); 94 | 95 | let start = start.into(); 96 | let end = end.into(); 97 | 98 | let start_line = start.map_or(0, |n| n.get() - 1); 99 | let end_line = end.map_or(lines.len(), |n| n.get()); 100 | 101 | if start_line > lines.len() { 102 | return Ok(Some(String::new())); 103 | } 104 | 105 | return Ok(Some( 106 | lines[start_line..end_line.min(lines.len())].join("\n"), 107 | )); 108 | } 109 | } 110 | 111 | Ok(None) 112 | } 113 | 114 | /// Lists all files in the crate within a specified range. 115 | /// 116 | pub fn get_all_file_list( 117 | &self, 118 | range: impl RangeBounds, 119 | ) -> anyhow::Result>> { 120 | let mut archive = tar::Archive::new(self.tar_data.as_slice()); 121 | let root_dir = self.crate_version.root_dir(); 122 | let entries = archive.entries()?; 123 | let mut list = BTreeSet::default(); 124 | for (i, entry) in entries.enumerate() { 125 | if !range.contains(&i) { 126 | continue; 127 | } 128 | let Ok(entry) = entry else { 129 | continue; 130 | }; 131 | 132 | let Ok(path) = entry.path() else { 133 | continue; 134 | }; 135 | 136 | let Ok(path) = path.strip_prefix(&root_dir) else { 137 | continue; 138 | }; 139 | list.insert(path.to_path_buf()); 140 | } 141 | Ok(Some(list)) 142 | } 143 | 144 | /// Reads the contents of a directory within the crate. 145 | /// 146 | pub fn read_directory>(&self, path: P) -> anyhow::Result> { 147 | let mut archive = tar::Archive::new(self.tar_data.as_slice()); 148 | let base_dir = self.crate_version.root_dir().join(path); 149 | let entries = archive.entries()?; 150 | let mut dir = DirectoryMut::default(); 151 | for entry in entries { 152 | let Ok(entry) = entry else { 153 | continue; 154 | }; 155 | 156 | let Ok(path) = entry.path() else { 157 | continue; 158 | }; 159 | 160 | let Ok(path) = path.strip_prefix(&base_dir) else { 161 | continue; 162 | }; 163 | 164 | let mut components = path.components(); 165 | if let Some(path) = components 166 | .next() 167 | .map(|comp| PathBuf::from(comp.as_os_str())) 168 | { 169 | if components.next().is_none() { 170 | dir.files.insert(path.to_path_buf()); 171 | } else { 172 | dir.directories.insert(path.to_path_buf()); 173 | } 174 | } 175 | } 176 | 177 | Ok(Some(dir.freeze())) 178 | } 179 | } 180 | 181 | /// Enumerates the possible data formats of a crate file. 182 | /// 183 | /// This enum helps in distinguishing between different text encoding formats of the files contained in a crate. 184 | #[derive(Debug, Default, Copy, Clone, Ord, PartialOrd, Eq, PartialEq, Hash)] 185 | pub enum FileDataType { 186 | /// Represents a UTF-8 formatted file. 187 | Utf8, 188 | /// Represents a non-UTF-8 formatted file. 189 | #[default] 190 | NonUtf8, 191 | } 192 | 193 | /// Describes a crate file with its data type and range in the crate's data buffer. 194 | /// 195 | /// This struct is used to quickly access the file's content and its encoding format. 196 | /// 197 | #[derive(Debug, Clone, Default, PartialEq, Eq, Hash)] 198 | pub struct CrateFileDataDesc { 199 | /// The data type of the file (UTF-8 or Non-UTF-8). 200 | pub data_type: FileDataType, 201 | /// The byte range of the file content within the crate's data buffer. 202 | pub range: Range, 203 | } 204 | 205 | /// Contains the actual content of a file within a crate. 206 | /// 207 | /// This struct holds the file data and its data type, which is useful for encoding-specific operations. 208 | #[derive(Debug, Clone)] 209 | pub struct FileContent { 210 | /// The data type of the file. 211 | pub data_type: FileDataType, 212 | /// The byte content of the file. 213 | pub data: Bytes, 214 | } 215 | 216 | impl From for FileContent { 217 | fn from(data: Bytes) -> Self { 218 | FileContent { 219 | data_type: if std::str::from_utf8(data.as_ref()).is_ok() { 220 | FileDataType::Utf8 221 | } else { 222 | FileDataType::NonUtf8 223 | }, 224 | data, 225 | } 226 | } 227 | } 228 | 229 | /// Represents a crate with its data and indexes for quick access to its contents. 230 | /// 231 | /// This struct stores the complete data of a crate and provides indexes for accessing individual files, 232 | /// directories, and search functionalities within the crate. 233 | /// 234 | #[derive(Debug, Clone)] 235 | pub struct Crate { 236 | data: Bytes, 237 | files_index: Arc>, 238 | directories_index: Arc>, 239 | item_search_index: SearchIndex, 240 | } 241 | 242 | impl Crate { 243 | /// Retrieves the content of a file by specifying a line range. 244 | /// 245 | pub fn get_file_by_file_line_range>( 246 | &self, 247 | file: P, 248 | FileLineRange { start, end }: FileLineRange, 249 | ) -> anyhow::Result> { 250 | match (start, end) { 251 | (Some(start), Some(end)) => self.get_file_by_line_range(file, start..=end), 252 | (Some(start), None) => self.get_file_by_line_range(file, start..), 253 | (None, Some(end)) => self.get_file_by_line_range(file, ..=end), 254 | (None, None) => self.get_file_by_line_range(file, ..), 255 | } 256 | } 257 | 258 | /// Retrieves the content of a file by specifying a line range. 259 | /// 260 | /// This method is used to extract a specific range of lines from a file in the crate. 261 | /// 262 | pub fn get_file_by_line_range>( 263 | &self, 264 | file: P, 265 | line_range: impl RangeBounds, 266 | ) -> anyhow::Result> { 267 | let file = file.as_ref(); 268 | let Some(CrateFileDataDesc { range, data_type }) = self.files_index.get(file) else { 269 | return Ok(None); 270 | }; 271 | 272 | let data = self.data.slice(range.clone()); 273 | 274 | if matches!( 275 | (line_range.start_bound(), line_range.end_bound()), 276 | (Bound::Unbounded, Bound::Unbounded) 277 | ) { 278 | return Ok(Some(FileContent { 279 | data, 280 | data_type: *data_type, 281 | })); 282 | } 283 | 284 | if let FileDataType::NonUtf8 = data_type { 285 | anyhow::bail!("Non-UTF8 formatted files do not support line-range querying."); 286 | } 287 | 288 | let s = std::str::from_utf8(data.as_ref())?; 289 | let start_line = match line_range.start_bound() { 290 | Bound::Included(n) => n.get() - 1, 291 | Bound::Excluded(n) => n.get(), 292 | Bound::Unbounded => 0, 293 | }; 294 | let end_line = match line_range.end_bound() { 295 | Bound::Included(n) => n.get(), 296 | Bound::Excluded(n) => n.get() - 1, 297 | Bound::Unbounded => usize::MAX, 298 | }; 299 | 300 | let mut line_start = 0; 301 | let mut line_end = s.len(); 302 | let mut current_line = 0; 303 | 304 | // 定位起始行的开始 305 | for _ in 0..start_line { 306 | if let Some(pos) = s[line_start..].find('\n') { 307 | line_start += pos + 1; 308 | current_line += 1; 309 | } else { 310 | // 找不到更多的行 311 | break; 312 | } 313 | } 314 | 315 | // 定位结束行的结束 316 | if current_line < end_line { 317 | line_end = line_start; 318 | for _ in current_line..end_line { 319 | if let Some(pos) = s[line_end..].find('\n') { 320 | line_end += pos + 1; 321 | } else { 322 | break; 323 | } 324 | } 325 | } 326 | 327 | if line_start < line_end { 328 | let line_bytes_range = range.start + line_start..range.start + line_end; 329 | return Ok(Some(FileContent { 330 | data_type: FileDataType::Utf8, 331 | data: self.data.slice(line_bytes_range), 332 | })); 333 | } 334 | 335 | Ok(None) 336 | } 337 | 338 | /// Reads the content of a specified directory within the crate. 339 | /// 340 | pub fn read_directory>(&self, path: P) -> Option<&Directory> { 341 | self.directories_index.get(path.as_ref()) 342 | } 343 | 344 | /// Searches for items in the crate based on a given query. 345 | /// 346 | pub fn search_item(&self, query: &ItemQuery) -> Vec { 347 | self.item_search_index.search(query) 348 | } 349 | 350 | /// Searches for lines in the crate's files based on a given query. 351 | /// 352 | pub fn search_line(&self, query: &LineQuery) -> anyhow::Result> { 353 | let mut results = Vec::new(); 354 | let file_ext = query 355 | .file_ext 356 | .split(",") 357 | .map(|s| s.trim()) 358 | .filter(|s| !s.is_empty()) 359 | .collect::>(); 360 | 361 | let mut regex_pattern = match query.mode { 362 | SearchMode::PlainText => regex::escape(&query.query), 363 | SearchMode::Regex => query.query.clone(), 364 | }; 365 | 366 | // 如果需要全字匹配,则对模式进行相应包装 367 | if query.whole_word { 368 | regex_pattern = format!(r"\b{}\b", regex_pattern); 369 | } 370 | 371 | // 创建正则表达式,考虑大小写敏感设置 372 | let pattern = RegexBuilder::new(®ex_pattern) 373 | .case_insensitive(!query.case_sensitive) 374 | .build()?; 375 | 376 | for (path, file_desc) in self.files_index.iter() { 377 | if let Some(query_path) = &query.path { 378 | if !path.starts_with(query_path) { 379 | continue; 380 | } 381 | }; 382 | if !file_ext.is_empty() { 383 | if let Some(extension) = path.extension() { 384 | if !file_ext 385 | .iter() 386 | .any(|ext| extension.eq_ignore_ascii_case(ext)) 387 | { 388 | continue; 389 | } 390 | } else { 391 | // 如果路径没有扩展名,则跳过 392 | continue; 393 | } 394 | } 395 | 396 | let content_range = file_desc.range.clone(); 397 | let content = &self.data.slice(content_range); 398 | 399 | let cursor = Cursor::new(content); 400 | 401 | for (line_number, line) in cursor.lines().enumerate() { 402 | let line = line?; 403 | let Some(line_number) = NonZeroUsize::new(line_number + 1) else { 404 | continue; 405 | }; 406 | 407 | // 使用 pattern 对每一行进行匹配 408 | if let Some(mat) = pattern.find(&line) { 409 | let column_range = NonZeroUsize::new(mat.start() + 1).unwrap() 410 | ..NonZeroUsize::new(mat.end() + 1).unwrap(); 411 | 412 | let line_result = Line { 413 | line, 414 | file: path.clone(), 415 | line_number, 416 | column_range, 417 | }; 418 | results.push(line_result); 419 | 420 | if let Some(max_results) = query.max_results { 421 | if results.len() >= max_results.get() { 422 | break; 423 | } 424 | } 425 | } 426 | } 427 | 428 | if let Some(max_results) = query.max_results { 429 | if results.len() >= max_results.get() { 430 | break; 431 | } 432 | } 433 | } 434 | 435 | Ok(results) 436 | } 437 | } 438 | 439 | impl TryFrom for Crate { 440 | type Error = std::io::Error; 441 | fn try_from(crate_tar: CrateTar) -> std::io::Result { 442 | let mut archive = tar::Archive::new(crate_tar.tar_data.as_slice()); 443 | let root_dir = crate_tar.crate_version.root_dir(); 444 | 445 | let mut data = BytesMut::new(); 446 | let mut files_index = FnvHashMap::default(); 447 | let mut directories_index = FnvHashMap::default(); 448 | let mut search_index_builder = SearchIndexBuilder::default(); 449 | 450 | let mut buffer = Vec::new(); 451 | let entries = archive.entries()?; 452 | for entry in entries { 453 | let Ok(mut entry) = entry else { 454 | continue; 455 | }; 456 | 457 | let Ok(path) = entry.path() else { 458 | continue; 459 | }; 460 | 461 | let Ok(path) = path.strip_prefix(&root_dir) else { 462 | continue; 463 | }; 464 | 465 | let Some(last) = path.components().last() else { 466 | continue; 467 | }; 468 | 469 | let filename = PathBuf::from(last.as_os_str()); 470 | let is_rust_src = 471 | matches!(filename.extension(), Some(ext) if ext.eq_ignore_ascii_case("rs")); 472 | 473 | let path = path.to_path_buf(); 474 | if let EntryType::Regular = entry.header().entry_type() { 475 | buffer.clear(); 476 | entry.read_to_end(&mut buffer)?; 477 | 478 | let data_type = match std::str::from_utf8(&buffer) { 479 | Ok(utf8_src) => { 480 | if is_rust_src { 481 | search_index_builder.update(path.as_path(), utf8_src); 482 | } 483 | FileDataType::Utf8 484 | } 485 | Err(_) => FileDataType::NonUtf8, 486 | }; 487 | 488 | let range = data.len()..data.len() + buffer.len(); 489 | 490 | data.extend_from_slice(buffer.as_slice()); 491 | files_index.insert(path.clone(), CrateFileDataDesc { data_type, range }); 492 | let parent = path.parent().map(|p| p.to_path_buf()).unwrap_or_default(); 493 | directories_index 494 | .entry(parent) 495 | .and_modify(|o: &mut DirectoryMut| { 496 | o.files.insert(filename.clone()); 497 | }) 498 | .or_insert({ 499 | let mut set = BTreeSet::default(); 500 | set.insert(filename); 501 | DirectoryMut { 502 | files: set, 503 | directories: Default::default(), 504 | } 505 | }); 506 | } 507 | } 508 | 509 | let mut subdirectories_index = FnvHashMap::default(); 510 | for key in directories_index.keys() { 511 | let Some(last) = key.components().last() else { 512 | continue; 513 | }; 514 | 515 | let sub_dir_name = PathBuf::from(last.as_os_str()); 516 | let parent = key.parent().map(|p| p.to_path_buf()).unwrap_or_default(); 517 | subdirectories_index 518 | .entry(parent) 519 | .and_modify(|s: &mut BTreeSet| { 520 | s.insert(sub_dir_name.clone()); 521 | }) 522 | .or_insert({ 523 | let mut set = BTreeSet::default(); 524 | set.insert(sub_dir_name); 525 | set 526 | }); 527 | } 528 | 529 | for (k, directories) in subdirectories_index { 530 | directories_index 531 | .entry(k) 532 | .and_modify(|directory: &mut DirectoryMut| { 533 | directory.directories = directories.clone(); 534 | }) 535 | .or_insert(DirectoryMut { 536 | files: Default::default(), 537 | directories, 538 | }); 539 | } 540 | 541 | let directories_index = directories_index 542 | .into_iter() 543 | .map(|(k, v)| (k, v.freeze())) 544 | .collect(); 545 | 546 | Ok(Self { 547 | data: data.freeze(), 548 | files_index: Arc::new(files_index), 549 | directories_index: Arc::new(directories_index), 550 | item_search_index: search_index_builder.finish(), 551 | }) 552 | } 553 | } 554 | 555 | /// A cache for storing and retrieving `Crate` instances to minimize redundant operations. 556 | /// 557 | /// This cache uses a least-recently-used (LRU) strategy and is thread-safe. 558 | #[derive(Clone)] 559 | pub struct CrateCache { 560 | lru: Arc>>, 561 | } 562 | 563 | impl Default for CrateCache { 564 | fn default() -> Self { 565 | Self::new(unsafe { NonZeroUsize::new_unchecked(2048) }) 566 | } 567 | } 568 | 569 | impl CrateCache { 570 | /// Creates a new `CrateCache` with a specified capacity. 571 | /// 572 | pub fn new(capacity: NonZeroUsize) -> Self { 573 | CrateCache { 574 | lru: Arc::new(Mutex::new(LruCache::with_hasher( 575 | capacity, 576 | fnv::FnvBuildHasher::default(), 577 | ))), 578 | } 579 | } 580 | 581 | /// Retrieves a crate from the cache if it exists. 582 | /// 583 | pub fn get_crate(&self, crate_version: &CrateVersion) -> Option { 584 | self.lru.lock().get(crate_version).cloned() 585 | } 586 | 587 | /// Inserts or updates a crate in the cache. 588 | /// 589 | pub fn set_crate( 590 | &self, 591 | crate_version: impl Into, 592 | krate: impl Into, 593 | ) -> Option { 594 | self.lru.lock().put(crate_version.into(), krate.into()) 595 | } 596 | } 597 | -------------------------------------------------------------------------------- /crates/rust-assistant/src/download.rs: -------------------------------------------------------------------------------- 1 | //! The `download` module. 2 | //! 3 | //! Responsible for downloading crates and their contents from sources like crates.io. 4 | //! This module likely includes structures like `CrateDownloader` which handle the intricacies 5 | //! of making network requests, handling responses, and processing the downloaded data. 6 | //! 7 | use crate::CrateVersion; 8 | use reqwest::{Client, ClientBuilder}; 9 | use std::io::Read; 10 | 11 | /// The `CrateDownloader` struct, responsible for downloading crate files from the internet. 12 | /// 13 | /// This struct uses the `reqwest` crate's `Client` to make HTTP requests for crate files. 14 | #[derive(Debug, Default, Clone)] 15 | pub struct CrateDownloader { 16 | client: Client, 17 | } 18 | 19 | impl From for CrateDownloader { 20 | /// Creates a `CrateDownloader` from a `reqwest::Client`. 21 | /// 22 | /// This allows for custom configuration of the HTTP client used for downloading. 23 | /// 24 | fn from(client: Client) -> Self { 25 | Self { client } 26 | } 27 | } 28 | 29 | impl TryFrom for CrateDownloader { 30 | type Error = reqwest::Error; 31 | 32 | /// Tries to create a `CrateDownloader` from a `reqwest::ClientBuilder`. 33 | /// 34 | /// This method attempts to build a `reqwest::Client` and returns a `CrateDownloader` if successful. 35 | /// 36 | fn try_from(value: ClientBuilder) -> Result { 37 | Ok(Self { 38 | client: value.build()?, 39 | }) 40 | } 41 | } 42 | 43 | impl CrateDownloader { 44 | /// Asynchronously downloads a crate file from crates.io. 45 | /// 46 | /// This method constructs the URL for the crate file based on the provided `CrateVersion` 47 | /// and uses the internal HTTP client to download it. 48 | /// 49 | pub async fn download_crate_file( 50 | &self, 51 | crate_version: &CrateVersion, 52 | ) -> anyhow::Result> { 53 | let url = format!( 54 | "https://static.crates.io/crates/{}/{}-{}.crate", 55 | crate_version.krate, crate_version.krate, crate_version.version 56 | ); 57 | 58 | let resp = self.client.get(url).send().await?; 59 | 60 | if !resp.status().is_success() { 61 | anyhow::bail!("Http status is not 200: {}", resp.text().await?); 62 | } 63 | 64 | let compressed_data = resp.bytes().await?; 65 | 66 | let data = tokio::task::spawn_blocking(move || { 67 | let mut dc = flate2::bufread::GzDecoder::new(compressed_data.as_ref()); 68 | let mut tar_data = Vec::new(); 69 | dc.read_to_end(&mut tar_data)?; 70 | 71 | Ok::<_, anyhow::Error>(tar_data) 72 | }) 73 | .await??; 74 | 75 | Ok(data) 76 | } 77 | } 78 | -------------------------------------------------------------------------------- /crates/rust-assistant/src/github.rs: -------------------------------------------------------------------------------- 1 | use crate::cache::FileContent; 2 | use crate::{Directory, DirectoryMut}; 3 | use reqwest::header::HeaderMap; 4 | use reqwest::{Client, Proxy, StatusCode}; 5 | use serde::{Deserialize, Serialize}; 6 | use serde_json::json; 7 | use std::path::PathBuf; 8 | use std::sync::Arc; 9 | 10 | #[cfg(feature = "utoipa")] 11 | use utoipa::ToSchema; 12 | 13 | #[derive(Debug, Clone)] 14 | pub struct GithubClient { 15 | client: Client, 16 | } 17 | 18 | /// A struct representing a GitHub repository. 19 | #[derive(Debug, Clone, Serialize, Deserialize)] 20 | pub struct Repository { 21 | /// The owner of the repository. 22 | pub owner: Arc, 23 | /// The name of the repository. 24 | pub repo: Arc, 25 | } 26 | 27 | /// A struct representing a GitHub branch. 28 | #[derive(Debug, Serialize, Deserialize)] 29 | pub struct Branch { 30 | /// The name of the branch. 31 | pub branch: Option, 32 | } 33 | 34 | impl Branch { 35 | /// Returns the branch name as a string slice. 36 | /// 37 | pub fn as_str(&self) -> Option<&str> { 38 | self.branch.as_deref() 39 | } 40 | } 41 | 42 | /// A struct representing a GitHub repository and a path within it. 43 | #[derive(Debug, Clone, Serialize, Deserialize)] 44 | pub struct RepositoryPath { 45 | /// The repository. 46 | #[serde(flatten)] 47 | pub repo: Repository, 48 | /// The path. 49 | pub path: Arc, 50 | } 51 | 52 | /// A struct representing a GitHub repository and an issue number. 53 | #[derive(Debug, Clone, Serialize, Deserialize)] 54 | pub struct RepositoryIssue { 55 | /// The repository. 56 | #[serde(flatten)] 57 | pub repo: Repository, 58 | /// The path. 59 | pub number: u64, 60 | } 61 | 62 | /// The Query string for searching issues. 63 | #[derive(Debug, Clone, Serialize, Deserialize)] 64 | pub struct IssueQuery { 65 | /// The query string. 66 | pub query: String, 67 | } 68 | 69 | impl AsRef for IssueQuery { 70 | fn as_ref(&self) -> &str { 71 | self.query.as_str() 72 | } 73 | } 74 | 75 | impl From<(O, R)> for Repository 76 | where 77 | O: AsRef, 78 | R: AsRef, 79 | { 80 | fn from((owner, repo): (O, R)) -> Self { 81 | Self { 82 | owner: Arc::from(owner.as_ref()), 83 | repo: Arc::from(repo.as_ref()), 84 | } 85 | } 86 | } 87 | 88 | impl GithubClient { 89 | pub fn new(token: &str, proxy: impl Into>) -> anyhow::Result { 90 | let authorization = format!("token {token}"); 91 | let mut headers = HeaderMap::new(); 92 | headers.insert(reqwest::header::AUTHORIZATION, authorization.parse()?); 93 | headers.insert(reqwest::header::USER_AGENT, "Rust Assistant".parse()?); 94 | 95 | let mut builder = reqwest::ClientBuilder::default().default_headers(headers); 96 | if let Some(proxy) = proxy.into() { 97 | builder = builder.proxy(proxy); 98 | } 99 | 100 | Ok(Self { 101 | client: builder.build()?, 102 | }) 103 | } 104 | 105 | pub fn build_file_url(&self, repo: &Repository, path: &str) -> String { 106 | format!( 107 | "https://api.github.com/repos/{}/{}/contents/{path}", 108 | repo.owner, repo.repo 109 | ) 110 | } 111 | 112 | pub async fn get_file( 113 | &self, 114 | repo: &Repository, 115 | path: &str, 116 | branch: impl Into>, 117 | ) -> anyhow::Result> { 118 | let file_path = self.build_file_url(repo, path); 119 | let mut builder = self.client.get(file_path); 120 | if let Some(branch) = branch.into() { 121 | builder = builder.query(&[("ref", branch)]); 122 | } 123 | let resp = builder.send().await?; 124 | let status = resp.status(); 125 | if status == StatusCode::NOT_FOUND { 126 | return Ok(None); 127 | } 128 | if status != StatusCode::OK { 129 | anyhow::bail!( 130 | "The server returned a non-200 status code when fetching the file download URL ({status}): {}", 131 | resp.text().await? 132 | ); 133 | } 134 | 135 | let body = resp.json::().await?; 136 | if body.is_array() || body.get("type") != Some(&json!("file")) { 137 | anyhow::bail!("The path is not a regular file."); 138 | } 139 | let Some(download_url) = body.get("download_url").map(|u| u.as_str()).flatten() else { 140 | anyhow::bail!("Failed to get download url from response body: {body}"); 141 | }; 142 | 143 | let resp = self.client.get(download_url).send().await?; 144 | if !resp.status().is_success() { 145 | anyhow::bail!( 146 | "The server returned a non-200 status code when fetching file content ({status}): {}", 147 | resp.text().await? 148 | ); 149 | } 150 | let bytes = resp.bytes().await?; 151 | Ok(Some(crate::cache::FileContent::from(bytes))) 152 | } 153 | 154 | pub async fn read_dir( 155 | &self, 156 | repo: &Repository, 157 | path: &str, 158 | branch: impl Into>, 159 | ) -> anyhow::Result> { 160 | let file_path = self.build_file_url(repo, path); 161 | let mut builder = self.client.get(file_path); 162 | if let Some(branch) = branch.into() { 163 | builder = builder.query(&[("ref", branch)]); 164 | } 165 | let resp = builder.send().await?; 166 | let status = resp.status(); 167 | if status == StatusCode::NOT_FOUND { 168 | return Ok(None); 169 | } 170 | if status != StatusCode::OK { 171 | anyhow::bail!( 172 | "The server returned a non-200 status code when fetching the file download URL ({status}): {}", 173 | resp.text().await? 174 | ); 175 | } 176 | 177 | let items = resp.json::>().await?; 178 | let mut directories = DirectoryMut::default(); 179 | for item in items { 180 | match item.r#type.as_str() { 181 | "file" => { 182 | directories.files.insert(PathBuf::from(item.name)); 183 | } 184 | "dir" => { 185 | directories.directories.insert(PathBuf::from(item.name)); 186 | } 187 | _ => { 188 | continue; 189 | } 190 | } 191 | } 192 | Ok(Some(directories.freeze())) 193 | } 194 | 195 | /// Search for issues. 196 | /// 197 | /// # Arguments 198 | /// 199 | /// * `query` - The query string to search for. 200 | /// 201 | /// # Returns 202 | /// 203 | /// A vector of issues matching the query. 204 | /// 205 | pub async fn search_for_issues( 206 | &self, 207 | Repository { owner, repo }: &Repository, 208 | keyword: &str, 209 | ) -> anyhow::Result> { 210 | let url = format!("https://api.github.com/search/issues?q={keyword}+repo:{owner}/{repo}",); 211 | let resp = self.client.get(url).send().await?; 212 | let status = resp.status(); 213 | if status != StatusCode::OK { 214 | anyhow::bail!( 215 | "The server returned a non-200 status code when fetching the file download URL ({status}): {}", 216 | resp.text().await? 217 | ); 218 | } 219 | 220 | let body = resp.json::().await?; 221 | Ok(body.items) 222 | } 223 | 224 | /// Get the timeline of an issue. 225 | pub async fn get_issue_timeline( 226 | &self, 227 | Repository { owner, repo }: &Repository, 228 | issue_number: u64, 229 | ) -> anyhow::Result> { 230 | let url = format!( 231 | "https://api.github.com/repos/{owner}/{repo}/issues/{issue_number}/timeline", 232 | owner = owner, 233 | repo = repo, 234 | issue_number = issue_number 235 | ); 236 | let resp = self.client.get(url).send().await?; 237 | let status = resp.status(); 238 | if status != StatusCode::OK { 239 | anyhow::bail!( 240 | "The server returned a non-200 status code when fetching the file download URL ({status}): {}", 241 | resp.text().await? 242 | ); 243 | } 244 | 245 | let body = resp.json::>().await?; 246 | Ok(body) 247 | } 248 | 249 | /// Get the branches of a repository. 250 | pub async fn get_repo_branches( 251 | &self, 252 | Repository { owner, repo }: &Repository, 253 | ) -> anyhow::Result> { 254 | #[derive(Deserialize, Debug)] 255 | struct Branch { 256 | name: String, 257 | } 258 | 259 | let url = format!("https://api.github.com/repos/{owner}/{repo}/branches",); 260 | let resp = self.client.get(url).send().await?; 261 | let status = resp.status(); 262 | if status != StatusCode::OK { 263 | anyhow::bail!( 264 | "The server returned a non-200 status code when fetching the file download URL ({status}): {}", 265 | resp.text().await? 266 | ); 267 | } 268 | 269 | let body = resp.json::>().await?; 270 | Ok(body.into_iter().map(|b| b.name).collect()) 271 | } 272 | } 273 | 274 | #[derive(Deserialize, Serialize, Debug)] 275 | struct Item { 276 | r#type: String, 277 | name: String, 278 | } 279 | 280 | /// A struct representing a GitHub issue. 281 | #[derive(Serialize, Deserialize, Debug)] 282 | #[cfg_attr(feature = "utoipa", derive(ToSchema))] 283 | pub struct Issue { 284 | pub number: u64, 285 | pub title: String, 286 | pub url: String, 287 | pub state: String, 288 | pub body: Option, 289 | } 290 | 291 | /// A struct representing a response from a GitHub issue search. 292 | #[derive(Deserialize, Debug)] 293 | pub struct SearchIssuesResponse { 294 | pub items: Vec, 295 | } 296 | 297 | /// A struct representing a GitHub issue event. 298 | /// https://docs.github.com/en/rest/reference/issues#list-issue-events 299 | /// https://docs.github.com/en/rest/reference/issues#events 300 | /// 301 | #[derive(Serialize, Deserialize, Debug)] 302 | #[cfg_attr(feature = "utoipa", derive(ToSchema))] 303 | pub struct IssueEvent { 304 | /// The event type. 305 | pub event: String, 306 | /// The actor of the event. 307 | pub actor: Option, 308 | /// The author of the event. 309 | pub author: Option, 310 | /// The time the event was created. 311 | pub created_at: Option, 312 | /// The body of the event. 313 | pub body: Option, 314 | } 315 | 316 | /// A struct representing a GitHub actor. 317 | /// 318 | #[derive(Serialize, Deserialize, Debug)] 319 | #[cfg_attr(feature = "utoipa", derive(ToSchema))] 320 | pub struct Actor { 321 | pub login: String, 322 | pub avatar_url: String, 323 | } 324 | 325 | /// A struct representing a GitHub author. 326 | #[derive(Serialize, Deserialize, Debug)] 327 | #[cfg_attr(feature = "utoipa", derive(ToSchema))] 328 | pub struct Author { 329 | /// The author's email. 330 | pub email: String, 331 | /// The author's name. 332 | pub name: String, 333 | } 334 | // 335 | // #[cfg(test)] 336 | // mod tests { 337 | // use super::*; 338 | // 339 | // #[tokio::test] 340 | // async fn test_get_file() -> anyhow::Result<()> { 341 | // let token = dotenv::var("GITHUB_ACCESS_TOKEN")?; 342 | // let proxy = if tokio::net::TcpStream::connect("127.0.0.1:7890") 343 | // .await 344 | // .is_ok() 345 | // { 346 | // Some(Proxy::all("http://127.0.0.1:7890")?) 347 | // } else { 348 | // None 349 | // }; 350 | // let repo = Repository::from(("gengteng", "rust-assistant")); 351 | // // https://github.com/rust-lang/crates.io-index 352 | // let client = GithubClient::new(token.as_str(), proxy)?; 353 | // let content = client.get_file(&repo, "Cargo.toml", "fff").await?; 354 | // println!("content: {content:?}"); 355 | // 356 | // let dir = client.read_dir(&repo, "crates", None).await?; 357 | // println!("dir crates: {dir:#?}"); 358 | // 359 | // let issues = client.search_for_issues(&repo, "test").await?; 360 | // println!("issues: {issues:#?}"); 361 | // 362 | // for issue in issues { 363 | // let timeline = client.get_issue_timeline(&repo, issue.number).await?; 364 | // println!("timeline: {timeline:#?}"); 365 | // } 366 | // 367 | // let branches = client.get_repo_branches(&repo).await?; 368 | // println!("branches: {branches:#?}"); 369 | // Ok(()) 370 | // } 371 | // } 372 | -------------------------------------------------------------------------------- /crates/rust-assistant/src/lib.rs: -------------------------------------------------------------------------------- 1 | //! # Rust Assistant Library 2 | //! 3 | //! `rust_assistant` is a comprehensive library designed to enhance the Rust development experience, 4 | //! offering a suite of tools and functionalities for downloading, caching, searching, and analyzing Rust crates. 5 | //! 6 | //! This library encapsulates a range of modules, each specializing in different aspects of crate management 7 | //! and code analysis. It aims to streamline the process of working with Rust crates, providing developers 8 | //! with efficient access to crate data, advanced search capabilities, and more. 9 | //! 10 | //! ## Features 11 | //! 12 | //! - **Crate Downloading**: Facilitates the downloading of crates from sources like crates.io, 13 | //! handling network requests and data processing. 14 | //! 15 | //! - **Crate Caching**: Implements caching mechanisms to store downloaded crates, optimizing 16 | //! performance and reducing redundant operations. 17 | //! 18 | //! - **Search Functionality**: Provides advanced search functionalities within crate contents, 19 | //! including source code, documentation, and other relevant data. 20 | //! 21 | //! ## Modules 22 | //! 23 | //! - `app`: Contains the core application logic for the Rust Assistant. 24 | //! - `cache`: Provides caching functionalities for crates. 25 | //! - `download`: Handles the downloading of crates and their contents. 26 | //! - `search`: Implements search algorithms and data structures for efficient crate content search. 27 | //! 28 | pub mod app; 29 | 30 | #[cfg(feature = "axum")] 31 | pub mod axum; 32 | pub mod cache; 33 | pub mod download; 34 | pub mod github; 35 | pub mod search; 36 | 37 | use serde::{Deserialize, Serialize}; 38 | use std::collections::BTreeSet; 39 | use std::fmt::{Display, Formatter}; 40 | use std::num::NonZeroUsize; 41 | use std::ops::{Range, RangeInclusive}; 42 | use std::path::{Path, PathBuf}; 43 | use std::sync::Arc; 44 | 45 | #[cfg(feature = "utoipa")] 46 | use utoipa::ToSchema; 47 | 48 | pub use app::*; 49 | pub use github::*; 50 | pub use search::*; 51 | 52 | /// Represents the name and version of a crate. 53 | /// 54 | /// This struct is used to uniquely identify a crate with its name and version number. 55 | #[derive(Debug, Deserialize, Serialize, Hash, Clone, PartialEq, Eq, PartialOrd, Ord)] 56 | pub struct CrateVersion { 57 | /// The exact name of the crate 58 | #[serde(rename = "crate")] 59 | pub krate: Arc, 60 | /// The semantic version number of the specified crate, following the Semantic versioning specification. 61 | pub version: Arc, 62 | } 63 | 64 | impl CrateVersion { 65 | /// Computes the root directory for the specified crate version. 66 | /// 67 | /// This method concatenates the crate name and version number to form a path-like string, 68 | /// which can be used as a directory name to store crate-related data. 69 | /// 70 | pub fn root_dir(&self) -> PathBuf { 71 | PathBuf::from(format!("{}-{}", self.krate, self.version)) 72 | } 73 | } 74 | 75 | impl From<(C, V)> for CrateVersion 76 | where 77 | C: AsRef, 78 | V: AsRef, 79 | { 80 | /// Creates a `CrateVersion` instance from a tuple of crate name and version. 81 | /// 82 | /// This method allows for a convenient way to construct a `CrateVersion` from separate 83 | /// name and version strings. 84 | fn from(value: (C, V)) -> Self { 85 | Self { 86 | krate: Arc::from(value.0.as_ref()), 87 | version: Arc::from(value.1.as_ref()), 88 | } 89 | } 90 | } 91 | 92 | impl Display for CrateVersion { 93 | fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { 94 | write!(f, "{}-{}", self.krate, self.version) 95 | } 96 | } 97 | 98 | /// Represents a path within a specific crate's directory structure. 99 | /// 100 | /// It combines the crate version information with the relative path within the crate. 101 | #[derive(Debug, Deserialize, Serialize)] 102 | pub struct CrateVersionPath { 103 | /// The name and version of a crate. 104 | #[serde(flatten)] 105 | pub crate_version: CrateVersion, 106 | /// The path. 107 | pub path: Arc, 108 | } 109 | 110 | /// Represents a range of lines in a file. 111 | /// 112 | /// This struct is used to specify a start and end line for operations that work with line ranges. 113 | #[derive(Debug, Deserialize, Serialize, Copy, Clone)] 114 | pub struct FileLineRange { 115 | /// The start line number. 116 | pub start: Option, 117 | /// The end line number. 118 | pub end: Option, 119 | } 120 | 121 | /// Represents the contents of a directory, including files and subdirectories. 122 | /// 123 | /// This is used to provide a snapshot of a directory's contents, listing all files and directories. 124 | #[derive(Debug, Deserialize, Serialize, Clone)] 125 | #[cfg_attr(feature = "utoipa", derive(ToSchema))] 126 | pub struct Directory { 127 | /// Files in the directory. 128 | #[cfg_attr(feature = "utoipa", schema(value_type = BTreeSet))] 129 | pub files: Arc>, 130 | /// Subdirectories in the directory. 131 | #[cfg_attr(feature = "utoipa", schema(value_type = BTreeSet))] 132 | pub directories: Arc>, 133 | } 134 | 135 | impl Directory { 136 | /// Checks whether the directory is empty. 137 | /// 138 | /// This method returns `true` if both the `files` and `directories` sets are empty, 139 | /// indicating that the directory has no contents. 140 | pub fn is_empty(&self) -> bool { 141 | self.files.is_empty() && self.directories.is_empty() 142 | } 143 | } 144 | 145 | #[derive(Debug, Default)] 146 | pub struct DirectoryMut { 147 | pub files: BTreeSet, 148 | pub directories: BTreeSet, 149 | } 150 | 151 | impl DirectoryMut { 152 | /// Checks whether the mutable directory is empty. 153 | /// 154 | /// Similar to `Directory::is_empty`, but for the mutable version of the directory. 155 | /// It's useful for scenarios where directory contents are being modified. 156 | pub fn is_empty(&self) -> bool { 157 | self.files.is_empty() && self.directories.is_empty() 158 | } 159 | 160 | /// Freezes the directory, converting it into an immutable `Directory`. 161 | /// 162 | /// This method converts `DirectoryMut` into `Directory` by wrapping its contents 163 | /// in `Arc`, thus allowing for safe shared access. 164 | /// 165 | pub fn freeze(self) -> Directory { 166 | Directory { 167 | files: Arc::new(self.files), 168 | directories: Arc::new(self.directories), 169 | } 170 | } 171 | } 172 | 173 | /// Represents a query for searching items in a crate. 174 | /// 175 | /// This struct is used to specify the criteria for searching items like structs, enums, traits, etc., within a crate. 176 | #[derive(Debug, Clone, Serialize, Deserialize)] 177 | #[cfg_attr(feature = "utoipa", derive(ToSchema))] 178 | pub struct ItemQuery { 179 | /// The type of item to search for. 180 | #[serde(rename = "type")] 181 | pub type_: ItemType, 182 | /// The query string used for searching. 183 | pub query: String, 184 | /// Optional path within the crate to narrow down the search scope. 185 | #[cfg_attr(feature = "utoipa", schema(value_type = String))] 186 | pub path: Option, 187 | } 188 | 189 | /// Represents an item found in a crate. 190 | /// 191 | /// This struct describes an item, such as a struct or function, including its location within the crate. 192 | #[derive(Debug, Clone, Serialize, Deserialize)] 193 | #[cfg_attr(feature = "utoipa", derive(ToSchema))] 194 | pub struct Item { 195 | /// The name of the item. 196 | pub name: String, 197 | /// The type of the item. 198 | #[serde(rename = "type")] 199 | pub type_: ItemType, 200 | /// The file path where the item is located. 201 | #[cfg_attr(feature = "utoipa", schema(value_type = String))] 202 | pub file: Arc, 203 | /// The range of lines in the file where the item is defined. 204 | #[cfg_attr(feature = "utoipa", schema(value_type = RangeSchema))] 205 | pub line_range: RangeInclusive, 206 | } 207 | 208 | /// Defines various types of items that can be searched for in a crate. 209 | /// 210 | /// This enum lists different types of code constructs like structs, enums, traits, etc. 211 | #[derive(Debug, Default, Serialize, Deserialize, Copy, Clone, Ord, PartialOrd, Eq, PartialEq)] 212 | #[serde(rename_all = "kebab-case")] 213 | #[cfg_attr(feature = "utoipa", derive(ToSchema))] 214 | pub enum ItemType { 215 | /// Represents all item types. 216 | #[default] 217 | All, 218 | /// A struct definition. 219 | Struct, 220 | /// An enum definition. 221 | Enum, 222 | /// A trait definition. 223 | Trait, 224 | /// Type implementation. 225 | ImplType, 226 | /// Trait implementation for a type. 227 | ImplTraitForType, 228 | /// A macro definition. 229 | Macro, 230 | /// An attribute macro. 231 | AttributeMacro, 232 | /// A standalone function. 233 | Function, 234 | /// A type alias. 235 | TypeAlias, 236 | } 237 | 238 | /// Represents a query for searching lines within files in a crate. 239 | /// 240 | /// This struct is used for specifying criteria for line-based searches, such as finding specific text within files. 241 | #[derive(Debug, Clone, Serialize, Deserialize)] 242 | #[cfg_attr(feature = "utoipa", derive(ToSchema))] 243 | pub struct LineQuery { 244 | /// The text or pattern to search for. 245 | pub query: String, 246 | /// The search mode (e.g., plain text or regular expression). 247 | pub mode: SearchMode, 248 | /// Indicates if the search should be case-sensitive. 249 | #[serde(default)] 250 | pub case_sensitive: bool, 251 | /// Indicates if the search should match whole words only. 252 | #[serde(default)] 253 | pub whole_word: bool, 254 | /// The maximum number of results to return. 255 | #[cfg_attr(feature = "utoipa", schema(value_type = usize))] 256 | pub max_results: Option, 257 | /// A comma-separated string specifying file extensions to include in the search. 258 | /// Each segment represents a file extension, e.g., "rs,txt" for Rust and text files. 259 | #[serde(default)] 260 | pub file_ext: String, 261 | /// Optional path within the crate to limit the search scope. 262 | #[cfg_attr(feature = "utoipa", schema(value_type = Option))] 263 | pub path: Option, 264 | } 265 | 266 | /// Defines different modes for searching text. 267 | /// 268 | /// This enum distinguishes between plain text searches and regular expression searches. 269 | #[derive(Debug, Serialize, Deserialize, Ord, PartialOrd, Eq, PartialEq, Copy, Clone)] 270 | #[cfg_attr(feature = "utoipa", derive(ToSchema))] 271 | #[serde(rename_all = "kebab-case")] 272 | pub enum SearchMode { 273 | /// A plain text search. 274 | PlainText, 275 | /// A regular expression search. 276 | Regex, 277 | } 278 | 279 | /// Represents a specific line found in a search operation. 280 | /// 281 | /// This struct contains details about a line of text found in a file, including its content and location. 282 | #[derive(Debug, Serialize, Deserialize)] 283 | #[cfg_attr(feature = "utoipa", derive(ToSchema))] 284 | pub struct Line { 285 | /// The content of the line. 286 | pub line: String, 287 | /// The file path where the line is located. 288 | #[cfg_attr(feature = "utoipa", schema(value_type = String))] 289 | pub file: PathBuf, 290 | /// The line number within the file. 291 | #[cfg_attr(feature = "utoipa", schema(value_type = usize))] 292 | pub line_number: NonZeroUsize, 293 | /// The range of columns in the line where the text was found. 294 | #[cfg_attr(feature = "utoipa", schema(value_type = RangeSchema))] 295 | pub column_range: Range, 296 | } 297 | 298 | /// Schema for representing a range, used in other structs to describe line and column ranges. 299 | #[cfg(feature = "utoipa")] 300 | #[derive(ToSchema)] 301 | pub struct RangeSchema { 302 | /// The start line number. 303 | pub start: usize, 304 | /// The end line number. 305 | pub end: usize, 306 | } 307 | 308 | #[cfg(test)] 309 | mod tests { 310 | use super::*; 311 | use crate::cache::{Crate, CrateCache, CrateTar}; 312 | use crate::download::CrateDownloader; 313 | use std::num::NonZeroUsize; 314 | 315 | #[tokio::test] 316 | async fn download_and_read() -> anyhow::Result<()> { 317 | // let start = Instant::now(); 318 | let crate_version = CrateVersion::from(("tokio", "1.35.1")); 319 | let downloader = CrateDownloader::default(); 320 | let tar_data = downloader.download_crate_file(&crate_version).await?; 321 | let cache = CrateCache::new(NonZeroUsize::new(1024).unwrap()); 322 | let crate_tar = CrateTar::from((crate_version.clone(), tar_data)); 323 | let krate = Crate::try_from(crate_tar)?; 324 | let old = cache.set_crate(crate_version.clone(), krate); 325 | assert!(old.is_none()); 326 | 327 | let crate_ = cache.get_crate(&crate_version).expect("get crate"); 328 | 329 | let files = crate_.read_directory("").expect("read directory"); 330 | assert!(!files.is_empty()); 331 | println!("{:#?}", files); 332 | 333 | let lib_rs_content = crate_.get_file_by_line_range("src/lib.rs", ..)?; 334 | assert!(lib_rs_content.is_some()); 335 | let lib_rs_range_content = 336 | crate_.get_file_by_line_range("src/lib.rs", ..NonZeroUsize::new(27).unwrap())?; 337 | assert!(lib_rs_range_content.is_some()); 338 | // println!("{}", lib_rs_range_content.expect("lib.rs")); 339 | // println!("Elapsed: {}µs", start.elapsed().as_micros()); 340 | 341 | let file = crate_ 342 | .get_file_by_line_range("src/lib.rs", ..=NonZeroUsize::new(3).unwrap())? 343 | .unwrap(); 344 | println!("[{}]", std::str::from_utf8(file.data.as_ref()).unwrap()); 345 | 346 | let lines = crate_.search_line(&LineQuery { 347 | query: "Sleep".to_string(), 348 | mode: SearchMode::PlainText, 349 | case_sensitive: true, 350 | whole_word: true, 351 | max_results: Some(6.try_into().expect("6")), 352 | file_ext: "rs".into(), 353 | path: Some(PathBuf::from("src")), 354 | })?; 355 | println!("{:#?}", lines); 356 | Ok(()) 357 | } 358 | } 359 | -------------------------------------------------------------------------------- /crates/rust-assistant/src/search.rs: -------------------------------------------------------------------------------- 1 | //! The `search` module. 2 | //! 3 | //! Focused on providing search functionalities within crates. This module might contain 4 | //! implementations for searching through crate contents, such as source code files, documentation, 5 | //! and other relevant data. It could include various search algorithms and data structures optimized 6 | //! for quick and efficient search operations, like `SearchIndex`. 7 | //! 8 | use fnv::FnvHashMap; 9 | use serde::{Deserialize, Serialize}; 10 | use std::num::NonZeroUsize; 11 | use std::path::Path; 12 | use std::sync::Arc; 13 | use syn::spanned::Spanned; 14 | use syn::{Attribute, ItemEnum, ItemFn, ItemImpl, ItemMacro, ItemStruct, ItemTrait}; 15 | 16 | use crate::{Item, ItemQuery, ItemType}; 17 | 18 | /// A mutable search index containing categorized items for searching within a crate. 19 | /// 20 | /// This struct stores various items like structs, enums, traits, etc., in categorized hash maps, 21 | /// facilitating efficient search operations. 22 | /// 23 | #[derive(Debug, Default, Serialize, Deserialize)] 24 | pub struct SearchIndexMut { 25 | pub structs: FnvHashMap>, 26 | pub enums: FnvHashMap>, 27 | pub traits: FnvHashMap>, 28 | pub impl_types: FnvHashMap>, 29 | pub impl_trait_for_types: FnvHashMap>, 30 | pub macros: FnvHashMap>, 31 | pub attribute_macros: FnvHashMap>, 32 | pub functions: FnvHashMap>, 33 | pub type_aliases: FnvHashMap>, 34 | } 35 | 36 | impl SearchIndexMut { 37 | /// Searches for items within the index based on the provided query. 38 | /// 39 | pub fn search(&self, query: &ItemQuery) -> Vec { 40 | let ItemQuery { type_, query, path } = query; 41 | let query = query.to_lowercase(); 42 | let path = path.as_ref().map(|p| p.as_path()); 43 | match type_ { 44 | ItemType::All => { 45 | let mut all = Vec::new(); 46 | all.extend(filter_items(&query, &self.structs, path)); 47 | all.extend(filter_items(&query, &self.enums, path)); 48 | all.extend(filter_items(&query, &self.traits, path)); 49 | all.extend(filter_items(&query, &self.impl_types, path)); 50 | all.extend(filter_items(&query, &self.impl_trait_for_types, path)); 51 | all.extend(filter_items(&query, &self.macros, path)); 52 | all.extend(filter_items(&query, &self.attribute_macros, path)); 53 | all.extend(filter_items(&query, &self.functions, path)); 54 | all.extend(filter_items(&query, &self.type_aliases, path)); 55 | all 56 | } 57 | ItemType::Struct => filter_items(&query, &self.structs, path), 58 | ItemType::Enum => filter_items(&query, &self.enums, path), 59 | ItemType::Trait => filter_items(&query, &self.traits, path), 60 | ItemType::ImplType => filter_items(&query, &self.impl_types, path), 61 | ItemType::ImplTraitForType => filter_items(&query, &self.impl_trait_for_types, path), 62 | ItemType::Macro => filter_items(&query, &self.macros, path), 63 | ItemType::AttributeMacro => filter_items(&query, &self.attribute_macros, path), 64 | ItemType::Function => filter_items(&query, &self.functions, path), 65 | ItemType::TypeAlias => filter_items(&query, &self.type_aliases, path), 66 | } 67 | } 68 | } 69 | 70 | /// Filters items from a hashmap based on a query and optional path. 71 | /// 72 | fn filter_items( 73 | query: &str, 74 | items: &FnvHashMap>, 75 | path: Option<&Path>, 76 | ) -> Vec { 77 | let flatten = items 78 | .iter() 79 | .filter(|(name, _)| name.contains(&query)) 80 | .map(|(_, item)| item) 81 | .flatten(); 82 | match path { 83 | None => flatten.cloned().collect::>(), 84 | Some(path) => flatten 85 | .filter(|item| item.file.starts_with(path)) 86 | .cloned() 87 | .collect::>(), 88 | } 89 | } 90 | 91 | /// Shared immutable search index, used for efficient read access across multiple threads. 92 | pub type SearchIndex = Arc; 93 | 94 | impl SearchIndexMut { 95 | /// Freezes the mutable search index into an immutable one. 96 | /// 97 | pub fn freeze(self) -> SearchIndex { 98 | Arc::new(self) 99 | } 100 | } 101 | 102 | /// A builder for constructing a `SearchIndex`. 103 | /// 104 | /// This struct facilitates the creation and population of a `SearchIndexMut` 105 | /// by parsing Rust source files and adding items to the index. 106 | #[derive(Debug, Default)] 107 | pub struct SearchIndexBuilder { 108 | index: SearchIndexMut, 109 | } 110 | 111 | impl SearchIndexBuilder { 112 | /// Updates the search index with items parsed from a Rust source file. 113 | /// 114 | pub fn update>(&mut self, file: P, content: &str) -> bool { 115 | let mut visitor = IndexVisitor::new(&mut self.index, file); 116 | if let Ok(ast) = syn::parse_file(content) { 117 | syn::visit::visit_file(&mut visitor, &ast); 118 | true 119 | } else { 120 | false 121 | } 122 | } 123 | 124 | /// Finalizes the construction of the `SearchIndex`. 125 | /// 126 | pub fn finish(self) -> SearchIndex { 127 | self.index.freeze() 128 | } 129 | } 130 | 131 | /// A visitor struct for traversing and indexing Rust syntax trees. 132 | /// 133 | /// This struct is used in conjunction with `syn::visit::Visit` to extract items from Rust source files 134 | /// and add them to a `SearchIndexMut`. 135 | pub struct IndexVisitor<'i> { 136 | index: &'i mut SearchIndexMut, 137 | current_file: Arc, 138 | } 139 | 140 | impl<'i> IndexVisitor<'i> { 141 | /// Creates a new `IndexVisitor`. 142 | /// 143 | pub fn new>(index: &'i mut SearchIndexMut, current_file: P) -> Self { 144 | IndexVisitor { 145 | index, 146 | current_file: Arc::from(current_file.as_ref()), 147 | } 148 | } 149 | 150 | fn create_item( 151 | &self, 152 | name: String, 153 | type_: ItemType, 154 | item_span: proc_macro2::Span, 155 | attrs: &[Attribute], 156 | ) -> Item { 157 | // 获取项的 span 158 | let mut start_line = item_span.start().line; 159 | let end_line = item_span.end().line; 160 | 161 | // 检查并调整起始行号以包含文档注释 162 | for attr in attrs { 163 | if attr.path().is_ident("doc") { 164 | let attr_span = attr.span(); 165 | start_line = start_line.min(attr_span.start().line); 166 | } 167 | } 168 | 169 | let start_line = NonZeroUsize::new(start_line).unwrap_or(NonZeroUsize::MIN); 170 | let end_line = NonZeroUsize::new(end_line).unwrap_or(NonZeroUsize::MAX); 171 | 172 | Item { 173 | name, 174 | type_, 175 | file: self.current_file.clone(), 176 | line_range: start_line..=end_line, 177 | } 178 | } 179 | } 180 | 181 | impl<'i, 'ast> syn::visit::Visit<'ast> for IndexVisitor<'i> { 182 | fn visit_item_enum(&mut self, i: &'ast ItemEnum) { 183 | let name = i.ident.to_string(); 184 | let item = self.create_item(name, ItemType::Enum, i.span(), &i.attrs); 185 | self.index 186 | .enums 187 | .entry(item.name.to_lowercase()) 188 | .or_default() 189 | .push(item); 190 | } 191 | 192 | fn visit_item_fn(&mut self, i: &'ast ItemFn) { 193 | if is_attribute_macro(&i.attrs) { 194 | let name = i.sig.ident.to_string(); 195 | let item = self.create_item(name, ItemType::AttributeMacro, i.span(), &i.attrs); 196 | self.index 197 | .attribute_macros 198 | .entry(item.name.to_lowercase()) 199 | .or_default() 200 | .push(item); 201 | } else { 202 | let name = i.sig.ident.to_string(); 203 | let item = self.create_item(name, ItemType::Function, i.span(), &i.attrs); 204 | self.index 205 | .functions 206 | .entry(item.name.to_lowercase()) 207 | .or_default() 208 | .push(item); 209 | } 210 | } 211 | 212 | fn visit_item_impl(&mut self, i: &'ast ItemImpl) { 213 | let self_ty = &i.self_ty; 214 | 215 | match &i.trait_ { 216 | Some((_, path, _)) => { 217 | // impl Trait for Type 218 | let impl_name = format!( 219 | "impl {} for {}", 220 | quote::quote! { #path }, 221 | quote::quote! { #self_ty } 222 | ); 223 | let item = 224 | self.create_item(impl_name, ItemType::ImplTraitForType, i.span(), &i.attrs); 225 | self.index 226 | .impl_trait_for_types 227 | .entry(item.name.to_lowercase()) 228 | .or_default() 229 | .push(item); 230 | } 231 | None => { 232 | // impl Type 233 | let impl_name = format!("impl {}", quote::quote! { #self_ty }); 234 | let item = self.create_item(impl_name, ItemType::ImplType, i.span(), &i.attrs); 235 | self.index 236 | .impl_types 237 | .entry(item.name.to_lowercase()) 238 | .or_default() 239 | .push(item); 240 | } 241 | }; 242 | } 243 | 244 | fn visit_item_macro(&mut self, i: &'ast ItemMacro) { 245 | if let Some(ident) = &i.ident { 246 | let name = ident.to_string(); 247 | let item = self.create_item(name, ItemType::Macro, i.span(), &i.attrs); 248 | self.index 249 | .macros 250 | .entry(item.name.to_lowercase()) 251 | .or_default() 252 | .push(item); 253 | } 254 | } 255 | 256 | fn visit_item_struct(&mut self, i: &'ast ItemStruct) { 257 | let name = i.ident.to_string(); 258 | let item = self.create_item(name, ItemType::Struct, i.span(), &i.attrs); 259 | self.index 260 | .structs 261 | .entry(item.name.to_lowercase()) 262 | .or_default() 263 | .push(item); 264 | } 265 | 266 | fn visit_item_trait(&mut self, i: &'ast ItemTrait) { 267 | let name = i.ident.to_string(); 268 | let item = self.create_item(name, ItemType::Trait, i.span(), &i.attrs); 269 | self.index 270 | .traits 271 | .entry(item.name.to_lowercase()) 272 | .or_default() 273 | .push(item); 274 | } 275 | 276 | fn visit_item_type(&mut self, i: &'ast syn::ItemType) { 277 | let name = i.ident.to_string(); 278 | let item = self.create_item(name, ItemType::TypeAlias, i.span(), &i.attrs); 279 | self.index 280 | .type_aliases 281 | .entry(item.name.to_lowercase()) 282 | .or_default() 283 | .push(item); 284 | } 285 | } 286 | 287 | fn is_attribute_macro(attrs: &[Attribute]) -> bool { 288 | attrs.iter().any(|attr| { 289 | // check proc_macro_attribute 290 | attr.path().is_ident("proc_macro_attribute") 291 | }) 292 | } 293 | -------------------------------------------------------------------------------- /doc/icon.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/gengteng/rust-assistant/f66eb0a0666f6d342d1dd989553ac9f32eedea1f/doc/icon.png -------------------------------------------------------------------------------- /doc/privacy-policy.md: -------------------------------------------------------------------------------- 1 | # Privacy Policy for Rust Assistant API 2 | 3 | ## Introduction 4 | The Rust Assistant API is committed to protecting your privacy. This Privacy Policy outlines our practices concerning the collection, use, and protection of your data. 5 | 6 | ## Data Collection 7 | - The Rust Assistant API does not collect personal information. 8 | - The API processes requests containing crate names, version numbers, and file paths, which are considered non-sensitive data. 9 | 10 | ## Data Usage 11 | - The data provided to the API is exclusively used for processing requests and generating responses. 12 | - No data is stored, shared, or used for any purposes beyond the scope of immediate request handling. 13 | 14 | ## Data Protection 15 | - We implement appropriate technical measures to ensure data security during transmission to and from the API. 16 | - The API is designed to avoid unnecessary data retention and exposure. 17 | 18 | ## User Consent 19 | - By using the Rust Assistant API, users agree to the terms outlined in this Privacy Policy. 20 | - Users are responsible for any data they choose to submit to the API. 21 | 22 | ## Changes to This Policy 23 | - We reserve the right to modify this policy at any time. Any changes will be promptly reflected in this document. --------------------------------------------------------------------------------