Skip to content

Commit

Permalink
tidying
Browse files Browse the repository at this point in the history
  • Loading branch information
richardjennings committed Oct 23, 2024
1 parent 9e7c0dd commit e021e37
Show file tree
Hide file tree
Showing 9 changed files with 57 additions and 71 deletions.
34 changes: 19 additions & 15 deletions config.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,12 +14,12 @@ const (
DefaultObjectsDirectory = "objects"
DefaultRefsDirectory = "refs"
DefaultRefsHeadsDirectory = "heads"
DefaultBranch = "refs/heads/main"
DefaultBranchName = "main"
DefaultEditor = "vim"
DefaultPackedRefsFile = "info/refs"
)

var Config Cnf
var config Cnf

type (
Cnf struct {
Expand Down Expand Up @@ -72,7 +72,7 @@ func Configure(opts ...Opt) error {
RefsDirectory: DefaultRefsDirectory,
RefsHeadsDirectory: DefaultRefsHeadsDirectory,
PackedRefsFile: DefaultPackedRefsFile,
DefaultBranch: DefaultBranch,
DefaultBranch: DefaultBranchName,
Editor: DefaultEditor,
GitIgnore: []string{ //@todo read from .gitignore
".idea/",
Expand All @@ -90,56 +90,56 @@ func Configure(opts ...Opt) error {
}
c.Path = p
}
Config = *c
config = *c
return nil
}

func Path() string {
return Config.Path
return config.Path
}

func GitPath() string {
return filepath.Join(Config.Path, Config.GitDirectory)
return filepath.Join(config.Path, config.GitDirectory)
}

func ObjectPath() string {
return filepath.Join(Config.Path, Config.GitDirectory, Config.ObjectsDirectory)
return filepath.Join(config.Path, config.GitDirectory, config.ObjectsDirectory)
}

func WorkingDirectory() string {
return Config.Path + string(filepath.Separator)
return config.Path + string(filepath.Separator)
}

func IndexFilePath() string {
return filepath.Join(Config.Path, Config.GitDirectory, Config.IndexFile)
return filepath.Join(config.Path, config.GitDirectory, config.IndexFile)
}

func RefsDirectory() string {
return filepath.Join(Config.Path, Config.GitDirectory, Config.RefsDirectory)
return filepath.Join(config.Path, config.GitDirectory, config.RefsDirectory)
}

func RefsHeadPrefix() string {
return filepath.Join(Config.RefsDirectory, Config.RefsHeadsDirectory) + string(os.PathSeparator)
return filepath.Join(config.RefsDirectory, config.RefsHeadsDirectory) + string(os.PathSeparator)
}

func RefsHeadsDirectory() string {
return filepath.Join(Config.Path, Config.GitDirectory, Config.RefsDirectory, Config.RefsHeadsDirectory)
return filepath.Join(config.Path, config.GitDirectory, config.RefsDirectory, config.RefsHeadsDirectory)
}

func PackedRefsFile() string {
return filepath.Join(Config.Path, Config.GitDirectory, Config.PackedRefsFile)
return filepath.Join(config.Path, config.GitDirectory, config.PackedRefsFile)
}

func GitHeadPath() string {
return filepath.Join(Config.Path, Config.GitDirectory, Config.HeadFile)
return filepath.Join(config.Path, config.GitDirectory, config.HeadFile)
}

func Pager() (string, []string) {
return "/usr/bin/less", []string{"-X", "-F"}
}

func Editor() (string, []string) {
return Config.Editor, Config.EditorArgs
return config.Editor, config.EditorArgs
}

func EditorFile() string {
Expand Down Expand Up @@ -173,3 +173,7 @@ func CommitterEmail() string {
}
return AuthorEmail()
}

func DefaultBranch() string {
return config.DefaultBranch
}
47 changes: 29 additions & 18 deletions fs.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"bytes"
"encoding/hex"
"fmt"
"log"
"os"
"path/filepath"
"strings"
Expand Down Expand Up @@ -36,7 +37,7 @@ type (
Path string
IdxStatus IndexStatus
WdStatus WDStatus
Sha *Sha
Sha Sha
Finfo os.FileInfo
}
Sha struct {
Expand Down Expand Up @@ -68,28 +69,19 @@ type (
}
)

func NewSha(b []byte) (*Sha, error) {
// NewSha creates a Sha from either a binary or hex encoded byte slice
func NewSha(b []byte) (Sha, error) {
if len(b) == 40 {
s := &Sha{}
s := Sha{}
_, _ = hex.Decode(s.hash[:], b)
return s, nil
}
if len(b) == 20 {
s := &Sha{}
s := Sha{}
copy(s.hash[:], b)
return s, nil
}
return nil, fmt.Errorf("invalid sha %s", b)
}

func (s *Sha) Same(ss *Sha) bool {
if ss == nil {
return false
}
if s == nil {
return false
}
return s.hash == ss.hash
return Sha{}, fmt.Errorf("invalid sha %s", b)
}

func (s Sha) AsHexString() string {
Expand All @@ -108,8 +100,8 @@ func (s Sha) AsArray() [20]byte {
return r
}

// @todo this is more AsSlice ...
func (s Sha) AsBytes() []byte {
// AsByteSlice returns a Sha as a byte slice
func (s Sha) AsByteSlice() []byte {
return s.hash[:]
}

Expand Down Expand Up @@ -217,7 +209,7 @@ func (fs *FileSet) MergeFromIndex(fss *FileSet) {
continue
}
fs.idx[v.Path].Finfo = v.Finfo
if !bytes.Equal(v.Sha.AsBytes(), fs.idx[v.Path].Sha.AsBytes()) {
if !bytes.Equal(v.Sha.AsByteSlice(), fs.idx[v.Path].Sha.AsByteSlice()) {
fs.idx[v.Path].IdxStatus = IndexUpdatedInIndex
continue
}
Expand Down Expand Up @@ -301,3 +293,22 @@ func (fi *Finfo) Sys() any { return nil }
func (fi *Finfo) ModTime() time.Time {
return time.Unix(int64(fi.MTimeS), int64(fi.MTimeN))
}

// Init initializes a git repository
func Init() error {
path := GitPath()
if err := os.MkdirAll(path, 0755); err != nil {
return err
}
for _, v := range []string{
ObjectPath(),
RefsDirectory(),
RefsHeadsDirectory(),
} {
if err := os.MkdirAll(v, 0755); err != nil {
log.Fatalln(err)
}
}
// set default main branch
return os.WriteFile(GitHeadPath(), []byte(fmt.Sprintf("ref: %s\n", filepath.Join(RefsHeadPrefix(), DefaultBranch()))), 0644)
}
24 changes: 2 additions & 22 deletions git/init.go
Original file line number Diff line number Diff line change
@@ -1,27 +1,7 @@
package git

import (
"fmt"
"github.com/richardjennings/g"
"log"
"os"
)
import "github.com/richardjennings/g"

// Init initializes a git repository
func Init() error {
path := g.GitPath()
if err := os.MkdirAll(path, 0755); err != nil {
return err
}
for _, v := range []string{
g.ObjectPath(),
g.RefsDirectory(),
g.RefsHeadsDirectory(),
} {
if err := os.MkdirAll(v, 0755); err != nil {
log.Fatalln(err)
}
}
// set default main branch
return os.WriteFile(g.GitHeadPath(), []byte(fmt.Sprintf("ref: %s\n", g.Config.DefaultBranch)), 0644)
return g.Init()
}
1 change: 0 additions & 1 deletion git/init_test.go
Original file line number Diff line number Diff line change
@@ -1,2 +1 @@
package git

4 changes: 2 additions & 2 deletions ignore.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,10 +13,10 @@ func IsIgnored(path string) bool {
return true
}
// @todo fix literal string prefix matching and iteration
for _, v := range Config.GitIgnore {
for _, v := range config.GitIgnore {
if strings.HasPrefix(path, v) {
return true
}
}
return strings.HasPrefix(path, Config.GitDirectory+string(filepath.Separator))
return strings.HasPrefix(path, config.GitDirectory+string(filepath.Separator))
}
6 changes: 0 additions & 6 deletions index.go
Original file line number Diff line number Diff line change
Expand Up @@ -166,9 +166,6 @@ func (idx *Index) Write() error {
}

func item(f *File) (*indexItem, error) {
if f.Sha == nil {
return nil, errors.New("missing Sha from working directory file toIndexItem")
}
if f.Finfo == nil {
info, err := os.Stat(filepath.Join(Path(), f.Path))
if err != nil {
Expand Down Expand Up @@ -244,8 +241,6 @@ func fromIndexItemP(p *indexItemP) *Finfo {
return f
}



// Status returns a FileSet containing all files from commit, index and working directory
// with the corresponding status.
func Status(idx *Index, commitSha []byte) (*FileSet, error) {
Expand Down Expand Up @@ -284,7 +279,6 @@ func FsStatus(path string) (*FileSet, error) {
return idxSet, nil
}


// ReadIndex reads the Git Index into an Index struct
func ReadIndex() (*Index, error) {
path := IndexFilePath()
Expand Down
2 changes: 1 addition & 1 deletion index_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import (

func TestAdd_WDUntracked(t *testing.T) {
idx := NewIndex()
err := idx.Add(&File{Path: "test_assets/test.file", Sha: &Sha{}, WdStatus: WDUntracked})
err := idx.Add(&File{Path: "test_assets/test.file", Sha: Sha{}, WdStatus: WDUntracked})
assert.Nil(t, err)
files := idx.Files()
assert.Equal(t, 1, len(files))
Expand Down
6 changes: 2 additions & 4 deletions object.go
Original file line number Diff line number Diff line change
Expand Up @@ -86,13 +86,13 @@ func ObjectTree(files []*File) *Object {
for _, v := range files {
parts := strings.Split(strings.TrimPrefix(v.Path, WorkingDirectory()), string(filepath.Separator))
if len(parts) == 1 {
root.Objects = append(root.Objects, &Object{Typ: ObjectTypeBlob, Path: v.Path, Sha: v.Sha.AsBytes()})
root.Objects = append(root.Objects, &Object{Typ: ObjectTypeBlob, Path: v.Path, Sha: v.Sha.AsByteSlice()})
continue // top level file
}
pn = root
for i, p := range parts {
if i == len(parts)-1 {
pn.Objects = append(pn.Objects, &Object{Typ: ObjectTypeBlob, Path: v.Path, Sha: v.Sha.AsBytes()})
pn.Objects = append(pn.Objects, &Object{Typ: ObjectTypeBlob, Path: v.Path, Sha: v.Sha.AsByteSlice()})
continue // leaf
}
// key for cached nodes
Expand All @@ -112,7 +112,6 @@ func ObjectTree(files []*File) *Object {
return root
}


// FlattenTree turns a TreeObject structure into a flat list of file paths
func (o *Object) FlattenTree() []*File {
var objFiles []*File
Expand Down Expand Up @@ -417,7 +416,6 @@ func CommittedFiles(sha []byte) ([]*File, error) {
return obj.FlattenTree(), nil
}


// WriteTree writes an Object Tree to the object store.
func (o *Object) WriteTree() ([]byte, error) {
// resolve child tree Objects
Expand Down
4 changes: 2 additions & 2 deletions refs.go
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ func HeadSHA(currentBranch string) ([]byte, error) {
bytes, err := os.ReadFile(path)
if err != nil && errors.Is(err, fs.ErrNotExist) {
// the default branch does not exist in refs/heads when there are no commits
if fmt.Sprintf("refs/heads/%s", currentBranch) == DefaultBranch {
if currentBranch == DefaultBranchName {
return nil, nil
}
return nil, fmt.Errorf("fatal: not a valid object name: '%s'", currentBranch)
Expand Down Expand Up @@ -124,7 +124,7 @@ func ListBranches() ([]string, error) {
for k := range branchMap {
branches = append(branches, k)
}
sort.Sort(sort.StringSlice(branches))
sort.Strings(branches)
return branches, nil
}

Expand Down

0 comments on commit e021e37

Please sign in to comment.