├── .gitignore ├── book ├── .gitignore ├── src │ ├── images │ │ ├── introduction_vim.png │ │ └── tutorial_comment.png │ ├── install.md │ ├── install_github.md │ ├── examples │ │ ├── snip.md │ │ ├── description_comment.md │ │ ├── file_comment.md │ │ ├── inline_comment.md │ │ ├── review_comment.md │ │ ├── prr_directive.md │ │ └── spanned_inline_comment.md │ ├── install_config.md │ ├── README.md │ ├── release.md │ ├── contributing.md │ ├── SUMMARY.md │ ├── install_binary.md │ ├── vim.md │ ├── review.md │ ├── config.md │ └── tutorial.md └── book.toml ├── vim ├── ftdetect │ └── prr.vim ├── ftplugin │ └── prr.vim └── syntax │ └── prr.vim ├── testdata ├── testgitrepo │ ├── README.md │ └── README-applied.md ├── add_oneliner ├── review │ ├── apply_pr │ │ └── review │ │ │ ├── 1.prr │ │ │ └── .1 │ ├── status │ │ ├── review │ │ └── metadata │ ├── snip_single │ │ ├── review │ │ ├── metadata │ │ └── gold │ ├── pr_description │ │ ├── metadata │ │ └── review │ ├── pr_description_interleaving │ │ ├── metadata │ │ └── review │ ├── snip_multiple │ │ ├── review │ │ ├── metadata │ │ └── gold │ ├── snip_comments │ │ ├── review │ │ ├── metadata │ │ └── gold │ └── trailing_whitespace │ │ ├── metadata │ │ └── review ├── inline_and_review_comments_with_pr_description ├── spaces_in_filename ├── review_comments_interleaved_with_pr_description ├── empty_file ├── unterminated_span ├── cross_file_span_ignored ├── multiple_files ├── single_comment ├── file_comment ├── approve_review ├── reject_review ├── unknown_directive ├── unterminated_back_to_back_span ├── back_to_back_span ├── review_comment ├── review_comment_whitespace ├── multiline_comment ├── cross_hunk_span ├── hunk_start_no_trailing_whitespace ├── trailing_comment └── deleted_file ├── README.md ├── Cargo.toml ├── .github └── workflows │ ├── rust.yml │ └── docs.yml ├── src ├── cli.rs ├── main.rs ├── review.rs ├── parser.rs └── prr.rs ├── NOTES.md └── LICENSE /.gitignore: -------------------------------------------------------------------------------- 1 | /target 2 | -------------------------------------------------------------------------------- /book/.gitignore: -------------------------------------------------------------------------------- 1 | book 2 | -------------------------------------------------------------------------------- /vim/ftdetect/prr.vim: -------------------------------------------------------------------------------- 1 | au BufNewFile,BufRead *.prr set filetype=prr 2 | -------------------------------------------------------------------------------- /testdata/testgitrepo/README.md: -------------------------------------------------------------------------------- 1 | For testing 2 | =========== 3 | 4 | This is a readme 5 | -------------------------------------------------------------------------------- /testdata/testgitrepo/README-applied.md: -------------------------------------------------------------------------------- 1 | For testing 2 | =========== 3 | 4 | This is a better readme line! 5 | -------------------------------------------------------------------------------- /book/src/images/introduction_vim.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/danobi/prr/HEAD/book/src/images/introduction_vim.png -------------------------------------------------------------------------------- /book/src/images/tutorial_comment.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/danobi/prr/HEAD/book/src/images/tutorial_comment.png -------------------------------------------------------------------------------- /book/src/install.md: -------------------------------------------------------------------------------- 1 | # Installation 2 | 3 | Installation has two steps: 4 | 5 | 1. Install the `prr` binary 6 | 1. Acquire a token from Github 7 | 1. Give the token to `prr` 8 | 9 | The following sub-chapters provide more details. 10 | -------------------------------------------------------------------------------- /testdata/add_oneliner: -------------------------------------------------------------------------------- 1 | > diff --git a/foo.rs b/foo.rs 2 | > new file mode 100644 3 | > index 0000000..5a64612 4 | > --- /dev/null 5 | > +++ b/foo.rs 6 | > @@ -0,0 +1 @@ 7 | 8 | Comment 1 9 | 10 | > +License: Unlicense 11 | 12 | Comment 2 13 | -------------------------------------------------------------------------------- /testdata/review/apply_pr/review/1.prr: -------------------------------------------------------------------------------- 1 | > Much better this way! 2 | > 3 | > diff --git a/README.md b/README.md 4 | > index 007306a..1a480f2 100644 5 | > --- a/README.md 6 | > +++ b/README.md 7 | > @@ -1,4 +1,4 @@ 8 | > For testing 9 | > =========== 10 | > 11 | > -This is a readme 12 | > +This is a better readme line! 13 | -------------------------------------------------------------------------------- /book/book.toml: -------------------------------------------------------------------------------- 1 | [book] 2 | authors = ["Daniel Xu"] 3 | language = "en" 4 | multilingual = false 5 | src = "src" 6 | title = "prr" 7 | 8 | [output.html] 9 | git-repository-url = "https://github.com/danobi/prr" 10 | git-repository-icon = "fa-github" 11 | edit-url-template = "https://github.com/danobi/prr/edit/master/book/{path}" 12 | -------------------------------------------------------------------------------- /testdata/review/apply_pr/review/.1: -------------------------------------------------------------------------------- 1 | {"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"} -------------------------------------------------------------------------------- /testdata/review/status/review: -------------------------------------------------------------------------------- 1 | > diff --git a/src/utils.cpp b/src/utils.cpp 2 | > index b02c16bc3df..fca25d6c839 100644 3 | > --- a/src/utils.cpp 4 | > +++ b/src/utils.cpp 5 | > @@ -1,5 +1,6 @@ 6 | > #include 7 | > #include 8 | > +#include 9 | > #include 10 | > #include 11 | > #include 12 | -------------------------------------------------------------------------------- /testdata/review/status/metadata: -------------------------------------------------------------------------------- 1 | {"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 \n #include \n+#include \n #include \n #include \n #include \n","submitted":null,"commit_id":"58c3ef68bbb9082e5a16449baa15c18ccf7e5707"} -------------------------------------------------------------------------------- /book/src/install_github.md: -------------------------------------------------------------------------------- 1 | # Acquire Github token 2 | 3 | `prr` needs a token so it can make Github API calls on your behalf. 4 | 5 | Create the token by going to: 6 | 7 | ``` 8 | Settings -> Developer settings -> Personal access tokens -> Generate new token 9 | ``` 10 | 11 | and give the token `repo` permissions. Keep the newly generated token handy 12 | for the next step. 13 | -------------------------------------------------------------------------------- /book/src/examples/snip.md: -------------------------------------------------------------------------------- 1 | ``` 2 | [...] 3 | 4 | > 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. 5 | > 6 | > +asdf 7 | > +asdf 8 | > +asdf 9 | > +adsf 10 | > + 11 | 12 | We snipped the top and bottom of this document so we can focus on the review comment here. 13 | 14 | [...] 15 | ``` 16 | -------------------------------------------------------------------------------- /testdata/review/snip_single/review: -------------------------------------------------------------------------------- 1 | > diff --git a/src/review.rs b/src/review.rs 2 | [...] 3 | > } 4 | > 5 | > + fn has_metadata(&self) -> bool { 6 | > + fs::metadata(self.metadata_path()).is_ok() 7 | > + } 8 | > + 9 | > fn metadata_path(&self) -> PathBuf { 10 | > let mut metadata_path = self.path(); 11 | > metadata_path.set_file_name(format!(".{}", self.pr_num)); 12 | -------------------------------------------------------------------------------- /testdata/review/pr_description/metadata: -------------------------------------------------------------------------------- 1 | {"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"} -------------------------------------------------------------------------------- /testdata/review/pr_description_interleaving/metadata: -------------------------------------------------------------------------------- 1 | {"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"} -------------------------------------------------------------------------------- /vim/ftplugin/prr.vim: -------------------------------------------------------------------------------- 1 | setlocal foldmethod=expr 2 | setlocal foldexpr=s:DiffFoldLevel() 3 | setlocal foldcolumn=3 4 | 5 | " Adapted from https://github.com/sgeb/vim-diff-fold 6 | function! s:DiffFoldLevel() 7 | let l:line=getline(v:lnum) 8 | 9 | if l:line =~# '^> \(diff\|Index\)' " file 10 | return '>1' 11 | elseif l:line =~# '^> \(@@\|\d\)' " hunk 12 | return '>2' 13 | else 14 | return '=' 15 | endif 16 | endfunction 17 | 18 | let b:undo_ftplugin = 'setl fdm< | setl fde< | setl fdc<' 19 | -------------------------------------------------------------------------------- /book/src/install_config.md: -------------------------------------------------------------------------------- 1 | # Configure prr 2 | 3 | First, create the config directory: 4 | 5 | ```sh 6 | mkdir -p ~/.config/prr 7 | ``` 8 | 9 | Next, create a basic global config: 10 | 11 | ```sh 12 | cat << EOF > ~/.config/prr/config.toml 13 | [prr] 14 | token = "$YOUR_PAT_FROM_LAST_STEP" 15 | workdir = "/home/dxu/dev/review" 16 | EOF 17 | ``` 18 | 19 | See [`token`](./config.md#the-token-field) for further details on how to provide a GitHub token. 20 | 21 | Note `workdir` can be any directory. (You don't have to use my unix name) 22 | -------------------------------------------------------------------------------- /testdata/review/pr_description/review: -------------------------------------------------------------------------------- 1 | Not necessary but seems ok. 2 | 3 | @prr approve 4 | 5 | > This is just for testing purposes. 6 | > diff --git a/README.md b/README.md 7 | > index eda592e..ba84732 100644 8 | > --- a/README.md 9 | > +++ b/README.md 10 | > @@ -1,5 +1,5 @@ 11 | > -MA-FSA for Go 12 | > -============= 13 | > +MA-FSA for Golang 14 | > +================= 15 | 16 | Doesn't seem necessary ... 17 | 18 | 19 | > 20 | > Package mafsa implements Minimal Acyclic Finite State Automata (MA-FSA) 21 | > with Minimal Perfect Hashing (MPH). Basically, it's a set of strings that 22 | -------------------------------------------------------------------------------- /testdata/inline_and_review_comments_with_pr_description: -------------------------------------------------------------------------------- 1 | Not necessary. 2 | 3 | @prr reject 4 | 5 | > This is just for testing purposes. 6 | > diff --git a/README.md b/README.md 7 | > index eda592e..ba84732 100644 8 | > --- a/README.md 9 | > +++ b/README.md 10 | > @@ -1,5 +1,5 @@ 11 | > -MA-FSA for Go 12 | > -============= 13 | > +MA-FSA for Golang 14 | > +================= 15 | 16 | Doesn't seem necessary ... 17 | 18 | 19 | > 20 | > Package mafsa implements Minimal Acyclic Finite State Automata (MA-FSA) 21 | > with Minimal Perfect Hashing (MPH). Basically, it's a set of strings that 22 | -------------------------------------------------------------------------------- /testdata/spaces_in_filename: -------------------------------------------------------------------------------- 1 | > diff --git a/build/scripts/grafana/provisioning/dashboards/Docker Prometheus Monitoring-1571332751387.json b/build/scripts/grafana/provisioning/dashboards/Docker Prometheus Monitoring-1571332751387.json 2 | > new file mode 100644 3 | > index 0000000..5daac7b 4 | > --- /dev/null 5 | > +++ b/build/scripts/grafana/provisioning/dashboards/Docker Prometheus Monitoring-1571332751387.json 6 | > @@ -0,0 +1,1831 @@ 7 | > +{ 8 | > + "annotations": { 9 | foo 10 | > + "list": [ 11 | > + { 12 | > + "builtIn": 1, 13 | > + "datasource": "-- Grafana --", 14 | 15 | -------------------------------------------------------------------------------- /testdata/review/pr_description_interleaving/review: -------------------------------------------------------------------------------- 1 | Not necessary. 2 | 3 | @prr reject 4 | 5 | > This is just for testing purposes. 6 | 7 | This might be fine or not. 8 | 9 | > diff --git a/README.md b/README.md 10 | > index eda592e..ba84732 100644 11 | > --- a/README.md 12 | > +++ b/README.md 13 | > @@ -1,5 +1,5 @@ 14 | > -MA-FSA for Go 15 | > -============= 16 | > +MA-FSA for Golang 17 | > +================= 18 | 19 | Doesn't seem necessary ... 20 | 21 | 22 | > 23 | > Package mafsa implements Minimal Acyclic Finite State Automata (MA-FSA) 24 | > with Minimal Perfect Hashing (MPH). Basically, it's a set of strings that 25 | -------------------------------------------------------------------------------- /testdata/review_comments_interleaved_with_pr_description: -------------------------------------------------------------------------------- 1 | Not necessary. 2 | 3 | 4 | > This is just for testing purposes. 5 | 6 | This might be fine or not. 7 | 8 | @prr reject 9 | 10 | > diff --git a/README.md b/README.md 11 | > index eda592e..ba84732 100644 12 | > --- a/README.md 13 | > +++ b/README.md 14 | > @@ -1,5 +1,5 @@ 15 | > -MA-FSA for Go 16 | > -============= 17 | > +MA-FSA for Golang 18 | > +================= 19 | 20 | Doesn't seem necessary ... 21 | 22 | 23 | > 24 | > Package mafsa implements Minimal Acyclic Finite State Automata (MA-FSA) 25 | > with Minimal Perfect Hashing (MPH). Basically, it's a set of strings that 26 | -------------------------------------------------------------------------------- /testdata/review/snip_multiple/review: -------------------------------------------------------------------------------- 1 | [...] 2 | > index e39fd6f..e94680e 100644 3 | [..] 4 | > +++ b/src/review.rs 5 | > @@ -155,7 +155,7 @@ impl Review { 6 | > fs::create_dir_all(review_dir).context("Failed to create workdir directories")?; 7 | > 8 | [...] 9 | > + if !force && review.has_metadata() && review.status()? == ReviewStatus::Reviewed { 10 | > bail!( 11 | > "You have unsubmitted changes to the requested review. \ 12 | [...] 13 | > } 14 | > 15 | > + fn has_metadata(&self) -> bool { 16 | > + fs::metadata(self.metadata_path()).is_ok() 17 | > + } 18 | > + 19 | > fn metadata_path(&self) -> PathBuf { 20 | [..] 21 | -------------------------------------------------------------------------------- /book/src/README.md: -------------------------------------------------------------------------------- 1 | # Introduction 2 | 3 | `prr` is a tool that brings mailing list style code reviews to Github PRs. 4 | This means offline reviews and a file oriented interface, more or less. 5 | 6 | To that end, `prr` introduces a new workflow for reviewing PRs: 7 | 8 | 1. Download the PR into a "review file" on your filesystem 9 | 1. Mark up the review file using your favorite text editor 10 | 1. Submit the review at your convenience 11 | 12 | The tool was born of frustration from using the point-and-click editor text 13 | boxes on PRs. I happen to do a lot of code review and tabbing to and from the 14 | browser to cross reference code from the changes was driving me nuts. 15 | 16 | ![](./images/introduction_vim.png) 17 | -------------------------------------------------------------------------------- /book/src/release.md: -------------------------------------------------------------------------------- 1 | # Releases 2 | 3 | Releases are currently managed by [`cargo-release`][0]. 4 | 5 | We are currently pre-1.0, so we are only cutting minor and patch releases. We 6 | try to follow [semantic versioning][1]. Cut a minor release by running: 7 | 8 | ```sh 9 | cargo release minor 10 | ``` 11 | 12 | Similarly, a patch release is: 13 | 14 | ```sh 15 | cargo release patch 16 | ``` 17 | 18 | ## Github releases and binary artifacts 19 | 20 | At some point it'd be good to automatically cut GH releases and upload binary 21 | (statically linked) artifacts to it. It's not too hard to do using GHA. Just 22 | lazy. Contributions welcome. 23 | 24 | [0]: https://github.com/crate-ci/cargo-release 25 | [1]: https://semver.org/ 26 | -------------------------------------------------------------------------------- /testdata/review/snip_comments/review: -------------------------------------------------------------------------------- 1 | > diff --git a/src/review.rs b/src/review.rs 2 | 3 | 4 | file comment! 5 | [...] 6 | > - if !force && review.status()? == ReviewStatus::Reviewed { 7 | > + if !force && review.has_metadata() && review.status()? == ReviewStatus::Reviewed { 8 | woah! 9 | > bail!( 10 | > "You have unsubmitted changes to the requested review. \ 11 | > Either submit the existing changes, delete the existing review file, \ 12 | > @@ -353,6 +353,10 @@ impl Review { 13 | > serde_json::from_str::(&meta).context("Failed to parse metadata file") 14 | > } 15 | [...] 16 | nice 17 | 18 | > + fs::metadata(self.metadata_path()).is_ok() 19 | 20 | sheesh 21 | 22 | [...] 23 | -------------------------------------------------------------------------------- /book/src/contributing.md: -------------------------------------------------------------------------------- 1 | # Contributing 2 | 3 | There isn't much process yet, so this page is light. But a few things to keep 4 | in mind: 5 | 6 | * I highly encourage floating an idea before implementing it. So that we can 7 | avoid any potential wasted work. My (@danobi) SLA for providing _some_ kind 8 | of feedback is 1-2 days. 9 | 10 | * Tests are mandatory for any parser changes. Tests are currently kinda light 11 | especially as it's closer to API call layer, but we should be adding tests 12 | where possible. 13 | 14 | * All user facing changes must come with documentation update. Documentation 15 | lives in `book/` and is rendered by [mdBook][0]. Documentation changes are 16 | automatically deployed upon merge. 17 | 18 | [0]: https://rust-lang.github.io/mdBook/ 19 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Pull request review 2 | 3 | [![Rust](https://github.com/danobi/prr/actions/workflows/rust.yml/badge.svg?branch=master)](https://github.com/danobi/prr/actions/workflows/rust.yml) 4 | 5 | `prr` is a tool that brings mailing list style code reviews to Github PRs. 6 | This means offline reviews and inline comments, more or less. 7 | 8 | To that end, `prr` introduces a new workflow for reviewing PRs: 9 | 10 | 1. Download the PR into a "review file" on your filesystem 11 | 1. Mark up the review file using your favorite text editor 12 | 1. Submit the review at your convenience 13 | 14 | The tool was born of frustration from using the point-and-click editor text 15 | boxes on PRs. I happen to do a lot of code review and tabbing to and from the 16 | browser to cross reference code from the changes was driving me nuts. 17 | 18 | For full documentation, please visit https://doc.dxuuu.xyz/prr/. 19 | -------------------------------------------------------------------------------- /book/src/SUMMARY.md: -------------------------------------------------------------------------------- 1 | # Summary 2 | 3 | [Introduction](./README.md) 4 | 5 | # User Guide 6 | 7 | - [Installation](./install.md) 8 | - [Install Binary](./install_binary.md) 9 | - [Acquire Github token](./install_github.md) 10 | - [Configure `prr`](./install_config.md) 11 | - [Tutorial](./tutorial.md) 12 | - [Vim integration](./vim.md) 13 | 14 | # Reference Guide 15 | 16 | - [Configuration](./config.md) 17 | - [Review file markups](./review.md) 18 | - [Prr directive example](./examples/prr_directive.md) 19 | - [Review comment example](./examples/review_comment.md) 20 | - [Description comment example](./examples/description_comment.md) 21 | - [Inline comment example](./examples/inline_comment.md) 22 | - [Spanned inline comment example](./examples/spanned_inline_comment.md) 23 | - [File comment example](./examples/file_comment.md) 24 | - [Snip example](./examples/snip.md) 25 | 26 | # Development 27 | 28 | - [Contributing](./contributing.md) 29 | - [Releases](./release.md) 30 | -------------------------------------------------------------------------------- /book/src/examples/description_comment.md: -------------------------------------------------------------------------------- 1 | ``` 2 | > First line of description. 3 | 4 | The above line will be quoted in Github UI. The comment below will not quote 5 | the PR description b/c the review directive terminates the quoting. 6 | 7 | @prr comment 8 | 9 | > 10 | > The second paragraph has three sentences. This is the second sentence. 11 | > The third and final sentence is on a new line. 12 | > 13 | > Final line. 14 | 15 | Final comment; no quote. 16 | 17 | > diff --git a/ch3.txt b/ch3.txt 18 | > index 159cf1c..cc376fa 100644 19 | > --- a/ch3.txt 20 | > +++ b/ch3.txt 21 | > @@ -20,6 +20,8 @@ CHAPTER 3. ATTACK BY STRATAGEM 22 | > 23 | > 10. Hence, though an obstinate fight may be made by a small force, in the end it must be captured by the larger force. 24 | > 25 | > +10.5. new line 26 | > + 27 | > 11. Now the general is the bulwark of the State; if the bulwark is complete at all points; the State will be strong; if the bulwark is defective, the State will be weak. 28 | > 29 | > 12. There are three ways in which a ruler can bring misfortune upon his army: 30 | ``` 31 | -------------------------------------------------------------------------------- /book/src/install_binary.md: -------------------------------------------------------------------------------- 1 | # Install binary 2 | 3 | There are multiple ways to install `prr` CLI tool. Choose any one of the 4 | methods below that best suit your needs. 5 | 6 | ## Build from source 7 | 8 | To build `prr` from source, you will first need to install Rust and Cargo. 9 | Follow the instructions on the [Rust installation page][0]. 10 | 11 | Once you have installed Rust, the following command can be used to build and 12 | install `prr`: 13 | 14 | ```sh 15 | cargo install prr 16 | ``` 17 | 18 | This will automatically download `prr` from [crates.io][1], build it, and 19 | install it in Cargo's global binary directory (`~/.cargo/bin/` by default). 20 | 21 | To uninstall, run the command: 22 | 23 | ```sh 24 | cargo uninstall prr 25 | ``` 26 | 27 | ## Install using Homebrew 28 | 29 | To install `prr` using [Homebrew][2], first follow [Homebrew install 30 | instructions][3]. 31 | 32 | Once Homebrew is installed, run: 33 | 34 | ```sh 35 | brew install prr 36 | ``` 37 | 38 | 39 | [0]: https://www.rust-lang.org/tools/install 40 | [1]: https://crates.io/ 41 | [2]: https://brew.sh/ 42 | [3]: https://docs.brew.sh/Installation 43 | -------------------------------------------------------------------------------- /testdata/review/snip_comments/metadata: -------------------------------------------------------------------------------- 1 | {"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::(&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"} -------------------------------------------------------------------------------- /testdata/review/snip_multiple/metadata: -------------------------------------------------------------------------------- 1 | {"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::(&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"} -------------------------------------------------------------------------------- /testdata/review/snip_single/metadata: -------------------------------------------------------------------------------- 1 | {"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::(&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"} -------------------------------------------------------------------------------- /testdata/empty_file: -------------------------------------------------------------------------------- 1 | > diff --git a/libbpf-cargo/src/btf/btf.rs b/libbpf-cargo/src/btf/btf.rs 2 | > index 0000000..fffb281 100644 3 | > --- /dev/null 4 | > +++ b/libbpf-cargo/src/btf/btf.rs 5 | > diff --git a/libbpf-cargo/src/test.rs b/libbpf-cargo/src/test.rs 6 | > index 5b08843..82a0586 100644 7 | > --- a/libbpf-cargo/src/test.rs 8 | > +++ b/libbpf-cargo/src/test.rs 9 | > @@ -2145,3 +2145,27 @@ pub struct __anon_3 { 10 | > 11 | > assert_definition(&btf, struct_bpf_sock_tuple, expected_output); 12 | > } 13 | > + 14 | > +#[test] 15 | > +fn test_btf_dump_float() { 16 | > + let prog_text = r#" 17 | > +float f = 2.16; 18 | > +double d = 12.15; 19 | > +"#; 20 | > + 21 | > + let btf = build_btf_prog(prog_text); 22 | > + 23 | > + let f = find_type_in_btf!(btf, Var, "f"); 24 | > + let d = find_type_in_btf!(btf, Var, "d"); 25 | 26 | Comment 27 | 28 | > + 29 | > + assert_eq!( 30 | > + "f32", 31 | > + btf.type_declaration(f) 32 | > + .expect("Failed to generate f decl") 33 | > + ); 34 | > + assert_eq!( 35 | > + "f64", 36 | > + btf.type_declaration(d) 37 | > + .expect("Failed to generate d decl") 38 | > + ); 39 | > +} 40 | -------------------------------------------------------------------------------- /testdata/review/snip_multiple/gold: -------------------------------------------------------------------------------- 1 | > diff --git a/src/review.rs b/src/review.rs 2 | > index e39fd6f..e94680e 100644 3 | > --- a/src/review.rs 4 | > +++ b/src/review.rs 5 | > @@ -155,7 +155,7 @@ impl Review { 6 | > fs::create_dir_all(review_dir).context("Failed to create workdir directories")?; 7 | > 8 | > // Check if there are unsubmitted changes 9 | > - if !force && review.status()? == ReviewStatus::Reviewed { 10 | > + if !force && review.has_metadata() && review.status()? == ReviewStatus::Reviewed { 11 | > bail!( 12 | > "You have unsubmitted changes to the requested review. \ 13 | > Either submit the existing changes, delete the existing review file, \ 14 | > @@ -353,6 +353,10 @@ impl Review { 15 | > serde_json::from_str::(&meta).context("Failed to parse metadata file") 16 | > } 17 | > 18 | > + fn has_metadata(&self) -> bool { 19 | > + fs::metadata(self.metadata_path()).is_ok() 20 | > + } 21 | > + 22 | > fn metadata_path(&self) -> PathBuf { 23 | > let mut metadata_path = self.path(); 24 | > metadata_path.set_file_name(format!(".{}", self.pr_num)); 25 | -------------------------------------------------------------------------------- /testdata/review/snip_single/gold: -------------------------------------------------------------------------------- 1 | > diff --git a/src/review.rs b/src/review.rs 2 | > index e39fd6f..e94680e 100644 3 | > --- a/src/review.rs 4 | > +++ b/src/review.rs 5 | > @@ -155,7 +155,7 @@ impl Review { 6 | > fs::create_dir_all(review_dir).context("Failed to create workdir directories")?; 7 | > 8 | > // Check if there are unsubmitted changes 9 | > - if !force && review.status()? == ReviewStatus::Reviewed { 10 | > + if !force && review.has_metadata() && review.status()? == ReviewStatus::Reviewed { 11 | > bail!( 12 | > "You have unsubmitted changes to the requested review. \ 13 | > Either submit the existing changes, delete the existing review file, \ 14 | > @@ -353,6 +353,10 @@ impl Review { 15 | > serde_json::from_str::(&meta).context("Failed to parse metadata file") 16 | > } 17 | > 18 | > + fn has_metadata(&self) -> bool { 19 | > + fs::metadata(self.metadata_path()).is_ok() 20 | > + } 21 | > + 22 | > fn metadata_path(&self) -> PathBuf { 23 | > let mut metadata_path = self.path(); 24 | > metadata_path.set_file_name(format!(".{}", self.pr_num)); 25 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "prr" 3 | description = "Mailing list style code reviews for github" 4 | license = "GPL-2.0-or-later" 5 | repository = "https://github.com/danobi/prr" 6 | version = "0.21.0" 7 | edition = "2021" 8 | rust-version = "1.78.0" 9 | build = "build.rs" 10 | 11 | [dependencies] 12 | anyhow = "1.0" 13 | clap = { version = "4.4", features = ["derive"] } 14 | git2 = "0.20.0" 15 | http = "1.1.0" 16 | lazy_static = "1.4" 17 | octocrab = "0.38" 18 | prettytable-rs = "0.10.0" 19 | regex = "1.5" 20 | serde = "1.0" 21 | serde_derive = "1.0" 22 | serde_json = "1.0" 23 | tokio = { version = "1.17", default-features = false, features = ["macros", "rt-multi-thread"] } 24 | toml = "0.5" 25 | xdg = "2.4" 26 | 27 | [dev-dependencies] 28 | pretty_assertions = "1.4.0" 29 | tempfile = "3.8.1" 30 | 31 | [build-dependencies] 32 | anyhow = "1.0" 33 | clap = { version = "4.4", features = ["derive"] } 34 | clap_complete = "4.5.2" 35 | clap_mangen = "0.2.20" 36 | 37 | [features] 38 | # Statically link a vendored copy OpenSSL. OpenSSL is used by all of `git2`, `reqwest` and 39 | # `octocrab`, enabling vendoring for just one of them should be enough. 40 | vendored-openssl = ["git2/vendored-openssl"] 41 | -------------------------------------------------------------------------------- /.github/workflows/rust.yml: -------------------------------------------------------------------------------- 1 | name: Rust 2 | 3 | on: 4 | push: 5 | branches: [ master ] 6 | pull_request: 7 | branches: [ master ] 8 | 9 | env: 10 | CARGO_TERM_COLOR: always 11 | 12 | jobs: 13 | build: 14 | runs-on: ubuntu-latest 15 | env: 16 | RUSTFLAGS: -Dwarnings 17 | steps: 18 | - uses: actions/checkout@v4 19 | - name: Build 20 | run: cargo test --verbose --no-run 21 | - name: Run tests 22 | run: cargo test --verbose 23 | 24 | static: 25 | runs-on: ubuntu-latest 26 | steps: 27 | - uses: actions/checkout@v4 28 | - uses: dtolnay/rust-toolchain@stable 29 | with: 30 | targets: x86_64-unknown-linux-musl 31 | - name: Install host deps 32 | run: sudo apt-get install -y musl-tools 33 | - name: Build + link statically 34 | run: cargo build --verbose --release --target=x86_64-unknown-linux-musl --features vendored-openssl 35 | - name: Validate binary is statically linked 36 | run: ldd ./target/x86_64-unknown-linux-musl/release/prr 2>&1 | grep -q "statically linked" 37 | 38 | format: 39 | runs-on: ubuntu-latest 40 | steps: 41 | - uses: actions/checkout@v2 42 | - name: Run rustfmt 43 | run: cargo fmt --check 44 | -------------------------------------------------------------------------------- /vim/syntax/prr.vim: -------------------------------------------------------------------------------- 1 | " Vim syntax file 2 | " Language: prr 3 | " Maintainer: Daniel Xu 4 | " Last Change: 2023 Nov 07 5 | " Credits: Bram Moolenaar , 6 | " Łukasz Niemier 7 | 8 | " Check whether an earlier file has defined a syntax already 9 | if exists("b:current_syntax") 10 | finish 11 | endif 12 | 13 | " match + but not +++ 14 | syn match prrAdded "^> +\(++\)\@!.*" 15 | " match - but not --- 16 | syn match prrRemoved "^> -\(--\)\@!.*" 17 | 18 | syn match prrHeader "^> diff --git .*" 19 | syn match prrIndex "^> index \w*\.\.\w*\( \w*\)\?" 20 | syn match prrChunkH "^> @@ .* @@" 21 | 22 | syn match prrTag "^@prr .*" contains=prrTagName,prrResult transparent 23 | 24 | syn match prrTagName contained "@prr" nextgroup=prrResult 25 | syn keyword prrResult contained approve reject comment 26 | 27 | " Define the default highlighting. 28 | " Only used when an item doesn't have highlighting yet 29 | hi def link prrAdded Added 30 | hi def link prrRemoved Removed 31 | 32 | hi def link prrTagName Keyword 33 | hi def link prrResult String 34 | hi def link prrHeader Include 35 | hi def link prrIndex Comment 36 | hi def link prrChunkH Function 37 | 38 | let b:current_syntax = "prr" 39 | -------------------------------------------------------------------------------- /testdata/review/snip_comments/gold: -------------------------------------------------------------------------------- 1 | > diff --git a/src/review.rs b/src/review.rs 2 | 3 | 4 | file comment! 5 | > index e39fd6f..e94680e 100644 6 | > --- a/src/review.rs 7 | > +++ b/src/review.rs 8 | > @@ -155,7 +155,7 @@ impl Review { 9 | > fs::create_dir_all(review_dir).context("Failed to create workdir directories")?; 10 | > 11 | > // Check if there are unsubmitted changes 12 | > - if !force && review.status()? == ReviewStatus::Reviewed { 13 | > + if !force && review.has_metadata() && review.status()? == ReviewStatus::Reviewed { 14 | woah! 15 | > bail!( 16 | > "You have unsubmitted changes to the requested review. \ 17 | > Either submit the existing changes, delete the existing review file, \ 18 | > @@ -353,6 +353,10 @@ impl Review { 19 | > serde_json::from_str::(&meta).context("Failed to parse metadata file") 20 | > } 21 | > 22 | > + fn has_metadata(&self) -> bool { 23 | nice 24 | 25 | > + fs::metadata(self.metadata_path()).is_ok() 26 | 27 | sheesh 28 | 29 | > + } 30 | > + 31 | > fn metadata_path(&self) -> PathBuf { 32 | > let mut metadata_path = self.path(); 33 | > metadata_path.set_file_name(format!(".{}", self.pr_num)); 34 | -------------------------------------------------------------------------------- /.github/workflows/docs.yml: -------------------------------------------------------------------------------- 1 | name: Deploy docs 2 | on: 3 | push: 4 | branches: 5 | - master 6 | 7 | jobs: 8 | deploy: 9 | runs-on: ubuntu-latest 10 | permissions: 11 | contents: write # To push a branch 12 | pages: write # To push to a GitHub Pages site 13 | id-token: write # To update the deployment status 14 | steps: 15 | - uses: actions/checkout@v4 16 | with: 17 | fetch-depth: 0 18 | - name: Install latest mdbook 19 | run: | 20 | tag=$(curl 'https://api.github.com/repos/rust-lang/mdbook/releases/latest' | jq -r '.tag_name') 21 | url="https://github.com/rust-lang/mdbook/releases/download/${tag}/mdbook-${tag}-x86_64-unknown-linux-gnu.tar.gz" 22 | mkdir mdbook 23 | curl -sSL $url | tar -xz --directory=./mdbook 24 | echo `pwd`/mdbook >> $GITHUB_PATH 25 | - name: Build Book 26 | run: | 27 | cd book 28 | mdbook build 29 | - name: Setup Pages 30 | uses: actions/configure-pages@v5 31 | - name: Upload artifact 32 | uses: actions/upload-pages-artifact@v3 33 | with: 34 | path: 'book/book' 35 | - name: Deploy to GitHub Pages 36 | id: deployment 37 | uses: actions/deploy-pages@v4 38 | -------------------------------------------------------------------------------- /testdata/unterminated_span: -------------------------------------------------------------------------------- 1 | > diff --git a/libbpf-cargo/src/btf/btf.rs b/libbpf-cargo/src/btf/btf.rs 2 | > index a26b2a5..fffb281 100644 3 | > --- a/libbpf-cargo/src/btf/btf.rs 4 | > +++ b/libbpf-cargo/src/btf/btf.rs 5 | > @@ -731,7 +731,7 @@ impl<'a> Btf<'a> { 6 | > fn load_type(&mut self, data: &'a [u8]) -> Result> { 7 | > let t = data.pread::(0)?; 8 | > let extra = &data[size_of::()..]; 9 | > - let kind = (t.info >> 24) & 0xf; 10 | 11 | > + let kind = (t.info >> 24) & 0x1f; 12 | > 13 | > match BtfKind::try_from(kind)? { 14 | > BtfKind::Void => { 15 | > diff --git a/libbpf-cargo/src/test.rs b/libbpf-cargo/src/test.rs 16 | > index 5b08843..82a0586 100644 17 | > --- a/libbpf-cargo/src/test.rs 18 | > +++ b/libbpf-cargo/src/test.rs 19 | > @@ -2145,3 +2145,27 @@ pub struct __anon_3 { 20 | > 21 | > assert_definition(&btf, struct_bpf_sock_tuple, expected_output); 22 | > } 23 | > + 24 | > +#[test] 25 | > +fn test_btf_dump_float() { 26 | > + let prog_text = r#" 27 | > +float f = 2.16; 28 | > +double d = 12.15; 29 | > +"#; 30 | > + 31 | > + let btf = build_btf_prog(prog_text); 32 | > + 33 | > + let f = find_type_in_btf!(btf, Var, "f"); 34 | > + let d = find_type_in_btf!(btf, Var, "d"); 35 | > + 36 | > + assert_eq!( 37 | > + "f32", 38 | > + btf.type_declaration(f) 39 | > + .expect("Failed to generate f decl") 40 | > + ); 41 | > + assert_eq!( 42 | > + "f64", 43 | > + btf.type_declaration(d) 44 | > + .expect("Failed to generate d decl") 45 | > + ); 46 | > +} 47 | -------------------------------------------------------------------------------- /testdata/cross_file_span_ignored: -------------------------------------------------------------------------------- 1 | > diff --git a/libbpf-cargo/src/btf/btf.rs b/libbpf-cargo/src/btf/btf.rs 2 | > index a26b2a5..fffb281 100644 3 | > --- a/libbpf-cargo/src/btf/btf.rs 4 | > +++ b/libbpf-cargo/src/btf/btf.rs 5 | > @@ -731,7 +731,7 @@ impl<'a> Btf<'a> { 6 | > fn load_type(&mut self, data: &'a [u8]) -> Result> { 7 | > let t = data.pread::(0)?; 8 | > let extra = &data[size_of::()..]; 9 | > - let kind = (t.info >> 24) & 0xf; 10 | 11 | > + let kind = (t.info >> 24) & 0x1f; 12 | > 13 | > match BtfKind::try_from(kind)? { 14 | > BtfKind::Void => { 15 | > diff --git a/libbpf-cargo/src/test.rs b/libbpf-cargo/src/test.rs 16 | > index 5b08843..82a0586 100644 17 | > --- a/libbpf-cargo/src/test.rs 18 | > +++ b/libbpf-cargo/src/test.rs 19 | > @@ -2145,3 +2145,27 @@ pub struct __anon_3 { 20 | > 21 | > assert_definition(&btf, struct_bpf_sock_tuple, expected_output); 22 | > } 23 | > + 24 | > +#[test] 25 | > +fn test_btf_dump_float() { 26 | > + let prog_text = r#" 27 | > +float f = 2.16; 28 | > +double d = 12.15; 29 | > +"#; 30 | > + 31 | > + let btf = build_btf_prog(prog_text); 32 | Comment 1 33 | > + 34 | > + let f = find_type_in_btf!(btf, Var, "f"); 35 | > + let d = find_type_in_btf!(btf, Var, "d"); 36 | > + 37 | > + assert_eq!( 38 | > + "f32", 39 | > + btf.type_declaration(f) 40 | > + .expect("Failed to generate f decl") 41 | > + ); 42 | > + assert_eq!( 43 | > + "f64", 44 | > + btf.type_declaration(d) 45 | > + .expect("Failed to generate d decl") 46 | > + ); 47 | > +} 48 | -------------------------------------------------------------------------------- /testdata/multiple_files: -------------------------------------------------------------------------------- 1 | > diff --git a/libbpf-cargo/src/btf/btf.rs b/libbpf-cargo/src/btf/btf.rs 2 | > index a26b2a5..fffb281 100644 3 | > --- a/libbpf-cargo/src/btf/btf.rs 4 | > +++ b/libbpf-cargo/src/btf/btf.rs 5 | > @@ -731,7 +731,7 @@ impl<'a> Btf<'a> { 6 | > fn load_type(&mut self, data: &'a [u8]) -> Result> { 7 | > let t = data.pread::(0)?; 8 | > let extra = &data[size_of::()..]; 9 | > - let kind = (t.info >> 24) & 0xf; 10 | > + let kind = (t.info >> 24) & 0x1f; 11 | Comment 1 12 | 13 | > 14 | > match BtfKind::try_from(kind)? { 15 | > BtfKind::Void => { 16 | > diff --git a/libbpf-cargo/src/test.rs b/libbpf-cargo/src/test.rs 17 | > index 5b08843..82a0586 100644 18 | > --- a/libbpf-cargo/src/test.rs 19 | > +++ b/libbpf-cargo/src/test.rs 20 | > @@ -2145,3 +2145,27 @@ pub struct __anon_3 { 21 | > 22 | > assert_definition(&btf, struct_bpf_sock_tuple, expected_output); 23 | > } 24 | > + 25 | > +#[test] 26 | > +fn test_btf_dump_float() { 27 | > + let prog_text = r#" 28 | > +float f = 2.16; 29 | > +double d = 12.15; 30 | > +"#; 31 | > + 32 | > + let btf = build_btf_prog(prog_text); 33 | > + 34 | > + let f = find_type_in_btf!(btf, Var, "f"); 35 | > + let d = find_type_in_btf!(btf, Var, "d"); 36 | Comment 2 37 | > + 38 | > + assert_eq!( 39 | > + "f32", 40 | > + btf.type_declaration(f) 41 | > + .expect("Failed to generate f decl") 42 | > + ); 43 | > + assert_eq!( 44 | > + "f64", 45 | > + btf.type_declaration(d) 46 | > + .expect("Failed to generate d decl") 47 | > + ); 48 | > +} 49 | -------------------------------------------------------------------------------- /testdata/single_comment: -------------------------------------------------------------------------------- 1 | > diff --git a/libbpf-cargo/src/btf/btf.rs b/libbpf-cargo/src/btf/btf.rs 2 | > index a26b2a5..fffb281 100644 3 | > --- a/libbpf-cargo/src/btf/btf.rs 4 | > +++ b/libbpf-cargo/src/btf/btf.rs 5 | > @@ -731,7 +731,7 @@ impl<'a> Btf<'a> { 6 | 7 | > fn load_type(&mut self, data: &'a [u8]) -> Result> { 8 | > let t = data.pread::(0)?; 9 | > let extra = &data[size_of::()..]; 10 | > - let kind = (t.info >> 24) & 0xf; 11 | > + let kind = (t.info >> 24) & 0x1f; 12 | 13 | Comment 1 14 | 15 | > 16 | > match BtfKind::try_from(kind)? { 17 | > BtfKind::Void => { 18 | > diff --git a/libbpf-cargo/src/test.rs b/libbpf-cargo/src/test.rs 19 | > index 5b08843..82a0586 100644 20 | > --- a/libbpf-cargo/src/test.rs 21 | > +++ b/libbpf-cargo/src/test.rs 22 | > @@ -2145,3 +2145,27 @@ pub struct __anon_3 { 23 | > 24 | > assert_definition(&btf, struct_bpf_sock_tuple, expected_output); 25 | > } 26 | > + 27 | > +#[test] 28 | > +fn test_btf_dump_float() { 29 | > + let prog_text = r#" 30 | > +float f = 2.16; 31 | > +double d = 12.15; 32 | > +"#; 33 | > + 34 | > + let btf = build_btf_prog(prog_text); 35 | > + 36 | > + let f = find_type_in_btf!(btf, Var, "f"); 37 | > + let d = find_type_in_btf!(btf, Var, "d"); 38 | > + 39 | > + assert_eq!( 40 | > + "f32", 41 | > + btf.type_declaration(f) 42 | > + .expect("Failed to generate f decl") 43 | > + ); 44 | > + assert_eq!( 45 | > + "f64", 46 | > + btf.type_declaration(d) 47 | > + .expect("Failed to generate d decl") 48 | > + ); 49 | > +} 50 | -------------------------------------------------------------------------------- /testdata/file_comment: -------------------------------------------------------------------------------- 1 | > diff --git a/libbpf-cargo/src/btf/btf.rs b/libbpf-cargo/src/btf/btf.rs 2 | 3 | This is a file-level comment! 4 | 5 | > index a26b2a5..fffb281 100644 6 | > --- a/libbpf-cargo/src/btf/btf.rs 7 | > +++ b/libbpf-cargo/src/btf/btf.rs 8 | > @@ -731,7 +731,7 @@ impl<'a> Btf<'a> { 9 | > fn load_type(&mut self, data: &'a [u8]) -> Result> { 10 | > let t = data.pread::(0)?; 11 | > let extra = &data[size_of::()..]; 12 | > - let kind = (t.info >> 24) & 0xf; 13 | > + let kind = (t.info >> 24) & 0x1f; 14 | > 15 | > match BtfKind::try_from(kind)? { 16 | > BtfKind::Void => { 17 | > diff --git a/libbpf-cargo/src/test.rs b/libbpf-cargo/src/test.rs 18 | > index 5b08843..82a0586 100644 19 | > --- a/libbpf-cargo/src/test.rs 20 | > +++ b/libbpf-cargo/src/test.rs 21 | > @@ -2145,3 +2145,27 @@ pub struct __anon_3 { 22 | > 23 | > assert_definition(&btf, struct_bpf_sock_tuple, expected_output); 24 | > } 25 | > + 26 | > +#[test] 27 | > +fn test_btf_dump_float() { 28 | > + let prog_text = r#" 29 | > +float f = 2.16; 30 | > +double d = 12.15; 31 | > +"#; 32 | > + 33 | > + let btf = build_btf_prog(prog_text); 34 | > + 35 | > + let f = find_type_in_btf!(btf, Var, "f"); 36 | > + let d = find_type_in_btf!(btf, Var, "d"); 37 | > + 38 | > + assert_eq!( 39 | > + "f32", 40 | > + btf.type_declaration(f) 41 | > + .expect("Failed to generate f decl") 42 | > + ); 43 | > + assert_eq!( 44 | > + "f64", 45 | > + btf.type_declaration(d) 46 | > + .expect("Failed to generate d decl") 47 | > + ); 48 | > +} 49 | -------------------------------------------------------------------------------- /testdata/approve_review: -------------------------------------------------------------------------------- 1 | @prr approve 2 | > diff --git a/libbpf-cargo/src/btf/btf.rs b/libbpf-cargo/src/btf/btf.rs 3 | > index a26b2a5..fffb281 100644 4 | > --- a/libbpf-cargo/src/btf/btf.rs 5 | > +++ b/libbpf-cargo/src/btf/btf.rs 6 | > @@ -731,7 +731,7 @@ impl<'a> Btf<'a> { 7 | 8 | > fn load_type(&mut self, data: &'a [u8]) -> Result> { 9 | > let t = data.pread::(0)?; 10 | > let extra = &data[size_of::()..]; 11 | > - let kind = (t.info >> 24) & 0xf; 12 | > + let kind = (t.info >> 24) & 0x1f; 13 | 14 | Comment 1 15 | 16 | > 17 | > match BtfKind::try_from(kind)? { 18 | > BtfKind::Void => { 19 | > diff --git a/libbpf-cargo/src/test.rs b/libbpf-cargo/src/test.rs 20 | > index 5b08843..82a0586 100644 21 | > --- a/libbpf-cargo/src/test.rs 22 | > +++ b/libbpf-cargo/src/test.rs 23 | > @@ -2145,3 +2145,27 @@ pub struct __anon_3 { 24 | > 25 | > assert_definition(&btf, struct_bpf_sock_tuple, expected_output); 26 | > } 27 | > + 28 | > +#[test] 29 | > +fn test_btf_dump_float() { 30 | > + let prog_text = r#" 31 | > +float f = 2.16; 32 | > +double d = 12.15; 33 | > +"#; 34 | > + 35 | > + let btf = build_btf_prog(prog_text); 36 | > + 37 | > + let f = find_type_in_btf!(btf, Var, "f"); 38 | > + let d = find_type_in_btf!(btf, Var, "d"); 39 | > + 40 | > + assert_eq!( 41 | > + "f32", 42 | > + btf.type_declaration(f) 43 | > + .expect("Failed to generate f decl") 44 | > + ); 45 | > + assert_eq!( 46 | > + "f64", 47 | > + btf.type_declaration(d) 48 | > + .expect("Failed to generate d decl") 49 | > + ); 50 | > +} 51 | -------------------------------------------------------------------------------- /testdata/reject_review: -------------------------------------------------------------------------------- 1 | @prr reject 2 | > diff --git a/libbpf-cargo/src/btf/btf.rs b/libbpf-cargo/src/btf/btf.rs 3 | > index a26b2a5..fffb281 100644 4 | > --- a/libbpf-cargo/src/btf/btf.rs 5 | > +++ b/libbpf-cargo/src/btf/btf.rs 6 | > @@ -731,7 +731,7 @@ impl<'a> Btf<'a> { 7 | 8 | > fn load_type(&mut self, data: &'a [u8]) -> Result> { 9 | > let t = data.pread::(0)?; 10 | > let extra = &data[size_of::()..]; 11 | > - let kind = (t.info >> 24) & 0xf; 12 | > + let kind = (t.info >> 24) & 0x1f; 13 | 14 | Comment 1 15 | 16 | > 17 | > match BtfKind::try_from(kind)? { 18 | > BtfKind::Void => { 19 | > diff --git a/libbpf-cargo/src/test.rs b/libbpf-cargo/src/test.rs 20 | > index 5b08843..82a0586 100644 21 | > --- a/libbpf-cargo/src/test.rs 22 | > +++ b/libbpf-cargo/src/test.rs 23 | > @@ -2145,3 +2145,27 @@ pub struct __anon_3 { 24 | > 25 | > assert_definition(&btf, struct_bpf_sock_tuple, expected_output); 26 | > } 27 | > + 28 | > +#[test] 29 | > +fn test_btf_dump_float() { 30 | > + let prog_text = r#" 31 | > +float f = 2.16; 32 | > +double d = 12.15; 33 | > +"#; 34 | > + 35 | > + let btf = build_btf_prog(prog_text); 36 | > + 37 | > + let f = find_type_in_btf!(btf, Var, "f"); 38 | > + let d = find_type_in_btf!(btf, Var, "d"); 39 | > + 40 | > + assert_eq!( 41 | > + "f32", 42 | > + btf.type_declaration(f) 43 | > + .expect("Failed to generate f decl") 44 | > + ); 45 | > + assert_eq!( 46 | > + "f64", 47 | > + btf.type_declaration(d) 48 | > + .expect("Failed to generate d decl") 49 | > + ); 50 | > +} 51 | -------------------------------------------------------------------------------- /testdata/unknown_directive: -------------------------------------------------------------------------------- 1 | @prr asdf 2 | > diff --git a/libbpf-cargo/src/btf/btf.rs b/libbpf-cargo/src/btf/btf.rs 3 | > index a26b2a5..fffb281 100644 4 | > --- a/libbpf-cargo/src/btf/btf.rs 5 | > +++ b/libbpf-cargo/src/btf/btf.rs 6 | > @@ -731,7 +731,7 @@ impl<'a> Btf<'a> { 7 | 8 | > fn load_type(&mut self, data: &'a [u8]) -> Result> { 9 | > let t = data.pread::(0)?; 10 | > let extra = &data[size_of::()..]; 11 | > - let kind = (t.info >> 24) & 0xf; 12 | > + let kind = (t.info >> 24) & 0x1f; 13 | 14 | Comment 1 15 | 16 | > 17 | > match BtfKind::try_from(kind)? { 18 | > BtfKind::Void => { 19 | > diff --git a/libbpf-cargo/src/test.rs b/libbpf-cargo/src/test.rs 20 | > index 5b08843..82a0586 100644 21 | > --- a/libbpf-cargo/src/test.rs 22 | > +++ b/libbpf-cargo/src/test.rs 23 | > @@ -2145,3 +2145,27 @@ pub struct __anon_3 { 24 | > 25 | > assert_definition(&btf, struct_bpf_sock_tuple, expected_output); 26 | > } 27 | > + 28 | > +#[test] 29 | > +fn test_btf_dump_float() { 30 | > + let prog_text = r#" 31 | > +float f = 2.16; 32 | > +double d = 12.15; 33 | > +"#; 34 | > + 35 | > + let btf = build_btf_prog(prog_text); 36 | > + 37 | > + let f = find_type_in_btf!(btf, Var, "f"); 38 | > + let d = find_type_in_btf!(btf, Var, "d"); 39 | > + 40 | > + assert_eq!( 41 | > + "f32", 42 | > + btf.type_declaration(f) 43 | > + .expect("Failed to generate f decl") 44 | > + ); 45 | > + assert_eq!( 46 | > + "f64", 47 | > + btf.type_declaration(d) 48 | > + .expect("Failed to generate d decl") 49 | > + ); 50 | > +} 51 | -------------------------------------------------------------------------------- /testdata/unterminated_back_to_back_span: -------------------------------------------------------------------------------- 1 | > diff --git a/libbpf-cargo/src/btf/btf.rs b/libbpf-cargo/src/btf/btf.rs 2 | > index a26b2a5..fffb281 100644 3 | > --- a/libbpf-cargo/src/btf/btf.rs 4 | > +++ b/libbpf-cargo/src/btf/btf.rs 5 | > @@ -731,7 +731,7 @@ impl<'a> Btf<'a> { 6 | 7 | > fn load_type(&mut self, data: &'a [u8]) -> Result> { 8 | > let t = data.pread::(0)?; 9 | > let extra = &data[size_of::()..]; 10 | > - let kind = (t.info >> 24) & 0xf; 11 | > + let kind = (t.info >> 24) & 0x1f; 12 | 13 | > 14 | > match BtfKind::try_from(kind)? { 15 | > BtfKind::Void => { 16 | 17 | Comment 1 18 | 19 | > diff --git a/libbpf-cargo/src/test.rs b/libbpf-cargo/src/test.rs 20 | > index 5b08843..82a0586 100644 21 | > --- a/libbpf-cargo/src/test.rs 22 | > +++ b/libbpf-cargo/src/test.rs 23 | > @@ -2145,3 +2145,27 @@ pub struct __anon_3 { 24 | > 25 | > assert_definition(&btf, struct_bpf_sock_tuple, expected_output); 26 | > } 27 | > + 28 | > +#[test] 29 | > +fn test_btf_dump_float() { 30 | > + let prog_text = r#" 31 | > +float f = 2.16; 32 | > +double d = 12.15; 33 | > +"#; 34 | > + 35 | > + let btf = build_btf_prog(prog_text); 36 | > + 37 | > + let f = find_type_in_btf!(btf, Var, "f"); 38 | > + let d = find_type_in_btf!(btf, Var, "d"); 39 | > + 40 | > + assert_eq!( 41 | > + "f32", 42 | > + btf.type_declaration(f) 43 | > + .expect("Failed to generate f decl") 44 | > + ); 45 | > + assert_eq!( 46 | > + "f64", 47 | > + btf.type_declaration(d) 48 | > + .expect("Failed to generate d decl") 49 | > + ); 50 | > +} 51 | -------------------------------------------------------------------------------- /testdata/back_to_back_span: -------------------------------------------------------------------------------- 1 | > diff --git a/libbpf-cargo/src/btf/btf.rs b/libbpf-cargo/src/btf/btf.rs 2 | > index a26b2a5..fffb281 100644 3 | > --- a/libbpf-cargo/src/btf/btf.rs 4 | > +++ b/libbpf-cargo/src/btf/btf.rs 5 | > @@ -731,7 +731,7 @@ impl<'a> Btf<'a> { 6 | 7 | > fn load_type(&mut self, data: &'a [u8]) -> Result> { 8 | > let t = data.pread::(0)?; 9 | > let extra = &data[size_of::()..]; 10 | > - let kind = (t.info >> 24) & 0xf; 11 | > + let kind = (t.info >> 24) & 0x1f; 12 | 13 | Comment 1 14 | 15 | > 16 | > match BtfKind::try_from(kind)? { 17 | > BtfKind::Void => { 18 | 19 | Comment 2 20 | 21 | > diff --git a/libbpf-cargo/src/test.rs b/libbpf-cargo/src/test.rs 22 | > index 5b08843..82a0586 100644 23 | > --- a/libbpf-cargo/src/test.rs 24 | > +++ b/libbpf-cargo/src/test.rs 25 | > @@ -2145,3 +2145,27 @@ pub struct __anon_3 { 26 | > 27 | > assert_definition(&btf, struct_bpf_sock_tuple, expected_output); 28 | > } 29 | > + 30 | > +#[test] 31 | > +fn test_btf_dump_float() { 32 | > + let prog_text = r#" 33 | > +float f = 2.16; 34 | > +double d = 12.15; 35 | > +"#; 36 | > + 37 | > + let btf = build_btf_prog(prog_text); 38 | > + 39 | > + let f = find_type_in_btf!(btf, Var, "f"); 40 | > + let d = find_type_in_btf!(btf, Var, "d"); 41 | > + 42 | > + assert_eq!( 43 | > + "f32", 44 | > + btf.type_declaration(f) 45 | > + .expect("Failed to generate f decl") 46 | > + ); 47 | > + assert_eq!( 48 | > + "f64", 49 | > + btf.type_declaration(d) 50 | > + .expect("Failed to generate d decl") 51 | > + ); 52 | > +} 53 | -------------------------------------------------------------------------------- /testdata/review_comment: -------------------------------------------------------------------------------- 1 | 2 | Review comment 3 | 4 | > diff --git a/libbpf-cargo/src/btf/btf.rs b/libbpf-cargo/src/btf/btf.rs 5 | > index a26b2a5..fffb281 100644 6 | > --- a/libbpf-cargo/src/btf/btf.rs 7 | > +++ b/libbpf-cargo/src/btf/btf.rs 8 | > @@ -731,7 +731,7 @@ impl<'a> Btf<'a> { 9 | 10 | > fn load_type(&mut self, data: &'a [u8]) -> Result> { 11 | > let t = data.pread::(0)?; 12 | > let extra = &data[size_of::()..]; 13 | > - let kind = (t.info >> 24) & 0xf; 14 | > + let kind = (t.info >> 24) & 0x1f; 15 | 16 | Comment 1 17 | 18 | > 19 | > match BtfKind::try_from(kind)? { 20 | > BtfKind::Void => { 21 | > diff --git a/libbpf-cargo/src/test.rs b/libbpf-cargo/src/test.rs 22 | > index 5b08843..82a0586 100644 23 | > --- a/libbpf-cargo/src/test.rs 24 | > +++ b/libbpf-cargo/src/test.rs 25 | > @@ -2145,3 +2145,27 @@ pub struct __anon_3 { 26 | > 27 | > assert_definition(&btf, struct_bpf_sock_tuple, expected_output); 28 | > } 29 | > + 30 | > +#[test] 31 | > +fn test_btf_dump_float() { 32 | > + let prog_text = r#" 33 | > +float f = 2.16; 34 | > +double d = 12.15; 35 | > +"#; 36 | > + 37 | > + let btf = build_btf_prog(prog_text); 38 | > + 39 | > + let f = find_type_in_btf!(btf, Var, "f"); 40 | > + let d = find_type_in_btf!(btf, Var, "d"); 41 | > + 42 | > + assert_eq!( 43 | > + "f32", 44 | > + btf.type_declaration(f) 45 | > + .expect("Failed to generate f decl") 46 | > + ); 47 | > + assert_eq!( 48 | > + "f64", 49 | > + btf.type_declaration(d) 50 | > + .expect("Failed to generate d decl") 51 | > + ); 52 | > +} 53 | -------------------------------------------------------------------------------- /testdata/review_comment_whitespace: -------------------------------------------------------------------------------- 1 | 2 | @prr approve 3 | 4 | Review comment 5 | 6 | 7 | > diff --git a/libbpf-cargo/src/btf/btf.rs b/libbpf-cargo/src/btf/btf.rs 8 | > index a26b2a5..fffb281 100644 9 | > --- a/libbpf-cargo/src/btf/btf.rs 10 | > +++ b/libbpf-cargo/src/btf/btf.rs 11 | > @@ -731,7 +731,7 @@ impl<'a> Btf<'a> { 12 | > fn load_type(&mut self, data: &'a [u8]) -> Result> { 13 | > let t = data.pread::(0)?; 14 | > let extra = &data[size_of::()..]; 15 | > - let kind = (t.info >> 24) & 0xf; 16 | > + let kind = (t.info >> 24) & 0x1f; 17 | > 18 | > match BtfKind::try_from(kind)? { 19 | > BtfKind::Void => { 20 | > diff --git a/libbpf-cargo/src/test.rs b/libbpf-cargo/src/test.rs 21 | > index 5b08843..82a0586 100644 22 | > --- a/libbpf-cargo/src/test.rs 23 | > +++ b/libbpf-cargo/src/test.rs 24 | > @@ -2145,3 +2145,27 @@ pub struct __anon_3 { 25 | > 26 | > assert_definition(&btf, struct_bpf_sock_tuple, expected_output); 27 | > } 28 | > + 29 | > +#[test] 30 | > +fn test_btf_dump_float() { 31 | > + let prog_text = r#" 32 | > +float f = 2.16; 33 | > +double d = 12.15; 34 | > +"#; 35 | > + 36 | > + let btf = build_btf_prog(prog_text); 37 | > + 38 | > + let f = find_type_in_btf!(btf, Var, "f"); 39 | > + let d = find_type_in_btf!(btf, Var, "d"); 40 | > + 41 | > + assert_eq!( 42 | > + "f32", 43 | > + btf.type_declaration(f) 44 | > + .expect("Failed to generate f decl") 45 | > + ); 46 | > + assert_eq!( 47 | > + "f64", 48 | > + btf.type_declaration(d) 49 | > + .expect("Failed to generate d decl") 50 | > + ); 51 | > +} 52 | -------------------------------------------------------------------------------- /testdata/multiline_comment: -------------------------------------------------------------------------------- 1 | > diff --git a/libbpf-cargo/src/btf/btf.rs b/libbpf-cargo/src/btf/btf.rs 2 | > index a26b2a5..fffb281 100644 3 | > --- a/libbpf-cargo/src/btf/btf.rs 4 | > +++ b/libbpf-cargo/src/btf/btf.rs 5 | > @@ -731,7 +731,7 @@ impl<'a> Btf<'a> { 6 | > fn load_type(&mut self, data: &'a [u8]) -> Result> { 7 | > let t = data.pread::(0)?; 8 | > let extra = &data[size_of::()..]; 9 | > - let kind = (t.info >> 24) & 0xf; 10 | > + let kind = (t.info >> 24) & 0x1f; 11 | > 12 | > match BtfKind::try_from(kind)? { 13 | 14 | 15 | 16 | Comment line 1 17 | Comment line 2 18 | 19 | Comment line 4 20 | 21 | 22 | 23 | 24 | 25 | 26 | > BtfKind::Void => { 27 | > diff --git a/libbpf-cargo/src/test.rs b/libbpf-cargo/src/test.rs 28 | > index 5b08843..82a0586 100644 29 | > --- a/libbpf-cargo/src/test.rs 30 | > +++ b/libbpf-cargo/src/test.rs 31 | > @@ -2145,3 +2145,27 @@ pub struct __anon_3 { 32 | > 33 | > assert_definition(&btf, struct_bpf_sock_tuple, expected_output); 34 | > } 35 | > + 36 | > +#[test] 37 | > +fn test_btf_dump_float() { 38 | > + let prog_text = r#" 39 | > +float f = 2.16; 40 | > +double d = 12.15; 41 | > +"#; 42 | > + 43 | > + let btf = build_btf_prog(prog_text); 44 | > + 45 | > + let f = find_type_in_btf!(btf, Var, "f"); 46 | > + let d = find_type_in_btf!(btf, Var, "d"); 47 | > + 48 | > + assert_eq!( 49 | > + "f32", 50 | > + btf.type_declaration(f) 51 | > + .expect("Failed to generate f decl") 52 | > + ); 53 | > + assert_eq!( 54 | > + "f64", 55 | > + btf.type_declaration(d) 56 | > + .expect("Failed to generate d decl") 57 | > + ); 58 | > +} 59 | -------------------------------------------------------------------------------- /src/cli.rs: -------------------------------------------------------------------------------- 1 | use clap::{Parser, Subcommand}; 2 | use std::path::PathBuf; 3 | 4 | #[derive(Subcommand, Debug)] 5 | pub(crate) enum Command { 6 | /// Get a pull request and begin a review 7 | Get { 8 | /// Ignore unsubmitted review checks 9 | #[clap(short, long)] 10 | force: bool, 11 | /// Pull request to review (eg. `danobi/prr/24`) 12 | pr: String, 13 | /// Open review file in $EDITOR after download 14 | #[clap(long)] 15 | open: bool, 16 | }, 17 | /// Open an existing review in $EDITOR 18 | Edit { 19 | /// Pull request to edit (eg. `danobi/prr/24`) 20 | pr: String, 21 | }, 22 | /// Submit a review 23 | Submit { 24 | /// Pull request to review (eg. `danobi/prr/24`) 25 | pr: String, 26 | #[clap(short, long)] 27 | debug: bool, 28 | }, 29 | /// Apply a pull request to the working directory 30 | /// 31 | /// This can be useful for building/testing PRs 32 | Apply { pr: String }, 33 | /// Print a status summary of all known reviews 34 | Status { 35 | /// Hide column titles from output 36 | #[clap(short, long)] 37 | no_titles: bool, 38 | }, 39 | /// Remove a review 40 | Remove { 41 | /// Pull requests to remove (eg. `danobi/prr/24`) 42 | prs: Vec, 43 | /// Ignore unsubmitted review checks 44 | #[clap(short, long)] 45 | force: bool, 46 | /// Remove submitted reviews in addition to provided reviews 47 | #[clap(short, long)] 48 | submitted: bool, 49 | }, 50 | } 51 | 52 | #[derive(Parser, Debug)] 53 | #[clap(version)] 54 | #[command(name = "prr")] 55 | pub struct Cli { 56 | /// Path to config file 57 | #[clap(long)] 58 | pub(crate) config: Option, 59 | #[clap(subcommand)] 60 | pub(crate) command: Command, 61 | } 62 | -------------------------------------------------------------------------------- /NOTES.md: -------------------------------------------------------------------------------- 1 | # TODO 2 | 3 | - [x] Parse review files 4 | - [x] Create parser 5 | - [x] Create `include_str!()` based unit-tests for expected comments 6 | - [x] Test invalid spans (span that does not have a comment that 7 | terminates it and another span starts) 8 | - [x] Wire up comment uploading to GH 9 | - [x] Inspect response error codes and body 10 | - [x] Fix bug where `line` and `start_line` are being set instead of `position` 11 | - [x] Check if `start_position` is accepted 12 | - [x] Add test for trying to comment on a hunk start 13 | - [x] Figure out how to calculate line for diffs w/ changes on both sides 14 | - [x] Add test for comment at end of review file 15 | - [x] Prohibit cross hunk spanned comments 16 | - [x] Support review-level comments at top of review file 17 | - [x] Manual test that comments on a changed file work 18 | - [x] Support approve/rejecting PRs 19 | - [x] Need some kind of meta syntax (like go's //+) 20 | - [ ] Think about if it could be generalized to comment threads 21 | - [x] Support updating a PR's review file, but ask for confirmation if review file has been modified and not submitted yet 22 | - [x] Maybe even check mtime between review file and submission time? 23 | - [x] Support parsing github url from stdin 24 | - [x] Save commit hash of downloaded review file 25 | - [x] Support [...] snipping 26 | - [ ] Support comment threads. Maybe do nested '>'s like actual mailing lists? 27 | 28 | # Thoughts 29 | 30 | * Make a comment spanned by inserting a whitespace line before the 31 | start of the span 32 | 33 | * To compose with back-to-back spanned comments, the latter comment 34 | must be assumed to be a single line comment. Otherwise, using 35 | a single spanned comment always makes the next comment a span. 36 | This kinda actually makes sense conceptually too cuz if the user 37 | actually wants back-to-back spans then they should've just used 38 | a single, larger span. 39 | 40 | * Need to be careful to prohibit a spanned comment over multiple files 41 | -------------------------------------------------------------------------------- /testdata/review/trailing_whitespace/metadata: -------------------------------------------------------------------------------- 1 | {"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"} -------------------------------------------------------------------------------- /testdata/review/trailing_whitespace/review: -------------------------------------------------------------------------------- 1 | > diff --git a/ch2.txt b/ch2.txt 2 | > index 4d729e6..2641120 100644 3 | > --- a/ch2.txt 4 | > +++ b/ch2.txt 5 | > @@ -2,13 +2,6 @@ CHAPTER 2. WAGING WAR 6 | > 7 | > 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. 8 | > 9 | > -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. 10 | > - 11 | > -3. Again, if the campaign is protracted, the resources of the State will not be equal to the strain. 12 | > - 13 | > -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. 14 | > - 15 | > -5. Thus, though we have heard of stupid haste in war, cleverness has never been seen associated with long delays. 16 | > 17 | > 6. There is no instance of a country having benefited from prolonged warfare. 18 | > 19 | > @@ -30,6 +23,11 @@ CHAPTER 2. WAGING WAR 20 | > 21 | > 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. 22 | > 23 | > +asdf 24 | > +asdf 25 | > +asdf 26 | > +adsf 27 | > + 28 | > 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. 29 | > 30 | > 18. This is called, using the conquered foe to augment one's own strength. 31 | -------------------------------------------------------------------------------- /book/src/vim.md: -------------------------------------------------------------------------------- 1 | # Vim integration 2 | 3 | The `vim/` directory in `prr` source contains Vim plugin providing syntax 4 | coloring, filetype detection and folding configuration for `*.prr` files. 5 | 6 | To install, modify `&runtimepath` to add this directory or use a plugin manager 7 | of your choice to add this plugin. 8 | 9 | ## Vundle installation 10 | 11 | Add the following to your `.vimrc`: 12 | 13 | ``` 14 | Plugin 'danobi/prr', {'rtp': 'vim/'} 15 | ``` 16 | 17 | ## Manual installation 18 | 19 | Copy the provided `*.vim` files into their appropriate subdirectories in 20 | `~/.vim`. 21 | 22 | ## Syntax colors 23 | 24 | The `prr` "plugin" exports some preconfigured syntax hooks. 25 | 26 | Example [from my dotfiles][0]: 27 | 28 | ```vim 29 | "Automatically set up highlighting for `.prr` review files 30 | "Use `:hi` to see the various definitions we kinda abuse here 31 | augroup Prr 32 | autocmd! 33 | autocmd BufRead,BufNewFile *.prr set syntax=on 34 | 35 | "Make prr added/deleted highlighting more apparent 36 | autocmd BufRead,BufNewFile *.prr hi! link prrAdded Function 37 | autocmd BufRead,BufNewFile *.prr hi! link prrRemoved Keyword 38 | autocmd BufRead,BufNewFile *.prr hi! link prrFile Special 39 | 40 | "Make file delimiters more apparent 41 | autocmd BufRead,BufNewFile *.prr hi! link prrHeader Directory 42 | 43 | "Reduce all the noise from color 44 | autocmd BufRead,BufNewFile *.prr hi! link prrIndex Special 45 | autocmd BufRead,BufNewFile *.prr hi! link prrChunk Special 46 | autocmd BufRead,BufNewFile *.prr hi! link prrChunkH Special 47 | autocmd BufRead,BufNewFile *.prr hi! link prrTagName Special 48 | autocmd BufRead,BufNewFile *.prr hi! link prrResult Special 49 | augroup END 50 | ``` 51 | 52 | ## Folding 53 | 54 | With default Vim configuration all folds will be closed by default, so if you 55 | want them to be opened then you need to do one of these: 56 | 57 | - Add `set foldlevel=9999` in your Vim config to open all folds by default 58 | - Add `set nofoldenable` to disable folding 59 | 60 | Consult `:h folding` for more details. 61 | 62 | 63 | [0]: https://github.com/danobi/dotfiles/blob/ab00f235fffd4c8d5e2496657e8047e1473d9257/vim/.vimrc#L81-L94 64 | -------------------------------------------------------------------------------- /testdata/cross_hunk_span: -------------------------------------------------------------------------------- 1 | > diff --git a/ch2.txt b/ch2.txt 2 | > index 4d729e6..2641120 100644 3 | > --- a/ch2.txt 4 | > +++ b/ch2.txt 5 | > @@ -2,13 +2,6 @@ CHAPTER 2. WAGING WAR 6 | > 7 | > 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. 8 | > 9 | 10 | > -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. 11 | > - 12 | > -3. Again, if the campaign is protracted, the resources of the State will not be equal to the strain. 13 | > - 14 | > -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. 15 | > - 16 | > -5. Thus, though we have heard of stupid haste in war, cleverness has never been seen associated with long delays. 17 | > 18 | > 6. There is no instance of a country having benefited from prolonged warfare. 19 | > 20 | > @@ -30,6 +23,11 @@ CHAPTER 2. WAGING WAR 21 | > 22 | > 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. 23 | > 24 | > +asdf 25 | > +asdf 26 | > +asdf 27 | > +adsf 28 | > + 29 | 30 | Cross span comment 31 | 32 | > 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. 33 | > 34 | > 18. This is called, using the conquered foe to augment one's own strength. 35 | -------------------------------------------------------------------------------- /book/src/examples/file_comment.md: -------------------------------------------------------------------------------- 1 | ``` 2 | > diff --git a/ch2.txt b/ch2.txt 3 | 4 | This is a file-level comment on ch2.txt 5 | 6 | > index 4d729e6..2641120 100644 7 | > --- a/ch2.txt 8 | > +++ b/ch2.txt 9 | > @@ -2,13 +2,6 @@ CHAPTER 2. WAGING WAR 10 | > 11 | > 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. 12 | > 13 | > -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. 14 | > - 15 | > -3. Again, if the campaign is protracted, the resources of the State will not be equal to the strain. 16 | > - 17 | > -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. 18 | > - 19 | > -5. Thus, though we have heard of stupid haste in war, cleverness has never been seen associated with long delays. 20 | > 21 | > 6. There is no instance of a country having benefited from prolonged warfare. 22 | > 23 | > @@ -30,6 +23,11 @@ CHAPTER 2. WAGING WAR 24 | > 25 | > 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. 26 | > 27 | > +asdf 28 | > +asdf 29 | > +asdf 30 | > +adsf 31 | > + 32 | > 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. 33 | > 34 | > 18. This is called, using the conquered foe to augment one's own strength. 35 | ``` 36 | -------------------------------------------------------------------------------- /book/src/examples/inline_comment.md: -------------------------------------------------------------------------------- 1 | ``` 2 | > diff --git a/ch2.txt b/ch2.txt 3 | > index 4d729e6..2641120 100644 4 | > --- a/ch2.txt 5 | > +++ b/ch2.txt 6 | > @@ -2,13 +2,6 @@ CHAPTER 2. WAGING WAR 7 | > 8 | > 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. 9 | > 10 | > -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. 11 | > - 12 | > -3. Again, if the campaign is protracted, the resources of the State will not be equal to the strain. 13 | > - 14 | > -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. 15 | 16 | This is an inline comment attached to passage 4. 17 | 18 | > - 19 | > -5. Thus, though we have heard of stupid haste in war, cleverness has never been seen associated with long delays. 20 | > 21 | > 6. There is no instance of a country having benefited from prolonged warfare. 22 | > 23 | > @@ -30,6 +23,11 @@ CHAPTER 2. WAGING WAR 24 | > 25 | > 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. 26 | > 27 | > +asdf 28 | > +asdf 29 | > +asdf 30 | > +adsf 31 | > + 32 | > 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. 33 | > 34 | > 18. This is called, using the conquered foe to augment one's own strength. 35 | ``` 36 | -------------------------------------------------------------------------------- /book/src/review.md: -------------------------------------------------------------------------------- 1 | # Review file 2 | 3 | `prr` supports various review file markups. This document captures all of them. 4 | 5 | ## Review directives 6 | 7 | Description: Meta-directives to give to `prr` in review comment. Currently 8 | only supports approving, requesting changes to, and commenting on a PR. 9 | 10 | Syntax: `@prr approve`, `@prr reject`, or `@prr comment`. 11 | 12 | [Example](./examples/prr_directive.md) 13 | 14 | ## Review comment 15 | 16 | Description: PR-level review comment. You only get one of these per review. 17 | 18 | Syntax: Non-whitespace, non-quoted text at the beginning of the review file. 19 | 20 | [Example](./examples/review_comment.md) 21 | 22 | ## Description comment 23 | 24 | Description: Specialized form of review comment. When 25 | [`activate_pr_metadata_experiment`](./config.md#the-activate_pr_metadata_experiment-field) 26 | is active, review files come with the PR description quoted at the top of the 27 | review file. Comments, when uploaded, will quote the preceding description. PR 28 | description will continue to be quoted until a review directive is found. 29 | 30 | Syntax: Same as review comment. 31 | 32 | [Example](./examples/review_description.md) 33 | 34 | ## Inline comment 35 | 36 | Description: Inline comment attached to a specific line of the diff. 37 | 38 | Syntax: None-whitespace, non-quoted text on a newline immediately following 39 | a quoted non-header part of the diff. 40 | 41 | [Example](./examples/inline_comment.md) 42 | 43 | ## Spanned inline comment 44 | 45 | Description: Like an inline comment, except it covers a span of lines. 46 | 47 | Syntax: To start a span, insert one or more newlines immediately before 48 | a quoted, non-header part of the diff. To terminate a span, insert a 49 | inline comment. 50 | 51 | [Example](./examples/spanned_inline_comment.md) 52 | 53 | ## File comment 54 | 55 | Description: File-level comment. 56 | 57 | Syntax: Non-whitespace, non-quoted text immediately following the `diff --git` header 58 | 59 | [Example](./examples/file_comment.md) 60 | 61 | ## Snips 62 | 63 | Description: Use `[...]` to replace (ie. snip) contiguous quoted lines. 64 | 65 | Syntax: `[...]` or `[..]` on its own line. Multiple snips may be used in a review file. 66 | 67 | [Example](./examples/snip.md) 68 | -------------------------------------------------------------------------------- /book/src/examples/review_comment.md: -------------------------------------------------------------------------------- 1 | ``` 2 | This is a PR-level review comment. You can only leave one of these per review. 3 | 4 | > diff --git a/ch2.txt b/ch2.txt 5 | > index 4d729e6..2641120 100644 6 | > --- a/ch2.txt 7 | > +++ b/ch2.txt 8 | > @@ -2,13 +2,6 @@ CHAPTER 2. WAGING WAR 9 | > 10 | > 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. 11 | > 12 | > -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. 13 | > - 14 | > -3. Again, if the campaign is protracted, the resources of the State will not be equal to the strain. 15 | > - 16 | > -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. 17 | > - 18 | > -5. Thus, though we have heard of stupid haste in war, cleverness has never been seen associated with long delays. 19 | > 20 | > 6. There is no instance of a country having benefited from prolonged warfare. 21 | > 22 | > @@ -30,6 +23,11 @@ CHAPTER 2. WAGING WAR 23 | > 24 | > 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. 25 | > 26 | > +asdf 27 | > +asdf 28 | > +asdf 29 | > +adsf 30 | > + 31 | > 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. 32 | > 33 | > 18. This is called, using the conquered foe to augment one's own strength. 34 | ``` 35 | -------------------------------------------------------------------------------- /book/src/examples/prr_directive.md: -------------------------------------------------------------------------------- 1 | ``` 2 | This is a PR-level review comment. The following is a review directive 3 | to approve the PR: 4 | 5 | @prr approve 6 | 7 | > diff --git a/ch2.txt b/ch2.txt 8 | > index 4d729e6..2641120 100644 9 | > --- a/ch2.txt 10 | > +++ b/ch2.txt 11 | > @@ -2,13 +2,6 @@ CHAPTER 2. WAGING WAR 12 | > 13 | > 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. 14 | > 15 | > -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. 16 | > - 17 | > -3. Again, if the campaign is protracted, the resources of the State will not be equal to the strain. 18 | > - 19 | > -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. 20 | > - 21 | > -5. Thus, though we have heard of stupid haste in war, cleverness has never been seen associated with long delays. 22 | > 23 | > 6. There is no instance of a country having benefited from prolonged warfare. 24 | > 25 | > @@ -30,6 +23,11 @@ CHAPTER 2. WAGING WAR 26 | > 27 | > 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. 28 | > 29 | > +asdf 30 | > +asdf 31 | > +asdf 32 | > +adsf 33 | > + 34 | > 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. 35 | > 36 | > 18. This is called, using the conquered foe to augment one's own strength. 37 | ``` 38 | -------------------------------------------------------------------------------- /book/src/examples/spanned_inline_comment.md: -------------------------------------------------------------------------------- 1 | > diff --git a/ch2.txt b/ch2.txt 2 | > index 4d729e6..2641120 100644 3 | > --- a/ch2.txt 4 | > +++ b/ch2.txt 5 | > @@ -2,13 +2,6 @@ CHAPTER 2. WAGING WAR 6 | > 7 | > 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. 8 | > 9 | 10 | > -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. 11 | > - 12 | > -3. Again, if the campaign is protracted, the resources of the State will not be equal to the strain. 13 | > - 14 | > -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. 15 | 16 | This is a spanned inline comment attached to passages 2 through 4. 17 | 18 | > - 19 | > -5. Thus, though we have heard of stupid haste in war, cleverness has never been seen associated with long delays. 20 | > 21 | > 6. There is no instance of a country having benefited from prolonged warfare. 22 | > 23 | > @@ -30,6 +23,11 @@ CHAPTER 2. WAGING WAR 24 | > 25 | > 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. 26 | > 27 | 28 | > +asdf 29 | > +asdf 30 | > +asdf 31 | > +adsf 32 | > + 33 | 34 | This is another spanned comment attached to the newly added text, that 35 | GitHub will interpret as a code suggestion [0], suggesting the added text 36 | be removed. 37 | 38 | ```suggestion 39 | ``` 40 | 41 | [0]: https://docs.github.com/en/pull-requests/collaborating-with-pull-requests/reviewing-changes-in-pull-requests/incorporating-feedback-in-your-pull-request 42 | 43 | > 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. 44 | > 45 | > 18. This is called, using the conquered foe to augment one's own strength. 46 | -------------------------------------------------------------------------------- /src/main.rs: -------------------------------------------------------------------------------- 1 | use std::env; 2 | use std::path::{Path, PathBuf}; 3 | use std::process; 4 | 5 | use anyhow::{bail, Context, Result}; 6 | use clap::Parser; 7 | 8 | mod cli; 9 | mod parser; 10 | mod prr; 11 | mod review; 12 | 13 | use cli::*; 14 | use prr::Prr; 15 | 16 | /// The name of the local configuration file 17 | pub const LOCAL_CONFIG_FILE_NAME: &str = ".prr.toml"; 18 | 19 | /// Returns if exists the config file for the current project 20 | fn find_project_config_file() -> Option { 21 | env::current_dir().ok().and_then(|mut path| loop { 22 | path.push(LOCAL_CONFIG_FILE_NAME); 23 | if path.exists() { 24 | return Some(path); 25 | } 26 | 27 | path.pop(); 28 | if !path.pop() { 29 | return None; 30 | } 31 | }) 32 | } 33 | 34 | /// Opens a file in $EDITOR 35 | fn open_review(file: &Path) -> Result<()> { 36 | // This check should only ever trip for prr-edit 37 | if !file.try_exists()? { 38 | bail!("Review file does not exist yet"); 39 | } 40 | 41 | let editor = env::var("EDITOR").context("Failed to read $EDITOR")?; 42 | let status = process::Command::new(editor) 43 | .arg(file) 44 | .status() 45 | .context("Failed to execute editor process")?; 46 | 47 | match status.code() { 48 | Some(0) => Ok(()), 49 | Some(rc) => bail!("EDITOR exited unclean: {}", rc), 50 | None => bail!("Failed to get EDITOR exit status"), 51 | } 52 | } 53 | 54 | #[tokio::main] 55 | async fn main() -> Result<()> { 56 | let args = Cli::parse(); 57 | 58 | // Figure out where config file is 59 | let config_path = match args.config { 60 | Some(c) => c, 61 | None => { 62 | let xdg_dirs = xdg::BaseDirectories::with_prefix("prr")?; 63 | xdg_dirs.get_config_file("config.toml") 64 | } 65 | }; 66 | 67 | let prr = Prr::new(&config_path, find_project_config_file())?; 68 | 69 | match args.command { 70 | Command::Get { pr, force, open } => { 71 | let (owner, repo, pr_num) = prr.parse_pr_str(&pr)?; 72 | let review = prr.get_pr(&owner, &repo, pr_num, force).await?; 73 | let path = review.path(); 74 | println!("{}", path.display()); 75 | if open { 76 | open_review(&path).context("Failed to open review file")?; 77 | } 78 | } 79 | Command::Edit { pr } => { 80 | let (owner, repo, pr_num) = prr.parse_pr_str(&pr)?; 81 | let review = prr.get_review(&owner, &repo, pr_num)?; 82 | open_review(&review.path()).context("Failed to open review file")?; 83 | } 84 | Command::Submit { pr, debug } => { 85 | let (owner, repo, pr_num) = prr.parse_pr_str(&pr)?; 86 | prr.submit_pr(&owner, &repo, pr_num, debug).await?; 87 | } 88 | Command::Apply { pr } => { 89 | let (owner, repo, pr_num) = prr.parse_pr_str(&pr)?; 90 | prr.apply_pr(&owner, &repo, pr_num, Path::new("./"))?; 91 | } 92 | Command::Status { no_titles } => { 93 | prr.print_status(no_titles)?; 94 | } 95 | Command::Remove { 96 | prs, 97 | force, 98 | submitted, 99 | } => { 100 | prr.remove(&prs, force, submitted).await?; 101 | } 102 | } 103 | 104 | Ok(()) 105 | } 106 | -------------------------------------------------------------------------------- /book/src/config.md: -------------------------------------------------------------------------------- 1 | # Configuration 2 | 3 | `prr` supports two types of configuration: global and local. 4 | 5 | Global configuration controls global behavior. Local configuration controls 6 | behavior for the directory the configuration is in as well as its 7 | subdirectories. 8 | 9 | `prr` respects the [XDG Base Directory Specification][0] where possible. 10 | 11 | ## Global configuration 12 | 13 | `prr` reads global configuration from both `prr --config` as well as 14 | `$XDG_CONFIG_HOME/prr/config.toml`. It places priority on the `--config` flag. 15 | 16 | The following global configuration options are supported: 17 | 18 | * `[prr]` 19 | * [`token`](#the-token-field) 20 | * [`workdir`](#the-workdir-field) 21 | * [`url`](#the-url-field) 22 | * [`activate_pr_metadata_experiment`](#the-activate_pr_metadata_experiment-field) 23 | 24 | ### The `token` field 25 | 26 | The `token` field is your Github Personal Authentical Token as a string. 27 | 28 | Example: 29 | 30 | ```toml 31 | [prr] 32 | token = "ghp_Kuzzzzzzzzzzzzdonteventryzzzzzzzzzzz" 33 | ``` 34 | 35 | If the `token` field is absent - or set to an empty string - then the following environment 36 | variables will be checked in order and the first token found will be used: 37 | 38 | - `GH_TOKEN` 39 | - `GITHUB_TOKEN` 40 | - `GH_ENTERPRISE_TOKEN` 41 | - `GITHUB_ENTERPRISE_TOKEN` 42 | 43 | ### The `workdir` field 44 | 45 | The optional `workdir` field takes a path in string form. 46 | 47 | Review files and metadata will be placed here. Note `~` and `$HOME` do not 48 | expand. Paths must also be absolute. 49 | 50 | If omitted, `workdir` defaults to `$XDG_DATA_HOME/prr`. 51 | 52 | Example: 53 | 54 | ```toml 55 | [prr] 56 | workdir = "/home/dxu/dev/review" 57 | ``` 58 | 59 | ### The `url` field 60 | 61 | The optional `url` field takes a URL to the Github API in string form. 62 | 63 | This is useful for Github Enterprise deployments where the API endpoint is non-standard. 64 | 65 | Example: 66 | 67 | ```toml 68 | [prr] 69 | url = "https://github.company.com/api/v3" 70 | ``` 71 | 72 | ### The `activate_pr_metadata_experiment` field 73 | 74 | The optional `activate_pr_metadata_experiment` field determines whether, 75 | prr is downloading the PR description as well as the diff of the PR. Note 76 | that the effect as well as the name of this option may change in the 77 | future. 78 | 79 | If this is not explicitly set to "true", it is considered to be set to 80 | "false". 81 | 82 | Example: 83 | 84 | ```toml 85 | [prr] 86 | activate_pr_metadata_experiment = true 87 | ``` 88 | 89 | ## Local configuration 90 | 91 | Local config files must be named `.prr.toml` and will be searched for starting 92 | from the current working directory up every parent directory until either the 93 | first match or the root directory is hit. Local config files override values in 94 | the global config in some cases. 95 | 96 | If the [`[prr]`](#global-configuration) table is provided in a local config 97 | file, it must be fully specified and will override the global config file. 98 | 99 | The following local configuration options are supported: 100 | 101 | * `[local]` 102 | * [`repository`](#the-repository-field) 103 | * [`workdir`](#the-local-workdir-field) 104 | 105 | ### The `repository` field 106 | 107 | The optional `repository` field takes a string in format of 108 | `${ORG}/${REPO}`. 109 | 110 | If specified, you may omit the `${ORG}/${REPO}` from PR string arguments. 111 | For example, you may run `prr get 6` instead of `prr get danobi/prr/6`. 112 | 113 | 114 | Example: 115 | 116 | ```toml 117 | [local] 118 | repository = "danobi/prr" 119 | ``` 120 | 121 | ### The local `workdir` field 122 | 123 | The optional `workdir` field takes a string that represents a path. 124 | 125 | The semantics are the same as [prr.workdir](#the-workdir-field) with the 126 | following exception: in contrast to global workdir, relative local workdir 127 | paths are interpreted as relative to the local config file. 128 | 129 | Example: 130 | 131 | ```toml 132 | [local] 133 | repository = ".prr" 134 | ``` 135 | 136 | [0]: https://specifications.freedesktop.org/basedir-spec/basedir-spec-latest.html 137 | -------------------------------------------------------------------------------- /testdata/hunk_start_no_trailing_whitespace: -------------------------------------------------------------------------------- 1 | > diff --git a/ch5.txt b/ch5.txt 2 | > new file mode 100644 3 | > index 0000000..762722f 4 | > --- /dev/null 5 | > +++ b/ch5.txt 6 | > @@ -0,0 +1,47 @@ 7 | > +CHAPTER 5. ENERGY 8 | > + 9 | > +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. 10 | > + 11 | > +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. 12 | > + 13 | > +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. 14 | 15 | Great passage 16 | 17 | > + 18 | > +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. 19 | > + 20 | > +5. In all fighting, the direct method may be used for joining battle, but indirect methods will be needed in order to secure victory. 21 | > + 22 | > +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. 23 | > + 24 | > +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. 25 | > + 26 | > +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. 27 | > + 28 | > +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. 29 | > + 30 | > +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. 31 | > + 32 | > +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? 33 | > + 34 | > +12. The onset of troops is like the rush of a torrent which will even roll stones along in its course. 35 | > + 36 | > +13. The quality of decision is like the well-timed swoop of a falcon which enables it to strike and destroy its victim. 37 | > + 38 | > +14. Therefore the good fighter will be terrible in his onset, and prompt in his decision. 39 | > + 40 | > +15. Energy may be likened to the bending of a crossbow; decision, to the releasing of a trigger. 41 | > + 42 | > +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. 43 | > + 44 | > +17. Simulated disorder postulates perfect discipline, simulated fear postulates courage; simulated weakness postulates strength. 45 | > + 46 | > +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. 47 | > + 48 | > +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. 49 | > + 50 | > +20. By holding out baits, he keeps him on the march; then with a body of picked men he lies in wait for him. 51 | > + 52 | > +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. 53 | > + 54 | > +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. 55 | > + 56 | > +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. 57 | -------------------------------------------------------------------------------- /testdata/trailing_comment: -------------------------------------------------------------------------------- 1 | > diff --git a/ch1.txt b/ch1.txt 2 | > deleted file mode 100644 3 | > index d30353f..0000000 4 | > --- a/ch1.txt 5 | > +++ /dev/null 6 | > @@ -1,59 +0,0 @@ 7 | 8 | > -THE ART OF WAR BY SUN TZU 9 | > - 10 | > -Translated by Lionel Giles 11 | > -Originally published 1910 12 | > - 13 | > -This version was generated automatically at www.suntzusaid.com. 14 | > - 15 | > - 16 | > -CHAPTER 1. LAYING PLANS 17 | > - 18 | > -1. Sun Tzu said: The art of war is of vital importance to the State. 19 | > - 20 | > -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. 21 | > - 22 | > -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. 23 | > - 24 | > -4. These are: (1) The Moral Law; (2) Heaven; (3) Earth; (4) The Commander; (5) Method and discipline. 25 | > - 26 | > -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. 27 | > - 28 | > -7. HEAVEN signifies night and day, cold and heat, times and seasons. 29 | > - 30 | > -8. EARTH comprises distances, great and small; danger and security; open ground and narrow passes; the chances of life and death. 31 | > - 32 | > -9. The COMMANDER stands for the virtues of wisdom, sincerity, benevolence, courage and strictness. 33 | > - 34 | > -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. 35 | > - 36 | > -11. These five heads should be familiar to every general: he who knows them will be victorious; he who knows them not will fail. 37 | > - 38 | > -12. Therefore, in your deliberations, when seeking to determine the military conditions, let them be made the basis of a comparison, in this wise: 39 | > - 40 | > -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? 41 | > - 42 | > -14. By means of these seven considerations I can forecast victory or defeat. 43 | > - 44 | > -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! 45 | > - 46 | > -16. While heeding the profit of my counsel, avail yourself also of any helpful circumstances over and beyond the ordinary rules. 47 | > - 48 | > -17. According as circumstances are favorable, one should modify one's plans. 49 | > - 50 | > -18. All warfare is based on deception. 51 | > - 52 | > -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. 53 | > - 54 | > -20. Hold out baits to entice the enemy. Feign disorder, and crush him. 55 | > - 56 | > -21. If he is secure at all points, be prepared for him. If he is in superior strength, evade him. 57 | > - 58 | > -22. If your opponent is of choleric temper, seek to irritate him. Pretend to be weak, that he may grow arrogant. 59 | > - 60 | > -23. If he is taking his ease, give him no rest. If his forces are united, separate them. 61 | > - 62 | > -24. Attack him where he is unprepared, appear where you are not expected. 63 | > - 64 | > -25. These military devices, leading to victory, must not be divulged beforehand. 65 | > - 66 | > -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. 67 | 68 | Comment 1 69 | 70 | -------------------------------------------------------------------------------- /testdata/deleted_file: -------------------------------------------------------------------------------- 1 | > diff --git a/ch1.txt b/ch1.txt 2 | > deleted file mode 100644 3 | > index d30353f..0000000 4 | > --- a/ch1.txt 5 | > +++ /dev/null 6 | > @@ -1,59 +0,0 @@ 7 | 8 | > -THE ART OF WAR BY SUN TZU 9 | > - 10 | > -Translated by Lionel Giles 11 | > -Originally published 1910 12 | > - 13 | > -This version was generated automatically at www.suntzusaid.com. 14 | > - 15 | > - 16 | > -CHAPTER 1. LAYING PLANS 17 | > - 18 | > -1. Sun Tzu said: The art of war is of vital importance to the State. 19 | > - 20 | > -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. 21 | > - 22 | > -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. 23 | > - 24 | > -4. These are: (1) The Moral Law; (2) Heaven; (3) Earth; (4) The Commander; (5) Method and discipline. 25 | > - 26 | > -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. 27 | > - 28 | > -7. HEAVEN signifies night and day, cold and heat, times and seasons. 29 | > - 30 | > -8. EARTH comprises distances, great and small; danger and security; open ground and narrow passes; the chances of life and death. 31 | > - 32 | > -9. The COMMANDER stands for the virtues of wisdom, sincerity, benevolence, courage and strictness. 33 | > - 34 | > -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. 35 | > - 36 | > -11. These five heads should be familiar to every general: he who knows them will be victorious; he who knows them not will fail. 37 | > - 38 | > -12. Therefore, in your deliberations, when seeking to determine the military conditions, let them be made the basis of a comparison, in this wise: 39 | > - 40 | > -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? 41 | > - 42 | > -14. By means of these seven considerations I can forecast victory or defeat. 43 | > - 44 | > -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! 45 | > - 46 | > -16. While heeding the profit of my counsel, avail yourself also of any helpful circumstances over and beyond the ordinary rules. 47 | > - 48 | > -17. According as circumstances are favorable, one should modify one's plans. 49 | > - 50 | > -18. All warfare is based on deception. 51 | > - 52 | > -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. 53 | > - 54 | > -20. Hold out baits to entice the enemy. Feign disorder, and crush him. 55 | > - 56 | > -21. If he is secure at all points, be prepared for him. If he is in superior strength, evade him. 57 | > - 58 | > -22. If your opponent is of choleric temper, seek to irritate him. Pretend to be weak, that he may grow arrogant. 59 | > - 60 | > -23. If he is taking his ease, give him no rest. If his forces are united, separate them. 61 | > - 62 | > -24. Attack him where he is unprepared, appear where you are not expected. 63 | > - 64 | > -25. These military devices, leading to victory, must not be divulged beforehand. 65 | > - 66 | 67 | Comment 1 68 | 69 | > -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. 70 | 71 | -------------------------------------------------------------------------------- /book/src/tutorial.md: -------------------------------------------------------------------------------- 1 | # Tutorial 2 | 3 | This tutorial shows you how to create a review against 4 | [prr-test-repo#6][0]. Feel free to review it! 5 | 6 | We assume you've followed all the instructions in 7 | [Installation](./install.md). 8 | 9 | ### Download the PR 10 | 11 | First, let's download a PR: 12 | 13 | ```sh 14 | $ prr get danobi/prr-test-repo/6 15 | /home/dxu/dev/review/danobi/prr-test-repo/6.prr 16 | ``` 17 | 18 | `prr-get` downloads a pull request onto your filesystem into what we call a 19 | "review file". On success, the path to the review file is printed to your 20 | terminal. 21 | 22 | But to be sure, let's check our status: 23 | 24 | ```sh 25 | $ prr status 26 | Handle Status Review file 27 | danobi/prr-test-repo/6 NEW /home/dxu/dev/review/danobi/prr-test-repo/6.prr 28 | ``` 29 | 30 | Great! We've confirmed the review was downloaded. 31 | 32 | ### Mark up the review file 33 | 34 | Now that the review file is downloaded, let's mark it up. You can open 35 | the review file in your favorite editor or use `prr-edit` to automatically 36 | open it in `$EDITOR`. 37 | 38 | ``` 39 | $ prr edit danobi/prr-test-repo/6 40 | ``` 41 | 42 | Your editor should show the contents as something like this: 43 | 44 | ``` 45 | > diff --git a/ch2.txt b/ch2.txt 46 | > index 4d729e6..2641120 100644 47 | > --- a/ch2.txt 48 | > +++ b/ch2.txt 49 | > @@ -2,13 +2,6 @@ CHAPTER 2. WAGING WAR 50 | > 51 | > 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. 52 | > 53 | > -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. 54 | > - 55 | > -3. Again, if the campaign is protracted, the resources of the State will not be equal to the strain. 56 | > - 57 | > -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. 58 | > - 59 | > -5. Thus, though we have heard of stupid haste in war, cleverness has never been seen associated with long delays. 60 | > 61 | > 6. There is no instance of a country having benefited from prolonged warfare. 62 | > 63 | > @@ -30,6 +23,11 @@ CHAPTER 2. WAGING WAR 64 | > 65 | > 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. 66 | > 67 | > +asdf 68 | > +asdf 69 | > +asdf 70 | > +adsf 71 | > + 72 | > 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. 73 | > 74 | > 18. This is called, using the conquered foe to augment one's own strength. 75 | ``` 76 | 77 | There's a lot of diff we don't particularly care about. So let's snip away the 78 | top portion. We can do this by replacing as many contiguous lines as we want 79 | with `[...]`. 80 | 81 | After snipping your review file will look exactly like this: 82 | 83 | ``` 84 | [...] 85 | > @@ -30,6 +23,11 @@ CHAPTER 2. WAGING WAR 86 | > 87 | > 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. 88 | > 89 | > +asdf 90 | > +asdf 91 | > +asdf 92 | > +adsf 93 | > + 94 | > 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. 95 | > 96 | > 18. This is called, using the conquered foe to augment one's own strength. 97 | ``` 98 | 99 | Looks like someone is trying to ruin a classic text with gibberish! Let's tell them to remove it: 100 | 101 | ``` 102 | [...] 103 | > @@ -30,6 +23,11 @@ CHAPTER 2. WAGING WAR 104 | > 105 | > 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. 106 | > 107 | 108 | > +asdf 109 | > +asdf 110 | > +asdf 111 | > +adsf 112 | > + 113 | 114 | Please remove this text! 115 | 116 | [...] 117 | ``` 118 | 119 | Here we've done two things: 120 | 121 | 1. Create a "spanned inline" comment that attaches our comment to a block of 122 | lines. If we omitted the leading newline, we would have a regular "inline" 123 | comment that attaches to the most immediately quoted line. Using spanned 124 | inline comments can be useful when we want to be precise during review. 125 | 1. Snip the trailing text. We didn't have to do this, but it makes the example 126 | a little clearer. 127 | 128 | ### Submit the review 129 | 130 | Now that we're done with our review, it's time to submit it to Github. 131 | Do this by running: 132 | 133 | ```sh 134 | $ prr submit danobi/prr-test-repo/6 135 | ``` 136 | 137 | On success there will not be any output. But just to be safe, let's confirm 138 | submission status: 139 | 140 | ```sh 141 | $ prr status 142 | Handle Status Review file 143 | danobi/prr-test-repo/6 SUBMITTED /home/dxu/dev/review/danobi/prr-test-repo/6.prr 144 | ``` 145 | 146 | Looks like it made it to the web interface as well: 147 | 148 | ![](./images/tutorial_comment.png) 149 | 150 | ### Homework 151 | 152 | Try figuring out how to "request changes" on the PR! 153 | 154 | [0]: https://github.com/danobi/prr-test-repo/pull/6 155 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 2, June 1991 3 | 4 | Copyright (C) 1989, 1991 Free Software Foundation, Inc., 5 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA 6 | Everyone is permitted to copy and distribute verbatim copies 7 | of this license document, but changing it is not allowed. 8 | 9 | Preamble 10 | 11 | The licenses for most software are designed to take away your 12 | freedom to share and change it. By contrast, the GNU General Public 13 | License is intended to guarantee your freedom to share and change free 14 | software--to make sure the software is free for all its users. This 15 | General Public License applies to most of the Free Software 16 | Foundation's software and to any other program whose authors commit to 17 | using it. (Some other Free Software Foundation software is covered by 18 | the GNU Lesser General Public License instead.) You can apply it to 19 | your programs, too. 20 | 21 | When we speak of free software, we are referring to freedom, not 22 | price. Our General Public Licenses are designed to make sure that you 23 | have the freedom to distribute copies of free software (and charge for 24 | this service if you wish), that you receive source code or can get it 25 | if you want it, that you can change the software or use pieces of it 26 | in new free programs; and that you know you can do these things. 27 | 28 | To protect your rights, we need to make restrictions that forbid 29 | anyone to deny you these rights or to ask you to surrender the rights. 30 | These restrictions translate to certain responsibilities for you if you 31 | distribute copies of the software, or if you modify it. 32 | 33 | For example, if you distribute copies of such a program, whether 34 | gratis or for a fee, you must give the recipients all the rights that 35 | you have. You must make sure that they, too, receive or can get the 36 | source code. And you must show them these terms so they know their 37 | rights. 38 | 39 | We protect your rights with two steps: (1) copyright the software, and 40 | (2) offer you this license which gives you legal permission to copy, 41 | distribute and/or modify the software. 42 | 43 | Also, for each author's protection and ours, we want to make certain 44 | that everyone understands that there is no warranty for this free 45 | software. If the software is modified by someone else and passed on, we 46 | want its recipients to know that what they have is not the original, so 47 | that any problems introduced by others will not reflect on the original 48 | authors' reputations. 49 | 50 | Finally, any free program is threatened constantly by software 51 | patents. We wish to avoid the danger that redistributors of a free 52 | program will individually obtain patent licenses, in effect making the 53 | program proprietary. To prevent this, we have made it clear that any 54 | patent must be licensed for everyone's free use or not licensed at all. 55 | 56 | The precise terms and conditions for copying, distribution and 57 | modification follow. 58 | 59 | GNU GENERAL PUBLIC LICENSE 60 | TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 61 | 62 | 0. This License applies to any program or other work which contains 63 | a notice placed by the copyright holder saying it may be distributed 64 | under the terms of this General Public License. The "Program", below, 65 | refers to any such program or work, and a "work based on the Program" 66 | means either the Program or any derivative work under copyright law: 67 | that is to say, a work containing the Program or a portion of it, 68 | either verbatim or with modifications and/or translated into another 69 | language. (Hereinafter, translation is included without limitation in 70 | the term "modification".) Each licensee is addressed as "you". 71 | 72 | Activities other than copying, distribution and modification are not 73 | covered by this License; they are outside its scope. The act of 74 | running the Program is not restricted, and the output from the Program 75 | is covered only if its contents constitute a work based on the 76 | Program (independent of having been made by running the Program). 77 | Whether that is true depends on what the Program does. 78 | 79 | 1. You may copy and distribute verbatim copies of the Program's 80 | source code as you receive it, in any medium, provided that you 81 | conspicuously and appropriately publish on each copy an appropriate 82 | copyright notice and disclaimer of warranty; keep intact all the 83 | notices that refer to this License and to the absence of any warranty; 84 | and give any other recipients of the Program a copy of this License 85 | along with the Program. 86 | 87 | You may charge a fee for the physical act of transferring a copy, and 88 | you may at your option offer warranty protection in exchange for a fee. 89 | 90 | 2. You may modify your copy or copies of the Program or any portion 91 | of it, thus forming a work based on the Program, and copy and 92 | distribute such modifications or work under the terms of Section 1 93 | above, provided that you also meet all of these conditions: 94 | 95 | a) You must cause the modified files to carry prominent notices 96 | stating that you changed the files and the date of any change. 97 | 98 | b) You must cause any work that you distribute or publish, that in 99 | whole or in part contains or is derived from the Program or any 100 | part thereof, to be licensed as a whole at no charge to all third 101 | parties under the terms of this License. 102 | 103 | c) If the modified program normally reads commands interactively 104 | when run, you must cause it, when started running for such 105 | interactive use in the most ordinary way, to print or display an 106 | announcement including an appropriate copyright notice and a 107 | notice that there is no warranty (or else, saying that you provide 108 | a warranty) and that users may redistribute the program under 109 | these conditions, and telling the user how to view a copy of this 110 | License. (Exception: if the Program itself is interactive but 111 | does not normally print such an announcement, your work based on 112 | the Program is not required to print an announcement.) 113 | 114 | These requirements apply to the modified work as a whole. If 115 | identifiable sections of that work are not derived from the Program, 116 | and can be reasonably considered independent and separate works in 117 | themselves, then this License, and its terms, do not apply to those 118 | sections when you distribute them as separate works. But when you 119 | distribute the same sections as part of a whole which is a work based 120 | on the Program, the distribution of the whole must be on the terms of 121 | this License, whose permissions for other licensees extend to the 122 | entire whole, and thus to each and every part regardless of who wrote it. 123 | 124 | Thus, it is not the intent of this section to claim rights or contest 125 | your rights to work written entirely by you; rather, the intent is to 126 | exercise the right to control the distribution of derivative or 127 | collective works based on the Program. 128 | 129 | In addition, mere aggregation of another work not based on the Program 130 | with the Program (or with a work based on the Program) on a volume of 131 | a storage or distribution medium does not bring the other work under 132 | the scope of this License. 133 | 134 | 3. You may copy and distribute the Program (or a work based on it, 135 | under Section 2) in object code or executable form under the terms of 136 | Sections 1 and 2 above provided that you also do one of the following: 137 | 138 | a) Accompany it with the complete corresponding machine-readable 139 | source code, which must be distributed under the terms of Sections 140 | 1 and 2 above on a medium customarily used for software interchange; or, 141 | 142 | b) Accompany it with a written offer, valid for at least three 143 | years, to give any third party, for a charge no more than your 144 | cost of physically performing source distribution, a complete 145 | machine-readable copy of the corresponding source code, to be 146 | distributed under the terms of Sections 1 and 2 above on a medium 147 | customarily used for software interchange; or, 148 | 149 | c) Accompany it with the information you received as to the offer 150 | to distribute corresponding source code. (This alternative is 151 | allowed only for noncommercial distribution and only if you 152 | received the program in object code or executable form with such 153 | an offer, in accord with Subsection b above.) 154 | 155 | The source code for a work means the preferred form of the work for 156 | making modifications to it. For an executable work, complete source 157 | code means all the source code for all modules it contains, plus any 158 | associated interface definition files, plus the scripts used to 159 | control compilation and installation of the executable. However, as a 160 | special exception, the source code distributed need not include 161 | anything that is normally distributed (in either source or binary 162 | form) with the major components (compiler, kernel, and so on) of the 163 | operating system on which the executable runs, unless that component 164 | itself accompanies the executable. 165 | 166 | If distribution of executable or object code is made by offering 167 | access to copy from a designated place, then offering equivalent 168 | access to copy the source code from the same place counts as 169 | distribution of the source code, even though third parties are not 170 | compelled to copy the source along with the object code. 171 | 172 | 4. You may not copy, modify, sublicense, or distribute the Program 173 | except as expressly provided under this License. Any attempt 174 | otherwise to copy, modify, sublicense or distribute the Program is 175 | void, and will automatically terminate your rights under this License. 176 | However, parties who have received copies, or rights, from you under 177 | this License will not have their licenses terminated so long as such 178 | parties remain in full compliance. 179 | 180 | 5. You are not required to accept this License, since you have not 181 | signed it. However, nothing else grants you permission to modify or 182 | distribute the Program or its derivative works. These actions are 183 | prohibited by law if you do not accept this License. Therefore, by 184 | modifying or distributing the Program (or any work based on the 185 | Program), you indicate your acceptance of this License to do so, and 186 | all its terms and conditions for copying, distributing or modifying 187 | the Program or works based on it. 188 | 189 | 6. Each time you redistribute the Program (or any work based on the 190 | Program), the recipient automatically receives a license from the 191 | original licensor to copy, distribute or modify the Program subject to 192 | these terms and conditions. You may not impose any further 193 | restrictions on the recipients' exercise of the rights granted herein. 194 | You are not responsible for enforcing compliance by third parties to 195 | this License. 196 | 197 | 7. If, as a consequence of a court judgment or allegation of patent 198 | infringement or for any other reason (not limited to patent issues), 199 | conditions are imposed on you (whether by court order, agreement or 200 | otherwise) that contradict the conditions of this License, they do not 201 | excuse you from the conditions of this License. If you cannot 202 | distribute so as to satisfy simultaneously your obligations under this 203 | License and any other pertinent obligations, then as a consequence you 204 | may not distribute the Program at all. For example, if a patent 205 | license would not permit royalty-free redistribution of the Program by 206 | all those who receive copies directly or indirectly through you, then 207 | the only way you could satisfy both it and this License would be to 208 | refrain entirely from distribution of the Program. 209 | 210 | If any portion of this section is held invalid or unenforceable under 211 | any particular circumstance, the balance of the section is intended to 212 | apply and the section as a whole is intended to apply in other 213 | circumstances. 214 | 215 | It is not the purpose of this section to induce you to infringe any 216 | patents or other property right claims or to contest validity of any 217 | such claims; this section has the sole purpose of protecting the 218 | integrity of the free software distribution system, which is 219 | implemented by public license practices. Many people have made 220 | generous contributions to the wide range of software distributed 221 | through that system in reliance on consistent application of that 222 | system; it is up to the author/donor to decide if he or she is willing 223 | to distribute software through any other system and a licensee cannot 224 | impose that choice. 225 | 226 | This section is intended to make thoroughly clear what is believed to 227 | be a consequence of the rest of this License. 228 | 229 | 8. If the distribution and/or use of the Program is restricted in 230 | certain countries either by patents or by copyrighted interfaces, the 231 | original copyright holder who places the Program under this License 232 | may add an explicit geographical distribution limitation excluding 233 | those countries, so that distribution is permitted only in or among 234 | countries not thus excluded. In such case, this License incorporates 235 | the limitation as if written in the body of this License. 236 | 237 | 9. The Free Software Foundation may publish revised and/or new versions 238 | of the General Public License from time to time. Such new versions will 239 | be similar in spirit to the present version, but may differ in detail to 240 | address new problems or concerns. 241 | 242 | Each version is given a distinguishing version number. If the Program 243 | specifies a version number of this License which applies to it and "any 244 | later version", you have the option of following the terms and conditions 245 | either of that version or of any later version published by the Free 246 | Software Foundation. If the Program does not specify a version number of 247 | this License, you may choose any version ever published by the Free Software 248 | Foundation. 249 | 250 | 10. If you wish to incorporate parts of the Program into other free 251 | programs whose distribution conditions are different, write to the author 252 | to ask for permission. For software which is copyrighted by the Free 253 | Software Foundation, write to the Free Software Foundation; we sometimes 254 | make exceptions for this. Our decision will be guided by the two goals 255 | of preserving the free status of all derivatives of our free software and 256 | of promoting the sharing and reuse of software generally. 257 | 258 | NO WARRANTY 259 | 260 | 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY 261 | FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN 262 | OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES 263 | PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED 264 | OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF 265 | MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS 266 | TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE 267 | PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, 268 | REPAIR OR CORRECTION. 269 | 270 | 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 271 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR 272 | REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, 273 | INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING 274 | OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED 275 | TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY 276 | YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER 277 | PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE 278 | POSSIBILITY OF SUCH DAMAGES. 279 | 280 | END OF TERMS AND CONDITIONS 281 | 282 | How to Apply These Terms to Your New Programs 283 | 284 | If you develop a new program, and you want it to be of the greatest 285 | possible use to the public, the best way to achieve this is to make it 286 | free software which everyone can redistribute and change under these terms. 287 | 288 | To do so, attach the following notices to the program. It is safest 289 | to attach them to the start of each source file to most effectively 290 | convey the exclusion of warranty; and each file should have at least 291 | the "copyright" line and a pointer to where the full notice is found. 292 | 293 | 294 | Copyright (C) 295 | 296 | This program is free software; you can redistribute it and/or modify 297 | it under the terms of the GNU General Public License as published by 298 | the Free Software Foundation; either version 2 of the License, or 299 | (at your option) any later version. 300 | 301 | This program is distributed in the hope that it will be useful, 302 | but WITHOUT ANY WARRANTY; without even the implied warranty of 303 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 304 | GNU General Public License for more details. 305 | 306 | You should have received a copy of the GNU General Public License along 307 | with this program; if not, write to the Free Software Foundation, Inc., 308 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. 309 | 310 | Also add information on how to contact you by electronic and paper mail. 311 | 312 | If the program is interactive, make it output a short notice like this 313 | when it starts in an interactive mode: 314 | 315 | Gnomovision version 69, Copyright (C) year name of author 316 | Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 317 | This is free software, and you are welcome to redistribute it 318 | under certain conditions; type `show c' for details. 319 | 320 | The hypothetical commands `show w' and `show c' should show the appropriate 321 | parts of the General Public License. Of course, the commands you use may 322 | be called something other than `show w' and `show c'; they could even be 323 | mouse-clicks or menu items--whatever suits your program. 324 | 325 | You should also get your employer (if you work as a programmer) or your 326 | school, if any, to sign a "copyright disclaimer" for the program, if 327 | necessary. Here is a sample; alter the names: 328 | 329 | Yoyodyne, Inc., hereby disclaims all copyright interest in the program 330 | `Gnomovision' (which makes passes at compilers) written by James Hacker. 331 | 332 | , 1 April 1989 333 | Ty Coon, President of Vice 334 | 335 | This General Public License does not permit incorporating your program into 336 | proprietary programs. If your program is a subroutine library, you may 337 | consider it more useful to permit linking proprietary applications with the 338 | library. If this is what you want to do, use the GNU Lesser General 339 | Public License instead of this License. 340 | -------------------------------------------------------------------------------- /src/review.rs: -------------------------------------------------------------------------------- 1 | use std::fmt::{Display, Formatter, Result as fmt_result, Write as fmt_write}; 2 | use std::fs; 3 | use std::fs::OpenOptions; 4 | use std::io::Write; 5 | use std::path::{Path, PathBuf}; 6 | use std::time::SystemTime; 7 | 8 | use anyhow::{anyhow, bail, Context, Result}; 9 | use serde_derive::{Deserialize, Serialize}; 10 | 11 | use crate::parser::{Comment, FileComment, InlineComment, ReviewAction, ReviewParser}; 12 | 13 | /// We support a few common variants of snips. 14 | /// These are semantically identical. 15 | const SNIP_VARIANTS: &[&str] = &["[..]", "[...]"]; 16 | 17 | /// Represents the state of a single review 18 | pub struct Review { 19 | /// Path to workdir 20 | workdir: PathBuf, 21 | /// Name of the owner of the repository 22 | owner: String, 23 | /// Name of the repository 24 | repo: String, 25 | /// Issue # of the pull request 26 | pr_num: u64, 27 | } 28 | 29 | /// Metadata for a single review. Stored as dotfile next to user-facing review file 30 | #[derive(Serialize, Deserialize, Debug)] 31 | struct ReviewMetadata { 32 | /// Original .diff file contents. Used to detect corrupted review files 33 | original: String, 34 | /// Time (seconds since epoch) the review file was last submitted 35 | submitted: Option, 36 | /// The commit hash of the PR at the time the review was started 37 | commit_id: Option, 38 | } 39 | 40 | /// Status of a review 41 | #[derive(PartialEq, Debug)] 42 | pub enum ReviewStatus { 43 | /// Newly downloaded review; no changes yet 44 | New, 45 | /// Unsubmitted changes have been made to review file 46 | Reviewed, 47 | /// Review has been submitted. Any further changes to the review file are ignored 48 | Submitted, 49 | } 50 | 51 | /// Represents a single line in a review file. 52 | enum LineType<'a> { 53 | /// Original text (but stored without the leading `> `) 54 | Quoted(&'a str), 55 | /// A snip (`[..]`) 56 | Snip, 57 | /// User supplied comment 58 | Comment(&'a str), 59 | } 60 | 61 | impl Display for ReviewStatus { 62 | fn fmt(&self, f: &mut Formatter<'_>) -> fmt_result { 63 | let text = match self { 64 | Self::New => "NEW", 65 | Self::Reviewed => "REVIEWED", 66 | Self::Submitted => "SUBMITTED", 67 | }; 68 | 69 | write!(f, "{text}") 70 | } 71 | } 72 | 73 | impl<'a> From<&'a str> for LineType<'a> { 74 | fn from(line: &'a str) -> Self { 75 | if let Some(text) = line.strip_prefix("> ") { 76 | Self::Quoted(text) 77 | } else if SNIP_VARIANTS.contains(&line.trim()) { 78 | Self::Snip 79 | } else { 80 | Self::Comment(line) 81 | } 82 | } 83 | } 84 | 85 | fn prefix_lines(s: &str, prefix: &str) -> String { 86 | let mut ret = String::with_capacity(s.len()); 87 | 88 | for line in s.lines() { 89 | if line.is_empty() { 90 | ret += &(prefix.to_owned() + " \n"); 91 | } else { 92 | // Appending to heap allocated string cannot fail 93 | writeln!(ret, "{} {}", prefix, line).expect("Failed to write to string"); 94 | } 95 | } 96 | 97 | ret 98 | } 99 | 100 | /// Returns a list of all reviews in a workdir 101 | pub fn get_all_existing(workdir: &Path) -> Result> { 102 | // This pipeline does the following: 103 | // * Iterate through all org directories in workdir 104 | // * For each org directory, iterate through all contained repo directories 105 | // * For each repo directory, enumerate all non-metadata review files 106 | let reviews: Vec = fs::read_dir(workdir) 107 | .context("Failed to read workdir")? 108 | .filter_map(|entry| entry.ok()) 109 | .map(|org| org.path()) 110 | .filter(|org| org.is_dir()) 111 | .filter_map(|org| fs::read_dir(org).ok()) 112 | .flatten() 113 | .filter_map(|repo| repo.ok()) 114 | .map(|repo| repo.path()) 115 | .filter(|repo| repo.is_dir()) 116 | .filter_map(|repo| fs::read_dir(repo).ok()) 117 | .flatten() 118 | .filter_map(|review| review.ok()) 119 | .map(|review| review.path()) 120 | .filter(|review| review.is_file()) 121 | .filter(|review| match review.extension() { 122 | Some(e) => e == "prr", 123 | None => false, 124 | }) 125 | .collect(); 126 | 127 | let mut ret = Vec::with_capacity(reviews.len()); 128 | for review in reviews { 129 | let parts: Vec<_> = review 130 | .iter() 131 | .rev() 132 | .take(3) 133 | .map(|p| p.to_string_lossy()) 134 | .collect(); 135 | 136 | if parts.len() != 3 { 137 | bail!("malformed review file path: {}", review.display()); 138 | } 139 | 140 | let pr_num: u64 = parts[0] 141 | .strip_suffix(".prr") 142 | .unwrap_or(&parts[0]) 143 | .parse() 144 | .with_context(|| format!("Failed to parse PR num: {}", review.display()))?; 145 | 146 | // Note the vec has components reversed 147 | let r = Review::new_existing(workdir, &parts[2], &parts[1], pr_num); 148 | ret.push(r); 149 | } 150 | 151 | Ok(ret) 152 | } 153 | 154 | /// Recursive helper for `resolve_snips()`. 155 | /// 156 | /// This function will return Some(lines), where lines is a Vec of resolved 157 | /// lines. There should not be any trailing newlines in `lines`. 158 | /// 159 | /// The problem of resolving snips transposes pretty cleanly to the classic 160 | /// glob matching algorithm. We implement the glob matching fairly naively 161 | /// using recursion b/c it's cleaner to recurse when we want to eventually 162 | /// return a value. 163 | /// 164 | /// This would be in contrast to rsc's glob algorithm [0] where it's more 165 | /// efficient and has less pathological corner cases. We choose to trade off 166 | /// performance for simplicity here. 167 | /// 168 | /// [0]: https://research.swtch.com/glob 169 | fn resolve_snips_recurse<'a>(pattern: &[LineType<'a>], text: &[&'a str]) -> Option> { 170 | let mut resolved = Vec::new(); 171 | let mut pattern_idx = 0; 172 | let mut text_idx = 0; 173 | while pattern_idx < pattern.len() || text_idx < text.len() { 174 | if pattern_idx < pattern.len() { 175 | match pattern[pattern_idx] { 176 | LineType::Quoted(line) => { 177 | if text_idx < text.len() && text[text_idx] == line { 178 | resolved.push(format!("> {line}")); 179 | pattern_idx += 1; 180 | text_idx += 1; 181 | continue; 182 | } 183 | } 184 | // Comments are semantically irrelevant to snip resolution. But we still 185 | // need to account for them in returned output. 186 | LineType::Comment(line) => { 187 | resolved.push(line.to_string()); 188 | pattern_idx += 1; 189 | continue; 190 | } 191 | // Begin glob logic 192 | LineType::Snip => { 193 | // Here we try making the snip consume 0 lines, 1 line, and so forth. 194 | // 195 | // Skipping comments is technically a noop and in theory we could rework 196 | // this code to only skip matchable text. But that is just an optimization. 197 | for cand_text_idx in text_idx..=text.len() { 198 | let cand_pattern = &pattern[pattern_idx + 1..]; 199 | let cand_text = &text[cand_text_idx..]; 200 | if let Some(mut r) = resolve_snips_recurse(cand_pattern, cand_text) { 201 | let skipped: Vec = text[text_idx..cand_text_idx] 202 | .iter() 203 | .map(|&line| format!("> {line}")) 204 | .collect(); 205 | resolved.extend_from_slice(&skipped); 206 | resolved.append(&mut r); 207 | return Some(resolved); 208 | } 209 | } 210 | } 211 | } 212 | } 213 | 214 | // If we reach here, we either have some `pattern` or `text` still left to 215 | // process. Meaning one ran out before the other. Which implies a resolution 216 | // failure. 217 | return None; 218 | } 219 | 220 | // We've finished processing all of `text` and `pattern`. So resolution success. 221 | Some(resolved) 222 | } 223 | 224 | impl Review { 225 | /// Creates a new `Review` 226 | /// 227 | /// `review_file` is the path where the user-facing review file should 228 | /// be created. Additional metadata files (dotfiles) may be created in the same 229 | /// directory. 230 | pub fn new( 231 | workdir: &Path, 232 | diff: String, 233 | owner: &str, 234 | repo: &str, 235 | pr_description: Option, 236 | pr_num: u64, 237 | commit_id: String, 238 | force: bool, 239 | ) -> Result { 240 | let review = Review { 241 | workdir: workdir.to_owned(), 242 | owner: owner.to_owned(), 243 | repo: repo.to_owned(), 244 | pr_num, 245 | }; 246 | 247 | // First create directories leading up to review file if necessary 248 | let review_path = review.path(); 249 | let review_dir = review_path 250 | .parent() 251 | .ok_or_else(|| anyhow!("Review path has no parent!"))?; 252 | fs::create_dir_all(review_dir).context("Failed to create workdir directories")?; 253 | 254 | // Check if there are unsubmitted changes 255 | if !force && review.has_metadata() && review.status()? == ReviewStatus::Reviewed { 256 | bail!( 257 | "You have unsubmitted changes to the requested review. \ 258 | Either submit the existing changes, delete the existing review file, \ 259 | or re-run this command with --force." 260 | ); 261 | } 262 | 263 | // Now create review file 264 | let mut review_file = OpenOptions::new() 265 | .write(true) 266 | .create(true) 267 | .truncate(true) 268 | .open(&review_path) 269 | .context("Failed to create review file")?; 270 | 271 | let mut description = pr_description.unwrap_or_else(String::default); 272 | if !description.is_empty() { 273 | description += "\n"; 274 | } 275 | 276 | let original_contents = description + &diff; 277 | let prefixed_contents = prefix_lines(&original_contents, ">"); 278 | review_file 279 | .write_all(prefixed_contents.as_bytes()) 280 | .context("Failed to write review file")?; 281 | 282 | // Create metadata file 283 | let metadata = ReviewMetadata { 284 | original: original_contents, 285 | submitted: None, 286 | commit_id: Some(commit_id), 287 | }; 288 | let json = serde_json::to_string(&metadata)?; 289 | let metadata_path = review.metadata_path(); 290 | let mut metadata_file = OpenOptions::new() 291 | .write(true) 292 | .create(true) 293 | .truncate(true) 294 | .open(metadata_path) 295 | .context("Failed to create metadata file")?; 296 | metadata_file 297 | .write_all(json.as_bytes()) 298 | .context("Failed to write metadata file")?; 299 | 300 | Ok(review) 301 | } 302 | 303 | /// Creates a `Review` that already exists on disk 304 | /// 305 | /// Note we do not check that anything actually exists on disk because that is 306 | /// inherently racy. We'll handle ENOENT errors when we actually use any files. 307 | pub fn new_existing(workdir: &Path, owner: &str, repo: &str, pr_num: u64) -> Review { 308 | Review { 309 | workdir: workdir.to_owned(), 310 | owner: owner.to_owned(), 311 | repo: repo.to_owned(), 312 | pr_num, 313 | } 314 | } 315 | 316 | /// Parse the user-supplied comments on a review 317 | /// 318 | /// Returns (overall review action, overall review comment, inline comments, file comments) 319 | pub fn comments(&self) -> Result<(ReviewAction, String, Vec, Vec)> { 320 | let raw = fs::read_to_string(self.path()).context("Failed to read review file")?; 321 | let contents = self.resolve_snips(&raw)?; 322 | self.validate_review_file(&contents)?; 323 | 324 | let mut parser = ReviewParser::new(); 325 | let mut review_action = ReviewAction::Comment; 326 | let mut review_comment = String::new(); 327 | let mut inline_comments = Vec::new(); 328 | let mut file_comments = Vec::new(); 329 | for (idx, line) in contents.lines().enumerate() { 330 | let res = parser 331 | .parse_line(line) 332 | .with_context(|| format!("Failed to parse review on line {}", idx + 1))?; 333 | 334 | match res { 335 | Some(Comment::Review(c)) => { 336 | if !review_comment.is_empty() { 337 | bail!("Somehow saw more than one review comment"); 338 | } 339 | 340 | review_comment = c; 341 | } 342 | Some(Comment::Inline(c)) => inline_comments.push(c), 343 | Some(Comment::ReviewAction(a)) => review_action = a, 344 | Some(Comment::File(fc)) => file_comments.push(fc), 345 | None => {} 346 | } 347 | } 348 | 349 | match parser.finish() { 350 | Some(Comment::Inline(c)) => inline_comments.push(c), 351 | // Original diff must have been short to begin with 352 | Some(Comment::Review(_)) => bail!("Unexpected review comment at parser finish"), 353 | Some(Comment::ReviewAction(_)) => bail!("Unexpected review action at parser finish"), 354 | Some(Comment::File(_)) => bail!("Unexpected file-level comment at parser finish"), 355 | None => {} 356 | }; 357 | 358 | Ok(( 359 | review_action, 360 | review_comment, 361 | inline_comments, 362 | file_comments, 363 | )) 364 | } 365 | 366 | /// Update the review file's submission time 367 | pub fn mark_submitted(&self) -> Result<()> { 368 | let metadata_path = self.metadata_path(); 369 | let mut metadata = self.metadata()?; 370 | 371 | let submission_time = SystemTime::now() 372 | .duration_since(SystemTime::UNIX_EPOCH) 373 | .expect("Time went backwards"); 374 | metadata.submitted = Some(submission_time.as_secs()); 375 | 376 | let json = serde_json::to_string(&metadata)?; 377 | let mut metadata_file = OpenOptions::new() 378 | .write(true) 379 | .create(true) 380 | .truncate(true) 381 | .open(metadata_path) 382 | .context("Failed to create metadata file")?; 383 | metadata_file 384 | .write_all(json.as_bytes()) 385 | .context("Failed to write metadata file")?; 386 | 387 | Ok(()) 388 | } 389 | 390 | /// Replaces all snips (`[...]`s) from `contents` with original, quoted text. 391 | /// Returns resolved contents as new string. 392 | fn resolve_snips(&self, contents: &str) -> Result { 393 | // First, classify contents into line types. This is henceforth 394 | // known as the "pattern" we want to resolve against original text. 395 | let pattern: Vec = contents.lines().map(LineType::from).collect(); 396 | 397 | // If the review file does not have any snips, just skip snip resolution. 398 | // 399 | // We do this so user gets more informative error message thru validate_review_file() 400 | // if they corrupted a quoted line. If we naively (and more efficiently) always 401 | // try to resolve snips, they might get the less informative error below. 402 | if !pattern.iter().any(|line| matches!(line, LineType::Snip)) { 403 | return Ok(contents.to_string()); 404 | } 405 | 406 | // Next, store original text as lines. It's easier to index into this way. 407 | // The original text here is unquoted. 408 | let original = self.metadata()?.original; 409 | let text: Vec<&str> = original.lines().collect(); 410 | 411 | Ok(resolve_snips_recurse(&pattern, &text) 412 | .ok_or_else(|| anyhow!("Failed to resolve snips. Did you corrupt quoted text?"))? 413 | .iter() 414 | .map(|line| format!("{line}\n")) 415 | .collect()) 416 | } 417 | 418 | /// Validates whether the user corrupted the quoted contents 419 | fn validate_review_file(&self, contents: &str) -> Result<()> { 420 | let mut reconstructed = String::with_capacity(contents.len()); 421 | for line in contents.lines() { 422 | if let Some(stripped) = line.strip_prefix("> ") { 423 | reconstructed += stripped.trim_end(); 424 | reconstructed += "\n"; 425 | } 426 | 427 | if line == ">" { 428 | reconstructed += "\n"; 429 | } 430 | } 431 | 432 | let metadata = self.metadata()?; 433 | let original: String = metadata 434 | .original 435 | .lines() 436 | .map(|line| line.trim_end().to_owned() + "\n") 437 | .collect(); 438 | 439 | if reconstructed != original { 440 | // Be helpful and provide exact line number of mismatch. 441 | // 442 | // This loop on zip() will work as long as there isn't any truncation or trailing junk 443 | // in the original text. To handle this case, there's the final bail!() 444 | for (idx, (l, r)) in reconstructed.lines().zip(original.lines()).enumerate() { 445 | if l != r { 446 | // Get number of user generated lines up until the mismatch 447 | let user_lines = contents 448 | .lines() 449 | .take(idx) 450 | .filter(|l| !l.starts_with('>')) 451 | .count(); 452 | let err = format!("Line {}, found '{l}' expected '{r}'", idx + 1 + user_lines); 453 | bail!("Detected corruption in quoted part of review file: {err}"); 454 | } 455 | } 456 | 457 | bail!("Detected corruption in quoted part of review file: found trailing or truncated lines"); 458 | } 459 | 460 | Ok(()) 461 | } 462 | 463 | /// Returns whether or not there exists review comments 464 | fn reviewed(&self) -> Result { 465 | let (_, review_comment, comments, file_comments) = self 466 | .comments() 467 | .with_context(|| anyhow!("Failed to parse comments for {}", self.path().display()))?; 468 | 469 | Ok(!review_comment.is_empty() || !comments.is_empty() || !file_comments.is_empty()) 470 | } 471 | 472 | /// Returns path to user-facing review file 473 | pub fn path(&self) -> PathBuf { 474 | let mut p = self.workdir.clone(); 475 | p.push(&self.owner); 476 | p.push(&self.repo); 477 | p.push(format!("{}.prr", self.pr_num)); 478 | 479 | p 480 | } 481 | 482 | /// Loads and returns the parsed contents of the metadata file for the review file 483 | fn metadata(&self) -> Result { 484 | let meta = 485 | fs::read_to_string(self.metadata_path()).context("Failed to load metadata file")?; 486 | serde_json::from_str::(&meta).context("Failed to parse metadata file") 487 | } 488 | 489 | fn has_metadata(&self) -> bool { 490 | fs::metadata(self.metadata_path()).is_ok() 491 | } 492 | 493 | fn metadata_path(&self) -> PathBuf { 494 | let mut metadata_path = self.path(); 495 | metadata_path.set_file_name(format!(".{}", self.pr_num)); 496 | 497 | metadata_path 498 | } 499 | 500 | /// Returns the commit_id associated with the review 501 | pub fn commit_id(&self) -> Result> { 502 | Ok(self.metadata()?.commit_id.clone()) 503 | } 504 | 505 | /// Returns the original review diff 506 | pub fn diff(&self) -> Result { 507 | Ok(self.metadata()?.original.clone()) 508 | } 509 | 510 | /// Returns a handle (eg "owner/repo/pr_num") to this review 511 | pub fn handle(&self) -> String { 512 | format!("{}/{}/{}", self.owner, self.repo, self.pr_num) 513 | } 514 | 515 | /// Gets the status of a review 516 | pub fn status(&self) -> Result { 517 | let metadata = self.metadata()?; 518 | let reviewed = self.reviewed()?; 519 | let status = if metadata.submitted.is_some() { 520 | ReviewStatus::Submitted 521 | } else if reviewed { 522 | ReviewStatus::Reviewed 523 | } else { 524 | ReviewStatus::New 525 | }; 526 | 527 | Ok(status) 528 | } 529 | 530 | /// Remove review from filesystem 531 | pub fn remove(self, force: bool) -> Result<()> { 532 | if !force && self.status()? == ReviewStatus::Reviewed { 533 | bail!( 534 | "You have unsubmitted changes to the requested review. \ 535 | Re-run this command with --force to ignore this check." 536 | ); 537 | } 538 | 539 | fs::remove_file(self.path()).context("Failed to remove review file")?; 540 | fs::remove_file(self.metadata_path()).context("Failed to remove metadata file")?; 541 | 542 | Ok(()) 543 | } 544 | } 545 | 546 | #[cfg(test)] 547 | mod tests { 548 | use std::collections::VecDeque; 549 | use std::fs::{create_dir_all, File}; 550 | 551 | use pretty_assertions::assert_eq as assert_eq_pretty; 552 | use tempfile::{tempdir, TempDir}; 553 | 554 | use super::*; 555 | 556 | fn setup(review: &str, metadata: &str) -> (Review, TempDir) { 557 | let dir = tempdir().expect("Failed to create tempdir"); 558 | 559 | // Create directory structure 560 | let project_dir = dir.path().join("some_owner").join("some_repo"); 561 | create_dir_all(&project_dir).expect("Failed to create workdir structure"); 562 | 563 | // Create and write review file 564 | let mut review_file = 565 | File::create(project_dir.join("3.prr")).expect("Failed to create review file"); 566 | review_file 567 | .write_all(review.as_bytes()) 568 | .expect("Failed to write review file"); 569 | 570 | // Create and write metadata file 571 | let mut metadata_file = 572 | File::create(project_dir.join(".3")).expect("Failed to create metadata file"); 573 | metadata_file 574 | .write_all(metadata.as_bytes()) 575 | .expect("Failed to write metadata file"); 576 | 577 | let r = Review::new_existing(dir.path(), "some_owner", "some_repo", 3); 578 | 579 | (r, dir) 580 | } 581 | 582 | // Review file has all trailing whitespace stripped 583 | #[test] 584 | fn test_validate_stripped() { 585 | let review = include_str!("../testdata/review/trailing_whitespace/review"); 586 | let metadata = include_str!("../testdata/review/trailing_whitespace/metadata"); 587 | let (r, _dir) = setup(review, metadata); 588 | 589 | r.validate_review_file(review) 590 | .expect("Failed to validate review file"); 591 | } 592 | 593 | // Step through review status state machine and validate each state 594 | #[test] 595 | fn test_review_status() { 596 | let review = include_str!("../testdata/review/status/review"); 597 | let metadata = include_str!("../testdata/review/status/metadata"); 598 | let (r, _dir) = setup(review, metadata); 599 | 600 | // Using more verbose match to ensure build failure if new states added. 601 | // We only need this verbosity once. 602 | match r.status().expect("Failed to get review status") { 603 | ReviewStatus::New => (), 604 | ReviewStatus::Reviewed => panic!("Unexpected Reviewed state"), 605 | ReviewStatus::Submitted => panic!("Unpexected Submitted state"), 606 | }; 607 | 608 | // Do a "review" 609 | let mut file = OpenOptions::new() 610 | .write(true) 611 | .append(true) 612 | .open(r.path()) 613 | .expect("Failed to open review file"); 614 | file.write_all(b"asdf\n") 615 | .expect("Failed to write review comment"); 616 | assert_eq!(r.status().unwrap(), ReviewStatus::Reviewed); 617 | 618 | // "Submit" the review 619 | r.mark_submitted().expect("Failed to submit review"); 620 | assert_eq!(r.status().unwrap(), ReviewStatus::Submitted); 621 | } 622 | 623 | #[test] 624 | fn test_review_validation_with_pr_description() { 625 | let review = include_str!("../testdata/review/pr_description/review"); 626 | let metadata = include_str!("../testdata/review/pr_description/metadata"); 627 | let (r, _dir) = setup(review, metadata); 628 | 629 | r.validate_review_file(review) 630 | .expect("Failed to validate review file with PR description"); 631 | } 632 | 633 | #[test] 634 | fn test_review_validation_with_interleaving_pr_description() { 635 | let review = include_str!("../testdata/review/pr_description_interleaving/review"); 636 | let metadata = include_str!("../testdata/review/pr_description_interleaving/metadata"); 637 | let (r, _dir) = setup(review, metadata); 638 | 639 | r.validate_review_file(review) 640 | .expect("Failed to validate review file with interleaving PR description"); 641 | } 642 | 643 | // Tests creation of a new review 644 | #[test] 645 | fn test_new_review() { 646 | // Create directory structure 647 | let workdir = tempdir().expect("Failed to create tempdir"); 648 | 649 | // Create a review 650 | let review = Review::new( 651 | workdir.path(), 652 | "some_review_contents".to_string(), 653 | "some_owner", 654 | "some_repo", 655 | Some("some_pr_desc".to_string()), 656 | 3, 657 | "111".to_string(), 658 | false, 659 | ) 660 | .expect("Failed to create new non-existent review"); 661 | 662 | // Check on disk "database" 663 | fs::metadata(review.path()).expect("Failed to read review file"); 664 | fs::metadata(review.metadata_path()).expect("Failed to read review file"); 665 | } 666 | 667 | #[test] 668 | fn test_snip_single() { 669 | let review = include_str!("../testdata/review/snip_single/review"); 670 | let gold = include_str!("../testdata/review/snip_single/gold"); 671 | let metadata = include_str!("../testdata/review/snip_single/metadata"); 672 | 673 | let (r, _dir) = setup(review, metadata); 674 | assert_eq_pretty!(r.resolve_snips(review).unwrap(), gold); 675 | } 676 | 677 | #[test] 678 | fn test_snip_multiple() { 679 | let review = include_str!("../testdata/review/snip_multiple/review"); 680 | let gold = include_str!("../testdata/review/snip_multiple/gold"); 681 | let metadata = include_str!("../testdata/review/snip_multiple/metadata"); 682 | 683 | let (r, _dir) = setup(review, metadata); 684 | assert_eq_pretty!(r.resolve_snips(review).unwrap(), gold); 685 | } 686 | 687 | #[test] 688 | fn test_snip_comments() { 689 | let review = include_str!("../testdata/review/snip_comments/review"); 690 | let gold = include_str!("../testdata/review/snip_comments/gold"); 691 | let metadata = include_str!("../testdata/review/snip_comments/metadata"); 692 | 693 | let (r, _dir) = setup(review, metadata); 694 | assert_eq_pretty!(r.resolve_snips(review).unwrap(), gold); 695 | } 696 | 697 | // Here we exhaustively check all possible single snips. It may be worth doing something 698 | // similar for multiple snips but it'll be a bit more complicated to implement. 699 | #[test] 700 | fn test_snip_single_exhaustive() { 701 | let gold = include_str!("../testdata/review/snip_single/gold"); 702 | let metadata = include_str!("../testdata/review/snip_single/metadata"); 703 | let (r, _dir) = setup("", metadata); 704 | 705 | let nr_lines = gold.lines().count(); 706 | 707 | for position in 0..=nr_lines { 708 | for length in 0..=nr_lines { 709 | let mut lines: VecDeque<&str> = gold.lines().collect(); 710 | let mut contents = String::new(); 711 | let mut idx = 0; 712 | 713 | while !lines.is_empty() { 714 | if idx == position { 715 | writeln!(&mut contents, "[...]").unwrap(); 716 | for _ in 0..length { 717 | lines.pop_front(); 718 | idx += 1; 719 | } 720 | } 721 | 722 | // A snip appended to gold file will go past "end" of lines 723 | if let Some(line) = lines.pop_front() { 724 | writeln!(&mut contents, "{line}").unwrap(); 725 | } 726 | 727 | idx += 1; 728 | } 729 | 730 | // Handle 0 length trailing snip 731 | if idx == position { 732 | writeln!(&mut contents, "[...]").unwrap(); 733 | } 734 | 735 | assert_eq_pretty!(r.resolve_snips(&contents).unwrap(), gold); 736 | } 737 | } 738 | } 739 | } 740 | -------------------------------------------------------------------------------- /src/parser.rs: -------------------------------------------------------------------------------- 1 | use anyhow::{anyhow, bail, Context, Result}; 2 | use lazy_static::lazy_static; 3 | use regex::Regex; 4 | 5 | // Use lazy static to ensure regex is only compiled once 6 | lazy_static! { 7 | // Regex for the start of a hunk. The start of a hunk should look like: 8 | // 9 | // `@@ -731,7 +731,7 @@[...]` 10 | // 11 | static ref HUNK_START: Regex = Regex::new(r"^@@ -(?P\d+)(?:,(?P\d+))? \+(?P\d+)(?:,(?P\d+))? @@").unwrap(); 12 | // Regex for start of a file diff. The start of a file diff should look like: 13 | // 14 | // `diff --git a/ch1.txt b/ch1.txt` 15 | // 16 | static ref DIFF_START: Regex = Regex::new(r"^diff --git a/.+ b/(?P.+)$").unwrap(); 17 | } 18 | 19 | /// The location of a line 20 | /// 21 | /// The distinction between Left and Right is important when commenting on 22 | /// deleted or added lines. A useful way to think about the line location is 23 | /// the line number a comment should be attached to in the file pre-change (left) 24 | /// or the file post-change (right) 25 | #[derive(Debug, PartialEq, Eq, Clone)] 26 | pub enum LineLocation { 27 | /// The "red"/deleted side of the diff 28 | Left(u64), 29 | /// The "green"/added or "white"/existing side of the diff 30 | Right(u64), 31 | } 32 | 33 | /// Represents a single inline comment on a review 34 | #[derive(Debug, PartialEq, Eq)] 35 | pub struct InlineComment { 36 | /// File the comment is in 37 | /// 38 | /// Note that this is the new filename if the file was also moved 39 | pub file: String, 40 | pub line: LineLocation, 41 | /// For a spanned comment, the first line of the span. See `line` for docs on semantics 42 | pub start_line: Option, 43 | /// The user-supplied review comment 44 | pub comment: String, 45 | } 46 | 47 | /// Represents a single file-level comment on a review 48 | #[derive(Debug, PartialEq, Eq)] 49 | pub struct FileComment { 50 | /// File the comment is in 51 | /// 52 | /// Note that this is the new filename if the file was also moved 53 | pub file: String, 54 | /// The user-supplied review comment 55 | pub comment: String, 56 | } 57 | 58 | #[derive(Debug, PartialEq, Eq)] 59 | pub enum ReviewAction { 60 | Approve, 61 | RequestChanges, 62 | Comment, 63 | } 64 | 65 | /// Represents a comment of some sort on a review 66 | #[derive(Debug, PartialEq, Eq)] 67 | pub enum Comment { 68 | /// Overall review comment (the summary comment) 69 | Review(String), 70 | /// An inline comment (attached to a line) 71 | Inline(InlineComment), 72 | /// Overall approve, reject, or comment on review 73 | ReviewAction(ReviewAction), 74 | // A file-level comment (attached to the whole file) 75 | File(FileComment), 76 | } 77 | 78 | #[derive(Default)] 79 | struct StartState { 80 | /// Each line of review-level comment is stored as an entry 81 | comment: Vec, 82 | 83 | /// Only if there was unquoted content in the Start state we should 84 | /// send a review comment. If there was no unquoted content, there 85 | /// was no review comment. 86 | had_unquoted_content: bool, 87 | 88 | /// After we have seen the prr directive we assume the review 89 | /// comment is done. This allows us to ignore the PR description as 90 | /// long as we have the prr directive before it. 91 | had_review_action: bool, 92 | } 93 | 94 | struct FilePreambleState { 95 | /// Relative path of the file under diff 96 | file: String, 97 | /// Each line of file-level comment is stored as an entry 98 | comment: Vec, 99 | } 100 | 101 | #[derive(Clone)] 102 | struct FileDiffState { 103 | /// Relative path of the file under diff 104 | file: String, 105 | /// Current left line position. See `LineLocation` for docs on semantics of `line` 106 | left_line: u64, 107 | /// Current right line position. See `LineLocation` for docs on semantics of `line` 108 | right_line: u64, 109 | /// Current line position 110 | line: LineLocation, 111 | /// First line of the span. See `LineLocation` for docs on 112 | /// semantics of `line` 113 | span_start_line: Option, 114 | } 115 | 116 | struct SpanStartOrCommentState { 117 | /// State of the file diff before we entered this state 118 | file_diff_state: FileDiffState, 119 | } 120 | 121 | struct CommentState { 122 | /// State of the file diff before we entered comment processing 123 | file_diff_state: FileDiffState, 124 | /// Each line of comment is stored as an entry 125 | comment: Vec, 126 | } 127 | 128 | /// State machine states 129 | /// 130 | /// Only the following state transitions are valid: 131 | /// 132 | /// +---------------+ 133 | /// | | 134 | /// v | 135 | /// Start -> FilePreamble -> FileDiff -> StartSpanOrComment -> Comment 136 | /// ^ ^ | | ^ ^ | 137 | /// | | | | | | | 138 | /// | +--------+--+-+----------------------------+---+ 139 | /// | | | | 140 | /// +-------------+ +------------------------------+ 141 | /// 142 | enum State { 143 | /// Starting state 144 | Start(StartState), 145 | /// The `diff --git a/...` preamble as well as the lines before the first hunk 146 | FilePreamble(FilePreambleState), 147 | /// We are inside the diff of a file 148 | FileDiff(FileDiffState), 149 | /// We are either the start of a span or the beginning of a comment 150 | /// 151 | /// The uncertainty comes from the fact that comments typically begin with one 152 | /// or more newlines 153 | SpanStartOrComment(SpanStartOrCommentState), 154 | /// We are inside a user-supplied comment 155 | Comment(CommentState), 156 | } 157 | 158 | /// Simple state machine to parse a review file 159 | pub struct ReviewParser { 160 | state: State, 161 | } 162 | 163 | fn is_diff_header(s: &str) -> bool { 164 | s.starts_with("diff --git ") 165 | } 166 | 167 | /// Parses lines in the form of `@prr DIRECTIVE` 168 | /// 169 | /// Returns Some(directive) if found, else None 170 | fn is_prr_directive(s: &str) -> Option<&str> { 171 | let t = s.trim(); 172 | if let Some(d) = t.strip_prefix("@prr ") { 173 | Some(d) 174 | } else { 175 | None 176 | } 177 | } 178 | 179 | /// Parses the new filename out of a diff header 180 | fn parse_diff_header(line: &str) -> Result { 181 | if let Some(captures) = DIFF_START.captures(line) { 182 | let new: &str = captures.name("new").unwrap().as_str(); 183 | 184 | Ok(new.trim().to_owned()) 185 | } else { 186 | Err(anyhow!("Invalid diff header: could not parse")) 187 | } 188 | } 189 | 190 | /// Parses the starting left & right lines out of the hunk start 191 | fn parse_hunk_start(line: &str) -> Result> { 192 | if let Some(captures) = HUNK_START.captures(line) { 193 | let hunk_start_line_left: u64 = captures 194 | .name("lstart") 195 | .unwrap() 196 | .as_str() 197 | .parse() 198 | .context("Failed to parse hunk start left line")?; 199 | 200 | let hunk_start_line_right: u64 = captures 201 | .name("rstart") 202 | .map(|s| s.as_str()) 203 | .unwrap_or_else(|| { 204 | if hunk_start_line_left == 0 { 205 | "0" 206 | } else { 207 | unreachable!( 208 | "Unexpected non-zero left-hand-side of git diff header. Expected 0." 209 | ) 210 | } 211 | }) 212 | .parse() 213 | .context("Failed to parse hunk start right line")?; 214 | // Note that for newly added files or deleted files, both sides 215 | // of the line info might be zero. `saturating_*` operations must hence 216 | // be used for the following subtraction to be safe. 217 | 218 | return Ok(Some((hunk_start_line_left, hunk_start_line_right))); 219 | } 220 | 221 | Ok(None) 222 | } 223 | 224 | fn is_left_line(line: &str) -> bool { 225 | line.starts_with('-') 226 | } 227 | 228 | /// Given the current line and line positions, returns what the next line positions should be 229 | fn get_next_lines(line: &str, left: u64, right: u64) -> (u64, u64) { 230 | if is_left_line(line) { 231 | (left + 1, right) 232 | } else if line.starts_with('+') { 233 | (left, right + 1) 234 | } else { 235 | (left + 1, right + 1) 236 | } 237 | } 238 | 239 | impl ReviewParser { 240 | pub fn new() -> ReviewParser { 241 | ReviewParser { 242 | state: State::Start(StartState::default()), 243 | } 244 | } 245 | 246 | pub fn parse_line(&mut self, mut line: &str) -> Result> { 247 | let is_quoted = line.starts_with('>'); 248 | if is_quoted { 249 | if let Some(stripped) = line.strip_prefix("> ") { 250 | line = stripped; 251 | } else if let Some(stripped) = line.strip_prefix('>') { 252 | line = stripped; 253 | } 254 | } 255 | 256 | match &mut self.state { 257 | // we are adding all the lines, regardless if they are 258 | // quoted are not because they may be interleaving the 259 | // PR description as long as we haven't seen the prr 260 | // directive. Once the diff header starts, we determine 261 | // whether or not we should send the review comment. The 262 | // comment should only be sent, if we ever encountered a 263 | // non-quoted string in this state. 264 | State::Start(state) => { 265 | if is_quoted { 266 | if !is_diff_header(line) { 267 | if !state.had_review_action { 268 | state.comment.push("> ".to_owned() + line); 269 | } 270 | 271 | return Ok(None); 272 | } 273 | 274 | let mut review_comment = None; 275 | if state.had_unquoted_content { 276 | review_comment = 277 | Some(Comment::Review(state.comment.join("\n").trim().to_string())); 278 | } 279 | 280 | self.state = State::FilePreamble(FilePreambleState { 281 | file: parse_diff_header(line)?, 282 | comment: vec![], 283 | }); 284 | 285 | return Ok(review_comment); 286 | } else if let Some(d) = is_prr_directive(line) { 287 | state.had_review_action = true; 288 | 289 | return match d { 290 | "approve" => Ok(Some(Comment::ReviewAction(ReviewAction::Approve))), 291 | "reject" => Ok(Some(Comment::ReviewAction(ReviewAction::RequestChanges))), 292 | "comment" => Ok(Some(Comment::ReviewAction(ReviewAction::Comment))), 293 | _ => bail!("Unknown @prr directive: {}", d), 294 | }; 295 | } else { 296 | state.comment.push(line.to_owned()); 297 | if !state.had_unquoted_content { 298 | state.had_unquoted_content = true 299 | } 300 | } 301 | 302 | Ok(None) 303 | } 304 | State::FilePreamble(state) => { 305 | if !is_quoted { 306 | state.comment.push(line.to_owned()); 307 | } 308 | 309 | if is_diff_header(line) { 310 | self.state = State::FilePreamble(FilePreambleState { 311 | file: parse_diff_header(line)?, 312 | comment: vec![], 313 | }); 314 | return Ok(None); 315 | } 316 | 317 | if let Some((mut left_start, mut right_start)) = parse_hunk_start(line)? { 318 | // Subtract 1 b/c this line is before the actual diff hunk 319 | left_start = left_start.saturating_sub(1); 320 | right_start = right_start.saturating_sub(1); 321 | 322 | // Finish up our file-level comment if we had one 323 | let comment = if !state.comment.is_empty() { 324 | Some(Comment::File(FileComment { 325 | file: state.file.to_owned(), 326 | comment: state.comment.join("\n").trim().to_string(), 327 | })) 328 | } else { 329 | None 330 | }; 331 | 332 | self.state = State::FileDiff(FileDiffState { 333 | file: state.file.to_owned(), 334 | left_line: left_start, 335 | right_line: right_start, 336 | line: if is_left_line(line) { 337 | LineLocation::Left(left_start) 338 | } else { 339 | LineLocation::Right(right_start) 340 | }, 341 | span_start_line: None, 342 | }); 343 | 344 | if let Some(comment) = comment { 345 | return Ok(Some(comment)); 346 | } 347 | } 348 | 349 | Ok(None) 350 | } 351 | State::FileDiff(state) => { 352 | if is_quoted { 353 | if is_diff_header(line) { 354 | if state.span_start_line.is_some() { 355 | bail!( 356 | "Detected span that was not terminated with a comment, file: {}", 357 | state.file 358 | ); 359 | } 360 | 361 | self.state = State::FilePreamble(FilePreambleState { 362 | file: parse_diff_header(line)?, 363 | comment: vec![], 364 | }); 365 | } else if let Some((mut left_start, mut right_start)) = parse_hunk_start(line)? 366 | { 367 | if state.span_start_line.is_some() { 368 | bail!("Detected cross chunk span, file: {}", state.file); 369 | } 370 | 371 | // Subtract 1 b/c this line is before the actual diff hunk 372 | left_start = left_start.saturating_sub(1); 373 | right_start = right_start.saturating_sub(1); 374 | 375 | state.left_line = left_start; 376 | state.right_line = right_start; 377 | if is_left_line(line) { 378 | state.line = LineLocation::Left(left_start); 379 | } else { 380 | state.line = LineLocation::Right(right_start); 381 | } 382 | } else { 383 | let (next_left, next_right) = 384 | get_next_lines(line, state.left_line, state.right_line); 385 | state.left_line = next_left; 386 | state.right_line = next_right; 387 | if is_left_line(line) { 388 | state.line = LineLocation::Left(next_left); 389 | } else { 390 | state.line = LineLocation::Right(next_right); 391 | } 392 | } 393 | 394 | return Ok(None); 395 | } 396 | 397 | // Now that we know this line is not quoted, there's only two options: 398 | // 1) beginning of a spanned comment 399 | // 2) beginning of a comment 400 | if line.trim().is_empty() { 401 | self.state = State::SpanStartOrComment(SpanStartOrCommentState { 402 | file_diff_state: state.clone(), 403 | }) 404 | } else { 405 | self.state = State::Comment(CommentState { 406 | file_diff_state: state.clone(), 407 | comment: vec![line.to_owned()], 408 | }) 409 | } 410 | 411 | Ok(None) 412 | } 413 | State::SpanStartOrComment(state) => { 414 | if is_quoted { 415 | if state.file_diff_state.span_start_line.is_some() { 416 | bail!( 417 | "Detected span that was not terminated with a comment, file: {}", 418 | state.file_diff_state.file 419 | ); 420 | } 421 | 422 | // Back to the original file diff 423 | let (next_left, next_right) = get_next_lines( 424 | line, 425 | state.file_diff_state.left_line, 426 | state.file_diff_state.right_line, 427 | ); 428 | self.state = State::FileDiff(FileDiffState { 429 | file: state.file_diff_state.file.to_owned(), 430 | left_line: next_left, 431 | right_line: next_right, 432 | line: if is_left_line(line) { 433 | LineLocation::Left(next_left) 434 | } else { 435 | LineLocation::Right(next_right) 436 | }, 437 | span_start_line: Some(if is_left_line(line) { 438 | LineLocation::Left(next_left) 439 | } else { 440 | LineLocation::Right(next_right) 441 | }), 442 | }); 443 | 444 | Ok(None) 445 | } else if line.trim().is_empty() { 446 | // In a multi-line span spart 447 | Ok(None) 448 | } else { 449 | // In a comment now 450 | self.state = State::Comment(CommentState { 451 | file_diff_state: state.file_diff_state.clone(), 452 | comment: vec![line.to_owned()], 453 | }); 454 | 455 | Ok(None) 456 | } 457 | } 458 | State::Comment(state) => { 459 | if is_quoted { 460 | let comment = Comment::Inline(InlineComment { 461 | file: state.file_diff_state.file.clone(), 462 | line: state.file_diff_state.line.clone(), 463 | start_line: state.file_diff_state.span_start_line.clone(), 464 | comment: state.comment.join("\n").trim_end().to_string(), 465 | }); 466 | 467 | if is_diff_header(line) { 468 | self.state = State::FilePreamble(FilePreambleState { 469 | file: parse_diff_header(line)?, 470 | comment: vec![], 471 | }); 472 | } else { 473 | let (next_left, next_right) = get_next_lines( 474 | line, 475 | state.file_diff_state.left_line, 476 | state.file_diff_state.right_line, 477 | ); 478 | self.state = State::FileDiff(FileDiffState { 479 | file: state.file_diff_state.file.to_owned(), 480 | left_line: next_left, 481 | right_line: next_right, 482 | line: if is_left_line(line) { 483 | LineLocation::Left(next_left) 484 | } else { 485 | LineLocation::Right(next_right) 486 | }, 487 | span_start_line: None, 488 | }); 489 | } 490 | 491 | return Ok(Some(comment)); 492 | } 493 | 494 | state.comment.push(line.to_owned()); 495 | Ok(None) 496 | } 497 | } 498 | } 499 | 500 | pub fn finish(self) -> Option { 501 | match self.state { 502 | State::Comment(state) => Some(Comment::Inline(InlineComment { 503 | file: state.file_diff_state.file, 504 | line: state.file_diff_state.line, 505 | start_line: state.file_diff_state.span_start_line, 506 | comment: state.comment.join("\n").trim_end().to_string(), 507 | })), 508 | _ => None, 509 | } 510 | } 511 | } 512 | 513 | #[cfg(test)] 514 | mod tests { 515 | use super::*; 516 | 517 | fn test_fail(input: &str) { 518 | let mut parser = ReviewParser::new(); 519 | 520 | for line in input.lines() { 521 | if parser.parse_line(line).is_err() { 522 | return; 523 | } 524 | } 525 | 526 | panic!("Parser succeeded when it should have failed"); 527 | } 528 | 529 | fn test(input: &str, expected: &[Comment]) { 530 | let mut parser = ReviewParser::new(); 531 | let mut comments = Vec::new(); 532 | 533 | for line in input.lines() { 534 | if let Some(c) = parser.parse_line(line).unwrap() { 535 | comments.push(c); 536 | } 537 | } 538 | 539 | if let Some(c) = parser.finish() { 540 | comments.push(c); 541 | } 542 | 543 | assert!( 544 | comments == expected, 545 | "Parsed different comments than expected.\n Got: {:#?}\nExpected: {:#?}", 546 | comments, 547 | expected 548 | ); 549 | } 550 | 551 | #[test] 552 | fn single_comment() { 553 | let input = include_str!("../testdata/single_comment"); 554 | let expected = vec![Comment::Inline(InlineComment { 555 | file: "libbpf-cargo/src/btf/btf.rs".to_string(), 556 | line: LineLocation::Right(734), 557 | start_line: Some(LineLocation::Right(731)), 558 | comment: "Comment 1".to_string(), 559 | })]; 560 | 561 | test(input, &expected); 562 | } 563 | 564 | #[test] 565 | fn approve_review() { 566 | let input = include_str!("../testdata/approve_review"); 567 | let expected = vec![ 568 | Comment::ReviewAction(ReviewAction::Approve), 569 | Comment::Inline(InlineComment { 570 | file: "libbpf-cargo/src/btf/btf.rs".to_string(), 571 | line: LineLocation::Right(734), 572 | start_line: Some(LineLocation::Right(731)), 573 | comment: "Comment 1".to_string(), 574 | }), 575 | ]; 576 | 577 | test(input, &expected); 578 | } 579 | 580 | #[test] 581 | fn reject_review() { 582 | let input = include_str!("../testdata/reject_review"); 583 | let expected = vec![ 584 | Comment::ReviewAction(ReviewAction::RequestChanges), 585 | Comment::Inline(InlineComment { 586 | file: "libbpf-cargo/src/btf/btf.rs".to_string(), 587 | line: LineLocation::Right(734), 588 | start_line: Some(LineLocation::Right(731)), 589 | comment: "Comment 1".to_string(), 590 | }), 591 | ]; 592 | 593 | test(input, &expected); 594 | } 595 | 596 | #[test] 597 | fn review_comment() { 598 | let input = include_str!("../testdata/review_comment"); 599 | let expected = vec![ 600 | Comment::Review("Review comment".to_string()), 601 | Comment::Inline(InlineComment { 602 | file: "libbpf-cargo/src/btf/btf.rs".to_string(), 603 | line: LineLocation::Right(734), 604 | start_line: Some(LineLocation::Right(731)), 605 | comment: "Comment 1".to_string(), 606 | }), 607 | ]; 608 | 609 | test(input, &expected); 610 | } 611 | 612 | #[test] 613 | fn file_comment() { 614 | let input = include_str!("../testdata/file_comment"); 615 | let expected = vec![Comment::File(FileComment { 616 | file: "libbpf-cargo/src/btf/btf.rs".to_string(), 617 | comment: "This is a file-level comment!".to_string(), 618 | })]; 619 | 620 | test(input, &expected); 621 | } 622 | 623 | #[test] 624 | fn review_comment_whitespace() { 625 | let input = include_str!("../testdata/review_comment_whitespace"); 626 | let expected = vec![ 627 | Comment::ReviewAction(ReviewAction::Approve), 628 | Comment::Review("Review comment".to_string()), 629 | ]; 630 | 631 | test(input, &expected); 632 | } 633 | 634 | #[test] 635 | fn multiline_comment() { 636 | let input = include_str!("../testdata/multiline_comment"); 637 | let expected = vec![Comment::Inline(InlineComment { 638 | file: "libbpf-cargo/src/btf/btf.rs".to_string(), 639 | line: LineLocation::Right(736), 640 | start_line: None, 641 | comment: "Comment line 1\nComment line 2\n\nComment line 4".to_string(), 642 | })]; 643 | 644 | test(input, &expected); 645 | } 646 | 647 | #[test] 648 | fn back_to_back_span() { 649 | let input = include_str!("../testdata/back_to_back_span"); 650 | let expected = vec![ 651 | Comment::Inline(InlineComment { 652 | file: "libbpf-cargo/src/btf/btf.rs".to_string(), 653 | line: LineLocation::Right(734), 654 | start_line: Some(LineLocation::Right(731)), 655 | comment: "Comment 1".to_string(), 656 | }), 657 | Comment::Inline(InlineComment { 658 | file: "libbpf-cargo/src/btf/btf.rs".to_string(), 659 | line: LineLocation::Right(737), 660 | start_line: None, 661 | comment: "Comment 2".to_string(), 662 | }), 663 | ]; 664 | 665 | test(input, &expected); 666 | } 667 | 668 | #[test] 669 | fn multiple_files() { 670 | let input = include_str!("../testdata/multiple_files"); 671 | let expected = vec![ 672 | Comment::Inline(InlineComment { 673 | file: "libbpf-cargo/src/btf/btf.rs".to_string(), 674 | line: LineLocation::Right(734), 675 | start_line: None, 676 | comment: "Comment 1".to_string(), 677 | }), 678 | Comment::Inline(InlineComment { 679 | file: "libbpf-cargo/src/test.rs".to_string(), 680 | line: LineLocation::Right(2159), 681 | start_line: None, 682 | comment: "Comment 2".to_string(), 683 | }), 684 | ]; 685 | 686 | test(input, &expected); 687 | } 688 | 689 | #[test] 690 | fn hunk_start_no_trailing_whitespace() { 691 | let input = include_str!("../testdata/hunk_start_no_trailing_whitespace"); 692 | let expected = vec![Comment::Inline(InlineComment { 693 | file: "ch5.txt".to_string(), 694 | line: LineLocation::Right(7), 695 | start_line: None, 696 | comment: "Great passage".to_string(), 697 | })]; 698 | 699 | test(input, &expected); 700 | } 701 | 702 | #[test] 703 | fn add_oneliner() { 704 | let input = include_str!("../testdata/add_oneliner"); 705 | let expected = vec![ 706 | Comment::Inline(InlineComment { 707 | file: "foo.rs".to_string(), 708 | line: LineLocation::Right(0), 709 | start_line: None, 710 | comment: "Comment 1".to_string(), 711 | }), 712 | Comment::Inline(InlineComment { 713 | file: "foo.rs".to_string(), 714 | line: LineLocation::Right(1), 715 | start_line: None, 716 | comment: "Comment 2".to_string(), 717 | }), 718 | ]; 719 | 720 | test(input, &expected); 721 | } 722 | 723 | #[test] 724 | fn deleted_file() { 725 | let input = include_str!("../testdata/deleted_file"); 726 | let expected = vec![Comment::Inline(InlineComment { 727 | file: "ch1.txt".to_string(), 728 | line: LineLocation::Left(58), 729 | start_line: Some(LineLocation::Left(1)), 730 | comment: "Comment 1".to_string(), 731 | })]; 732 | 733 | test(input, &expected); 734 | } 735 | 736 | #[test] 737 | fn empty_file() { 738 | let input = include_str!("../testdata/empty_file"); 739 | let expected = vec![Comment::Inline(InlineComment { 740 | file: "libbpf-cargo/src/test.rs".to_string(), 741 | line: LineLocation::Right(2159), 742 | start_line: None, 743 | comment: "Comment".to_string(), 744 | })]; 745 | 746 | test(input, &expected); 747 | } 748 | 749 | #[test] 750 | fn trailing_comment() { 751 | let input = include_str!("../testdata/trailing_comment"); 752 | let expected = vec![Comment::Inline(InlineComment { 753 | file: "ch1.txt".to_string(), 754 | line: LineLocation::Left(59), 755 | start_line: Some(LineLocation::Left(1)), 756 | comment: "Comment 1".to_string(), 757 | })]; 758 | 759 | test(input, &expected); 760 | } 761 | 762 | #[test] 763 | /// https://github.com/danobi/prr/issues/3 764 | fn spaces_in_filename() { 765 | let input = include_str!("../testdata/spaces_in_filename"); 766 | let expected = vec![Comment::Inline(InlineComment { 767 | file: "build/scripts/grafana/provisioning/dashboards/Docker Prometheus Monitoring-1571332751387.json".to_string(), 768 | line: LineLocation::Right(2), 769 | start_line: None, 770 | comment: "foo".to_string(), 771 | })]; 772 | 773 | test(input, &expected); 774 | } 775 | 776 | #[test] 777 | fn unterminated_span() { 778 | let input = include_str!("../testdata/unterminated_span"); 779 | test_fail(input); 780 | } 781 | 782 | #[test] 783 | fn cross_file_span_ignored() { 784 | let input = include_str!("../testdata/cross_file_span_ignored"); 785 | test_fail(input); 786 | } 787 | 788 | #[test] 789 | fn unterminated_back_to_back_span() { 790 | let input = include_str!("../testdata/unterminated_back_to_back_span"); 791 | test_fail(input); 792 | } 793 | 794 | #[test] 795 | fn cross_hunk_span() { 796 | let input = include_str!("../testdata/cross_hunk_span"); 797 | test_fail(input); 798 | } 799 | 800 | #[test] 801 | fn unknown_directive() { 802 | let input = include_str!("../testdata/unknown_directive"); 803 | test_fail(input); 804 | } 805 | 806 | #[test] 807 | fn hunk_oneliner_regex() { 808 | let captures = HUNK_START 809 | .captures("@@ -0,0 +1 @@") 810 | .expect("Must match regex."); 811 | assert_eq!(captures.name("rstart").unwrap().as_str(), "1"); 812 | assert!(captures.name("rlen").is_none()); 813 | assert_eq!(captures.name("lstart").unwrap().as_str(), "0"); 814 | assert_eq!(captures.name("llen").unwrap().as_str(), "0"); 815 | } 816 | 817 | #[test] 818 | fn hunk_normal_regex() { 819 | let captures = HUNK_START 820 | .captures("@@ -0,7 +0,1 @@") 821 | .expect("Must match regex."); 822 | assert_eq!(captures.name("rstart").unwrap().as_str(), "0"); 823 | assert_eq!(captures.name("rlen").unwrap().as_str(), "1"); 824 | assert_eq!(captures.name("lstart").unwrap().as_str(), "0"); 825 | assert_eq!(captures.name("llen").unwrap().as_str(), "7"); 826 | } 827 | 828 | #[test] 829 | fn hunk_only_one_line_on_each_side() { 830 | let captures = HUNK_START 831 | .captures("@@ -5 +5 @@") 832 | .expect("Must match regex."); 833 | assert_eq!(captures.name("rstart").unwrap().as_str(), "5"); 834 | assert!(captures.name("rlen").is_none()); 835 | assert_eq!(captures.name("lstart").unwrap().as_str(), "5"); 836 | assert!(captures.name("llen").is_none()); 837 | } 838 | 839 | #[test] 840 | fn inline_and_review_comments_with_pr_description_present() { 841 | let input = include_str!("../testdata/inline_and_review_comments_with_pr_description"); 842 | let expected = vec![ 843 | Comment::ReviewAction(ReviewAction::RequestChanges), 844 | Comment::Review("Not necessary.".to_string()), 845 | Comment::Inline(InlineComment { 846 | file: "README.md".to_string(), 847 | line: LineLocation::Right(2), 848 | start_line: None, 849 | comment: "Doesn't seem necessary ...".to_string(), 850 | }), 851 | ]; 852 | 853 | test(input, &expected); 854 | } 855 | 856 | #[test] 857 | fn review_comments_interleaved_with_pr_description() { 858 | let input = include_str!("../testdata/review_comments_interleaved_with_pr_description"); 859 | let expected = vec![ 860 | Comment::ReviewAction(ReviewAction::RequestChanges), 861 | Comment::Review("Not necessary.\n\n\n> This is just for testing purposes.\n\nThis might be fine or not.".to_string()), 862 | Comment::Inline(InlineComment { 863 | file: "README.md".to_string(), 864 | line: LineLocation::Right(2), 865 | start_line: None, 866 | comment: "Doesn't seem necessary ...".to_string(), 867 | }), 868 | ]; 869 | 870 | test(input, &expected); 871 | } 872 | } 873 | -------------------------------------------------------------------------------- /src/prr.rs: -------------------------------------------------------------------------------- 1 | use std::env; 2 | use std::fs; 3 | use std::path::{Path, PathBuf}; 4 | 5 | use anyhow::{anyhow, bail, Context, Result}; 6 | use git2::{ApplyLocation, Diff, Repository, StatusOptions}; 7 | use http::{StatusCode, Uri}; 8 | use lazy_static::lazy_static; 9 | use octocrab::Octocrab; 10 | use prettytable::{format, row, Table}; 11 | use serde_derive::Deserialize; 12 | use serde_json::{json, Value}; 13 | 14 | use crate::parser::{FileComment, LineLocation, ReviewAction}; 15 | use crate::review::{get_all_existing, Review, ReviewStatus}; 16 | use regex::Regex; 17 | 18 | // Use lazy static to ensure regex is only compiled once 19 | lazy_static! { 20 | // Regex for short input. Example: 21 | // 22 | // danobi/prr-test-repo/6 23 | // 24 | static ref SHORT: Regex = Regex::new(r"^(?P[\w\-_\.]+)/(?P[\w\-_\.]+)/(?P\d+)").unwrap(); 25 | } 26 | 27 | const GITHUB_BASE_URL: &str = "https://api.github.com"; 28 | 29 | /// Resolves a GitHub token from either environment variables or config value. 30 | /// 31 | /// If a config token is provided and not empty, returns the config token as-is. 32 | /// If no config token is provided or it's empty, we check standard GitHub environment variables 33 | /// in order of precedence as per https://cli.github.com/manual/gh_help_environment: 34 | /// GH_TOKEN, GITHUB_TOKEN, GH_ENTERPRISE_TOKEN, GITHUB_ENTERPRISE_TOKEN. 35 | /// If none are found, returns an error. 36 | fn resolve_github_token(config_token: Option<&str>, env_lookup: F) -> Result 37 | where 38 | F: for<'a> Fn(&'a str) -> Result, 39 | { 40 | if let Some(token) = config_token { 41 | if !token.is_empty() { 42 | return Ok(token.to_string()); 43 | } 44 | } 45 | 46 | let known_env_vars = [ 47 | "GH_TOKEN", 48 | "GITHUB_TOKEN", 49 | "GH_ENTERPRISE_TOKEN", 50 | "GITHUB_ENTERPRISE_TOKEN", 51 | ]; 52 | 53 | for env_var in &known_env_vars { 54 | if let Ok(token) = env_lookup(env_var) { 55 | if token.is_empty() { 56 | bail!("Environment variable '{}' located but is empty", env_var); 57 | } 58 | return Ok(token); 59 | } 60 | } 61 | 62 | bail!("No GitHub token found in config or environment variables") 63 | } 64 | 65 | #[derive(Debug, Deserialize)] 66 | struct PrrConfig { 67 | /// GH personal token 68 | token: Option, 69 | /// Directory to place review files 70 | workdir: Option, 71 | /// Github URL 72 | /// 73 | /// Useful for enterprise instances with custom URLs 74 | url: Option, 75 | 76 | /// Activate experimental PR metadata support. Currently this option 77 | /// just activates downloading the actual PR description in addition 78 | /// to the diff. 79 | #[serde(default)] 80 | activate_pr_metadata_experiment: bool, 81 | } 82 | 83 | #[derive(Debug, Deserialize)] 84 | struct PrrLocalConfig { 85 | /// Default url for this current project 86 | repository: Option, 87 | /// Local workdir override 88 | workdir: Option, 89 | } 90 | 91 | #[derive(Debug, Deserialize)] 92 | struct Config { 93 | prr: PrrConfig, 94 | local: Option, 95 | } 96 | 97 | /// Main struct that coordinates all business logic and talks to GH 98 | pub struct Prr { 99 | /// User config 100 | config: Config, 101 | /// Path to local config file 102 | local_config: Option, 103 | /// Instantiated github client 104 | crab: Octocrab, 105 | } 106 | 107 | impl Config { 108 | /// Returns GH URL to use. Sanitizes if necessary. 109 | fn url(&self) -> String { 110 | match &self.prr.url { 111 | Some(url) => { 112 | // Custom URLs must have a trailing `/`. Otherwise the custom 113 | // path can be truncated. 114 | // 115 | // See: https://docs.rs/reqwest/0.11.22/reqwest/struct.Url.html#method.join 116 | let mut sanitized = url.clone(); 117 | if !url.ends_with('/') { 118 | sanitized.push('/'); 119 | } 120 | 121 | sanitized 122 | } 123 | None => GITHUB_BASE_URL.into(), 124 | } 125 | } 126 | } 127 | 128 | impl Prr { 129 | /// Create a new Prr object using the main config and/or the local config. 130 | /// If a local config has the `[prr]` section use this one instead of the main config. 131 | /// If `[prr]` section is not defined merge the local config with the main local. 132 | /// If local config file does not exist, use only the main config. 133 | /// 134 | /// A `[prr]` redefinition must be complete; if not, panics with a 135 | /// `redefinition of table `prr` for key `prr` at ...` 136 | pub fn new(config_path: &Path, local_config_path: Option) -> Result { 137 | let config_contents = fs::read_to_string(config_path).context("Failed to read config")?; 138 | let local_config_contents = if let Some(project_config_path) = &local_config_path { 139 | fs::read_to_string(project_config_path).context("Failed to read local config")? 140 | } else { 141 | String::new() 142 | }; 143 | 144 | let override_config = toml::from_str::(&local_config_contents); 145 | 146 | let config: Config = match override_config { 147 | // If `override_config` does not raise an error, use this one as config. 148 | Ok(config) => config, 149 | // Else merge the two config contents. 150 | Err(_) => { 151 | let contents = format!("{}\n{}", config_contents, local_config_contents); 152 | 153 | toml::from_str::(&contents)? 154 | } 155 | }; 156 | 157 | let token = resolve_github_token(config.prr.token.as_deref(), |var| env::var(var)) 158 | .context("Failed to locate GitHub token")?; 159 | 160 | let octocrab = Octocrab::builder() 161 | .personal_token(token) 162 | .base_uri(config.url()) 163 | .context("Failed to parse github base URL")? 164 | .build() 165 | .context("Failed to create GH client")?; 166 | 167 | Ok(Prr { 168 | config, 169 | local_config: local_config_path, 170 | crab: octocrab, 171 | }) 172 | } 173 | 174 | /// Returns path to prr workdir 175 | fn workdir(&self) -> Result { 176 | // Try local config first 177 | if let Some(lcfg) = &self.config.local { 178 | // Can't have a parsed local config without a stored path 179 | debug_assert!(self.local_config.is_some()); 180 | 181 | if let Some(wd) = &lcfg.workdir { 182 | if wd.starts_with('~') { 183 | bail!("Invalid workdir={wd}: may not use '~'"); 184 | } 185 | 186 | // We allow resolving relative paths in local config relative to the local config file 187 | let mut resolved_wd = PathBuf::new(); 188 | // No parent seems impossible but I think it's correct to not push anything 189 | if let Some(local_dir) = self.local_config.as_ref().unwrap().parent() { 190 | resolved_wd.push(local_dir); 191 | } 192 | // NB: pushing an absolute path overwrites the PathBuf 193 | resolved_wd.push(wd); 194 | 195 | return Ok(resolved_wd); 196 | } 197 | } 198 | 199 | // Now try global config 200 | if let Some(wd) = &self.config.prr.workdir { 201 | if wd.starts_with('~') { 202 | bail!("Invalid workdir={wd}: may not use '~'"); 203 | } 204 | 205 | let p = Path::new(wd).to_path_buf(); 206 | if !p.is_absolute() { 207 | bail!("Invalid workdir={wd}: must be absolute path"); 208 | } 209 | 210 | return Ok(p); 211 | } 212 | 213 | // Default workdir 214 | let xdg_dirs = xdg::BaseDirectories::with_prefix("prr")?; 215 | Ok(xdg_dirs.get_data_home()) 216 | } 217 | 218 | pub fn is_pr_metadata_experiment_active(&self) -> bool { 219 | self.config.prr.activate_pr_metadata_experiment 220 | } 221 | 222 | /// Parses a PR string in the form of `danobi/prr/24` and returns 223 | /// a tuple ("danobi", "prr", 24) or an error if string is malformed. 224 | pub fn parse_pr_str(&self, s: &str) -> Result<(String, String, u64)> { 225 | let repo = if let Some(local_config) = &self.config.local { 226 | if let Some(url) = &local_config.repository { 227 | if url.ends_with('/') { 228 | format!("{}{}", url, s) 229 | } else { 230 | format!("{}/{}", url, s) 231 | } 232 | } else { 233 | s.to_string() 234 | } 235 | } else { 236 | s.to_string() 237 | }; 238 | 239 | if let Some(captures) = SHORT.captures(&repo) { 240 | let owner = captures.name("org").unwrap().as_str().to_owned(); 241 | let repo = captures.name("repo").unwrap().as_str().to_owned(); 242 | let pr_nr: u64 = captures 243 | .name("pr_num") 244 | .unwrap() 245 | .as_str() 246 | .parse() 247 | .context("Failed to parse pr number")?; 248 | 249 | return Ok((owner, repo, pr_nr)); 250 | } 251 | 252 | if repo.starts_with("http") || repo.contains("://") { 253 | let uri: Uri = repo.parse().context("Failed to parse URL")?; 254 | 255 | let path = uri.path().trim_start_matches('/'); 256 | let segments: Vec<_> = path.split('/').collect(); 257 | 258 | if segments.len() >= 4 && segments[2] == "pull" { 259 | let pr_num = segments[3] 260 | .parse::() 261 | .context("Failed to parse PR number")?; 262 | 263 | return Ok((segments[0].to_string(), segments[1].to_string(), pr_num)); 264 | } 265 | } 266 | 267 | bail!("Invalid PR ref format") 268 | } 269 | 270 | /// Gets a new review from the internet and writes it to the filesystem 271 | pub async fn get_pr( 272 | &self, 273 | owner: &str, 274 | repo: &str, 275 | pr_num: u64, 276 | force: bool, 277 | ) -> Result { 278 | let pr_handler = self.crab.pulls(owner, repo); 279 | 280 | let diff = pr_handler 281 | .get_diff(pr_num) 282 | .await 283 | .context("Failed to fetch diff")?; 284 | 285 | let pr = pr_handler.get(pr_num).await.context("Failed to fetch pr")?; 286 | let commit_id = pr.head.sha; 287 | 288 | let mut pr_description = None; 289 | if self.is_pr_metadata_experiment_active() { 290 | pr_description = Some(pr.body.unwrap_or("".to_string())); 291 | } 292 | 293 | Review::new( 294 | &self.workdir()?, 295 | diff, 296 | owner, 297 | repo, 298 | pr_description, 299 | pr_num, 300 | commit_id, 301 | force, 302 | ) 303 | } 304 | 305 | /// Gets an existing review from the filesystem 306 | pub fn get_review(&self, owner: &str, repo: &str, pr_num: u64) -> Result { 307 | let workdir = self.workdir()?; 308 | Ok(Review::new_existing(&workdir, owner, repo, pr_num)) 309 | } 310 | 311 | pub async fn submit_pr(&self, owner: &str, repo: &str, pr_num: u64, debug: bool) -> Result<()> { 312 | let review = Review::new_existing(&self.workdir()?, owner, repo, pr_num); 313 | let (review_action, review_comment, inline_comments, file_comments) = review.comments()?; 314 | 315 | if review_comment.is_empty() 316 | && inline_comments.is_empty() 317 | && review_action != ReviewAction::Approve 318 | { 319 | bail!("No review comments"); 320 | } 321 | 322 | let mut body = json!({ 323 | "body": review_comment, 324 | "event": match review_action { 325 | ReviewAction::Approve => "APPROVE", 326 | ReviewAction::RequestChanges => "REQUEST_CHANGES", 327 | ReviewAction::Comment => "COMMENT" 328 | }, 329 | "comments": inline_comments 330 | .iter() 331 | .map(|c| { 332 | let (line, side) = match c.line { 333 | LineLocation::Left(line) => (line, "LEFT"), 334 | LineLocation::Right(line) => (line, "RIGHT"), 335 | }; 336 | 337 | let mut json_comment = json!({ 338 | "path": c.file, 339 | "line": line, 340 | "body": c.comment, 341 | "side": side, 342 | }); 343 | if let Some(start_line) = &c.start_line { 344 | let (line, side) = match start_line { 345 | LineLocation::Left(line) => (line, "LEFT"), 346 | LineLocation::Right(line) => (line, "RIGHT"), 347 | }; 348 | 349 | json_comment["start_line"] = (*line).into(); 350 | json_comment["start_side"] = side.into(); 351 | } 352 | 353 | json_comment 354 | }) 355 | .collect::>(), 356 | }); 357 | 358 | let commit = review.commit_id()?; 359 | if let Some(id) = &commit { 360 | if let serde_json::Value::Object(ref mut obj) = body { 361 | obj.insert("commit_id".to_string(), json!(id)); 362 | } 363 | } else if !file_comments.is_empty() { 364 | bail!( 365 | "Metadata contained no commit_id, but it's required to leave file-level comments" 366 | ); 367 | } 368 | 369 | if debug { 370 | println!("{}", serde_json::to_string_pretty(&body)?); 371 | } 372 | self.submit_review(&review, owner, repo, pr_num, &body) 373 | .await?; 374 | 375 | for fc in &file_comments { 376 | self.submit_file_comment(owner, repo, pr_num, commit.as_ref().unwrap(), fc) 377 | .await? 378 | } 379 | 380 | Ok(()) 381 | } 382 | 383 | async fn submit_review( 384 | &self, 385 | review: &Review, 386 | owner: &str, 387 | repo: &str, 388 | pr_num: u64, 389 | body: &Value, 390 | ) -> Result<()> { 391 | let path = format!("repos/{}/{}/pulls/{}/reviews", owner, repo, pr_num); 392 | let uri = Uri::builder() 393 | .path_and_query(path) 394 | .build() 395 | .context("Invalid URI")?; 396 | match self.crab._post(uri, Some(body)).await { 397 | Ok(resp) => { 398 | let status = resp.status(); 399 | if status != StatusCode::OK { 400 | let text = self 401 | .crab 402 | .body_to_string(resp) 403 | .await 404 | .context("Failed to decode failed response")?; 405 | bail!("Error during POST: Status code: {}, Body: {}", status, text); 406 | } 407 | 408 | review 409 | .mark_submitted() 410 | .context("Failed to update review metadata")?; 411 | 412 | Ok(()) 413 | } 414 | // GH is known to send unescaped control characters in JSON responses which 415 | // serde will fail to parse (not that it should succeed) 416 | Err(octocrab::Error::Json { 417 | source: _, 418 | backtrace: _, 419 | }) => { 420 | eprintln!("Warning: GH response had invalid JSON"); 421 | Ok(()) 422 | } 423 | Err(e) => bail!("Error during POST: {}", e), 424 | } 425 | } 426 | 427 | async fn submit_file_comment( 428 | &self, 429 | owner: &str, 430 | repo: &str, 431 | pr_num: u64, 432 | commit_id: &str, 433 | fc: &FileComment, 434 | ) -> Result<()> { 435 | let body = json!({ 436 | "body": fc.comment, 437 | "commit_id": commit_id, 438 | "path": fc.file, 439 | "subject_type": "file", 440 | }); 441 | let path = format!("repos/{}/{}/pulls/{}/comments", owner, repo, pr_num); 442 | let uri = Uri::builder() 443 | .path_and_query(path) 444 | .build() 445 | .context("Invalid URI")?; 446 | match self.crab._post(uri, Some(&body)).await { 447 | Ok(resp) => { 448 | let status = resp.status(); 449 | if status != StatusCode::CREATED { 450 | let text = self 451 | .crab 452 | .body_to_string(resp) 453 | .await 454 | .context("Failed to decode failed response")?; 455 | bail!("Error during POST: Status code: {}, Body: {}", status, text); 456 | } 457 | Ok(()) 458 | } 459 | // GH is known to send unescaped control characters in JSON responses which 460 | // serde will fail to parse (not that it should succeed) 461 | Err(octocrab::Error::Json { 462 | source: _, 463 | backtrace: _, 464 | }) => { 465 | eprintln!("Warning: GH response had invalid JSON"); 466 | Ok(()) 467 | } 468 | Err(e) => bail!("Error during POST: {}", e), 469 | } 470 | } 471 | 472 | pub fn apply_pr(&self, owner: &str, repo: &str, pr_num: u64, apply_repo: &Path) -> Result<()> { 473 | let review = Review::new_existing(&self.workdir()?, owner, repo, pr_num); 474 | let diff = Diff::from_buffer(review.diff()?.as_bytes()).context("Failed to load diff")?; 475 | let apply_repo_path = Path::new(apply_repo); 476 | let apply_repo = 477 | Repository::open(apply_repo_path).context("Failed to open git repository")?; 478 | 479 | // Best effort check to prevent clobbering any work in progress 480 | let mut opts = StatusOptions::new(); 481 | opts.include_ignored(false); 482 | let statuses = apply_repo 483 | .statuses(Some(&mut opts)) 484 | .context("Failed to get repo status")?; 485 | if !statuses.is_empty() { 486 | bail!("Working directory is dirty"); 487 | } 488 | 489 | apply_repo 490 | .apply(&diff, ApplyLocation::WorkDir, None) 491 | .context("Failed to apply diff") 492 | } 493 | 494 | pub fn print_status(&self, no_titles: bool) -> Result<()> { 495 | let mut table = Table::new(); 496 | let mut table_fmt = *format::consts::FORMAT_CLEAN; 497 | // Get rid of leading padding on each line 498 | table_fmt.padding(0, 2); 499 | table.set_format(table_fmt); 500 | if !no_titles { 501 | table.set_titles(row!["Handle", "Status", "Review file"]) 502 | } 503 | 504 | let reviews = get_all_existing(&self.workdir()?).context("Failed to get all reviews")?; 505 | for review in reviews { 506 | table.add_row(row![ 507 | review.handle(), 508 | review.status()?, 509 | review.path().display() 510 | ]); 511 | } 512 | 513 | table.printstd(); 514 | 515 | Ok(()) 516 | } 517 | 518 | /// Removes reviews from the filesystem 519 | pub async fn remove(&self, prs: &[String], force: bool, submitted: bool) -> Result<()> { 520 | for pr in prs { 521 | let (owner, repo, pr_num) = self.parse_pr_str(pr)?; 522 | let review = self.get_review(&owner, &repo, pr_num)?; 523 | review 524 | .remove(force) 525 | .with_context(|| anyhow!("Failed to remove {}", pr))?; 526 | } 527 | 528 | if !submitted { 529 | return Ok(()); 530 | } 531 | 532 | let reviews = get_all_existing(&self.workdir()?).context("Failed to all reviews")?; 533 | for review in reviews { 534 | if review.status()? == ReviewStatus::Submitted { 535 | let handle = review.handle(); 536 | review 537 | .remove(force) 538 | .with_context(|| anyhow!("Failed to remove {}", handle))?; 539 | } 540 | } 541 | 542 | Ok(()) 543 | } 544 | } 545 | 546 | #[cfg(test)] 547 | mod tests { 548 | use super::*; 549 | use std::fs::File; 550 | use std::io::Write; 551 | use tempfile::TempDir; 552 | 553 | // Lays down configs in a tempdir 554 | // 555 | // NB: Configs get deleted if returned `TempDir` is dropped 556 | fn config(global: &str, local: Option<&str>) -> (Prr, TempDir) { 557 | let dir = TempDir::new().unwrap(); 558 | let gpath = dir.path().join("config.toml"); 559 | let mut gfile = File::create(&gpath).unwrap(); 560 | write!(&mut gfile, "{}", global).unwrap(); 561 | 562 | let lpath = if let Some(lcontents) = local { 563 | let lpath = dir.path().join("local_config.toml"); 564 | let mut lfile = File::create(&lpath).unwrap(); 565 | write!(&mut lfile, "{}", lcontents).unwrap(); 566 | Some(lpath) 567 | } else { 568 | None 569 | }; 570 | 571 | let prr = Prr::new(&gpath, lpath).unwrap(); 572 | (prr, dir) 573 | } 574 | 575 | lazy_static! { 576 | // Basic dummy config just to avoid errors 577 | static ref PRR: (Prr, TempDir) = { 578 | let gconfig = r#" 579 | [prr] 580 | token = "test" 581 | workdir = "/tmp" 582 | "#; 583 | 584 | config(gconfig, None) 585 | }; 586 | } 587 | 588 | #[tokio::test] 589 | async fn test_parse_basic_pr_str() { 590 | let pr_ref = "example/prr/42"; 591 | assert_eq!( 592 | PRR.0.parse_pr_str(pr_ref).unwrap(), 593 | ("example".to_string(), "prr".to_string(), 42) 594 | ) 595 | } 596 | 597 | #[tokio::test] 598 | async fn test_parse_dotted_pr_str() { 599 | let pr_ref = "example/prr.test/42"; 600 | assert_eq!( 601 | PRR.0.parse_pr_str(pr_ref).unwrap(), 602 | ("example".to_string(), "prr.test".to_string(), 42) 603 | ) 604 | } 605 | 606 | #[tokio::test] 607 | async fn test_parse_underscored_pr_str() { 608 | let pr_ref = "example/prr_test/42"; 609 | assert_eq!( 610 | PRR.0.parse_pr_str(pr_ref).unwrap(), 611 | ("example".to_string(), "prr_test".to_string(), 42) 612 | ) 613 | } 614 | 615 | #[tokio::test] 616 | async fn test_parse_dashed_pr_str() { 617 | let pr_ref = "example/prr-test/42"; 618 | assert_eq!( 619 | PRR.0.parse_pr_str(pr_ref).unwrap(), 620 | ("example".to_string(), "prr-test".to_string(), 42) 621 | ) 622 | } 623 | 624 | #[tokio::test] 625 | async fn test_parse_numbered_pr_str() { 626 | let pr_ref = "example/prr1/42"; 627 | assert_eq!( 628 | PRR.0.parse_pr_str(pr_ref).unwrap(), 629 | ("example".to_string(), "prr1".to_string(), 42) 630 | ) 631 | } 632 | 633 | #[tokio::test] 634 | async fn test_parse_mixed_pr_str() { 635 | let pr_ref = "example/prr1.test_test-/42"; 636 | assert_eq!( 637 | PRR.0.parse_pr_str(pr_ref).unwrap(), 638 | ("example".to_string(), "prr1.test_test-".to_string(), 42) 639 | ) 640 | } 641 | 642 | #[tokio::test] 643 | async fn test_parse_github_url() { 644 | let pr_ref = "https://github.com/example/repo/pull/42"; 645 | assert_eq!( 646 | PRR.0.parse_pr_str(pr_ref).unwrap(), 647 | ("example".to_string(), "repo".to_string(), 42) 648 | ) 649 | } 650 | 651 | #[tokio::test] 652 | async fn test_parse_github_url_with_extra_path() { 653 | let pr_ref = "https://github.com/example/repo/pull/42/files"; 654 | assert_eq!( 655 | PRR.0.parse_pr_str(pr_ref).unwrap(), 656 | ("example".to_string(), "repo".to_string(), 42) 657 | ) 658 | } 659 | 660 | #[tokio::test] 661 | async fn test_parse_github_url_with_complex_path() { 662 | let pr_ref = "https://github.com/example/repo/pull/42/files/abc123..def456"; 663 | assert_eq!( 664 | PRR.0.parse_pr_str(pr_ref).unwrap(), 665 | ("example".to_string(), "repo".to_string(), 42) 666 | ) 667 | } 668 | 669 | #[tokio::test] 670 | async fn test_parse_custom_github_host() { 671 | let pr_ref = "https://github.acme.com/example/repo/pull/42"; 672 | assert_eq!( 673 | PRR.0.parse_pr_str(pr_ref).unwrap(), 674 | ("example".to_string(), "repo".to_string(), 42) 675 | ) 676 | } 677 | 678 | #[tokio::test] 679 | async fn test_local_config_repository() { 680 | let gconfig = r#" 681 | [prr] 682 | token = "test" 683 | "#; 684 | let lconfig = r#" 685 | [local] 686 | repository = "testorg/testrepo" 687 | "#; 688 | 689 | let (prr, _dir) = config(gconfig, Some(lconfig)); 690 | assert_eq!( 691 | prr.parse_pr_str("42").unwrap(), 692 | ("testorg".to_string(), "testrepo".to_string(), 42) 693 | ) 694 | } 695 | 696 | #[tokio::test] 697 | async fn test_global_workdir() { 698 | let gconfig = r#" 699 | [prr] 700 | token = "test" 701 | workdir = "/globalworkdir" 702 | "#; 703 | 704 | let (prr, _dir) = config(gconfig, None); 705 | assert_eq!(prr.workdir().unwrap(), Path::new("/globalworkdir")) 706 | } 707 | 708 | #[tokio::test] 709 | async fn test_local_workdir() { 710 | let gconfig = r#" 711 | [prr] 712 | token = "test" 713 | "#; 714 | let lconfig = r#" 715 | [local] 716 | workdir = "/localworkdir" 717 | "#; 718 | 719 | let (prr, _dir) = config(gconfig, Some(lconfig)); 720 | assert_eq!(prr.workdir().unwrap(), Path::new("/localworkdir")) 721 | } 722 | 723 | #[tokio::test] 724 | async fn test_local_workdir_relative() { 725 | let gconfig = r#" 726 | [prr] 727 | token = "test" 728 | "#; 729 | let lconfig = r#" 730 | [local] 731 | workdir = "localrelativeworkdir" 732 | "#; 733 | 734 | let (prr, dir) = config(gconfig, Some(lconfig)); 735 | assert_eq!( 736 | prr.workdir().unwrap(), 737 | dir.path().join("localrelativeworkdir") 738 | ) 739 | } 740 | 741 | #[tokio::test] 742 | async fn test_local_workdir_override() { 743 | let gconfig = r#" 744 | [prr] 745 | token = "test" 746 | workdir = "/globalworkdir" 747 | "#; 748 | let lconfig = r#" 749 | [local] 750 | workdir = "/localworkdir" 751 | "#; 752 | 753 | let (prr, _dir) = config(gconfig, Some(lconfig)); 754 | assert_eq!(prr.workdir().unwrap(), Path::new("/localworkdir")) 755 | } 756 | 757 | #[tokio::test] 758 | async fn test_invalid_relative_workdir() { 759 | let gconfig = r#" 760 | [prr] 761 | token = "test" 762 | workdir = "relativeworkdir" 763 | "#; 764 | 765 | let (prr, _dir) = config(gconfig, None); 766 | assert!(prr.workdir().is_err()); 767 | } 768 | 769 | fn copy_dir_all(src: impl AsRef, dst: impl AsRef) { 770 | fs::create_dir_all(&dst).expect("could not create_dir_all"); 771 | for entry in fs::read_dir(src).expect("could not read_dir") { 772 | let entry = entry.expect("entry is not valid"); 773 | let ty = entry.file_type().expect("cannot get filetype"); 774 | if ty.is_dir() { 775 | copy_dir_all(entry.path(), dst.as_ref().join(entry.file_name())); 776 | } else { 777 | fs::copy(entry.path(), dst.as_ref().join(entry.file_name())) 778 | .expect("copy in copy_dir_all failed"); 779 | } 780 | } 781 | } 782 | 783 | #[test] 784 | fn test_resolve_github_token_with_no_config_token_fallback_to_env() { 785 | let env_lookup = |var: &str| -> Result { 786 | match var { 787 | "GITHUB_TOKEN" => Ok("fallback_env_token".to_string()), 788 | _ => Err(std::env::VarError::NotPresent), 789 | } 790 | }; 791 | 792 | let result = resolve_github_token(None, env_lookup).unwrap(); 793 | assert_eq!(result, "fallback_env_token"); 794 | } 795 | 796 | #[test] 797 | fn test_resolve_github_token_with_no_config_token_no_env_error() { 798 | let env_lookup = |_var: &str| -> Result { 799 | Err(std::env::VarError::NotPresent) 800 | }; 801 | 802 | let result = resolve_github_token(None, env_lookup); 803 | assert!(result.is_err()); 804 | let error_msg = result.err().unwrap().to_string(); 805 | assert!(error_msg.contains("No GitHub token found in config or environment variables")); 806 | } 807 | 808 | #[test] 809 | fn test_resolve_github_token_config_token_preferred_over_env() { 810 | let env_lookup = |var: &str| -> Result { 811 | match var { 812 | "GITHUB_TOKEN" => Ok("env_token".to_string()), 813 | _ => Err(std::env::VarError::NotPresent), 814 | } 815 | }; 816 | 817 | let result = resolve_github_token(Some("config_token"), env_lookup).unwrap(); 818 | assert_eq!(result, "config_token"); 819 | } 820 | 821 | #[test] 822 | fn test_resolve_github_token_empty_config_token_falls_back_to_env() { 823 | let env_lookup = |var: &str| -> Result { 824 | match var { 825 | "GITHUB_TOKEN" => Ok("env_token".to_string()), 826 | _ => Err(std::env::VarError::NotPresent), 827 | } 828 | }; 829 | 830 | let result = resolve_github_token(Some(""), env_lookup).unwrap(); 831 | assert_eq!(result, "env_token"); 832 | } 833 | 834 | #[test] 835 | fn test_resolve_github_token_env_var_precedence() { 836 | let env_lookup = |var: &str| -> Result { 837 | match var { 838 | "GH_TOKEN" => Ok("gh_token".to_string()), 839 | "GITHUB_TOKEN" => Ok("github_token".to_string()), 840 | _ => Err(std::env::VarError::NotPresent), 841 | } 842 | }; 843 | 844 | let result = resolve_github_token(None, env_lookup).unwrap(); 845 | // GH_TOKEN should have higher precedence 846 | assert_eq!(result, "gh_token"); 847 | } 848 | 849 | #[test] 850 | fn test_resolve_github_token_empty_env_var_error() { 851 | let env_lookup = |var: &str| -> Result { 852 | match var { 853 | // Empty token 854 | "GITHUB_TOKEN" => Ok("".to_string()), 855 | _ => Err(std::env::VarError::NotPresent), 856 | } 857 | }; 858 | 859 | let result = resolve_github_token(None, env_lookup); 860 | assert!(result.is_err()); 861 | let error_msg = result.err().unwrap().to_string(); 862 | assert!(error_msg.contains("Environment variable 'GITHUB_TOKEN' located but is empty")); 863 | } 864 | 865 | #[tokio::test] 866 | async fn test_apply_pr() { 867 | let gconfig = r#" 868 | [prr] 869 | token = "doesn'tmatter" 870 | workdir = "doesn'tmatter" 871 | "#; 872 | let lconfig = r#" 873 | [local] 874 | workdir = "testdata/" 875 | "#; 876 | 877 | let (prr, dir) = config(gconfig, Some(lconfig)); 878 | let test_review_path = 879 | dir.path().to_str().expect("tmp path invalid").to_string() + "/testdata/apply_pr"; 880 | fs::create_dir_all(&test_review_path).expect("failed to create temp directory"); 881 | copy_dir_all("testdata/review/apply_pr", &test_review_path); 882 | 883 | let test_repo_path = dir.path().to_str().unwrap().to_string() + "/testgitrepo/"; 884 | fs::create_dir_all(&test_repo_path).expect("couldn't create testgitrepo"); 885 | let test_repo = git2::Repository::init(&test_repo_path).expect("couldn't init testgitrepo"); 886 | 887 | std::fs::copy( 888 | "testdata/testgitrepo/README.md", 889 | test_repo_path.clone() + "README.md", 890 | ) 891 | .expect("copy README.md failed"); 892 | 893 | let mut index = test_repo.index().expect("couldn't get repo index"); 894 | index 895 | .add_path(Path::new("README.md")) 896 | .expect("couldn't add path"); 897 | 898 | let new_tree_oid = index.write_tree().expect("couldn't write tree"); 899 | index.write().expect("couldn't write index"); 900 | 901 | let signature = git2::Signature::now("someone", "someone@somewhere.com") 902 | .expect("failed to create signature"); 903 | let new_tree = test_repo.find_tree(new_tree_oid).unwrap(); 904 | test_repo 905 | .commit( 906 | Some("HEAD"), 907 | &signature, 908 | &signature, 909 | "Initial commit", 910 | &new_tree, 911 | &[], 912 | ) 913 | .expect("failed to commit"); 914 | 915 | // add non-tracked file for testing purposes 916 | std::fs::copy( 917 | "testdata/testgitrepo/README.md", 918 | test_repo_path.clone() + "README-not-tracked.md", 919 | ) 920 | .expect("copy README-not-tracked.md failed"); 921 | 922 | prr.apply_pr("apply_pr", "review", 1, Path::new(&test_repo_path)) 923 | .expect("apply_pr failed"); 924 | 925 | let got_after_apply = fs::read(test_repo_path.clone() + "README.md") 926 | .expect("failed to read README.md with diff applied"); 927 | let want_after_apply = fs::read("testdata/testgitrepo/README-applied.md") 928 | .expect("failed to read README-applied.md"); 929 | assert_eq!(got_after_apply, want_after_apply); 930 | } 931 | } 932 | --------------------------------------------------------------------------------