[
  {
    "path": ".github/workflows/docs.yml",
    "content": "name: Deploy docs\non:\n  push:\n    branches:\n      - master\n\njobs:\n  deploy:\n    runs-on: ubuntu-latest\n    permissions:\n      contents: write  # To push a branch\n      pages: write     # To push to a GitHub Pages site\n      id-token: write  # To update the deployment status\n    steps:\n      - uses: actions/checkout@v4\n        with:\n          fetch-depth: 0\n      - name: Install latest mdbook\n        run: |\n          tag=$(curl 'https://api.github.com/repos/rust-lang/mdbook/releases/latest' | jq -r '.tag_name')\n          url=\"https://github.com/rust-lang/mdbook/releases/download/${tag}/mdbook-${tag}-x86_64-unknown-linux-gnu.tar.gz\"\n          mkdir mdbook\n          curl -sSL $url | tar -xz --directory=./mdbook\n          echo `pwd`/mdbook >> $GITHUB_PATH\n      - name: Build Book\n        run: |\n          cd book\n          mdbook build\n      - name: Setup Pages\n        uses: actions/configure-pages@v5\n      - name: Upload artifact\n        uses: actions/upload-pages-artifact@v3\n        with:\n          path: 'book/book'\n      - name: Deploy to GitHub Pages\n        id: deployment\n        uses: actions/deploy-pages@v4\n"
  },
  {
    "path": ".github/workflows/rust.yml",
    "content": "name: Rust\n\non:\n  push:\n    branches: [ master ]\n  pull_request:\n    branches: [ master ]\n\nenv:\n  CARGO_TERM_COLOR: always\n\njobs:\n  build:\n    runs-on: ubuntu-latest\n    env:\n      RUSTFLAGS: -Dwarnings\n    steps:\n    - uses: actions/checkout@v4\n    - name: Build\n      run: cargo test --verbose --no-run\n    - name: Run tests\n      run: cargo test --verbose\n\n  static:\n    runs-on: ubuntu-latest\n    steps:\n    - uses: actions/checkout@v4\n    - uses: dtolnay/rust-toolchain@stable\n      with:\n        targets: x86_64-unknown-linux-musl\n    - name: Install host deps\n      run: sudo apt-get install -y musl-tools\n    - name: Build + link statically\n      run: cargo build --verbose --release --target=x86_64-unknown-linux-musl --features vendored-openssl\n    - name: Validate binary is statically linked\n      run: ldd ./target/x86_64-unknown-linux-musl/release/prr 2>&1 | grep -q \"statically linked\"\n\n  format:\n    runs-on: ubuntu-latest\n    steps:\n    - uses: actions/checkout@v2\n    - name: Run rustfmt\n      run: cargo fmt --check\n"
  },
  {
    "path": ".gitignore",
    "content": "/target\n"
  },
  {
    "path": "Cargo.toml",
    "content": "[package]\nname = \"prr\"\ndescription = \"Mailing list style code reviews for github\"\nlicense = \"GPL-2.0-or-later\"\nrepository = \"https://github.com/danobi/prr\"\nversion = \"0.21.0\"\nedition = \"2021\"\nrust-version = \"1.78.0\"\nbuild = \"build.rs\"\n\n[dependencies]\nanyhow = \"1.0\"\nclap = { version = \"4.4\", features = [\"derive\"] }\ngit2 = \"0.20.0\"\nhttp = \"1.1.0\"\nlazy_static = \"1.4\"\noctocrab = \"0.38\"\nprettytable-rs = \"0.10.0\"\nregex = \"1.5\"\nserde = \"1.0\"\nserde_derive = \"1.0\"\nserde_json = \"1.0\"\ntokio = { version = \"1.17\", default-features = false, features = [\"macros\", \"rt-multi-thread\"] }\ntoml = \"0.5\"\nxdg = \"2.4\"\n\n[dev-dependencies]\npretty_assertions = \"1.4.0\"\ntempfile = \"3.8.1\"\n\n[build-dependencies]\nanyhow = \"1.0\"\nclap = { version = \"4.4\", features = [\"derive\"] }\nclap_complete = \"4.5.2\"\nclap_mangen = \"0.2.20\"\n\n[features]\n# Statically link a vendored copy OpenSSL. OpenSSL is used by all of `git2`, `reqwest` and\n# `octocrab`, enabling vendoring for just one of them should be enough.\nvendored-openssl = [\"git2/vendored-openssl\"]\n"
  },
  {
    "path": "LICENSE",
    "content": "                    GNU GENERAL PUBLIC LICENSE\n                       Version 2, June 1991\n\n Copyright (C) 1989, 1991 Free Software Foundation, Inc.,\n 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n Everyone is permitted to copy and distribute verbatim copies\n of this license document, but changing it is not allowed.\n\n                            Preamble\n\n  The licenses for most software are designed to take away your\nfreedom to share and change it.  By contrast, the GNU General Public\nLicense is intended to guarantee your freedom to share and change free\nsoftware--to make sure the software is free for all its users.  This\nGeneral Public License applies to most of the Free Software\nFoundation's software and to any other program whose authors commit to\nusing it.  (Some other Free Software Foundation software is covered by\nthe GNU Lesser General Public License instead.)  You can apply it to\nyour programs, too.\n\n  When we speak of free software, we are referring to freedom, not\nprice.  Our General Public Licenses are designed to make sure that you\nhave the freedom to distribute copies of free software (and charge for\nthis service if you wish), that you receive source code or can get it\nif you want it, that you can change the software or use pieces of it\nin new free programs; and that you know you can do these things.\n\n  To protect your rights, we need to make restrictions that forbid\nanyone to deny you these rights or to ask you to surrender the rights.\nThese restrictions translate to certain responsibilities for you if you\ndistribute copies of the software, or if you modify it.\n\n  For example, if you distribute copies of such a program, whether\ngratis or for a fee, you must give the recipients all the rights that\nyou have.  You must make sure that they, too, receive or can get the\nsource code.  And you must show them these terms so they know their\nrights.\n\n  We protect your rights with two steps: (1) copyright the software, and\n(2) offer you this license which gives you legal permission to copy,\ndistribute and/or modify the software.\n\n  Also, for each author's protection and ours, we want to make certain\nthat everyone understands that there is no warranty for this free\nsoftware.  If the software is modified by someone else and passed on, we\nwant its recipients to know that what they have is not the original, so\nthat any problems introduced by others will not reflect on the original\nauthors' reputations.\n\n  Finally, any free program is threatened constantly by software\npatents.  We wish to avoid the danger that redistributors of a free\nprogram will individually obtain patent licenses, in effect making the\nprogram proprietary.  To prevent this, we have made it clear that any\npatent must be licensed for everyone's free use or not licensed at all.\n\n  The precise terms and conditions for copying, distribution and\nmodification follow.\n\n                    GNU GENERAL PUBLIC LICENSE\n   TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION\n\n  0. This License applies to any program or other work which contains\na notice placed by the copyright holder saying it may be distributed\nunder the terms of this General Public License.  The \"Program\", below,\nrefers to any such program or work, and a \"work based on the Program\"\nmeans either the Program or any derivative work under copyright law:\nthat is to say, a work containing the Program or a portion of it,\neither verbatim or with modifications and/or translated into another\nlanguage.  (Hereinafter, translation is included without limitation in\nthe term \"modification\".)  Each licensee is addressed as \"you\".\n\nActivities other than copying, distribution and modification are not\ncovered by this License; they are outside its scope.  The act of\nrunning the Program is not restricted, and the output from the Program\nis covered only if its contents constitute a work based on the\nProgram (independent of having been made by running the Program).\nWhether that is true depends on what the Program does.\n\n  1. You may copy and distribute verbatim copies of the Program's\nsource code as you receive it, in any medium, provided that you\nconspicuously and appropriately publish on each copy an appropriate\ncopyright notice and disclaimer of warranty; keep intact all the\nnotices that refer to this License and to the absence of any warranty;\nand give any other recipients of the Program a copy of this License\nalong with the Program.\n\nYou may charge a fee for the physical act of transferring a copy, and\nyou may at your option offer warranty protection in exchange for a fee.\n\n  2. You may modify your copy or copies of the Program or any portion\nof it, thus forming a work based on the Program, and copy and\ndistribute such modifications or work under the terms of Section 1\nabove, provided that you also meet all of these conditions:\n\n    a) You must cause the modified files to carry prominent notices\n    stating that you changed the files and the date of any change.\n\n    b) You must cause any work that you distribute or publish, that in\n    whole or in part contains or is derived from the Program or any\n    part thereof, to be licensed as a whole at no charge to all third\n    parties under the terms of this License.\n\n    c) If the modified program normally reads commands interactively\n    when run, you must cause it, when started running for such\n    interactive use in the most ordinary way, to print or display an\n    announcement including an appropriate copyright notice and a\n    notice that there is no warranty (or else, saying that you provide\n    a warranty) and that users may redistribute the program under\n    these conditions, and telling the user how to view a copy of this\n    License.  (Exception: if the Program itself is interactive but\n    does not normally print such an announcement, your work based on\n    the Program is not required to print an announcement.)\n\nThese requirements apply to the modified work as a whole.  If\nidentifiable sections of that work are not derived from the Program,\nand can be reasonably considered independent and separate works in\nthemselves, then this License, and its terms, do not apply to those\nsections when you distribute them as separate works.  But when you\ndistribute the same sections as part of a whole which is a work based\non the Program, the distribution of the whole must be on the terms of\nthis License, whose permissions for other licensees extend to the\nentire whole, and thus to each and every part regardless of who wrote it.\n\nThus, it is not the intent of this section to claim rights or contest\nyour rights to work written entirely by you; rather, the intent is to\nexercise the right to control the distribution of derivative or\ncollective works based on the Program.\n\nIn addition, mere aggregation of another work not based on the Program\nwith the Program (or with a work based on the Program) on a volume of\na storage or distribution medium does not bring the other work under\nthe scope of this License.\n\n  3. You may copy and distribute the Program (or a work based on it,\nunder Section 2) in object code or executable form under the terms of\nSections 1 and 2 above provided that you also do one of the following:\n\n    a) Accompany it with the complete corresponding machine-readable\n    source code, which must be distributed under the terms of Sections\n    1 and 2 above on a medium customarily used for software interchange; or,\n\n    b) Accompany it with a written offer, valid for at least three\n    years, to give any third party, for a charge no more than your\n    cost of physically performing source distribution, a complete\n    machine-readable copy of the corresponding source code, to be\n    distributed under the terms of Sections 1 and 2 above on a medium\n    customarily used for software interchange; or,\n\n    c) Accompany it with the information you received as to the offer\n    to distribute corresponding source code.  (This alternative is\n    allowed only for noncommercial distribution and only if you\n    received the program in object code or executable form with such\n    an offer, in accord with Subsection b above.)\n\nThe source code for a work means the preferred form of the work for\nmaking modifications to it.  For an executable work, complete source\ncode means all the source code for all modules it contains, plus any\nassociated interface definition files, plus the scripts used to\ncontrol compilation and installation of the executable.  However, as a\nspecial exception, the source code distributed need not include\nanything that is normally distributed (in either source or binary\nform) with the major components (compiler, kernel, and so on) of the\noperating system on which the executable runs, unless that component\nitself accompanies the executable.\n\nIf distribution of executable or object code is made by offering\naccess to copy from a designated place, then offering equivalent\naccess to copy the source code from the same place counts as\ndistribution of the source code, even though third parties are not\ncompelled to copy the source along with the object code.\n\n  4. You may not copy, modify, sublicense, or distribute the Program\nexcept as expressly provided under this License.  Any attempt\notherwise to copy, modify, sublicense or distribute the Program is\nvoid, and will automatically terminate your rights under this License.\nHowever, parties who have received copies, or rights, from you under\nthis License will not have their licenses terminated so long as such\nparties remain in full compliance.\n\n  5. You are not required to accept this License, since you have not\nsigned it.  However, nothing else grants you permission to modify or\ndistribute the Program or its derivative works.  These actions are\nprohibited by law if you do not accept this License.  Therefore, by\nmodifying or distributing the Program (or any work based on the\nProgram), you indicate your acceptance of this License to do so, and\nall its terms and conditions for copying, distributing or modifying\nthe Program or works based on it.\n\n  6. Each time you redistribute the Program (or any work based on the\nProgram), the recipient automatically receives a license from the\noriginal licensor to copy, distribute or modify the Program subject to\nthese terms and conditions.  You may not impose any further\nrestrictions on the recipients' exercise of the rights granted herein.\nYou are not responsible for enforcing compliance by third parties to\nthis License.\n\n  7. If, as a consequence of a court judgment or allegation of patent\ninfringement or for any other reason (not limited to patent issues),\nconditions are imposed on you (whether by court order, agreement or\notherwise) that contradict the conditions of this License, they do not\nexcuse you from the conditions of this License.  If you cannot\ndistribute so as to satisfy simultaneously your obligations under this\nLicense and any other pertinent obligations, then as a consequence you\nmay not distribute the Program at all.  For example, if a patent\nlicense would not permit royalty-free redistribution of the Program by\nall those who receive copies directly or indirectly through you, then\nthe only way you could satisfy both it and this License would be to\nrefrain entirely from distribution of the Program.\n\nIf any portion of this section is held invalid or unenforceable under\nany particular circumstance, the balance of the section is intended to\napply and the section as a whole is intended to apply in other\ncircumstances.\n\nIt is not the purpose of this section to induce you to infringe any\npatents or other property right claims or to contest validity of any\nsuch claims; this section has the sole purpose of protecting the\nintegrity of the free software distribution system, which is\nimplemented by public license practices.  Many people have made\ngenerous contributions to the wide range of software distributed\nthrough that system in reliance on consistent application of that\nsystem; it is up to the author/donor to decide if he or she is willing\nto distribute software through any other system and a licensee cannot\nimpose that choice.\n\nThis section is intended to make thoroughly clear what is believed to\nbe a consequence of the rest of this License.\n\n  8. If the distribution and/or use of the Program is restricted in\ncertain countries either by patents or by copyrighted interfaces, the\noriginal copyright holder who places the Program under this License\nmay add an explicit geographical distribution limitation excluding\nthose countries, so that distribution is permitted only in or among\ncountries not thus excluded.  In such case, this License incorporates\nthe limitation as if written in the body of this License.\n\n  9. The Free Software Foundation may publish revised and/or new versions\nof the General Public License from time to time.  Such new versions will\nbe similar in spirit to the present version, but may differ in detail to\naddress new problems or concerns.\n\nEach version is given a distinguishing version number.  If the Program\nspecifies a version number of this License which applies to it and \"any\nlater version\", you have the option of following the terms and conditions\neither of that version or of any later version published by the Free\nSoftware Foundation.  If the Program does not specify a version number of\nthis License, you may choose any version ever published by the Free Software\nFoundation.\n\n  10. If you wish to incorporate parts of the Program into other free\nprograms whose distribution conditions are different, write to the author\nto ask for permission.  For software which is copyrighted by the Free\nSoftware Foundation, write to the Free Software Foundation; we sometimes\nmake exceptions for this.  Our decision will be guided by the two goals\nof preserving the free status of all derivatives of our free software and\nof promoting the sharing and reuse of software generally.\n\n                            NO WARRANTY\n\n  11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY\nFOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW.  EXCEPT WHEN\nOTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES\nPROVIDE THE PROGRAM \"AS IS\" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED\nOR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF\nMERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.  THE ENTIRE RISK AS\nTO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU.  SHOULD THE\nPROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,\nREPAIR OR CORRECTION.\n\n  12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING\nWILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR\nREDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,\nINCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING\nOUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED\nTO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY\nYOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER\nPROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE\nPOSSIBILITY OF SUCH DAMAGES.\n\n                     END OF TERMS AND CONDITIONS\n\n            How to Apply These Terms to Your New Programs\n\n  If you develop a new program, and you want it to be of the greatest\npossible use to the public, the best way to achieve this is to make it\nfree software which everyone can redistribute and change under these terms.\n\n  To do so, attach the following notices to the program.  It is safest\nto attach them to the start of each source file to most effectively\nconvey the exclusion of warranty; and each file should have at least\nthe \"copyright\" line and a pointer to where the full notice is found.\n\n    <one line to give the program's name and a brief idea of what it does.>\n    Copyright (C) <year>  <name of author>\n\n    This program is free software; you can redistribute it and/or modify\n    it under the terms of the GNU General Public License as published by\n    the Free Software Foundation; either version 2 of the License, or\n    (at your option) any later version.\n\n    This program is distributed in the hope that it will be useful,\n    but WITHOUT ANY WARRANTY; without even the implied warranty of\n    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n    GNU General Public License for more details.\n\n    You should have received a copy of the GNU General Public License along\n    with this program; if not, write to the Free Software Foundation, Inc.,\n    51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.\n\nAlso add information on how to contact you by electronic and paper mail.\n\nIf the program is interactive, make it output a short notice like this\nwhen it starts in an interactive mode:\n\n    Gnomovision version 69, Copyright (C) year name of author\n    Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.\n    This is free software, and you are welcome to redistribute it\n    under certain conditions; type `show c' for details.\n\nThe hypothetical commands `show w' and `show c' should show the appropriate\nparts of the General Public License.  Of course, the commands you use may\nbe called something other than `show w' and `show c'; they could even be\nmouse-clicks or menu items--whatever suits your program.\n\nYou should also get your employer (if you work as a programmer) or your\nschool, if any, to sign a \"copyright disclaimer\" for the program, if\nnecessary.  Here is a sample; alter the names:\n\n  Yoyodyne, Inc., hereby disclaims all copyright interest in the program\n  `Gnomovision' (which makes passes at compilers) written by James Hacker.\n\n  <signature of Ty Coon>, 1 April 1989\n  Ty Coon, President of Vice\n\nThis General Public License does not permit incorporating your program into\nproprietary programs.  If your program is a subroutine library, you may\nconsider it more useful to permit linking proprietary applications with the\nlibrary.  If this is what you want to do, use the GNU Lesser General\nPublic License instead of this License.\n"
  },
  {
    "path": "NOTES.md",
    "content": "# TODO\n\n- [x] Parse review files\n    - [x] Create parser\n    - [x] Create `include_str!()` based unit-tests for expected comments\n        - [x] Test invalid spans (span that does not have a comment that\n              terminates it and another span starts)\n- [x] Wire up comment uploading to GH\n- [x] Inspect response error codes and body\n- [x] Fix bug where `line` and `start_line` are being set instead of `position`\n    - [x] Check if `start_position` is accepted\n    - [x] Add test for trying to comment on a hunk start\n- [x] Figure out how to calculate line for diffs w/ changes on both sides\n- [x] Add test for comment at end of review file\n- [x] Prohibit cross hunk spanned comments\n- [x] Support review-level comments at top of review file\n- [x] Manual test that comments on a changed file work\n- [x] Support approve/rejecting PRs\n    - [x] Need some kind of meta syntax (like go's //+)\n        - [ ] Think about if it could be generalized to comment threads\n- [x] Support updating a PR's review file, but ask for confirmation if review file has been modified and not submitted yet\n    - [x] Maybe even check mtime between review file and submission time?\n- [x] Support parsing github url from stdin\n- [x] Save commit hash of downloaded review file\n- [x] Support [...] snipping\n- [ ] Support comment threads. Maybe do nested '>'s like actual mailing lists?\n\n# Thoughts\n\n* Make a comment spanned by inserting a whitespace line before the\n  start of the span\n\n    * To compose with back-to-back spanned comments, the latter comment\n      must be assumed to be a single line comment. Otherwise, using\n      a single spanned comment always makes the next comment a span.\n      This kinda actually makes sense conceptually too cuz if the user\n      actually wants back-to-back spans then they should've just used\n      a single, larger span.\n\n* Need to be careful to prohibit a spanned comment over multiple files\n"
  },
  {
    "path": "README.md",
    "content": "# Pull request review\n\n[![Rust](https://github.com/danobi/prr/actions/workflows/rust.yml/badge.svg?branch=master)](https://github.com/danobi/prr/actions/workflows/rust.yml)\n\n`prr` is a tool that brings mailing list style code reviews to Github PRs.\nThis means offline reviews and inline comments, more or less.\n\nTo that end, `prr` introduces a new workflow for reviewing PRs:\n\n1. Download the PR into a \"review file\" on your filesystem\n1. Mark up the review file using your favorite text editor\n1. Submit the review at your convenience\n\nThe tool was born of frustration from using the point-and-click editor text\nboxes on PRs. I happen to do a lot of code review and tabbing to and from the\nbrowser to cross reference code from the changes was driving me nuts.\n\nFor full documentation, please visit https://doc.dxuuu.xyz/prr/.\n"
  },
  {
    "path": "build.rs",
    "content": "mod cli {\n    include!(\"src/cli.rs\");\n}\n\nconst LONG_ABOUT: &str =\n    \"prr is a tool that brings mailing list style code reviews to Github PRs. This \\\nmeans offline reviews and inline comments, more or less.\n\nTo that end, prr introduces a new workflow for reviewing PRs:\n  1. Download the PR into a \\\"review file\\\" on your filesystem\n  2. Mark up the review file using your favorite text editor\n  3. Submit the review at your convenience\n\nFor full documentation, please visit https://doc.dxuuu.xyz/prr/.\";\n\nfn main() -> std::io::Result<()> {\n    if let Some(out_path) = std::env::var_os(\"GEN_DIR\").or(std::env::var_os(\"OUT_DIR\")) {\n        use clap::CommandFactory;\n        #[allow(unused_variables)]\n        let out_dir = std::path::PathBuf::from(out_path);\n        #[allow(unused_mut, unused_variables)]\n        let mut cmd = cli::Cli::command()\n            .author(\"Daniel Xu <dxu@apache.org>\")\n            .about(\"Mailing list style code reviews for GitHub\")\n            .long_about(LONG_ABOUT);\n\n        let man_dir = std::path::Path::join(&out_dir, \"man\");\n        std::fs::create_dir_all(&man_dir)?;\n        clap_mangen::generate_to(cmd.clone(), &man_dir)?;\n\n        use clap::ValueEnum;\n        let completions_dir = std::path::Path::join(&out_dir, \"completions\");\n        std::fs::create_dir_all(&completions_dir)?;\n        for shell in clap_complete::Shell::value_variants() {\n            clap_complete::generate_to(*shell, &mut cmd, \"prr\", &completions_dir)?;\n        }\n    }\n\n    println!(\n        \"cargo:rustc-env=TARGET={}\",\n        std::env::var(\"TARGET\").unwrap()\n    );\n    println!(\"cargo:rerun-if-env-changed=GEN_DIR\");\n\n    Ok(())\n}\n"
  },
  {
    "path": "completions/_prr",
    "content": "#compdef prr\n\n_prr_reviews() {\n  local -a reviews\n  local handle r_status file\n\n  if (( ${_PRR_IN_COMPLETION:-0} )); then\n    return 1\n  fi\n\n  local _PRR_IN_COMPLETION=1\n\n  while IFS=' ' read -r handle r_status file _; do\n    [[ -z $handle ]] && continue\n    reviews+=(\"${handle}:${r_status}  ${file}\")\n  done < <(prr status --no-titles 2>/dev/null)\n\n  (( ${#reviews[@]} )) || return 1\n\n  _describe -t reviews 'review' reviews\n}\n\n_prr() {\n  local -a commands\n  local curcontext=\"$curcontext\" state line\n\n  commands=(\n    'get:Get a pull request and begin a review'\n    'edit:Open an existing review in $EDITOR'\n    'submit:Submit a review'\n    'apply:Apply a pull request to the working directory'\n    'status:Print a status summary of all known reviews'\n    'remove:Remove a review'\n  )\n\n  _arguments -C \\\n    '(-h --help)'{-h,--help}'[Print help information]' \\\n    '(-V --version)'{-V,--version}'[Print version information]' \\\n    '--config[Path to config file]:config file:_files' \\\n    '1: :->cmd' \\\n    '*:: :->args'\n\n  case $state in\n    cmd)\n      _describe -t commands 'prr command' commands\n      ;;\n\n    args)\n      case $line[1] in\n        get)\n          _arguments \\\n            '(-h --help)'{-h,--help}'[Print help information]' \\\n            '(-f --force)'{-f,--force}'[Ignore unsubmitted review checks]' \\\n            '--open[Open review file in $EDITOR after download]' \\\n            '1:pull request (eg. danobi/prr/24):'\n          ;;\n\n        edit)\n          _arguments \\\n            '(-h --help)'{-h,--help}'[Print help information]' \\\n            '1:review to edit:_prr_reviews'\n          ;;\n\n        submit)\n          _arguments \\\n            '(-h --help)'{-h,--help}'[Print help information]' \\\n            '(-d --debug)'{-d,--debug}'[Print debug output while submitting]' \\\n            '1:review to submit:_prr_reviews'\n          ;;\n\n        apply)\n          _arguments \\\n            '(-h --help)'{-h,--help}'[Print help information]' \\\n            '1:pull request (eg. danobi/prr/24):'\n          ;;\n\n        status)\n          _arguments \\\n            '(-h --help)'{-h,--help}'[Print help information]' \\\n            '(-n --no-titles)'{-n,--no-titles}'[Hide column titles from output]' \\\n            '1::status argument:'\n          ;;\n\n        remove)\n          _arguments \\\n            '(-h --help)'{-h,--help}'[Print help information]' \\\n            '(-f --force)'{-f,--force}'[Ignore unsubmitted review checks]' \\\n            '(-s --submitted)'{-s,--submitted}'[Remove submitted reviews in addition to provided reviews]' \\\n            '1:review to remove:_prr_reviews'\n          ;;\n      esac\n      ;;\n  esac\n}\n"
  },
  {
    "path": "src/cli.rs",
    "content": "use clap::{Parser, Subcommand};\nuse std::path::PathBuf;\n\n#[derive(Subcommand, Debug)]\npub(crate) enum Command {\n    /// Get a pull request and begin a review\n    Get {\n        /// Ignore unsubmitted review checks\n        #[clap(short, long)]\n        force: bool,\n        /// Pull request to review (eg. `danobi/prr/24`)\n        pr: String,\n        /// Open review file in $EDITOR after download\n        #[clap(long)]\n        open: bool,\n    },\n    /// Open an existing review in $EDITOR\n    Edit {\n        /// Pull request to edit (eg. `danobi/prr/24`)\n        pr: String,\n    },\n    /// Submit a review\n    Submit {\n        /// Pull request to review (eg. `danobi/prr/24`)\n        pr: String,\n        #[clap(short, long)]\n        debug: bool,\n    },\n    /// Apply a pull request to the working directory\n    ///\n    /// This can be useful for building/testing PRs\n    Apply { pr: String },\n    /// Print a status summary of all known reviews\n    Status {\n        /// Hide column titles from output\n        #[clap(short, long)]\n        no_titles: bool,\n    },\n    /// Remove a review\n    Remove {\n        /// Pull requests to remove (eg. `danobi/prr/24`)\n        prs: Vec<String>,\n        /// Ignore unsubmitted review checks\n        #[clap(short, long)]\n        force: bool,\n        /// Remove submitted reviews in addition to provided reviews\n        #[clap(short, long)]\n        submitted: bool,\n    },\n}\n\n#[derive(Parser, Debug)]\n#[clap(version)]\n#[command(name = \"prr\")]\npub struct Cli {\n    /// Path to config file\n    #[clap(long)]\n    pub(crate) config: Option<PathBuf>,\n    #[clap(subcommand)]\n    pub(crate) command: Command,\n}\n"
  },
  {
    "path": "src/main.rs",
    "content": "use std::env;\nuse std::path::{Path, PathBuf};\nuse std::process;\n\nuse anyhow::{bail, Context, Result};\nuse clap::Parser;\n\nmod cli;\nmod parser;\nmod prr;\nmod review;\n\nuse cli::*;\nuse prr::Prr;\n\n/// The name of the local configuration file\npub const LOCAL_CONFIG_FILE_NAME: &str = \".prr.toml\";\n\n/// Returns if exists the config file for the current project\nfn find_project_config_file() -> Option<PathBuf> {\n    env::current_dir().ok().and_then(|mut path| loop {\n        path.push(LOCAL_CONFIG_FILE_NAME);\n        if path.exists() {\n            return Some(path);\n        }\n\n        path.pop();\n        if !path.pop() {\n            return None;\n        }\n    })\n}\n\n/// Opens a file in $EDITOR\nfn open_review(file: &Path) -> Result<()> {\n    // This check should only ever trip for prr-edit\n    if !file.try_exists()? {\n        bail!(\"Review file does not exist yet\");\n    }\n\n    let editor = env::var(\"EDITOR\").context(\"Failed to read $EDITOR\")?;\n    let status = process::Command::new(editor)\n        .arg(file)\n        .status()\n        .context(\"Failed to execute editor process\")?;\n\n    match status.code() {\n        Some(0) => Ok(()),\n        Some(rc) => bail!(\"EDITOR exited unclean: {}\", rc),\n        None => bail!(\"Failed to get EDITOR exit status\"),\n    }\n}\n\n#[tokio::main]\nasync fn main() -> Result<()> {\n    let args = Cli::parse();\n\n    // Figure out where config file is\n    let config_path = match args.config {\n        Some(c) => c,\n        None => {\n            let xdg_dirs = xdg::BaseDirectories::with_prefix(\"prr\")?;\n            xdg_dirs.get_config_file(\"config.toml\")\n        }\n    };\n\n    let prr = Prr::new(&config_path, find_project_config_file())?;\n\n    match args.command {\n        Command::Get { pr, force, open } => {\n            let (owner, repo, pr_num) = prr.parse_pr_str(&pr)?;\n            let review = prr.get_pr(&owner, &repo, pr_num, force).await?;\n            let path = review.path();\n            println!(\"{}\", path.display());\n            if open {\n                open_review(&path).context(\"Failed to open review file\")?;\n            }\n        }\n        Command::Edit { pr } => {\n            let (owner, repo, pr_num) = prr.parse_pr_str(&pr)?;\n            let review = prr.get_review(&owner, &repo, pr_num)?;\n            open_review(&review.path()).context(\"Failed to open review file\")?;\n        }\n        Command::Submit { pr, debug } => {\n            let (owner, repo, pr_num) = prr.parse_pr_str(&pr)?;\n            prr.submit_pr(&owner, &repo, pr_num, debug).await?;\n        }\n        Command::Apply { pr } => {\n            let (owner, repo, pr_num) = prr.parse_pr_str(&pr)?;\n            prr.apply_pr(&owner, &repo, pr_num, Path::new(\"./\"))?;\n        }\n        Command::Status { no_titles } => {\n            prr.print_status(no_titles)?;\n        }\n        Command::Remove {\n            prs,\n            force,\n            submitted,\n        } => {\n            prr.remove(&prs, force, submitted).await?;\n        }\n    }\n\n    Ok(())\n}\n"
  },
  {
    "path": "src/parser.rs",
    "content": "use anyhow::{anyhow, bail, Context, Result};\nuse lazy_static::lazy_static;\nuse regex::Regex;\n\n// Use lazy static to ensure regex is only compiled once\nlazy_static! {\n    // Regex for the start of a hunk. The start of a hunk should look like:\n    //\n    //      `@@ -731,7 +731,7 @@[...]`\n    //\n    static ref HUNK_START: Regex = Regex::new(r\"^@@ -(?P<lstart>\\d+)(?:,(?P<llen>\\d+))? \\+(?P<rstart>\\d+)(?:,(?P<rlen>\\d+))? @@\").unwrap();\n    // Regex for start of a file diff. The start of a file diff should look like:\n    //\n    //      `diff --git a/ch1.txt b/ch1.txt`\n    //\n    static ref DIFF_START: Regex = Regex::new(r\"^diff --git a/.+ b/(?P<new>.+)$\").unwrap();\n}\n\n/// The location of a line\n///\n/// The distinction between Left and Right is important when commenting on\n/// deleted or added lines. A useful way to think about the line location is\n/// the line number a comment should be attached to in the file pre-change (left)\n/// or the file post-change (right)\n#[derive(Debug, PartialEq, Eq, Clone)]\npub enum LineLocation {\n    /// The \"red\"/deleted side of the diff\n    Left(u64),\n    /// The \"green\"/added or \"white\"/existing side of the diff\n    Right(u64),\n}\n\n/// Represents a single inline comment on a review\n#[derive(Debug, PartialEq, Eq)]\npub struct InlineComment {\n    /// File the comment is in\n    ///\n    /// Note that this is the new filename if the file was also moved\n    pub file: String,\n    pub line: LineLocation,\n    /// For a spanned comment, the first line of the span. See `line` for docs on semantics\n    pub start_line: Option<LineLocation>,\n    /// The user-supplied review comment\n    pub comment: String,\n}\n\n/// Represents a single file-level comment on a review\n#[derive(Debug, PartialEq, Eq)]\npub struct FileComment {\n    /// File the comment is in\n    ///\n    /// Note that this is the new filename if the file was also moved\n    pub file: String,\n    /// The user-supplied review comment\n    pub comment: String,\n}\n\n#[derive(Debug, PartialEq, Eq)]\npub enum ReviewAction {\n    Approve,\n    RequestChanges,\n    Comment,\n}\n\n/// Represents a comment of some sort on a review\n#[derive(Debug, PartialEq, Eq)]\npub enum Comment {\n    /// Overall review comment (the summary comment)\n    Review(String),\n    /// An inline comment (attached to a line)\n    Inline(InlineComment),\n    /// Overall approve, reject, or comment on review\n    ReviewAction(ReviewAction),\n    // A file-level comment (attached to the whole file)\n    File(FileComment),\n}\n\n#[derive(Default)]\nstruct StartState {\n    /// Each line of review-level comment is stored as an entry\n    comment: Vec<String>,\n\n    /// Only if there was unquoted content in the Start state we should\n    /// send a review comment.  If there was no unquoted content, there\n    /// was no review comment.\n    had_unquoted_content: bool,\n\n    /// After we have seen the prr directive we assume the review\n    /// comment is done. This allows us to ignore the PR description as\n    /// long as we have the prr directive before it.\n    had_review_action: bool,\n}\n\nstruct FilePreambleState {\n    /// Relative path of the file under diff\n    file: String,\n    /// Each line of file-level comment is stored as an entry\n    comment: Vec<String>,\n}\n\n#[derive(Clone)]\nstruct FileDiffState {\n    /// Relative path of the file under diff\n    file: String,\n    /// Current left line position. See `LineLocation` for docs on semantics of `line`\n    left_line: u64,\n    /// Current right line position. See `LineLocation` for docs on semantics of `line`\n    right_line: u64,\n    /// Current line position\n    line: LineLocation,\n    /// First line of the span. See `LineLocation` for docs on\n    /// semantics of `line`\n    span_start_line: Option<LineLocation>,\n}\n\nstruct SpanStartOrCommentState {\n    /// State of the file diff before we entered this state\n    file_diff_state: FileDiffState,\n}\n\nstruct CommentState {\n    /// State of the file diff before we entered comment processing\n    file_diff_state: FileDiffState,\n    /// Each line of comment is stored as an entry\n    comment: Vec<String>,\n}\n\n/// State machine states\n///\n/// Only the following state transitions are valid:\n///\n///                                  +---------------+\n///                                  |               |\n///                                  v               |\n///     Start -> FilePreamble -> FileDiff -> StartSpanOrComment -> Comment\n///                 ^    ^        |  | ^                            ^   |\n///                 |    |        |  | |                            |   |\n///                 |    +--------+--+-+----------------------------+---+\n///                 |             |  |                              |\n///                 +-------------+  +------------------------------+\n///\nenum State {\n    /// Starting state\n    Start(StartState),\n    /// The `diff --git a/...` preamble as well as the lines before the first hunk\n    FilePreamble(FilePreambleState),\n    /// We are inside the diff of a file\n    FileDiff(FileDiffState),\n    /// We are either the start of a span or the beginning of a comment\n    ///\n    /// The uncertainty comes from the fact that comments typically begin with one\n    /// or more newlines\n    SpanStartOrComment(SpanStartOrCommentState),\n    /// We are inside a user-supplied comment\n    Comment(CommentState),\n}\n\n/// Simple state machine to parse a review file\npub struct ReviewParser {\n    state: State,\n}\n\nfn is_diff_header(s: &str) -> bool {\n    s.starts_with(\"diff --git \")\n}\n\n/// Parses lines in the form of `@prr DIRECTIVE`\n///\n/// Returns Some(directive) if found, else None\nfn is_prr_directive(s: &str) -> Option<&str> {\n    let t = s.trim();\n    if let Some(d) = t.strip_prefix(\"@prr \") {\n        Some(d)\n    } else {\n        None\n    }\n}\n\n/// Parses the new filename out of a diff header\nfn parse_diff_header(line: &str) -> Result<String> {\n    if let Some(captures) = DIFF_START.captures(line) {\n        let new: &str = captures.name(\"new\").unwrap().as_str();\n\n        Ok(new.trim().to_owned())\n    } else {\n        Err(anyhow!(\"Invalid diff header: could not parse\"))\n    }\n}\n\n/// Parses the starting left & right lines out of the hunk start\nfn parse_hunk_start(line: &str) -> Result<Option<(u64, u64)>> {\n    if let Some(captures) = HUNK_START.captures(line) {\n        let hunk_start_line_left: u64 = captures\n            .name(\"lstart\")\n            .unwrap()\n            .as_str()\n            .parse()\n            .context(\"Failed to parse hunk start left line\")?;\n\n        let hunk_start_line_right: u64 = captures\n            .name(\"rstart\")\n            .map(|s| s.as_str())\n            .unwrap_or_else(|| {\n                if hunk_start_line_left == 0 {\n                    \"0\"\n                } else {\n                    unreachable!(\n                        \"Unexpected non-zero left-hand-side of git diff header. Expected 0.\"\n                    )\n                }\n            })\n            .parse()\n            .context(\"Failed to parse hunk start right line\")?;\n        // Note that for newly added files or deleted files, both sides\n        // of the line info might be zero. `saturating_*` operations must hence\n        // be used for the following subtraction to be safe.\n\n        return Ok(Some((hunk_start_line_left, hunk_start_line_right)));\n    }\n\n    Ok(None)\n}\n\nfn is_left_line(line: &str) -> bool {\n    line.starts_with('-')\n}\n\n/// Given the current line and line positions, returns what the next line positions should be\nfn get_next_lines(line: &str, left: u64, right: u64) -> (u64, u64) {\n    if is_left_line(line) {\n        (left + 1, right)\n    } else if line.starts_with('+') {\n        (left, right + 1)\n    } else {\n        (left + 1, right + 1)\n    }\n}\n\nimpl ReviewParser {\n    pub fn new() -> ReviewParser {\n        ReviewParser {\n            state: State::Start(StartState::default()),\n        }\n    }\n\n    pub fn parse_line(&mut self, mut line: &str) -> Result<Option<Comment>> {\n        let is_quoted = line.starts_with('>');\n        if is_quoted {\n            if let Some(stripped) = line.strip_prefix(\"> \") {\n                line = stripped;\n            } else if let Some(stripped) = line.strip_prefix('>') {\n                line = stripped;\n            }\n        }\n\n        match &mut self.state {\n            // we are adding all the lines, regardless if they are\n            // quoted are not because they may be interleaving the\n            // PR description as long as we haven't seen the prr\n            // directive. Once the diff header starts, we determine\n            // whether or not we should send the review comment. The\n            // comment should only be sent, if we ever encountered a\n            // non-quoted string in this state.\n            State::Start(state) => {\n                if is_quoted {\n                    if !is_diff_header(line) {\n                        if !state.had_review_action {\n                            state.comment.push(\"> \".to_owned() + line);\n                        }\n\n                        return Ok(None);\n                    }\n\n                    let mut review_comment = None;\n                    if state.had_unquoted_content {\n                        review_comment =\n                            Some(Comment::Review(state.comment.join(\"\\n\").trim().to_string()));\n                    }\n\n                    self.state = State::FilePreamble(FilePreambleState {\n                        file: parse_diff_header(line)?,\n                        comment: vec![],\n                    });\n\n                    return Ok(review_comment);\n                } else if let Some(d) = is_prr_directive(line) {\n                    state.had_review_action = true;\n\n                    return match d {\n                        \"approve\" => Ok(Some(Comment::ReviewAction(ReviewAction::Approve))),\n                        \"reject\" => Ok(Some(Comment::ReviewAction(ReviewAction::RequestChanges))),\n                        \"comment\" => Ok(Some(Comment::ReviewAction(ReviewAction::Comment))),\n                        _ => bail!(\"Unknown @prr directive: {}\", d),\n                    };\n                } else {\n                    state.comment.push(line.to_owned());\n                    if !state.had_unquoted_content {\n                        state.had_unquoted_content = true\n                    }\n                }\n\n                Ok(None)\n            }\n            State::FilePreamble(state) => {\n                if !is_quoted {\n                    state.comment.push(line.to_owned());\n                }\n\n                if is_diff_header(line) {\n                    self.state = State::FilePreamble(FilePreambleState {\n                        file: parse_diff_header(line)?,\n                        comment: vec![],\n                    });\n                    return Ok(None);\n                }\n\n                if let Some((mut left_start, mut right_start)) = parse_hunk_start(line)? {\n                    // Subtract 1 b/c this line is before the actual diff hunk\n                    left_start = left_start.saturating_sub(1);\n                    right_start = right_start.saturating_sub(1);\n\n                    // Finish up our file-level comment if we had one\n                    let comment = if !state.comment.is_empty() {\n                        Some(Comment::File(FileComment {\n                            file: state.file.to_owned(),\n                            comment: state.comment.join(\"\\n\").trim().to_string(),\n                        }))\n                    } else {\n                        None\n                    };\n\n                    self.state = State::FileDiff(FileDiffState {\n                        file: state.file.to_owned(),\n                        left_line: left_start,\n                        right_line: right_start,\n                        line: if is_left_line(line) {\n                            LineLocation::Left(left_start)\n                        } else {\n                            LineLocation::Right(right_start)\n                        },\n                        span_start_line: None,\n                    });\n\n                    if let Some(comment) = comment {\n                        return Ok(Some(comment));\n                    }\n                }\n\n                Ok(None)\n            }\n            State::FileDiff(state) => {\n                if is_quoted {\n                    if is_diff_header(line) {\n                        if state.span_start_line.is_some() {\n                            bail!(\n                                \"Detected span that was not terminated with a comment, file: {}\",\n                                state.file\n                            );\n                        }\n\n                        self.state = State::FilePreamble(FilePreambleState {\n                            file: parse_diff_header(line)?,\n                            comment: vec![],\n                        });\n                    } else if let Some((mut left_start, mut right_start)) = parse_hunk_start(line)?\n                    {\n                        if state.span_start_line.is_some() {\n                            bail!(\"Detected cross chunk span, file: {}\", state.file);\n                        }\n\n                        // Subtract 1 b/c this line is before the actual diff hunk\n                        left_start = left_start.saturating_sub(1);\n                        right_start = right_start.saturating_sub(1);\n\n                        state.left_line = left_start;\n                        state.right_line = right_start;\n                        if is_left_line(line) {\n                            state.line = LineLocation::Left(left_start);\n                        } else {\n                            state.line = LineLocation::Right(right_start);\n                        }\n                    } else {\n                        let (next_left, next_right) =\n                            get_next_lines(line, state.left_line, state.right_line);\n                        state.left_line = next_left;\n                        state.right_line = next_right;\n                        if is_left_line(line) {\n                            state.line = LineLocation::Left(next_left);\n                        } else {\n                            state.line = LineLocation::Right(next_right);\n                        }\n                    }\n\n                    return Ok(None);\n                }\n\n                // Now that we know this line is not quoted, there's only two options:\n                // 1) beginning of a spanned comment\n                // 2) beginning of a comment\n                if line.trim().is_empty() {\n                    self.state = State::SpanStartOrComment(SpanStartOrCommentState {\n                        file_diff_state: state.clone(),\n                    })\n                } else {\n                    self.state = State::Comment(CommentState {\n                        file_diff_state: state.clone(),\n                        comment: vec![line.to_owned()],\n                    })\n                }\n\n                Ok(None)\n            }\n            State::SpanStartOrComment(state) => {\n                if is_quoted {\n                    if state.file_diff_state.span_start_line.is_some() {\n                        bail!(\n                            \"Detected span that was not terminated with a comment, file: {}\",\n                            state.file_diff_state.file\n                        );\n                    }\n\n                    // Back to the original file diff\n                    let (next_left, next_right) = get_next_lines(\n                        line,\n                        state.file_diff_state.left_line,\n                        state.file_diff_state.right_line,\n                    );\n                    self.state = State::FileDiff(FileDiffState {\n                        file: state.file_diff_state.file.to_owned(),\n                        left_line: next_left,\n                        right_line: next_right,\n                        line: if is_left_line(line) {\n                            LineLocation::Left(next_left)\n                        } else {\n                            LineLocation::Right(next_right)\n                        },\n                        span_start_line: Some(if is_left_line(line) {\n                            LineLocation::Left(next_left)\n                        } else {\n                            LineLocation::Right(next_right)\n                        }),\n                    });\n\n                    Ok(None)\n                } else if line.trim().is_empty() {\n                    // In a multi-line span spart\n                    Ok(None)\n                } else {\n                    // In a comment now\n                    self.state = State::Comment(CommentState {\n                        file_diff_state: state.file_diff_state.clone(),\n                        comment: vec![line.to_owned()],\n                    });\n\n                    Ok(None)\n                }\n            }\n            State::Comment(state) => {\n                if is_quoted {\n                    let comment = Comment::Inline(InlineComment {\n                        file: state.file_diff_state.file.clone(),\n                        line: state.file_diff_state.line.clone(),\n                        start_line: state.file_diff_state.span_start_line.clone(),\n                        comment: state.comment.join(\"\\n\").trim_end().to_string(),\n                    });\n\n                    if is_diff_header(line) {\n                        self.state = State::FilePreamble(FilePreambleState {\n                            file: parse_diff_header(line)?,\n                            comment: vec![],\n                        });\n                    } else {\n                        let (next_left, next_right) = get_next_lines(\n                            line,\n                            state.file_diff_state.left_line,\n                            state.file_diff_state.right_line,\n                        );\n                        self.state = State::FileDiff(FileDiffState {\n                            file: state.file_diff_state.file.to_owned(),\n                            left_line: next_left,\n                            right_line: next_right,\n                            line: if is_left_line(line) {\n                                LineLocation::Left(next_left)\n                            } else {\n                                LineLocation::Right(next_right)\n                            },\n                            span_start_line: None,\n                        });\n                    }\n\n                    return Ok(Some(comment));\n                }\n\n                state.comment.push(line.to_owned());\n                Ok(None)\n            }\n        }\n    }\n\n    pub fn finish(self) -> Option<Comment> {\n        match self.state {\n            State::Comment(state) => Some(Comment::Inline(InlineComment {\n                file: state.file_diff_state.file,\n                line: state.file_diff_state.line,\n                start_line: state.file_diff_state.span_start_line,\n                comment: state.comment.join(\"\\n\").trim_end().to_string(),\n            })),\n            _ => None,\n        }\n    }\n}\n\n#[cfg(test)]\nmod tests {\n    use super::*;\n\n    fn test_fail(input: &str) {\n        let mut parser = ReviewParser::new();\n\n        for line in input.lines() {\n            if parser.parse_line(line).is_err() {\n                return;\n            }\n        }\n\n        panic!(\"Parser succeeded when it should have failed\");\n    }\n\n    fn test(input: &str, expected: &[Comment]) {\n        let mut parser = ReviewParser::new();\n        let mut comments = Vec::new();\n\n        for line in input.lines() {\n            if let Some(c) = parser.parse_line(line).unwrap() {\n                comments.push(c);\n            }\n        }\n\n        if let Some(c) = parser.finish() {\n            comments.push(c);\n        }\n\n        assert!(\n            comments == expected,\n            \"Parsed different comments than expected.\\n Got: {:#?}\\nExpected: {:#?}\",\n            comments,\n            expected\n        );\n    }\n\n    #[test]\n    fn single_comment() {\n        let input = include_str!(\"../testdata/single_comment\");\n        let expected = vec![Comment::Inline(InlineComment {\n            file: \"libbpf-cargo/src/btf/btf.rs\".to_string(),\n            line: LineLocation::Right(734),\n            start_line: Some(LineLocation::Right(731)),\n            comment: \"Comment 1\".to_string(),\n        })];\n\n        test(input, &expected);\n    }\n\n    #[test]\n    fn approve_review() {\n        let input = include_str!(\"../testdata/approve_review\");\n        let expected = vec![\n            Comment::ReviewAction(ReviewAction::Approve),\n            Comment::Inline(InlineComment {\n                file: \"libbpf-cargo/src/btf/btf.rs\".to_string(),\n                line: LineLocation::Right(734),\n                start_line: Some(LineLocation::Right(731)),\n                comment: \"Comment 1\".to_string(),\n            }),\n        ];\n\n        test(input, &expected);\n    }\n\n    #[test]\n    fn reject_review() {\n        let input = include_str!(\"../testdata/reject_review\");\n        let expected = vec![\n            Comment::ReviewAction(ReviewAction::RequestChanges),\n            Comment::Inline(InlineComment {\n                file: \"libbpf-cargo/src/btf/btf.rs\".to_string(),\n                line: LineLocation::Right(734),\n                start_line: Some(LineLocation::Right(731)),\n                comment: \"Comment 1\".to_string(),\n            }),\n        ];\n\n        test(input, &expected);\n    }\n\n    #[test]\n    fn review_comment() {\n        let input = include_str!(\"../testdata/review_comment\");\n        let expected = vec![\n            Comment::Review(\"Review comment\".to_string()),\n            Comment::Inline(InlineComment {\n                file: \"libbpf-cargo/src/btf/btf.rs\".to_string(),\n                line: LineLocation::Right(734),\n                start_line: Some(LineLocation::Right(731)),\n                comment: \"Comment 1\".to_string(),\n            }),\n        ];\n\n        test(input, &expected);\n    }\n\n    #[test]\n    fn file_comment() {\n        let input = include_str!(\"../testdata/file_comment\");\n        let expected = vec![Comment::File(FileComment {\n            file: \"libbpf-cargo/src/btf/btf.rs\".to_string(),\n            comment: \"This is a file-level comment!\".to_string(),\n        })];\n\n        test(input, &expected);\n    }\n\n    #[test]\n    fn review_comment_whitespace() {\n        let input = include_str!(\"../testdata/review_comment_whitespace\");\n        let expected = vec![\n            Comment::ReviewAction(ReviewAction::Approve),\n            Comment::Review(\"Review comment\".to_string()),\n        ];\n\n        test(input, &expected);\n    }\n\n    #[test]\n    fn multiline_comment() {\n        let input = include_str!(\"../testdata/multiline_comment\");\n        let expected = vec![Comment::Inline(InlineComment {\n            file: \"libbpf-cargo/src/btf/btf.rs\".to_string(),\n            line: LineLocation::Right(736),\n            start_line: None,\n            comment: \"Comment line 1\\nComment line 2\\n\\nComment line 4\".to_string(),\n        })];\n\n        test(input, &expected);\n    }\n\n    #[test]\n    fn back_to_back_span() {\n        let input = include_str!(\"../testdata/back_to_back_span\");\n        let expected = vec![\n            Comment::Inline(InlineComment {\n                file: \"libbpf-cargo/src/btf/btf.rs\".to_string(),\n                line: LineLocation::Right(734),\n                start_line: Some(LineLocation::Right(731)),\n                comment: \"Comment 1\".to_string(),\n            }),\n            Comment::Inline(InlineComment {\n                file: \"libbpf-cargo/src/btf/btf.rs\".to_string(),\n                line: LineLocation::Right(737),\n                start_line: None,\n                comment: \"Comment 2\".to_string(),\n            }),\n        ];\n\n        test(input, &expected);\n    }\n\n    #[test]\n    fn multiple_files() {\n        let input = include_str!(\"../testdata/multiple_files\");\n        let expected = vec![\n            Comment::Inline(InlineComment {\n                file: \"libbpf-cargo/src/btf/btf.rs\".to_string(),\n                line: LineLocation::Right(734),\n                start_line: None,\n                comment: \"Comment 1\".to_string(),\n            }),\n            Comment::Inline(InlineComment {\n                file: \"libbpf-cargo/src/test.rs\".to_string(),\n                line: LineLocation::Right(2159),\n                start_line: None,\n                comment: \"Comment 2\".to_string(),\n            }),\n        ];\n\n        test(input, &expected);\n    }\n\n    #[test]\n    fn hunk_start_no_trailing_whitespace() {\n        let input = include_str!(\"../testdata/hunk_start_no_trailing_whitespace\");\n        let expected = vec![Comment::Inline(InlineComment {\n            file: \"ch5.txt\".to_string(),\n            line: LineLocation::Right(7),\n            start_line: None,\n            comment: \"Great passage\".to_string(),\n        })];\n\n        test(input, &expected);\n    }\n\n    #[test]\n    fn add_oneliner() {\n        let input = include_str!(\"../testdata/add_oneliner\");\n        let expected = vec![\n            Comment::Inline(InlineComment {\n                file: \"foo.rs\".to_string(),\n                line: LineLocation::Right(0),\n                start_line: None,\n                comment: \"Comment 1\".to_string(),\n            }),\n            Comment::Inline(InlineComment {\n                file: \"foo.rs\".to_string(),\n                line: LineLocation::Right(1),\n                start_line: None,\n                comment: \"Comment 2\".to_string(),\n            }),\n        ];\n\n        test(input, &expected);\n    }\n\n    #[test]\n    fn deleted_file() {\n        let input = include_str!(\"../testdata/deleted_file\");\n        let expected = vec![Comment::Inline(InlineComment {\n            file: \"ch1.txt\".to_string(),\n            line: LineLocation::Left(58),\n            start_line: Some(LineLocation::Left(1)),\n            comment: \"Comment 1\".to_string(),\n        })];\n\n        test(input, &expected);\n    }\n\n    #[test]\n    fn empty_file() {\n        let input = include_str!(\"../testdata/empty_file\");\n        let expected = vec![Comment::Inline(InlineComment {\n            file: \"libbpf-cargo/src/test.rs\".to_string(),\n            line: LineLocation::Right(2159),\n            start_line: None,\n            comment: \"Comment\".to_string(),\n        })];\n\n        test(input, &expected);\n    }\n\n    #[test]\n    fn trailing_comment() {\n        let input = include_str!(\"../testdata/trailing_comment\");\n        let expected = vec![Comment::Inline(InlineComment {\n            file: \"ch1.txt\".to_string(),\n            line: LineLocation::Left(59),\n            start_line: Some(LineLocation::Left(1)),\n            comment: \"Comment 1\".to_string(),\n        })];\n\n        test(input, &expected);\n    }\n\n    #[test]\n    /// https://github.com/danobi/prr/issues/3\n    fn spaces_in_filename() {\n        let input = include_str!(\"../testdata/spaces_in_filename\");\n        let expected = vec![Comment::Inline(InlineComment {\n            file: \"build/scripts/grafana/provisioning/dashboards/Docker Prometheus Monitoring-1571332751387.json\".to_string(),\n            line: LineLocation::Right(2),\n            start_line: None,\n            comment: \"foo\".to_string(),\n        })];\n\n        test(input, &expected);\n    }\n\n    #[test]\n    fn unterminated_span() {\n        let input = include_str!(\"../testdata/unterminated_span\");\n        test_fail(input);\n    }\n\n    #[test]\n    fn cross_file_span_ignored() {\n        let input = include_str!(\"../testdata/cross_file_span_ignored\");\n        test_fail(input);\n    }\n\n    #[test]\n    fn unterminated_back_to_back_span() {\n        let input = include_str!(\"../testdata/unterminated_back_to_back_span\");\n        test_fail(input);\n    }\n\n    #[test]\n    fn cross_hunk_span() {\n        let input = include_str!(\"../testdata/cross_hunk_span\");\n        test_fail(input);\n    }\n\n    #[test]\n    fn unknown_directive() {\n        let input = include_str!(\"../testdata/unknown_directive\");\n        test_fail(input);\n    }\n\n    #[test]\n    fn hunk_oneliner_regex() {\n        let captures = HUNK_START\n            .captures(\"@@ -0,0 +1 @@\")\n            .expect(\"Must match regex.\");\n        assert_eq!(captures.name(\"rstart\").unwrap().as_str(), \"1\");\n        assert!(captures.name(\"rlen\").is_none());\n        assert_eq!(captures.name(\"lstart\").unwrap().as_str(), \"0\");\n        assert_eq!(captures.name(\"llen\").unwrap().as_str(), \"0\");\n    }\n\n    #[test]\n    fn hunk_normal_regex() {\n        let captures = HUNK_START\n            .captures(\"@@ -0,7 +0,1 @@\")\n            .expect(\"Must match regex.\");\n        assert_eq!(captures.name(\"rstart\").unwrap().as_str(), \"0\");\n        assert_eq!(captures.name(\"rlen\").unwrap().as_str(), \"1\");\n        assert_eq!(captures.name(\"lstart\").unwrap().as_str(), \"0\");\n        assert_eq!(captures.name(\"llen\").unwrap().as_str(), \"7\");\n    }\n\n    #[test]\n    fn hunk_only_one_line_on_each_side() {\n        let captures = HUNK_START\n            .captures(\"@@ -5 +5 @@\")\n            .expect(\"Must match regex.\");\n        assert_eq!(captures.name(\"rstart\").unwrap().as_str(), \"5\");\n        assert!(captures.name(\"rlen\").is_none());\n        assert_eq!(captures.name(\"lstart\").unwrap().as_str(), \"5\");\n        assert!(captures.name(\"llen\").is_none());\n    }\n\n    #[test]\n    fn inline_and_review_comments_with_pr_description_present() {\n        let input = include_str!(\"../testdata/inline_and_review_comments_with_pr_description\");\n        let expected = vec![\n            Comment::ReviewAction(ReviewAction::RequestChanges),\n            Comment::Review(\"Not necessary.\".to_string()),\n            Comment::Inline(InlineComment {\n                file: \"README.md\".to_string(),\n                line: LineLocation::Right(2),\n                start_line: None,\n                comment: \"Doesn't seem necessary ...\".to_string(),\n            }),\n        ];\n\n        test(input, &expected);\n    }\n\n    #[test]\n    fn review_comments_interleaved_with_pr_description() {\n        let input = include_str!(\"../testdata/review_comments_interleaved_with_pr_description\");\n        let expected = vec![\n            Comment::ReviewAction(ReviewAction::RequestChanges),\n            Comment::Review(\"Not necessary.\\n\\n\\n> This is just for testing purposes.\\n\\nThis might be fine or not.\".to_string()),\n            Comment::Inline(InlineComment {\n                file: \"README.md\".to_string(),\n                line: LineLocation::Right(2),\n                start_line: None,\n                comment: \"Doesn't seem necessary ...\".to_string(),\n            }),\n        ];\n\n        test(input, &expected);\n    }\n}\n"
  },
  {
    "path": "src/prr.rs",
    "content": "use std::env;\nuse std::fs;\nuse std::path::{Path, PathBuf};\n\nuse anyhow::{anyhow, bail, Context, Result};\nuse git2::{ApplyLocation, Diff, Repository, StatusOptions};\nuse http::{StatusCode, Uri};\nuse lazy_static::lazy_static;\nuse octocrab::Octocrab;\nuse prettytable::{format, row, Table};\nuse serde_derive::Deserialize;\nuse serde_json::{json, Value};\n\nuse crate::parser::{FileComment, LineLocation, ReviewAction};\nuse crate::review::{get_all_existing, Review, ReviewStatus};\nuse regex::Regex;\n\n// Use lazy static to ensure regex is only compiled once\nlazy_static! {\n    // Regex for short input. Example:\n    //\n    //      danobi/prr-test-repo/6\n    //\n    static ref SHORT: Regex = Regex::new(r\"^(?P<org>[\\w\\-_\\.]+)/(?P<repo>[\\w\\-_\\.]+)/(?P<pr_num>\\d+)\").unwrap();\n}\n\nconst GITHUB_BASE_URL: &str = \"https://api.github.com\";\n\n/// Resolves a GitHub token from either environment variables or config value.\n///\n/// If a config token is provided and not empty, returns the config token as-is.\n/// If no config token is provided or it's empty, we check standard GitHub environment variables\n/// in order of precedence as per https://cli.github.com/manual/gh_help_environment:\n/// GH_TOKEN, GITHUB_TOKEN, GH_ENTERPRISE_TOKEN, GITHUB_ENTERPRISE_TOKEN.\n/// If none are found, returns an error.\nfn resolve_github_token<F>(config_token: Option<&str>, env_lookup: F) -> Result<String>\nwhere\n    F: for<'a> Fn(&'a str) -> Result<String, std::env::VarError>,\n{\n    if let Some(token) = config_token {\n        if !token.is_empty() {\n            return Ok(token.to_string());\n        }\n    }\n\n    let known_env_vars = [\n        \"GH_TOKEN\",\n        \"GITHUB_TOKEN\",\n        \"GH_ENTERPRISE_TOKEN\",\n        \"GITHUB_ENTERPRISE_TOKEN\",\n    ];\n\n    for env_var in &known_env_vars {\n        if let Ok(token) = env_lookup(env_var) {\n            if token.is_empty() {\n                bail!(\"Environment variable '{}' located but is empty\", env_var);\n            }\n            return Ok(token);\n        }\n    }\n\n    bail!(\"No GitHub token found in config or environment variables\")\n}\n\n#[derive(Debug, Deserialize)]\nstruct PrrConfig {\n    /// GH personal token\n    token: Option<String>,\n    /// Directory to place review files\n    workdir: Option<String>,\n    /// Github URL\n    ///\n    /// Useful for enterprise instances with custom URLs\n    url: Option<String>,\n\n    /// Activate experimental PR metadata support. Currently this option\n    /// just activates downloading the actual PR description in addition\n    /// to the diff.\n    #[serde(default)]\n    activate_pr_metadata_experiment: bool,\n}\n\n#[derive(Debug, Deserialize)]\nstruct PrrLocalConfig {\n    /// Default url for this current project\n    repository: Option<String>,\n    /// Local workdir override\n    workdir: Option<String>,\n}\n\n#[derive(Debug, Deserialize)]\nstruct Config {\n    prr: PrrConfig,\n    local: Option<PrrLocalConfig>,\n}\n\n/// Main struct that coordinates all business logic and talks to GH\npub struct Prr {\n    /// User config\n    config: Config,\n    /// Path to local config file\n    local_config: Option<PathBuf>,\n    /// Instantiated github client\n    crab: Octocrab,\n}\n\nimpl Config {\n    /// Returns GH URL to use. Sanitizes if necessary.\n    fn url(&self) -> String {\n        match &self.prr.url {\n            Some(url) => {\n                // Custom URLs must have a trailing `/`. Otherwise the custom\n                // path can be truncated.\n                //\n                // See: https://docs.rs/reqwest/0.11.22/reqwest/struct.Url.html#method.join\n                let mut sanitized = url.clone();\n                if !url.ends_with('/') {\n                    sanitized.push('/');\n                }\n\n                sanitized\n            }\n            None => GITHUB_BASE_URL.into(),\n        }\n    }\n}\n\nimpl Prr {\n    /// Create a new Prr object using the main config and/or the local config.\n    /// If a local config has the `[prr]` section use this one instead of the main config.\n    /// If `[prr]` section is not defined merge the local config with the main local.\n    /// If local config file does not exist, use only the main config.\n    ///\n    /// A `[prr]` redefinition must be complete; if not, panics with a\n    /// `redefinition of table `prr` for key `prr` at ...`\n    pub fn new(config_path: &Path, local_config_path: Option<PathBuf>) -> Result<Prr> {\n        let config_contents = fs::read_to_string(config_path).context(\"Failed to read config\")?;\n        let local_config_contents = if let Some(project_config_path) = &local_config_path {\n            fs::read_to_string(project_config_path).context(\"Failed to read local config\")?\n        } else {\n            String::new()\n        };\n\n        let override_config = toml::from_str::<Config>(&local_config_contents);\n\n        let config: Config = match override_config {\n            // If `override_config` does not raise an error, use this one as config.\n            Ok(config) => config,\n            // Else merge the two config contents.\n            Err(_) => {\n                let contents = format!(\"{}\\n{}\", config_contents, local_config_contents);\n\n                toml::from_str::<Config>(&contents)?\n            }\n        };\n\n        let token = resolve_github_token(config.prr.token.as_deref(), |var| env::var(var))\n            .context(\"Failed to locate GitHub token\")?;\n\n        let octocrab = Octocrab::builder()\n            .personal_token(token)\n            .base_uri(config.url())\n            .context(\"Failed to parse github base URL\")?\n            .build()\n            .context(\"Failed to create GH client\")?;\n\n        Ok(Prr {\n            config,\n            local_config: local_config_path,\n            crab: octocrab,\n        })\n    }\n\n    /// Returns path to prr workdir\n    fn workdir(&self) -> Result<PathBuf> {\n        // Try local config first\n        if let Some(lcfg) = &self.config.local {\n            // Can't have a parsed local config without a stored path\n            debug_assert!(self.local_config.is_some());\n\n            if let Some(wd) = &lcfg.workdir {\n                if wd.starts_with('~') {\n                    bail!(\"Invalid workdir={wd}: may not use '~'\");\n                }\n\n                // We allow resolving relative paths in local config relative to the local config file\n                let mut resolved_wd = PathBuf::new();\n                // No parent seems impossible but I think it's correct to not push anything\n                if let Some(local_dir) = self.local_config.as_ref().unwrap().parent() {\n                    resolved_wd.push(local_dir);\n                }\n                // NB: pushing an absolute path overwrites the PathBuf\n                resolved_wd.push(wd);\n\n                return Ok(resolved_wd);\n            }\n        }\n\n        // Now try global config\n        if let Some(wd) = &self.config.prr.workdir {\n            if wd.starts_with('~') {\n                bail!(\"Invalid workdir={wd}: may not use '~'\");\n            }\n\n            let p = Path::new(wd).to_path_buf();\n            if !p.is_absolute() {\n                bail!(\"Invalid workdir={wd}: must be absolute path\");\n            }\n\n            return Ok(p);\n        }\n\n        // Default workdir\n        let xdg_dirs = xdg::BaseDirectories::with_prefix(\"prr\")?;\n        Ok(xdg_dirs.get_data_home())\n    }\n\n    pub fn is_pr_metadata_experiment_active(&self) -> bool {\n        self.config.prr.activate_pr_metadata_experiment\n    }\n\n    /// Parses a PR string in the form of `danobi/prr/24` and returns\n    /// a tuple (\"danobi\", \"prr\", 24) or an error if string is malformed.\n    pub fn parse_pr_str(&self, s: &str) -> Result<(String, String, u64)> {\n        let repo = if let Some(local_config) = &self.config.local {\n            if let Some(url) = &local_config.repository {\n                if url.ends_with('/') {\n                    format!(\"{}{}\", url, s)\n                } else {\n                    format!(\"{}/{}\", url, s)\n                }\n            } else {\n                s.to_string()\n            }\n        } else {\n            s.to_string()\n        };\n\n        if let Some(captures) = SHORT.captures(&repo) {\n            let owner = captures.name(\"org\").unwrap().as_str().to_owned();\n            let repo = captures.name(\"repo\").unwrap().as_str().to_owned();\n            let pr_nr: u64 = captures\n                .name(\"pr_num\")\n                .unwrap()\n                .as_str()\n                .parse()\n                .context(\"Failed to parse pr number\")?;\n\n            return Ok((owner, repo, pr_nr));\n        }\n\n        if repo.starts_with(\"http\") || repo.contains(\"://\") {\n            let uri: Uri = repo.parse().context(\"Failed to parse URL\")?;\n\n            let path = uri.path().trim_start_matches('/');\n            let segments: Vec<_> = path.split('/').collect();\n\n            if segments.len() >= 4 && segments[2] == \"pull\" {\n                let pr_num = segments[3]\n                    .parse::<u64>()\n                    .context(\"Failed to parse PR number\")?;\n\n                return Ok((segments[0].to_string(), segments[1].to_string(), pr_num));\n            }\n        }\n\n        bail!(\"Invalid PR ref format\")\n    }\n\n    /// Gets a new review from the internet and writes it to the filesystem\n    pub async fn get_pr(\n        &self,\n        owner: &str,\n        repo: &str,\n        pr_num: u64,\n        force: bool,\n    ) -> Result<Review> {\n        let pr_handler = self.crab.pulls(owner, repo);\n\n        let diff = pr_handler\n            .get_diff(pr_num)\n            .await\n            .context(\"Failed to fetch diff\")?;\n\n        let pr = pr_handler.get(pr_num).await.context(\"Failed to fetch pr\")?;\n        let commit_id = pr.head.sha;\n\n        let mut pr_description = None;\n        if self.is_pr_metadata_experiment_active() {\n            pr_description = Some(pr.body.unwrap_or(\"\".to_string()));\n        }\n\n        Review::new(\n            &self.workdir()?,\n            diff,\n            owner,\n            repo,\n            pr_description,\n            pr_num,\n            commit_id,\n            force,\n        )\n    }\n\n    /// Gets an existing review from the filesystem\n    pub fn get_review(&self, owner: &str, repo: &str, pr_num: u64) -> Result<Review> {\n        let workdir = self.workdir()?;\n        Ok(Review::new_existing(&workdir, owner, repo, pr_num))\n    }\n\n    pub async fn submit_pr(&self, owner: &str, repo: &str, pr_num: u64, debug: bool) -> Result<()> {\n        let review = Review::new_existing(&self.workdir()?, owner, repo, pr_num);\n        let (review_action, review_comment, inline_comments, file_comments) = review.comments()?;\n\n        if review_comment.is_empty()\n            && inline_comments.is_empty()\n            && review_action != ReviewAction::Approve\n        {\n            bail!(\"No review comments\");\n        }\n\n        let mut body = json!({\n            \"body\": review_comment,\n            \"event\": match review_action {\n                ReviewAction::Approve => \"APPROVE\",\n                ReviewAction::RequestChanges => \"REQUEST_CHANGES\",\n                ReviewAction::Comment => \"COMMENT\"\n            },\n            \"comments\": inline_comments\n                .iter()\n                .map(|c| {\n                    let (line, side) = match c.line {\n                        LineLocation::Left(line) => (line, \"LEFT\"),\n                        LineLocation::Right(line) => (line, \"RIGHT\"),\n                    };\n\n                    let mut json_comment = json!({\n                        \"path\": c.file,\n                        \"line\": line,\n                        \"body\": c.comment,\n                        \"side\": side,\n                    });\n                    if let Some(start_line) = &c.start_line {\n                        let (line, side) = match start_line {\n                            LineLocation::Left(line) => (line, \"LEFT\"),\n                            LineLocation::Right(line) => (line, \"RIGHT\"),\n                        };\n\n                        json_comment[\"start_line\"] = (*line).into();\n                        json_comment[\"start_side\"] = side.into();\n                    }\n\n                    json_comment\n                })\n                .collect::<Vec<Value>>(),\n        });\n\n        let commit = review.commit_id()?;\n        if let Some(id) = &commit {\n            if let serde_json::Value::Object(ref mut obj) = body {\n                obj.insert(\"commit_id\".to_string(), json!(id));\n            }\n        } else if !file_comments.is_empty() {\n            bail!(\n                \"Metadata contained no commit_id, but it's required to leave file-level comments\"\n            );\n        }\n\n        if debug {\n            println!(\"{}\", serde_json::to_string_pretty(&body)?);\n        }\n        self.submit_review(&review, owner, repo, pr_num, &body)\n            .await?;\n\n        for fc in &file_comments {\n            self.submit_file_comment(owner, repo, pr_num, commit.as_ref().unwrap(), fc)\n                .await?\n        }\n\n        Ok(())\n    }\n\n    async fn submit_review(\n        &self,\n        review: &Review,\n        owner: &str,\n        repo: &str,\n        pr_num: u64,\n        body: &Value,\n    ) -> Result<()> {\n        let path = format!(\"repos/{}/{}/pulls/{}/reviews\", owner, repo, pr_num);\n        let uri = Uri::builder()\n            .path_and_query(path)\n            .build()\n            .context(\"Invalid URI\")?;\n        match self.crab._post(uri, Some(body)).await {\n            Ok(resp) => {\n                let status = resp.status();\n                if status != StatusCode::OK {\n                    let text = self\n                        .crab\n                        .body_to_string(resp)\n                        .await\n                        .context(\"Failed to decode failed response\")?;\n                    bail!(\"Error during POST: Status code: {}, Body: {}\", status, text);\n                }\n\n                review\n                    .mark_submitted()\n                    .context(\"Failed to update review metadata\")?;\n\n                Ok(())\n            }\n            // GH is known to send unescaped control characters in JSON responses which\n            // serde will fail to parse (not that it should succeed)\n            Err(octocrab::Error::Json {\n                source: _,\n                backtrace: _,\n            }) => {\n                eprintln!(\"Warning: GH response had invalid JSON\");\n                Ok(())\n            }\n            Err(e) => bail!(\"Error during POST: {}\", e),\n        }\n    }\n\n    async fn submit_file_comment(\n        &self,\n        owner: &str,\n        repo: &str,\n        pr_num: u64,\n        commit_id: &str,\n        fc: &FileComment,\n    ) -> Result<()> {\n        let body = json!({\n            \"body\": fc.comment,\n            \"commit_id\": commit_id,\n            \"path\": fc.file,\n            \"subject_type\": \"file\",\n        });\n        let path = format!(\"repos/{}/{}/pulls/{}/comments\", owner, repo, pr_num);\n        let uri = Uri::builder()\n            .path_and_query(path)\n            .build()\n            .context(\"Invalid URI\")?;\n        match self.crab._post(uri, Some(&body)).await {\n            Ok(resp) => {\n                let status = resp.status();\n                if status != StatusCode::CREATED {\n                    let text = self\n                        .crab\n                        .body_to_string(resp)\n                        .await\n                        .context(\"Failed to decode failed response\")?;\n                    bail!(\"Error during POST: Status code: {}, Body: {}\", status, text);\n                }\n                Ok(())\n            }\n            // GH is known to send unescaped control characters in JSON responses which\n            // serde will fail to parse (not that it should succeed)\n            Err(octocrab::Error::Json {\n                source: _,\n                backtrace: _,\n            }) => {\n                eprintln!(\"Warning: GH response had invalid JSON\");\n                Ok(())\n            }\n            Err(e) => bail!(\"Error during POST: {}\", e),\n        }\n    }\n\n    pub fn apply_pr(&self, owner: &str, repo: &str, pr_num: u64, apply_repo: &Path) -> Result<()> {\n        let review = Review::new_existing(&self.workdir()?, owner, repo, pr_num);\n        let diff = Diff::from_buffer(review.diff()?.as_bytes()).context(\"Failed to load diff\")?;\n        let apply_repo_path = Path::new(apply_repo);\n        let apply_repo =\n            Repository::open(apply_repo_path).context(\"Failed to open git repository\")?;\n\n        // Best effort check to prevent clobbering any work in progress\n        let mut opts = StatusOptions::new();\n        opts.include_ignored(false);\n        let statuses = apply_repo\n            .statuses(Some(&mut opts))\n            .context(\"Failed to get repo status\")?;\n        if !statuses.is_empty() {\n            bail!(\"Working directory is dirty\");\n        }\n\n        apply_repo\n            .apply(&diff, ApplyLocation::WorkDir, None)\n            .context(\"Failed to apply diff\")\n    }\n\n    pub fn print_status(&self, no_titles: bool) -> Result<()> {\n        let mut table = Table::new();\n        let mut table_fmt = *format::consts::FORMAT_CLEAN;\n        // Get rid of leading padding on each line\n        table_fmt.padding(0, 2);\n        table.set_format(table_fmt);\n        if !no_titles {\n            table.set_titles(row![\"Handle\", \"Status\", \"Review file\"])\n        }\n\n        let reviews = get_all_existing(&self.workdir()?).context(\"Failed to get all reviews\")?;\n        for review in reviews {\n            table.add_row(row![\n                review.handle(),\n                review.status()?,\n                review.path().display()\n            ]);\n        }\n\n        table.printstd();\n\n        Ok(())\n    }\n\n    /// Removes reviews from the filesystem\n    pub async fn remove(&self, prs: &[String], force: bool, submitted: bool) -> Result<()> {\n        for pr in prs {\n            let (owner, repo, pr_num) = self.parse_pr_str(pr)?;\n            let review = self.get_review(&owner, &repo, pr_num)?;\n            review\n                .remove(force)\n                .with_context(|| anyhow!(\"Failed to remove {}\", pr))?;\n        }\n\n        if !submitted {\n            return Ok(());\n        }\n\n        let reviews = get_all_existing(&self.workdir()?).context(\"Failed to all reviews\")?;\n        for review in reviews {\n            if review.status()? == ReviewStatus::Submitted {\n                let handle = review.handle();\n                review\n                    .remove(force)\n                    .with_context(|| anyhow!(\"Failed to remove {}\", handle))?;\n            }\n        }\n\n        Ok(())\n    }\n}\n\n#[cfg(test)]\nmod tests {\n    use super::*;\n    use std::fs::File;\n    use std::io::Write;\n    use tempfile::TempDir;\n\n    // Lays down configs in a tempdir\n    //\n    // NB: Configs get deleted if returned `TempDir` is dropped\n    fn config(global: &str, local: Option<&str>) -> (Prr, TempDir) {\n        let dir = TempDir::new().unwrap();\n        let gpath = dir.path().join(\"config.toml\");\n        let mut gfile = File::create(&gpath).unwrap();\n        write!(&mut gfile, \"{}\", global).unwrap();\n\n        let lpath = if let Some(lcontents) = local {\n            let lpath = dir.path().join(\"local_config.toml\");\n            let mut lfile = File::create(&lpath).unwrap();\n            write!(&mut lfile, \"{}\", lcontents).unwrap();\n            Some(lpath)\n        } else {\n            None\n        };\n\n        let prr = Prr::new(&gpath, lpath).unwrap();\n        (prr, dir)\n    }\n\n    lazy_static! {\n        // Basic dummy config just to avoid errors\n        static ref PRR: (Prr, TempDir) = {\n            let gconfig = r#\"\n                [prr]\n                token = \"test\"\n                workdir = \"/tmp\"\n            \"#;\n\n            config(gconfig, None)\n        };\n    }\n\n    #[tokio::test]\n    async fn test_parse_basic_pr_str() {\n        let pr_ref = \"example/prr/42\";\n        assert_eq!(\n            PRR.0.parse_pr_str(pr_ref).unwrap(),\n            (\"example\".to_string(), \"prr\".to_string(), 42)\n        )\n    }\n\n    #[tokio::test]\n    async fn test_parse_dotted_pr_str() {\n        let pr_ref = \"example/prr.test/42\";\n        assert_eq!(\n            PRR.0.parse_pr_str(pr_ref).unwrap(),\n            (\"example\".to_string(), \"prr.test\".to_string(), 42)\n        )\n    }\n\n    #[tokio::test]\n    async fn test_parse_underscored_pr_str() {\n        let pr_ref = \"example/prr_test/42\";\n        assert_eq!(\n            PRR.0.parse_pr_str(pr_ref).unwrap(),\n            (\"example\".to_string(), \"prr_test\".to_string(), 42)\n        )\n    }\n\n    #[tokio::test]\n    async fn test_parse_dashed_pr_str() {\n        let pr_ref = \"example/prr-test/42\";\n        assert_eq!(\n            PRR.0.parse_pr_str(pr_ref).unwrap(),\n            (\"example\".to_string(), \"prr-test\".to_string(), 42)\n        )\n    }\n\n    #[tokio::test]\n    async fn test_parse_numbered_pr_str() {\n        let pr_ref = \"example/prr1/42\";\n        assert_eq!(\n            PRR.0.parse_pr_str(pr_ref).unwrap(),\n            (\"example\".to_string(), \"prr1\".to_string(), 42)\n        )\n    }\n\n    #[tokio::test]\n    async fn test_parse_mixed_pr_str() {\n        let pr_ref = \"example/prr1.test_test-/42\";\n        assert_eq!(\n            PRR.0.parse_pr_str(pr_ref).unwrap(),\n            (\"example\".to_string(), \"prr1.test_test-\".to_string(), 42)\n        )\n    }\n\n    #[tokio::test]\n    async fn test_parse_github_url() {\n        let pr_ref = \"https://github.com/example/repo/pull/42\";\n        assert_eq!(\n            PRR.0.parse_pr_str(pr_ref).unwrap(),\n            (\"example\".to_string(), \"repo\".to_string(), 42)\n        )\n    }\n\n    #[tokio::test]\n    async fn test_parse_github_url_with_extra_path() {\n        let pr_ref = \"https://github.com/example/repo/pull/42/files\";\n        assert_eq!(\n            PRR.0.parse_pr_str(pr_ref).unwrap(),\n            (\"example\".to_string(), \"repo\".to_string(), 42)\n        )\n    }\n\n    #[tokio::test]\n    async fn test_parse_github_url_with_complex_path() {\n        let pr_ref = \"https://github.com/example/repo/pull/42/files/abc123..def456\";\n        assert_eq!(\n            PRR.0.parse_pr_str(pr_ref).unwrap(),\n            (\"example\".to_string(), \"repo\".to_string(), 42)\n        )\n    }\n\n    #[tokio::test]\n    async fn test_parse_custom_github_host() {\n        let pr_ref = \"https://github.acme.com/example/repo/pull/42\";\n        assert_eq!(\n            PRR.0.parse_pr_str(pr_ref).unwrap(),\n            (\"example\".to_string(), \"repo\".to_string(), 42)\n        )\n    }\n\n    #[tokio::test]\n    async fn test_local_config_repository() {\n        let gconfig = r#\"\n            [prr]\n            token = \"test\"\n        \"#;\n        let lconfig = r#\"\n            [local]\n            repository = \"testorg/testrepo\"\n        \"#;\n\n        let (prr, _dir) = config(gconfig, Some(lconfig));\n        assert_eq!(\n            prr.parse_pr_str(\"42\").unwrap(),\n            (\"testorg\".to_string(), \"testrepo\".to_string(), 42)\n        )\n    }\n\n    #[tokio::test]\n    async fn test_global_workdir() {\n        let gconfig = r#\"\n            [prr]\n            token = \"test\"\n            workdir = \"/globalworkdir\"\n        \"#;\n\n        let (prr, _dir) = config(gconfig, None);\n        assert_eq!(prr.workdir().unwrap(), Path::new(\"/globalworkdir\"))\n    }\n\n    #[tokio::test]\n    async fn test_local_workdir() {\n        let gconfig = r#\"\n            [prr]\n            token = \"test\"\n        \"#;\n        let lconfig = r#\"\n            [local]\n            workdir = \"/localworkdir\"\n        \"#;\n\n        let (prr, _dir) = config(gconfig, Some(lconfig));\n        assert_eq!(prr.workdir().unwrap(), Path::new(\"/localworkdir\"))\n    }\n\n    #[tokio::test]\n    async fn test_local_workdir_relative() {\n        let gconfig = r#\"\n            [prr]\n            token = \"test\"\n        \"#;\n        let lconfig = r#\"\n            [local]\n            workdir = \"localrelativeworkdir\"\n        \"#;\n\n        let (prr, dir) = config(gconfig, Some(lconfig));\n        assert_eq!(\n            prr.workdir().unwrap(),\n            dir.path().join(\"localrelativeworkdir\")\n        )\n    }\n\n    #[tokio::test]\n    async fn test_local_workdir_override() {\n        let gconfig = r#\"\n            [prr]\n            token = \"test\"\n            workdir = \"/globalworkdir\"\n        \"#;\n        let lconfig = r#\"\n            [local]\n            workdir = \"/localworkdir\"\n        \"#;\n\n        let (prr, _dir) = config(gconfig, Some(lconfig));\n        assert_eq!(prr.workdir().unwrap(), Path::new(\"/localworkdir\"))\n    }\n\n    #[tokio::test]\n    async fn test_invalid_relative_workdir() {\n        let gconfig = r#\"\n            [prr]\n            token = \"test\"\n            workdir = \"relativeworkdir\"\n        \"#;\n\n        let (prr, _dir) = config(gconfig, None);\n        assert!(prr.workdir().is_err());\n    }\n\n    fn copy_dir_all(src: impl AsRef<Path>, dst: impl AsRef<Path>) {\n        fs::create_dir_all(&dst).expect(\"could not create_dir_all\");\n        for entry in fs::read_dir(src).expect(\"could not read_dir\") {\n            let entry = entry.expect(\"entry is not valid\");\n            let ty = entry.file_type().expect(\"cannot get filetype\");\n            if ty.is_dir() {\n                copy_dir_all(entry.path(), dst.as_ref().join(entry.file_name()));\n            } else {\n                fs::copy(entry.path(), dst.as_ref().join(entry.file_name()))\n                    .expect(\"copy in copy_dir_all failed\");\n            }\n        }\n    }\n\n    #[test]\n    fn test_resolve_github_token_with_no_config_token_fallback_to_env() {\n        let env_lookup = |var: &str| -> Result<String, std::env::VarError> {\n            match var {\n                \"GITHUB_TOKEN\" => Ok(\"fallback_env_token\".to_string()),\n                _ => Err(std::env::VarError::NotPresent),\n            }\n        };\n\n        let result = resolve_github_token(None, env_lookup).unwrap();\n        assert_eq!(result, \"fallback_env_token\");\n    }\n\n    #[test]\n    fn test_resolve_github_token_with_no_config_token_no_env_error() {\n        let env_lookup = |_var: &str| -> Result<String, std::env::VarError> {\n            Err(std::env::VarError::NotPresent)\n        };\n\n        let result = resolve_github_token(None, env_lookup);\n        assert!(result.is_err());\n        let error_msg = result.err().unwrap().to_string();\n        assert!(error_msg.contains(\"No GitHub token found in config or environment variables\"));\n    }\n\n    #[test]\n    fn test_resolve_github_token_config_token_preferred_over_env() {\n        let env_lookup = |var: &str| -> Result<String, std::env::VarError> {\n            match var {\n                \"GITHUB_TOKEN\" => Ok(\"env_token\".to_string()),\n                _ => Err(std::env::VarError::NotPresent),\n            }\n        };\n\n        let result = resolve_github_token(Some(\"config_token\"), env_lookup).unwrap();\n        assert_eq!(result, \"config_token\");\n    }\n\n    #[test]\n    fn test_resolve_github_token_empty_config_token_falls_back_to_env() {\n        let env_lookup = |var: &str| -> Result<String, std::env::VarError> {\n            match var {\n                \"GITHUB_TOKEN\" => Ok(\"env_token\".to_string()),\n                _ => Err(std::env::VarError::NotPresent),\n            }\n        };\n\n        let result = resolve_github_token(Some(\"\"), env_lookup).unwrap();\n        assert_eq!(result, \"env_token\");\n    }\n\n    #[test]\n    fn test_resolve_github_token_env_var_precedence() {\n        let env_lookup = |var: &str| -> Result<String, std::env::VarError> {\n            match var {\n                \"GH_TOKEN\" => Ok(\"gh_token\".to_string()),\n                \"GITHUB_TOKEN\" => Ok(\"github_token\".to_string()),\n                _ => Err(std::env::VarError::NotPresent),\n            }\n        };\n\n        let result = resolve_github_token(None, env_lookup).unwrap();\n        // GH_TOKEN should have higher precedence\n        assert_eq!(result, \"gh_token\");\n    }\n\n    #[test]\n    fn test_resolve_github_token_empty_env_var_error() {\n        let env_lookup = |var: &str| -> Result<String, std::env::VarError> {\n            match var {\n                // Empty token\n                \"GITHUB_TOKEN\" => Ok(\"\".to_string()),\n                _ => Err(std::env::VarError::NotPresent),\n            }\n        };\n\n        let result = resolve_github_token(None, env_lookup);\n        assert!(result.is_err());\n        let error_msg = result.err().unwrap().to_string();\n        assert!(error_msg.contains(\"Environment variable 'GITHUB_TOKEN' located but is empty\"));\n    }\n\n    #[tokio::test]\n    async fn test_apply_pr() {\n        let gconfig = r#\"\n             [prr]\n             token = \"doesn'tmatter\"\n             workdir = \"doesn'tmatter\"\n         \"#;\n        let lconfig = r#\"\n             [local]\n             workdir = \"testdata/\"\n         \"#;\n\n        let (prr, dir) = config(gconfig, Some(lconfig));\n        let test_review_path =\n            dir.path().to_str().expect(\"tmp path invalid\").to_string() + \"/testdata/apply_pr\";\n        fs::create_dir_all(&test_review_path).expect(\"failed to create temp directory\");\n        copy_dir_all(\"testdata/review/apply_pr\", &test_review_path);\n\n        let test_repo_path = dir.path().to_str().unwrap().to_string() + \"/testgitrepo/\";\n        fs::create_dir_all(&test_repo_path).expect(\"couldn't create testgitrepo\");\n        let test_repo = git2::Repository::init(&test_repo_path).expect(\"couldn't init testgitrepo\");\n\n        std::fs::copy(\n            \"testdata/testgitrepo/README.md\",\n            test_repo_path.clone() + \"README.md\",\n        )\n        .expect(\"copy README.md failed\");\n\n        let mut index = test_repo.index().expect(\"couldn't get repo index\");\n        index\n            .add_path(Path::new(\"README.md\"))\n            .expect(\"couldn't add path\");\n\n        let new_tree_oid = index.write_tree().expect(\"couldn't write tree\");\n        index.write().expect(\"couldn't write index\");\n\n        let signature = git2::Signature::now(\"someone\", \"someone@somewhere.com\")\n            .expect(\"failed to create signature\");\n        let new_tree = test_repo.find_tree(new_tree_oid).unwrap();\n        test_repo\n            .commit(\n                Some(\"HEAD\"),\n                &signature,\n                &signature,\n                \"Initial commit\",\n                &new_tree,\n                &[],\n            )\n            .expect(\"failed to commit\");\n\n        // add non-tracked file for testing purposes\n        std::fs::copy(\n            \"testdata/testgitrepo/README.md\",\n            test_repo_path.clone() + \"README-not-tracked.md\",\n        )\n        .expect(\"copy README-not-tracked.md failed\");\n\n        prr.apply_pr(\"apply_pr\", \"review\", 1, Path::new(&test_repo_path))\n            .expect(\"apply_pr failed\");\n\n        let got_after_apply = fs::read(test_repo_path.clone() + \"README.md\")\n            .expect(\"failed to read README.md with diff applied\");\n        let want_after_apply = fs::read(\"testdata/testgitrepo/README-applied.md\")\n            .expect(\"failed to read README-applied.md\");\n        assert_eq!(got_after_apply, want_after_apply);\n    }\n}\n"
  },
  {
    "path": "src/review.rs",
    "content": "use std::fmt::{Display, Formatter, Result as fmt_result, Write as fmt_write};\nuse std::fs;\nuse std::fs::OpenOptions;\nuse std::io::Write;\nuse std::path::{Path, PathBuf};\nuse std::time::SystemTime;\n\nuse anyhow::{anyhow, bail, Context, Result};\nuse serde_derive::{Deserialize, Serialize};\n\nuse crate::parser::{Comment, FileComment, InlineComment, ReviewAction, ReviewParser};\n\n/// We support a few common variants of snips.\n/// These are semantically identical.\nconst SNIP_VARIANTS: &[&str] = &[\"[..]\", \"[...]\"];\n\n/// Represents the state of a single review\npub struct Review {\n    /// Path to workdir\n    workdir: PathBuf,\n    /// Name of the owner of the repository\n    owner: String,\n    /// Name of the repository\n    repo: String,\n    /// Issue # of the pull request\n    pr_num: u64,\n}\n\n/// Metadata for a single review. Stored as dotfile next to user-facing review file\n#[derive(Serialize, Deserialize, Debug)]\nstruct ReviewMetadata {\n    /// Original .diff file contents. Used to detect corrupted review files\n    original: String,\n    /// Time (seconds since epoch) the review file was last submitted\n    submitted: Option<u64>,\n    /// The commit hash of the PR at the time the review was started\n    commit_id: Option<String>,\n}\n\n/// Status of a review\n#[derive(PartialEq, Debug)]\npub enum ReviewStatus {\n    /// Newly downloaded review; no changes yet\n    New,\n    /// Unsubmitted changes have been made to review file\n    Reviewed,\n    /// Review has been submitted. Any further changes to the review file are ignored\n    Submitted,\n}\n\n/// Represents a single line in a review file.\nenum LineType<'a> {\n    /// Original text (but stored without the leading `> `)\n    Quoted(&'a str),\n    /// A snip (`[..]`)\n    Snip,\n    /// User supplied comment\n    Comment(&'a str),\n}\n\nimpl Display for ReviewStatus {\n    fn fmt(&self, f: &mut Formatter<'_>) -> fmt_result {\n        let text = match self {\n            Self::New => \"NEW\",\n            Self::Reviewed => \"REVIEWED\",\n            Self::Submitted => \"SUBMITTED\",\n        };\n\n        write!(f, \"{text}\")\n    }\n}\n\nimpl<'a> From<&'a str> for LineType<'a> {\n    fn from(line: &'a str) -> Self {\n        if let Some(text) = line.strip_prefix(\"> \") {\n            Self::Quoted(text)\n        } else if SNIP_VARIANTS.contains(&line.trim()) {\n            Self::Snip\n        } else {\n            Self::Comment(line)\n        }\n    }\n}\n\nfn prefix_lines(s: &str, prefix: &str) -> String {\n    let mut ret = String::with_capacity(s.len());\n\n    for line in s.lines() {\n        if line.is_empty() {\n            ret += &(prefix.to_owned() + \" \\n\");\n        } else {\n            // Appending to heap allocated string cannot fail\n            writeln!(ret, \"{} {}\", prefix, line).expect(\"Failed to write to string\");\n        }\n    }\n\n    ret\n}\n\n/// Returns a list of all reviews in a workdir\npub fn get_all_existing(workdir: &Path) -> Result<Vec<Review>> {\n    // This pipeline does the following:\n    //   * Iterate through all org directories in workdir\n    //   * For each org directory, iterate through all contained repo directories\n    //   * For each repo directory, enumerate all non-metadata review files\n    let reviews: Vec<PathBuf> = fs::read_dir(workdir)\n        .context(\"Failed to read workdir\")?\n        .filter_map(|entry| entry.ok())\n        .map(|org| org.path())\n        .filter(|org| org.is_dir())\n        .filter_map(|org| fs::read_dir(org).ok())\n        .flatten()\n        .filter_map(|repo| repo.ok())\n        .map(|repo| repo.path())\n        .filter(|repo| repo.is_dir())\n        .filter_map(|repo| fs::read_dir(repo).ok())\n        .flatten()\n        .filter_map(|review| review.ok())\n        .map(|review| review.path())\n        .filter(|review| review.is_file())\n        .filter(|review| match review.extension() {\n            Some(e) => e == \"prr\",\n            None => false,\n        })\n        .collect();\n\n    let mut ret = Vec::with_capacity(reviews.len());\n    for review in reviews {\n        let parts: Vec<_> = review\n            .iter()\n            .rev()\n            .take(3)\n            .map(|p| p.to_string_lossy())\n            .collect();\n\n        if parts.len() != 3 {\n            bail!(\"malformed review file path: {}\", review.display());\n        }\n\n        let pr_num: u64 = parts[0]\n            .strip_suffix(\".prr\")\n            .unwrap_or(&parts[0])\n            .parse()\n            .with_context(|| format!(\"Failed to parse PR num: {}\", review.display()))?;\n\n        // Note the vec has components reversed\n        let r = Review::new_existing(workdir, &parts[2], &parts[1], pr_num);\n        ret.push(r);\n    }\n\n    Ok(ret)\n}\n\n/// Recursive helper for `resolve_snips()`.\n///\n/// This function will return Some(lines), where lines is a Vec of resolved\n/// lines. There should not be any trailing newlines in `lines`.\n///\n/// The problem of resolving snips transposes pretty cleanly to the classic\n/// glob matching algorithm. We implement the glob matching fairly naively\n/// using recursion b/c it's cleaner to recurse when we want to eventually\n/// return a value.\n///\n/// This would be in contrast to rsc's glob algorithm [0] where it's more\n/// efficient and has less pathological corner cases. We choose to trade off\n/// performance for simplicity here.\n///\n/// [0]: https://research.swtch.com/glob\nfn resolve_snips_recurse<'a>(pattern: &[LineType<'a>], text: &[&'a str]) -> Option<Vec<String>> {\n    let mut resolved = Vec::new();\n    let mut pattern_idx = 0;\n    let mut text_idx = 0;\n    while pattern_idx < pattern.len() || text_idx < text.len() {\n        if pattern_idx < pattern.len() {\n            match pattern[pattern_idx] {\n                LineType::Quoted(line) => {\n                    if text_idx < text.len() && text[text_idx] == line {\n                        resolved.push(format!(\"> {line}\"));\n                        pattern_idx += 1;\n                        text_idx += 1;\n                        continue;\n                    }\n                }\n                // Comments are semantically irrelevant to snip resolution. But we still\n                // need to account for them in returned output.\n                LineType::Comment(line) => {\n                    resolved.push(line.to_string());\n                    pattern_idx += 1;\n                    continue;\n                }\n                // Begin glob logic\n                LineType::Snip => {\n                    // Here we try making the snip consume 0 lines, 1 line, and so forth.\n                    //\n                    // Skipping comments is technically a noop and in theory we could rework\n                    // this code to only skip matchable text. But that is just an optimization.\n                    for cand_text_idx in text_idx..=text.len() {\n                        let cand_pattern = &pattern[pattern_idx + 1..];\n                        let cand_text = &text[cand_text_idx..];\n                        if let Some(mut r) = resolve_snips_recurse(cand_pattern, cand_text) {\n                            let skipped: Vec<String> = text[text_idx..cand_text_idx]\n                                .iter()\n                                .map(|&line| format!(\"> {line}\"))\n                                .collect();\n                            resolved.extend_from_slice(&skipped);\n                            resolved.append(&mut r);\n                            return Some(resolved);\n                        }\n                    }\n                }\n            }\n        }\n\n        // If we reach here, we either have some `pattern` or `text` still left to\n        // process. Meaning one ran out before the other. Which implies a resolution\n        // failure.\n        return None;\n    }\n\n    // We've finished processing all of `text` and `pattern`. So resolution success.\n    Some(resolved)\n}\n\nimpl Review {\n    /// Creates a new `Review`\n    ///\n    /// `review_file` is the path where the user-facing review file should\n    /// be created. Additional metadata files (dotfiles) may be created in the same\n    /// directory.\n    pub fn new(\n        workdir: &Path,\n        diff: String,\n        owner: &str,\n        repo: &str,\n        pr_description: Option<String>,\n        pr_num: u64,\n        commit_id: String,\n        force: bool,\n    ) -> Result<Review> {\n        let review = Review {\n            workdir: workdir.to_owned(),\n            owner: owner.to_owned(),\n            repo: repo.to_owned(),\n            pr_num,\n        };\n\n        // First create directories leading up to review file if necessary\n        let review_path = review.path();\n        let review_dir = review_path\n            .parent()\n            .ok_or_else(|| anyhow!(\"Review path has no parent!\"))?;\n        fs::create_dir_all(review_dir).context(\"Failed to create workdir directories\")?;\n\n        // Check if there are unsubmitted changes\n        if !force && review.has_metadata() && review.status()? == ReviewStatus::Reviewed {\n            bail!(\n                \"You have unsubmitted changes to the requested review. \\\n                Either submit the existing changes, delete the existing review file, \\\n                or re-run this command with --force.\"\n            );\n        }\n\n        // Now create review file\n        let mut review_file = OpenOptions::new()\n            .write(true)\n            .create(true)\n            .truncate(true)\n            .open(&review_path)\n            .context(\"Failed to create review file\")?;\n\n        let mut description = pr_description.unwrap_or_else(String::default);\n        if !description.is_empty() {\n            description += \"\\n\";\n        }\n\n        let original_contents = description + &diff;\n        let prefixed_contents = prefix_lines(&original_contents, \">\");\n        review_file\n            .write_all(prefixed_contents.as_bytes())\n            .context(\"Failed to write review file\")?;\n\n        // Create metadata file\n        let metadata = ReviewMetadata {\n            original: original_contents,\n            submitted: None,\n            commit_id: Some(commit_id),\n        };\n        let json = serde_json::to_string(&metadata)?;\n        let metadata_path = review.metadata_path();\n        let mut metadata_file = OpenOptions::new()\n            .write(true)\n            .create(true)\n            .truncate(true)\n            .open(metadata_path)\n            .context(\"Failed to create metadata file\")?;\n        metadata_file\n            .write_all(json.as_bytes())\n            .context(\"Failed to write metadata file\")?;\n\n        Ok(review)\n    }\n\n    /// Creates a `Review` that already exists on disk\n    ///\n    /// Note we do not check that anything actually exists on disk because that is\n    /// inherently racy. We'll handle ENOENT errors when we actually use any files.\n    pub fn new_existing(workdir: &Path, owner: &str, repo: &str, pr_num: u64) -> Review {\n        Review {\n            workdir: workdir.to_owned(),\n            owner: owner.to_owned(),\n            repo: repo.to_owned(),\n            pr_num,\n        }\n    }\n\n    /// Parse the user-supplied comments on a review\n    ///\n    /// Returns (overall review action, overall review comment, inline comments, file comments)\n    pub fn comments(&self) -> Result<(ReviewAction, String, Vec<InlineComment>, Vec<FileComment>)> {\n        let raw = fs::read_to_string(self.path()).context(\"Failed to read review file\")?;\n        let contents = self.resolve_snips(&raw)?;\n        self.validate_review_file(&contents)?;\n\n        let mut parser = ReviewParser::new();\n        let mut review_action = ReviewAction::Comment;\n        let mut review_comment = String::new();\n        let mut inline_comments = Vec::new();\n        let mut file_comments = Vec::new();\n        for (idx, line) in contents.lines().enumerate() {\n            let res = parser\n                .parse_line(line)\n                .with_context(|| format!(\"Failed to parse review on line {}\", idx + 1))?;\n\n            match res {\n                Some(Comment::Review(c)) => {\n                    if !review_comment.is_empty() {\n                        bail!(\"Somehow saw more than one review comment\");\n                    }\n\n                    review_comment = c;\n                }\n                Some(Comment::Inline(c)) => inline_comments.push(c),\n                Some(Comment::ReviewAction(a)) => review_action = a,\n                Some(Comment::File(fc)) => file_comments.push(fc),\n                None => {}\n            }\n        }\n\n        match parser.finish() {\n            Some(Comment::Inline(c)) => inline_comments.push(c),\n            // Original diff must have been short to begin with\n            Some(Comment::Review(_)) => bail!(\"Unexpected review comment at parser finish\"),\n            Some(Comment::ReviewAction(_)) => bail!(\"Unexpected review action at parser finish\"),\n            Some(Comment::File(_)) => bail!(\"Unexpected file-level comment at parser finish\"),\n            None => {}\n        };\n\n        Ok((\n            review_action,\n            review_comment,\n            inline_comments,\n            file_comments,\n        ))\n    }\n\n    /// Update the review file's submission time\n    pub fn mark_submitted(&self) -> Result<()> {\n        let metadata_path = self.metadata_path();\n        let mut metadata = self.metadata()?;\n\n        let submission_time = SystemTime::now()\n            .duration_since(SystemTime::UNIX_EPOCH)\n            .expect(\"Time went backwards\");\n        metadata.submitted = Some(submission_time.as_secs());\n\n        let json = serde_json::to_string(&metadata)?;\n        let mut metadata_file = OpenOptions::new()\n            .write(true)\n            .create(true)\n            .truncate(true)\n            .open(metadata_path)\n            .context(\"Failed to create metadata file\")?;\n        metadata_file\n            .write_all(json.as_bytes())\n            .context(\"Failed to write metadata file\")?;\n\n        Ok(())\n    }\n\n    /// Replaces all snips (`[...]`s) from `contents` with original, quoted text.\n    /// Returns resolved contents as new string.\n    fn resolve_snips(&self, contents: &str) -> Result<String> {\n        // First, classify contents into line types. This is henceforth\n        // known as the \"pattern\" we want to resolve against original text.\n        let pattern: Vec<LineType> = contents.lines().map(LineType::from).collect();\n\n        // If the review file does not have any snips, just skip snip resolution.\n        //\n        // We do this so user gets more informative error message thru validate_review_file()\n        // if they corrupted a quoted line. If we naively (and more efficiently) always\n        // try to resolve snips, they might get the less informative error below.\n        if !pattern.iter().any(|line| matches!(line, LineType::Snip)) {\n            return Ok(contents.to_string());\n        }\n\n        // Next, store original text as lines. It's easier to index into this way.\n        // The original text here is unquoted.\n        let original = self.metadata()?.original;\n        let text: Vec<&str> = original.lines().collect();\n\n        Ok(resolve_snips_recurse(&pattern, &text)\n            .ok_or_else(|| anyhow!(\"Failed to resolve snips. Did you corrupt quoted text?\"))?\n            .iter()\n            .map(|line| format!(\"{line}\\n\"))\n            .collect())\n    }\n\n    /// Validates whether the user corrupted the quoted contents\n    fn validate_review_file(&self, contents: &str) -> Result<()> {\n        let mut reconstructed = String::with_capacity(contents.len());\n        for line in contents.lines() {\n            if let Some(stripped) = line.strip_prefix(\"> \") {\n                reconstructed += stripped.trim_end();\n                reconstructed += \"\\n\";\n            }\n\n            if line == \">\" {\n                reconstructed += \"\\n\";\n            }\n        }\n\n        let metadata = self.metadata()?;\n        let original: String = metadata\n            .original\n            .lines()\n            .map(|line| line.trim_end().to_owned() + \"\\n\")\n            .collect();\n\n        if reconstructed != original {\n            // Be helpful and provide exact line number of mismatch.\n            //\n            // This loop on zip() will work as long as there isn't any truncation or trailing junk\n            // in the original text. To handle this case, there's the final bail!()\n            for (idx, (l, r)) in reconstructed.lines().zip(original.lines()).enumerate() {\n                if l != r {\n                    // Get number of user generated lines up until the mismatch\n                    let user_lines = contents\n                        .lines()\n                        .take(idx)\n                        .filter(|l| !l.starts_with('>'))\n                        .count();\n                    let err = format!(\"Line {}, found '{l}' expected '{r}'\", idx + 1 + user_lines);\n                    bail!(\"Detected corruption in quoted part of review file: {err}\");\n                }\n            }\n\n            bail!(\"Detected corruption in quoted part of review file: found trailing or truncated lines\");\n        }\n\n        Ok(())\n    }\n\n    /// Returns whether or not there exists review comments\n    fn reviewed(&self) -> Result<bool> {\n        let (_, review_comment, comments, file_comments) = self\n            .comments()\n            .with_context(|| anyhow!(\"Failed to parse comments for {}\", self.path().display()))?;\n\n        Ok(!review_comment.is_empty() || !comments.is_empty() || !file_comments.is_empty())\n    }\n\n    /// Returns path to user-facing review file\n    pub fn path(&self) -> PathBuf {\n        let mut p = self.workdir.clone();\n        p.push(&self.owner);\n        p.push(&self.repo);\n        p.push(format!(\"{}.prr\", self.pr_num));\n\n        p\n    }\n\n    /// Loads and returns the parsed contents of the metadata file for the review file\n    fn metadata(&self) -> Result<ReviewMetadata> {\n        let meta =\n            fs::read_to_string(self.metadata_path()).context(\"Failed to load metadata file\")?;\n        serde_json::from_str::<ReviewMetadata>(&meta).context(\"Failed to parse metadata file\")\n    }\n\n    fn has_metadata(&self) -> bool {\n        fs::metadata(self.metadata_path()).is_ok()\n    }\n\n    fn metadata_path(&self) -> PathBuf {\n        let mut metadata_path = self.path();\n        metadata_path.set_file_name(format!(\".{}\", self.pr_num));\n\n        metadata_path\n    }\n\n    /// Returns the commit_id associated with the review\n    pub fn commit_id(&self) -> Result<Option<String>> {\n        Ok(self.metadata()?.commit_id.clone())\n    }\n\n    /// Returns the original review diff\n    pub fn diff(&self) -> Result<String> {\n        Ok(self.metadata()?.original.clone())\n    }\n\n    /// Returns a handle (eg \"owner/repo/pr_num\") to this review\n    pub fn handle(&self) -> String {\n        format!(\"{}/{}/{}\", self.owner, self.repo, self.pr_num)\n    }\n\n    /// Gets the status of a review\n    pub fn status(&self) -> Result<ReviewStatus> {\n        let metadata = self.metadata()?;\n        let reviewed = self.reviewed()?;\n        let status = if metadata.submitted.is_some() {\n            ReviewStatus::Submitted\n        } else if reviewed {\n            ReviewStatus::Reviewed\n        } else {\n            ReviewStatus::New\n        };\n\n        Ok(status)\n    }\n\n    /// Remove review from filesystem\n    pub fn remove(self, force: bool) -> Result<()> {\n        if !force && self.status()? == ReviewStatus::Reviewed {\n            bail!(\n                \"You have unsubmitted changes to the requested review. \\\n                Re-run this command with --force to ignore this check.\"\n            );\n        }\n\n        fs::remove_file(self.path()).context(\"Failed to remove review file\")?;\n        fs::remove_file(self.metadata_path()).context(\"Failed to remove metadata file\")?;\n\n        Ok(())\n    }\n}\n\n#[cfg(test)]\nmod tests {\n    use std::collections::VecDeque;\n    use std::fs::{create_dir_all, File};\n\n    use pretty_assertions::assert_eq as assert_eq_pretty;\n    use tempfile::{tempdir, TempDir};\n\n    use super::*;\n\n    fn setup(review: &str, metadata: &str) -> (Review, TempDir) {\n        let dir = tempdir().expect(\"Failed to create tempdir\");\n\n        // Create directory structure\n        let project_dir = dir.path().join(\"some_owner\").join(\"some_repo\");\n        create_dir_all(&project_dir).expect(\"Failed to create workdir structure\");\n\n        // Create and write review file\n        let mut review_file =\n            File::create(project_dir.join(\"3.prr\")).expect(\"Failed to create review file\");\n        review_file\n            .write_all(review.as_bytes())\n            .expect(\"Failed to write review file\");\n\n        // Create and write metadata file\n        let mut metadata_file =\n            File::create(project_dir.join(\".3\")).expect(\"Failed to create metadata file\");\n        metadata_file\n            .write_all(metadata.as_bytes())\n            .expect(\"Failed to write metadata file\");\n\n        let r = Review::new_existing(dir.path(), \"some_owner\", \"some_repo\", 3);\n\n        (r, dir)\n    }\n\n    // Review file has all trailing whitespace stripped\n    #[test]\n    fn test_validate_stripped() {\n        let review = include_str!(\"../testdata/review/trailing_whitespace/review\");\n        let metadata = include_str!(\"../testdata/review/trailing_whitespace/metadata\");\n        let (r, _dir) = setup(review, metadata);\n\n        r.validate_review_file(review)\n            .expect(\"Failed to validate review file\");\n    }\n\n    // Step through review status state machine and validate each state\n    #[test]\n    fn test_review_status() {\n        let review = include_str!(\"../testdata/review/status/review\");\n        let metadata = include_str!(\"../testdata/review/status/metadata\");\n        let (r, _dir) = setup(review, metadata);\n\n        // Using more verbose match to ensure build failure if new states added.\n        // We only need this verbosity once.\n        match r.status().expect(\"Failed to get review status\") {\n            ReviewStatus::New => (),\n            ReviewStatus::Reviewed => panic!(\"Unexpected Reviewed state\"),\n            ReviewStatus::Submitted => panic!(\"Unpexected Submitted state\"),\n        };\n\n        // Do a \"review\"\n        let mut file = OpenOptions::new()\n            .write(true)\n            .append(true)\n            .open(r.path())\n            .expect(\"Failed to open review file\");\n        file.write_all(b\"asdf\\n\")\n            .expect(\"Failed to write review comment\");\n        assert_eq!(r.status().unwrap(), ReviewStatus::Reviewed);\n\n        // \"Submit\" the review\n        r.mark_submitted().expect(\"Failed to submit review\");\n        assert_eq!(r.status().unwrap(), ReviewStatus::Submitted);\n    }\n\n    #[test]\n    fn test_review_validation_with_pr_description() {\n        let review = include_str!(\"../testdata/review/pr_description/review\");\n        let metadata = include_str!(\"../testdata/review/pr_description/metadata\");\n        let (r, _dir) = setup(review, metadata);\n\n        r.validate_review_file(review)\n            .expect(\"Failed to validate review file with PR description\");\n    }\n\n    #[test]\n    fn test_review_validation_with_interleaving_pr_description() {\n        let review = include_str!(\"../testdata/review/pr_description_interleaving/review\");\n        let metadata = include_str!(\"../testdata/review/pr_description_interleaving/metadata\");\n        let (r, _dir) = setup(review, metadata);\n\n        r.validate_review_file(review)\n            .expect(\"Failed to validate review file with interleaving PR description\");\n    }\n\n    // Tests creation of a new review\n    #[test]\n    fn test_new_review() {\n        // Create directory structure\n        let workdir = tempdir().expect(\"Failed to create tempdir\");\n\n        // Create a review\n        let review = Review::new(\n            workdir.path(),\n            \"some_review_contents\".to_string(),\n            \"some_owner\",\n            \"some_repo\",\n            Some(\"some_pr_desc\".to_string()),\n            3,\n            \"111\".to_string(),\n            false,\n        )\n        .expect(\"Failed to create new non-existent review\");\n\n        // Check on disk \"database\"\n        fs::metadata(review.path()).expect(\"Failed to read review file\");\n        fs::metadata(review.metadata_path()).expect(\"Failed to read review file\");\n    }\n\n    #[test]\n    fn test_snip_single() {\n        let review = include_str!(\"../testdata/review/snip_single/review\");\n        let gold = include_str!(\"../testdata/review/snip_single/gold\");\n        let metadata = include_str!(\"../testdata/review/snip_single/metadata\");\n\n        let (r, _dir) = setup(review, metadata);\n        assert_eq_pretty!(r.resolve_snips(review).unwrap(), gold);\n    }\n\n    #[test]\n    fn test_snip_multiple() {\n        let review = include_str!(\"../testdata/review/snip_multiple/review\");\n        let gold = include_str!(\"../testdata/review/snip_multiple/gold\");\n        let metadata = include_str!(\"../testdata/review/snip_multiple/metadata\");\n\n        let (r, _dir) = setup(review, metadata);\n        assert_eq_pretty!(r.resolve_snips(review).unwrap(), gold);\n    }\n\n    #[test]\n    fn test_snip_comments() {\n        let review = include_str!(\"../testdata/review/snip_comments/review\");\n        let gold = include_str!(\"../testdata/review/snip_comments/gold\");\n        let metadata = include_str!(\"../testdata/review/snip_comments/metadata\");\n\n        let (r, _dir) = setup(review, metadata);\n        assert_eq_pretty!(r.resolve_snips(review).unwrap(), gold);\n    }\n\n    // Here we exhaustively check all possible single snips. It may be worth doing something\n    // similar for multiple snips but it'll be a bit more complicated to implement.\n    #[test]\n    fn test_snip_single_exhaustive() {\n        let gold = include_str!(\"../testdata/review/snip_single/gold\");\n        let metadata = include_str!(\"../testdata/review/snip_single/metadata\");\n        let (r, _dir) = setup(\"\", metadata);\n\n        let nr_lines = gold.lines().count();\n\n        for position in 0..=nr_lines {\n            for length in 0..=nr_lines {\n                let mut lines: VecDeque<&str> = gold.lines().collect();\n                let mut contents = String::new();\n                let mut idx = 0;\n\n                while !lines.is_empty() {\n                    if idx == position {\n                        writeln!(&mut contents, \"[...]\").unwrap();\n                        for _ in 0..length {\n                            lines.pop_front();\n                            idx += 1;\n                        }\n                    }\n\n                    // A snip appended to gold file will go past \"end\" of lines\n                    if let Some(line) = lines.pop_front() {\n                        writeln!(&mut contents, \"{line}\").unwrap();\n                    }\n\n                    idx += 1;\n                }\n\n                // Handle 0 length trailing snip\n                if idx == position {\n                    writeln!(&mut contents, \"[...]\").unwrap();\n                }\n\n                assert_eq_pretty!(r.resolve_snips(&contents).unwrap(), gold);\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "testdata/add_oneliner",
    "content": "> diff --git a/foo.rs b/foo.rs\n> new file mode 100644\n> index 0000000..5a64612\n> --- /dev/null\n> +++ b/foo.rs\n> @@ -0,0 +1 @@\n\nComment 1\n\n> +License: Unlicense\n\nComment 2\n"
  },
  {
    "path": "testdata/approve_review",
    "content": "@prr approve\n> diff --git a/libbpf-cargo/src/btf/btf.rs b/libbpf-cargo/src/btf/btf.rs\n> index a26b2a5..fffb281 100644\n> --- a/libbpf-cargo/src/btf/btf.rs\n> +++ b/libbpf-cargo/src/btf/btf.rs\n> @@ -731,7 +731,7 @@ impl<'a> Btf<'a> {\n\n>      fn load_type(&mut self, data: &'a [u8]) -> Result<BtfType<'a>> {\n>          let t = data.pread::<btf_type>(0)?;\n>          let extra = &data[size_of::<btf_type>()..];\n> -        let kind = (t.info >> 24) & 0xf;\n> +        let kind = (t.info >> 24) & 0x1f;\n\nComment 1\n\n>  \n>          match BtfKind::try_from(kind)? {\n>              BtfKind::Void => {\n> diff --git a/libbpf-cargo/src/test.rs b/libbpf-cargo/src/test.rs\n> index 5b08843..82a0586 100644\n> --- a/libbpf-cargo/src/test.rs\n> +++ b/libbpf-cargo/src/test.rs\n> @@ -2145,3 +2145,27 @@ pub struct __anon_3 {\n>  \n>      assert_definition(&btf, struct_bpf_sock_tuple, expected_output);\n>  }\n> +\n> +#[test]\n> +fn test_btf_dump_float() {\n> +    let prog_text = r#\"\n> +float f = 2.16;\n> +double d = 12.15;\n> +\"#;\n> +\n> +    let btf = build_btf_prog(prog_text);\n> +\n> +    let f = find_type_in_btf!(btf, Var, \"f\");\n> +    let d = find_type_in_btf!(btf, Var, \"d\");\n> +\n> +    assert_eq!(\n> +        \"f32\",\n> +        btf.type_declaration(f)\n> +            .expect(\"Failed to generate f decl\")\n> +    );\n> +    assert_eq!(\n> +        \"f64\",\n> +        btf.type_declaration(d)\n> +            .expect(\"Failed to generate d decl\")\n> +    );\n> +}\n"
  },
  {
    "path": "testdata/back_to_back_span",
    "content": "> diff --git a/libbpf-cargo/src/btf/btf.rs b/libbpf-cargo/src/btf/btf.rs\n> index a26b2a5..fffb281 100644\n> --- a/libbpf-cargo/src/btf/btf.rs\n> +++ b/libbpf-cargo/src/btf/btf.rs\n> @@ -731,7 +731,7 @@ impl<'a> Btf<'a> {\n\n>      fn load_type(&mut self, data: &'a [u8]) -> Result<BtfType<'a>> {\n>          let t = data.pread::<btf_type>(0)?;\n>          let extra = &data[size_of::<btf_type>()..];\n> -        let kind = (t.info >> 24) & 0xf;\n> +        let kind = (t.info >> 24) & 0x1f;\n\nComment 1\n\n>  \n>          match BtfKind::try_from(kind)? {\n>              BtfKind::Void => {\n\nComment 2\n\n> diff --git a/libbpf-cargo/src/test.rs b/libbpf-cargo/src/test.rs\n> index 5b08843..82a0586 100644\n> --- a/libbpf-cargo/src/test.rs\n> +++ b/libbpf-cargo/src/test.rs\n> @@ -2145,3 +2145,27 @@ pub struct __anon_3 {\n>  \n>      assert_definition(&btf, struct_bpf_sock_tuple, expected_output);\n>  }\n> +\n> +#[test]\n> +fn test_btf_dump_float() {\n> +    let prog_text = r#\"\n> +float f = 2.16;\n> +double d = 12.15;\n> +\"#;\n> +\n> +    let btf = build_btf_prog(prog_text);\n> +\n> +    let f = find_type_in_btf!(btf, Var, \"f\");\n> +    let d = find_type_in_btf!(btf, Var, \"d\");\n> +\n> +    assert_eq!(\n> +        \"f32\",\n> +        btf.type_declaration(f)\n> +            .expect(\"Failed to generate f decl\")\n> +    );\n> +    assert_eq!(\n> +        \"f64\",\n> +        btf.type_declaration(d)\n> +            .expect(\"Failed to generate d decl\")\n> +    );\n> +}\n"
  },
  {
    "path": "testdata/cross_file_span_ignored",
    "content": "> diff --git a/libbpf-cargo/src/btf/btf.rs b/libbpf-cargo/src/btf/btf.rs\n> index a26b2a5..fffb281 100644\n> --- a/libbpf-cargo/src/btf/btf.rs\n> +++ b/libbpf-cargo/src/btf/btf.rs\n> @@ -731,7 +731,7 @@ impl<'a> Btf<'a> {\n>      fn load_type(&mut self, data: &'a [u8]) -> Result<BtfType<'a>> {\n>          let t = data.pread::<btf_type>(0)?;\n>          let extra = &data[size_of::<btf_type>()..];\n> -        let kind = (t.info >> 24) & 0xf;\n\n> +        let kind = (t.info >> 24) & 0x1f;\n>  \n>          match BtfKind::try_from(kind)? {\n>              BtfKind::Void => {\n> diff --git a/libbpf-cargo/src/test.rs b/libbpf-cargo/src/test.rs\n> index 5b08843..82a0586 100644\n> --- a/libbpf-cargo/src/test.rs\n> +++ b/libbpf-cargo/src/test.rs\n> @@ -2145,3 +2145,27 @@ pub struct __anon_3 {\n>  \n>      assert_definition(&btf, struct_bpf_sock_tuple, expected_output);\n>  }\n> +\n> +#[test]\n> +fn test_btf_dump_float() {\n> +    let prog_text = r#\"\n> +float f = 2.16;\n> +double d = 12.15;\n> +\"#;\n> +\n> +    let btf = build_btf_prog(prog_text);\nComment 1\n> +\n> +    let f = find_type_in_btf!(btf, Var, \"f\");\n> +    let d = find_type_in_btf!(btf, Var, \"d\");\n> +\n> +    assert_eq!(\n> +        \"f32\",\n> +        btf.type_declaration(f)\n> +            .expect(\"Failed to generate f decl\")\n> +    );\n> +    assert_eq!(\n> +        \"f64\",\n> +        btf.type_declaration(d)\n> +            .expect(\"Failed to generate d decl\")\n> +    );\n> +}\n"
  },
  {
    "path": "testdata/cross_hunk_span",
    "content": "> diff --git a/ch2.txt b/ch2.txt\n> index 4d729e6..2641120 100644\n> --- a/ch2.txt\n> +++ b/ch2.txt\n> @@ -2,13 +2,6 @@ CHAPTER 2. WAGING WAR\n>  \n>  1.  Sun Tzu said: In the operations of war, where there are in the field a thousand swift chariots, as many heavy chariots, and a hundred thousand mail-clad soldiers, with provisions enough to carry them a thousand LI, the expenditure at home and at the front, including entertainment of guests, small items such as glue and paint, and sums spent on chariots and armor, will reach the total of a thousand ounces of silver per day. Such is the cost of raising an army of 100,000 men. \n>  \n\n> -2. When you engage in actual fighting, if victory is long in coming, then men's weapons will grow dull and their ardor will be damped. If you lay siege to a town, you will exhaust your strength. \n> -\n> -3. Again, if the campaign is protracted, the resources of the State will not be equal to the strain. \n> -\n> -4. Now, when your weapons are dulled, your ardor damped, your strength exhausted and your treasure spent, other chieftains will spring up to take advantage of your extremity. Then no man, however wise, will be able to avert the consequences that must ensue. \n> -\n> -5. Thus, though we have heard of stupid haste in war, cleverness has never been seen associated with long delays. \n>  \n>  6. There is no instance of a country having benefited from prolonged warfare. \n>  \n> @@ -30,6 +23,11 @@ CHAPTER 2. WAGING WAR\n>  \n>  16. Now in order to kill the enemy, our men must be roused to anger; that there may be advantage from defeating the enemy, they must have their rewards. \n>  \n> +asdf\n> +asdf\n> +asdf\n> +adsf\n> +\n\nCross span comment\n\n>  17. Therefore in chariot fighting, when ten or more chariots have been taken, those should be rewarded who took the first. Our own flags should be substituted for those of the enemy, and the chariots mingled and used in conjunction with ours. The captured soldiers should be kindly treated and kept. \n>  \n>  18. This is called, using the conquered foe to augment one's own strength. \n"
  },
  {
    "path": "testdata/deleted_file",
    "content": "> diff --git a/ch1.txt b/ch1.txt\n> deleted file mode 100644\n> index d30353f..0000000\n> --- a/ch1.txt\n> +++ /dev/null\n> @@ -1,59 +0,0 @@\n\n> -THE ART OF WAR BY SUN TZU\n> -\n> -Translated by Lionel Giles\n> -Originally published 1910\n> -\n> -This version was generated automatically at www.suntzusaid.com.\n> -\n> -\n> -CHAPTER 1. LAYING PLANS\n> -\n> -1.  Sun Tzu said: The art of war is of vital importance to the State. \n> -\n> -2. It is a matter of life and death, a road either to safety or to ruin. Hence it is a subject of inquiry which can on no account be neglected. \n> -\n> -3. The art of war, then, is governed by five constant factors, to be taken into account in one's deliberations, when seeking to determine the conditions obtaining in the field. \n> -\n> -4. These are: (1) The Moral Law; (2) Heaven; (3) Earth; (4) The Commander; (5) Method and discipline. \n> -\n> -5,6. The MORAL LAW causes the people to be in complete accord with their ruler, so that they will follow him regardless of their lives, undismayed by any danger. \n> -\n> -7. HEAVEN signifies night and day, cold and heat, times and seasons. \n> -\n> -8. EARTH comprises distances, great and small; danger and security; open ground and narrow passes; the chances of life and death. \n> -\n> -9. The COMMANDER stands for the virtues of wisdom, sincerity, benevolence, courage and strictness. \n> -\n> -10. By METHOD AND DISCIPLINE are to be understood the marshaling of the army in its proper subdivisions, the graduations of rank among the officers, the maintenance of roads by which supplies may reach the army, and the control of military expenditure. \n> -\n> -11. These five heads should be familiar to every general: he who knows them will be victorious; he who knows them not will fail. \n> -\n> -12. Therefore, in your deliberations, when seeking to determine the military conditions, let them be made the basis of a comparison, in this wise: \n> -\n> -13. (1) Which of the two sovereigns is imbued with the Moral law? (2) Which of the two generals has most ability? (3) With whom lie the advantages derived from Heaven and Earth? (4) On which side is discipline most rigorously enforced? (5) Which army is stronger? (6) On which side are officers and men more highly trained? (7) In which army is there the greater constancy both in reward and punishment? \n> -\n> -14. By means of these seven considerations I can forecast victory or defeat. \n> -\n> -15. The general that hearkens to my counsel and acts upon it, will conquer: let such a one be retained in command! The general that hearkens not to my counsel nor acts upon it, will suffer defeat: let such a one be dismissed! \n> -\n> -16. While heeding the profit of my counsel, avail yourself also of any helpful circumstances over and beyond the ordinary rules. \n> -\n> -17. According as circumstances are favorable, one should modify one's plans. \n> -\n> -18. All warfare is based on deception. \n> -\n> -19. Hence, when able to attack, we must seem unable; when using our forces, we must seem inactive; when we are near, we must make the enemy believe we are far away; when far away, we must make him believe we are near. \n> -\n> -20. Hold out baits to entice the enemy. Feign disorder, and crush him. \n> -\n> -21. If he is secure at all points, be prepared for him. If he is in superior strength, evade him. \n> -\n> -22. If your opponent is of choleric temper, seek to irritate him. Pretend to be weak, that he may grow arrogant. \n> -\n> -23. If he is taking his ease, give him no rest. If his forces are united, separate them. \n> -\n> -24. Attack him where he is unprepared, appear where you are not expected. \n> -\n> -25. These military devices, leading to victory, must not be divulged beforehand. \n> -\n\nComment 1\n\n> -26. Now the general who wins a battle makes many calculations in his temple ere the battle is fought. The general who loses a battle makes but few calculations beforehand. Thus do many calculations lead to victory, and few calculations to defeat: how much more no calculation at all! It is by attention to this point that I can foresee who is likely to win or lose. \n\n"
  },
  {
    "path": "testdata/empty_file",
    "content": "> diff --git a/libbpf-cargo/src/btf/btf.rs b/libbpf-cargo/src/btf/btf.rs\n> index 0000000..fffb281 100644\n> --- /dev/null\n> +++ b/libbpf-cargo/src/btf/btf.rs\n> diff --git a/libbpf-cargo/src/test.rs b/libbpf-cargo/src/test.rs\n> index 5b08843..82a0586 100644\n> --- a/libbpf-cargo/src/test.rs\n> +++ b/libbpf-cargo/src/test.rs\n> @@ -2145,3 +2145,27 @@ pub struct __anon_3 {\n>  \n>      assert_definition(&btf, struct_bpf_sock_tuple, expected_output);\n>  }\n> +\n> +#[test]\n> +fn test_btf_dump_float() {\n> +    let prog_text = r#\"\n> +float f = 2.16;\n> +double d = 12.15;\n> +\"#;\n> +\n> +    let btf = build_btf_prog(prog_text);\n> +\n> +    let f = find_type_in_btf!(btf, Var, \"f\");\n> +    let d = find_type_in_btf!(btf, Var, \"d\");\n\nComment\n\n> +\n> +    assert_eq!(\n> +        \"f32\",\n> +        btf.type_declaration(f)\n> +            .expect(\"Failed to generate f decl\")\n> +    );\n> +    assert_eq!(\n> +        \"f64\",\n> +        btf.type_declaration(d)\n> +            .expect(\"Failed to generate d decl\")\n> +    );\n> +}\n"
  },
  {
    "path": "testdata/file_comment",
    "content": "> diff --git a/libbpf-cargo/src/btf/btf.rs b/libbpf-cargo/src/btf/btf.rs\n\nThis is a file-level comment!\n\n> index a26b2a5..fffb281 100644\n> --- a/libbpf-cargo/src/btf/btf.rs\n> +++ b/libbpf-cargo/src/btf/btf.rs\n> @@ -731,7 +731,7 @@ impl<'a> Btf<'a> {\n>      fn load_type(&mut self, data: &'a [u8]) -> Result<BtfType<'a>> {\n>          let t = data.pread::<btf_type>(0)?;\n>          let extra = &data[size_of::<btf_type>()..];\n> -        let kind = (t.info >> 24) & 0xf;\n> +        let kind = (t.info >> 24) & 0x1f;\n>  \n>          match BtfKind::try_from(kind)? {\n>              BtfKind::Void => {\n> diff --git a/libbpf-cargo/src/test.rs b/libbpf-cargo/src/test.rs\n> index 5b08843..82a0586 100644\n> --- a/libbpf-cargo/src/test.rs\n> +++ b/libbpf-cargo/src/test.rs\n> @@ -2145,3 +2145,27 @@ pub struct __anon_3 {\n>  \n>      assert_definition(&btf, struct_bpf_sock_tuple, expected_output);\n>  }\n> +\n> +#[test]\n> +fn test_btf_dump_float() {\n> +    let prog_text = r#\"\n> +float f = 2.16;\n> +double d = 12.15;\n> +\"#;\n> +\n> +    let btf = build_btf_prog(prog_text);\n> +\n> +    let f = find_type_in_btf!(btf, Var, \"f\");\n> +    let d = find_type_in_btf!(btf, Var, \"d\");\n> +\n> +    assert_eq!(\n> +        \"f32\",\n> +        btf.type_declaration(f)\n> +            .expect(\"Failed to generate f decl\")\n> +    );\n> +    assert_eq!(\n> +        \"f64\",\n> +        btf.type_declaration(d)\n> +            .expect(\"Failed to generate d decl\")\n> +    );\n> +}\n"
  },
  {
    "path": "testdata/hunk_start_no_trailing_whitespace",
    "content": "> diff --git a/ch5.txt b/ch5.txt\n> new file mode 100644\n> index 0000000..762722f\n> --- /dev/null\n> +++ b/ch5.txt\n> @@ -0,0 +1,47 @@\n> +CHAPTER 5. ENERGY\n> +\n> +1. Sun Tzu said: The control of a large force is the same principle as the control of a few men: it is merely a question of dividing up their numbers. \n> +\n> +2. Fighting with a large army under your command is nowise different from fighting with a small one: it is merely a question of instituting signs and signals. \n> +\n> +3. To ensure that your whole host may withstand the brunt of the enemy's attack and remain unshaken---this is effected by maneuvers direct and indirect. \n\nGreat passage\n\n> +\n> +4. That the impact of your army may be like a grindstone dashed against an egg---this is effected by the science of weak points and strong. \n> +\n> +5. In all fighting, the direct method may be used for joining battle, but indirect methods will be needed in order to secure victory. \n> +\n> +6. Indirect tactics, efficiently applied, are inexhaustible as Heaven and Earth, unending as the flow of rivers and streams; like the sun and moon, they end but to begin anew; like the four seasons, they pass away to return once more. \n> +\n> +7. There are not more than five musical notes, yet the combinations of these five give rise to more melodies than can ever be heard. \n> +\n> +8. There are not more than five primary colors (blue, yellow, red, white, and black), yet in combination they produce more hues than can ever been seen. \n> +\n> +9. There are not more than five cardinal tastes (sour, acrid, salt, sweet, bitter), yet combinations of them yield more flavors than can ever be tasted. \n> +\n> +10. In battle, there are not more than two methods of attack: the direct and the indirect; yet these two in combination give rise to an endless series of maneuvers. \n> +\n> +11. The direct and the indirect lead on to each other in turn. It is like moving in a circle---you never come to an end.  Who can exhaust the possibilities of their combination? \n> +\n> +12. The onset of troops is like the rush of a torrent which will even roll stones along in its course. \n> +\n> +13. The quality of decision is like the well-timed swoop of a falcon which enables it to strike and destroy its victim. \n> +\n> +14. Therefore the good fighter will be terrible in his onset, and prompt in his decision. \n> +\n> +15. Energy may be likened to the bending of a crossbow; decision, to the releasing of a trigger. \n> +\n> +16. Amid the turmoil and tumult of battle, there may be seeming disorder and yet no real disorder at all; amid confusion and chaos, your array may be without head or tail, yet it will be proof against defeat. \n> +\n> +17. Simulated disorder postulates perfect discipline, simulated fear postulates courage; simulated weakness postulates strength. \n> +\n> +18. Hiding order beneath the cloak of disorder is simply a question of subdivision; concealing courage under a show of timidity presupposes a fund of latent energy; masking strength with weakness is to be effected by tactical dispositions. \n> +\n> +19. Thus one who is skillful at keeping the enemy on the move maintains deceitful appearances, according to which the enemy will act. He sacrifices something, that the enemy may snatch at it. \n> +\n> +20. By holding out baits, he keeps him on the march; then with a body of picked men he lies in wait for him. \n> +\n> +21. The clever combatant looks to the effect of combined energy, and does not require too much from individuals. Hence his ability to pick out the right men and utilize combined energy. \n> +\n> +22. When he utilizes combined energy, his fighting men become as it were like unto rolling logs or stones. For it is the nature of a log or stone to remain motionless on level ground, and to move when on a slope; if four-cornered, to come to a standstill, but if round-shaped, to go rolling down. \n> +\n> +23. Thus the energy developed by good fighting men is as the momentum of a round stone rolled down a mountain thousands of feet in height. So much on the subject of energy. \n"
  },
  {
    "path": "testdata/inline_and_review_comments_with_pr_description",
    "content": "Not necessary.\n\n@prr reject\n\n> This is just for testing purposes.\n> diff --git a/README.md b/README.md\n> index eda592e..ba84732 100644\n> --- a/README.md\n> +++ b/README.md\n> @@ -1,5 +1,5 @@\n> -MA-FSA for Go\n> -=============\n> +MA-FSA for Golang\n> +=================\n\nDoesn't seem necessary ...\n\n\n>  \n>  Package mafsa implements Minimal Acyclic Finite State Automata (MA-FSA)\n>  with Minimal Perfect Hashing (MPH). Basically, it's a set of strings that\n"
  },
  {
    "path": "testdata/multiline_comment",
    "content": "> diff --git a/libbpf-cargo/src/btf/btf.rs b/libbpf-cargo/src/btf/btf.rs\n> index a26b2a5..fffb281 100644\n> --- a/libbpf-cargo/src/btf/btf.rs\n> +++ b/libbpf-cargo/src/btf/btf.rs\n> @@ -731,7 +731,7 @@ impl<'a> Btf<'a> {\n>      fn load_type(&mut self, data: &'a [u8]) -> Result<BtfType<'a>> {\n>          let t = data.pread::<btf_type>(0)?;\n>          let extra = &data[size_of::<btf_type>()..];\n> -        let kind = (t.info >> 24) & 0xf;\n> +        let kind = (t.info >> 24) & 0x1f;\n>  \n>          match BtfKind::try_from(kind)? {\n\n\n\nComment line 1\nComment line 2\n\nComment line 4\n\n\n\n\n\n\n>              BtfKind::Void => {\n> diff --git a/libbpf-cargo/src/test.rs b/libbpf-cargo/src/test.rs\n> index 5b08843..82a0586 100644\n> --- a/libbpf-cargo/src/test.rs\n> +++ b/libbpf-cargo/src/test.rs\n> @@ -2145,3 +2145,27 @@ pub struct __anon_3 {\n>  \n>      assert_definition(&btf, struct_bpf_sock_tuple, expected_output);\n>  }\n> +\n> +#[test]\n> +fn test_btf_dump_float() {\n> +    let prog_text = r#\"\n> +float f = 2.16;\n> +double d = 12.15;\n> +\"#;\n> +\n> +    let btf = build_btf_prog(prog_text);\n> +\n> +    let f = find_type_in_btf!(btf, Var, \"f\");\n> +    let d = find_type_in_btf!(btf, Var, \"d\");\n> +\n> +    assert_eq!(\n> +        \"f32\",\n> +        btf.type_declaration(f)\n> +            .expect(\"Failed to generate f decl\")\n> +    );\n> +    assert_eq!(\n> +        \"f64\",\n> +        btf.type_declaration(d)\n> +            .expect(\"Failed to generate d decl\")\n> +    );\n> +}\n"
  },
  {
    "path": "testdata/multiple_files",
    "content": "> diff --git a/libbpf-cargo/src/btf/btf.rs b/libbpf-cargo/src/btf/btf.rs\n> index a26b2a5..fffb281 100644\n> --- a/libbpf-cargo/src/btf/btf.rs\n> +++ b/libbpf-cargo/src/btf/btf.rs\n> @@ -731,7 +731,7 @@ impl<'a> Btf<'a> {\n>      fn load_type(&mut self, data: &'a [u8]) -> Result<BtfType<'a>> {\n>          let t = data.pread::<btf_type>(0)?;\n>          let extra = &data[size_of::<btf_type>()..];\n> -        let kind = (t.info >> 24) & 0xf;\n> +        let kind = (t.info >> 24) & 0x1f;\nComment 1\n\n>  \n>          match BtfKind::try_from(kind)? {\n>              BtfKind::Void => {\n> diff --git a/libbpf-cargo/src/test.rs b/libbpf-cargo/src/test.rs\n> index 5b08843..82a0586 100644\n> --- a/libbpf-cargo/src/test.rs\n> +++ b/libbpf-cargo/src/test.rs\n> @@ -2145,3 +2145,27 @@ pub struct __anon_3 {\n>  \n>      assert_definition(&btf, struct_bpf_sock_tuple, expected_output);\n>  }\n> +\n> +#[test]\n> +fn test_btf_dump_float() {\n> +    let prog_text = r#\"\n> +float f = 2.16;\n> +double d = 12.15;\n> +\"#;\n> +\n> +    let btf = build_btf_prog(prog_text);\n> +\n> +    let f = find_type_in_btf!(btf, Var, \"f\");\n> +    let d = find_type_in_btf!(btf, Var, \"d\");\nComment 2\n> +\n> +    assert_eq!(\n> +        \"f32\",\n> +        btf.type_declaration(f)\n> +            .expect(\"Failed to generate f decl\")\n> +    );\n> +    assert_eq!(\n> +        \"f64\",\n> +        btf.type_declaration(d)\n> +            .expect(\"Failed to generate d decl\")\n> +    );\n> +}\n"
  },
  {
    "path": "testdata/reject_review",
    "content": "@prr reject\n> diff --git a/libbpf-cargo/src/btf/btf.rs b/libbpf-cargo/src/btf/btf.rs\n> index a26b2a5..fffb281 100644\n> --- a/libbpf-cargo/src/btf/btf.rs\n> +++ b/libbpf-cargo/src/btf/btf.rs\n> @@ -731,7 +731,7 @@ impl<'a> Btf<'a> {\n\n>      fn load_type(&mut self, data: &'a [u8]) -> Result<BtfType<'a>> {\n>          let t = data.pread::<btf_type>(0)?;\n>          let extra = &data[size_of::<btf_type>()..];\n> -        let kind = (t.info >> 24) & 0xf;\n> +        let kind = (t.info >> 24) & 0x1f;\n\nComment 1\n\n>  \n>          match BtfKind::try_from(kind)? {\n>              BtfKind::Void => {\n> diff --git a/libbpf-cargo/src/test.rs b/libbpf-cargo/src/test.rs\n> index 5b08843..82a0586 100644\n> --- a/libbpf-cargo/src/test.rs\n> +++ b/libbpf-cargo/src/test.rs\n> @@ -2145,3 +2145,27 @@ pub struct __anon_3 {\n>  \n>      assert_definition(&btf, struct_bpf_sock_tuple, expected_output);\n>  }\n> +\n> +#[test]\n> +fn test_btf_dump_float() {\n> +    let prog_text = r#\"\n> +float f = 2.16;\n> +double d = 12.15;\n> +\"#;\n> +\n> +    let btf = build_btf_prog(prog_text);\n> +\n> +    let f = find_type_in_btf!(btf, Var, \"f\");\n> +    let d = find_type_in_btf!(btf, Var, \"d\");\n> +\n> +    assert_eq!(\n> +        \"f32\",\n> +        btf.type_declaration(f)\n> +            .expect(\"Failed to generate f decl\")\n> +    );\n> +    assert_eq!(\n> +        \"f64\",\n> +        btf.type_declaration(d)\n> +            .expect(\"Failed to generate d decl\")\n> +    );\n> +}\n"
  },
  {
    "path": "testdata/review/apply_pr/review/.1",
    "content": "{\"original\":\"Much better this way!\\n\\ndiff --git a/README.md b/README.md\\nindex 007306a..1a480f2 100644\\n--- a/README.md\\n+++ b/README.md\\n@@ -1,4 +1,4 @@\\n For testing\\n ===========\\n \\n-This is a readme\\n+This is a better readme line!\\n\",\"submitted\":null,\"commit_id\":\"7e427a4fffc13a306d91deba55957dc800ee50a8\"}"
  },
  {
    "path": "testdata/review/apply_pr/review/1.prr",
    "content": "> Much better this way!\n> \n> diff --git a/README.md b/README.md\n> index 007306a..1a480f2 100644\n> --- a/README.md\n> +++ b/README.md\n> @@ -1,4 +1,4 @@\n>  For testing\n>  ===========\n>  \n> -This is a readme\n> +This is a better readme line!\n"
  },
  {
    "path": "testdata/review/pr_description/metadata",
    "content": "{\"original\":\"This is just for testing purposes.\\ndiff --git a/README.md b/README.md\\nindex eda592e..ba84732 100644\\n--- a/README.md\\n+++ b/README.md\\n@@ -1,5 +1,5 @@\\n-MA-FSA for Go\\n-=============\\n+MA-FSA for Golang\\n+=================\\n \\n Package mafsa implements Minimal Acyclic Finite State Automata (MA-FSA)\\n with Minimal Perfect Hashing (MPH). Basically, it's a set of strings that\\n\",\"submitted\":null,\"commit_id\":\"2c4e14eeb62b2279f185cec0eb986e388da96760\"}"
  },
  {
    "path": "testdata/review/pr_description/review",
    "content": "Not necessary but seems ok.\n\n@prr approve\n\n> This is just for testing purposes.\n> diff --git a/README.md b/README.md\n> index eda592e..ba84732 100644\n> --- a/README.md\n> +++ b/README.md\n> @@ -1,5 +1,5 @@\n> -MA-FSA for Go\n> -=============\n> +MA-FSA for Golang\n> +=================\n\nDoesn't seem necessary ...\n\n\n>  \n>  Package mafsa implements Minimal Acyclic Finite State Automata (MA-FSA)\n>  with Minimal Perfect Hashing (MPH). Basically, it's a set of strings that\n"
  },
  {
    "path": "testdata/review/pr_description_interleaving/metadata",
    "content": "{\"original\":\"This is just for testing purposes.\\ndiff --git a/README.md b/README.md\\nindex eda592e..ba84732 100644\\n--- a/README.md\\n+++ b/README.md\\n@@ -1,5 +1,5 @@\\n-MA-FSA for Go\\n-=============\\n+MA-FSA for Golang\\n+=================\\n \\n Package mafsa implements Minimal Acyclic Finite State Automata (MA-FSA)\\n with Minimal Perfect Hashing (MPH). Basically, it's a set of strings that\\n\",\"submitted\":null,\"commit_id\":\"2c4e14eeb62b2279f185cec0eb986e388da96760\"}"
  },
  {
    "path": "testdata/review/pr_description_interleaving/review",
    "content": "Not necessary.\n\n@prr reject\n\n> This is just for testing purposes.\n\nThis might be fine or not.\n\n> diff --git a/README.md b/README.md\n> index eda592e..ba84732 100644\n> --- a/README.md\n> +++ b/README.md\n> @@ -1,5 +1,5 @@\n> -MA-FSA for Go\n> -=============\n> +MA-FSA for Golang\n> +=================\n\nDoesn't seem necessary ...\n\n\n>  \n>  Package mafsa implements Minimal Acyclic Finite State Automata (MA-FSA)\n>  with Minimal Perfect Hashing (MPH). Basically, it's a set of strings that\n"
  },
  {
    "path": "testdata/review/snip_comments/gold",
    "content": "> diff --git a/src/review.rs b/src/review.rs\n\n\nfile comment!\n> index e39fd6f..e94680e 100644\n> --- a/src/review.rs\n> +++ b/src/review.rs\n> @@ -155,7 +155,7 @@ impl Review {\n>          fs::create_dir_all(review_dir).context(\"Failed to create workdir directories\")?;\n>  \n>          // Check if there are unsubmitted changes\n> -        if !force && review.status()? == ReviewStatus::Reviewed {\n> +        if !force && review.has_metadata() && review.status()? == ReviewStatus::Reviewed {\nwoah!\n>              bail!(\n>                  \"You have unsubmitted changes to the requested review. \\\n>                  Either submit the existing changes, delete the existing review file, \\\n> @@ -353,6 +353,10 @@ impl Review {\n>          serde_json::from_str::<ReviewMetadata>(&meta).context(\"Failed to parse metadata file\")\n>      }\n>  \n> +    fn has_metadata(&self) -> bool {\nnice\n\n> +        fs::metadata(self.metadata_path()).is_ok()\n\nsheesh\n\n> +    }\n> +\n>      fn metadata_path(&self) -> PathBuf {\n>          let mut metadata_path = self.path();\n>          metadata_path.set_file_name(format!(\".{}\", self.pr_num));\n"
  },
  {
    "path": "testdata/review/snip_comments/metadata",
    "content": "{\"original\":\"diff --git a/src/review.rs b/src/review.rs\\nindex e39fd6f..e94680e 100644\\n--- a/src/review.rs\\n+++ b/src/review.rs\\n@@ -155,7 +155,7 @@ impl Review {\\n         fs::create_dir_all(review_dir).context(\\\"Failed to create workdir directories\\\")?;\\n \\n         // Check if there are unsubmitted changes\\n-        if !force && review.status()? == ReviewStatus::Reviewed {\\n+        if !force && review.has_metadata() && review.status()? == ReviewStatus::Reviewed {\\n             bail!(\\n                 \\\"You have unsubmitted changes to the requested review. \\\\\\n                 Either submit the existing changes, delete the existing review file, \\\\\\n@@ -353,6 +353,10 @@ impl Review {\\n         serde_json::from_str::<ReviewMetadata>(&meta).context(\\\"Failed to parse metadata file\\\")\\n     }\\n \\n+    fn has_metadata(&self) -> bool {\\n+        fs::metadata(self.metadata_path()).is_ok()\\n+    }\\n+\\n     fn metadata_path(&self) -> PathBuf {\\n         let mut metadata_path = self.path();\\n         metadata_path.set_file_name(format!(\\\".{}\\\", self.pr_num));\\n\",\"submitted\":null,\"commit_id\":\"1fa28537aa07ac608e9d5bc4ed953ddd4b348cee\"}"
  },
  {
    "path": "testdata/review/snip_comments/review",
    "content": "> diff --git a/src/review.rs b/src/review.rs\n\n\nfile comment!\n[...]\n> -        if !force && review.status()? == ReviewStatus::Reviewed {\n> +        if !force && review.has_metadata() && review.status()? == ReviewStatus::Reviewed {\nwoah!\n>              bail!(\n>                  \"You have unsubmitted changes to the requested review. \\\n>                  Either submit the existing changes, delete the existing review file, \\\n> @@ -353,6 +353,10 @@ impl Review {\n>          serde_json::from_str::<ReviewMetadata>(&meta).context(\"Failed to parse metadata file\")\n>      }\n[...]\nnice\n\n> +        fs::metadata(self.metadata_path()).is_ok()\n\nsheesh\n\n[...]\n"
  },
  {
    "path": "testdata/review/snip_multiple/gold",
    "content": "> diff --git a/src/review.rs b/src/review.rs\n> index e39fd6f..e94680e 100644\n> --- a/src/review.rs\n> +++ b/src/review.rs\n> @@ -155,7 +155,7 @@ impl Review {\n>          fs::create_dir_all(review_dir).context(\"Failed to create workdir directories\")?;\n>  \n>          // Check if there are unsubmitted changes\n> -        if !force && review.status()? == ReviewStatus::Reviewed {\n> +        if !force && review.has_metadata() && review.status()? == ReviewStatus::Reviewed {\n>              bail!(\n>                  \"You have unsubmitted changes to the requested review. \\\n>                  Either submit the existing changes, delete the existing review file, \\\n> @@ -353,6 +353,10 @@ impl Review {\n>          serde_json::from_str::<ReviewMetadata>(&meta).context(\"Failed to parse metadata file\")\n>      }\n>  \n> +    fn has_metadata(&self) -> bool {\n> +        fs::metadata(self.metadata_path()).is_ok()\n> +    }\n> +\n>      fn metadata_path(&self) -> PathBuf {\n>          let mut metadata_path = self.path();\n>          metadata_path.set_file_name(format!(\".{}\", self.pr_num));\n"
  },
  {
    "path": "testdata/review/snip_multiple/metadata",
    "content": "{\"original\":\"diff --git a/src/review.rs b/src/review.rs\\nindex e39fd6f..e94680e 100644\\n--- a/src/review.rs\\n+++ b/src/review.rs\\n@@ -155,7 +155,7 @@ impl Review {\\n         fs::create_dir_all(review_dir).context(\\\"Failed to create workdir directories\\\")?;\\n \\n         // Check if there are unsubmitted changes\\n-        if !force && review.status()? == ReviewStatus::Reviewed {\\n+        if !force && review.has_metadata() && review.status()? == ReviewStatus::Reviewed {\\n             bail!(\\n                 \\\"You have unsubmitted changes to the requested review. \\\\\\n                 Either submit the existing changes, delete the existing review file, \\\\\\n@@ -353,6 +353,10 @@ impl Review {\\n         serde_json::from_str::<ReviewMetadata>(&meta).context(\\\"Failed to parse metadata file\\\")\\n     }\\n \\n+    fn has_metadata(&self) -> bool {\\n+        fs::metadata(self.metadata_path()).is_ok()\\n+    }\\n+\\n     fn metadata_path(&self) -> PathBuf {\\n         let mut metadata_path = self.path();\\n         metadata_path.set_file_name(format!(\\\".{}\\\", self.pr_num));\\n\",\"submitted\":null,\"commit_id\":\"1fa28537aa07ac608e9d5bc4ed953ddd4b348cee\"}"
  },
  {
    "path": "testdata/review/snip_multiple/review",
    "content": "[...]\n> index e39fd6f..e94680e 100644\n[..]\n> +++ b/src/review.rs\n> @@ -155,7 +155,7 @@ impl Review {\n>          fs::create_dir_all(review_dir).context(\"Failed to create workdir directories\")?;\n>  \n[...]\n> +        if !force && review.has_metadata() && review.status()? == ReviewStatus::Reviewed {\n>              bail!(\n>                  \"You have unsubmitted changes to the requested review. \\\n[...]\n>      }\n>  \n> +    fn has_metadata(&self) -> bool {\n> +        fs::metadata(self.metadata_path()).is_ok()\n> +    }\n> +\n>      fn metadata_path(&self) -> PathBuf {\n[..]\n"
  },
  {
    "path": "testdata/review/snip_single/gold",
    "content": "> diff --git a/src/review.rs b/src/review.rs\n> index e39fd6f..e94680e 100644\n> --- a/src/review.rs\n> +++ b/src/review.rs\n> @@ -155,7 +155,7 @@ impl Review {\n>          fs::create_dir_all(review_dir).context(\"Failed to create workdir directories\")?;\n>  \n>          // Check if there are unsubmitted changes\n> -        if !force && review.status()? == ReviewStatus::Reviewed {\n> +        if !force && review.has_metadata() && review.status()? == ReviewStatus::Reviewed {\n>              bail!(\n>                  \"You have unsubmitted changes to the requested review. \\\n>                  Either submit the existing changes, delete the existing review file, \\\n> @@ -353,6 +353,10 @@ impl Review {\n>          serde_json::from_str::<ReviewMetadata>(&meta).context(\"Failed to parse metadata file\")\n>      }\n>  \n> +    fn has_metadata(&self) -> bool {\n> +        fs::metadata(self.metadata_path()).is_ok()\n> +    }\n> +\n>      fn metadata_path(&self) -> PathBuf {\n>          let mut metadata_path = self.path();\n>          metadata_path.set_file_name(format!(\".{}\", self.pr_num));\n"
  },
  {
    "path": "testdata/review/snip_single/metadata",
    "content": "{\"original\":\"diff --git a/src/review.rs b/src/review.rs\\nindex e39fd6f..e94680e 100644\\n--- a/src/review.rs\\n+++ b/src/review.rs\\n@@ -155,7 +155,7 @@ impl Review {\\n         fs::create_dir_all(review_dir).context(\\\"Failed to create workdir directories\\\")?;\\n \\n         // Check if there are unsubmitted changes\\n-        if !force && review.status()? == ReviewStatus::Reviewed {\\n+        if !force && review.has_metadata() && review.status()? == ReviewStatus::Reviewed {\\n             bail!(\\n                 \\\"You have unsubmitted changes to the requested review. \\\\\\n                 Either submit the existing changes, delete the existing review file, \\\\\\n@@ -353,6 +353,10 @@ impl Review {\\n         serde_json::from_str::<ReviewMetadata>(&meta).context(\\\"Failed to parse metadata file\\\")\\n     }\\n \\n+    fn has_metadata(&self) -> bool {\\n+        fs::metadata(self.metadata_path()).is_ok()\\n+    }\\n+\\n     fn metadata_path(&self) -> PathBuf {\\n         let mut metadata_path = self.path();\\n         metadata_path.set_file_name(format!(\\\".{}\\\", self.pr_num));\\n\",\"submitted\":null,\"commit_id\":\"1fa28537aa07ac608e9d5bc4ed953ddd4b348cee\"}"
  },
  {
    "path": "testdata/review/snip_single/review",
    "content": "> diff --git a/src/review.rs b/src/review.rs\n[...]\n>      }\n>  \n> +    fn has_metadata(&self) -> bool {\n> +        fs::metadata(self.metadata_path()).is_ok()\n> +    }\n> +\n>      fn metadata_path(&self) -> PathBuf {\n>          let mut metadata_path = self.path();\n>          metadata_path.set_file_name(format!(\".{}\", self.pr_num));\n"
  },
  {
    "path": "testdata/review/status/metadata",
    "content": "{\"original\":\"diff --git a/src/utils.cpp b/src/utils.cpp\\nindex b02c16bc3df..fca25d6c839 100644\\n--- a/src/utils.cpp\\n+++ b/src/utils.cpp\\n@@ -1,5 +1,6 @@\\n #include <algorithm>\\n #include <array>\\n+#include <climits>\\n #include <cmath>\\n #include <cstring>\\n #include <errno.h>\\n\",\"submitted\":null,\"commit_id\":\"58c3ef68bbb9082e5a16449baa15c18ccf7e5707\"}"
  },
  {
    "path": "testdata/review/status/review",
    "content": "> diff --git a/src/utils.cpp b/src/utils.cpp\n> index b02c16bc3df..fca25d6c839 100644\n> --- a/src/utils.cpp\n> +++ b/src/utils.cpp\n> @@ -1,5 +1,6 @@\n>  #include <algorithm>\n>  #include <array>\n> +#include <climits>\n>  #include <cmath>\n>  #include <cstring>\n>  #include <errno.h>\n"
  },
  {
    "path": "testdata/review/trailing_whitespace/metadata",
    "content": "{\"original\":\"diff --git a/ch2.txt b/ch2.txt\\nindex 4d729e6..2641120 100644\\n--- a/ch2.txt\\n+++ b/ch2.txt\\n@@ -2,13 +2,6 @@ CHAPTER 2. WAGING WAR\\n \\n 1.  Sun Tzu said: In the operations of war, where there are in the field a thousand swift chariots, as many heavy chariots, and a hundred thousand mail-clad soldiers, with provisions enough to carry them a thousand LI, the expenditure at home and at the front, including entertainment of guests, small items such as glue and paint, and sums spent on chariots and armor, will reach the total of a thousand ounces of silver per day. Such is the cost of raising an army of 100,000 men. \\n \\n-2. When you engage in actual fighting, if victory is long in coming, then men's weapons will grow dull and their ardor will be damped. If you lay siege to a town, you will exhaust your strength. \\n-\\n-3. Again, if the campaign is protracted, the resources of the State will not be equal to the strain. \\n-\\n-4. Now, when your weapons are dulled, your ardor damped, your strength exhausted and your treasure spent, other chieftains will spring up to take advantage of your extremity. Then no man, however wise, will be able to avert the consequences that must ensue. \\n-\\n-5. Thus, though we have heard of stupid haste in war, cleverness has never been seen associated with long delays. \\n \\n 6. There is no instance of a country having benefited from prolonged warfare. \\n \\n@@ -30,6 +23,11 @@ CHAPTER 2. WAGING WAR\\n \\n 16. Now in order to kill the enemy, our men must be roused to anger; that there may be advantage from defeating the enemy, they must have their rewards. \\n \\n+asdf\\n+asdf\\n+asdf\\n+adsf\\n+\\n 17. Therefore in chariot fighting, when ten or more chariots have been taken, those should be rewarded who took the first. Our own flags should be substituted for those of the enemy, and the chariots mingled and used in conjunction with ours. The captured soldiers should be kindly treated and kept. \\n \\n 18. This is called, using the conquered foe to augment one's own strength. \\n\",\"submitted\":null,\"commit_id\":\"ddb1d0d0d4accb2e9e39feb4597a7be1f21b62a9\"}"
  },
  {
    "path": "testdata/review/trailing_whitespace/review",
    "content": "> diff --git a/ch2.txt b/ch2.txt\n> index 4d729e6..2641120 100644\n> --- a/ch2.txt\n> +++ b/ch2.txt\n> @@ -2,13 +2,6 @@ CHAPTER 2. WAGING WAR\n>\n>  1.  Sun Tzu said: In the operations of war, where there are in the field a thousand swift chariots, as many heavy chariots, and a hundred thousand mail-clad soldiers, with provisions enough to carry them a thousand LI, the expenditure at home and at the front, including entertainment of guests, small items such as glue and paint, and sums spent on chariots and armor, will reach the total of a thousand ounces of silver per day. Such is the cost of raising an army of 100,000 men.\n>\n> -2. When you engage in actual fighting, if victory is long in coming, then men's weapons will grow dull and their ardor will be damped. If you lay siege to a town, you will exhaust your strength.\n> -\n> -3. Again, if the campaign is protracted, the resources of the State will not be equal to the strain.\n> -\n> -4. Now, when your weapons are dulled, your ardor damped, your strength exhausted and your treasure spent, other chieftains will spring up to take advantage of your extremity. Then no man, however wise, will be able to avert the consequences that must ensue.\n> -\n> -5. Thus, though we have heard of stupid haste in war, cleverness has never been seen associated with long delays.\n>\n>  6. There is no instance of a country having benefited from prolonged warfare.\n>\n> @@ -30,6 +23,11 @@ CHAPTER 2. WAGING WAR\n>\n>  16. Now in order to kill the enemy, our men must be roused to anger; that there may be advantage from defeating the enemy, they must have their rewards.\n>\n> +asdf\n> +asdf\n> +asdf\n> +adsf\n> +\n>  17. Therefore in chariot fighting, when ten or more chariots have been taken, those should be rewarded who took the first. Our own flags should be substituted for those of the enemy, and the chariots mingled and used in conjunction with ours. The captured soldiers should be kindly treated and kept.\n>\n>  18. This is called, using the conquered foe to augment one's own strength.\n"
  },
  {
    "path": "testdata/review_comment",
    "content": "\nReview comment\n\n> diff --git a/libbpf-cargo/src/btf/btf.rs b/libbpf-cargo/src/btf/btf.rs\n> index a26b2a5..fffb281 100644\n> --- a/libbpf-cargo/src/btf/btf.rs\n> +++ b/libbpf-cargo/src/btf/btf.rs\n> @@ -731,7 +731,7 @@ impl<'a> Btf<'a> {\n\n>      fn load_type(&mut self, data: &'a [u8]) -> Result<BtfType<'a>> {\n>          let t = data.pread::<btf_type>(0)?;\n>          let extra = &data[size_of::<btf_type>()..];\n> -        let kind = (t.info >> 24) & 0xf;\n> +        let kind = (t.info >> 24) & 0x1f;\n\nComment 1\n\n>  \n>          match BtfKind::try_from(kind)? {\n>              BtfKind::Void => {\n> diff --git a/libbpf-cargo/src/test.rs b/libbpf-cargo/src/test.rs\n> index 5b08843..82a0586 100644\n> --- a/libbpf-cargo/src/test.rs\n> +++ b/libbpf-cargo/src/test.rs\n> @@ -2145,3 +2145,27 @@ pub struct __anon_3 {\n>  \n>      assert_definition(&btf, struct_bpf_sock_tuple, expected_output);\n>  }\n> +\n> +#[test]\n> +fn test_btf_dump_float() {\n> +    let prog_text = r#\"\n> +float f = 2.16;\n> +double d = 12.15;\n> +\"#;\n> +\n> +    let btf = build_btf_prog(prog_text);\n> +\n> +    let f = find_type_in_btf!(btf, Var, \"f\");\n> +    let d = find_type_in_btf!(btf, Var, \"d\");\n> +\n> +    assert_eq!(\n> +        \"f32\",\n> +        btf.type_declaration(f)\n> +            .expect(\"Failed to generate f decl\")\n> +    );\n> +    assert_eq!(\n> +        \"f64\",\n> +        btf.type_declaration(d)\n> +            .expect(\"Failed to generate d decl\")\n> +    );\n> +}\n"
  },
  {
    "path": "testdata/review_comment_whitespace",
    "content": "\n@prr approve\n\nReview comment\n\n\n> diff --git a/libbpf-cargo/src/btf/btf.rs b/libbpf-cargo/src/btf/btf.rs\n> index a26b2a5..fffb281 100644\n> --- a/libbpf-cargo/src/btf/btf.rs\n> +++ b/libbpf-cargo/src/btf/btf.rs\n> @@ -731,7 +731,7 @@ impl<'a> Btf<'a> {\n>      fn load_type(&mut self, data: &'a [u8]) -> Result<BtfType<'a>> {\n>          let t = data.pread::<btf_type>(0)?;\n>          let extra = &data[size_of::<btf_type>()..];\n> -        let kind = (t.info >> 24) & 0xf;\n> +        let kind = (t.info >> 24) & 0x1f;\n>  \n>          match BtfKind::try_from(kind)? {\n>              BtfKind::Void => {\n> diff --git a/libbpf-cargo/src/test.rs b/libbpf-cargo/src/test.rs\n> index 5b08843..82a0586 100644\n> --- a/libbpf-cargo/src/test.rs\n> +++ b/libbpf-cargo/src/test.rs\n> @@ -2145,3 +2145,27 @@ pub struct __anon_3 {\n>  \n>      assert_definition(&btf, struct_bpf_sock_tuple, expected_output);\n>  }\n> +\n> +#[test]\n> +fn test_btf_dump_float() {\n> +    let prog_text = r#\"\n> +float f = 2.16;\n> +double d = 12.15;\n> +\"#;\n> +\n> +    let btf = build_btf_prog(prog_text);\n> +\n> +    let f = find_type_in_btf!(btf, Var, \"f\");\n> +    let d = find_type_in_btf!(btf, Var, \"d\");\n> +\n> +    assert_eq!(\n> +        \"f32\",\n> +        btf.type_declaration(f)\n> +            .expect(\"Failed to generate f decl\")\n> +    );\n> +    assert_eq!(\n> +        \"f64\",\n> +        btf.type_declaration(d)\n> +            .expect(\"Failed to generate d decl\")\n> +    );\n> +}\n"
  },
  {
    "path": "testdata/review_comments_interleaved_with_pr_description",
    "content": "Not necessary.\n\n\n> This is just for testing purposes.\n\nThis might be fine or not.\n\n@prr reject\n\n> diff --git a/README.md b/README.md\n> index eda592e..ba84732 100644\n> --- a/README.md\n> +++ b/README.md\n> @@ -1,5 +1,5 @@\n> -MA-FSA for Go\n> -=============\n> +MA-FSA for Golang\n> +=================\n\nDoesn't seem necessary ...\n\n\n>  \n>  Package mafsa implements Minimal Acyclic Finite State Automata (MA-FSA)\n>  with Minimal Perfect Hashing (MPH). Basically, it's a set of strings that\n"
  },
  {
    "path": "testdata/single_comment",
    "content": "> diff --git a/libbpf-cargo/src/btf/btf.rs b/libbpf-cargo/src/btf/btf.rs\n> index a26b2a5..fffb281 100644\n> --- a/libbpf-cargo/src/btf/btf.rs\n> +++ b/libbpf-cargo/src/btf/btf.rs\n> @@ -731,7 +731,7 @@ impl<'a> Btf<'a> {\n\n>      fn load_type(&mut self, data: &'a [u8]) -> Result<BtfType<'a>> {\n>          let t = data.pread::<btf_type>(0)?;\n>          let extra = &data[size_of::<btf_type>()..];\n> -        let kind = (t.info >> 24) & 0xf;\n> +        let kind = (t.info >> 24) & 0x1f;\n\nComment 1\n\n>  \n>          match BtfKind::try_from(kind)? {\n>              BtfKind::Void => {\n> diff --git a/libbpf-cargo/src/test.rs b/libbpf-cargo/src/test.rs\n> index 5b08843..82a0586 100644\n> --- a/libbpf-cargo/src/test.rs\n> +++ b/libbpf-cargo/src/test.rs\n> @@ -2145,3 +2145,27 @@ pub struct __anon_3 {\n>  \n>      assert_definition(&btf, struct_bpf_sock_tuple, expected_output);\n>  }\n> +\n> +#[test]\n> +fn test_btf_dump_float() {\n> +    let prog_text = r#\"\n> +float f = 2.16;\n> +double d = 12.15;\n> +\"#;\n> +\n> +    let btf = build_btf_prog(prog_text);\n> +\n> +    let f = find_type_in_btf!(btf, Var, \"f\");\n> +    let d = find_type_in_btf!(btf, Var, \"d\");\n> +\n> +    assert_eq!(\n> +        \"f32\",\n> +        btf.type_declaration(f)\n> +            .expect(\"Failed to generate f decl\")\n> +    );\n> +    assert_eq!(\n> +        \"f64\",\n> +        btf.type_declaration(d)\n> +            .expect(\"Failed to generate d decl\")\n> +    );\n> +}\n"
  },
  {
    "path": "testdata/spaces_in_filename",
    "content": "> diff --git a/build/scripts/grafana/provisioning/dashboards/Docker Prometheus Monitoring-1571332751387.json b/build/scripts/grafana/provisioning/dashboards/Docker Prometheus Monitoring-1571332751387.json\n> new file mode 100644\n> index 0000000..5daac7b\n> --- /dev/null\n> +++ b/build/scripts/grafana/provisioning/dashboards/Docker Prometheus Monitoring-1571332751387.json\t\n> @@ -0,0 +1,1831 @@\n> +{\n> +    \"annotations\": {\nfoo\n> +      \"list\": [\n> +        {\n> +          \"builtIn\": 1,\n> +          \"datasource\": \"-- Grafana --\",\n\n"
  },
  {
    "path": "testdata/testgitrepo/README-applied.md",
    "content": "For testing\n===========\n\nThis is a better readme line!\n"
  },
  {
    "path": "testdata/testgitrepo/README.md",
    "content": "For testing\n===========\n\nThis is a readme\n"
  },
  {
    "path": "testdata/trailing_comment",
    "content": "> diff --git a/ch1.txt b/ch1.txt\n> deleted file mode 100644\n> index d30353f..0000000\n> --- a/ch1.txt\n> +++ /dev/null\n> @@ -1,59 +0,0 @@\n\n> -THE ART OF WAR BY SUN TZU\n> -\n> -Translated by Lionel Giles\n> -Originally published 1910\n> -\n> -This version was generated automatically at www.suntzusaid.com.\n> -\n> -\n> -CHAPTER 1. LAYING PLANS\n> -\n> -1.  Sun Tzu said: The art of war is of vital importance to the State. \n> -\n> -2. It is a matter of life and death, a road either to safety or to ruin. Hence it is a subject of inquiry which can on no account be neglected. \n> -\n> -3. The art of war, then, is governed by five constant factors, to be taken into account in one's deliberations, when seeking to determine the conditions obtaining in the field. \n> -\n> -4. These are: (1) The Moral Law; (2) Heaven; (3) Earth; (4) The Commander; (5) Method and discipline. \n> -\n> -5,6. The MORAL LAW causes the people to be in complete accord with their ruler, so that they will follow him regardless of their lives, undismayed by any danger. \n> -\n> -7. HEAVEN signifies night and day, cold and heat, times and seasons. \n> -\n> -8. EARTH comprises distances, great and small; danger and security; open ground and narrow passes; the chances of life and death. \n> -\n> -9. The COMMANDER stands for the virtues of wisdom, sincerity, benevolence, courage and strictness. \n> -\n> -10. By METHOD AND DISCIPLINE are to be understood the marshaling of the army in its proper subdivisions, the graduations of rank among the officers, the maintenance of roads by which supplies may reach the army, and the control of military expenditure. \n> -\n> -11. These five heads should be familiar to every general: he who knows them will be victorious; he who knows them not will fail. \n> -\n> -12. Therefore, in your deliberations, when seeking to determine the military conditions, let them be made the basis of a comparison, in this wise: \n> -\n> -13. (1) Which of the two sovereigns is imbued with the Moral law? (2) Which of the two generals has most ability? (3) With whom lie the advantages derived from Heaven and Earth? (4) On which side is discipline most rigorously enforced? (5) Which army is stronger? (6) On which side are officers and men more highly trained? (7) In which army is there the greater constancy both in reward and punishment? \n> -\n> -14. By means of these seven considerations I can forecast victory or defeat. \n> -\n> -15. The general that hearkens to my counsel and acts upon it, will conquer: let such a one be retained in command! The general that hearkens not to my counsel nor acts upon it, will suffer defeat: let such a one be dismissed! \n> -\n> -16. While heeding the profit of my counsel, avail yourself also of any helpful circumstances over and beyond the ordinary rules. \n> -\n> -17. According as circumstances are favorable, one should modify one's plans. \n> -\n> -18. All warfare is based on deception. \n> -\n> -19. Hence, when able to attack, we must seem unable; when using our forces, we must seem inactive; when we are near, we must make the enemy believe we are far away; when far away, we must make him believe we are near. \n> -\n> -20. Hold out baits to entice the enemy. Feign disorder, and crush him. \n> -\n> -21. If he is secure at all points, be prepared for him. If he is in superior strength, evade him. \n> -\n> -22. If your opponent is of choleric temper, seek to irritate him. Pretend to be weak, that he may grow arrogant. \n> -\n> -23. If he is taking his ease, give him no rest. If his forces are united, separate them. \n> -\n> -24. Attack him where he is unprepared, appear where you are not expected. \n> -\n> -25. These military devices, leading to victory, must not be divulged beforehand. \n> -\n> -26. Now the general who wins a battle makes many calculations in his temple ere the battle is fought. The general who loses a battle makes but few calculations beforehand. Thus do many calculations lead to victory, and few calculations to defeat: how much more no calculation at all! It is by attention to this point that I can foresee who is likely to win or lose. \n\nComment 1\n\n"
  },
  {
    "path": "testdata/unknown_directive",
    "content": "@prr asdf\n> diff --git a/libbpf-cargo/src/btf/btf.rs b/libbpf-cargo/src/btf/btf.rs\n> index a26b2a5..fffb281 100644\n> --- a/libbpf-cargo/src/btf/btf.rs\n> +++ b/libbpf-cargo/src/btf/btf.rs\n> @@ -731,7 +731,7 @@ impl<'a> Btf<'a> {\n\n>      fn load_type(&mut self, data: &'a [u8]) -> Result<BtfType<'a>> {\n>          let t = data.pread::<btf_type>(0)?;\n>          let extra = &data[size_of::<btf_type>()..];\n> -        let kind = (t.info >> 24) & 0xf;\n> +        let kind = (t.info >> 24) & 0x1f;\n\nComment 1\n\n>  \n>          match BtfKind::try_from(kind)? {\n>              BtfKind::Void => {\n> diff --git a/libbpf-cargo/src/test.rs b/libbpf-cargo/src/test.rs\n> index 5b08843..82a0586 100644\n> --- a/libbpf-cargo/src/test.rs\n> +++ b/libbpf-cargo/src/test.rs\n> @@ -2145,3 +2145,27 @@ pub struct __anon_3 {\n>  \n>      assert_definition(&btf, struct_bpf_sock_tuple, expected_output);\n>  }\n> +\n> +#[test]\n> +fn test_btf_dump_float() {\n> +    let prog_text = r#\"\n> +float f = 2.16;\n> +double d = 12.15;\n> +\"#;\n> +\n> +    let btf = build_btf_prog(prog_text);\n> +\n> +    let f = find_type_in_btf!(btf, Var, \"f\");\n> +    let d = find_type_in_btf!(btf, Var, \"d\");\n> +\n> +    assert_eq!(\n> +        \"f32\",\n> +        btf.type_declaration(f)\n> +            .expect(\"Failed to generate f decl\")\n> +    );\n> +    assert_eq!(\n> +        \"f64\",\n> +        btf.type_declaration(d)\n> +            .expect(\"Failed to generate d decl\")\n> +    );\n> +}\n"
  },
  {
    "path": "testdata/unterminated_back_to_back_span",
    "content": "> diff --git a/libbpf-cargo/src/btf/btf.rs b/libbpf-cargo/src/btf/btf.rs\n> index a26b2a5..fffb281 100644\n> --- a/libbpf-cargo/src/btf/btf.rs\n> +++ b/libbpf-cargo/src/btf/btf.rs\n> @@ -731,7 +731,7 @@ impl<'a> Btf<'a> {\n\n>      fn load_type(&mut self, data: &'a [u8]) -> Result<BtfType<'a>> {\n>          let t = data.pread::<btf_type>(0)?;\n>          let extra = &data[size_of::<btf_type>()..];\n> -        let kind = (t.info >> 24) & 0xf;\n> +        let kind = (t.info >> 24) & 0x1f;\n\n>  \n>          match BtfKind::try_from(kind)? {\n>              BtfKind::Void => {\n\nComment 1\n\n> diff --git a/libbpf-cargo/src/test.rs b/libbpf-cargo/src/test.rs\n> index 5b08843..82a0586 100644\n> --- a/libbpf-cargo/src/test.rs\n> +++ b/libbpf-cargo/src/test.rs\n> @@ -2145,3 +2145,27 @@ pub struct __anon_3 {\n>  \n>      assert_definition(&btf, struct_bpf_sock_tuple, expected_output);\n>  }\n> +\n> +#[test]\n> +fn test_btf_dump_float() {\n> +    let prog_text = r#\"\n> +float f = 2.16;\n> +double d = 12.15;\n> +\"#;\n> +\n> +    let btf = build_btf_prog(prog_text);\n> +\n> +    let f = find_type_in_btf!(btf, Var, \"f\");\n> +    let d = find_type_in_btf!(btf, Var, \"d\");\n> +\n> +    assert_eq!(\n> +        \"f32\",\n> +        btf.type_declaration(f)\n> +            .expect(\"Failed to generate f decl\")\n> +    );\n> +    assert_eq!(\n> +        \"f64\",\n> +        btf.type_declaration(d)\n> +            .expect(\"Failed to generate d decl\")\n> +    );\n> +}\n"
  },
  {
    "path": "testdata/unterminated_span",
    "content": "> diff --git a/libbpf-cargo/src/btf/btf.rs b/libbpf-cargo/src/btf/btf.rs\n> index a26b2a5..fffb281 100644\n> --- a/libbpf-cargo/src/btf/btf.rs\n> +++ b/libbpf-cargo/src/btf/btf.rs\n> @@ -731,7 +731,7 @@ impl<'a> Btf<'a> {\n>      fn load_type(&mut self, data: &'a [u8]) -> Result<BtfType<'a>> {\n>          let t = data.pread::<btf_type>(0)?;\n>          let extra = &data[size_of::<btf_type>()..];\n> -        let kind = (t.info >> 24) & 0xf;\n\n> +        let kind = (t.info >> 24) & 0x1f;\n>  \n>          match BtfKind::try_from(kind)? {\n>              BtfKind::Void => {\n> diff --git a/libbpf-cargo/src/test.rs b/libbpf-cargo/src/test.rs\n> index 5b08843..82a0586 100644\n> --- a/libbpf-cargo/src/test.rs\n> +++ b/libbpf-cargo/src/test.rs\n> @@ -2145,3 +2145,27 @@ pub struct __anon_3 {\n>  \n>      assert_definition(&btf, struct_bpf_sock_tuple, expected_output);\n>  }\n> +\n> +#[test]\n> +fn test_btf_dump_float() {\n> +    let prog_text = r#\"\n> +float f = 2.16;\n> +double d = 12.15;\n> +\"#;\n> +\n> +    let btf = build_btf_prog(prog_text);\n> +\n> +    let f = find_type_in_btf!(btf, Var, \"f\");\n> +    let d = find_type_in_btf!(btf, Var, \"d\");\n> +\n> +    assert_eq!(\n> +        \"f32\",\n> +        btf.type_declaration(f)\n> +            .expect(\"Failed to generate f decl\")\n> +    );\n> +    assert_eq!(\n> +        \"f64\",\n> +        btf.type_declaration(d)\n> +            .expect(\"Failed to generate d decl\")\n> +    );\n> +}\n"
  },
  {
    "path": "vim/ftdetect/prr.vim",
    "content": "au BufNewFile,BufRead *.prr set filetype=prr\n"
  },
  {
    "path": "vim/ftplugin/prr.vim",
    "content": "setlocal foldmethod=expr\nsetlocal foldexpr=s:DiffFoldLevel()\nsetlocal foldcolumn=3\n\n\" Adapted from https://github.com/sgeb/vim-diff-fold\nfunction! s:DiffFoldLevel()\n    let l:line=getline(v:lnum)\n\n    if l:line =~# '^> \\(diff\\|Index\\)' \" file\n        return '>1'\n    elseif l:line =~# '^> \\(@@\\|\\d\\)' \" hunk\n        return '>2'\n    else\n        return '='\n    endif\nendfunction\n\nlet b:undo_ftplugin = 'setl fdm< | setl fde< | setl fdc<'\n"
  },
  {
    "path": "vim/syntax/prr.vim",
    "content": "\" Vim syntax file\n\" Language:     prr\n\" Maintainer:   Daniel Xu <dxu@dxuuu.xyz>\n\" Last Change:  2023 Nov 07\n\" Credits:      Bram Moolenaar <Bram@vim.org>,\n\"               Łukasz Niemier <lukasz@niemier.pl>\n\n\" Check whether an earlier file has defined a syntax already\nif exists(\"b:current_syntax\")\n  finish\nendif\n\n\" match + but not +++\nsyn match prrAdded   \"^> +\\(++\\)\\@!.*\"\n\" match - but not ---\nsyn match prrRemoved \"^> -\\(--\\)\\@!.*\"\n\nsyn match prrHeader \"^> diff --git .*\"\nsyn match prrIndex \"^> index \\w*\\.\\.\\w*\\( \\w*\\)\\?\"\nsyn match prrChunkH \"^> @@ .* @@\"\n\nsyn match prrTag \"^@prr .*\" contains=prrTagName,prrResult transparent\n\nsyn match prrTagName contained \"@prr\" nextgroup=prrResult\nsyn keyword prrResult contained approve reject comment\n\n\" Define the default highlighting.\n\" Only used when an item doesn't have highlighting yet\nhi def link prrAdded           Added\nhi def link prrRemoved         Removed\n\nhi def link prrTagName Keyword\nhi def link prrResult String\nhi def link prrHeader Include\nhi def link prrIndex Comment\nhi def link prrChunkH Function\n\nlet b:current_syntax = \"prr\"\n"
  }
]