Welcome to mirror list, hosted at ThFree Co, Russian Federation.

OdbBackend.cs « LibGit2Sharp - github.com/mono/libgit2sharp.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 8ecd3f73425ff7782dd2f9d56290ec31bbd9a2e5 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
using System;
using System.Globalization;
using System.IO;
using System.Runtime.InteropServices;
using LibGit2Sharp.Core;

namespace LibGit2Sharp
{
    /// <summary>
    /// Base class for all custom managed backends for the libgit2 object database (ODB).
    /// <para>
    /// If the derived backend implements <see cref="IDisposable"/>, the <see cref="IDisposable.Dispose"/>
    /// method will be honored and invoked upon the disposal of the repository.
    /// </para>
    /// </summary>
    public abstract class OdbBackend
    {
        /// <summary>
        /// Invoked by libgit2 when this backend is no longer needed.
        /// </summary>
        internal void Free()
        {
            if (nativeBackendPointer == IntPtr.Zero)
            {
                return;
            }

            GCHandle.FromIntPtr(Marshal.ReadIntPtr(nativeBackendPointer, GitOdbBackend.GCHandleOffset)).Free();
            Marshal.FreeHGlobal(nativeBackendPointer);
            nativeBackendPointer = IntPtr.Zero;
        }

        /// <summary>
        /// In your subclass, override this member to provide the list of actions your backend supports.
        /// </summary>
        protected abstract OdbBackendOperations SupportedOperations
        {
            get;
        }

        /// <summary>
        /// Call this method from your implementations of Read and ReadPrefix to allocate a buffer in
        /// which to return the object's data.
        /// </summary>
        /// <param name="bytes">The bytes to be copied to the stream.</param>
        /// <returns>
        /// A Stream already filled with the content of provided the byte array.
        /// Do not dispose this object before returning it.
        /// </returns>
        protected UnmanagedMemoryStream AllocateAndBuildFrom(byte[] bytes)
        {
            var stream = Allocate(bytes.Length);

            stream.Write(bytes, 0, bytes.Length);

            return stream;
        }

        /// <summary>
        /// Call this method from your implementations of Read and ReadPrefix to allocate a buffer in
        /// which to return the object's data.
        /// </summary>
        /// <param name="size">Number of bytes to allocate</param>
        /// <returns>A Stream for you to write to and then return. Do not dispose this object before returning it.</returns>
        protected unsafe UnmanagedMemoryStream Allocate(long size)
        {
            if (size < 0 ||
                (UIntPtr.Size == sizeof(int) && size > int.MaxValue))
            {
                throw new ArgumentOutOfRangeException("size");
            }

            IntPtr buffer = Proxy.git_odb_backend_malloc(this.GitOdbBackendPointer, new UIntPtr((ulong)size));

            return new UnmanagedMemoryStream((byte*)buffer, 0, size, FileAccess.ReadWrite);
        }

        /// <summary>
        /// Requests that this backend read an object.
        /// </summary>
        public abstract int Read(
            ObjectId id,
            out UnmanagedMemoryStream data,
            out ObjectType objectType);

        /// <summary>
        /// Requests that this backend read an object. The object ID may not be complete (may be a prefix).
        /// </summary>
        public abstract int ReadPrefix(
            string shortSha,
            out ObjectId oid,
            out UnmanagedMemoryStream data,
            out ObjectType objectType);

        /// <summary>
        /// Requests that this backend read an object's header (length and object type) but not its contents.
        /// </summary>
        public abstract int ReadHeader(
            ObjectId id,
            out int length,
            out ObjectType objectType);

        /// <summary>
        /// Requests that this backend write an object to the backing store.
        /// </summary>
        public abstract int Write(
            ObjectId id,
            Stream dataStream,
            long length,
            ObjectType objectType);

        /// <summary>
        /// Requests that this backend read an object. Returns a stream so that the caller can read the data in chunks.
        /// </summary>
        public abstract int ReadStream(
            ObjectId id,
            out OdbBackendStream stream);

        /// <summary>
        /// Requests that this backend write an object to the backing store. Returns a stream so that the caller can write
        /// the data in chunks.
        /// </summary>
        public abstract int WriteStream(
            long length,
            ObjectType objectType,
            out OdbBackendStream stream);

        /// <summary>
        /// Requests that this backend check if an object ID exists.
        /// </summary>
        public abstract bool Exists(ObjectId id);

        /// <summary>
        /// Requests that this backend check if an object ID exists. The object ID may not be complete (may be a prefix).
        /// </summary>
        public abstract int ExistsPrefix(string shortSha, out ObjectId found);

        /// <summary>
        /// Requests that this backend enumerate all items in the backing store.
        /// </summary>
        public abstract int ForEach(ForEachCallback callback);

        /// <summary>
        /// The signature of the callback method provided to the Foreach method.
        /// </summary>
        /// <param name="oid">The object ID of the object in the backing store.</param>
        /// <returns>A non-negative result indicates the enumeration should continue. Otherwise, the enumeration should stop.</returns>
        public delegate int ForEachCallback(ObjectId oid);

        private IntPtr nativeBackendPointer;

        internal IntPtr GitOdbBackendPointer
        {
            get
            {
                if (IntPtr.Zero == nativeBackendPointer)
                {
                    var nativeBackend = new GitOdbBackend();
                    nativeBackend.Version = 1;

                    // The "free" entry point is always provided.
                    nativeBackend.Free = BackendEntryPoints.FreeCallback;

                    var supportedOperations = this.SupportedOperations;

                    if ((supportedOperations & OdbBackendOperations.Read) != 0)
                    {
                        nativeBackend.Read = BackendEntryPoints.ReadCallback;
                    }

                    if ((supportedOperations & OdbBackendOperations.ReadPrefix) != 0)
                    {
                        nativeBackend.ReadPrefix = BackendEntryPoints.ReadPrefixCallback;
                    }

                    if ((supportedOperations & OdbBackendOperations.ReadHeader) != 0)
                    {
                        nativeBackend.ReadHeader = BackendEntryPoints.ReadHeaderCallback;
                    }

                    if ((supportedOperations & OdbBackendOperations.ReadStream) != 0)
                    {
                        nativeBackend.ReadStream = BackendEntryPoints.ReadStreamCallback;
                    }

                    if ((supportedOperations & OdbBackendOperations.Write) != 0)
                    {
                        nativeBackend.Write = BackendEntryPoints.WriteCallback;
                    }

                    if ((supportedOperations & OdbBackendOperations.WriteStream) != 0)
                    {
                        nativeBackend.WriteStream = BackendEntryPoints.WriteStreamCallback;
                    }

                    if ((supportedOperations & OdbBackendOperations.Exists) != 0)
                    {
                        nativeBackend.Exists = BackendEntryPoints.ExistsCallback;
                    }

                    if ((supportedOperations & OdbBackendOperations.ExistsPrefix) != 0)
                    {
                        nativeBackend.ExistsPrefix = BackendEntryPoints.ExistsPrefixCallback;
                    }

                    if ((supportedOperations & OdbBackendOperations.ForEach) != 0)
                    {
                        nativeBackend.Foreach = BackendEntryPoints.ForEachCallback;
                    }

                    nativeBackend.GCHandle = GCHandle.ToIntPtr(GCHandle.Alloc(this));
                    nativeBackendPointer = Marshal.AllocHGlobal(Marshal.SizeOf(nativeBackend));
                    Marshal.StructureToPtr(nativeBackend, nativeBackendPointer, false);
                }

                return nativeBackendPointer;
            }
        }

        private static class BackendEntryPoints
        {
            // Because our GitOdbBackend structure exists on the managed heap only for a short time (to be marshaled
            // to native memory with StructureToPtr), we need to bind to static delegates. If at construction time
            // we were to bind to the methods directly, that's the same as newing up a fresh delegate every time.
            // Those delegates won't be rooted in the object graph and can be collected as soon as StructureToPtr finishes.
            public static readonly GitOdbBackend.read_callback ReadCallback = Read;
            public static readonly GitOdbBackend.read_prefix_callback ReadPrefixCallback = ReadPrefix;
            public static readonly GitOdbBackend.read_header_callback ReadHeaderCallback = ReadHeader;
            public static readonly GitOdbBackend.readstream_callback ReadStreamCallback = ReadStream;
            public static readonly GitOdbBackend.write_callback WriteCallback = Write;
            public static readonly GitOdbBackend.writestream_callback WriteStreamCallback = WriteStream;
            public static readonly GitOdbBackend.exists_callback ExistsCallback = Exists;
            public static readonly GitOdbBackend.exists_prefix_callback ExistsPrefixCallback = ExistsPrefix;
            public static readonly GitOdbBackend.foreach_callback ForEachCallback = Foreach;
            public static readonly GitOdbBackend.free_callback FreeCallback = Free;

            private static OdbBackend MarshalOdbBackend(IntPtr backendPtr)
            {

                var intPtr = Marshal.ReadIntPtr(backendPtr, GitOdbBackend.GCHandleOffset);
                var odbBackend = GCHandle.FromIntPtr(intPtr).Target as OdbBackend;

                if (odbBackend == null)
                {
                    Proxy.giterr_set_str(GitErrorCategory.Reference, "Cannot retrieve the managed OdbBackend.");
                    return null;
                }

                return odbBackend;
            }

            private unsafe static int Read(
                out IntPtr buffer_p,
                out UIntPtr len_p,
                out GitObjectType type_p,
                IntPtr backend,
                ref GitOid oid)
            {
                buffer_p = IntPtr.Zero;
                len_p = UIntPtr.Zero;
                type_p = GitObjectType.Bad;

                OdbBackend odbBackend = MarshalOdbBackend(backend);
                if (odbBackend == null)
                {
                    return (int)GitErrorCode.Error;
                }

                UnmanagedMemoryStream memoryStream = null;

                try
                {
                    ObjectType objectType;
                    int toReturn = odbBackend.Read(new ObjectId(oid), out memoryStream, out objectType);

                    if (toReturn != 0)
                    {
                        return toReturn;
                    }

                    if (memoryStream == null)
                    {
                        return (int)GitErrorCode.Error;
                    }

                    len_p = new UIntPtr((ulong)memoryStream.Capacity);
                    type_p = objectType.ToGitObjectType();

                    memoryStream.Seek(0, SeekOrigin.Begin);
                    buffer_p = new IntPtr(memoryStream.PositionPointer);

                }
                catch (Exception ex)
                {
                    Proxy.giterr_set_str(GitErrorCategory.Odb, ex);
                    return (int)GitErrorCode.Error;
                }
                finally
                {
                    if (memoryStream != null)
                    {
                        memoryStream.Dispose();
                    }
                }

                return (int)GitErrorCode.Ok;
            }

            private unsafe static int ReadPrefix(
                out GitOid out_oid,
                out IntPtr buffer_p,
                out UIntPtr len_p,
                out GitObjectType type_p,
                IntPtr backend,
                ref GitOid short_oid,
                UIntPtr len)
            {
                out_oid = default(GitOid);
                buffer_p = IntPtr.Zero;
                len_p = UIntPtr.Zero;
                type_p = GitObjectType.Bad;

                OdbBackend odbBackend = MarshalOdbBackend(backend);
                if (odbBackend == null)
                {
                    return (int)GitErrorCode.Error;
                }

                UnmanagedMemoryStream memoryStream = null;

                try
                {
                    var shortSha = ObjectId.ToString(short_oid.Id, (int) len);

                    ObjectId oid;
                    ObjectType objectType;

                    int toReturn = odbBackend.ReadPrefix(shortSha, out oid, out memoryStream, out objectType);

                    if (toReturn != 0)
                    {
                        return toReturn;
                    }

                    if (memoryStream == null)
                    {
                        return (int)GitErrorCode.Error;
                    }

                    out_oid.Id = oid.RawId;
                    len_p = new UIntPtr((ulong)memoryStream.Capacity);
                    type_p = objectType.ToGitObjectType();

                    memoryStream.Seek(0, SeekOrigin.Begin);
                    buffer_p = new IntPtr(memoryStream.PositionPointer);
                }
                catch (Exception ex)
                {
                    Proxy.giterr_set_str(GitErrorCategory.Odb, ex);
                    return (int)GitErrorCode.Error;
                }
                finally
                {
                    if (memoryStream != null)
                    {
                        memoryStream.Dispose();
                    }
                }

                return (int)GitErrorCode.Ok;
            }

            private static int ReadHeader(
                out UIntPtr len_p,
                out GitObjectType type_p,
                IntPtr backend,
                ref GitOid oid)
            {
                len_p = UIntPtr.Zero;
                type_p = GitObjectType.Bad;

                OdbBackend odbBackend = MarshalOdbBackend(backend);
                if (odbBackend == null)
                {
                    return (int)GitErrorCode.Error;
                }

                try
                {
                    int length;
                    ObjectType objectType;
                    int toReturn = odbBackend.ReadHeader(new ObjectId(oid), out length, out objectType);

                    if (toReturn != 0)
                    {
                        return toReturn;
                    }

                    len_p = new UIntPtr((uint)length);
                    type_p = objectType.ToGitObjectType();
                }
                catch (Exception ex)
                {
                    Proxy.giterr_set_str(GitErrorCategory.Odb, ex);
                    return (int)GitErrorCode.Error;
                }

                return (int)GitErrorCode.Ok;
            }

            private static unsafe int Write(
                IntPtr backend,
                ref GitOid oid,
                IntPtr data,
                UIntPtr len,
                GitObjectType type)
            {
                long length = ConverToLong(len);

                OdbBackend odbBackend = MarshalOdbBackend(backend);
                if (odbBackend == null)
                {
                    return (int)GitErrorCode.Error;
                }

                try
                {
                    using (var stream = new UnmanagedMemoryStream((byte*)data, length))
                    {
                        return odbBackend.Write(new ObjectId(oid), stream, length, type.ToObjectType());
                    }
                }
                catch (Exception ex)
                {
                    Proxy.giterr_set_str(GitErrorCategory.Odb, ex);
                    return (int)GitErrorCode.Error;
                }
            }

            private static int WriteStream(
                out IntPtr stream_out,
                IntPtr backend,
                long len,
                GitObjectType type)
            {
                stream_out = IntPtr.Zero;

                OdbBackend odbBackend = MarshalOdbBackend(backend);
                if (odbBackend == null)
                {
                    return (int)GitErrorCode.Error;
                }

                ObjectType objectType = type.ToObjectType();

                try
                {
                    OdbBackendStream stream;
                    int toReturn = odbBackend.WriteStream(len, objectType, out stream);

                    if (toReturn == 0)
                    {
                        stream_out = stream.GitOdbBackendStreamPointer;
                    }

                    return toReturn;
                }
                catch (Exception ex)
                {
                    Proxy.giterr_set_str(GitErrorCategory.Odb, ex);
                    return (int)GitErrorCode.Error;
                }
            }

            private static int ReadStream(
                out IntPtr stream_out,
                IntPtr backend,
                ref GitOid oid)
            {
                stream_out = IntPtr.Zero;

                OdbBackend odbBackend = MarshalOdbBackend(backend);
                if (odbBackend == null)
                {
                    return (int)GitErrorCode.Error;
                }

                try
                {
                    OdbBackendStream stream;
                    int toReturn = odbBackend.ReadStream(new ObjectId(oid), out stream);

                    if (toReturn == 0)
                    {
                        stream_out = stream.GitOdbBackendStreamPointer;
                    }

                    return toReturn;
                }
                catch (Exception ex)
                {
                    Proxy.giterr_set_str(GitErrorCategory.Odb, ex);
                    return (int)GitErrorCode.Error;
                }
            }

            private static bool Exists(
                IntPtr backend,
                ref GitOid oid)
            {
                OdbBackend odbBackend = MarshalOdbBackend(backend);
                if (odbBackend == null)
                {
                    return false; // Weird
                }

                try
                {
                    return odbBackend.Exists(new ObjectId(oid));
                }
                catch (Exception ex)
                {
                    Proxy.giterr_set_str(GitErrorCategory.Odb, ex);
                    return false;
                }
            }

            private static int ExistsPrefix(
                ref GitOid found_oid,
                IntPtr backend,
                ref GitOid short_oid,
                UIntPtr len)
            {
                OdbBackend odbBackend = MarshalOdbBackend(backend);
                if (odbBackend == null)
                {
                    return (int)GitErrorCode.Error;
                }

                try
                {
                    ObjectId found;
                    var shortSha = ObjectId.ToString(short_oid.Id, (int)len);

                    found_oid.Id = ObjectId.Zero.RawId;
                    int result = odbBackend.ExistsPrefix(shortSha, out found);

                    if (result == (int) GitErrorCode.Ok)
                    {
                        found_oid.Id = found.RawId;
                    }

                    return result;
                }
                catch (Exception ex)
                {
                    Proxy.giterr_set_str(GitErrorCategory.Odb, ex);
                    return (int)GitErrorCode.Error;
                }
            }

            private static int Foreach(
                IntPtr backend,
                GitOdbBackend.foreach_callback_callback cb,
                IntPtr data)
            {
                OdbBackend odbBackend = MarshalOdbBackend(backend);
                if (odbBackend == null)
                {
                    return (int)GitErrorCode.Error;
                }

                try
                {
                    return odbBackend.ForEach(new ForeachState(cb, data).ManagedCallback);
                }
                catch (Exception ex)
                {
                    Proxy.giterr_set_str(GitErrorCategory.Odb, ex);
                    return (int)GitErrorCode.Error;
                }
            }

            private static void Free(
                IntPtr backend)
            {
                OdbBackend odbBackend = MarshalOdbBackend(backend);
                if (odbBackend == null)
                {
                    return;
                }

                try
                {
                    odbBackend.Free();

                    var disposable = odbBackend as IDisposable;

                    if (disposable == null)
                    {
                        return;
                    }

                    disposable.Dispose();
                }
                catch (Exception ex)
                {
                    Proxy.giterr_set_str(GitErrorCategory.Odb, ex);
                }
            }

            private class ForeachState
            {
                public ForeachState(GitOdbBackend.foreach_callback_callback cb, IntPtr data)
                {
                    this.cb = cb;
                    this.data = data;
                    this.ManagedCallback = CallbackMethod;
                }

                private unsafe int CallbackMethod(ObjectId id)
                {
                    var oid = id.RawId;

                    fixed(void* ptr = &oid[0])
                    {
                        return cb(new IntPtr(ptr), data);
                    }
                }

                public readonly ForEachCallback ManagedCallback;

                private readonly GitOdbBackend.foreach_callback_callback cb;
                private readonly IntPtr data;
            }
        }

        internal static long ConverToLong(UIntPtr len)
        {
            if (len.ToUInt64() > long.MaxValue)
            {
                throw new InvalidOperationException(
                    string.Format(
                        CultureInfo.InvariantCulture,
                        "Provided length ({0}) exceeds long.MaxValue ({1}).",
                        len.ToUInt64(), long.MaxValue));
            }

            return (long)len.ToUInt64();
        }

        /// <summary>
        /// Flags used by subclasses of OdbBackend to indicate which operations they support.
        /// </summary>
        [Flags]
        protected enum OdbBackendOperations
        {
            /// <summary>
            /// This OdbBackend declares that it supports the Read method.
            /// </summary>
            Read = 1,

            /// <summary>
            /// This OdbBackend declares that it supports the ReadPrefix method.
            /// </summary>
            ReadPrefix = 2,

            /// <summary>
            /// This OdbBackend declares that it supports the ReadHeader method.
            /// </summary>
            ReadHeader = 4,

            /// <summary>
            /// This OdbBackend declares that it supports the Write method.
            /// </summary>
            Write = 8,

            /// <summary>
            /// This OdbBackend declares that it supports the ReadStream method.
            /// </summary>
            ReadStream = 16,

            /// <summary>
            /// This OdbBackend declares that it supports the WriteStream method.
            /// </summary>
            WriteStream = 32,

            /// <summary>
            /// This OdbBackend declares that it supports the Exists method.
            /// </summary>
            Exists = 64,

            /// <summary>
            /// This OdbBackend declares that it supports the ExistsPrefix method.
            /// </summary>
            ExistsPrefix = 128,

            /// <summary>
            /// This OdbBackend declares that it supports the Foreach method.
            /// </summary>
            ForEach = 256,
        }

        /// <summary>
        /// Libgit2 expected backend return codes.
        /// </summary>
        protected enum ReturnCode
        {
            /// <summary>
            /// No error has occured.
            /// </summary>
            GIT_OK = 0,

            /// <summary>
            /// No object matching the oid, or short oid, can be found in the backend.
            /// </summary>
            GIT_ENOTFOUND = -3,

            /// <summary>
            /// The given short oid is ambiguous.
            /// </summary>
            GIT_EAMBIGUOUS = -5,

            /// <summary>
            /// Interruption of the foreach() callback is requested.
            /// </summary>
            GIT_EUSER = -7,
        }
    }
}