GitRoot

craft your forge, build your project, grow your community freely
 1// SPDX-FileCopyrightText: 2025 Romain Maneschi <romain@gitroot.dev>
 2//
 3// SPDX-License-Identifier: EUPL-1.2
 4
 5package main
 6
 7import (
 8	"bytes"
 9	"fmt"
10	"io/fs"
11	"strings"
12	"testing"
13	"time"
14
15	gitroot "gitroot.dev/libs/golang/plugin"
16	"gitroot.dev/libs/golang/plugin/test"
17)
18
19func TestState(t *testing.T) {
20	// init mock
21	s := test.NewFakeServer(t, test.Override{
22		DiffWithParent: func(hash, oldFilepath, newFilepath string) (string, error) {
23			return "```diff\n+ coucou\n```", nil
24		},
25	})
26	p := Build(s)
27
28	//init worktree
29	s.ModifyContent("index.md", "hello")
30
31	//var
32	branchName := "branchName"
33	graftFilepath := fmt.Sprintf("grafts/%s.md", branchName)
34	commit := gitroot.Commit{Branch: branchName, Hash: "0000", Message: "add branch", Date: time.Now()}
35
36	//check init
37	p.Init("repoName", false, `{"defaultTargetBranch": "main"}`)
38	p.StartCommit(commit)
39	p.AddFile("index.md")
40	p.EndCommit(commit)
41	p.Finish()
42	res, _ := fs.ReadFile(s.Worktree(), graftFilepath)
43	if !bytes.Contains(res, []byte("status: draft")) {
44		t.Errorf("---\n%s\n---\n\nwant\n\n---\n%s\n---", res, "status: draft")
45	}
46
47	//check start review
48	s.ModifyContent(graftFilepath, strings.Replace(string(res), "status: draft", "status: review", 1))
49	p.Init("repoName", false, `{"defaultTargetBranch": "main"}`)
50	p.StartCommit(commit)
51	p.ModFile(graftFilepath, graftFilepath)
52	p.EndCommit(commit)
53	p.Finish()
54	res, _ = fs.ReadFile(s.Worktree(), graftFilepath)
55	if !bytes.Contains(res, []byte("status: review")) {
56		t.Errorf("---\n%s\n---\n\nwant\n\n---\n%s\n---", res, "status: review")
57	}
58
59	//check during review
60	s.ModifyContent("index.md", "hello\ncoucou")
61	p.Init("repoName", false, `{"defaultTargetBranch": "main"}`)
62	p.StartCommit(commit)
63	p.ModFile("index.md", "index.md")
64	p.EndCommit(commit)
65	p.Finish()
66	res, _ = fs.ReadFile(s.Worktree(), graftFilepath)
67	if !bytes.Contains(res, []byte("status: review")) {
68		t.Errorf("---\n%s\n---\n\nwant\n\n---\n%s\n---", res, "status: review")
69	}
70	if !bytes.Contains(res, []byte("```diff")) {
71		t.Errorf("---\n%s\n---\n\nwant\n\n---\n%s\n---", res, "```diff")
72	}
73
74	//check merge
75	s.ModifyContent(graftFilepath, strings.Replace(string(res), "status: review", "status: merge", 1))
76	p.Init("repoName", false, `{"defaultTargetBranch": "main"}`)
77	p.StartCommit(commit)
78	p.ModFile(graftFilepath, graftFilepath)
79	p.EndCommit(commit)
80	p.Finish()
81	if s.NbCall.Merge != 1 {
82		t.Errorf("Merge called %d times", s.NbCall.Merge)
83	}
84}