licenses
sequencelengths 1
3
| version
stringclasses 677
values | tree_hash
stringlengths 40
40
| path
stringclasses 1
value | type
stringclasses 2
values | size
stringlengths 2
8
| text
stringlengths 25
67.1M
| package_name
stringlengths 2
41
| repo
stringlengths 33
86
|
---|---|---|---|---|---|---|---|---|
[
"MIT"
] | 1.0.0 | f39ffb3c8e62a54a0f0be44742c99748ec492ff1 | code | 4698 | using LinearAlgebra
export Ω, A_generate, transform_list, shift, w_gen, transform_coordinates, transform_back
"""
Ω(masses::Array)
Calculate the Jacobi transformation matrix `J` and its inverse `U` for a system of particles with specified `masses`.
# Arguments
- `masses::Array`: A vector of masses for the particles.
# Returns
- `J::Matrix`: The Jacobi transformation matrix.
- `U::Matrix`: The inverse of the Jacobi transformation matrix.
# Notes
- For systems with more than one particle, the returned matrices exclude the last row/column for proper dimensionality in transformations.
"""
Ω(masses::Array) = begin
dim = size(masses, 1)
J = zeros(dim, dim)
for i in 1:dim
sum_m = sum(masses[1:i])
for j in 1:dim
J[i, j] = j == i + 1 ? -1 : i + 1 < j ? 0 : masses[j] / sum_m
J[i, j] = isnan(J[i, j]) ? 1 : J[i, j]
end
end
U = inv(J)
U = dim > 1 ? U[:, 1:end-1] : U
J = dim > 1 ? J[1:end-1, :] : J
return J, U
end
"""
A_generate(bij::Array, w_list::Array)
Generate a matrix A for Gaussian basis functions given width parameters `bij` and weight vectors `w_list`.
# Arguments
- `bij::Array`: A vector of width parameters for the Gaussian basis functions.
- `w_list::Array`: A list of weight vectors.
# Returns
- `Matrix`: The sum of weighted outer products of `w_list`, scaled by `bij`.
# Notes
- This function is used to construct basis elements for the expansion of few-body wavefunctions.
"""
A_generate(bij, w_list::Array) = begin
dim = length(w_list)
mat_list = [(w_list[i] * w_list[i]') ./ (bij[i]^2) for i in 1:dim]
return sum(mat_list)
end
"""
transform_list(α::Array)
Transform a list of scalar values `α` into a list of 1x1 matrices.
# Arguments
- `α::Array`: A list of scalar values.
# Returns
- `Array`: A list of 1x1 matrices where each matrix contains one of the scalar values from `α`.
"""
function transform_list(α::Array)
return[ones(1, 1) .* α[i] for i in 1:length(α)]
end
"""
shift(a::Array, b::Array, mat::Matrix=I)
Calculate the weighted sum of the element-wise product of vectors `a` and `b` using matrix `mat`.
# Arguments
- `a::Array`: A vector or matrix.
- `b::Array`: A vector or matrix of the same size as `a`.
- `mat::Matrix`: An optional matrix to weight the product (default is the identity matrix).
# Returns
- `Float64`: The weighted sum of products.
# Notes
- `a` and `b` are typically shift vectors in the configuration space of a few-body system.
- If `mat` is provided, its dimensions must match the number of elements in `a` and `b`.
"""
shift(a, b, mat=nothing) = begin
n = size(a, 2)
sum_val = 0.0
mat = isnothing(mat) ? I : mat
@assert n == size(mat, 1) "ERROR! Matrix shape does not match number of shift vectors."
for i in 1:n
for j in 1:n
sum_val += mat[i, j] * (a[:, i]' * b[:, j])
end
end
return sum_val
end
"""
w_gen(dim::Int, i::Int, j::Int)
Generate a weight vector for the i-th and j-th coordinates in a space of dimension `dim`.
# Arguments
- `dim::Int`: The dimension of the space.
- `i::Int`: The index for the positive element in the weight vector.
- `j::Int`: The index for the negative element in the weight vector.
# Returns
- `Vector{Int}`: A vector with 1 at the i-th position, -1 at the j-th position, and 0 elsewhere.
# Notes
- This function is useful for generating basis vectors in few-body coordinate transformations.
"""
w_gen(dim, i, j) = dim == 1 ? [1] : [k == i && 1 || k == j && -1 || 0 for k in 1:dim]
"""
transform_coordinates(Ω::Matrix{Float64}, r::Vector{Float64})
Transform the coordinates `r` of a system using the Jacobi matrix `Ω`.
# Arguments
- `Ω::Matrix{Float64}`: The Jacobi transformation matrix.
- `r::Vector{Float64}`: The coordinates to be transformed.
# Returns
- `Vector{Float64}`: The transformed coordinates.
# Notes
- This function applies the inverse of Jacobi matrix `J` to the coordinate vector `r`.
"""
function transform_coordinates(Ω::Matrix{Float64}, r::Vector{Float64})
J, U = Ω(masses)
return J \ r
end
"""
transform_back(Ω::Matrix{Float64}, x::Matrix{Float64})
Transform the coordinates `x` back to the original system using the inverse of the Jacobi matrix `Ω`.
# Arguments
- `Ω::Matrix{Float64}`: The Jacobi transformation matrix.
- `x::Matrix{Float64}`: The coordinates to be transformed back.
# Returns
- `Matrix{Float64}`: The coordinates transformed back to the original system.
# Notes
- This function applies the inverse of matrix `U` to the coordinate matrix `x`.
"""
function transform_back(Ω::Matrix{Float64},x::Matrix{Float64})
J, U = Ω(masses)
return U \ x
end
| FewBodyPhysics | https://github.com/MartinMikkelsen/FewBodyPhysics.jl.git |
|
[
"MIT"
] | 1.0.0 | f39ffb3c8e62a54a0f0be44742c99748ec492ff1 | code | 9688 | using Optim, LinearAlgebra
export S_elements, S_wave, S_energy, P_elements, pion_nucleon, Energy_pion_photodisintegration
struct PositiveDefiniteSymmetricMatrix{T<:Real}
matrix::Matrix{T}
function PositiveDefiniteSymmetricMatrix(mat::Matrix{T}) where T <: Real
if size(mat, 1) != size(mat, 2)
throw(ArgumentError("The matrix must be square."))
end
if !issymmetric(mat)
throw(ArgumentError("The matrix must be symmetric."))
end
if !isposdef(mat)
throw(ArgumentError("The matrix must be positive definite."))
end
return new{T}(mat)
end
end
"""
S_elements(A, B, K, w=nothing)
Calculate matrix elements for overlap, kinetic energy, and optionally the Coulomb term.
# Arguments
- `A::Matrix`: Matrix representing the width of Gaussian basis functions for state `i`.
- `B::Matrix`: Matrix representing the width of Gaussian basis functions for state `j`.
- `K::Matrix`: Kinetic energy matrix.
- `w::Vector` (optional): Weight vectors for the particles involved.
# Returns
- `M0::Float64`: The overlap matrix element between the two states.
- `tra::Float64`: The trace used in the kinetic energy calculation.
- `Coulomb_term::Float64` (optional): The Coulomb interaction term, if weight vectors `w` are provided.
# Notes
- The Coulomb term is calculated only if the weight vectors `w` are specified.
"""
S_elements(A, B, K, w=nothing) = begin
dim = size(A, 1)
Coulomb_term = 0.0
D = A + B
R = inv(D)
M0 = (π^dim / det(D))^(3.0 / 2)
trace = tr(B * K * A * R)
if !isnothing(w)
for k in 1:length(w)
β = 1 / (w[k]' * R * w[k])
Coulomb_term += (k == 3 ? 2 : -2) * sqrt(β / π) * M0
end
return M0, trace, Coulomb_term
else
return M0, trace
end
end
"""
S_wave(α, K, w=nothing)
Calculate the wavefunction overlap, kinetic energy, and optionally Coulomb interaction matrices for a given set of basis functions.
# Arguments
- `α::Vector`: A list of scalar width parameters for the Gaussian basis functions.
- `K::Matrix`: Kinetic energy matrix.
- `w::Vector` (optional): Weight vectors for the particles involved.
# Returns
- `overlap::Matrix`: The overlap matrix for the basis functions.
- `kinetic::Matrix`: The kinetic energy matrix for the basis functions.
- `Coulomb::Matrix` (optional): The Coulomb interaction matrix, if weight vectors `w` are specified.
# Notes
- The Coulomb matrix is computed only if the weight vectors `w` are specified.
"""
S_wave(α, K, w=nothing) = begin
len = length(α)
α = transform_list(α)
overlap = zeros(len, len)
kinetic = zeros(len, len)
Coulomb = zeros(len, len)
for i in 1:len
for j in 1:i
A, B = α[i], α[j]
M0, trace, Coulomb_term = S_elements(A, B, K, w)
overlap[i, j] = overlap[j, i] = M0
kinetic[i, j] = kinetic[j, i] = 6 * trace * M0
Coulomb[i, j] = Coulomb[j, i] = Coulomb_term
end
end
return overlap, kinetic, Coulomb
end
"""
S_energy(bij, K, w)
Compute the ground state energy of the system using the basis functions specified by the width parameters `bij`.
# Arguments
- `bij::Vector`: A list of width parameters for the Gaussian basis functions.
- `K::Matrix`: Kinetic energy matrix.
- `w::Vector`: Weight vectors for the particles involved.
# Returns
- `E0::Float64`: The lowest eigenvalue computed from the Hamiltonian, considered as the ground state energy of the system.
# Notes
- This function constructs the Hamiltonian from the overlap, kinetic, and Coulomb matrices and solves for its eigenvalues.
"""
function S_energy(bij, K, w)
α = []
dim = length(w)
for i in 1:dim:length(bij)
A = A_generate(bij[i:i+dim-1], w)
push!(α, A)
end
N, kinetic, Coulomb = S_wave(α, K, w)
H = kinetic + Coulomb
E,v = eigen(H, N)
E0 = minimum(E)
return E0
end
"""
P_elements(a, b, A, B, K, w=nothing)
Calculate the perturbation matrix elements given two basis states represented by vectors `a` and `b`, and their respective width matrices `A` and `B`.
# Arguments
- `a::Vector`: The coefficient vector for basis state `i`.
- `b::Vector`: The coefficient vector for basis state `j`.
- `A::Matrix`: Matrix representing the width of Gaussian basis functions for state `i`.
- `B::Matrix`: Matrix representing the width of Gaussian basis functions for state `j`.
- `K::Matrix`: Kinetic energy matrix.
- `w::Vector` (optional): Weight vectors for the particles involved.
# Returns
- `M1::Float64`: The overlap perturbation term.
- `kinetic::Float64`: The kinetic energy perturbation term.
- `Coulomb_term::Float64` (optional): The Coulomb interaction perturbation term, if weight vectors `w` are provided.
# Notes
- The Coulomb interaction perturbation term is calculated only if the weight vectors `w` are specified.
"""
function P_elements(a, b, A::PositiveDefiniteSymmetricMatrix, B, K, w=nothing)
D = A + B
R = inv(D)
M0, trace = S_elements(A, B, K)
M1 = 1/2 * (a' * R * b) * M0 # Overlap
kinetic = 6 * trace * M1 # Kinetic matrix elements
kinetic += (a' * K * b) * M0
kinetic += -(a' * (K * A * R) * b) * M0
kinetic += -(a' * (R * B * K) * b) * M0
kinetic += (a' * (R * B * K * A * R) * b) * M0
kinetic += (a' * (R * B * K * A * R) * b) * M0
if w !== nothing
β = 1 / ((w' * R * w)[1]) # Coulomb terms
Coulomb_term = 2 * sqrt(β / π) * M1
Coulomb_term += -sqrt(β / π) * β / 3 * (a' * (R * w * w' * R) * b) * M0
return M1, kinetic, Coulomb_term
else
return M1, kinetic
end
end
function pion_nucleon(alphas, masses, params)
ħc = 197.3
b = params[1]
S = params[2]
mass_nucleon = masses[1]
mass_π = masses[2]
mass_reduced = mass_nucleon * mass_π / (mass_nucleon + mass_π)
K = (ħc)^2 / (2 * mass_reduced)
κ = 1 / b^2
κ = [κ]
Amplitude = S / b
length = size(alphas, 1) + 1
kinetic = zeros(length, length)
overlap = zeros(length, length)
overlap[1, 1] = 1
kinetic[1, 1] = 0
for i in 1:length
for j in 1:i
if i == 1 && j == 1
continue
elseif j == 1 && i != 1
B = alphas[i - 1]
overlap[i, j] = 0
overlap[j, i] = overlap[i, j]
kinetic[i, j] = 3 * Amplitude * 3 / 2 * 1 / (B + κ[1]) * (π / (B + κ[1]))^(3 / 2)
kinetic[j, i] = kinetic[i, j]
else
A = alphas[i - 1]; B = alphas[j - 1]
overlap[i, j] = 3 * 3 / 2 * 1 / (B + A) * (π / (B + A))^(3 / 2)
overlap[j, i] = overlap[i, j]
kinetic[i, j] = 3 * K * 15 * A * B / ((A + B)^2) * (π / (A + B))^(3 / 2) + mass_π * overlap[i, j]
kinetic[j, i] = kinetic[i, j]
end
end
end
return overlap, kinetic
end
"""
ComputeEigenSystem(bs, masses, params)
Calculate the eigenvalues and eigenvectors of a system defined by parameters `bs`, `masses`, and `params`.
# Arguments
- `bs`: Array of parameter values used in the computation.
- `masses`: Array of masses, representing physical properties of the system.
- `params`: Additional parameters required for the calculation.
# Returns
- Tuple of eigenvalues (`E`) and eigenvectors (`c`).
"""
function ComputeEigenSystem(bs, masses, params)
A = [1 / b^2 for b in bs]
N, H = pion_nucleon(A, masses, params)
E, c = eigen(H, N)
return E, c
end
"""
GetMinimumEnergy(bs, masses, params)
Compute the minimum energy of a system characterized by `bs`, `masses`, and `params`.
# Arguments
- `bs`: Array of parameter values used in the computation.
- `masses`: Array of masses, representing physical properties of the system.
- `params`: Additional parameters required for the calculation.
# Returns
- Minimum energy value of the system.
"""
function GetMinimumEnergy(bs, masses, params)
E, _ = ComputeEigenSystem(bs, masses, params)
return E[1]
end
"""
OptimizeGlobalParameters(ngauss, dim, bmax, masses, params)
Perform global optimization over a given parameter space to find optimal parameters for a physical system.
# Arguments
- `ngauss`: Number of Gaussian functions used in the optimization.
- `dim`: Dimensionality of the parameter space.
- `bmax`: Maximum value of the parameter `b`.
- `masses`: Array of masses, representing physical properties of the system.
- `params`: Additional parameters used in the optimization.
# Returns
- `E_list`: List of optimized energies.
- `gaussians`: List of Gaussian functions used.
- `coords`: Optimized coordinates in the parameter space.
- `eigenvectors`: Eigenvectors corresponding to the optimized coordinates.
- `masses`: Updated masses array.
"""
function OptimizeGlobalParameters(ngauss, dim, bmax, masses, params)
E_list = []
gaussians = []
coords = []
eigenvectors = []
global E0S = 0.0
masses_min = copy(masses)
n_calls = 2
for i in 1:ngauss
halt = halton(i, dim)
bs = log.(halt) * bmax
for j in 1:n_calls
masses_min[1] = masses[1] .- E0S
resS = optimize(bs -> GetMinimumEnergy(bs, masses_min, params), bs, NelderMead(), Optim.Options())
global optimized_bs = Optim.minimizer(resS)
global E0S, C0S = ComputeEigenSystem(optimized_bs, masses_min, params)
global E0S = E0S[1]
end
push!(E_list, E0S)
push!(coords, optimized_bs)
push!(eigenvectors, C0S)
push!(gaussians, i)
end
return E_list, gaussians, eigenvectors, coords, masses
end | FewBodyPhysics | https://github.com/MartinMikkelsen/FewBodyPhysics.jl.git |
|
[
"MIT"
] | 1.0.0 | f39ffb3c8e62a54a0f0be44742c99748ec492ff1 | code | 7041 | using Plots
export corput, halton, run_simulation, run_simulation_nuclear, plot_convergence
"""
Generate the nth element of the van der Corput sequence in base b.
# Arguments
- `n`: The nth element of the sequence to be generated.
- `b`: The base for the van der Corput sequence. Default is 3.
# Returns
- `q`: The nth element of the van der Corput sequence in base b.
"""
corput(n, b=3) = begin
q, bk = 0.0, 1 / b
while n > 0
n, rem = divrem(n, b)
q += rem * bk
bk /= b
end
return q
end
"""
Generate the nth d-dimensional point in the Halton sequence.
# Arguments
- `n`: The nth element of the sequence to be generated.
- `d`: The dimension of the space.
# Returns
- An array containing the nth d-dimensional point in the Halton sequence.
# Errors
- Throws an assertion error if `d` exceeds the number of basis elements.
"""
halton(n, d) = begin
base = [2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97,101,103,107,109,113,127,131,137,139,149,151,157,163,167,173,179,181,191,193,197,199,211,223,227,233,239,241,251,257,263,269,271,277,281]
@assert length(base) ≥ d "Error: d exceeds the number of basis elements."
return [corput(n, base[i]) for i in 1:d]
end
"""
Run the simulation for a quantum system using quasi-random or pseudo-random methods to determine the S-wave convergence.
# Arguments
- `num_gauss::Int`: The number of Gaussians to use in the simulation. Default is 15.
- `method::Symbol`: The method to use for the simulation. Can be `:quasirandom`, `:quasirandomrefined`, or `:psudorandom`. Default is `:quasirandom`.
- `plot_result::Bool`: Whether to plot the results. Default is true.
# Returns
- `p`: The plot object if `plot_result` is true.
# Notes
- The function prints various convergence information and, if `plot_result` is true, displays a plot of the numerical result against the theoretical value.
"""
function run_simulation(num_gauss=25::Int, method=:quasirandom::Symbol, plot_result=true::Bool)
b1 = 10
E_list = []
gaussians = []
E_theory = []
bij = []
E_S = -0.527 #Ground state energy of hydrogen anion in Hartree
E_low = Inf
global bases = []
global base_test = []
if method == :quasirandom
println("---------QUASI-RANDOM METHOD---------")
for i in 1:num_gauss
hal = halton(i, 15 * length(w_trans))
bij = -log.(hal) .* b1
for j in 1:length(w_trans):length(hal)
append!(base_test, bij[j:j+length(w_trans)-1])
E0 = S_energy(base_test, K_trans, w_trans)
if E0 <= E_low
E_low = E0
global base_curr = copy(bij[j:j+length(w_trans)-1])
end
base_test = base_test[1:end-length(w_trans)]
end
append!(bases, base_curr)
append!(base_test, base_curr)
push!(E_list, E_low)
println(E_low)
push!(gaussians, i)
push!(E_theory, E_S)
end
elseif method == :quasirandomrefined
println("---------QUASI-RANDOM METHOD W. REFINEMENT---------")
for i in 1:num_gauss
hal = halton(i, 15 * length(w_trans))
bij = -log.(hal) .* b1
for j in 1:length(w_trans):length(hal)
append!(base_test, bij[j:j+length(w_trans)-1])
E0 = S_energy(base_test, K_trans, w_trans)
if E0 <= E_low
E_low = E0
global base_curr = copy(bij[j:j+length(w_trans)-1])
end
base_test = base_test[1:end-length(w_trans)]
end
append!(bases, base_curr)
append!(base_test, base_curr)
push!(E_list, E_low)
println(E_low)
push!(gaussians, i)
push!(E_theory, E_S)
end
bases_ref = copy(bases)
E_ref = E_list[end]
E_list_ref = []
for i in 1:length(bases_ref)-length(w_trans)
rand_ref = rand(200 * length(w_trans))
bij_ref = .-log.(rand_ref) * b1
for j in 1:length(w_trans):length(rand_ref)
bases_ref[i:i+length(w_trans)-1] = bij_ref[j:j+length(w_trans)-1]
E_test = S_energy(bases_ref, K_trans, w_trans)
if E_test < E_ref
E_ref = E_test
bases[i:i+length(w_trans)-1] = bij_ref[j:j+length(w_trans)-1]
end
end
bases_ref = copy(bases)
push!(E_list_ref, E_ref)
println("E_ref: ", E_ref)
end
println("Energy after refinement: ", E_ref)
println("Difference in energy from before refinement: ", abs(E_ref - E_list[end]))
println("Difference from target value: ", abs(E_ref - E_S))
elseif method == :psudorandom
println("---------PSEUDO-RANDOM METHOD (RANDOM GUESSING)---------")
for i in 1:num_gauss
rnd = rand(400 * length(w_trans))
bij2 = -log.(rnd) * b1
for j in 1:length(w_trans):length(rnd)
append!(base_test, bij2[j:j+length(w_trans)-1])
E0 = S_energy(base_test, K_trans, w_trans)
if E0 <= E_low
E_low = E0
global base_curr = copy(bij2[j:j+length(w_trans)-1])
end
base_test = base_test[1:end-length(w_trans)]
end
append!(bases, base_curr)
append!(base_test, base_curr)
push!(E_list, E_low)
push!(gaussians, i)
push!(E_theory, E_S)
end
println("Best convergent numerical value: ", E_list[end])
println("Theoretical value: ", E_S)
println("Difference: ", abs(E_list[end] - E_S))
else
error("Invalid method provided!")
end
println("Best convergent numerical value: ", E_list[end])
println("Theoretical value: ", E_S)
println("Difference: ", abs(E_list[end] - E_S))
p = plot(gaussians, E_list, marker=:circle, label="Numerical result")
plot!(p, gaussians, E_theory, linestyle=:dash, label="Theoretical value")
title!(p, "S-wave convergence of Positron and two Electron System")
xlabel!(p, "Number of Gaussians")
ylabel!(p, "Energy [Hartree]")
if plot_result==true
display(p)
end
return p
end
"""
run_simulation_nuclear(ngauss=2, dim=2, bmax=5)
Run a nuclear simulation and print the final energy.
# Arguments
- `ngauss`: Number of Gaussian functions to use in the simulation (default is 2).
- `dim`: Dimension of the simulation (default is 2).
- `bmax`: Maximum impact parameter (default is 5).
# Outputs
Prints the final energy of the simulation.
# Example
```julia
run_simulation_nuclear(3, 3, 10)
"""
function run_simulation_nuclear(ngauss=2, dim=2, bmax=5)
return E_list, gaussians, eigenvectors, coords, masses = OptimizeGlobalParameters(ngauss, dim, bmax, [mbare, m_π], [b, S])
end
| FewBodyPhysics | https://github.com/MartinMikkelsen/FewBodyPhysics.jl.git |
|
[
"MIT"
] | 1.0.0 | f39ffb3c8e62a54a0f0be44742c99748ec492ff1 | code | 1978 | using FewBodyPhysics
using Test
using LinearAlgebra
@testset "FewBodyPhysics.jl" begin
# Test for Ω function
@testset "Ω Function Tests" begin
masses = [1.0, 2.0, 3.0]
J, U = Ω(masses)
@test size(J) == (2, 3)
@test size(U) == (3, 2)
@test J * U ≈ I(2) atol=1e-10
end
# Test for A_generate function
@testset "A_generate Function Tests" begin
bij = [1.0, 2.0, 3.0]
w_list = [rand(3) for _ in 1:3]
A = A_generate(bij, w_list)
@test size(A) == (3, 3)
# test properties of matrix A (e.g., symmetry, trace)
end
# Test for transform_list function
@testset "transform_list Function Tests" begin
α = [1.0, 2.0, 3.0]
transformed_list = transform_list(α)
@test all([isequal(m, [a]) for (m, a) in zip(transformed_list, α)])
end
# Test for shift function
@testset "Shift Function Tests" begin
a = rand(3)
b = rand(3)
mat = rand(3, 3)
s = shift(a, b, mat)
@test typeof(s) == Float64
# More specific tests on the output based on known input
end
# Test for w_gen function
@testset "w_gen Function Tests" begin
dim = 5
i = 2
j = 4
w = w_gen(dim, i, j)
@test length(w) == dim
@test w[i] == 1 && w[j] == -1
@test sum(w) == 0
end
# Test for transform_coordinates function
@testset "transform_coordinates Function Tests" begin
masses = [1.0, 2.0, 3.0]
r = rand(3)
Ω_matrix = Ω(masses)[1]
x = transform_coordinates(Ω_matrix, r)
@test length(x) == length(r) - 1 # as the last dimension is reduced
end
# Test for transform_back function
@testset "transform_back Function Tests" begin
masses = [1.0, 2.0, 3.0]
x = rand(3, 2)
Ω_matrix = Ω(masses)[1]
r_back = transform_back(Ω_matrix, x)
@test size(r_back) == size(x)
end
end
| FewBodyPhysics | https://github.com/MartinMikkelsen/FewBodyPhysics.jl.git |
|
[
"MIT"
] | 1.0.0 | f39ffb3c8e62a54a0f0be44742c99748ec492ff1 | docs | 667 | # FewBodyPhysics
[](https://github.com/MartinMikkelsen/FewBodyPhysics.jl/actions/workflows/CI.yml?query=branch%3Amain)
This is a Julia package for simulating quantum mechanical few-body systems. It includes functionality for optimizing global parameters and computing eigenvalues and eigenvectors of the system.
## Features
- Optimization of global parameters
- Computation of eigenvalues and eigenvectors
- Support for different dimensions and masses
## Usage
To use this package, import it in your Julia script:
```julia
using FewBodyPhysics | FewBodyPhysics | https://github.com/MartinMikkelsen/FewBodyPhysics.jl.git |
|
[
"MIT"
] | 1.0.0 | f39ffb3c8e62a54a0f0be44742c99748ec492ff1 | docs | 145 | # API
## Coordinates
```@docs
Ω
A_generate
transform_list
shift
w_gen
transform_coordinates
transform_back
```
## Matrix elements
## Sampling | FewBodyPhysics | https://github.com/MartinMikkelsen/FewBodyPhysics.jl.git |
|
[
"MIT"
] | 1.0.0 | f39ffb3c8e62a54a0f0be44742c99748ec492ff1 | docs | 308 | # FewBodyPhysics.jl
## Installation
Get the latest stable release with Julia's package manager:
```
julia ] add FewBodyPhysics
```
## Quick example
```@example EulerSpiral
using Plots, FewBodyPhysics
w_list = [ [1, -1, 0], [1, 0, -1], [0, 1, -1] ]
masses = [1, 1, 1]
K = [0 0 0; 0 1/2 0; 0 0 1/2]
``` | FewBodyPhysics | https://github.com/MartinMikkelsen/FewBodyPhysics.jl.git |
|
[
"MIT"
] | 0.1.0 | b9a720b8371b8eaadd3fe3c803e6a6344da8a6be | code | 478 | using Documenter, PyramidScheme
makedocs(
modules = [PyramidScheme],
format = Documenter.HTML(; prettyurls = get(ENV, "CI", nothing) == "true"),
authors = "Felix Cremer, Fabian Gans",
sitename = "PyramidScheme.jl",
pages = Any[
"index.md",
"interface.md",
]
# strict = true,
# clean = true,
# checkdocs = :exports,
)
deploydocs(
repo = "github.com/JuliaDataCubes/PyramidScheme.jl.git",
push_preview = true
)
| PyramidScheme | https://github.com/JuliaDataCubes/PyramidScheme.jl.git |
|
[
"MIT"
] | 0.1.0 | b9a720b8371b8eaadd3fe3c803e6a6344da8a6be | code | 1008 | module PyramidSchemeArchGDALExt
using ArchGDAL: ArchGDAL as AG
using PyramidScheme: PyramidScheme as PS
import PyramidScheme: _pyramid_gdal
using YAXArrays
using DimensionalData
function _pyramid_gdal(path::AbstractString)
base = Cube(path)
agbase = AG.readraster(path)
band = AG.getband(agbase,1)
numlevels = AG.noverview(band)
pyrlevels = if AG.nraster(agbase) > 1
banddim = dims(base, 3)
bandindices = 1: AG.nraster(agbase)
dbase = dims(base,(1,2))
pyrlevels = AbstractDimArray[]
for n in 0:numlevels-1
levelbands = [YAXArray(PS.agg_axis.(dbase, 2^(n+1)), AG.getoverview(AG.getband(agbase,bind), n)) for bind in bandindices]
level = cat(levelbands..., dims=banddim)
push!(pyrlevels, level)
end
pyrlevels
else
pyrlevels = [YAXArray(PS.agg_axis.(dims(base), 2^(n+1)),AG.getoverview(band, n)) for n in 0:numlevels-1]
end
PS.Pyramid(base, pyrlevels, metadata(base))
end
end | PyramidScheme | https://github.com/JuliaDataCubes/PyramidScheme.jl.git |
|
[
"MIT"
] | 0.1.0 | b9a720b8371b8eaadd3fe3c803e6a6344da8a6be | code | 18872 | """
PyramidScheme is a package to generate and work with Pyramids.
A pyramid is a data structure that holds a two dimensional base array and corresponding aggregations,
which can be used for interactive plotting and analysis.
The main entry point of the package is the `Pyramid` type for the use of already available pyramids
and the `buildpyramids` function to generate the aggregation layers for an existing dataset.
"""
module PyramidScheme
using DiskArrayEngine: DiskArrayEngine, GMDWop, InputArray, LocalRunner, MovingWindow, RegularWindows
using DiskArrayEngine: create_outwindows, engine
using DiskArrays: DiskArrays
#using YAXArrays: savecube
using Zarr
using YAXArrayBase
const YAB = YAXArrayBase
using YAXArrays: Cube, YAXArray, to_dataset, savedataset, setchunks, open_dataset
using Zarr: zcreate, writeattrs
using DimensionalData: DimensionalData as DD
using DimensionalData.Dimensions: XDim, YDim
using Extents
using FillArrays: Zeros
using Proj
using Makie: Axis, Colorbar, DataAspect, Figure, FigureAxisPlot, Observable, Relative
using Makie: on, heatmap!, image!
import MakieCore: plot, plot!
using OffsetArrays
using Statistics
export Pyramid, buildpyramids
"""
Pyramid
A Pyramid will act as a DimArray with the data of the highest resolution,
but subsetting will return another Pyramid.
"""
struct Pyramid{T,N,D,A,B<:DD.AbstractDimArray{T,N,D,A},L, Me} <: DD.AbstractDimArray{T,N,D,A}
"Highest resolution data of the pyramid"
base::B
"Aggregation layers of the `base` layer."
levels::L
"Metadata that describes the aggregation step if available"
metadata::Me
end
function Pyramid(data::DD.AbstractDimArray)
pyrdata, pyraxs = getpyramids(mean ∘ skipmissing, data, recursive=false)
levels = DD.DimArray.(pyrdata, pyraxs)
meta = Dict(deepcopy(DD.metadata(data)))
push!(meta, "resampling_method" => "mean_skipmissing")
Pyramid(data, levels, meta)
end
Pyramid(path::AbstractString) = Pyramid(path, YAB.backendfrompath(path)(path))
function Pyramid(path::AbstractString, backend)
#This should rather be solved via dispatch, but this is not working because of Requires in YAXArrayBase.
if backend isa YAB.ZarrDataset
_pyramid_zarr(path)
elseif backend isa YAB.GDALDataset
_pyramid_gdal(path)
else
throw(ArgumentError("""
Loading is only supported for Zarr and GDAL Datasets got $backend.
If you want to use GDAL you first have to load ArchGDAL.jl
"""))
end
end
function _pyramid_gdal end
function _pyramid_zarr(path)
g = zopen(path)
allkeys = collect(keys(g.groups))
base = Cube(path)[Ti=1] # This getindex should be unnecessary and I should rather fix my data on disk
levavail = extrema(parse.(Int,allkeys[contains.(allkeys, r"\d")]))
clevels = [Cube(open_dataset(g[string(l)])) for l in 1:last(levavail)]
Pyramid(base, clevels, Dict())
end
# refdims
# name
"""
levels(pyramid::Pyramid)
Return all levels of the `pyramid`. These are order from the base to the coarsest aggregation.
This is an OffsetArray starting at zero for the base of the pyramid.
"""
levels(pyramid::Pyramid) = OffsetArray([pyramid.base, pyramid.levels...], 0:length(pyramid.levels))
levels(pyramid::Pyramid, i::Integer) = i==0 ? pyramid.base : pyramid.levels[i]
"""
nlevels(pyramid)
Return the number of levels of the `pyramid`
"""
nlevels(pyramid::Pyramid) = length(levels(pyramid)) - 1
Base.parent(pyramid::Pyramid) = pyramid.base
Base.size(pyramid::Pyramid) = size(parent(pyramid))
DD.name(pyramid::Pyramid) = DD.name(parent(pyramid))
DD.refdims(pyramid::Pyramid) = DD.refdims(parent(pyramid))
DD.dims(pyramid::Pyramid) = DD.dims(parent(pyramid))
DD.metadata(pyramid::Pyramid) = pyramid.metadata
@inline function DD.rebuild(A::Pyramid, data, dims::Tuple=dims(A), refdims=refdims(A), name=name(A))
Pyramid(DD.rebuild(parent(A), data, dims, refdims, name, nothing), A.levels, A.metadata)
end
@inline function DD.rebuild(A::Pyramid; kw...)
newbase = DD.rebuild(parent(A);dims=DD.dims(A), kw...)
Pyramid(newbase, A.levels, DD.metadata(A))
end
@inline function DD.rebuildsliced(f::Function, A::Pyramid, data::AbstractArray, I::Tuple, name=DD.name(A))
newbase = DD.rebuild(parent(A), parent(data), DD.slicedims(f, A, I)..., name)
newlevels = map(enumerate(A.levels)) do (z, level)
Ilevel = levelindex(z, I)
leveldata = f(parent(level), Ilevel...)
DD.rebuild(level, leveldata, DD.slicedims(f, level, Ilevel)..., name)
end
Pyramid(newbase, newlevels, DD.metadata(A))
end
function Base.map(f, A::Pyramid)
newbase = map(f, parent(A))
newlevels = [map(f, levels(A,i)) for i in 1:nlevels(A)]
@show typeof(newlevels)
Pyramid(newbase, newlevels, DD.metadata(A)) # This should handle metadata better.
end
function DD.show_after(io::IO, mime, A::Pyramid)
blockwidth = get(io, :blockwidth, 0)
DD.print_block_separator(io, "pyramidlevels", blockwidth)
println(io)
println(io, " Number of levels: $(nlevels(A)) ")
for l in levels(A)
println(io, " ", size(l))
end
DD.print_block_close(io, blockwidth)
end
"""
levelindex(z, i)
Internal function.
# Extended help
Compute the index into the level `z` from the index i by shifting by a power of two on the Integer level
"""
levelindex(z, i::Integer) = (i - 1) >> z +1
# TODO: This should be also done generically for OrdinalRanges
levelindex(z, i::AbstractUnitRange) = levelindex(z, first(i)):levelindex(z, last(i))
levelindex(z, I::Tuple) = map(i -> levelindex(z, i), I)
"""
Internal function
# Extended help
aggregate_by_factor(xout, x, f)
Aggregate the data `x` using the function `f` and store the results in `xout`.
This function is used as the inner function for the DiskArrayEngine call.
"""
function aggregate_by_factor(xout,x,f)
fac = ceil(Int,size(x,1)/size(xout,1))
for j in axes(xout,2)
for i in axes(xout,1)
xview = ((i-1)*fac+1):min(size(x,1),(i*fac))
yview = ((j-1)*fac+1):min(size(x,2),(j*fac))
xout[i,j] = f(view(x,xview,yview))
end
end
end
"""
all_pyramids!(xout, x, recursive, f)
Compute all tiles of the pyramids for data `x` and store it in `xout`.
Uses function `f` as a aggregating function.
`recursive` indicates whether higher tiles are computed from lower tiles or directly from the original data.
This is an optimization which for functions like median might lead to misleading results.
"""
function all_pyramids!(xout,x,recursive,f)
xnow = x
for xcur in xout
aggregate_by_factor(xcur,xnow,f)
if recursive
xnow = xcur
end
end
end
"""
gen_pyr(x; recursive=true)
Generate the pyramid for the data `x`.
I do not understand what is `x`
"""
function gen_pyr(x...;recursive=true)
allx = Base.front(x)
f = last(x)
all_pyramids!(Base.front(allx),last(allx),recursive,f)
end
"""
fill_pyramids(data, outputs, func, recursive)
Fill the pyramids generated from the `data` with the aggregation function `func` into the list `outputs`.
`recursive` indicates whether higher tiles are computed from lower tiles or directly from the original data.
This is an optimization which for functions like median might lead to misleading results.
"""
function fill_pyramids(data, outputs,func,recursive;runner=LocalRunner, kwargs...)
n_level = length(outputs)
pixel_base_size = 2^n_level
pyramid_sizes = size.(outputs)
tmp_sizes = [ceil(Int,pixel_base_size / 2^i) for i in 1:n_level]
ia = InputArray(data, windows = arraywindows(size(data),pixel_base_size))
oa = ntuple(i->create_outwindows(pyramid_sizes[i],windows = arraywindows(pyramid_sizes[i],tmp_sizes[i])),n_level)
func = DiskArrayEngine.create_userfunction(gen_pyr,ntuple(_->eltype(first(outputs)),length(outputs));is_mutating=true,kwargs = (;recursive),args = (func,))
op = GMDWop((ia,), oa, func)
lr = DiskArrayEngine.optimize_loopranges(op,5e8,tol_low=0.2,tol_high=0.05,max_order=2)
r = runner(op,lr,outputs;kwargs...)
run(r)
end
"""
ESALCMode(counts)
Struct for more efficient handling of aggregating categorical land cover data.
"""
struct ESALCMode
counts::Vector{Vector{Int}}
end
ESALCMode() = ESALCMode([zeros(Int,256) for _ in 1:Threads.nthreads()])
function (f::ESALCMode)(x)
cv = f.counts[Threads.threadid()]
fill!(cv,0)
for ix in x
cv[Int(ix)+1] += 1
end
_,ind = findmax(cv)
UInt8(ind-1)
end
"""
arraywindows(s,w)
Construct a list of `RegularWindows` for the size list in `s` for windows `w`.
??
"""
function arraywindows(s,w)
map(s) do l
RegularWindows(1,l,window=w)
end
end
"""
compute_nlevels(data, tilesize=1024)
Compute the number of levels for the aggregation based on the size of `data`.
"""
compute_nlevels(data, tilesize=256) = max(0,ceil(Int,log2(maximum(size(data))/tilesize)))
function agg_axis(d,n)
# TODO this might be problematic for explicitly set axes
DD.set(d, LinRange(first(d), last(d), cld(length(d), n)))
end
"""
gen_output(t,s)
Create output array of type `t` and size `s`
If the array is smaller than 10e6 it is created on disk and otherwise as a temporary zarr file.
"""
function gen_output(t,s; path=tempname())
# This should be dispatching on the output type whether it is internal or external
outsize = sizeof(t)*prod(s)
z = Zeros(t, s...)
if outsize > 100e6
# This should be zgroup instead of zcreate, could use savedataset(skelton=true)
# Dummy dataset with FillArrays with the shape of the pyramidlevel
zcreate(t,s...;path,chunks = (1024,1024),fill_value=zero(t))
else
zeros(t,s...)
end
end
function DiskArrayEngine.engine(dimarr::DD.AbstractDimArray)
dataengine = engine(dimarr.data)
DD.rebuild(dimarr, data=dataengine)
end
DiskArrayEngine.engine(pyr::Pyramid) = Pyramid(engine(parent(pyr)), engine.(pyr.levels), DD.metadata(pyr))
"""
output_arrays(pyramid_sizes)
Create the output arrays for the given `pyramid_sizes`
"""
output_arrays(pyramid_sizes, T) = [gen_output(T,p) for p in pyramid_sizes]
"""
SpatialDim
Union of Dimensions which are assumed to be in space and are therefore used in the pyramid building.
"""
SpatialDim = Union{DD.Dimensions.XDim, DD.Dimensions.YDim}
"""
buildpyramids(path; resampling_method=mean)
Build the pyramids for the zarr dataset at `path` and write the pyramid layers into the zarr folder.
The different scales are written according to the GeoZarr spec and a multiscales entry is added to the attributes of the zarr dataset.
The data is aggregated with the specified `resampling_method`.
Keyword arguments are forwarded to the `fill_pyramids` function.
"""
function buildpyramids(path; resampling_method=mean, recursive=true, runner=LocalRunner, verbose=false)
if YAB.backendfrompath(path) != YAB.ZarrDataset
throw(ArgumentError("$path is not a Zarr dataset therefore we can't build the Pyramids inplace"))
end
# Should this be a dataset not a Cube?
# Build a loop for all variables in a dataset?
org = Cube(path)
# We run the method once to derive the output type
t = typeof(resampling_method(zeros(eltype(org), 2,2)))
n_level = compute_nlevels(org)
input_axes = filter(x-> x isa SpatialDim, DD.dims(org))
if length(input_axes) != 2
throw(ArgumentError("Expected two spatial dimensions got $input_axes"))
end
verbose && println("Constructing output arrays")
outarrs = [output_zarr(n, input_axes, t, joinpath(path, string(n))) for n in 1:n_level]
verbose && println("Start computation")
fill_pyramids(org, outarrs, resampling_method, recursive;runner)
pyraxs = [agg_axis.(input_axes, 2^n) for n in 1:n_level]
pyrlevels = DD.DimArray.(outarrs, pyraxs)
meta = Dict(deepcopy(DD.metadata(org)))
push!(meta, "resampling_method" => string(resampling_method))
multiscale = Dict{String, Any}()
push!(multiscale, "datasets" => ["path"=> "", ["path" => string(i) for i in 1:n_level]...])
push!(multiscale, "type" => "reduce")
push!(meta, "multiscales" => [multiscale,])
storage, basepath = Zarr.storefromstring(path)
writeattrs(storage,basepath, meta)
Pyramid(org, pyrlevels, meta)
# Construct the TMS metadata from the info of the array
# Save TMS to the .zattrs of the original data
end
# TODO: Decide on how we count levels rather from the bottom to the top or the other way around.
# I find bottom to top more intuitive but TMS specifies it differently
"""
output_zarr(n, input_axes, t, path)
Construct a Zarr dataset for the level n of a pyramid for the dimensions `input_axes`.
It sets the type to `t` and saves it to `path/n`
"""
function output_zarr(n, input_axes, t, path)
aggdims = agg_axis.(input_axes, 2^n)
s = length.(aggdims)
z = Zeros(t, s...)
yax = YAXArray(aggdims, z)
chunked = setchunks(yax , (1024, 1024))
# This assumes that there is only the spatial dimensions to save
ds = to_dataset(chunked, )
dssaved = savedataset(ds; path, skeleton=true, driver=:zarr)
zar = dssaved.layer.data
zar
end
"""
getpyramids(ras)
Compute the data of the pyramids of a given data cube `ras`.
This returns the data of the pyramids and the dimension values of the aggregated axes.
"""
function getpyramids(reducefunc, ras;recursive=true)
input_axes = DD.dims(ras)
n_level = compute_nlevels(ras)
if iszero(n_level)
@info "Array is smaller than the tilesize no pyramids are computed"
[ras], [dims(ras)]
end
pyramid_sizes = [ceil.(Int, size(ras) ./ 2^i) for i in 1:n_level]
pyramid_axes = [agg_axis.(input_axes,2^i) for i in 1:n_level]
outmin = output_arrays(pyramid_sizes, Float32)
fill_pyramids(ras,outmin,reducefunc,recursive; threaded=true)
outmin, pyramid_axes
end
"""
selectlevel(pyramids, ext, resolution; target_imsize=(1024,512)
Internal function to select the raster data that should be plotted on screen.
`pyramids` is a Vector of Raster objects with increasing coarsity.
`ext` is the extent of the zoomed in area
`target_imsize` is the target size of the output data that should be plotted.
"""
function selectlevel(pyramid, ext;target_imsize=(1024, 512))
pyrext = extent(pyramid)
basepixels = map(keys(pyrext)) do bb
pyrspan = pyrext[bb][2] - pyrext[bb][1]
imsize = ext[bb][2] - ext[bb][1]
imsize / pyrspan * size(pyramid, bb)
end
dimlevels = log2.(basepixels ./ target_imsize)
minlevel = maximum(dimlevels)
n_agg = min(max(ceil(Int,minlevel),0),nlevels(pyramid))
@debug "Selected level $n_agg"
levels(pyramid)[n_agg][ext]
end
"""
plot(pyramids)
Plot a Pyramid.
This will plot the coarsest resolution level at the beginning and will plot higher resolutions after zooming into the plot.
This is expected to be used with interactive Makie backends.
"""
function plot(pyramid::Pyramid;colorbar=true, kwargs...)
#This should be converted into a proper recipe for Makie but this would depend on a pyramid type.
fig = Figure()
lon, lat = DD.dims(parent(pyramid))
ax = Axis(fig[1,1], limits=(extrema(lon), extrema(lat)), aspect=DataAspect())
hmap = plot!(ax, pyramid;kwargs...)
if colorbar
Colorbar(fig[1,2], hmap, height = Relative(3.5 / 4))
end
ax.autolimitaspect = 1
FigureAxisPlot(fig, ax, hmap)
end
xkey(keyext) = DD.dim2key(DD.dims(keyext, XDim))
ykey(keyext) = DD.dim2key(DD.dims(keyext, YDim))
#TODO write test, move to utils.jl
"""
switchkeys(dataext, keyext)
Internal function
### Extended help
Return an Extent with the limits from `dataext` on the keys of `keyext`.
We assume that dataext has keys X, and Y and the keys of keyext are XDim and YDim from DimensionalData
"""
function switchkeys(dataext, keyext)
xk = xkey(keyext)
yk = ykey(keyext)
nt = NamedTuple{(xk, yk)}((dataext.X, dataext.Y))
Extent(nt)
end
function plot!(ax, pyramid::Pyramid;interp=false, kwargs...)#; rastercrs=crs(parent(pyramid)),plotcrs=EPSG(3857), kwargs...)
tip = levels(pyramid)[end-2][:,:]
#@show typeof(tip)
data = Observable{DD.AbstractDimMatrix}(tip)
xval = only(values(Extents.extent(pyramid, XDim)))
yval = only(values(Extents.extent(pyramid, YDim)))
rasdataext = Extent(X=xval, Y=yval)
rasext = extent(pyramid)
xk = xkey(rasext)
yk = ykey(rasext)
on(ax.scene.viewport) do viewport
limext = Extents.extent(ax.finallimits[])
datalimit = switchkeys(limext, rasext)
data.val = selectlevel(pyramid, datalimit, target_imsize=viewport.widths)
notify(data)
end
on(ax.finallimits) do limits
limext = Extents.extent(limits)
# Compute limit in raster projection
#trans = Proj.Transformation(plotcrs, rastercrs, always_xy=true)
#datalimit = trans_bounds(trans, limext)
datalimit = switchkeys(limext, rasext)
if Extents.intersects(rasdataext, limext)
rasdata = selectlevel(pyramid, datalimit, target_imsize=ax.scene.viewport[].widths)
# Project selected data to plotcrs
#data.val = Rasters.resample(rasdata, crs=plotcrs, method=:bilinear )
data.val = rasdata
end
notify(data)
end
#@show typeof(data)
hmap = image!(ax, data; interpolate=interp, kwargs...)
end
"""
trans_bounds(trans::Proj.Transformation, bbox::Extent, densify_pts::Integer)
Compute the projection of `bbox` with the transformation `trans`.
This is used to project the data on the fly to another transformation.
"""
function trans_bounds(
trans::Proj.Transformation,
bbox::Extent,
densify_pts::Integer = 21,
)::Extent
xlims, ylims = Proj.bounds(trans, bbox.X, bbox.Y; densify_pts)
return Extent(X = xlims, Y = ylims)
end
function write(path, pyramid::Pyramid; kwargs...)
savecube(parent(pyramid), path; kwargs...)
for (i,l) in enumerate(reverse(pyramid.levels))
outpath = joinpath(path, string(i-1))
@show outpath
savecube(l,outpath)
end
end
"""
tms_json(dimarray)
Construct a Tile Matrix Set json description from an AbstractDimArray.
This assumes, that we use an ag3ycgregation of two by two pixels in the spatial domain to derive the underlying layers of the pyramids.
This returns a string representation of the json and is mainly used for writing the TMS definition to the metadata of the Zarr dataset.
"""
function tms_json(pyramid)
tms = Dict{String, Any}()
push!(tms, "id"=>"TMS_$(string(DD.name(pyramid)))")
push!(tms, "title" => "TMS of $(crs(pyramid)) for pyramid")
push!(tms, "crs" => string(crs(pyramid)))
push!(tms, "orderedAxes" => pyramidaxes())
return tms
end
include("broadcast.jl")
end | PyramidScheme | https://github.com/JuliaDataCubes/PyramidScheme.jl.git |
|
[
"MIT"
] | 0.1.0 | b9a720b8371b8eaadd3fe3c803e6a6344da8a6be | code | 1324 | import Base.Broadcast: Broadcasted, BroadcastStyle
struct PyramidStyle <:Base.BroadcastStyle end
Base.BroadcastStyle(::Type{<:Pyramid}) = PyramidStyle()
Base.BroadcastStyle(::PyramidStyle, ::PyramidStyle) = PyramidStyle()
function Base.copy(bc::Broadcasted{PyramidStyle})
bcf = Base.Broadcast.flatten(bc)
inputs = bcf.args
func = bcf.f
numlevels = checklevelcompat(inputs)
newlevels = map(0:numlevels) do l
argslevel = levels.(inputs, (l,))
argdata = getproperty.(argslevel, :data)
newdata = func.(argdata...)
newdimarr = DD.rebuild(first(argslevel), data=newdata, dims=DD.dims(first(argslevel)))
newdimarr
end
#@show typeof(newlevels)
base = newlevels[1]
layers = newlevels[2:end]
#@show typeof(base)
#@show eltype(layers)
Pyramid(base, layers, broadcast_metadata(inputs))
end
#function Base.copyto!(pyr::Pyramid, bc::Broadcasted{PyramidStyle}) = pyr
# TODO Implement proper metadata handling for broadcast
broadcast_metadata(inputs) = Dict()
function checklevelcompat(inputs)
levfirstpyr = nlevels(first(inputs))
for inp in inputs
if nlevels(inp) != levfirstpyr
error("Pyramids should have the same number of levels got $levfirstpyr and $(nlevels(inp))")
end
end
return levfirstpyr
end | PyramidScheme | https://github.com/JuliaDataCubes/PyramidScheme.jl.git |
|
[
"MIT"
] | 0.1.0 | b9a720b8371b8eaadd3fe3c803e6a6344da8a6be | code | 146 | @testitem "broadcasting two Arrays" begin
using PyramidScheme: PyramidScheme as PS
using DimensionalData
using ArchGDAL
end | PyramidScheme | https://github.com/JuliaDataCubes/PyramidScheme.jl.git |
|
[
"MIT"
] | 0.1.0 | b9a720b8371b8eaadd3fe3c803e6a6344da8a6be | code | 3617 | using PyramidScheme:PyramidScheme as PS
using Test
using TestItemRunner
using DimensionalData
using CairoMakie: plot
@run_package_tests
@testitem "Aqua unbound args" begin
using Aqua
#Aqua.test_ambiguities([PyramidScheme, Base, Core])
Aqua.test_unbound_args(PyramidScheme)
end
@testitem "Aqua undefined exports" begin
using Aqua
Aqua.test_undefined_exports(PyramidScheme)
end
@testitem "Aqua project extras" begin
using Aqua
Aqua.test_project_extras(PyramidScheme)
end
@testitem "Aqua stale deps" begin
using Aqua
Aqua.test_stale_deps(PyramidScheme)
end
@testitem "Aqua deps compat" begin
using Aqua
Aqua.test_deps_compat(PyramidScheme)
end
@testitem "Pyramid" begin
using DimensionalData
using PyramidScheme: PyramidScheme as PS
using CairoMakie
data = zeros(2000,2000)
dd = DimArray(data, (X(1:2000), Y(1:2000)))
pyramid = PS.Pyramid(dd)
#@test PS.nlevels(pyramid) == 2
subpyramid = pyramid[X=1..10, Y=1..10]
@test subpyramid isa PS.Pyramid
@test size(subpyramid) == (10,10)
@test parent(subpyramid) == data[1:10,1:10]
fig, axis, h = plot(pyramid)
end
@testitem "Helper functions" begin
using PyramidScheme: PyramidScheme as PS
@test PS.compute_nlevels(zeros(1000)) == 2
@test PS.compute_nlevels(zeros(1000,1025)) == 3
@test PS.compute_nlevels(zeros(10000, 8000)) == 6
end
@testitem "ArchGDAL Loading of Geotiff Overviews" begin
using ArchGDAL: ArchGDAL as AG
using PyramidScheme: PyramidScheme as PS
@show pwd()
@show @__DIR__
path = joinpath(@__DIR__,"data/pyramidmiddle.tif")
#ras = Raster(path, lazy=true)
pyr =PS.Pyramid(path)
@test pyr isa PS.Pyramid
@test PS.nlevels(pyr) == 2
sub = pyr[1:10,1:10]
@test sub isa PS.Pyramid
end
@testitem "Zarr build Pyramid inplace" begin
using Zarr
using PyramidScheme
using YAXArrays
using Statistics
using DimensionalData
a = rand(1200,1200)
yax = YAXArray((X(1.:size(a,1)),Y(1.:size(a,2))), a)
path = tempname() *".zarr"
savecube(yax, path)
pyr = buildpyramids(path, resampling_method=mean)
@test pyr isa Pyramid
pyrdisk = Pyramid(path)
@test pyrdisk isa Pyramid
@test pyr == pyrdisk
#pyrmem = PS.Pyramid(yax)
#@test pyrmem.levels[end][1,1] == pyr.levels[end][1,1]
end
@testitem "selectlevel" begin
using PyramidScheme: PyramidScheme as PS
using YAXArrays
using Extents
using DimensionalData: DimensionalData as DD
using DimensionalData.Dimensions
using Test
a = rand(1500, 1524)
yax = YAXArray((X(1.:size(a,1)),Y(1.:size(a,2))), a)
pyramid = PS.Pyramid(yax)
target_imsize=(1024, 1024)
sub = PS.selectlevel(pyramid, extent(pyramid); target_imsize)
@test any( (target_imsize ./ 2) .<= size(sub) .<= target_imsize)
@test size(sub) == (750, 762)
target_imsize=(256, 256)
sub = PS.selectlevel(pyramid, extent(pyramid); target_imsize)
@test any( (target_imsize ./ 2) .<= size(sub) .<= target_imsize)
target_imsize=(400, 300)
sub = PS.selectlevel(pyramid, extent(pyramid); target_imsize)
@test any( (target_imsize ./ 2) .<= size(sub) .<= target_imsize)
end
#=
@testitem "Comparing zarr pyramid with tif pyramid" begin
using PyramidScheme: PyramidScheme as PS
using ArchGDAL
using Zarr
using YAXArrays
pyrtif = PS.Pyramid("test/data/bremen_sea_ice_conc_2022_9_9.tif")
path = tempname() * ".zarr"
savecube(parent(pyrtif), path)
@time pyrzarr = PS.buildpyramids(path)
pyrdisk = PS.Pyramid(path)
pyrzarr == pyrtif
end
=#
| PyramidScheme | https://github.com/JuliaDataCubes/PyramidScheme.jl.git |
|
[
"MIT"
] | 0.1.0 | b9a720b8371b8eaadd3fe3c803e6a6344da8a6be | docs | 2419 | # PyramidScheme
PyramidScheme.jl is a package to easily and efficiently compute pyramids of a given datacube which might be larger than RAM.
It uses DiskArrayEngine.jl as the computational backend.
The pyramids can then be used to interactively explore the data.
The long term aim of PyramidScheme.jl is to enable computing based on the layers of the pyramid to enable a more interactive exploration of computations based of pyramided datasets.
[PyramidScheme.jl in action](https://github.com/JuliaDataCubes/PyramidScheme.jl/assets/17124431/63166348-7b18-4af1-b6bb-4eb0af2def9e)
## Usage
To compute the pyramids of a given data cube use the following steps:
```julia
using Rasters
using RasterDataSources
using ArchGDAL
using Statistics
using Extents
using PyramidScheme: PyramidScheme as PS
path =
ras = Raster(WorldClim{Elevation},:elev, res="30s", lazy=true)
pyr = PS.Pyramid(ras)
# Now we can plot the data in GLMakie and get a nice interactive plot which uses the pyramids to provide a nice smooth experience by only loading the pixels which can fit into the Makie axis from an appropriate pyramid.
using GLMakie
plot(pyr)
```
## Preparing the Pyramid for zarr data
If you want to prepare a pyramid which is saved inside of a Zarr dataset you can use the `buildpyramids` function. The buildpyramids function adds the
Here we use the same example data as above, but we first save the data in a zarr file.
```julia
using YAXArrays
elevpath = getraster(WorldClim{Elevation},:elev, res="30s")
elev = Cube(elevpath)
zarrpath = tempname() * ".zarr"
savecube(elev, zarrpath)
@time PS.buildpyramids(zarrpath)
```
### Example above
To reproduce the zooming example shown at the top of the README you can get the Above Ground Biomass here or try to load it from the cloud, but this might have some serious lag.
```julia
using YAXArrays, PyramidScheme
using GLMakie
p2020 = PS.Pyramid("https://s3.bgc-jena.mpg.de:9000/pyramids/ESACCI-BIOMASS-L4-AGB-MERGED-100m-2020-fv4.0.zarr")
replacenan(nanval) = data -> <=(nanval)(data) ? NaN32 : Float32(data)
p2020nan = replacenan(0).(p2020)
plot(p2020nan, colormap=:speed, colorscale=sqrt)
# to save the base data use YAXArrays to load the underlying data
c = Cube("https://s3.bgc-jena.mpg.de:9000/pyramids/ESACCI-BIOMASS-L4-AGB-MERGED-100m-2020-fv4.0.zarr")
savecube(c, "somepath.zarr")
# Build the pyramid from this data locally
buildpyramids("somepath.zarr")
```
| PyramidScheme | https://github.com/JuliaDataCubes/PyramidScheme.jl.git |
|
[
"MIT"
] | 0.1.0 | b9a720b8371b8eaadd3fe3c803e6a6344da8a6be | docs | 1252 | # Aim of PyramidScheme.jl
The aim of the PyramidScheme.jl package is to provide an easy way to interactively work with larger than memory data.
When the data does not have pyramid layers computed it provides an easy way to compute the pyramid layers and save them efficiently in Zarr format.
When the pyramid layers are already available this information will be used to run the computations first on the coarsest level to then enable a first glimpse at the results and to interactively run the computations on the parts of the data that the user is currently looking at.
## Simple example
As a proof of concept we could look at the sum of two datasets which are too large to fit into memory and therefore the computation of the sum should be taking some time but when we only do it on the highest level which would by convention be only 256 by 256 pixels it should be able to be plotted instantaneously.
```julia
using PyramidScheme
pyr = Pyramid("path/to/layeredfile.tiff")
pyrzarr = Pyramid("path/to/layeredfile.zarr")
# This computation should only be lazily registered at this stage
pyrsum = pyr .+ pyrzarr
using GLMakie
plot(pyrsum) # This should plot the sum in the highest level and zooming in would compute the rest of the layers.
``` | PyramidScheme | https://github.com/JuliaDataCubes/PyramidScheme.jl.git |
|
[
"MIT"
] | 10.7.0 | f0341c8179a869629d90fe549511d6ffaf1da9a1 | code | 7261 | module RememberToUpdateRegistryCI
# using GitCommand
using GitHub
using Pkg
# Some of the code in this file is taken from:
# https://github.com/bcbi/CompatHelper.jl
struct AlwaysAssertionError <: Exception end
@inline function always_assert(cond::Bool)::Nothing
cond || throw(AlwaysAssertionError())
return nothing
end
function get_all_pull_requests(
api::GitHub.GitHubAPI,
repo::GitHub.Repo,
state::String;
auth::GitHub.Authorization,
per_page::Integer=100,
page_limit::Integer=100,
)
all_pull_requests = Vector{GitHub.PullRequest}(undef, 0)
myparams = Dict("state" => state, "per_page" => per_page, "page" => 1)
prs, page_data = GitHub.pull_requests(
api, repo; auth=auth, params=myparams, page_limit=page_limit
)
append!(all_pull_requests, prs)
while haskey(page_data, "next")
prs, page_data = GitHub.pull_requests(
api, repo; auth=auth, page_limit=page_limit, start_page=page_data["next"]
)
append!(all_pull_requests, prs)
end
unique!(all_pull_requests)
return all_pull_requests
end
_repos_are_the_same(::GitHub.Repo, ::Nothing) = false
_repos_are_the_same(::Nothing, ::GitHub.Repo) = false
_repos_are_the_same(::Nothing, ::Nothing) = false
function _repos_are_the_same(x::GitHub.Repo, y::GitHub.Repo)
if x.name == y.name &&
x.full_name == y.full_name &&
x.owner == y.owner &&
x.id == y.id &&
x.url == y.url &&
x.html_url == y.html_url &&
x.fork == y.fork
return true
else
return false
end
end
function exclude_pull_requests_from_forks(
repo::GitHub.Repo, pr_list::Vector{GitHub.PullRequest}
)
non_forked_pull_requests = Vector{GitHub.PullRequest}(undef, 0)
for pr in pr_list
always_assert(_repos_are_the_same(repo, pr.base.repo))
if _repos_are_the_same(repo, pr.head.repo)
push!(non_forked_pull_requests, pr)
end
end
return non_forked_pull_requests
end
function only_my_pull_requests(pr_list::Vector{GitHub.PullRequest}; my_username::String)
_my_username_lowercase = lowercase(strip(my_username))
n = length(pr_list)
pr_is_mine = BitVector(undef, n)
for i in 1:n
pr_user_login = pr_list[i].user.login
if lowercase(strip(pr_user_login)) == _my_username_lowercase
pr_is_mine[i] = true
else
pr_is_mine[i] = false
end
end
my_pr_list = pr_list[pr_is_mine]
return my_pr_list
end
function create_new_pull_request(
api::GitHub.GitHubAPI,
repo::GitHub.Repo;
base_branch::String,
head_branch::String,
title::String,
body::String,
auth::GitHub.Authorization,
)
params = Dict{String,String}()
params["title"] = title
params["head"] = head_branch
params["base"] = base_branch
params["body"] = body
result = GitHub.create_pull_request(api, repo; params=params, auth=auth)
return result
end
function git_commit(message)::Bool
return try
git() do git
success(`$git commit -m "$(message)"`)
end
catch
false
end
end
function generate_username_mentions(usernames::AbstractVector)::String
intermediate_result = ""
for username in usernames
_username = filter(x -> x != '@', strip(username))
if length(_username) > 0
intermediate_result = intermediate_result * "\ncc: @$(_username)"
end
end
final_result = convert(String, strip(intermediate_result))
return final_result
end
function set_git_identity(username, email)
git() do git
run(`$git config user.name "$(username)"`)
run(`$git config user.email "$(email)"`)
end
return nothing
end
function create_new_pull_request(
api::GitHub.GitHubAPI,
repo::GitHub.Repo;
base_branch::String,
head_branch::String,
title::String,
body::String,
auth::GitHub.Authorization,
)
params = Dict{String,String}()
params["title"] = title
params["head"] = head_branch
params["base"] = base_branch
params["body"] = body
result = GitHub.create_pull_request(api, repo; params=params, auth=auth)
return result
end
function main(
relative_path;
registry,
github_token=ENV["GITHUB_TOKEN"],
master_branch="master",
pr_branch="github_actions/remember_to_update_registryci",
pr_title="Update RegistryCI.jl by updating the .ci/Manifest.toml file",
cc_usernames=String[],
my_username="github-actions[bot]",
my_email="41898282+github-actions[bot]@users.noreply.github.com",
)
original_project = Base.active_project()
original_directory = pwd()
api = GitHubWebAPI(HTTP.URI("https://api.github.com"))
tmp_dir = mktempdir()
atexit(() -> rm(tmp_dir; force=true, recursive=true))
cd(tmp_dir)
auth = GitHub.authenticate(api, github_token)
my_repo = GitHub.repo(api, registry; auth=auth)
registry_url_with_auth = "https://x-access-token:$(github_token)@github.com/$(registry)"
_all_open_prs = get_all_pull_requests(api, my_repo, "open"; auth=auth)
_nonforked_prs = exclude_pull_requests_from_forks(my_repo, _all_open_prs)
pr_list = only_my_pull_requests(_nonforked_prs; my_username=my_username)
pr_titles = Vector{String}(undef, length(pr_list))
for i in 1:length(pr_list)
pr_titles[i] = convert(String, strip(pr_list[i].title))::String
end
username_mentions_text = generate_username_mentions(cc_usernames)
git() do git
run(`$git clone $(registry_url_with_auth) REGISTRY`)
end
cd("REGISTRY")
git() do git
run(`$git checkout $(master_branch)`)
end
git() do git
run(`$git checkout -B $(pr_branch)`)
end
cd(relative_path)
manifest_filename = joinpath(pwd(), "Manifest.toml")
rm(manifest_filename; force=true, recursive=true)
Pkg.activate(pwd())
Pkg.instantiate()
Pkg.update()
set_git_identity(my_username, my_email)
try
git() do git
run(`$git add Manifest.toml`)
end
catch
end
commit_was_success = git_commit("Update .ci/Manifest.toml")
@info("commit_was_success: $(commit_was_success)")
if commit_was_success
git() do git
run(`$git push -f origin $(pr_branch)`)
end
if pr_title in pr_titles
@info("An open PR with the title already exists", pr_title)
else
new_pr_body = strip(
string(
"This pull request updates ",
"RegistryCI.jl by updating the ",
"`.ci/Manifest.toml` file.\n\n",
username_mentions_text,
),
)
_new_pr_body = convert(String, strip(new_pr_body))
create_new_pull_request(
api,
my_repo;
base_branch=master_branch,
head_branch=pr_branch,
title=pr_title,
body=_new_pr_body,
auth=auth,
)
end
end
cd(original_directory)
rm(tmp_dir; force=true, recursive=true)
Pkg.activate(original_project)
return commit_was_success
end
end # end module RememberToUpdateRegistryCI
| RegistryCI | https://github.com/JuliaRegistries/RegistryCI.jl.git |
|
[
"MIT"
] | 10.7.0 | f0341c8179a869629d90fe549511d6ffaf1da9a1 | code | 931 | using RegistryCI
using Documenter
DocMeta.setdocmeta!(RegistryCI, :DocTestSetup, :(using RegistryCI); recursive=true)
makedocs(;
modules=[RegistryCI],
authors="Dilum Aluthge <[email protected]>, Fredrik Ekre <[email protected]>, contributors",
repo=Remotes.GitHub("JuliaRegistries", "RegistryCI.jl"),
sitename="RegistryCI.jl",
format=Documenter.HTML(;
prettyurls=get(ENV, "CI", "false") == "true",
canonical="https://JuliaRegistries.github.io/RegistryCI.jl",
assets=String[],
),
pages=[
"Home" => "index.md",
"Automatic merging guidelines" => "guidelines.md",
"Regexes" => "regexes.md",
"Using RegistryCI on your own package registry" => "private-registries.md",
"Public API" => "public.md",
"Internals (Private)" => "internals.md",
],
)
deploydocs(; repo="github.com/JuliaRegistries/RegistryCI.jl", push_preview=false)
| RegistryCI | https://github.com/JuliaRegistries/RegistryCI.jl.git |
|
[
"MIT"
] | 10.7.0 | f0341c8179a869629d90fe549511d6ffaf1da9a1 | code | 167 | module RegistryCI
# import GitCommand
include("TagBot/TagBot.jl")
include("AutoMerge/AutoMerge.jl")
include("registry_testing.jl")
include("utils.jl")
end # module
| RegistryCI | https://github.com/JuliaRegistries/RegistryCI.jl.git |
|
[
"MIT"
] | 10.7.0 | f0341c8179a869629d90fe549511d6ffaf1da9a1 | code | 11711 | using Pkg: Pkg
# import GitCommand
using HTTP: HTTP
using RegistryTools: RegistryTools
using Test: Test
function gather_stdlib_uuids()
return Set{Base.UUID}(x for x in keys(RegistryTools.stdlibs()))
end
@static if Base.VERSION >= v"1.7.0-"
const collect_registries = Pkg.Registry.reachable_registries
else
const collect_registries = Pkg.Types.collect_registries
end
is_valid_url(str::AbstractString) = !isempty(HTTP.URI(str).scheme) && isvalid(HTTP.URI(str))
function _include_this_registry(
registry_spec, registry_deps_names::Vector{<:AbstractString}
)
all_fieldvalues = []
for fieldname in [:name, :repo, :url]
if hasproperty(registry_spec, fieldname)
fieldvalue = getproperty(registry_spec, fieldname)
if fieldvalue isa AbstractString
push!(all_fieldvalues, fieldvalue)
end
end
end
for fieldvalue in all_fieldvalues
for registry_deps_name in registry_deps_names
if strip(fieldvalue) == strip(registry_deps_name)
return true
end
if strip(fieldvalue) == strip("$(registry_deps_name).git")
return true
end
if strip("$(fieldvalue).git") == strip(registry_deps_name)
return true
end
end
end
return false
end
# For when you have a registry that has packages with dependencies obtained from
# another dependency registry. For example, packages registered at the BioJuliaRegistry
# that have General dependencies. BJW.
function load_registry_dep_uuids(registry_deps_names::Vector{<:AbstractString}=String[])
return with_temp_depot() do
# Get the registries!
for repo_spec in registry_deps_names
if is_valid_url(repo_spec)
Pkg.Registry.add(Pkg.RegistrySpec(; url=repo_spec))
else
Pkg.Registry.add(repo_spec)
end
end
# Now use the RegistrySpec's to find the Project.toml's. I know
# .julia/registires/XYZ/ABC is the most likely place, but this way the
# function never has to assume. BJW.
extrauuids = Set{Base.UUID}()
for spec in collect_registries()
if _include_this_registry(spec, registry_deps_names)
reg = Pkg.TOML.parsefile(joinpath(spec.path, "Registry.toml"))
for x in keys(reg["packages"])
push!(extrauuids, Base.UUID(x))
end
end
end
return extrauuids
end
end
#########################
# Testing of registries #
#########################
function load_package_data(
::Type{T}, path::String, versions::Vector{VersionNumber}
) where {T}
compressed = Pkg.TOML.parsefile(path)
compressed = convert(Dict{String,Dict{String,Union{String,Vector{String}}}}, compressed)
uncompressed = Dict{VersionNumber,Dict{String,T}}()
# Many of the entries are repeated so we keep a cache so there is no need to re-create
# a bunch of identical objects
cache = Dict{String,T}()
vsorted = sort(versions)
for (vers, data) in compressed
vs = Pkg.Types.VersionRange(vers)
first = length(vsorted) + 1
# We find the first and last version that are in the range
# and since the versions are sorted, all versions in between are sorted
for i in eachindex(vsorted)
v = vsorted[i]
v in vs && (first = i; break)
end
last = 0
for i in reverse(eachindex(vsorted))
v = vsorted[i]
v in vs && (last = i; break)
end
for i in first:last
v = vsorted[i]
uv = get!(() -> Dict{String,T}(), uncompressed, v)
for (key, value) in data
if haskey(uv, key)
error("Overlapping ranges for $(key) in $(repr(path)) for version $v.")
else
Tvalue = if value isa String
Tvalue = get!(() -> T(value), cache, value)
else
Tvalue = T(value)
end
uv[key] = Tvalue
end
end
end
end
return uncompressed
end
function load_deps(depsfile, versions)
r =
load_package_data(Base.UUID, depsfile, versions) isa
Dict{VersionNumber,Dict{String,Base.UUID}}
return r
end
function load_compat(compatfile, versions)
r =
load_package_data(Pkg.Types.VersionSpec, compatfile, versions) isa
Dict{VersionNumber,Dict{String,Pkg.Types.VersionSpec}}
return r
end
"""
test(path)
Run various checks on the registry located at `path`.
Checks for example that all files are parsable and
understandable by Pkg and consistency between Registry.toml
and each Package.toml.
If your registry has packages that have dependencies that are registered in other
registries elsewhere, then you may provide the github urls for those registries
using the `registry_deps` parameter.
"""
function test(path=pwd(); registry_deps::Vector{<:AbstractString}=String[])
Test.@testset "(Registry|Package|Versions|Deps|Compat).toml" begin
cd(path) do
reg = Pkg.TOML.parsefile("Registry.toml")
reguuids = Set{Base.UUID}(Base.UUID(x) for x in keys(reg["packages"]))
stdlibuuids = gather_stdlib_uuids()
registry_dep_uuids = load_registry_dep_uuids(registry_deps)
alluuids = reguuids ∪ stdlibuuids ∪ registry_dep_uuids
# Test that each entry in Registry.toml has a corresponding Package.toml
# at the expected path with the correct uuid and name
Test.@testset "$(get(data, "name", uuid))" for (uuid, data) in reg["packages"]
# Package.toml testing
pkg = Pkg.TOML.parsefile(abspath(data["path"], "Package.toml"))
Test.@test Base.UUID(uuid) == Base.UUID(pkg["uuid"])
Test.@test data["name"] == pkg["name"]
Test.@test Base.isidentifier(data["name"])
Test.@test haskey(pkg, "repo")
# Versions.toml testing
vers = Pkg.TOML.parsefile(abspath(data["path"], "Versions.toml"))
vnums = VersionNumber.(keys(vers))
for (v, data) in vers
Test.@test VersionNumber(v) isa VersionNumber
Test.@test haskey(data, "git-tree-sha1")
# https://github.com/JuliaRegistries/RegistryCI.jl/issues/523
# "yanked" is correct.
# "yank" (and all other variants) are incorrect.
Test.@test keys(data) ⊆ ["git-tree-sha1", "yanked"]
end
# Deps.toml testing
depsfile = abspath(data["path"], "Deps.toml")
if isfile(depsfile)
deps = Pkg.TOML.parsefile(depsfile)
# Require all deps to exist in the General registry or be a stdlib
depuuids = Set{Base.UUID}(
Base.UUID(x) for (_, d) in deps for (_, x) in d
)
if !(depuuids ⊆ alluuids)
msg = "It is not the case that all dependencies exist in the General registry"
@error msg setdiff(depuuids, alluuids)
end
Test.@test depuuids ⊆ alluuids
# Test that the way Pkg loads this data works
Test.@test load_deps(depsfile, vnums)
# Make sure the content roundtrips through decompression/compression
compressed = RegistryTools.Compress.compress(
depsfile, RegistryTools.Compress.load(depsfile)
)
Test.@test _spacify_hyphens(compressed) == _spacify_hyphens(deps)
else
@debug "Deps.toml file does not exist" depsfile
end
# Compat.toml testing
compatfile = abspath(data["path"], "Compat.toml")
if isfile(compatfile)
compat = Pkg.TOML.parsefile(compatfile)
# Test that all names with compat is a dependency
compatnames = Set{String}(x for (_, d) in compat for (x, _) in d)
if !(
isempty(compatnames) ||
(length(compatnames) == 1 && "julia" in compatnames)
)
depnames = Set{String}(
x for (_, d) in Pkg.TOML.parsefile(depsfile) for (x, _) in d
)
push!(depnames, "julia") # All packages has an implicit dependency on julia
if !(compatnames ⊆ depnames)
throw(
ErrorException("Assertion failed: compatnames ⊆ depnames")
)
end
end
# Test that the way Pkg loads this data works
Test.@test load_compat(compatfile, vnums)
# Make sure the content roundtrips through decompression/compression.
# However, before we check for equality, we change the compat ranges
# from `String`s to `VersionRanges`.
compressed = RegistryTools.Compress.compress(
compatfile, RegistryTools.Compress.load(compatfile)
)
mapvalues = (f, dict) -> Dict(k => f(v) for (k, v) in dict)
f_inner = v -> Pkg.Types.VersionRange.(v)
f_outer = dict -> mapvalues(f_inner, dict)
Test.@test _spacify_hyphens(mapvalues(f_outer, compressed)) == _spacify_hyphens(mapvalues(f_outer, compat))
else
@debug "Compat.toml file does not exist" compatfile
end
end
# Make sure all paths are unique
path_parts = [splitpath(data["path"]) for (_, data) in reg["packages"]]
for i in 1:maximum(length, path_parts)
i_parts = Set(
joinpath(x[1:i]...) for
x in path_parts if get(x, i, nothing) !== nothing
)
i_parts′ = Set(
joinpath(lowercase.(x[1:i])...) for
x in path_parts if get(x, i, nothing) !== nothing
)
Test.@test length(i_parts) == length(i_parts′)
end
end
end
return nothing
end
# Change all occurences of "digit-digit" to "digit - digit"
function _spacify_hyphens(str::AbstractString)
r = r"(\d)-(\d)"
s = s"\1 - \2"
new_str = replace(str, r => s)
end
# Apply `_spacify_hyphens()` recursively through a dictionary
function _spacify_hyphens(dict::Dict{K, V}) where {K, V}
new_dict = Dict{K, V}()
# Note: `Base.Dict` iterates key-value pairs, so it's sufficient for us to do
# `for (k, v) in dict`. However, there are some other dictionary implementations
# (such as the Dictionaries.jl package) that do not iterate key-value pairs. So,
# if we ever decide to widen the type signature of this method, we'll need to
# change `(k, v) in dict` to `(k, v) in pairs(dict)`.
for (k, v) in dict
new_k = _spacify_hyphens(k)
new_v = _spacify_hyphens(v)
end
return new_dict
end
_spacify_hyphens(range::Pkg.Types.VersionRange) = range
_spacify_hyphens(ranges::Vector{Pkg.Types.VersionRange}) = ranges
| RegistryCI | https://github.com/JuliaRegistries/RegistryCI.jl.git |
|
[
"MIT"
] | 10.7.0 | f0341c8179a869629d90fe549511d6ffaf1da9a1 | code | 669 | function with_temp_dir(f::Function)
original_working_directory = pwd()
temp_dir = mktempdir()
atexit(() -> rm(temp_dir; force=true, recursive=true))
cd(temp_dir)
result = f(temp_dir)
cd(original_working_directory)
rm(temp_dir; force=true, recursive=true)
return result
end
function with_temp_depot(f::Function)
original_depot_path = deepcopy(Base.DEPOT_PATH)
result = with_temp_dir() do temp_depot
empty!(Base.DEPOT_PATH)
push!(Base.DEPOT_PATH, temp_depot)
return f()
end
empty!(Base.DEPOT_PATH)
for x in original_depot_path
push!(Base.DEPOT_PATH, x)
end
return result
end
| RegistryCI | https://github.com/JuliaRegistries/RegistryCI.jl.git |
|
[
"MIT"
] | 10.7.0 | f0341c8179a869629d90fe549511d6ffaf1da9a1 | code | 944 | module AutoMerge
using Dates: Dates
# import GitCommand
using GitHub: GitHub
using HTTP: HTTP
using LibGit2: LibGit2
using Pkg: Pkg
using TimeZones: TimeZones
using JSON: JSON
using VisualStringDistances: VisualStringDistances
using StringDistances: StringDistances
using LicenseCheck: LicenseCheck
using TOML: TOML
using Printf: Printf
using RegistryTools: RegistryTools
using ..RegistryCI: RegistryCI
using Tar: Tar
include("types.jl")
include("ciservice.jl")
include("api_rate_limiting.jl")
include("assert.jl")
include("automerge_comment.jl")
include("changed_files.jl")
include("cron.jl")
include("dates.jl")
include("dependency_confusion.jl")
include("github.jl")
include("guidelines.jl")
include("jll.jl")
include("not_automerge_applicable.jl")
include("package_path_in_registry.jl")
include("public.jl")
include("pull_requests.jl")
include("semver.jl")
include("toml.jl")
include("update_status.jl")
include("util.jl")
end # module
| RegistryCI | https://github.com/JuliaRegistries/RegistryCI.jl.git |
|
[
"MIT"
] | 10.7.0 | f0341c8179a869629d90fe549511d6ffaf1da9a1 | code | 128 | function my_retry(f::Function)
delays = ExponentialBackOff(; n=10, max_delay=30.0)
return retry(f; delays=delays)()
end
| RegistryCI | https://github.com/JuliaRegistries/RegistryCI.jl.git |
|
[
"MIT"
] | 10.7.0 | f0341c8179a869629d90fe549511d6ffaf1da9a1 | code | 446 | AlwaysAssertionError() = AlwaysAssertionError("")
# The documentation for the `Base.@assert` macro says: "Warning: An assert might be
# disabled at various optimization levels."
# Therefore, we have the `always_assert` function. `always_assert` is like
# `Base.@assert`, except that `always_assert` will always run and will never be
# disabled.
function always_assert(cond::Bool)
cond || throw(AlwaysAssertionError())
return nothing
end
| RegistryCI | https://github.com/JuliaRegistries/RegistryCI.jl.git |
|
[
"MIT"
] | 10.7.0 | f0341c8179a869629d90fe549511d6ffaf1da9a1 | code | 1642 | function update_automerge_comment!(data::GitHubAutoMergeData, body::AbstractString)::Nothing
if data.read_only
@info "`read_only` mode; skipping updating automerge comment."
return nothing
end
api = data.api
repo = data.registry
pr = data.pr
auth = data.auth
whoami = data.whoami
my_comments = my_retry(
() -> get_all_my_pull_request_comments(api, repo, pr; auth=auth, whoami=whoami)
)
num_comments = length(my_comments)
_body = string(
strip(
string(
body, "\n", "<!---\n", "this_is_the_single_automerge_comment\n", "--->\n"
),
),
)
if num_comments > 1
for i in 2:num_comments
comment_to_delete = my_comments[i]
try
my_retry(() -> delete_comment!(api, repo, pr, comment_to_delete; auth=auth))
catch ex
@error("Ignoring error: ", exception = (ex, catch_backtrace()))
end
end
comment_to_update = my_comments[1]
if strip(comment_to_update.body) != _body
my_retry(
() -> edit_comment!(api, repo, pr, comment_to_update, _body; auth=auth)
)
end
elseif num_comments == 1
comment_to_update = my_comments[1]
if strip(comment_to_update.body) != _body
my_retry(
() -> edit_comment!(api, repo, pr, comment_to_update, _body; auth=auth)
)
end
else
always_assert(num_comments < 1)
my_retry(() -> post_comment!(api, repo, pr, _body; auth=auth))
end
return nothing
end
| RegistryCI | https://github.com/JuliaRegistries/RegistryCI.jl.git |
|
[
"MIT"
] | 10.7.0 | f0341c8179a869629d90fe549511d6ffaf1da9a1 | code | 2939 | function allowed_changed_files(::NewPackage, pkg::String)
_package_relpath_per_scheme = _get_package_relpath_per_name_scheme(; package_name=pkg)
result = String[
"Registry.toml",
"$(_package_relpath_per_scheme)/Compat.toml",
"$(_package_relpath_per_scheme)/WeakCompat.toml",
"$(_package_relpath_per_scheme)/Deps.toml",
"$(_package_relpath_per_scheme)/WeakDeps.toml",
"$(_package_relpath_per_scheme)/Package.toml",
"$(_package_relpath_per_scheme)/Versions.toml",
]
return result
end
function allowed_changed_files(::NewVersion, pkg::String)
_package_relpath_per_scheme = _get_package_relpath_per_name_scheme(; package_name=pkg)
result = String[
"$(_package_relpath_per_scheme)/Compat.toml",
"$(_package_relpath_per_scheme)/WeakCompat.toml",
"$(_package_relpath_per_scheme)/Deps.toml",
"$(_package_relpath_per_scheme)/WeakDeps.toml",
"$(_package_relpath_per_scheme)/Versions.toml",
]
return result
end
const guideline_pr_only_changes_allowed_files = Guideline(;
info="Only modifies the files that it's allowed to modify.",
docs=nothing,
check=data -> pr_only_changes_allowed_files(
data.api,
data.registration_type,
data.registry,
data.pr,
data.pkg;
auth=data.auth,
),
)
function pr_only_changes_allowed_files(
api::GitHub.GitHubAPI,
t::Union{NewPackage,NewVersion},
registry::GitHub.Repo,
pr::GitHub.PullRequest,
pkg::String;
auth::GitHub.Authorization,
)
_allowed_changed_files = allowed_changed_files(t, pkg)
_num_allowed_changed_files = length(_allowed_changed_files)
this_pr_num_changed_files = num_changed_files(pr)
if this_pr_num_changed_files > _num_allowed_changed_files
g0 = false
m0 = "This PR is allowed to modify at most $(_num_allowed_changed_files) files, but it actually modified $(this_pr_num_changed_files) files."
return g0, m0
else
this_pr_changed_files = get_changed_filenames(api, registry, pr; auth=auth)
if length(this_pr_changed_files) != this_pr_num_changed_files
g0 = false
m0 = "Something weird happened when I tried to get the list of changed files"
return g0, m0
else
if issubset(this_pr_changed_files, _allowed_changed_files)
g0 = true
m0 = ""
return g0, m0
else
g0 = false
m0 = string(
"This pull request modified at least one file ",
"that it is not allowed to modify. It is only ",
"allowed to modify the following files ",
"(or a subset thereof): ",
"$(join(_allowed_changed_files, ", "))",
)
return g0, m0
end
end
end
end
| RegistryCI | https://github.com/JuliaRegistries/RegistryCI.jl.git |
|
[
"MIT"
] | 10.7.0 | f0341c8179a869629d90fe549511d6ffaf1da9a1 | code | 5514 | abstract type CIService end
###############
## Travis CI ##
###############
struct TravisCI <: CIService
enable_cron_builds::Bool
enable_api_builds::Bool
function TravisCI(; enable_cron_builds=true, enable_api_builds=true)
return new(enable_cron_builds, enable_api_builds)
end
end
function conditions_met_for_pr_build(cfg::TravisCI; env=ENV, master_branch, kwargs...)
return get(env, "TRAVIS_EVENT_TYPE", nothing) == "pull_request" &&
get(env, "TRAVIS_BRANCH", nothing) == master_branch
end
function conditions_met_for_merge_build(cfg::TravisCI; env=ENV, master_branch, kwargs...)
## Check that we are on the correct branch
branch_ok = get(env, "TRAVIS_BRANCH", nothing) == master_branch
## Check that we are running a cron or api job
event_type = get(env, "TRAVIS_EVENT_TYPE", nothing)
cron_ok = event_type == "cron" && cfg.enable_cron_builds
api_ok = event_type == "api" && cfg.enable_api_builds
return branch_ok && (cron_ok || api_ok)
end
function pull_request_number(cfg::TravisCI; env=ENV, kwargs...)
return parse(Int, env["TRAVIS_PULL_REQUEST"])
end
function current_pr_head_commit_sha(cfg::TravisCI; env=ENV, kwargs...)
return env["TRAVIS_PULL_REQUEST_SHA"]
end
function directory_of_cloned_registry(cfg::TravisCI; env=ENV, kwargs...)
return env["TRAVIS_BUILD_DIR"]
end
function username(api::GitHub.GitHubAPI, cfg::TravisCI; auth)
return username(api, auth) # use /user endpoint
end
####################
## GitHub Actions ##
####################
struct GitHubActions <: CIService
enable_cron_builds::Bool
function GitHubActions(; enable_cron_builds=true)
return new(enable_cron_builds)
end
end
function conditions_met_for_pr_build(cfg::GitHubActions; env=ENV, kwargs...)
# TODO: Should also check the PR is against "master" or maybe thats done later?
return get(env, "GITHUB_EVENT_NAME", nothing) == "pull_request"
end
function conditions_met_for_merge_build(
cfg::GitHubActions; env=ENV, master_branch, kwargs...
)
## Check that we are on the correct branch
m = match(r"^refs\/heads\/(.*)$", get(env, "GITHUB_REF", ""))
branch_ok = m !== nothing && m.captures[1] == master_branch
## Check that we are running a cron job
event_type = get(env, "GITHUB_EVENT_NAME", nothing)
is_schedule = event_type == "schedule"
is_workflow_dispatch = event_type == "workflow_dispatch"
is_schedule_or_workflow_dispatch = is_schedule || is_workflow_dispatch
cron_ok = is_schedule_or_workflow_dispatch && cfg.enable_cron_builds
result = branch_ok && cron_ok
return result
end
function pull_request_number(cfg::GitHubActions; env=ENV, kwargs...)
m = match(r"^refs\/pull\/(\d+)\/merge$", get(env, "GITHUB_REF", ""))
always_assert(m !== nothing)
return parse(Int, m.captures[1])
end
function current_pr_head_commit_sha(cfg::GitHubActions; env=ENV, kwargs...)
always_assert(get(env, "GITHUB_EVENT_NAME", nothing) == "pull_request")
file = get(env, "GITHUB_EVENT_PATH", nothing)
file === nothing && return nothing
content = JSON.parsefile(file)
return content["pull_request"]["head"]["sha"]
end
function directory_of_cloned_registry(cfg::GitHubActions; env=ENV, kwargs...)
return get(env, "GITHUB_WORKSPACE", nothing)
end
function username(api::GitHub.GitHubAPI, cfg::GitHubActions; auth)
# /user endpoint of GitHub API not available
# with the GITHUB_TOKEN authentication
return "github-actions[bot]"
end
##############
## TeamCity ##
##############
struct TeamCity <: CIService end
function conditions_met_for_pr_build(cfg::TeamCity; env=ENV, kwargs...)
pr_number_ok = tryparse(Int, get(env, "teamcity_pullRequest_number", "")) !== nothing
return haskey(env, "teamcity_pullRequest_title") && pr_number_ok
end
function conditions_met_for_merge_build(cfg::TeamCity; env=ENV, master_branch, kwargs...)
pr_number_ok = tryparse(Int, get(env, "teamcity_pullRequest_number", "")) !== nothing
haskey(env, "teamcity_pullRequest_title") && pr_number_ok && return false
## Check that we are on the correct branch
m = match(r"^refs\/heads\/(.*)$", get(env, "vcsroot_branch", ""))
branch_ok = m !== nothing && m.captures[1] == master_branch
return branch_ok
end
function pull_request_number(cfg::TeamCity; env=ENV, kwargs...)
pr_number = tryparse(Int, get(env, "teamcity_pullRequest_number", ""))
always_assert(pr_number !== nothing)
return pr_number
end
function current_pr_head_commit_sha(cfg::TeamCity; env=ENV, kwargs...)
# black magic relying on TC build parameter teamcity.git.fetchAllHeads=true
tc_pr_branch_name = get(env, "teamcity_pullRequest_source_branch", nothing)
always_assert(!isnothing(tc_pr_branch_name))
git_info = read(pipeline(`git show-ref`, `grep $tc_pr_branch_name`), String)
git_info_row = split(git_info, "\n")[1]
pr_sha = split(git_info_row, " ")[1]
return string(pr_sha)
end
directory_of_cloned_registry(cfg::TeamCity; env=ENV, kwargs...) = get(env, "PWD", nothing)
username(api::GitHub.GitHubAPI, cfg::TeamCity; auth) = "svc-aivision-reg"
####################
## Auto detection ##
####################
function auto_detect_ci_service(; env=ENV)
if haskey(env, "TRAVIS_REPO_SLUG")
return TravisCI()
elseif haskey(env, "GITHUB_REPOSITORY")
return GitHubActions()
elseif haskey(env, "TEAMCITY_PROJECT_NAME")
return TeamCity()
else
error("Could not detect system.")
end
end
| RegistryCI | https://github.com/JuliaRegistries/RegistryCI.jl.git |
|
[
"MIT"
] | 10.7.0 | f0341c8179a869629d90fe549511d6ffaf1da9a1 | code | 16982 | using GitHub: GitHub
function all_specified_statuses_passed(
api::GitHub.GitHubAPI,
registry::GitHub.Repo,
pr::GitHub.PullRequest,
sha::AbstractString,
specified_status_contexts::AbstractVector{<:AbstractString};
auth::GitHub.Authorization,
)
# Keep track of the values of the specified statuses. If all of
# these are switched over to true, the result is a success. Do not
# care about the result of unspecified statuses.
status_passed = Dict{String,Bool}(
context => false for context in specified_status_contexts
)
combined_status = GitHub.status(api, registry, sha; auth=auth)
all_statuses = combined_status.statuses
for status in all_statuses
context = status.context
if haskey(status_passed, context)
status_passed[context] = status.state == "success"
end
end
return all(values(status_passed))
end
function all_specified_check_runs_passed(
api::GitHub.GitHubAPI,
registry::GitHub.Repo,
pr::GitHub.PullRequest,
sha::AbstractString,
specified_checks::AbstractVector{<:AbstractString};
auth::GitHub.Authorization,
)
# Keep track of the results of the specified checks. If all of
# these are switched over to true, the result is a success. Do not
# care about the result of unspecified checks.
check_passed = Dict{String,Bool}(context => false for context in specified_checks)
endpoint = "/repos/$(registry.full_name)/commits/$(sha)/check-runs"
check_runs = GitHub.gh_get_json(
api,
endpoint;
auth=auth,
headers=Dict("Accept" => "application/vnd.github.antiope-preview+json"),
)
for check_run in check_runs["check_runs"]
name = check_run["name"]
check_run_was_success =
(check_run["status"] == "completed") && (check_run["conclusion"] == "success")
if haskey(check_passed, name)
check_passed[name] = check_run_was_success
end
end
return all(values(check_passed))
end
function pr_comment_is_blocking(c::GitHub.Comment)
# Note: `[merge approved]` is not case sensitive, to match the semantics of `contains` on GitHub Actions
not_blocking = occursin("[noblock]", body(c)) || occursin("[merge approved]", lowercase(body(c)))
return !not_blocking
end
function pr_has_no_blocking_comments(
api::GitHub.GitHubAPI,
registry::GitHub.Repo,
pr::GitHub.PullRequest;
auth::GitHub.Authorization,
)
all_pr_comments = get_all_pull_request_comments(api, registry, pr; auth=auth)
return !any(pr_comment_is_blocking.(all_pr_comments))
end
function pr_is_old_enough(
pr_type::Symbol,
pr_age::Dates.Period;
pkg::AbstractString,
new_package_waiting_period::Dates.Period,
new_jll_package_waiting_period::Dates.Period,
new_version_waiting_period::Dates.Period,
new_jll_version_waiting_period::Dates.Period,
pr_author,
authorized_authors,
authorized_authors_special_jll_exceptions,
)
this_is_jll_package = is_jll_name(pkg)
if this_is_jll_package
if pr_author in authorized_authors_special_jll_exceptions
this_pr_can_use_special_jll_exceptions = true
else
this_pr_can_use_special_jll_exceptions = false
end
else
this_pr_can_use_special_jll_exceptions = false
end
if this_pr_can_use_special_jll_exceptions
if pr_type == :NewPackage
return pr_age > new_jll_package_waiting_period
elseif pr_type == :NewVersion
return pr_age > new_jll_version_waiting_period
else
throw(ArgumentError("pr_type must be either :NewPackage or :NewVersion"))
end
else
if pr_type == :NewPackage
return pr_age > new_package_waiting_period
elseif pr_type == :NewVersion
return pr_age > new_version_waiting_period
else
throw(ArgumentError("pr_type must be either :NewPackage or :NewVersion"))
end
end
end
function _get_all_pr_statuses(
api::GitHub.GitHubAPI,
repo::GitHub.Repo,
pr::GitHub.PullRequest;
auth::GitHub.Authorization,
)
combined_status = GitHub.status(api, repo, pr.head.sha; auth=auth)
all_statuses = combined_status.statuses
return all_statuses
end
function _get_status_description(status::GitHub.Status)::String
if hasproperty(status, :description)
if status.description === nothing
return ""
else
return status.description
end
else
return ""
end
end
function _postprocess_automerge_decision_status(status::GitHub.Status; whoami)
@debug("status: ", status)
@debug("status.creator: ", status.creator)
new_package_passed_regex = r"New package. Approved. name=\"(\w*)\". sha=\"(\w*)\""
new_version_passed_regex = r"New version. Approved. name=\"(\w*)\". sha=\"(\w*)\""
status_description = _get_status_description(status)
if status.state == "success" && occursin(new_package_passed_regex, status_description)
m = match(new_package_passed_regex, status_description)
passed_pkg_name = m[1]
passed_pr_head_sha = m[2]
return true, passed_pkg_name, passed_pr_head_sha, :NewPackage
end
if status.state == "success" && occursin(new_version_passed_regex, status_description)
m = match(new_version_passed_regex, status_description)
passed_pkg_name = m[1]
passed_pr_head_sha = m[2]
return true, passed_pkg_name, passed_pr_head_sha, :NewVersion
end
return false, "", "", :failing
end
function pr_has_passing_automerge_decision_status(
api::GitHub.GitHubAPI,
repo::GitHub.Repo,
pr::GitHub.PullRequest;
auth::GitHub.Authorization,
whoami,
)
all_statuses = _get_all_pr_statuses(api, repo, pr; auth=auth)
for status in all_statuses
if status.context == "automerge/decision"
return _postprocess_automerge_decision_status(status; whoami=whoami)
end
end
return false, "", "", :failing
end
function cron_or_api_build(
api::GitHub.GitHubAPI,
registry::GitHub.Repo;
auth::GitHub.Authorization,
authorized_authors::Vector{String},
authorized_authors_special_jll_exceptions::Vector{String},
merge_new_packages::Bool,
merge_new_versions::Bool,
new_package_waiting_period,
new_jll_package_waiting_period,
new_version_waiting_period,
new_jll_version_waiting_period,
whoami::String,
all_statuses::AbstractVector{<:AbstractString},
all_check_runs::AbstractVector{<:AbstractString},
read_only::Bool,
)
# first, get a list of ALL open pull requests on this repository
# then, loop through each of them.
all_currently_open_pull_requests = my_retry(
() -> get_all_pull_requests(api, registry, "open"; auth=auth)
)
reverse!(all_currently_open_pull_requests)
at_least_one_exception_was_thrown = false
if isempty(all_currently_open_pull_requests)
@info("There are no open pull requests.")
else
for pr in all_currently_open_pull_requests
try
my_retry() do
cron_or_api_build(
api,
pr,
registry;
auth=auth,
authorized_authors=authorized_authors,
authorized_authors_special_jll_exceptions=authorized_authors_special_jll_exceptions,
merge_new_packages=merge_new_packages,
merge_new_versions=merge_new_versions,
new_package_waiting_period=new_package_waiting_period,
new_jll_package_waiting_period=new_jll_package_waiting_period,
new_version_waiting_period=new_version_waiting_period,
new_jll_version_waiting_period=new_jll_version_waiting_period,
whoami=whoami,
all_statuses=all_statuses,
all_check_runs=all_check_runs,
read_only=read_only,
)
end
catch ex
at_least_one_exception_was_thrown = true
showerror(stderr, ex)
Base.show_backtrace(stderr, catch_backtrace())
println(stderr)
end
end
if at_least_one_exception_was_thrown
throw(
AutoMergeCronJobError(
"At least one exception was thrown. Check the logs for details."
),
)
end
end
return nothing
end
function cron_or_api_build(
api::GitHub.GitHubAPI,
pr::GitHub.PullRequest,
registry::GitHub.Repo;
auth::GitHub.Authorization,
authorized_authors::Vector{String},
authorized_authors_special_jll_exceptions::Vector{String},
merge_new_packages::Bool,
merge_new_versions::Bool,
new_package_waiting_period,
new_jll_package_waiting_period,
new_version_waiting_period,
new_jll_version_waiting_period,
whoami::String,
all_statuses::AbstractVector{<:AbstractString},
all_check_runs::AbstractVector{<:AbstractString},
read_only::Bool,
)
# first, see if the author is an authorized author. if not, then skip.
# next, see if the title matches either the "New Version" regex or
# the "New Package regex". if it is not either a new
# package or a new version, skip.
# next, see if it is old enough. if it is not old enough, then skip.
# then, get the `automerge/decision` status and make sure it is passing
# then, get all of the pull request comments. if there is any comment that is
# (1) not by me, and (2) does not contain the text [noblock], then skip
# if all of the above criteria were met, then merge the pull request
pr_number = number(pr)
@info("Now examining pull request $(pr_number)")
pr_author = author_login(pr)
if pr_author ∉ vcat(authorized_authors, authorized_authors_special_jll_exceptions)
@info(
string(
"Pull request: $(pr_number). ",
"Decision: do not merge. ",
"Reason: pull request author is not authorized to automerge.",
),
pr_author,
authorized_authors,
authorized_authors_special_jll_exceptions
)
return nothing
end
if !(is_new_package(pr) || is_new_version(pr))
@info(
string(
"Pull request: $(pr_number). ",
"Decision: do not merge. ",
"Reason: pull request is neither a new package nor a new version.",
),
title(pr)
)
return nothing
end
if is_new_package(pr) # it is a new package
pr_type = :NewPackage
pkg, version = parse_pull_request_title(NewPackage(), pr)
else # it is a new version
pr_type = :NewVersion
pkg, version = parse_pull_request_title(NewVersion(), pr)
end
pr_age = time_since_pr_creation(pr)
this_pr_is_old_enough = pr_is_old_enough(
pr_type,
pr_age;
pkg=pkg,
new_package_waiting_period=new_package_waiting_period,
new_jll_package_waiting_period=new_jll_package_waiting_period,
new_version_waiting_period=new_version_waiting_period,
new_jll_version_waiting_period=new_jll_version_waiting_period,
pr_author=pr_author,
authorized_authors=authorized_authors,
authorized_authors_special_jll_exceptions=authorized_authors_special_jll_exceptions,
)
if !this_pr_is_old_enough
@info(
string(
"Pull request: $(pr_number). ",
"Type: $(pr_type). ",
"Decision: do not merge. ",
"Reason: mandatory waiting period has not elapsed.",
),
pr_type,
pr_age,
_canonicalize_period(pr_age),
pkg,
is_jll_name(pkg),
new_package_waiting_period,
_canonicalize_period(new_package_waiting_period),
new_jll_package_waiting_period,
_canonicalize_period(new_jll_package_waiting_period),
new_version_waiting_period,
_canonicalize_period(new_version_waiting_period),
new_jll_version_waiting_period,
_canonicalize_period(new_jll_version_waiting_period),
pr_author,
authorized_authors,
authorized_authors_special_jll_exceptions
)
return nothing
end
i_passed_this_pr, passed_pkg_name, passed_pr_head_sha, status_pr_type = pr_has_passing_automerge_decision_status(
api, registry, pr; auth=auth, whoami=whoami
)
if !i_passed_this_pr
@info(
string(
"Pull request: $(pr_number). ",
"Type: $(pr_type). ",
"Decision: do not merge. ",
"Reason: automerge/decision status is not passing",
),
whoami
)
return nothing
end
always_assert(pkg == passed_pkg_name)
always_assert(pr.head.sha == passed_pr_head_sha)
_statuses_good = all_specified_statuses_passed(
api, registry, pr, passed_pr_head_sha, all_statuses; auth=auth
)
_checkruns_good = all_specified_check_runs_passed(
api, registry, pr, passed_pr_head_sha, all_check_runs; auth=auth
)
if !(_statuses_good && _checkruns_good)
@error(
string(
"Pull request: $(pr_number). ",
"Type: $(pr_type). ",
"Decision: do not merge. ",
"Reason: ",
"It is not the case that ",
"all of the specified statuses and ",
"check runs passed. ",
)
)
return nothing
end
if !pr_has_no_blocking_comments(api, registry, pr; auth=auth)
@info(
string(
"Pull request: $(pr_number). ",
"Type: $(pr_type). ",
"Decision: do not merge. ",
"Reason: pull request has one or more blocking comments.",
)
)
return nothing
end
if pr_type == :NewPackage # it is a new package
always_assert(status_pr_type == :NewPackage)
if merge_new_packages
@info(
string(
"Pull request: $(pr_number). ",
"Type: $(pr_type). ",
"Decision: merge now.",
)
)
if read_only
@info "`read_only` mode on; skipping merge"
else
my_retry(() -> merge!(api, registry, pr, passed_pr_head_sha; auth=auth))
end
else
@info(
string(
"Pull request: $(pr_number). ",
"Type: $(pr_type). ",
"Decision: do not merge. ",
"Reason: ",
"This is a new package pull request. ",
"All of the criteria for automerging ",
"were met. ",
"However, merge_new_packages is false, ",
"so I will not merge. ",
"If merge_new_packages had been set to ",
"true, I would have merged this ",
"pull request right now.",
)
)
end
else # it is a new version
always_assert(pr_type == :NewVersion)
always_assert(status_pr_type == :NewVersion)
if merge_new_versions
@info(
string(
"Pull request: $(pr_number). ",
"Type: $(pr_type). ",
"Decision: merge now.",
)
)
if read_only
@info "`read_only` mode on; skipping merge"
else
my_retry(() -> merge!(api, registry, pr, passed_pr_head_sha; auth=auth))
end
else
@info(
string(
"Pull request: $(pr_number). ",
"Type: $(pr_type). ",
"Decision: do not merge. ",
"Reason: merge_new_versions is false",
"This is a new version pull request. ",
"All of the criteria for automerging ",
"were met. ",
"However, merge_new_versions is false, ",
"so I will not merge. ",
"If merge_new_versions had been set to ",
"true, I would have merged this ",
"pull request right now.",
)
)
end
end
return nothing
end
| RegistryCI | https://github.com/JuliaRegistries/RegistryCI.jl.git |
|
[
"MIT"
] | 10.7.0 | f0341c8179a869629d90fe549511d6ffaf1da9a1 | code | 201 | function _canonicalize_period(p::Dates.CompoundPeriod)
return Dates.canonicalize(p)
end
function _canonicalize_period(p::Dates.Period)
return _canonicalize_period(Dates.CompoundPeriod(p))
end
| RegistryCI | https://github.com/JuliaRegistries/RegistryCI.jl.git |
|
[
"MIT"
] | 10.7.0 | f0341c8179a869629d90fe549511d6ffaf1da9a1 | code | 2426 | # TODO: Add a more thorough explanation of the dependency confusion
# vulnerability and how this guideline mitigates it.
const guideline_dependency_confusion = Guideline(;
info="No UUID conflict with other registries.",
docs=nothing,
check=data ->
has_no_dependency_confusion(data.pkg, data.registry_head, data.public_registries),
)
# TODO: Needs a strategy to handle connection failures for the public
# registries. Preferably they should also be cloned only once and then
# just updated to mitigate the effect of them being temporarily
# offline. This could be implemented with the help of the Scratch
# package, but requires Julia >= 1.5.
function has_no_dependency_confusion(pkg, registry_head, public_registries)
uuid, package_repo = parse_registry_pkg_info(registry_head, pkg)
for repo in public_registries
try
registry = clone_repo(repo)
registry_toml = TOML.parsefile(joinpath(registry, "Registry.toml"))
packages = registry_toml["packages"]
if haskey(packages, uuid)
message = string(
"UUID $uuid conflicts with the package ",
packages[uuid]["name"],
" in registry ",
registry_toml["name"],
" at $repo. ",
"This could be a dependency confusion attack.",
)
# Conflict detected. This is benign if the package name
# *and* the package URL matches.
if packages[uuid]["name"] != pkg
return false, message
end
package_path = packages[uuid]["path"]
other_package_repo = TOML.parsefile(
joinpath(registry, package_path, "Package.toml")
)["repo"]
if package_repo != other_package_repo
return false, message
end
end
catch
message = string(
"Failed to clone public registry $(repo) for a check against dependency confusion.\n",
"This is an internal issue with the AutoMerge process and has nothing to do with "."the package being registered but requires manual intervention before AutoMerge ",
"can be resumed.",
)
return false, message
end
end
return true, ""
end
| RegistryCI | https://github.com/JuliaRegistries/RegistryCI.jl.git |
|
[
"MIT"
] | 10.7.0 | f0341c8179a869629d90fe549511d6ffaf1da9a1 | code | 6862 | author_login(pull_request::GitHub.PullRequest) = pull_request.user.login
base_repo(pull_request::GitHub.PullRequest) = pull_request.base.repo
body(c::GitHub.Comment) = c.body
body(pr::GitHub.PullRequest) = pr.body
function created_at(pull_request::GitHub.PullRequest)
result = time_is_already_in_utc(pull_request.created_at)
return result
end
function delete_comment!(
api::GitHub.GitHubAPI,
repo::GitHub.Repo,
pr::GitHub.PullRequest,
comment_to_delete::GitHub.Comment;
auth::GitHub.Authorization,
)
GitHub.delete_comment(api, repo, comment_to_delete, :pr; auth=auth)
return nothing
end
function delete_merged_branch!(
api::GitHub.GitHubAPI,
repo::GitHub.Repo,
pr::GitHub.PullRequest;
auth::GitHub.Authorization,
)
updated_pr = _get_updated_pull_request(api, pr; auth=auth)
if is_merged(updated_pr)
try
head_branch = pull_request_head_branch(updated_pr)
repo = head_branch.repo
ref = "heads/$(head_branch.ref)"
GitHub.delete_reference(api, repo, ref; auth=auth)
catch ex
# showerror(stderr, ex)
# Base.show_backtrace(stderr, catch_backtrace())
# println(stderr)
end
end
return nothing
end
function edit_comment!(
api::GitHub.GitHubAPI,
repo::GitHub.Repo,
pr::GitHub.PullRequest,
comment::GitHub.Comment,
body::String;
auth::GitHub.Authorization,
)
myparams = Dict("body" => body)
GitHub.edit_comment(api, repo, comment, :pr; auth=auth, params=myparams)
return nothing
end
full_name(repo::GitHub.Repo) = repo.full_name
function _get_updated_pull_request(
api::GitHub.GitHubAPI, pull_request::GitHub.PullRequest; auth::GitHub.Authorization
)
pr_base_repo = base_repo(pull_request)
pr_number = number(pull_request)
updated_pr = GitHub.pull_request(api, pr_base_repo, pr_number; auth=auth)
return updated_pr
end
function get_all_my_pull_request_comments(
api::GitHub.GitHubAPI,
repo::GitHub.Repo,
pr::GitHub.PullRequest;
auth::GitHub.Authorization,
whoami,
)
all_comments = get_all_pull_request_comments(api, repo, pr; auth=auth)
my_comments = GitHub.Comment[]
for c in all_comments
if c.user.login == whoami
push!(my_comments, c)
end
end
unique!(my_comments)
my_comments = my_comments[sortperm([x.created_at for x in my_comments])]
return my_comments
end
function get_all_pull_request_comments(
api::GitHub.GitHubAPI,
repo::GitHub.Repo,
pr::GitHub.PullRequest;
auth::GitHub.Authorization,
)
all_comments = GitHub.Comment[]
myparams = Dict("per_page" => 100, "page" => 1)
cs, page_data = GitHub.comments(
api, repo, pr, :pr; auth=auth, params=myparams, page_limit=100
)
append!(all_comments, cs)
while haskey(page_data, "next")
cs, page_data = GitHub.comments(
api, repo, pr, :pr; auth=auth, page_limit=100, start_page=page_data["next"]
)
append!(all_comments, cs)
end
unique!(all_comments)
all_comments = all_comments[sortperm([x.created_at for x in all_comments])]
return all_comments
end
function get_all_pull_requests(
api::GitHub.GitHubAPI, repo::GitHub.Repo, state::String; auth::GitHub.Authorization
)
all_pull_requests = GitHub.PullRequest[]
myparams = Dict("state" => state, "per_page" => 100, "page" => 1)
prs, page_data = GitHub.pull_requests(
api, repo; auth=auth, params=myparams, page_limit=100
)
append!(all_pull_requests, prs)
while haskey(page_data, "next")
prs, page_data = GitHub.pull_requests(
api, repo; auth=auth, page_limit=100, start_page=page_data["next"]
)
append!(all_pull_requests, prs)
end
unique!(all_pull_requests)
return all_pull_requests
end
function get_changed_filenames(
api::GitHub.GitHubAPI,
repo::GitHub.Repo,
pull_request::GitHub.PullRequest;
auth::GitHub.Authorization,
)
files = GitHub.pull_request_files(api, repo, pull_request; auth=auth)
return [file.filename for file in files]
end
is_merged(pull_request::GitHub.PullRequest) = pull_request.merged
function is_open(pull_request::GitHub.PullRequest)
result = pr_state(pull_request) == "open"
!result && @error("Pull request is not open")
return result
end
function merge!(
api::GitHub.GitHubAPI,
registry_repo::GitHub.Repo,
pr::GitHub.PullRequest,
approved_pr_head_sha::AbstractString;
auth::GitHub.Authorization,
)
pr = wait_pr_compute_mergeability(api, registry_repo, pr; auth=auth)
_approved_pr_head_sha = convert(String, strip(approved_pr_head_sha))::String
pr_number = number(pr)
@info("Attempting to squash-merge pull request #$(pr_number)")
@debug("sha = $(_approved_pr_head_sha)")
@debug("pr.mergeable = $(pr.mergeable)")
params = Dict("sha" => _approved_pr_head_sha, "merge_method" => "squash")
try
GitHub.merge_pull_request(api, registry_repo, pr_number; auth=auth, params=params)
catch ex
showerror(stderr, ex)
Base.show_backtrace(stderr, catch_backtrace())
println(stderr)
end
try
delete_merged_branch!(api, registry_repo, pr; auth=auth)
catch
end
return nothing
end
function wait_pr_compute_mergeability(
api::GitHub.GitHubAPI,
repo::GitHub.Repo,
pr::GitHub.PullRequest;
auth::GitHub.Authorization,
)
sleep(5)
max_tries = 10
num_tries = 0
pr = GitHub.pull_request(api, repo, pr.number; auth=auth)
while !(pr.mergeable isa Bool) && num_tries <= max_tries
num_tries += 1
sleep(5)
pr = GitHub.pull_request(api, repo, pr.number; auth=auth)
end
return pr
end
num_changed_files(pull_request::GitHub.PullRequest) = pull_request.changed_files
number(pull_request::GitHub.PullRequest) = pull_request.number
function post_comment!(
api::GitHub.GitHubAPI,
repo::GitHub.Repo,
pr::GitHub.PullRequest,
body::String;
auth::GitHub.Authorization,
)
myparams = Dict("body" => body)
GitHub.create_comment(api, repo, pr, :pr; auth=auth, params=myparams)
return nothing
end
pull_request_head_branch(pull_request::GitHub.PullRequest) = pull_request.head
pull_request_head_sha(pull_request::GitHub.PullRequest) = pull_request.head.sha
repo_url(repo::GitHub.Repo) = repo.html_url.uri
pr_state(pull_request::GitHub.PullRequest) = pull_request.state
function time_since_pr_creation(pull_request::GitHub.PullRequest)
return now_utc() - created_at(pull_request)
end
title(pull_request::GitHub.PullRequest) = pull_request.title
function username(api::GitHub.GitHubAPI, auth::GitHub.Authorization)
user_information = GitHub.gh_get_json(api, "/user"; auth=auth)
return user_information["login"]::String
end
| RegistryCI | https://github.com/JuliaRegistries/RegistryCI.jl.git |
|
[
"MIT"
] | 10.7.0 | f0341c8179a869629d90fe549511d6ffaf1da9a1 | code | 44488 | using HTTP: HTTP
# TODO: change this value to `true` once we are ready to re-enable the
# "Require `[compat]` for stdlib dependencies" feature.
#
# For example, we might consider changing this value to `true`
# once Julia 1.6 is no longer the LTS.
const _AUTOMERGE_REQUIRE_STDLIB_COMPAT = false
const guideline_registry_consistency_tests_pass = Guideline(;
info="Registy consistency tests",
docs=nothing,
check=data ->
meets_registry_consistency_tests_pass(data.registry_head, data.registry_deps),
)
function meets_registry_consistency_tests_pass(
registry_head::String, registry_deps::Vector{String}
)
try
RegistryCI.test(registry_head; registry_deps=registry_deps)
return true, ""
catch ex
@error "" exception = (ex, catch_backtrace())
end
return false, "The registry consistency tests failed"
end
const guideline_compat_for_julia = Guideline(;
info="Compat with upper bound for julia",
docs=string(
"There is an upper-bounded `[compat]` entry for `julia` that ",
"only includes a finite number of breaking releases of Julia.",
),
check=data -> meets_compat_for_julia(data.registry_head, data.pkg, data.version),
)
function meets_compat_for_julia(working_directory::AbstractString, pkg, version)
package_relpath = get_package_relpath_in_registry(;
package_name=pkg, registry_path=working_directory
)
compat_file = joinpath(working_directory, package_relpath, "Compat.toml")
compat = maybe_parse_toml(compat_file)
# Go through all the compat entries looking for the julia compat
# of the new version. When found, test
# 1. that it is a bounded range,
# 2. that the upper bound is not 2 or higher,
# 3. that the range includes at least one 1.x version.
for version_range in keys(compat)
if version in Pkg.Types.VersionRange(version_range)
if haskey(compat[version_range], "julia")
julia_compat = Pkg.Types.VersionSpec(compat[version_range]["julia"])
if !isempty(
intersect(
julia_compat, Pkg.Types.VersionSpec("$(typemax(Base.VInt))-*")
),
)
return false, "The compat entry for `julia` is unbounded."
elseif !isempty(intersect(julia_compat, Pkg.Types.VersionSpec("2-*")))
return false,
"The compat entry for `julia` has an upper bound of 2 or higher."
elseif isempty(intersect(julia_compat, Pkg.Types.VersionSpec("1")))
# For completeness, although this seems rather
# unlikely to occur.
return false,
"The compat entry for `julia` doesn't include any 1.x version."
else
return true, ""
end
end
end
end
return false, "There is no compat entry for `julia`."
end
const guideline_compat_for_all_deps = Guideline(;
info="Compat (with upper bound) for all dependencies",
docs=string(
"Dependencies: All dependencies should have `[compat]` entries that ",
"are upper-bounded and only include a finite number of breaking releases. ",
"For more information, please see the \"Upper-bounded `[compat]` entries\" subsection under \"Additional information\" below.",
),
check=data -> meets_compat_for_all_deps(data.registry_head, data.pkg, data.version),
)
function compat_violation_message(bad_dependencies)
return string(
"The following dependencies do not have a `[compat]` entry ",
"that is upper-bounded and only includes a finite number ",
"of breaking releases: ",
join(bad_dependencies, ", "),
# Note the indentation here is important for the proper formatting within a bulleted list later
"""
<details><summary>Extended explanation</summary>
Your package has a Project.toml file which might look something like the following:
```toml
name = "YourPackage"
uuid = "random id"
authors = ["Author Names"]
version = "major.minor"
[deps]
# Package dependencies
# ...
[compat]
# ...
```
Every package listed in `[deps]`, along with `julia` itself, must also be listed under `[compat]` (if you don't have a `[compat]` section, make one!). See the [Pkg docs](https://pkgdocs.julialang.org/v1/compatibility/) for the syntax for compatibility bounds, and [this documentation](https://juliaregistries.github.io/RegistryCI.jl/stable/guidelines/#Upper-bounded-%5Bcompat%5D-entries) for more on the kinds of compat bounds required for AutoMerge.
</details>
"""
)
end
function meets_compat_for_all_deps(working_directory::AbstractString, pkg, version)
package_relpath = get_package_relpath_in_registry(;
package_name=pkg, registry_path=working_directory
)
compat_file = joinpath(working_directory, package_relpath, "Compat.toml")
deps_file = joinpath(working_directory, package_relpath, "Deps.toml")
compat = maybe_parse_toml(compat_file)
deps = maybe_parse_toml(deps_file)
# First, we construct a Dict in which the keys are the package's
# dependencies, and the value is always false.
dep_has_compat_with_upper_bound = Dict{String,Bool}()
for version_range in keys(deps)
if version in Pkg.Types.VersionRange(version_range)
for name in keys(deps[version_range])
if _AUTOMERGE_REQUIRE_STDLIB_COMPAT
debug_msg = "Found a new (non-JLL) dependency: $(name)"
apply_compat_requirement = !is_jll_name(name)
else
debug_msg = "Found a new (non-stdlib non-JLL) dependency: $(name)"
apply_compat_requirement = !is_jll_name(name) && !is_julia_stdlib(name)
end
if apply_compat_requirement
@debug debug_msg
dep_has_compat_with_upper_bound[name] = false
end
end
end
end
# Now, we go through all the compat entries. If a dependency has a compat
# entry with an upper bound, we change the corresponding value in the Dict
# to true.
for version_range in keys(compat)
if version in Pkg.Types.VersionRange(version_range)
for (name, value) in compat[version_range]
if value isa Vector
if !isempty(value)
value_ranges = Pkg.Types.VersionRange.(value)
each_range_has_upper_bound = _has_upper_bound.(value_ranges)
if all(each_range_has_upper_bound)
@debug(
"Dependency \"$(name)\" has compat entries that all have upper bounds"
)
dep_has_compat_with_upper_bound[name] = true
end
end
else
value_range = Pkg.Types.VersionRange(value)
if _has_upper_bound(value_range)
@debug(
"Dependency \"$(name)\" has a compat entry with an upper bound"
)
dep_has_compat_with_upper_bound[name] = true
end
end
end
end
end
meets_this_guideline = all(values(dep_has_compat_with_upper_bound))
if meets_this_guideline
return true, ""
else
bad_dependencies = Vector{String}()
for name in keys(dep_has_compat_with_upper_bound)
if !(dep_has_compat_with_upper_bound[name])
@error(
"Dependency \"$(name)\" does not have a compat entry that has an upper bound"
)
push!(bad_dependencies, name)
end
end
sort!(bad_dependencies)
message = compat_violation_message(bad_dependencies)
return false, message
end
end
const guideline_patch_release_does_not_narrow_julia_compat = Guideline(;
info="If it is a patch release on a post-1.0 package, then it does not narrow the `[compat]` range for `julia`.",
check=data -> meets_patch_release_does_not_narrow_julia_compat(
data.pkg,
data.version;
registry_head=data.registry_head,
registry_master=data.registry_master,
),
)
function meets_patch_release_does_not_narrow_julia_compat(
pkg::String, new_version::VersionNumber; registry_head::String, registry_master::String
)
old_version = latest_version(pkg, registry_master)
if old_version.major != new_version.major || old_version.minor != new_version.minor
# Not a patch release.
return true, ""
end
julia_compats_for_old_version = julia_compat(pkg, old_version, registry_master)
julia_compats_for_new_version = julia_compat(pkg, new_version, registry_head)
if Set(julia_compats_for_old_version) == Set(julia_compats_for_new_version)
return true, ""
end
meets_this_guideline = range_did_not_narrow(
julia_compats_for_old_version, julia_compats_for_new_version
)
if meets_this_guideline
return true, ""
else
if (old_version >= v"1") || (new_version >= v"1")
msg = string(
"A patch release is not allowed to narrow the ",
"supported ranges of Julia versions. ",
"The ranges have changed from ",
"$(julia_compats_for_old_version) ",
"(in $(old_version)) ",
"to $(julia_compats_for_new_version) ",
"(in $(new_version)).",
)
return false, msg
else
@info("Narrows Julia compat, but it's OK since package is pre-1.0")
return true, ""
end
end
end
const _AUTOMERGE_NEW_PACKAGE_MINIMUM_NAME_LENGTH = 5
const guideline_name_length = Guideline(;
info="Name not too short",
docs="The name is at least $(_AUTOMERGE_NEW_PACKAGE_MINIMUM_NAME_LENGTH) characters long.",
check=data -> meets_name_length(data.pkg),
)
function meets_name_length(pkg)
meets_this_guideline = length(pkg) >= _AUTOMERGE_NEW_PACKAGE_MINIMUM_NAME_LENGTH
if meets_this_guideline
return true, ""
else
return false,
"Name is not at least $(_AUTOMERGE_NEW_PACKAGE_MINIMUM_NAME_LENGTH) characters long"
end
end
const guideline_name_ascii = Guideline(;
info="Name is composed of ASCII characters only.",
check=data -> meets_name_ascii(data.pkg),
)
function meets_name_ascii(pkg)
if isascii(pkg)
return true, ""
else
return false, "Name is not ASCII"
end
end
const guideline_julia_name_check = Guideline(;
info="Name does not include \"julia\", start with \"Ju\", or end with \"jl\".",
check=data -> meets_julia_name_check(data.pkg),
)
function meets_julia_name_check(pkg)
if occursin("julia", lowercase(pkg))
return false,
"Lowercase package name $(lowercase(pkg)) contains the string \"julia\"."
elseif startswith(pkg, "Ju")
return false, "Package name starts with \"Ju\"."
elseif endswith(lowercase(pkg), "jl")
return false, "Lowercase package name $(lowercase(pkg)) ends with \"jl\"."
else
return true, ""
end
end
damerau_levenshtein(name1, name2) = StringDistances.DamerauLevenshtein()(name1, name2)
function sqrt_normalized_vd(name1, name2)
return VisualStringDistances.visual_distance(name1, name2; normalize=x -> 5 + sqrt(x))
end
# This check cannot be overridden, since it's important for registry integrity
const guideline_name_match_check = Guideline(;
info = "Name does not match the name of any existing package names (up-to-case)",
docs = "Packages must not match the name of existing package up-to-case, since on case-insensitive filesystems, this will break the registry.",
check=data -> meets_name_match_check(data.pkg, data.registry_master))
function meets_name_match_check(pkg_name::AbstractString, registry_master::AbstractString)
other_packages = get_all_non_jll_package_names(registry_master)
return meets_name_match_check(pkg_name, other_packages)
end
function meets_name_match_check(
pkg_name::AbstractString,
other_packages::Vector;
)
for other_pkg in other_packages
if pkg_name == other_pkg
# We short-circuit in this case; more information doesn't help.
return (false, "Package name already exists in the registry.")
elseif lowercase(pkg_name) == lowercase(other_pkg)
return (false, "Package name matches existing package name $(other_pkg) up-to-case.")
end
end
return (true, "")
end
# This check looks for similar (but not exactly matching) names. It can be
# overridden by a label.
const guideline_distance_check = Guideline(;
info="Name is not too similar to existing package names",
docs="""
To prevent confusion between similarly named packages, the names of new packages must also satisfy the following three checks: (for more information, please see the \"Name similarity distance check\" subsection under \"Additional information\" below)
- the [Damerau–Levenshtein
distance](https://en.wikipedia.org/wiki/Damerau%E2%80%93Levenshtein_distance)
between the package name and the name of any existing package must be at
least 3.
- the Damerau–Levenshtein distance between the lowercased version of a
package name and the lowercased version of the name of any existing
package must be at least 2.
- and a visual distance from
[VisualStringDistances.jl](https://github.com/ericphanson/VisualStringDistances.jl)
between the package name and any existing package must exceeds a certain
a hand-chosen threshold (currently 2.5).
These checks can be overridden by applying a label `Override AutoMerge: name similarity is okay` to the PR. This will turn off the check as long as the label is applied to the PR.
""",
check=data -> meets_distance_check(data.pkg, data.registry_master),
)
function meets_distance_check(
pkg_name::AbstractString, registry_master::AbstractString; kwargs...
)
other_packages = get_all_non_jll_package_names(registry_master)
return meets_distance_check(pkg_name, other_packages; kwargs...)
end
function meets_distance_check(
pkg_name::AbstractString,
other_packages::Vector;
DL_lowercase_cutoff=1,
DL_cutoff=2,
sqrt_normalized_vd_cutoff=2.5,
comment_collapse_cutoff=10,
)
problem_messages = Tuple{String,Tuple{Float64,Float64,Float64}}[]
for other_pkg in other_packages
if lowercase(pkg_name) == lowercase(other_pkg)
# We handle this case in `meets_name_match_check`
continue
else
msg = ""
# Distance check 1: DL distance
dl = damerau_levenshtein(pkg_name, other_pkg)
if dl <= DL_cutoff
msg = string(
msg,
" Damerau-Levenshtein distance $dl is at or below cutoff of $(DL_cutoff).",
)
end
# Distance check 2: lowercase DL distance
dl_lowercase = damerau_levenshtein(lowercase(pkg_name), lowercase(other_pkg))
if dl_lowercase <= DL_lowercase_cutoff
msg = string(
msg,
" Damerau-Levenshtein distance $(dl_lowercase) between lowercased names is at or below cutoff of $(DL_lowercase_cutoff).",
)
end
# Distance check 3: normalized visual distance,
# gated by a `dl` check for speed.
if (sqrt_normalized_vd_cutoff > 0 && dl <= 4)
nrm_vd = sqrt_normalized_vd(pkg_name, other_pkg)
if nrm_vd <= sqrt_normalized_vd_cutoff
msg = string(
msg,
" Normalized visual distance ",
Printf.@sprintf("%.2f", nrm_vd),
" is at or below cutoff of ",
Printf.@sprintf("%.2f", sqrt_normalized_vd_cutoff),
".",
)
end
else
# need to choose something for sorting purposes
nrm_vd = 10.0
end
if msg != ""
# We must have found a clash.
push!(
problem_messages,
(string("Similar to $(other_pkg).", msg), (dl, dl_lowercase, nrm_vd)),
)
end
end
end
isempty(problem_messages) && return (true, "")
sort!(problem_messages; by=Base.tail)
message = string(
"Package name similar to $(length(problem_messages)) existing package",
length(problem_messages) > 1 ? "s" : "",
".\n",
)
use_spoiler = length(problem_messages) > comment_collapse_cutoff
# we indent each line by two spaces in all the following
# so that it nests properly in the outer list.
if use_spoiler
message *= """
<details>
<summary>Similar package names</summary>
"""
end
numbers = string.(" ", 1:length(problem_messages))
message *= join(join.(zip(numbers, first.(problem_messages)), Ref(". ")), '\n')
if use_spoiler
message *= "\n\n </details>\n"
end
return (false, message)
end
# Used in `pull_request_build` to determine if we should
# perform the distance check or not.
# We expect to be passed the `labels` field of a PullRequest:
# <https://github.com/JuliaWeb/GitHub.jl/blob/d24bd6798609ae356db308d65577e99aad0cf432/src/issues/pull_requests.jl#L33>
function perform_distance_check(labels)
# No labels? Do the check
isnothing(labels) && return true
for label in labels
if label.name === "Override AutoMerge: name similarity is okay"
# found the override! Skip the check
@debug "Found label; skipping distance check" label.name
return false
end
end
# Did not find the override. Perform the check.
return true
end
const guideline_name_identifier = Guideline(;
info="Name is a Julia identifier",
docs=string(
"The package name should be a valid Julia identifier (according to `Base.isidentifier`).",
),
check=data -> meets_name_is_identifier(data.pkg),
)
function meets_name_is_identifier(pkg)
if Base.isidentifier(pkg)
return true, ""
else
return false, "The package's name ($pkg) is not a valid Julia identifier according to `Base.isidentifier`. Typically this means it contains `-` or other characters that can't be used in defining a variable name or module. The package must be renamed to be registered."
end
end
const guideline_normal_capitalization = Guideline(;
info="Normal capitalization",
docs=string(
"The package name should start with an upper-case letter, ",
"contain only ASCII alphanumeric characters, ",
"and contain at least one lowercase letter.",
),
check=data -> meets_normal_capitalization(data.pkg),
)
function meets_normal_capitalization(pkg)
# We intentionally do not use `\w` in this regex.
# `\w` includes underscores, but we don't want to include underscores.
# So, instead of `\w`, we use `[A-Za-z0-9]`.
meets_this_guideline = occursin(r"^[A-Z][A-Za-z0-9]*[a-z][A-Za-z0-9]*[0-9]?$", pkg)
if meets_this_guideline
return true, ""
else
return false,
"Name does not meet all of the following: starts with an upper-case letter, ASCII alphanumerics only, not all letters are upper-case."
end
end
const guideline_repo_url_requirement = Guideline(;
info="Repo URL ends with `/PackageName.jl.git`.",
check=data -> meets_repo_url_requirement(data.pkg; registry_head=data.registry_head),
)
function meets_repo_url_requirement(pkg::String; registry_head::String)
package_relpath = get_package_relpath_in_registry(;
package_name=pkg, registry_path=registry_head
)
package_toml_parsed = Pkg.TOML.parsefile(
joinpath(registry_head, package_relpath, "Package.toml")
)
url = package_toml_parsed["repo"]
subdir = get(package_toml_parsed, "subdir", "")
is_subdirectory_package = occursin(r"[A-Za-z0-9]", subdir)
meets_this_guideline = url_has_correct_ending(url, pkg)
if is_subdirectory_package
return true, "" # we do not apply this check if the package is a subdirectory package
end
if meets_this_guideline
return true, ""
end
return false, "Repo URL does not end with /name.jl.git, where name is the package name"
end
function _invalid_sequential_version(reason::AbstractString)
return false, "Does not meet sequential version number guideline: $(reason). $PACKAGE_AUTHOR_APPROVAL_INSTRUCTIONS", :invalid
end
function _valid_change(old_version::VersionNumber, new_version::VersionNumber)
diff = difference(old_version, new_version)
if !(diff isa VersionNumber)
if diff isa ErrorCannotComputeVersionDifference
old_msg = diff.msg
else
T = typeof(diff)
old_msg = "Unknown diff type: $(T)"
end
new_msg = "Error occured while trying to compute version bump. Message: $(old_msg)"
return _invalid_sequential_version(new_msg)
end
@debug("Difference between versions: ", old_version, new_version, diff)
if diff == v"0.0.1"
return true, "", :patch
elseif diff == v"0.1.0"
return true, "", :minor
elseif diff == v"1.0.0"
return true, "", :major
else
return _invalid_sequential_version("increment is not one of: 0.0.1, 0.1.0, 1.0.0")
end
end
const PACKAGE_AUTHOR_APPROVAL_INSTRUCTIONS = string(
"**If this was not a mistake and you wish to merge this PR anyway, ",
"write a comment that says `[merge approved]`.**")
const guideline_sequential_version_number = Guideline(;
info="Sequential version number",
docs=string(
"Version number: Should be a standard increment and not skip versions. ",
"This means incrementing the patch/minor/major version with +1 compared to ",
"previous (if any) releases. ",
"If, for example, `1.0.0` and `1.1.0` are existing versions, ",
"valid new versions are `1.0.1`, `1.1.1`, `1.2.0` and `2.0.0`. ",
"Invalid new versions include `1.0.2` (skips `1.0.1`), ",
"`1.3.0` (skips `1.2.0`), `3.0.0` (skips `2.0.0`) etc.",
),
check=data -> meets_sequential_version_number(
data.pkg,
data.version;
registry_head=data.registry_head,
registry_master=data.registry_master,
),
)
function meets_sequential_version_number(
existing::Vector{VersionNumber}, ver::VersionNumber
)
always_assert(!isempty(existing))
if ver in existing
return _invalid_sequential_version("version $ver already exists")
end
issorted(existing) || (existing = sort(existing))
idx = searchsortedlast(existing, ver)
idx > 0 || return _invalid_sequential_version(
"version $ver less than least existing version $(existing[1])"
)
prv = existing[idx]
always_assert(ver != prv)
nxt = if thismajor(ver) != thismajor(prv)
nextmajor(prv)
elseif thisminor(ver) != thisminor(prv)
nextminor(prv)
else
nextpatch(prv)
end
ver <= nxt || return _invalid_sequential_version("version $ver skips over $nxt")
return _valid_change(prv, ver)
end
function meets_sequential_version_number(
pkg::String, new_version::VersionNumber; registry_head::String, registry_master::String
)
_all_versions = all_versions(pkg, registry_master)
return meets_sequential_version_number(_all_versions, new_version)
end
const guideline_standard_initial_version_number = Guideline(;
info="Standard initial version number. Must be one of: `0.0.1`, `0.1.0`, `1.0.0`, or `X.0.0`.",
check=data -> meets_standard_initial_version_number(data.version),
)
function meets_standard_initial_version_number(version)
meets_this_guideline =
version == v"0.0.1" ||
version == v"0.1.0" ||
version == v"1.0.0" ||
_is_x_0_0(version)
if meets_this_guideline
return true, ""
else
return false, "Version number is not 0.0.1, 0.1.0, 1.0.0, or X.0.0"
end
end
function _is_x_0_0(version::VersionNumber)
result = (version.major >= 1) && (version.minor == 0) && (version.patch == 0)
return result
end
const guideline_version_number_no_prerelease = Guideline(;
info="No prerelease data in the version number",
docs = "Version number is not allowed to contain prerelease data",
check = data -> meets_version_number_no_prerelease(
data.version,
),
)
const guideline_version_number_no_build = Guideline(;
info="No build data in the version number",
docs = "Version number is not allowed to contain build data",
check = data -> meets_version_number_no_build(
data.version,
),
)
function meets_version_number_no_prerelease(version::VersionNumber)
if isempty(version.prerelease)
return true, ""
else
return false, "Version number is not allowed to contain prerelease data"
end
end
function meets_version_number_no_build(version::VersionNumber)
if isempty(version.build)
return true, ""
else
return false, "Version number is not allowed to contain build data"
end
end
const guideline_code_can_be_downloaded = Guideline(;
info="Code can be downloaded.",
check=data -> meets_code_can_be_downloaded(
data.registry_head,
data.pkg,
data.version,
data.pr;
pkg_code_path=data.pkg_code_path,
),
)
function _find_lowercase_duplicates(v)
elts = Dict{String, String}()
for x in v
lower_x = lowercase(x)
if haskey(elts, lower_x)
return (elts[lower_x], x)
else
elts[lower_x] = x
end
end
return nothing
end
const DISALLOWED_CHARS = ['/', '<', '>', ':', '"', '/', '\\', '|', '?', '*', Char.(0:31)...]
const DISALLOWED_NAMES = ["CON", "PRN", "AUX", "NUL",
("COM$i" for i in 1:9)...,
("LPT$i" for i in 1:9)...]
function meets_file_dir_name_check(name)
# https://stackoverflow.com/a/31976060
idx = findfirst(n -> occursin(n, name), DISALLOWED_CHARS)
if idx !== nothing
return false, "contains character $(DISALLOWED_CHARS[idx]) which may not be valid as a file or directory name on some platforms"
end
base, ext = splitext(name)
if uppercase(name) in DISALLOWED_NAMES || uppercase(base) in DISALLOWED_NAMES
return false, "is not allowed"
end
if endswith(name, ".") || endswith(name, r"\s")
return false, "ends with `.` or space"
end
return true, ""
end
function meets_src_names_ok(pkg_code_path)
src = joinpath(pkg_code_path, "src/")
isdir(src) || return false, "`src` directory not found"
for (root, dirs, files) in walkdir(src)
files_dirs = Iterators.flatten((files, dirs))
result = _find_lowercase_duplicates(files_dirs)
if result !== nothing
x = joinpath(root, result[1])
y = joinpath(root, result[2])
return false, "Found files or directories in `src` which will cause problems on case insensitive filesystems: `$x` and `$y`"
end
for f in files_dirs
ok, msg = meets_file_dir_name_check(f)
if !ok
return false, "the name of file or directory $(joinpath(root, f)) $(msg). This can cause problems on some operating systems or file systems."
end
end
end
return true, ""
end
const guideline_src_names_OK = Guideline(;
info="`src` files and directories names are OK",
check=data -> meets_src_names_ok(data.pkg_code_path),
)
function meets_code_can_be_downloaded(registry_head, pkg, version, pr; pkg_code_path)
uuid, package_repo, subdir, tree_hash_from_toml = parse_registry_pkg_info(
registry_head, pkg, version
)
# We get the `tree_hash` two ways and check they agree, which helps ensures the `subdir` parameter is correct. Two ways:
# 1. By the commit hash in the PR body and the subdir parameter
# 2. By the tree hash in the Versions.toml
commit_hash = commit_from_pull_request_body(pr)
local tree_hash_from_commit, tree_hash_from_commit_success
clone_success = load_files_from_url_and_tree_hash(
pkg_code_path, package_repo, tree_hash_from_toml
) do dir
tree_hash_from_commit, tree_hash_from_commit_success = try
readchomp(Cmd(`git rev-parse $(commit_hash):$(subdir)`; dir=dir)), true
catch e
@error e
"", false
end
end
if !clone_success
return false, "Cloning repository failed."
end
if !tree_hash_from_commit_success
return false,
"Could not obtain tree hash from commit hash and subdir parameter. Possibly this indicates that an incorrect `subdir` parameter was passed during registration."
end
if tree_hash_from_commit != tree_hash_from_toml
@error "`tree_hash_from_commit != tree_hash_from_toml`" tree_hash_from_commit tree_hash_from_toml
return false,
"Tree hash obtained from the commit message and subdirectory does not match the tree hash in the Versions.toml file. Possibly this indicates that an incorrect `subdir` parameter was passed during registration."
else
return true, ""
end
end
function _generate_pkg_add_command(pkg::String, version::VersionNumber)::String
return "Pkg.add(Pkg.PackageSpec(name=\"$(pkg)\", version=v\"$(string(version))\"));"
end
is_valid_url(str::AbstractString) = !isempty(HTTP.URI(str).scheme) && isvalid(HTTP.URI(str))
const guideline_version_can_be_pkg_added = Guideline(;
info="Version can be `Pkg.add`ed",
docs="Package installation: The package should be installable (`Pkg.add(\"PackageName\")`).",
check=data -> meets_version_can_be_pkg_added(
data.registry_head,
data.pkg,
data.version;
registry_deps=data.registry_deps,
environment_variables_to_pass=data.environment_variables_to_pass,
),
)
function meets_version_can_be_pkg_added(
working_directory::String,
pkg::String,
version::VersionNumber;
registry_deps::Vector{<:AbstractString}=String[],
environment_variables_to_pass::Vector{String},
)
pkg_add_command = _generate_pkg_add_command(pkg, version)
_registry_deps = convert(Vector{String}, registry_deps)
_registry_deps_is_valid_url = is_valid_url.(_registry_deps)
code = """
import Pkg;
Pkg.Registry.add(Pkg.RegistrySpec(path=\"$(working_directory)\"));
_registry_deps = $(_registry_deps);
_registry_deps_is_valid_url = $(_registry_deps_is_valid_url);
for i = 1:length(_registry_deps)
regdep = _registry_deps[i]
if _registry_deps_is_valid_url[i]
Pkg.Registry.add(Pkg.RegistrySpec(url = regdep))
else
Pkg.Registry.add(regdep)
end
end
@info("Attempting to `Pkg.add` package...");
$(pkg_add_command)
@info("Successfully `Pkg.add`ed package");
"""
cmd_ran_successfully = _run_pkg_commands(
working_directory,
pkg,
version;
code=code,
before_message="Attempting to `Pkg.add` the package",
environment_variables_to_pass=environment_variables_to_pass,
)
if cmd_ran_successfully
@info "Successfully `Pkg.add`ed the package"
return true, ""
else
@error "Was not able to successfully `Pkg.add` the package"
return false,
string(
"I was not able to install the package ",
"(i.e. `Pkg.add(\"$(pkg)\")` failed). ",
"See the AutoMerge logs for details.",
)
end
end
const guideline_version_has_osi_license = Guideline(;
info="Version has OSI-approved license",
docs=string(
"License: The package should have an ",
"[OSI-approved software license](https://opensource.org/licenses/alphabetical) ",
"located in the top-level directory of the package code, ",
"e.g. in a file named `LICENSE` or `LICENSE.md`. ",
"This check is required for the General registry. ",
"For other registries, registry maintainers have the option to disable this check.",
),
check=data -> meets_version_has_osi_license(data.pkg; pkg_code_path=data.pkg_code_path),
)
function meets_version_has_osi_license(pkg::String; pkg_code_path)
pkgdir = pkg_code_path
if !isdir(pkgdir) || isempty(readdir(pkgdir))
return false,
"Could not check license because could not access package code. Perhaps the `can_download_code` check failed earlier."
end
license_results = LicenseCheck.find_licenses(pkgdir)
# Failure mode 1: no licenses
if isempty(license_results)
@error "Could not find any licenses"
return false,
string(
"No licenses detected in the package's top-level folder. An OSI-approved license is required.",
)
end
flat_results = [
(
filename=lic.license_filename,
identifier=identifier,
approved=LicenseCheck.is_osi_approved(identifier),
) for lic in license_results for identifier in lic.licenses_found
]
osi_results = [
string(r.identifier, " license in ", r.filename) for r in flat_results if r.approved
]
non_osi_results = [
string(r.identifier, " license in ", r.filename) for
r in flat_results if !r.approved
]
osi_string = string(
"Found OSI-approved license(s): ", join(osi_results, ", ", ", and "), "."
)
non_osi_string = string(
"Found non-OSI license(s): ", join(non_osi_results, ", ", ", and "), "."
)
# Failure mode 2: no OSI-approved licenses, but has some kind of license detected
if isempty(osi_results)
@error "Found no OSI-approved licenses" non_osi_string
return false, string("Found no OSI-approved licenses. ", non_osi_string)
end
# Pass: at least one OSI-approved license, possibly other licenses.
@info "License check passed; results" osi_results non_osi_results
if !isempty(non_osi_results)
return true, string(osi_string, " Also ", non_osi_string)
else
return true, string(osi_string, " Found no other licenses.")
end
end
const guideline_version_can_be_imported = Guideline(;
info="Version can be `import`ed",
docs="Package loading: The package should be loadable (`import PackageName`).",
check=data -> meets_version_can_be_imported(
data.registry_head,
data.pkg,
data.version;
registry_deps=data.registry_deps,
environment_variables_to_pass=data.environment_variables_to_pass,
),
)
function meets_version_can_be_imported(
working_directory::String,
pkg::String,
version::VersionNumber;
registry_deps::Vector{<:AbstractString}=String[],
environment_variables_to_pass::Vector{String},
)
pkg_add_command = _generate_pkg_add_command(pkg, version)
_registry_deps = convert(Vector{String}, registry_deps)
_registry_deps_is_valid_url = is_valid_url.(_registry_deps)
code = """
import Pkg;
Pkg.Registry.add(Pkg.RegistrySpec(path=\"$(working_directory)\"));
_registry_deps = $(_registry_deps);
_registry_deps_is_valid_url = $(_registry_deps_is_valid_url);
for i = 1:length(_registry_deps)
regdep = _registry_deps[i]
if _registry_deps_is_valid_url[i]
Pkg.Registry.add(Pkg.RegistrySpec(url = regdep))
else
Pkg.Registry.add(regdep)
end
end
@info("Attempting to `Pkg.add` package...");
$(pkg_add_command)
@info("Successfully `Pkg.add`ed package");
@info("Attempting to `import` package");
Pkg.precompile()
import $(pkg);
@info("Successfully `import`ed package");
"""
cmd_ran_successfully = _run_pkg_commands(
working_directory,
pkg,
version;
code=code,
before_message="Attempting to `import` the package",
environment_variables_to_pass=environment_variables_to_pass,
)
if cmd_ran_successfully
@info "Successfully `import`ed the package"
return true, ""
else
@error "Was not able to successfully `import` the package"
return false,
string(
"I was not able to load the package ",
"(i.e. `import $(pkg)` failed). ",
"See the AutoMerge logs for details.",
)
end
end
function _run_pkg_commands(
working_directory::String,
pkg::String,
version::VersionNumber;
code,
before_message,
environment_variables_to_pass::Vector{String},
)
original_directory = pwd()
tmp_dir_1 = mktempdir()
atexit(() -> rm(tmp_dir_1; force=true, recursive=true))
cd(tmp_dir_1)
# We need to be careful with what environment variables we pass to the child
# process. For example, we don't want to pass an environment variable containing
# our GitHub token to the child process. Because if the Julia package that we are
# testing has malicious code in its __init__() function, it could try to steal
# our token. So we only pass these environment variables:
# 1. HTTP_PROXY. If it's set, it is delegated to the child process.
# 2. HTTPS_PROXY. If it's set, it is delegated to the child process.
# 3. JULIA_DEPOT_PATH. We set JULIA_DEPOT_PATH to the temporary directory that
# we created. This is because we don't want the child process using our
# real Julia depot. So we set up a fake depot for the child process to use.
# 4. JULIA_PKG_SERVER. If it's set, it is delegated to the child process.
# 5. JULIA_REGISTRYCI_AUTOMERGE. We set JULIA_REGISTRYCI_AUTOMERGE to "true".
# 6. PATH. If we don't pass PATH, things break. And PATH should not contain any
# sensitive information.
# 7. PYTHON. We set PYTHON to the empty string. This forces any packages that use
# PyCall to install their own version of Python instead of using the system
# Python.
# 8. R_HOME. We set R_HOME to "*".
# 9. HOME. Lots of things need HOME.
#
# If registry maintainers need additional environment variables to be passed
# to the child process, they can do so by providing the `environment_variables_to_pass`
# kwarg to the `AutoMerge.run` function.
env = Dict(
"JULIA_DEPOT_PATH" => mktempdir(),
"JULIA_PKG_PRECOMPILE_AUTO" => "0",
"JULIA_REGISTRYCI_AUTOMERGE" => "true",
"PYTHON" => "",
"R_HOME" => "*",
)
default_environment_variables_to_pass = [
"HOME",
"JULIA_PKG_SERVER",
"PATH",
"HTTP_PROXY",
"HTTPS_PROXY",
]
all_environment_variables_to_pass = vcat(
default_environment_variables_to_pass,
environment_variables_to_pass,
)
for k in all_environment_variables_to_pass
if haskey(ENV, k)
env[k] = ENV[k]
end
end
cmd = Cmd(`$(Base.julia_cmd()) -e $(code)`; env=env)
# GUI toolkits may need a display just to load the package
xvfb = Sys.which("xvfb-run")
@info("xvfb: ", xvfb)
if xvfb !== nothing
pushfirst!(cmd.exec, "-a")
pushfirst!(cmd.exec, xvfb)
end
@info(before_message)
@info(string(
"IMPORTANT: If you see any messages of the form \"Error: Some registries failed to update\"",
"or \"registry dirty\", ",
"please disregard those messages. Those messages are normal and do not indicate an error.",
))
cmd_ran_successfully = success(pipeline(cmd; stdout=stdout, stderr=stderr))
cd(original_directory)
rmdir(tmp_dir_1)
return cmd_ran_successfully
end
function rmdir(dir)
try
chmod(dir, 0o700; recursive=true)
catch
end
return rm(dir; force=true, recursive=true)
end
url_has_correct_ending(url, pkg) = endswith(url, "/$(pkg).jl.git")
function get_automerge_guidelines(
::NewPackage;
check_license::Bool,
this_is_jll_package::Bool,
this_pr_can_use_special_jll_exceptions::Bool,
use_distance_check::Bool,
package_author_approved::Bool # currently unused for new packages
)
guidelines = [
# We first verify the name is a valid Julia identifier.
# If not, we early exit (`:early_exit_if_failed`), since we don't want to proceed further.
(guideline_name_identifier, true),
(:early_exit_if_failed, true),
(guideline_registry_consistency_tests_pass, true),
(guideline_pr_only_changes_allowed_files, true),
# (guideline_only_changes_specified_package, true), # not yet implemented
(guideline_normal_capitalization, !this_pr_can_use_special_jll_exceptions),
(guideline_name_length, !this_pr_can_use_special_jll_exceptions),
(guideline_julia_name_check, true),
(guideline_repo_url_requirement, true),
(guideline_version_number_no_prerelease, true),
(guideline_version_number_no_build, !this_pr_can_use_special_jll_exceptions),
(guideline_compat_for_julia, true),
(guideline_compat_for_all_deps, true),
(guideline_allowed_jll_nonrecursive_dependencies, this_is_jll_package),
(guideline_name_ascii, true),
(:update_status, true),
(guideline_version_can_be_pkg_added, true),
(guideline_code_can_be_downloaded, true),
# `guideline_version_has_osi_license` must be run
# after `guideline_code_can_be_downloaded` so
# that it can use the downloaded code!
(guideline_version_has_osi_license, check_license),
(guideline_src_names_OK, true),
(guideline_version_can_be_imported, true),
(:update_status, true),
(guideline_dependency_confusion, true),
# this is the non-optional part of name checking
(guideline_name_match_check, true),
# We always run the `guideline_distance_check`
# check last, because if the check fails, it
# prints the list of similar package names in
# the automerge comment. To make the comment easy
# to read, we want this list to be at the end.
(guideline_distance_check, use_distance_check),
]
return guidelines
end
function get_automerge_guidelines(
::NewVersion;
check_license::Bool,
this_is_jll_package::Bool,
this_pr_can_use_special_jll_exceptions::Bool,
use_distance_check::Bool, # unused for new versions
package_author_approved::Bool,
)
guidelines = [
(guideline_registry_consistency_tests_pass, true),
(guideline_pr_only_changes_allowed_files, true),
(guideline_sequential_version_number, !this_pr_can_use_special_jll_exceptions && !package_author_approved),
(guideline_version_number_no_prerelease, true),
(guideline_version_number_no_build, !this_pr_can_use_special_jll_exceptions),
(guideline_compat_for_julia, true),
(guideline_compat_for_all_deps, true),
(
guideline_patch_release_does_not_narrow_julia_compat,
!this_pr_can_use_special_jll_exceptions,
),
(guideline_allowed_jll_nonrecursive_dependencies, this_is_jll_package),
(:update_status, true),
(guideline_version_can_be_pkg_added, true),
(guideline_code_can_be_downloaded, true),
# `guideline_version_has_osi_license` must be run
# after `guideline_code_can_be_downloaded` so
# that it can use the downloaded code!
(guideline_version_has_osi_license, check_license),
(guideline_src_names_OK, true),
(guideline_version_can_be_imported, true),
]
return guidelines
end
| RegistryCI | https://github.com/JuliaRegistries/RegistryCI.jl.git |
|
[
"MIT"
] | 10.7.0 | f0341c8179a869629d90fe549511d6ffaf1da9a1 | code | 1871 | function is_jll_name(name::AbstractString)::Bool
return endswith(name, "_jll")
end
function _get_all_dependencies_nonrecursive(working_directory::AbstractString, pkg, version)
all_dependencies = String[]
package_relpath = get_package_relpath_in_registry(;
package_name=pkg, registry_path=working_directory
)
deps_file = joinpath(working_directory, package_relpath, "Deps.toml")
deps = maybe_parse_toml(deps_file)
for version_range in keys(deps)
if version in Pkg.Types.VersionRange(version_range)
for name in keys(deps[version_range])
push!(all_dependencies, name)
end
end
end
unique!(all_dependencies)
return all_dependencies
end
const guideline_allowed_jll_nonrecursive_dependencies = Guideline(;
info="If this is a JLL package, only deps are Pkg, Libdl, and other JLL packages",
docs=nothing,
check=data -> meets_allowed_jll_nonrecursive_dependencies(
data.registry_head, data.pkg, data.version
),
)
function meets_allowed_jll_nonrecursive_dependencies(
working_directory::AbstractString, pkg, version
)
# If you are a JLL package, you are only allowed to have five kinds of dependencies:
# 1. Pkg
# 2. Libdl
# 3. Artifacts
# 4. JLLWrappers
# 5. LazyArtifacts
# 6. TOML
# 8. MPIPreferences
# 7. other JLL packages
all_dependencies = _get_all_dependencies_nonrecursive(working_directory, pkg, version)
allowed_dependencies = ("Pkg", "Libdl", "Artifacts", "JLLWrappers", "LazyArtifacts", "TOML", "MPIPreferences")
for dep in all_dependencies
if dep ∉ allowed_dependencies && !is_jll_name(dep)
return false,
"JLL packages are only allowed to depend on $(join(allowed_dependencies, ", ")) and other JLL packages"
end
end
return true, ""
end
| RegistryCI | https://github.com/JuliaRegistries/RegistryCI.jl.git |
|
[
"MIT"
] | 10.7.0 | f0341c8179a869629d90fe549511d6ffaf1da9a1 | code | 385 | function throw_not_automerge_applicable(
::Type{EXCEPTION_TYPE}, message::String; error_exit_if_automerge_not_applicable::Bool
) where {EXCEPTION_TYPE}
try
throw(EXCEPTION_TYPE(message))
catch ex
@error "" exception = (ex, catch_backtrace())
if error_exit_if_automerge_not_applicable
rethrow()
end
end
return nothing
end
| RegistryCI | https://github.com/JuliaRegistries/RegistryCI.jl.git |
|
[
"MIT"
] | 10.7.0 | f0341c8179a869629d90fe549511d6ffaf1da9a1 | code | 1555 | # The actual relative path of the package as specified in the `Registry.toml` file.
function get_package_relpath_in_registry(; package_name::String, registry_path::String)
registry_toml_file_name = joinpath(registry_path, "Registry.toml")
registry_toml_parsed = TOML.parsefile(registry_toml_file_name)
all_packages = registry_toml_parsed["packages"]
all_package_names_and_paths = map(x -> (x["name"], x["path"]), values(all_packages))
matching_package_indices = findall(
getindex.(all_package_names_and_paths, 1) .== package_name
)
num_indices = length(matching_package_indices)
(num_indices == 0) &&
throw(ErrorException("no package found with the name $(package_name)"))
(num_indices != 1) && throw(
ErrorException(
"multiple ($(num_indices)) packages found with the name $(package_name)"
),
)
single_matching_index = only(matching_package_indices)
single_matching_package = all_package_names_and_paths[single_matching_index]
_pkgname, _pkgrelpath = single_matching_package
always_assert(_pkgname == package_name)
_pkgrelpath::String
return _pkgrelpath
end
# What the relative path of the package *should* be, in theory.
# This function should ONLY be used in the
# "PR only changes a subset of the allowed files" check.
# For all other uses, you shoud use the `get_package_relpath_in_registry`
# function instead.
function _get_package_relpath_per_name_scheme(; package_name::String)
return RegistryTools.package_relpath(package_name)
end
| RegistryCI | https://github.com/JuliaRegistries/RegistryCI.jl.git |
|
[
"MIT"
] | 10.7.0 | f0341c8179a869629d90fe549511d6ffaf1da9a1 | code | 8344 | """
run([env, cicfg::CIService]; kwargs...)
Run the `RegistryCI.AutoMerge` service.
# Arguments
- `env`: an `AbstractDictionary` used to read environmental variables from.
Defaults to `ENV` but a plain `Dict` can be passed to mimic an alternate environment.
- `ciccfg`: Configuration struct describing the continuous integration (CI) environment in which AutoMerge is being run.
# Keyword Arguments
- `merge_new_packages`: should AutoMerge merge registration PRs for new packages
- `merge_new_versions`: should AutoMerge merge registration PRs for new versions of packages
- `new_package_waiting_period`: new package waiting period, e.g `Day(3)`.
- `new_jll_package_waiting_period`: new JLL package waiting period, e.g `Minute(20)`.
- `new_version_waiting_period`: new package version waiting period, e.g `Minute(10)`.
- `new_jll_version_waiting_period`: new JLL package version waiting period, e.g `Minute(10)`.
- `registry`: the registry name you want to run AutoMerge on.
- `tagbot_enabled`: if tagbot is enabled.
- `authorized_authors`: list of who can submit registration, e.g `String["JuliaRegistrator"]`.
- `authorized_authors_special_jll_exceptions`: a list of users who can submit JLL packages (which have strict rules about allowed dependencies and are subject to `new_jll_*_waiting_period`s instead of `new_*_waiting_period`s).
- `additional_statuses`: list of additional commit statuses that must pass before AutoMerge will merge a PR
- `additional_check_runs`: list of additional check runs that must pass before AutoMerge will merge a PR
- `error_exit_if_automerge_not_applicable`: if `false`, AutoMerge will not error on PRs made by non-AutoMerge-authorized users
- `master_branch`: name of `master_branch`, e.g you may want to specify this to `"main"` for new GitHub repositories.
- `master_branch_is_default_branch`: if `master_branch` specified above is the default branch.
- `suggest_onepointzero`: should the AutoMerge comment include a suggestion to tag a 1.0 release for v0.x.y packages.
- `point_to_slack`: should the AutoMerge comment recommend sending a message to the `#pkg-registration` Julia-Slack channel when auto-merging is not possible.
- `registry_deps`: list of registry dependencies, e.g your packages may depend on `General`.
- `api_url`: the registry host API URL, default is `"https://api.github.com"`.
- `check_license`: check package has a valid license, default is `false`.
- `public_registries`: If a new package registration has a UUID that matches
that of a package already registered in one of these registries supplied here
(and has either a different name or different URL) then an error will be thrown.
This to prevent AutoMerge from being used for "dependency confusion"
attacks on those registries.
- `read_only`: run in read only mode, default is `false`.
# Example
Here is an example of how `General` registry is configured
```julia
using RegistryCI
using Dates
RegistryCI.AutoMerge.run(
merge_new_packages = ENV["MERGE_NEW_PACKAGES"] == "true",
merge_new_versions = ENV["MERGE_NEW_VERSIONS"] == "true",
new_package_waiting_period = Day(3),
new_jll_package_waiting_period = Minute(20),
new_version_waiting_period = Minute(10),
new_jll_version_waiting_period = Minute(10),
registry = "JuliaLang/General",
tagbot_enabled = true,
authorized_authors = String["JuliaRegistrator"],
authorized_authors_special_jll_exceptions = String["jlbuild"],
suggest_onepointzero = false,
point_to_slack = false,
additional_statuses = String[],
additional_check_runs = String[],
check_license = true,
public_registries = String["https://github.com/HolyLab/HolyLabRegistry"],
)
```
"""
function run(;
env=ENV,
cicfg::CIService=auto_detect_ci_service(; env=env),
merge_new_packages::Bool,
merge_new_versions::Bool,
new_package_waiting_period,
new_jll_package_waiting_period,
new_version_waiting_period,
new_jll_version_waiting_period,
registry::String,
#
tagbot_enabled::Bool=false,
#
authorized_authors::Vector{String},
authorized_authors_special_jll_exceptions::Vector{String},
#
additional_statuses::AbstractVector{<:AbstractString}=String[],
additional_check_runs::AbstractVector{<:AbstractString}=String[],
#
error_exit_if_automerge_not_applicable::Bool=false,
#
master_branch::String="master",
master_branch_is_default_branch::Bool=true,
suggest_onepointzero::Bool=true,
point_to_slack::Bool=false,
#
registry_deps::Vector{<:AbstractString}=String[],
api_url::String="https://api.github.com",
check_license::Bool=false,
# A list of public Julia registries (repository URLs)
# which will be checked for UUID collisions in order to
# mitigate the dependency confusion vulnerability. See
# the `dependency_confusion.jl` file for details.
public_registries::Vector{<:AbstractString}=String[],
read_only::Bool=false,
environment_variables_to_pass::Vector{<:AbstractString}=String[],
)::Nothing
all_statuses = deepcopy(additional_statuses)
all_check_runs = deepcopy(additional_check_runs)
push!(all_statuses, "automerge/decision")
unique!(all_statuses)
unique!(all_check_runs)
api = GitHub.GitHubWebAPI(HTTP.URI(api_url))
registry_head = directory_of_cloned_registry(cicfg; env=env)
# Figure out what type of build this is
run_pr_build = conditions_met_for_pr_build(cicfg; env=env, master_branch=master_branch)
run_merge_build = conditions_met_for_merge_build(
cicfg; env=env, master_branch=master_branch
)
if !(run_pr_build || run_merge_build)
throw_not_automerge_applicable(
AutoMergeWrongBuildType,
"Build not determined to be either a PR build or a merge build. Exiting.";
error_exit_if_automerge_not_applicable=error_exit_if_automerge_not_applicable,
)
return nothing
end
# Authentication
key = if run_pr_build || !tagbot_enabled
"AUTOMERGE_GITHUB_TOKEN"
else
"AUTOMERGE_TAGBOT_TOKEN"
end
auth = my_retry(() -> GitHub.authenticate(api, env[key]))
whoami = my_retry(() -> username(api, cicfg; auth=auth))
@info("Authenticated to GitHub as \"$(whoami)\"")
registry_repo = my_retry(() -> GitHub.repo(api, registry; auth=auth))
if run_pr_build
pr_number = pull_request_number(cicfg; env=env)
pr_head_commit_sha = current_pr_head_commit_sha(cicfg; env=env)
pull_request_build(
api,
pr_number,
pr_head_commit_sha,
registry_repo,
registry_head;
auth=auth,
authorized_authors=authorized_authors,
authorized_authors_special_jll_exceptions=authorized_authors_special_jll_exceptions,
error_exit_if_automerge_not_applicable=error_exit_if_automerge_not_applicable,
master_branch=master_branch,
master_branch_is_default_branch=master_branch_is_default_branch,
suggest_onepointzero=suggest_onepointzero,
point_to_slack=point_to_slack,
whoami=whoami,
registry_deps=registry_deps,
check_license=check_license,
public_registries=public_registries,
read_only=read_only,
environment_variables_to_pass=environment_variables_to_pass,
new_package_waiting_period=new_package_waiting_period,
)
else
always_assert(run_merge_build)
cron_or_api_build(
api,
registry_repo;
auth=auth,
authorized_authors=authorized_authors,
authorized_authors_special_jll_exceptions=authorized_authors_special_jll_exceptions,
merge_new_packages=merge_new_packages,
merge_new_versions=merge_new_versions,
new_package_waiting_period=new_package_waiting_period,
new_jll_package_waiting_period=new_jll_package_waiting_period,
new_version_waiting_period=new_version_waiting_period,
new_jll_version_waiting_period=new_jll_version_waiting_period,
whoami=whoami,
all_statuses=all_statuses,
all_check_runs=all_check_runs,
read_only=read_only,
)
end
return nothing
end
| RegistryCI | https://github.com/JuliaRegistries/RegistryCI.jl.git |
|
[
"MIT"
] | 10.7.0 | f0341c8179a869629d90fe549511d6ffaf1da9a1 | code | 9435 | const new_package_title_regex = r"^New package: (\S*) v(\S*)$"
const new_version_title_regex = r"^New version: (\w*?) v(\S*?)$"
const commit_regex = r"Commit: ([0-9a-f]+)"
function is_new_package(pull_request::GitHub.PullRequest)
return occursin(new_package_title_regex, title(pull_request))
end
function is_new_version(pull_request::GitHub.PullRequest)
return occursin(new_version_title_regex, title(pull_request))
end
function check_authorization(
pkg,
pr_author_login,
authorized_authors,
authorized_authors_special_jll_exceptions,
error_exit_if_automerge_not_applicable,
)
if pr_author_login ∉ vcat(authorized_authors, authorized_authors_special_jll_exceptions)
throw_not_automerge_applicable(
AutoMergeAuthorNotAuthorized,
"Author $(pr_author_login) is not authorized to automerge. Exiting...";
error_exit_if_automerge_not_applicable=error_exit_if_automerge_not_applicable,
)
return :not_authorized
end
# A JLL-only author (e.g. `jlbuild`) is not allowed to register
# non-JLL packages.
this_is_jll_package = is_jll_name(pkg)
if (!this_is_jll_package && pr_author_login ∉ authorized_authors)
throw_not_automerge_applicable(
AutoMergeAuthorNotAuthorized,
"This package is not a JLL package. Author $(pr_author_login) is not authorized to register non-JLL packages. Exiting...";
error_exit_if_automerge_not_applicable=error_exit_if_automerge_not_applicable,
)
return :not_authorized
end
if pr_author_login ∈ authorized_authors_special_jll_exceptions
return :jll
end
return :normal
end
function parse_pull_request_title(::NewVersion, pull_request::GitHub.PullRequest)
m = match(new_version_title_regex, title(pull_request))
pkg = convert(String, m.captures[1])::String
version = VersionNumber(m.captures[2])
return pkg, version
end
function commit_from_pull_request_body(pull_request::GitHub.PullRequest)
pr_body = body(pull_request)
m = match(commit_regex, pr_body)
commit = convert(String, m.captures[1])::String
always_assert(length(commit) == 40)
return commit
end
function parse_pull_request_title(::NewPackage, pull_request::GitHub.PullRequest)
m = match(new_package_title_regex, title(pull_request))
pkg = convert(String, m.captures[1])::String
version = VersionNumber(m.captures[2])
return pkg, version
end
function pull_request_build(
api::GitHub.GitHubAPI,
pr_number::Integer,
current_pr_head_commit_sha::String,
registry::GitHub.Repo,
registry_head::String;
whoami::String,
auth::GitHub.Authorization,
authorized_authors::Vector{String},
authorized_authors_special_jll_exceptions::Vector{String},
error_exit_if_automerge_not_applicable=error_exit_if_automerge_not_applicable,
master_branch::String,
master_branch_is_default_branch::Bool,
suggest_onepointzero::Bool,
point_to_slack::Bool,
registry_deps::Vector{<:AbstractString}=String[],
check_license::Bool,
public_registries::Vector{<:AbstractString}=String[],
read_only::Bool,
environment_variables_to_pass::Vector{<:AbstractString}=String[],
new_package_waiting_period=new_package_waiting_period,
)::Nothing
pr = my_retry(() -> GitHub.pull_request(api, registry, pr_number; auth=auth))
_github_api_pr_head_commit_sha = pull_request_head_sha(pr)
if current_pr_head_commit_sha != _github_api_pr_head_commit_sha
throw(
AutoMergeShaMismatch(
"Current commit sha (\"$(current_pr_head_commit_sha)\") does not match what the GitHub API tells us (\"$(_github_api_pr_head_commit_sha)\")",
),
)
end
# 1. Check if the PR is open, if not quit.
# 2. Determine if it is a new package or new version of an
# existing package, if neither quit.
# 3. Check if the author is authorized, if not quit.
# 4. Call the appropriate method for new package or new version.
if !is_open(pr)
throw_not_automerge_applicable(
AutoMergePullRequestNotOpen,
"The pull request is not open. Exiting...";
error_exit_if_automerge_not_applicable=error_exit_if_automerge_not_applicable,
)
return nothing
end
if is_new_package(pr)
registration_type = NewPackage()
elseif is_new_version(pr)
registration_type = NewVersion()
else
throw_not_automerge_applicable(
AutoMergeNeitherNewPackageNorNewVersion,
"Neither a new package nor a new version. Exiting...";
error_exit_if_automerge_not_applicable=error_exit_if_automerge_not_applicable,
)
return nothing
end
pkg, version = parse_pull_request_title(registration_type, pr)
pr_author_login = author_login(pr)
authorization = check_authorization(
pkg,
pr_author_login,
authorized_authors,
authorized_authors_special_jll_exceptions,
error_exit_if_automerge_not_applicable,
)
if authorization == :not_authorized
return nothing
end
registry_master = clone_repo(registry)
if !master_branch_is_default_branch
checkout_branch(registry_master, master_branch)
end
data = GitHubAutoMergeData(;
api=api,
registration_type=registration_type,
pr=pr,
pkg=pkg,
version=version,
current_pr_head_commit_sha=current_pr_head_commit_sha,
registry=registry,
auth=auth,
authorization=authorization,
registry_head=registry_head,
registry_master=registry_master,
suggest_onepointzero=suggest_onepointzero,
point_to_slack=point_to_slack,
whoami=whoami,
registry_deps=registry_deps,
public_registries=public_registries,
read_only=read_only,
environment_variables_to_pass=environment_variables_to_pass,
)
pull_request_build(data; check_license=check_license, new_package_waiting_period=new_package_waiting_period)
rm(registry_master; force=true, recursive=true)
return nothing
end
function pull_request_build(data::GitHubAutoMergeData; check_license, new_package_waiting_period)::Nothing
kind = package_or_version(data.registration_type)
this_is_jll_package = is_jll_name(data.pkg)
@info(
"This is a new $kind pull request",
pkg = data.pkg,
version = data.version,
this_is_jll_package
)
update_status(
data;
state="pending",
context="automerge/decision",
description="New $kind. Pending.",
)
this_pr_can_use_special_jll_exceptions =
this_is_jll_package && data.authorization == :jll
guidelines = get_automerge_guidelines(
data.registration_type;
check_license=check_license,
this_is_jll_package=this_is_jll_package,
this_pr_can_use_special_jll_exceptions=this_pr_can_use_special_jll_exceptions,
use_distance_check=perform_distance_check(data.pr.labels),
package_author_approved=has_package_author_approved_label(data.pr.labels)
)
checked_guidelines = Guideline[]
for (guideline, applicable) in guidelines
applicable || continue
if guideline == :early_exit_if_failed
all(passed, checked_guidelines) || break
elseif guideline == :update_status
if !all(passed, checked_guidelines)
update_status(
data;
state="failure",
context="automerge/decision",
description="New version. Failed.",
)
end
else
check!(guideline, data)
@info(
guideline.info,
meets_this_guideline = passed(guideline),
message = message(guideline)
)
push!(checked_guidelines, guideline)
end
end
if all(passed, checked_guidelines) # success
description = "New $kind. Approved. name=\"$(data.pkg)\". sha=\"$(data.current_pr_head_commit_sha)\""
update_status(
data; state="success", context="automerge/decision", description=description
)
this_pr_comment_pass = comment_text_pass(
data.registration_type,
data.suggest_onepointzero,
data.version,
this_pr_can_use_special_jll_exceptions;
new_package_waiting_period=new_package_waiting_period
)
my_retry(() -> update_automerge_comment!(data, this_pr_comment_pass))
else # failure
update_status(
data;
state="failure",
context="automerge/decision",
description="New $kind. Failed.",
)
failing_messages = message.(filter(!passed, checked_guidelines))
this_pr_comment_fail = comment_text_fail(
data.registration_type,
failing_messages,
data.suggest_onepointzero,
data.version;
point_to_slack=data.point_to_slack,
)
my_retry(() -> update_automerge_comment!(data, this_pr_comment_fail))
throw(AutoMergeGuidelinesNotMet("The automerge guidelines were not met."))
end
return nothing
end
package_or_version(::NewPackage) = "package"
package_or_version(::NewVersion) = "version"
| RegistryCI | https://github.com/JuliaRegistries/RegistryCI.jl.git |
|
[
"MIT"
] | 10.7.0 | f0341c8179a869629d90fe549511d6ffaf1da9a1 | code | 6254 | @static if Base.VERSION >= v"1.7.0-"
const isless_ll = Pkg.Versions.isless_ll
const isless_uu = Pkg.Versions.isless_uu
else
const isless_ll = Pkg.Types.isless_ll
const isless_uu = Pkg.Types.isless_uu
end
function difference(x::VersionNumber, y::VersionNumber)
if y.major > x.major
return VersionNumber(y.major - x.major, y.minor, y.patch)
elseif y.minor > x.minor
return VersionNumber(y.major - x.major, y.minor - x.minor, y.patch)
elseif y.patch > x.patch
return VersionNumber(y.major - x.major, y.minor - x.minor, y.patch - x.patch)
else
msg = "first argument $(x) must be strictly less than the second argument $(y)"
@warn msg x y
return ErrorCannotComputeVersionDifference(msg)
end
end
function leftmost_nonzero(v::VersionNumber)::Symbol
if v.major != 0
return :major
elseif v.minor != 0
return :minor
elseif v.patch != 0
return :patch
else
throw(ArgumentError("there are no nonzero components"))
end
end
function is_breaking(a::VersionNumber, b::VersionNumber)::Bool
if a < b
a_leftmost_nonzero = leftmost_nonzero(a)
if a_leftmost_nonzero == :major
if a.major == b.major
return false # major stayed the same nonzero value => nonbreaking
else
return true # major increased => breaking
end
elseif a_leftmost_nonzero == :minor
if a.major == b.major
if a.minor == b.minor
return false # major stayed 0, minor stayed the same nonzero value, patch increased => nonbreaking
else
return true # major stayed 0 and minor increased => breaking
end
else
return true # major increased => breaking
end
else
always_assert(a_leftmost_nonzero == :patch)
if a.major == b.major
if a.minor == b.minor
# this corresponds to 0.0.1 -> 0.0.2
# set it to true if 0.0.1 -> 0.0.2 should be breaking
# set it to false if 0.0.1 -> 0.0.2 should be non-breaking
return true # major stayed 0, minor stayed 0, patch increased
else
return true # major stayed 0 and minor increased => breaking
end
else
return true # major increased => breaking
end
end
else
throw(
ArgumentError("first argument must be strictly less than the second argument")
)
end
end
function all_versions(pkg::String, registry_path::String)
package_relpath = get_package_relpath_in_registry(;
package_name=pkg, registry_path=registry_path
)
return VersionNumber.(
keys(Pkg.TOML.parsefile(joinpath(registry_path, package_relpath, "Versions.toml")))
)
end
function latest_version(pkg::String, registry_path::String)
return maximum(all_versions(pkg, registry_path))
end
function julia_compat(pkg::String, version::VersionNumber, registry_path::String)
package_relpath = get_package_relpath_in_registry(;
package_name=pkg, registry_path=registry_path
)
all_compat_entries_for_julia = Pkg.Types.VersionRange[]
compat_file = joinpath(registry_path, package_relpath, "Compat.toml")
compat = maybe_parse_toml(compat_file)
for version_range in keys(compat)
if version in Pkg.Types.VersionRange(version_range)
for compat_entry in compat[version_range]
name = compat_entry[1]
if strip(lowercase(name)) == strip(lowercase("julia"))
value = compat_entry[2]
if value isa Vector
for x in value
x_range = Pkg.Types.VersionRange(x)
push!(all_compat_entries_for_julia, x_range)
end
else
value_range = Pkg.Types.VersionRange(value)
push!(all_compat_entries_for_julia, value_range)
end
end
end
end
end
if length(all_compat_entries_for_julia) < 1
return Pkg.Types.VersionRange[Pkg.Types.VersionRange("* - *")]
else
return all_compat_entries_for_julia
end
end
function _has_upper_bound(r::Pkg.Types.VersionRange)
a = r.upper != Pkg.Types.VersionBound("*")
b = r.upper != Pkg.Types.VersionBound("0")
c = !(Base.VersionNumber(0, typemax(Base.VInt), typemax(Base.VInt)) in r)
d =
!(
Base.VersionNumber(
typemax(Base.VInt), typemax(Base.VInt), typemax(Base.VInt)
) in r
)
e = !(typemax(Base.VersionNumber) in r)
result = a && b && c && d && e
return result
end
function range_did_not_narrow(r1::Pkg.Types.VersionRange, r2::Pkg.Types.VersionRange)
result = !isless_ll(r1.lower, r2.lower) && !isless_uu(r2.upper, r1.upper)
return result
end
function range_did_not_narrow(
v1::Vector{Pkg.Types.VersionRange}, v2::Vector{Pkg.Types.VersionRange}
)
@debug("", v1, v2, repr(v1), repr(v2))
if isempty(v1) || isempty(v2)
return false
else
n_1 = length(v1)
n_2 = length(v2)
results = falses(n_1, n_2) # v1 along the rows, v2 along the columns
for i in 1:n_1
for j in 1:n_2
results[i, j] = range_did_not_narrow(v1[i], v2[j])
end
end
@debug("", results, repr(results))
return all(results)
end
end
thispatch(v::VersionNumber) = VersionNumber(v.major, v.minor, v.patch)
thisminor(v::VersionNumber) = VersionNumber(v.major, v.minor, 0)
thismajor(v::VersionNumber) = VersionNumber(v.major, 0, 0)
function nextpatch(v::VersionNumber)
return v < thispatch(v) ? thispatch(v) : VersionNumber(v.major, v.minor, v.patch + 1)
end
function nextminor(v::VersionNumber)
return v < thisminor(v) ? thisminor(v) : VersionNumber(v.major, v.minor + 1, 0)
end
function nextmajor(v::VersionNumber)
return v < thismajor(v) ? thismajor(v) : VersionNumber(v.major + 1, 0, 0)
end
| RegistryCI | https://github.com/JuliaRegistries/RegistryCI.jl.git |
|
[
"MIT"
] | 10.7.0 | f0341c8179a869629d90fe549511d6ffaf1da9a1 | code | 94 | maybe_parse_toml(f::AbstractString) = ispath(f) ? Pkg.TOML.parsefile(f) : Dict{String, Any}()
| RegistryCI | https://github.com/JuliaRegistries/RegistryCI.jl.git |
|
[
"MIT"
] | 10.7.0 | f0341c8179a869629d90fe549511d6ffaf1da9a1 | code | 4391 | struct AlwaysAssertionError <: Exception
msg::String
end
struct NewPackage end
struct NewVersion end
abstract type AutoMergeException <: Exception end
struct AutoMergeAuthorNotAuthorized <: AutoMergeException
msg::String
end
struct AutoMergeCronJobError <: AutoMergeException
msg::String
end
struct AutoMergeGuidelinesNotMet <: AutoMergeException
msg::String
end
struct AutoMergeNeitherNewPackageNorNewVersion <: AutoMergeException
msg::String
end
struct AutoMergePullRequestNotOpen <: AutoMergeException
msg::String
end
struct AutoMergeShaMismatch <: AutoMergeException
msg::String
end
struct AutoMergeWrongBuildType <: AutoMergeException
msg::String
end
struct ErrorCannotComputeVersionDifference
msg::String
end
struct GitHubAutoMergeData
# Handle to the GitHub API. Used to query the PR and update
# comments and status.
api::GitHub.GitHubAPI
# Whether the registry PR refers to a new package or a new version
# of an existing package.
registration_type::Union{NewPackage,NewVersion}
# The GitHub pull request data.
pr::GitHub.PullRequest
# Name of the package being registered.
pkg::String
# Version of the package being registered.
version::VersionNumber
# Used for updating CI status.
current_pr_head_commit_sha::String
# The GitHub repo data for the registry.
registry::GitHub.Repo
# GitHub authorization data.
auth::GitHub.Authorization
# Type of authorization for automerge. This can be either:
# :jll - special jll exceptions are allowed,
# :normal - normal automerge rules.
authorization::Symbol
# Directory of a registry clone that includes the PR.
registry_head::String
# Directory of a registry clone that excludes the PR.
registry_master::String
# Whether to add a comment suggesting bumping package version to
# 1.0 if appropriate.
suggest_onepointzero::Bool
# Whether to add a comment suggesting to ask on the #pkg-registration
# Julia-Slack channel when AutoMerge is not possible
point_to_slack::Bool
# GitHub identity resulting from the use of an authentication token.
whoami::String
# List of dependent registries. Typically this would contain
# "General" when running automerge for a private registry.
registry_deps::Vector{String}
# Location of the directory where the package code
# will be downloaded into. Populated at construction time
# via `mktempdir`.
pkg_code_path::String
# A list of public Julia registries (repository URLs) which will
# be checked for UUID collisions in order to mitigate the
# dependency confusion vulnerability. See the
# `dependency_confusion.jl` file for details.
public_registries::Vector{String}
# whether only read-only actions should be taken
read_only::Bool
# Environment variables to pass to the subprocess that does `Pkg.add("Foo")` and `import Foo`
environment_variables_to_pass::Vector{String}
end
# Constructor that requires all fields (except `pkg_code_path`) as named arguments.
function GitHubAutoMergeData(; kwargs...)
pkg_code_path = mktempdir(; cleanup=true)
kwargs = (; pkg_code_path=pkg_code_path, kwargs...)
fields = fieldnames(GitHubAutoMergeData)
always_assert(Set(keys(kwargs)) == Set(fields))
always_assert(kwargs[:authorization] ∈ (:normal, :jll))
return GitHubAutoMergeData(getindex.(Ref(kwargs), fields)...)
end
Base.@kwdef mutable struct Guideline
# Short description of the guideline. Only used for logging.
info::String
# Documentation for the guideline
docs::Union{String,Nothing} = info
# Function that is run in order to determine whether a guideline
# is met. Input is an instance of `GitHubAutoMergeData` and output
# is passed status plus a user facing message explaining the
# guideline result.
check::Function
# Saved result of the `check` function.
passed::Bool = false
# Saved output message from the `check` function.
message::String = "Internal error. A check that was supposed to run never did: $(info)"
end
passed(guideline::Guideline) = guideline.passed
message(guideline::Guideline) = guideline.message
function check!(guideline::Guideline, data::GitHubAutoMergeData)
return guideline.passed, guideline.message = guideline.check(data)
end
| RegistryCI | https://github.com/JuliaRegistries/RegistryCI.jl.git |
|
[
"MIT"
] | 10.7.0 | f0341c8179a869629d90fe549511d6ffaf1da9a1 | code | 413 | function update_status(data::GitHubAutoMergeData; kwargs...)
if data.read_only
@info "`read_only` mode; skipping updating the status"
return nothing
end
return my_retry(
() -> GitHub.create_status(
data.api,
data.registry,
data.current_pr_head_commit_sha;
auth=data.auth,
params=Dict(kwargs...),
),
)
end
| RegistryCI | https://github.com/JuliaRegistries/RegistryCI.jl.git |
|
[
"MIT"
] | 10.7.0 | f0341c8179a869629d90fe549511d6ffaf1da9a1 | code | 13376 | function checkout_branch(
dir::AbstractString, branch::AbstractString; git_command::AbstractString="git"
)
return Base.run(Cmd(`$(git_command) checkout $(branch)`; dir=dir))
end
clone_repo(repo::GitHub.Repo) = clone_repo(repo_url(repo))
function clone_repo(url::AbstractString)
parent_dir = mktempdir(; cleanup=true)
repo_dir = joinpath(parent_dir, "REPO")
my_retry(() -> _clone_repo_into_dir(url, repo_dir))
@info("Clone was successful")
return repo_dir
end
function _clone_repo_into_dir(url::AbstractString, repo_dir)
@info("Attempting to clone...")
rm(repo_dir; force=true, recursive=true)
mkpath(repo_dir)
LibGit2.clone(url, repo_dir)
return repo_dir
end
"""
load_files_from_url_and_tree_hash(f, destination::String, url::String, tree_hash::String) -> Bool
Attempts to clone a git repo from `url` into a temporary directory, runs `f(dir)` on that directory,
then extract the files and folders from a given `tree_hash`, placing them in `destination`.
Returns a boolean indicating if the cloning succeeded.
"""
function load_files_from_url_and_tree_hash(
f, destination::String, url::String, tree_hash::String
)
pkg_clone_dir = mktempdir()
clone_success = try
_clone_repo_into_dir(url, pkg_clone_dir)
true
catch e
@error "Cloning $url failed" e
false
end
# if cloning failed, bail now
!clone_success && return clone_success
f(pkg_clone_dir)
Tar.extract(Cmd(`git archive $tree_hash`; dir=pkg_clone_dir), destination)
return clone_success
end
"""
parse_registry_pkg_info(registry_path, pkg, version=nothing) -> @NamedTuple{uuid::String, repo::String, subdir::String, tree_hash::Union{Nothing, String}}
Searches the registry located at `registry_path` for a package with name `pkg`. Upon finding it,
it parses the associated `Package.toml` file and returns the UUID and repository URI, and `subdir`.
If `version` is supplied, then the associated `tree_hash` will be returned. Otherwise, `tree_hash` will be `nothing`.
"""
function parse_registry_pkg_info(registry_path, pkg, version=nothing)
# We know the name of this package but not its uuid. Look it up in
# the registry that includes the current PR.
packages = TOML.parsefile(joinpath(registry_path, "Registry.toml"))["packages"]
filter!(packages) do (key, value)
value["name"] == pkg
end
# For Julia >= 1.4 this can be simplified with the `only` function.
always_assert(length(packages) == 1)
uuid = convert(String, first(keys(packages)))
# Also need to find out the package repository.
package = TOML.parsefile(
joinpath(registry_path, packages[uuid]["path"], "Package.toml")
)
repo = convert(String, package["repo"])
subdir = convert(String, get(package, "subdir", ""))
if version === nothing
tree_hash = nothing
else
versions = TOML.parsefile(
joinpath(registry_path, packages[uuid]["path"], "Versions.toml")
)
tree_hash = convert(String, versions[string(version)]["git-tree-sha1"])
end
return (; uuid=uuid, repo=repo, subdir=subdir, tree_hash=tree_hash)
end
#####
##### AutoMerge comment
#####
# The AutoMerge comment is divided into numbered sections.
# Besides the "AutoMerge Guidelines which are not met" and "AutoMerge Guidelines have all passed!"
# sections, we keep these minimally customized, and instead simply include or exclude
# whole sections depending on the context. This way, users can understand the message
# without necessarily reading the details of each section each time.
# We hope they will at least read the section titles, and if they aren't
# familiar, hopefully they will also read the sections themselves.
function _comment_bot_intro()
return string("Hello, I am an automated registration bot.",
" I help manage the registration process by checking your registration against a set of ","[AutoMerge guidelines](https://juliaregistries.github.io/RegistryCI.jl/stable/guidelines/). ",
"If all these guidelines are met, this pull request will be merged automatically, completing your registration. It is **strongly recommended** to follow the guidelines, since otherwise ",
"the pull request needs to be manually reviewed and merged by a human.\n\n")
end
function _new_package_section(n)
return string("## $n. New package registration", "\n\n",
"Please make sure that you have read the ",
"[package naming guidelines](https://julialang.github.io/Pkg.jl/dev/creating-packages/#Package-naming-guidelines-1).\n\n")
end
function _what_next_if_fail(n; point_to_slack=false)
msg = """
## $n. *Needs action*: here's what to do next
1. Please try to update your package to conform to these guidelines. The [General registry's README](https://github.com/JuliaRegistries/General/blob/master/README.md) has an FAQ that can help figure out how to do so."""
msg = string(msg, "\n",
"2. After you have fixed the AutoMerge issues, simply retrigger Registrator, the same way you did in the initial registration. This will automatically update this pull request. You do not need to change the version number in your `Project.toml` file (unless the AutoMerge issue is that you skipped a version number).",
"\n\n",
"If you need help fixing the AutoMerge issues, or want your pull request to be manually merged instead, please post a comment explaining what you need help with or why you would like this pull request to be manually merged.")
if point_to_slack
msg = string(msg, " Then, send a message to the `#pkg-registration` channel in the [public Julia Slack](https://julialang.org/slack/) for better visibility.")
end
msg = string(msg, "\n\n")
return msg
end
function _automerge_guidelines_failed_section_title(n)
return "## $n. [AutoMerge Guidelines](https://juliaregistries.github.io/RegistryCI.jl/stable/guidelines/) which are not met ❌\n\n"
end
function _automerge_guidelines_passed_section_title(n)
"## $n. [AutoMerge Guidelines](https://juliaregistries.github.io/RegistryCI.jl/stable/guidelines/) are all met! ✅\n\n"
end
function _comment_noblock(n)
result = string(
"## $n. To pause or stop registration\n\n",
"If you want to prevent this pull request from ",
"being auto-merged, simply leave a comment. ",
"If you want to post a comment without blocking ",
"auto-merging, you must include the text ",
"`[noblock]` in your comment. ",
"\n\n_Tip: You can edit blocking comments to add `[noblock]` ",
"in order to unblock auto-merging._\n\n",
)
return result
end
function comment_text_pass(
::NewVersion, suggest_onepointzero::Bool, version::VersionNumber, is_jll::Bool; new_package_waiting_period
)
# Need to know this ahead of time to get the section numbers right
suggest_onepointzero &= version < v"1.0.0"
result = string(
_comment_bot_intro(),
_automerge_guidelines_passed_section_title(1),
"Your new version registration met all of the ",
"guidelines for auto-merging and is scheduled to ",
"be merged in the next round.\n\n",
_onepointzero_suggestion(2, suggest_onepointzero, version),
_comment_noblock(suggest_onepointzero ? 3 : 2),
"<!-- [noblock] -->",
)
return result
end
function comment_text_pass(
::NewPackage, suggest_onepointzero::Bool, version::VersionNumber, is_jll::Bool; new_package_waiting_period
)
suggest_onepointzero &= version < v"1.0.0"
if is_jll
result = string(
_comment_bot_intro(),
_automerge_guidelines_passed_section_title(1),
"Your new `_jll` package registration met all of the ",
"guidelines for auto-merging and is scheduled to ",
"be merged in the next round.\n\n",
_onepointzero_suggestion(2, suggest_onepointzero, version),
_comment_noblock(suggest_onepointzero ? 3 : 2),
"<!-- [noblock] -->",
)
else
result = string(
_comment_bot_intro(),
_new_package_section(1),
_automerge_guidelines_passed_section_title(2),
"Your new package registration met all of the ",
"guidelines for auto-merging and is scheduled to ",
"be merged when the mandatory waiting period ($new_package_waiting_period) has elapsed.\n\n",
_onepointzero_suggestion(3, suggest_onepointzero, version),
_comment_noblock(suggest_onepointzero ? 4 : 3),
"<!-- [noblock] -->",
)
end
return result
end
function comment_text_fail(
::NewPackage,
reasons::Vector{String},
suggest_onepointzero::Bool,
version::VersionNumber;
point_to_slack::Bool=false,
)
suggest_onepointzero &= version < v"1.0.0"
reasons_formatted = string(join(string.("- ", reasons), "\n"), "\n\n")
result = string(
_comment_bot_intro(),
_new_package_section(1),
_automerge_guidelines_failed_section_title(2),
reasons_formatted,
_what_next_if_fail(3; point_to_slack=point_to_slack),
_onepointzero_suggestion(4, suggest_onepointzero, version),
_comment_noblock(suggest_onepointzero ? 5 : 4),
"<!-- [noblock] -->",
)
return result
end
function comment_text_fail(
::NewVersion,
reasons::Vector{String},
suggest_onepointzero::Bool,
version::VersionNumber;
point_to_slack::Bool=false,
)
suggest_onepointzero &= version < v"1.0.0"
reasons_formatted = string(join(string.("- ", reasons), "\n"), "\n\n")
result = string(
_comment_bot_intro(),
_automerge_guidelines_failed_section_title(1),
reasons_formatted,
_what_next_if_fail(2; point_to_slack=point_to_slack),
_onepointzero_suggestion(3, suggest_onepointzero, version),
_comment_noblock(suggest_onepointzero ? 4 : 3),
"<!-- [noblock] -->",
)
return result
end
is_julia_stdlib(name) = name in julia_stdlib_list()
function julia_stdlib_list()
stdlib_list = readdir(Pkg.Types.stdlib_dir())
# Before Julia v1.6 Artifacts.jl isn't a standard library, but
# we want to include it because JLL packages depend on the empty
# placeholder https://github.com/JuliaPackaging/Artifacts.jl
# in older versions for compatibility.
if VERSION < v"1.6.0"
push!(stdlib_list, "Artifacts")
end
return stdlib_list
end
function now_utc()
utc = TimeZones.tz"UTC"
return Dates.now(utc)
end
function _onepointzero_suggestion(n, suggest_onepointzero::Bool, version::VersionNumber)
if suggest_onepointzero && version < v"1.0.0"
result = string(
"## $n. Declare v1.0?\n\n",
"On a separate note, I see that you are registering ",
"a release with a version number of the form ",
"`v0.X.Y`.\n\n",
"Does your package have a stable public API? ",
"If so, then it's time for you to register version ",
"`v1.0.0` of your package. ",
"(This is not a requirement. ",
"It's just a recommendation.)\n\n",
"If your package does not yet have a stable public ",
"API, then of course you are not yet ready to ",
"release version `v1.0.0`.\n\n",
)
return result
else
return ""
end
end
function time_is_already_in_utc(dt::Dates.DateTime)
utc = TimeZones.tz"UTC"
return TimeZones.ZonedDateTime(dt, utc; from_utc=true)
end
"""
get_all_non_jll_package_names(registry_dir::AbstractString) -> Vector{String}
get_all_non_jll_package_names(registry::RegistryInstance) -> Vector{String}
Given either:
- a path to a directory holding an uncompressed registry
or
- a `RegistryInstance` object (from [RegistryInstances.jl](https://github.com/GunnarFarneback/RegistryInstances.jl)) associated to a registry,
returns a sorted list of the names of Julia's standard libraries
and all the non-JLL packages defined in that registry.
"""
function get_all_non_jll_package_names(registry_dir::AbstractString)
# Mimic the structure of a RegistryInstance
list = TOML.parsefile(joinpath(registry_dir, "Registry.toml"))["packages"]
registry = (; pkgs=Dict(k => (; name=v["name"]) for (k,v) in pairs(list)))
return get_all_non_jll_package_names(registry)
end
# Generic method intended for RegistryInstance (without taking on the dependency,
# which is only valid on Julia 1.7+)
function get_all_non_jll_package_names(registry)
packages = [entry.name for entry in values(registry.pkgs)]
append!(packages, (RegistryTools.get_stdlib_name(x) for x in values(RegistryTools.stdlibs())))
sort!(packages)
filter!(x -> !endswith(x, "_jll"), packages)
unique!(packages)
return packages
end
const PACKAGE_AUTHOR_APPROVED_LABEL = "Override AutoMerge: package author approved"
function has_package_author_approved_label(labels)
# No labels? Not approved
isnothing(labels) && return false
for label in labels
if label.name === PACKAGE_AUTHOR_APPROVED_LABEL
# found the approval
@debug "Found `$(PACKAGE_AUTHOR_APPROVED_LABEL)` label"
return true
end
end
# Did not find approval
return false
end
| RegistryCI | https://github.com/JuliaRegistries/RegistryCI.jl.git |
|
[
"MIT"
] | 10.7.0 | f0341c8179a869629d90fe549511d6ffaf1da9a1 | code | 4940 | module TagBot
using Base64: base64decode, base64encode
using Dates: Day, Minute, UTC, now
using Random: randstring
using SHA: sha1
using GitHub: GitHub
using JSON: JSON
const GH = GitHub
const AUTH = Ref{GH.OAuth2}()
const TAGBOT_USER = Ref{String}()
const ISSUE_TITLE = "TagBot trigger issue"
const ISSUE_BODY = """
This issue is used to trigger TagBot; feel free to unsubscribe.
If you haven't already, you should update your `TagBot.yml` to include issue comment triggers.
Please see [this post on Discourse](https://discourse.julialang.org/t/ann-required-updates-to-tagbot-yml/49249) for instructions and more details.
If you'd like for me to do this for you, comment `TagBot fix` on this issue.
I'll open a PR within a few hours, please be patient!
"""
const CRON_ADDENDUM = """
This extra notification is being sent because I expected a tag to exist by now, but it doesn't.
You may want to check your TagBot configuration to ensure that it's running, and if it is, check the logs to make sure that there are no errors.
"""
include("cron.jl")
include("pull_request.jl")
include("fixup.jl")
function main()
AUTH[] = GH.authenticate(ENV["GITHUB_TOKEN"])
TAGBOT_USER[] = GH.whoami(; auth=AUTH[]).login
event = JSON.parse(read(ENV["GITHUB_EVENT_PATH"], String))
if is_merged_pull_request(event)
handle_merged_pull_request(event)
elseif is_cron(event)
handle_cron(event)
end
end
function repo_and_version_of_pull_request_body(body)
# Return immediately if the pull request's description is empty. In this
# case no further information can be obtained about a registration
isnothing(body) && return (nothing, nothing)
if occursin("JLL package", body)
@info "Skipping JLL package registration"
return nothing, nothing
end
m = match(r"Repository: .*github\.com[:/](.*)", body)
repo = m === nothing ? nothing : strip(m[1])
repo !== nothing && endswith(repo, ".git") && (repo = repo[1:(end - 4)])
m = match(r"Version: (.*)", body)
version = m === nothing ? nothing : strip(m[1])
return repo, version
end
function tagbot_file(repo; issue_comments=false)
files, pages = try
GH.directory(repo, ".github/workflows"; auth=AUTH[])
catch e
occursin("404", e.msg) && return nothing
rethrow()
end
for f in files
f.typ == "file" || continue
file = GH.file(repo, f.path; auth=AUTH[])
contents = String(base64decode(file.content))
if occursin("JuliaRegistries/TagBot", contents) || occursin("julia-vscode/testitem-workflow/.github/workflows/juliaci.yml", contents)
issue_comments && !occursin("issue_comment", contents) && continue
return f.path, contents
end
end
return nothing
end
function get_repo_notification_issue(repo)
issues, _ = GH.issues(
repo; auth=AUTH[], params=(; creator=TAGBOT_USER[], state="closed")
)
filter!(x -> x.pull_request === nothing, issues)
return if isempty(issues)
@info "Creating new notification issue"
issue = try
GH.create_issue(repo; auth=AUTH[], params=(; title=ISSUE_TITLE, body=ISSUE_BODY))
catch e
occursin("Issues are disabled", e.msg) || rethrow()
@info "Issues are disabled on $repo"
return nothing
end
GH.edit_issue(repo, issue; auth=AUTH[], params=(; state="closed"))
issue
else
@info "Found existing notification issue"
issues[1]
end
end
function notification_body(event; cron=false)
url = get(get(event, "pull_request", Dict()), "html_url", "")
body = "Triggering TagBot for merged registry pull request"
isempty(url) || (body = "$body: $url")
cron && (body *= CRON_ADDENDUM)
return body
end
function notify(repo, issue, body)
return GH.create_comment(repo, issue, :issue; auth=AUTH[], params=(; body=body))
end
function tag_exists(repo, version)
return try
GH.tag(repo, version; auth=AUTH[])
true
catch e
if !occursin("404", e.msg)
@warn "Unknown error when checking for existing tag" ex = (e, catch_backtrace())
end
false
end
end
function maybe_notify(event, repo, version; cron=false)
@info "Processing version $version of $repo"
if tagbot_file(repo) === nothing
@info "TagBot is not enabled on $repo"
return nothing
end
if cron && tag_exists(repo, version)
@info "Tag $version already exists for $repo"
return nothing
end
issue = get_repo_notification_issue(repo)
if issue === nothing
@info "Couldn't get notification issue for $repo"
return nothing
end
if cron && should_fixup(repo, issue)
@info "Opening fixup PR for $repo"
open_fixup_pr(repo)
end
body = notification_body(event; cron=cron)
return notify(repo, issue, body)
end
end
| RegistryCI | https://github.com/JuliaRegistries/RegistryCI.jl.git |
|
[
"MIT"
] | 10.7.0 | f0341c8179a869629d90fe549511d6ffaf1da9a1 | code | 1478 | is_cron(event) = get(ENV, "GITHUB_EVENT_NAME", "") in ("schedule", "workflow_dispatch")
function handle_cron(event)
pulls = collect_pulls(ENV["GITHUB_REPOSITORY"])
repos_versions = map(pull -> repo_and_version_of_pull_request_body(pull.body), pulls)
filter!(rv -> first(rv) !== nothing, repos_versions)
unique!(first, repos_versions) # Send at most one notification per repo.
for (repo, version) in repos_versions
maybe_notify(event, repo, version; cron=true)
end
end
function collect_pulls(repo)
acc = GH.PullRequest[]
kwargs = Dict(
:auth => AUTH[],
:page_limit => 1,
:params => (; state="closed", sort="updated", direction="desc", per_page=100),
)
done = false
while !done
pulls, pages = get_pulls(repo; kwargs...)
for pull in pulls
pull.merged_at === nothing && continue
if now(UTC) - pull.merged_at < Day(3)
push!(acc, pull)
else
done = true
end
end
if haskey(pages, "next")
delete!(kwargs, :params)
kwargs[:start_page] = pages["next"]
else
done = true
end
end
return acc
end
function get_pulls(args...; kwargs...)
return retry(
() -> GH.pull_requests(args...; kwargs...);
check=(s, e) -> occursin("Server error", e.msg),
delays=ExponentialBackOff(; n=5, first_delay=1, factor=2),
)()
end
| RegistryCI | https://github.com/JuliaRegistries/RegistryCI.jl.git |
|
[
"MIT"
] | 10.7.0 | f0341c8179a869629d90fe549511d6ffaf1da9a1 | code | 3221 | const FIXUP_PR_TITLE = "TagBot: Use issue comment triggers"
const FIXUP_COMMIT_MESSAGE = "[ci skip] $FIXUP_PR_TITLE"
const FIXUP_PR_BODY = """
As requested, I've updated your TagBot configuration to use issue comment triggers.
Please note that this PR does not take into account your existing configuration.
If you had any custom configuration, you'll need to add it back yourself.
"""
const TAGBOT_YML = raw"""
name: TagBot
on:
issue_comment:
types:
- created
workflow_dispatch:
jobs:
TagBot:
if: github.event_name == 'workflow_dispatch' || github.actor == 'JuliaTagBot'
runs-on: ubuntu-latest
steps:
- uses: JuliaRegistries/TagBot@v1
with:
token: ${{ secrets.GITHUB_TOKEN }}
ssh: ${{ secrets.DOCUMENTER_KEY }}
"""
function should_fixup(repo, issue)
return fixup_comment_exists(repo, issue) &&
!fixup_done(repo) &&
tagbot_file(repo; issue_comments=true) === nothing
end
function get_fork(repo)
fork = GH.create_fork(repo; auth=AUTH[])
# Make sure the fork is new, otherwise it might be outdated.
return if now(UTC) - fork.created_at > Minute(1)
GH.delete_repo(fork; auth=AUTH[])
get_fork(repo)
else
fork
end
end
function open_fixup_pr(repo; branch="tagbot/$(randstring())", fork=get_fork(repo))
head = GH.commit(fork, "HEAD"; auth=AUTH[])
GH.create_reference(
fork; auth=AUTH[], params=(; sha=head.sha, ref="refs/heads/$branch")
)
path, contents = tagbot_file(fork)
GH.update_file(
fork,
path;
auth=AUTH[],
params=(;
branch=branch,
content=base64encode(TAGBOT_YML),
message=FIXUP_COMMIT_MESSAGE,
sha=bytes2hex(sha1("blob $(length(contents))\0$contents")),
),
)
result = try
GH.create_pull_request(
repo;
auth=AUTH[],
params=(;
title=FIXUP_PR_TITLE,
body=FIXUP_PR_BODY,
head="$(TAGBOT_USER[]):$branch",
base=fork.default_branch,
),
)
catch ex
@error "Encountered an error while trying to create the fixup PR" exception = (
ex, catch_backtrace()
)
nothing
end
return result
end
function fixup_comment_exists(repo, issue)
kwargs = Dict(:auth => AUTH[], :page_limit => 1, :params => (; per_page=100))
while true
comments, pages = GH.comments(repo, issue; kwargs...)
for comment in comments
if is_fixup_trigger(comment)
return true
end
end
if haskey(pages, "next")
delete!(kwargs, :params)
kwargs[:start_page] = pages["next"]
else
return false
end
end
end
function is_fixup_trigger(comment)
return comment.user.login != TAGBOT_USER[] && occursin(r"TagBot fix"i, comment.body)
end
function fixup_done(repo)
pulls, _ = GH.pull_requests(
repo; auth=AUTH[], params=(; creator=TAGBOT_USER[], state="all")
)
for pull in pulls
if pull.title == FIXUP_PR_TITLE
return true
end
end
return false
end
| RegistryCI | https://github.com/JuliaRegistries/RegistryCI.jl.git |
|
[
"MIT"
] | 10.7.0 | f0341c8179a869629d90fe549511d6ffaf1da9a1 | code | 484 | is_merged_pull_request(event) = get(get(event, "pull_request", Dict()), "merged", false)
function handle_merged_pull_request(event)
number = event["pull_request"]["number"]
@info "Processing pull request $number"
repo, version = repo_and_version_of_pull_request_body(event["pull_request"]["body"])
if repo === nothing
@info "Failed to parse GitHub repository from pull request"
return nothing
end
return maybe_notify(event, repo, version)
end
| RegistryCI | https://github.com/JuliaRegistries/RegistryCI.jl.git |
|
[
"MIT"
] | 10.7.0 | f0341c8179a869629d90fe549511d6ffaf1da9a1 | code | 8654 | using Dates
# using GitCommand
using GitHub
using JSON
using Pkg
using Printf
using RegistryCI
using Test
using TimeZones
const AutoMerge = RegistryCI.AutoMerge
const timestamp_regex = r"integration\/(\d\d\d\d-\d\d-\d\d-\d\d-\d\d-\d\d-\d\d\d)\/"
function wait_pr_compute_mergeability(
api::GitHub.GitHubAPI,
repo::GitHub.Repo,
pr::GitHub.PullRequest;
auth::GitHub.Authorization,
)
while !(pr.mergeable isa Bool)
sleep(5)
pr = GitHub.pull_request(api, repo, pr.number; auth=auth)
end
return pr
end
function templates(parts...)
this_filename = @__FILE__
test_directory = dirname(this_filename)
templates_directory = joinpath(test_directory, "templates")
result = joinpath(templates_directory, parts...)
return result
end
function get_random_number_from_system()
result =
parse(Int, strip(read(pipeline(`cat /dev/random`, `od -vAn -N4 -D`), String)))::Int
return result
end
function my_two_datetimes_now()
_now_utc = now(tz"UTC")
_now_et = astimezone(_now_zdt, tz"America/New_York")
return _now_utc, _now_et
end
function my_two_times_now()
_now_utc, _now_et = my_two_datetimes_now()
utc_string = @sprintf "%02d:%02d UTC" hour(_now_utc) minute(_now_utc)
et_string = @sprintf "%02d:%02d %s" hour(_now_et) minute(_now_et) _now_et.zone.name
return result = "$(et_string) ($(utc_string))"
end
function utc_to_string(zdt::ZonedDateTime)
zdt_as_utc = astimezone(zdt, tz"UTC")
y = year(zdt_as_utc)
m = month(zdt_as_utc)
d = day(zdt_as_utc)
h = hour(zdt_as_utc)
mi = minute(zdt_as_utc)
s = second(zdt_as_utc)
ms = millisecond(zdt_as_utc)
result = @sprintf "%04d-%02d-%02d-%02d-%02d-%02d-%03d" y m d h mi s ms
return result
end
function string_to_utc(s::AbstractString)
dt = parse(DateTime, s, dateformat"yyyy-mm-dd-HH-MM-SS-sss")
return ZonedDateTime(dt, tz"UTC")
end
function list_all_origin_branches(git_repo_dir; GIT)
result = Vector{String}(undef, 0)
original_working_directory = pwd()
cd(git_repo_dir)
a = try
read(`$(GIT) branch -a`, String)
catch
""
end
b = split(strip(a), '\n')
b_length = length(b)
c = Vector{String}(undef, b_length)
for i in 1:b_length
c[i] = strip(strip(strip(b[i]), '*'))
c[i] = first(split(c[i], "->"))
c[i] = strip(c[i])
end
my_regex = r"^remotes\/origin\/(.*)$"
for i in 1:b_length
if occursin(my_regex, c[i])
m = match(my_regex, c[i])
if m[1] != "HEAD"
push!(result, m[1])
end
end
end
cd(original_working_directory)
return result
end
function get_age_of_commit(commit)
commit_date_string = strip(read(`git show -s --format=%cI $(commit)`, String))
commit_date = TimeZones.ZonedDateTime(commit_date_string, "yyyy-mm-ddTHH:MM:SSzzzz")
now = TimeZones.ZonedDateTime(TimeZones.now(), TimeZones.localzone())
age = max(now - commit_date, Dates.Millisecond(0))
return age
end
function delete_old_pull_request_branches(AUTOMERGE_INTEGRATION_TEST_REPO, older_than; GIT)
with_cloned_repo(AUTOMERGE_INTEGRATION_TEST_REPO; GIT=GIT) do git_repo_dir
cd(git_repo_dir)
all_origin_branches =
list_all_origin_branches(git_repo_dir; GIT=GIT)::Vector{String}
for branch_name in all_origin_branches
if occursin(timestamp_regex, branch_name)
commit = strip(read(`git rev-parse origin/$(branch_name)`, String))
age = get_age_of_commit(commit)
if age >= older_than
try
run(`$(GIT) push origin --delete $(branch_name)`)
catch ex
@info "Encountered an error while trying to delete branch" exception = (
ex, catch_backtrace()
) branch_name
end
end
end
end
end
return nothing
end
function empty_git_repo(git_repo_dir::AbstractString)
original_working_directory = pwd()
cd(git_repo_dir)
for x in readdir(git_repo_dir)
if x != ".git"
path = joinpath(git_repo_dir, x)
rm(path; force=true, recursive=true)
end
end
cd(original_working_directory)
return nothing
end
function with_temp_dir(f)
original_working_directory = pwd()
tmp_dir = mktempdir()
atexit(() -> rm(tmp_dir; force=true, recursive=true))
cd(tmp_dir)
result = f(tmp_dir)
cd(original_working_directory)
rm(tmp_dir; force=true, recursive=true)
return result
end
function with_cloned_repo(f, repo_url; GIT)
original_working_directory = pwd()
result = with_temp_dir() do dir
git_repo_dir = joinpath(dir, "REPO")
cd(dir)
try
run(`$(GIT) clone $(repo_url) REPO`)
catch
end
cd(git_repo_dir)
return f(git_repo_dir)
end
cd(original_working_directory)
return result
end
function get_git_current_head(dir)
original_working_directory = pwd()
cd(dir)
result = convert(String, strip(read(`git rev-parse HEAD`, String)))::String
cd(original_working_directory)
return result
end
function with_pr_merge_commit(
f::Function, pr::GitHub.PullRequest, repo_url::AbstractString; GIT
)
original_working_directory = pwd()
result = with_cloned_repo(repo_url; GIT=GIT) do git_repo_dir
cd(git_repo_dir)
number = pr.number
run(`$(GIT) fetch origin +refs/pull/$(number)/merge`)
run(`$(GIT) checkout -qf FETCH_HEAD`)
head = get_git_current_head(git_repo_dir)
merge_commit_sha = pr.merge_commit_sha
@test strip(head) == strip(merge_commit_sha)
return f(git_repo_dir)
end
cd(original_working_directory)
return result
end
function _generate_branch_name(name::AbstractString)
sleep(0.1)
_now_utc = now(tz"UTC")
_now_utc_string = utc_to_string(_now_utc)
b = "integration/$(_now_utc_string)/$(rand(UInt32))/$(name)"
sleep(0.1)
return b
end
function generate_branch(
name::AbstractString,
path_to_content::AbstractString,
parent_branch::AbstractString="master";
GIT,
repo_url,
)
original_working_directory = pwd()
b = _generate_branch_name(name)
with_cloned_repo(repo_url; GIT=GIT) do git_repo_dir
cd(git_repo_dir)
run(`$(GIT) checkout $(parent_branch)`)
run(`$(GIT) branch $(b)`)
run(`$(GIT) checkout $(b)`)
empty_git_repo(git_repo_dir)
for x in readdir(path_to_content)
src = joinpath(path_to_content, x)
dst = joinpath(git_repo_dir, x)
rm(dst; force=true, recursive=true)
cp(src, dst; force=true)
end
cd(git_repo_dir)
try
run(`$(GIT) add -A`)
catch
end
try
run(`$(GIT) commit -m "Automatic commit - AutoMerge integration tests"`)
catch
end
try
run(`$(GIT) push origin $(b)`)
catch
end
cd(original_working_directory)
rm(git_repo_dir; force=true, recursive=true)
end
return b
end
function generate_master_branch(
path_to_content::AbstractString, parent_branch::AbstractString="master"; GIT, repo_url
)
name = "master"
b = generate_branch(name, path_to_content, parent_branch; GIT=GIT, repo_url=repo_url)
return b
end
function generate_feature_branch(
path_to_content::AbstractString, parent_branch::AbstractString; GIT, repo_url
)
name = "feature"
b = generate_branch(name, path_to_content, parent_branch; GIT=GIT, repo_url=repo_url)
return b
end
function with_master_branch(
f::Function,
path_to_content::AbstractString,
parent_branch::AbstractString;
GIT,
repo_url,
)
b = generate_master_branch(path_to_content, parent_branch; GIT=GIT, repo_url=repo_url)
result = f(b)
return result
end
function with_feature_branch(
f::Function,
path_to_content::AbstractString,
parent_branch::AbstractString;
GIT,
repo_url,
)
b = generate_feature_branch(path_to_content, parent_branch; GIT=GIT, repo_url=repo_url)
result = f(b)
return result
end
function generate_public_registry(public_dir::AbstractString, GIT)
public_git_repo = mktempdir()
cp(templates(public_dir), public_git_repo; force=true)
run(`$(GIT) -C $(public_git_repo) init`)
run(`$(GIT) -C $(public_git_repo) add .`)
run(`$(GIT) -C $(public_git_repo) commit -m "create"`)
return public_git_repo
end
| RegistryCI | https://github.com/JuliaRegistries/RegistryCI.jl.git |
|
[
"MIT"
] | 10.7.0 | f0341c8179a869629d90fe549511d6ffaf1da9a1 | code | 11636 | using Dates
# using GitCommand
using GitHub
using JSON
using Pkg
using Printf
using RegistryCI
using Test
using TimeZones
const AutoMerge = RegistryCI.AutoMerge
include("automerge-integration-utils.jl")
AUTOMERGE_INTEGRATION_TEST_REPO = ENV["AUTOMERGE_INTEGRATION_TEST_REPO"]::String
TEST_USER_GITHUB_TOKEN = ENV["BCBI_TEST_USER_GITHUB_TOKEN"]::String
INTEGRATION_TEST_READ_ONLY_TOKEN = ENV["INTEGRATION_TEST_READ_ONLY_TOKEN"]::String
GIT = "git"
auth = GitHub.authenticate(TEST_USER_GITHUB_TOKEN)
whoami = RegistryCI.AutoMerge.username(GitHub.DEFAULT_API, auth)
repo_url_without_auth = "https://github.com/$(AUTOMERGE_INTEGRATION_TEST_REPO)"
repo_url_with_auth = "https://$(whoami):$(TEST_USER_GITHUB_TOKEN)@github.com/$(AUTOMERGE_INTEGRATION_TEST_REPO)"
repo = GitHub.repo(AUTOMERGE_INTEGRATION_TEST_REPO; auth=auth)
@test success(`$(GIT) --version`)
@info("Authenticated to GitHub as \"$(whoami)\"")
_delete_branches_older_than = Dates.Hour(3)
delete_old_pull_request_branches(repo_url_with_auth, _delete_branches_older_than; GIT=GIT)
requires_commit = "1c843ed4d4d568345ca557fea48f43efdcd0271f"
hello_world_commit1 = "197e0e03f3f840f830cb5095ab6407d00fbee61c"
hello_world_commit2 = "57b0aec49622faa962c6752d4bc39a62b91fe37c"
@testset "Integration tests" begin
for (
test_number,
(master_dir, feature_dir, public_dir, title, point_to_slack, check_license, pass, commit),
) in enumerate([
(
"master_1",
"feature_1",
"",
"New package: Requires v1.0.0",
true, # point_to_slack
true, # check_license
true, # pass
requires_commit,
), # OK: new package
(
"master_1",
"feature_1",
"",
"New package: Requires v1.0.0",
true, # point_to_slack
true, # check_license
false, # pass
"659e09770ba9fda4a503f8bf281d446c9583ff3b",
), # FAIL: wrong commit!
(
"master_2",
"feature_2",
"",
"New version: Requires v2.0.0",
false, # point_to_slack
false, # check_license
true, # pass
requires_commit,
), # OK: new version
(
"master_1",
"feature_3",
"",
"New package: Req v1.0.0",
false, # point_to_slack
false, # check_license
false, # pass
requires_commit,
), # FAIL: name too short
(
"master_2",
"feature_4",
"",
"New version: Requires v2.0.1",
false, # point_to_slack
false, # check_license
false, # pass
requires_commit,
), # FAIL: skips v2.0.0
(
"master_3",
"feature_5",
"",
"New version: Requires v2.0.0",
false, # point_to_slack
false, # check_license
false, # pass
requires_commit,
), # FAIL: modifies extra file
(
"master_1",
"feature_6",
"",
"New package: HelloWorldC_jll v1.0.6+0",
false, # point_to_slack
false, # check_license
true, # pass
hello_world_commit1,
), # OK: new JLL package
(
"master_4",
"feature_7",
"",
"New version: HelloWorldC_jll v1.0.8+0",
false, # point_to_slack
false, # check_license
true, # pass
hello_world_commit2,
), # OK: new JLL version
(
"master_1",
"feature_8",
"",
"New package: HelloWorldC_jll v1.0.6+0",
false, # point_to_slack
false, # check_license
false, # pass
hello_world_commit1,
), # FAIL: unallowed dependency
(
"master_1",
"feature_1",
"public_1",
"New package: Requires v1.0.0",
false, # point_to_slack
false, # check_license
true, # pass
requires_commit,
), # OK: no UUID conflict
(
"master_1",
"feature_1",
"public_2",
"New package: Requires v1.0.0",
false, # point_to_slack
false, # check_license
false, # pass
requires_commit,
), # FAIL: UUID conflict, name differs
(
"master_1",
"feature_1",
"public_3",
"New package: Requires v1.0.0",
false, # point_to_slack
false, # check_license
false, # pass
requires_commit,
), # FAIL: UUID conflict, repo differs
(
"master_1",
"feature_1",
"public_4",
"New package: Requires v1.0.0",
false, # point_to_slack
false, # check_license
true, # pass
requires_commit,
), # OK: UUID conflict but name and repo match
(
"master_1",
"feature_9",
"",
"New package: Requires-dash v1.0.0",
true, # point_to_slack
true, # check_license
false, # pass
requires_commit,
), # FAIL: new package name is not a Julia identifier
])
@info "Performing integration tests with settings" test_number master_dir feature_dir public_dir title point_to_slack check_license pass commit
with_master_branch(
templates(master_dir), "master"; GIT=GIT, repo_url=repo_url_with_auth
) do master
with_feature_branch(
templates(feature_dir), master; GIT=GIT, repo_url=repo_url_with_auth
) do feature
public_registries = String[]
if public_dir != ""
public_git_repo = generate_public_registry(public_dir, GIT)
push!(public_registries, "file://$(public_git_repo)/.git")
end
head = feature
base = master
body = """
- Foo: Bar
- Commit: $commit
- Hello: World
"""
params = Dict(
"title" => title, "head" => head, "base" => base, "body" => body
)
sleep(1)
pr = GitHub.create_pull_request(repo; auth=auth, params=params)
pr = wait_pr_compute_mergeability(GitHub.DEFAULT_API, repo, pr; auth=auth)
@test pr.mergeable
sleep(1)
with_pr_merge_commit(pr, repo_url_without_auth; GIT=GIT) do build_dir
withenv(
"AUTOMERGE_GITHUB_TOKEN" => TEST_USER_GITHUB_TOKEN,
"TRAVIS_BRANCH" => master,
"TRAVIS_BUILD_DIR" => build_dir,
"TRAVIS_EVENT_TYPE" => "pull_request",
"TRAVIS_PULL_REQUEST" => string(pr.number),
"TRAVIS_PULL_REQUEST_SHA" =>
string(AutoMerge.pull_request_head_sha(pr)),
"TRAVIS_REPO_SLUG" => AUTOMERGE_INTEGRATION_TEST_REPO,
) do
sleep(1)
run_thunk =
() -> AutoMerge.run(;
merge_new_packages=true,
merge_new_versions=true,
new_package_waiting_period=Minute(typemax(Int32)),
new_jll_package_waiting_period=Minute(typemax(Int32)),
new_version_waiting_period=Minute(typemax(Int32)),
new_jll_version_waiting_period=Minute(typemax(Int32)),
registry=AUTOMERGE_INTEGRATION_TEST_REPO,
authorized_authors=String[whoami],
authorized_authors_special_jll_exceptions=String[whoami],
error_exit_if_automerge_not_applicable=true,
master_branch=master,
master_branch_is_default_branch=false,
point_to_slack=point_to_slack,
check_license=check_license,
public_registries=public_registries,
)
@info "Running integration test for " test_number master_dir feature_dir public_dir title point_to_slack check_license pass commit
if pass
run_thunk()
else
@test_throws(
RegistryCI.AutoMerge.AutoMergeGuidelinesNotMet, run_thunk()
)
end
end
withenv(
"AUTOMERGE_GITHUB_TOKEN" => TEST_USER_GITHUB_TOKEN,
"TRAVIS_BRANCH" => master,
"TRAVIS_BUILD_DIR" => build_dir,
"TRAVIS_EVENT_TYPE" => "cron",
"TRAVIS_PULL_REQUEST" => "false",
"TRAVIS_PULL_REQUEST_SHA" => "",
"TRAVIS_REPO_SLUG" => AUTOMERGE_INTEGRATION_TEST_REPO,
) do
sleep(1)
AutoMerge.run(;
merge_new_packages=true,
merge_new_versions=true,
new_package_waiting_period=Minute(typemax(Int32)),
new_jll_package_waiting_period=Minute(typemax(Int32)),
new_version_waiting_period=Minute(typemax(Int32)),
new_jll_version_waiting_period=Minute(typemax(Int32)),
registry=AUTOMERGE_INTEGRATION_TEST_REPO,
authorized_authors=String[whoami],
authorized_authors_special_jll_exceptions=String[whoami],
error_exit_if_automerge_not_applicable=true,
master_branch=master,
master_branch_is_default_branch=false,
)
sleep(1)
AutoMerge.run(;
merge_new_packages=true,
merge_new_versions=true,
new_package_waiting_period=Minute(0),
new_jll_package_waiting_period=Minute(0),
new_version_waiting_period=Minute(0),
new_jll_version_waiting_period=Minute(0),
registry=AUTOMERGE_INTEGRATION_TEST_REPO,
authorized_authors=String[whoami],
authorized_authors_special_jll_exceptions=String[whoami],
error_exit_if_automerge_not_applicable=true,
master_branch=master,
master_branch_is_default_branch=false,
)
end
end
end
end
end
end
| RegistryCI | https://github.com/JuliaRegistries/RegistryCI.jl.git |
|
[
"MIT"
] | 10.7.0 | f0341c8179a869629d90fe549511d6ffaf1da9a1 | code | 36672 | using Dates
# using GitCommand
using GitHub
using JSON
using Pkg
using Printf
using RegistryCI
using Test
using TimeZones
const AutoMerge = RegistryCI.AutoMerge
TEMP_DEPOT_FOR_TESTING = nothing
function setup_global_depot()::String
global TEMP_DEPOT_FOR_TESTING
if TEMP_DEPOT_FOR_TESTING isa String
return TEMP_DEPOT_FOR_TESTING
end
tmp_depot = mktempdir()
env1 = copy(ENV)
env1["JULIA_DEPOT_PATH"] = tmp_depot
delete!(env1, "JULIA_LOAD_PATH")
delete!(env1, "JULIA_PROJECT")
env2 = copy(env1)
env2["JULIA_PKG_SERVER"] = ""
run(setenv(`julia -e 'import Pkg; Pkg.Registry.add("General")'`, env2))
run(setenv(`julia -e 'import Pkg; Pkg.add(["RegistryCI"])'`, env1))
TEMP_DEPOT_FOR_TESTING = tmp_depot
tmp_depot
end
# helper for testing `AutoMerge.meets_version_has_osi_license`
function pkgdir_from_depot(depot_path::String, pkg::String)
pkgdir_parent = joinpath(depot_path, "packages", pkg)
isdir(pkgdir_parent) || return nothing
all_pkgdir_elements = readdir(pkgdir_parent)
@info "" pkgdir_parent all_pkgdir_elements
(length(all_pkgdir_elements) == 1) || return nothing
only_pkgdir_element = all_pkgdir_elements[1]
only_pkdir = joinpath(pkgdir_parent, only_pkgdir_element)
isdir(only_pkdir) || return nothing
return only_pkdir
end
strip_equal(x, y) = strip(x) == strip(y)
# Here we reference test all the permutations of the AutoMerge comments.
# This allows us to see the diffs in PRs that change the AutoMerge comment.
function comment_reference_test()
for pass in (true, false),
(type_name,type) in (("new_version", AutoMerge.NewVersion()), ("new_package", AutoMerge.NewPackage())),
suggest_onepointzero in (true, false),
# some code depends on above or below v"1"
version in (v"0.1", v"1")
if pass
for is_jll in (true, false)
name = string("comment", "_pass_", pass, "_type_", type_name,
"_suggest_onepointzero_", suggest_onepointzero,
"_version_", version, "_is_jll_", is_jll)
@test_reference "reference_comments/$name.md" AutoMerge.comment_text_pass(type, suggest_onepointzero, version, is_jll, new_package_waiting_period=Day(3)) by=strip_equal
end
else
for point_to_slack in (true, false)
name = string("comment", "_pass_", pass, "_type_", type_name,
"_suggest_onepointzero_", suggest_onepointzero,
"_version_", version, "_point_to_slack_", point_to_slack)
reasons = [
AutoMerge.compat_violation_message(["julia"]),
"Example guideline failed. Please fix it."]
fail_text = AutoMerge.comment_text_fail(type, reasons, suggest_onepointzero, version; point_to_slack=point_to_slack)
@test_reference "reference_comments/$name.md" fail_text by=strip_equal
# `point_to_slack=false` should yield no references to Slack in the text
if !point_to_slack
@test !occursin("slack", fail_text)
end
end
end
end
end
@testset "Utilities" begin
@testset "comment_reference_test" begin
comment_reference_test()
end
@testset "Customized `new_package_waiting_period` in AutoMerge comment " begin
text = AutoMerge.comment_text_pass(AutoMerge.NewPackage(), false, v"1", false; new_package_waiting_period=Minute(45))
@test occursin("(45 minutes)", text)
end
@testset "`AutoMerge.parse_registry_pkg_info`" begin
registry_path = joinpath(DEPOT_PATH[1], "registries", "General")
result = AutoMerge.parse_registry_pkg_info(registry_path, "RegistryCI", "1.0.0")
@test result == (;
uuid="0c95cc5f-2f7e-43fe-82dd-79dbcba86b32",
repo="https://github.com/JuliaRegistries/RegistryCI.jl.git",
subdir="",
tree_hash="1036c9c4d600468785fbd9dae87587e59d2f66a9",
)
result = AutoMerge.parse_registry_pkg_info(registry_path, "RegistryCI")
@test result == (;
uuid="0c95cc5f-2f7e-43fe-82dd-79dbcba86b32",
repo="https://github.com/JuliaRegistries/RegistryCI.jl.git",
subdir="",
tree_hash=nothing,
)
result = AutoMerge.parse_registry_pkg_info(
registry_path, "SnoopCompileCore", "2.5.2"
)
@test result == (;
uuid="e2b509da-e806-4183-be48-004708413034",
repo="https://github.com/timholy/SnoopCompile.jl.git",
subdir="SnoopCompileCore",
tree_hash="bb6d6df44d9aa3494c997aebdee85b713b92c0de",
)
end
end
@testset "Guidelines for new packages" begin
@testset "Package name is a valid identifier" begin
@test AutoMerge.meets_name_is_identifier("Hello")[1]
@test !AutoMerge.meets_name_is_identifier("Hello-GoodBye")[1]
end
@testset "Normal capitalization" begin
@test AutoMerge.meets_normal_capitalization("Zygote")[1] # Regular name
@test AutoMerge.meets_normal_capitalization("Zygote")[1]
@test !AutoMerge.meets_normal_capitalization("HTTP")[1] # All upper-case
@test !AutoMerge.meets_normal_capitalization("HTTP")[1]
@test AutoMerge.meets_normal_capitalization("ForwardDiff2")[1] # Ends with a number
@test AutoMerge.meets_normal_capitalization("ForwardDiff2")[1]
@test !AutoMerge.meets_normal_capitalization("JSON2")[1] # All upper-case and ends with number
@test !AutoMerge.meets_normal_capitalization("JSON2")[1]
@test AutoMerge.meets_normal_capitalization("RegistryCI")[1] # Ends with upper-case
@test AutoMerge.meets_normal_capitalization("RegistryCI")[1]
end
@testset "Not too short - at least five letters" begin
@test AutoMerge.meets_name_length("Zygote")[1]
@test AutoMerge.meets_name_length("Zygote")[1]
@test !AutoMerge.meets_name_length("Flux")[1]
@test !AutoMerge.meets_name_length("Flux")[1]
end
@testset "Name does not include \"julia\", start with \"Ju\", or end with \"jl\"" begin
@test AutoMerge.meets_julia_name_check("Zygote")[1]
@test AutoMerge.meets_julia_name_check("RegistryCI")[1]
@test !AutoMerge.meets_julia_name_check("JuRegistryCI")[1]
@test !AutoMerge.meets_julia_name_check("ZygoteJulia")[1]
@test !AutoMerge.meets_julia_name_check("Zygotejulia")[1]
@test !AutoMerge.meets_julia_name_check("Sortingjl")[1]
@test !AutoMerge.meets_julia_name_check("BananasJL")[1]
@test !AutoMerge.meets_julia_name_check("AbcJuLiA")[1]
end
@testset "Package name is ASCII" begin
@test !AutoMerge.meets_name_ascii("ábc")[1]
@test AutoMerge.meets_name_ascii("abc")[1]
end
@testset "Package name match check" begin
@test AutoMerge.meets_name_match_check("Flux", ["Abc", "Def"])[1]
@test !AutoMerge.meets_name_match_check("Websocket", ["websocket"])[1]
end
@testset "Package name distance" begin
@test AutoMerge.meets_distance_check("Flux", ["Abc", "Def"])[1]
@test !AutoMerge.meets_distance_check("Flux", ["FIux", "Abc", "Def"])[1]
@test !AutoMerge.meets_distance_check("Websocket", ["WebSockets"])[1]
@test !AutoMerge.meets_distance_check("ThreabTooIs", ["ThreadTools"])[1]
@test !AutoMerge.meets_distance_check("JiII", ["Jill"])[1]
@test !AutoMerge.meets_distance_check(
"FooBar",
["FOO8ar"];
DL_cutoff=0,
sqrt_normalized_vd_cutoff=0,
DL_lowercase_cutoff=1,
)[1]
@test !AutoMerge.meets_distance_check(
"ReallyLooooongNameCD", ["ReallyLooooongNameAB"]
)[1]
end
@testset "perform_distance_check" begin
@test AutoMerge.perform_distance_check(nothing)
@test AutoMerge.perform_distance_check([GitHub.Label(; name="hi")])
@test !AutoMerge.perform_distance_check([GitHub.Label(; name="Override AutoMerge: name similarity is okay")])
@test !AutoMerge.perform_distance_check([GitHub.Label(; name="hi"), GitHub.Label(; name="Override AutoMerge: name similarity is okay")])
end
@testset "has_author_approved_label" begin
@test !AutoMerge.has_package_author_approved_label(nothing)
@test !AutoMerge.has_package_author_approved_label([GitHub.Label(; name="hi")])
@test AutoMerge.has_package_author_approved_label([GitHub.Label(; name="Override AutoMerge: package author approved")])
@test AutoMerge.has_package_author_approved_label([GitHub.Label(; name="hi"), GitHub.Label(; name="Override AutoMerge: package author approved")])
end
@testset "pr_comment_is_blocking" begin
@test AutoMerge.pr_comment_is_blocking(GitHub.Comment(; body="hi"))
@test AutoMerge.pr_comment_is_blocking(GitHub.Comment(; body="block"))
@test !AutoMerge.pr_comment_is_blocking(GitHub.Comment(; body="[noblock]"))
@test !AutoMerge.pr_comment_is_blocking(GitHub.Comment(; body="[noblock]hi"))
@test !AutoMerge.pr_comment_is_blocking(GitHub.Comment(; body="[merge approved] abc"))
end
@testset "`get_all_non_jll_package_names`" begin
registry_path = joinpath(DEPOT_PATH[1], "registries", "General")
packages = AutoMerge.get_all_non_jll_package_names(registry_path)
@test "RegistryCI" ∈ packages
@test "Logging" ∈ packages
@test "Poppler_jll" ∉ packages
end
@testset "Standard initial version number" begin
@test AutoMerge.meets_standard_initial_version_number(v"0.0.1")[1]
@test AutoMerge.meets_standard_initial_version_number(v"0.1.0")[1]
@test AutoMerge.meets_standard_initial_version_number(v"1.0.0")[1]
@test !AutoMerge.meets_standard_initial_version_number(v"0.0.2")[1]
@test !AutoMerge.meets_standard_initial_version_number(v"0.1.1")[1]
@test !AutoMerge.meets_standard_initial_version_number(v"0.2.0")[1]
@test !AutoMerge.meets_standard_initial_version_number(v"1.0.1")[1]
@test !AutoMerge.meets_standard_initial_version_number(v"1.1.0")[1]
@test !AutoMerge.meets_standard_initial_version_number(v"1.1.1")[1]
@test AutoMerge.meets_standard_initial_version_number(v"2.0.0")[1]
@test !AutoMerge.meets_standard_initial_version_number(v"2.0.1")[1]
@test !AutoMerge.meets_standard_initial_version_number(v"2.1.0")[1]
@test !AutoMerge.meets_standard_initial_version_number(v"2.1.1")[1]
@test AutoMerge.meets_standard_initial_version_number(v"3.0.0")[1]
@test !AutoMerge.meets_standard_initial_version_number(v"3.0.1")[1]
@test !AutoMerge.meets_standard_initial_version_number(v"3.1.0")[1]
end
@testset "Repo URL ends with /name.jl.git where name is the package name" begin
@test AutoMerge.url_has_correct_ending(
"https://github.com/FluxML/Flux.jl.git", "Flux"
)[1]
@test !AutoMerge.url_has_correct_ending(
"https://github.com/FluxML/Flux.jl", "Flux"
)[1]
@test !AutoMerge.url_has_correct_ending(
"https://github.com/FluxML/Zygote.jl.git", "Flux"
)[1]
@test !AutoMerge.url_has_correct_ending(
"https://github.com/FluxML/Zygote.jl", "Flux"
)[1]
end
end
@testset "Guidelines for new versions" begin
@testset "Sequential version number" begin
@test AutoMerge.meets_sequential_version_number([v"0.0.1"], v"0.0.2")[1]
@test AutoMerge.meets_sequential_version_number([v"0.1.0"], v"0.1.1")[1]
@test AutoMerge.meets_sequential_version_number([v"0.1.0"], v"0.2.0")[1]
@test AutoMerge.meets_sequential_version_number([v"1.0.0"], v"1.0.1")[1]
@test AutoMerge.meets_sequential_version_number([v"1.0.0"], v"1.1.0")[1]
@test AutoMerge.meets_sequential_version_number([v"1.0.0"], v"2.0.0")[1]
@test !AutoMerge.meets_sequential_version_number([v"0.0.1"], v"0.0.3")[1]
@test !AutoMerge.meets_sequential_version_number([v"0.1.0"], v"0.3.0")[1]
@test !AutoMerge.meets_sequential_version_number([v"1.0.0"], v"1.0.2")[1]
@test !AutoMerge.meets_sequential_version_number([v"1.0.0"], v"1.2.0")[1]
@test !AutoMerge.meets_sequential_version_number([v"1.0.0"], v"3.0.0")[1]
@test AutoMerge.meets_sequential_version_number([v"0.1.1"], v"0.2.0")[1]
@test AutoMerge.meets_sequential_version_number([v"0.1.2"], v"0.2.0")[1]
@test AutoMerge.meets_sequential_version_number([v"0.1.3"], v"0.2.0")[1]
@test AutoMerge.meets_sequential_version_number([v"1.0.1"], v"1.1.0")[1]
@test AutoMerge.meets_sequential_version_number([v"1.0.2"], v"1.1.0")[1]
@test AutoMerge.meets_sequential_version_number([v"1.0.3"], v"1.1.0")[1]
@test !AutoMerge.meets_sequential_version_number([v"0.1.1"], v"0.2.1")[1]
@test !AutoMerge.meets_sequential_version_number([v"0.1.2"], v"0.2.2")[1]
@test !AutoMerge.meets_sequential_version_number([v"1.0.1"], v"1.1.1")[1]
@test !AutoMerge.meets_sequential_version_number([v"1.0.3"], v"1.2.0")[1]
@test !AutoMerge.meets_sequential_version_number([v"1.0.3"], v"1.2.1")[1]
@test !AutoMerge.meets_sequential_version_number([v"1.0.3"], v"1.1.1")[1]
@test !AutoMerge.meets_sequential_version_number([v"1.0.0"], v"2.0.1")[1]
@test !AutoMerge.meets_sequential_version_number([v"1.0.0"], v"2.1.0")[1]
@test !AutoMerge.meets_sequential_version_number([v"1.0.0"], v"2.1.0")[1]
@test AutoMerge.meets_sequential_version_number([v"0.0.1"], v"0.0.2")[1]
@test AutoMerge.meets_sequential_version_number([v"0.0.1"], v"0.1.0")[1]
@test AutoMerge.meets_sequential_version_number([v"0.0.1"], v"1.0.0")[1]
@test AutoMerge.meets_sequential_version_number([v"0.0.1", v"0.1.0"], v"0.0.2")[1] # issue #49
@test AutoMerge.meets_sequential_version_number([v"0.0.1", v"0.1.0"], v"0.1.1")[1]
@test AutoMerge.meets_sequential_version_number([v"0.0.1", v"0.1.0"], v"0.2.0")[1]
@test AutoMerge.meets_sequential_version_number([v"0.0.1", v"0.1.0"], v"1.0.0")[1]
@test AutoMerge.meets_sequential_version_number(
[v"0.0.1", v"0.1.0", v"1.0.0"], v"0.0.2"
)[1] # issue #49
@test AutoMerge.meets_sequential_version_number(
[v"0.0.1", v"0.1.0", v"1.0.0"], v"0.1.1"
)[1] # issue #49
@test AutoMerge.meets_sequential_version_number(
[v"0.0.1", v"0.1.0", v"1.0.0"], v"0.2.0"
)[1]
@test AutoMerge.meets_sequential_version_number(
[v"0.0.1", v"0.1.0", v"1.0.0"], v"1.0.1"
)[1]
@test AutoMerge.meets_sequential_version_number(
[v"0.0.1", v"0.1.0", v"1.0.0"], v"1.1.0"
)[1]
@test AutoMerge.meets_sequential_version_number(
[v"0.0.1", v"0.1.0", v"1.0.0"], v"2.0.0"
)[1]
@test AutoMerge.meets_sequential_version_number([v"1", v"2"], v"3")[1]
@test AutoMerge.meets_sequential_version_number([v"2", v"1"], v"3")[1]
@test !AutoMerge.meets_sequential_version_number([v"1", v"2"], v"2")[1]
@test !AutoMerge.meets_sequential_version_number([v"1", v"2", v"3"], v"2")[1]
@test !AutoMerge.meets_sequential_version_number([v"1", v"2"], v"4")[1]
@test !AutoMerge.meets_sequential_version_number([v"1", v"2"], v"0")[1]
@test !AutoMerge.meets_sequential_version_number([v"1", v"2"], v"0.9")[1]
@test AutoMerge.meets_sequential_version_number([v"1", v"2"], v"2.0.1")[1]
@test AutoMerge.meets_sequential_version_number([v"1", v"2"], v"2.1")[1]
@test AutoMerge.meets_sequential_version_number([v"1", v"2"], v"3")[1]
let vers = [v"2", v"1"]
@test AutoMerge.meets_sequential_version_number(vers, v"3")[1]
@test vers == [v"2", v"1"] # no mutation
end
end
@testset "Patch releases cannot narrow Julia compat" begin
r1 = Pkg.Types.VersionRange("1.3-1.7")
r2 = Pkg.Types.VersionRange("1.4-1.7")
r3 = Pkg.Types.VersionRange("1.3-1.6")
@test AutoMerge.range_did_not_narrow(r1, r1)[1]
@test AutoMerge.range_did_not_narrow(r2, r2)[1]
@test AutoMerge.range_did_not_narrow(r3, r3)[1]
@test AutoMerge.range_did_not_narrow(r2, r1)[1]
@test AutoMerge.range_did_not_narrow(r3, r1)[1]
@test !AutoMerge.range_did_not_narrow(r1, r2)[1]
@test !AutoMerge.range_did_not_narrow(r1, r3)[1]
@test !AutoMerge.range_did_not_narrow(r2, r3)[1]
@test !AutoMerge.range_did_not_narrow(r3, r2)[1]
end
end
@testset "Guidelines for both new packages and new versions" begin
@testset "Version numbers may not contain prerelease data" begin
@test AutoMerge.meets_version_number_no_prerelease(v"1.2.3")[1]
@test !AutoMerge.meets_version_number_no_prerelease(v"1.2.3-alpha")[1]
@test AutoMerge.meets_version_number_no_prerelease(v"1.2.3+456")[1]
@test !AutoMerge.meets_version_number_no_prerelease(v"1.2.3-alpha+456")[1]
end
@testset "Version numbers may not contain build data" begin
@test AutoMerge.meets_version_number_no_build(v"1.2.3")[1]
@test AutoMerge.meets_version_number_no_build(v"1.2.3-alpha")[1]
@test !AutoMerge.meets_version_number_no_build(v"1.2.3+456")[1]
@test !AutoMerge.meets_version_number_no_build(v"1.2.3-alpha+456")[1]
end
end
@testset "Unit tests" begin
@testset "assert.jl" begin
@test nothing == @test_nowarn AutoMerge.always_assert(1 == 1)
@test_throws AutoMerge.AlwaysAssertionError AutoMerge.always_assert(1 == 2)
end
@testset "_find_lowercase_duplicates" begin
@test AutoMerge._find_lowercase_duplicates(("a", "b", "A")) == ("a", "A")
@test AutoMerge._find_lowercase_duplicates(("ab", "bb", "aB")) == ("ab", "aB")
@test AutoMerge._find_lowercase_duplicates(["ab", "bc"]) === nothing
@test AutoMerge._find_lowercase_duplicates(("ab", "bb", "aB", "AB")) == ("ab", "aB")
end
@testset "meets_file_dir_name_check" begin
@test AutoMerge.meets_file_dir_name_check("hi")[1]
@test AutoMerge.meets_file_dir_name_check("hi bye")[1]
@test AutoMerge.meets_file_dir_name_check("hi.txt")[1]
@test AutoMerge.meets_file_dir_name_check("hi.con")[1]
@test !AutoMerge.meets_file_dir_name_check("con")[1]
@test !AutoMerge.meets_file_dir_name_check("lpt5")[1]
@test !AutoMerge.meets_file_dir_name_check("hi.")[1]
@test !AutoMerge.meets_file_dir_name_check("hi.txt.")[1]
@test !AutoMerge.meets_file_dir_name_check("hi ")[1]
@test !AutoMerge.meets_file_dir_name_check("hi:")[1]
@test !AutoMerge.meets_file_dir_name_check("hi:bye")[1]
@test !AutoMerge.meets_file_dir_name_check("hi?bye")[1]
@test !AutoMerge.meets_file_dir_name_check("hi>bye")[1]
end
@testset "meets_src_names_ok: duplicates" begin
@test !AutoMerge.meets_src_names_ok("DOES NOT EXIST")[1]
tmp = mktempdir()
@test !AutoMerge.meets_src_names_ok(tmp)[1]
mkdir(joinpath(tmp, "src"))
@test AutoMerge.meets_src_names_ok(tmp)[1]
touch(joinpath(tmp, "src", "a"))
@test AutoMerge.meets_src_names_ok(tmp)[1]
if !isdir(joinpath(tmp, "SRC"))
mkdir(joinpath(tmp, "src", "A"))
# dir vs file fails
@test !AutoMerge.meets_src_names_ok(tmp)[1]
rm(joinpath(tmp, "src", "a"))
@test AutoMerge.meets_src_names_ok(tmp)[1]
touch(joinpath(tmp, "src", "A", "b"))
@test AutoMerge.meets_src_names_ok(tmp)[1]
touch(joinpath(tmp, "src", "b"))
# repetition at different levels is OK
@test AutoMerge.meets_src_names_ok(tmp)[1]
touch(joinpath(tmp, "src", "A", "B"))
# repetition at the same level is not OK
@test !AutoMerge.meets_src_names_ok(tmp)[1]
else
@warn "Case insensitive filesystem detected, so skipping some `meets_src_files_distinct` checks."
end
end
@testset "meets_src_names_ok: names" begin
tmp = mktempdir()
mkdir(joinpath(tmp, "src"))
@test AutoMerge.meets_src_names_ok(tmp)[1]
mkdir(joinpath(tmp, "src", "B"))
@test AutoMerge.meets_src_names_ok(tmp)[1]
touch(joinpath(tmp, "src", "B", "con"))
@test !AutoMerge.meets_src_names_ok(tmp)[1]
end
@testset "pull-requests.jl" begin
@testset "regexes" begin
@testset "new_package_title_regex" begin
@test occursin(
AutoMerge.new_package_title_regex, "New package: HelloWorld v1.2.3"
)
# This one is not a valid package name, but nonetheless we want AutoMerge
# to run and fail.
@test occursin(
AutoMerge.new_package_title_regex, "New package: Mathieu-Functions v1.0.0"
)
@test occursin(
AutoMerge.new_package_title_regex, "New package: HelloWorld v1.2.3+0"
)
@test !occursin(
AutoMerge.new_package_title_regex, "New version: HelloWorld v1.2.3"
)
@test !occursin(
AutoMerge.new_package_title_regex, "New version: HelloWorld v1.2.3+0"
)
let
m = match(
AutoMerge.new_package_title_regex,
"New package: HelloWorld v1.2.3+0",
)
@test length(m.captures) == 2
@test m.captures[1] == "HelloWorld"
@test m.captures[2] == "1.2.3+0"
end
end
@testset "new_version_title_regex" begin
@test !occursin(
AutoMerge.new_version_title_regex, "New package: HelloWorld v1.2.3"
)
@test !occursin(
AutoMerge.new_version_title_regex, "New package: HelloWorld v1.2.3+0"
)
@test occursin(
AutoMerge.new_version_title_regex, "New version: HelloWorld v1.2.3"
)
@test occursin(
AutoMerge.new_version_title_regex, "New version: HelloWorld v1.2.3+0"
)
let
m = match(
AutoMerge.new_version_title_regex,
"New version: HelloWorld v1.2.3+0",
)
@test length(m.captures) == 2
@test m.captures[1] == "HelloWorld"
@test m.captures[2] == "1.2.3+0"
end
end
@testset "commit_regex" begin
commit_hash = "012345678901234567890123456789abcdef0000"
@test occursin(AutoMerge.commit_regex, "- Foo\n- Commit: $(commit_hash)\n- Bar")
@test occursin(AutoMerge.commit_regex, "- Commit: $(commit_hash)\n- Bar")
@test occursin(AutoMerge.commit_regex, "- Foo\n- Commit: $(commit_hash)")
@test occursin(AutoMerge.commit_regex, "- Commit: $(commit_hash)")
@test occursin(AutoMerge.commit_regex, "Commit: $(commit_hash)")
@test occursin(AutoMerge.commit_regex, "* Foo\n* Commit: $(commit_hash)\n* Bar")
@test occursin(AutoMerge.commit_regex, "* Commit: $(commit_hash)\n* Bar")
@test occursin(AutoMerge.commit_regex, "* Foo\n* Commit: $(commit_hash)")
@test occursin(AutoMerge.commit_regex, "* Commit: $(commit_hash)")
@test !occursin(AutoMerge.commit_regex, "- Commit: mycommit hash 123")
let
m = match(
AutoMerge.commit_regex, "- Foo\n- Commit: $(commit_hash)\n- Bar"
)
@test length(m.captures) == 1
@test m.captures[1] == "$(commit_hash)"
end
end
end
end
@testset "semver.jl" begin
@test AutoMerge.leftmost_nonzero(v"1.2.3") == :major
@test AutoMerge.leftmost_nonzero(v"0.2.3") == :minor
@test AutoMerge.leftmost_nonzero(v"0.0.3") == :patch
@test_throws ArgumentError AutoMerge.leftmost_nonzero(v"0")
@test_throws ArgumentError AutoMerge.leftmost_nonzero(v"0.0")
@test_throws ArgumentError AutoMerge.leftmost_nonzero(v"0.0.0")
@test_throws ArgumentError AutoMerge.is_breaking(v"1.2.3", v"1.2.0")
@test_throws ArgumentError AutoMerge.is_breaking(v"1.2.3", v"1.2.2")
@test_throws ArgumentError AutoMerge.is_breaking(v"1.2.3", v"1.2.3")
@test !AutoMerge.is_breaking(v"1.2.3", v"1.2.4")
@test !AutoMerge.is_breaking(v"1.2.3", v"1.2.5")
@test !AutoMerge.is_breaking(v"1.2.3", v"1.3.0")
@test !AutoMerge.is_breaking(v"1.2.3", v"1.4.0")
@test AutoMerge.is_breaking(v"1.2.3", v"2.0.0")
@test AutoMerge.is_breaking(v"1.2.3", v"2.1.0")
@test AutoMerge.is_breaking(v"1.2.3", v"2.2.0")
@test AutoMerge.is_breaking(v"1.2.3", v"3.0.0")
@test AutoMerge.is_breaking(v"1.2.3", v"3.1.0")
@test AutoMerge.is_breaking(v"1.2.3", v"3.2.0")
@test !AutoMerge.is_breaking(v"0.2.3", v"0.2.4")
@test !AutoMerge.is_breaking(v"0.2.3", v"0.2.5")
@test AutoMerge.is_breaking(v"0.2.3", v"0.3.0")
@test AutoMerge.is_breaking(v"0.2.3", v"0.4.0")
@test AutoMerge.is_breaking(v"0.2.3", v"1.0.0")
@test AutoMerge.is_breaking(v"0.2.3", v"1.1.0")
@test AutoMerge.is_breaking(v"0.2.3", v"1.2.0")
@test AutoMerge.is_breaking(v"0.2.3", v"2.0.0")
@test AutoMerge.is_breaking(v"0.2.3", v"2.1.0")
@test AutoMerge.is_breaking(v"0.2.3", v"2.2.0")
@test AutoMerge.is_breaking(v"0.0.3", v"0.0.4")
@test AutoMerge.is_breaking(v"0.0.3", v"0.0.5")
@test AutoMerge.is_breaking(v"0.0.3", v"0.1.0")
@test AutoMerge.is_breaking(v"0.0.3", v"0.2.0")
@test AutoMerge.is_breaking(v"0.0.3", v"1.0.0")
@test AutoMerge.is_breaking(v"0.0.3", v"1.1.0")
@test AutoMerge.is_breaking(v"0.0.3", v"1.2.0")
@test AutoMerge.is_breaking(v"0.0.3", v"2.0.0")
@test AutoMerge.is_breaking(v"0.0.3", v"2.1.0")
@test AutoMerge.is_breaking(v"0.0.3", v"2.2.0")
@test AutoMerge.thispatch(v"1.2.3") == v"1.2.3"
@test AutoMerge.thisminor(v"1.2.3") == v"1.2"
@test AutoMerge.thismajor(v"1.2.3") == v"1"
@test AutoMerge.nextpatch(v"1.2.3") == v"1.2.4"
@test AutoMerge.nextminor(v"1.2") == v"1.3"
@test AutoMerge.nextminor(v"1.2.3") == v"1.3"
@test AutoMerge.nextmajor(v"1") == v"2"
@test AutoMerge.nextmajor(v"1.2") == v"2"
@test AutoMerge.nextmajor(v"1.2.3") == v"2"
@test AutoMerge.difference(v"1", v"2") == v"1"
@test AutoMerge.difference(v"1", v"1") isa AutoMerge.ErrorCannotComputeVersionDifference
@test AutoMerge.difference(v"2", v"1") isa AutoMerge.ErrorCannotComputeVersionDifference
@test !AutoMerge._has_upper_bound(Pkg.Types.VersionRange("0"))
@test AutoMerge._has_upper_bound(Pkg.Types.VersionRange("1"))
@test !AutoMerge._has_upper_bound(Pkg.Types.VersionRange("*"))
@test !AutoMerge._has_upper_bound(Pkg.Types.VersionRange("0-1"))
@test AutoMerge._has_upper_bound(Pkg.Types.VersionRange("1-2"))
@test !AutoMerge._has_upper_bound(Pkg.Types.VersionRange("1-*"))
@test !AutoMerge._has_upper_bound(Pkg.Types.VersionRange("0-0"))
@test !AutoMerge._has_upper_bound(Pkg.Types.VersionRange("0-*"))
@test !AutoMerge._has_upper_bound(Pkg.Types.VersionRange("0.2-0"))
@test !AutoMerge._has_upper_bound(Pkg.Types.VersionRange("0.2-*"))
if Base.VERSION >= v"1.4-"
# We skip this test on Julia 1.3, because it requires `Base.only`.
@testset "julia_compat" begin
registry_path = registry_path = joinpath(DEPOT_PATH[1], "registries", "General")
@test AutoMerge.julia_compat("Example", v"0.5.3", registry_path) isa AbstractVector{<:Pkg.Types.VersionRange}
end
end
end
end
@testset "CIService unit testing" begin
@testset "Travis CI" begin
# pull request build
withenv(
"TRAVIS_BRANCH" => "master",
"TRAVIS_EVENT_TYPE" => "pull_request",
"TRAVIS_PULL_REQUEST" => "42",
"TRAVIS_PULL_REQUEST_SHA" => "abc123",
"TRAVIS_BUILD_DIR" => "/tmp/clone",
) do
cfg = AutoMerge.TravisCI()
@test AutoMerge.conditions_met_for_pr_build(cfg; master_branch="master")
@test !AutoMerge.conditions_met_for_pr_build(cfg; master_branch="retsam")
@test !AutoMerge.conditions_met_for_merge_build(cfg; master_branch="master")
@test AutoMerge.pull_request_number(cfg) == 42
@test AutoMerge.current_pr_head_commit_sha(cfg) == "abc123"
@test AutoMerge.directory_of_cloned_registry(cfg) == "/tmp/clone"
end
# merge build with cron
withenv(
"TRAVIS_BRANCH" => "master",
"TRAVIS_EVENT_TYPE" => "cron",
"TRAVIS_PULL_REQUEST" => "false",
"TRAVIS_PULL_REQUEST_SHA" => "abc123",
"TRAVIS_BUILD_DIR" => "/tmp/clone",
) do
cfg = AutoMerge.TravisCI()
@test !AutoMerge.conditions_met_for_pr_build(cfg; master_branch="master")
@test AutoMerge.conditions_met_for_merge_build(cfg; master_branch="master")
@test !AutoMerge.conditions_met_for_merge_build(cfg; master_branch="retsam")
@test !AutoMerge.conditions_met_for_merge_build(
AutoMerge.TravisCI(; enable_cron_builds=false); master_branch="master"
)
@test AutoMerge.current_pr_head_commit_sha(cfg) == "abc123"
@test AutoMerge.directory_of_cloned_registry(cfg) == "/tmp/clone"
end
# merge build with api
withenv(
"TRAVIS_BRANCH" => "master",
"TRAVIS_EVENT_TYPE" => "api",
"TRAVIS_PULL_REQUEST" => "false",
"TRAVIS_PULL_REQUEST_SHA" => "abc123",
"TRAVIS_BUILD_DIR" => "/tmp/clone",
) do
cfg = AutoMerge.TravisCI()
@test !AutoMerge.conditions_met_for_pr_build(cfg; master_branch="master")
@test AutoMerge.conditions_met_for_merge_build(cfg; master_branch="master")
@test !AutoMerge.conditions_met_for_merge_build(cfg; master_branch="retsam")
@test !AutoMerge.conditions_met_for_merge_build(
AutoMerge.TravisCI(; enable_api_builds=false); master_branch="master"
)
@test AutoMerge.current_pr_head_commit_sha(cfg) == "abc123"
@test AutoMerge.directory_of_cloned_registry(cfg) == "/tmp/clone"
end
# neither pull request nor merge build
withenv("TRAVIS_BRANCH" => nothing, "TRAVIS_EVENT_TYPE" => nothing) do
cfg = AutoMerge.TravisCI()
@test !AutoMerge.conditions_met_for_pr_build(cfg; master_branch="master")
@test !AutoMerge.conditions_met_for_merge_build(cfg; master_branch="master")
end
end
@testset "GitHub Actions" begin
mktemp() do file, io
# mimic the workflow file for GitHub Actions
workflow = Dict("pull_request" => Dict("head" => Dict("sha" => "abc123")))
JSON.print(io, workflow)
close(io)
# pull request build
withenv(
"GITHUB_REF" => "refs/pull/42/merge",
"GITHUB_EVENT_NAME" => "pull_request",
"GITHUB_SHA" => "123abc", # "wrong", should be taken from workflow file
"GITHUB_EVENT_PATH" => file,
"GITHUB_WORKSPACE" => "/tmp/clone",
) do
cfg = AutoMerge.GitHubActions()
@test AutoMerge.conditions_met_for_pr_build(cfg; master_branch="master")
@test_broken !AutoMerge.conditions_met_for_pr_build(
cfg; master_branch="retsam"
)
@test !AutoMerge.conditions_met_for_merge_build(cfg; master_branch="master")
@test AutoMerge.pull_request_number(cfg) == 42
@test AutoMerge.current_pr_head_commit_sha(cfg) == "abc123"
@test AutoMerge.directory_of_cloned_registry(cfg) == "/tmp/clone"
end
# merge build with schedule: cron
withenv(
"GITHUB_REF" => "refs/heads/master",
"GITHUB_EVENT_NAME" => "schedule",
"GITHUB_SHA" => "123abc",
"GITHUB_WORKSPACE" => "/tmp/clone",
) do
cfg = AutoMerge.GitHubActions()
@test !AutoMerge.conditions_met_for_pr_build(cfg; master_branch="master")
@test AutoMerge.conditions_met_for_merge_build(cfg; master_branch="master")
@test !AutoMerge.conditions_met_for_merge_build(cfg; master_branch="retsam")
@test !AutoMerge.conditions_met_for_merge_build(
AutoMerge.GitHubActions(; enable_cron_builds=false);
master_branch="master",
)
@test AutoMerge.directory_of_cloned_registry(cfg) == "/tmp/clone"
end
# neither pull request nor merge build
withenv("GITHUB_REF" => nothing, "GITHUB_EVENT_NAME" => nothing) do
cfg = AutoMerge.GitHubActions()
@test !AutoMerge.conditions_met_for_pr_build(cfg; master_branch="master")
@test !AutoMerge.conditions_met_for_merge_build(cfg; master_branch="master")
end
end
end
@testset "auto detection" begin
withenv(
"TRAVIS_REPO_SLUG" => "JuliaRegistries/General", "GITHUB_REPOSITORY" => nothing
) do
@test AutoMerge.auto_detect_ci_service() == AutoMerge.TravisCI()
@test AutoMerge.auto_detect_ci_service(; env=ENV) == AutoMerge.TravisCI()
end
withenv(
"TRAVIS_REPO_SLUG" => nothing, "GITHUB_REPOSITORY" => "JuliaRegistries/General"
) do
@test AutoMerge.auto_detect_ci_service() == AutoMerge.GitHubActions()
@test AutoMerge.auto_detect_ci_service(; env=ENV) == AutoMerge.GitHubActions()
end
end
@testset "`AutoMerge.meets_version_has_osi_license`" begin
withenv("JULIA_PKG_PRECOMPILE_AUTO" => "0") do
# Let's install a fresh depot in a temporary directory
# and add some packages to inspect.
tmp_depot = setup_global_depot()
function has_osi_license_in_depot(pkg)
return AutoMerge.meets_version_has_osi_license(
pkg; pkg_code_path=pkgdir_from_depot(tmp_depot, pkg)
)
end
# Let's test ourselves and some of our dependencies that just have MIT licenses:
result = has_osi_license_in_depot("RegistryCI")
@test result[1]
result = has_osi_license_in_depot("UnbalancedOptimalTransport")
@test result[1]
result = has_osi_license_in_depot("VisualStringDistances")
@test result[1]
# Now, what happens if there's also a non-OSI license in another file?
pkg_path = pkgdir_from_depot(tmp_depot, "UnbalancedOptimalTransport")
open(joinpath(pkg_path, "LICENSE2"); write=true) do io
cc0_bytes = read(joinpath(@__DIR__, "license_data", "CC0.txt"))
println(io)
write(io, cc0_bytes)
end
result = has_osi_license_in_depot("UnbalancedOptimalTransport")
@test result[1]
# What if we also remove the original license, leaving only the CC0 license?
rm(joinpath(pkg_path, "LICENSE"))
result = has_osi_license_in_depot("UnbalancedOptimalTransport")
@test !result[1]
# What about no license at all?
pkg_path = pkgdir_from_depot(tmp_depot, "VisualStringDistances")
rm(joinpath(pkg_path, "LICENSE"))
result = has_osi_license_in_depot("VisualStringDistances")
@test !result[1]
end
end
end
| RegistryCI | https://github.com/JuliaRegistries/RegistryCI.jl.git |
|
[
"MIT"
] | 10.7.0 | f0341c8179a869629d90fe549511d6ffaf1da9a1 | code | 855 | using Dates
# using GitCommand
using GitHub
using JSON
using Pkg
using Printf
using RegistryCI
using Test
using TimeZones
@testset "Public interface" begin
@testset "RegistryCI.test" begin
path = joinpath(DEPOT_PATH[1], "registries", "General")
RegistryCI.test(path)
end
end
@testset "Internal functions (private)" begin
@testset "RegistryCI.load_registry_dep_uuids" begin
all_registry_deps_names = [
["General"],
["https://github.com/JuliaRegistries/General"],
["https://github.com/JuliaRegistries/General.git"],
]
for registry_deps_names in all_registry_deps_names
extrauuids = RegistryCI.load_registry_dep_uuids(registry_deps_names)
@test extrauuids isa Set{Base.UUID}
@test length(extrauuids) > 1_000
end
end
end
| RegistryCI | https://github.com/JuliaRegistries/RegistryCI.jl.git |
|
[
"MIT"
] | 10.7.0 | f0341c8179a869629d90fe549511d6ffaf1da9a1 | code | 2079 | using Dates
# using GitCommand
using GitHub
using JSON
using Pkg
using Printf
using RegistryCI
using Test
using TimeZones
using ReferenceTests
const AutoMerge = RegistryCI.AutoMerge
# Starting with Julia 1.7, when you use the Pkg server registry, the registry tarball does
# not get unpacked, and thus the registry files are not available. Of course, RegistryCI
# requires that the registry files are available. So for the RegistryCI test suite, we will
# disable the Pkg server.
ENV["JULIA_PKG_SERVER"] = ""
@static if v"1.6-" <= Base.VERSION < v"1.11-"
# BrokenRecord fails to precompile on Julia 1.11
let
# The use of `VersionNumber`s here (e.g. `version = v"foo.bar.baz"`) tells Pkg to install the exact version.
brokenrecord = Pkg.PackageSpec(name = "BrokenRecord", uuid = "bdd55f5b-6e67-4da1-a080-6086e55655a0", version = v"0.1.9")
jld2 = Pkg.PackageSpec(name = "JLD2", uuid = "033835bb-8acc-5ee8-8aae-3f567f8a3819", version = v"0.4.33")
pkgs = [brokenrecord, jld2]
Pkg.add(pkgs)
end
import BrokenRecord
end
@testset "RegistryCI.jl" begin
@testset "RegistryCI.jl unit tests" begin
@info("Running the RegistryCI.jl unit tests")
include("registryci_registry_testing.jl")
end
@testset "TagBot.jl unit tests" begin
# if v"1.0" <= VERSION < VersionNumber(1, 5, typemax(UInt32))
if false
@info("Running the TagBot.jl unit tests", VERSION)
include("tagbot-unit.jl")
else
@warn("Skipping the TagBot.jl unit tests", VERSION)
end
end
@testset "AutoMerge.jl unit tests" begin
@info("Running the AutoMerge.jl unit tests")
include("automerge-unit.jl")
end
AUTOMERGE_RUN_INTEGRATION_TESTS =
get(ENV, "AUTOMERGE_RUN_INTEGRATION_TESTS", "")::String
if AUTOMERGE_RUN_INTEGRATION_TESTS == "true"
@testset "AutoMerge.jl integration tests" begin
@info("Running the AutoMerge.jl integration tests")
include("automerge-integration.jl")
end
end
end
| RegistryCI | https://github.com/JuliaRegistries/RegistryCI.jl.git |
|
[
"MIT"
] | 10.7.0 | f0341c8179a869629d90fe549511d6ffaf1da9a1 | code | 6611 | using BrokenRecord: BrokenRecord, HTTP, playback
using Dates: DateTime, Day, UTC, now
using RegistryCI: TagBot
using SimpleMock: Mock, called_with, mock
using Test: @test, @testset, @test_logs
const TB = TagBot
const GH = TB.GH
TB.AUTH[] = GH.OAuth2(get(ENV, "GITHUB_TOKEN", "abcdef"))
TB.TAGBOT_USER[] = "JuliaTagBot"
BrokenRecord.configure!(;
path=joinpath(@__DIR__, "cassettes"), ignore_headers=["Authorization"]
)
@testset "is_merged_pull_request" begin
@test !TB.is_merged_pull_request(Dict())
@test !TB.is_merged_pull_request(Dict("pull_request" => Dict("merged" => false)))
@test TB.is_merged_pull_request(Dict("pull_request" => Dict("merged" => true)))
end
@testset "is_cron" begin
withenv(() -> @test(!TB.is_cron(())), "GITHUB_EVENT_NAME" => nothing)
withenv(() -> @test(!TB.is_cron(())), "GITHUB_EVENT_NAME" => "pull_request")
withenv(() -> @test(TB.is_cron(())), "GITHUB_EVENT_NAME" => "schedule")
end
@testset "repo_and_version_of_pull_request" begin
body(url) = """
- Repository: $url
- Version: v1.2.3
"""
github = body("https://github.com/Foo/Bar")
@test TB.repo_and_version_of_pull_request_body(github) == ("Foo/Bar", "v1.2.3")
ssh = body("[email protected]:Foo/Bar.git")
@test TB.repo_and_version_of_pull_request_body(ssh) == ("Foo/Bar", "v1.2.3")
gitlab = body("https://gitlab.com/Foo/Bar")
@test TB.repo_and_version_of_pull_request_body(gitlab) == (nothing, "v1.2.3")
no_body = nothing
@test TB.repo_and_version_of_pull_request_body(no_body) == (nothing, nothing)
end
@testset "tagbot_file" begin
playback("tagbot_file.bson") do
@test TB.tagbot_file("Repo/DoesNotExist") === nothing
@test TB.tagbot_file("torvalds/linux") === nothing
path, contents = TB.tagbot_file("JuliaRegistries/RegistryCI.jl")
@test path == ".github/workflows/TagBot.yml"
@test occursin("JuliaRegistries/TagBot", contents)
@test TB.tagbot_file("JuliaWeb/HTTP.jl") !== nothing
@test TB.tagbot_file("JuliaWeb/HTTP.jl"; issue_comments=true) === nothing
end
end
@testset "get_repo_notification_issue" begin
playback("get_repo_notification_issue.bson") do
@test_logs match_mode = :any (:info, "Creating new notification issue") begin
issue = TB.get_repo_notification_issue("christopher-dG/TestRepo")
@test issue.number == 11
end
@test_logs match_mode = :any (:info, "Found existing notification issue") begin
issue = TB.get_repo_notification_issue("christopher-dG/TestRepo")
@test issue.number == 11
end
end
end
@testset "notification_body" begin
base = "Triggering TagBot for merged registry pull request"
@test TB.notification_body(Dict()) == base
event = Dict("pull_request" => Dict("html_url" => "foo"))
@test TB.notification_body(event) == "$base: foo"
@test occursin("extra notification", TB.notification_body(event; cron=true))
end
@testset "notify" begin
playback("notify.bson") do
comment = TB.notify("christopher-dG/TestRepo", 4, "test notification")
@test comment.body == "test notification"
end
end
@testset "collect_pulls" begin
PR = GH.PullRequest
prs = [
[PR(), PR(; merged_at=now(UTC))],
[PR(; merged_at=now(UTC) - Day(2)), PR(; merged_at=now(UTC) - Day(4))],
]
pages = [Dict("next" => "abc"), Dict()]
pulls = mock(GH.pull_requests => Mock(collect(zip(prs, pages)))) do _prs
TB.collect_pulls("JuliaRegistries/General")
end
@test pulls == [prs[1][2], prs[2][1]]
end
@testset "tag_exists" begin
playback("tag_exists.bson") do
@test TB.tag_exists("JuliaRegistries/RegistryCI.jl", "v0.1.0")
@test !TB.tag_exists("JuliaRegistries/RegistryCI.jl", "v0.0.0")
end
end
@testset "maybe_notify" begin
@test_logs match_mode = :any (:info, r"not enabled") begin
mock(TB.tagbot_file => Mock(nothing)) do _tf
TB.maybe_notify((), "repo", "v")
end
end
@test_logs match_mode = :any (:info, r"already exists") begin
mock(TB.tagbot_file => Mock(true), TB.tag_exists => Mock(true)) do tf, te
TB.maybe_notify((), "repo", "v"; cron=true)
end
end
mock(
TB.tagbot_file => Mock(("path", "contents")),
TB.get_repo_notification_issue => Mock(1),
TB.should_fixup => Mock(false),
TB.notification_body => Mock("foo"),
TB.notify,
) do tagbot_file, get_issue, should_fixup, body, notify
TB.maybe_notify(Dict(), "repo", "v"; cron=true)
@test called_with(tagbot_file, "repo")
@test called_with(get_issue, "repo")
@test called_with(should_fixup, "repo", 1)
@test called_with(notify, "repo", 1, "foo")
end
end
@testset "should_fixup" begin
mock(
TB.fixup_comment_exists => Mock([false, true, true, true]),
TB.fixup_done => Mock([true, false, false]),
TB.tagbot_file => Mock([("path", "contents"), nothing]),
) do fce, fd, tf
@test !TB.should_fixup("repo", 1)
@test !TB.should_fixup("repo", 2)
@test !TB.should_fixup("repo", 3)
@test TB.should_fixup("repo", 4)
end
end
@testset "get_fork" begin
playback("get_fork.bson") do
mock(now => tz -> DateTime(2020, 11, 5, 19, 2)) do _now
fork = TB.get_fork("christopher-dG/TestRepo")
@test fork isa GH.Repo
end
end
end
@testset "open_fixup_pr" begin
playback("open_fixup_pr.bson") do
fork = GH.repo("JuliaTagBot/TestRepo"; auth=TB.AUTH[])
pr = TB.open_fixup_pr("christopher-dG/TestRepo"; branch="abc", fork=fork)
@test pr.number == 10
end
end
@testset "fixup_comment_exists" begin
playback("fixup_comment_exists.bson") do
no = GH.issue("christopher-dG/TestRepo", 7; auth=TB.AUTH[])
yes = GH.issue("christopher-dG/TestRepo", 8; auth=TB.AUTH[])
@test !TB.fixup_comment_exists("christopher-dG/TestRepo", no)
@test TB.fixup_comment_exists("christopher-dG/TestRepo", yes)
end
end
@testset "is_fixup_trigger" begin
comment = GH.Comment(Dict("user" => Dict("login" => "foo"), "body" => "foo"))
@test !TB.is_fixup_trigger(comment)
comment.body = "foo bar tagbot fix baz"
@test TB.is_fixup_trigger(comment)
comment.user.login = TB.TAGBOT_USER[]
@test !TB.is_fixup_trigger(comment)
end
@testset "fixup_done" begin
playback("fixup_done.bson") do
@test !TB.fixup_done("JuliaWeb/HTTP.jl")
@test TB.fixup_done("christopher-dG/TestRepo")
end
end
| RegistryCI | https://github.com/JuliaRegistries/RegistryCI.jl.git |
|
[
"MIT"
] | 10.7.0 | f0341c8179a869629d90fe549511d6ffaf1da9a1 | docs | 1459 | # Integration tests for RegistryCI.jl
## How to run the integration tests on your local machine
You may find it helpful to set up your own test repo and run the integration tests on your local machine. Here are the steps:
1. Set up a test repository, i.e. create a new public GitHub repository for testing purposes. For this example, suppose that this repo is called `MY_GITHUB_USERNAME/MY_REGISTRYCI_TEST_REPO`.
2. Make sure that there is some content in the `master` branch of `MY_GITHUB_USERNAME/MY_REGISTRYCI_TEST_REPO`. Perhaps just a `README.md` file with a single word or something like that.
3. Set the environment variable: `export AUTOMERGE_INTEGRATION_TEST_REPO="MY_GITHUB_USERNAME/MY_REGISTRYCI_TEST_REPO"`
4. Set the environment variable: `export AUTOMERGE_RUN_INTEGRATION_TESTS="true"`
5. Go to https://github.com/settings/tokens and generate a new GitHub personal access token. The token only needs the `repo` and `public_repo` permissions - you can uncheck all other permissions. Save that token somewhere - I recommend saving the token in a secure location like a password manager.
6. Set the environment variable containing your GitHub personal access token: `export BCBI_TEST_USER_GITHUB_TOKEN="YOUR_GITHUB_PERSONAL_ACCESS_TOKEN"`
7. Run the package tests `Pkg.test("RegistryCI")`. Watch the logs - you should see the message `Running the AutoMerge.jl integration tests`, which confirms that you are running the integration tests.
| RegistryCI | https://github.com/JuliaRegistries/RegistryCI.jl.git |
|
[
"MIT"
] | 10.7.0 | f0341c8179a869629d90fe549511d6ffaf1da9a1 | docs | 2521 | # RegistryCI.jl
| Category | Status |
| ----------------- | ------------------------------------------------------------------------------------------------------------------ |
| Unit Tests | [![Continuous Integration (Unit Tests)][ci-unit-img]][ci-unit-url] |
| Integration Tests | [![Continuous Integration (Integration Tests)][ci-integration-img]][ci-integration-url] |
| Documentation | [![Documentation (stable)][docs-stable-img]][docs-stable-url] [![Documentation (dev)][docs-dev-img]][docs-dev-url] |
| Code Coverage | [![Code Coverage][codecov-img]][codecov-url] |
| Style Guide | [![Style Guide][bluestyle-img]][bluestyle-url] |
[docs-stable-img]: https://img.shields.io/badge/docs-stable-blue.svg "Documentation (stable)"
[docs-stable-url]: https://JuliaRegistries.github.io/RegistryCI.jl/stable
[docs-dev-img]: https://img.shields.io/badge/docs-dev-blue.svg "Documentation (dev)"
[docs-dev-url]: https://JuliaRegistries.github.io/RegistryCI.jl/dev
[ci-unit-img]: https://github.com/JuliaRegistries/RegistryCI.jl/workflows/CI%20(unit%20tests)/badge.svg?branch=master "Continuous Integration (Unit Tests)"
[ci-unit-url]: https://github.com/JuliaRegistries/RegistryCI.jl/actions?query=workflow%3A%22CI+%28unit+tests%29%22
[ci-integration-img]: https://github.com/JuliaRegistries/RegistryCI.jl/workflows/CI%20(integration%20tests)/badge.svg?branch=master "Continuous Integration (Integration Tests)"
[ci-integration-url]: https://github.com/JuliaRegistries/RegistryCI.jl/actions?query=workflow%3A%22CI+%28integration+tests%29%22
[codecov-img]: https://codecov.io/gh/JuliaRegistries/RegistryCI.jl/branch/master/graph/badge.svg "Code Coverage"
[codecov-url]: https://codecov.io/gh/JuliaRegistries/RegistryCI.jl/branch/master
[bluestyle-img]: https://img.shields.io/badge/code%20style-blue-4495d1.svg "Blue Style"
[bluestyle-url]: https://github.com/invenia/BlueStyle
RegistryCI.jl
provides continuous integration (CI) tools for Julia package registries, including registry consistency testing, automatic merging (automerge) of pull requests, and automatic TagBot triggers.
Please see the [documentation](https://JuliaRegistries.github.io/RegistryCI.jl/stable).
| RegistryCI | https://github.com/JuliaRegistries/RegistryCI.jl.git |
|
[
"MIT"
] | 10.7.0 | f0341c8179a869629d90fe549511d6ffaf1da9a1 | docs | 6357 | ```@meta
CurrentModule = RegistryCI
```
# Automatic merging guidelines
These are the guidelines that a pull request must pass in order to be automatically merged.
All of those guidelines are enabled on the General registry.
For other registries, some of these guidelines can be disabled.
## New packages
```@eval
import RegistryCI
import Markdown
function guidelines_to_markdown_output(guidelines_function::Function)
guidelines = guidelines_function(
registration_type;
check_license = true,
this_is_jll_package = false,
this_pr_can_use_special_jll_exceptions = false,
use_distance_check = false,
package_author_approved = false,
)
filter!(x -> !(x[1] isa Symbol), guidelines)
filter!(x -> !(x[1].docs isa Nothing), guidelines)
docs = [rstrip(x[1].docs) for x in guidelines]
output_string = join(string.(collect(1:length(docs)), Ref(". "), docs), "\n")
output_markdown = Markdown.parse(output_string)
return output_markdown
end
const guidelines_function = RegistryCI.AutoMerge.get_automerge_guidelines
const registration_type = RegistryCI.AutoMerge.NewPackage()
const output_markdown = guidelines_to_markdown_output(guidelines_function)
return output_markdown
```
## New versions of existing packages
```@eval
import RegistryCI
import Markdown
function guidelines_to_markdown_output(guidelines_function::Function)
guidelines = guidelines_function(
registration_type;
check_license = true,
this_is_jll_package = false,
this_pr_can_use_special_jll_exceptions = false,
use_distance_check = false,
package_author_approved = false,
)
filter!(x -> !(x[1] isa Symbol), guidelines)
filter!(x -> !(x[1].docs isa Nothing), guidelines)
docs = [rstrip(x[1].docs) for x in guidelines]
output_string = join(string.(collect(1:length(docs)), Ref(". "), docs), "\n")
output_markdown = Markdown.parse(output_string)
return output_markdown
end
const guidelines_function = RegistryCI.AutoMerge.get_automerge_guidelines
const registration_type = RegistryCI.AutoMerge.NewVersion()
const output_markdown = guidelines_to_markdown_output(guidelines_function)
return output_markdown
```
## Additional information
### Upper-bounded `[compat]` entries
For example, the following `[compat]` entries meet the criteria for automatic merging:
```toml
[compat]
PackageA = "1" # [1.0.0, 2.0.0), has upper bound (good)
PackageB = "0.1, 0.2" # [0.1.0, 0.3.0), has upper bound (good)
```
The following `[compat]` entries do NOT meet the criteria for automatic merging:
```toml
[compat]
PackageC = ">=3" # [3.0.0, ∞), no upper bound (bad)
PackageD = ">=0.4, <1" # [0, ∞), no lower bound, no upper bound (very bad)
```
Please note: each `[compat]` entry must include only a finite number of breaking releases. Therefore, the following `[compat]` entries do NOT meet the criteria for automatic merging:
```toml
[compat]
PackageE = "0" # includes infinitely many breaking 0.x releases of PackageE (bad)
PackageF = "0.2 - 0" # includes infinitely many breaking 0.x releases of PackageF (bad)
PackageG = "0.2 - 1" # includes infinitely many breaking 0.x releases of PackageG (bad)
```
See [Pkg's documentation](https://julialang.github.io/Pkg.jl/v1/compatibility/) for specification of `[compat]` entries in your
`Project.toml` file.
(**Note:** JLL dependencies are excluded from this criterion because they often have non-standard version numbering schemes; however, this may change in the future.)
You may find [CompatHelper.jl](https://github.com/bcbi/CompatHelper.jl) and [PackageCompatUI.jl](https://github.com/GunnarFarneback/PackageCompatUI.jl) helpful for maintaining up-to-date `[compat]` entries.
### Name similarity distance check
These checks and tolerances are subject to change in order to improve the
process.
To test yourself that a tentative package name, say `MyPackage` meets these
checks, you can use the following code (after adding the RegistryCI package
to your Julia environment):
```@example
using RegistryCI, RegistryInstances
using RegistryCI.AutoMerge
path_to_registry = joinpath(DEPOT_PATH[1], "registries", "General.toml")
all_pkg_names = AutoMerge.get_all_non_jll_package_names(RegistryInstance(path_to_registry))
AutoMerge.meets_distance_check("MyPackage123", all_pkg_names)
```
where `path_to_registry` is a path to the registry of
interest. For the General Julia registry, usually `path_to_registry =
joinpath(DEPOT_PATH[1], "registries", "General.toml")` if you haven't changed
your `DEPOT_PATH` (or `path_to_registry =
joinpath(DEPOT_PATH[1], "registries", "General")` if you have an uncompressed registry at the directory there). This will return a boolean, indicating whether or not
your tentative package name passed the check, as well as a string,
indicating what the problem is in the event the check did not pass.
Note that these automerge guidelines are deliberately conservative: it is
very possible for a perfectly good name to not pass the automatic checks and
require manual merging. They simply exist to provide a fast path so that
manual review is not required for every new package.
## List of all GitHub PR labels that can influence AutoMerge
AutoMerge reads certain labels on GitHub registration pull requests to influence its decisions.
Specifically, these labels are:
* `Override AutoMerge: name similarity is okay`
* This label can be manually applied by folks with triage-level access to the registry repository.
* AutoMerge skips the "name similarity check" on new package registration PRs with this label.
* `Override AutoMerge: package author approved`
* This label can be manually applied, but typically is applied by a separate Github Actions workflow which monitors the PR for comments by the package author, and applies this label if they write `[merge approved]`.
* This label currently only skips the "sequential version number" check in new versions. In the future, the author-approval mechanism may be used for other checks (on both "new version" registrations and also "new package" registrations).
* When AutoMerge fails a check that can be skipped by author-approval, it will mention so in the comment, and direct authors to comment `[merge approved]` if they want to skip the check.
| RegistryCI | https://github.com/JuliaRegistries/RegistryCI.jl.git |
|
[
"MIT"
] | 10.7.0 | f0341c8179a869629d90fe549511d6ffaf1da9a1 | docs | 368 | ```@meta
CurrentModule = RegistryCI
```
# [RegistryCI.jl](https://github.com/JuliaRegistries/RegistryCI.jl)
[RegistryCI.jl](https://github.com/JuliaRegistries/RegistryCI.jl)
provides continuous integration (CI) tools for Julia package registries, including registry consistency testing, automatic merging (automerge) of pull requests, and automatic TagBot triggers.
| RegistryCI | https://github.com/JuliaRegistries/RegistryCI.jl.git |
|
[
"MIT"
] | 10.7.0 | f0341c8179a869629d90fe549511d6ffaf1da9a1 | docs | 165 | ```@meta
CurrentModule = RegistryCI
```
# Internals
```@autodocs
Modules = [RegistryCI, RegistryCI.AutoMerge, RegistryCI.TagBot]
Public = false
Private = true
```
| RegistryCI | https://github.com/JuliaRegistries/RegistryCI.jl.git |
|
[
"MIT"
] | 10.7.0 | f0341c8179a869629d90fe549511d6ffaf1da9a1 | docs | 5588 | ```@meta
CurrentModule = RegistryCI
```
# Using RegistryCI on your own package registry
In order to create and maintain a custom Julia registry, you can use [LocalRegistry.jl](https://github.com/GunnarFarneback/LocalRegistry.jl).
After you have the registry configured, you can setup CI using RegistryCI by following how it is used in the
[General registry](https://github.com/JuliaRegistries/General).
## Basic configuration
You will first need to copy the `.ci` folder in the root of the General registry to the root of your own registry. This folder contains some resources required for the RegistryCI package to work and update itself. If you do not need AutoMerge support, there is no need to copy the
`stopwatch.jl` file in the `.ci` folder.
Next, you will need to copy the `registry-consistency-ci.yml` and `update_manifest.yml` workflow files.
The `registry-consistency-ci.yml` file should be modified as follows if you have packages in your registry that depend on packages in the General registry.
If the packages in your registry depend on packages in other registries, they should also be added to `registry_deps`
```diff
- run: julia --project=.ci/ --color=yes -e 'import RegistryCI; RegistryCI.test()'
+ run: julia --project=.ci/ --color=yes -e 'import RegistryCI; RegistryCI.test(registry_deps=["https://github.com/JuliaRegistries/General"])'
```
You can optionally use the registry name instead of the URL:
```diff
- run: julia --project=.ci/ --color=yes -e 'import RegistryCI; RegistryCI.test()'
+ run: julia --project=.ci/ --color=yes -e 'import RegistryCI; RegistryCI.test(registry_deps=["General"])'
```
If Julia pkg server is available and recognized, then the Julia Pkg will try to download registry from it. This can be useful to reduce the
unnecessary network traffic, for example, if you host a private pkg server in your local network(e.g., enterprise network with firewall)
and properly set up the environment variable `JULIA_PKG_SERVER`, then the network traffic doesn't need to pass through the proxy to GitHub.
!!! warning
Registry fetched from Julia pkg server currently has some observable latency(e.g., hours). Check [here](https://github.com/JuliaRegistries/General/issues/16777) for more information.
The self-update mechanism mentioned above uses a `TAGBOT_TOKEN` secret in order to create a pull request with the update.
This secret is a [personal access token](https://help.github.com/en/github/authenticating-to-github/creating-a-personal-access-token-for-the-command-line#creating-a-token) which must have the `repo` scope enabled.
To create the repository secret follow the instructions [here](https://help.github.com/en/actions/automating-your-workflow-with-github-actions/creating-and-using-encrypted-secrets#creating-encrypted-secrets). Use the name `TAGBOT_TOKEN` and the new PAT as the value.
## TagBot triggers
If you want to use TagBot in the packages that you register in your registry, you need to also copy the `TagBotTriggers.yml` file.
That workflow file also needs the `TAGBOT_TOKEN` secret mentioned above.
In the `TagBot.yml` workflows of the registered packages you will also need to add the `registry` input as stated in the [TagBot readme](https://github.com/JuliaRegistries/TagBot#custom-registries)
```
with:
token: ${{ secrets.GITHUB_TOKEN }}
registry: MyOrg/MyRegistry
```
## AutoMerge support
In order to enable automerge support, you will also have to copy the `automerge.yml` file and change the `AutoMerge` invocation appropriately
```julia
using RegistryCI
using Dates
RegistryCI.AutoMerge.run(
merge_new_packages = ENV["MERGE_NEW_PACKAGES"] == "true",
merge_new_versions = ENV["MERGE_NEW_VERSIONS"] == "true",
new_package_waiting_period = Day(3),
new_jll_package_waiting_period = Minute(20),
new_version_waiting_period = Minute(10),
new_jll_version_waiting_period = Minute(10),
registry = "MyOrg/MyRegistry",
tagbot_enabled = true,
authorized_authors = String["TrustedUser"],
authorized_authors_special_jll_exceptions = String[""],
suggest_onepointzero = false,
additional_statuses = String[],
additional_check_runs = String[],
check_license = true,
public_registries = String["https://github.com/HolyLab/HolyLabRegistry"],
)
```
Most importantly, the following should be changed
```
registry = "MyOrg/MyRegistry",
authorized_authors = String["TrustedUser"],
```
You will also have to make the following change in `.ci/stopwatch.jl`
```diff
- registry = GitHub.Repo("JuliaRegistries/General")
+ registry = GitHub.Repo("MyOrg/MyRegistry")
```
## Note regarding private registries
In the case of a private registry, you might get permission errors when executing the `instantiate.sh` script.
In that case you will also have to add the following
```diff
- run: chmod 400 .ci/Project.toml
- run: chmod 400 .ci/Manifest.toml
+ - run: chmod +x .ci/instantiate.sh
```
in `registry-consistency-ci.yml` and also `TagBotTriggers.yml` and `automerge.yml` (in which the above appears twice) files if those features are used.
## Author approval workflow support
Some guidelines allow the person invoking registration (typically the package author) to "approve" AutoMerge even if the guideline is not passing. This is facilitated by a labelling workflow `author_approval.yml` that must run on the registry in order to translate author-approval comments into labels that AutoMerge can use. The [General registry's workflows](https://github.com/JuliaRegistries/General/tree/master/.github/workflows) should once again be used as an example.
| RegistryCI | https://github.com/JuliaRegistries/RegistryCI.jl.git |
|
[
"MIT"
] | 10.7.0 | f0341c8179a869629d90fe549511d6ffaf1da9a1 | docs | 221 | ```@meta
CurrentModule = RegistryCI
```
# Public API
```@docs
RegistryCI.test
RegistryCI.AutoMerge.run
```
```@autodocs
Modules = [RegistryCI, RegistryCI.AutoMerge, RegistryCI.TagBot]
Public = true
Private = false
```
| RegistryCI | https://github.com/JuliaRegistries/RegistryCI.jl.git |
|
[
"MIT"
] | 10.7.0 | f0341c8179a869629d90fe549511d6ffaf1da9a1 | docs | 2076 | ```@meta
CurrentModule = RegistryCI
```
# Regexes
In order for AutoMerge to work, each pull request (PR) must match the following
regular expressions:
```@eval
import RegistryCI
import Markdown
Base.@kwdef struct TableRow
regex::Regex
regex_str::String
pr_field::String
pr_type::String
example::String
end
escape_pipes(str::String) = replace(str, "|" => "\\|")
function table_row(; regex::Regex,
pr_field::String,
pr_type::String,
example::String)
regex_str = regex |> Base.repr |> escape_pipes
result = TableRow(;
regex,
regex_str,
pr_field,
pr_type,
example,
)
return result
end
const row_1 = table_row(;
regex = RegistryCI.AutoMerge.new_package_title_regex,
pr_field = "PR title",
pr_type = "New packages",
example = "New package: HelloWorld v1.2.3",
)
const row_2 = table_row(;
regex = RegistryCI.AutoMerge.new_version_title_regex,
pr_field = "PR title",
pr_type = "New versions",
example = "New version: HelloWorld v1.2.3",
)
const row_3 = table_row(;
regex = RegistryCI.AutoMerge.commit_regex,
pr_field = "PR body",
pr_type = "All",
example = "* Commit: 012345678901234567890123456789abcdef0000",
)
const rows = [
row_1,
row_2,
row_3,
]
for row in rows
regex_occurs_in_example = occursin(row.regex, row.example)
if !regex_occurs_in_example
@error("Regex does not occur in example", row.regex, row.example)
throw(ErrorException("Regex `$(row.regex)` does not occur in example \"$(row.example)\""))
end
end
const markdown_lines = String[
"| Regex | Field | PR Type | Example |",
"| ----- | ----- | ------- | ------- |",
]
for row in rows
line = "| `$(row.regex_str)` | $(row.pr_field) | $(row.pr_type) | `$(row.example)` |"
push!(markdown_lines, line)
end
const markdown_string = join(markdown_lines, "\n")
const markdown_parsed = Markdown.parse(markdown_string)
return markdown_parsed
```
| RegistryCI | https://github.com/JuliaRegistries/RegistryCI.jl.git |
|
[
"MIT"
] | 10.7.0 | f0341c8179a869629d90fe549511d6ffaf1da9a1 | docs | 2945 | Hello, I am an automated registration bot. I help manage the registration process by checking your registration against a set of [AutoMerge guidelines](https://juliaregistries.github.io/RegistryCI.jl/stable/guidelines/). If all these guidelines are met, this pull request will be merged automatically, completing your registration. It is **strongly recommended** to follow the guidelines, since otherwise the pull request needs to be manually reviewed and merged by a human.
## 1. New package registration
Please make sure that you have read the [package naming guidelines](https://julialang.github.io/Pkg.jl/dev/creating-packages/#Package-naming-guidelines-1).
## 2. [AutoMerge Guidelines](https://juliaregistries.github.io/RegistryCI.jl/stable/guidelines/) which are not met ❌
- The following dependencies do not have a `[compat]` entry that is upper-bounded and only includes a finite number of breaking releases: julia
<details><summary>Extended explanation</summary>
Your package has a Project.toml file which might look something like the following:
```toml
name = "YourPackage"
uuid = "random id"
authors = ["Author Names"]
version = "major.minor"
[deps]
# Package dependencies
# ...
[compat]
# ...
```
Every package listed in `[deps]`, along with `julia` itself, must also be listed under `[compat]` (if you don't have a `[compat]` section, make one!). See the [Pkg docs](https://pkgdocs.julialang.org/v1/compatibility/) for the syntax for compatibility bounds, and [this documentation](https://juliaregistries.github.io/RegistryCI.jl/stable/guidelines/#Upper-bounded-%5Bcompat%5D-entries) for more on the kinds of compat bounds required for AutoMerge.
</details>
- Example guideline failed. Please fix it.
## 3. *Needs action*: here's what to do next
1. Please try to update your package to conform to these guidelines. The [General registry's README](https://github.com/JuliaRegistries/General/blob/master/README.md) has an FAQ that can help figure out how to do so.
2. After you have fixed the AutoMerge issues, simply retrigger Registrator, the same way you did in the initial registration. This will automatically update this pull request. You do not need to change the version number in your `Project.toml` file (unless the AutoMerge issue is that you skipped a version number).
If you need help fixing the AutoMerge issues, or want your pull request to be manually merged instead, please post a comment explaining what you need help with or why you would like this pull request to be manually merged.
## 4. To pause or stop registration
If you want to prevent this pull request from being auto-merged, simply leave a comment. If you want to post a comment without blocking auto-merging, you must include the text `[noblock]` in your comment.
_Tip: You can edit blocking comments to add `[noblock]` in order to unblock auto-merging._
<!-- [noblock] --> | RegistryCI | https://github.com/JuliaRegistries/RegistryCI.jl.git |
|
[
"MIT"
] | 10.7.0 | f0341c8179a869629d90fe549511d6ffaf1da9a1 | docs | 3082 | Hello, I am an automated registration bot. I help manage the registration process by checking your registration against a set of [AutoMerge guidelines](https://juliaregistries.github.io/RegistryCI.jl/stable/guidelines/). If all these guidelines are met, this pull request will be merged automatically, completing your registration. It is **strongly recommended** to follow the guidelines, since otherwise the pull request needs to be manually reviewed and merged by a human.
## 1. New package registration
Please make sure that you have read the [package naming guidelines](https://julialang.github.io/Pkg.jl/dev/creating-packages/#Package-naming-guidelines-1).
## 2. [AutoMerge Guidelines](https://juliaregistries.github.io/RegistryCI.jl/stable/guidelines/) which are not met ❌
- The following dependencies do not have a `[compat]` entry that is upper-bounded and only includes a finite number of breaking releases: julia
<details><summary>Extended explanation</summary>
Your package has a Project.toml file which might look something like the following:
```toml
name = "YourPackage"
uuid = "random id"
authors = ["Author Names"]
version = "major.minor"
[deps]
# Package dependencies
# ...
[compat]
# ...
```
Every package listed in `[deps]`, along with `julia` itself, must also be listed under `[compat]` (if you don't have a `[compat]` section, make one!). See the [Pkg docs](https://pkgdocs.julialang.org/v1/compatibility/) for the syntax for compatibility bounds, and [this documentation](https://juliaregistries.github.io/RegistryCI.jl/stable/guidelines/#Upper-bounded-%5Bcompat%5D-entries) for more on the kinds of compat bounds required for AutoMerge.
</details>
- Example guideline failed. Please fix it.
## 3. *Needs action*: here's what to do next
1. Please try to update your package to conform to these guidelines. The [General registry's README](https://github.com/JuliaRegistries/General/blob/master/README.md) has an FAQ that can help figure out how to do so.
2. After you have fixed the AutoMerge issues, simply retrigger Registrator, the same way you did in the initial registration. This will automatically update this pull request. You do not need to change the version number in your `Project.toml` file (unless the AutoMerge issue is that you skipped a version number).
If you need help fixing the AutoMerge issues, or want your pull request to be manually merged instead, please post a comment explaining what you need help with or why you would like this pull request to be manually merged. Then, send a message to the `#pkg-registration` channel in the [public Julia Slack](https://julialang.org/slack/) for better visibility.
## 4. To pause or stop registration
If you want to prevent this pull request from being auto-merged, simply leave a comment. If you want to post a comment without blocking auto-merging, you must include the text `[noblock]` in your comment.
_Tip: You can edit blocking comments to add `[noblock]` in order to unblock auto-merging._
<!-- [noblock] --> | RegistryCI | https://github.com/JuliaRegistries/RegistryCI.jl.git |
|
[
"MIT"
] | 10.7.0 | f0341c8179a869629d90fe549511d6ffaf1da9a1 | docs | 2945 | Hello, I am an automated registration bot. I help manage the registration process by checking your registration against a set of [AutoMerge guidelines](https://juliaregistries.github.io/RegistryCI.jl/stable/guidelines/). If all these guidelines are met, this pull request will be merged automatically, completing your registration. It is **strongly recommended** to follow the guidelines, since otherwise the pull request needs to be manually reviewed and merged by a human.
## 1. New package registration
Please make sure that you have read the [package naming guidelines](https://julialang.github.io/Pkg.jl/dev/creating-packages/#Package-naming-guidelines-1).
## 2. [AutoMerge Guidelines](https://juliaregistries.github.io/RegistryCI.jl/stable/guidelines/) which are not met ❌
- The following dependencies do not have a `[compat]` entry that is upper-bounded and only includes a finite number of breaking releases: julia
<details><summary>Extended explanation</summary>
Your package has a Project.toml file which might look something like the following:
```toml
name = "YourPackage"
uuid = "random id"
authors = ["Author Names"]
version = "major.minor"
[deps]
# Package dependencies
# ...
[compat]
# ...
```
Every package listed in `[deps]`, along with `julia` itself, must also be listed under `[compat]` (if you don't have a `[compat]` section, make one!). See the [Pkg docs](https://pkgdocs.julialang.org/v1/compatibility/) for the syntax for compatibility bounds, and [this documentation](https://juliaregistries.github.io/RegistryCI.jl/stable/guidelines/#Upper-bounded-%5Bcompat%5D-entries) for more on the kinds of compat bounds required for AutoMerge.
</details>
- Example guideline failed. Please fix it.
## 3. *Needs action*: here's what to do next
1. Please try to update your package to conform to these guidelines. The [General registry's README](https://github.com/JuliaRegistries/General/blob/master/README.md) has an FAQ that can help figure out how to do so.
2. After you have fixed the AutoMerge issues, simply retrigger Registrator, the same way you did in the initial registration. This will automatically update this pull request. You do not need to change the version number in your `Project.toml` file (unless the AutoMerge issue is that you skipped a version number).
If you need help fixing the AutoMerge issues, or want your pull request to be manually merged instead, please post a comment explaining what you need help with or why you would like this pull request to be manually merged.
## 4. To pause or stop registration
If you want to prevent this pull request from being auto-merged, simply leave a comment. If you want to post a comment without blocking auto-merging, you must include the text `[noblock]` in your comment.
_Tip: You can edit blocking comments to add `[noblock]` in order to unblock auto-merging._
<!-- [noblock] --> | RegistryCI | https://github.com/JuliaRegistries/RegistryCI.jl.git |
|
[
"MIT"
] | 10.7.0 | f0341c8179a869629d90fe549511d6ffaf1da9a1 | docs | 3082 | Hello, I am an automated registration bot. I help manage the registration process by checking your registration against a set of [AutoMerge guidelines](https://juliaregistries.github.io/RegistryCI.jl/stable/guidelines/). If all these guidelines are met, this pull request will be merged automatically, completing your registration. It is **strongly recommended** to follow the guidelines, since otherwise the pull request needs to be manually reviewed and merged by a human.
## 1. New package registration
Please make sure that you have read the [package naming guidelines](https://julialang.github.io/Pkg.jl/dev/creating-packages/#Package-naming-guidelines-1).
## 2. [AutoMerge Guidelines](https://juliaregistries.github.io/RegistryCI.jl/stable/guidelines/) which are not met ❌
- The following dependencies do not have a `[compat]` entry that is upper-bounded and only includes a finite number of breaking releases: julia
<details><summary>Extended explanation</summary>
Your package has a Project.toml file which might look something like the following:
```toml
name = "YourPackage"
uuid = "random id"
authors = ["Author Names"]
version = "major.minor"
[deps]
# Package dependencies
# ...
[compat]
# ...
```
Every package listed in `[deps]`, along with `julia` itself, must also be listed under `[compat]` (if you don't have a `[compat]` section, make one!). See the [Pkg docs](https://pkgdocs.julialang.org/v1/compatibility/) for the syntax for compatibility bounds, and [this documentation](https://juliaregistries.github.io/RegistryCI.jl/stable/guidelines/#Upper-bounded-%5Bcompat%5D-entries) for more on the kinds of compat bounds required for AutoMerge.
</details>
- Example guideline failed. Please fix it.
## 3. *Needs action*: here's what to do next
1. Please try to update your package to conform to these guidelines. The [General registry's README](https://github.com/JuliaRegistries/General/blob/master/README.md) has an FAQ that can help figure out how to do so.
2. After you have fixed the AutoMerge issues, simply retrigger Registrator, the same way you did in the initial registration. This will automatically update this pull request. You do not need to change the version number in your `Project.toml` file (unless the AutoMerge issue is that you skipped a version number).
If you need help fixing the AutoMerge issues, or want your pull request to be manually merged instead, please post a comment explaining what you need help with or why you would like this pull request to be manually merged. Then, send a message to the `#pkg-registration` channel in the [public Julia Slack](https://julialang.org/slack/) for better visibility.
## 4. To pause or stop registration
If you want to prevent this pull request from being auto-merged, simply leave a comment. If you want to post a comment without blocking auto-merging, you must include the text `[noblock]` in your comment.
_Tip: You can edit blocking comments to add `[noblock]` in order to unblock auto-merging._
<!-- [noblock] --> | RegistryCI | https://github.com/JuliaRegistries/RegistryCI.jl.git |
|
[
"MIT"
] | 10.7.0 | f0341c8179a869629d90fe549511d6ffaf1da9a1 | docs | 3372 | Hello, I am an automated registration bot. I help manage the registration process by checking your registration against a set of [AutoMerge guidelines](https://juliaregistries.github.io/RegistryCI.jl/stable/guidelines/). If all these guidelines are met, this pull request will be merged automatically, completing your registration. It is **strongly recommended** to follow the guidelines, since otherwise the pull request needs to be manually reviewed and merged by a human.
## 1. New package registration
Please make sure that you have read the [package naming guidelines](https://julialang.github.io/Pkg.jl/dev/creating-packages/#Package-naming-guidelines-1).
## 2. [AutoMerge Guidelines](https://juliaregistries.github.io/RegistryCI.jl/stable/guidelines/) which are not met ❌
- The following dependencies do not have a `[compat]` entry that is upper-bounded and only includes a finite number of breaking releases: julia
<details><summary>Extended explanation</summary>
Your package has a Project.toml file which might look something like the following:
```toml
name = "YourPackage"
uuid = "random id"
authors = ["Author Names"]
version = "major.minor"
[deps]
# Package dependencies
# ...
[compat]
# ...
```
Every package listed in `[deps]`, along with `julia` itself, must also be listed under `[compat]` (if you don't have a `[compat]` section, make one!). See the [Pkg docs](https://pkgdocs.julialang.org/v1/compatibility/) for the syntax for compatibility bounds, and [this documentation](https://juliaregistries.github.io/RegistryCI.jl/stable/guidelines/#Upper-bounded-%5Bcompat%5D-entries) for more on the kinds of compat bounds required for AutoMerge.
</details>
- Example guideline failed. Please fix it.
## 3. *Needs action*: here's what to do next
1. Please try to update your package to conform to these guidelines. The [General registry's README](https://github.com/JuliaRegistries/General/blob/master/README.md) has an FAQ that can help figure out how to do so.
2. After you have fixed the AutoMerge issues, simply retrigger Registrator, the same way you did in the initial registration. This will automatically update this pull request. You do not need to change the version number in your `Project.toml` file (unless the AutoMerge issue is that you skipped a version number).
If you need help fixing the AutoMerge issues, or want your pull request to be manually merged instead, please post a comment explaining what you need help with or why you would like this pull request to be manually merged.
## 4. Declare v1.0?
On a separate note, I see that you are registering a release with a version number of the form `v0.X.Y`.
Does your package have a stable public API? If so, then it's time for you to register version `v1.0.0` of your package. (This is not a requirement. It's just a recommendation.)
If your package does not yet have a stable public API, then of course you are not yet ready to release version `v1.0.0`.
## 5. To pause or stop registration
If you want to prevent this pull request from being auto-merged, simply leave a comment. If you want to post a comment without blocking auto-merging, you must include the text `[noblock]` in your comment.
_Tip: You can edit blocking comments to add `[noblock]` in order to unblock auto-merging._
<!-- [noblock] --> | RegistryCI | https://github.com/JuliaRegistries/RegistryCI.jl.git |
|
[
"MIT"
] | 10.7.0 | f0341c8179a869629d90fe549511d6ffaf1da9a1 | docs | 3509 | Hello, I am an automated registration bot. I help manage the registration process by checking your registration against a set of [AutoMerge guidelines](https://juliaregistries.github.io/RegistryCI.jl/stable/guidelines/). If all these guidelines are met, this pull request will be merged automatically, completing your registration. It is **strongly recommended** to follow the guidelines, since otherwise the pull request needs to be manually reviewed and merged by a human.
## 1. New package registration
Please make sure that you have read the [package naming guidelines](https://julialang.github.io/Pkg.jl/dev/creating-packages/#Package-naming-guidelines-1).
## 2. [AutoMerge Guidelines](https://juliaregistries.github.io/RegistryCI.jl/stable/guidelines/) which are not met ❌
- The following dependencies do not have a `[compat]` entry that is upper-bounded and only includes a finite number of breaking releases: julia
<details><summary>Extended explanation</summary>
Your package has a Project.toml file which might look something like the following:
```toml
name = "YourPackage"
uuid = "random id"
authors = ["Author Names"]
version = "major.minor"
[deps]
# Package dependencies
# ...
[compat]
# ...
```
Every package listed in `[deps]`, along with `julia` itself, must also be listed under `[compat]` (if you don't have a `[compat]` section, make one!). See the [Pkg docs](https://pkgdocs.julialang.org/v1/compatibility/) for the syntax for compatibility bounds, and [this documentation](https://juliaregistries.github.io/RegistryCI.jl/stable/guidelines/#Upper-bounded-%5Bcompat%5D-entries) for more on the kinds of compat bounds required for AutoMerge.
</details>
- Example guideline failed. Please fix it.
## 3. *Needs action*: here's what to do next
1. Please try to update your package to conform to these guidelines. The [General registry's README](https://github.com/JuliaRegistries/General/blob/master/README.md) has an FAQ that can help figure out how to do so.
2. After you have fixed the AutoMerge issues, simply retrigger Registrator, the same way you did in the initial registration. This will automatically update this pull request. You do not need to change the version number in your `Project.toml` file (unless the AutoMerge issue is that you skipped a version number).
If you need help fixing the AutoMerge issues, or want your pull request to be manually merged instead, please post a comment explaining what you need help with or why you would like this pull request to be manually merged. Then, send a message to the `#pkg-registration` channel in the [public Julia Slack](https://julialang.org/slack/) for better visibility.
## 4. Declare v1.0?
On a separate note, I see that you are registering a release with a version number of the form `v0.X.Y`.
Does your package have a stable public API? If so, then it's time for you to register version `v1.0.0` of your package. (This is not a requirement. It's just a recommendation.)
If your package does not yet have a stable public API, then of course you are not yet ready to release version `v1.0.0`.
## 5. To pause or stop registration
If you want to prevent this pull request from being auto-merged, simply leave a comment. If you want to post a comment without blocking auto-merging, you must include the text `[noblock]` in your comment.
_Tip: You can edit blocking comments to add `[noblock]` in order to unblock auto-merging._
<!-- [noblock] --> | RegistryCI | https://github.com/JuliaRegistries/RegistryCI.jl.git |
|
[
"MIT"
] | 10.7.0 | f0341c8179a869629d90fe549511d6ffaf1da9a1 | docs | 2945 | Hello, I am an automated registration bot. I help manage the registration process by checking your registration against a set of [AutoMerge guidelines](https://juliaregistries.github.io/RegistryCI.jl/stable/guidelines/). If all these guidelines are met, this pull request will be merged automatically, completing your registration. It is **strongly recommended** to follow the guidelines, since otherwise the pull request needs to be manually reviewed and merged by a human.
## 1. New package registration
Please make sure that you have read the [package naming guidelines](https://julialang.github.io/Pkg.jl/dev/creating-packages/#Package-naming-guidelines-1).
## 2. [AutoMerge Guidelines](https://juliaregistries.github.io/RegistryCI.jl/stable/guidelines/) which are not met ❌
- The following dependencies do not have a `[compat]` entry that is upper-bounded and only includes a finite number of breaking releases: julia
<details><summary>Extended explanation</summary>
Your package has a Project.toml file which might look something like the following:
```toml
name = "YourPackage"
uuid = "random id"
authors = ["Author Names"]
version = "major.minor"
[deps]
# Package dependencies
# ...
[compat]
# ...
```
Every package listed in `[deps]`, along with `julia` itself, must also be listed under `[compat]` (if you don't have a `[compat]` section, make one!). See the [Pkg docs](https://pkgdocs.julialang.org/v1/compatibility/) for the syntax for compatibility bounds, and [this documentation](https://juliaregistries.github.io/RegistryCI.jl/stable/guidelines/#Upper-bounded-%5Bcompat%5D-entries) for more on the kinds of compat bounds required for AutoMerge.
</details>
- Example guideline failed. Please fix it.
## 3. *Needs action*: here's what to do next
1. Please try to update your package to conform to these guidelines. The [General registry's README](https://github.com/JuliaRegistries/General/blob/master/README.md) has an FAQ that can help figure out how to do so.
2. After you have fixed the AutoMerge issues, simply retrigger Registrator, the same way you did in the initial registration. This will automatically update this pull request. You do not need to change the version number in your `Project.toml` file (unless the AutoMerge issue is that you skipped a version number).
If you need help fixing the AutoMerge issues, or want your pull request to be manually merged instead, please post a comment explaining what you need help with or why you would like this pull request to be manually merged.
## 4. To pause or stop registration
If you want to prevent this pull request from being auto-merged, simply leave a comment. If you want to post a comment without blocking auto-merging, you must include the text `[noblock]` in your comment.
_Tip: You can edit blocking comments to add `[noblock]` in order to unblock auto-merging._
<!-- [noblock] --> | RegistryCI | https://github.com/JuliaRegistries/RegistryCI.jl.git |
|
[
"MIT"
] | 10.7.0 | f0341c8179a869629d90fe549511d6ffaf1da9a1 | docs | 3082 | Hello, I am an automated registration bot. I help manage the registration process by checking your registration against a set of [AutoMerge guidelines](https://juliaregistries.github.io/RegistryCI.jl/stable/guidelines/). If all these guidelines are met, this pull request will be merged automatically, completing your registration. It is **strongly recommended** to follow the guidelines, since otherwise the pull request needs to be manually reviewed and merged by a human.
## 1. New package registration
Please make sure that you have read the [package naming guidelines](https://julialang.github.io/Pkg.jl/dev/creating-packages/#Package-naming-guidelines-1).
## 2. [AutoMerge Guidelines](https://juliaregistries.github.io/RegistryCI.jl/stable/guidelines/) which are not met ❌
- The following dependencies do not have a `[compat]` entry that is upper-bounded and only includes a finite number of breaking releases: julia
<details><summary>Extended explanation</summary>
Your package has a Project.toml file which might look something like the following:
```toml
name = "YourPackage"
uuid = "random id"
authors = ["Author Names"]
version = "major.minor"
[deps]
# Package dependencies
# ...
[compat]
# ...
```
Every package listed in `[deps]`, along with `julia` itself, must also be listed under `[compat]` (if you don't have a `[compat]` section, make one!). See the [Pkg docs](https://pkgdocs.julialang.org/v1/compatibility/) for the syntax for compatibility bounds, and [this documentation](https://juliaregistries.github.io/RegistryCI.jl/stable/guidelines/#Upper-bounded-%5Bcompat%5D-entries) for more on the kinds of compat bounds required for AutoMerge.
</details>
- Example guideline failed. Please fix it.
## 3. *Needs action*: here's what to do next
1. Please try to update your package to conform to these guidelines. The [General registry's README](https://github.com/JuliaRegistries/General/blob/master/README.md) has an FAQ that can help figure out how to do so.
2. After you have fixed the AutoMerge issues, simply retrigger Registrator, the same way you did in the initial registration. This will automatically update this pull request. You do not need to change the version number in your `Project.toml` file (unless the AutoMerge issue is that you skipped a version number).
If you need help fixing the AutoMerge issues, or want your pull request to be manually merged instead, please post a comment explaining what you need help with or why you would like this pull request to be manually merged. Then, send a message to the `#pkg-registration` channel in the [public Julia Slack](https://julialang.org/slack/) for better visibility.
## 4. To pause or stop registration
If you want to prevent this pull request from being auto-merged, simply leave a comment. If you want to post a comment without blocking auto-merging, you must include the text `[noblock]` in your comment.
_Tip: You can edit blocking comments to add `[noblock]` in order to unblock auto-merging._
<!-- [noblock] --> | RegistryCI | https://github.com/JuliaRegistries/RegistryCI.jl.git |
|
[
"MIT"
] | 10.7.0 | f0341c8179a869629d90fe549511d6ffaf1da9a1 | docs | 2756 | Hello, I am an automated registration bot. I help manage the registration process by checking your registration against a set of [AutoMerge guidelines](https://juliaregistries.github.io/RegistryCI.jl/stable/guidelines/). If all these guidelines are met, this pull request will be merged automatically, completing your registration. It is **strongly recommended** to follow the guidelines, since otherwise the pull request needs to be manually reviewed and merged by a human.
## 1. [AutoMerge Guidelines](https://juliaregistries.github.io/RegistryCI.jl/stable/guidelines/) which are not met ❌
- The following dependencies do not have a `[compat]` entry that is upper-bounded and only includes a finite number of breaking releases: julia
<details><summary>Extended explanation</summary>
Your package has a Project.toml file which might look something like the following:
```toml
name = "YourPackage"
uuid = "random id"
authors = ["Author Names"]
version = "major.minor"
[deps]
# Package dependencies
# ...
[compat]
# ...
```
Every package listed in `[deps]`, along with `julia` itself, must also be listed under `[compat]` (if you don't have a `[compat]` section, make one!). See the [Pkg docs](https://pkgdocs.julialang.org/v1/compatibility/) for the syntax for compatibility bounds, and [this documentation](https://juliaregistries.github.io/RegistryCI.jl/stable/guidelines/#Upper-bounded-%5Bcompat%5D-entries) for more on the kinds of compat bounds required for AutoMerge.
</details>
- Example guideline failed. Please fix it.
## 2. *Needs action*: here's what to do next
1. Please try to update your package to conform to these guidelines. The [General registry's README](https://github.com/JuliaRegistries/General/blob/master/README.md) has an FAQ that can help figure out how to do so.
2. After you have fixed the AutoMerge issues, simply retrigger Registrator, the same way you did in the initial registration. This will automatically update this pull request. You do not need to change the version number in your `Project.toml` file (unless the AutoMerge issue is that you skipped a version number).
If you need help fixing the AutoMerge issues, or want your pull request to be manually merged instead, please post a comment explaining what you need help with or why you would like this pull request to be manually merged.
## 3. To pause or stop registration
If you want to prevent this pull request from being auto-merged, simply leave a comment. If you want to post a comment without blocking auto-merging, you must include the text `[noblock]` in your comment.
_Tip: You can edit blocking comments to add `[noblock]` in order to unblock auto-merging._
<!-- [noblock] --> | RegistryCI | https://github.com/JuliaRegistries/RegistryCI.jl.git |
|
[
"MIT"
] | 10.7.0 | f0341c8179a869629d90fe549511d6ffaf1da9a1 | docs | 2893 | Hello, I am an automated registration bot. I help manage the registration process by checking your registration against a set of [AutoMerge guidelines](https://juliaregistries.github.io/RegistryCI.jl/stable/guidelines/). If all these guidelines are met, this pull request will be merged automatically, completing your registration. It is **strongly recommended** to follow the guidelines, since otherwise the pull request needs to be manually reviewed and merged by a human.
## 1. [AutoMerge Guidelines](https://juliaregistries.github.io/RegistryCI.jl/stable/guidelines/) which are not met ❌
- The following dependencies do not have a `[compat]` entry that is upper-bounded and only includes a finite number of breaking releases: julia
<details><summary>Extended explanation</summary>
Your package has a Project.toml file which might look something like the following:
```toml
name = "YourPackage"
uuid = "random id"
authors = ["Author Names"]
version = "major.minor"
[deps]
# Package dependencies
# ...
[compat]
# ...
```
Every package listed in `[deps]`, along with `julia` itself, must also be listed under `[compat]` (if you don't have a `[compat]` section, make one!). See the [Pkg docs](https://pkgdocs.julialang.org/v1/compatibility/) for the syntax for compatibility bounds, and [this documentation](https://juliaregistries.github.io/RegistryCI.jl/stable/guidelines/#Upper-bounded-%5Bcompat%5D-entries) for more on the kinds of compat bounds required for AutoMerge.
</details>
- Example guideline failed. Please fix it.
## 2. *Needs action*: here's what to do next
1. Please try to update your package to conform to these guidelines. The [General registry's README](https://github.com/JuliaRegistries/General/blob/master/README.md) has an FAQ that can help figure out how to do so.
2. After you have fixed the AutoMerge issues, simply retrigger Registrator, the same way you did in the initial registration. This will automatically update this pull request. You do not need to change the version number in your `Project.toml` file (unless the AutoMerge issue is that you skipped a version number).
If you need help fixing the AutoMerge issues, or want your pull request to be manually merged instead, please post a comment explaining what you need help with or why you would like this pull request to be manually merged. Then, send a message to the `#pkg-registration` channel in the [public Julia Slack](https://julialang.org/slack/) for better visibility.
## 3. To pause or stop registration
If you want to prevent this pull request from being auto-merged, simply leave a comment. If you want to post a comment without blocking auto-merging, you must include the text `[noblock]` in your comment.
_Tip: You can edit blocking comments to add `[noblock]` in order to unblock auto-merging._
<!-- [noblock] --> | RegistryCI | https://github.com/JuliaRegistries/RegistryCI.jl.git |
|
[
"MIT"
] | 10.7.0 | f0341c8179a869629d90fe549511d6ffaf1da9a1 | docs | 2756 | Hello, I am an automated registration bot. I help manage the registration process by checking your registration against a set of [AutoMerge guidelines](https://juliaregistries.github.io/RegistryCI.jl/stable/guidelines/). If all these guidelines are met, this pull request will be merged automatically, completing your registration. It is **strongly recommended** to follow the guidelines, since otherwise the pull request needs to be manually reviewed and merged by a human.
## 1. [AutoMerge Guidelines](https://juliaregistries.github.io/RegistryCI.jl/stable/guidelines/) which are not met ❌
- The following dependencies do not have a `[compat]` entry that is upper-bounded and only includes a finite number of breaking releases: julia
<details><summary>Extended explanation</summary>
Your package has a Project.toml file which might look something like the following:
```toml
name = "YourPackage"
uuid = "random id"
authors = ["Author Names"]
version = "major.minor"
[deps]
# Package dependencies
# ...
[compat]
# ...
```
Every package listed in `[deps]`, along with `julia` itself, must also be listed under `[compat]` (if you don't have a `[compat]` section, make one!). See the [Pkg docs](https://pkgdocs.julialang.org/v1/compatibility/) for the syntax for compatibility bounds, and [this documentation](https://juliaregistries.github.io/RegistryCI.jl/stable/guidelines/#Upper-bounded-%5Bcompat%5D-entries) for more on the kinds of compat bounds required for AutoMerge.
</details>
- Example guideline failed. Please fix it.
## 2. *Needs action*: here's what to do next
1. Please try to update your package to conform to these guidelines. The [General registry's README](https://github.com/JuliaRegistries/General/blob/master/README.md) has an FAQ that can help figure out how to do so.
2. After you have fixed the AutoMerge issues, simply retrigger Registrator, the same way you did in the initial registration. This will automatically update this pull request. You do not need to change the version number in your `Project.toml` file (unless the AutoMerge issue is that you skipped a version number).
If you need help fixing the AutoMerge issues, or want your pull request to be manually merged instead, please post a comment explaining what you need help with or why you would like this pull request to be manually merged.
## 3. To pause or stop registration
If you want to prevent this pull request from being auto-merged, simply leave a comment. If you want to post a comment without blocking auto-merging, you must include the text `[noblock]` in your comment.
_Tip: You can edit blocking comments to add `[noblock]` in order to unblock auto-merging._
<!-- [noblock] --> | RegistryCI | https://github.com/JuliaRegistries/RegistryCI.jl.git |
|
[
"MIT"
] | 10.7.0 | f0341c8179a869629d90fe549511d6ffaf1da9a1 | docs | 2893 | Hello, I am an automated registration bot. I help manage the registration process by checking your registration against a set of [AutoMerge guidelines](https://juliaregistries.github.io/RegistryCI.jl/stable/guidelines/). If all these guidelines are met, this pull request will be merged automatically, completing your registration. It is **strongly recommended** to follow the guidelines, since otherwise the pull request needs to be manually reviewed and merged by a human.
## 1. [AutoMerge Guidelines](https://juliaregistries.github.io/RegistryCI.jl/stable/guidelines/) which are not met ❌
- The following dependencies do not have a `[compat]` entry that is upper-bounded and only includes a finite number of breaking releases: julia
<details><summary>Extended explanation</summary>
Your package has a Project.toml file which might look something like the following:
```toml
name = "YourPackage"
uuid = "random id"
authors = ["Author Names"]
version = "major.minor"
[deps]
# Package dependencies
# ...
[compat]
# ...
```
Every package listed in `[deps]`, along with `julia` itself, must also be listed under `[compat]` (if you don't have a `[compat]` section, make one!). See the [Pkg docs](https://pkgdocs.julialang.org/v1/compatibility/) for the syntax for compatibility bounds, and [this documentation](https://juliaregistries.github.io/RegistryCI.jl/stable/guidelines/#Upper-bounded-%5Bcompat%5D-entries) for more on the kinds of compat bounds required for AutoMerge.
</details>
- Example guideline failed. Please fix it.
## 2. *Needs action*: here's what to do next
1. Please try to update your package to conform to these guidelines. The [General registry's README](https://github.com/JuliaRegistries/General/blob/master/README.md) has an FAQ that can help figure out how to do so.
2. After you have fixed the AutoMerge issues, simply retrigger Registrator, the same way you did in the initial registration. This will automatically update this pull request. You do not need to change the version number in your `Project.toml` file (unless the AutoMerge issue is that you skipped a version number).
If you need help fixing the AutoMerge issues, or want your pull request to be manually merged instead, please post a comment explaining what you need help with or why you would like this pull request to be manually merged. Then, send a message to the `#pkg-registration` channel in the [public Julia Slack](https://julialang.org/slack/) for better visibility.
## 3. To pause or stop registration
If you want to prevent this pull request from being auto-merged, simply leave a comment. If you want to post a comment without blocking auto-merging, you must include the text `[noblock]` in your comment.
_Tip: You can edit blocking comments to add `[noblock]` in order to unblock auto-merging._
<!-- [noblock] --> | RegistryCI | https://github.com/JuliaRegistries/RegistryCI.jl.git |
|
[
"MIT"
] | 10.7.0 | f0341c8179a869629d90fe549511d6ffaf1da9a1 | docs | 3183 | Hello, I am an automated registration bot. I help manage the registration process by checking your registration against a set of [AutoMerge guidelines](https://juliaregistries.github.io/RegistryCI.jl/stable/guidelines/). If all these guidelines are met, this pull request will be merged automatically, completing your registration. It is **strongly recommended** to follow the guidelines, since otherwise the pull request needs to be manually reviewed and merged by a human.
## 1. [AutoMerge Guidelines](https://juliaregistries.github.io/RegistryCI.jl/stable/guidelines/) which are not met ❌
- The following dependencies do not have a `[compat]` entry that is upper-bounded and only includes a finite number of breaking releases: julia
<details><summary>Extended explanation</summary>
Your package has a Project.toml file which might look something like the following:
```toml
name = "YourPackage"
uuid = "random id"
authors = ["Author Names"]
version = "major.minor"
[deps]
# Package dependencies
# ...
[compat]
# ...
```
Every package listed in `[deps]`, along with `julia` itself, must also be listed under `[compat]` (if you don't have a `[compat]` section, make one!). See the [Pkg docs](https://pkgdocs.julialang.org/v1/compatibility/) for the syntax for compatibility bounds, and [this documentation](https://juliaregistries.github.io/RegistryCI.jl/stable/guidelines/#Upper-bounded-%5Bcompat%5D-entries) for more on the kinds of compat bounds required for AutoMerge.
</details>
- Example guideline failed. Please fix it.
## 2. *Needs action*: here's what to do next
1. Please try to update your package to conform to these guidelines. The [General registry's README](https://github.com/JuliaRegistries/General/blob/master/README.md) has an FAQ that can help figure out how to do so.
2. After you have fixed the AutoMerge issues, simply retrigger Registrator, the same way you did in the initial registration. This will automatically update this pull request. You do not need to change the version number in your `Project.toml` file (unless the AutoMerge issue is that you skipped a version number).
If you need help fixing the AutoMerge issues, or want your pull request to be manually merged instead, please post a comment explaining what you need help with or why you would like this pull request to be manually merged.
## 3. Declare v1.0?
On a separate note, I see that you are registering a release with a version number of the form `v0.X.Y`.
Does your package have a stable public API? If so, then it's time for you to register version `v1.0.0` of your package. (This is not a requirement. It's just a recommendation.)
If your package does not yet have a stable public API, then of course you are not yet ready to release version `v1.0.0`.
## 4. To pause or stop registration
If you want to prevent this pull request from being auto-merged, simply leave a comment. If you want to post a comment without blocking auto-merging, you must include the text `[noblock]` in your comment.
_Tip: You can edit blocking comments to add `[noblock]` in order to unblock auto-merging._
<!-- [noblock] --> | RegistryCI | https://github.com/JuliaRegistries/RegistryCI.jl.git |
|
[
"MIT"
] | 10.7.0 | f0341c8179a869629d90fe549511d6ffaf1da9a1 | docs | 3320 | Hello, I am an automated registration bot. I help manage the registration process by checking your registration against a set of [AutoMerge guidelines](https://juliaregistries.github.io/RegistryCI.jl/stable/guidelines/). If all these guidelines are met, this pull request will be merged automatically, completing your registration. It is **strongly recommended** to follow the guidelines, since otherwise the pull request needs to be manually reviewed and merged by a human.
## 1. [AutoMerge Guidelines](https://juliaregistries.github.io/RegistryCI.jl/stable/guidelines/) which are not met ❌
- The following dependencies do not have a `[compat]` entry that is upper-bounded and only includes a finite number of breaking releases: julia
<details><summary>Extended explanation</summary>
Your package has a Project.toml file which might look something like the following:
```toml
name = "YourPackage"
uuid = "random id"
authors = ["Author Names"]
version = "major.minor"
[deps]
# Package dependencies
# ...
[compat]
# ...
```
Every package listed in `[deps]`, along with `julia` itself, must also be listed under `[compat]` (if you don't have a `[compat]` section, make one!). See the [Pkg docs](https://pkgdocs.julialang.org/v1/compatibility/) for the syntax for compatibility bounds, and [this documentation](https://juliaregistries.github.io/RegistryCI.jl/stable/guidelines/#Upper-bounded-%5Bcompat%5D-entries) for more on the kinds of compat bounds required for AutoMerge.
</details>
- Example guideline failed. Please fix it.
## 2. *Needs action*: here's what to do next
1. Please try to update your package to conform to these guidelines. The [General registry's README](https://github.com/JuliaRegistries/General/blob/master/README.md) has an FAQ that can help figure out how to do so.
2. After you have fixed the AutoMerge issues, simply retrigger Registrator, the same way you did in the initial registration. This will automatically update this pull request. You do not need to change the version number in your `Project.toml` file (unless the AutoMerge issue is that you skipped a version number).
If you need help fixing the AutoMerge issues, or want your pull request to be manually merged instead, please post a comment explaining what you need help with or why you would like this pull request to be manually merged. Then, send a message to the `#pkg-registration` channel in the [public Julia Slack](https://julialang.org/slack/) for better visibility.
## 3. Declare v1.0?
On a separate note, I see that you are registering a release with a version number of the form `v0.X.Y`.
Does your package have a stable public API? If so, then it's time for you to register version `v1.0.0` of your package. (This is not a requirement. It's just a recommendation.)
If your package does not yet have a stable public API, then of course you are not yet ready to release version `v1.0.0`.
## 4. To pause or stop registration
If you want to prevent this pull request from being auto-merged, simply leave a comment. If you want to post a comment without blocking auto-merging, you must include the text `[noblock]` in your comment.
_Tip: You can edit blocking comments to add `[noblock]` in order to unblock auto-merging._
<!-- [noblock] --> | RegistryCI | https://github.com/JuliaRegistries/RegistryCI.jl.git |
|
[
"MIT"
] | 10.7.0 | f0341c8179a869629d90fe549511d6ffaf1da9a1 | docs | 2756 | Hello, I am an automated registration bot. I help manage the registration process by checking your registration against a set of [AutoMerge guidelines](https://juliaregistries.github.io/RegistryCI.jl/stable/guidelines/). If all these guidelines are met, this pull request will be merged automatically, completing your registration. It is **strongly recommended** to follow the guidelines, since otherwise the pull request needs to be manually reviewed and merged by a human.
## 1. [AutoMerge Guidelines](https://juliaregistries.github.io/RegistryCI.jl/stable/guidelines/) which are not met ❌
- The following dependencies do not have a `[compat]` entry that is upper-bounded and only includes a finite number of breaking releases: julia
<details><summary>Extended explanation</summary>
Your package has a Project.toml file which might look something like the following:
```toml
name = "YourPackage"
uuid = "random id"
authors = ["Author Names"]
version = "major.minor"
[deps]
# Package dependencies
# ...
[compat]
# ...
```
Every package listed in `[deps]`, along with `julia` itself, must also be listed under `[compat]` (if you don't have a `[compat]` section, make one!). See the [Pkg docs](https://pkgdocs.julialang.org/v1/compatibility/) for the syntax for compatibility bounds, and [this documentation](https://juliaregistries.github.io/RegistryCI.jl/stable/guidelines/#Upper-bounded-%5Bcompat%5D-entries) for more on the kinds of compat bounds required for AutoMerge.
</details>
- Example guideline failed. Please fix it.
## 2. *Needs action*: here's what to do next
1. Please try to update your package to conform to these guidelines. The [General registry's README](https://github.com/JuliaRegistries/General/blob/master/README.md) has an FAQ that can help figure out how to do so.
2. After you have fixed the AutoMerge issues, simply retrigger Registrator, the same way you did in the initial registration. This will automatically update this pull request. You do not need to change the version number in your `Project.toml` file (unless the AutoMerge issue is that you skipped a version number).
If you need help fixing the AutoMerge issues, or want your pull request to be manually merged instead, please post a comment explaining what you need help with or why you would like this pull request to be manually merged.
## 3. To pause or stop registration
If you want to prevent this pull request from being auto-merged, simply leave a comment. If you want to post a comment without blocking auto-merging, you must include the text `[noblock]` in your comment.
_Tip: You can edit blocking comments to add `[noblock]` in order to unblock auto-merging._
<!-- [noblock] --> | RegistryCI | https://github.com/JuliaRegistries/RegistryCI.jl.git |
|
[
"MIT"
] | 10.7.0 | f0341c8179a869629d90fe549511d6ffaf1da9a1 | docs | 2893 | Hello, I am an automated registration bot. I help manage the registration process by checking your registration against a set of [AutoMerge guidelines](https://juliaregistries.github.io/RegistryCI.jl/stable/guidelines/). If all these guidelines are met, this pull request will be merged automatically, completing your registration. It is **strongly recommended** to follow the guidelines, since otherwise the pull request needs to be manually reviewed and merged by a human.
## 1. [AutoMerge Guidelines](https://juliaregistries.github.io/RegistryCI.jl/stable/guidelines/) which are not met ❌
- The following dependencies do not have a `[compat]` entry that is upper-bounded and only includes a finite number of breaking releases: julia
<details><summary>Extended explanation</summary>
Your package has a Project.toml file which might look something like the following:
```toml
name = "YourPackage"
uuid = "random id"
authors = ["Author Names"]
version = "major.minor"
[deps]
# Package dependencies
# ...
[compat]
# ...
```
Every package listed in `[deps]`, along with `julia` itself, must also be listed under `[compat]` (if you don't have a `[compat]` section, make one!). See the [Pkg docs](https://pkgdocs.julialang.org/v1/compatibility/) for the syntax for compatibility bounds, and [this documentation](https://juliaregistries.github.io/RegistryCI.jl/stable/guidelines/#Upper-bounded-%5Bcompat%5D-entries) for more on the kinds of compat bounds required for AutoMerge.
</details>
- Example guideline failed. Please fix it.
## 2. *Needs action*: here's what to do next
1. Please try to update your package to conform to these guidelines. The [General registry's README](https://github.com/JuliaRegistries/General/blob/master/README.md) has an FAQ that can help figure out how to do so.
2. After you have fixed the AutoMerge issues, simply retrigger Registrator, the same way you did in the initial registration. This will automatically update this pull request. You do not need to change the version number in your `Project.toml` file (unless the AutoMerge issue is that you skipped a version number).
If you need help fixing the AutoMerge issues, or want your pull request to be manually merged instead, please post a comment explaining what you need help with or why you would like this pull request to be manually merged. Then, send a message to the `#pkg-registration` channel in the [public Julia Slack](https://julialang.org/slack/) for better visibility.
## 3. To pause or stop registration
If you want to prevent this pull request from being auto-merged, simply leave a comment. If you want to post a comment without blocking auto-merging, you must include the text `[noblock]` in your comment.
_Tip: You can edit blocking comments to add `[noblock]` in order to unblock auto-merging._
<!-- [noblock] --> | RegistryCI | https://github.com/JuliaRegistries/RegistryCI.jl.git |
|
[
"MIT"
] | 10.7.0 | f0341c8179a869629d90fe549511d6ffaf1da9a1 | docs | 1292 | Hello, I am an automated registration bot. I help manage the registration process by checking your registration against a set of [AutoMerge guidelines](https://juliaregistries.github.io/RegistryCI.jl/stable/guidelines/). If all these guidelines are met, this pull request will be merged automatically, completing your registration. It is **strongly recommended** to follow the guidelines, since otherwise the pull request needs to be manually reviewed and merged by a human.
## 1. New package registration
Please make sure that you have read the [package naming guidelines](https://julialang.github.io/Pkg.jl/dev/creating-packages/#Package-naming-guidelines-1).
## 2. [AutoMerge Guidelines](https://juliaregistries.github.io/RegistryCI.jl/stable/guidelines/) are all met! ✅
Your new package registration met all of the guidelines for auto-merging and is scheduled to be merged when the mandatory waiting period (3 days) has elapsed.
## 3. To pause or stop registration
If you want to prevent this pull request from being auto-merged, simply leave a comment. If you want to post a comment without blocking auto-merging, you must include the text `[noblock]` in your comment.
_Tip: You can edit blocking comments to add `[noblock]` in order to unblock auto-merging._
<!-- [noblock] --> | RegistryCI | https://github.com/JuliaRegistries/RegistryCI.jl.git |
|
[
"MIT"
] | 10.7.0 | f0341c8179a869629d90fe549511d6ffaf1da9a1 | docs | 1073 | Hello, I am an automated registration bot. I help manage the registration process by checking your registration against a set of [AutoMerge guidelines](https://juliaregistries.github.io/RegistryCI.jl/stable/guidelines/). If all these guidelines are met, this pull request will be merged automatically, completing your registration. It is **strongly recommended** to follow the guidelines, since otherwise the pull request needs to be manually reviewed and merged by a human.
## 1. [AutoMerge Guidelines](https://juliaregistries.github.io/RegistryCI.jl/stable/guidelines/) are all met! ✅
Your new `_jll` package registration met all of the guidelines for auto-merging and is scheduled to be merged in the next round.
## 2. To pause or stop registration
If you want to prevent this pull request from being auto-merged, simply leave a comment. If you want to post a comment without blocking auto-merging, you must include the text `[noblock]` in your comment.
_Tip: You can edit blocking comments to add `[noblock]` in order to unblock auto-merging._
<!-- [noblock] --> | RegistryCI | https://github.com/JuliaRegistries/RegistryCI.jl.git |
|
[
"MIT"
] | 10.7.0 | f0341c8179a869629d90fe549511d6ffaf1da9a1 | docs | 1292 | Hello, I am an automated registration bot. I help manage the registration process by checking your registration against a set of [AutoMerge guidelines](https://juliaregistries.github.io/RegistryCI.jl/stable/guidelines/). If all these guidelines are met, this pull request will be merged automatically, completing your registration. It is **strongly recommended** to follow the guidelines, since otherwise the pull request needs to be manually reviewed and merged by a human.
## 1. New package registration
Please make sure that you have read the [package naming guidelines](https://julialang.github.io/Pkg.jl/dev/creating-packages/#Package-naming-guidelines-1).
## 2. [AutoMerge Guidelines](https://juliaregistries.github.io/RegistryCI.jl/stable/guidelines/) are all met! ✅
Your new package registration met all of the guidelines for auto-merging and is scheduled to be merged when the mandatory waiting period (3 days) has elapsed.
## 3. To pause or stop registration
If you want to prevent this pull request from being auto-merged, simply leave a comment. If you want to post a comment without blocking auto-merging, you must include the text `[noblock]` in your comment.
_Tip: You can edit blocking comments to add `[noblock]` in order to unblock auto-merging._
<!-- [noblock] --> | RegistryCI | https://github.com/JuliaRegistries/RegistryCI.jl.git |
|
[
"MIT"
] | 10.7.0 | f0341c8179a869629d90fe549511d6ffaf1da9a1 | docs | 1073 | Hello, I am an automated registration bot. I help manage the registration process by checking your registration against a set of [AutoMerge guidelines](https://juliaregistries.github.io/RegistryCI.jl/stable/guidelines/). If all these guidelines are met, this pull request will be merged automatically, completing your registration. It is **strongly recommended** to follow the guidelines, since otherwise the pull request needs to be manually reviewed and merged by a human.
## 1. [AutoMerge Guidelines](https://juliaregistries.github.io/RegistryCI.jl/stable/guidelines/) are all met! ✅
Your new `_jll` package registration met all of the guidelines for auto-merging and is scheduled to be merged in the next round.
## 2. To pause or stop registration
If you want to prevent this pull request from being auto-merged, simply leave a comment. If you want to post a comment without blocking auto-merging, you must include the text `[noblock]` in your comment.
_Tip: You can edit blocking comments to add `[noblock]` in order to unblock auto-merging._
<!-- [noblock] --> | RegistryCI | https://github.com/JuliaRegistries/RegistryCI.jl.git |
|
[
"MIT"
] | 10.7.0 | f0341c8179a869629d90fe549511d6ffaf1da9a1 | docs | 1719 | Hello, I am an automated registration bot. I help manage the registration process by checking your registration against a set of [AutoMerge guidelines](https://juliaregistries.github.io/RegistryCI.jl/stable/guidelines/). If all these guidelines are met, this pull request will be merged automatically, completing your registration. It is **strongly recommended** to follow the guidelines, since otherwise the pull request needs to be manually reviewed and merged by a human.
## 1. New package registration
Please make sure that you have read the [package naming guidelines](https://julialang.github.io/Pkg.jl/dev/creating-packages/#Package-naming-guidelines-1).
## 2. [AutoMerge Guidelines](https://juliaregistries.github.io/RegistryCI.jl/stable/guidelines/) are all met! ✅
Your new package registration met all of the guidelines for auto-merging and is scheduled to be merged when the mandatory waiting period (3 days) has elapsed.
## 3. Declare v1.0?
On a separate note, I see that you are registering a release with a version number of the form `v0.X.Y`.
Does your package have a stable public API? If so, then it's time for you to register version `v1.0.0` of your package. (This is not a requirement. It's just a recommendation.)
If your package does not yet have a stable public API, then of course you are not yet ready to release version `v1.0.0`.
## 4. To pause or stop registration
If you want to prevent this pull request from being auto-merged, simply leave a comment. If you want to post a comment without blocking auto-merging, you must include the text `[noblock]` in your comment.
_Tip: You can edit blocking comments to add `[noblock]` in order to unblock auto-merging._
<!-- [noblock] --> | RegistryCI | https://github.com/JuliaRegistries/RegistryCI.jl.git |
|
[
"MIT"
] | 10.7.0 | f0341c8179a869629d90fe549511d6ffaf1da9a1 | docs | 1500 | Hello, I am an automated registration bot. I help manage the registration process by checking your registration against a set of [AutoMerge guidelines](https://juliaregistries.github.io/RegistryCI.jl/stable/guidelines/). If all these guidelines are met, this pull request will be merged automatically, completing your registration. It is **strongly recommended** to follow the guidelines, since otherwise the pull request needs to be manually reviewed and merged by a human.
## 1. [AutoMerge Guidelines](https://juliaregistries.github.io/RegistryCI.jl/stable/guidelines/) are all met! ✅
Your new `_jll` package registration met all of the guidelines for auto-merging and is scheduled to be merged in the next round.
## 2. Declare v1.0?
On a separate note, I see that you are registering a release with a version number of the form `v0.X.Y`.
Does your package have a stable public API? If so, then it's time for you to register version `v1.0.0` of your package. (This is not a requirement. It's just a recommendation.)
If your package does not yet have a stable public API, then of course you are not yet ready to release version `v1.0.0`.
## 3. To pause or stop registration
If you want to prevent this pull request from being auto-merged, simply leave a comment. If you want to post a comment without blocking auto-merging, you must include the text `[noblock]` in your comment.
_Tip: You can edit blocking comments to add `[noblock]` in order to unblock auto-merging._
<!-- [noblock] --> | RegistryCI | https://github.com/JuliaRegistries/RegistryCI.jl.git |
|
[
"MIT"
] | 10.7.0 | f0341c8179a869629d90fe549511d6ffaf1da9a1 | docs | 1292 | Hello, I am an automated registration bot. I help manage the registration process by checking your registration against a set of [AutoMerge guidelines](https://juliaregistries.github.io/RegistryCI.jl/stable/guidelines/). If all these guidelines are met, this pull request will be merged automatically, completing your registration. It is **strongly recommended** to follow the guidelines, since otherwise the pull request needs to be manually reviewed and merged by a human.
## 1. New package registration
Please make sure that you have read the [package naming guidelines](https://julialang.github.io/Pkg.jl/dev/creating-packages/#Package-naming-guidelines-1).
## 2. [AutoMerge Guidelines](https://juliaregistries.github.io/RegistryCI.jl/stable/guidelines/) are all met! ✅
Your new package registration met all of the guidelines for auto-merging and is scheduled to be merged when the mandatory waiting period (3 days) has elapsed.
## 3. To pause or stop registration
If you want to prevent this pull request from being auto-merged, simply leave a comment. If you want to post a comment without blocking auto-merging, you must include the text `[noblock]` in your comment.
_Tip: You can edit blocking comments to add `[noblock]` in order to unblock auto-merging._
<!-- [noblock] --> | RegistryCI | https://github.com/JuliaRegistries/RegistryCI.jl.git |
|
[
"MIT"
] | 10.7.0 | f0341c8179a869629d90fe549511d6ffaf1da9a1 | docs | 1073 | Hello, I am an automated registration bot. I help manage the registration process by checking your registration against a set of [AutoMerge guidelines](https://juliaregistries.github.io/RegistryCI.jl/stable/guidelines/). If all these guidelines are met, this pull request will be merged automatically, completing your registration. It is **strongly recommended** to follow the guidelines, since otherwise the pull request needs to be manually reviewed and merged by a human.
## 1. [AutoMerge Guidelines](https://juliaregistries.github.io/RegistryCI.jl/stable/guidelines/) are all met! ✅
Your new `_jll` package registration met all of the guidelines for auto-merging and is scheduled to be merged in the next round.
## 2. To pause or stop registration
If you want to prevent this pull request from being auto-merged, simply leave a comment. If you want to post a comment without blocking auto-merging, you must include the text `[noblock]` in your comment.
_Tip: You can edit blocking comments to add `[noblock]` in order to unblock auto-merging._
<!-- [noblock] --> | RegistryCI | https://github.com/JuliaRegistries/RegistryCI.jl.git |
|
[
"MIT"
] | 10.7.0 | f0341c8179a869629d90fe549511d6ffaf1da9a1 | docs | 1066 | Hello, I am an automated registration bot. I help manage the registration process by checking your registration against a set of [AutoMerge guidelines](https://juliaregistries.github.io/RegistryCI.jl/stable/guidelines/). If all these guidelines are met, this pull request will be merged automatically, completing your registration. It is **strongly recommended** to follow the guidelines, since otherwise the pull request needs to be manually reviewed and merged by a human.
## 1. [AutoMerge Guidelines](https://juliaregistries.github.io/RegistryCI.jl/stable/guidelines/) are all met! ✅
Your new version registration met all of the guidelines for auto-merging and is scheduled to be merged in the next round.
## 2. To pause or stop registration
If you want to prevent this pull request from being auto-merged, simply leave a comment. If you want to post a comment without blocking auto-merging, you must include the text `[noblock]` in your comment.
_Tip: You can edit blocking comments to add `[noblock]` in order to unblock auto-merging._
<!-- [noblock] --> | RegistryCI | https://github.com/JuliaRegistries/RegistryCI.jl.git |
|
[
"MIT"
] | 10.7.0 | f0341c8179a869629d90fe549511d6ffaf1da9a1 | docs | 1066 | Hello, I am an automated registration bot. I help manage the registration process by checking your registration against a set of [AutoMerge guidelines](https://juliaregistries.github.io/RegistryCI.jl/stable/guidelines/). If all these guidelines are met, this pull request will be merged automatically, completing your registration. It is **strongly recommended** to follow the guidelines, since otherwise the pull request needs to be manually reviewed and merged by a human.
## 1. [AutoMerge Guidelines](https://juliaregistries.github.io/RegistryCI.jl/stable/guidelines/) are all met! ✅
Your new version registration met all of the guidelines for auto-merging and is scheduled to be merged in the next round.
## 2. To pause or stop registration
If you want to prevent this pull request from being auto-merged, simply leave a comment. If you want to post a comment without blocking auto-merging, you must include the text `[noblock]` in your comment.
_Tip: You can edit blocking comments to add `[noblock]` in order to unblock auto-merging._
<!-- [noblock] --> | RegistryCI | https://github.com/JuliaRegistries/RegistryCI.jl.git |
|
[
"MIT"
] | 10.7.0 | f0341c8179a869629d90fe549511d6ffaf1da9a1 | docs | 1066 | Hello, I am an automated registration bot. I help manage the registration process by checking your registration against a set of [AutoMerge guidelines](https://juliaregistries.github.io/RegistryCI.jl/stable/guidelines/). If all these guidelines are met, this pull request will be merged automatically, completing your registration. It is **strongly recommended** to follow the guidelines, since otherwise the pull request needs to be manually reviewed and merged by a human.
## 1. [AutoMerge Guidelines](https://juliaregistries.github.io/RegistryCI.jl/stable/guidelines/) are all met! ✅
Your new version registration met all of the guidelines for auto-merging and is scheduled to be merged in the next round.
## 2. To pause or stop registration
If you want to prevent this pull request from being auto-merged, simply leave a comment. If you want to post a comment without blocking auto-merging, you must include the text `[noblock]` in your comment.
_Tip: You can edit blocking comments to add `[noblock]` in order to unblock auto-merging._
<!-- [noblock] --> | RegistryCI | https://github.com/JuliaRegistries/RegistryCI.jl.git |
|
[
"MIT"
] | 10.7.0 | f0341c8179a869629d90fe549511d6ffaf1da9a1 | docs | 1066 | Hello, I am an automated registration bot. I help manage the registration process by checking your registration against a set of [AutoMerge guidelines](https://juliaregistries.github.io/RegistryCI.jl/stable/guidelines/). If all these guidelines are met, this pull request will be merged automatically, completing your registration. It is **strongly recommended** to follow the guidelines, since otherwise the pull request needs to be manually reviewed and merged by a human.
## 1. [AutoMerge Guidelines](https://juliaregistries.github.io/RegistryCI.jl/stable/guidelines/) are all met! ✅
Your new version registration met all of the guidelines for auto-merging and is scheduled to be merged in the next round.
## 2. To pause or stop registration
If you want to prevent this pull request from being auto-merged, simply leave a comment. If you want to post a comment without blocking auto-merging, you must include the text `[noblock]` in your comment.
_Tip: You can edit blocking comments to add `[noblock]` in order to unblock auto-merging._
<!-- [noblock] --> | RegistryCI | https://github.com/JuliaRegistries/RegistryCI.jl.git |
|
[
"MIT"
] | 10.7.0 | f0341c8179a869629d90fe549511d6ffaf1da9a1 | docs | 1493 | Hello, I am an automated registration bot. I help manage the registration process by checking your registration against a set of [AutoMerge guidelines](https://juliaregistries.github.io/RegistryCI.jl/stable/guidelines/). If all these guidelines are met, this pull request will be merged automatically, completing your registration. It is **strongly recommended** to follow the guidelines, since otherwise the pull request needs to be manually reviewed and merged by a human.
## 1. [AutoMerge Guidelines](https://juliaregistries.github.io/RegistryCI.jl/stable/guidelines/) are all met! ✅
Your new version registration met all of the guidelines for auto-merging and is scheduled to be merged in the next round.
## 2. Declare v1.0?
On a separate note, I see that you are registering a release with a version number of the form `v0.X.Y`.
Does your package have a stable public API? If so, then it's time for you to register version `v1.0.0` of your package. (This is not a requirement. It's just a recommendation.)
If your package does not yet have a stable public API, then of course you are not yet ready to release version `v1.0.0`.
## 3. To pause or stop registration
If you want to prevent this pull request from being auto-merged, simply leave a comment. If you want to post a comment without blocking auto-merging, you must include the text `[noblock]` in your comment.
_Tip: You can edit blocking comments to add `[noblock]` in order to unblock auto-merging._
<!-- [noblock] --> | RegistryCI | https://github.com/JuliaRegistries/RegistryCI.jl.git |
|
[
"MIT"
] | 10.7.0 | f0341c8179a869629d90fe549511d6ffaf1da9a1 | docs | 1493 | Hello, I am an automated registration bot. I help manage the registration process by checking your registration against a set of [AutoMerge guidelines](https://juliaregistries.github.io/RegistryCI.jl/stable/guidelines/). If all these guidelines are met, this pull request will be merged automatically, completing your registration. It is **strongly recommended** to follow the guidelines, since otherwise the pull request needs to be manually reviewed and merged by a human.
## 1. [AutoMerge Guidelines](https://juliaregistries.github.io/RegistryCI.jl/stable/guidelines/) are all met! ✅
Your new version registration met all of the guidelines for auto-merging and is scheduled to be merged in the next round.
## 2. Declare v1.0?
On a separate note, I see that you are registering a release with a version number of the form `v0.X.Y`.
Does your package have a stable public API? If so, then it's time for you to register version `v1.0.0` of your package. (This is not a requirement. It's just a recommendation.)
If your package does not yet have a stable public API, then of course you are not yet ready to release version `v1.0.0`.
## 3. To pause or stop registration
If you want to prevent this pull request from being auto-merged, simply leave a comment. If you want to post a comment without blocking auto-merging, you must include the text `[noblock]` in your comment.
_Tip: You can edit blocking comments to add `[noblock]` in order to unblock auto-merging._
<!-- [noblock] --> | RegistryCI | https://github.com/JuliaRegistries/RegistryCI.jl.git |
|
[
"MIT"
] | 10.7.0 | f0341c8179a869629d90fe549511d6ffaf1da9a1 | docs | 1066 | Hello, I am an automated registration bot. I help manage the registration process by checking your registration against a set of [AutoMerge guidelines](https://juliaregistries.github.io/RegistryCI.jl/stable/guidelines/). If all these guidelines are met, this pull request will be merged automatically, completing your registration. It is **strongly recommended** to follow the guidelines, since otherwise the pull request needs to be manually reviewed and merged by a human.
## 1. [AutoMerge Guidelines](https://juliaregistries.github.io/RegistryCI.jl/stable/guidelines/) are all met! ✅
Your new version registration met all of the guidelines for auto-merging and is scheduled to be merged in the next round.
## 2. To pause or stop registration
If you want to prevent this pull request from being auto-merged, simply leave a comment. If you want to post a comment without blocking auto-merging, you must include the text `[noblock]` in your comment.
_Tip: You can edit blocking comments to add `[noblock]` in order to unblock auto-merging._
<!-- [noblock] --> | RegistryCI | https://github.com/JuliaRegistries/RegistryCI.jl.git |
|
[
"MIT"
] | 10.7.0 | f0341c8179a869629d90fe549511d6ffaf1da9a1 | docs | 1066 | Hello, I am an automated registration bot. I help manage the registration process by checking your registration against a set of [AutoMerge guidelines](https://juliaregistries.github.io/RegistryCI.jl/stable/guidelines/). If all these guidelines are met, this pull request will be merged automatically, completing your registration. It is **strongly recommended** to follow the guidelines, since otherwise the pull request needs to be manually reviewed and merged by a human.
## 1. [AutoMerge Guidelines](https://juliaregistries.github.io/RegistryCI.jl/stable/guidelines/) are all met! ✅
Your new version registration met all of the guidelines for auto-merging and is scheduled to be merged in the next round.
## 2. To pause or stop registration
If you want to prevent this pull request from being auto-merged, simply leave a comment. If you want to post a comment without blocking auto-merging, you must include the text `[noblock]` in your comment.
_Tip: You can edit blocking comments to add `[noblock]` in order to unblock auto-merging._
<!-- [noblock] --> | RegistryCI | https://github.com/JuliaRegistries/RegistryCI.jl.git |
|
[
"MIT"
] | 0.2.2 | 805af53b51077c382eafab33772073fcbfd83d11 | code | 158 | # execute this file in the docs directory with this
# julia --color=yes --project make.jl
using Documenter, SimplePadics
makedocs(; sitename="SimplePadics")
| SimplePadics | https://github.com/scheinerman/SimplePadics.jl.git |
|
[
"MIT"
] | 0.2.2 | 805af53b51077c382eafab33772073fcbfd83d11 | code | 902 | using SimplePadics, Primes
"""
sqrt_table(p::Int = 2, lo::Int = -20, hi::Int = 20)
Print out a table of `p`-adic square roots of integers
in the range `lo` to `hi`, skipping those that do not have
square roots.
"""
function sqrt_table(p::Int = 2, lo::Int = -20, hi::Int = 20)
for a = lo:hi
x = Padic{p}(a)
try
y = sqrt(x)
println("√", a, "\t", y)
catch
end
end
end
"""
has_i(p::Int)::Bool
Determine if `√-1` exists as a `p`-adic number.
"""
function has_i(p::Int)::Bool
a = Padic{p}(-1)
try
b = sqrt(a)
return true
catch
end
return false
end
"""
has_i_list(max_p::Int = 100)::Vector{Int}
Generate a list of primes, `p`, up to `max_p`
for which `√-1` exists as a `p`-adic number.
"""
function has_i_list(max_p::Int = 100)::Vector{Int}
[p for p in primes(max_p) if has_i(p)]
end
| SimplePadics | https://github.com/scheinerman/SimplePadics.jl.git |
|
[
"MIT"
] | 0.2.2 | 805af53b51077c382eafab33772073fcbfd83d11 | code | 2743 | module SimplePadics
using Base: String, prec_arrow, get_preferences
using Nemo, SimplePolynomials
_PF = PadicField
export Padic, Dyadic
const _DEFAULT_PRECISION = 10
_PREC = _DEFAULT_PRECISION # standard precision for p-adic numbers
export set_precision, get_precision
"""
set_precision(prec::Integer)
Controls the number of digits of precision for `Padic` numbers.
Without an argument, set the precision to a default value (`_DEFAULT_PRECISION`).
"""
function set_precision(prec::Integer = _DEFAULT_PRECISION)
@assert prec > 1 "Precision must be set to 2 or higher"
global _PREC = prec
end
"""
get_precision()
Return the number of digits of precision for `Padic` numbers.
"""
get_precision() = _PREC
"""
Padic
Constructor for `p`-adic numbers:
* `Padic{P}(n::Integer)`
* `Padic{P}(r::Rational)`
"""
struct Padic{P} <: Number
x::padic
function Padic{P}(s::Integer) where {P}
F = _PF(P, _PREC)
new(F(s))
end
function Padic{P}(r::Rational) where {P}
F = _PF(P, _PREC)
a = F(numerator(r)) // F(denominator(r))
new(a)
end
function Padic(s::padic) # conver Nemo padic to our Padic
F = s.parent
digits = F.prec_max
P = F.p
new{P}(s)
end
function Padic(s::Padic)
return s
end
end
"""
Dyadic
This is an abbrevation for `Padic{2}`.
"""
Dyadic = Padic{2}
function padic2str(a::padic)::String
r = lift(QQ, a)
t = numerator(r)
b = BigInt(denominator(r))
p = a.parent.p
prefix = "…"
digs = base(t, p)
if b > 1 # we need to shift to
ndigs = length(digs)
shift = Int(round(log(p, b)))
if shift < ndigs
digs = digs[1:end-shift] * "." * digs[end-shift+1:end]
elseif shift == ndigs
digs = "0." * digs
else
pad = "0"^(shift - ndigs + 1)
digs = pad * digs
digs = digs[1:end-shift] * "." * digs[end-shift+1:end]
end
end
suffix = valuation(a) >= 0 ? ".0" : ""
return prefix * digs * suffix
end
function padic2str(a::Padic{P})::String where {P}
s = padic2str(a.x)
return s * "_{$P}"
end
import Base.Multimedia.display
display(a::Padic) = println(padic2str(a))
import Base.show
show(io::IO, a::Padic) = print(io, padic2str(a))
import Base: digits
"""
digits(a::Padic)
Return the digits of `a`, starting from the right.
```
julia> a = Padic{7}(124//49)
…2.35_{7}
julia> digits(a)
3-element Vector{Int64}:
5
3
2
```
"""
function digits(a::Padic{P})::Vector{Int} where {P}
z = numerator(lift(QQ, a.x))
return digits(z, base = P)
end
include("arithmetic.jl")
include("functions.jl")
include("hensel.jl")
end # module
| SimplePadics | https://github.com/scheinerman/SimplePadics.jl.git |
|
[
"MIT"
] | 0.2.2 | 805af53b51077c382eafab33772073fcbfd83d11 | code | 774 | import Base: (+), (-), (*), (//), (/), (==), hash
(+)(a::Padic{P}, b::Padic{P}) where {P} = Padic(a.x + b.x)
(-)(a::Padic{P}) where {P} = Padic(-(a.x))
(-)(a::Padic{P}, b::Padic{P}) where {P} = a + (-b)
(*)(a::Padic{P}, b::Padic{P}) where {P} = Padic(a.x * b.x)
(/)(a::Padic{P}, b::Padic{P}) where {P} = Padic(a.x // b.x)
(==)(a::Padic{P}, b::Padic{Q}) where {P,Q} = (P == Q) && (a.x == b.x)
import Base: promote_rule
promote_rule(::Type{Padic{P}}, ::Type{T}) where {P,T<:Integer} = Padic{P}
promote_rule(::Type{Padic{P}}, ::Type{T}) where {P,T<:Rational} = Padic{P}
(//)(a::Padic, b::Number) = a / b
(//)(a::Number, b::Padic) = a / b
(//)(a::Padic, b::Padic) = a / b
hash(a::Padic{P}, h::UInt64) where {P} = hash(a.x, h)
hash(a::Padic{P}) where {P} = hash(a.x)
| SimplePadics | https://github.com/scheinerman/SimplePadics.jl.git |
|
[
"MIT"
] | 0.2.2 | 805af53b51077c382eafab33772073fcbfd83d11 | code | 613 | import Base: precision
"""
precision(a::Padic)
Return the number of digits of precision in `a`
"""
precision(a::Padic) = a.x.parent.prec_max
import Nemo: valuation, base
export base
"""
base(a::Padic)
Return the prime number `p` for this `p`-adic number.
"""
base(a::Padic{P}) where {P} = P
export valuation
valuation(a::Padic) = valuation(a.x)
import Base: sqrt, exp, log, abs
sqrt(a::Padic) = Padic(sqrt(a.x))
exp(a::Padic) = Padic(exp(a.x))
log(a::Padic) = Padic(log(a.x))
function abs(a::Padic{P}) where {P}
if a == 0
return 0.0
end
return Float64(P)^(-valuation(a))
end
| SimplePadics | https://github.com/scheinerman/SimplePadics.jl.git |
|
[
"MIT"
] | 0.2.2 | 805af53b51077c382eafab33772073fcbfd83d11 | code | 1666 | using SimplePadics, SimplePolynomials
"""
_clear_denominators(F::SimplePolynomial)
If `F` has rational coefficients, return a multiple of `F` that has integer
coefficients.
"""
function _clear_denominators(F::SimplePolynomial)
coes = SimplePolynomials.coeffs(F)
d = lcm(denominator.(coes))
return integerize(d * F)
end
"""
has_p_root(F::SimplePolynomial, p::Int)::Bool
Test if the polynomial `F` has a `p`-adic root for a prime `p`.
"""
function has_p_root(F::SimplePolynomial, p::Int)::Bool
b, a = _has_p_root(F, p)
return b
end
"""
_has_p_root(F::SimplePolynomial, p::Int)
Helper function for `has_p_root` that returns extra information
that is used by `p_root`.
"""
function _has_p_root(F::SimplePolynomial, p::Int)
F = _clear_denominators(F)
for a = 0:p-1
if F(a) % p == 0 && F'(a) % p != 0
return true, a
end
end
return false, -1
end
"""
p_root(F::SimplePolynomial, p::Int)
Find a `p`-adic root of the polynomial `F`.
"""
function p_root(F::SimplePolynomial, p::Int)
F = _clear_denominators(F)
(tst, a) = _has_p_root(F, p)
if !tst
error("This polynomial does not have a $p-adic root.")
end
prec = get_precision()
value = big(a)
P = big(p)
for t = 2:prec+5
PP = P^(t - 2)
for b = 0:p-1
x = b * PP + value
if F(x) % (PP * P) == 0
value = x
pv = Padic{p}(value)
if F(pv) == 0
return pv
end
break
end
end
end
return Padic{p}(value)
end
export has_p_root, p_root
| SimplePadics | https://github.com/scheinerman/SimplePadics.jl.git |
|
[
"MIT"
] | 0.2.2 | 805af53b51077c382eafab33772073fcbfd83d11 | code | 779 | using Test, SimplePadics, SimplePolynomials
x = Padic{5}(-1)
@test x * x == 1
@test x == -1
y = sqrt(x)
@test y * y == -1
@test x + x == 2x
@test x + 1 == 0
@test x - 1 == -Padic{5}(2)
@test valuation(x) == 0
@test valuation(x / 5) == -1
@test valuation(5x) == 1
@test base(x) == 5
@test x // 5 == x / 5
@test x / x == 1
@test x // x == Padic{5}(1)
y = exp(5x)
@test log(y) == -5
@test Padic{5}(2 // 3) * 3 == 2
s = string(x)
@test s[1] == '…'
@test s[end-5:end] == ".0_{5}"
a = Padic{17}(1000)
d = digits(a)
@test d[1] + 17 * d[2] + 17^2 * d[3] == 1000
set_precision(20)
@test get_precision() == 20
a = Padic{5}(100)
@test abs(1 / a) == 25
@test abs(a) == abs(-a)
@test abs(0 * a) == 0
x = getx()
F = x^2 + 1
@test has_p_root(F, 5)
t = p_root(F, 5)
@test F(t) == 0
| SimplePadics | https://github.com/scheinerman/SimplePadics.jl.git |
|
[
"MIT"
] | 0.2.2 | 805af53b51077c382eafab33772073fcbfd83d11 | docs | 5339 | # SimplePadics
Easy to use and nicely formatted [p-adic numbers](https://en.wikipedia.org/wiki/P-adic_number).
Everything rides on
[Nemo](https://github.com/Nemocas/Nemo.jl.git).
## Basics
This module provides the type `Padic{p}` to represent `p`-adic numbers (for prime `p`).
Numbers of this sort are created either with `Integer` or `Rational` arguments:
```
julia> using SimplePadics
julia> Padic{5}(82)
…312.0_{5}
julia> Padic{5}(1//15)
…313131313.2_{5}
```
For `p` equal to `2` we have the abbreviation `Dyadic` that is exacly equivalent to `Padic{2}`.
```
julia> Dyadic(1//10)
…1100110.1_{2}
```
The function `base` returns `p` for numbers of type `Padic{p}`:
```
julia> a = Padic{7}(100//49)
…2.02_{7}
julia> base(a)
7
```
## Arithmetic
The standard arithmetic operations (addition, subtraction, multiplication, division) may be performed with arguments that are both of the same `p`-adic type, or a mixture of a `p`-adic and an `Integer` or `Rational`. Some examples:
```
julia> a = Padic{7}(10)
…13.0_{7}
julia> a+1
…14.0_{7}
julia> 2a
…26.0_{7}
julia> a/a
…1.0_{7}
julia> inv(a)
…462046205.0_{7}
```
## Digits
When the prime `p` is greater than 7, we use letters to stand for digits beyond 9 (that is, `a` for ten, `b` for eleven, and so forth).
```
julia> a = Padic{17}(1000)
…37e.0_{17}
julia> 3 * 17^2 + 7 * 17 + 14
1000
```
To get the digits as a list of integers, use `digits(a)`. The first entry in the result is the most significant digit (rightmost).
```
julia> a = Padic{7}(124//49)
…2.35_{7}
julia> digits(a)
3-element Vector{Int64}:
5
3
2
```
See `valuation` to determine the location of the radix point.
```
julia> valuation(a)
-2
```
## Adjusting Precision
The precision of `Padic` numbers is globally controlled using the functions `set_precision` and `get_precision`.
Use `set_precision(n::Int)` to set the precision to `n` digits. Use `set_precision()` to
set the precision to the default value (10).
The function `get_precision()` returns the current setting.
> **Warning**: `Padic` numbers created with different precisions cannot be compared for equality or combined in operations.
```
julia> a = Padic{5}(-1)
…4444444444.0_{5}
julia> set_precision(20)
20
julia> b = Padic{5}(-1)
…44444444444444444444.0_{5}
julia> a == b
ERROR: Incompatible padic rings in padic operation
```
## Functions
The functions `sqrt`, `exp`, `log`, and `valuation` from Nemo are imported into this module. For example:
```
julia> a = Padic{5}(-1)
…4444444444.0_{5}
julia> sqrt(a)
…3032431212.0_{5}
julia> ans^2
…4444444444.0_{5}
julia> a = Padic{5}(500)
…4000.0_{5}
julia> valuation(a)
3
julia> 1/a
…3333333.334_{5}
julia> valuation(1/a)
-3
julia> abs(a)
0.008
julia> abs(1/a)
125.0
```
## Roots of Polynomials
Let `F` be a `SimplePolynomial` with integer or rational coefficients. The function `p_root(F,p)` returns a `p`-adic root of `F` (if one exists) or throws an error otherwise.
```
julia> using SimplePadics, SimplePolynomials
julia> x = getx()
x
julia> F = x^2 + 1
1 + x^2
julia> t = p_root(F,5)
…3032431212.0_{5}
julia> t^2 + 1
…0.0_{5}
julia> sqrt(Padic{5}(-1))
…3032431212.0_{5}
```
The function `has_p_root(F,p)` tests if a polynomial has a `p`-adic root.
Returns `true` if `F` has a root and `false` otherwise.
## Compatability with `LinearAlgebraX`
Matrices/vectors populated with `Padic` numbers can be used in the `LinearAlgebraX`
module. Some examples here:
```
julia> using LinearAlgebraX
julia> A = rand(Int,5,5) .% 10 # create a random matrix with entries between -9 and 9.
5×5 Matrix{Int64}:
-9 -5 -4 -9 -8
0 -1 9 -3 8
2 -9 0 0 -4
0 7 -6 -5 8
0 -5 6 -2 -6
julia> A = Padic{5}.(A) # convert those values to 5-adic numbers
5×5 Matrix{Padic{5}}:
…4444444431.0_{5} …44444444440.0_{5} …4444444441.0_{5} …4444444431.0_{5} …4444444432.0_{5}
…0.0_{5} …4444444444.0_{5} …14.0_{5} …4444444442.0_{5} …13.0_{5}
…2.0_{5} …4444444431.0_{5} …0.0_{5} …0.0_{5} …4444444441.0_{5}
…0.0_{5} …12.0_{5} …4444444434.0_{5} …44444444440.0_{5} …13.0_{5}
…0.0_{5} …44444444440.0_{5} …11.0_{5} …4444444443.0_{5} …4444444434.0_{5}
julia> detx(A)
…4441202132.0_{5}
julia> invx(A)
5×5 Matrix{Padic{5}}:
…4344224002.0_{5} …4441024033.0_{5} …1242400242.0_{5} …2100330003.0_{5} …211103034.0_{5}
…4333241114.0_{5} …2024323204.0_{5} …1141013103.0_{5} …3103232201.0_{5} …4420230301.0_{5}
…1011004214.0_{5} …3224241133.0_{5} …4324312303.0_{5} …404043040.0_{5} …2430224440.0_{5}
…1031224011.0_{5} …2022011034.0_{5} …2244123102.0_{5} …1312340431.0_{5} …23100104.0_{5}
…1324102422.0_{5} …2324440300.0_{5} …101223004.0_{5} …21033133.0_{5} …220320101.0_{5}
julia> A * ans
5×5 Matrix{Any}:
…1.0_{5} …0.0_{5} …0.0_{5} …0.0_{5} …0.0_{5}
…0.0_{5} …1.0_{5} …0.0_{5} …0.0_{5} …0.0_{5}
…0.0_{5} …0.0_{5} …1.0_{5} …0.0_{5} …0.0_{5}
…0.0_{5} …0.0_{5} …0.0_{5} …1.0_{5} …0.0_{5}
…0.0_{5} …0.0_{5} …0.0_{5} …0.0_{5} …1.0_{5}
julia> nullspacex(A[1:3,:])
5×2 Matrix{Padic{5}}:
…3414203434.0_{5} …2234314433.0_{5}
…3020203312.0_{5} …241004443.0_{5}
…3314221230.0_{5} …2120313420.0_{5}
…1.0_{5} …0.0_{5}
…0.0_{5} …1.0_{5}
```
| SimplePadics | https://github.com/scheinerman/SimplePadics.jl.git |
|
[
"MIT"
] | 0.2.2 | 805af53b51077c382eafab33772073fcbfd83d11 | docs | 5339 | # SimplePadics
Easy to use and nicely formatted [p-adic numbers](https://en.wikipedia.org/wiki/P-adic_number).
Everything rides on
[Nemo](https://github.com/Nemocas/Nemo.jl.git).
## Basics
This module provides the type `Padic{p}` to represent `p`-adic numbers (for prime `p`).
Numbers of this sort are created either with `Integer` or `Rational` arguments:
```
julia> using SimplePadics
julia> Padic{5}(82)
…312.0_{5}
julia> Padic{5}(1//15)
…313131313.2_{5}
```
For `p` equal to `2` we have the abbreviation `Dyadic` that is exacly equivalent to `Padic{2}`.
```
julia> Dyadic(1//10)
…1100110.1_{2}
```
The function `base` returns `p` for numbers of type `Padic{p}`:
```
julia> a = Padic{7}(100//49)
…2.02_{7}
julia> base(a)
7
```
## Arithmetic
The standard arithmetic operations (addition, subtraction, multiplication, division) may be performed with arguments that are both of the same `p`-adic type, or a mixture of a `p`-adic and an `Integer` or `Rational`. Some examples:
```
julia> a = Padic{7}(10)
…13.0_{7}
julia> a+1
…14.0_{7}
julia> 2a
…26.0_{7}
julia> a/a
…1.0_{7}
julia> inv(a)
…462046205.0_{7}
```
## Digits
When the prime `p` is greater than 7, we use letters to stand for digits beyond 9 (that is, `a` for ten, `b` for eleven, and so forth).
```
julia> a = Padic{17}(1000)
…37e.0_{17}
julia> 3 * 17^2 + 7 * 17 + 14
1000
```
To get the digits as a list of integers, use `digits(a)`. The first entry in the result is the most significant digit (rightmost).
```
julia> a = Padic{7}(124//49)
…2.35_{7}
julia> digits(a)
3-element Vector{Int64}:
5
3
2
```
See `valuation` to determine the location of the radix point.
```
julia> valuation(a)
-2
```
## Adjusting Precision
The precision of `Padic` numbers is globally controlled using the functions `set_precision` and `get_precision`.
Use `set_precision(n::Int)` to set the precision to `n` digits. Use `set_precision()` to
set the precision to the default value (10).
The function `get_precision()` returns the current setting.
> **Warning**: `Padic` numbers created with different precisions cannot be compared for equality or combined in operations.
```
julia> a = Padic{5}(-1)
…4444444444.0_{5}
julia> set_precision(20)
20
julia> b = Padic{5}(-1)
…44444444444444444444.0_{5}
julia> a == b
ERROR: Incompatible padic rings in padic operation
```
## Functions
The functions `sqrt`, `exp`, `log`, and `valuation` from Nemo are imported into this module. For example:
```
julia> a = Padic{5}(-1)
…4444444444.0_{5}
julia> sqrt(a)
…3032431212.0_{5}
julia> ans^2
…4444444444.0_{5}
julia> a = Padic{5}(500)
…4000.0_{5}
julia> valuation(a)
3
julia> 1/a
…3333333.334_{5}
julia> valuation(1/a)
-3
julia> abs(a)
0.008
julia> abs(1/a)
125.0
```
## Roots of Polynomials
Let `F` be a `SimplePolynomial` with integer or rational coefficients. The function `p_root(F,p)` returns a `p`-adic root of `F` (if one exists) or throws an error otherwise.
```
julia> using SimplePadics, SimplePolynomials
julia> x = getx()
x
julia> F = x^2 + 1
1 + x^2
julia> t = p_root(F,5)
…3032431212.0_{5}
julia> t^2 + 1
…0.0_{5}
julia> sqrt(Padic{5}(-1))
…3032431212.0_{5}
```
The function `has_p_root(F,p)` tests if a polynomial has a `p`-adic root.
Returns `true` if `F` has a root and `false` otherwise.
## Compatability with `LinearAlgebraX`
Matrices/vectors populated with `Padic` numbers can be used in the `LinearAlgebraX`
module. Some examples here:
```
julia> using LinearAlgebraX
julia> A = rand(Int,5,5) .% 10 # create a random matrix with entries between -9 and 9.
5×5 Matrix{Int64}:
-9 -5 -4 -9 -8
0 -1 9 -3 8
2 -9 0 0 -4
0 7 -6 -5 8
0 -5 6 -2 -6
julia> A = Padic{5}.(A) # convert those values to 5-adic numbers
5×5 Matrix{Padic{5}}:
…4444444431.0_{5} …44444444440.0_{5} …4444444441.0_{5} …4444444431.0_{5} …4444444432.0_{5}
…0.0_{5} …4444444444.0_{5} …14.0_{5} …4444444442.0_{5} …13.0_{5}
…2.0_{5} …4444444431.0_{5} …0.0_{5} …0.0_{5} …4444444441.0_{5}
…0.0_{5} …12.0_{5} …4444444434.0_{5} …44444444440.0_{5} …13.0_{5}
…0.0_{5} …44444444440.0_{5} …11.0_{5} …4444444443.0_{5} …4444444434.0_{5}
julia> detx(A)
…4441202132.0_{5}
julia> invx(A)
5×5 Matrix{Padic{5}}:
…4344224002.0_{5} …4441024033.0_{5} …1242400242.0_{5} …2100330003.0_{5} …211103034.0_{5}
…4333241114.0_{5} …2024323204.0_{5} …1141013103.0_{5} …3103232201.0_{5} …4420230301.0_{5}
…1011004214.0_{5} …3224241133.0_{5} …4324312303.0_{5} …404043040.0_{5} …2430224440.0_{5}
…1031224011.0_{5} …2022011034.0_{5} …2244123102.0_{5} …1312340431.0_{5} …23100104.0_{5}
…1324102422.0_{5} …2324440300.0_{5} …101223004.0_{5} …21033133.0_{5} …220320101.0_{5}
julia> A * ans
5×5 Matrix{Any}:
…1.0_{5} …0.0_{5} …0.0_{5} …0.0_{5} …0.0_{5}
…0.0_{5} …1.0_{5} …0.0_{5} …0.0_{5} …0.0_{5}
…0.0_{5} …0.0_{5} …1.0_{5} …0.0_{5} …0.0_{5}
…0.0_{5} …0.0_{5} …0.0_{5} …1.0_{5} …0.0_{5}
…0.0_{5} …0.0_{5} …0.0_{5} …0.0_{5} …1.0_{5}
julia> nullspacex(A[1:3,:])
5×2 Matrix{Padic{5}}:
…3414203434.0_{5} …2234314433.0_{5}
…3020203312.0_{5} …241004443.0_{5}
…3314221230.0_{5} …2120313420.0_{5}
…1.0_{5} …0.0_{5}
…0.0_{5} …1.0_{5}
```
| SimplePadics | https://github.com/scheinerman/SimplePadics.jl.git |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.