text:
# This file is a part of Julia. License is MIT: https://julialang.org/license

import Base.@kwdef
import .Consts: GIT_SUBMODULE_IGNORE, GIT_MERGE_FILE_FAVOR, GIT_MERGE_FILE, GIT_CONFIG

const OID_RAWSZ = 20
const OID_HEXSZ = OID_RAWSZ * 2
const OID_MINPREFIXLEN = 4

abstract type AbstractGitHash end

"""
    GitHash

A git object identifier, based on the sha-1 hash. It is a $OID_RAWSZ byte string
($OID_HEXSZ hex digits) used to identify a `GitObject` in a repository.
"""
struct GitHash <: AbstractGitHash
    val::NTuple{OID_RAWSZ, UInt8}
    GitHash(val::NTuple{OID_RAWSZ, UInt8}) = new(val)
end
GitHash() = GitHash(ntuple(i->zero(UInt8), OID_RAWSZ))

"""
    GitShortHash(hash::GitHash, len::Integer)

A shortened git object identifier, which can be used to identify a git object when it is
unique, consisting of the initial `len` hexadecimal digits of `hash` (the remaining digits
are ignored).
"""
struct GitShortHash <: AbstractGitHash
    hash::GitHash   # underlying hash: unused digits are ignored
    len::Csize_t    # length in hex digits
end

"""
    LibGit2.TimeStruct

Time in a signature.
Matches the [`git_time`](https://libgit2.github.com/libgit2/#HEAD/type/git_time) struct.
"""
struct TimeStruct
    time::Int64     # time in seconds from epoch
    offset::Cint    # timezone offset in minutes
end

"""
    LibGit2.SignatureStruct

An action signature (e.g. for committers, taggers, etc).
Matches the [`git_signature`](https://libgit2.github.com/libgit2/#HEAD/type/git_signature) struct.

The fields represent:
  * `name`: The full name of the committer or author of the commit.
  * `email`: The email at which the committer/author can be contacted.
  * `when`: a [`TimeStruct`](@ref) indicating when the commit was
     authored/committed into the repository.
"""
struct SignatureStruct
    name::Ptr{UInt8}  # full name of the author
    email::Ptr{UInt8} # email of the author
    when::TimeStruct  # time when the action happened
end

"""
    LibGit2.StrArrayStruct

A LibGit2 representation of an array of strings.
Matches the [`git_strarray`](https://libgit2.github.com/libgit2/#HEAD/type/git_strarray) struct.

When fetching data from LibGit2, a typical usage would look like:
```julia
sa_ref = Ref(StrArrayStruct())
@check ccall(..., (Ptr{StrArrayStruct},), sa_ref)
res = convert(Vector{String}, sa_ref[])
free(sa_ref)
```
In particular, note that `LibGit2.free` should be called afterward on the `Ref` object.

Conversely, when passing a vector of strings to LibGit2, it is generally simplest to rely
on implicit conversion:
```julia
strs = String[...]
@check ccall(..., (Ptr{StrArrayStruct},), strs)
```
Note that no call to `free` is required as the data is allocated by Julia.
"""
struct StrArrayStruct
   strings::Ptr{Cstring}
   count::Csize_t
end
StrArrayStruct() = StrArrayStruct(C_NULL, 0)

function free(sa_ref::Base.Ref{StrArrayStruct})
    ccall((:git_strarray_free, :libgit2), Void, (Ptr{StrArrayStruct},), sa_ref)
end

"""
    LibGit2.Buffer

A data buffer for exporting data from libgit2.
Matches the [`git_buf`](https://libgit2.github.com/libgit2/#HEAD/type/git_buf) struct.

When fetching data from LibGit2, a typical usage would look like:
```julia
buf_ref = Ref(Buffer())
@check ccall(..., (Ptr{Buffer},), buf_ref)
# operation on buf_ref
free(buf_ref)
```
In particular, note that `LibGit2.free` should be called afterward on the `Ref` object.
"""
struct Buffer
    ptr::Ptr{Cchar}
    asize::Csize_t
    size::Csize_t
end
Buffer() = Buffer(C_NULL, 0, 0)

function free(buf_ref::Base.Ref{Buffer})
    ccall((:git_buf_free, :libgit2), Void, (Ptr{Buffer},), buf_ref)
end

"""
    LibGit2.CheckoutOptions

Matches the [`git_checkout_options`](https://libgit2.github.com/libgit2/#HEAD/type/git_checkout_options) struct.

The fields represent:
  * `version`: version of the struct in use, in case this changes later. For now, always `1`.
  * `checkout_strategy`: determine how to handle conflicts and whether to force the
     checkout/recreate missing files.
  * `disable_filters`: if nonzero, do not apply filters like CLRF (to convert file newlines between UNIX and DOS).
  * `dir_mode`: read/write/access mode for any directories involved in the checkout. Default is `0755`.
  * `file_mode`: read/write/access mode for any files involved in the checkout.
     Default is `0755` or `0644`, depending on the blob.
  * `file_open_flags`: bitflags used to open any files during the checkout.
  * `notify_flags`: Flags for what sort of conflicts the user should be notified about.
  * `notify_cb`: An optional callback function to notify the user if a checkout conflict occurs.
     If this function returns a non-zero value, the checkout will be cancelled.
  * `notify_payload`: Payload for the notify callback function.
  * `progress_cb`: An optional callback function to display checkout progress.
  * `progress_payload`: Payload for the progress callback.
  * `paths`: If not empty, describes which paths to search during the checkout.
     If empty, the checkout will occur over all files in the repository.
  * `baseline`: Expected content of the [`workdir`](@ref), captured in a (pointer to a)
     [`GitTree`](@ref). Defaults to the state of the tree at HEAD.
  * `baseline_index`: Expected content of the [`workdir`](@ref), captured in a (pointer to a)
     `GitIndex`. Defaults to the state of the index at HEAD.
  * `target_directory`: If not empty, checkout to this directory instead of the `workdir`.
  * `ancestor_label`: In case of conflicts, the name of the common ancestor side.
  * `our_label`: In case of conflicts, the name of "our" side.
  * `their_label`: In case of conflicts, the name of "their" side.
  * `perfdata_cb`: An optional callback function to display performance data.
  * `perfdata_payload`: Payload for the performance callback.
"""
@kwdef struct CheckoutOptions
    version::Cuint = 1

    checkout_strategy::Cuint    = Consts.CHECKOUT_SAFE

    disable_filters::Cint
    dir_mode::Cuint
    file_mode::Cuint
    file_open_flags::Cint

    notify_flags::Cuint         = Consts.CHECKOUT_NOTIFY_NONE
    notify_cb::Ptr{Void}
    notify_payload::Ptr{Void}

    progress_cb::Ptr{Void}
    progress_payload::Ptr{Void}

    paths::StrArrayStruct

    baseline::Ptr{Void}
    baseline_index::Ptr{Void}

    target_directory::Cstring
    ancestor_label::Cstring
    our_label::Cstring
    their_label::Cstring

    perfdata_cb::Ptr{Void}
    perfdata_payload::Ptr{Void}
end

abstract type Payload end

@kwdef struct RemoteCallbacksStruct
    version::Cuint                    = 1
    sideband_progress::Ptr{Void}
    completion::Ptr{Void}
    credentials::Ptr{Void}
    certificate_check::Ptr{Void}
    transfer_progress::Ptr{Void}
    update_tips::Ptr{Void}
    pack_progress::Ptr{Void}
    push_transfer_progress::Ptr{Void}
    push_update_reference::Ptr{Void}
    push_negotiation::Ptr{Void}
    transport::Ptr{Void}
    payload::Ptr{Void}
end

"""
    LibGit2.RemoteCallbacks

Callback settings.
Matches the [`git_remote_callbacks`](https://libgit2.github.com/libgit2/#HEAD/type/git_remote_callbacks) struct.
"""
struct RemoteCallbacks
    cb::RemoteCallbacksStruct
    gcroot::Ref{Any}
    function RemoteCallbacks(; payload::Union{Payload, Void}=nothing, kwargs...)
        p = Ref{Any}(payload)
        if payload === nothing
            pp = C_NULL
        else
            pp = unsafe_load(Ptr{Ptr{Void}}(Base.unsafe_convert(Ptr{Any}, p)))
        end
        return new(RemoteCallbacksStruct(; kwargs..., payload=pp), p)
    end
end

"""
    LibGit2.ProxyOptions

Options for connecting through a proxy.

Matches the [`git_proxy_options`](https://libgit2.github.com/libgit2/#HEAD/type/git_proxy_options) struct.

The fields represent:
  * `version`: version of the struct in use, in case this changes later. For now, always `1`.
  * `proxytype`: an `enum` for the type of proxy to use.
     Defined in [`git_proxy_t`](https://libgit2.github.com/libgit2/#HEAD/type/git_proxy_t).
     The corresponding Julia enum is `GIT_PROXY` and has values:
     - `PROXY_NONE`: do not attempt the connection through a proxy.
     - `PROXY_AUTO`: attempt to figure out the proxy configuration from the git configuration.
     - `PROXY_SPECIFIED`: connect using the URL given in the `url` field of this struct.
     Default is to auto-detect the proxy type.
  * `url`: the URL of the proxy.
  * `credential_cb`: a pointer to a callback function which will be called if the remote
    requires authentication to connect.
  * `certificate_cb`: a pointer to a callback function which will be called if certificate
    verification fails. This lets the user decide whether or not to keep connecting. If
    the function returns `1`, connecting will be allowed. If it returns `0`, the connection
    will not be allowed. A negative value can be used to return errors.
  * `payload`: the payload to be provided to the two callback functions.

# Examples
```julia-repl
julia> fo = LibGit2.FetchOptions(
           proxy_opts = LibGit2.ProxyOptions(url = Cstring("https://my_proxy_url.com")))

julia> fetch(remote, "master", options=fo)
```
"""
@kwdef struct ProxyOptions
    version::Cuint               = 1
    proxytype::Consts.GIT_PROXY  = Consts.PROXY_AUTO
    url::Cstring
    credential_cb::Ptr{Void}
    certificate_cb::Ptr{Void}
    payload::Ptr{Void}
end

@kwdef struct FetchOptionsStruct
    version::Cuint                  = 1
    callbacks::RemoteCallbacksStruct
    prune::Cint                     = Consts.FETCH_PRUNE_UNSPECIFIED
    update_fetchhead::Cint          = 1
    download_tags::Cint             = Consts.REMOTE_DOWNLOAD_TAGS_AUTO
    @static if LibGit2.VERSION >= v"0.25.0"
        proxy_opts::ProxyOptions
    end
    @static if LibGit2.VERSION >= v"0.24.0"
        custom_headers::StrArrayStruct
    end
end

"""
    LibGit2.FetchOptions

Matches the [`git_fetch_options`](https://libgit2.github.com/libgit2/#HEAD/type/git_fetch_options) struct.

The fields represent:
  * `version`: version of the struct in use, in case this changes later. For now, always `1`.
  * `callbacks`: remote callbacks to use during the fetch.
  * `prune`: whether to perform a prune after the fetch or not. The default is to
     use the setting from the `GitConfig`.
  * `update_fetchhead`: whether to update the [`FetchHead`](@ref) after the fetch.
     The default is to perform the update, which is the normal git behavior.
  * `download_tags`: whether to download tags present at the remote or not. The default
     is to request the tags for objects which are being downloaded anyway from the server.
  * `proxy_opts`: options for connecting to the remote through a proxy. See [`ProxyOptions`](@ref).
     Only present on libgit2 versions newer than or equal to 0.25.0.
  * `custom_headers`: any extra headers needed for the fetch. Only present on libgit2 versions
     newer than or equal to 0.24.0.
"""
struct FetchOptions
    opts::FetchOptionsStruct
    cb_gcroot::Ref{Any}
    function FetchOptions(; callbacks::RemoteCallbacks=RemoteCallbacks(), kwargs...)
        return new(FetchOptionsStruct(; kwargs..., callbacks=callbacks.cb), callbacks.gcroot)
    end
end

@kwdef struct CloneOptionsStruct
    version::Cuint                      = 1
    checkout_opts::CheckoutOptions
    fetch_opts::FetchOptionsStruct
    bare::Cint
    localclone::Cint                    = Consts.CLONE_LOCAL_AUTO
    checkout_branch::Cstring
    repository_cb::Ptr{Void}
    repository_cb_payload::Ptr{Void}
    remote_cb::Ptr{Void}
    remote_cb_payload::Ptr{Void}
end

"""
    LibGit2.CloneOptions

Matches the [`git_clone_options`](https://libgit2.github.com/libgit2/#HEAD/type/git_clone_options) struct.

The fields represent:
  * `version`: version of the struct in use, in case this changes later. For now, always `1`.
  * `checkout_opts`: The options for performing the checkout of the remote as part of the clone.
  * `fetch_opts`: The options for performing the pre-checkout fetch of the remote as part of the clone.
  * `bare`: If `0`, clone the full remote repository. If non-zero, perform a bare clone, in which
     there is no local copy of the source files in the repository and the [`gitdir`](@ref) and [`workdir`](@ref)
     are the same.
  * `localclone`: Flag whether to clone a local object database or do a fetch. The default is to let git decide.
     It will not use the git-aware transport for a local clone, but will use it for URLs which begin with `file://`.
  * `checkout_branch`: The name of the branch to checkout. If an empty string, the default branch of the
     remote will be checked out.
  * `repository_cb`: An optional callback which will be used to create the *new* repository into which
     the clone is made.
  * `repository_cb_payload`: The payload for the repository callback.
  * `remote_cb`: An optional callback used to create the [`GitRemote`](@ref) before making the clone from it.
  * `remote_cb_payload`: The payload for the remote callback.
"""
struct CloneOptions
    opts::CloneOptionsStruct
    cb_gcroot::Ref{Any}
    function CloneOptions(; fetch_opts::FetchOptions=FetchOptions(), kwargs...)
        return new(CloneOptionsStruct(; kwargs..., fetch_opts=fetch_opts.opts), fetch_opts.cb_gcroot)
    end
end

"""
    LibGit2.DiffOptionsStruct

Matches the [`git_diff_options`](https://libgit2.github.com/libgit2/#HEAD/type/git_diff_options) struct.

The fields represent:
  * `version`: version of the struct in use, in case this changes later. For now, always `1`.
  * `flags`: flags controlling which files will appear in the diff. Defaults to `DIFF_NORMAL`.
  * `ignore_submodules`: whether to look at files in submodules or not. Defaults to
    `SUBMODULE_IGNORE_UNSPECIFIED`, which means the submodule's configuration will control
     whether it appears in the diff or not.
  * `pathspec`: path to files to include in the diff. Default is to use all files in the repository.
  * `notify_cb`: optional callback which will notify the user of changes to the diff as file deltas are
     added to it.
  * `progress_cb`: optional callback which will display diff progress. Only relevant on libgit2 versions
     at least as new as 0.24.0.
  * `payload`: the payload to pass to `notify_cb` and `progress_cb`.
  * `context_lines`: the number of *unchanged* lines used to define the edges of a hunk.
     This is also the number of lines which will be shown before/after a hunk to provide
     context. Default is 3.
  * `interhunk_lines`: the maximum number of *unchanged* lines *between* two separate
     hunks allowed before the hunks will be combined. Default is 0.
  * `id_abbrev`: sets the length of the abbreviated [`GitHash`](@ref) to print.
     Default is `7`.
  * `max_size`: the maximum file size of a blob. Above this size, it will be treated
     as a binary blob. The default is 512 MB.
  * `old_prefix`: the virtual file directory in which to place old files on one side
     of the diff. Default is `"a"`.
  * `new_prefix`: the virtual file directory in which to place new files on one side
     of the diff. Default is `"b"`.
"""
@kwdef struct DiffOptionsStruct
    version::Cuint                           = Consts.DIFF_OPTIONS_VERSION
    flags::UInt32                            = Consts.DIFF_NORMAL

    # options controlling which files are in the diff
    ignore_submodules::GIT_SUBMODULE_IGNORE  = Consts.SUBMODULE_IGNORE_UNSPECIFIED
    pathspec::StrArrayStruct
    notify_cb::Ptr{Void}
    @static if LibGit2.VERSION >= v"0.24.0"
        progress_cb::Ptr{Void}
    end
    payload::Ptr{Void}

    # options controlling how the diff text is generated
    context_lines::UInt32                    = UInt32(3)
    interhunk_lines::UInt32
    id_abbrev::UInt16                        = UInt16(7)
    max_size::Int64                          = Int64(512*1024*1024) #512Mb
    old_prefix::Cstring
    new_prefix::Cstring
end

"""
    LibGit2.DescribeOptions

Matches the [`git_describe_options`](https://libgit2.github.com/libgit2/#HEAD/type/git_describe_options) struct.

The fields represent:
  * `version`: version of the struct in use, in case this changes later. For now, always `1`.
  * `max_candidates_tags`: consider this many most recent tags in `refs/tags` to describe a commit.
     Defaults to 10 (so that the 10 most recent tags would be examined to see if they describe a commit).
  * `describe_strategy`: whether to consider all entries in `refs/tags` (equivalent to `git-describe --tags`)
     or all entries in `refs/` (equivalent to `git-describe --all`). The default is to only show annotated tags.
     If `Consts.DESCRIBE_TAGS` is passed, all tags, annotated or not, will be considered.
     If `Consts.DESCRIBE_ALL` is passed, any ref in `refs/` will be considered.
  * `pattern`: only consider tags which match `pattern`. Supports glob expansion.
  * `only_follow_first_parent`: when finding the distance from a matching reference to the described
     object, only consider the distance from the first parent.
  * `show_commit_oid_as_fallback`: if no matching reference can be found which describes a commit, show the
     commit's [`GitHash`](@ref) instead of throwing an error (the default behavior).
"""
@kwdef struct DescribeOptions
    version::Cuint             = 1
    max_candidates_tags::Cuint = 10
    describe_strategy::Cuint   = Consts.DESCRIBE_DEFAULT

    pattern::Cstring
    only_follow_first_parent::Cint
    show_commit_oid_as_fallback::Cint
end

"""
    LibGit2.DescribeFormatOptions

Matches the [`git_describe_format_options`](https://libgit2.github.com/libgit2/#HEAD/type/git_describe_format_options) struct.

The fields represent:
  * `version`: version of the struct in use, in case this changes later. For now, always `1`.
  * `abbreviated_size`: lower bound on the size of the abbreviated `GitHash` to use, defaulting to `7`.
  * `always_use_long_format`: set to `1` to use the long format for strings even if a short format can be used.
  * `dirty_suffix`: if set, this will be appended to the end of the description string if the [`workdir`](@ref) is dirty.
"""
@kwdef struct DescribeFormatOptions
    version::Cuint          = 1
    abbreviated_size::Cuint = 7
    always_use_long_format::Cint
    dirty_suffix::Cstring
end

"""
    LibGit2.DiffFile

Description of one side of a delta.
Matches the [`git_diff_file`](https://libgit2.github.com/libgit2/#HEAD/type/git_diff_file) struct.

The fields represent:
  * `id`: the [`GitHash`](@ref) of the item in the diff. If the item is empty on this
     side of the diff (for instance, if the diff is of the removal of a file), this will
     be `GitHash(0)`.
  * `path`: a `NULL` terminated path to the item relative to the working directory of the repository.
  * `size`: the size of the item in bytes.
  * `flags`: a combination of the [`git_diff_flag_t`](https://libgit2.github.com/libgit2/#HEAD/type/git_diff_flag_t)
     flags. The `i`th bit of this integer sets the `i`th flag.
  * `mode`: the [`stat`](@ref) mode for the item.
  * `id_abbrev`: only present in LibGit2 versions newer than or equal to `0.25.0`.
     The length of the `id` field when converted using [`hex`](@ref). Usually equal to `OID_HEXSZ` ($OID_HEXSZ).
"""
struct DiffFile
    id::GitHash
    path::Cstring
    size::Int64
    flags::UInt32
    mode::UInt16
    @static if LibGit2.VERSION >= v"0.25.0"
        id_abbrev::UInt16
    end
end

function Base.show(io::IO, df::DiffFile)
    println(io, "DiffFile:")
    println(io, "Oid: $(df.id))")
    println(io, "Path: $(df.path)")
    println(io, "Size: $(df.size)")
end

"""
    LibGit2.DiffDelta

Description of changes to one entry.
Matches the [`git_diff_delta`](https://libgit2.github.com/libgit2/#HEAD/type/git_diff_delta) struct.

The fields represent:
  * `status`: One of `Consts.DELTA_STATUS`, indicating whether the file has been added/modified/deleted.
  * `flags`: Flags for the delta and the objects on each side. Determines whether to treat the file(s)
     as binary/text, whether they exist on each side of the diff, and whether the object ids are known
     to be correct.
  * `similarity`: Used to indicate if a file has been renamed or copied.
  * `nfiles`: The number of files in the delta (for instance, if the delta
     was run on a submodule commit id, it may contain more than one file).
  * `old_file`: A [`DiffFile`](@ref) containing information about the file(s) before the changes.
  * `new_file`: A [`DiffFile`](@ref) containing information about the file(s) after the changes.
"""
struct DiffDelta
    status::Cint
    flags::UInt32
    similarity::UInt16
    nfiles::UInt16
    old_file::DiffFile
    new_file::DiffFile
end

function Base.show(io::IO, dd::DiffDelta)
    println(io, "DiffDelta:")
    println(io, "Status: $(Consts.DELTA_STATUS(dd.status))")
    println(io, "Number of files: $(dd.nfiles)")
    println(io, "Old file:\n$(dd.old_file)")
    println(io, "New file:\n$(dd.new_file)")
end

"""
    LibGit2.MergeOptions

Matches the [`git_merge_options`](https://libgit2.github.com/libgit2/#HEAD/type/git_merge_options) struct.

The fields represent:
  * `version`: version of the struct in use, in case this changes later. For now, always `1`.
  * `flags`: an `enum` for flags describing merge behavior.
     Defined in [`git_merge_flag_t`](https://github.com/libgit2/libgit2/blob/HEAD/include/git2/merge.h#L95).
     The corresponding Julia enum is `GIT_MERGE` and has values:
     - `MERGE_FIND_RENAMES`: detect if a file has been renamed between the common
       ancestor and the "ours" or "theirs" side of the merge. Allows merges where
       a file has been renamed.
     - `MERGE_FAIL_ON_CONFLICT`: exit immediately if a conflict is found rather
       than trying to resolve it.
     - `MERGE_SKIP_REUC`: do not write the REUC extension on the index resulting
       from the merge.
     - `MERGE_NO_RECURSIVE`: if the commits being merged have multiple merge bases,
       use the first one, rather than trying to recursively merge the bases.
  * `rename_threshold`: how similar two files must to consider one a rename of the other.
    This is an integer that sets the percentage similarity. The default is 50.
  * `target_limit`: the maximum number of files to compare with to look for renames.
    The default is 200.
  * `metric`: optional custom function to use to determine the similarity between two
    files for rename detection.
  * `recursion_limit`: the upper limit on the number of merges of common ancestors to
    perform to try to build a new virtual merge base for the merge. The default is no
    limit. This field is only present on libgit2 versions newer than 0.24.0.
  * `default_driver`: the merge driver to use if both sides have changed. This field
    is only present on libgit2 versions newer than 0.25.0.
  * `file_favor`: how to handle conflicting file contents for the `text` driver.
    - `MERGE_FILE_FAVOR_NORMAL`: if both sides of the merge have changes to a section,
       make a note of the conflict in the index which `git checkout` will use to create
       a merge file, which the user can then reference to resolve the conflicts. This is
       the default.
    - `MERGE_FILE_FAVOR_OURS`: if both sides of the merge have changes to a section,
       use the version in the "ours" side of the merge in the index.
    - `MERGE_FILE_FAVOR_THEIRS`: if both sides of the merge have changes to a section,
       use the version in the "theirs" side of the merge in the index.
    - `MERGE_FILE_FAVOR_UNION`: if both sides of the merge have changes to a section,
       include each unique line from both sides in the file which is put into the index.
  * `file_flags`: guidelines for merging files.
"""
@kwdef struct MergeOptions
    version::Cuint                    = 1
    flags::Cint
    rename_threshold::Cuint           = 50
    target_limit::Cuint               = 200
    metric::Ptr{Void}
    @static if LibGit2.VERSION >= v"0.24.0"
        recursion_limit::Cuint
    end
    @static if LibGit2.VERSION >= v"0.25.0"
        default_driver::Cstring
    end
    file_favor::GIT_MERGE_FILE_FAVOR  = Consts.MERGE_FILE_FAVOR_NORMAL
    file_flags::GIT_MERGE_FILE        = Consts.MERGE_FILE_DEFAULT
end

"""
    LibGit2.BlameOptions

Matches the [`git_blame_options`](https://libgit2.github.com/libgit2/#HEAD/type/git_blame_options) struct.

The fields represent:
  * `version`: version of the struct in use, in case this changes later. For now, always `1`.
  * `flags`: one of `Consts.BLAME_NORMAL` or `Consts.BLAME_FIRST_PARENT` (the other blame flags
     are not yet implemented by libgit2).
  * `min_match_characters`: the minimum number of *alphanumeric* characters which much change
    in a commit in order for the change to be associated with that commit. The default is 20.
    Only takes effect if one of the `Consts.BLAME_*_COPIES` flags are used, which libgit2 does
    not implement yet.
  * `newest_commit`: the [`GitHash`](@ref) of the newest commit from which to look at changes.
  * `oldest_commit`: the [`GitHash`](@ref) of the oldest commit from which to look at changes.
  * `min_line`: the first line of the file from which to starting blaming. The default is `1`.
  * `max_line`: the last line of the file to which to blame. The default is `0`, meaning the
    last line of the file.
"""
@kwdef struct BlameOptions
    version::Cuint                    = 1
    flags::UInt32                     = 0
    min_match_characters::UInt16      = 20
    newest_commit::GitHash
    oldest_commit::GitHash
    min_line::Csize_t                 = 1
    max_line::Csize_t                 = 0
end

@kwdef struct PushOptionsStruct
    version::Cuint                     = 1
    parallelism::Cint                  = 1
    callbacks::RemoteCallbacksStruct
    @static if LibGit2.VERSION >= v"0.25.0"
        proxy_opts::ProxyOptions
    end
    @static if LibGit2.VERSION >= v"0.24.0"
        custom_headers::StrArrayStruct
    end
end

"""
    LibGit2.PushOptions

Matches the [`git_push_options`](https://libgit2.github.com/libgit2/#HEAD/type/git_push_options) struct.

The fields represent:
  * `version`: version of the struct in use, in case this changes later. For now, always `1`.
  * `parallelism`: if a pack file must be created, this variable sets the number of worker
     threads which will be spawned by the packbuilder. If `0`, the packbuilder will auto-set
     the number of threads to use. The default is `1`.
  * `callbacks`: the callbacks (e.g. for authentication with the remote) to use for the push.
  * `proxy_opts`: only relevant if the LibGit2 version is greater than or equal to `0.25.0`.
     Sets options for using a proxy to communicate with a remote. See [`ProxyOptions`](@ref)
     for more information.
  * `custom_headers`: only relevant if the LibGit2 version is greater than or equal to `0.24.0`.
     Extra headers needed for the push operation.
"""
struct PushOptions
    opts::PushOptionsStruct
    cb_gcroot::Ref{Any}
    function PushOptions(; callbacks::RemoteCallbacks=RemoteCallbacks(), kwargs...)
        return new(PushOptionsStruct(; kwargs..., callbacks=callbacks.cb), callbacks.gcroot)
    end
end

"""
    LibGit2.CherrypickOptions

Matches the [`git_cherrypick_options`](https://libgit2.github.com/libgit2/#HEAD/type/git_cherrypick_options) struct.

The fields represent:
  * `version`: version of the struct in use, in case this changes later. For now, always `1`.
  * `mainline`: if cherrypicking a merge commit, specifies the parent number (starting at `1`)
    which will allow cherrypick to apply the changes relative to that parent. Only relevant if
    cherrypicking a merge commit. Default is `0`.
  * `merge_opts`: options for merging the changes in. See [`MergeOptions`](@ref) for more information.
  * `checkout_opts`: options for the checkout of the commit being cherrypicked. See [`CheckoutOptions`](@ref)
     for more information.
"""
@kwdef struct CherrypickOptions
    version::Cuint = 1
    mainline::Cuint = 0
    merge_opts::MergeOptions=MergeOptions()
    checkout_opts::CheckoutOptions=CheckoutOptions()
end

"""
    LibGit2.IndexTime

Matches the [`git_index_time`](https://libgit2.github.com/libgit2/#HEAD/type/git_index_time) struct.
"""
struct IndexTime
    seconds::Int64
    nanoseconds::Cuint
end

"""
    LibGit2.IndexEntry

In-memory representation of a file entry in the index.
Matches the [`git_index_entry`](https://libgit2.github.com/libgit2/#HEAD/type/git_index_entry) struct.
"""
struct IndexEntry
    ctime::IndexTime
    mtime::IndexTime

    dev::UInt32
    ino::UInt32
    mode::UInt32
    uid::UInt32
    gid::UInt32
    file_size::Int64

    id::GitHash

    flags::UInt16
    flags_extended::UInt16

    path::Ptr{UInt8}
end
Base.show(io::IO, ie::IndexEntry) = print(io, "IndexEntry($(string(ie.id)))")

"""
    LibGit2.RebaseOptions

Matches the `git_rebase_options` struct.

The fields represent:
  * `version`: version of the struct in use, in case this changes later. For now, always `1`.
  * `quiet`: inform other git clients helping with/working on the rebase that the rebase
    should be done "quietly". Used for interoperability. The default is `1`.
  * `inmemory`: start an in-memory rebase. Callers working on the rebase can go through its
    steps and commit any changes, but cannot rewind HEAD or update the repository. The
    [`workdir`](@ref) will not be modified. Only present on libgit2 versions newer than or equal to 0.24.0.
  * `rewrite_notes_ref`: name of the reference to notes to use to rewrite the commit notes as
    the rebase is finished.
  * `merge_opts`: merge options controlling how the trees will be merged at each rebase step.
     Only present on libgit2 versions newer than or equal to 0.24.0.
  * `checkout_opts`: checkout options for writing files when initializing the rebase, stepping
    through it, and aborting it. See [`CheckoutOptions`](@ref) for more information.
"""
@kwdef struct RebaseOptions
    version::Cuint                 = 1
    quiet::Cint                    = 1
    @static if LibGit2.VERSION >= v"0.24.0"
        inmemory::Cint
    end
    rewrite_notes_ref::Cstring
    @static if LibGit2.VERSION >= v"0.24.0"
        merge_opts::MergeOptions
    end
    checkout_opts::CheckoutOptions
end

"""
    LibGit2.RebaseOperation

Describes a single instruction/operation to be performed during the rebase.
Matches the [`git_rebase_operation`](https://libgit2.github.com/libgit2/#HEAD/type/git_rebase_operation_t) struct.

The fields represent:
  * `optype`: the type of rebase operation currently being performed. The options are:
      - `REBASE_OPERATION_PICK`: cherry-pick the commit in question.
      - `REBASE_OPERATION_REWORD`: cherry-pick the commit in question, but rewrite its
        message using the prompt.
      - `REBASE_OPERATION_EDIT`: cherry-pick the commit in question, but allow the user
        to edit the commit's contents and its message.
      - `REBASE_OPERATION_SQUASH`: squash the commit in question into the previous commit.
        The commit messages of the two commits will be merged.
      - `REBASE_OPERATION_FIXUP`: squash the commit in question into the previous commit.
        Only the commit message of the previous commit will be used.
      - `REBASE_OPERATION_EXEC`: do not cherry-pick a commit. Run a command and continue if
        the command exits successfully.
  * `id`: the [`GitHash`](@ref) of the commit being worked on during this rebase step.
  * `exec`: in case `REBASE_OPERATION_EXEC` is used, the command to run during this step
    (for instance, running the test suite after each commit).
"""
struct RebaseOperation
    optype::Cint
    id::GitHash
    exec::Cstring
end
function Base.show(io::IO, rbo::RebaseOperation)
    println(io, "RebaseOperation($(string(rbo.id)))")
    println(io, "Operation type: $(Consts.GIT_REBASE_OPERATION(rbo.optype))")
end

"""
    LibGit2.StatusOptions

Options to control how `git_status_foreach_ext()` will issue callbacks.
Matches the [`git_status_opt_t`](https://libgit2.github.com/libgit2/#HEAD/type/git_status_opt_t) struct.

The fields represent:
  * `version`: version of the struct in use, in case this changes later. For now, always `1`.
  * `show`: a flag for which files to examine and in which order.
    The default is `Consts.STATUS_SHOW_INDEX_AND_WORKDIR`.
  * `flags`: flags for controlling any callbacks used in a status call.
  * `pathspec`: an array of paths to use for path-matching. The behavior of the path-matching
    will vary depending on the values of `show` and `flags`.
"""
@kwdef struct StatusOptions
    version::Cuint           = 1
    show::Cint               = Consts.STATUS_SHOW_INDEX_AND_WORKDIR
    flags::Cuint             = Consts.STATUS_OPT_INCLUDE_UNTRACKED |
                               Consts.STATUS_OPT_RECURSE_UNTRACKED_DIRS |
                               Consts.STATUS_OPT_RENAMES_HEAD_TO_INDEX |
                               Consts.STATUS_OPT_SORT_CASE_SENSITIVELY
    pathspec::StrArrayStruct
end

"""
    LibGit2.StatusEntry

Providing the differences between the file as it exists in HEAD and the index, and
providing the differences between the index and the working directory.
Matches the `git_status_entry` struct.

The fields represent:
  * `status`: contains the status flags for the file, indicating if it is current,
    or has been changed in some way in the index or work tree.
  * `head_to_index`: a pointer to a [`DiffDelta`](@ref) which encapsulates the difference(s)
    between the file as it exists in HEAD and in the index.
  * `index_to_workdir`: a pointer to a `DiffDelta` which encapsulates the difference(s)
    between the file as it exists in the index and in the [`workdir`](@ref).
"""
struct StatusEntry
    status::Cuint
    head_to_index::Ptr{DiffDelta}
    index_to_workdir::Ptr{DiffDelta}
end

"""
    LibGit2.FetchHead

Contains the information about HEAD during a fetch, including the name and URL
of the branch fetched from, the oid of the HEAD, and whether the fetched HEAD
has been merged locally.

The fields represent:
  * `name`: The name in the local reference database of the fetch head, for example,
     `"refs/heads/master"`.
  * `url`: The URL of the fetch head.
  * `oid`: The [`GitHash`](@ref) of the tip of the fetch head.
  * `ismerge`: Boolean flag indicating whether the changes at the
     remote have been merged into the local copy yet or not. If `true`, the local
     copy is up to date with the remote fetch head.
"""
struct FetchHead
    name::String
    url::String
    oid::GitHash
    ismerge::Bool
end

function Base.show(io::IO, fh::FetchHead)
    println(io, "FetchHead:")
    println(io, "Name: $(fh.name)")
    println(io, "URL: $(fh.url)")
    print(io, "OID: ")
    show(io, fh.oid)
    println(io)
    println(io, "Merged: $(fh.ismerge)")
end

"""
    LibGit2.ConfigEntry

Matches the [`git_config_entry`](https://libgit2.github.com/libgit2/#HEAD/type/git_config_entry) struct.
"""
@kwdef struct ConfigEntry
    name::Cstring
    value::Cstring
    level::GIT_CONFIG = Consts.CONFIG_LEVEL_DEFAULT
    free::Ptr{Void}
    payload::Ptr{Void}
end

function Base.show(io::IO, ce::ConfigEntry)
    print(io, "ConfigEntry(\"", unsafe_string(ce.name), "\", \"", unsafe_string(ce.value), "\")")
end

"""
    split(ce::LibGit2.ConfigEntry) -> Tuple{String,String,String,String}

Break the `ConfigEntry` up to the following pieces: section, subsection, name, and value.

# Examples
Given the git configuration file containing:
```
[credential "https://example.com"]
    username = me
```

The `ConfigEntry` would look like the following:

```julia-repl
julia> entry
ConfigEntry("credential.https://example.com.username", "me")

julia> split(entry)
("credential", "https://example.com", "username", "me")
```

Refer to the [git config syntax documenation](https://git-scm.com/docs/git-config#_syntax)
for more details.
"""
function Base.split(ce::ConfigEntry)
    key = unsafe_string(ce.name)

    # Determine the positions of the delimiters
    subsection_delim = search(key, '.')
    name_delim = rsearch(key, '.')

    section = SubString(key, 1, subsection_delim - 1)
    subsection = SubString(key, subsection_delim + 1, name_delim - 1)
    name = SubString(key, name_delim + 1)
    value = unsafe_string(ce.value)

    return (section, subsection, name, value)
end

# Abstract object types
abstract type AbstractGitObject end
Base.isempty(obj::AbstractGitObject) = (obj.ptr == C_NULL)

abstract type GitObject <: AbstractGitObject end

for (typ, owntyp, sup, cname) in [
    (:GitRepo,           nothing,               :AbstractGitObject, :git_repository),
    (:GitConfig,         :(Nullable{GitRepo}),  :AbstractGitObject, :git_config),
    (:GitIndex,          :(Nullable{GitRepo}),  :AbstractGitObject, :git_index),
    (:GitRemote,         :GitRepo,              :AbstractGitObject, :git_remote),
    (:GitRevWalker,      :GitRepo,              :AbstractGitObject, :git_revwalk),
    (:GitReference,      :GitRepo,              :AbstractGitObject, :git_reference),
    (:GitDescribeResult, :GitRepo,              :AbstractGitObject, :git_describe_result),
    (:GitDiff,           :GitRepo,              :AbstractGitObject, :git_diff),
    (:GitDiffStats,      :GitRepo,              :AbstractGitObject, :git_diff_stats),
    (:GitAnnotated,      :GitRepo,              :AbstractGitObject, :git_annotated_commit),
    (:GitRebase,         :GitRepo,              :AbstractGitObject, :git_rebase),
    (:GitBlame,          :GitRepo,              :AbstractGitObject, :git_blame),
    (:GitStatus,         :GitRepo,              :AbstractGitObject, :git_status_list),
    (:GitBranchIter,     :GitRepo,              :AbstractGitObject, :git_branch_iterator),
    (:GitConfigIter,     nothing,               :AbstractGitObject, :git_config_iterator),
    (:GitUnknownObject,  :GitRepo,              :GitObject,         :git_object),
    (:GitCommit,         :GitRepo,              :GitObject,         :git_commit),
    (:GitBlob,           :GitRepo,              :GitObject,         :git_blob),
    (:GitTree,           :GitRepo,              :GitObject,         :git_tree),
    (:GitTag,            :GitRepo,              :GitObject,         :git_tag),
    (:GitTreeEntry,      :GitTree,              :AbstractGitObject, :git_tree_entry),
    ]

    if owntyp === nothing
        @eval mutable struct $typ <: $sup
            ptr::Ptr{Void}
            function $typ(ptr::Ptr{Void}, fin::Bool=true)
                # fin=false should only be used when the pointer should not be free'd
                # e.g. from within callback functions which are passed a pointer
                @assert ptr != C_NULL
                obj = new(ptr)
                if fin
                    Threads.atomic_add!(REFCOUNT, UInt(1))
                    finalizer(Base.close, obj)
                end
                return obj
            end
        end
    else
        @eval mutable struct $typ <: $sup
            owner::$owntyp
            ptr::Ptr{Void}
            function $typ(owner::$owntyp, ptr::Ptr{Void}, fin::Bool=true)
                @assert ptr != C_NULL
                obj = new(owner, ptr)
                if fin
                    Threads.atomic_add!(REFCOUNT, UInt(1))
                    finalizer(Base.close, obj)
                end
                return obj
            end
        end
        if isa(owntyp, Expr) && owntyp.args[1] == :Nullable
            @eval begin
                $typ(ptr::Ptr{Void}, fin::Bool=true) = $typ($owntyp(), ptr, fin)
                $typ(owner::$(owntyp.args[2]), ptr::Ptr{Void}, fin::Bool=true) =
                    $typ($owntyp(owner), ptr, fin)
            end
        end
    end
    @eval function Base.close(obj::$typ)
        if obj.ptr != C_NULL
            ccall(($(string(cname, :_free)), :libgit2), Void, (Ptr{Void},), obj.ptr)
            obj.ptr = C_NULL
            if Threads.atomic_sub!(REFCOUNT, UInt(1)) == 1
                # will the last finalizer please turn out the lights?
                ccall((:git_libgit2_shutdown, :libgit2), Cint, ())
            end
        end
    end
end

## Calling `GitObject(repo, ...)` will automatically resolve to the appropriate type.
function GitObject(repo::GitRepo, ptr::Ptr{Void})
    T = objtype(Consts.OBJECT(ptr))
    T(repo, ptr)
end

"""
    LibGit2.GitSignature

This is a Julia wrapper around a pointer to a
[`git_signature`](https://libgit2.github.com/libgit2/#HEAD/type/git_signature) object.
"""
mutable struct GitSignature <: AbstractGitObject
    ptr::Ptr{SignatureStruct}
    function GitSignature(ptr::Ptr{SignatureStruct})
        @assert ptr != C_NULL
        obj = new(ptr)
        finalizer(Base.close, obj)
        return obj
    end
end
function Base.close(obj::GitSignature)
    if obj.ptr != C_NULL
        ccall((:git_signature_free, :libgit2), Void, (Ptr{SignatureStruct},), obj.ptr)
        obj.ptr = C_NULL
    end
end

# Structure has the same layout as SignatureStruct
mutable struct Signature
    name::String
    email::String
    time::Int64
    time_offset::Cint
end

"""
    LibGit2.BlameHunk

Matches the [`git_blame_hunk`](https://libgit2.github.com/libgit2/#HEAD/type/git_blame_hunk) struct.
The fields represent:
    * `lines_in_hunk`: the number of lines in this hunk of the blame.
    * `final_commit_id`: the [`GitHash`](@ref) of the commit where this section was last changed.
    * `final_start_line_number`: the *one based* line number in the file where the
       hunk starts, in the *final* version of the file.
    * `final_signature`: the signature of the person who last modified this hunk. You will
       need to pass this to `Signature` to access its fields.
    * `orig_commit_id`: the [`GitHash`](@ref) of the commit where this hunk was first found.
    * `orig_path`: the path to the file where the hunk originated. This may be different
       than the current/final path, for instance if the file has been moved.
    * `orig_start_line_number`: the *one based* line number in the file where the
       hunk starts, in the *original* version of the file at `orig_path`.
    * `orig_signature`: the signature of the person who introduced this hunk. You will
       need to pass this to `Signature` to access its fields.
    * `boundary`: `'1'` if the original commit is a "boundary" commit (for instance, if it's
       equal to an oldest commit set in `options`).
"""
@kwdef struct BlameHunk
    lines_in_hunk::Csize_t

    final_commit_id::GitHash
    final_start_line_number::Csize_t
    final_signature::Ptr{SignatureStruct}

    orig_commit_id::GitHash
    orig_path::Cstring
    orig_start_line_number::Csize_t
    orig_signature::Ptr{SignatureStruct}

    boundary::Char
end

"""
    with(f::Function, obj)

Resource management helper function. Applies `f` to `obj`, making sure to call
`close` on `obj` after `f` successfully returns or throws an error. Ensures that
allocated git resources are finalized as soon as they are no longer needed.
"""
function with(f::Function, obj)
    try
        f(obj)
    finally
        close(obj)
    end
end

with(f::Function, ::Type{T}, args...) where {T} = with(f, T(args...))

"""
    with_warn(f::Function, ::Type{T}, args...)

Resource management helper function. Apply `f` to `args`, first constructing
an instance of type `T` from `args`. Makes sure to call `close` on the resulting
object after `f` successfully returns or throws an error. Ensures that
allocated git resources are finalized as soon as they are no longer needed. If an
error is thrown by `f`, a warning is shown containing the error.
"""
function with_warn(f::Function, ::Type{T}, args...) where T
    obj = T(args...)
    try
        with(f, obj)
    catch err
        warn("$(string(T)) thrown exception: $err")
    end
end

"""
    LibGit2.Consts.OBJECT(::Type{T}) where T<:GitObject

The `OBJECT` enum value corresponding to type `T`.
"""
Consts.OBJECT(::Type{GitCommit})        = Consts.OBJ_COMMIT
Consts.OBJECT(::Type{GitTree})          = Consts.OBJ_TREE
Consts.OBJECT(::Type{GitBlob})          = Consts.OBJ_BLOB
Consts.OBJECT(::Type{GitTag})           = Consts.OBJ_TAG
Consts.OBJECT(::Type{GitUnknownObject}) = Consts.OBJ_ANY
Consts.OBJECT(::Type{GitObject})        = Consts.OBJ_ANY

Consts.OBJECT(ptr::Ptr{Void}) =
    ccall((:git_object_type, :libgit2), Consts.OBJECT, (Ptr{Void},), ptr)

"""
    objtype(obj_type::Consts.OBJECT)

Return the type corresponding to the enum value.
"""
function objtype(obj_type::Consts.OBJECT)
    if obj_type == Consts.OBJ_COMMIT
        GitCommit
    elseif obj_type == Consts.OBJ_TREE
        GitTree
    elseif obj_type == Consts.OBJ_BLOB
        GitBlob
    elseif obj_type == Consts.OBJ_TAG
        GitTag
    elseif obj_type == Consts.OBJ_ANY #this name comes from the header
        GitUnknownObject
    else
        throw(GitError(Error.Object, Error.ENOTFOUND, "Object type $obj_type is not supported"))
    end
end

import Base.securezero!

abstract type AbstractCredential end

"""
    isfilled(cred::AbstractCredential) -> Bool

Verifies that a credential is ready for use in authentication.
"""
isfilled(::AbstractCredential)

"Credential that support only `user` and `password` parameters"
mutable struct UserPasswordCredential <: AbstractCredential
    user::String
    pass::String
    function UserPasswordCredential(user::AbstractString="", pass::AbstractString="")
        c = new(user, pass)
        finalizer(securezero!, c)
        return c
    end

    # Deprecated constructors
    function UserPasswordCredential(u::AbstractString,p::AbstractString,prompt_if_incorrect::Bool)
        Base.depwarn(string(
            "`UserPasswordCredential` no longer supports the `prompt_if_incorrect` parameter. ",
            "Use the `allow_prompt` keyword in supported by `LibGit2.CredentialPayload` ",
            "instead."), :UserPasswordCredential)
        UserPasswordCredential(u, p)
    end
    UserPasswordCredential(prompt_if_incorrect::Bool) = UserPasswordCredential("","",prompt_if_incorrect)
end

function securezero!(cred::UserPasswordCredential)
    securezero!(cred.user)
    securezero!(cred.pass)
    return cred
end

function Base.:(==)(a::UserPasswordCredential, b::UserPasswordCredential)
    a.user == b.user && a.pass == b.pass
end

function isfilled(cred::UserPasswordCredential)
    !isempty(cred.user) && !isempty(cred.pass)
end

"SSH credential type"
mutable struct SSHCredential <: AbstractCredential
    user::String
    pass::String
    prvkey::String
    pubkey::String
    function SSHCredential(user::AbstractString="", pass::AbstractString="",
                            prvkey::AbstractString="", pubkey::AbstractString="")
        c = new(user, pass, prvkey, pubkey)
        finalizer(securezero!, c)
        return c
    end

    # Deprecated constructors
    function SSHCredential(u::AbstractString,p::AbstractString,prvkey::AbstractString,pubkey::AbstractString,prompt_if_incorrect::Bool)
        Base.depwarn(string(
            "`SSHCredential` no longer supports the `prompt_if_incorrect` parameter. ",
            "Use the `allow_prompt` keyword in supported by `LibGit2.CredentialPayload` ",
            "instead."), :SSHCredential)
        SSHCredential(u, p, prvkey, pubkey)
    end
    SSHCredential(u::AbstractString, p::AbstractString, prompt_if_incorrect::Bool) = SSHCredential(u,p,"","",prompt_if_incorrect)
    SSHCredential(prompt_if_incorrect::Bool) = SSHCredential("","","","",prompt_if_incorrect)
end

function securezero!(cred::SSHCredential)
    securezero!(cred.user)
    securezero!(cred.pass)
    securezero!(cred.prvkey)
    securezero!(cred.pubkey)
    return cred
end

function Base.:(==)(a::SSHCredential, b::SSHCredential)
    a.user == b.user && a.pass == b.pass && a.prvkey == b.prvkey && a.pubkey == b.pubkey
end

function isfilled(cred::SSHCredential)
    !isempty(cred.user) && isfile(cred.prvkey) && isfile(cred.pubkey) &&
    (!isempty(cred.pass) || !is_passphrase_required(cred.prvkey))
end

"Caches credential information for re-use"
struct CachedCredentials
    cred::Dict{String,AbstractCredential}
    CachedCredentials() = new(Dict{String,AbstractCredential}())
end

Base.haskey(cache::CachedCredentials, cred_id) = Base.haskey(cache.cred, cred_id)
Base.getindex(cache::CachedCredentials, cred_id) = Base.getindex(cache.cred, cred_id)
Base.get!(cache::CachedCredentials, cred_id, default) = Base.get!(cache.cred, cred_id, default)

function securezero!(p::CachedCredentials)
    foreach(securezero!, values(p.cred))
    return p
end

function approve(cache::CachedCredentials, cred::AbstractCredential, url::AbstractString)
    cred_id = credential_identifier(url)
    cache.cred[cred_id] = cred
    nothing
end

function reject(cache::CachedCredentials, cred::AbstractCredential, url::AbstractString)
    cred_id = credential_identifier(url)
    if haskey(cache.cred, cred_id)
        delete!(cache.cred, cred_id)
    end
    nothing
end

"""
    LibGit2.CredentialPayload

Retains the state between multiple calls to the credential callback for the same URL.
A `CredentialPayload` instance is expected to be `reset!` whenever it will be used with a
different URL.
"""
mutable struct CredentialPayload <: Payload
    explicit::Nullable{AbstractCredential}
    cache::Nullable{CachedCredentials}
    allow_ssh_agent::Bool    # Allow the use of the SSH agent to get credentials
    allow_git_helpers::Bool  # Allow the use of git credential helpers
    allow_prompt::Bool       # Allow prompting the user for credentials

    config::GitConfig

    # Ephemeral state fields
    credential::Nullable{AbstractCredential}
    first_pass::Bool
    use_ssh_agent::Bool
    use_env::Bool
    use_git_helpers::Bool
    remaining_prompts::Int

    url::String
    scheme::String
    username::String
    host::String

    function CredentialPayload(
            credential::Nullable{<:AbstractCredential}=Nullable{AbstractCredential}(),
            cache::Nullable{CachedCredentials}=Nullable{CachedCredentials}(),
            config::GitConfig=GitConfig();
            allow_ssh_agent::Bool=true,
            allow_git_helpers::Bool=true,
            allow_prompt::Bool=true)

        payload = new(credential, cache, allow_ssh_agent, allow_git_helpers, allow_prompt, config)
        return reset!(payload)
    end
end

function CredentialPayload(credential::AbstractCredential; kwargs...)
    CredentialPayload(Nullable(credential), Nullable{CachedCredentials}(); kwargs...)
end

function CredentialPayload(cache::CachedCredentials; kwargs...)
    CredentialPayload(Nullable{AbstractCredential}(), Nullable(cache); kwargs...)
end

"""
    reset!(payload, [config]) -> CredentialPayload

Reset the `payload` state back to the initial values so that it can be used again within
the credential callback. If a `config` is provided the configuration will also be updated.
"""
function reset!(p::CredentialPayload, config::GitConfig=p.config)
    p.config = config
    p.credential = Nullable{AbstractCredential}()
    p.first_pass = true
    p.use_ssh_agent = p.allow_ssh_agent
    p.use_env = true
    p.use_git_helpers = p.allow_git_helpers
    p.remaining_prompts = p.allow_prompt ? 3 : 0
    p.url = ""
    p.scheme = ""
    p.username = ""
    p.host = ""

    return p
end

"""
    approve(payload::CredentialPayload; shred::Bool=true) -> Void

Store the `payload` credential for re-use in a future authentication. Should only be called
when authentication was successful.

The `shred` keyword controls whether sensitive information in the payload credential field
should be destroyed. Should only be set to `false` during testing.
"""
function approve(p::CredentialPayload; shred::Bool=true)
    isnull(p.credential) && return  # No credentials were used
    cred = unsafe_get(p.credential)

    if !isnull(p.cache)
        approve(unsafe_get(p.cache), cred, p.url)
        shred = false  # Avoid wiping `cred` as this would also wipe the cached copy
    end
    if p.allow_git_helpers
        approve(p.config, cred, p.url)
    end

    shred && securezero!(cred)
    nothing
end

"""
    reject(payload::CredentialPayload; shred::Bool=true) -> Void

Discard the `payload` credential from begin re-used in future authentication. Should only be
called when authentication was unsuccessful.

The `shred` keyword controls whether sensitive information in the payload credential field
should be destroyed. Should only be set to `false` during testing.
"""
function reject(p::CredentialPayload; shred::Bool=true)
    isnull(p.credential) && return  # No credentials were used
    cred = unsafe_get(p.credential)

    if !isnull(p.cache)
        reject(unsafe_get(p.cache), cred, p.url)
        shred = false  # Avoid wiping `cred` as this would also wipe the cached copy
    end
    if p.allow_git_helpers
        reject(p.config, cred, p.url)
    end

    shred && securezero!(cred)
    nothing
end

max_stars_repo_name: JuliaLangEs/julieta

max_issues_repo_name: JuliaLangEs/julieta

max_forks_repo_name: JuliaLangEs/julieta


text:
"""
Initialize variable values by taking the mean of lower and upper bounds.
"""
function init_vars(pm::AbstractPowerModel)
    init_branch_vars(pm)
    init_dc_vars(pm)
    init_gen_vars(pm)
    init_voltage_vars(pm)
end

"""
Initialize variable values for ACPPowerModel from Ipopt solution.
"""
function init_vars_from_ipopt(pm::T, pm2::T) where T<:AbstractPowerModel
    optimize_model!(pm2, optimizer = Ipopt.Optimizer)
    init_branch_vars(pm, pm2)
    init_dc_vars(pm, pm2)
    init_gen_vars(pm, pm2)
    init_voltage_vars(pm, pm2)
end

"""
Set initial variable value to JuMP, if the variable has both lower and upper bounds.
"""
function set_start_value(v::JuMP.VariableRef)
    if has_lower_bound(v) && has_upper_bound(v)
        JuMP.set_start_value(v, (upper_bound(v)+lower_bound(v))/2)
    end
end

"""
Initilize branch variable values
"""

function init_branch_vars(pm::AbstractPowerModel)
    for (l,i,j) in ref(pm,:arcs)
        set_start_value(var(pm,:p)[(l,i,j)])
        set_start_value(var(pm,:q)[(l,i,j)])
    end
end

function init_branch_vars(pm::AbstractPowerModel, pm_solved::AbstractPowerModel)
    for (l,i,j) in ref(pm,:arcs)
        JuMP.set_start_value(var(pm,:p)[(l,i,j)], JuMP.value(var(pm_solved,:p)[(l,i,j)]))
        JuMP.set_start_value(var(pm,:q)[(l,i,j)], JuMP.value(var(pm_solved,:q)[(l,i,j)]))
    end
end

function init_branch_vars(pm::IVRPowerModel)
    for (l,i,j) in ref(pm,:arcs)
        set_start_value(var(pm,:cr)[(l,i,j)])
        set_start_value(var(pm,:ci)[(l,i,j)])
    end
    for l in ids(pm,:branch)
        set_start_value(var(pm,:csr)[l])
        set_start_value(var(pm,:csi)[l])
    end
end

function init_branch_vars(pm::IVRPowerModel, pm_solved::IVRPowerModel)
    for (l,i,j) in ref(pm,:arcs)
        JuMP.set_start_value(var(pm,:cr)[(l,i,j)], JuMP.value(var(pm_solved,:cr)[(l,i,j)]))
        JuMP.set_start_value(var(pm,:ci)[(l,i,j)], JuMP.value(var(pm_solved,:ci)[(l,i,j)]))
    end
    for l in ids(pm,:branch)
        JuMP.set_start_value(var(pm,:csr)[l], JuMP.value(var(pm_solved,:csr)[l]))
        JuMP.set_start_value(var(pm,:csi)[l], JuMP.value(var(pm_solved,:csi)[l]))
    end
end

"""
Initilize direct current branch variable values
"""

function init_dc_vars(pm::AbstractPowerModel)
    for arc in ref(pm,:arcs_dc)
        set_start_value(var(pm,:p_dc)[arc])
        set_start_value(var(pm,:q_dc)[arc])
    end
end

function init_dc_vars(pm::AbstractPowerModel, pm_solved::AbstractPowerModel)
    for arc in ref(pm,:arcs_dc)
        JuMP.set_start_value(var(pm,:p_dc)[arc], JuMP.value(var(pm_solved,:p_dc)[arc]))
        JuMP.set_start_value(var(pm,:q_dc)[arc], JuMP.value(var(pm_solved,:q_dc)[arc]))
    end
end

function init_dc_vars(pm::IVRPowerModel)
    for arc in ref(pm,:arcs_dc)
        set_start_value(var(pm,:crdc)[arc])
        set_start_value(var(pm,:cidc)[arc])
    end
end

function init_dc_vars(pm::IVRPowerModel, pm_solved::IVRPowerModel)
    for arc in ref(pm,:arcs_dc)
        JuMP.set_start_value(var(pm,:crdc)[arc], JuMP.value(var(pm_solved,:crdc)[arc]))
        JuMP.set_start_value(var(pm,:crdc)[arc], JuMP.value(var(pm_solved,:crdc)[arc]))
    end
end

"""
Initilize generation variable values
"""

function init_gen_vars(pm::AbstractPowerModel)
    for (i,gen) in ref(pm,:gen)
        set_start_value(var(pm,:pg)[i])
        set_start_value(var(pm,:qg)[i])
    end
end

function init_gen_vars(pm::AbstractPowerModel, pm_solved::AbstractPowerModel)
    for (i,gen) in ref(pm,:gen)
        JuMP.set_start_value(var(pm,:pg)[i], JuMP.value(var(pm_solved,:pg)[i]))
        JuMP.set_start_value(var(pm,:qg)[i], JuMP.value(var(pm_solved,:qg)[i]))
    end
end

function init_gen_vars(pm::IVRPowerModel)
    for (i,gen) in ref(pm,:gen)
        set_start_value(var(pm,:crg)[i])
        set_start_value(var(pm,:cig)[i])
    end
end

function init_gen_vars(pm::IVRPowerModel, pm_solved::IVRPowerModel)
    for (i,gen) in ref(pm,:gen)
        JuMP.set_start_value(var(pm,:crg)[i], JuMP.value(var(pm_solved,:crg)[i]))
        JuMP.set_start_value(var(pm,:crg)[i], JuMP.value(var(pm_solved,:crg)[i]))
    end
end

"""
Initilize voltage variable values
"""

function init_voltage_vars(pm::AbstractACPModel)
    for (i,bus) in ref(pm,:bus)
        set_start_value(var(pm,:va)[i])
        set_start_value(var(pm,:vm)[i])
    end
end

function init_voltage_vars(pm::AbstractACPModel, pm_solved::AbstractACPModel)
    for (i,bus) in ref(pm,:bus)
        JuMP.set_start_value(var(pm,:va)[i], JuMP.value(var(pm_solved,:va)[i]))
        JuMP.set_start_value(var(pm,:vm)[i], JuMP.value(var(pm_solved,:vm)[i]))
    end
end

function init_voltage_vars(pm::AbstractACRModel)
    for (i,bus) in ref(pm,:bus)
        set_start_value(var(pm,:vr)[i])
        set_start_value(var(pm,:vi)[i])
    end
end

function init_voltage_vars(pm::AbstractACRModel, pm_solved::AbstractACRModel)
    for (i,bus) in ref(pm,:bus)
        JuMP.set_start_value(var(pm,:vr)[i], JuMP.value(var(pm_solved,:vr)[i]))
        JuMP.set_start_value(var(pm,:vi)[i], JuMP.value(var(pm_solved,:vi)[i]))
    end
end

ext: jl

max_issues_repo_name: exanauts/ActiveSetMethods


text:
@testset "Status" begin
  vals = [1, 0, -1]
  @test Jtac.is_over(Jtac.Status()) == false
  @test Jtac.Status.(vals) .|> Jtac.is_over |> all
  @test Jtac.Status.(vals) == vals
  @test (Jtac.with_default.(Jtac.Status(), vals) .== vals) |> all
  @test Jtac.with_default.(Jtac.Status.(vals), Jtac.Status()) == vals
end

@testset "Augment" begin
  hmirror = Jtac.hmirror
  vmirror = Jtac.vmirror
  dmirror = Jtac.dmirror
  a = rand(25)
  ma = reshape(a, (5, 5))
  @test all(ma |> hmirror |> hmirror .== ma)
  @test all(ma |> vmirror |> vmirror .== ma)
  @test all(ma |> dmirror |> dmirror .== ma)
  for i in [1, 7, 15, 23]
    @test a[i] == reshape(hmirror(ma), (25,))[hmirror(i, (5,5))]
    @test a[i] == reshape(vmirror(ma), (25,))[vmirror(i, (5,5))]
    @test a[i] == reshape(dmirror(ma), (25,))[dmirror(i, (5,5))]
  end

end

@testset "TicTacToe" begin

  game = TicTacToe()
  @test size(TicTacToe) == size(game) == size(representation(game)) == (3, 3, 1)
  @test size(representation([game, game])) == (3, 3, 1, 2)
  @test policy_length(TicTacToe) == policy_length(game) == 9
  @test current_player(game) == 1
  @test_throws BoundsError apply_action!(game, -1)

  apply_action!(game, 5)
  @test legal_actions(game) == [ i for i in 1:9 if i != 5]
  @test current_player(game) == -1
  @test Jtac.random_action(game) in legal_actions(game)

  apply_action!(game, 3)
  @test .!Jtac.is_action_legal.(game, [3, 5]) |> all
  @test Jtac.is_action_legal.(game, legal_actions(game)) |> all
  @test Jtac.status(game) == Jtac.Status()
  @test copy(game).board == game.board
  @test_throws AssertionError apply_action!(game, 5)

  game = random_playout(game)
  @test legal_actions(game) == []
  @test Jtac.is_over(game) == Jtac.is_over(Jtac.status(game))

  games, policies = augment(game, rand(Float32, 10))
  @test length(games) == length(policies) == 8

end

max_stars_repo_name: roSievers/jtac


text:
@testset "Unit tests" begin
    @testset "requests.jl" begin
        @testset "_add_trailing_slash" begin
            @test FHIRClientJSON._add_trailing_slash(HTTP.URI("http://julialang.org")) == HTTP.URI("http://julialang.org/")
            @test FHIRClientJSON._add_trailing_slash(HTTP.URI("http://julialang.org/")) == HTTP.URI("http://julialang.org/")
        end
        @testset "_write_struct_request_body" begin
            @test FHIRClientJSON._write_struct_request_body(nothing) == nothing
            @test FHIRClientJSON._write_struct_request_body(JSON3.read("{}")) == "{}"
        end
    end
end


text:
module GR3

using Compat

import GR

const None = Union{}

macro triplet(t)
    :( Tuple{$t, $t, $t} )
end

type PNG
   s::Array{UInt8}
end
@compat Base.show(io::IO, ::MIME"image/png", x::PNG) = write(io, x.s)

type HTML
   s::AbstractString
end
@compat Base.show(io::IO, ::MIME"text/html", x::HTML) = print(io, x.s)

function _readfile(path)
    data = Array(UInt8, filesize(path))
    s = open(path, "r")
    Compat.String(read!(s, data))
end

type GR3Exception <: Exception
    msg::AbstractString
end
Base.showerror(io::IO, e::GR3Exception) = print(io, e.msg);

const msgs = [ "none", "invalid value", "invalid attribute", "init failed",
               "OpenGL error", "out of memory", "not initialized",
               "camera not initialized", "unknown file extension",
               "cannot open file", "export failed" ]

function _check_error()
  line = Cint[0]
  file = Ptr{UInt8}[0]
  error_code = ccall((:gr3_geterror, GR.libGR3), Int32, (Int32, Ptr{Cint}, Ptr{Ptr{UInt8}}), 1, line, file)
  if (error_code != 0)
    line = line[1]
    file = Compat.String(file[1])
    if 0 <= error_code < length(msgs)
      msg = msgs[error_code + 1]
    else
      msg = "unknown error"
    end
    message = string("GR3 error (", file, ", l. ", line, "): ", msg)
    throw(GR3Exception(message))
  end
end

function init(attrib_list)
  ccall((:gr3_init, GR.libGR3), Int32, (Ptr{Int}, ), attrib_list)
  _check_error()
end
export init

function free(pointer)
  ccall((:gr3_free, GR.libGR3), Void, (Ptr{Void}, ), pointer)
  _check_error()
end
export free

function terminate()
  ccall((:gr3_terminate, GR.libGR3), Void, ())
  _check_error()
end
export terminate

function getimage(width, height, use_alpha=true)
  bpp = use_alpha ? 4 : 3
  bitmap = zeros(UInt8, width * height * bpp)
  ccall((:gr3_getimage, GR.libGR3),
        Int32,
        (Int32, Int32, Int32, Ptr{UInt8}),
        width, height, use_alpha, bitmap)
  _check_error()
  return bitmap
end
export getimage

function save(filename, width, height)
  ccall((:gr3_export, GR.libGR3),
        Int32,
        (Ptr{Cchar}, Int32, Int32),
        filename, width, height)
  _check_error()
  ext = splitext(filename)[end:end][1]
  if ext == ".png"
    content = PNG(_readfile(filename))
  elseif ext == ".html"
    content = HTML(@sprintf("<iframe src=\"%s\" width=%d height=%d></iframe>", filename, width, height))
  else
    content = None
  end
  return content
end
export save

function getrenderpathstring()
  val = ccall((:gr3_getrenderpathstring, GR.libGR3),
              Ptr{UInt8}, (), )
  _check_error()
  Compat.String(val)
end
export getrenderpathstring

function drawimage(xmin, xmax, ymin, ymax, pixel_width, pixel_height, window)
  ccall((:gr3_drawimage, GR.libGR3),
        Int32,
        (Float32, Float32, Float32, Float32, Int32, Int32, Int32),
        xmin, xmax, ymin, ymax, pixel_width, pixel_height, window)
  _check_error()
end
export drawimage

function createmesh(n, vertices, normals, colors)
  mesh = Cint[0]
  _vertices = [ Float32(x) for x in vertices ]
  _normals = [ Float32(x) for x in normals ]
  _colors = [ Float32(x) for x in colors ]
  ccall((:gr3_createmesh, GR.libGR3),
        Int32,
        (Ptr{Cint}, Int32, Ptr{Float32}, Ptr{Float32}, Ptr{Float32}),
        mesh, n, convert(Vector{Float32}, _vertices), convert(Vector{Float32}, _normals), convert(Vector{Float32}, _colors))
  _check_error()
  return mesh[1]
end
export createmesh

function createindexedmesh(num_vertices, vertices, normals, colors, num_indices, indices)
  mesh = Cint[0]
  _vertices = [ Float32(x) for x in vertices ]
  _normals = [ Float32(x) for x in normals ]
  _colors = [ Float32(x) for x in colors ]
  _indices = [ Float32(x) for x in indices ]
  ccall((:gr3_createindexedmesh, GR.libGR3),
        Int32,
        (Ptr{Cint}, Int32, Ptr{Float32}, Ptr{Float32}, Ptr{Float32}, Int32, Ptr{Int32}),
        mesh, num_vertices, convert(Vector{Float32}, _vertices), convert(Vector{Float32}, _normals), convert(Vector{Float32}, _colors), num_indices, convert(Vector{Float32}, _indices))
  _check_error()
  return mesh[1]
end
export createindexedmesh

function drawmesh(mesh::Int32, n, positions::@triplet(Real), directions::@triplet(Real), ups::@triplet(Real), colors::@triplet(Real), scales::@triplet(Real))
  _positions = [ Float32(x) for x in positions ]
  _directions = [ Float32(x) for x in directions ]
  _ups = [ Float32(x) for x in ups ]
  _colors = [ Float32(x) for x in colors ]
  _scales = [ Float32(x) for x in scales ]
  ccall((:gr3_drawmesh, GR.libGR3),
        Void,
        (Int32, Int32, Ptr{Float32}, Ptr{Float32}, Ptr{Float32}, Ptr{Float32}, Ptr{Float32}),
        mesh, n, convert(Vector{Float32}, _positions), convert(Vector{Float32}, _directions), convert(Vector{Float32}, _ups), convert(Vector{Float32}, _colors), convert(Vector{Float32}, _scales))
  _check_error()
end
export drawmesh

function createheightmapmesh(heightmap, num_columns, num_rows)
  if num_columns * num_rows == length(heightmap)
    if ndims(heightmap) == 2
      heightmap = reshape(heightmap, num_columns * num_rows)
    end
    ccall((:gr3_createheightmapmesh, GR.libGR3),
          Void,
          (Ptr{Float32}, Int32, Int32),
          convert(Vector{Float32}, heightmap), num_columns, num_rows)
    _check_error()
  else
    println("Array has incorrect length or dimension.")
  end
end
export createheightmapmesh

function drawheightmap(heightmap, num_columns, num_rows, positions, scales)
  if num_columns * num_rows == length(heightmap)
    if ndims(heightmap) == 2
      heightmap = reshape(heightmap, num_columns * num_rows)
    end
    _positions = [ Float32(x) for x in positions ]
    _scales = [ Float32(x) for x in scales ]
    ccall((:gr3_drawheightmap, GR.libGR3),
          Void,
          (Ptr{Float32}, Int32, Int32, Ptr{Float32}, Ptr{Float32}),
          convert(Vector{Float32}, heightmap), num_columns, num_rows, convert(Vector{Float32}, _positions), convert(Vector{Float32}, _scales))
    _check_error()
  else
    println("Array has incorrect length or dimension.")
  end
end
export drawheightmap

function deletemesh(mesh)
  ccall((:gr3_deletemesh, GR.libGR3), Void, (Int32, ), mesh)
  _check_error()
end
export deletemesh

function setquality(quality)
  ccall((:gr3_setquality, GR.libGR3), Void, (Int32, ), quality)
  _check_error()
end
export setquality

function clear()
  ccall((:gr3_clear, GR.libGR3), Void, ())
  _check_error()
end
export clear

function cameralookat(camera_x, camera_y, camera_z,
                      center_x, center_y, center_z,
                      up_x, up_y, up_z)
  ccall((:gr3_cameralookat, GR.libGR3),
        Void,
        (Float32, Float32, Float32, Float32, Float32, Float32, Float32, Float32, Float32),
        camera_x, camera_y, camera_z, center_x, center_y, center_z, up_x, up_y, up_z)
  _check_error()
end
export cameralookat

function setcameraprojectionparameters(vertical_field_of_view, zNear, zFar)
  ccall((:gr3_setcameraprojectionparameters, GR.libGR3),
        Void,
        (Float32, Float32, Float32),
        vertical_field_of_view, zNear, zFar)
  _check_error()
end
export setcameraprojectionparameters

function setlightdirection(x, y, z)
  ccall((:gr3_setlightdirection, GR.libGR3),
        Void,
        (Float32, Float32, Float32),
        x, y, z)
  _check_error()
end
export setlightdirection

function drawcylindermesh(n, positions, directions, colors, radii, lengths)
  _positions = [ Float32(x) for x in positions ]
  _directions = [ Float32(x) for x in directions ]
  _colors = [ Float32(x) for x in colors ]
  _radii = [ Float32(x) for x in radii ]
  _lengths = [ Float32(x) for x in lengths ]
  ccall((:gr3_drawcylindermesh, GR.libGR3),
        Void,
        (Int32, Ptr{Float32}, Ptr{Float32}, Ptr{Float32}, Ptr{Float32}, Ptr{Float32}),
        n, convert(Vector{Float32}, _positions), convert(Vector{Float32}, _directions), convert(Vector{Float32}, _colors), convert(Vector{Float32}, _radii), convert(Vector{Float32}, _lengths))
  _check_error()
end
export drawcylindermesh

function drawconemesh(n, positions, directions, colors, radii, lengths)
  _positions = [ Float32(x) for x in positions ]
  _directions = [ Float32(x) for x in directions ]
  _colors = [ Float32(x) for x in colors ]
  _radii = [ Float32(x) for x in radii ]
  _lengths = [ Float32(x) for x in lengths ]
  ccall((:gr3_drawconemesh, GR.libGR3),
        Void,
        (Int32, Ptr{Float32}, Ptr{Float32}, Ptr{Float32}, Ptr{Float32}, Ptr{Float32}),
        n, convert(Vector{Float32}, _positions), convert(Vector{Float32}, _directions), convert(Vector{Float32}, _colors), convert(Vector{Float32}, _radii), convert(Vector{Float32}, _lengths))
  _check_error()
end
export drawconemesh

function drawspheremesh(n, positions, colors, radii)
  _positions = [ Float32(x) for x in positions ]
  _colors = [ Float32(x) for x in colors ]
  _radii = [ Float32(x) for x in radii ]
  ccall((:gr3_drawspheremesh, GR.libGR3),
        Void,
        (Int32, Ptr{Float32}, Ptr{Float32}, Ptr{Float32}),
        n, convert(Vector{Float32}, _positions), convert(Vector{Float32}, _colors), convert(Vector{Float32}, _radii))
  _check_error()
end
export drawspheremesh

function drawcubemesh(n, positions, directions, ups, colors, scales)
  _positions = [ Float32(x) for x in positions ]
  _directions = [ Float32(x) for x in directions ]
  _ups = [ Float32(x) for x in ups ]
  _colors = [ Float32(x) for x in colors ]
  _scales = [ Float32(x) for x in scales ]
  ccall((:gr3_drawcubemesh, GR.libGR3),
        Void,
        (Int32, Ptr{Float32}, Ptr{Float32}, Ptr{Float32}, Ptr{Float32}, Ptr{Float32}),
        n, convert(Vector{Float32}, _positions), convert(Vector{Float32}, _directions), convert(Vector{Float32}, _ups), convert(Vector{Float32}, _colors), convert(Vector{Float32}, _scales))
  _check_error()
end
export drawcubemesh

function setbackgroundcolor(red, green, blue, alpha)
  ccall((:gr3_setbackgroundcolor, GR.libGR3),
        Void,
        (Float32, Float32, Float32, Float32),
        red, green, blue, alpha)
  _check_error()
end
export setbackgroundcolor

function createisosurfacemesh(grid::Array{UInt16,3}, step::@triplet(Float64), offset::@triplet(Float64), isolevel::Int64)
  mesh = Cint[0]
  dim_x, dim_y, dim_z = size(grid)
  data = reshape(grid, dim_x * dim_y * dim_z)
  stride_x, stride_y, stride_z = strides(grid)
  step_x, step_y, step_z = [ float(x) for x in step ]
  offset_x, offset_y, offset_z = [ float(x) for x in offset ]
  err = ccall((:gr3_createisosurfacemesh, GR.libGR3),
              Int32,
              (Ptr{Cint}, Ptr{UInt16}, UInt16, Int32, Int32, Int32, Int32, Int32, Int32, Float64, Float64, Float64, Float64, Float64, Float64),
              mesh, convert(Vector{UInt16}, data), UInt16(isolevel), dim_x, dim_y, dim_z, stride_x, stride_y, stride_z, step_x, step_y, step_z, offset_x, offset_y, offset_z)
  _check_error()
  return mesh[1]
end
export createisosurfacemesh

function surface(px, py, pz, option::Int)
  nx = length(px)
  ny = length(py)
  nz = length(pz)
  if ndims(pz) == 1
    out_of_bounds = nz != nx * ny
  elseif ndims(pz) == 2
    out_of_bounds = size(pz)[1] != nx || size(pz)[2] != ny
  else
    out_of_bounds = true
  end
  if !out_of_bounds
    _px = [ Float32(x) for x in px ]
    _py = [ Float32(y) for y in py ]
    _pz = [ Float32(z) for z in pz ]
    ccall((:gr3_surface, GR.libGR3),
          Void,
          (Int32, Int32, Ptr{Float32}, Ptr{Float32}, Ptr{Float32}, Int32),
          nx, ny, convert(Vector{Float32}, _px), convert(Vector{Float32}, _py), convert(Vector{Float32}, _pz), option)
    _check_error()
  else
    println("Arrays have incorrect length or dimension.")
  end
end

IA_END_OF_LIST = 0
IA_FRAMEBUFFER_WIDTH = 1
IA_FRAMEBUFFER_HEIGHT = 2

ERROR_NONE = 0
ERROR_INVALID_VALUE = 1
ERROR_INVALID_ATTRIBUTE = 2
ERROR_INIT_FAILED = 3
ERROR_OPENGL_ERR = 4
ERROR_OUT_OF_MEM = 5
ERROR_NOT_INITIALIZED = 6
ERROR_CAMERA_NOT_INITIALIZED = 7
ERROR_UNKNOWN_FILE_EXTENSION = 8
ERROR_CANNOT_OPEN_FILE = 9
ERROR_EXPORT = 10

QUALITY_OPENGL_NO_SSAA  = 0
QUALITY_OPENGL_2X_SSAA  = 2
QUALITY_OPENGL_4X_SSAA  = 4
QUALITY_OPENGL_8X_SSAA  = 8
QUALITY_OPENGL_16X_SSAA = 16
QUALITY_POVRAY_NO_SSAA  = 0+1
QUALITY_POVRAY_2X_SSAA  = 2+1
QUALITY_POVRAY_4X_SSAA  = 4+1
QUALITY_POVRAY_8X_SSAA  = 8+1
QUALITY_POVRAY_16X_SSAA = 16+1

DRAWABLE_OPENGL = 1
DRAWABLE_GKS = 2

SURFACE_DEFAULT     =  0
SURFACE_NORMALS     =  1
SURFACE_FLAT        =  2
SURFACE_GRTRANSFORM =  4
SURFACE_GRCOLOR     =  8
SURFACE_GRZSHADED   = 16

end # module


text:
using Documenter

using Waterfall

if haskey(ENV, "DOCSARGS")
    for arg in split(ENV["DOCSARGS"])
        (arg in ARGS) || push!(ARGS, arg)
    end
end

DocMeta.setdocmeta!(Waterfall, :DocTestSetup, :(using Waterfall, DataFrames); recursive=true)

# Now, generate the documentation.
makedocs(clean = true,
    modules = [Waterfall],
    format = Documenter.HTML(
        mathengine = Documenter.MathJax(),
        prettyurls = get(ENV, "CI", nothing) == "true",
    ),
    sitename = "Waterfall.jl",
    authors = "Caroline L. Hughes",
    # workdir = "../",
    pages = [
        "Home" => "index.md",
        "Data Generation" => Any[
            "Architecture" => "man/data/overview.md",
            "Distribution" => "man/data/distribution.md",
            "Correlation" =>  "man/data/correlation.md",
        ],
        "API" => "api/functions.md",
    ]
)

# deploydocs(
#     repo = "https://github.com/NREL/SLiDE.git",
#     target = "build",
#     branch = "gh-pages",
#     devbranch = "docs",
#     devurl = "dev",
#     versions = ["stable" => "v^", "v#.#"],
# )


text:
@recipe function f(::Type{Val{:vector}}, x, y, z;
        headlength = 0.1, headwidth = 0.05 )
    origin = x
    vector = y
    target = origin + vector
    hl = headlength
    hw = headwidth
    T = eltype(origin)
    eX = CartesianVector{T}(1,0,0)
    eY = CartesianVector{T}(0,1,0)
    eZ = CartesianVector{T}(0,0,1)
    apxl = target - hl*vector - hw * normalize(vector × eX) * norm(vector)
    apxr = target - hl*vector + hw * normalize(vector × eX) * norm(vector)
    apyl = target - hl*vector - hw * normalize(vector × eY) * norm(vector)
    apyr = target - hl*vector + hw * normalize(vector × eY) * norm(vector)
    apzl = target - hl*vector - hw * normalize(vector × eZ) * norm(vector)
    apzr = target - hl*vector + hw * normalize(vector × eZ) * norm(vector)

    label --> nothing
    linecolor --> :black
    xguide --> "x"
    yguide --> "y"
    zguide --> "z"
    unitformat --> :slash
    if occursin("GRBackend", string(typeof(plotattributes[:plot_object].backend)))
        aspect_ratio --> 1.0
    end
    x := [origin[1], target[1], apxl[1], target[1], apxr[1], target[1], apyl[1], target[1], apyr[1], target[1], apzl[1], target[1], apzr[1]]*internal_length_unit
    y := [origin[2], target[2], apxl[2], target[2], apxr[2], target[2], apyl[2], target[2], apyr[2], target[2], apzl[2], target[2], apzr[2]]*internal_length_unit
    z := [origin[3], target[3], apxl[3], target[3], apxr[3], target[3], apyl[3], target[3], apyr[3], target[3], apzl[3], target[3], apzr[3]]*internal_length_unit
    seriestype := :path3d
    ()
end

@recipe function f(v::CartesianVector{T}) where {T}
    @series begin
        seriestype --> :vector
        label --> nothing
        CartesianPoint{T}(0,0,0), v
    end
end


text:
#==
const all = '∀'
const exist = '∃'
const dot = '.'
const lpar = '('
const rpar = ')'
const land = '∧'
const lor  = '∨'
const imp  = '⇒'
const eqv  = '≡'
const neg  = '¬'

const fpos = :+
const fneg = :-
const fall = :all
const fexist = :exist
const fimp = :imply
const feqv = :equiv
const and  = :and
const or   = :or
==#

max_stars_repo_name: sazare/cheapViews

max_issues_repo_name: sazare/cheapViews

max_forks_repo_name: sazare/cheapViews


text:
function UTCTAIHistoryFilesLoader()
    return UTCTAIHistoryFilesLoader(())
end

function UTCTAIHistoryFilesLoader(arg0::DataProvidersManager)
    return UTCTAIHistoryFilesLoader((DataProvidersManager,), arg0)
end

function load_offsets(obj::UTCTAIHistoryFilesLoader)
    return jcall(obj, "loadOffsets", List, ())
end


text:
"""
gmres_test.jl

Tests the linear GMRES code, kl_gmres.

This is for CI only. Nothing to see here. Move along.
"""

function gmres_test()
    pass3 = test3x3()
    passint = test_integop(40)
    passint_rs = test_integop_restart(40)
    passr1 = testR1()
    passorth = orth_test()
    passqr = qr_test()
    passgm = pass3 && passint && passr1 && passint_rs
    return passgm
end

"""
test3x3()

Do the nasty problem in Float64 or Float32. When you orthogonalize in Float32,
the iteration thinks it's ok and is wrong.
"""
function test3x3()
    A = [0.001 0 0; 0 0.0011 0; 0 0 1.e4];
    V = zeros(3, 10);
    V32= zeros(Float32,3, 10);
    b = [1.0; 1.0; 1.0];
    x0 = zeros(3);
    eta = 1.e-10
    passgm = true
    rightsize = [10, 6, 5, 4]
    rightsize32 = [10, 7, 7, 3]
    Methods = ("cgs1", "mgs1", "mgs2", "cgs2")
    TestC = (false, true, true, true)
    i = 1
    kl_store=kstore(3,"gmres")
    kl_store32=kstore(3,"gmres")
    tol=1.e-10
    tol32=1.e-7
    lhistpass=true
    ididpass=true
    locpass=true
    for orth in Methods
        gout = kl_gmres(x0, b, atv, V, tol; pdata = A, orth = orth,
                       kl_store=kl_store)
        resnorm = norm(A * gout.sol - b)
# If I don't have separate kl_stores then the gout.sol is overwritten.
# I will fix this at some point. For now, only the nonlinear solvers really
# use kl_store.
        gout32 = kl_gmres(x0, b, atv, V32, tol32; pdata = A, orth = orth,
                       kl_store=kl_store32)
        ithist = gout.reshist
        ithist32 = gout32.reshist
        lhist = length(ithist)
        lhist32 = length(ithist32)
        lhistpass = lhistpass && (lhist == rightsize[i])
        lhistpass = lhistpass && (lhist32 == rightsize32[i])
        ididpass = ididpass && (gout.idid == TestC[i])
        ididpass = ididpass && (gout32.idid == TestC[i])
        resnormx = norm(A * gout.sol - b)
        resnorm32 = norm(A * gout32.sol - b)
        locpass = (resnorm < 1.e-8) && (resnorm32 > .1)
println(lhistpass,"  ",ididpass,"  ",locpass)
println(resnorm,"  ",resnorm32,"  ",resnormx,"  ",norm(c-gout.sol))
# For the Float32 computation, the iteration terminates with success, but
# the real residual is bad.
println(lhistpass,"  ",ididpass,"  ",locpass)
        locpass || println(
            "failure at orth = ",
            orth,
            ", lhist = ",
            lhist,
            ", Res norm = ",
            resnorm,
        )
        passgm = passgm && locpass && lhistpass && ididpass
        i += 1
    end
    #    return (pass = passgm, RH = R)
    return passgm
end

function testR1()
    A = Float64.([1 2 3 4 5])
    E = A' * A
    A = I + E
    b = ones(5)
    x0 = zeros(5)
    V = zeros(5, 4)
    gout = kl_gmres(x0, b, atv, V, 1.e-7; pdata = A)
    lhist = length(gout.reshist)
    nerr = norm(A * gout.sol - b, Inf)
    pass = (lhist == 3) && (nerr < 1.e-14)
    pass || println("Rank one test fails")
    return pass
end

function test_integop(n)
    pdata = integopinit(n)
    f = pdata.f
    ue = pdata.xe
    u0 = zeros(size(f))
    V = zeros(n, 20)
    Methods = ("cgs1", "mgs1", "mgs2", "cgs2")
    pass = true
#
# run through the orthogonalizers
#
    for orth in Methods
        goutinteg = kl_gmres(u0, f, integop, V, 1.e-10; pdata = pdata, orth = orth)
        errn = norm(goutinteg.sol - ue, Inf)
        rhist = goutinteg.reshist
        lhist = length(rhist)
        rred = rhist[4] ./ rhist[1]
        lpass = (errn < 1.e-14) && (rred < 1.e-14) && (lhist == 4)
        lpass || println("Failure with orth = ", orth)
        pass = pass && lpass
    end
#
#  force a failure
#
    failout=kl_gmres(u0, f, integop, V, 1.e-10; pdata = pdata, lmaxit=2);
    pass = pass && ~failout.idid
    pass || println("Integral operator test fails.")
    return pass
end

#
# Test integral equation with restarted GMRES
#
function test_integop_restart(n)
    pdata = integopinit(n)
    f = pdata.f
    ue = pdata.xe
    u0 = zeros(size(f))
    V = zeros(n, 3); V32 = zeros(Float32, n, 3)
    gout = kl_gmres(u0, f, integop, V, 1.e-10; pdata = pdata, lmaxit=20);
    gout32 = kl_gmres(u0, f, integop, V32, 1.e-10; pdata = pdata, lmaxit=20);
    dhist=norm(gout.reshist-gout32.reshist,Inf);
    lhist=length(gout.reshist)
    gerr=norm(gout.sol-pdata.xe,Inf)
    g32err=norm(gout32.sol-pdata.xe,Inf)
    histpass = dhist < 2.e-7
    histpass || println("restart history wrong size = ",dhist)
    errpass = (gerr < 1.e-10) && (g32err < 1.e-10)
    errpass || println("restart error too large")
    lenpass = (lhist == 6)
    lenpass || println("restart history wrong length")
    return histpass && errpass && lenpass
end

function atv(x, A)
    return A * x
end

function integop(u, pdata)
    K = pdata.K
#    f = pdata.f
    return u - K * u
end

function integopinit(n)
    h = 1 / n
    X = collect(0.5*h:h:1.0-0.5*h)
    K = [ker(x, y) for x in X, y in X]
    #    K = zeros(n, n)
    #    for j = 1:n
    #        for i = 1:n
    #            K[i, j] = ker(x[i], x[j])
    #        end
    #    end
    K .*= h
    #    sol = exp.(x) .* log.(2.0 * x .+ 1.0)
    #    sol = usol.(X)
    sol = [usol(x) for x in X]
    f = sol - K * sol
    pdata = (K = K, xe = sol, f = f)
    return pdata
end

function usol(x)
    return exp.(x) .* log.(2.0 * x .+ 1.0)
end

function ker(x, y)
    ker = 0.1 * sin(x + exp(y))
end

"""
orth_test()

Used for CI to make sure the orthogonalizers do what I expect.
"""
function orth_test()
    A = collect(0.01:0.01:0.25)
    A = reshape(A, 5, 5)
    A = I - A
    B = Float32.(A)
    C = Float16.(A)
    pass64 = qr_test(A, 4.e-16)
    pass32 = qr_test(B, 2.e-7)
    pass16 = qr_test(C, 2.e-3)
    return pass64 && pass32 && pass16
end

function qr_test(A = rand(3, 3), tol = 1.e-13)
    OM = ("mgs1", "mgs2", "cgs1", "cgs2")
    T = eltype(A)
    passqr = true
    for orth in OM
        C = copy(A)
        (Q, R) = qrctk!(C, orth)
        fres = norm(Q * R - A, Inf) / norm(A, Inf)
        ores = norm(Q' * Q - I, Inf)
        npass = fres + ores
        #println(eltype(Q)," ",eltype(R),"  ",typeof(npass)," ",
        #        orth, "   ", npass)
        pass = (npass < tol)
        pass || println(
            "qr_test fails with precision = ",
            T,
            ", method = ",
            orth,
            "error = ",
            npass,
        )
        passqr = passqr && pass
    end
    passqr
end

function qrctk!(A, orth = "cgs2")
    T = typeof(A[1, 1])
    (m, n) = size(A)
    R = zeros(T, n, n)
    @views R[1, 1] = norm(A[:, 1])
    @views A[:, 1] /= R[1, 1]
    @views for k = 2:n
        hv = vec(R[1:k, k])
        Qkm = view(A, :, 1:k-1)
        vv = vec(A[:, k])
        Orthogonalize!(Qkm, hv, vv, orth)
    end
    return (Q = A, R = R)
end


text:
"computes the fraunhofer pattern only considering the states inside the parent gap using
exact diagonalization"
fraunhofer_abs_exact(Bperp::Array{T,1}, p; kw...) where {T} =
    fraunhofer_abs_exact(Bperp, p, missing; kw...)
function fraunhofer_abs_exact(Bperp::Array{T,1}, p,
        Δϕ::Union{Array{T,1}, Missing}; kw...) where {T}
    println("computing current matrix...")
    icmax = SharedArray(similar(Bperp))
    ic = icϕ_exactdiag(Bperp, p, Δϕ; kw...)
    for i in 1:length(Bperp)
        println("it: ", i/length(Bperp))
        icmax[i] = maximum(abs.(ic[:, i]))
    end
    return Bperp, icmax, ic
end

function fraunhofer_abs_exact_adaptive(Bperplist, p; kw...)
    icmax = maxicϕ_exactdiag(Bperplist, p; kw...)
    return Bperp, icmax
end

"""
    `icϕ_exactdiag(Bperplist::Array{T,1}, p, Δϕ::Union{Array{T,1}, Missing}; kw...)`
supercurrent sweep with both Bperp and Δϕ. See: `supercurrent_exactdiag()`
"""
function icϕ_exactdiag(Bperplist::Array{T,1}, p; kw...) where {T}
    # Δϕlist = ifelse(isa(Δϕ, Missing) == true, -0.5:.5:π+0.5, Δϕ)
    Δϕlist = collect(-0.5:.5:π+0.5)
    I = zeros(Float64, length(Δϕlist), length(Bperplist))
    [I[:, i] = supercurrent_exactdiag(collect(Δϕlist),
        reconstruct(p, B = SA[0,0,Bperplist[i]]); kw...) for i in 1:length(Bperplist)]
    return [maximum(abs.(I[:,i])) for i in 1:length(Bperplist)]
end

"""
    `maxicϕ_exactdiag(Bperplist::Array{T,1}, p, Δϕ::Union{Array{T,1}, Missing}; kw...)`
computes the Ic_optim = max(Ic, ϕ) using a ML K-cross validation search algorithm for the
minimum. See: `adaptive_max_finder.jl`
"""
function maxicϕ_exactdiag(Bperplist::Array{T,1}, p; mask = true, Δx_mask = 20, Δy_mask = 20,
    kw...) where {T}
    icmax = SharedArray(similar(Bperplist))
    @sync @distributed for i in 1:length(Bperplist)
        hpar = rectangle_weaklink(reconstruct(p, B = SA[0,0, Bperplist[i]]),
            false, mask, Δx_mask = Δx_mask, Δy_mask = Δy_mask)

        gen_model(x::Array, hp; kw...) =
            supercurrent_exactdiag_adaptive(x, hp; kw...)  #not sure if p is being updated as it should
        gen_model(x::Array, f::Array, xmax::Number, hp; kw...) =
            supercurrent_exactdiag_adaptive(x, f, xmax, hp; kw...)

        icmax[i] = adaptive_max_finder(gen_model, fourier_model, hpar; kw)[1]
    end
    return icmax
end

"""
    `supercurrent_exactdiag(Δϕlist, p = Params() ; nev = 10)`
Computes the supercurrent for a fixed Bperp value specified in p. If `nev::Missing` it
iteratively finds all ABS (i.e. with energies inside a lengthscale which we set us the gap).
It returns the supercurrent contribution of these subgap subspace. Note that this subspace
is chosen to always capture all the ABS contribution although it may contain also continuum
states, because the parent gap will be larger that the induced gap. However, once the
subspace is specified, we can always substract this contribution for the full KPM
contribution.
    `method = :free_energy`
"""

supercurrent_exactdiag(Δϕlist, p = Params()::Params; mask = true, Δx_mask = 20, Δy_mask = 20, kw...) =
    supercurrent_exactdiag(Δϕlist, rectangle_weaklink(p, false, mask, Δx_mask = Δx_mask, Δy_mask = Δy_mask); kw...)

function supercurrent_exactdiag(Δϕlist, hpar::Quantica.ParametricHamiltonian; kw...)
    f = SharedArray(zeros(Float64, length(Δϕlist)))
    @sync @distributed for i in 1:length(Δϕlist)
        println(i/length(Δϕlist))
        f[i] = f_e(hpar, Δϕlist[i]; kw...)
    end
    ip = interpolate((Δϕlist,), f, Gridded(Linear()));
    deriv =[Interpolations.gradient(ip, i)[1] for i in Δϕlist]
    return @. 2/ħoec .* deriv
end

"""
`supercurrent_exactdiag_adaptive()`
Same as `supercurrent_exactdiag()` but for the fact it uses the adaptive_max_finder approach
instead of a sweep in SC phase differences.
 See: `adaptive_max_finder.jl`
"""

function supercurrent_exactdiag_adaptive(ϕ, f, ϕnew, hpar::Quantica.ParametricHamiltonian; kw...)
    fnew = f_e(hpar, ϕnew; kw...)
    ϕn = vcat(ϕ, ϕnew)
    fn = vcat(f, fnew)
    perm = sortperm(ϕn)
    ϕn = ϕn[perm]
    fn = fn[perm]
    newindex = findall(x-> x == ϕnew, ϕn)[1]
    ip = interpolate((ϕn,), fn, Gridded(Linear()));
    deriv =[Interpolations.gradient(ip, i)[1] for i in ϕn] # check if the returned index Ic# is the correct one
    return fnew, @. 2/ħoec * deriv[newindex]
end

function supercurrent_exactdiag_adaptive(Δϕlist, hpar::Quantica.ParametricHamiltonian; kw...)
    f = zeros(Float64, length(Δϕlist))
    for i in 1:length(Δϕlist)
        println("init phases: ", i/length(Δϕlist))
        f[i] = f_e(hpar, Δϕlist[i]; kw...)
    end
    ip = interpolate((Δϕlist,), f, Gridded(Linear()));
    deriv =[Interpolations.gradient(ip, i)[1] for i in Δϕlist]
    return Δϕlist, f, @. 2/ħoec .* deriv
end

"""
returns the free energy computed using the exact eigenvalues for the exact evaluation of
the supercurrent over a finite set of eigenvectors
"""
f_e(hpar::Quantica.ParametricHamiltonian, Δϕ; kw...) = -sum(negative_eigen(hpar, Δϕ))

"""
returns the NEGATIVE eigenvalues withing the gap using for the exact supercurrent
calculation an adaptive procedure for setting the number of nevs calculated with the shift
invert method
"""
function negative_eigen(hpar, Δϕ)
    sp = spectrum(hpar(ϕ = Δϕ))#, method = ArpackPackage(nev = 300,sigma = 0.00001im)) #104 sigma = -0.001im
    # sp = DACPdiagonaliser(hpar(ϕ = Δϕ), 0.1)
    λ = real(sp.energies)
    λneg = λ[λ.<=0];
    return λneg
end


text:
function choice_gradients(trace::VectorTrace{MapType,T,U}, selection::Selection,
                        retval_grad) where {T,U}

    args = get_args(trace)
    n_args = length(args)
    len = length(args[1])

    has_grads = has_argument_grads(trace.gen_fn.kernel)
    arg_grad = Vector(undef, n_args)
    for (i, has_grad) in enumerate(has_grads)
        if has_grad
            arg_grad[i] = Vector(undef, len)
        else
            arg_grad[i] = nothing
        end
    end

    value_choices = choicemap()
    gradient_choices = choicemap()

    for key=1:len
        subtrace = trace.subtraces[key]
        sub_selection = selection[key]
        kernel_retval_grad = (retval_grad == nothing) ? nothing : retval_grad[key]
        (kernel_arg_grad::Tuple, kernel_value_choices, kernel_gradient_choices) = choice_gradients(
            subtrace, sub_selection, kernel_retval_grad)
        set_submap!(value_choices, key, kernel_value_choices)
        set_submap!(gradient_choices, key, kernel_gradient_choices)
        for (i, grad, has_grad) in zip(1:n_args, kernel_arg_grad, has_grads)
            if has_grad
                arg_grad[i][key] = grad
            end
        end
    end
    ((arg_grad...,), value_choices, gradient_choices)
end

function accumulate_param_gradients!(trace::VectorTrace{MapType,T,U}, retval_grad) where {T,U}

    args = get_args(trace)
    n_args = length(args)
    len = length(args[1])

    has_grads = has_argument_grads(trace.gen_fn.kernel)
    arg_grad = Vector(undef, n_args)
    for (i, has_grad) in enumerate(has_grads)
        if has_grad
            arg_grad[i] = Vector(undef, len)
        else
            arg_grad[i] = nothing
        end
    end

    for key=1:len
        subtrace = trace.subtraces[key]
        kernel_retval_grad = (retval_grad == nothing) ? nothing : retval_grad[key]
        kernel_arg_grad::Tuple = accumulate_param_gradients!(subtrace, kernel_retval_grad)
        for (i, grad, has_grad) in zip(1:n_args, kernel_arg_grad, has_grads)
            if has_grad
                arg_grad[i][key] = grad
            end
        end
    end
    (arg_grad...,)
end

max_stars_repo_name: georgematheos/Gen

max_issues_repo_name: georgematheos/Gen

max_forks_repo_name: georgematheos/Gen


text:
using Test
using Unitful
using UnitfulAtomic

siunits = (u"m", u"kg", u"s", u"A", u"K", # base units
           u"Hz", u"N", u"Pa", u"J", u"W", u"C", u"V", u"Ω", u"S", u"F", u"H", u"T", u"Wb", u"Sv",
           u"J*s", u"J/K", u"kg*m/s", u"N/m^2", u"V/m", u"V*s/m^2", u"C*m^2")

atomicunits = (u"me_au", u"e_au", u"ħ_au", u"k_au", u"a0_au", # base units
               u"Eh_au", u"ħ_au/a0_au", u"ħ_au/Eh_au")

otherunits = (u"μ_N", u"Ry", u"°", NoUnits)

@testset "aunit" begin
    for u in (siunits..., otherunits...)
        @test dimension(u) ≡ dimension(aunit(u))
        @test aunit(1u) ≡ aunit(u) ≡ aunit(dimension(u))
        @test aunit(u) ≡ aunit(aunit(u))
    end
    for u in atomicunits
        @test aunit(u) ≡ u
    end
    @test aunit(u"a0_au^2*me_au*Eh_au^2/ħ_au^2") ≡ u"Eh_au"
end

unity = (1, u"me", u"q", u"ħ", u"1/(4π*ε0)", u"k", 2u"Ry", 2u"μB")

@testset "Atomic units" begin
    for q in unity
        @test austrip(q) ≈ 1
        @test auconvert(unit(q), 1) ≈ q
    end
    for u in atomicunits
        @test austrip(1u) ≈ 1
        @test auconvert(u, 1) ≈ 1u
    end
    # CODATA 2018 values
    @test austrip(u"c0") ≈ 137.035_999_084
    for (si,au) in ((3.206_361_3061e-53u"C^3*m^3*J^-2",   u"e_au^3*a0_au^3/Eh_au^2"), # 1st hyperpolarizability
                    (6.235_379_9905e-65u"C^4*m^4*J^-3",   u"e_au^4*a0_au^4/Eh_au^3"), # 2nd hyperpolarizability
                    (1.054_571_817e-34u"J*s",             u"ħ_au"),                   # action
                    (1.602_176_634e-19u"C",               u"e_au"),                   # charge
                    (1.081_202_384_57e+12u"C*m^-3",       u"e_au/a0_au^3"),           # charge density
                    (6.623_618_237_510e-3u"A",            u"e_au*Eh_au/ħ_au"),        # current
                    (8.478_353_6255e-30u"C*m",            u"e_au*a0_au"),             # electric dipole moment
                    (5.142_206_757_63e+11u"V*m^-1",       u"Eh_au/e_au/a0_au"),       # electric field
                    (9.717_362_4292e+21u"V*m^-2",         u"Eh_au/e_au/a0_au^2"),     # electric field gradient
                    (1.648_777_274_36e-41u"C^2*m^2*J^-1", u"e_au^2*a0_au^2/Eh_au"),   # electric polarizability
                    (27.211_386_245_988u"V",              u"Eh_au/e_au"),             # electric potential
                    (4.486_551_5246e-40u"C*m^2",          u"e_au*a0_au^2"),           # electric quadrupole moment
                    (4.359_744_722_2071e-18u"J",          u"Eh_au"),                  # energy
                    (8.238_723_4983e-8u"N",               u"Eh_au/a0_au"),            # force
                    (5.291_772_109_03e-11u"m",            u"a0_au"),                  # length
                    (1.854_802_015_66e-23u"J*T^-1",       u"ħ_au*e_au/me_au"),        # magnetic dipole moment
                    (2.350_517_567_58e+5u"T",             u"ħ_au/e_au/a0_au^2"),      # magnetic flux density
                    (7.891_036_6008e-29u"J*T^-2",         u"e_au^2*a0_au^2/me_au"),   # magnetizability
                    (9.109_383_7015e-31u"kg",             u"me_au"),                  # mass
                    (1.992_851_914_10e-24u"kg*m*s^-1",    u"ħ_au/a0_au"),             # momentum
                    (1.112_650_055_45e-10u"F*m^-1",       u"e_au^2/a0_au/Eh_au"),     # permittivity
                    (2.418_884_326_5857e-17u"s",          u"ħ_au/Eh_au"),             # time
                    (2.187_691_263_64e+6u"m*s^-1",        u"a0_au*Eh_au/ħ_au"))       # velocity
        @eval @test aunit($si) ≡ $au
        @eval @test auconvert($si) ≈ 1*$au
    end
end

@testset "Aliases" begin
    @test u"hartree" ≡ u"Eh_au"
    @test 1.0u"hartree" ≡ 1.0u"Eh_au"
    @test u"bohr" ≡ u"a0_au"
    @test 1.0u"bohr" ≡ 1.0u"a0_au"
end

@testset "Conversion" begin
    for q in (2.818e-15u"m", 9.81u"m/s^2", 1u"Ry")
        @test austrip(q) == ustrip(auconvert(q))
        @test auconvert(unit(q), austrip(q)) ≈ q
    end
    for number in (2, 1.5, 3//2, big(π))
        @test aunit(number) ≡ NoUnits
        @test auconvert(number) == number
        @test austrip(number) == number
    end
end

@testset "Type inference" begin
    for q in (1u"m", 1.0u"J", 3//2*u"C*m^2")
        @test @inferred(aunit(q)) ≡ aunit(q)
        @test @inferred(auconvert(q)) ≡ auconvert(q)
        @test @inferred(auconvert(unit(q), ustrip(q))) ≡ auconvert(unit(q), ustrip(q))
        @test @inferred(austrip(q)) ≡ austrip(q)
    end
end

@dimension 𝛁 "𝛁" TestDim
@refunit ∇ "∇" TestUnit 𝛁 false

@testset "Unsupported dimensions" begin
    for u in (∇, u"cd", u"mol", u"g/mol")
        @test_throws ArgumentError aunit(dimension(u))
        @test_throws ArgumentError aunit(u)
        @test_throws ArgumentError aunit(1.0u)
        @test_throws ArgumentError auconvert(1.0*∇)
        @test_throws ArgumentError auconvert(∇, 1.0)
        @test_throws ArgumentError austrip(1.0*∇)
    end
end


text:
using SparseArrays

"""
    σ⁰

The 2×2 unit matrix.

# Examples
```julia-repl
julia> σ⁰
2×2 SparseMatrixCSC{Complex{Float64},Int64} with 2 stored entries:
 [1, 1]  =  1.0+0.0im
 [2, 2]  =  1.0+0.0im
```
"""
const σ⁰ = sparse([1.0+0.0im 0.0; 0.0 1.0+0.0im])

"""
    σˣ

``x``-component of the Pauli matrix, ``\\sigma^x``.

# Examples
```julia-repl
julia> σˣ
2×2 SparseMatrixCSC{Complex{Float64},Int64} with 2 stored entries:
  [2, 1]  =  1.0+0.0im
  [1, 2]  =  1.0+0.0im
```
"""
const σˣ = sparse([0.0 1.0+0.0im; 1.0+0.0im 0.0])

"""
    σʸ

``y``-component of the Pauli matrix, ``\\sigma^y``.

# Examples
```julia-repl
julia> σʸ
2×2 SparseMatrixCSC{Complex{Float64},Int64} with 2 stored entries:
  [2, 1]  =  0.0+1.0im
  [1, 2]  =  -0.0-1.0im
```
"""
const σʸ = sparse([0.0 -1.0im; 1.0im 0.0])

"""
    σᶻ

``z``-component of the Pauli matrix, ``\\sigma^z``.

# Examples
```julia-repl
julia> σᶻ
2×2 SparseMatrixCSC{Complex{Float64},Int64} with 2 stored entries:
  [1, 1]  =  1.0+0.0im
  [2, 2]  =  -1.0+0.0im
```
"""
const σᶻ = sparse([1.0+0.0im 0.0; 0.0 -1.0+0.0im])

const P⁰ = sparse([1.0+0.0im 0.0; 0.0 0.0])

const P¹ = sparse([0.0 0.0; 0.0 1.0+0.0im])

const Had = sparse([1.0+0.0im 1.0; 1.0 -1.0])/sqrt(2)

const Smat = sparse([1.0+0.0im 0.0; 0.0 1.0im])

const Tmat = sparse([1.0+0.0im 0.0; 0.0 exp(1.0im*π/4)])

function Rˣmat(θ)
    sparse([cos(θ/2) -1.0im*sin(θ/2); -1.0im*sin(θ/2) cos(θ/2)])
end

function Rʸmat(θ)
    sparse([cos(θ/2)+0.0im -sin(θ/2); sin(θ/2) cos(θ/2)])
end

function Rᶻmat(θ)
    sparse([exp(-1.0im*θ/2) 0.0; 0.0 exp(1.0im*θ/2)])
end


text:
export scheduled

# TODO: documentation

import Base: show

struct ScheduledActor{L, H, A} <: Actor{L}
    scheduler :: H
    actor     :: A
end

on_next!(actor::ScheduledActor{L}, data::L) where L = next!(actor.actor, data, actor.scheduler)
on_error!(actor::ScheduledActor, err)               = error!(actor.actor, err, actor.scheduler)
on_complete!(actor::ScheduledActor)                 = complete!(actor.actor, actor.scheduler)

struct ScheduledSource{L, H <: AbstractScheduler, S} <: ScheduledSubscribable{L}
    source    :: S
    scheduler :: H
end

getscheduler(observable::ScheduledSource) = observable.scheduler

function on_subscribe!(source::ScheduledSource{L}, actor::A, scheduler::H) where { L, A, H }
    return subscribe!(source.source, ScheduledActor{L, H, A}(scheduler, actor))
end

Base.show(io::IO, ::ScheduledSource{L, H}) where { L, H } = print(io, "ScheduledSource($L, $H)")
Base.show(io::IO, ::ScheduledActor{L, H})  where { L, H } = print(io, "ScheduledActor($L, $H)")

scheduled(source::S, scheduler::H) where { S, H <: AbstractScheduler } = as_scheduled(as_subscribable(S), source, scheduler)

as_scheduled(::InvalidSubscribableTrait,      source, scheduler)                         = throw(InvalidSubscribableTraitUsageError(source))
as_scheduled(::SimpleSubscribableTrait{L},    source::S, scheduler::H) where { L, H, S } = ScheduledSource{L, H, S}(source, scheduler)
as_scheduled(::ScheduledSubscribableTrait{L}, source::S, scheduler::H) where { L, H, S } = ScheduledSource{L, H, S}(source, scheduler)

as_scheduled(::SimpleSubscribableTrait,    source, scheduler::AsapScheduler) = source
as_scheduled(::ScheduledSubscribableTrait, source, scheduler::AsapScheduler) = source


text:
using Documenter
using PEPOKit

makedocs(sitename="PEPOKit.jl")

deploydocs(
    repo = "github.com/jack-dunham/PEPOKit.git",
)

max_stars_repo_name: jack-dunham/PEPOKit

max_issues_repo_name: jack-dunham/PEPOKit

max_forks_repo_name: jack-dunham/PEPOKit