Exemplo n.º 1
0
        private int LineCallback(GitDiffDelta delta, GitDiffHunk hunk, GitDiffLine line, IntPtr payload)
        {
            string decodedContent = LaxUtf8Marshaler.FromNative(line.content, (int)line.contentLen);

            string prefix;

            switch (line.lineOrigin)
            {
            case GitDiffLineOrigin.GIT_DIFF_LINE_ADDITION:
                LinesAdded++;
                prefix = Encoding.ASCII.GetString(new[] { (byte)line.lineOrigin });
                break;

            case GitDiffLineOrigin.GIT_DIFF_LINE_DELETION:
                LinesDeleted++;
                prefix = Encoding.ASCII.GetString(new[] { (byte)line.lineOrigin });
                break;

            case GitDiffLineOrigin.GIT_DIFF_LINE_CONTEXT:
                prefix = Encoding.ASCII.GetString(new[] { (byte)line.lineOrigin });
                break;

            default:
                prefix = string.Empty;
                break;
            }

            AppendToPatch(prefix);
            AppendToPatch(decodedContent);
            return(0);
        }
Exemplo n.º 2
0
        internal unsafe BlameHunk(IRepository repository, git_blame_hunk *rawHunk)
        {
            var origId  = ObjectId.BuildFromPtr(&rawHunk->orig_commit_id);
            var finalId = ObjectId.BuildFromPtr(&rawHunk->final_commit_id);

            finalCommit = new Lazy <Commit>(() => repository.Lookup <Commit>(finalId));
            origCommit  = new Lazy <Commit>(() => repository.Lookup <Commit>(origId));


            if (rawHunk->orig_path != null)
            {
                InitialPath = LaxUtf8Marshaler.FromNative(rawHunk->orig_path);
            }

            LineCount = (int)rawHunk->lines_in_hunk.ToUInt32();

            // Libgit2's line numbers are 1-based
            FinalStartLineNumber   = (int)rawHunk->final_start_line_number.ToUInt32() - 1;
            InitialStartLineNumber = (int)rawHunk->orig_start_line_number.ToUInt32() - 1;

            // Signature objects need to have ownership of their native pointers
            if (rawHunk->final_signature != null)
            {
                FinalSignature = new Signature(rawHunk->final_signature);
            }

            if (rawHunk->orig_signature != null)
            {
                InitialSignature = new Signature(rawHunk->orig_signature);
            }
        }
Exemplo n.º 3
0
            public int Callback(IntPtr referenceNamePtr, IntPtr msgPtr, IntPtr payload)
            {
                // Exit early if there is no callback.
                if (onError == null)
                {
                    return(0);
                }

                // The reference name pointer should never be null - if it is,
                // this indicates a bug somewhere (libgit2, server, etc).
                if (referenceNamePtr == IntPtr.Zero)
                {
                    Proxy.giterr_set_str(GitErrorCategory.Invalid, "Not expecting null for reference name in push status.");
                    return(-1);
                }

                // Only report updates where there is a message - indicating
                // that there was an error.
                if (msgPtr != IntPtr.Zero)
                {
                    string referenceName = LaxUtf8Marshaler.FromNative(referenceNamePtr);
                    string msg           = LaxUtf8Marshaler.FromNative(msgPtr);
                    onError(new PushStatusError(referenceName, msg));
                }

                return(0);
            }
Exemplo n.º 4
0
        private unsafe int GitCertificateCheck(git_certificate *certPtr, int valid, IntPtr cHostname, IntPtr payload)
        {
            string      hostname = LaxUtf8Marshaler.FromNative(cHostname);
            Certificate cert     = null;

            switch (certPtr->type)
            {
            case GitCertificateType.X509:
                cert = new CertificateX509((git_certificate_x509 *)certPtr);
                break;

            case GitCertificateType.Hostkey:
                cert = new CertificateSsh((git_certificate_ssh *)certPtr);
                break;
            }

            bool result = false;

            try
            {
                result = CertificateCheck(cert, valid != 0, hostname);
            }
            catch (Exception exception)
            {
                Proxy.giterr_set_str(GitErrorCategory.Callback, exception);
            }

            return(Proxy.ConvertResultToCancelFlag(result));
        }
Exemplo n.º 5
0
 internal unsafe PushUpdate(git_push_update *update)
 {
     DestinationObjectId = ObjectId.BuildFromPtr(&update->dst);
     DestinationRefName  = LaxUtf8Marshaler.FromNative(update->dst_refname);
     SourceObjectId      = ObjectId.BuildFromPtr(&update->src);
     SourceRefName       = LaxUtf8Marshaler.FromNative(update->src_refname);
 }
Exemplo n.º 6
0
        private int GitCredentialHandler(
            out IntPtr ptr,
            IntPtr cUrl,
            IntPtr usernameFromUrl,
            GitCredentialType credTypes,
            IntPtr payload)
        {
            string url      = LaxUtf8Marshaler.FromNative(cUrl);
            string username = LaxUtf8Marshaler.FromNative(usernameFromUrl);

            SupportedCredentialTypes types = default(SupportedCredentialTypes);

            if (credTypes.HasFlag(GitCredentialType.UserPassPlaintext))
            {
                types |= SupportedCredentialTypes.UsernamePassword;
            }
            if (credTypes.HasFlag(GitCredentialType.Default))
            {
                types |= SupportedCredentialTypes.Default;
            }

            var cred = CredentialsProvider(url, username, types);

            return(cred.GitCredentialHandler(out ptr));
        }
Exemplo n.º 7
0
 internal PushUpdate(GitPushUpdate update)
 {
     DestinationObjectId = update.dst;
     DestinationRefName  = LaxUtf8Marshaler.FromNative(update.dst_refname);
     SourceObjectId      = update.src;
     SourceRefName       = LaxUtf8Marshaler.FromNative(update.src_refname);
 }
Exemplo n.º 8
0
        private int HunkCallback(GitDiffDelta delta, GitDiffHunk hunk, IntPtr payload)
        {
            string decodedContent = LaxUtf8Marshaler.FromBuffer(hunk.Header, (int)hunk.HeaderLen);

            AppendToPatch(decodedContent);
            return(0);
        }
Exemplo n.º 9
0
        internal BlameHunk(IRepository repository, GitBlameHunk rawHunk)
        {
            finalCommit = new Lazy <Commit>(() => repository.Lookup <Commit>(rawHunk.FinalCommitId));
            origCommit  = new Lazy <Commit>(() => repository.Lookup <Commit>(rawHunk.OrigCommitId));

            if (rawHunk.OrigPath != IntPtr.Zero)
            {
                InitialPath = LaxUtf8Marshaler.FromNative(rawHunk.OrigPath);
            }
            LineCount = rawHunk.LinesInHunk.ConvertToInt();

            // Libgit2's line numbers are 1-based
            FinalStartLineNumber   = rawHunk.FinalStartLineNumber.ConvertToInt() - 1;
            InitialStartLineNumber = rawHunk.OrigStartLineNumber.ConvertToInt() - 1;

            // Signature objects need to have ownership of their native pointers
            if (rawHunk.FinalSignature != IntPtr.Zero)
            {
                FinalSignature = new Signature(Proxy.git_signature_dup(rawHunk.FinalSignature));
            }

            if (rawHunk.OrigSignature != IntPtr.Zero)
            {
                InitialSignature = new Signature(Proxy.git_signature_dup(rawHunk.OrigSignature));
            }
        }
Exemplo n.º 10
0
            private static int Action(
                out IntPtr stream,
                IntPtr subtransport,
                IntPtr url,
                GitSmartSubtransportAction action)
            {
                stream = IntPtr.Zero;

                SmartSubtransport t           = GCHandle.FromIntPtr(Marshal.ReadIntPtr(subtransport, GitSmartSubtransport.GCHandleOffset)).Target as SmartSubtransport;
                String            urlAsString = LaxUtf8Marshaler.FromNative(url);

                if (null != t &&
                    !String.IsNullOrEmpty(urlAsString))
                {
                    try
                    {
                        stream = t.Action(urlAsString, action).GitSmartTransportStreamPointer;

                        return(0);
                    }
                    catch (Exception ex)
                    {
                        Proxy.git_error_set_str(GitErrorCategory.Net, ex);
                    }
                }

                return((int)GitErrorCode.Error);
            }
 static internal UsernamePasswordCredentials FromNative(GitCredentialUserpass gitCred)
 {
     return(new UsernamePasswordCredentials()
     {
         Username = LaxUtf8Marshaler.FromNative(gitCred.username),
         Password = LaxUtf8Marshaler.FromNative(gitCred.password),
     });
 }
Exemplo n.º 12
0
        internal Signature(IntPtr signaturePtr)
        {
            var handle = signaturePtr.MarshalAs <GitSignature>();

            name  = LaxUtf8Marshaler.FromNative(handle.Name);
            email = LaxUtf8Marshaler.FromNative(handle.Email);
            when  = Epoch.ToDateTimeOffset(handle.When.Time, handle.When.Offset);
        }
Exemplo n.º 13
0
        internal static unsafe ConfigurationEntry <string> BuildConfigEntry(IntPtr entryPtr)
        {
            var entry = (GitConfigEntry *)entryPtr.ToPointer();

            return(new ConfigurationEntry <string>(LaxUtf8Marshaler.FromNative(entry->namePtr),
                                                   LaxUtf8Marshaler.FromNative(entry->valuePtr),
                                                   (ConfigurationLevel)entry->level));
        }
Exemplo n.º 14
0
        private static ConfigurationEntry <string> BuildConfigEntry(IntPtr entryPtr)
        {
            var entry = entryPtr.MarshalAs <GitConfigEntry>();

            return(new ConfigurationEntry <string>(LaxUtf8Marshaler.FromNative(entry.namePtr),
                                                   LaxUtf8Marshaler.FromNative(entry.valuePtr),
                                                   (ConfigurationLevel)entry.level));
        }
Exemplo n.º 15
0
        /// <summary>
        /// Handler for libgit2 update_tips callback. Converts values
        /// received from libgit2 callback to more suitable types
        /// and calls delegate provided by LibGit2Sharp consumer.
        /// </summary>
        /// <param name="str">IntPtr to string</param>
        /// <param name="oldId">Old reference ID</param>
        /// <param name="newId">New referene ID</param>
        /// <param name="data">IntPtr to optional payload passed back to the callback.</param>
        /// <returns>0 on success; a negative value to abort the process.</returns>
        private int GitUpdateTipsHandler(IntPtr str, ref GitOid oldId, ref GitOid newId, IntPtr data)
        {
            UpdateTipsHandler onUpdateTips = UpdateTips;
            bool shouldContinue            = true;

            if (onUpdateTips != null)
            {
                string refName = LaxUtf8Marshaler.FromNative(str);
                shouldContinue = onUpdateTips(refName, oldId, newId);
            }

            return(Proxy.ConvertResultToCancelFlag(shouldContinue));
        }
Exemplo n.º 16
0
        internal unsafe TreeEntryChanges(git_diff_delta *delta)
        {
            Path    = LaxUtf8Marshaler.FromNative(delta->new_file.Path);
            OldPath = LaxUtf8Marshaler.FromNative(delta->old_file.Path);

            Mode      = (Mode)delta->new_file.Mode;
            OldMode   = (Mode)delta->old_file.Mode;
            Oid       = ObjectId.BuildFromPtr(&delta->new_file.Id);
            OldOid    = ObjectId.BuildFromPtr(&delta->old_file.Id);
            Exists    = (delta->new_file.Flags & GitDiffFlags.GIT_DIFF_FLAG_EXISTS) != 0;
            OldExists = (delta->old_file.Flags & GitDiffFlags.GIT_DIFF_FLAG_EXISTS) != 0;

            Status = GetStatusFromChangeKind(delta->status);
        }
Exemplo n.º 17
0
        /// <summary>
        /// Handler for libgit2 Progress callback. Converts values
        /// received from libgit2 callback to more suitable types
        /// and calls delegate provided by LibGit2Sharp consumer.
        /// </summary>
        /// <param name="str">IntPtr to string from libgit2</param>
        /// <param name="len">length of string</param>
        /// <param name="data">IntPtr to optional payload passed back to the callback.</param>
        /// <returns>0 on success; a negative value to abort the process.</returns>
        private int GitProgressHandler(IntPtr str, int len, IntPtr data)
        {
            ProgressHandler onProgress = Progress;

            bool shouldContinue = true;

            if (onProgress != null)
            {
                string message = LaxUtf8Marshaler.FromNative(str, len);
                shouldContinue = onProgress(message);
            }

            return(Proxy.ConvertResultToCancelFlag(shouldContinue));
        }
Exemplo n.º 18
0
        /// <summary>
        /// The delegate with the signature that matches the native push_update_reference function's signature
        /// </summary>
        /// <param name="str">IntPtr to string, the name of the reference</param>
        /// <param name="status">IntPtr to string, the update status message</param>
        /// <param name="data">IntPtr to optional payload passed back to the callback.</param>
        /// <returns>0 on success; a negative value to abort the process.</returns>
        private int GitPushUpdateReference(IntPtr str, IntPtr status, IntPtr data)
        {
            PushStatusErrorHandler onPushError = PushStatusError;

            if (onPushError != null)
            {
                string reference = LaxUtf8Marshaler.FromNative(str);
                string message   = LaxUtf8Marshaler.FromNative(status);
                if (message != null)
                {
                    onPushError(new PushStatusError(reference, message));
                }
            }

            return(Proxy.ConvertResultToCancelFlag(true));
        }
Exemplo n.º 19
0
        private unsafe void AddStatusEntryForDelta(FileStatus gitStatus, git_diff_delta *deltaHeadToIndex, git_diff_delta *deltaIndexToWorkDir)
        {
            RenameDetails headToIndexRenameDetails    = null;
            RenameDetails indexToWorkDirRenameDetails = null;

            if ((gitStatus & FileStatus.RenamedInIndex) == FileStatus.RenamedInIndex)
            {
                headToIndexRenameDetails =
                    new RenameDetails(LaxUtf8Marshaler.FromNative(deltaHeadToIndex->old_file.Path),
                                      LaxUtf8Marshaler.FromNative(deltaHeadToIndex->new_file.Path),
                                      (int)deltaHeadToIndex->similarity);
            }

            if ((gitStatus & FileStatus.RenamedInWorkdir) == FileStatus.RenamedInWorkdir)
            {
                indexToWorkDirRenameDetails =
                    new RenameDetails(LaxUtf8Marshaler.FromNative(deltaIndexToWorkDir->old_file.Path),
                                      LaxUtf8Marshaler.FromNative(deltaIndexToWorkDir->new_file.Path),
                                      (int)deltaIndexToWorkDir->similarity);
            }

            var filePath = LaxUtf8Marshaler.FromNative(deltaIndexToWorkDir != null ?
                                                       deltaIndexToWorkDir->new_file.Path :
                                                       deltaHeadToIndex->new_file.Path);

            StatusEntry statusEntry = new StatusEntry(filePath, gitStatus, headToIndexRenameDetails, indexToWorkDirRenameDetails);

            if (gitStatus == FileStatus.Unaltered)
            {
                unaltered.Add(statusEntry);
            }
            else
            {
                foreach (KeyValuePair <FileStatus, Action <RepositoryStatus, StatusEntry> > kvp in dispatcher)
                {
                    if (!gitStatus.HasFlag(kvp.Key))
                    {
                        continue;
                    }

                    kvp.Value(this, statusEntry);
                }
            }

            statusEntries.Add(statusEntry);
        }
Exemplo n.º 20
0
        private int GitCredentialHandler(
            out IntPtr ptr,
            IntPtr cUrl,
            IntPtr usernameFromUrl,
            GitCredentialType credTypes,
            IntPtr payload)
        {
            string url      = LaxUtf8Marshaler.FromNative(cUrl);
            string username = LaxUtf8Marshaler.FromNative(usernameFromUrl);

            SupportedCredentialTypes types = default(SupportedCredentialTypes);

            if (credTypes.HasFlag(GitCredentialType.UserPassPlaintext))
            {
                types |= SupportedCredentialTypes.UsernamePassword;
            }
            if (credTypes.HasFlag(GitCredentialType.Default))
            {
                types |= SupportedCredentialTypes.Default;
            }
            if (credTypes.HasFlag(GitCredentialType.SshKey))
            {
                types |= SupportedCredentialTypes.Ssh;
            }
            if (credTypes.HasFlag(GitCredentialType.Username))
            {
                types |= SupportedCredentialTypes.UsernameQuery;
            }

            ptr = IntPtr.Zero;
            try
            {
                var cred = CredentialsProvider(url, username, types);
                if (cred == null)
                {
                    return((int)GitErrorCode.PassThrough);
                }
                return(cred.GitCredentialHandler(out ptr));
            }
            catch (Exception exception)
            {
                Proxy.giterr_set_str(GitErrorCategory.Callback, exception);
                return((int)GitErrorCode.Error);
            }
        }
Exemplo n.º 21
0
        internal static unsafe IndexEntry BuildFromPtr(git_index_entry *entry)
        {
            if (entry == null)
            {
                return(null);
            }

            string path = LaxUtf8Marshaler.FromNative(entry->path);

            return(new IndexEntry
            {
                Path = path,
                Id = new ObjectId(entry->id.Id),
                StageLevel = Proxy.git_index_entry_stage(entry),
                Mode = (Mode)entry->mode,
                AssumeUnchanged = (git_index_entry.GIT_IDXENTRY_VALID & entry->flags) == git_index_entry.GIT_IDXENTRY_VALID
            });
        }
Exemplo n.º 22
0
        private unsafe int PrintCallBack(git_diff_delta *delta, GitDiffHunk hunk, GitDiffLine line, IntPtr payload)
        {
            string patchPart = LaxUtf8Marshaler.FromNative(line.content, (int)line.contentLen);

            // Deleted files mean no "new file" path

            var pathPtr = delta->new_file.Path != null
                ? delta->new_file.Path
                : delta->old_file.Path;
            var filePath = LaxFilePathMarshaler.FromNative(pathPtr);

            PatchEntryChanges currentChange = this[filePath];
            string            prefix        = string.Empty;

            switch (line.lineOrigin)
            {
            case GitDiffLineOrigin.GIT_DIFF_LINE_CONTEXT:
                prefix = " ";
                break;

            case GitDiffLineOrigin.GIT_DIFF_LINE_ADDITION:
                linesAdded++;
                currentChange.LinesAdded++;
                currentChange.AddedLines.Add(new Line(line.NewLineNo, patchPart));
                prefix = "+";
                break;

            case GitDiffLineOrigin.GIT_DIFF_LINE_DELETION:
                linesDeleted++;
                currentChange.LinesDeleted++;
                currentChange.DeletedLines.Add(new Line(line.OldLineNo, patchPart));
                prefix = "-";
                break;
            }

            string formattedOutput = string.Concat(prefix, patchPart);

            fullPatchBuilder.Append(formattedOutput);
            currentChange.AppendToPatch(formattedOutput);

            return(0);
        }
Exemplo n.º 23
0
        internal static unsafe IndexReucEntry BuildFromPtr(git_index_reuc_entry *entry)
        {
            if (entry == null)
            {
                return(null);
            }

            FilePath path = LaxUtf8Marshaler.FromNative(entry->Path);

            return(new IndexReucEntry
            {
                Path = path.Native,
                AncestorId = ObjectId.BuildFromPtr(&entry->AncestorId),
                AncestorMode = (Mode)entry->AncestorMode,
                OurId = ObjectId.BuildFromPtr(&entry->OurId),
                OurMode = (Mode)entry->OurMode,
                TheirId = ObjectId.BuildFromPtr(&entry->TheirId),
                TheirMode = (Mode)entry->TheirMode,
            });
        }
Exemplo n.º 24
0
        /// <summary>
        /// Get info on the specified step
        /// </summary>
        /// <param name="stepIndex"></param>
        /// <returns></returns>
        public virtual unsafe RebaseStepInfo GetStepInfo(long stepIndex)
        {
            if (repository.Info.CurrentOperation != LibGit2Sharp.CurrentOperation.RebaseMerge)
            {
                return(null);
            }

            GitRebaseOptions gitRebaseOptions = new GitRebaseOptions()
            {
                version = 1,
            };

            using (RebaseHandle rebaseHandle = Proxy.git_rebase_open(repository.Handle, gitRebaseOptions))
            {
                git_rebase_operation *gitRebasestepInfo = Proxy.git_rebase_operation_byindex(rebaseHandle, stepIndex);
                var stepInfo = new RebaseStepInfo(gitRebasestepInfo->type,
                                                  repository.Lookup <Commit>(ObjectId.BuildFromPtr(&gitRebasestepInfo->id)),
                                                  LaxUtf8Marshaler.FromNative(gitRebasestepInfo->exec));
                return(stepInfo);
            }
        }
            private static int Action(
                out IntPtr stream,
                IntPtr subtransport,
                IntPtr url,
                GitSmartSubtransportAction action)
            {
                stream = IntPtr.Zero;

                SmartSubtransport t = GCHandle.FromIntPtr(Marshal.ReadIntPtr(subtransport, GitSmartSubtransport.GCHandleOffset)).Target as SmartSubtransport;
                String urlAsString = LaxUtf8Marshaler.FromNative(url);

                if (t == null)
                {
                    Proxy.git_error_set_str(GitErrorCategory.Net, "no subtransport provided");
                    return (int)GitErrorCode.Error;
                }

                if (String.IsNullOrEmpty(urlAsString))
                {
                    urlAsString = t.LastActionUrl;
                }

                if (String.IsNullOrEmpty(urlAsString))
                {
                    Proxy.git_error_set_str(GitErrorCategory.Net, "no url provided");
                    return (int)GitErrorCode.Error;
                }

                try
                {
                    stream = t.Action(urlAsString, action).GitSmartTransportStreamPointer;
                    t.LastActionUrl = urlAsString;
                    return 0;
                }
                catch (Exception ex)
                {
                    Proxy.git_error_set_str(GitErrorCategory.Net, ex);
                    return (int)GitErrorCode.Error;
                }
            }
Exemplo n.º 26
0
        /// <summary>
        /// The info on the current step.
        /// </summary>
        public virtual RebaseStepInfo GetCurrentStepInfo()
        {
            if (repository.Info.CurrentOperation != LibGit2Sharp.CurrentOperation.RebaseMerge)
            {
                return(null);
            }

            GitRebaseOptions gitRebaseOptions = new GitRebaseOptions()
            {
                version = 1,
            };

            using (RebaseSafeHandle rebaseHandle = Proxy.git_rebase_open(repository.Handle, gitRebaseOptions))
            {
                long currentStepIndex = Proxy.git_rebase_operation_current(rebaseHandle);
                GitRebaseOperation gitRebasestepInfo = Proxy.git_rebase_operation_byindex(rebaseHandle, currentStepIndex);
                var stepInfo = new RebaseStepInfo(gitRebasestepInfo.type,
                                                  repository.Lookup <Commit>(new ObjectId(gitRebasestepInfo.id)),
                                                  LaxUtf8Marshaler.FromNative(gitRebasestepInfo.exec));
                return(stepInfo);
            }
        }
Exemplo n.º 27
0
 /// <summary>
 /// Returns an enumerator that iterates through the collection.
 /// </summary>
 /// <returns>An <see cref="IEnumerator{T}"/> object that can be used to iterate through the collection.</returns>
 public virtual IEnumerator <Submodule> GetEnumerator()
 {
     return(Proxy.git_submodule_foreach(repo.Handle, (h, n) => LaxUtf8Marshaler.FromNative(n))
            .Select(n => this[n])
            .GetEnumerator());
 }
Exemplo n.º 28
0
 internal unsafe Signature(git_signature *sig)
 {
     name  = LaxUtf8Marshaler.FromNative(sig->name);
     email = LaxUtf8Marshaler.FromNative(sig->email);
     when  = Epoch.ToDateTimeOffset(sig->when.time, sig->when.offset);
 }
Exemplo n.º 29
0
 internal unsafe Signature(git_signature *sig)
 {
     name  = LaxUtf8Marshaler.FromNative(sig->name);
     email = LaxUtf8Marshaler.FromNative(sig->email);
     when  = DateTimeOffset.FromUnixTimeSeconds(sig->when.time).ToOffset(TimeSpan.FromMinutes(sig->when.offset));
 }
Exemplo n.º 30
0
        /// <summary>
        /// This private method will be called from LibGit2 (from C code via
        /// the GitTraceCallback delegate) to route LibGit2 log messages to
        /// the same LogHandler as Simula.Scripting.Git messages.
        /// </summary>
        private void GitTraceHandler(LogLevel level, IntPtr msg)
        {
            string message = LaxUtf8Marshaler.FromNative(msg);

            Handler(level, message);
        }