Giter VIP home page Giter VIP logo

github-commenter's Introduction

github-commenter Build Status Docker Status Latest Release Slack Community

README Header

Cloud Posse

Command line utility for creating GitHub comments on Commits, Pull Request Reviews, Pull Request Files, Issues and Pull Requests.

GitHub API supports these types of comments:

Since GitHub considers Pull Requests as Issues, Comments on Issues and Comments on Pull Requests use the same API.

The utility supports all these types of comments (commit, pr-review, pr-file, issue, pr).


This project is part of our comprehensive "SweetOps" approach towards DevOps.

It's 100% Open Source and licensed under the APACHE2.

Screenshots

PR GitHub PR Review Comment

Usage

NOTE: Create a GitHub token with repo:status and public_repo scopes.

NOTE: The utility accepts parameters as command-line arguments or as ENV variables (or any combination of command-line arguments and ENV vars). Command-line arguments take precedence over ENV vars.

Command-line argument ENV var Description
token GITHUB_TOKEN Github access token
owner GITHUB_OWNER Github repository owner (e.g. cloudposse)
repo GITHUB_REPO Github repository name (e.g. github-commenter)
type GITHUB_COMMENT_TYPE Comment type: commit, pr, issue, pr-review or pr-file
sha GITHUB_COMMIT_SHA Commit SHA. Required when type=commit or type=pr-file
number GITHUB_PR_ISSUE_NUMBER Pull Request or Issue number. Required for all comment types except for commit
file GITHUB_PR_FILE Pull Request File Name to comment on. For more info see create comment
position GITHUB_PR_FILE_POSITION Position in Pull Request File. For more info see create comment
template GITHUB_COMMENT_TEMPLATE Template to format comment (optional). Supports Go templates. E.g. My comment:<br/>{{.}}. Use either template or template_file
template_file GITHUB_COMMENT_TEMPLATE_FILE The path to a template file to format comment (optional). Supports Go templates. Use either template or template_file
format GITHUB_COMMENT_FORMAT Alias of template
format_file GITHUB_COMMENT_FORMAT_FILE Alias of template_file
comment GITHUB_COMMENT Comment text. If neither comment nor GITHUB_COMMENT provided, will read from stdin
delete-comment-regex GITHUB_DELETE_COMMENT_REGEX Regex to find previous comments to delete before creating the new comment. Supported for comment types commit, pr-file, issue and pr
edit-comment-regex GITHUB_EDIT_COMMENT_REGEX Regex to find previous comments to replace with new content, or create new comment if none found. Supported for comment types commit, pr-file, issue and pr
baseURL GITHUB_BASE_URL Github Enterprise URL. E.g. https://github.example.com/api/v3
uploadURL GITHUB_UPLOAD_URL Github Enterprise Upload URL to pass to the Github client
insecure GITHUB_INSECURE Boolean to ignore SSL certificate check

NOTE: The utility accepts the text of the comment from the command-line argument comment, from the ENV variable GITHUB_COMMENT, or from the standard input. Command-line argument takes precedence over ENV var, and ENV var takes precedence over standard input. Accepting comments from stdin allows using Unix pipes to send the output from another program as the input to the tool:

    cat comment.txt | github-commenter ...
    terraform plan 2>&1 | github-commenter -format "Output from `terraform plan`<br/>```{{.}}```"

NOTE: The utility supports sprig functions in Go templates, allowing to use string replacement and Regular Expressions in the format argument.

See string functions for more details.

For example:

GITHUB_COMMENT_FORMAT="Helm diff:<br><br><pre>{{regexReplaceAllLiteral `\\n` . `<br>` }}<pre>"

Examples

The utility can be called directly or as a Docker container.

Build the Go program locally

go get

CGO_ENABLED=0 go build -v -o "./dist/bin/github-commenter" *.go

Run locally with ENV vars

run_locally_with_env_vars.sh

export GITHUB_TOKEN=XXXXXXXXXXXXXXXX
export GITHUB_OWNER=cloudposse
export GITHUB_REPO=github-commenter
export GITHUB_COMMENT_TYPE=pr
export GITHUB_PR_ISSUE_NUMBER=1
export GITHUB_COMMENT_FORMAT="My comment:<br/>{{.}}"
export GITHUB_COMMENT="+1 LGTM"

./dist/bin/github-commenter

Run locally with command-line arguments

run_locally_with_command_line_args.sh

./dist/bin/github-commenter \
        -token XXXXXXXXXXXXXXXX \
        -owner cloudposse \
        -repo github-commenter \
        -type pr \
        -number 1 \
        -format "My comment:<br/>{{.}}" \
        -comment "+1 LGTM"

Build the Docker image

NOTE: it will download all Go dependencies and then build the program inside the container (see Dockerfile)

docker build --tag github-commenter  --no-cache=true .

Run in a Docker container with ENV vars

run_docker_with_env_vars.sh

docker run -i --rm \
        -e GITHUB_TOKEN=XXXXXXXXXXXXXXXX \
        -e GITHUB_OWNER=cloudposse \
        -e GITHUB_REPO=github-commenter \
        -e GITHUB_COMMENT_TYPE=pr \
        -e GITHUB_PR_ISSUE_NUMBER=1 \
        -e GITHUB_COMMENT_FORMAT="My comment:<br/>{{.}}" \
        -e GITHUB_COMMENT="+1 LGTM" \
        github-commenter

Run with Docker

Run github-commenter in a Docker container with local ENV vars propagated into the container's environment. run_docker_with_local_env_vars.sh

export GITHUB_TOKEN=XXXXXXXXXXXXXXXX
export GITHUB_OWNER=cloudposse
export GITHUB_REPO=github-commenter
export GITHUB_COMMENT_TYPE=pr
export GITHUB_PR_ISSUE_NUMBER=1
export GITHUB_COMMENT_FORMAT="Helm diff:<br><br><pre>{{regexReplaceAllLiteral `\\n` . `<br>` }}<pre>"
export GITHUB_COMMENT="Helm diff comment"

docker run -i --rm \
        -e GITHUB_TOKEN \
        -e GITHUB_OWNER \
        -e GITHUB_REPO \
        -e GITHUB_COMMENT_TYPE \
        -e GITHUB_PR_ISSUE_NUMBER \
        -e GITHUB_COMMENT_FORMAT \
        -e GITHUB_COMMENT \
        github-commenter

Run with Docker using Env File

Run the github-commenter in a Docker container with ENV vars declared in a file. run_docker_with_env_vars_file.sh

docker run -i --rm --env-file ./example.env github-commenter

delete-comment-regex example 1

Delete all previous comments on Pull Request #2 that contain the string test1 in the body of the comments and create a new PR comment

./dist/bin/github-commenter \
        -token XXXXXXXXXXXXXXXX \
        -owner cloudposse \
        -repo github-commenter \
        -type pr \
        -number 2 \
        -format "{{.}}" \
        -delete-comment-regex "test1" \
        -comment "New Pull Request comment"

delete-comment-regex example 2

Delete all previous comments on Issue #1 that contain the string test2 at the end of the comment's body and create a new Issue comment

./dist/bin/github-commenter \
        -token XXXXXXXXXXXXXXXX \
        -owner cloudposse \
        -repo github-commenter \
        -type issue \
        -number 1 \
        -format "{{.}}" \
        -delete-comment-regex "test2$" \
        -comment "New Issue comment"

delete-comment-regex example 3

Delete all previous commit comments that contain the string test3 in the body and create a new commit comment

./dist/bin/github-commenter \
        -token XXXXXXXXXXXXXXXX \
        -owner cloudposse \
        -repo github-commenter \
        -type commit \
        -sha xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx \
        -format "{{.}}" \
        -delete-comment-regex "test3" \
        -comment "New commit comment"

delete-comment-regex example 4

Delete all previous comments on a Pull Request file doc.txt that contain the string test4 in the body of the comments and create a new comment on the file

./dist/bin/github-commenter \
        -token XXXXXXXXXXXXXXXX \
        -owner cloudposse \
        -repo github-commenter \
        -type pr-file \
        -sha xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx \
        -number 2 \
        -file doc.txt \
        -position 1 \
        -format "{{.}}" \
        -delete-comment-regex "test4" \
        -comment "New comment on the PR file"

edit-comment-regex

The -edit-comment-regex flag operates similarly to the -delete-comment-regex except existing comments will be updated instead of deleted. If no matching comment is found a new comment is created.

Share the Love

Like this project? Please give it a ★ on our GitHub! (it helps us a lot)

Are you using this project or any of our other projects? Consider leaving a testimonial. =)

Related Projects

Check out these related projects.

  • github-status-updater - Command line utility for updating GitHub commit statuses and enabling required status checks for pull requests
  • slack-notifier - Command line utility to send messages with attachments to Slack channels via Incoming Webhooks

Help

Got a question? We got answers.

File a GitHub issue, send us an email or join our Slack Community.

README Commercial Support

DevOps Accelerator for Startups

We are a DevOps Accelerator. We'll help you build your cloud infrastructure from the ground up so you can own it. Then we'll show you how to operate it and stick around for as long as you need us.

Learn More

Work directly with our team of DevOps experts via email, slack, and video conferencing.

We deliver 10x the value for a fraction of the cost of a full-time engineer. Our track record is not even funny. If you want things done right and you need it done FAST, then we're your best bet.

  • Reference Architecture. You'll get everything you need from the ground up built using 100% infrastructure as code.
  • Release Engineering. You'll have end-to-end CI/CD with unlimited staging environments.
  • Site Reliability Engineering. You'll have total visibility into your apps and microservices.
  • Security Baseline. You'll have built-in governance with accountability and audit logs for all changes.
  • GitOps. You'll be able to operate your infrastructure via Pull Requests.
  • Training. You'll receive hands-on training so your team can operate what we build.
  • Questions. You'll have a direct line of communication between our teams via a Shared Slack channel.
  • Troubleshooting. You'll get help to triage when things aren't working.
  • Code Reviews. You'll receive constructive feedback on Pull Requests.
  • Bug Fixes. We'll rapidly work with you to fix any bugs in our projects.

Slack Community

Join our Open Source Community on Slack. It's FREE for everyone! Our "SweetOps" community is where you get to talk with others who share a similar vision for how to rollout and manage infrastructure. This is the best place to talk shop, ask questions, solicit feedback, and work together as a community to build totally sweet infrastructure.

Discourse Forums

Participate in our Discourse Forums. Here you'll find answers to commonly asked questions. Most questions will be related to the enormous number of projects we support on our GitHub. Come here to collaborate on answers, find solutions, and get ideas about the products and services we value. It only takes a minute to get started! Just sign in with SSO using your GitHub account.

Newsletter

Sign up for our newsletter that covers everything on our technology radar. Receive updates on what we're up to on GitHub as well as awesome new projects we discover.

Office Hours

Join us every Wednesday via Zoom for our weekly "Lunch & Learn" sessions. It's FREE for everyone!

zoom

Contributing

Bug Reports & Feature Requests

Please use the issue tracker to report any bugs or file feature requests.

Developing

If you are interested in being a contributor and want to get involved in developing this project or help out with our other projects, we would love to hear from you! Shoot us an email.

In general, PRs are welcome. We follow the typical "fork-and-pull" Git workflow.

  1. Fork the repo on GitHub
  2. Clone the project to your own machine
  3. Commit changes to your own branch
  4. Push your work back up to your fork
  5. Submit a Pull Request so that we can review your changes

NOTE: Be sure to merge the latest changes from "upstream" before making a pull request!

Copyright

Copyright © 2017-2023 Cloud Posse, LLC

License

License

See LICENSE for full details.

Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements.  See the NOTICE file
distributed with this work for additional information
regarding copyright ownership.  The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License.  You may obtain a copy of the License at

  https://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied.  See the License for the
specific language governing permissions and limitations
under the License.

Trademarks

All other trademarks referenced herein are the property of their respective owners.

About

This project is maintained and funded by Cloud Posse, LLC. Like it? Please let us know by leaving a testimonial!

Cloud Posse

We're a DevOps Professional Services company based in Los Angeles, CA. We ❤️ Open Source Software.

We offer paid support on all of our projects.

Check out our other projects, follow us on twitter, apply for a job, or hire us to help with your cloud strategy and implementation.

Contributors

Erik Osterman
Erik Osterman
Andriy Knysh
Andriy Knysh
Igor Rodionov
Igor Rodionov

README Footer Beacon

github-commenter's People

Contributors

aknysh avatar audriusbutkevicius avatar danjbh avatar dylanbannon avatar goruha avatar joemiller avatar joshmyers avatar max-lobur avatar nuru avatar osterman avatar renovate[bot] avatar sukrit007wawa avatar tocy1 avatar vadim-hleif avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

github-commenter's Issues

is it possible to support an edit mode instead of delete and replace?

Is it possible to support an edit mode that could be used instead of the delete/replace method?

This is a nice-to-have.

Reasons:

  • With delete/replace, if you have a window open on the PR, you will see both the old and new comment. The old comment will disappear after a manual refresh of the window.
  • If there is a lot of discussion and new pushes on the PR the new comment will keep moving down the thread. I think it might be ideal if folks could always expect the comment is near the top.

Sorry if this has been asked already. I looked around the repo and didn't see any mention of an edit-existing mode. Again, this would just be a nice-to-have. Really love this tool! glad we found it. thanks

Command help can expose sensitive credentials

If sensitive parameters (e.g. GitHub access token) is passed by environment variable, then the help page includes this information as a "default" value. Sensitive values should not be exposed here, in case a mistake causes the help page to be displayed.

e.g.

...
  -token string
    	Github access token (default "01234567890abcdef")
...
2020/05/07 16:29:56 -sha or GITHUB_COMMIT_SHA required

Cannot comment on PR

Given the following config in codefresh to use the container:

  add_url_to_comment_on_pr:
    title: Comment on PR with the deployed URL
    stage: Deploy
    image: cloudposse/github-commenter
    environment:
      - GITHUB_TOKEN=${{GITHUB_REPO_STATUS_TOKEN}}
      - GITHUB_OWNER=${{CF_REPO_OWNER}}
      - GITHUB_REPO=${{CF_REPO_NAME}}
      - GITHUB_COMMENT_TYPE=pr
      - GITHUB_PR_ISSUE_NUMBER=${{CF_PULL_REQUEST_NUMBER}}
      - GITHUB_COMMENT_FORMAT="My comment:<br/>{{.}}"
      - GITHUB_COMMENT="Version ${{CF_SHORT_REVISION}} should be up, the health page is at http://${{APP_HOST}}/healthz/"
    when:
      condition:
        all:
          deployLabel: "match('${{CF_PULL_REQUEST_LABELS}}', 'deploy', false) == true"
          githubNotificationsEnabled: "'${{GITHUB_NOTIFICATIONS_ENABLED}}' == 'true'"

The container exits with the following error

2019/07/15 21:26:44 POST https://api.github.com/repos/example-org/example-app/issues/82/comments: 404 Not Found []      

It looks like the URL is incorrect according to the documentation here:

https://developer.github.com/v3/pulls/comments/#create-a-comment

POST /repos/:owner/:repo/pulls/:pull_number/comments

If I get time, I'll try to fix this issue myself, just ran out of work day today.

Message body too long?

Describe the Feature

If message body exceeds githubs max char limit, it fails. Would it be possible to count characters in message and split into separate comment calls if necessary.

Expected Behavior

split messsage into separate comments/multiple comments if char limit is exceeded

Use Case

Fails to comment on PR if message body is too long.

Describe Ideal Solution

Split into multiple comments

Alternatives Considered

No response

Additional Context

No response

GitHub app based authentication

Describe the Feature

Most organizations prefer to use the GitHub app instead of a user token for authentication as the token has an API limit of 5000 whereas the GitHub app goes all the way to 12500.

Expected Behavior

https://docs.github.com/en/apps/creating-github-apps/authenticating-with-a-github-app/about-authentication-with-a-github-app

Use Case

We reach the API limit on our application on a daily basis.

Describe Ideal Solution

https://docs.github.com/en/apps/creating-github-apps/authenticating-with-a-github-app/about-authentication-with-a-github-app

Alternatives Considered

No response

Additional Context

No response

Feature request: hiding (instead of editing/deleting) existing comment

Describe the Feature

Being able to hide comments matching a regex, as an alternative to delete-comment-regex (or edit-comment-regex added in #26).

Expected Behavior

Hiding existing comments, for example by using a hide-comment-regex.

Use Case

Sometimes keeping old comments might make sense for historical/compliance reasons.

Describe Ideal Solution

Not sure, open for thoughts.

Alternatives Considered

  1. delete-comment-regex
  2. edit-comment-regex (added in #26)

But they don't keep the history in an equally accessible way.

Additional Context

...

Feature request: Support specifying a template file

What about allowing the user to specify a go template file that will be applied to the comment? This would allow for more advanced templates, and avoid the complexity of needing to escape special characters for bash.

Feature Request: Expose Flags/Vars to Templating

It would be quite neat if we could call the other global vars defined in the main.go when writing our Go templates.
Perhaps in turn call our comment data type explicitly. (i.e. {{.comment}}
token,owner,repo,commentType,sha,number,file,position,templ,format,comment,deleteCommentRegex,baseURL,uploadURL

Example Template:

## Things Deployed to Platform in #{{.number}}
This is a test of the emergency broadcast system, this is only a test.

#A Header about the things we are deploying
{{.comment}} - `A body that is generated in via bash`

If I am reading func formatComment(comment string) (string, error) correct, presently it passes comment to the formatter explicitly.

Feature request: Restrict deletion of previous comments to current user

GITHUB_DELETE_COMMENT_REGEX can be used to delete previous comments before posting the new one. The current implementation will delete matching comments regardless of who they were posted by. This can easily lead to false positives where someone happens to post comment that matches your regex (due to loose regex, or quoting, etc).

I do not see a use case to delete comments by others, and recommend restricting it to the user that the tool is running as.

Dependency Dashboard

This issue lists Renovate updates and detected dependencies. Read the Dependency Dashboard docs to learn more.

Open

These updates have all been created already. Click a checkbox below to force a retry/rebase of any.

Ignored or Blocked

These are blocked by an existing closed PR and will not be recreated unless you click a checkbox below.

Detected dependencies

dockerfile
Dockerfile
  • golang 1.19-alpine3.16
  • alpine 3.16
github-actions
.github/workflows/auto-release.yml
.github/workflows/build.yml
  • actions/checkout v4
  • actions/setup-go v5
  • goreleaser/goreleaser-action v5
  • goreleaser/goreleaser-action v5
.github/workflows/docker.yml
  • actions/checkout v4
  • docker/setup-qemu-action v3
  • docker/setup-buildx-action v3
  • docker/login-action v3
  • docker/build-push-action v5
.github/workflows/validate-codeowners.yml
  • actions/checkout v4
  • mszostok/codeowners-validator v0.7.1
  • mszostok/codeowners-validator v0.7.1
gomod
go.mod
  • go 1.19
  • github.com/Masterminds/sprig v2.22.0+incompatible
  • github.com/google/go-github/v50 v50.2.0
  • github.com/pkg/errors v0.9.1
  • golang.org/x/net v0.17.0

  • Check this box to trigger a request for Renovate to run again on this repository

Don't add the comment if it already exists

Rather than requiring regex to delete comments, it would be great if this would automatically check if the comment exists, and if so, do not add a further comment.

For example, when setting up a PR review environment, we don't want it to constantly post the URL to the PR. We only need it done once.

Build amd64 version for Linux

Versions 0.10.0 and 0.10.1 was released with 386 and amd64 versions for Darwin and FreeBSD, but not Linux. Linux amd64 was included in releases v0.9.0 and earlier. Please include Linux amd64 in the releases again.

Need some way of translating the line in a file to the `position` param for a pull request review

Most of the code style/static analysis tools that I use work on an entire file, and not just a diff. It would be awesome to be able to run a code style check on whatever file changed, and then use this tool to automatically add a comment to the line in question inline in the PR.

Right now, there's not really a great way translate between a line in a file and the position param that Github needs in e.g. a bash script that's calling this utility, so I'm wondering if that might be easier in Go as a helper command or something. If this utility isn't the right place for that translation to happen, do you have any suggestions for other utilities that might handle that translation?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.