Recently I’ve started to move all my project to Codeberg. This is working great, but one of the things I really missed where the git-push options from GitLab where you can create a PR just by pushing a branch upstream.

Thanks to my whining about this on Mastodon I got this reply about an create-pr-action.

Well, putting this all together, I right now have this script (with little, or no error checking) that does the heavy lifting of creating a PR using Forgejo’s API. This needs an API token with read/write rights on your repo (and only that):

#!/bin/zsh

local URL=https://codeberg.org
local ORIGIN=$(git config --get remote.origin.url)

local parts=(${(@s:/:)ORIGIN})
local REPO=$parts[-1]
local OWNER=$parts[-2]
local REPO=${REPO%.git}
local BRANCH=$(git rev-parse --abbrev-ref 'HEAD')
local TITLE=$(git log -1  --pretty=format:%s)

response=$(curl -s -X 'POST' \
          "${URL}/api/v1/repos/${OWNER}/${REPO}/pulls" \
          -H 'accept: application/json' \
          -H 'Authorization: token <YOUR_LITERAL_TOKEN>' \
          -H 'Content-Type: application/json' \
          -d "{ \"base\": \"main\", \"head\": \"${BRANCH}\", \"title\": \"${TITLE}\" }"
)
local PR=$(echo $response | jq -r '.number')
echo remote:
echo remote: Created new pull request for \'${BRANCH}\':
echo remote: "  ${URL}/${OWNER}/${REPO}/pulls/${PR}"
echo remote:

Then in ~/.gitconfig:

[alias]
 hubtype = "!f() { case $(git remote get-url origin) in *github*) echo github;; *gitlab*) echo gitlab;; *codeberg*) echo codeberg;; esac; }; f"
 pr = "!f() { \
   case $(git hubtype) in \
   github) git githubpr;; \
   gitlab) git gitlabpr;; \
   codeberg) git codebergpr;; \
   esac; \
 }; f"
 ...
 codebergpr = "!f() { git push; ~/bin/codebergpr; }; f"

Which is a round-about way of being able to do git pr anywhere and the right thing will happen.

An example:

% g pr
Enumerating objects: 4, done.
Counting objects: 100% (4/4), done.
Delta compression using up to 8 threads
Compressing objects: 100% (2/2), done.
Writing objects: 100% (3/3), 354 bytes | 354.00 KiB/s, done.
Total 3 (delta 0), reused 0 (delta 0), pack-reused 0 (from 0)
remote:
remote: Create a new pull request for 'miek/26/jan28wo/07':
remote:   https://codeberg.org/miekg/forgejo-runner/compare/main...miek/26/jan28wo/07
remote:
To ssh://codeberg.org/miekg/forgejo-runner.git
 * [new branch]      miek/26/jan28wo/07 -> miek/26/jan28wo/07
branch 'miek/26/jan28wo/07' set up to track 'origin/miek/26/jan28wo/07'.
remote:
remote: Created new pull request for 'miek/26/jan28wo/07':
remote:   https://codeberg.org/miekg/forgejo-runner/pulls/11
remote: