gip-remote 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,131 @@
1
+ # gip-remote
2
+
3
+ Git-in-Pear remote database. Store and replicate Git repositories over Hyperswarm using HyperDB.
4
+
5
+ ```
6
+ npm install gip-remote
7
+ ```
8
+
9
+ ## Usage
10
+
11
+ ```js
12
+ const Corestore = require('corestore')
13
+ const Hyperswarm = require('hyperswarm')
14
+ const { Remote } = require('gip-remote')
15
+
16
+ const store = new Corestore('./my-store')
17
+ const swarm = new Hyperswarm()
18
+
19
+ const remote = new Remote({ name: 'my-repo', store, swarm })
20
+ await remote.ready()
21
+
22
+ console.log(remote.key) // public key
23
+ ```
24
+
25
+ ### Push
26
+
27
+ ```js
28
+ // objects is a Map of oid => { type, size, data }
29
+ await remote.push('main', commitOid, objects)
30
+ ```
31
+
32
+ ### Fetch
33
+
34
+ ```js
35
+ const refs = await remote.getAllRefs()
36
+ const objects = await remote.getRefObjects(commitOid)
37
+ ```
38
+
39
+ ### toDrive
40
+
41
+ Get a Hyperdrive-compatible interface for a branch. Works with `mirror-drive`.
42
+
43
+ ```js
44
+ const drive = await remote.toDrive('main')
45
+
46
+ const content = await drive.get('/README.md')
47
+
48
+ for await (const path of drive.list('/')) {
49
+ console.log(path)
50
+ }
51
+
52
+ // Mirror to a local Hyperdrive
53
+ const mirror = drive.mirror(localDrive)
54
+ await mirror.done()
55
+ ```
56
+
57
+ ### toDisk
58
+
59
+ Write git objects directly to a `.git` directory on disk.
60
+
61
+ ```js
62
+ const { toDisk } = require('gip-remote/lib/git')
63
+
64
+ const objects = await remote.getRefObjects(commitOid)
65
+
66
+ await toDisk({
67
+ gitDir: '/path/to/repo/.git',
68
+ objects,
69
+ refs: { 'refs/heads/main': commitOid },
70
+ head: 'main'
71
+ })
72
+ ```
73
+
74
+ ## API
75
+
76
+ #### `const remote = new Remote(opts)`
77
+
78
+ Create a new remote.
79
+
80
+ - `opts.name` - repository name
81
+ - `opts.store` - a Corestore instance
82
+ - `opts.swarm` - a Hyperswarm instance
83
+ - `opts.key` - optional public key to open an existing remote
84
+ - `opts.timeout` - peer discovery timeout in ms (default `240000`)
85
+
86
+ #### `remote.key`
87
+
88
+ Public key of the underlying Hypercore.
89
+
90
+ #### `remote.discoveryKey`
91
+
92
+ Discovery key used for swarming.
93
+
94
+ #### `await remote.push(branch, commitOid, objects)`
95
+
96
+ Push a commit. `objects` is a `Map<oid, { type, size, data }>`.
97
+
98
+ #### `await remote.getAllRefs()`
99
+
100
+ Returns an array of `{ ref, oid }`.
101
+
102
+ #### `await remote.getBranchRef(branch)`
103
+
104
+ Returns `{ ref, oid }` or `null`.
105
+
106
+ #### `await remote.getRefObjects(commitOid)`
107
+
108
+ Returns all stored objects for a commit.
109
+
110
+ #### `await remote.getObject(oid)`
111
+
112
+ Get a single object by OID.
113
+
114
+ #### `const drive = await remote.toDrive(branch)`
115
+
116
+ Returns a `RemoteDrive` or `null` if the branch doesn't exist. The drive is compatible with `mirror-drive`.
117
+
118
+ #### `await toDisk(opts)`
119
+
120
+ Write git objects to a `.git` directory.
121
+
122
+ - `opts.gitDir` - path to the `.git` directory (required)
123
+ - `opts.objects` - array of `{ type, id, size, data }` (required)
124
+ - `opts.refs` - object mapping ref names to OIDs, e.g. `{ 'refs/heads/main': commitOid }`
125
+ - `opts.head` - branch name to set HEAD to, e.g. `'main'`
126
+ - `opts.objectFormat` - hash algorithm, only `'sha1'` supported (default)
127
+ - `opts.verifySizes` - verify declared sizes match buffer lengths (default `true`)
128
+
129
+ ## License
130
+
131
+ Apache-2.0
package/index.d.ts ADDED
@@ -0,0 +1,110 @@
1
+ import { Readable } from 'streamx'
2
+
3
+ interface RemoteOpts {
4
+ name?: string
5
+ store: any
6
+ swarm: any
7
+ key?: Buffer
8
+ timeout?: number
9
+ blind?: boolean
10
+ }
11
+
12
+ interface GitObject {
13
+ oid: string
14
+ type: string
15
+ size: number
16
+ data: Buffer
17
+ }
18
+
19
+ interface Ref {
20
+ ref: string
21
+ oid: string
22
+ }
23
+
24
+ interface RefObject extends GitObject {
25
+ id: string
26
+ }
27
+
28
+ declare class Remote {
29
+ constructor(opts: RemoteOpts)
30
+
31
+ readonly name: string
32
+ readonly core: any
33
+ readonly key: Buffer
34
+ readonly discoveryKey: Buffer
35
+ readonly availablePeers: number
36
+
37
+ ready(): Promise<void>
38
+ close(): Promise<void>
39
+
40
+ push(
41
+ branch: string,
42
+ commitOid: string,
43
+ objects: Map<string, { type: string; size: number; data: Buffer }>
44
+ ): Promise<void>
45
+ getAllRefs(): Promise<Ref[]>
46
+ getBranchRef(branch: string): Promise<Ref | null>
47
+ getObject(oid: string): Promise<GitObject | null>
48
+ getRefObjects(commitOid: string, onLoad?: (size: number) => void): Promise<RefObject[]>
49
+ toDrive(branch: string): Promise<RemoteDrive | null>
50
+ waitForPeers(): Promise<void>
51
+ }
52
+
53
+ interface DriveEntry {
54
+ key: string
55
+ value: {
56
+ executable: boolean
57
+ linkname: null
58
+ blob: { byteLength: number }
59
+ metadata: null
60
+ }
61
+ }
62
+
63
+ declare class RemoteDrive {
64
+ constructor(db: any, opts?: { branch?: string })
65
+
66
+ ready(): Promise<void>
67
+
68
+ entry(nameOrEntry: string | { key: string }): Promise<DriveEntry | null>
69
+ get(nameOrEntry: string | { key: string }): Promise<Buffer | null>
70
+ createReadStream(entryOrKey: string | { key: string }): Readable
71
+ list(folder: string, opts?: { ignore?: (path: string) => boolean }): Readable
72
+ readdir(folder: string): Readable
73
+ mirror(out: any, opts?: any): any
74
+ }
75
+
76
+ interface ToDiskOpts {
77
+ gitDir: string
78
+ objects: Array<{ type: string; id: string; size: number; data: Buffer }>
79
+ refs?: Record<string, string>
80
+ head?: string
81
+ objectFormat?: 'sha1'
82
+ fs?: any
83
+ verifySizes?: boolean
84
+ }
85
+
86
+ declare function toDisk(opts: ToDiskOpts): Promise<void>
87
+
88
+ interface Commit {
89
+ tree: string | null
90
+ parents: string[]
91
+ author: string | null
92
+ timestamp: number
93
+ message: string
94
+ }
95
+
96
+ interface FileEntry {
97
+ path: string
98
+ oid: string
99
+ mode: string
100
+ size: number
101
+ }
102
+
103
+ declare function parseCommit(data: Buffer): Commit
104
+ declare function walkTree(
105
+ objects: Map<string, { type: string; size: number; data: Buffer }>,
106
+ treeOid: string,
107
+ prefix: string
108
+ ): FileEntry[]
109
+
110
+ export { Remote, RemoteDrive, toDisk, parseCommit, walkTree }
package/index.js ADDED
@@ -0,0 +1,218 @@
1
+ const ReadyResource = require('ready-resource')
2
+ const HyperDB = require('hyperdb')
3
+ const Hyperbee = require('hyperbee2')
4
+ const def = require('./schema/hyperdb/index')
5
+ const RemoteDrive = require('./lib/drive')
6
+ const { parseCommit, walkTree } = require('./lib/git')
7
+
8
+ class Remote extends ReadyResource {
9
+ _swarm = null
10
+ _store = null
11
+ _db = null
12
+ _key = null
13
+
14
+ constructor(args = {}) {
15
+ super()
16
+
17
+ this._name = args.name
18
+ this._store = args.store
19
+ this._swarm = args.swarm
20
+ this._timeout = args.timeout || 240_000
21
+ this._blind = args.blind
22
+ this._key = args.key
23
+
24
+ const bee = new Hyperbee(this._store, { key: args.key })
25
+ this._db = HyperDB.bee2(bee, def)
26
+
27
+ this._onconnection = (conn) => {
28
+ this._store.replicate(conn)
29
+ this.emit('connection', conn)
30
+ }
31
+
32
+ this._swarm.on('connection', this._onconnection)
33
+ }
34
+
35
+ async _open() {
36
+ await this._db.ready()
37
+
38
+ this._topic = this._swarm.join(this.discoveryKey)
39
+
40
+ await this._db.update()
41
+ }
42
+
43
+ async _close() {
44
+ this._swarm.off('connection', this._onconnection)
45
+
46
+ if (this._topic) await this._topic.destroy()
47
+
48
+ await this._db.close()
49
+ }
50
+
51
+ get name() {
52
+ return this._name
53
+ }
54
+ get core() {
55
+ return this._db.core
56
+ }
57
+ get key() {
58
+ return this._db.core.key
59
+ }
60
+ get discoveryKey() {
61
+ return this._db.core.discoveryKey
62
+ }
63
+ get availablePeers() {
64
+ return this._db.core.peers.length
65
+ }
66
+
67
+ // --- Objects ---
68
+
69
+ async getObject(oid) {
70
+ return this._db.get('@gip/objects', { oid })
71
+ }
72
+
73
+ // --- Refs / Branches ---
74
+
75
+ async getAllRefs() {
76
+ const branches = this._db.find('@gip/branches')
77
+ const refs = []
78
+
79
+ for await (const b of branches) {
80
+ refs.push({ ref: `refs/heads/${b.name}`, oid: b.commitOid })
81
+ }
82
+
83
+ const main = refs.find((r) => r.ref === 'refs/heads/main')
84
+ if (main) refs.push({ ref: 'HEAD', oid: main.oid })
85
+
86
+ return refs.reverse()
87
+ }
88
+
89
+ async getBranchRef(branch) {
90
+ const b = await this._db.get('@gip/branches', { name: branch })
91
+ if (!b) return null
92
+ return { ref: `refs/heads/${b.name}`, oid: b.commitOid }
93
+ }
94
+
95
+ // --- Push: store objects + index branch + files ---
96
+
97
+ async push(branchName, commitOid, objects) {
98
+ // 1. Store all git objects
99
+ for (const [oid, obj] of objects) {
100
+ const existing = await this.getObject(oid)
101
+ if (existing) continue
102
+
103
+ await this._db.insert('@gip/objects', {
104
+ oid,
105
+ type: obj.type,
106
+ size: obj.size,
107
+ data: obj.data
108
+ })
109
+ }
110
+
111
+ // 2. Parse commit metadata
112
+ const commitObj = objects.get(commitOid)
113
+ if (!commitObj) throw new Error('Commit object not found: ' + commitOid)
114
+
115
+ const commit = parseCommit(commitObj.data)
116
+ if (!commit.tree) throw new Error('Commit has no tree: ' + commitOid)
117
+
118
+ // 3. Walk tree to enumerate files
119
+ const files = walkTree(objects, commit.tree, '')
120
+
121
+ // 4. Insert file records
122
+ for (const file of files) {
123
+ await this._db.insert('@gip/files', {
124
+ branch: branchName,
125
+ path: file.path,
126
+ oid: file.oid,
127
+ mode: file.mode,
128
+ size: file.size,
129
+ author: commit.author,
130
+ message: commit.message,
131
+ timestamp: commit.timestamp
132
+ })
133
+ }
134
+
135
+ // 5. Insert branch record
136
+ await this._db.insert('@gip/branches', {
137
+ name: branchName,
138
+ commitOid,
139
+ treeOid: commit.tree,
140
+ author: commit.author,
141
+ message: commit.message,
142
+ timestamp: commit.timestamp,
143
+ objects: [...objects.keys()]
144
+ })
145
+
146
+ // 6. Flush
147
+ await this._db.flush()
148
+ }
149
+
150
+ // --- Fetch support ---
151
+
152
+ async getRefObjects(commitOid, onLoad) {
153
+ const branches = this._db.find('@gip/branches')
154
+ let branch = null
155
+
156
+ for await (const b of branches) {
157
+ if (b.commitOid === commitOid) {
158
+ branch = b
159
+ break
160
+ }
161
+ }
162
+
163
+ if (!branch) return []
164
+
165
+ const results = []
166
+ for (const oid of branch.objects) {
167
+ const obj = await this.getObject(oid)
168
+ if (!obj) continue
169
+
170
+ // Empty blobs have null data after round-tripping through compact-encoding
171
+ const data = obj.data || Buffer.alloc(0)
172
+
173
+ if (onLoad) onLoad(obj.size)
174
+ results.push({ ...obj, data, id: oid })
175
+ }
176
+
177
+ return results
178
+ }
179
+
180
+ // --- Drive ---
181
+
182
+ async toDrive(branch) {
183
+ const b = await this._db.get('@gip/branches', { name: branch })
184
+ if (!b) return null
185
+
186
+ const drive = new RemoteDrive(this._db, { branch })
187
+ await drive.ready()
188
+ return drive
189
+ }
190
+
191
+ // --- Peer discovery ---
192
+
193
+ async waitForPeers() {
194
+ return new Promise((resolve, reject) => {
195
+ const timeout = setTimeout(() => {
196
+ clearInterval(interval)
197
+ reject(new Error(`Timeout waiting for peers after ${this._timeout}ms`))
198
+ }, this._timeout)
199
+
200
+ const interval = setInterval(async () => {
201
+ if (this.availablePeers > 0) {
202
+ clearInterval(interval)
203
+ clearTimeout(timeout)
204
+ resolve()
205
+ } else {
206
+ await this._db.update()
207
+ }
208
+ }, 500)
209
+ })
210
+ }
211
+ }
212
+
213
+ module.exports = {
214
+ Remote,
215
+ RemoteDrive,
216
+ parseCommit,
217
+ walkTree
218
+ }
package/lib/drive.js ADDED
@@ -0,0 +1,133 @@
1
+ const ReadyResource = require('ready-resource')
2
+ const MirrorDrive = require('mirror-drive')
3
+ const { Readable } = require('streamx')
4
+
5
+ class RemoteDrive extends ReadyResource {
6
+ constructor(db, { branch = 'main' } = {}) {
7
+ super()
8
+ this._db = db
9
+ this._branch = branch
10
+ }
11
+
12
+ async _open() {
13
+ await this._db.ready()
14
+ }
15
+
16
+ _resolveKey(nameOrEntry) {
17
+ if (typeof nameOrEntry === 'object' && nameOrEntry !== null) return nameOrEntry.key
18
+ return nameOrEntry
19
+ }
20
+
21
+ async entry(nameOrEntry) {
22
+ const key = this._resolveKey(nameOrEntry)
23
+ const record = await this._db.get('@gip/files', {
24
+ branch: this._branch,
25
+ path: key
26
+ })
27
+ if (!record) return null
28
+
29
+ return {
30
+ key,
31
+ value: {
32
+ executable: record.mode === '100755',
33
+ linkname: null,
34
+ blob: { byteLength: record.size },
35
+ metadata: null
36
+ }
37
+ }
38
+ }
39
+
40
+ async get(nameOrEntry) {
41
+ const key = this._resolveKey(nameOrEntry)
42
+ const record = await this._db.get('@gip/files', {
43
+ branch: this._branch,
44
+ path: key
45
+ })
46
+ if (!record) return null
47
+
48
+ const obj = await this._db.get('@gip/objects', { oid: record.oid })
49
+ if (!obj) return null
50
+ return obj.data
51
+ }
52
+
53
+ createReadStream(entryOrKey) {
54
+ const self = this
55
+ const key = typeof entryOrKey === 'object' ? entryOrKey.key : entryOrKey
56
+
57
+ return new Readable({
58
+ async read(cb) {
59
+ try {
60
+ const buf = await self.get(key)
61
+ if (buf) this.push(buf)
62
+ this.push(null)
63
+ cb(null)
64
+ } catch (err) {
65
+ cb(err)
66
+ }
67
+ }
68
+ })
69
+ }
70
+
71
+ _findRange(folder) {
72
+ const branch = this._branch
73
+ if (!folder || folder === '/') {
74
+ return this._db.find('@gip/files-by-branch', { branch })
75
+ }
76
+
77
+ return this._db.find('@gip/files-by-branch', {
78
+ gte: { branch, path: folder + '/' },
79
+ lt: { branch, path: folder + '/\uffff' }
80
+ })
81
+ }
82
+
83
+ list(folder, opts) {
84
+ const ignore = opts && opts.ignore
85
+ const stream = this._findRange(folder)
86
+
87
+ return new Readable({
88
+ async read(cb) {
89
+ try {
90
+ for await (const record of stream) {
91
+ if (ignore && ignore(record.path)) continue
92
+ this.push(record.path)
93
+ }
94
+ this.push(null)
95
+ cb(null)
96
+ } catch (err) {
97
+ cb(err)
98
+ }
99
+ }
100
+ })
101
+ }
102
+
103
+ readdir(folder) {
104
+ const prefix = !folder || folder === '/' ? '/' : folder + '/'
105
+ const seen = new Set()
106
+ const stream = this._findRange(folder)
107
+
108
+ return new Readable({
109
+ async read(cb) {
110
+ try {
111
+ for await (const record of stream) {
112
+ const rest = prefix === '/' ? record.path.slice(1) : record.path.slice(prefix.length)
113
+ const name = rest.split('/')[0]
114
+ if (!seen.has(name)) {
115
+ seen.add(name)
116
+ this.push(name)
117
+ }
118
+ }
119
+ this.push(null)
120
+ cb(null)
121
+ } catch (err) {
122
+ cb(err)
123
+ }
124
+ }
125
+ })
126
+ }
127
+
128
+ mirror(out, opts) {
129
+ return new MirrorDrive(this, out, opts)
130
+ }
131
+ }
132
+
133
+ module.exports = RemoteDrive
package/lib/git.js ADDED
@@ -0,0 +1,139 @@
1
+ const git = require('rebuild-git')
2
+ const { GitTree } = git
3
+ const { dirname } = require('path')
4
+ const { promises: defaultFs } = require('fs')
5
+
6
+ // --- Git commit parser ---
7
+
8
+ function parseCommit(data) {
9
+ const text = data.toString('utf8')
10
+ const lines = text.split('\n')
11
+ const result = { tree: null, parents: [], author: null, timestamp: 0, message: '' }
12
+
13
+ let i = 0
14
+ for (; i < lines.length; i++) {
15
+ const line = lines[i]
16
+ if (line === '') {
17
+ i++
18
+ break
19
+ }
20
+
21
+ if (line.startsWith('tree ')) {
22
+ result.tree = line.slice(5)
23
+ } else if (line.startsWith('parent ')) {
24
+ result.parents.push(line.slice(7))
25
+ } else if (line.startsWith('author ')) {
26
+ const match = line.match(/^author (.+) <.+> (\d+) [+-]\d+$/)
27
+ if (match) {
28
+ result.author = match[1]
29
+ result.timestamp = parseInt(match[2])
30
+ }
31
+ }
32
+ }
33
+
34
+ result.message = lines.slice(i).join('\n').trim()
35
+ return result
36
+ }
37
+
38
+ // --- Tree walker: extracts all file paths from git tree objects ---
39
+
40
+ function walkTree(objects, treeOid, prefix) {
41
+ const treeObj = objects.get(treeOid)
42
+ if (!treeObj || treeObj.type !== 'tree') return []
43
+
44
+ const entries = GitTree.from(treeObj.data).entries()
45
+ const files = []
46
+
47
+ for (const entry of entries) {
48
+ const path = prefix + '/' + entry.path
49
+ if (entry.type === 'tree') {
50
+ files.push(...walkTree(objects, entry.oid, path))
51
+ } else {
52
+ const blob = objects.get(entry.oid)
53
+ files.push({
54
+ path,
55
+ oid: entry.oid,
56
+ mode: entry.mode || '100644',
57
+ size: blob ? blob.size : 0
58
+ })
59
+ }
60
+ }
61
+
62
+ return files
63
+ }
64
+
65
+ /**
66
+ * Write git objects to disk, rebuilding a Git repo from in-memory objects.
67
+ *
68
+ * @param {object} opts
69
+ * @param {string} opts.gitDir - Path to the .git directory
70
+ * @param {string} [opts.objectFormat='sha1'] - Hash algorithm
71
+ * @param {Array} opts.objects - Array of { type, id, size, data }
72
+ * @param {boolean} [opts.verifySizes=true] - Verify object sizes match
73
+ */
74
+ async function toDisk(opts) {
75
+ const {
76
+ gitDir,
77
+ objectFormat = 'sha1',
78
+ objects,
79
+ refs,
80
+ head,
81
+ fs = defaultFs,
82
+ verifySizes = true
83
+ } = opts
84
+
85
+ if (!gitDir) throw new Error('gitDir is required')
86
+
87
+ if (objectFormat !== 'sha1') {
88
+ throw new Error('Only sha1 is supported')
89
+ }
90
+
91
+ if (!objects?.length) throw new Error('No objects supplied.')
92
+
93
+ for (const o of objects) {
94
+ if (!o.type || !o.id || o.data == null) {
95
+ throw new Error('Invalid object entry: missing type/id/data')
96
+ }
97
+ const data = o.data || Buffer.alloc(0)
98
+ if (verifySizes && data.length !== o.size) {
99
+ throw new Error(
100
+ `Size mismatch for ${o.type} ${o.id}: declared ${o.size}, buffer ${o.data.length}`
101
+ )
102
+ }
103
+
104
+ const oid = await git.writeObject({
105
+ fs,
106
+ dir: dirname(gitDir),
107
+ type: o.type,
108
+ object: data
109
+ })
110
+
111
+ if (oid !== o.id) {
112
+ throw new Error(`OID mismatch for ${o.type}: expected ${o.id} but git computed ${oid}`)
113
+ }
114
+ }
115
+
116
+ if (refs) {
117
+ for (const [refName, oid] of Object.entries(refs)) {
118
+ await git.writeRef({
119
+ fs,
120
+ dir: dirname(gitDir),
121
+ ref: refName,
122
+ value: oid,
123
+ force: true
124
+ })
125
+ }
126
+ }
127
+
128
+ if (head) {
129
+ await git.writeRef({
130
+ fs,
131
+ dir: dirname(gitDir),
132
+ ref: 'HEAD',
133
+ value: `ref: refs/heads/${head}`,
134
+ force: true
135
+ })
136
+ }
137
+ }
138
+
139
+ module.exports = { parseCommit, walkTree, toDisk }
package/package.json ADDED
@@ -0,0 +1,64 @@
1
+ {
2
+ "name": "gip-remote",
3
+ "version": "1.0.0",
4
+ "description": "Git+Pear remote DB for handling git data",
5
+ "main": "index.js",
6
+ "scripts": {
7
+ "format": "prettier . --write",
8
+ "test": "prettier . --check && lunte && brittle-bare test/index.js",
9
+ "lint": "lunte"
10
+ },
11
+ "type": "commonjs",
12
+ "imports": {
13
+ "fs": {
14
+ "bare": "bare-fs",
15
+ "default": "fs"
16
+ },
17
+ "path": {
18
+ "bare": "bare-path",
19
+ "default": "path"
20
+ }
21
+ },
22
+ "exports": {
23
+ "./package": "./package.json",
24
+ ".": {
25
+ "default": "./index.js"
26
+ }
27
+ },
28
+ "files": [
29
+ "package.json",
30
+ "index.js",
31
+ "index.d.ts",
32
+ "lib"
33
+ ],
34
+ "keywords": [],
35
+ "repository": {
36
+ "type": "git",
37
+ "url": "https://github.com/holepunchto/gip-remote.git"
38
+ },
39
+ "author": "Holepunch Inc",
40
+ "license": "Apache-2.0",
41
+ "bugs": {
42
+ "url": "https://github.com/holepunchto/gip-remote/issues"
43
+ },
44
+ "homepage": "https://github.com/holepunchto/gip-remote",
45
+ "devDependencies": {
46
+ "brittle": "^3.19.1",
47
+ "corestore": "^7.9.2",
48
+ "hyperdht": "^6.29.6",
49
+ "hyperswarm": "^4.17.0",
50
+ "prettier": "^3.8.1",
51
+ "prettier-config-holepunch": "^2.0.0",
52
+ "test-tmp": "^1.4.0"
53
+ },
54
+ "dependencies": {
55
+ "bare-fs": "^4.5.6",
56
+ "bare-path": "^3.0.0",
57
+ "hyperbee2": "^2.8.0",
58
+ "hyperdb": "^6.3.0",
59
+ "mirror-drive": "^1.13.0",
60
+ "ready-resource": "^1.2.0",
61
+ "rebuild-git": "^1.1.1",
62
+ "streamx": "^2.25.0"
63
+ }
64
+ }