Debian Codegraph @

pkg/otbuiltin/init.go

raw
1 package otbuiltin
2
3 import (
4 "strings"
5 "unsafe"
6 )
7
8 // #cgo pkg-config: ostree-1
9 // #include <stdlib.h>
10 // #include <glib.h>
11 // #include <ostree.h>
12 // #include "builtin.go.h"
13 import "C"
14
15 // initOptions contains all of the options for initializing an ostree repo
16 //
17 // Note: while this is private, exported fields are public and part of the API.
18 type initOptions struct {
19 // Mode defines repository mode: either bare, archive-z2, or bare-user
20 Mode string
21 }
22
23 // NewInitOptions instantiates and returns an initOptions struct with default values set
24 func NewInitOptions() initOptions {
25 return initOptions{
26 Mode: "bare",
27 }
28 }
29
30 // Init initializes a new ostree repository at the given path. Returns true
31 // if the repo exists at the location, regardless of whether it was initialized
32 // by the function or if it already existed. Returns an error if the repo could
33 // not be initialized
34 func Init(path string, options initOptions) (bool, error) {
35 repoMode, err := parseRepoMode(options.Mode)
36 if err != nil {
37 return false, err
38 }
39
40 // Create a repo struct from the path
41 cpath := C.CString(path)
42 defer C.free(unsafe.Pointer(cpath))
43 pathc := C.g_file_new_for_path(cpath)
44 defer C.g_object_unref(C.gpointer(pathc))
45 repo := C.ostree_repo_new(pathc)
46
47 // If the repo exists in the filesystem, return an error but set exists to true
48 /* var exists C.gboolean = 0
49 success := glib.GoBool(glib.GBoolean(C.ostree_repo_exists(crepo, &exists, &cerr)))
50 if exists != 0 {
51 err = errors.New("repository already exists")
52 return true, err
53 } else if !success {
54 return false, generateError(cerr)
55 }*/
56
57 var cErr *C.GError
58 defer C.free(unsafe.Pointer(cErr))
59 if r := C.ostree_repo_create(repo, repoMode, nil, &cErr); !isOk(r) {
60 err := generateError(cErr)
61 if strings.Contains(err.Error(), "File exists") {
62 return true, err
63 }
64 return false, err
65 }
66 return true, nil
67 }
68
69 // parseRepoMode converts a mode string to a C.OSTREE_REPO_MODE enum value
70 func parseRepoMode(modeLabel string) (C.OstreeRepoMode, error) {
71 var cErr *C.GError
72 defer C.free(unsafe.Pointer(cErr))
73
74 cModeLabel := C.CString(modeLabel)
75 defer C.free(unsafe.Pointer(cModeLabel))
76
77 var retMode C.OstreeRepoMode
78 if r := C.ostree_repo_mode_from_string(cModeLabel, &retMode, &cErr); !isOk(r) {
79 // NOTE(lucab): zero-value for this C enum has no special/invalid meaning.
80 return C.OSTREE_REPO_MODE_BARE, generateError(cErr)
81 }
82
83 return retMode, nil
84 }