forked from tangled.org/core
this repo has no description

Compare changes

Choose any two refs to compare.

Changed files
+4964 -2215
appview
cmd
combinediff
interdiff
docker
docs
knotserver
patchutil
rbac
types
+35 -20
appview/db/issues.go
···
"time"
"github.com/bluesky-social/indigo/atproto/syntax"
+
"tangled.sh/tangled.sh/core/appview/pagination"
)
type Issue struct {
···
return ownerDid, err
}
-
func GetIssues(e Execer, repoAt syntax.ATURI, isOpen bool) ([]Issue, error) {
+
func GetIssues(e Execer, repoAt syntax.ATURI, isOpen bool, page pagination.Page) ([]Issue, error) {
var issues []Issue
openValue := 0
if isOpen {
···
}
rows, err := e.Query(
-
`select
-
i.owner_did,
-
i.issue_id,
-
i.created,
-
i.title,
-
i.body,
-
i.open,
-
count(c.id)
-
from
-
issues i
-
left join
-
comments c on i.repo_at = c.repo_at and i.issue_id = c.issue_id
-
where
-
i.repo_at = ? and i.open = ?
-
group by
-
i.id, i.owner_did, i.issue_id, i.created, i.title, i.body, i.open
-
order by
-
i.created desc`,
-
repoAt, openValue)
+
`
+
with numbered_issue as (
+
select
+
i.owner_did,
+
i.issue_id,
+
i.created,
+
i.title,
+
i.body,
+
i.open,
+
count(c.id) as comment_count,
+
row_number() over (order by i.created desc) as row_num
+
from
+
issues i
+
left join
+
comments c on i.repo_at = c.repo_at and i.issue_id = c.issue_id
+
where
+
i.repo_at = ? and i.open = ?
+
group by
+
i.id, i.owner_did, i.issue_id, i.created, i.title, i.body, i.open
+
)
+
select
+
owner_did,
+
issue_id,
+
created,
+
title,
+
body,
+
open,
+
comment_count
+
from
+
numbered_issue
+
where
+
row_num between ? and ?`,
+
repoAt, openValue, page.Offset+1, page.Offset+page.Limit)
if err != nil {
return nil, err
}
+161 -12
appview/db/pulls.go
···
"database/sql"
"fmt"
"log"
+
"sort"
"strings"
"time"
"github.com/bluekeyes/go-gitdiff/gitdiff"
"github.com/bluesky-social/indigo/atproto/syntax"
+
"tangled.sh/tangled.sh/core/patchutil"
"tangled.sh/tangled.sh/core/types"
)
···
return len(p.Submissions) - 1
}
-
func (p *Pull) IsSameRepoBranch() bool {
+
func (p *Pull) IsPatchBased() bool {
+
return p.PullSource == nil
+
}
+
+
func (p *Pull) IsBranchBased() bool {
if p.PullSource != nil {
if p.PullSource.RepoAt != nil {
return p.PullSource.RepoAt == &p.RepoAt
···
return false
}
-
func (p *Pull) IsPatch() bool {
-
return p.PullSource == nil
+
func (p *Pull) IsForkBased() bool {
+
if p.PullSource != nil {
+
if p.PullSource.RepoAt != nil {
+
// make sure repos are different
+
return p.PullSource.RepoAt != &p.RepoAt
+
}
+
}
+
return false
}
-
func (s PullSubmission) AsNiceDiff(targetBranch string) types.NiceDiff {
+
func (s PullSubmission) AsDiff(targetBranch string) ([]*gitdiff.File, error) {
patch := s.Patch
-
diffs, _, err := gitdiff.Parse(strings.NewReader(patch))
+
// if format-patch; then extract each patch
+
var diffs []*gitdiff.File
+
if patchutil.IsFormatPatch(patch) {
+
patches, err := patchutil.ExtractPatches(patch)
+
if err != nil {
+
return nil, err
+
}
+
var ps [][]*gitdiff.File
+
for _, p := range patches {
+
ps = append(ps, p.Files)
+
}
+
+
diffs = patchutil.CombineDiff(ps...)
+
} else {
+
d, _, err := gitdiff.Parse(strings.NewReader(patch))
+
if err != nil {
+
return nil, err
+
}
+
diffs = d
+
}
+
+
return diffs, nil
+
}
+
+
func (s PullSubmission) AsNiceDiff(targetBranch string) types.NiceDiff {
+
diffs, err := s.AsDiff(targetBranch)
if err != nil {
log.Println(err)
}
···
nd.Stat.FilesChanged = len(diffs)
return nd
+
}
+
+
func (s PullSubmission) IsFormatPatch() bool {
+
return patchutil.IsFormatPatch(s.Patch)
+
}
+
+
func (s PullSubmission) AsFormatPatch() []patchutil.FormatPatch {
+
patches, err := patchutil.ExtractPatches(s.Patch)
+
if err != nil {
+
log.Println("error extracting patches from submission:", err)
+
return []patchutil.FormatPatch{}
+
}
+
+
return patches
}
func NewPull(tx *sql.Tx, pull *Pull) error {
···
return pullId - 1, err
}
-
func GetPulls(e Execer, repoAt syntax.ATURI, state PullState) ([]Pull, error) {
-
var pulls []Pull
+
func GetPulls(e Execer, repoAt syntax.ATURI, state PullState) ([]*Pull, error) {
+
pulls := make(map[int]*Pull)
rows, err := e.Query(`
select
···
from
pulls
where
-
repo_at = ? and state = ?
-
order by
-
created desc`, repoAt, state)
+
repo_at = ? and state = ?`, repoAt, state)
if err != nil {
return nil, err
}
···
}
}
-
pulls = append(pulls, pull)
+
pulls[pull.PullId] = &pull
+
}
+
+
// get latest round no. for each pull
+
inClause := strings.TrimSuffix(strings.Repeat("?, ", len(pulls)), ", ")
+
submissionsQuery := fmt.Sprintf(`
+
select
+
id, pull_id, round_number
+
from
+
pull_submissions
+
where
+
repo_at = ? and pull_id in (%s)
+
`, inClause)
+
+
args := make([]any, len(pulls)+1)
+
args[0] = repoAt.String()
+
idx := 1
+
for _, p := range pulls {
+
args[idx] = p.PullId
+
idx += 1
}
+
submissionsRows, err := e.Query(submissionsQuery, args...)
+
if err != nil {
+
return nil, err
+
}
+
defer submissionsRows.Close()
+
+
for submissionsRows.Next() {
+
var s PullSubmission
+
err := submissionsRows.Scan(
+
&s.ID,
+
&s.PullId,
+
&s.RoundNumber,
+
)
+
if err != nil {
+
return nil, err
+
}
+
if p, ok := pulls[s.PullId]; ok {
+
p.Submissions = make([]*PullSubmission, s.RoundNumber+1)
+
p.Submissions[s.RoundNumber] = &s
+
}
+
}
if err := rows.Err(); err != nil {
return nil, err
}
-
return pulls, nil
+
// get comment count on latest submission on each pull
+
inClause = strings.TrimSuffix(strings.Repeat("?, ", len(pulls)), ", ")
+
commentsQuery := fmt.Sprintf(`
+
select
+
count(id), pull_id
+
from
+
pull_comments
+
where
+
submission_id in (%s)
+
group by
+
submission_id
+
`, inClause)
+
+
args = []any{}
+
for _, p := range pulls {
+
args = append(args, p.Submissions[p.LastRoundNumber()].ID)
+
}
+
commentsRows, err := e.Query(commentsQuery, args...)
+
if err != nil {
+
return nil, err
+
}
+
defer commentsRows.Close()
+
+
for commentsRows.Next() {
+
var commentCount, pullId int
+
err := commentsRows.Scan(
+
&commentCount,
+
&pullId,
+
)
+
if err != nil {
+
return nil, err
+
}
+
if p, ok := pulls[pullId]; ok {
+
p.Submissions[p.LastRoundNumber()].Comments = make([]PullComment, commentCount)
+
}
+
}
+
if err := rows.Err(); err != nil {
+
return nil, err
+
}
+
+
orderedByDate := []*Pull{}
+
for _, p := range pulls {
+
orderedByDate = append(orderedByDate, p)
+
}
+
sort.Slice(orderedByDate, func(i, j int) bool {
+
return orderedByDate[i].Created.After(orderedByDate[j].Created)
+
})
+
+
return orderedByDate, nil
}
func GetPull(e Execer, repoAt syntax.ATURI, pullId int) (*Pull, error) {
···
}
if err = commentsRows.Err(); err != nil {
return nil, err
+
}
+
+
var pullSourceRepo *Repo
+
if pull.PullSource != nil {
+
if pull.PullSource.RepoAt != nil {
+
pullSourceRepo, err = GetRepoByAtUri(e, pull.PullSource.RepoAt.String())
+
if err != nil {
+
log.Printf("failed to get repo by at uri: %v", err)
+
} else {
+
pull.PullSource.Repo = pullSourceRepo
+
}
+
}
}
pull.Submissions = make([]*PullSubmission, len(submissionsMap))
+62
appview/filetree/filetree.go
···
+
package filetree
+
+
import (
+
"path/filepath"
+
"sort"
+
"strings"
+
)
+
+
type FileTreeNode struct {
+
Name string
+
Path string
+
IsDirectory bool
+
Children map[string]*FileTreeNode
+
}
+
+
// NewNode creates a new node
+
func newNode(name, path string, isDir bool) *FileTreeNode {
+
return &FileTreeNode{
+
Name: name,
+
Path: path,
+
IsDirectory: isDir,
+
Children: make(map[string]*FileTreeNode),
+
}
+
}
+
+
func FileTree(files []string) *FileTreeNode {
+
rootNode := newNode("", "", true)
+
+
sort.Strings(files)
+
+
for _, file := range files {
+
if file == "" {
+
continue
+
}
+
+
parts := strings.Split(filepath.Clean(file), "/")
+
if len(parts) == 0 {
+
continue
+
}
+
+
currentNode := rootNode
+
currentPath := ""
+
+
for i, part := range parts {
+
if currentPath == "" {
+
currentPath = part
+
} else {
+
currentPath = filepath.Join(currentPath, part)
+
}
+
+
isDir := i < len(parts)-1
+
+
if _, exists := currentNode.Children[part]; !exists {
+
currentNode.Children[part] = newNode(part, currentPath, isDir)
+
}
+
+
currentNode = currentNode.Children[part]
+
}
+
}
+
+
return rootNode
+
}
+126
appview/middleware/middleware.go
···
+
package middleware
+
+
import (
+
"context"
+
"log"
+
"net/http"
+
"strconv"
+
"time"
+
+
comatproto "github.com/bluesky-social/indigo/api/atproto"
+
"github.com/bluesky-social/indigo/xrpc"
+
"tangled.sh/tangled.sh/core/appview"
+
"tangled.sh/tangled.sh/core/appview/auth"
+
"tangled.sh/tangled.sh/core/appview/pagination"
+
)
+
+
type Middleware func(http.Handler) http.Handler
+
+
func AuthMiddleware(a *auth.Auth) Middleware {
+
return func(next http.Handler) http.Handler {
+
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+
redirectFunc := func(w http.ResponseWriter, r *http.Request) {
+
http.Redirect(w, r, "/login", http.StatusTemporaryRedirect)
+
}
+
if r.Header.Get("HX-Request") == "true" {
+
redirectFunc = func(w http.ResponseWriter, _ *http.Request) {
+
w.Header().Set("HX-Redirect", "/login")
+
w.WriteHeader(http.StatusOK)
+
}
+
}
+
+
session, err := a.GetSession(r)
+
if session.IsNew || err != nil {
+
log.Printf("not logged in, redirecting")
+
redirectFunc(w, r)
+
return
+
}
+
+
authorized, ok := session.Values[appview.SessionAuthenticated].(bool)
+
if !ok || !authorized {
+
log.Printf("not logged in, redirecting")
+
redirectFunc(w, r)
+
return
+
}
+
+
// refresh if nearing expiry
+
// TODO: dedup with /login
+
expiryStr := session.Values[appview.SessionExpiry].(string)
+
expiry, err := time.Parse(time.RFC3339, expiryStr)
+
if err != nil {
+
log.Println("invalid expiry time", err)
+
redirectFunc(w, r)
+
return
+
}
+
pdsUrl, ok1 := session.Values[appview.SessionPds].(string)
+
did, ok2 := session.Values[appview.SessionDid].(string)
+
refreshJwt, ok3 := session.Values[appview.SessionRefreshJwt].(string)
+
+
if !ok1 || !ok2 || !ok3 {
+
log.Println("invalid expiry time", err)
+
redirectFunc(w, r)
+
return
+
}
+
+
if time.Now().After(expiry) {
+
log.Println("token expired, refreshing ...")
+
+
client := xrpc.Client{
+
Host: pdsUrl,
+
Auth: &xrpc.AuthInfo{
+
Did: did,
+
AccessJwt: refreshJwt,
+
RefreshJwt: refreshJwt,
+
},
+
}
+
atSession, err := comatproto.ServerRefreshSession(r.Context(), &client)
+
if err != nil {
+
log.Println("failed to refresh session", err)
+
redirectFunc(w, r)
+
return
+
}
+
+
sessionish := auth.RefreshSessionWrapper{atSession}
+
+
err = a.StoreSession(r, w, &sessionish, pdsUrl)
+
if err != nil {
+
log.Printf("failed to store session for did: %s\n: %s", atSession.Did, err)
+
return
+
}
+
+
log.Println("successfully refreshed token")
+
}
+
+
next.ServeHTTP(w, r)
+
})
+
}
+
}
+
+
func Paginate(next http.Handler) http.Handler {
+
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+
page := pagination.FirstPage()
+
+
offsetVal := r.URL.Query().Get("offset")
+
if offsetVal != "" {
+
offset, err := strconv.Atoi(offsetVal)
+
if err != nil {
+
log.Println("invalid offset")
+
} else {
+
page.Offset = offset
+
}
+
}
+
+
limitVal := r.URL.Query().Get("limit")
+
if limitVal != "" {
+
limit, err := strconv.Atoi(limitVal)
+
if err != nil {
+
log.Println("invalid limit")
+
} else {
+
page.Limit = limit
+
}
+
}
+
+
ctx := context.WithValue(r.Context(), "page", page)
+
next.ServeHTTP(w, r.WithContext(ctx))
+
})
+
}
-40
appview/pages/chroma.go
···
-
package pages
-
-
import "github.com/alecthomas/chroma/v2"
-
-
var tangledTheme map[chroma.TokenType]string = map[chroma.TokenType]string{
-
// Keywords
-
chroma.Keyword: "text-blue-400",
-
chroma.KeywordConstant: "text-indigo-400",
-
chroma.KeywordDeclaration: "text-purple-400",
-
chroma.KeywordNamespace: "text-teal-400",
-
chroma.KeywordReserved: "text-pink-400",
-
-
// Names
-
chroma.Name: "text-gray-700",
-
chroma.NameFunction: "text-green-500",
-
chroma.NameClass: "text-orange-400",
-
chroma.NameNamespace: "text-cyan-500",
-
chroma.NameVariable: "text-red-400",
-
chroma.NameBuiltin: "text-yellow-500",
-
-
// Literals
-
chroma.LiteralString: "text-emerald-500 ",
-
chroma.LiteralStringChar: "text-lime-500",
-
chroma.LiteralNumber: "text-rose-400",
-
chroma.LiteralNumberFloat: "text-amber-500",
-
-
// Operators
-
chroma.Operator: "text-blue-500",
-
chroma.OperatorWord: "text-indigo-500",
-
-
// Comments
-
chroma.Comment: "text-gray-500 italic",
-
chroma.CommentSingle: "text-gray-400 italic",
-
-
// Generic
-
chroma.GenericError: "text-red-600",
-
chroma.GenericHeading: "text-purple-500 font-bold",
-
chroma.GenericDeleted: "text-red-400 line-through",
-
chroma.GenericInserted: "text-green-400 underline",
-
}
+2
appview/pages/funcmap.go
···
"time"
"github.com/dustin/go-humanize"
+
"tangled.sh/tangled.sh/core/appview/filetree"
"tangled.sh/tangled.sh/core/appview/pages/markup"
)
···
return template.HTML(data)
},
"cssContentHash": CssContentHash,
+
"fileTree": filetree.FileTree,
}
}
+226 -82
appview/pages/pages.go
···
"io/fs"
"log"
"net/http"
+
"os"
"path"
"path/filepath"
"slices"
"strings"
+
"tangled.sh/tangled.sh/core/appview/auth"
+
"tangled.sh/tangled.sh/core/appview/db"
+
"tangled.sh/tangled.sh/core/appview/pages/markup"
+
"tangled.sh/tangled.sh/core/appview/pagination"
+
"tangled.sh/tangled.sh/core/appview/state/userutil"
+
"tangled.sh/tangled.sh/core/patchutil"
+
"tangled.sh/tangled.sh/core/types"
+
"github.com/alecthomas/chroma/v2"
chromahtml "github.com/alecthomas/chroma/v2/formatters/html"
"github.com/alecthomas/chroma/v2/lexers"
"github.com/alecthomas/chroma/v2/styles"
"github.com/bluesky-social/indigo/atproto/syntax"
"github.com/microcosm-cc/bluemonday"
-
"tangled.sh/tangled.sh/core/appview/auth"
-
"tangled.sh/tangled.sh/core/appview/db"
-
"tangled.sh/tangled.sh/core/appview/pages/markup"
-
"tangled.sh/tangled.sh/core/appview/state/userutil"
-
"tangled.sh/tangled.sh/core/types"
)
//go:embed templates/* static
var Files embed.FS
type Pages struct {
-
t map[string]*template.Template
+
t map[string]*template.Template
+
dev bool
+
embedFS embed.FS
+
templateDir string // Path to templates on disk for dev mode
+
}
+
+
func NewPages(dev bool) *Pages {
+
p := &Pages{
+
t: make(map[string]*template.Template),
+
dev: dev,
+
embedFS: Files,
+
templateDir: "appview/pages",
+
}
+
+
// Initial load of all templates
+
p.loadAllTemplates()
+
+
return p
}
-
func NewPages() *Pages {
+
func (p *Pages) loadAllTemplates() {
templates := make(map[string]*template.Template)
+
var fragmentPaths []string
-
// Walk through embedded templates directory and parse all .html files
-
err := fs.WalkDir(Files, "templates", func(path string, d fs.DirEntry, err error) error {
+
// Use embedded FS for initial loading
+
// First, collect all fragment paths
+
err := fs.WalkDir(p.embedFS, "templates", func(path string, d fs.DirEntry, err error) error {
if err != nil {
return err
}
-
-
if !d.IsDir() && strings.HasSuffix(path, ".html") {
-
name := strings.TrimPrefix(path, "templates/")
-
name = strings.TrimSuffix(name, ".html")
+
if d.IsDir() {
+
return nil
+
}
+
if !strings.HasSuffix(path, ".html") {
+
return nil
+
}
+
if !strings.Contains(path, "fragments/") {
+
return nil
+
}
+
name := strings.TrimPrefix(path, "templates/")
+
name = strings.TrimSuffix(name, ".html")
+
tmpl, err := template.New(name).
+
Funcs(funcMap()).
+
ParseFS(p.embedFS, path)
+
if err != nil {
+
log.Fatalf("setting up fragment: %v", err)
+
}
+
templates[name] = tmpl
+
fragmentPaths = append(fragmentPaths, path)
+
log.Printf("loaded fragment: %s", name)
+
return nil
+
})
+
if err != nil {
+
log.Fatalf("walking template dir for fragments: %v", err)
+
}
-
// add fragments as templates
-
if strings.HasPrefix(path, "templates/fragments/") {
-
tmpl, err := template.New(name).
-
Funcs(funcMap()).
-
ParseFS(Files, path)
-
if err != nil {
-
return fmt.Errorf("setting up fragment: %w", err)
-
}
+
// Then walk through and setup the rest of the templates
+
err = fs.WalkDir(p.embedFS, "templates", func(path string, d fs.DirEntry, err error) error {
+
if err != nil {
+
return err
+
}
+
if d.IsDir() {
+
return nil
+
}
+
if !strings.HasSuffix(path, "html") {
+
return nil
+
}
+
// Skip fragments as they've already been loaded
+
if strings.Contains(path, "fragments/") {
+
return nil
+
}
+
// Skip layouts
+
if strings.Contains(path, "layouts/") {
+
return nil
+
}
+
name := strings.TrimPrefix(path, "templates/")
+
name = strings.TrimSuffix(name, ".html")
+
// Add the page template on top of the base
+
allPaths := []string{}
+
allPaths = append(allPaths, "templates/layouts/*.html")
+
allPaths = append(allPaths, fragmentPaths...)
+
allPaths = append(allPaths, path)
+
tmpl, err := template.New(name).
+
Funcs(funcMap()).
+
ParseFS(p.embedFS, allPaths...)
+
if err != nil {
+
return fmt.Errorf("setting up template: %w", err)
+
}
+
templates[name] = tmpl
+
log.Printf("loaded template: %s", name)
+
return nil
+
})
+
if err != nil {
+
log.Fatalf("walking template dir: %v", err)
+
}
-
templates[name] = tmpl
-
log.Printf("loaded fragment: %s", name)
-
}
+
log.Printf("total templates loaded: %d", len(templates))
+
p.t = templates
+
}
-
// layouts and fragments are applied first
-
if !strings.HasPrefix(path, "templates/layouts/") &&
-
!strings.HasPrefix(path, "templates/fragments/") {
-
// Add the page template on top of the base
-
tmpl, err := template.New(name).
-
Funcs(funcMap()).
-
ParseFS(Files, "templates/layouts/*.html", "templates/fragments/*.html", path)
-
if err != nil {
-
return fmt.Errorf("setting up template: %w", err)
-
}
+
// loadTemplateFromDisk loads a template from the filesystem in dev mode
+
func (p *Pages) loadTemplateFromDisk(name string) error {
+
if !p.dev {
+
return nil
+
}
-
templates[name] = tmpl
-
log.Printf("loaded template: %s", name)
-
}
+
log.Printf("reloading template from disk: %s", name)
+
// Find all fragments first
+
var fragmentPaths []string
+
err := filepath.WalkDir(filepath.Join(p.templateDir, "templates"), func(path string, d fs.DirEntry, err error) error {
+
if err != nil {
+
return err
+
}
+
if d.IsDir() {
return nil
}
+
if !strings.HasSuffix(path, ".html") {
+
return nil
+
}
+
if !strings.Contains(path, "fragments/") {
+
return nil
+
}
+
fragmentPaths = append(fragmentPaths, path)
return nil
})
if err != nil {
-
log.Fatalf("walking template dir: %v", err)
+
return fmt.Errorf("walking disk template dir for fragments: %w", err)
+
}
+
+
// Find the template path on disk
+
templatePath := filepath.Join(p.templateDir, "templates", name+".html")
+
if _, err := os.Stat(templatePath); os.IsNotExist(err) {
+
return fmt.Errorf("template not found on disk: %s", name)
+
}
+
+
// Create a new template
+
tmpl := template.New(name).Funcs(funcMap())
+
+
// Parse layouts
+
layoutGlob := filepath.Join(p.templateDir, "templates", "layouts", "*.html")
+
layouts, err := filepath.Glob(layoutGlob)
+
if err != nil {
+
return fmt.Errorf("finding layout templates: %w", err)
}
-
log.Printf("total templates loaded: %d", len(templates))
+
// Create paths for parsing
+
allFiles := append(layouts, fragmentPaths...)
+
allFiles = append(allFiles, templatePath)
-
return &Pages{
-
t: templates,
+
// Parse all templates
+
tmpl, err = tmpl.ParseFiles(allFiles...)
+
if err != nil {
+
return fmt.Errorf("parsing template files: %w", err)
}
+
+
// Update the template in the map
+
p.t[name] = tmpl
+
log.Printf("template reloaded from disk: %s", name)
+
return nil
}
-
type LoginParams struct {
+
func (p *Pages) executeOrReload(templateName string, w io.Writer, base string, params any) error {
+
// In dev mode, reload the template from disk before executing
+
if p.dev {
+
if err := p.loadTemplateFromDisk(templateName); err != nil {
+
log.Printf("warning: failed to reload template %s from disk: %v", templateName, err)
+
// Continue with the existing template
+
}
+
}
+
+
tmpl, exists := p.t[templateName]
+
if !exists {
+
return fmt.Errorf("template not found: %s", templateName)
+
}
+
+
if base == "" {
+
return tmpl.Execute(w, params)
+
} else {
+
return tmpl.ExecuteTemplate(w, base, params)
+
}
}
func (p *Pages) execute(name string, w io.Writer, params any) error {
-
return p.t[name].ExecuteTemplate(w, "layouts/base", params)
+
return p.executeOrReload(name, w, "layouts/base", params)
}
func (p *Pages) executePlain(name string, w io.Writer, params any) error {
-
return p.t[name].Execute(w, params)
+
return p.executeOrReload(name, w, "", params)
}
func (p *Pages) executeRepo(name string, w io.Writer, params any) error {
-
return p.t[name].ExecuteTemplate(w, "layouts/repobase", params)
+
return p.executeOrReload(name, w, "layouts/repobase", params)
+
}
+
+
type LoginParams struct {
}
func (p *Pages) Login(w io.Writer, params LoginParams) error {
···
}
func (p *Pages) FollowFragment(w io.Writer, params FollowFragmentParams) error {
-
return p.executePlain("fragments/follow", w, params)
+
return p.executePlain("user/fragments/follow", w, params)
}
type RepoActionsFragmentParams struct {
···
}
func (p *Pages) RepoActionsFragment(w io.Writer, params RepoActionsFragmentParams) error {
-
return p.executePlain("fragments/repoActions", w, params)
+
return p.executePlain("repo/fragments/repoActions", w, params)
}
type RepoDescriptionParams struct {
···
}
func (p *Pages) EditRepoDescriptionFragment(w io.Writer, params RepoDescriptionParams) error {
-
return p.executePlain("fragments/editRepoDescription", w, params)
+
return p.executePlain("repo/fragments/editRepoDescription", w, params)
}
func (p *Pages) RepoDescriptionFragment(w io.Writer, params RepoDescriptionParams) error {
-
return p.executePlain("fragments/repoDescription", w, params)
+
return p.executePlain("repo/fragments/repoDescription", w, params)
}
type RepoInfo struct {
···
}
type RepoCommitParams struct {
-
LoggedInUser *auth.User
-
RepoInfo RepoInfo
-
Active string
-
types.RepoCommitResponse
+
LoggedInUser *auth.User
+
RepoInfo RepoInfo
+
Active string
EmailToDidOrHandle map[string]string
+
+
types.RepoCommitResponse
}
func (p *Pages) RepoCommit(w io.Writer, params RepoCommitParams) error {
···
}
func (p *Pages) RepoBlob(w io.Writer, params RepoBlobParams) error {
-
style := styles.Get("bw")
-
b := style.Builder()
-
b.Add(chroma.LiteralString, "noitalic")
-
style, _ = b.Build()
+
var style *chroma.Style = styles.Get("catpuccin-latte")
if params.ShowRendered {
switch markup.GetFormat(params.Path) {
···
chromahtml.WithLineNumbers(true),
chromahtml.WithLinkableLineNumbers(true, "L"),
chromahtml.Standalone(false),
+
chromahtml.WithClasses(true),
)
lexer := lexers.Get(filepath.Base(params.Path))
···
}
type RepoIssuesParams struct {
-
LoggedInUser *auth.User
-
RepoInfo RepoInfo
-
Active string
-
Issues []db.Issue
-
DidHandleMap map[string]string
-
+
LoggedInUser *auth.User
+
RepoInfo RepoInfo
+
Active string
+
Issues []db.Issue
+
DidHandleMap map[string]string
+
Page pagination.Page
FilteringByOpen bool
}
···
}
func (p *Pages) EditIssueCommentFragment(w io.Writer, params EditIssueCommentParams) error {
-
return p.executePlain("fragments/editIssueComment", w, params)
+
return p.executePlain("repo/issues/fragments/editIssueComment", w, params)
}
type SingleIssueCommentParams struct {
···
}
func (p *Pages) SingleIssueCommentFragment(w io.Writer, params SingleIssueCommentParams) error {
-
return p.executePlain("fragments/issueComment", w, params)
+
return p.executePlain("repo/issues/fragments/issueComment", w, params)
}
type RepoNewPullParams struct {
···
type RepoPullsParams struct {
LoggedInUser *auth.User
RepoInfo RepoInfo
-
Pulls []db.Pull
+
Pulls []*db.Pull
Active string
DidHandleMap map[string]string
FilteringBy db.PullState
···
}
type RepoSinglePullParams struct {
-
LoggedInUser *auth.User
-
RepoInfo RepoInfo
-
Active string
-
DidHandleMap map[string]string
-
Pull *db.Pull
-
PullSourceRepo *db.Repo
-
MergeCheck types.MergeCheckResponse
-
ResubmitCheck ResubmitResult
+
LoggedInUser *auth.User
+
RepoInfo RepoInfo
+
Active string
+
DidHandleMap map[string]string
+
Pull *db.Pull
+
MergeCheck types.MergeCheckResponse
+
ResubmitCheck ResubmitResult
}
func (p *Pages) RepoSinglePull(w io.Writer, params RepoSinglePullParams) error {
···
DidHandleMap map[string]string
RepoInfo RepoInfo
Pull *db.Pull
-
Diff types.NiceDiff
+
Diff *types.NiceDiff
Round int
Submission *db.PullSubmission
}
···
return p.execute("repo/pulls/patch", w, params)
}
+
type RepoPullInterdiffParams struct {
+
LoggedInUser *auth.User
+
DidHandleMap map[string]string
+
RepoInfo RepoInfo
+
Pull *db.Pull
+
Round int
+
Interdiff *patchutil.InterdiffResult
+
}
+
+
// this name is a mouthful
+
func (p *Pages) RepoPullInterdiffPage(w io.Writer, params RepoPullInterdiffParams) error {
+
return p.execute("repo/pulls/interdiff", w, params)
+
}
+
type PullPatchUploadParams struct {
RepoInfo RepoInfo
}
func (p *Pages) PullPatchUploadFragment(w io.Writer, params PullPatchUploadParams) error {
-
return p.executePlain("fragments/pullPatchUpload", w, params)
+
return p.executePlain("repo/pulls/fragments/pullPatchUpload", w, params)
}
type PullCompareBranchesParams struct {
···
}
func (p *Pages) PullCompareBranchesFragment(w io.Writer, params PullCompareBranchesParams) error {
-
return p.executePlain("fragments/pullCompareBranches", w, params)
+
return p.executePlain("repo/pulls/fragments/pullCompareBranches", w, params)
}
type PullCompareForkParams struct {
···
}
func (p *Pages) PullCompareForkFragment(w io.Writer, params PullCompareForkParams) error {
-
return p.executePlain("fragments/pullCompareForks", w, params)
+
return p.executePlain("repo/pulls/fragments/pullCompareForks", w, params)
}
type PullCompareForkBranchesParams struct {
···
}
func (p *Pages) PullCompareForkBranchesFragment(w io.Writer, params PullCompareForkBranchesParams) error {
-
return p.executePlain("fragments/pullCompareForksBranches", w, params)
+
return p.executePlain("repo/pulls/fragments/pullCompareForksBranches", w, params)
}
type PullResubmitParams struct {
···
}
func (p *Pages) PullResubmitFragment(w io.Writer, params PullResubmitParams) error {
-
return p.executePlain("fragments/pullResubmit", w, params)
+
return p.executePlain("repo/pulls/fragments/pullResubmit", w, params)
}
type PullActionsParams struct {
···
}
func (p *Pages) PullActionsFragment(w io.Writer, params PullActionsParams) error {
-
return p.executePlain("fragments/pullActions", w, params)
+
return p.executePlain("repo/pulls/fragments/pullActions", w, params)
}
type PullNewCommentParams struct {
···
}
func (p *Pages) PullNewCommentFragment(w io.Writer, params PullNewCommentParams) error {
-
return p.executePlain("fragments/pullNewComment", w, params)
+
return p.executePlain("repo/pulls/fragments/pullNewComment", w, params)
}
func (p *Pages) Static() http.Handler {
+
if p.dev {
+
return http.StripPrefix("/static/", http.FileServer(http.Dir("appview/pages/static")))
+
}
+
sub, err := fs.Sub(Files, "static")
if err != nil {
log.Fatalf("no static dir found? that's crazy: %v", err)
-33
appview/pages/templates/fragments/cloneInstructions.html
···
-
{{ define "fragments/cloneInstructions" }}
-
<section class="mt-4 p-6 rounded bg-white dark:bg-gray-800 dark:text-white w-full mx-auto overflow-auto flex flex-col gap-4">
-
<div class="flex flex-col gap-2">
-
<strong>push</strong>
-
<div class="md:pl-4 overflow-x-auto whitespace-nowrap">
-
<code class="dark:text-gray-100">git remote add origin git@{{.RepoInfo.Knot}}:{{ .RepoInfo.OwnerHandle }}/{{ .RepoInfo.Name }}</code>
-
</div>
-
</div>
-
-
<div class="flex flex-col gap-2">
-
<strong>clone</strong>
-
<div class="md:pl-4 flex flex-col gap-2">
-
-
<div class="flex items-center gap-3">
-
<span class="bg-gray-100 dark:bg-gray-700 p-1 mr-1 font-mono text-sm rounded select-none dark:text-white">HTTP</span>
-
<div class="overflow-x-auto whitespace-nowrap flex-1">
-
<code class="dark:text-gray-100">git clone https://tangled.sh/{{ .RepoInfo.OwnerWithAt }}/{{ .RepoInfo.Name }}</code>
-
</div>
-
</div>
-
-
<div class="flex items-center gap-3">
-
<span class="bg-gray-100 dark:bg-gray-700 p-1 mr-1 font-mono text-sm rounded select-none dark:text-white">SSH</span>
-
<div class="overflow-x-auto whitespace-nowrap flex-1">
-
<code class="dark:text-gray-100">git clone git@{{.RepoInfo.Knot}}:{{ .RepoInfo.OwnerHandle }}/{{ .RepoInfo.Name }}</code>
-
</div>
-
</div>
-
</div>
-
</div>
-
-
-
<p class="py-2 text-gray-500 dark:text-gray-400">Note that for self-hosted knots, clone URLs may be different based on your setup.</p>
-
</section>
-
{{ end }}
-132
appview/pages/templates/fragments/diff.html
···
-
{{ define "fragments/diff" }}
-
{{ $repo := index . 0 }}
-
{{ $diff := index . 1 }}
-
{{ $commit := $diff.Commit }}
-
{{ $stat := $diff.Stat }}
-
{{ $diff := $diff.Diff }}
-
-
{{ $this := $commit.This }}
-
{{ $parent := $commit.Parent }}
-
-
{{ $last := sub (len $diff) 1 }}
-
{{ range $idx, $hunk := $diff }}
-
{{ with $hunk }}
-
<section class="mt-6 border border-gray-200 dark:border-gray-700 w-full mx-auto rounded bg-white dark:bg-gray-800 drop-shadow-sm">
-
<div id="file-{{ .Name.New }}">
-
<div id="diff-file">
-
<details open>
-
<summary class="list-none cursor-pointer sticky top-0">
-
<div id="diff-file-header" class="rounded cursor-pointer bg-white dark:bg-gray-800 flex justify-between">
-
<div id="left-side-items" class="p-2 flex gap-2 items-center overflow-x-auto" style="direction: rtl;">
-
{{ $markerstyle := "diff-type p-1 mr-1 font-mono text-sm rounded select-none" }}
-
-
<div class="flex gap-2 items-center" style="direction: ltr;">
-
{{ if .IsNew }}
-
<span class="bg-green-100 text-green-700 dark:bg-green-800/50 dark:text-green-400 {{ $markerstyle }}">ADDED</span>
-
{{ else if .IsDelete }}
-
<span class="bg-red-100 text-red-700 dark:bg-red-800/50 dark:text-red-400 {{ $markerstyle }}">DELETED</span>
-
{{ else if .IsCopy }}
-
<span class="bg-gray-100 text-gray-700 dark:bg-gray-700 dark:text-gray-300 {{ $markerstyle }}">COPIED</span>
-
{{ else if .IsRename }}
-
<span class="bg-gray-100 text-gray-700 dark:bg-gray-700 dark:text-gray-300 {{ $markerstyle }}">RENAMED</span>
-
{{ else }}
-
<span class="bg-gray-100 text-gray-700 dark:bg-gray-700 dark:text-gray-300 {{ $markerstyle }}">MODIFIED</span>
-
{{ end }}
-
-
{{ if .IsDelete }}
-
<a class="dark:text-white whitespace-nowrap overflow-x-auto" {{if $this }}href="/{{ $repo }}/blob/{{ $this }}/{{ .Name.Old }}"{{end}}>
-
{{ .Name.Old }}
-
</a>
-
{{ else if (or .IsCopy .IsRename) }}
-
<a class="dark:text-white whitespace-nowrap overflow-x-auto" {{if $parent}}href="/{{ $repo }}/blob/{{ $parent }}/{{ .Name.Old }}"{{end}}>
-
{{ .Name.Old }}
-
</a>
-
{{ i "arrow-right" "w-4 h-4" }}
-
<a class="dark:text-white whitespace-nowrap overflow-x-auto" {{if $this}}href="/{{ $repo }}/blob/{{ $this }}/{{ .Name.New }}"{{end}}>
-
{{ .Name.New }}
-
</a>
-
{{ else }}
-
<a class="dark:text-white whitespace-nowrap overflow-x-auto" {{if $this}}href="/{{ $repo }}/blob/{{ $this }}/{{ .Name.New }}"{{end}}>
-
{{ .Name.New }}
-
</a>
-
{{ end }}
-
</div>
-
</div>
-
-
{{ $iconstyle := "p-1 mx-1 hover:bg-gray-100 dark:hover:bg-gray-700 rounded" }}
-
<div id="right-side-items" class="p-2 flex items-center">
-
<a title="top of file" href="#file-{{ .Name.New }}" class="{{ $iconstyle }}">{{ i "arrow-up-to-line" "w-4 h-4" }}</a>
-
{{ if gt $idx 0 }}
-
{{ $prev := index $diff (sub $idx 1) }}
-
<a title="previous file" href="#file-{{ $prev.Name.New }}" class="{{ $iconstyle }}">{{ i "arrow-up" "w-4 h-4" }}</a>
-
{{ end }}
-
-
{{ if lt $idx $last }}
-
{{ $next := index $diff (add $idx 1) }}
-
<a title="next file" href="#file-{{ $next.Name.New }}" class="{{ $iconstyle }}">{{ i "arrow-down" "w-4 h-4" }}</a>
-
{{ end }}
-
</div>
-
-
</div>
-
</summary>
-
-
<div class="transition-all duration-700 ease-in-out">
-
{{ if .IsDelete }}
-
<p class="text-center text-gray-400 dark:text-gray-500 p-4">
-
This file has been deleted in this commit.
-
</p>
-
{{ else }}
-
{{ if .IsBinary }}
-
<p class="text-center text-gray-400 dark:text-gray-500 p-4">
-
This is a binary file and will not be displayed.
-
</p>
-
{{ else }}
-
<pre class="overflow-x-auto"><div class="overflow-x-auto"><div class="min-w-full inline-block">{{- range .TextFragments -}}<div class="bg-gray-100 dark:bg-gray-700 text-gray-500 dark:text-gray-400 select-none text-center">&middot;&middot;&middot;</div>
-
{{- $oldStart := .OldPosition -}}
-
{{- $newStart := .NewPosition -}}
-
{{- $lineNrStyle := "min-w-[3rem] flex-shrink-0 select-none text-right" -}}
-
{{- $lineNrSepStyle1 := "text-gray-400 dark:text-gray-500 bg-white dark:bg-gray-800" -}}
-
{{- $lineNrSepStyle2 := "text-gray-400 dark:text-gray-500 bg-white dark:bg-gray-800 pr-2" -}}
-
{{- range .Lines -}}
-
{{- if eq .Op.String "+" -}}
-
<div class="bg-green-100 dark:bg-green-800/30 text-green-700 dark:text-green-400 flex min-w-full items-center">
-
<div class="{{$lineNrStyle}} {{$lineNrSepStyle1}}"><span aria-hidden="true" class="invisible">{{$newStart}}</span></div>
-
<div class="{{$lineNrStyle}} {{$lineNrSepStyle2}}">{{ $newStart }}</div>
-
<div class="w-5 flex-shrink-0 select-none text-center">{{ .Op.String }}</div>
-
<div class="px-2">{{ .Line }}</div>
-
</div>
-
{{- $newStart = add64 $newStart 1 -}}
-
{{- end -}}
-
{{- if eq .Op.String "-" -}}
-
<div class="bg-red-100 dark:bg-red-800/30 text-red-700 dark:text-red-400 flex min-w-full items-center">
-
<div class="{{$lineNrStyle}} {{$lineNrSepStyle1}}">{{ $oldStart }}</div>
-
<div class="{{$lineNrStyle}} {{$lineNrSepStyle2}}"><span aria-hidden="true" class="invisible">{{$oldStart}}</span></div>
-
<div class="w-5 flex-shrink-0 select-none text-center">{{ .Op.String }}</div>
-
<div class="px-2">{{ .Line }}</div>
-
</div>
-
{{- $oldStart = add64 $oldStart 1 -}}
-
{{- end -}}
-
{{- if eq .Op.String " " -}}
-
<div class="bg-white dark:bg-gray-800 text-gray-500 dark:text-gray-400 flex min-w-full items-center">
-
<div class="{{$lineNrStyle}} {{$lineNrSepStyle1}}">{{ $oldStart }}</div>
-
<div class="{{$lineNrStyle}} {{$lineNrSepStyle2}}">{{ $newStart }}</div>
-
<div class="w-5 flex-shrink-0 select-none text-center">{{ .Op.String }}</div>
-
<div class="px-2">{{ .Line }}</div>
-
</div>
-
{{- $newStart = add64 $newStart 1 -}}
-
{{- $oldStart = add64 $oldStart 1 -}}
-
{{- end -}}
-
{{- end -}}
-
{{- end -}}</div></div></pre>
-
{{- end -}}
-
{{ end }}
-
</div>
-
-
</details>
-
-
</div>
-
</div>
-
</section>
-
{{ end }}
-
{{ end }}
-
{{ end }}
-52
appview/pages/templates/fragments/editIssueComment.html
···
-
{{ define "fragments/editIssueComment" }}
-
{{ with .Comment }}
-
<div id="comment-container-{{.CommentId}}">
-
<div class="flex items-center gap-2 mb-2 text-gray-500 text-sm">
-
{{ $owner := didOrHandle $.LoggedInUser.Did $.LoggedInUser.Handle }}
-
<a href="/{{ $owner }}" class="no-underline hover:underline">{{ $owner }}</a>
-
-
<!-- show user "hats" -->
-
{{ $isIssueAuthor := eq .OwnerDid $.Issue.OwnerDid }}
-
{{ if $isIssueAuthor }}
-
<span class="before:content-['ยท']"></span>
-
<span class="rounded bg-gray-100 text-black font-mono px-2 mx-1/2 inline-flex items-center">
-
author
-
</span>
-
{{ end }}
-
-
<span class="before:content-['ยท']"></span>
-
<a
-
href="#{{ .CommentId }}"
-
class="text-gray-500 hover:text-gray-500 hover:underline no-underline"
-
id="{{ .CommentId }}">
-
{{ .Created | timeFmt }}
-
</a>
-
-
<button
-
class="btn px-2 py-1 flex items-center gap-2 text-sm"
-
hx-post="/{{ $.RepoInfo.FullName }}/issues/{{ .Issue }}/comment/{{ .CommentId }}/edit"
-
hx-include="#edit-textarea-{{ .CommentId }}"
-
hx-target="#comment-container-{{ .CommentId }}"
-
hx-swap="outerHTML">
-
{{ i "check" "w-4 h-4" }}
-
</button>
-
<button
-
class="btn px-2 py-1 flex items-center gap-2 text-sm"
-
hx-get="/{{ $.RepoInfo.FullName }}/issues/{{ .Issue }}/comment/{{ .CommentId }}/"
-
hx-target="#comment-container-{{ .CommentId }}"
-
hx-swap="outerHTML">
-
{{ i "x" "w-4 h-4" }}
-
</button>
-
<span id="comment-{{.CommentId}}-status"></span>
-
</div>
-
-
<div>
-
<textarea
-
id="edit-textarea-{{ .CommentId }}"
-
name="body"
-
class="w-full p-2 border rounded min-h-[100px]">{{ .Body }}</textarea>
-
</div>
-
</div>
-
{{ end }}
-
{{ end }}
-
-11
appview/pages/templates/fragments/editRepoDescription.html
···
-
{{ define "fragments/editRepoDescription" }}
-
<form hx-put="/{{ .RepoInfo.FullName }}/description" hx-target="this" hx-swap="outerHTML" class="flex flex-wrap gap-2">
-
<input type="text" class="p-1" name="description" value="{{ .RepoInfo.Description }}">
-
<button type="submit" class="btn p-1 flex items-center gap-2 no-underline text-sm">
-
{{ i "check" "w-3 h-3" }} save
-
</button>
-
<button type="button" class="btn p-1 flex items-center gap-2 no-underline text-sm" hx-get="/{{ .RepoInfo.FullName }}/description" >
-
{{ i "x" "w-3 h-3" }} cancel
-
</button>
-
</form>
-
{{ end }}
-17
appview/pages/templates/fragments/follow.html
···
-
{{ define "fragments/follow" }}
-
<button id="followBtn"
-
class="btn mt-2 w-full"
-
-
{{ if eq .FollowStatus.String "IsNotFollowing" }}
-
hx-post="/follow?subject={{.UserDid}}"
-
{{ else }}
-
hx-delete="/follow?subject={{.UserDid}}"
-
{{ end }}
-
-
hx-trigger="click"
-
hx-target="#followBtn"
-
hx-swap="outerHTML"
-
>
-
{{ if eq .FollowStatus.String "IsNotFollowing" }}Follow{{ else }}Unfollow{{ end }}
-
</button>
-
{{ end }}
-60
appview/pages/templates/fragments/issueComment.html
···
-
{{ define "fragments/issueComment" }}
-
{{ with .Comment }}
-
<div id="comment-container-{{.CommentId}}">
-
<div class="flex items-center gap-2 mb-2 text-gray-500 text-sm">
-
{{ $owner := index $.DidHandleMap .OwnerDid }}
-
<a href="/{{ $owner }}" class="no-underline hover:underline">{{ $owner }}</a>
-
-
<!-- show user "hats" -->
-
{{ $isIssueAuthor := eq .OwnerDid $.Issue.OwnerDid }}
-
{{ if $isIssueAuthor }}
-
<span class="before:content-['ยท']"></span>
-
<span class="rounded bg-gray-100 dark:bg-gray-700 text-black dark:text-white font-mono px-2 mx-1/2 inline-flex items-center">
-
author
-
</span>
-
{{ end }}
-
-
<span class="before:content-['ยท']"></span>
-
<a
-
href="#{{ .CommentId }}"
-
class="text-gray-500 hover:text-gray-500 hover:underline no-underline"
-
id="{{ .CommentId }}">
-
{{ if .Deleted }}
-
deleted {{ .Deleted | timeFmt }}
-
{{ else if .Edited }}
-
edited {{ .Edited | timeFmt }}
-
{{ else }}
-
{{ .Created | timeFmt }}
-
{{ end }}
-
</a>
-
-
{{ $isCommentOwner := and $.LoggedInUser (eq $.LoggedInUser.Did .OwnerDid) }}
-
{{ if and $isCommentOwner (not .Deleted) }}
-
<button
-
class="btn px-2 py-1 text-sm"
-
hx-get="/{{ $.RepoInfo.FullName }}/issues/{{ .Issue }}/comment/{{ .CommentId }}/edit"
-
hx-swap="outerHTML"
-
hx-target="#comment-container-{{.CommentId}}"
-
>
-
{{ i "pencil" "w-4 h-4" }}
-
</button>
-
<button
-
class="btn px-2 py-1 text-sm text-red-500"
-
hx-delete="/{{ $.RepoInfo.FullName }}/issues/{{ .Issue }}/comment/{{ .CommentId }}/"
-
hx-confirm="Are you sure you want to delete your comment?"
-
hx-swap="outerHTML"
-
hx-target="#comment-container-{{.CommentId}}"
-
>
-
{{ i "trash-2" "w-4 h-4" }}
-
</button>
-
{{ end }}
-
-
</div>
-
{{ if not .Deleted }}
-
<div class="prose dark:prose-invert">
-
{{ .Body | markdown }}
-
</div>
-
{{ end }}
-
</div>
-
{{ end }}
-
{{ end }}
-91
appview/pages/templates/fragments/pullActions.html
···
-
{{ define "fragments/pullActions" }}
-
{{ $lastIdx := sub (len .Pull.Submissions) 1 }}
-
{{ $roundNumber := .RoundNumber }}
-
-
{{ $isPushAllowed := .RepoInfo.Roles.IsPushAllowed }}
-
{{ $isMerged := .Pull.State.IsMerged }}
-
{{ $isClosed := .Pull.State.IsClosed }}
-
{{ $isOpen := .Pull.State.IsOpen }}
-
{{ $isConflicted := and .MergeCheck (or .MergeCheck.Error .MergeCheck.IsConflicted) }}
-
{{ $isPullAuthor := and .LoggedInUser (eq .LoggedInUser.Did .Pull.OwnerDid) }}
-
{{ $isLastRound := eq $roundNumber $lastIdx }}
-
{{ $isSameRepoBranch := .Pull.IsSameRepoBranch }}
-
{{ $isUpToDate := .ResubmitCheck.No }}
-
<div class="relative w-fit">
-
<div class="absolute left-8 -top-2 w-px h-2 bg-gray-300 dark:bg-gray-600"></div>
-
<div id="actions-{{$roundNumber}}" class="flex flex-wrap gap-2">
-
<button
-
hx-get="/{{ .RepoInfo.FullName }}/pulls/{{ .Pull.PullId }}/round/{{ $roundNumber }}/comment"
-
hx-target="#actions-{{$roundNumber}}"
-
hx-swap="outerHtml"
-
class="btn p-2 flex items-center gap-2 no-underline hover:no-underline">
-
{{ i "message-square-plus" "w-4 h-4" }}
-
<span>comment</span>
-
</button>
-
{{ if and $isPushAllowed $isOpen $isLastRound }}
-
{{ $disabled := "" }}
-
{{ if $isConflicted }}
-
{{ $disabled = "disabled" }}
-
{{ end }}
-
<button
-
hx-post="/{{ .RepoInfo.FullName }}/pulls/{{ .Pull.PullId }}/merge"
-
hx-swap="none"
-
hx-confirm="Are you sure you want to merge pull #{{ .Pull.PullId }} into the `{{ .Pull.TargetBranch }}` branch?"
-
class="btn p-2 flex items-center gap-2" {{ $disabled }}>
-
{{ i "git-merge" "w-4 h-4" }}
-
<span>merge</span>
-
</button>
-
{{ end }}
-
-
{{ if and $isPullAuthor $isOpen $isLastRound }}
-
{{ $disabled := "" }}
-
{{ if $isUpToDate }}
-
{{ $disabled = "disabled" }}
-
{{ end }}
-
<button id="resubmitBtn"
-
{{ if not .Pull.IsPatch }}
-
hx-post="/{{ .RepoInfo.FullName }}/pulls/{{ .Pull.PullId }}/resubmit"
-
{{ else }}
-
hx-get="/{{ .RepoInfo.FullName }}/pulls/{{ .Pull.PullId }}/resubmit"
-
hx-target="#actions-{{$roundNumber}}"
-
hx-swap="outerHtml"
-
{{ end }}
-
-
hx-disabled-elt="#resubmitBtn"
-
class="btn p-2 flex items-center gap-2 disabled:opacity-50 disabled:cursor-not-allowed" {{ $disabled }}
-
-
{{ if $disabled }}
-
title="Update this branch to resubmit this pull request"
-
{{ else }}
-
title="Resubmit this pull request"
-
{{ end }}
-
>
-
{{ i "rotate-ccw" "w-4 h-4" }}
-
<span>resubmit</span>
-
</button>
-
{{ end }}
-
-
{{ if and (or $isPullAuthor $isPushAllowed) $isOpen $isLastRound }}
-
<button
-
hx-post="/{{ .RepoInfo.FullName }}/pulls/{{ .Pull.PullId }}/close"
-
hx-swap="none"
-
class="btn p-2 flex items-center gap-2">
-
{{ i "ban" "w-4 h-4" }}
-
<span>close</span>
-
</button>
-
{{ end }}
-
-
{{ if and (or $isPullAuthor $isPushAllowed) $isClosed $isLastRound }}
-
<button
-
hx-post="/{{ .RepoInfo.FullName }}/pulls/{{ .Pull.PullId }}/reopen"
-
hx-swap="none"
-
class="btn p-2 flex items-center gap-2">
-
{{ i "circle-dot" "w-4 h-4" }}
-
<span>reopen</span>
-
</button>
-
{{ end }}
-
</div>
-
</div>
-
{{ end }}
-
-
-20
appview/pages/templates/fragments/pullCompareBranches.html
···
-
{{ define "fragments/pullCompareBranches" }}
-
<div id="patch-upload">
-
<label for="targetBranch" class="dark:text-white"
-
>select a branch</label
-
>
-
<div class="flex flex-wrap gap-2 items-center">
-
<select
-
name="sourceBranch"
-
class="p-1 border border-gray-200 bg-white dark:bg-gray-700 dark:text-white dark:border-gray-600"
-
>
-
<option disabled selected>source branch</option>
-
{{ range .Branches }}
-
<option value="{{ .Reference.Name }}" class="py-1">
-
{{ .Reference.Name }}
-
</option>
-
{{ end }}
-
</select>
-
</div>
-
</div>
-
{{ end }}
-42
appview/pages/templates/fragments/pullCompareForks.html
···
-
{{ define "fragments/pullCompareForks" }}
-
<div id="patch-upload">
-
<label for="forkSelect" class="dark:text-white"
-
>select a fork to compare</label
-
>
-
<div class="flex flex-wrap gap-4 items-center mb-4">
-
<div class="flex flex-wrap gap-2 items-center">
-
<select
-
id="forkSelect"
-
name="fork"
-
required
-
class="p-1 border border-gray-200 bg-white dark:bg-gray-700 dark:text-white dark:border-gray-600"
-
hx-get="/{{ $.RepoInfo.FullName }}/pulls/new/fork-branches"
-
hx-target="#branch-selection"
-
hx-vals='{"fork": this.value}'
-
hx-swap="innerHTML"
-
onchange="document.getElementById('hiddenForkInput').value = this.value;"
-
>
-
<option disabled selected>select a fork</option>
-
{{ range .Forks }}
-
<option value="{{ .Name }}" class="py-1">
-
{{ .Name }}
-
</option>
-
{{ end }}
-
</select>
-
-
<input
-
type="hidden"
-
id="hiddenForkInput"
-
name="fork"
-
value=""
-
/>
-
</div>
-
-
<div id="branch-selection">
-
<div class="text-sm text-gray-500 dark:text-gray-400">
-
Select a fork first to view available branches
-
</div>
-
</div>
-
</div>
-
</div>
-
{{ end }}
-15
appview/pages/templates/fragments/pullCompareForksBranches.html
···
-
{{ define "fragments/pullCompareForksBranches" }}
-
<div class="flex flex-wrap gap-2 items-center">
-
<select
-
name="sourceBranch"
-
class="p-1 border border-gray-200 bg-white dark:bg-gray-700 dark:text-white dark:border-gray-600"
-
>
-
<option disabled selected>source branch</option>
-
{{ range .SourceBranches }}
-
<option value="{{ .Reference.Name }}" class="py-1">
-
{{ .Reference.Name }}
-
</option>
-
{{ end }}
-
</select>
-
</div>
-
{{ end }}
-32
appview/pages/templates/fragments/pullNewComment.html
···
-
{{ define "fragments/pullNewComment" }}
-
<div
-
id="pull-comment-card-{{ .RoundNumber }}"
-
class="bg-white dark:bg-gray-800 rounded drop-shadow-sm p-4 relative w-full flex flex-col gap-2">
-
<div class="text-sm text-gray-500 dark:text-gray-400">
-
{{ didOrHandle .LoggedInUser.Did .LoggedInUser.Handle }}
-
</div>
-
<form
-
hx-post="/{{ .RepoInfo.FullName }}/pulls/{{ .Pull.PullId }}/round/{{ .RoundNumber }}/comment"
-
hx-swap="none"
-
class="w-full flex flex-wrap gap-2">
-
<textarea
-
name="body"
-
class="w-full p-2 rounded border border-gray-200"
-
placeholder="Add to the discussion..."></textarea>
-
<button type="submit" class="btn flex items-center gap-2">
-
{{ i "message-square" "w-4 h-4" }} comment
-
</button>
-
<button
-
type="button"
-
class="btn flex items-center gap-2"
-
hx-get="/{{ .RepoInfo.FullName }}/pulls/{{ .Pull.PullId }}/round/{{ .RoundNumber }}/actions"
-
hx-swap="outerHTML"
-
hx-target="#pull-comment-card-{{ .RoundNumber }}">
-
{{ i "x" "w-4 h-4" }}
-
<span>cancel</span>
-
</button>
-
<div id="pull-comment"></div>
-
</form>
-
</div>
-
{{ end }}
-
-14
appview/pages/templates/fragments/pullPatchUpload.html
···
-
{{ define "fragments/pullPatchUpload" }}
-
<div id="patch-upload">
-
<textarea
-
name="patch"
-
id="patch"
-
rows="12"
-
class="w-full resize-y font-mono dark:bg-gray-700 dark:text-white dark:border-gray-600"
-
placeholder="diff --git a/file.txt b/file.txt
-
index 1234567..abcdefg 100644
-
--- a/file.txt
-
+++ b/file.txt"
-
></textarea>
-
</div>
-
{{ end }}
-52
appview/pages/templates/fragments/pullResubmit.html
···
-
{{ define "fragments/pullResubmit" }}
-
<div
-
id="resubmit-pull-card"
-
class="rounded relative border bg-amber-50 dark:bg-amber-900 border-amber-200 dark:border-amber-500 px-6 py-2">
-
-
<div class="flex items-center gap-2 text-amber-500 dark:text-amber-50">
-
{{ i "pencil" "w-4 h-4" }}
-
<span class="font-medium">resubmit your patch</span>
-
</div>
-
-
<div class="mt-2 text-sm text-gray-700 dark:text-gray-200">
-
You can update this patch to address any reviews.
-
This will begin a new round of reviews,
-
but you'll still be able to view your previous submissions and feedback.
-
</div>
-
-
<div class="mt-4 flex flex-col">
-
<form
-
hx-post="/{{ .RepoInfo.FullName }}/pulls/{{ .Pull.PullId }}/resubmit"
-
hx-swap="none"
-
class="w-full flex flex-wrap gap-2">
-
<textarea
-
name="patch"
-
class="w-full p-2 mb-2"
-
placeholder="Paste your updated patch here."
-
rows="15"
-
>{{.Pull.LatestPatch}}</textarea>
-
<button
-
type="submit"
-
class="btn flex items-center gap-2"
-
{{ if or .Pull.State.IsClosed }}
-
disabled
-
{{ end }}>
-
{{ i "rotate-ccw" "w-4 h-4" }}
-
<span>resubmit</span>
-
</button>
-
<button
-
type="button"
-
class="btn flex items-center gap-2"
-
hx-get="/{{ .RepoInfo.FullName }}/pulls/{{ .Pull.PullId }}/round/{{ .Pull.LastRoundNumber }}/actions"
-
hx-swap="outerHTML"
-
hx-target="#resubmit-pull-card">
-
{{ i "x" "w-4 h-4" }}
-
<span>cancel</span>
-
</button>
-
</form>
-
-
<div id="resubmit-error" class="error"></div>
-
<div id="resubmit-success" class="success"></div>
-
</div>
-
</div>
-
{{ end }}
-41
appview/pages/templates/fragments/repoActions.html
···
-
{{ define "fragments/repoActions" }}
-
<div class="flex items-center gap-2 z-auto">
-
<button id="starBtn"
-
class="btn disabled:opacity-50 disabled:cursor-not-allowed"
-
-
{{ if .IsStarred }}
-
hx-delete="/star?subject={{.RepoAt}}&countHint={{.Stats.StarCount}}"
-
{{ else }}
-
hx-post="/star?subject={{.RepoAt}}&countHint={{.Stats.StarCount}}"
-
{{ end }}
-
-
hx-trigger="click"
-
hx-target="#starBtn"
-
hx-swap="outerHTML"
-
hx-disabled-elt="#starBtn"
-
>
-
<div class="flex gap-2 items-center">
-
{{ if .IsStarred }}
-
{{ i "star" "w-4 h-4 fill-current" }}
-
{{ else }}
-
{{ i "star" "w-4 h-4" }}
-
{{ end }}
-
<span>
-
{{ .Stats.StarCount }}
-
</span>
-
</div>
-
</button>
-
{{ if .DisableFork }}
-
<button class="btn no-underline hover:no-underline flex items-center gap-2 disabled:opacity-50 disabled:cursor-not-allowed" disabled title="Empty repositories cannot be forked">
-
{{ i "git-fork" "w-4 h-4"}}
-
fork
-
</button>
-
{{ else }}
-
<a class="btn no-underline hover:no-underline flex items-center gap-2" href="/{{ .FullName }}/fork">
-
{{ i "git-fork" "w-4 h-4"}}
-
fork
-
</a>
-
{{ end }}
-
</div>
-
{{ end }}
-
-15
appview/pages/templates/fragments/repoDescription.html
···
-
{{ define "fragments/repoDescription" }}
-
<span id="repo-description" class="flex flex-wrap items-center gap-2 text-sm" hx-target="this" hx-swap="outerHTML">
-
{{ if .RepoInfo.Description }}
-
{{ .RepoInfo.Description }}
-
{{ else }}
-
<span class="italic">this repo has no description</span>
-
{{ end }}
-
-
{{ if .RepoInfo.Roles.IsOwner }}
-
<button class="flex items-center gap-2 no-underline text-sm" hx-get="/{{ .RepoInfo.FullName }}/description/edit">
-
{{ i "pencil" "w-3 h-3" }}
-
</button>
-
{{ end }}
-
</span>
-
{{ end }}
+2 -2
appview/pages/templates/layouts/repobase.html
···
<a href="/{{ .RepoInfo.FullName }}" class="font-bold">{{ .RepoInfo.Name }}</a>
</div>
-
{{ template "fragments/repoActions" .RepoInfo }}
+
{{ template "repo/fragments/repoActions" .RepoInfo }}
</div>
-
{{ template "fragments/repoDescription" . }}
+
{{ template "repo/fragments/repoDescription" . }}
</section>
<section class="min-h-screen flex flex-col drop-shadow-sm">
<nav class="w-full pl-4 overflow-auto">
+2 -21
appview/pages/templates/repo/commit.html
···
{{ $repo := .RepoInfo.FullName }}
{{ $commit := .Diff.Commit }}
-
{{ $stat := .Diff.Stat }}
-
{{ $diff := .Diff.Diff }}
<section class="commit dark:text-white">
<div id="commit-message">
···
<div>
<p class="pb-2">{{ index $messageParts 0 }}</p>
{{ if gt (len $messageParts) 1 }}
-
<p class="mt-1 cursor-text pb-2 text-sm">{{ nl2br (unwrapText (index $messageParts 1)) }}</p>
+
<p class="mt-1 cursor-text pb-2 text-sm">{{ nl2br (index $messageParts 1) }}</p>
{{ end }}
</div>
</div>
···
{{ end }}
<span class="px-1 select-none before:content-['\00B7']"></span>
{{ timeFmt $commit.Author.When }}
-
<span class="px-1 select-none before:content-['\00B7']"></span>
-
<span>{{ $stat.FilesChanged }}</span> files <span class="font-mono">(+{{ $stat.Insertions }}, -{{ $stat.Deletions }})</span>
<span class="px-1 select-none before:content-['\00B7']"></span>
</p>
···
</p>
</div>
-
<div class="diff-stat">
-
<br>
-
<strong class="text-sm uppercase mb-4 dark:text-gray-200">Changed files</strong>
-
<div class="overflow-x-auto">
-
{{ range $diff }}
-
<ul class="dark:text-gray-200">
-
{{ if .IsDelete }}
-
<li><a href="#file-{{ .Name.Old }}" class="dark:hover:text-gray-300">{{ .Name.Old }}</a></li>
-
{{ else }}
-
<li><a href="#file-{{ .Name.New }}" class="dark:hover:text-gray-300">{{ .Name.New }}</a></li>
-
{{ end }}
-
</ul>
-
{{ end }}
-
</div>
-
</div>
</section>
{{end}}
{{ define "repoAfter" }}
-
{{ template "fragments/diff" (list .RepoInfo.FullName .Diff) }}
+
{{ template "repo/fragments/diff" (list .RepoInfo.FullName .Diff) }}
{{end}}
+1 -1
appview/pages/templates/repo/empty.html
···
{{ end }}
{{ define "repoAfter" }}
-
{{ template "fragments/cloneInstructions" . }}
+
{{ template "repo/fragments/cloneInstructions" . }}
{{ end }}
+51
appview/pages/templates/repo/fragments/cloneInstructions.html
···
+
{{ define "repo/fragments/cloneInstructions" }}
+
<section
+
class="mt-4 p-6 rounded bg-white dark:bg-gray-800 dark:text-white w-full mx-auto overflow-auto flex flex-col gap-4"
+
>
+
<div class="flex flex-col gap-2">
+
<strong>push</strong>
+
<div class="md:pl-4 overflow-x-auto whitespace-nowrap">
+
<code class="dark:text-gray-100"
+
>git remote add origin
+
git@{{ .RepoInfo.Knot }}:{{ .RepoInfo.OwnerHandle }}/{{ .RepoInfo.Name }}</code
+
>
+
</div>
+
</div>
+
+
<div class="flex flex-col gap-2">
+
<strong>clone</strong>
+
<div class="md:pl-4 flex flex-col gap-2">
+
<div class="flex items-center gap-3">
+
<span
+
class="bg-gray-100 dark:bg-gray-700 p-1 mr-1 font-mono text-sm rounded select-none dark:text-white"
+
>HTTP</span
+
>
+
<div class="overflow-x-auto whitespace-nowrap flex-1">
+
<code class="dark:text-gray-100"
+
>git clone
+
https://tangled.sh/{{ .RepoInfo.OwnerWithAt }}/{{ .RepoInfo.Name }}</code
+
>
+
</div>
+
</div>
+
+
<div class="flex items-center gap-3">
+
<span
+
class="bg-gray-100 dark:bg-gray-700 p-1 mr-1 font-mono text-sm rounded select-none dark:text-white"
+
>SSH</span
+
>
+
<div class="overflow-x-auto whitespace-nowrap flex-1">
+
<code class="dark:text-gray-100"
+
>git clone
+
git@{{ .RepoInfo.Knot }}:{{ .RepoInfo.OwnerHandle }}/{{ .RepoInfo.Name }}</code
+
>
+
</div>
+
</div>
+
</div>
+
</div>
+
+
<p class="py-2 text-gray-500 dark:text-gray-400">
+
Note that for self-hosted knots, clone URLs may be different based
+
on your setup.
+
</p>
+
</section>
+
{{ end }}
+163
appview/pages/templates/repo/fragments/diff.html
···
+
{{ define "repo/fragments/diff" }}
+
{{ $repo := index . 0 }}
+
{{ $diff := index . 1 }}
+
{{ $commit := $diff.Commit }}
+
{{ $stat := $diff.Stat }}
+
{{ $fileTree := fileTree $diff.ChangedFiles }}
+
{{ $diff := $diff.Diff }}
+
+
{{ $this := $commit.This }}
+
{{ $parent := $commit.Parent }}
+
+
<section class="mt-6 p-6 border border-gray-200 dark:border-gray-700 w-full mx-auto rounded bg-white dark:bg-gray-800 drop-shadow-sm">
+
<div class="diff-stat">
+
<div class="flex gap-2 items-center">
+
<strong class="text-sm uppercase dark:text-gray-200">Changed files</strong>
+
{{ block "statPill" $stat }} {{ end }}
+
</div>
+
{{ block "fileTree" $fileTree }} {{ end }}
+
</div>
+
</section>
+
+
{{ $last := sub (len $diff) 1 }}
+
{{ range $idx, $hunk := $diff }}
+
{{ with $hunk }}
+
<section class="mt-6 border border-gray-200 dark:border-gray-700 w-full mx-auto rounded bg-white dark:bg-gray-800 drop-shadow-sm">
+
<div id="file-{{ .Name.New }}">
+
<div id="diff-file">
+
<details open>
+
<summary class="list-none cursor-pointer sticky top-0">
+
<div id="diff-file-header" class="rounded cursor-pointer bg-white dark:bg-gray-800 flex justify-between">
+
<div id="left-side-items" class="p-2 flex gap-2 items-center overflow-x-auto">
+
<div class="flex gap-1 items-center">
+
{{ $markerstyle := "diff-type p-1 mr-1 font-mono text-sm rounded select-none" }}
+
{{ if .IsNew }}
+
<span class="bg-green-100 text-green-700 dark:bg-green-800/50 dark:text-green-400 {{ $markerstyle }}">ADDED</span>
+
{{ else if .IsDelete }}
+
<span class="bg-red-100 text-red-700 dark:bg-red-800/50 dark:text-red-400 {{ $markerstyle }}">DELETED</span>
+
{{ else if .IsCopy }}
+
<span class="bg-gray-100 text-gray-700 dark:bg-gray-700 dark:text-gray-300 {{ $markerstyle }}">COPIED</span>
+
{{ else if .IsRename }}
+
<span class="bg-gray-100 text-gray-700 dark:bg-gray-700 dark:text-gray-300 {{ $markerstyle }}">RENAMED</span>
+
{{ else }}
+
<span class="bg-gray-100 text-gray-700 dark:bg-gray-700 dark:text-gray-300 {{ $markerstyle }}">MODIFIED</span>
+
{{ end }}
+
+
{{ block "statPill" .Stats }} {{ end }}
+
</div>
+
+
<div class="flex gap-2 items-center overflow-x-auto">
+
{{ if .IsDelete }}
+
<a class="dark:text-white whitespace-nowrap overflow-x-auto" {{if $this }}href="/{{ $repo }}/blob/{{ $this }}/{{ .Name.Old }}"{{end}}>
+
{{ .Name.Old }}
+
</a>
+
{{ else if (or .IsCopy .IsRename) }}
+
<a class="dark:text-white whitespace-nowrap overflow-x-auto" {{if $parent}}href="/{{ $repo }}/blob/{{ $parent }}/{{ .Name.Old }}"{{end}}>
+
{{ .Name.Old }}
+
</a>
+
{{ i "arrow-right" "w-4 h-4" }}
+
<a class="dark:text-white whitespace-nowrap overflow-x-auto" {{if $this}}href="/{{ $repo }}/blob/{{ $this }}/{{ .Name.New }}"{{end}}>
+
{{ .Name.New }}
+
</a>
+
{{ else }}
+
<a class="dark:text-white whitespace-nowrap overflow-x-auto" {{if $this}}href="/{{ $repo }}/blob/{{ $this }}/{{ .Name.New }}"{{end}}>
+
{{ .Name.New }}
+
</a>
+
{{ end }}
+
</div>
+
</div>
+
+
{{ $iconstyle := "p-1 mx-1 hover:bg-gray-100 dark:hover:bg-gray-700 rounded" }}
+
<div id="right-side-items" class="p-2 flex items-center">
+
<a title="top of file" href="#file-{{ .Name.New }}" class="{{ $iconstyle }}">{{ i "arrow-up-to-line" "w-4 h-4" }}</a>
+
{{ if gt $idx 0 }}
+
{{ $prev := index $diff (sub $idx 1) }}
+
<a title="previous file" href="#file-{{ $prev.Name.New }}" class="{{ $iconstyle }}">{{ i "arrow-up" "w-4 h-4" }}</a>
+
{{ end }}
+
+
{{ if lt $idx $last }}
+
{{ $next := index $diff (add $idx 1) }}
+
<a title="next file" href="#file-{{ $next.Name.New }}" class="{{ $iconstyle }}">{{ i "arrow-down" "w-4 h-4" }}</a>
+
{{ end }}
+
</div>
+
+
</div>
+
</summary>
+
+
<div class="transition-all duration-700 ease-in-out">
+
{{ if .IsDelete }}
+
<p class="text-center text-gray-400 dark:text-gray-500 p-4">
+
This file has been deleted.
+
</p>
+
{{ else if .IsCopy }}
+
<p class="text-center text-gray-400 dark:text-gray-500 p-4">
+
This file has been copied.
+
</p>
+
{{ else if .IsBinary }}
+
<p class="text-center text-gray-400 dark:text-gray-500 p-4">
+
This is a binary file and will not be displayed.
+
</p>
+
{{ else }}
+
{{ $name := .Name.New }}
+
<pre class="overflow-x-auto"><div class="overflow-x-auto"><div class="min-w-full inline-block">{{- range .TextFragments -}}<div class="bg-gray-100 dark:bg-gray-700 text-gray-500 dark:text-gray-400 select-none text-center">&middot;&middot;&middot;</div>
+
{{- $oldStart := .OldPosition -}}
+
{{- $newStart := .NewPosition -}}
+
{{- $lineNrStyle := "min-w-[3.5rem] flex-shrink-0 select-none text-right bg-white dark:bg-gray-800 scroll-mt-10 target:border target:border-amber-500 target:rounded " -}}
+
{{- $linkStyle := "text-gray-400 dark:text-gray-500 hover:underline" -}}
+
{{- $lineNrSepStyle1 := "" -}}
+
{{- $lineNrSepStyle2 := "pr-2" -}}
+
{{- range .Lines -}}
+
{{- if eq .Op.String "+" -}}
+
<div class="bg-green-100 dark:bg-green-800/30 text-green-700 dark:text-green-400 flex min-w-full items-center">
+
<div class="{{$lineNrStyle}} {{$lineNrSepStyle1}}"><span aria-hidden="true" class="invisible">{{$newStart}}</span></div>
+
<div class="{{$lineNrStyle}} {{$lineNrSepStyle2}}" id="{{$name}}-N{{$newStart}}"><a class="{{$linkStyle}}" href="#{{$name}}-N{{$newStart}}">{{ $newStart }}</a></div>
+
<div class="w-5 flex-shrink-0 select-none text-center">{{ .Op.String }}</div>
+
<div class="px-2">{{ .Line }}</div>
+
</div>
+
{{- $newStart = add64 $newStart 1 -}}
+
{{- end -}}
+
{{- if eq .Op.String "-" -}}
+
<div class="bg-red-100 dark:bg-red-800/30 text-red-700 dark:text-red-400 flex min-w-full items-center">
+
<div class="{{$lineNrStyle}} {{$lineNrSepStyle1}}" id="{{$name}}-O{{$oldStart}}"><a class="{{$linkStyle}}" href="#{{$name}}-O{{$oldStart}}">{{ $oldStart }}</a></div>
+
<div class="{{$lineNrStyle}} {{$lineNrSepStyle2}}"><span aria-hidden="true" class="invisible">{{$oldStart}}</span></div>
+
<div class="w-5 flex-shrink-0 select-none text-center">{{ .Op.String }}</div>
+
<div class="px-2">{{ .Line }}</div>
+
</div>
+
{{- $oldStart = add64 $oldStart 1 -}}
+
{{- end -}}
+
{{- if eq .Op.String " " -}}
+
<div class="bg-white dark:bg-gray-800 text-gray-500 dark:text-gray-400 flex min-w-full items-center">
+
<div class="{{$lineNrStyle}} {{$lineNrSepStyle1}}" id="{{$name}}-O{{$oldStart}}"><a class="{{$linkStyle}}" href="#{{$name}}-O{{$oldStart}}">{{ $oldStart }}</a></div>
+
<div class="{{$lineNrStyle}} {{$lineNrSepStyle2}}" id="{{$name}}-N{{$newStart}}"><a class="{{$linkStyle}}" href="#{{$name}}-N{{$newStart}}">{{ $newStart }}</a></div>
+
<div class="w-5 flex-shrink-0 select-none text-center">{{ .Op.String }}</div>
+
<div class="px-2">{{ .Line }}</div>
+
</div>
+
{{- $newStart = add64 $newStart 1 -}}
+
{{- $oldStart = add64 $oldStart 1 -}}
+
{{- end -}}
+
{{- end -}}
+
{{- end -}}</div></div></pre>
+
{{- end -}}
+
</div>
+
+
</details>
+
+
</div>
+
</div>
+
</section>
+
{{ end }}
+
{{ end }}
+
{{ end }}
+
+
{{ define "statPill" }}
+
<div class="flex items-center font-mono text-sm">
+
{{ if and .Insertions .Deletions }}
+
<span class="rounded-l p-1 select-none bg-green-100 text-green-700 dark:bg-green-800/50 dark:text-green-400">+{{ .Insertions }}</span>
+
<span class="rounded-r p-1 select-none bg-red-100 text-red-700 dark:bg-red-800/50 dark:text-red-400">-{{ .Deletions }}</span>
+
{{ else if .Insertions }}
+
<span class="rounded p-1 select-none bg-green-100 text-green-700 dark:bg-green-800/50 dark:text-green-400">+{{ .Insertions }}</span>
+
{{ else if .Deletions }}
+
<span class="rounded p-1 select-none bg-red-100 text-red-700 dark:bg-red-800/50 dark:text-red-400">-{{ .Deletions }}</span>
+
{{ end }}
+
</div>
+
{{ end }}
+11
appview/pages/templates/repo/fragments/editRepoDescription.html
···
+
{{ define "repo/fragments/editRepoDescription" }}
+
<form hx-put="/{{ .RepoInfo.FullName }}/description" hx-target="this" hx-swap="outerHTML" class="flex flex-wrap gap-2">
+
<input type="text" class="p-1" name="description" value="{{ .RepoInfo.Description }}">
+
<button type="submit" class="btn p-1 flex items-center gap-2 no-underline text-sm">
+
{{ i "check" "w-3 h-3" }} save
+
</button>
+
<button type="button" class="btn p-1 flex items-center gap-2 no-underline text-sm" hx-get="/{{ .RepoInfo.FullName }}/description" >
+
{{ i "x" "w-3 h-3" }} cancel
+
</button>
+
</form>
+
{{ end }}
+27
appview/pages/templates/repo/fragments/filetree.html
···
+
{{ define "fileTree" }}
+
{{ if and .Name .IsDirectory }}
+
<details open>
+
<summary class="cursor-pointer list-none pt-1">
+
<span class="inline-flex items-center gap-2 ">
+
{{ i "folder" "w-3 h-3 fill-current" }}
+
<span class="text-black dark:text-white">{{ .Name }}</span>
+
</span>
+
</summary>
+
<div class="ml-1 pl-4 border-l border-gray-200 dark:border-gray-700">
+
{{ range $child := .Children }}
+
{{ block "fileTree" $child }} {{ end }}
+
{{ end }}
+
</div>
+
</details>
+
{{ else if .Name }}
+
<div class="flex items-center gap-2 pt-1">
+
{{ i "file" "w-3 h-3" }}
+
<a href="#file-{{ .Path }}" class="text-black dark:text-white no-underline hover:underline">{{ .Name }}</a>
+
</div>
+
{{ else }}
+
{{ range $child := .Children }}
+
{{ block "fileTree" $child }} {{ end }}
+
{{ end }}
+
{{ end }}
+
{{ end }}
+
+143
appview/pages/templates/repo/fragments/interdiff.html
···
+
{{ define "repo/fragments/interdiff" }}
+
{{ $repo := index . 0 }}
+
{{ $x := index . 1 }}
+
{{ $fileTree := fileTree $x.AffectedFiles }}
+
{{ $diff := $x.Files }}
+
+
<section class="mt-6 p-6 border border-gray-200 dark:border-gray-700 w-full mx-auto rounded bg-white dark:bg-gray-800 drop-shadow-sm">
+
<div class="diff-stat">
+
<div class="flex gap-2 items-center">
+
<strong class="text-sm uppercase dark:text-gray-200">files</strong>
+
</div>
+
{{ block "fileTree" $fileTree }} {{ end }}
+
</div>
+
</section>
+
+
{{ $last := sub (len $diff) 1 }}
+
{{ range $idx, $hunk := $diff }}
+
{{ with $hunk }}
+
<section class="mt-6 border border-gray-200 dark:border-gray-700 w-full mx-auto rounded bg-white dark:bg-gray-800 drop-shadow-sm">
+
<div id="file-{{ .Name }}">
+
<div id="diff-file">
+
<details {{ if not (.Status.IsOnlyInOne) }}open{{end}}>
+
<summary class="list-none cursor-pointer sticky top-0">
+
<div id="diff-file-header" class="rounded cursor-pointer bg-white dark:bg-gray-800 flex justify-between">
+
<div id="left-side-items" class="p-2 flex gap-2 items-center overflow-x-auto">
+
<div class="flex gap-1 items-center" style="direction: ltr;">
+
{{ $markerstyle := "diff-type p-1 mr-1 font-mono text-sm rounded select-none" }}
+
{{ if .Status.IsOk }}
+
<span class="bg-gray-100 text-gray-700 dark:bg-gray-700 dark:text-gray-300 {{ $markerstyle }}">CHANGED</span>
+
{{ else if .Status.IsUnchanged }}
+
<span class="bg-gray-100 text-gray-700 dark:bg-gray-700 dark:text-gray-300 {{ $markerstyle }}">UNCHANGED</span>
+
{{ else if .Status.IsOnlyInOne }}
+
<span class="bg-red-100 text-red-700 dark:bg-red-800/50 dark:text-red-400 {{ $markerstyle }}">REVERTED</span>
+
{{ else if .Status.IsOnlyInTwo }}
+
<span class="bg-green-100 text-green-700 dark:bg-green-800/50 dark:text-green-400 {{ $markerstyle }}">NEW</span>
+
{{ else if .Status.IsRebased }}
+
<span class="bg-amber-100 text-amber-700 dark:bg-amber-800/50 dark:text-amber-400 {{ $markerstyle }}">REBASED</span>
+
{{ else }}
+
<span class="bg-red-100 text-red-700 dark:bg-red-800/50 dark:text-red-400 {{ $markerstyle }}">ERROR</span>
+
{{ end }}
+
</div>
+
+
<div class="flex gap-2 items-center overflow-x-auto" style="direction: rtl;">
+
<a class="dark:text-white whitespace-nowrap overflow-x-auto" href="">
+
{{ .Name }}
+
</a>
+
</div>
+
</div>
+
+
{{ $iconstyle := "p-1 mx-1 hover:bg-gray-100 dark:hover:bg-gray-700 rounded" }}
+
<div id="right-side-items" class="p-2 flex items-center">
+
<a title="top of file" href="#file-{{ .Name }}" class="{{ $iconstyle }}">{{ i "arrow-up-to-line" "w-4 h-4" }}</a>
+
{{ if gt $idx 0 }}
+
{{ $prev := index $diff (sub $idx 1) }}
+
<a title="previous file" href="#file-{{ $prev.Name }}" class="{{ $iconstyle }}">{{ i "arrow-up" "w-4 h-4" }}</a>
+
{{ end }}
+
+
{{ if lt $idx $last }}
+
{{ $next := index $diff (add $idx 1) }}
+
<a title="next file" href="#file-{{ $next.Name }}" class="{{ $iconstyle }}">{{ i "arrow-down" "w-4 h-4" }}</a>
+
{{ end }}
+
</div>
+
+
</div>
+
</summary>
+
+
<div class="transition-all duration-700 ease-in-out">
+
{{ if .Status.IsUnchanged }}
+
<p class="text-center text-gray-400 dark:text-gray-500 p-4">
+
This file has not been changed.
+
</p>
+
{{ else if .Status.IsRebased }}
+
<p class="text-center text-gray-400 dark:text-gray-500 p-4">
+
This patch was likely rebased, as context lines do not match.
+
</p>
+
{{ else if .Status.IsError }}
+
<p class="text-center text-gray-400 dark:text-gray-500 p-4">
+
Failed to calculate interdiff for this file.
+
</p>
+
{{ else }}
+
{{ $name := .Name }}
+
<pre class="overflow-x-auto"><div class="overflow-x-auto"><div class="min-w-full inline-block">{{- range .TextFragments -}}<div class="bg-gray-100 dark:bg-gray-700 text-gray-500 dark:text-gray-400 select-none text-center">&middot;&middot;&middot;</div>
+
{{- $oldStart := .OldPosition -}}
+
{{- $newStart := .NewPosition -}}
+
{{- $lineNrStyle := "min-w-[3.5rem] flex-shrink-0 select-none text-right bg-white dark:bg-gray-800 scroll-mt-10 target:border target:border-amber-500 target:rounded " -}}
+
{{- $linkStyle := "text-gray-400 dark:text-gray-500 hover:underline" -}}
+
{{- $lineNrSepStyle1 := "" -}}
+
{{- $lineNrSepStyle2 := "pr-2" -}}
+
{{- range .Lines -}}
+
{{- if eq .Op.String "+" -}}
+
<div class="bg-green-100 dark:bg-green-800/30 text-green-700 dark:text-green-400 flex min-w-full items-center">
+
<div class="{{$lineNrStyle}} {{$lineNrSepStyle1}}"><span aria-hidden="true" class="invisible">{{$newStart}}</span></div>
+
<div class="{{$lineNrStyle}} {{$lineNrSepStyle2}}" id="{{$name}}-N{{$newStart}}"><a class="{{$linkStyle}}" href="#{{$name}}-N{{$newStart}}">{{ $newStart }}</a></div>
+
<div class="w-5 flex-shrink-0 select-none text-center">{{ .Op.String }}</div>
+
<div class="px-2">{{ .Line }}</div>
+
</div>
+
{{- $newStart = add64 $newStart 1 -}}
+
{{- end -}}
+
{{- if eq .Op.String "-" -}}
+
<div class="bg-red-100 dark:bg-red-800/30 text-red-700 dark:text-red-400 flex min-w-full items-center">
+
<div class="{{$lineNrStyle}} {{$lineNrSepStyle1}}" id="{{$name}}-O{{$oldStart}}"><a class="{{$linkStyle}}" href="#{{$name}}-O{{$oldStart}}">{{ $oldStart }}</a></div>
+
<div class="{{$lineNrStyle}} {{$lineNrSepStyle2}}"><span aria-hidden="true" class="invisible">{{$oldStart}}</span></div>
+
<div class="w-5 flex-shrink-0 select-none text-center">{{ .Op.String }}</div>
+
<div class="px-2">{{ .Line }}</div>
+
</div>
+
{{- $oldStart = add64 $oldStart 1 -}}
+
{{- end -}}
+
{{- if eq .Op.String " " -}}
+
<div class="bg-white dark:bg-gray-800 text-gray-500 dark:text-gray-400 flex min-w-full items-center">
+
<div class="{{$lineNrStyle}} {{$lineNrSepStyle1}}" id="{{$name}}-O{{$oldStart}}"><a class="{{$linkStyle}}" href="#{{$name}}-O{{$oldStart}}">{{ $oldStart }}</a></div>
+
<div class="{{$lineNrStyle}} {{$lineNrSepStyle2}}" id="{{$name}}-N{{$newStart}}"><a class="{{$linkStyle}}" href="#{{$name}}-N{{$newStart}}">{{ $newStart }}</a></div>
+
<div class="w-5 flex-shrink-0 select-none text-center">{{ .Op.String }}</div>
+
<div class="px-2">{{ .Line }}</div>
+
</div>
+
{{- $newStart = add64 $newStart 1 -}}
+
{{- $oldStart = add64 $oldStart 1 -}}
+
{{- end -}}
+
{{- end -}}
+
{{- end -}}</div></div></pre>
+
{{- end -}}
+
</div>
+
+
</details>
+
+
</div>
+
</div>
+
</section>
+
{{ end }}
+
{{ end }}
+
{{ end }}
+
+
{{ define "statPill" }}
+
<div class="flex items-center font-mono text-sm">
+
{{ if and .Insertions .Deletions }}
+
<span class="rounded-l p-1 select-none bg-green-100 text-green-700 dark:bg-green-800/50 dark:text-green-400">+{{ .Insertions }}</span>
+
<span class="rounded-r p-1 select-none bg-red-100 text-red-700 dark:bg-red-800/50 dark:text-red-400">-{{ .Deletions }}</span>
+
{{ else if .Insertions }}
+
<span class="rounded p-1 select-none bg-green-100 text-green-700 dark:bg-green-800/50 dark:text-green-400">+{{ .Insertions }}</span>
+
{{ else if .Deletions }}
+
<span class="rounded p-1 select-none bg-red-100 text-red-700 dark:bg-red-800/50 dark:text-red-400">-{{ .Deletions }}</span>
+
{{ end }}
+
</div>
+
{{ end }}
+47
appview/pages/templates/repo/fragments/repoActions.html
···
+
{{ define "repo/fragments/repoActions" }}
+
<div class="flex items-center gap-2 z-auto">
+
<button
+
id="starBtn"
+
class="btn disabled:opacity-50 disabled:cursor-not-allowed"
+
{{ if .IsStarred }}
+
hx-delete="/star?subject={{ .RepoAt }}&countHint={{ .Stats.StarCount }}"
+
{{ else }}
+
hx-post="/star?subject={{ .RepoAt }}&countHint={{ .Stats.StarCount }}"
+
{{ end }}
+
+
hx-trigger="click"
+
hx-target="#starBtn"
+
hx-swap="outerHTML"
+
hx-disabled-elt="#starBtn"
+
>
+
<div class="flex gap-2 items-center">
+
{{ if .IsStarred }}
+
{{ i "star" "w-4 h-4 fill-current" }}
+
{{ else }}
+
{{ i "star" "w-4 h-4" }}
+
{{ end }}
+
<span class="text-sm">
+
{{ .Stats.StarCount }}
+
</span>
+
</div>
+
</button>
+
{{ if .DisableFork }}
+
<button
+
class="btn text-sm no-underline hover:no-underline flex items-center gap-2 disabled:opacity-50 disabled:cursor-not-allowed"
+
disabled
+
title="Empty repositories cannot be forked"
+
>
+
{{ i "git-fork" "w-4 h-4" }}
+
fork
+
</button>
+
{{ else }}
+
<a
+
class="btn text-sm no-underline hover:no-underline flex items-center gap-2"
+
href="/{{ .FullName }}/fork"
+
>
+
{{ i "git-fork" "w-4 h-4" }}
+
fork
+
</a>
+
{{ end }}
+
</div>
+
{{ end }}
+15
appview/pages/templates/repo/fragments/repoDescription.html
···
+
{{ define "repo/fragments/repoDescription" }}
+
<span id="repo-description" class="flex flex-wrap items-center gap-2 text-sm" hx-target="this" hx-swap="outerHTML">
+
{{ if .RepoInfo.Description }}
+
{{ .RepoInfo.Description }}
+
{{ else }}
+
<span class="italic">this repo has no description</span>
+
{{ end }}
+
+
{{ if .RepoInfo.Roles.IsOwner }}
+
<button class="flex items-center gap-2 no-underline text-sm" hx-get="/{{ .RepoInfo.FullName }}/description/edit">
+
{{ i "pencil" "w-3 h-3" }}
+
</button>
+
{{ end }}
+
</span>
+
{{ end }}
+207 -172
appview/pages/templates/repo/index.html
···
{{ define "title" }}{{ .RepoInfo.FullName }} at {{ .Ref }}{{ end }}
-
{{ define "extrameta" }}
-
<meta name="vcs:clone" content="https://tangled.sh/{{ .RepoInfo.FullName }}"/>
-
<meta name="forge:summary" content="https://tangled.sh/{{ .RepoInfo.FullName }}">
-
<meta name="forge:dir" content="https://tangled.sh/{{ .RepoInfo.FullName }}/tree/{ref}/{path}">
-
<meta name="forge:file" content="https://tangled.sh/{{ .RepoInfo.FullName }}/blob/{ref}/{path}">
-
<meta name="forge:line" content="https://tangled.sh/{{ .RepoInfo.FullName }}/blob/{ref}/{path}#L{line}">
-
<meta name="go-import" content="tangled.sh/{{ .RepoInfo.FullNameWithoutAt }} git https://tangled.sh/{{ .RepoInfo.FullName }}">
+
<meta
+
name="vcs:clone"
+
content="https://tangled.sh/{{ .RepoInfo.FullName }}"
+
/>
+
<meta
+
name="forge:summary"
+
content="https://tangled.sh/{{ .RepoInfo.FullName }}"
+
/>
+
<meta
+
name="forge:dir"
+
content="https://tangled.sh/{{ .RepoInfo.FullName }}/tree/{ref}/{path}"
+
/>
+
<meta
+
name="forge:file"
+
content="https://tangled.sh/{{ .RepoInfo.FullName }}/blob/{ref}/{path}"
+
/>
+
<meta
+
name="forge:line"
+
content="https://tangled.sh/{{ .RepoInfo.FullName }}/blob/{ref}/{path}#L{line}"
+
/>
+
<meta
+
name="go-import"
+
content="tangled.sh/{{ .RepoInfo.FullNameWithoutAt }} git https://tangled.sh/{{ .RepoInfo.FullName }}"
+
/>
{{ end }}
-
{{ define "repoContent" }}
<main>
-
{{ block "branchSelector" . }} {{ end }}
+
{{ block "branchSelector" . }}{{ end }}
<div class="grid grid-cols-1 md:grid-cols-2 gap-2">
-
{{ block "fileTree" . }} {{ end }}
-
{{ block "commitLog" . }} {{ end }}
+
{{ block "fileTree" . }}{{ end }}
+
{{ block "commitLog" . }}{{ end }}
</div>
</main>
{{ end }}
{{ define "branchSelector" }}
-
<div class="flex justify-between pb-5">
-
<select
-
onchange="window.location.href = '/{{ .RepoInfo.FullName }}/tree/' + encodeURIComponent(this.value)"
-
class="p-1 border border-gray-200 bg-white dark:bg-gray-800 dark:text-white dark:border-gray-700"
-
>
-
<optgroup label="branches" class="bold text-sm">
-
{{ range .Branches }}
-
<option
-
value="{{ .Reference.Name }}"
-
class="py-1"
-
{{ if eq .Reference.Name $.Ref }}
-
selected
-
{{ end }}
-
>
-
{{ .Reference.Name }}
-
</option>
-
{{ end }}
-
</optgroup>
-
<optgroup label="tags" class="bold text-sm">
-
{{ range .Tags }}
-
<option
-
value="{{ .Reference.Name }}"
-
class="py-1"
-
{{ if eq .Reference.Name $.Ref }}
-
selected
-
{{ end }}
-
>
-
{{ .Reference.Name }}
-
</option>
-
{{ else }}
-
<option class="py-1" disabled>no tags found</option>
-
{{ end }}
-
</optgroup>
-
</select>
-
<a
-
href="/{{ .RepoInfo.FullName }}/commits/{{ .Ref | urlquery }}"
-
class="ml-2 no-underline flex items-center gap-2 text-sm uppercase font-bold dark:text-white"
-
>
-
{{ i "logs" "w-4 h-4" }}
-
{{ .TotalCommits }}
-
{{ if eq .TotalCommits 1 }}commit{{ else }}commits{{ end }}
-
</a>
-
</div>
+
<div class="flex justify-between pb-5">
+
<select
+
onchange="window.location.href = '/{{ .RepoInfo.FullName }}/tree/' + encodeURIComponent(this.value)"
+
class="p-1 border border-gray-200 bg-white dark:bg-gray-800 dark:text-white dark:border-gray-700"
+
>
+
<optgroup label="branches" class="bold text-sm">
+
{{ range .Branches }}
+
<option
+
value="{{ .Reference.Name }}"
+
class="py-1"
+
{{ if eq .Reference.Name $.Ref }}
+
selected
+
{{ end }}
+
>
+
{{ .Reference.Name }}
+
</option>
+
{{ end }}
+
</optgroup>
+
<optgroup label="tags" class="bold text-sm">
+
{{ range .Tags }}
+
<option
+
value="{{ .Reference.Name }}"
+
class="py-1"
+
{{ if eq .Reference.Name $.Ref }}
+
selected
+
{{ end }}
+
>
+
{{ .Reference.Name }}
+
</option>
+
{{ else }}
+
<option class="py-1" disabled>no tags found</option>
+
{{ end }}
+
</optgroup>
+
</select>
+
<a
+
href="/{{ .RepoInfo.FullName }}/commits/{{ .Ref | urlquery }}"
+
class="ml-2 no-underline flex items-center gap-2 text-sm uppercase font-bold dark:text-white"
+
>
+
{{ i "logs" "w-4 h-4" }}
+
{{ .TotalCommits }}
+
{{ if eq .TotalCommits 1 }}commit{{ else }}commits{{ end }}
+
</a>
+
</div>
{{ end }}
{{ define "fileTree" }}
-
<div id="file-tree" class="col-span-1 pr-2 md:border-r md:border-gray-200 dark:md:border-gray-700">
-
{{ $containerstyle := "py-1" }}
-
{{ $linkstyle := "no-underline hover:underline dark:text-white" }}
+
<div
+
id="file-tree"
+
class="col-span-1 pr-2 md:border-r md:border-gray-200 dark:md:border-gray-700"
+
>
+
{{ $containerstyle := "py-1" }}
+
{{ $linkstyle := "no-underline hover:underline dark:text-white" }}
-
{{ range .Files }}
-
{{ if not .IsFile }}
-
<div class="{{ $containerstyle }}">
-
<div class="flex justify-between items-center">
-
<a
-
href="/{{ $.RepoInfo.FullName }}/tree/{{ $.Ref | urlquery }}/{{ .Name }}"
-
class="{{ $linkstyle }}"
-
>
-
<div class="flex items-center gap-2">
-
{{ i "folder" "w-3 h-3 fill-current" }}
-
{{ .Name }}
-
</div>
-
</a>
+
{{ range .Files }}
+
{{ if not .IsFile }}
+
<div class="{{ $containerstyle }}">
+
<div class="flex justify-between items-center">
+
<a
+
href="/{{ $.RepoInfo.FullName }}/tree/{{ $.Ref | urlquery }}/{{ .Name }}"
+
class="{{ $linkstyle }}"
+
>
+
<div class="flex items-center gap-2">
+
{{ i "folder" "w-3 h-3 fill-current" }}
+
{{ .Name }}
+
</div>
+
</a>
-
<time class="text-xs text-gray-500 dark:text-gray-400"
-
>{{ timeFmt .LastCommit.When }}</time
-
>
+
<time class="text-xs text-gray-500 dark:text-gray-400"
+
>{{ timeFmt .LastCommit.When }}</time
+
>
+
</div>
</div>
-
</div>
+
{{ end }}
{{ end }}
-
{{ end }}
-
{{ range .Files }}
-
{{ if .IsFile }}
-
<div class="{{ $containerstyle }}">
-
<div class="flex justify-between items-center">
-
<a
-
href="/{{ $.RepoInfo.FullName }}/blob/{{ $.Ref | urlquery }}/{{ .Name }}"
-
class="{{ $linkstyle }}"
-
>
-
<div class="flex items-center gap-2">
-
{{ i "file" "w-3 h-3" }}{{ .Name }}
-
</div>
-
</a>
+
{{ range .Files }}
+
{{ if .IsFile }}
+
<div class="{{ $containerstyle }}">
+
<div class="flex justify-between items-center">
+
<a
+
href="/{{ $.RepoInfo.FullName }}/blob/{{ $.Ref | urlquery }}/{{ .Name }}"
+
class="{{ $linkstyle }}"
+
>
+
<div class="flex items-center gap-2">
+
{{ i "file" "w-3 h-3" }}{{ .Name }}
+
</div>
+
</a>
-
<time class="text-xs text-gray-500 dark:text-gray-400"
-
>{{ timeFmt .LastCommit.When }}</time
-
>
+
<time class="text-xs text-gray-500 dark:text-gray-400"
+
>{{ timeFmt .LastCommit.When }}</time
+
>
+
</div>
</div>
-
</div>
+
{{ end }}
{{ end }}
-
{{ end }}
-
</div>
+
</div>
{{ end }}
-
{{ define "commitLog" }}
-
<div id="commit-log" class="hidden md:block md:col-span-1">
-
{{ range .Commits }}
-
<div class="relative px-2 pb-8">
-
<div id="commit-message">
-
{{ $messageParts := splitN .Message "\n\n" 2 }}
-
<div class="text-base cursor-pointer">
-
<div>
-
<div>
-
<a
-
href="/{{ $.RepoInfo.FullName }}/commit/{{ .Hash.String }}"
-
class="inline no-underline hover:underline dark:text-white"
-
>{{ index $messageParts 0 }}</a
-
>
-
{{ if gt (len $messageParts) 1 }}
+
<div id="commit-log" class="hidden md:block md:col-span-1">
+
{{ range .Commits }}
+
<div class="relative px-2 pb-8">
+
<div id="commit-message">
+
{{ $messageParts := splitN .Message "\n\n" 2 }}
+
<div class="text-base cursor-pointer">
+
<div>
+
<div>
+
<a
+
href="/{{ $.RepoInfo.FullName }}/commit/{{ .Hash.String }}"
+
class="inline no-underline hover:underline dark:text-white"
+
>{{ index $messageParts 0 }}</a
+
>
+
{{ if gt (len $messageParts) 1 }}
-
<button
-
class="py-1/2 px-1 bg-gray-200 hover:bg-gray-400 rounded dark:bg-gray-700 dark:hover:bg-gray-600"
-
hx-on:click="this.parentElement.nextElementSibling.classList.toggle('hidden')"
-
>
-
{{ i "ellipsis" "w-3 h-3" }}
-
</button>
-
{{ end }}
-
</div>
-
{{ if gt (len $messageParts) 1 }}
-
<p
-
class="hidden mt-1 text-sm cursor-text pb-2 dark:text-gray-300"
-
>
-
{{ nl2br (unwrapText (index $messageParts 1)) }}
-
</p>
-
{{ end }}
-
</div>
-
</div>
-
</div>
+
<button
+
class="py-1/2 px-1 bg-gray-200 hover:bg-gray-400 rounded dark:bg-gray-700 dark:hover:bg-gray-600"
+
hx-on:click="this.parentElement.nextElementSibling.classList.toggle('hidden')"
+
>
+
{{ i "ellipsis" "w-3 h-3" }}
+
</button>
+
{{ end }}
+
</div>
+
{{ if gt (len $messageParts) 1 }}
+
<p
+
class="hidden mt-1 text-sm cursor-text pb-2 dark:text-gray-300"
+
>
+
{{ nl2br (index $messageParts 1) }}
+
</p>
+
{{ end }}
+
</div>
+
</div>
+
</div>
-
<div class="text-xs text-gray-500 dark:text-gray-400">
-
<span class="font-mono">
-
<a
-
href="/{{ $.RepoInfo.FullName }}/commit/{{ .Hash.String }}"
-
class="text-gray-500 dark:text-gray-400 no-underline hover:underline"
-
>{{ slice .Hash.String 0 8 }}</a
-
>
-
</span>
-
<span
-
class="mx-2 before:content-['ยท'] before:select-none"
-
></span>
-
<span>
-
{{ $didOrHandle := index $.EmailToDidOrHandle .Author.Email }}
-
<a
-
href="{{ if $didOrHandle }}/{{ $didOrHandle }}{{ else }}mailto:{{ .Author.Email }}{{ end }}"
-
class="text-gray-500 dark:text-gray-400 no-underline hover:underline"
-
>{{ if $didOrHandle }}{{ $didOrHandle }}{{ else }}{{ .Author.Name }}{{ end }}</a
-
>
-
</span>
-
<div
-
class="inline-block px-1 select-none after:content-['ยท']"
-
></div>
-
<span>{{ timeFmt .Author.When }}</span>
-
{{ $tagsForCommit := index $.TagMap .Hash.String }}
-
{{ if gt (len $tagsForCommit) 0 }}
+
<div class="text-xs text-gray-500 dark:text-gray-400">
+
<span class="font-mono">
+
<a
+
href="/{{ $.RepoInfo.FullName }}/commit/{{ .Hash.String }}"
+
class="text-gray-500 dark:text-gray-400 no-underline hover:underline"
+
>{{ slice .Hash.String 0 8 }}</a></span>
+
<span
+
class="mx-2 before:content-['ยท'] before:select-none"
+
></span>
+
<span>
+
{{ $didOrHandle := index $.EmailToDidOrHandle .Author.Email }}
+
<a
+
href="{{ if $didOrHandle }}
+
/{{ $didOrHandle }}
+
{{ else }}
+
mailto:{{ .Author.Email }}
+
{{ end }}"
+
class="text-gray-500 dark:text-gray-400 no-underline hover:underline"
+
>{{ if $didOrHandle }}
+
{{ $didOrHandle }}
+
{{ else }}
+
{{ .Author.Name }}
+
{{ end }}</a
+
>
+
</span>
<div
class="inline-block px-1 select-none after:content-['ยท']"
></div>
-
{{ end }}
-
{{ range $tagsForCommit }}
-
<span class="text-xs rounded bg-gray-100 dark:bg-gray-700 text-black dark:text-white font-mono px-2 mx-1/2 inline-flex items-center">
-
{{ . }}
-
</span>
-
{{ end }}
-
</div>
-
</div>
-
{{ end }}
-
</div>
+
<span>{{ timeFmt .Author.When }}</span>
+
{{ $tagsForCommit := index $.TagMap .Hash.String }}
+
{{ if gt (len $tagsForCommit) 0 }}
+
<div
+
class="inline-block px-1 select-none after:content-['ยท']"
+
></div>
+
{{ end }}
+
{{ range $tagsForCommit }}
+
<span
+
class="text-xs rounded bg-gray-100 dark:bg-gray-700 text-black dark:text-white font-mono px-2 mx-1/2 inline-flex items-center"
+
>
+
{{ . }}
+
</span>
+
{{ end }}
+
</div>
+
</div>
+
{{ end }}
+
</div>
{{ end }}
-
{{ define "repoAfter" }}
{{- if .HTMLReadme }}
-
<section class="mt-4 p-6 rounded bg-white dark:bg-gray-800 dark:text-white w-full mx-auto overflow-auto {{ if not .Raw }} prose dark:prose-invert dark:[&_pre]:bg-gray-900 dark:[&_code]:text-gray-300 dark:[&_pre_code]:bg-gray-900 dark:[&_pre]:border dark:[&_pre]:border-gray-700 {{ end }}">
-
<article class="{{ if .Raw }}whitespace-pre{{end}}">
-
{{ if .Raw }}
-
<pre class="dark:bg-gray-900 dark:text-gray-200 dark:border dark:border-gray-700 dark:p-4 dark:rounded">{{ .HTMLReadme }}</pre>
-
{{ else }}
-
{{ .HTMLReadme }}
-
{{ end }}
-
</article>
-
</section>
+
<section
+
class="mt-4 p-6 rounded bg-white dark:bg-gray-800 dark:text-white w-full mx-auto overflow-auto {{ if not .Raw }}
+
prose dark:prose-invert dark:[&_pre]:bg-gray-900
+
dark:[&_code]:text-gray-300 dark:[&_pre_code]:bg-gray-900
+
dark:[&_pre]:border dark:[&_pre]:border-gray-700
+
{{ end }}"
+
>
+
<article class="{{ if .Raw }}whitespace-pre{{ end }}">
+
{{ if .Raw }}
+
<pre
+
class="dark:bg-gray-900 dark:text-gray-200 dark:border dark:border-gray-700 dark:p-4 dark:rounded"
+
>
+
{{ .HTMLReadme }}</pre
+
>
+
{{ else }}
+
{{ .HTMLReadme }}
+
{{ end }}
+
</article>
+
</section>
{{- end -}}
-
{{ template "fragments/cloneInstructions" . }}
+
{{ template "repo/fragments/cloneInstructions" . }}
{{ end }}
+52
appview/pages/templates/repo/issues/fragments/editIssueComment.html
···
+
{{ define "repo/issues/fragments/editIssueComment" }}
+
{{ with .Comment }}
+
<div id="comment-container-{{.CommentId}}">
+
<div class="flex items-center gap-2 mb-2 text-gray-500 text-sm">
+
{{ $owner := didOrHandle $.LoggedInUser.Did $.LoggedInUser.Handle }}
+
<a href="/{{ $owner }}" class="no-underline hover:underline">{{ $owner }}</a>
+
+
<!-- show user "hats" -->
+
{{ $isIssueAuthor := eq .OwnerDid $.Issue.OwnerDid }}
+
{{ if $isIssueAuthor }}
+
<span class="before:content-['ยท']"></span>
+
<span class="rounded bg-gray-100 text-black font-mono px-2 mx-1/2 inline-flex items-center">
+
author
+
</span>
+
{{ end }}
+
+
<span class="before:content-['ยท']"></span>
+
<a
+
href="#{{ .CommentId }}"
+
class="text-gray-500 hover:text-gray-500 hover:underline no-underline"
+
id="{{ .CommentId }}">
+
{{ .Created | timeFmt }}
+
</a>
+
+
<button
+
class="btn px-2 py-1 flex items-center gap-2 text-sm"
+
hx-post="/{{ $.RepoInfo.FullName }}/issues/{{ .Issue }}/comment/{{ .CommentId }}/edit"
+
hx-include="#edit-textarea-{{ .CommentId }}"
+
hx-target="#comment-container-{{ .CommentId }}"
+
hx-swap="outerHTML">
+
{{ i "check" "w-4 h-4" }}
+
</button>
+
<button
+
class="btn px-2 py-1 flex items-center gap-2 text-sm"
+
hx-get="/{{ $.RepoInfo.FullName }}/issues/{{ .Issue }}/comment/{{ .CommentId }}/"
+
hx-target="#comment-container-{{ .CommentId }}"
+
hx-swap="outerHTML">
+
{{ i "x" "w-4 h-4" }}
+
</button>
+
<span id="comment-{{.CommentId}}-status"></span>
+
</div>
+
+
<div>
+
<textarea
+
id="edit-textarea-{{ .CommentId }}"
+
name="body"
+
class="w-full p-2 border rounded min-h-[100px]">{{ .Body }}</textarea>
+
</div>
+
</div>
+
{{ end }}
+
{{ end }}
+
+59
appview/pages/templates/repo/issues/fragments/issueComment.html
···
+
{{ define "repo/issues/fragments/issueComment" }}
+
{{ with .Comment }}
+
<div id="comment-container-{{.CommentId}}">
+
<div class="flex items-center gap-2 mb-2 text-gray-500 dark:text-gray-400 text-sm">
+
{{ $owner := index $.DidHandleMap .OwnerDid }}
+
<a href="/{{ $owner }}" class="no-underline hover:underline">{{ $owner }}</a>
+
+
<span class="before:content-['ยท']"></span>
+
<a
+
href="#{{ .CommentId }}"
+
class="text-gray-500 dark:text-gray-400 hover:text-gray-500 dark:hover:text-gray-400 hover:underline no-underline"
+
id="{{ .CommentId }}">
+
{{ if .Deleted }}
+
deleted {{ .Deleted | timeFmt }}
+
{{ else if .Edited }}
+
edited {{ .Edited | timeFmt }}
+
{{ else }}
+
{{ .Created | timeFmt }}
+
{{ end }}
+
</a>
+
+
<!-- show user "hats" -->
+
{{ $isIssueAuthor := eq .OwnerDid $.Issue.OwnerDid }}
+
{{ if $isIssueAuthor }}
+
<span class="text-xs rounded bg-gray-100 dark:bg-gray-700 text-black dark:text-white font-mono px-2 mx-1/2 inline-flex items-center">
+
author
+
</span>
+
{{ end }}
+
+
{{ $isCommentOwner := and $.LoggedInUser (eq $.LoggedInUser.Did .OwnerDid) }}
+
{{ if and $isCommentOwner (not .Deleted) }}
+
<button
+
class="btn px-2 py-1 text-sm"
+
hx-get="/{{ $.RepoInfo.FullName }}/issues/{{ .Issue }}/comment/{{ .CommentId }}/edit"
+
hx-swap="outerHTML"
+
hx-target="#comment-container-{{.CommentId}}"
+
>
+
{{ i "pencil" "w-4 h-4" }}
+
</button>
+
<button
+
class="btn px-2 py-1 text-sm text-red-500"
+
hx-delete="/{{ $.RepoInfo.FullName }}/issues/{{ .Issue }}/comment/{{ .CommentId }}/"
+
hx-confirm="Are you sure you want to delete your comment?"
+
hx-swap="outerHTML"
+
hx-target="#comment-container-{{.CommentId}}"
+
>
+
{{ i "trash-2" "w-4 h-4" }}
+
</button>
+
{{ end }}
+
+
</div>
+
{{ if not .Deleted }}
+
<div class="prose dark:prose-invert">
+
{{ .Body | markdown }}
+
</div>
+
{{ end }}
+
</div>
+
{{ end }}
+
{{ end }}
+112 -42
appview/pages/templates/repo/issues/issue.html
···
{{ end }}
{{ define "repoAfter" }}
-
{{ if gt (len .Comments) 0 }}
-
<section id="comments" class="mt-8 space-y-4 relative">
+
<section id="comments" class="my-2 mt-2 space-y-2 relative">
{{ range $index, $comment := .Comments }}
<div
id="comment-{{ .CommentId }}"
-
class="rounded bg-white px-6 py-4 relative dark:bg-gray-800">
-
{{ if eq $index 0 }}
-
<div class="absolute left-8 -top-8 w-px h-8 bg-gray-300 dark:bg-gray-700" ></div>
-
{{ else }}
-
<div class="absolute left-8 -top-4 w-px h-4 bg-gray-300 dark:bg-gray-700" ></div>
+
class="bg-white dark:bg-gray-800 rounded drop-shadow-sm py-2 px-4 relative w-full md:max-w-3/5 md:w-fit">
+
{{ if gt $index 0 }}
+
<div class="absolute left-8 -top-2 w-px h-2 bg-gray-300 dark:bg-gray-600"></div>
{{ end }}
-
-
{{ template "fragments/issueComment" (dict "RepoInfo" $.RepoInfo "LoggedInUser" $.LoggedInUser "DidHandleMap" $.DidHandleMap "Issue" $.Issue "Comment" .)}}
+
{{ template "repo/issues/fragments/issueComment" (dict "RepoInfo" $.RepoInfo "LoggedInUser" $.LoggedInUser "DidHandleMap" $.DidHandleMap "Issue" $.Issue "Comment" .)}}
</div>
{{ end }}
</section>
-
{{ end }}
{{ block "newComment" . }} {{ end }}
-
{{ $isIssueAuthor := and .LoggedInUser (eq .LoggedInUser.Did .Issue.OwnerDid) }}
-
{{ $isRepoCollaborator := .RepoInfo.Roles.IsCollaborator }}
-
{{ if or $isIssueAuthor $isRepoCollaborator }}
-
{{ $action := "close" }}
-
{{ $icon := "circle-x" }}
-
{{ $hoverColor := "red" }}
-
{{ if eq .State "closed" }}
-
{{ $action = "reopen" }}
-
{{ $icon = "circle-dot" }}
-
{{ $hoverColor = "green" }}
-
{{ end }}
-
<form
-
hx-post="/{{ .RepoInfo.FullName }}/issues/{{ .Issue.IssueId }}/{{ $action }}"
-
hx-swap="none"
-
class="mt-8"
-
>
-
<button type="submit" class="btn hover:bg-{{ $hoverColor }}-300">
-
{{ i $icon "w-4 h-4 mr-2" }}
-
<span class="text-black dark:text-gray-400">{{ $action }}</span>
-
</button>
-
<div id="issue-action" class="error"></div>
-
</form>
-
{{ end }}
{{ end }}
{{ define "newComment" }}
{{ if .LoggedInUser }}
-
<div class="bg-white rounded drop-shadow-sm py-4 px-6 relative w-full flex flex-col gap-2 mt-8 dark:bg-gray-800 dark:text-gray-400">
-
<div class="absolute left-8 -top-8 w-px h-8 bg-gray-300 dark:bg-gray-700" ></div>
-
<div class="text-sm text-gray-500 dark:text-gray-400">
+
<form
+
id="comment-form"
+
hx-post="/{{ .RepoInfo.FullName }}/issues/{{ .Issue.IssueId }}/comment"
+
hx-on::after-request="if(event.detail.successful) this.reset()"
+
>
+
<div class="bg-white dark:bg-gray-800 rounded drop-shadow-sm py-4 px-4 relative w-full md:w-3/5">
+
<div class="text-sm pb-2 text-gray-500 dark:text-gray-400">
{{ didOrHandle .LoggedInUser.Did .LoggedInUser.Handle }}
</div>
-
<form hx-post="/{{ .RepoInfo.FullName }}/issues/{{ .Issue.IssueId }}/comment">
<textarea
+
id="comment-textarea"
name="body"
class="w-full p-2 rounded border border-gray-200 dark:border-gray-700"
-
placeholder="Add to the discussion..."
+
placeholder="Add to the discussion. Markdown is supported."
+
onkeyup="updateCommentForm()"
></textarea>
-
<button type="submit" class="btn mt-2">comment</button>
<div id="issue-comment"></div>
-
</form>
+
<div id="issue-action" class="error"></div>
</div>
+
+
<div class="flex gap-2 mt-2">
+
<button
+
id="comment-button"
+
hx-post="/{{ .RepoInfo.FullName }}/issues/{{ .Issue.IssueId }}/comment"
+
type="submit"
+
hx-disabled-elt="#comment-button"
+
class="btn p-2 flex items-center gap-2 no-underline hover:no-underline"
+
disabled
+
>
+
{{ i "message-square-plus" "w-4 h-4" }}
+
comment
+
</button>
+
+
{{ $isIssueAuthor := and .LoggedInUser (eq .LoggedInUser.Did .Issue.OwnerDid) }}
+
{{ $isRepoCollaborator := .RepoInfo.Roles.IsCollaborator }}
+
{{ if and (or $isIssueAuthor $isRepoCollaborator) (eq .State "open") }}
+
<button
+
id="close-button"
+
type="button"
+
class="btn flex items-center gap-2"
+
hx-trigger="click"
+
>
+
{{ i "ban" "w-4 h-4" }}
+
close
+
</button>
+
<div
+
id="close-with-comment"
+
hx-post="/{{ .RepoInfo.FullName }}/issues/{{ .Issue.IssueId }}/comment"
+
hx-trigger="click from:#close-button"
+
hx-disabled-elt="#close-with-comment"
+
hx-target="#issue-comment"
+
hx-vals="js:{body: document.getElementById('comment-textarea').value.trim() !== '' ? document.getElementById('comment-textarea').value : ''}"
+
hx-swap="none"
+
>
+
</div>
+
<div
+
id="close-issue"
+
hx-disabled-elt="#close-issue"
+
hx-post="/{{ .RepoInfo.FullName }}/issues/{{ .Issue.IssueId }}/close"
+
hx-trigger="click from:#close-button"
+
hx-target="#issue-action"
+
hx-swap="none"
+
>
+
</div>
+
<script>
+
document.addEventListener('htmx:configRequest', function(evt) {
+
if (evt.target.id === 'close-with-comment') {
+
const commentText = document.getElementById('comment-textarea').value.trim();
+
if (commentText === '') {
+
evt.detail.parameters = {};
+
evt.preventDefault();
+
}
+
}
+
});
+
</script>
+
{{ else if and (or $isIssueAuthor $isRepoCollaborator) (eq .State "closed") }}
+
<button
+
type="button"
+
class="btn flex items-center gap-2"
+
hx-post="/{{ .RepoInfo.FullName }}/issues/{{ .Issue.IssueId }}/reopen"
+
hx-swap="none"
+
>
+
{{ i "refresh-ccw-dot" "w-4 h-4" }}
+
reopen
+
</button>
+
{{ end }}
+
+
<script>
+
function updateCommentForm() {
+
const textarea = document.getElementById('comment-textarea');
+
const commentButton = document.getElementById('comment-button');
+
const closeButton = document.getElementById('close-button');
+
+
if (textarea.value.trim() !== '') {
+
commentButton.removeAttribute('disabled');
+
} else {
+
commentButton.setAttribute('disabled', '');
+
}
+
+
if (closeButton) {
+
if (textarea.value.trim() !== '') {
+
closeButton.innerHTML = '{{ i "ban" "w-4 h-4" }} close with comment';
+
} else {
+
closeButton.innerHTML = '{{ i "ban" "w-4 h-4" }} close';
+
}
+
}
+
}
+
+
document.addEventListener('DOMContentLoaded', function() {
+
updateCommentForm();
+
});
+
</script>
+
</div>
+
</form>
{{ else }}
-
<div class="bg-white dark:bg-gray-800 dark:text-gray-400 rounded drop-shadow-sm px-6 py-4 mt-8">
-
<div class="absolute left-8 -top-8 w-px h-8 bg-gray-300 dark:bg-gray-700" ></div>
+
<div class="bg-white dark:bg-gray-800 rounded drop-shadow-sm py-4 px-4 relative w-fit">
<a href="/login" class="underline">login</a> to join the discussion
</div>
{{ end }}
+41 -3
appview/pages/templates/repo/issues/issues.html
···
<div class="flex justify-between items-center">
<p>
filtering
-
<select class="border px-1 bg-white border-gray-200 dark:bg-gray-800 dark:border-gray-700" onchange="window.location.href = '/{{ .RepoInfo.FullName }}/issues?state=' + this.value">
+
<select class="border p-1 bg-white border-gray-200 dark:bg-gray-800 dark:border-gray-700" onchange="window.location.href = '/{{ .RepoInfo.FullName }}/issues?state=' + this.value">
<option value="open" {{ if .FilteringByOpen }}selected{{ end }}>open ({{ .RepoInfo.Stats.IssueCount.Open }})</option>
<option value="closed" {{ if not .FilteringByOpen }}selected{{ end }}>closed ({{ .RepoInfo.Stats.IssueCount.Closed }})</option>
</select>
···
<a
href="/{{ .RepoInfo.FullName }}/issues/new"
class="btn text-sm flex items-center gap-2 no-underline hover:no-underline">
-
{{ i "plus" "w-4 h-4" }}
-
<span>new issue</span>
+
{{ i "circle-plus" "w-4 h-4" }}
+
<span>new</span>
</a>
</div>
<div class="error" id="issues"></div>
···
</p>
</div>
{{ end }}
+
</div>
+
+
{{ block "pagination" . }} {{ end }}
+
+
{{ end }}
+
+
{{ define "pagination" }}
+
<div class="flex justify-end mt-4 gap-2">
+
{{ $currentState := "closed" }}
+
{{ if .FilteringByOpen }}
+
{{ $currentState = "open" }}
+
{{ end }}
+
+
{{ if gt .Page.Offset 0 }}
+
{{ $prev := .Page.Previous }}
+
<a
+
class="btn flex items-center gap-2 no-underline hover:no-underline dark:text-white dark:hover:bg-gray-700"
+
hx-boost="true"
+
href = "/{{ $.RepoInfo.FullName }}/issues?state={{ $currentState }}&offset={{ $prev.Offset }}&limit={{ $prev.Limit }}"
+
>
+
{{ i "chevron-left" "w-4 h-4" }}
+
previous
+
</a>
+
{{ else }}
+
<div></div>
+
{{ end }}
+
+
{{ if eq (len .Issues) .Page.Limit }}
+
{{ $next := .Page.Next }}
+
<a
+
class="btn flex items-center gap-2 no-underline hover:no-underline dark:text-white dark:hover:bg-gray-700"
+
hx-boost="true"
+
href = "/{{ $.RepoInfo.FullName }}/issues?state={{ $currentState }}&offset={{ $next.Offset }}&limit={{ $next.Limit }}"
+
>
+
next
+
{{ i "chevron-right" "w-4 h-4" }}
+
</a>
+
{{ end }}
</div>
{{ end }}
+1 -1
appview/pages/templates/repo/log.html
···
<p
class="hidden mt-1 text-sm cursor-text pb-2 dark:text-gray-300"
>
-
{{ nl2br (unwrapText (index $messageParts 1)) }}
+
{{ nl2br (index $messageParts 1) }}
</p>
{{ end }}
</div>
+90
appview/pages/templates/repo/pulls/fragments/pullActions.html
···
+
{{ define "repo/pulls/fragments/pullActions" }}
+
{{ $lastIdx := sub (len .Pull.Submissions) 1 }}
+
{{ $roundNumber := .RoundNumber }}
+
+
{{ $isPushAllowed := .RepoInfo.Roles.IsPushAllowed }}
+
{{ $isMerged := .Pull.State.IsMerged }}
+
{{ $isClosed := .Pull.State.IsClosed }}
+
{{ $isOpen := .Pull.State.IsOpen }}
+
{{ $isConflicted := and .MergeCheck (or .MergeCheck.Error .MergeCheck.IsConflicted) }}
+
{{ $isPullAuthor := and .LoggedInUser (eq .LoggedInUser.Did .Pull.OwnerDid) }}
+
{{ $isLastRound := eq $roundNumber $lastIdx }}
+
{{ $isSameRepoBranch := .Pull.IsBranchBased }}
+
{{ $isUpToDate := .ResubmitCheck.No }}
+
<div class="relative w-fit">
+
<div id="actions-{{$roundNumber}}" class="flex flex-wrap gap-2">
+
<button
+
hx-get="/{{ .RepoInfo.FullName }}/pulls/{{ .Pull.PullId }}/round/{{ $roundNumber }}/comment"
+
hx-target="#actions-{{$roundNumber}}"
+
hx-swap="outerHtml"
+
class="btn p-2 flex items-center gap-2 no-underline hover:no-underline">
+
{{ i "message-square-plus" "w-4 h-4" }}
+
<span>comment</span>
+
</button>
+
{{ if and $isPushAllowed $isOpen $isLastRound }}
+
{{ $disabled := "" }}
+
{{ if $isConflicted }}
+
{{ $disabled = "disabled" }}
+
{{ end }}
+
<button
+
hx-post="/{{ .RepoInfo.FullName }}/pulls/{{ .Pull.PullId }}/merge"
+
hx-swap="none"
+
hx-confirm="Are you sure you want to merge pull #{{ .Pull.PullId }} into the `{{ .Pull.TargetBranch }}` branch?"
+
class="btn p-2 flex items-center gap-2" {{ $disabled }}>
+
{{ i "git-merge" "w-4 h-4" }}
+
<span>merge</span>
+
</button>
+
{{ end }}
+
+
{{ if and $isPullAuthor $isOpen $isLastRound }}
+
{{ $disabled := "" }}
+
{{ if $isUpToDate }}
+
{{ $disabled = "disabled" }}
+
{{ end }}
+
<button id="resubmitBtn"
+
{{ if not .Pull.IsPatchBased }}
+
hx-post="/{{ .RepoInfo.FullName }}/pulls/{{ .Pull.PullId }}/resubmit"
+
{{ else }}
+
hx-get="/{{ .RepoInfo.FullName }}/pulls/{{ .Pull.PullId }}/resubmit"
+
hx-target="#actions-{{$roundNumber}}"
+
hx-swap="outerHtml"
+
{{ end }}
+
+
hx-disabled-elt="#resubmitBtn"
+
class="btn p-2 flex items-center gap-2 disabled:opacity-50 disabled:cursor-not-allowed" {{ $disabled }}
+
+
{{ if $disabled }}
+
title="Update this branch to resubmit this pull request"
+
{{ else }}
+
title="Resubmit this pull request"
+
{{ end }}
+
>
+
{{ i "rotate-ccw" "w-4 h-4" }}
+
<span>resubmit</span>
+
</button>
+
{{ end }}
+
+
{{ if and (or $isPullAuthor $isPushAllowed) $isOpen $isLastRound }}
+
<button
+
hx-post="/{{ .RepoInfo.FullName }}/pulls/{{ .Pull.PullId }}/close"
+
hx-swap="none"
+
class="btn p-2 flex items-center gap-2">
+
{{ i "ban" "w-4 h-4" }}
+
<span>close</span>
+
</button>
+
{{ end }}
+
+
{{ if and (or $isPullAuthor $isPushAllowed) $isClosed $isLastRound }}
+
<button
+
hx-post="/{{ .RepoInfo.FullName }}/pulls/{{ .Pull.PullId }}/reopen"
+
hx-swap="none"
+
class="btn p-2 flex items-center gap-2">
+
{{ i "refresh-ccw-dot" "w-4 h-4" }}
+
<span>reopen</span>
+
</button>
+
{{ end }}
+
</div>
+
</div>
+
{{ end }}
+
+
+25
appview/pages/templates/repo/pulls/fragments/pullCompareBranches.html
···
+
{{ define "repo/pulls/fragments/pullCompareBranches" }}
+
<div id="patch-upload">
+
<label for="targetBranch" class="dark:text-white"
+
>select a branch</label
+
>
+
<div class="flex flex-wrap gap-2 items-center">
+
<select
+
name="sourceBranch"
+
class="p-1 border border-gray-200 bg-white dark:bg-gray-700 dark:text-white dark:border-gray-600"
+
>
+
<option disabled selected>source branch</option>
+
{{ range .Branches }}
+
<option value="{{ .Reference.Name }}" class="py-1">
+
{{ .Reference.Name }}
+
</option>
+
{{ end }}
+
</select>
+
</div>
+
</div>
+
+
<p class="mt-4">
+
Title and description are optional; if left out, they will be extracted
+
from the first commit.
+
</p>
+
{{ end }}
+46
appview/pages/templates/repo/pulls/fragments/pullCompareForks.html
···
+
{{ define "repo/pulls/fragments/pullCompareForks" }}
+
<div id="patch-upload">
+
<label for="forkSelect" class="dark:text-white"
+
>select a fork to compare</label
+
>
+
<div class="flex flex-wrap gap-4 items-center mb-4">
+
<div class="flex flex-wrap gap-2 items-center">
+
<select
+
id="forkSelect"
+
name="fork"
+
required
+
class="p-1 border border-gray-200 bg-white dark:bg-gray-700 dark:text-white dark:border-gray-600"
+
hx-get="/{{ $.RepoInfo.FullName }}/pulls/new/fork-branches"
+
hx-target="#branch-selection"
+
hx-vals='{"fork": this.value}'
+
hx-swap="innerHTML"
+
onchange="document.getElementById('hiddenForkInput').value = this.value;"
+
>
+
<option disabled selected>select a fork</option>
+
{{ range .Forks }}
+
<option value="{{ .Name }}" class="py-1">
+
{{ .Name }}
+
</option>
+
{{ end }}
+
</select>
+
+
<input
+
type="hidden"
+
id="hiddenForkInput"
+
name="fork"
+
value=""
+
/>
+
</div>
+
+
<div id="branch-selection">
+
<div class="text-sm text-gray-500 dark:text-gray-400">
+
Select a fork first to view available branches
+
</div>
+
</div>
+
</div>
+
</div>
+
<p class="mt-4">
+
Title and description are optional; if left out, they will be extracted
+
from the first commit.
+
</p>
+
{{ end }}
+15
appview/pages/templates/repo/pulls/fragments/pullCompareForksBranches.html
···
+
{{ define "repo/pulls/fragments/pullCompareForksBranches" }}
+
<div class="flex flex-wrap gap-2 items-center">
+
<select
+
name="sourceBranch"
+
class="p-1 border border-gray-200 bg-white dark:bg-gray-700 dark:text-white dark:border-gray-600"
+
>
+
<option disabled selected>source branch</option>
+
{{ range .SourceBranches }}
+
<option value="{{ .Reference.Name }}" class="py-1">
+
{{ .Reference.Name }}
+
</option>
+
{{ end }}
+
</select>
+
</div>
+
{{ end }}
+70
appview/pages/templates/repo/pulls/fragments/pullHeader.html
···
+
{{ define "repo/pulls/fragments/pullHeader" }}
+
<header class="pb-4">
+
<h1 class="text-2xl dark:text-white">
+
{{ .Pull.Title }}
+
<span class="text-gray-500 dark:text-gray-400">#{{ .Pull.PullId }}</span>
+
</h1>
+
</header>
+
+
{{ $bgColor := "bg-gray-800 dark:bg-gray-700" }}
+
{{ $icon := "ban" }}
+
+
{{ if .Pull.State.IsOpen }}
+
{{ $bgColor = "bg-green-600 dark:bg-green-700" }}
+
{{ $icon = "git-pull-request" }}
+
{{ else if .Pull.State.IsMerged }}
+
{{ $bgColor = "bg-purple-600 dark:bg-purple-700" }}
+
{{ $icon = "git-merge" }}
+
{{ end }}
+
+
<section class="mt-2">
+
<div class="flex items-center gap-2">
+
<div
+
id="state"
+
class="inline-flex items-center rounded px-3 py-1 {{ $bgColor }}"
+
>
+
{{ i $icon "w-4 h-4 mr-1.5 text-white" }}
+
<span class="text-white">{{ .Pull.State.String }}</span>
+
</div>
+
<span class="text-gray-500 dark:text-gray-400 text-sm">
+
opened by
+
{{ $owner := index $.DidHandleMap .Pull.OwnerDid }}
+
<a href="/{{ $owner }}" class="no-underline hover:underline"
+
>{{ $owner }}</a
+
>
+
<span class="select-none before:content-['\00B7']"></span>
+
<time>{{ .Pull.Created | timeFmt }}</time>
+
<span class="select-none before:content-['\00B7']"></span>
+
<span>
+
targeting
+
<span class="text-xs rounded bg-gray-100 dark:bg-gray-700 text-black dark:text-white font-mono px-2 mx-1/2 inline-flex items-center">
+
<a href="/{{ .RepoInfo.FullName }}/tree/{{ .Pull.TargetBranch }}" class="no-underline hover:underline">{{ .Pull.TargetBranch }}</a>
+
</span>
+
</span>
+
{{ if not .Pull.IsPatchBased }}
+
<span>from
+
{{ if .Pull.IsForkBased }}
+
{{ if .Pull.PullSource.Repo }}
+
<a href="/{{ $owner }}/{{ .Pull.PullSource.Repo.Name }}" class="no-underline hover:underline">{{ $owner }}/{{ .Pull.PullSource.Repo.Name }}</a>
+
{{ else }}
+
<span class="italic">[deleted fork]</span>
+
{{ end }}
+
{{ end }}
+
+
<span class="text-xs rounded bg-gray-100 dark:bg-gray-700 text-black dark:text-white font-mono px-2 mx-1/2 inline-flex items-center">
+
{{ .Pull.PullSource.Branch }}
+
</span>
+
</span>
+
{{ end }}
+
</span>
+
</div>
+
+
{{ if .Pull.Body }}
+
<article id="body" class="mt-8 prose dark:prose-invert">
+
{{ .Pull.Body | markdown }}
+
</article>
+
{{ end }}
+
</section>
+
+
+
{{ end }}
+32
appview/pages/templates/repo/pulls/fragments/pullNewComment.html
···
+
{{ define "repo/pulls/fragments/pullNewComment" }}
+
<div
+
id="pull-comment-card-{{ .RoundNumber }}"
+
class="bg-white dark:bg-gray-800 rounded drop-shadow-sm p-4 relative w-full flex flex-col gap-2">
+
<div class="text-sm text-gray-500 dark:text-gray-400">
+
{{ didOrHandle .LoggedInUser.Did .LoggedInUser.Handle }}
+
</div>
+
<form
+
hx-post="/{{ .RepoInfo.FullName }}/pulls/{{ .Pull.PullId }}/round/{{ .RoundNumber }}/comment"
+
hx-swap="none"
+
class="w-full flex flex-wrap gap-2">
+
<textarea
+
name="body"
+
class="w-full p-2 rounded border border-gray-200"
+
placeholder="Add to the discussion..."></textarea>
+
<button type="submit" class="btn flex items-center gap-2">
+
{{ i "message-square" "w-4 h-4" }} comment
+
</button>
+
<button
+
type="button"
+
class="btn flex items-center gap-2"
+
hx-get="/{{ .RepoInfo.FullName }}/pulls/{{ .Pull.PullId }}/round/{{ .RoundNumber }}/actions"
+
hx-swap="outerHTML"
+
hx-target="#pull-comment-card-{{ .RoundNumber }}">
+
{{ i "x" "w-4 h-4" }}
+
<span>cancel</span>
+
</button>
+
<div id="pull-comment"></div>
+
</form>
+
</div>
+
{{ end }}
+
+21
appview/pages/templates/repo/pulls/fragments/pullPatchUpload.html
···
+
{{ define "repo/pulls/fragments/pullPatchUpload" }}
+
<div id="patch-upload">
+
<p>
+
You can paste a <code>git diff</code> or a
+
<code>git format-patch</code> patch series here.
+
</p>
+
<textarea
+
hx-trigger="keyup changed delay:500ms, paste delay:500ms"
+
hx-post="/{{ .RepoInfo.FullName }}/pulls/new/validate-patch"
+
hx-swap="none"
+
name="patch"
+
id="patch"
+
rows="12"
+
class="w-full mt-2 resize-y font-mono dark:bg-gray-700 dark:text-white dark:border-gray-600"
+
placeholder="diff --git a/file.txt b/file.txt
+
index 1234567..abcdefg 100644
+
--- a/file.txt
+
+++ b/file.txt"
+
></textarea>
+
</div>
+
{{ end }}
+52
appview/pages/templates/repo/pulls/fragments/pullResubmit.html
···
+
{{ define "repo/pulls/fragments/pullResubmit" }}
+
<div
+
id="resubmit-pull-card"
+
class="rounded relative border bg-amber-50 dark:bg-amber-900 border-amber-200 dark:border-amber-500 px-6 py-2">
+
+
<div class="flex items-center gap-2 text-amber-500 dark:text-amber-50">
+
{{ i "pencil" "w-4 h-4" }}
+
<span class="font-medium">resubmit your patch</span>
+
</div>
+
+
<div class="mt-2 text-sm text-gray-700 dark:text-gray-200">
+
You can update this patch to address any reviews.
+
This will begin a new round of reviews,
+
but you'll still be able to view your previous submissions and feedback.
+
</div>
+
+
<div class="mt-4 flex flex-col">
+
<form
+
hx-post="/{{ .RepoInfo.FullName }}/pulls/{{ .Pull.PullId }}/resubmit"
+
hx-swap="none"
+
class="w-full flex flex-wrap gap-2">
+
<textarea
+
name="patch"
+
class="w-full p-2 mb-2"
+
placeholder="Paste your updated patch here."
+
rows="15"
+
>{{.Pull.LatestPatch}}</textarea>
+
<button
+
type="submit"
+
class="btn flex items-center gap-2"
+
{{ if or .Pull.State.IsClosed }}
+
disabled
+
{{ end }}>
+
{{ i "rotate-ccw" "w-4 h-4" }}
+
<span>resubmit</span>
+
</button>
+
<button
+
type="button"
+
class="btn flex items-center gap-2"
+
hx-get="/{{ .RepoInfo.FullName }}/pulls/{{ .Pull.PullId }}/round/{{ .Pull.LastRoundNumber }}/actions"
+
hx-swap="outerHTML"
+
hx-target="#resubmit-pull-card">
+
{{ i "x" "w-4 h-4" }}
+
<span>cancel</span>
+
</button>
+
</form>
+
+
<div id="resubmit-error" class="error"></div>
+
<div id="resubmit-success" class="success"></div>
+
</div>
+
</div>
+
{{ end }}
+25
appview/pages/templates/repo/pulls/interdiff.html
···
+
{{ define "title" }}
+
interdiff of round #{{ .Round }} and #{{ sub .Round 1 }}; pull #{{ .Pull.PullId }} &middot; {{ .RepoInfo.FullName }}
+
{{ end }}
+
+
{{ define "content" }}
+
<section class="rounded drop-shadow-sm bg-white dark:bg-gray-800 py-4 px-6 dark:text-white">
+
<header class="pb-2">
+
<div class="flex gap-3 items-center mb-3">
+
<a href="/{{ .RepoInfo.FullName }}/pulls/{{ .Pull.PullId }}/" class="flex items-center gap-2 font-medium">
+
{{ i "arrow-left" "w-5 h-5" }}
+
back
+
</a>
+
<span class="select-none before:content-['\00B7']"></span>
+
interdiff of round #{{ .Round }} and #{{ sub .Round 1 }}
+
</div>
+
<div class="border-t border-gray-200 dark:border-gray-700 my-2"></div>
+
{{ template "repo/pulls/fragments/pullHeader" . }}
+
</header>
+
</section>
+
+
<section>
+
{{ template "repo/fragments/interdiff" (list .RepoInfo.FullName .Interdiff) }}
+
</section>
+
{{ end }}
+
+90 -81
appview/pages/templates/repo/pulls/new.html
···
hx-swap="none"
>
<div class="flex flex-col gap-4">
-
<div>
-
<label for="title" class="dark:text-white">write a title</label>
-
<input type="text" name="title" id="title" class="w-full dark:bg-gray-700 dark:text-white dark:border-gray-600" />
-
</div>
+
<label>configure your pull request</label>
-
<div>
-
<label for="body" class="dark:text-white">add a description</label>
-
<textarea
-
name="body"
-
id="body"
-
rows="6"
-
class="w-full resize-y dark:bg-gray-700 dark:text-white dark:border-gray-600"
-
placeholder="Describe your change. Markdown is supported."
-
></textarea>
-
</div>
+
<p>First, choose a target branch on {{ .RepoInfo.FullName }}.</p>
+
<div class="pb-2">
+
<select
+
required
+
name="targetBranch"
+
class="p-1 border border-gray-200 bg-white dark:bg-gray-700 dark:text-white dark:border-gray-600"
+
>
+
<option disabled selected>target branch</option>
+
{{ range .Branches }}
+
<option value="{{ .Reference.Name }}" class="py-1">
+
{{ .Reference.Name }}
+
</option>
+
{{ end }}
+
</select>
+
</div>
+
<p>Next, choose a pull strategy.</p>
+
<nav class="flex space-x-4 items-end">
+
<button
+
type="button"
+
class="px-3 py-2 pb-2 btn"
+
hx-get="/{{ .RepoInfo.FullName }}/pulls/new/patch-upload"
+
hx-target="#patch-strategy"
+
hx-swap="innerHTML"
+
>
+
paste patch
+
</button>
-
<label>configure your pull request</label>
+
{{ if .RepoInfo.Roles.IsPushAllowed }}
+
<span class="text-sm text-gray-500 dark:text-gray-400 pb-2">
+
or
+
</span>
+
<button
+
type="button"
+
class="px-3 py-2 pb-2 btn"
+
hx-get="/{{ .RepoInfo.FullName }}/pulls/new/compare-branches"
+
hx-target="#patch-strategy"
+
hx-swap="innerHTML"
+
>
+
compare branches
+
</button>
+
{{ end }}
-
<p>First, choose a target branch on {{ .RepoInfo.FullName }}.</p>
-
<div class="pb-2">
-
<select
-
required
-
name="targetBranch"
-
class="p-1 border border-gray-200 bg-white dark:bg-gray-700 dark:text-white dark:border-gray-600"
-
>
-
<option disabled selected>target branch</option>
-
{{ range .Branches }}
-
<option value="{{ .Reference.Name }}" class="py-1">
-
{{ .Reference.Name }}
-
</option>
-
{{ end }}
-
</select>
-
</div>
+
+
<span class="text-sm text-gray-500 dark:text-gray-400 pb-2">
+
or
+
</span>
+
<button
+
type="button"
+
class="px-3 py-2 pb-2 btn"
+
hx-get="/{{ .RepoInfo.FullName }}/pulls/new/compare-forks"
+
hx-target="#patch-strategy"
+
hx-swap="innerHTML"
+
>
+
compare forks
+
</button>
+
</nav>
+
+
<section id="patch-strategy">
+
{{ template "repo/pulls/fragments/pullPatchUpload" . }}
+
</section>
+
+
<p id="patch-preview"></p>
-
<p>Then, choose a pull strategy.</p>
-
<nav class="flex space-x-4 items-end">
-
<button
-
type="button"
-
class="px-3 py-2 pb-2 btn"
-
hx-get="/{{ .RepoInfo.FullName }}/pulls/new/patch-upload"
-
hx-target="#patch-strategy"
-
hx-swap="innerHTML"
-
>
-
paste patch
-
</button>
+
<div id="patch-error" class="error dark:text-red-300"></div>
-
{{ if .RepoInfo.Roles.IsPushAllowed }}
-
<span class="text-sm text-gray-500 dark:text-gray-400 pb-2">
-
or
-
</span>
-
<button
-
type="button"
-
class="px-3 py-2 pb-2 btn"
-
hx-get="/{{ .RepoInfo.FullName }}/pulls/new/compare-branches"
-
hx-target="#patch-strategy"
-
hx-swap="innerHTML"
-
>
-
compare branches
-
</button>
-
{{ end }}
+
<div>
+
<label for="title" class="dark:text-white">write a title</label>
-
<span class="text-sm text-gray-500 dark:text-gray-400 pb-2">
-
or
-
</span>
-
<button
-
type="button"
-
class="px-3 py-2 pb-2 btn"
-
hx-get="/{{ .RepoInfo.FullName }}/pulls/new/compare-forks"
-
hx-target="#patch-strategy"
-
hx-swap="innerHTML"
-
>
-
compare forks
-
</button>
-
</nav>
+
<input
+
type="text"
+
name="title"
+
id="title"
+
class="w-full dark:bg-gray-700 dark:text-white dark:border-gray-600"
+
placeholder="One-line summary of your change."
+
/>
+
</div>
-
<section id="patch-strategy">
-
{{ template "fragments/pullPatchUpload" . }}
-
</section>
+
<div>
+
<label for="body" class="dark:text-white"
+
>add a description</label
+
>
-
<div class="flex justify-start items-center gap-2 mt-4">
-
<button type="submit" class="btn flex items-center gap-2">
-
{{ i "git-pull-request-create" "w-4 h-4" }}
-
create pull
-
</button>
-
</div>
+
<textarea
+
name="body"
+
id="body"
+
rows="6"
+
class="w-full resize-y dark:bg-gray-700 dark:text-white dark:border-gray-600"
+
placeholder="Describe your change. Markdown is supported."
+
></textarea>
+
</div>
+
<div class="flex justify-start items-center gap-2 mt-4">
+
<button type="submit" class="btn flex items-center gap-2">
+
{{ i "git-pull-request-create" "w-4 h-4" }}
+
create pull
+
</button>
+
</div>
</div>
<div id="pull" class="error dark:text-red-300"></div>
</form>
{{ end }}
-
-
{{ define "repoAfter" }}
-
<div id="patch-preview" class="error dark:text-red-300"></div>
-
{{ end }}
+21 -84
appview/pages/templates/repo/pulls/patch.html
···
{{ end }}
{{ define "content" }}
-
{{ $stat := .Diff.Stat }}
-
<div class="rounded drop-shadow-sm bg-white dark:bg-gray-800 py-4 px-6 dark:text-white">
-
<header class="pb-2">
-
<div class="flex gap-3 items-center mb-3">
-
<a href="/{{ .RepoInfo.FullName }}/pulls/{{ .Pull.PullId }}/" class="flex items-center gap-2 font-medium">
-
{{ i "arrow-left" "w-5 h-5" }}
-
back
-
</a>
-
<span class="select-none before:content-['\00B7']"></span>
-
round #{{ .Round }}
-
<span class="select-none before:content-['\00B7']"></span>
-
<a href="/{{ .RepoInfo.FullName }}/pulls/{{ .Pull.PullId }}/round/{{ .Round }}.patch">
-
view raw
-
</a>
-
</div>
-
<div class="border-t border-gray-200 dark:border-gray-700 my-2"></div>
-
<h1 class="text-2xl mt-3">
-
{{ .Pull.Title }}
-
<span class="text-gray-500 dark:text-gray-400">#{{ .Pull.PullId }}</span>
-
</h1>
-
</header>
-
-
{{ $bgColor := "bg-gray-800" }}
-
{{ $icon := "ban" }}
-
-
{{ if .Pull.State.IsOpen }}
-
{{ $bgColor = "bg-green-600" }}
-
{{ $icon = "git-pull-request" }}
-
{{ else if .Pull.State.IsMerged }}
-
{{ $bgColor = "bg-purple-600" }}
-
{{ $icon = "git-merge" }}
-
{{ end }}
-
-
<section>
-
<div class="flex items-center gap-2">
-
<div
-
id="state"
-
class="inline-flex items-center rounded px-3 py-1 {{ $bgColor }}"
-
>
-
{{ i $icon "w-4 h-4 mr-1.5 text-white" }}
-
<span class="text-white">{{ .Pull.State.String }}</span>
-
</div>
-
<span class="text-gray-500 dark:text-gray-400 text-sm">
-
opened by
-
{{ $owner := index $.DidHandleMap .Pull.OwnerDid }}
-
<a href="/{{ $owner }}" class="no-underline hover:underline"
-
>{{ $owner }}</a
-
>
-
<span class="select-none before:content-['\00B7']"></span>
-
<time>{{ .Pull.Created | timeFmt }}</time>
-
<span class="select-none before:content-['\00B7']"></span>
-
<span>targeting branch
-
<span class="text-xs rounded bg-gray-100 dark:bg-gray-700 text-black dark:text-white font-mono px-2 mx-1/2 inline-flex items-center">
-
{{ .Pull.TargetBranch }}
-
</span>
-
</span>
-
</span>
-
</div>
-
-
{{ if .Pull.Body }}
-
<article id="body" class="mt-2 prose dark:prose-invert">
-
{{ .Pull.Body | markdown }}
-
</article>
-
{{ end }}
-
</section>
-
-
<div id="diff-stat">
-
<br>
-
<strong class="text-sm uppercase mb-4">Changed files</strong>
-
{{ range .Diff.Diff }}
-
<ul>
-
{{ if .IsDelete }}
-
<li><a href="#file-{{ .Name.Old }}">{{ .Name.Old }}</a></li>
-
{{ else }}
-
<li><a href="#file-{{ .Name.New }}">{{ .Name.New }}</a></li>
-
{{ end }}
-
</ul>
-
{{ end }}
-
</div>
-
</div>
-
-
<section>
-
{{ template "fragments/diff" (list .RepoInfo.FullName .Diff) }}
-
</section>
+
<section>
+
<section
+
class="bg-white dark:bg-gray-800 p-6 rounded relative z-20 w-full mx-auto drop-shadow-sm dark:text-white"
+
>
+
<div class="flex gap-3 items-center mb-3">
+
<a href="/{{ .RepoInfo.FullName }}/pulls/{{ .Pull.PullId }}/" class="flex items-center gap-2 font-medium">
+
{{ i "arrow-left" "w-5 h-5" }}
+
back
+
</a>
+
<span class="select-none before:content-['\00B7']"></span>
+
round<span class="flex items-center">{{ i "hash" "w-4 h-4" }}{{ .Round }}</span>
+
<span class="select-none before:content-['\00B7']"></span>
+
<a href="/{{ .RepoInfo.FullName }}/pulls/{{ .Pull.PullId }}/round/{{ .Round }}.patch">
+
view raw
+
</a>
+
</div>
+
<div class="border-t border-gray-200 dark:border-gray-700 my-2"></div>
+
{{ template "repo/pulls/fragments/pullHeader" . }}
+
</section>
+
{{ template "repo/fragments/diff" (list .RepoInfo.FullName .Diff) }}
+
</section>
{{ end }}
+83 -84
appview/pages/templates/repo/pulls/pull.html
···
{{ end }}
{{ define "repoContent" }}
-
<header class="pb-4">
-
<h1 class="text-2xl dark:text-white">
-
{{ .Pull.Title }}
-
<span class="text-gray-500 dark:text-gray-400">#{{ .Pull.PullId }}</span>
-
</h1>
-
</header>
-
-
{{ $bgColor := "bg-gray-800 dark:bg-gray-700" }}
-
{{ $icon := "ban" }}
-
-
{{ if .Pull.State.IsOpen }}
-
{{ $bgColor = "bg-green-600 dark:bg-green-700" }}
-
{{ $icon = "git-pull-request" }}
-
{{ else if .Pull.State.IsMerged }}
-
{{ $bgColor = "bg-purple-600 dark:bg-purple-700" }}
-
{{ $icon = "git-merge" }}
-
{{ end }}
-
-
<section>
-
<div class="flex items-center gap-2">
-
<div
-
id="state"
-
class="inline-flex items-center rounded px-3 py-1 {{ $bgColor }}"
-
>
-
{{ i $icon "w-4 h-4 mr-1.5 text-white" }}
-
<span class="text-white">{{ .Pull.State.String }}</span>
-
</div>
-
<span class="text-gray-500 dark:text-gray-400 text-sm">
-
opened by
-
{{ $owner := index $.DidHandleMap .Pull.OwnerDid }}
-
<a href="/{{ $owner }}" class="no-underline hover:underline"
-
>{{ $owner }}</a
-
>
-
<span class="select-none before:content-['\00B7']"></span>
-
<time>{{ .Pull.Created | timeFmt }}</time>
-
<span class="select-none before:content-['\00B7']"></span>
-
<span>
-
targeting
-
<span class="text-xs rounded bg-gray-100 dark:bg-gray-700 text-black dark:text-white font-mono px-2 mx-1/2 inline-flex items-center">
-
<a href="/{{ .RepoInfo.FullName }}/tree/{{ .Pull.TargetBranch }}" class="no-underline hover:underline">{{ .Pull.TargetBranch }}</a>
-
</span>
-
</span>
-
{{ if not .Pull.IsPatch }}
-
<span>from
-
{{ if not .Pull.IsSameRepoBranch }}
-
<a href="/{{ $owner }}/{{ .PullSourceRepo.Name }}" class="no-underline hover:underline">{{ $owner }}/{{ .PullSourceRepo.Name }}</a>
-
{{ end }}
-
-
{{ $fullRepo := .RepoInfo.FullName }}
-
{{ if not .Pull.IsSameRepoBranch }}
-
{{ $fullRepo = printf "%s/%s" $owner .PullSourceRepo.Name }}
-
{{ end }}
-
<span class="text-xs rounded bg-gray-100 dark:bg-gray-700 text-black dark:text-white font-mono px-2 mx-1/2 inline-flex items-center">
-
<a href="/{{ $fullRepo }}/tree/{{ .Pull.PullSource.Branch }}" class="no-underline hover:underline">{{ .Pull.PullSource.Branch }}</a>
-
</span>
-
</span>
-
{{ end }}
-
</span>
-
</div>
-
-
{{ if .Pull.Body }}
-
<article id="body" class="mt-2 prose dark:prose-invert">
-
{{ .Pull.Body | markdown }}
-
</article>
-
{{ end }}
-
</section>
-
+
{{ template "repo/pulls/fragments/pullHeader" . }}
{{ end }}
{{ define "repoAfter" }}
···
{{ $targetBranch := .Pull.TargetBranch }}
{{ $repoName := .RepoInfo.FullName }}
{{ range $idx, $item := .Pull.Submissions }}
-
{{ $diff := $item.AsNiceDiff $targetBranch }}
{{ with $item }}
<details {{ if eq $idx $lastIdx }}open{{ end }}>
<summary id="round-#{{ .RoundNumber }}" class="list-none cursor-pointer">
<div class="flex flex-wrap gap-2 items-center">
<!-- round number -->
<div class="rounded bg-white dark:bg-gray-800 drop-shadow-sm px-3 py-2 dark:text-white">
-
#{{ .RoundNumber }}
+
<span class="flex items-center">{{ i "hash" "w-4 h-4" }}{{ .RoundNumber }}</span>
</div>
<!-- round summary -->
<div class="rounded drop-shadow-sm bg-white dark:bg-gray-800 p-2 text-gray-500 dark:text-gray-400">
···
{{ len .Comments }} comment{{$s}}
</span>
</div>
-
<!-- view patch -->
+
<a class="btn flex items-center gap-2 no-underline hover:no-underline p-2"
hx-boost="true"
href="/{{ $.RepoInfo.FullName }}/pulls/{{ $.Pull.PullId }}/round/{{.RoundNumber}}">
{{ i "file-diff" "w-4 h-4" }} <span class="hidden md:inline">view patch</span>
</a>
+
{{ if not (eq .RoundNumber 0) }}
+
<a class="btn flex items-center gap-2 no-underline hover:no-underline p-2"
+
hx-boost="true"
+
href="/{{ $.RepoInfo.FullName }}/pulls/{{ $.Pull.PullId }}/round/{{.RoundNumber}}/interdiff">
+
{{ i "file-diff" "w-4 h-4" }} <span class="hidden md:inline">interdiff</span>
+
</a>
+
<span id="interdiff-error-{{.RoundNumber}}"></span>
+
{{ end }}
</div>
</summary>
-
<div class="md:pl-12 flex flex-col gap-2 mt-2 relative">
-
{{ range .Comments }}
-
<div id="comment-{{.ID}}" class="bg-white dark:bg-gray-800 rounded drop-shadow-sm py-2 px-4 relative w-full md:max-w-3/5 md:w-fit">
+
+
{{ if .IsFormatPatch }}
+
{{ $patches := .AsFormatPatch }}
+
{{ $round := .RoundNumber }}
+
<details class="group py-2 md:ml-[3.5rem] text-gray-500 dark:text-gray-400 flex flex-col gap-2 relative text-sm">
+
<summary class="py-1 list-none cursor-pointer hover:text-gray-500 hover:dark:text-gray-400">
+
{{ $s := "s" }}
+
{{ if eq (len $patches) 1 }}
+
{{ $s = "" }}
+
{{ end }}
+
<div class="group-open:hidden flex items-center gap-2 ml-2">
+
{{ i "chevrons-up-down" "w-4 h-4" }} expand {{ len $patches }} commit{{$s}}
+
</div>
+
<div class="hidden group-open:flex items-center gap-2 ml-2">
+
{{ i "chevrons-down-up" "w-4 h-4" }} hide {{ len $patches }} commit{{$s}}
+
</div>
+
</summary>
+
{{ range $patches }}
+
<div id="commit-{{.SHA}}" class="py-1 px-2 relative w-full md:max-w-3/5 md:w-fit flex flex-col">
+
<div class="flex items-center gap-2">
+
{{ i "git-commit-horizontal" "w-4 h-4" }}
+
<div class="text-sm text-gray-500 dark:text-gray-400">
+
{{ if not $.Pull.IsPatchBased }}
+
{{ $fullRepo := $.RepoInfo.FullName }}
+
{{ if $.Pull.IsForkBased }}
+
{{ if $.Pull.PullSource.Repo }}
+
{{ $fullRepo = printf "%s/%s" $owner $.Pull.PullSource.Repo.Name }}
+
<a href="/{{ $fullRepo }}/commit/{{ .SHA }}" class="font-mono text-gray-500 dark:text-gray-400">{{ slice .SHA 0 8 }}</a>
+
{{ else }}
+
<span class="font-mono">{{ slice .SHA 0 8 }}</span>
+
{{ end }}
+
{{ end }}
+
{{ else }}
+
<span class="font-mono">{{ slice .SHA 0 8 }}</span>
+
{{ end }}
+
</div>
+
<div class="flex items-center">
+
<span>{{ .Title }}</span>
+
{{ if gt (len .Body) 0 }}
+
<button
+
class="py-1/2 px-1 mx-2 bg-gray-200 hover:bg-gray-400 rounded dark:bg-gray-700 dark:hover:bg-gray-600"
+
hx-on:click="document.getElementById('body-{{$round}}-{{.SHA}}').classList.toggle('hidden')"
+
>
+
{{ i "ellipsis" "w-3 h-3" }}
+
</button>
+
{{ end }}
+
</div>
+
</div>
+
{{ if gt (len .Body) 0 }}
+
<p id="body-{{$round}}-{{.SHA}}" class="hidden mt-1 text-sm pb-2">
+
{{ nl2br .Body }}
+
</p>
+
{{ end }}
+
</div>
+
{{ end }}
+
</details>
+
{{ end }}
+
+
+
<div class="md:pl-[3.5rem] flex flex-col gap-2 mt-2 relative">
+
{{ range $cidx, $c := .Comments }}
+
<div id="comment-{{$c.ID}}" class="bg-white dark:bg-gray-800 rounded drop-shadow-sm py-2 px-4 relative w-full md:max-w-3/5 md:w-fit">
+
{{ if gt $cidx 0 }}
<div class="absolute left-8 -top-2 w-px h-2 bg-gray-300 dark:bg-gray-600"></div>
+
{{ end }}
<div class="text-sm text-gray-500 dark:text-gray-400">
-
{{ $owner := index $.DidHandleMap .OwnerDid }}
+
{{ $owner := index $.DidHandleMap $c.OwnerDid }}
<a href="/{{$owner}}">{{$owner}}</a>
<span class="before:content-['ยท']"></span>
-
<a class="text-gray-500 dark:text-gray-400 hover:text-gray-500 dark:hover:text-gray-300" href="#comment-{{.ID}}"><time>{{ .Created | shortTimeFmt }}</time></a>
+
<a class="text-gray-500 dark:text-gray-400 hover:text-gray-500 dark:hover:text-gray-300" href="#comment-{{.ID}}"><time>{{ $c.Created | shortTimeFmt }}</time></a>
</div>
<div class="prose dark:prose-invert">
-
{{ .Body | markdown }}
+
{{ $c.Body | markdown }}
</div>
</div>
{{ end }}
···
{{ end }}
{{ if $.LoggedInUser }}
-
{{ template "fragments/pullActions" (dict "LoggedInUser" $.LoggedInUser "Pull" $.Pull "RepoInfo" $.RepoInfo "RoundNumber" .RoundNumber "MergeCheck" $.MergeCheck "ResubmitCheck" $.ResubmitCheck) }}
+
{{ template "repo/pulls/fragments/pullActions" (dict "LoggedInUser" $.LoggedInUser "Pull" $.Pull "RepoInfo" $.RepoInfo "RoundNumber" .RoundNumber "MergeCheck" $.MergeCheck "ResubmitCheck" $.ResubmitCheck) }}
{{ else }}
<div class="bg-white dark:bg-gray-800 rounded drop-shadow-sm px-6 py-4 w-fit dark:text-white">
<div class="absolute left-8 -top-2 w-px h-2 bg-gray-300 dark:bg-gray-600"></div>
···
{{ end }}
</div>
</details>
-
<hr class="md:hidden"/>
+
<hr class="md:hidden border-t border-gray-300 dark:border-gray-600"/>
{{ end }}
{{ end }}
{{ end }}
···
{{ define "mergeStatus" }}
{{ if .Pull.State.IsClosed }}
<div class="bg-gray-50 dark:bg-gray-700 border border-black dark:border-gray-500 rounded drop-shadow-sm px-6 py-2 relative w-fit">
-
<div class="absolute left-8 -top-2 w-px h-2 bg-gray-300 dark:bg-gray-600"></div>
<div class="flex items-center gap-2 text-black dark:text-white">
{{ i "ban" "w-4 h-4" }}
<span class="font-medium">closed without merging</span
···
</div>
{{ else if .Pull.State.IsMerged }}
<div class="bg-purple-50 dark:bg-purple-900 border border-purple-500 rounded drop-shadow-sm px-6 py-2 relative w-fit">
-
<div class="absolute left-8 -top-2 w-px h-2 bg-gray-300 dark:bg-gray-600"></div>
<div class="flex items-center gap-2 text-purple-500 dark:text-purple-300">
{{ i "git-merge" "w-4 h-4" }}
<span class="font-medium">pull request successfully merged</span
···
</div>
{{ else if and .MergeCheck .MergeCheck.Error }}
<div class="bg-red-50 dark:bg-red-900 border border-red-500 rounded drop-shadow-sm px-6 py-2 relative w-fit">
-
<div class="absolute left-8 -top-2 w-px h-2 bg-gray-300 dark:bg-gray-600"></div>
<div class="flex items-center gap-2 text-red-500 dark:text-red-300">
{{ i "triangle-alert" "w-4 h-4" }}
<span class="font-medium">{{ .MergeCheck.Error }}</span>
···
</div>
{{ else if and .MergeCheck .MergeCheck.IsConflicted }}
<div class="bg-red-50 dark:bg-red-900 border border-red-500 rounded drop-shadow-sm px-6 py-2 relative w-fit">
-
<div class="absolute left-8 -top-2 w-px h-2 bg-gray-300 dark:bg-gray-600"></div>
<div class="flex flex-col gap-2 text-red-500 dark:text-red-300">
<div class="flex items-center gap-2">
{{ i "triangle-alert" "w-4 h-4" }}
···
</div>
{{ else if .MergeCheck }}
<div class="bg-green-50 dark:bg-green-900 border border-green-500 rounded drop-shadow-sm px-6 py-2 relative w-fit">
-
<div class="absolute left-8 -top-2 w-px h-2 bg-gray-300 dark:bg-gray-600"></div>
<div class="flex items-center gap-2 text-green-500 dark:text-green-300">
{{ i "circle-check-big" "w-4 h-4" }}
<span class="font-medium">no conflicts, ready to merge</span>
···
{{ define "resubmitStatus" }}
{{ if .ResubmitCheck.Yes }}
<div class="bg-amber-50 dark:bg-amber-900 border border-amber-500 rounded drop-shadow-sm px-6 py-2 relative w-fit">
-
<div class="absolute left-8 -top-2 w-px h-2 bg-gray-300 dark:bg-gray-600"></div>
<div class="flex items-center gap-2 text-amber-500 dark:text-amber-300">
{{ i "triangle-alert" "w-4 h-4" }}
<span class="font-medium">this branch has been updated, consider resubmitting</span>
···
</div>
{{ end }}
{{ end }}
+
+
{{ define "commits" }}
+
{{ end }}
+29 -6
appview/pages/templates/repo/pulls/pulls.html
···
<p class="dark:text-white">
filtering
<select
-
class="border px-1 bg-white dark:bg-gray-800 border-gray-200 dark:border-gray-600 dark:text-white"
+
class="border p-1 bg-white dark:bg-gray-800 border-gray-200 dark:border-gray-600 dark:text-white"
onchange="window.location.href = '/{{ .RepoInfo.FullName }}/pulls?state=' + this.value"
>
<option value="open" {{ if .FilteringBy.IsOpen }}selected{{ end }}>
···
</p>
<a
href="/{{ .RepoInfo.FullName }}/pulls/new"
-
class="btn text-sm flex items-center gap-2 no-underline hover:no-underline dark:text-white dark:bg-gray-700 dark:hover:bg-gray-600"
+
class="btn text-sm flex items-center gap-2 no-underline hover:no-underline"
>
-
{{ i "git-pull-request" "w-4 h-4" }}
-
<span>new pull request</span>
+
{{ i "git-pull-request-create" "w-4 h-4" }}
+
<span>new</span>
</a>
</div>
<div class="error" id="pulls"></div>
···
{{ .TargetBranch }}
</span>
</span>
-
{{ if not .IsPatch }}
+
{{ if not .IsPatchBased }}
<span>from
-
{{ if not .IsSameRepoBranch }}
+
{{ if .IsForkBased }}
+
{{ if .PullSource.Repo }}
<a href="/{{ $owner }}/{{ .PullSource.Repo.Name }}" class="no-underline hover:underline">{{ $owner }}/{{ .PullSource.Repo.Name }}</a>
+
{{ else }}
+
<span class="italic">[deleted fork]</span>
+
{{ end }}
{{ end }}
<span class="text-xs rounded bg-gray-100 dark:bg-gray-700 text-black dark:text-white font-mono px-2 mx-1/2 inline-flex items-center">
···
</span>
</span>
{{ end }}
+
<span class="before:content-['ยท']">
+
{{ $latestRound := .LastRoundNumber }}
+
{{ $lastSubmission := index .Submissions $latestRound }}
+
round
+
<span class="text-xs rounded bg-gray-100 dark:bg-gray-700 text-black dark:text-white font-mono px-2 mx-1/2 inline-flex items-center">
+
#{{ .LastRoundNumber }}
+
</span>
+
{{ $commentCount := len $lastSubmission.Comments }}
+
{{ $s := "s" }}
+
{{ if eq $commentCount 1 }}
+
{{ $s = "" }}
+
{{ end }}
+
+
{{ if eq $commentCount 0 }}
+
awaiting comments
+
{{ else }}
+
recieved {{ len $lastSubmission.Comments}} comment{{$s}}
+
{{ end }}
+
</span>
</p>
</div>
{{ end }}
+4 -3
appview/pages/templates/repo/tree.html
···
{{ $stats := .TreeStats }}
<span>at <a href="/{{ $.RepoInfo.FullName }}/tree/{{ $.Ref }}">{{ $.Ref }}</a></span>
-
<span class="select-none px-1 md:px-2 [&:before]:content-['ยท']"></span>
{{ if eq $stats.NumFolders 1 }}
-
<span>{{ $stats.NumFolders }} folder</span>
<span class="select-none px-1 md:px-2 [&:before]:content-['ยท']"></span>
+
<span>{{ $stats.NumFolders }} folder</span>
{{ else if gt $stats.NumFolders 1 }}
+
<span class="select-none px-1 md:px-2 [&:before]:content-['ยท']"></span>
<span>{{ $stats.NumFolders }} folders</span>
-
<span class="select-none px-1 md:px-2 [&:before]:content-['ยท']"></span>
{{ end }}
{{ if eq $stats.NumFiles 1 }}
+
<span class="select-none px-1 md:px-2 [&:before]:content-['ยท']"></span>
<span>{{ $stats.NumFiles }} file</span>
{{ else if gt $stats.NumFiles 1 }}
+
<span class="select-none px-1 md:px-2 [&:before]:content-['ยท']"></span>
<span>{{ $stats.NumFiles }} files</span>
{{ end }}
+1 -1
appview/pages/templates/timeline.html
···
</div>
<div class="italic text-lg">
tightly-knit social coding, <a href="/login" class="underline inline-flex gap-1 items-center">join now {{ i "arrow-right" "w-4 h-4" }}</a>
-
<p class="pt-5 px-10 text-sm text-gray-500 dark:text-gray-400">Join our IRC channel: <a href="https://web.libera.chat/#tangled"><code>#tangled</code> on Libera Chat</a>.
+
<p class="pt-5 px-10 text-sm text-gray-500 dark:text-gray-400">Join our <a href="https://chat.tangled.sh">Discord</a>or IRC channel: <a href="https://web.libera.chat/#tangled"><code>#tangled</code> on Libera Chat</a>.
Read an introduction to Tangled <a href="https://blog.tangled.sh/intro">here</a>.</p>
</div>
</div>
+17
appview/pages/templates/user/fragments/follow.html
···
+
{{ define "user/fragments/follow" }}
+
<button id="followBtn"
+
class="btn mt-2 w-full"
+
+
{{ if eq .FollowStatus.String "IsNotFollowing" }}
+
hx-post="/follow?subject={{.UserDid}}"
+
{{ else }}
+
hx-delete="/follow?subject={{.UserDid}}"
+
{{ end }}
+
+
hx-trigger="click"
+
hx-target="#followBtn"
+
hx-swap="outerHTML"
+
>
+
{{ if eq .FollowStatus.String "IsNotFollowing" }}Follow{{ else }}Unfollow{{ end }}
+
</button>
+
{{ end }}
+1 -1
appview/pages/templates/user/login.html
···
</button>
</form>
<p class="text-sm text-gray-500">
-
Join our IRC channel:
+
Join our <a href="https://chat.tangled.sh">Discord</a> or IRC channel:
<a href="https://web.libera.chat/#tangled"
><code>#tangled</code> on Libera Chat</a
>.
+2 -2
appview/pages/templates/user/profile.html
···
{{ if gt $stats.Closed 0 }}
-
<span class="px-2 py-1/2 text-sm rounded text-black dark:text-white bg-gray-50 dark:bg-gray-700 ">
+
<span class="px-2 py-1/2 text-sm rounded text-white bg-gray-800 dark:bg-gray-700">
{{$stats.Closed}} closed
</span>
{{ end }}
···
</div>
{{ if ne .FollowStatus.String "IsSelf" }}
-
{{ template "fragments/follow" . }}
+
{{ template "user/fragments/follow" . }}
{{ end }}
</div>
{{ end }}
+31
appview/pagination/page.go
···
+
package pagination
+
+
type Page struct {
+
Offset int // where to start from
+
Limit int // number of items in a page
+
}
+
+
func FirstPage() Page {
+
return Page{
+
Offset: 0,
+
Limit: 10,
+
}
+
}
+
+
func (p Page) Previous() Page {
+
if p.Offset-p.Limit < 0 {
+
return FirstPage()
+
} else {
+
return Page{
+
Offset: p.Offset - p.Limit,
+
Limit: p.Limit,
+
}
+
}
+
}
+
+
func (p Page) Next() Page {
+
return Page{
+
Offset: p.Offset + p.Limit,
+
Limit: p.Limit,
+
}
+
}
+451
appview/settings/settings.go
···
+
package settings
+
+
import (
+
"database/sql"
+
"errors"
+
"fmt"
+
"log"
+
"net/http"
+
"net/url"
+
"strings"
+
"time"
+
+
"github.com/go-chi/chi/v5"
+
"tangled.sh/tangled.sh/core/api/tangled"
+
"tangled.sh/tangled.sh/core/appview"
+
"tangled.sh/tangled.sh/core/appview/auth"
+
"tangled.sh/tangled.sh/core/appview/db"
+
"tangled.sh/tangled.sh/core/appview/email"
+
"tangled.sh/tangled.sh/core/appview/middleware"
+
"tangled.sh/tangled.sh/core/appview/pages"
+
+
comatproto "github.com/bluesky-social/indigo/api/atproto"
+
lexutil "github.com/bluesky-social/indigo/lex/util"
+
"github.com/gliderlabs/ssh"
+
"github.com/google/uuid"
+
)
+
+
type Settings struct {
+
Db *db.DB
+
Auth *auth.Auth
+
Pages *pages.Pages
+
Config *appview.Config
+
}
+
+
func (s *Settings) Router() http.Handler {
+
r := chi.NewRouter()
+
+
r.Use(middleware.AuthMiddleware(s.Auth))
+
+
r.Get("/", s.settings)
+
+
r.Route("/keys", func(r chi.Router) {
+
r.Put("/", s.keys)
+
r.Delete("/", s.keys)
+
})
+
+
r.Route("/emails", func(r chi.Router) {
+
r.Put("/", s.emails)
+
r.Delete("/", s.emails)
+
r.Get("/verify", s.emailsVerify)
+
r.Post("/verify/resend", s.emailsVerifyResend)
+
r.Post("/primary", s.emailsPrimary)
+
})
+
+
return r
+
}
+
+
func (s *Settings) settings(w http.ResponseWriter, r *http.Request) {
+
user := s.Auth.GetUser(r)
+
pubKeys, err := db.GetPublicKeys(s.Db, user.Did)
+
if err != nil {
+
log.Println(err)
+
}
+
+
emails, err := db.GetAllEmails(s.Db, user.Did)
+
if err != nil {
+
log.Println(err)
+
}
+
+
s.Pages.Settings(w, pages.SettingsParams{
+
LoggedInUser: user,
+
PubKeys: pubKeys,
+
Emails: emails,
+
})
+
}
+
+
// buildVerificationEmail creates an email.Email struct for verification emails
+
func (s *Settings) buildVerificationEmail(emailAddr, did, code string) email.Email {
+
verifyURL := s.verifyUrl(did, emailAddr, code)
+
+
return email.Email{
+
APIKey: s.Config.ResendApiKey,
+
From: "noreply@notifs.tangled.sh",
+
To: emailAddr,
+
Subject: "Verify your Tangled email",
+
Text: `Click the link below (or copy and paste it into your browser) to verify your email address.
+
` + verifyURL,
+
Html: `<p>Click the link (or copy and paste it into your browser) to verify your email address.</p>
+
<p><a href="` + verifyURL + `">` + verifyURL + `</a></p>`,
+
}
+
}
+
+
// sendVerificationEmail handles the common logic for sending verification emails
+
func (s *Settings) sendVerificationEmail(w http.ResponseWriter, did, emailAddr, code string, errorContext string) error {
+
emailToSend := s.buildVerificationEmail(emailAddr, did, code)
+
+
err := email.SendEmail(emailToSend)
+
if err != nil {
+
log.Printf("sending email: %s", err)
+
s.Pages.Notice(w, "settings-emails-error", fmt.Sprintf("Unable to send verification email at this moment, try again later. %s", errorContext))
+
return err
+
}
+
+
return nil
+
}
+
+
func (s *Settings) emails(w http.ResponseWriter, r *http.Request) {
+
switch r.Method {
+
case http.MethodGet:
+
s.Pages.Notice(w, "settings-emails", "Unimplemented.")
+
log.Println("unimplemented")
+
return
+
case http.MethodPut:
+
did := s.Auth.GetDid(r)
+
emAddr := r.FormValue("email")
+
emAddr = strings.TrimSpace(emAddr)
+
+
if !email.IsValidEmail(emAddr) {
+
s.Pages.Notice(w, "settings-emails-error", "Invalid email address.")
+
return
+
}
+
+
// check if email already exists in database
+
existingEmail, err := db.GetEmail(s.Db, did, emAddr)
+
if err != nil && !errors.Is(err, sql.ErrNoRows) {
+
log.Printf("checking for existing email: %s", err)
+
s.Pages.Notice(w, "settings-emails-error", "Unable to add email at this moment, try again later.")
+
return
+
}
+
+
if err == nil {
+
if existingEmail.Verified {
+
s.Pages.Notice(w, "settings-emails-error", "This email is already verified.")
+
return
+
}
+
+
s.Pages.Notice(w, "settings-emails-error", "This email is already added but not verified. Check your inbox for the verification link.")
+
return
+
}
+
+
code := uuid.New().String()
+
+
// Begin transaction
+
tx, err := s.Db.Begin()
+
if err != nil {
+
log.Printf("failed to start transaction: %s", err)
+
s.Pages.Notice(w, "settings-emails-error", "Unable to add email at this moment, try again later.")
+
return
+
}
+
defer tx.Rollback()
+
+
if err := db.AddEmail(tx, db.Email{
+
Did: did,
+
Address: emAddr,
+
Verified: false,
+
VerificationCode: code,
+
}); err != nil {
+
log.Printf("adding email: %s", err)
+
s.Pages.Notice(w, "settings-emails-error", "Unable to add email at this moment, try again later.")
+
return
+
}
+
+
if err := s.sendVerificationEmail(w, did, emAddr, code, ""); err != nil {
+
return
+
}
+
+
// Commit transaction
+
if err := tx.Commit(); err != nil {
+
log.Printf("failed to commit transaction: %s", err)
+
s.Pages.Notice(w, "settings-emails-error", "Unable to add email at this moment, try again later.")
+
return
+
}
+
+
s.Pages.Notice(w, "settings-emails-success", "Click the link in the email we sent you to verify your email address.")
+
return
+
case http.MethodDelete:
+
did := s.Auth.GetDid(r)
+
emailAddr := r.FormValue("email")
+
emailAddr = strings.TrimSpace(emailAddr)
+
+
// Begin transaction
+
tx, err := s.Db.Begin()
+
if err != nil {
+
log.Printf("failed to start transaction: %s", err)
+
s.Pages.Notice(w, "settings-emails-error", "Unable to delete email at this moment, try again later.")
+
return
+
}
+
defer tx.Rollback()
+
+
if err := db.DeleteEmail(tx, did, emailAddr); err != nil {
+
log.Printf("deleting email: %s", err)
+
s.Pages.Notice(w, "settings-emails-error", "Unable to delete email at this moment, try again later.")
+
return
+
}
+
+
// Commit transaction
+
if err := tx.Commit(); err != nil {
+
log.Printf("failed to commit transaction: %s", err)
+
s.Pages.Notice(w, "settings-emails-error", "Unable to delete email at this moment, try again later.")
+
return
+
}
+
+
s.Pages.HxLocation(w, "/settings")
+
return
+
}
+
}
+
+
func (s *Settings) verifyUrl(did string, email string, code string) string {
+
var appUrl string
+
if s.Config.Dev {
+
appUrl = "http://" + s.Config.ListenAddr
+
} else {
+
appUrl = "https://tangled.sh"
+
}
+
+
return fmt.Sprintf("%s/settings/emails/verify?did=%s&email=%s&code=%s", appUrl, url.QueryEscape(did), url.QueryEscape(email), url.QueryEscape(code))
+
}
+
+
func (s *Settings) emailsVerify(w http.ResponseWriter, r *http.Request) {
+
q := r.URL.Query()
+
+
// Get the parameters directly from the query
+
emailAddr := q.Get("email")
+
did := q.Get("did")
+
code := q.Get("code")
+
+
valid, err := db.CheckValidVerificationCode(s.Db, did, emailAddr, code)
+
if err != nil {
+
log.Printf("checking email verification: %s", err)
+
s.Pages.Notice(w, "settings-emails-error", "Error verifying email. Please try again later.")
+
return
+
}
+
+
if !valid {
+
s.Pages.Notice(w, "settings-emails-error", "Invalid verification code. Please request a new verification email.")
+
return
+
}
+
+
// Mark email as verified in the database
+
if err := db.MarkEmailVerified(s.Db, did, emailAddr); err != nil {
+
log.Printf("marking email as verified: %s", err)
+
s.Pages.Notice(w, "settings-emails-error", "Error updating email verification status. Please try again later.")
+
return
+
}
+
+
http.Redirect(w, r, "/settings", http.StatusSeeOther)
+
}
+
+
func (s *Settings) emailsVerifyResend(w http.ResponseWriter, r *http.Request) {
+
if r.Method != http.MethodPost {
+
s.Pages.Notice(w, "settings-emails-error", "Invalid request method.")
+
return
+
}
+
+
did := s.Auth.GetDid(r)
+
emAddr := r.FormValue("email")
+
emAddr = strings.TrimSpace(emAddr)
+
+
if !email.IsValidEmail(emAddr) {
+
s.Pages.Notice(w, "settings-emails-error", "Invalid email address.")
+
return
+
}
+
+
// Check if email exists and is unverified
+
existingEmail, err := db.GetEmail(s.Db, did, emAddr)
+
if err != nil {
+
if errors.Is(err, sql.ErrNoRows) {
+
s.Pages.Notice(w, "settings-emails-error", "Email not found. Please add it first.")
+
} else {
+
log.Printf("checking for existing email: %s", err)
+
s.Pages.Notice(w, "settings-emails-error", "Unable to resend verification email at this moment, try again later.")
+
}
+
return
+
}
+
+
if existingEmail.Verified {
+
s.Pages.Notice(w, "settings-emails-error", "This email is already verified.")
+
return
+
}
+
+
// Check if last verification email was sent less than 10 minutes ago
+
if existingEmail.LastSent != nil {
+
timeSinceLastSent := time.Since(*existingEmail.LastSent)
+
if timeSinceLastSent < 10*time.Minute {
+
waitTime := 10*time.Minute - timeSinceLastSent
+
s.Pages.Notice(w, "settings-emails-error", fmt.Sprintf("Please wait %d minutes before requesting another verification email.", int(waitTime.Minutes()+1)))
+
return
+
}
+
}
+
+
// Generate new verification code
+
code := uuid.New().String()
+
+
// Begin transaction
+
tx, err := s.Db.Begin()
+
if err != nil {
+
log.Printf("failed to start transaction: %s", err)
+
s.Pages.Notice(w, "settings-emails-error", "Unable to resend verification email at this moment, try again later.")
+
return
+
}
+
defer tx.Rollback()
+
+
// Update the verification code and last sent time
+
if err := db.UpdateVerificationCode(tx, did, emAddr, code); err != nil {
+
log.Printf("updating email verification: %s", err)
+
s.Pages.Notice(w, "settings-emails-error", "Unable to resend verification email at this moment, try again later.")
+
return
+
}
+
+
// Send verification email
+
if err := s.sendVerificationEmail(w, did, emAddr, code, ""); err != nil {
+
return
+
}
+
+
// Commit transaction
+
if err := tx.Commit(); err != nil {
+
log.Printf("failed to commit transaction: %s", err)
+
s.Pages.Notice(w, "settings-emails-error", "Unable to resend verification email at this moment, try again later.")
+
return
+
}
+
+
s.Pages.Notice(w, "settings-emails-success", "Verification email resent. Click the link in the email we sent you to verify your email address.")
+
}
+
+
func (s *Settings) emailsPrimary(w http.ResponseWriter, r *http.Request) {
+
did := s.Auth.GetDid(r)
+
emailAddr := r.FormValue("email")
+
emailAddr = strings.TrimSpace(emailAddr)
+
+
if emailAddr == "" {
+
s.Pages.Notice(w, "settings-emails-error", "Email address cannot be empty.")
+
return
+
}
+
+
if err := db.MakeEmailPrimary(s.Db, did, emailAddr); err != nil {
+
log.Printf("setting primary email: %s", err)
+
s.Pages.Notice(w, "settings-emails-error", "Error setting primary email. Please try again later.")
+
return
+
}
+
+
s.Pages.HxLocation(w, "/settings")
+
}
+
+
func (s *Settings) keys(w http.ResponseWriter, r *http.Request) {
+
switch r.Method {
+
case http.MethodGet:
+
s.Pages.Notice(w, "settings-keys", "Unimplemented.")
+
log.Println("unimplemented")
+
return
+
case http.MethodPut:
+
did := s.Auth.GetDid(r)
+
key := r.FormValue("key")
+
key = strings.TrimSpace(key)
+
name := r.FormValue("name")
+
client, _ := s.Auth.AuthorizedClient(r)
+
+
_, _, _, _, err := ssh.ParseAuthorizedKey([]byte(key))
+
if err != nil {
+
log.Printf("parsing public key: %s", err)
+
s.Pages.Notice(w, "settings-keys", "That doesn't look like a valid public key. Make sure it's a <strong>public</strong> key.")
+
return
+
}
+
+
rkey := appview.TID()
+
+
tx, err := s.Db.Begin()
+
if err != nil {
+
log.Printf("failed to start tx; adding public key: %s", err)
+
s.Pages.Notice(w, "settings-keys", "Unable to add public key at this moment, try again later.")
+
return
+
}
+
defer tx.Rollback()
+
+
if err := db.AddPublicKey(tx, did, name, key, rkey); err != nil {
+
log.Printf("adding public key: %s", err)
+
s.Pages.Notice(w, "settings-keys", "Failed to add public key.")
+
return
+
}
+
+
// store in pds too
+
resp, err := comatproto.RepoPutRecord(r.Context(), client, &comatproto.RepoPutRecord_Input{
+
Collection: tangled.PublicKeyNSID,
+
Repo: did,
+
Rkey: rkey,
+
Record: &lexutil.LexiconTypeDecoder{
+
Val: &tangled.PublicKey{
+
Created: time.Now().Format(time.RFC3339),
+
Key: key,
+
Name: name,
+
}},
+
})
+
// invalid record
+
if err != nil {
+
log.Printf("failed to create record: %s", err)
+
s.Pages.Notice(w, "settings-keys", "Failed to create record.")
+
return
+
}
+
+
log.Println("created atproto record: ", resp.Uri)
+
+
err = tx.Commit()
+
if err != nil {
+
log.Printf("failed to commit tx; adding public key: %s", err)
+
s.Pages.Notice(w, "settings-keys", "Unable to add public key at this moment, try again later.")
+
return
+
}
+
+
s.Pages.HxLocation(w, "/settings")
+
return
+
+
case http.MethodDelete:
+
did := s.Auth.GetDid(r)
+
q := r.URL.Query()
+
+
name := q.Get("name")
+
rkey := q.Get("rkey")
+
key := q.Get("key")
+
+
log.Println(name)
+
log.Println(rkey)
+
log.Println(key)
+
+
client, _ := s.Auth.AuthorizedClient(r)
+
+
if err := db.RemovePublicKey(s.Db, did, name, key); err != nil {
+
log.Printf("removing public key: %s", err)
+
s.Pages.Notice(w, "settings-keys", "Failed to remove public key.")
+
return
+
}
+
+
if rkey != "" {
+
// remove from pds too
+
_, err := comatproto.RepoDeleteRecord(r.Context(), client, &comatproto.RepoDeleteRecord_Input{
+
Collection: tangled.PublicKeyNSID,
+
Repo: did,
+
Rkey: rkey,
+
})
+
+
// invalid record
+
if err != nil {
+
log.Printf("failed to delete record from PDS: %s", err)
+
s.Pages.Notice(w, "settings-keys", "Failed to remove key from PDS.")
+
return
+
}
+
}
+
log.Println("deleted successfully")
+
+
s.Pages.HxLocation(w, "/settings")
+
return
+
}
+
}
+2 -1
appview/state/follow.go
···
comatproto "github.com/bluesky-social/indigo/api/atproto"
lexutil "github.com/bluesky-social/indigo/lex/util"
tangled "tangled.sh/tangled.sh/core/api/tangled"
+
"tangled.sh/tangled.sh/core/appview"
"tangled.sh/tangled.sh/core/appview/db"
"tangled.sh/tangled.sh/core/appview/pages"
)
···
switch r.Method {
case http.MethodPost:
createdAt := time.Now().Format(time.RFC3339)
-
rkey := s.TID()
+
rkey := appview.TID()
resp, err := comatproto.RepoPutRecord(r.Context(), client, &comatproto.RepoPutRecord_Input{
Collection: tangled.GraphFollowNSID,
Repo: currentUser.Did,
+16 -93
appview/state/middleware.go
···
"strings"
"time"
-
comatproto "github.com/bluesky-social/indigo/api/atproto"
+
"slices"
+
"github.com/bluesky-social/indigo/atproto/identity"
-
"github.com/bluesky-social/indigo/xrpc"
"github.com/go-chi/chi/v5"
-
"tangled.sh/tangled.sh/core/appview"
-
"tangled.sh/tangled.sh/core/appview/auth"
"tangled.sh/tangled.sh/core/appview/db"
+
"tangled.sh/tangled.sh/core/appview/middleware"
)
-
type Middleware func(http.Handler) http.Handler
-
-
func AuthMiddleware(s *State) Middleware {
-
return func(next http.Handler) http.Handler {
-
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
-
redirectFunc := func(w http.ResponseWriter, r *http.Request) {
-
http.Redirect(w, r, "/login", http.StatusTemporaryRedirect)
-
}
-
if r.Header.Get("HX-Request") == "true" {
-
redirectFunc = func(w http.ResponseWriter, _ *http.Request) {
-
w.Header().Set("HX-Redirect", "/login")
-
w.WriteHeader(http.StatusOK)
-
}
-
}
-
-
session, err := s.auth.GetSession(r)
-
if session.IsNew || err != nil {
-
log.Printf("not logged in, redirecting")
-
redirectFunc(w, r)
-
return
-
}
-
-
authorized, ok := session.Values[appview.SessionAuthenticated].(bool)
-
if !ok || !authorized {
-
log.Printf("not logged in, redirecting")
-
redirectFunc(w, r)
-
return
-
}
-
-
// refresh if nearing expiry
-
// TODO: dedup with /login
-
expiryStr := session.Values[appview.SessionExpiry].(string)
-
expiry, err := time.Parse(time.RFC3339, expiryStr)
-
if err != nil {
-
log.Println("invalid expiry time", err)
-
redirectFunc(w, r)
-
return
-
}
-
pdsUrl, ok1 := session.Values[appview.SessionPds].(string)
-
did, ok2 := session.Values[appview.SessionDid].(string)
-
refreshJwt, ok3 := session.Values[appview.SessionRefreshJwt].(string)
-
-
if !ok1 || !ok2 || !ok3 {
-
log.Println("invalid expiry time", err)
-
redirectFunc(w, r)
-
return
-
}
-
-
if time.Now().After(expiry) {
-
log.Println("token expired, refreshing ...")
-
-
client := xrpc.Client{
-
Host: pdsUrl,
-
Auth: &xrpc.AuthInfo{
-
Did: did,
-
AccessJwt: refreshJwt,
-
RefreshJwt: refreshJwt,
-
},
-
}
-
atSession, err := comatproto.ServerRefreshSession(r.Context(), &client)
-
if err != nil {
-
log.Println("failed to refresh session", err)
-
redirectFunc(w, r)
-
return
-
}
-
-
sessionish := auth.RefreshSessionWrapper{atSession}
-
-
err = s.auth.StoreSession(r, w, &sessionish, pdsUrl)
-
if err != nil {
-
log.Printf("failed to store session for did: %s\n: %s", atSession.Did, err)
-
return
-
}
-
-
log.Println("successfully refreshed token")
-
}
-
-
next.ServeHTTP(w, r)
-
})
-
}
-
}
-
-
func knotRoleMiddleware(s *State, group string) Middleware {
+
func knotRoleMiddleware(s *State, group string) middleware.Middleware {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// requires auth also
···
}
}
-
func KnotOwner(s *State) Middleware {
+
func KnotOwner(s *State) middleware.Middleware {
return knotRoleMiddleware(s, "server:owner")
}
-
func RepoPermissionMiddleware(s *State, requiredPerm string) Middleware {
+
func RepoPermissionMiddleware(s *State, requiredPerm string) middleware.Middleware {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// requires auth also
···
return
}
-
ok, err := s.enforcer.E.Enforce(actor.Did, f.Knot, f.OwnerSlashRepo(), requiredPerm)
+
ok, err := s.enforcer.E.Enforce(actor.Did, f.Knot, f.DidSlashRepo(), requiredPerm)
if err != nil || !ok {
// we need a logged in user
log.Printf("%s does not have perms of a %s in repo %s", actor.Did, requiredPerm, f.OwnerSlashRepo())
···
})
}
-
func ResolveIdent(s *State) Middleware {
+
func ResolveIdent(s *State) middleware.Middleware {
+
excluded := []string{"favicon.ico"}
+
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
didOrHandle := chi.URLParam(req, "user")
+
if slices.Contains(excluded, didOrHandle) {
+
next.ServeHTTP(w, req)
+
return
+
}
id, err := s.resolver.ResolveIdent(req.Context(), didOrHandle)
if err != nil {
···
}
}
-
func ResolveRepo(s *State) Middleware {
+
func ResolveRepo(s *State) middleware.Middleware {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
repoName := chi.URLParam(req, "repo")
···
}
// middleware that is tacked on top of /{user}/{repo}/pulls/{pull}
-
func ResolvePull(s *State) Middleware {
+
func ResolvePull(s *State) middleware.Middleware {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
f, err := fullyResolvedRepo(r)
+4 -4
appview/state/profile.go
···
"log"
"net/http"
+
"github.com/bluesky-social/indigo/atproto/identity"
"github.com/go-chi/chi/v5"
"tangled.sh/tangled.sh/core/appview/db"
"tangled.sh/tangled.sh/core/appview/pages"
···
return
}
-
ident, err := s.resolver.ResolveIdent(r.Context(), didOrHandle)
-
if err != nil {
-
log.Printf("resolving identity: %s", err)
-
w.WriteHeader(http.StatusNotFound)
+
ident, ok := r.Context().Value("resolvedId").(identity.Identity)
+
if !ok {
+
s.pages.Error404(w)
return
}
+521 -265
appview/state/pull.go
···
"net/http"
"net/url"
"strconv"
-
"strings"
"time"
-
"github.com/go-chi/chi/v5"
"tangled.sh/tangled.sh/core/api/tangled"
+
"tangled.sh/tangled.sh/core/appview"
"tangled.sh/tangled.sh/core/appview/auth"
"tangled.sh/tangled.sh/core/appview/db"
"tangled.sh/tangled.sh/core/appview/pages"
+
"tangled.sh/tangled.sh/core/patchutil"
"tangled.sh/tangled.sh/core/types"
comatproto "github.com/bluesky-social/indigo/api/atproto"
"github.com/bluesky-social/indigo/atproto/syntax"
lexutil "github.com/bluesky-social/indigo/lex/util"
+
"github.com/go-chi/chi/v5"
)
// htmx fragment
···
resubmitResult = s.resubmitCheck(f, pull)
}
-
var pullSourceRepo *db.Repo
-
if pull.PullSource != nil {
-
if pull.PullSource.RepoAt != nil {
-
pullSourceRepo, err = db.GetRepoByAtUri(s.db, pull.PullSource.RepoAt.String())
-
if err != nil {
-
log.Printf("failed to get repo by at uri: %v", err)
-
return
-
}
-
}
-
}
-
s.pages.RepoSinglePull(w, pages.RepoSinglePullParams{
-
LoggedInUser: user,
-
RepoInfo: f.RepoInfo(s, user),
-
DidHandleMap: didHandleMap,
-
Pull: pull,
-
PullSourceRepo: pullSourceRepo,
-
MergeCheck: mergeCheckResponse,
-
ResubmitCheck: resubmitResult,
+
LoggedInUser: user,
+
RepoInfo: f.RepoInfo(s, user),
+
DidHandleMap: didHandleMap,
+
Pull: pull,
+
MergeCheck: mergeCheckResponse,
+
ResubmitCheck: resubmitResult,
})
}
···
latestSubmission := pull.Submissions[pull.LastRoundNumber()]
if latestSubmission.SourceRev != result.Branch.Hash {
+
fmt.Println(latestSubmission.SourceRev, result.Branch.Hash)
return pages.ShouldResubmit
}
···
}
}
+
diff := pull.Submissions[roundIdInt].AsNiceDiff(pull.TargetBranch)
+
s.pages.RepoPullPatchPage(w, pages.RepoPullPatchParams{
LoggedInUser: user,
DidHandleMap: didHandleMap,
···
Pull: pull,
Round: roundIdInt,
Submission: pull.Submissions[roundIdInt],
-
Diff: pull.Submissions[roundIdInt].AsNiceDiff(pull.TargetBranch),
+
Diff: &diff,
})
}
+
func (s *State) RepoPullInterdiff(w http.ResponseWriter, r *http.Request) {
+
user := s.auth.GetUser(r)
+
+
f, err := fullyResolvedRepo(r)
+
if err != nil {
+
log.Println("failed to get repo and knot", err)
+
return
+
}
+
+
pull, ok := r.Context().Value("pull").(*db.Pull)
+
if !ok {
+
log.Println("failed to get pull")
+
s.pages.Notice(w, "pull-error", "Failed to get pull.")
+
return
+
}
+
+
roundId := chi.URLParam(r, "round")
+
roundIdInt, err := strconv.Atoi(roundId)
+
if err != nil || roundIdInt >= len(pull.Submissions) {
+
http.Error(w, "bad round id", http.StatusBadRequest)
+
log.Println("failed to parse round id", err)
+
return
+
}
+
+
if roundIdInt == 0 {
+
http.Error(w, "bad round id", http.StatusBadRequest)
+
log.Println("cannot interdiff initial submission")
+
return
+
}
+
+
identsToResolve := []string{pull.OwnerDid}
+
resolvedIds := s.resolver.ResolveIdents(r.Context(), identsToResolve)
+
didHandleMap := make(map[string]string)
+
for _, identity := range resolvedIds {
+
if !identity.Handle.IsInvalidHandle() {
+
didHandleMap[identity.DID.String()] = fmt.Sprintf("@%s", identity.Handle.String())
+
} else {
+
didHandleMap[identity.DID.String()] = identity.DID.String()
+
}
+
}
+
+
currentPatch, err := pull.Submissions[roundIdInt].AsDiff(pull.TargetBranch)
+
if err != nil {
+
log.Println("failed to interdiff; current patch malformed")
+
s.pages.Notice(w, fmt.Sprintf("interdiff-error-%d", roundIdInt), "Failed to calculate interdiff; current patch is invalid.")
+
return
+
}
+
+
previousPatch, err := pull.Submissions[roundIdInt-1].AsDiff(pull.TargetBranch)
+
if err != nil {
+
log.Println("failed to interdiff; previous patch malformed")
+
s.pages.Notice(w, fmt.Sprintf("interdiff-error-%d", roundIdInt), "Failed to calculate interdiff; previous patch is invalid.")
+
return
+
}
+
+
interdiff := patchutil.Interdiff(previousPatch, currentPatch)
+
+
s.pages.RepoPullInterdiffPage(w, pages.RepoPullInterdiffParams{
+
LoggedInUser: s.auth.GetUser(r),
+
RepoInfo: f.RepoInfo(s, user),
+
Pull: pull,
+
Round: roundIdInt,
+
DidHandleMap: didHandleMap,
+
Interdiff: interdiff,
+
})
+
return
+
}
+
func (s *State) RepoPullPatchRaw(w http.ResponseWriter, r *http.Request) {
pull, ok := r.Context().Value("pull").(*db.Pull)
if !ok {
···
pullSourceRepo, err = db.GetRepoByAtUri(s.db, p.PullSource.RepoAt.String())
if err != nil {
log.Printf("failed to get repo by at uri: %v", err)
-
return
+
continue
+
} else {
+
p.PullSource.Repo = pullSourceRepo
}
}
-
p.PullSource.Repo = pullSourceRepo
}
}
···
atResp, err := comatproto.RepoPutRecord(r.Context(), client, &comatproto.RepoPutRecord_Input{
Collection: tangled.RepoPullCommentNSID,
Repo: user.Did,
-
Rkey: s.TID(),
+
Rkey: appview.TID(),
Record: &lexutil.LexiconTypeDecoder{
Val: &tangled.RepoPullComment{
Repo: &atUri,
···
sourceBranch := r.FormValue("sourceBranch")
patch := r.FormValue("patch")
-
// Validate required fields for all PR types
-
if title == "" || body == "" || targetBranch == "" {
-
s.pages.Notice(w, "pull", "Title, body and target branch are required.")
-
return
-
}
-
-
us, err := NewUnsignedClient(f.Knot, s.config.Dev)
-
if err != nil {
-
log.Println("failed to create unsigned client to %s: %v", f.Knot, err)
-
s.pages.Notice(w, "pull", "Failed to create a pull request. Try again later.")
-
return
-
}
-
-
caps, err := us.Capabilities()
-
if err != nil {
-
log.Println("error fetching knot caps", f.Knot, err)
-
s.pages.Notice(w, "pull", "Failed to create a pull request. Try again later.")
+
if targetBranch == "" {
+
s.pages.Notice(w, "pull", "Target branch is required.")
return
}
···
isBranchBased := isPushAllowed && sourceBranch != "" && fromFork == ""
isForkBased := fromFork != "" && sourceBranch != ""
isPatchBased := patch != "" && !isBranchBased && !isForkBased
+
+
if isPatchBased && !patchutil.IsFormatPatch(patch) {
+
if title == "" {
+
s.pages.Notice(w, "pull", "Title is required for git-diff patches.")
+
return
+
}
+
}
// Validate we have at least one valid PR creation method
if !isBranchBased && !isPatchBased && !isForkBased {
···
return
}
+
us, err := NewUnsignedClient(f.Knot, s.config.Dev)
+
if err != nil {
+
log.Printf("failed to create unsigned client to %s: %v", f.Knot, err)
+
s.pages.Notice(w, "pull", "Failed to create a pull request. Try again later.")
+
return
+
}
+
+
caps, err := us.Capabilities()
+
if err != nil {
+
log.Println("error fetching knot caps", f.Knot, err)
+
s.pages.Notice(w, "pull", "Failed to create a pull request. Try again later.")
+
return
+
}
+
+
if !caps.PullRequests.FormatPatch {
+
s.pages.Notice(w, "pull", "This knot doesn't support format-patch. Unfortunately, there is no fallback for now.")
+
return
+
}
+
// Handle the PR creation based on the type
if isBranchBased {
if !caps.PullRequests.BranchSubmissions {
···
return
}
-
resp, err := ksClient.Compare(f.OwnerDid(), f.RepoName, targetBranch, sourceBranch)
-
switch resp.StatusCode {
-
case 404:
-
case 400:
-
s.pages.Notice(w, "pull", "Branch based pull requests are not supported on this knot.")
-
return
-
}
-
-
respBody, err := io.ReadAll(resp.Body)
+
comparison, err := ksClient.Compare(f.OwnerDid(), f.RepoName, targetBranch, sourceBranch)
if err != nil {
-
log.Println("failed to compare across branches")
-
s.pages.Notice(w, "pull", "Failed to create pull request. Try again later.")
+
log.Println("failed to compare", err)
+
s.pages.Notice(w, "pull", err.Error())
return
}
-
defer resp.Body.Close()
-
var diffTreeResponse types.RepoDiffTreeResponse
-
err = json.Unmarshal(respBody, &diffTreeResponse)
-
if err != nil {
-
log.Println("failed to unmarshal diff tree response", err)
-
s.pages.Notice(w, "pull", "Failed to create pull request. Try again later.")
-
return
-
}
+
sourceRev := comparison.Rev2
+
patch := comparison.Patch
-
sourceRev := diffTreeResponse.DiffTree.Rev2
-
patch := diffTreeResponse.DiffTree.Patch
-
-
if !isPatchValid(patch) {
+
if !patchutil.IsPatchValid(patch) {
s.pages.Notice(w, "pull", "Invalid patch format. Please provide a valid diff.")
return
}
···
}
func (s *State) handlePatchBasedPull(w http.ResponseWriter, r *http.Request, f *FullyResolvedRepo, user *auth.User, title, body, targetBranch, patch string) {
-
if !isPatchValid(patch) {
+
if !patchutil.IsPatchValid(patch) {
s.pages.Notice(w, "pull", "Invalid patch format. Please provide a valid diff.")
return
}
···
// hiddenRef: hidden/feature-1/main (on repo-fork)
// targetBranch: main (on repo-1)
// sourceBranch: feature-1 (on repo-fork)
-
diffResp, err := us.Compare(user.Did, fork.Name, hiddenRef, sourceBranch)
+
comparison, err := us.Compare(user.Did, fork.Name, hiddenRef, sourceBranch)
if err != nil {
log.Println("failed to compare across branches", err)
-
s.pages.Notice(w, "pull", "Failed to create pull request. Try again later.")
+
s.pages.Notice(w, "pull", err.Error())
return
}
-
respBody, err := io.ReadAll(diffResp.Body)
-
if err != nil {
-
log.Println("failed to read response body", err)
-
s.pages.Notice(w, "pull", "Failed to create pull request. Try again later.")
-
return
-
}
+
sourceRev := comparison.Rev2
+
patch := comparison.Patch
-
defer resp.Body.Close()
-
-
var diffTreeResponse types.RepoDiffTreeResponse
-
err = json.Unmarshal(respBody, &diffTreeResponse)
-
if err != nil {
-
log.Println("failed to unmarshal diff tree response", err)
-
s.pages.Notice(w, "pull", "Failed to create pull request. Try again later.")
-
return
-
}
-
-
sourceRev := diffTreeResponse.DiffTree.Rev2
-
patch := diffTreeResponse.DiffTree.Patch
-
-
if !isPatchValid(patch) {
+
if !patchutil.IsPatchValid(patch) {
s.pages.Notice(w, "pull", "Invalid patch format. Please provide a valid diff.")
return
}
···
}, &tangled.RepoPull_Source{Branch: sourceBranch, Repo: &fork.AtUri})
}
-
func (s *State) createPullRequest(w http.ResponseWriter, r *http.Request, f *FullyResolvedRepo, user *auth.User, title, body, targetBranch, patch, sourceRev string, pullSource *db.PullSource, recordPullSource *tangled.RepoPull_Source) {
+
func (s *State) createPullRequest(
+
w http.ResponseWriter,
+
r *http.Request,
+
f *FullyResolvedRepo,
+
user *auth.User,
+
title, body, targetBranch string,
+
patch string,
+
sourceRev string,
+
pullSource *db.PullSource,
+
recordPullSource *tangled.RepoPull_Source,
+
) {
tx, err := s.db.BeginTx(r.Context(), nil)
if err != nil {
log.Println("failed to start tx")
···
}
defer tx.Rollback()
-
rkey := s.TID()
+
// We've already checked earlier if it's diff-based and title is empty,
+
// so if it's still empty now, it's intentionally skipped owing to format-patch.
+
if title == "" {
+
formatPatches, err := patchutil.ExtractPatches(patch)
+
if err != nil {
+
s.pages.Notice(w, "pull", fmt.Sprintf("Failed to extract patches: %v", err))
+
return
+
}
+
if len(formatPatches) == 0 {
+
s.pages.Notice(w, "pull", "No patches found in the supplied format-patch.")
+
return
+
}
+
+
title = formatPatches[0].Title
+
body = formatPatches[0].Body
+
}
+
+
rkey := appview.TID()
initialSubmission := db.PullSubmission{
Patch: patch,
SourceRev: sourceRev,
···
}
s.pages.HxLocation(w, fmt.Sprintf("/%s/pulls/%d", f.OwnerSlashRepo(), pullId))
+
}
+
+
func (s *State) ValidatePatch(w http.ResponseWriter, r *http.Request) {
+
_, err := fullyResolvedRepo(r)
+
if err != nil {
+
log.Println("failed to get repo and knot", err)
+
return
+
}
+
+
patch := r.FormValue("patch")
+
if patch == "" {
+
s.pages.Notice(w, "patch-error", "Patch is required.")
+
return
+
}
+
+
if patch == "" || !patchutil.IsPatchValid(patch) {
+
s.pages.Notice(w, "patch-error", "Invalid patch format. Please provide a valid git diff or format-patch.")
+
return
+
}
+
+
if patchutil.IsFormatPatch(patch) {
+
s.pages.Notice(w, "patch-preview", "git-format-patch detected. Title and description are optional; if left out, they will be extracted from the first commit.")
+
} else {
+
s.pages.Notice(w, "patch-preview", "Regular git-diff detected. Please provide a title and description.")
+
}
}
func (s *State) PatchUploadFragment(w http.ResponseWriter, r *http.Request) {
···
})
return
case http.MethodPost:
-
patch := r.FormValue("patch")
-
var sourceRev string
-
var recordPullSource *tangled.RepoPull_Source
-
-
var ownerDid, repoName, knotName string
-
var isSameRepo bool = pull.IsSameRepoBranch()
-
sourceBranch := pull.PullSource.Branch
-
targetBranch := pull.TargetBranch
-
recordPullSource = &tangled.RepoPull_Source{
-
Branch: sourceBranch,
+
if pull.IsPatchBased() {
+
s.resubmitPatch(w, r)
+
return
+
} else if pull.IsBranchBased() {
+
s.resubmitBranch(w, r)
+
return
+
} else if pull.IsForkBased() {
+
s.resubmitFork(w, r)
+
return
+
}
+
}
-
isPushAllowed := f.RepoInfo(s, user).Roles.IsPushAllowed()
-
if isSameRepo && isPushAllowed {
-
ownerDid = f.OwnerDid()
-
repoName = f.RepoName
-
knotName = f.Knot
-
} else if !isSameRepo {
-
sourceRepo, err := db.GetRepoByAtUri(s.db, pull.PullSource.RepoAt.String())
-
if err != nil {
-
log.Println("failed to get source repo", err)
-
s.pages.Notice(w, "pull", "Failed to create pull request. Try again later.")
-
return
-
}
-
ownerDid = sourceRepo.Did
-
repoName = sourceRepo.Name
-
knotName = sourceRepo.Knot
-
}
+
func (s *State) resubmitPatch(w http.ResponseWriter, r *http.Request) {
+
user := s.auth.GetUser(r)
-
if sourceBranch != "" && knotName != "" {
-
// extract patch by performing compare
-
ksClient, err := NewUnsignedClient(knotName, s.config.Dev)
-
if err != nil {
-
log.Printf("failed to create client for %s: %s", knotName, err)
-
s.pages.Notice(w, "pull", "Failed to create pull request. Try again later.")
-
return
-
}
+
pull, ok := r.Context().Value("pull").(*db.Pull)
+
if !ok {
+
log.Println("failed to get pull")
+
s.pages.Notice(w, "pull-error", "Failed to edit patch. Try again later.")
+
return
+
}
-
if !isSameRepo {
-
secret, err := db.GetRegistrationKey(s.db, knotName)
-
if err != nil {
-
log.Printf("failed to get registration key for %s: %s", knotName, err)
-
s.pages.Notice(w, "pull", "Failed to create pull request. Try again later.")
-
return
-
}
-
// update the hidden tracking branch to latest
-
signedClient, err := NewSignedClient(knotName, secret, s.config.Dev)
-
if err != nil {
-
log.Printf("failed to create signed client for %s: %s", knotName, err)
-
s.pages.Notice(w, "pull", "Failed to create pull request. Try again later.")
-
return
-
}
-
resp, err := signedClient.NewHiddenRef(ownerDid, repoName, sourceBranch, targetBranch)
-
if err != nil || resp.StatusCode != http.StatusNoContent {
-
log.Printf("failed to update tracking branch: %s", err)
-
s.pages.Notice(w, "pull", "Failed to create pull request. Try again later.")
-
return
-
}
-
}
+
f, err := fullyResolvedRepo(r)
+
if err != nil {
+
log.Println("failed to get repo and knot", err)
+
return
+
}
-
var compareResp *http.Response
-
if !isSameRepo {
-
hiddenRef := url.QueryEscape(fmt.Sprintf("hidden/%s/%s", sourceBranch, targetBranch))
-
compareResp, err = ksClient.Compare(ownerDid, repoName, hiddenRef, sourceBranch)
-
} else {
-
compareResp, err = ksClient.Compare(ownerDid, repoName, targetBranch, sourceBranch)
-
}
-
if err != nil {
-
log.Printf("failed to compare branches: %s", err)
-
s.pages.Notice(w, "pull", "Failed to create pull request. Try again later.")
-
return
-
}
-
defer compareResp.Body.Close()
+
if user.Did != pull.OwnerDid {
+
log.Println("unauthorized user")
+
w.WriteHeader(http.StatusUnauthorized)
+
return
+
}
-
switch compareResp.StatusCode {
-
case 404:
-
case 400:
-
s.pages.Notice(w, "pull", "Branch based pull requests are not supported on this knot.")
-
return
-
}
+
patch := r.FormValue("patch")
-
respBody, err := io.ReadAll(compareResp.Body)
-
if err != nil {
-
log.Println("failed to compare across branches")
-
s.pages.Notice(w, "pull", "Failed to create pull request. Try again later.")
-
return
-
}
-
defer compareResp.Body.Close()
+
if err = validateResubmittedPatch(pull, patch); err != nil {
+
s.pages.Notice(w, "resubmit-error", err.Error())
+
return
+
}
-
var diffTreeResponse types.RepoDiffTreeResponse
-
err = json.Unmarshal(respBody, &diffTreeResponse)
-
if err != nil {
-
log.Println("failed to unmarshal diff tree response", err)
-
s.pages.Notice(w, "pull", "Failed to create pull request. Try again later.")
-
return
-
}
+
tx, err := s.db.BeginTx(r.Context(), nil)
+
if err != nil {
+
log.Println("failed to start tx")
+
s.pages.Notice(w, "resubmit-error", "Failed to create pull request. Try again later.")
+
return
+
}
+
defer tx.Rollback()
+
+
err = db.ResubmitPull(tx, pull, patch, "")
+
if err != nil {
+
log.Println("failed to resubmit pull request", err)
+
s.pages.Notice(w, "resubmit-error", "Failed to resubmit pull request. Try again later.")
+
return
+
}
+
client, _ := s.auth.AuthorizedClient(r)
+
+
ex, err := comatproto.RepoGetRecord(r.Context(), client, "", tangled.RepoPullNSID, user.Did, pull.Rkey)
+
if err != nil {
+
// failed to get record
+
s.pages.Notice(w, "resubmit-error", "Failed to update pull, no record found on PDS.")
+
return
+
}
+
+
_, err = comatproto.RepoPutRecord(r.Context(), client, &comatproto.RepoPutRecord_Input{
+
Collection: tangled.RepoPullNSID,
+
Repo: user.Did,
+
Rkey: pull.Rkey,
+
SwapRecord: ex.Cid,
+
Record: &lexutil.LexiconTypeDecoder{
+
Val: &tangled.RepoPull{
+
Title: pull.Title,
+
PullId: int64(pull.PullId),
+
TargetRepo: string(f.RepoAt),
+
TargetBranch: pull.TargetBranch,
+
Patch: patch, // new patch
+
},
+
},
+
})
+
if err != nil {
+
log.Println("failed to update record", err)
+
s.pages.Notice(w, "resubmit-error", "Failed to update pull request on the PDS. Try again later.")
+
return
+
}
+
+
if err = tx.Commit(); err != nil {
+
log.Println("failed to commit transaction", err)
+
s.pages.Notice(w, "resubmit-error", "Failed to resubmit pull.")
+
return
+
}
+
+
s.pages.HxLocation(w, fmt.Sprintf("/%s/pulls/%d", f.OwnerSlashRepo(), pull.PullId))
+
return
+
}
-
sourceRev = diffTreeResponse.DiffTree.Rev2
-
patch = diffTreeResponse.DiffTree.Patch
-
}
+
func (s *State) resubmitBranch(w http.ResponseWriter, r *http.Request) {
+
user := s.auth.GetUser(r)
+
+
pull, ok := r.Context().Value("pull").(*db.Pull)
+
if !ok {
+
log.Println("failed to get pull")
+
s.pages.Notice(w, "resubmit-error", "Failed to edit patch. Try again later.")
+
return
+
}
+
+
f, err := fullyResolvedRepo(r)
+
if err != nil {
+
log.Println("failed to get repo and knot", err)
+
return
+
}
+
+
if user.Did != pull.OwnerDid {
+
log.Println("unauthorized user")
+
w.WriteHeader(http.StatusUnauthorized)
+
return
+
}
+
+
if !f.RepoInfo(s, user).Roles.IsPushAllowed() {
+
log.Println("unauthorized user")
+
w.WriteHeader(http.StatusUnauthorized)
+
return
+
}
-
if patch == "" {
-
s.pages.Notice(w, "resubmit-error", "Patch is empty.")
-
return
-
}
+
ksClient, err := NewUnsignedClient(f.Knot, s.config.Dev)
+
if err != nil {
+
log.Printf("failed to create client for %s: %s", f.Knot, err)
+
s.pages.Notice(w, "resubmit-error", "Failed to create pull request. Try again later.")
+
return
+
}
-
if patch == pull.LatestPatch() {
-
s.pages.Notice(w, "resubmit-error", "Patch is identical to previous submission.")
-
return
-
}
+
comparison, err := ksClient.Compare(f.OwnerDid(), f.RepoName, pull.TargetBranch, pull.PullSource.Branch)
+
if err != nil {
+
log.Printf("compare request failed: %s", err)
+
s.pages.Notice(w, "resubmit-error", err.Error())
+
return
+
}
+
+
sourceRev := comparison.Rev2
+
patch := comparison.Patch
-
if sourceRev == pull.Submissions[pull.LastRoundNumber()].SourceRev {
-
s.pages.Notice(w, "resubmit-error", "This branch has not changed since the last submission.")
-
return
-
}
+
if err = validateResubmittedPatch(pull, patch); err != nil {
+
s.pages.Notice(w, "resubmit-error", err.Error())
+
return
+
}
-
if !isPatchValid(patch) {
-
s.pages.Notice(w, "resubmit-error", "Invalid patch format. Please provide a valid diff.")
-
return
-
}
+
if sourceRev == pull.Submissions[pull.LastRoundNumber()].SourceRev {
+
s.pages.Notice(w, "resubmit-error", "This branch has not changed since the last submission.")
+
return
+
}
-
tx, err := s.db.BeginTx(r.Context(), nil)
-
if err != nil {
-
log.Println("failed to start tx")
-
s.pages.Notice(w, "resubmit-error", "Failed to create pull request. Try again later.")
-
return
-
}
-
defer tx.Rollback()
+
tx, err := s.db.BeginTx(r.Context(), nil)
+
if err != nil {
+
log.Println("failed to start tx")
+
s.pages.Notice(w, "resubmit-error", "Failed to create pull request. Try again later.")
+
return
+
}
+
defer tx.Rollback()
-
err = db.ResubmitPull(tx, pull, patch, sourceRev)
-
if err != nil {
-
log.Println("failed to create pull request", err)
-
s.pages.Notice(w, "resubmit-error", "Failed to create pull request. Try again later.")
-
return
-
}
-
client, _ := s.auth.AuthorizedClient(r)
+
err = db.ResubmitPull(tx, pull, patch, sourceRev)
+
if err != nil {
+
log.Println("failed to create pull request", err)
+
s.pages.Notice(w, "resubmit-error", "Failed to create pull request. Try again later.")
+
return
+
}
+
client, _ := s.auth.AuthorizedClient(r)
-
ex, err := comatproto.RepoGetRecord(r.Context(), client, "", tangled.RepoPullNSID, user.Did, pull.Rkey)
-
if err != nil {
-
// failed to get record
-
s.pages.Notice(w, "resubmit-error", "Failed to update pull, no record found on PDS.")
-
return
-
}
+
ex, err := comatproto.RepoGetRecord(r.Context(), client, "", tangled.RepoPullNSID, user.Did, pull.Rkey)
+
if err != nil {
+
// failed to get record
+
s.pages.Notice(w, "resubmit-error", "Failed to update pull, no record found on PDS.")
+
return
+
}
-
_, err = comatproto.RepoPutRecord(r.Context(), client, &comatproto.RepoPutRecord_Input{
-
Collection: tangled.RepoPullNSID,
-
Repo: user.Did,
-
Rkey: pull.Rkey,
-
SwapRecord: ex.Cid,
-
Record: &lexutil.LexiconTypeDecoder{
-
Val: &tangled.RepoPull{
-
Title: pull.Title,
-
PullId: int64(pull.PullId),
-
TargetRepo: string(f.RepoAt),
-
TargetBranch: pull.TargetBranch,
-
Patch: patch, // new patch
-
Source: recordPullSource,
-
},
+
recordPullSource := &tangled.RepoPull_Source{
+
Branch: pull.PullSource.Branch,
+
}
+
_, err = comatproto.RepoPutRecord(r.Context(), client, &comatproto.RepoPutRecord_Input{
+
Collection: tangled.RepoPullNSID,
+
Repo: user.Did,
+
Rkey: pull.Rkey,
+
SwapRecord: ex.Cid,
+
Record: &lexutil.LexiconTypeDecoder{
+
Val: &tangled.RepoPull{
+
Title: pull.Title,
+
PullId: int64(pull.PullId),
+
TargetRepo: string(f.RepoAt),
+
TargetBranch: pull.TargetBranch,
+
Patch: patch, // new patch
+
Source: recordPullSource,
},
-
})
-
if err != nil {
-
log.Println("failed to update record", err)
-
s.pages.Notice(w, "resubmit-error", "Failed to update pull request on the PDS. Try again later.")
-
return
-
}
+
},
+
})
+
if err != nil {
+
log.Println("failed to update record", err)
+
s.pages.Notice(w, "resubmit-error", "Failed to update pull request on the PDS. Try again later.")
+
return
+
}
+
+
if err = tx.Commit(); err != nil {
+
log.Println("failed to commit transaction", err)
+
s.pages.Notice(w, "resubmit-error", "Failed to resubmit pull.")
+
return
+
}
+
+
s.pages.HxLocation(w, fmt.Sprintf("/%s/pulls/%d", f.OwnerSlashRepo(), pull.PullId))
+
return
+
}
+
+
func (s *State) resubmitFork(w http.ResponseWriter, r *http.Request) {
+
user := s.auth.GetUser(r)
+
+
pull, ok := r.Context().Value("pull").(*db.Pull)
+
if !ok {
+
log.Println("failed to get pull")
+
s.pages.Notice(w, "resubmit-error", "Failed to edit patch. Try again later.")
+
return
+
}
+
+
f, err := fullyResolvedRepo(r)
+
if err != nil {
+
log.Println("failed to get repo and knot", err)
+
return
+
}
+
+
if user.Did != pull.OwnerDid {
+
log.Println("unauthorized user")
+
w.WriteHeader(http.StatusUnauthorized)
+
return
+
}
+
+
forkRepo, err := db.GetRepoByAtUri(s.db, pull.PullSource.RepoAt.String())
+
if err != nil {
+
log.Println("failed to get source repo", err)
+
s.pages.Notice(w, "resubmit-error", "Failed to create pull request. Try again later.")
+
return
+
}
+
+
// extract patch by performing compare
+
ksClient, err := NewUnsignedClient(forkRepo.Knot, s.config.Dev)
+
if err != nil {
+
log.Printf("failed to create client for %s: %s", forkRepo.Knot, err)
+
s.pages.Notice(w, "resubmit-error", "Failed to create pull request. Try again later.")
+
return
+
}
+
+
secret, err := db.GetRegistrationKey(s.db, forkRepo.Knot)
+
if err != nil {
+
log.Printf("failed to get registration key for %s: %s", forkRepo.Knot, err)
+
s.pages.Notice(w, "resubmit-error", "Failed to create pull request. Try again later.")
+
return
+
}
+
+
// update the hidden tracking branch to latest
+
signedClient, err := NewSignedClient(forkRepo.Knot, secret, s.config.Dev)
+
if err != nil {
+
log.Printf("failed to create signed client for %s: %s", forkRepo.Knot, err)
+
s.pages.Notice(w, "resubmit-error", "Failed to create pull request. Try again later.")
+
return
+
}
+
+
resp, err := signedClient.NewHiddenRef(forkRepo.Did, forkRepo.Name, pull.PullSource.Branch, pull.TargetBranch)
+
if err != nil || resp.StatusCode != http.StatusNoContent {
+
log.Printf("failed to update tracking branch: %s", err)
+
s.pages.Notice(w, "resubmit-error", "Failed to create pull request. Try again later.")
+
return
+
}
+
+
hiddenRef := url.QueryEscape(fmt.Sprintf("hidden/%s/%s", pull.PullSource.Branch, pull.TargetBranch))
+
comparison, err := ksClient.Compare(forkRepo.Did, forkRepo.Name, hiddenRef, pull.PullSource.Branch)
+
if err != nil {
+
log.Printf("failed to compare branches: %s", err)
+
s.pages.Notice(w, "resubmit-error", err.Error())
+
return
+
}
+
+
sourceRev := comparison.Rev2
+
patch := comparison.Patch
+
+
if err = validateResubmittedPatch(pull, patch); err != nil {
+
s.pages.Notice(w, "resubmit-error", err.Error())
+
return
+
}
+
+
if sourceRev == pull.Submissions[pull.LastRoundNumber()].SourceRev {
+
s.pages.Notice(w, "resubmit-error", "This branch has not changed since the last submission.")
+
return
+
}
-
if err = tx.Commit(); err != nil {
-
log.Println("failed to commit transaction", err)
-
s.pages.Notice(w, "resubmit-error", "Failed to resubmit pull.")
-
return
-
}
+
tx, err := s.db.BeginTx(r.Context(), nil)
+
if err != nil {
+
log.Println("failed to start tx")
+
s.pages.Notice(w, "resubmit-error", "Failed to create pull request. Try again later.")
+
return
+
}
+
defer tx.Rollback()
+
+
err = db.ResubmitPull(tx, pull, patch, sourceRev)
+
if err != nil {
+
log.Println("failed to create pull request", err)
+
s.pages.Notice(w, "resubmit-error", "Failed to create pull request. Try again later.")
+
return
+
}
+
client, _ := s.auth.AuthorizedClient(r)
-
s.pages.HxLocation(w, fmt.Sprintf("/%s/pulls/%d", f.OwnerSlashRepo(), pull.PullId))
+
ex, err := comatproto.RepoGetRecord(r.Context(), client, "", tangled.RepoPullNSID, user.Did, pull.Rkey)
+
if err != nil {
+
// failed to get record
+
s.pages.Notice(w, "resubmit-error", "Failed to update pull, no record found on PDS.")
return
+
+
repoAt := pull.PullSource.RepoAt.String()
+
recordPullSource := &tangled.RepoPull_Source{
+
Branch: pull.PullSource.Branch,
+
Repo: &repoAt,
+
}
+
_, err = comatproto.RepoPutRecord(r.Context(), client, &comatproto.RepoPutRecord_Input{
+
Collection: tangled.RepoPullNSID,
+
Repo: user.Did,
+
Rkey: pull.Rkey,
+
SwapRecord: ex.Cid,
+
Record: &lexutil.LexiconTypeDecoder{
+
Val: &tangled.RepoPull{
+
Title: pull.Title,
+
PullId: int64(pull.PullId),
+
TargetRepo: string(f.RepoAt),
+
TargetBranch: pull.TargetBranch,
+
Patch: patch, // new patch
+
Source: recordPullSource,
+
},
+
},
+
})
+
if err != nil {
+
log.Println("failed to update record", err)
+
s.pages.Notice(w, "resubmit-error", "Failed to update pull request on the PDS. Try again later.")
+
return
+
}
+
+
if err = tx.Commit(); err != nil {
+
log.Println("failed to commit transaction", err)
+
s.pages.Notice(w, "resubmit-error", "Failed to resubmit pull.")
+
return
+
}
+
+
s.pages.HxLocation(w, fmt.Sprintf("/%s/pulls/%d", f.OwnerSlashRepo(), pull.PullId))
+
return
+
}
+
+
// validate a resubmission against a pull request
+
func validateResubmittedPatch(pull *db.Pull, patch string) error {
+
if patch == "" {
+
return fmt.Errorf("Patch is empty.")
+
}
+
+
if patch == pull.LatestPatch() {
+
return fmt.Errorf("Patch is identical to previous submission.")
+
}
+
+
if !patchutil.IsPatchValid(patch) {
+
return fmt.Errorf("Invalid patch format. Please provide a valid diff.")
+
}
+
+
return nil
func (s *State) MergePull(w http.ResponseWriter, r *http.Request) {
···
s.pages.HxLocation(w, fmt.Sprintf("/%s/pulls/%d", f.OwnerSlashRepo(), pull.PullId))
return
-
-
// Very basic validation to check if it looks like a diff/patch
-
// A valid patch usually starts with diff or --- lines
-
func isPatchValid(patch string) bool {
-
// Basic validation to check if it looks like a diff/patch
-
// A valid patch usually starts with diff or --- lines
-
if len(patch) == 0 {
-
return false
-
}
-
-
lines := strings.Split(patch, "\n")
-
if len(lines) < 2 {
-
return false
-
}
-
-
// Check for common patch format markers
-
firstLine := strings.TrimSpace(lines[0])
-
return strings.HasPrefix(firstLine, "diff ") ||
-
strings.HasPrefix(firstLine, "--- ") ||
-
strings.HasPrefix(firstLine, "Index: ") ||
-
strings.HasPrefix(firstLine, "+++ ") ||
-
strings.HasPrefix(firstLine, "@@ ")
-
}
+44 -15
appview/state/repo.go
···
"github.com/bluesky-social/indigo/atproto/syntax"
securejoin "github.com/cyphar/filepath-securejoin"
"github.com/go-chi/chi/v5"
+
"github.com/go-git/go-git/v5/plumbing"
"tangled.sh/tangled.sh/core/api/tangled"
+
"tangled.sh/tangled.sh/core/appview"
"tangled.sh/tangled.sh/core/appview/auth"
"tangled.sh/tangled.sh/core/appview/db"
"tangled.sh/tangled.sh/core/appview/pages"
"tangled.sh/tangled.sh/core/appview/pages/markup"
+
"tangled.sh/tangled.sh/core/appview/pagination"
"tangled.sh/tangled.sh/core/types"
comatproto "github.com/bluesky-social/indigo/api/atproto"
···
if !s.config.Dev {
protocol = "https"
}
+
+
if !plumbing.IsHash(ref) {
+
s.pages.Error404(w)
+
return
+
}
+
resp, err := http.Get(fmt.Sprintf("%s://%s/%s/%s/commit/%s", protocol, f.Knot, f.OwnerDid(), f.RepoName, ref))
if err != nil {
log.Println("failed to reach knotserver", err)
···
user := s.auth.GetUser(r)
var breadcrumbs [][]string
-
breadcrumbs = append(breadcrumbs, []string{f.RepoName, fmt.Sprintf("/%s/%s/tree/%s", f.OwnerDid(), f.RepoName, ref)})
+
breadcrumbs = append(breadcrumbs, []string{f.RepoName, fmt.Sprintf("/%s/tree/%s", f.OwnerSlashRepo(), ref)})
if treePath != "" {
for idx, elem := range strings.Split(treePath, "/") {
breadcrumbs = append(breadcrumbs, []string{elem, fmt.Sprintf("%s/%s", breadcrumbs[idx][1], elem)})
}
}
-
baseTreeLink := path.Join(f.OwnerDid(), f.RepoName, "tree", ref, treePath)
-
baseBlobLink := path.Join(f.OwnerDid(), f.RepoName, "blob", ref, treePath)
+
baseTreeLink := path.Join(f.OwnerSlashRepo(), "tree", ref, treePath)
+
baseBlobLink := path.Join(f.OwnerSlashRepo(), "blob", ref, treePath)
s.pages.RepoTree(w, pages.RepoTreeParams{
LoggedInUser: user,
···
}
var breadcrumbs [][]string
-
breadcrumbs = append(breadcrumbs, []string{f.RepoName, fmt.Sprintf("/%s/%s/tree/%s", f.OwnerDid(), f.RepoName, ref)})
+
breadcrumbs = append(breadcrumbs, []string{f.RepoName, fmt.Sprintf("/%s/tree/%s", f.OwnerSlashRepo(), ref)})
if filePath != "" {
for idx, elem := range strings.Split(filePath, "/") {
breadcrumbs = append(breadcrumbs, []string{elem, fmt.Sprintf("%s/%s", breadcrumbs[idx][1], elem)})
···
}
}()
-
err = s.enforcer.AddCollaborator(collaboratorIdent.DID.String(), f.Knot, f.OwnerSlashRepo())
+
err = s.enforcer.AddCollaborator(collaboratorIdent.DID.String(), f.Knot, f.DidSlashRepo())
if err != nil {
w.Write([]byte(fmt.Sprint("failed to add collaborator: ", err)))
return
···
}()
// remove collaborator RBAC
-
repoCollaborators, err := s.enforcer.E.GetImplicitUsersForResourceByDomain(f.OwnerSlashRepo(), f.Knot)
+
repoCollaborators, err := s.enforcer.E.GetImplicitUsersForResourceByDomain(f.DidSlashRepo(), f.Knot)
if err != nil {
s.pages.Notice(w, "settings-delete", "Failed to remove collaborators")
return
}
for _, c := range repoCollaborators {
did := c[0]
-
s.enforcer.RemoveCollaborator(did, f.Knot, f.OwnerSlashRepo())
+
s.enforcer.RemoveCollaborator(did, f.Knot, f.DidSlashRepo())
}
log.Println("removed collaborators")
// remove repo RBAC
-
err = s.enforcer.RemoveRepo(f.OwnerDid(), f.Knot, f.OwnerSlashRepo())
+
err = s.enforcer.RemoveRepo(f.OwnerDid(), f.Knot, f.DidSlashRepo())
if err != nil {
s.pages.Notice(w, "settings-delete", "Failed to update RBAC rules")
return
···
isCollaboratorInviteAllowed := false
if user != nil {
-
ok, err := s.enforcer.IsCollaboratorInviteAllowed(user.Did, f.Knot, f.OwnerSlashRepo())
+
ok, err := s.enforcer.IsCollaboratorInviteAllowed(user.Did, f.Knot, f.DidSlashRepo())
if err == nil && ok {
isCollaboratorInviteAllowed = true
}
···
}
func (f *FullyResolvedRepo) OwnerSlashRepo() string {
+
handle := f.OwnerId.Handle
+
+
var p string
+
if handle != "" && !handle.IsInvalidHandle() {
+
p, _ = securejoin.SecureJoin(fmt.Sprintf("@%s", handle), f.RepoName)
+
} else {
+
p, _ = securejoin.SecureJoin(f.OwnerDid(), f.RepoName)
+
}
+
+
return p
+
}
+
+
func (f *FullyResolvedRepo) DidSlashRepo() string {
p, _ := securejoin.SecureJoin(f.OwnerDid(), f.RepoName)
return p
}
func (f *FullyResolvedRepo) Collaborators(ctx context.Context, s *State) ([]pages.Collaborator, error) {
-
repoCollaborators, err := s.enforcer.E.GetImplicitUsersForResourceByDomain(f.OwnerSlashRepo(), f.Knot)
+
repoCollaborators, err := s.enforcer.E.GetImplicitUsersForResourceByDomain(f.DidSlashRepo(), f.Knot)
if err != nil {
return nil, err
}
···
_, err = comatproto.RepoPutRecord(r.Context(), client, &comatproto.RepoPutRecord_Input{
Collection: tangled.RepoIssueStateNSID,
Repo: user.Did,
-
Rkey: s.TID(),
+
Rkey: appview.TID(),
Record: &lexutil.LexiconTypeDecoder{
Val: &tangled.RepoIssueState{
Issue: issue.IssueAt,
···
commentId := mathrand.IntN(1000000)
-
rkey := s.TID()
+
rkey := appview.TID()
err := db.NewIssueComment(s.db, &db.Comment{
OwnerDid: user.Did,
···
isOpen = true
+
page, ok := r.Context().Value("page").(pagination.Page)
+
if !ok {
+
log.Println("failed to get page")
+
page = pagination.FirstPage()
+
}
+
user := s.auth.GetUser(r)
f, err := fullyResolvedRepo(r)
if err != nil {
···
return
-
issues, err := db.GetIssues(s.db, f.RepoAt, isOpen)
+
issues, err := db.GetIssues(s.db, f.RepoAt, isOpen, page)
if err != nil {
log.Println("failed to get issues", err)
s.pages.Notice(w, "issues", "Failed to load issues. Try again later.")
···
Issues: issues,
DidHandleMap: didHandleMap,
FilteringByOpen: isOpen,
+
Page: page,
})
return
···
resp, err := comatproto.RepoPutRecord(r.Context(), client, &comatproto.RepoPutRecord_Input{
Collection: tangled.RepoIssueNSID,
Repo: user.Did,
-
Rkey: s.TID(),
+
Rkey: appview.TID(),
Record: &lexutil.LexiconTypeDecoder{
Val: &tangled.RepoIssue{
Repo: atUri,
···
sourceUrl := fmt.Sprintf("%s://%s/%s/%s", uri, f.Knot, f.OwnerDid(), f.RepoName)
sourceAt := f.RepoAt.String()
-
rkey := s.TID()
+
rkey := appview.TID()
repo := &db.Repo{
Did: user.Did,
Name: forkName,
+1 -1
appview/state/repo_util.go
···
func RolesInRepo(s *State, u *auth.User, f *FullyResolvedRepo) pages.RolesInRepo {
if u != nil {
-
r := s.enforcer.GetPermissionsInRepo(u.Did, f.Knot, f.OwnerSlashRepo())
+
r := s.enforcer.GetPermissionsInRepo(u.Did, f.Knot, f.DidSlashRepo())
return pages.RolesInRepo{r}
} else {
return pages.RolesInRepo{}
+28 -23
appview/state/router.go
···
"strings"
"github.com/go-chi/chi/v5"
+
"tangled.sh/tangled.sh/core/appview/middleware"
+
"tangled.sh/tangled.sh/core/appview/settings"
"tangled.sh/tangled.sh/core/appview/state/userutil"
)
···
r.Get("/blob/{ref}/raw/*", s.RepoBlobRaw)
r.Route("/issues", func(r chi.Router) {
-
r.Get("/", s.RepoIssues)
+
r.With(middleware.Paginate).Get("/", s.RepoIssues)
r.Get("/{issue}", s.RepoSingleIssue)
r.Group(func(r chi.Router) {
-
r.Use(AuthMiddleware(s))
+
r.Use(middleware.AuthMiddleware(s.auth))
r.Get("/new", s.NewIssue)
r.Post("/new", s.NewIssue)
r.Post("/{issue}/comment", s.NewIssueComment)
···
})
r.Route("/fork", func(r chi.Router) {
-
r.Use(AuthMiddleware(s))
+
r.Use(middleware.AuthMiddleware(s.auth))
r.Get("/", s.ForkRepo)
r.Post("/", s.ForkRepo)
})
r.Route("/pulls", func(r chi.Router) {
r.Get("/", s.RepoPulls)
-
r.With(AuthMiddleware(s)).Route("/new", func(r chi.Router) {
+
r.With(middleware.AuthMiddleware(s.auth)).Route("/new", func(r chi.Router) {
r.Get("/", s.NewPull)
r.Get("/patch-upload", s.PatchUploadFragment)
+
r.Post("/validate-patch", s.ValidatePatch)
r.Get("/compare-branches", s.CompareBranchesFragment)
r.Get("/compare-forks", s.CompareForksFragment)
r.Get("/fork-branches", s.CompareForksBranchesFragment)
···
r.Route("/round/{round}", func(r chi.Router) {
r.Get("/", s.RepoPullPatch)
+
r.Get("/interdiff", s.RepoPullInterdiff)
r.Get("/actions", s.PullActions)
-
r.With(AuthMiddleware(s)).Route("/comment", func(r chi.Router) {
+
r.With(middleware.AuthMiddleware(s.auth)).Route("/comment", func(r chi.Router) {
r.Get("/", s.PullComment)
r.Post("/", s.PullComment)
})
···
})
r.Group(func(r chi.Router) {
-
r.Use(AuthMiddleware(s))
+
r.Use(middleware.AuthMiddleware(s.auth))
r.Route("/resubmit", func(r chi.Router) {
r.Get("/", s.ResubmitPull)
r.Post("/", s.ResubmitPull)
···
// settings routes, needs auth
r.Group(func(r chi.Router) {
-
r.Use(AuthMiddleware(s))
+
r.Use(middleware.AuthMiddleware(s.auth))
// repo description can only be edited by owner
r.With(RepoPermissionMiddleware(s, "repo:owner")).Route("/description", func(r chi.Router) {
r.Put("/", s.RepoDescription)
···
r.Get("/", s.Timeline)
-
r.With(AuthMiddleware(s)).Post("/logout", s.Logout)
+
r.With(middleware.AuthMiddleware(s.auth)).Post("/logout", s.Logout)
r.Route("/login", func(r chi.Router) {
r.Get("/", s.Login)
···
})
r.Route("/knots", func(r chi.Router) {
-
r.Use(AuthMiddleware(s))
+
r.Use(middleware.AuthMiddleware(s.auth))
r.Get("/", s.Knots)
r.Post("/key", s.RegistrationKey)
···
r.Route("/repo", func(r chi.Router) {
r.Route("/new", func(r chi.Router) {
-
r.Use(AuthMiddleware(s))
+
r.Use(middleware.AuthMiddleware(s.auth))
r.Get("/", s.NewRepo)
r.Post("/", s.NewRepo)
})
// r.Post("/import", s.ImportRepo)
})
-
r.With(AuthMiddleware(s)).Route("/follow", func(r chi.Router) {
+
r.With(middleware.AuthMiddleware(s.auth)).Route("/follow", func(r chi.Router) {
r.Post("/", s.Follow)
r.Delete("/", s.Follow)
})
-
r.With(AuthMiddleware(s)).Route("/star", func(r chi.Router) {
+
r.With(middleware.AuthMiddleware(s.auth)).Route("/star", func(r chi.Router) {
r.Post("/", s.Star)
r.Delete("/", s.Star)
})
-
r.Route("/settings", func(r chi.Router) {
-
r.Use(AuthMiddleware(s))
-
r.Get("/", s.Settings)
-
r.Put("/keys", s.SettingsKeys)
-
r.Delete("/keys", s.SettingsKeys)
-
r.Put("/emails", s.SettingsEmails)
-
r.Delete("/emails", s.SettingsEmails)
-
r.Get("/emails/verify", s.SettingsEmailsVerify)
-
r.Post("/emails/verify/resend", s.SettingsEmailsVerifyResend)
-
r.Post("/emails/primary", s.SettingsEmailsPrimary)
-
})
+
r.Mount("/settings", s.SettingsRouter())
r.Get("/keys/{user}", s.Keys)
···
})
return r
}
+
+
func (s *State) SettingsRouter() http.Handler {
+
settings := &settings.Settings{
+
Db: s.db,
+
Auth: s.auth,
+
Pages: s.pages,
+
Config: s.config,
+
}
+
+
return settings.Router()
+
}
-416
appview/state/settings.go
···
-
package state
-
-
import (
-
"database/sql"
-
"errors"
-
"fmt"
-
"log"
-
"net/http"
-
"net/url"
-
"strings"
-
"time"
-
-
comatproto "github.com/bluesky-social/indigo/api/atproto"
-
lexutil "github.com/bluesky-social/indigo/lex/util"
-
"github.com/gliderlabs/ssh"
-
"github.com/google/uuid"
-
"tangled.sh/tangled.sh/core/api/tangled"
-
"tangled.sh/tangled.sh/core/appview/db"
-
"tangled.sh/tangled.sh/core/appview/email"
-
"tangled.sh/tangled.sh/core/appview/pages"
-
)
-
-
func (s *State) Settings(w http.ResponseWriter, r *http.Request) {
-
user := s.auth.GetUser(r)
-
pubKeys, err := db.GetPublicKeys(s.db, user.Did)
-
if err != nil {
-
log.Println(err)
-
}
-
-
emails, err := db.GetAllEmails(s.db, user.Did)
-
if err != nil {
-
log.Println(err)
-
}
-
-
s.pages.Settings(w, pages.SettingsParams{
-
LoggedInUser: user,
-
PubKeys: pubKeys,
-
Emails: emails,
-
})
-
}
-
-
// buildVerificationEmail creates an email.Email struct for verification emails
-
func (s *State) buildVerificationEmail(emailAddr, did, code string) email.Email {
-
verifyURL := s.verifyUrl(did, emailAddr, code)
-
-
return email.Email{
-
APIKey: s.config.ResendApiKey,
-
From: "noreply@notifs.tangled.sh",
-
To: emailAddr,
-
Subject: "Verify your Tangled email",
-
Text: `Click the link below (or copy and paste it into your browser) to verify your email address.
-
` + verifyURL,
-
Html: `<p>Click the link (or copy and paste it into your browser) to verify your email address.</p>
-
<p><a href="` + verifyURL + `">` + verifyURL + `</a></p>`,
-
}
-
}
-
-
// sendVerificationEmail handles the common logic for sending verification emails
-
func (s *State) sendVerificationEmail(w http.ResponseWriter, did, emailAddr, code string, errorContext string) error {
-
emailToSend := s.buildVerificationEmail(emailAddr, did, code)
-
-
err := email.SendEmail(emailToSend)
-
if err != nil {
-
log.Printf("sending email: %s", err)
-
s.pages.Notice(w, "settings-emails-error", fmt.Sprintf("Unable to send verification email at this moment, try again later. %s", errorContext))
-
return err
-
}
-
-
return nil
-
}
-
-
func (s *State) SettingsEmails(w http.ResponseWriter, r *http.Request) {
-
switch r.Method {
-
case http.MethodGet:
-
s.pages.Notice(w, "settings-emails", "Unimplemented.")
-
log.Println("unimplemented")
-
return
-
case http.MethodPut:
-
did := s.auth.GetDid(r)
-
emAddr := r.FormValue("email")
-
emAddr = strings.TrimSpace(emAddr)
-
-
if !email.IsValidEmail(emAddr) {
-
s.pages.Notice(w, "settings-emails-error", "Invalid email address.")
-
return
-
}
-
-
// check if email already exists in database
-
existingEmail, err := db.GetEmail(s.db, did, emAddr)
-
if err != nil && !errors.Is(err, sql.ErrNoRows) {
-
log.Printf("checking for existing email: %s", err)
-
s.pages.Notice(w, "settings-emails-error", "Unable to add email at this moment, try again later.")
-
return
-
}
-
-
if err == nil {
-
if existingEmail.Verified {
-
s.pages.Notice(w, "settings-emails-error", "This email is already verified.")
-
return
-
}
-
-
s.pages.Notice(w, "settings-emails-error", "This email is already added but not verified. Check your inbox for the verification link.")
-
return
-
}
-
-
code := uuid.New().String()
-
-
// Begin transaction
-
tx, err := s.db.Begin()
-
if err != nil {
-
log.Printf("failed to start transaction: %s", err)
-
s.pages.Notice(w, "settings-emails-error", "Unable to add email at this moment, try again later.")
-
return
-
}
-
defer tx.Rollback()
-
-
if err := db.AddEmail(tx, db.Email{
-
Did: did,
-
Address: emAddr,
-
Verified: false,
-
VerificationCode: code,
-
}); err != nil {
-
log.Printf("adding email: %s", err)
-
s.pages.Notice(w, "settings-emails-error", "Unable to add email at this moment, try again later.")
-
return
-
}
-
-
if err := s.sendVerificationEmail(w, did, emAddr, code, ""); err != nil {
-
return
-
}
-
-
// Commit transaction
-
if err := tx.Commit(); err != nil {
-
log.Printf("failed to commit transaction: %s", err)
-
s.pages.Notice(w, "settings-emails-error", "Unable to add email at this moment, try again later.")
-
return
-
}
-
-
s.pages.Notice(w, "settings-emails-success", "Click the link in the email we sent you to verify your email address.")
-
return
-
case http.MethodDelete:
-
did := s.auth.GetDid(r)
-
emailAddr := r.FormValue("email")
-
emailAddr = strings.TrimSpace(emailAddr)
-
-
// Begin transaction
-
tx, err := s.db.Begin()
-
if err != nil {
-
log.Printf("failed to start transaction: %s", err)
-
s.pages.Notice(w, "settings-emails-error", "Unable to delete email at this moment, try again later.")
-
return
-
}
-
defer tx.Rollback()
-
-
if err := db.DeleteEmail(tx, did, emailAddr); err != nil {
-
log.Printf("deleting email: %s", err)
-
s.pages.Notice(w, "settings-emails-error", "Unable to delete email at this moment, try again later.")
-
return
-
}
-
-
// Commit transaction
-
if err := tx.Commit(); err != nil {
-
log.Printf("failed to commit transaction: %s", err)
-
s.pages.Notice(w, "settings-emails-error", "Unable to delete email at this moment, try again later.")
-
return
-
}
-
-
s.pages.HxLocation(w, "/settings")
-
return
-
}
-
}
-
-
func (s *State) verifyUrl(did string, email string, code string) string {
-
var appUrl string
-
if s.config.Dev {
-
appUrl = "http://" + s.config.ListenAddr
-
} else {
-
appUrl = "https://tangled.sh"
-
}
-
-
return fmt.Sprintf("%s/settings/emails/verify?did=%s&email=%s&code=%s", appUrl, url.QueryEscape(did), url.QueryEscape(email), url.QueryEscape(code))
-
}
-
-
func (s *State) SettingsEmailsVerify(w http.ResponseWriter, r *http.Request) {
-
q := r.URL.Query()
-
-
// Get the parameters directly from the query
-
emailAddr := q.Get("email")
-
did := q.Get("did")
-
code := q.Get("code")
-
-
valid, err := db.CheckValidVerificationCode(s.db, did, emailAddr, code)
-
if err != nil {
-
log.Printf("checking email verification: %s", err)
-
s.pages.Notice(w, "settings-emails-error", "Error verifying email. Please try again later.")
-
return
-
}
-
-
if !valid {
-
s.pages.Notice(w, "settings-emails-error", "Invalid verification code. Please request a new verification email.")
-
return
-
}
-
-
// Mark email as verified in the database
-
if err := db.MarkEmailVerified(s.db, did, emailAddr); err != nil {
-
log.Printf("marking email as verified: %s", err)
-
s.pages.Notice(w, "settings-emails-error", "Error updating email verification status. Please try again later.")
-
return
-
}
-
-
http.Redirect(w, r, "/settings", http.StatusSeeOther)
-
}
-
-
func (s *State) SettingsEmailsVerifyResend(w http.ResponseWriter, r *http.Request) {
-
if r.Method != http.MethodPost {
-
s.pages.Notice(w, "settings-emails-error", "Invalid request method.")
-
return
-
}
-
-
did := s.auth.GetDid(r)
-
emAddr := r.FormValue("email")
-
emAddr = strings.TrimSpace(emAddr)
-
-
if !email.IsValidEmail(emAddr) {
-
s.pages.Notice(w, "settings-emails-error", "Invalid email address.")
-
return
-
}
-
-
// Check if email exists and is unverified
-
existingEmail, err := db.GetEmail(s.db, did, emAddr)
-
if err != nil {
-
if errors.Is(err, sql.ErrNoRows) {
-
s.pages.Notice(w, "settings-emails-error", "Email not found. Please add it first.")
-
} else {
-
log.Printf("checking for existing email: %s", err)
-
s.pages.Notice(w, "settings-emails-error", "Unable to resend verification email at this moment, try again later.")
-
}
-
return
-
}
-
-
if existingEmail.Verified {
-
s.pages.Notice(w, "settings-emails-error", "This email is already verified.")
-
return
-
}
-
-
// Check if last verification email was sent less than 10 minutes ago
-
if existingEmail.LastSent != nil {
-
timeSinceLastSent := time.Since(*existingEmail.LastSent)
-
if timeSinceLastSent < 10*time.Minute {
-
waitTime := 10*time.Minute - timeSinceLastSent
-
s.pages.Notice(w, "settings-emails-error", fmt.Sprintf("Please wait %d minutes before requesting another verification email.", int(waitTime.Minutes()+1)))
-
return
-
}
-
}
-
-
// Generate new verification code
-
code := uuid.New().String()
-
-
// Begin transaction
-
tx, err := s.db.Begin()
-
if err != nil {
-
log.Printf("failed to start transaction: %s", err)
-
s.pages.Notice(w, "settings-emails-error", "Unable to resend verification email at this moment, try again later.")
-
return
-
}
-
defer tx.Rollback()
-
-
// Update the verification code and last sent time
-
if err := db.UpdateVerificationCode(tx, did, emAddr, code); err != nil {
-
log.Printf("updating email verification: %s", err)
-
s.pages.Notice(w, "settings-emails-error", "Unable to resend verification email at this moment, try again later.")
-
return
-
}
-
-
// Send verification email
-
if err := s.sendVerificationEmail(w, did, emAddr, code, ""); err != nil {
-
return
-
}
-
-
// Commit transaction
-
if err := tx.Commit(); err != nil {
-
log.Printf("failed to commit transaction: %s", err)
-
s.pages.Notice(w, "settings-emails-error", "Unable to resend verification email at this moment, try again later.")
-
return
-
}
-
-
s.pages.Notice(w, "settings-emails-success", "Verification email resent. Click the link in the email we sent you to verify your email address.")
-
}
-
-
func (s *State) SettingsEmailsPrimary(w http.ResponseWriter, r *http.Request) {
-
did := s.auth.GetDid(r)
-
emailAddr := r.FormValue("email")
-
emailAddr = strings.TrimSpace(emailAddr)
-
-
if emailAddr == "" {
-
s.pages.Notice(w, "settings-emails-error", "Email address cannot be empty.")
-
return
-
}
-
-
if err := db.MakeEmailPrimary(s.db, did, emailAddr); err != nil {
-
log.Printf("setting primary email: %s", err)
-
s.pages.Notice(w, "settings-emails-error", "Error setting primary email. Please try again later.")
-
return
-
}
-
-
s.pages.HxLocation(w, "/settings")
-
}
-
-
func (s *State) SettingsKeys(w http.ResponseWriter, r *http.Request) {
-
switch r.Method {
-
case http.MethodGet:
-
s.pages.Notice(w, "settings-keys", "Unimplemented.")
-
log.Println("unimplemented")
-
return
-
case http.MethodPut:
-
did := s.auth.GetDid(r)
-
key := r.FormValue("key")
-
key = strings.TrimSpace(key)
-
name := r.FormValue("name")
-
client, _ := s.auth.AuthorizedClient(r)
-
-
_, _, _, _, err := ssh.ParseAuthorizedKey([]byte(key))
-
if err != nil {
-
log.Printf("parsing public key: %s", err)
-
s.pages.Notice(w, "settings-keys", "That doesn't look like a valid public key. Make sure it's a <strong>public</strong> key.")
-
return
-
}
-
-
rkey := s.TID()
-
-
tx, err := s.db.Begin()
-
if err != nil {
-
log.Printf("failed to start tx; adding public key: %s", err)
-
s.pages.Notice(w, "settings-keys", "Unable to add public key at this moment, try again later.")
-
return
-
}
-
defer tx.Rollback()
-
-
if err := db.AddPublicKey(tx, did, name, key, rkey); err != nil {
-
log.Printf("adding public key: %s", err)
-
s.pages.Notice(w, "settings-keys", "Failed to add public key.")
-
return
-
}
-
-
// store in pds too
-
resp, err := comatproto.RepoPutRecord(r.Context(), client, &comatproto.RepoPutRecord_Input{
-
Collection: tangled.PublicKeyNSID,
-
Repo: did,
-
Rkey: rkey,
-
Record: &lexutil.LexiconTypeDecoder{
-
Val: &tangled.PublicKey{
-
Created: time.Now().Format(time.RFC3339),
-
Key: key,
-
Name: name,
-
}},
-
})
-
// invalid record
-
if err != nil {
-
log.Printf("failed to create record: %s", err)
-
s.pages.Notice(w, "settings-keys", "Failed to create record.")
-
return
-
}
-
-
log.Println("created atproto record: ", resp.Uri)
-
-
err = tx.Commit()
-
if err != nil {
-
log.Printf("failed to commit tx; adding public key: %s", err)
-
s.pages.Notice(w, "settings-keys", "Unable to add public key at this moment, try again later.")
-
return
-
}
-
-
s.pages.HxLocation(w, "/settings")
-
return
-
-
case http.MethodDelete:
-
did := s.auth.GetDid(r)
-
q := r.URL.Query()
-
-
name := q.Get("name")
-
rkey := q.Get("rkey")
-
key := q.Get("key")
-
-
log.Println(name)
-
log.Println(rkey)
-
log.Println(key)
-
-
client, _ := s.auth.AuthorizedClient(r)
-
-
if err := db.RemovePublicKey(s.db, did, name, key); err != nil {
-
log.Printf("removing public key: %s", err)
-
s.pages.Notice(w, "settings-keys", "Failed to remove public key.")
-
return
-
}
-
-
if rkey != "" {
-
// remove from pds too
-
_, err := comatproto.RepoDeleteRecord(r.Context(), client, &comatproto.RepoDeleteRecord_Input{
-
Collection: tangled.PublicKeyNSID,
-
Repo: did,
-
Rkey: rkey,
-
})
-
-
// invalid record
-
if err != nil {
-
log.Printf("failed to delete record from PDS: %s", err)
-
s.pages.Notice(w, "settings-keys", "Failed to remove key from PDS.")
-
return
-
}
-
}
-
log.Println("deleted successfully")
-
-
s.pages.HxLocation(w, "/settings")
-
return
-
}
-
}
+31 -3
appview/state/signer.go
···
"encoding/hex"
"encoding/json"
"fmt"
+
"io"
+
"log"
"net/http"
"net/url"
"time"
···
return &capabilities, nil
}
-
func (us *UnsignedClient) Compare(ownerDid, repoName, rev1, rev2 string) (*http.Response, error) {
+
func (us *UnsignedClient) Compare(ownerDid, repoName, rev1, rev2 string) (*types.RepoFormatPatchResponse, error) {
const (
Method = "GET"
)
···
req, err := us.newRequest(Method, endpoint, nil)
if err != nil {
-
return nil, err
+
return nil, fmt.Errorf("Failed to create request.")
}
-
return us.client.Do(req)
+
compareResp, err := us.client.Do(req)
+
if err != nil {
+
return nil, fmt.Errorf("Failed to create request.")
+
}
+
defer compareResp.Body.Close()
+
+
switch compareResp.StatusCode {
+
case 404:
+
case 400:
+
return nil, fmt.Errorf("Branch comparisons not supported on this knot.")
+
}
+
+
respBody, err := io.ReadAll(compareResp.Body)
+
if err != nil {
+
log.Println("failed to compare across branches")
+
return nil, fmt.Errorf("Failed to compare branches.")
+
}
+
defer compareResp.Body.Close()
+
+
var formatPatchResponse types.RepoFormatPatchResponse
+
err = json.Unmarshal(respBody, &formatPatchResponse)
+
if err != nil {
+
log.Println("failed to unmarshal format-patch response", err)
+
return nil, fmt.Errorf("failed to compare branches.")
+
}
+
+
return &formatPatchResponse, nil
}
+2 -1
appview/state/star.go
···
"github.com/bluesky-social/indigo/atproto/syntax"
lexutil "github.com/bluesky-social/indigo/lex/util"
tangled "tangled.sh/tangled.sh/core/api/tangled"
+
"tangled.sh/tangled.sh/core/appview"
"tangled.sh/tangled.sh/core/appview/db"
"tangled.sh/tangled.sh/core/appview/pages"
)
···
switch r.Method {
case http.MethodPost:
createdAt := time.Now().Format(time.RFC3339)
-
rkey := s.TID()
+
rkey := appview.TID()
resp, err := comatproto.RepoPutRecord(r.Context(), client, &comatproto.RepoPutRecord_Input{
Collection: tangled.FeedStarNSID,
Repo: currentUser.Did,
+5 -5
appview/state/state.go
···
clock := syntax.NewTIDClock(0)
-
pgs := pages.NewPages()
+
pgs := pages.NewPages(config.Dev)
resolver := appview.NewResolver()
···
return state, nil
}
-
func (s *State) TID() string {
-
return s.tidClock.Next().String()
+
func TID(c *syntax.TIDClock) string {
+
return c.Next().String()
}
func (s *State) Login(w http.ResponseWriter, r *http.Request) {
···
resp, err := comatproto.RepoPutRecord(r.Context(), client, &comatproto.RepoPutRecord_Input{
Collection: tangled.KnotMemberNSID,
Repo: currentUser.Did,
-
Rkey: s.TID(),
+
Rkey: appview.TID(),
Record: &lexutil.LexiconTypeDecoder{
Val: &tangled.KnotMember{
Member: memberIdent.DID.String(),
···
return
}
-
rkey := s.TID()
+
rkey := appview.TID()
repo := &db.Repo{
Did: user.Did,
Name: repoName,
+11
appview/tid.go
···
+
package appview
+
+
import (
+
"github.com/bluesky-social/indigo/atproto/syntax"
+
)
+
+
var c *syntax.TIDClock = syntax.NewTIDClock(0)
+
+
func TID() string {
+
return c.Next().String()
+
}
+38
cmd/combinediff/main.go
···
+
package main
+
+
import (
+
"fmt"
+
"os"
+
+
"github.com/bluekeyes/go-gitdiff/gitdiff"
+
"tangled.sh/tangled.sh/core/patchutil"
+
)
+
+
func main() {
+
if len(os.Args) != 3 {
+
fmt.Println("Usage: combinediff <patch1> <patch2>")
+
os.Exit(1)
+
}
+
+
patch1, err := os.Open(os.Args[1])
+
if err != nil {
+
fmt.Println(err)
+
}
+
patch2, err := os.Open(os.Args[2])
+
if err != nil {
+
fmt.Println(err)
+
}
+
+
files1, _, err := gitdiff.Parse(patch1)
+
if err != nil {
+
fmt.Println(err)
+
}
+
+
files2, _, err := gitdiff.Parse(patch2)
+
if err != nil {
+
fmt.Println(err)
+
}
+
+
combined := patchutil.CombineDiff(files1, files2)
+
fmt.Println(combined)
+
}
+38
cmd/interdiff/main.go
···
+
package main
+
+
import (
+
"fmt"
+
"os"
+
+
"github.com/bluekeyes/go-gitdiff/gitdiff"
+
"tangled.sh/tangled.sh/core/patchutil"
+
)
+
+
func main() {
+
if len(os.Args) != 3 {
+
fmt.Println("Usage: interdiff <patch1> <patch2>")
+
os.Exit(1)
+
}
+
+
patch1, err := os.Open(os.Args[1])
+
if err != nil {
+
fmt.Println(err)
+
}
+
patch2, err := os.Open(os.Args[2])
+
if err != nil {
+
fmt.Println(err)
+
}
+
+
files1, _, err := gitdiff.Parse(patch1)
+
if err != nil {
+
fmt.Println(err)
+
}
+
+
files2, _, err := gitdiff.Parse(patch2)
+
if err != nil {
+
fmt.Println(err)
+
}
+
+
interDiffResult := patchutil.Interdiff(files1, files2)
+
fmt.Println(interDiffResult)
+
}
+2 -2
docker/docker-compose.yml
···
context: ..
dockerfile: docker/Dockerfile
environment:
-
KNOT_SERVER_HOSTNAME: "knot.example.org"
-
KNOT_SERVER_SECRET: "secret"
+
KNOT_SERVER_HOSTNAME: ${KNOT_SERVER_HOSTNAME}
+
KNOT_SERVER_SECRET: ${KNOT_SERVER_SECRET}
KNOT_SERVER_DB_PATH: "/app/knotserver.db"
KNOT_REPO_SCAN_PATH: "/home/git/repositories"
volumes:
+9 -7
docs/contributing.md
···
### message format
```
-
<service/top-level directory>: <package/path>: <short summary of change>
+
<service/top-level directory>: <affected package/directory>: <short summary of change>
-
Optional longer description, if needed. Explain what the change does and
-
why, especially if not obvious. Reference relevant issues or PRs when
-
applicable. These can be links for now since we don't auto-link
-
issues/PRs yet.
+
Optional longer description can go here, if necessary. Explain what the
+
change does and why, especially if not obvious. Reference relevant
+
issues or PRs when applicable. These can be links for now since we don't
+
auto-link issues/PRs yet.
```
Here are some examples:
···
### general notes
-
- PRs get merged as a single commit, so keep PRs small and focused. Use
-
the above guidelines for the PR title and description.
+
- PRs get merged "as-is" (fast-forward) -- like applying a patch-series
+
using `git am`. At present, there is no squashing -- so please author
+
your commits as they would appear on `master`, following the above
+
guidelines.
- Use the imperative mood in the summary line (e.g., "fix bug" not
"fixed bug" or "fixes bug").
- Try to keep the summary line under 72 characters, but we aren't too
+83 -1
docs/knot-hosting.md
···
docker compose -f docker/docker-compose.yml up
```
-
### manual setup
+
## manual setup
First, clone this repository:
···
You should now have a running knot server! You can finalize your registration by hitting the
`initialize` button on the [/knots](/knots) page.
+
+
### custom paths
+
+
(This section applies to manual setup only. Docker users should edit the mounts
+
in `docker-compose.yml` instead.)
+
+
Right now, the database and repositories of your knot lives in `/home/git`. You
+
can move these paths if you'd like to store them in another folder. Be careful
+
when adjusting these paths:
+
+
* Stop your knot when moving data (e.g. `systemctl stop knotserver`) to prevent
+
any possible side effects. Remember to restart it once you're done.
+
* Make backups before moving in case something goes wrong.
+
* Make sure the `git` user can read and write from the new paths.
+
+
#### database
+
+
As an example, let's say the current database is at `/home/git/knotserver.db`,
+
and we want to move it to `/home/git/database/knotserver.db`.
+
+
Copy the current database to the new location. Make sure to copy the `.db-shm`
+
and `.db-wal` files if they exist.
+
+
```
+
mkdir /home/git/database
+
cp /home/git/knotserver.db* /home/git/database
+
```
+
+
In the environment (e.g. `/home/git/.knot.env`), set `KNOT_SERVER_DB_PATH` to
+
the new file path (_not_ the directory):
+
+
```
+
KNOT_SERVER_DB_PATH=/home/git/database/knotserver.db
+
```
+
+
#### repositories
+
+
As an example, let's say the repositories are currently in `/home/git`, and we
+
want to move them into `/home/git/repositories`.
+
+
Create the new folder, then move the existing repositories (if there are any):
+
+
```
+
mkdir /home/git/repositories
+
# move all DIDs into the new folder; these will vary for you!
+
mv /home/git/did:plc:wshs7t2adsemcrrd4snkeqli /home/git/repositories
+
```
+
+
In the environment (e.g. `/home/git/.knot.env`), update `KNOT_REPO_SCAN_PATH`
+
to the new directory:
+
+
```
+
KNOT_REPO_SCAN_PATH=/home/git/repositories
+
```
+
+
In your SSH config (e.g. `/etc/ssh/sshd_config.d/authorized_keys_command.conf`),
+
update the `AuthorizedKeysCommand` line to use the new folder. For example:
+
+
```
+
Match User git
+
AuthorizedKeysCommand /usr/local/libexec/tangled-keyfetch -git-dir /home/git/repositories
+
AuthorizedKeysCommandUser nobody
+
```
+
+
Make sure to restart your SSH server!
+
+
#### git
+
+
The keyfetch executable takes multiple arguments to change certain paths. You
+
can view a full list by running `/usr/local/libexec/tangled-keyfetch -h`.
+
+
As an example, if you wanted to change the path to the repoguard executable,
+
you would edit your SSH config (e.g. `/etc/ssh/sshd_config.d/authorized_keys_command.conf`)
+
and update the `AuthorizedKeysCommand` line:
+
+
```
+
Match User git
+
AuthorizedKeysCommand /usr/local/libexec/tangled-keyfetch -repoguard-path /path/to/repoguard
+
AuthorizedKeysCommandUser nobody
+
```
+
+
Make sure to restart your SSH server!
+3 -3
flake.lock
···
"indigo": {
"flake": false,
"locked": {
-
"lastModified": 1738491661,
-
"narHash": "sha256-+njDigkvjH4XmXZMog5Mp0K4x9mamHX6gSGJCZB9mE4=",
+
"lastModified": 1745333930,
+
"narHash": "sha256-83fIHqDE+dfnZ88HaNuwfKFO+R0RKAM1WxMfNh/Matk=",
"owner": "oppiliappan",
"repo": "indigo",
-
"rev": "feb802f02a462ac0a6392ffc3e40b0529f0cdf71",
+
"rev": "e4e59280737b8676611fc077a228d47b3e8e9491",
"type": "github"
},
"original": {
+12 -3
flake.nix
···
inherit (gitignore.lib) gitignoreSource;
in {
overlays.default = final: prev: let
-
goModHash = "sha256-2vljseczrvsl2T0P9k69ro72yU59l5fp9r/sszmXYY4=";
+
goModHash = "sha256-EilWxfqrcKDaSR5zA3ZuDSCq7V+/IfWpKPu8HWhpndA=";
buildCmdPackage = name:
final.buildGoModule {
pname = name;
···
${pkgs.air}/bin/air -c /dev/null \
-build.cmd "${pkgs.tailwindcss}/bin/tailwindcss -i input.css -o ./appview/pages/static/tw.css && ${pkgs.go}/bin/go build -o ./out/${name}.out ./cmd/${name}/main.go" \
-build.bin "./out/${name}.out" \
-
-build.include_ext "go,html,css"
+
-build.include_ext "go"
+
'';
+
tailwind-watcher =
+
pkgs.writeShellScriptBin "run"
+
''
+
${pkgs.tailwindcss}/bin/tailwindcss -w -i input.css -o ./appview/pages/static/tw.css
'';
in {
watch-appview = {
···
watch-knotserver = {
type = "app";
program = ''${air-watcher "knotserver"}/bin/run'';
+
};
+
watch-tailwind = {
+
type = "app";
+
program = ''${tailwind-watcher}/bin/run'';
};
});
···
g = config.services.tangled-knotserver.gitUser;
in [
"d /var/lib/knotserver 0770 ${u} ${g} - -" # Create the directory first
-
"f+ /var/lib/knotserver/secret 0660 ${u} ${g} - KNOT_SERVER_SECRET=6995e040e80e2d593b5e5e9ca611a70140b9ef8044add0a28b48b1ee34aa3e85"
+
"f+ /var/lib/knotserver/secret 0660 ${u} ${g} - KNOT_SERVER_SECRET=5b42390da4c6659f34c9a545adebd8af82c4a19960d735f651e3d582623ba9f2"
];
services.tangled-knotserver = {
enable = true;
+3 -3
go.mod
···
go.uber.org/atomic v1.11.0 // indirect
go.uber.org/multierr v1.11.0 // indirect
go.uber.org/zap v1.26.0 // indirect
-
golang.org/x/crypto v0.36.0 // indirect
-
golang.org/x/net v0.37.0 // indirect
-
golang.org/x/sys v0.31.0 // indirect
+
golang.org/x/crypto v0.37.0 // indirect
+
golang.org/x/net v0.39.0 // indirect
+
golang.org/x/sys v0.32.0 // indirect
golang.org/x/time v0.5.0 // indirect
google.golang.org/protobuf v1.34.2 // indirect
gopkg.in/warnings.v0 v0.1.2 // indirect
+10 -10
go.sum
···
golang.org/x/crypto v0.0.0-20220826181053-bd7e27e6170d/go.mod h1:IxCIyHEi3zRg3s0A5j5BB6A9Jmi73HwBIUl50j+osU4=
golang.org/x/crypto v0.1.0/go.mod h1:RecgLatLF4+eUMCP1PoPZQb+cVrJcOPbHkTkbkB9sbw=
golang.org/x/crypto v0.6.0/go.mod h1:OFC/31mSvZgRz0V1QTNCzfAI1aIRzbiufJtkMIlEp58=
-
golang.org/x/crypto v0.36.0 h1:AnAEvhDddvBdpY+uR+MyHmuZzzNqXSe/GvuDeob5L34=
-
golang.org/x/crypto v0.36.0/go.mod h1:Y4J0ReaxCR1IMaabaSMugxJES1EpwhBHhv2bDHklZvc=
+
golang.org/x/crypto v0.37.0 h1:kJNSjF/Xp7kU0iB2Z+9viTPMW4EqqsrywMXLJOOsXSE=
+
golang.org/x/crypto v0.37.0/go.mod h1:vg+k43peMZ0pUMhYmVAWysMK35e6ioLh3wB8ZCAfbVc=
golang.org/x/exp v0.0.0-20240719175910-8a7402abbf56 h1:2dVuKD2vS7b0QIHQbpyTISPd0LeHDbnYEryqj5Q1ug8=
golang.org/x/exp v0.0.0-20240719175910-8a7402abbf56/go.mod h1:M4RDyNAINzryxdtnbRXRL/OHtkFuWGRjvuhBJpk2IlY=
golang.org/x/lint v0.0.0-20190930215403-16217165b5de/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc=
···
golang.org/x/net v0.1.0/go.mod h1:Cx3nUiGt4eDBEyega/BKRp+/AlGL8hYe7U9odMt2Cco=
golang.org/x/net v0.6.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs=
golang.org/x/net v0.7.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs=
-
golang.org/x/net v0.37.0 h1:1zLorHbz+LYj7MQlSf1+2tPIIgibq2eL5xkrGk6f+2c=
-
golang.org/x/net v0.37.0/go.mod h1:ivrbrMbzFq5J41QOQh0siUuly180yBYtLp+CKbEaFx8=
+
golang.org/x/net v0.39.0 h1:ZCu7HMWDxpXpaiKdhzIfaltL9Lp31x/3fCP11bc6/fY=
+
golang.org/x/net v0.39.0/go.mod h1:X7NRbYVEA+ewNkCNyJ513WmMdQ3BineSwVtN2zD/d+E=
golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20190911185100-cd5d95a43a6e/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20201020160332-67f06af15bc9/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
···
golang.org/x/sys v0.3.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
-
golang.org/x/sys v0.31.0 h1:ioabZlmFYtWhL+TRYpcnNlLwhyxaM9kWTDEmfnprqik=
-
golang.org/x/sys v0.31.0/go.mod h1:BJP2sWEmIv4KK5OTEluFJCKSidICx8ciO85XgH3Ak8k=
+
golang.org/x/sys v0.32.0 h1:s77OFDvIQeibCmezSnk/q6iAfkdiQaJi4VzroCFrN20=
+
golang.org/x/sys v0.32.0/go.mod h1:BJP2sWEmIv4KK5OTEluFJCKSidICx8ciO85XgH3Ak8k=
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8=
golang.org/x/term v0.0.0-20220722155259-a9ba230a4035/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8=
golang.org/x/term v0.1.0/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8=
golang.org/x/term v0.5.0/go.mod h1:jMB1sMXY+tzblOD4FWmEbocvup2/aLOaQEp7JmGp78k=
-
golang.org/x/term v0.30.0 h1:PQ39fJZ+mfadBm0y5WlL4vlM7Sx1Hgf13sMIY2+QS9Y=
-
golang.org/x/term v0.30.0/go.mod h1:NYYFdzHoI5wRh/h5tDMdMqCqPJZEuNqVR5xJLd/n67g=
+
golang.org/x/term v0.31.0 h1:erwDkOK1Msy6offm1mOgvspSkslFnIGsFnxOKoufg3o=
+
golang.org/x/term v0.31.0/go.mod h1:R4BeIy7D95HzImkxGkTW1UQTtP54tio2RyHz7PwK0aw=
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ=
golang.org/x/text v0.4.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8=
golang.org/x/text v0.7.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8=
-
golang.org/x/text v0.23.0 h1:D71I7dUrlY+VX0gQShAThNGHFxZ13dGLBHQLVl1mJlY=
-
golang.org/x/text v0.23.0/go.mod h1:/BLNzu4aZCJ1+kcD0DNRotWKage4q2rGVAg4o22unh4=
+
golang.org/x/text v0.24.0 h1:dd5Bzh4yt5KYA8f9CJHCP4FB4D51c2c6JvN37xJJkJ0=
+
golang.org/x/text v0.24.0/go.mod h1:L8rBsPeo2pSS+xqN0d5u2ikmjtmoJbDBT1b7nHvFCdU=
golang.org/x/time v0.5.0 h1:o7cqy6amK/52YcAKIPlM3a+Fpj35zvRj2TP+e1xFSfk=
golang.org/x/time v0.5.0/go.mod h1:3BpzKBy/shNhVucY/MWOyx10tF3SFh9QdLuxbVysPQM=
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
+168 -5
input.css
···
font-size: 15px;
}
@supports (font-variation-settings: normal) {
-
html {
-
font-feature-settings: 'ss01' 1, 'kern' 1, 'liga' 1, 'cv05' 1, 'tnum' 1;
-
}
+
html {
+
font-feature-settings:
+
"ss01" 1,
+
"kern" 1,
+
"liga" 1,
+
"cv05" 1,
+
"tnum" 1;
+
}
}
a {
···
@apply block mb-2 text-gray-900 text-sm font-bold py-2 uppercase dark:text-gray-100;
}
input {
-
@apply bg-white border border-gray-400 rounded-sm focus:ring-black p-3 dark:bg-gray-800 dark:border-gray-600 dark:text-white dark:focus:ring-gray-400;
+
@apply border border-gray-400 block rounded bg-gray-50 focus:ring-black p-3 dark:bg-gray-800 dark:border-gray-600 dark:text-white dark:focus:ring-gray-400;
}
textarea {
-
@apply bg-white border border-gray-400 rounded-sm focus:ring-black p-3 dark:bg-gray-800 dark:border-gray-600 dark:text-white dark:focus:ring-gray-400;
+
@apply border border-gray-400 block rounded bg-gray-50 focus:ring-black p-3 dark:bg-gray-800 dark:border-gray-600 dark:text-white dark:focus:ring-gray-400;
}
details summary::-webkit-details-marker {
display: none;
···
}
}
}
+
+
/* Background */ .bg { color: #4c4f69; background-color: #eff1f5; }
+
/* PreWrapper */ .chroma { color: #4c4f69; background-color: #eff1f5; }
+
/* Error */ .chroma .err { color: #d20f39 }
+
/* LineLink */ .chroma .lnlinks { outline: none; text-decoration: none; color: inherit }
+
/* LineTableTD */ .chroma .lntd { vertical-align: top; padding: 0; margin: 0; border: 0; }
+
/* LineTable */ .chroma .lntable { border-spacing: 0; padding: 0; margin: 0; border: 0; }
+
/* LineHighlight */ .chroma .hl { background-color: #bcc0cc }
+
/* LineNumbersTable */ .chroma .lnt { white-space: pre; -webkit-user-select: none; user-select: none; margin-right: 0.4em; padding: 0 0.4em 0 0.4em;color: #8c8fa1 }
+
/* LineNumbers */ .chroma .ln { white-space: pre; -webkit-user-select: none; user-select: none; margin-right: 0.4em; padding: 0 0.4em 0 0.4em;color: #8c8fa1 }
+
/* Line */ .chroma .line { display: flex; }
+
/* Keyword */ .chroma .k { color: #8839ef }
+
/* KeywordConstant */ .chroma .kc { color: #fe640b }
+
/* KeywordDeclaration */ .chroma .kd { color: #d20f39 }
+
/* KeywordNamespace */ .chroma .kn { color: #179299 }
+
/* KeywordPseudo */ .chroma .kp { color: #8839ef }
+
/* KeywordReserved */ .chroma .kr { color: #8839ef }
+
/* KeywordType */ .chroma .kt { color: #d20f39 }
+
/* NameAttribute */ .chroma .na { color: #1e66f5 }
+
/* NameBuiltin */ .chroma .nb { color: #04a5e5 }
+
/* NameBuiltinPseudo */ .chroma .bp { color: #04a5e5 }
+
/* NameClass */ .chroma .nc { color: #df8e1d }
+
/* NameConstant */ .chroma .no { color: #df8e1d }
+
/* NameDecorator */ .chroma .nd { color: #1e66f5; font-weight: bold }
+
/* NameEntity */ .chroma .ni { color: #179299 }
+
/* NameException */ .chroma .ne { color: #fe640b }
+
/* NameFunction */ .chroma .nf { color: #1e66f5 }
+
/* NameFunctionMagic */ .chroma .fm { color: #1e66f5 }
+
/* NameLabel */ .chroma .nl { color: #04a5e5 }
+
/* NameNamespace */ .chroma .nn { color: #fe640b }
+
/* NameProperty */ .chroma .py { color: #fe640b }
+
/* NameTag */ .chroma .nt { color: #8839ef }
+
/* NameVariable */ .chroma .nv { color: #dc8a78 }
+
/* NameVariableClass */ .chroma .vc { color: #dc8a78 }
+
/* NameVariableGlobal */ .chroma .vg { color: #dc8a78 }
+
/* NameVariableInstance */ .chroma .vi { color: #dc8a78 }
+
/* NameVariableMagic */ .chroma .vm { color: #dc8a78 }
+
/* LiteralString */ .chroma .s { color: #40a02b }
+
/* LiteralStringAffix */ .chroma .sa { color: #d20f39 }
+
/* LiteralStringBacktick */ .chroma .sb { color: #40a02b }
+
/* LiteralStringChar */ .chroma .sc { color: #40a02b }
+
/* LiteralStringDelimiter */ .chroma .dl { color: #1e66f5 }
+
/* LiteralStringDoc */ .chroma .sd { color: #9ca0b0 }
+
/* LiteralStringDouble */ .chroma .s2 { color: #40a02b }
+
/* LiteralStringEscape */ .chroma .se { color: #1e66f5 }
+
/* LiteralStringHeredoc */ .chroma .sh { color: #9ca0b0 }
+
/* LiteralStringInterpol */ .chroma .si { color: #40a02b }
+
/* LiteralStringOther */ .chroma .sx { color: #40a02b }
+
/* LiteralStringRegex */ .chroma .sr { color: #179299 }
+
/* LiteralStringSingle */ .chroma .s1 { color: #40a02b }
+
/* LiteralStringSymbol */ .chroma .ss { color: #40a02b }
+
/* LiteralNumber */ .chroma .m { color: #fe640b }
+
/* LiteralNumberBin */ .chroma .mb { color: #fe640b }
+
/* LiteralNumberFloat */ .chroma .mf { color: #fe640b }
+
/* LiteralNumberHex */ .chroma .mh { color: #fe640b }
+
/* LiteralNumberInteger */ .chroma .mi { color: #fe640b }
+
/* LiteralNumberIntegerLong */ .chroma .il { color: #fe640b }
+
/* LiteralNumberOct */ .chroma .mo { color: #fe640b }
+
/* Operator */ .chroma .o { color: #04a5e5; font-weight: bold }
+
/* OperatorWord */ .chroma .ow { color: #04a5e5; font-weight: bold }
+
/* Comment */ .chroma .c { color: #9ca0b0; font-style: italic }
+
/* CommentHashbang */ .chroma .ch { color: #9ca0b0; font-style: italic }
+
/* CommentMultiline */ .chroma .cm { color: #9ca0b0; font-style: italic }
+
/* CommentSingle */ .chroma .c1 { color: #9ca0b0; font-style: italic }
+
/* CommentSpecial */ .chroma .cs { color: #9ca0b0; font-style: italic }
+
/* CommentPreproc */ .chroma .cp { color: #9ca0b0; font-style: italic }
+
/* CommentPreprocFile */ .chroma .cpf { color: #9ca0b0; font-weight: bold; font-style: italic }
+
/* GenericDeleted */ .chroma .gd { color: #d20f39; background-color: oklch(93.6% 0.032 17.717) }
+
/* GenericEmph */ .chroma .ge { font-style: italic }
+
/* GenericError */ .chroma .gr { color: #d20f39 }
+
/* GenericHeading */ .chroma .gh { color: #fe640b; font-weight: bold }
+
/* GenericInserted */ .chroma .gi { color: #40a02b; background-color: oklch(96.2% 0.044 156.743) }
+
/* GenericStrong */ .chroma .gs { font-weight: bold }
+
/* GenericSubheading */ .chroma .gu { color: #fe640b; font-weight: bold }
+
/* GenericTraceback */ .chroma .gt { color: #d20f39 }
+
/* GenericUnderline */ .chroma .gl { text-decoration: underline }
+
+
@media (prefers-color-scheme: dark) {
+
/* Background */ .bg { color: #cad3f5; background-color: #24273a; }
+
/* PreWrapper */ .chroma { color: #cad3f5; background-color: #24273a; }
+
/* Error */ .chroma .err { color: #ed8796 }
+
/* LineLink */ .chroma .lnlinks { outline: none; text-decoration: none; color: inherit }
+
/* LineTableTD */ .chroma .lntd { vertical-align: top; padding: 0; margin: 0; border: 0; }
+
/* LineTable */ .chroma .lntable { border-spacing: 0; padding: 0; margin: 0; border: 0; }
+
/* LineHighlight */ .chroma .hl { background-color: #494d64 }
+
/* LineNumbersTable */ .chroma .lnt { white-space: pre; -webkit-user-select: none; user-select: none; margin-right: 0.4em; padding: 0 0.4em 0 0.4em;color: #8087a2 }
+
/* LineNumbers */ .chroma .ln { white-space: pre; -webkit-user-select: none; user-select: none; margin-right: 0.4em; padding: 0 0.4em 0 0.4em;color: #8087a2 }
+
/* Line */ .chroma .line { display: flex; }
+
/* Keyword */ .chroma .k { color: #c6a0f6 }
+
/* KeywordConstant */ .chroma .kc { color: #f5a97f }
+
/* KeywordDeclaration */ .chroma .kd { color: #ed8796 }
+
/* KeywordNamespace */ .chroma .kn { color: #8bd5ca }
+
/* KeywordPseudo */ .chroma .kp { color: #c6a0f6 }
+
/* KeywordReserved */ .chroma .kr { color: #c6a0f6 }
+
/* KeywordType */ .chroma .kt { color: #ed8796 }
+
/* NameAttribute */ .chroma .na { color: #8aadf4 }
+
/* NameBuiltin */ .chroma .nb { color: #91d7e3 }
+
/* NameBuiltinPseudo */ .chroma .bp { color: #91d7e3 }
+
/* NameClass */ .chroma .nc { color: #eed49f }
+
/* NameConstant */ .chroma .no { color: #eed49f }
+
/* NameDecorator */ .chroma .nd { color: #8aadf4; font-weight: bold }
+
/* NameEntity */ .chroma .ni { color: #8bd5ca }
+
/* NameException */ .chroma .ne { color: #f5a97f }
+
/* NameFunction */ .chroma .nf { color: #8aadf4 }
+
/* NameFunctionMagic */ .chroma .fm { color: #8aadf4 }
+
/* NameLabel */ .chroma .nl { color: #91d7e3 }
+
/* NameNamespace */ .chroma .nn { color: #f5a97f }
+
/* NameProperty */ .chroma .py { color: #f5a97f }
+
/* NameTag */ .chroma .nt { color: #c6a0f6 }
+
/* NameVariable */ .chroma .nv { color: #f4dbd6 }
+
/* NameVariableClass */ .chroma .vc { color: #f4dbd6 }
+
/* NameVariableGlobal */ .chroma .vg { color: #f4dbd6 }
+
/* NameVariableInstance */ .chroma .vi { color: #f4dbd6 }
+
/* NameVariableMagic */ .chroma .vm { color: #f4dbd6 }
+
/* LiteralString */ .chroma .s { color: #a6da95 }
+
/* LiteralStringAffix */ .chroma .sa { color: #ed8796 }
+
/* LiteralStringBacktick */ .chroma .sb { color: #a6da95 }
+
/* LiteralStringChar */ .chroma .sc { color: #a6da95 }
+
/* LiteralStringDelimiter */ .chroma .dl { color: #8aadf4 }
+
/* LiteralStringDoc */ .chroma .sd { color: #6e738d }
+
/* LiteralStringDouble */ .chroma .s2 { color: #a6da95 }
+
/* LiteralStringEscape */ .chroma .se { color: #8aadf4 }
+
/* LiteralStringHeredoc */ .chroma .sh { color: #6e738d }
+
/* LiteralStringInterpol */ .chroma .si { color: #a6da95 }
+
/* LiteralStringOther */ .chroma .sx { color: #a6da95 }
+
/* LiteralStringRegex */ .chroma .sr { color: #8bd5ca }
+
/* LiteralStringSingle */ .chroma .s1 { color: #a6da95 }
+
/* LiteralStringSymbol */ .chroma .ss { color: #a6da95 }
+
/* LiteralNumber */ .chroma .m { color: #f5a97f }
+
/* LiteralNumberBin */ .chroma .mb { color: #f5a97f }
+
/* LiteralNumberFloat */ .chroma .mf { color: #f5a97f }
+
/* LiteralNumberHex */ .chroma .mh { color: #f5a97f }
+
/* LiteralNumberInteger */ .chroma .mi { color: #f5a97f }
+
/* LiteralNumberIntegerLong */ .chroma .il { color: #f5a97f }
+
/* LiteralNumberOct */ .chroma .mo { color: #f5a97f }
+
/* Operator */ .chroma .o { color: #91d7e3; font-weight: bold }
+
/* OperatorWord */ .chroma .ow { color: #91d7e3; font-weight: bold }
+
/* Comment */ .chroma .c { color: #6e738d; font-style: italic }
+
/* CommentHashbang */ .chroma .ch { color: #6e738d; font-style: italic }
+
/* CommentMultiline */ .chroma .cm { color: #6e738d; font-style: italic }
+
/* CommentSingle */ .chroma .c1 { color: #6e738d; font-style: italic }
+
/* CommentSpecial */ .chroma .cs { color: #6e738d; font-style: italic }
+
/* CommentPreproc */ .chroma .cp { color: #6e738d; font-style: italic }
+
/* CommentPreprocFile */ .chroma .cpf { color: #6e738d; font-weight: bold; font-style: italic }
+
/* GenericDeleted */ .chroma .gd { color: #ed8796; background-color: oklch(44.4% 0.177 26.899 / 0.5) }
+
/* GenericEmph */ .chroma .ge { font-style: italic }
+
/* GenericError */ .chroma .gr { color: #ed8796 }
+
/* GenericHeading */ .chroma .gh { color: #f5a97f; font-weight: bold }
+
/* GenericInserted */ .chroma .gi { color: #a6da95; background-color: oklch(44.8% 0.119 151.328 / 0.5) }
+
/* GenericStrong */ .chroma .gs { font-weight: bold }
+
/* GenericSubheading */ .chroma .gu { color: #f5a97f; font-weight: bold }
+
/* GenericTraceback */ .chroma .gt { color: #ed8796 }
+
/* GenericUnderline */ .chroma .gl { text-decoration: underline }
+
}
+
+
.chroma .line:has(.ln:target) {
+
@apply bg-amber-400/30 dark:bg-amber-500/20
+
}
+31
knotserver/git/diff.go
···
package git
import (
+
"bytes"
"fmt"
"log"
+
"os"
+
"os/exec"
"strings"
"github.com/bluekeyes/go-gitdiff/gitdiff"
"github.com/go-git/go-git/v5/plumbing"
"github.com/go-git/go-git/v5/plumbing/object"
+
"tangled.sh/tangled.sh/core/patchutil"
"tangled.sh/tangled.sh/core/types"
)
···
Patch: patch.String(),
Diff: diffs,
}, nil
+
}
+
+
// FormatPatch generates a git-format-patch output between two commits,
+
// and returns the raw format-patch series, a parsed FormatPatch and an error.
+
func (g *GitRepo) FormatPatch(base, commit2 *object.Commit) (string, []patchutil.FormatPatch, error) {
+
var stdout bytes.Buffer
+
cmd := exec.Command(
+
"git",
+
"-C",
+
g.path,
+
"format-patch",
+
fmt.Sprintf("%s..%s", base.Hash.String(), commit2.Hash.String()),
+
"--stdout",
+
)
+
cmd.Stdout = &stdout
+
cmd.Stderr = os.Stderr
+
err := cmd.Run()
+
if err != nil {
+
return "", nil, err
+
}
+
+
formatPatch, err := patchutil.ExtractPatches(stdout.String())
+
if err != nil {
+
return "", nil, err
+
}
+
+
return stdout.String(), formatPatch, nil
}
func (g *GitRepo) MergeBase(commit1, commit2 *object.Commit) (*object.Commit, error) {
+17 -2
knotserver/git/merge.go
···
"github.com/go-git/go-git/v5"
"github.com/go-git/go-git/v5/plumbing"
+
"tangled.sh/tangled.sh/core/patchutil"
)
type ErrMerge struct {
···
CommitBody string
AuthorName string
AuthorEmail string
+
FormatPatch bool
}
func (e ErrMerge) Error() string {
···
if checkOnly {
cmd = exec.Command("git", "-C", tmpDir, "apply", "--check", "-v", patchFile)
} else {
-
exec.Command("git", "-C", tmpDir, "config", "advice.mergeConflict", "false").Run()
+
// if patch is a format-patch, apply using 'git am'
+
if opts.FormatPatch {
+
amCmd := exec.Command("git", "-C", tmpDir, "am", patchFile)
+
amCmd.Stderr = &stderr
+
if err := amCmd.Run(); err != nil {
+
return fmt.Errorf("patch application failed: %s", stderr.String())
+
}
+
return nil
+
}
+
// else, apply using 'git apply' and commit it manually
+
exec.Command("git", "-C", tmpDir, "config", "advice.mergeConflict", "false").Run()
if opts != nil {
applyCmd := exec.Command("git", "-C", tmpDir, "apply", patchFile)
applyCmd.Stderr = &stderr
···
}
func (g *GitRepo) MergeCheck(patchData []byte, targetBranch string) error {
+
var opts MergeOptions
+
opts.FormatPatch = patchutil.IsFormatPatch(string(patchData))
+
patchFile, err := g.createTempFileWithPatch(patchData)
if err != nil {
return &ErrMerge{
···
}
defer os.RemoveAll(tmpDir)
-
return g.applyPatch(tmpDir, patchFile, true, nil)
+
return g.applyPatch(tmpDir, patchFile, true, &opts)
}
func (g *GitRepo) Merge(patchData []byte, targetBranch string) error {
+12 -2
knotserver/routes.go
···
"github.com/go-git/go-git/v5/plumbing/object"
"tangled.sh/tangled.sh/core/knotserver/db"
"tangled.sh/tangled.sh/core/knotserver/git"
+
"tangled.sh/tangled.sh/core/patchutil"
"tangled.sh/tangled.sh/core/types"
)
···
capabilities := map[string]any{
"pull_requests": map[string]any{
+
"format_patch": true,
"patch_submissions": true,
"branch_submissions": true,
"fork_submissions": true,
···
notFound(w)
return
}
+
+
mo.FormatPatch = patchutil.IsFormatPatch(patch)
+
if err := gr.MergeWithOptions([]byte(patch), branch, mo); err != nil {
var mergeErr *git.ErrMerge
if errors.As(err, &mergeErr) {
···
return
}
-
difftree, err := gr.DiffTree(mergeBase, commit2)
+
rawPatch, formatPatch, err := gr.FormatPatch(mergeBase, commit2)
if err != nil {
l.Error("error comparing revisions", "msg", err.Error())
writeError(w, "error comparing revisions", http.StatusBadRequest)
return
}
-
writeJSON(w, types.RepoDiffTreeResponse{difftree})
+
writeJSON(w, types.RepoFormatPatchResponse{
+
Rev1: commit1.Hash.String(),
+
Rev2: commit2.Hash.String(),
+
FormatPatch: formatPatch,
+
Patch: rawPatch,
+
})
return
}
+168
patchutil/combinediff.go
···
+
package patchutil
+
+
import (
+
"fmt"
+
"strings"
+
+
"github.com/bluekeyes/go-gitdiff/gitdiff"
+
)
+
+
// original1 -> patch1 -> rev1
+
// original2 -> patch2 -> rev2
+
//
+
// original2 must be equal to rev1, so we can merge them to get maximal context
+
//
+
// finally,
+
// rev2' <- apply(patch2, merged)
+
// combineddiff <- diff(rev2', original1)
+
func combineFiles(file1, file2 *gitdiff.File) (*gitdiff.File, error) {
+
fileName := bestName(file1)
+
+
o1 := CreatePreImage(file1)
+
r1 := CreatePostImage(file1)
+
o2 := CreatePreImage(file2)
+
+
merged, err := r1.Merge(&o2)
+
if err != nil {
+
return nil, err
+
}
+
+
r2Prime, err := merged.Apply(file2)
+
if err != nil {
+
return nil, err
+
}
+
+
// produce combined diff
+
diff, err := Unified(o1.String(), fileName, r2Prime, fileName)
+
if err != nil {
+
return nil, err
+
}
+
+
parsed, _, err := gitdiff.Parse(strings.NewReader(diff))
+
+
if len(parsed) != 1 {
+
// no diff? the second commit reverted the changes from the first
+
return nil, nil
+
}
+
+
return parsed[0], nil
+
}
+
+
// use empty lines for lines we are unaware of
+
//
+
// this raises an error only if the two patches were invalid or non-contiguous
+
func mergeLines(old, new string) (string, error) {
+
var i, j int
+
+
// TODO: use strings.Lines
+
linesOld := strings.Split(old, "\n")
+
linesNew := strings.Split(new, "\n")
+
+
result := []string{}
+
+
for i < len(linesOld) || j < len(linesNew) {
+
if i >= len(linesOld) {
+
// rest of the file is populated from `new`
+
result = append(result, linesNew[j])
+
j++
+
continue
+
}
+
+
if j >= len(linesNew) {
+
// rest of the file is populated from `old`
+
result = append(result, linesOld[i])
+
i++
+
continue
+
}
+
+
oldLine := linesOld[i]
+
newLine := linesNew[j]
+
+
if oldLine != newLine && (oldLine != "" && newLine != "") {
+
// context mismatch
+
return "", fmt.Errorf("failed to merge files, found context mismatch at %d; oldLine: `%s`, newline: `%s`", i+1, oldLine, newLine)
+
}
+
+
if oldLine == newLine {
+
result = append(result, oldLine)
+
} else if oldLine == "" {
+
result = append(result, newLine)
+
} else if newLine == "" {
+
result = append(result, oldLine)
+
}
+
i++
+
j++
+
}
+
+
return strings.Join(result, "\n"), nil
+
}
+
+
func combineTwo(patch1, patch2 []*gitdiff.File) []*gitdiff.File {
+
fileToIdx1 := make(map[string]int)
+
fileToIdx2 := make(map[string]int)
+
visited := make(map[string]struct{})
+
var result []*gitdiff.File
+
+
for idx, f := range patch1 {
+
fileToIdx1[bestName(f)] = idx
+
}
+
+
for idx, f := range patch2 {
+
fileToIdx2[bestName(f)] = idx
+
}
+
+
for _, f1 := range patch1 {
+
fileName := bestName(f1)
+
if idx, ok := fileToIdx2[fileName]; ok {
+
f2 := patch2[idx]
+
+
// we have f1 and f2, combine them
+
combined, err := combineFiles(f1, f2)
+
if err != nil {
+
fmt.Println(err)
+
}
+
+
result = append(result, combined)
+
} else {
+
// only in patch1; add as-is
+
result = append(result, f1)
+
}
+
+
visited[fileName] = struct{}{}
+
}
+
+
// for all files in patch2 that remain unvisited; we can just add them into the output
+
for _, f2 := range patch2 {
+
fileName := bestName(f2)
+
if _, ok := visited[fileName]; ok {
+
continue
+
}
+
+
result = append(result, f2)
+
}
+
+
return result
+
}
+
+
// pairwise combination from first to last patch
+
func CombineDiff(patches ...[]*gitdiff.File) []*gitdiff.File {
+
if len(patches) == 0 {
+
return nil
+
}
+
+
if len(patches) == 1 {
+
return patches[0]
+
}
+
+
combined := combineTwo(patches[0], patches[1])
+
+
newPatches := [][]*gitdiff.File{}
+
newPatches = append(newPatches, combined)
+
for i, p := range patches {
+
if i >= 2 {
+
newPatches = append(newPatches, p)
+
}
+
}
+
+
return CombineDiff(newPatches...)
+
}
+178
patchutil/image.go
···
+
package patchutil
+
+
import (
+
"bytes"
+
"fmt"
+
"strings"
+
+
"github.com/bluekeyes/go-gitdiff/gitdiff"
+
)
+
+
type Line struct {
+
LineNumber int64
+
Content string
+
IsUnknown bool
+
}
+
+
func NewLineAt(lineNumber int64, content string) Line {
+
return Line{
+
LineNumber: lineNumber,
+
Content: content,
+
IsUnknown: false,
+
}
+
}
+
+
type Image struct {
+
File string
+
Data []*Line
+
}
+
+
func (r *Image) String() string {
+
var i, j int64
+
var b strings.Builder
+
for {
+
i += 1
+
+
if int(j) >= (len(r.Data)) {
+
break
+
}
+
+
if r.Data[j].LineNumber == i {
+
// b.WriteString(fmt.Sprintf("%d:", r.Data[j].LineNumber))
+
b.WriteString(r.Data[j].Content)
+
j += 1
+
} else {
+
//b.WriteString(fmt.Sprintf("%d:\n", i))
+
b.WriteString("\n")
+
}
+
}
+
+
return b.String()
+
}
+
+
func (r *Image) AddLine(line *Line) {
+
r.Data = append(r.Data, line)
+
}
+
+
// rebuild the original file from a patch
+
func CreatePreImage(file *gitdiff.File) Image {
+
rf := Image{
+
File: bestName(file),
+
}
+
+
for _, fragment := range file.TextFragments {
+
position := fragment.OldPosition
+
for _, line := range fragment.Lines {
+
switch line.Op {
+
case gitdiff.OpContext:
+
rl := NewLineAt(position, line.Line)
+
rf.Data = append(rf.Data, &rl)
+
position += 1
+
case gitdiff.OpDelete:
+
rl := NewLineAt(position, line.Line)
+
rf.Data = append(rf.Data, &rl)
+
position += 1
+
case gitdiff.OpAdd:
+
// do nothing here
+
}
+
}
+
}
+
+
return rf
+
}
+
+
// rebuild the revised file from a patch
+
func CreatePostImage(file *gitdiff.File) Image {
+
rf := Image{
+
File: bestName(file),
+
}
+
+
for _, fragment := range file.TextFragments {
+
position := fragment.NewPosition
+
for _, line := range fragment.Lines {
+
switch line.Op {
+
case gitdiff.OpContext:
+
rl := NewLineAt(position, line.Line)
+
rf.Data = append(rf.Data, &rl)
+
position += 1
+
case gitdiff.OpAdd:
+
rl := NewLineAt(position, line.Line)
+
rf.Data = append(rf.Data, &rl)
+
position += 1
+
case gitdiff.OpDelete:
+
// do nothing here
+
}
+
}
+
}
+
+
return rf
+
}
+
+
type MergeError struct {
+
msg string
+
mismatchingLine int64
+
}
+
+
func (m MergeError) Error() string {
+
return fmt.Sprintf("%s: %v", m.msg, m.mismatchingLine)
+
}
+
+
// best effort merging of two reconstructed files
+
func (this *Image) Merge(other *Image) (*Image, error) {
+
mergedFile := Image{}
+
+
var i, j int64
+
+
for int(i) < len(this.Data) || int(j) < len(other.Data) {
+
if int(i) >= len(this.Data) {
+
// first file is done; the rest of the lines from file 2 can go in
+
mergedFile.AddLine(other.Data[j])
+
j++
+
continue
+
}
+
+
if int(j) >= len(other.Data) {
+
// first file is done; the rest of the lines from file 2 can go in
+
mergedFile.AddLine(this.Data[i])
+
i++
+
continue
+
}
+
+
line1 := this.Data[i]
+
line2 := other.Data[j]
+
+
if line1.LineNumber == line2.LineNumber {
+
if line1.Content != line2.Content {
+
return nil, MergeError{
+
msg: "mismatching lines, this patch might have undergone rebase",
+
mismatchingLine: line1.LineNumber,
+
}
+
} else {
+
mergedFile.AddLine(line1)
+
}
+
i++
+
j++
+
} else if line1.LineNumber < line2.LineNumber {
+
mergedFile.AddLine(line1)
+
i++
+
} else {
+
mergedFile.AddLine(line2)
+
j++
+
}
+
}
+
+
return &mergedFile, nil
+
}
+
+
func (r *Image) Apply(patch *gitdiff.File) (string, error) {
+
original := r.String()
+
var buffer bytes.Buffer
+
reader := strings.NewReader(original)
+
+
err := gitdiff.Apply(&buffer, reader, patch)
+
if err != nil {
+
return "", err
+
}
+
+
return buffer.String(), nil
+
}
+244
patchutil/interdiff.go
···
+
package patchutil
+
+
import (
+
"fmt"
+
"strings"
+
+
"github.com/bluekeyes/go-gitdiff/gitdiff"
+
)
+
+
type InterdiffResult struct {
+
Files []*InterdiffFile
+
}
+
+
func (i *InterdiffResult) AffectedFiles() []string {
+
files := make([]string, len(i.Files))
+
for _, f := range i.Files {
+
files = append(files, f.Name)
+
}
+
return files
+
}
+
+
func (i *InterdiffResult) String() string {
+
var b strings.Builder
+
for _, f := range i.Files {
+
b.WriteString(f.String())
+
b.WriteString("\n")
+
}
+
+
return b.String()
+
}
+
+
type InterdiffFile struct {
+
*gitdiff.File
+
Name string
+
Status InterdiffFileStatus
+
}
+
+
func (s *InterdiffFile) String() string {
+
var b strings.Builder
+
b.WriteString(s.Status.String())
+
b.WriteString(" ")
+
+
if s.File != nil {
+
b.WriteString(bestName(s.File))
+
b.WriteString("\n")
+
b.WriteString(s.File.String())
+
}
+
+
return b.String()
+
}
+
+
type InterdiffFileStatus struct {
+
StatusKind StatusKind
+
Error error
+
}
+
+
func (s *InterdiffFileStatus) String() string {
+
kind := s.StatusKind.String()
+
if s.Error != nil {
+
return fmt.Sprintf("%s [%s]", kind, s.Error.Error())
+
} else {
+
return kind
+
}
+
}
+
+
func (s *InterdiffFileStatus) IsOk() bool {
+
return s.StatusKind == StatusOk
+
}
+
+
func (s *InterdiffFileStatus) IsUnchanged() bool {
+
return s.StatusKind == StatusUnchanged
+
}
+
+
func (s *InterdiffFileStatus) IsOnlyInOne() bool {
+
return s.StatusKind == StatusOnlyInOne
+
}
+
+
func (s *InterdiffFileStatus) IsOnlyInTwo() bool {
+
return s.StatusKind == StatusOnlyInTwo
+
}
+
+
func (s *InterdiffFileStatus) IsRebased() bool {
+
return s.StatusKind == StatusRebased
+
}
+
+
func (s *InterdiffFileStatus) IsError() bool {
+
return s.StatusKind == StatusError
+
}
+
+
type StatusKind int
+
+
func (k StatusKind) String() string {
+
switch k {
+
case StatusOnlyInOne:
+
return "only in one"
+
case StatusOnlyInTwo:
+
return "only in two"
+
case StatusUnchanged:
+
return "unchanged"
+
case StatusRebased:
+
return "rebased"
+
case StatusError:
+
return "error"
+
default:
+
return "changed"
+
}
+
}
+
+
const (
+
StatusOk StatusKind = iota
+
StatusOnlyInOne
+
StatusOnlyInTwo
+
StatusUnchanged
+
StatusRebased
+
StatusError
+
)
+
+
func interdiffFiles(f1, f2 *gitdiff.File) *InterdiffFile {
+
re1 := CreatePreImage(f1)
+
re2 := CreatePreImage(f2)
+
+
interdiffFile := InterdiffFile{
+
Name: bestName(f1),
+
}
+
+
merged, err := re1.Merge(&re2)
+
if err != nil {
+
interdiffFile.Status = InterdiffFileStatus{
+
StatusKind: StatusRebased,
+
Error: err,
+
}
+
return &interdiffFile
+
}
+
+
rev1, err := merged.Apply(f1)
+
if err != nil {
+
interdiffFile.Status = InterdiffFileStatus{
+
StatusKind: StatusError,
+
Error: err,
+
}
+
return &interdiffFile
+
}
+
+
rev2, err := merged.Apply(f2)
+
if err != nil {
+
interdiffFile.Status = InterdiffFileStatus{
+
StatusKind: StatusError,
+
Error: err,
+
}
+
return &interdiffFile
+
}
+
+
diff, err := Unified(rev1, bestName(f1), rev2, bestName(f2))
+
if err != nil {
+
interdiffFile.Status = InterdiffFileStatus{
+
StatusKind: StatusError,
+
Error: err,
+
}
+
return &interdiffFile
+
}
+
+
parsed, _, err := gitdiff.Parse(strings.NewReader(diff))
+
if err != nil {
+
interdiffFile.Status = InterdiffFileStatus{
+
StatusKind: StatusError,
+
Error: err,
+
}
+
return &interdiffFile
+
}
+
+
if len(parsed) != 1 {
+
// files are identical?
+
interdiffFile.Status = InterdiffFileStatus{
+
StatusKind: StatusUnchanged,
+
}
+
return &interdiffFile
+
}
+
+
if interdiffFile.Status.StatusKind == StatusOk {
+
interdiffFile.File = parsed[0]
+
}
+
+
return &interdiffFile
+
}
+
+
func Interdiff(patch1, patch2 []*gitdiff.File) *InterdiffResult {
+
fileToIdx1 := make(map[string]int)
+
fileToIdx2 := make(map[string]int)
+
visited := make(map[string]struct{})
+
var result InterdiffResult
+
+
for idx, f := range patch1 {
+
fileToIdx1[bestName(f)] = idx
+
}
+
+
for idx, f := range patch2 {
+
fileToIdx2[bestName(f)] = idx
+
}
+
+
for _, f1 := range patch1 {
+
var interdiffFile *InterdiffFile
+
+
fileName := bestName(f1)
+
if idx, ok := fileToIdx2[fileName]; ok {
+
f2 := patch2[idx]
+
+
// we have f1 and f2, calculate interdiff
+
interdiffFile = interdiffFiles(f1, f2)
+
} else {
+
// only in patch 1, this change would have to be "inverted" to dissapear
+
// from patch 2, so we reverseDiff(f1)
+
reverseDiff(f1)
+
+
interdiffFile = &InterdiffFile{
+
File: f1,
+
Name: fileName,
+
Status: InterdiffFileStatus{
+
StatusKind: StatusOnlyInOne,
+
},
+
}
+
}
+
+
result.Files = append(result.Files, interdiffFile)
+
visited[fileName] = struct{}{}
+
}
+
+
// for all files in patch2 that remain unvisited; we can just add them into the output
+
for _, f2 := range patch2 {
+
fileName := bestName(f2)
+
if _, ok := visited[fileName]; ok {
+
continue
+
}
+
+
result.Files = append(result.Files, &InterdiffFile{
+
File: f2,
+
Name: fileName,
+
Status: InterdiffFileStatus{
+
StatusKind: StatusOnlyInTwo,
+
},
+
})
+
}
+
+
return &result
+
}
+196
patchutil/patchutil.go
···
+
package patchutil
+
+
import (
+
"fmt"
+
"os"
+
"os/exec"
+
"regexp"
+
"strings"
+
+
"github.com/bluekeyes/go-gitdiff/gitdiff"
+
)
+
+
type FormatPatch struct {
+
Files []*gitdiff.File
+
*gitdiff.PatchHeader
+
}
+
+
func ExtractPatches(formatPatch string) ([]FormatPatch, error) {
+
patches := splitFormatPatch(formatPatch)
+
+
result := []FormatPatch{}
+
+
for _, patch := range patches {
+
files, headerStr, err := gitdiff.Parse(strings.NewReader(patch))
+
if err != nil {
+
return nil, fmt.Errorf("failed to parse patch: %w", err)
+
}
+
+
header, err := gitdiff.ParsePatchHeader(headerStr)
+
if err != nil {
+
return nil, fmt.Errorf("failed to parse patch header: %w", err)
+
}
+
+
result = append(result, FormatPatch{
+
Files: files,
+
PatchHeader: header,
+
})
+
}
+
+
return result, nil
+
}
+
+
// IsPatchValid checks if the given patch string is valid.
+
// It performs very basic sniffing for either git-diff or git-format-patch
+
// header lines. For format patches, it attempts to extract and validate each one.
+
func IsPatchValid(patch string) bool {
+
if len(patch) == 0 {
+
return false
+
}
+
+
lines := strings.Split(patch, "\n")
+
if len(lines) < 2 {
+
return false
+
}
+
+
firstLine := strings.TrimSpace(lines[0])
+
+
// check if it's a git diff
+
if strings.HasPrefix(firstLine, "diff ") ||
+
strings.HasPrefix(firstLine, "--- ") ||
+
strings.HasPrefix(firstLine, "Index: ") ||
+
strings.HasPrefix(firstLine, "+++ ") ||
+
strings.HasPrefix(firstLine, "@@ ") {
+
return true
+
}
+
+
// check if it's format-patch
+
if strings.HasPrefix(firstLine, "From ") && strings.Contains(firstLine, " Mon Sep 17 00:00:00 2001") ||
+
strings.HasPrefix(firstLine, "From: ") {
+
// ExtractPatches already runs it through gitdiff.Parse so if that errors,
+
// it's safe to say it's broken.
+
patches, err := ExtractPatches(patch)
+
if err != nil {
+
return false
+
}
+
return len(patches) > 0
+
}
+
+
return false
+
}
+
+
func IsFormatPatch(patch string) bool {
+
lines := strings.Split(patch, "\n")
+
if len(lines) < 2 {
+
return false
+
}
+
+
firstLine := strings.TrimSpace(lines[0])
+
if strings.HasPrefix(firstLine, "From ") && strings.Contains(firstLine, " Mon Sep 17 00:00:00 2001") {
+
return true
+
}
+
+
headerCount := 0
+
for i := range min(10, len(lines)) {
+
line := strings.TrimSpace(lines[i])
+
if strings.HasPrefix(line, "From: ") ||
+
strings.HasPrefix(line, "Date: ") ||
+
strings.HasPrefix(line, "Subject: ") ||
+
strings.HasPrefix(line, "commit ") {
+
headerCount++
+
}
+
}
+
+
return headerCount >= 2
+
}
+
+
func splitFormatPatch(patchText string) []string {
+
re := regexp.MustCompile(`(?m)^From [0-9a-f]{40} .*$`)
+
+
indexes := re.FindAllStringIndex(patchText, -1)
+
+
if len(indexes) == 0 {
+
return []string{}
+
}
+
+
patches := make([]string, len(indexes))
+
+
for i := range indexes {
+
startPos := indexes[i][0]
+
endPos := len(patchText)
+
+
if i < len(indexes)-1 {
+
endPos = indexes[i+1][0]
+
}
+
+
patches[i] = strings.TrimSpace(patchText[startPos:endPos])
+
}
+
return patches
+
}
+
+
func bestName(file *gitdiff.File) string {
+
if file.IsDelete {
+
return file.OldName
+
} else {
+
return file.NewName
+
}
+
}
+
+
// in-place reverse of a diff
+
func reverseDiff(file *gitdiff.File) {
+
file.OldName, file.NewName = file.NewName, file.OldName
+
file.OldMode, file.NewMode = file.NewMode, file.OldMode
+
file.BinaryFragment, file.ReverseBinaryFragment = file.ReverseBinaryFragment, file.BinaryFragment
+
+
for _, fragment := range file.TextFragments {
+
// swap postions
+
fragment.OldPosition, fragment.NewPosition = fragment.NewPosition, fragment.OldPosition
+
fragment.OldLines, fragment.NewLines = fragment.NewLines, fragment.OldLines
+
fragment.LinesAdded, fragment.LinesDeleted = fragment.LinesDeleted, fragment.LinesAdded
+
+
for i := range fragment.Lines {
+
switch fragment.Lines[i].Op {
+
case gitdiff.OpAdd:
+
fragment.Lines[i].Op = gitdiff.OpDelete
+
case gitdiff.OpDelete:
+
fragment.Lines[i].Op = gitdiff.OpAdd
+
default:
+
// do nothing
+
}
+
}
+
}
+
}
+
+
func Unified(oldText, oldFile, newText, newFile string) (string, error) {
+
oldTemp, err := os.CreateTemp("", "old_*")
+
if err != nil {
+
return "", fmt.Errorf("failed to create temp file for oldText: %w", err)
+
}
+
defer os.Remove(oldTemp.Name())
+
if _, err := oldTemp.WriteString(oldText); err != nil {
+
return "", fmt.Errorf("failed to write to old temp file: %w", err)
+
}
+
oldTemp.Close()
+
+
newTemp, err := os.CreateTemp("", "new_*")
+
if err != nil {
+
return "", fmt.Errorf("failed to create temp file for newText: %w", err)
+
}
+
defer os.Remove(newTemp.Name())
+
if _, err := newTemp.WriteString(newText); err != nil {
+
return "", fmt.Errorf("failed to write to new temp file: %w", err)
+
}
+
newTemp.Close()
+
+
cmd := exec.Command("diff", "-u", "--label", oldFile, "--label", newFile, oldTemp.Name(), newTemp.Name())
+
output, err := cmd.CombinedOutput()
+
+
if exitErr, ok := err.(*exec.ExitError); ok && exitErr.ExitCode() == 1 {
+
return string(output), nil
+
}
+
if err != nil {
+
return "", fmt.Errorf("diff command failed: %w", err)
+
}
+
+
return string(output), nil
+
}
+324
patchutil/patchutil_test.go
···
+
package patchutil
+
+
import (
+
"reflect"
+
"testing"
+
)
+
+
func TestIsPatchValid(t *testing.T) {
+
tests := []struct {
+
name string
+
patch string
+
expected bool
+
}{
+
{
+
name: `empty patch`,
+
patch: ``,
+
expected: false,
+
},
+
{
+
name: `single line patch`,
+
patch: `single line`,
+
expected: false,
+
},
+
{
+
name: `valid diff patch`,
+
patch: `diff --git a/file.txt b/file.txt
+
index abc..def 100644
+
--- a/file.txt
+
+++ b/file.txt
+
@@ -1,3 +1,3 @@
+
-old line
+
+new line
+
context`,
+
expected: true,
+
},
+
{
+
name: `valid patch starting with ---`,
+
patch: `--- a/file.txt
+
+++ b/file.txt
+
@@ -1,3 +1,3 @@
+
-old line
+
+new line
+
context`,
+
expected: true,
+
},
+
{
+
name: `valid patch starting with Index`,
+
patch: `Index: file.txt
+
==========
+
--- a/file.txt
+
+++ b/file.txt
+
@@ -1,3 +1,3 @@
+
-old line
+
+new line
+
context`,
+
expected: true,
+
},
+
{
+
name: `valid patch starting with +++`,
+
patch: `+++ b/file.txt
+
--- a/file.txt
+
@@ -1,3 +1,3 @@
+
-old line
+
+new line
+
context`,
+
expected: true,
+
},
+
{
+
name: `valid patch starting with @@`,
+
patch: `@@ -1,3 +1,3 @@
+
-old line
+
+new line
+
context
+
`,
+
expected: true,
+
},
+
{
+
name: `valid format patch`,
+
patch: `From 3c5035488318164b81f60fe3adcd6c9199d76331 Mon Sep 17 00:00:00 2001
+
From: Author <author@example.com>
+
Date: Wed, 16 Apr 2025 11:01:00 +0300
+
Subject: [PATCH] Example patch
+
+
diff --git a/file.txt b/file.txt
+
index 123456..789012 100644
+
--- a/file.txt
+
+++ b/file.txt
+
@@ -1 +1 @@
+
-old content
+
+new content
+
--
+
2.48.1`,
+
expected: true,
+
},
+
{
+
name: `invalid format patch`,
+
patch: `From 1234567890123456789012345678901234567890 Mon Sep 17 00:00:00 2001
+
From: Author <author@example.com>
+
This is not a valid patch format`,
+
expected: false,
+
},
+
{
+
name: `not a patch at all`,
+
patch: `This is
+
just some
+
random text
+
that isn't a patch`,
+
expected: false,
+
},
+
}
+
+
for _, tt := range tests {
+
t.Run(tt.name, func(t *testing.T) {
+
result := IsPatchValid(tt.patch)
+
if result != tt.expected {
+
t.Errorf("IsPatchValid() = %v, want %v", result, tt.expected)
+
}
+
})
+
}
+
}
+
+
func TestSplitPatches(t *testing.T) {
+
tests := []struct {
+
name string
+
input string
+
expected []string
+
}{
+
{
+
name: "Empty input",
+
input: "",
+
expected: []string{},
+
},
+
{
+
name: "No valid patches",
+
input: "This is not a \nJust some random text",
+
expected: []string{},
+
},
+
{
+
name: "Single patch",
+
input: `From 3c5035488318164b81f60fe3adcd6c9199d76331 Mon Sep 17 00:00:00 2001
+
From: Author <author@example.com>
+
Date: Wed, 16 Apr 2025 11:01:00 +0300
+
Subject: [PATCH] Example patch
+
+
diff --git a/file.txt b/file.txt
+
index 123456..789012 100644
+
--- a/file.txt
+
+++ b/file.txt
+
@@ -1 +1 @@
+
-old content
+
+new content
+
--
+
2.48.1`,
+
expected: []string{
+
`From 3c5035488318164b81f60fe3adcd6c9199d76331 Mon Sep 17 00:00:00 2001
+
From: Author <author@example.com>
+
Date: Wed, 16 Apr 2025 11:01:00 +0300
+
Subject: [PATCH] Example patch
+
+
diff --git a/file.txt b/file.txt
+
index 123456..789012 100644
+
--- a/file.txt
+
+++ b/file.txt
+
@@ -1 +1 @@
+
-old content
+
+new content
+
--
+
2.48.1`,
+
},
+
},
+
{
+
name: "Two patches",
+
input: `From 3c5035488318164b81f60fe3adcd6c9199d76331 Mon Sep 17 00:00:00 2001
+
From: Author <author@example.com>
+
Date: Wed, 16 Apr 2025 11:01:00 +0300
+
Subject: [PATCH 1/2] First patch
+
+
diff --git a/file1.txt b/file1.txt
+
index 123456..789012 100644
+
--- a/file1.txt
+
+++ b/file1.txt
+
@@ -1 +1 @@
+
-old content
+
+new content
+
--
+
2.48.1
+
From a9529f3b3a653329a5268f0f4067225480207e3c Mon Sep 17 00:00:00 2001
+
From: Author <author@example.com>
+
Date: Wed, 16 Apr 2025 11:03:11 +0300
+
Subject: [PATCH 2/2] Second patch
+
+
diff --git a/file2.txt b/file2.txt
+
index abcdef..ghijkl 100644
+
--- a/file2.txt
+
+++ b/file2.txt
+
@@ -1 +1 @@
+
-foo bar
+
+baz qux
+
--
+
2.48.1`,
+
expected: []string{
+
`From 3c5035488318164b81f60fe3adcd6c9199d76331 Mon Sep 17 00:00:00 2001
+
From: Author <author@example.com>
+
Date: Wed, 16 Apr 2025 11:01:00 +0300
+
Subject: [PATCH 1/2] First patch
+
+
diff --git a/file1.txt b/file1.txt
+
index 123456..789012 100644
+
--- a/file1.txt
+
+++ b/file1.txt
+
@@ -1 +1 @@
+
-old content
+
+new content
+
--
+
2.48.1`,
+
`From a9529f3b3a653329a5268f0f4067225480207e3c Mon Sep 17 00:00:00 2001
+
From: Author <author@example.com>
+
Date: Wed, 16 Apr 2025 11:03:11 +0300
+
Subject: [PATCH 2/2] Second patch
+
+
diff --git a/file2.txt b/file2.txt
+
index abcdef..ghijkl 100644
+
--- a/file2.txt
+
+++ b/file2.txt
+
@@ -1 +1 @@
+
-foo bar
+
+baz qux
+
--
+
2.48.1`,
+
},
+
},
+
{
+
name: "Patches with additional text between them",
+
input: `Some text before the patches
+
+
From 3c5035488318164b81f60fe3adcd6c9199d76331 Mon Sep 17 00:00:00 2001
+
From: Author <author@example.com>
+
Subject: [PATCH] First patch
+
+
diff content here
+
--
+
2.48.1
+
+
Some text between patches
+
+
From a9529f3b3a653329a5268f0f4067225480207e3c Mon Sep 17 00:00:00 2001
+
From: Author <author@example.com>
+
Subject: [PATCH] Second patch
+
+
more diff content
+
--
+
2.48.1
+
+
Text after patches`,
+
expected: []string{
+
`From 3c5035488318164b81f60fe3adcd6c9199d76331 Mon Sep 17 00:00:00 2001
+
From: Author <author@example.com>
+
Subject: [PATCH] First patch
+
+
diff content here
+
--
+
2.48.1
+
+
Some text between patches`,
+
`From a9529f3b3a653329a5268f0f4067225480207e3c Mon Sep 17 00:00:00 2001
+
From: Author <author@example.com>
+
Subject: [PATCH] Second patch
+
+
more diff content
+
--
+
2.48.1
+
+
Text after patches`,
+
},
+
},
+
{
+
name: "Patches with whitespace padding",
+
input: `
+
+
From 3c5035488318164b81f60fe3adcd6c9199d76331 Mon Sep 17 00:00:00 2001
+
From: Author <author@example.com>
+
Subject: Patch
+
+
content
+
--
+
2.48.1
+
+
+
From a9529f3b3a653329a5268f0f4067225480207e3c Mon Sep 17 00:00:00 2001
+
From: Author <author@example.com>
+
Subject: Another patch
+
+
content
+
--
+
2.48.1
+
`,
+
expected: []string{
+
`From 3c5035488318164b81f60fe3adcd6c9199d76331 Mon Sep 17 00:00:00 2001
+
From: Author <author@example.com>
+
Subject: Patch
+
+
content
+
--
+
2.48.1`,
+
`From a9529f3b3a653329a5268f0f4067225480207e3c Mon Sep 17 00:00:00 2001
+
From: Author <author@example.com>
+
Subject: Another patch
+
+
content
+
--
+
2.48.1`,
+
},
+
},
+
}
+
+
for _, tt := range tests {
+
t.Run(tt.name, func(t *testing.T) {
+
result := splitFormatPatch(tt.input)
+
if !reflect.DeepEqual(result, tt.expected) {
+
t.Errorf("splitPatches() = %v, want %v", result, tt.expected)
+
}
+
})
+
}
+
}
+1 -17
rbac/rbac.go
···
import (
"database/sql"
"fmt"
-
"path"
"strings"
adapter "github.com/Blank-Xu/sql-adapter"
···
e = some(where (p.eft == allow))
[matchers]
-
m = r.act == p.act && r.dom == p.dom && keyMatch2(r.obj, p.obj) && g(r.sub, p.sub, r.dom)
+
m = r.act == p.act && r.dom == p.dom && r.obj == p.obj && g(r.sub, p.sub, r.dom)
`
)
···
E *casbin.Enforcer
}
-
func keyMatch2(key1 string, key2 string) bool {
-
matched, _ := path.Match(key2, key1)
-
return matched
-
}
-
func NewEnforcer(path string) (*Enforcer, error) {
m, err := model.NewModelFromString(Model)
if err != nil {
···
}
e.EnableAutoSave(false)
-
-
e.AddFunction("keyMatch2", keyMatch2Func)
return &Enforcer{e}, nil
}
···
}
return permissions
-
}
-
-
// keyMatch2Func is a wrapper for keyMatch2 to make it compatible with Casbin
-
func keyMatch2Func(args ...interface{}) (interface{}, error) {
-
name1 := args[0].(string)
-
name2 := args[1].(string)
-
-
return keyMatch2(name1, name2), nil
}
func checkRepoFormat(repo string) error {
+7 -1
readme.md
···
Read the introduction to Tangled [here](https://blog.tangled.sh/intro).
-
Documentation:
+
## docs
+
* [knot hosting
guide](https://tangled.sh/@tangled.sh/core/blob/master/docs/knot-hosting.md)
* [contributing
guide](https://tangled.sh/@tangled.sh/core/blob/master/docs/contributing.md)&mdash;**read this before opening a PR!**
+
+
## security
+
+
If you've identified a security issue in Tangled, please email
+
[security@tangled.sh](mailto:security@tangled.sh) with details!
+68 -45
tailwind.config.js
···
const colors = require("tailwindcss/colors");
module.exports = {
-
content: ["./appview/pages/templates/**/*.html", "./appview/pages/chroma.go"],
-
darkMode: "media",
-
theme: {
-
container: {
-
padding: "2rem",
-
center: true,
-
screens: {
-
sm: "500px",
-
md: "600px",
-
lg: "800px",
-
xl: "1000px",
-
"2xl": "1200px",
-
},
-
},
-
extend: {
-
fontFamily: {
-
sans: ["InterVariable", "system-ui", "sans-serif", "ui-sans-serif"],
-
mono: [
-
"IBMPlexMono",
-
"ui-monospace",
-
"SFMono-Regular",
-
"Menlo",
-
"Monaco",
-
"Consolas",
-
"Liberation Mono",
-
"Courier New",
-
"monospace",
-
],
-
},
-
typography: {
-
DEFAULT: {
-
css: {
-
maxWidth: "none",
-
pre: {
-
backgroundColor: colors.gray[100],
-
color: colors.black,
-
"@apply dark:bg-gray-900 dark:text-gray-300 dark:border-gray-700 dark:border":
-
{},
-
},
-
},
-
},
-
},
-
},
-
},
-
plugins: [require("@tailwindcss/typography")],
+
content: ["./appview/pages/templates/**/*.html", "./appview/pages/chroma.go"],
+
darkMode: "media",
+
theme: {
+
container: {
+
padding: "2rem",
+
center: true,
+
screens: {
+
sm: "500px",
+
md: "600px",
+
lg: "800px",
+
xl: "1000px",
+
"2xl": "1200px",
+
},
+
},
+
extend: {
+
fontFamily: {
+
sans: ["InterVariable", "system-ui", "sans-serif", "ui-sans-serif"],
+
mono: [
+
"IBMPlexMono",
+
"ui-monospace",
+
"SFMono-Regular",
+
"Menlo",
+
"Monaco",
+
"Consolas",
+
"Liberation Mono",
+
"Courier New",
+
"monospace",
+
],
+
},
+
typography: {
+
DEFAULT: {
+
css: {
+
maxWidth: "none",
+
pre: {
+
backgroundColor: colors.gray[100],
+
color: colors.black,
+
"@apply font-normal text-black bg-gray-100 dark:bg-gray-900 dark:text-gray-300 dark:border-gray-700 dark:border": {},
+
},
+
code: {
+
"@apply font-normal font-mono p-1 rounded text-black bg-gray-100 dark:bg-gray-900 dark:text-gray-300 dark:border-gray-700": {},
+
},
+
"code::before": {
+
content: '""',
+
},
+
"code::after": {
+
content: '""',
+
},
+
blockquote: {
+
quotes: "none",
+
},
+
'h1, h2, h3, h4': {
+
"@apply mt-4 mb-2": {}
+
},
+
h1: {
+
"@apply mt-3 pb-3 border-b border-gray-300 dark:border-gray-600": {}
+
},
+
h2: {
+
"@apply mt-3 pb-3 border-b border-gray-200 dark:border-gray-700": {}
+
},
+
h3: {
+
"@apply mt-2": {}
+
},
+
},
+
},
+
},
+
},
+
},
+
plugins: [require("@tailwindcss/typography")],
};
+1
types/capabilities.go
···
type Capabilities struct {
PullRequests struct {
+
FormatPatch bool `json:"format_patch"`
PatchSubmissions bool `json:"patch_submissions"`
BranchSubmissions bool `json:"branch_submissions"`
ForkSubmissions bool `json:"fork_submissions"`
+28
types/diff.go
···
IsRename bool `json:"is_rename"`
}
+
type DiffStat struct {
+
Insertions int64
+
Deletions int64
+
}
+
+
func (d *Diff) Stats() DiffStat {
+
var stats DiffStat
+
for _, f := range d.TextFragments {
+
stats.Insertions += f.LinesAdded
+
stats.Deletions += f.LinesDeleted
+
}
+
return stats
+
}
+
// A nicer git diff representation.
type NiceDiff struct {
Commit struct {
···
Patch string `json:"patch"`
Diff []*gitdiff.File `json:"diff"`
}
+
+
func (d *NiceDiff) ChangedFiles() []string {
+
files := make([]string, len(d.Diff))
+
+
for i, f := range d.Diff {
+
if f.IsDelete {
+
files[i] = f.Name.Old
+
} else {
+
files[i] = f.Name.New
+
}
+
}
+
+
return files
+
}
+6 -2
types/repo.go
···
import (
"github.com/go-git/go-git/v5/plumbing/object"
+
"tangled.sh/tangled.sh/core/patchutil"
)
type RepoIndexResponse struct {
···
Diff *NiceDiff `json:"diff,omitempty"`
}
-
type RepoDiffTreeResponse struct {
-
DiffTree *DiffTree `json:"difftree,omitempty"`
+
type RepoFormatPatchResponse struct {
+
Rev1 string `json:"rev1,omitempty"`
+
Rev2 string `json:"rev2,omitempty"`
+
FormatPatch []patchutil.FormatPatch `json:"format_patch,omitempty"`
+
Patch string `json:"patch,omitempty"`
}
type RepoTreeResponse struct {