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.6.0 | a7dc7bfc2fc6638c18241bfcdb9d73c7dd256482 | docs | 25185 | # [Linear Algebra](@id man-linalg)
```@meta
DocTestSetup = :(using LinearAlgebra, SparseArrays, SuiteSparse)
```
除了(且作为一部分)对多维数组的支持,Julia 还提供了许多常见和实用的线性代数运算的本地实现,可通过 `using LinearAlgebra` 加载。
基本的运算,比如 [`tr`](@ref),[`det`](@ref) 和 [`inv`](@ref) 都是支持的:
```jldoctest
julia> A = [1 2 3; 4 1 6; 7 8 1]
3×3 Matrix{Int64}:
1 2 3
4 1 6
7 8 1
julia> tr(A)
3
julia> det(A)
104.0
julia> inv(A)
3×3 Matrix{Float64}:
-0.451923 0.211538 0.0865385
0.365385 -0.192308 0.0576923
0.240385 0.0576923 -0.0673077
```
还有其它实用的运算,比如寻找特征值或特征向量:
```jldoctest
julia> A = [-4. -17.; 2. 2.]
2×2 Matrix{Float64}:
-4.0 -17.0
2.0 2.0
julia> eigvals(A)
2-element Vector{ComplexF64}:
-1.0 - 5.0im
-1.0 + 5.0im
julia> eigvecs(A)
2×2 Matrix{ComplexF64}:
0.945905-0.0im 0.945905+0.0im
-0.166924+0.278207im -0.166924-0.278207im
```
此外,Julia 提供了多种[矩阵分解](@ref man-linalg-factorizations),通过将矩阵预先分解成更适合问题的形式(出于性能或内存上的原因),它们可用于加快问题的求解,如线性求解或矩阵求幂。更多有关信息请参阅文档 [`factorize`](@ref)。举个例子:
```jldoctest
julia> A = [1.5 2 -4; 3 -1 -6; -10 2.3 4]
3×3 Matrix{Float64}:
1.5 2.0 -4.0
3.0 -1.0 -6.0
-10.0 2.3 4.0
julia> factorize(A)
LU{Float64, Matrix{Float64}}
L factor:
3×3 Matrix{Float64}:
1.0 0.0 0.0
-0.15 1.0 0.0
-0.3 -0.132196 1.0
U factor:
3×3 Matrix{Float64}:
-10.0 2.3 4.0
0.0 2.345 -3.4
0.0 0.0 -5.24947
```
因为 `A` 不是埃尔米特、对称、三角、三对角或双对角矩阵,LU 分解也许是我们能做的最好分解。与之相比:
```jldoctest
julia> B = [1.5 2 -4; 2 -1 -3; -4 -3 5]
3×3 Matrix{Float64}:
1.5 2.0 -4.0
2.0 -1.0 -3.0
-4.0 -3.0 5.0
julia> factorize(B)
BunchKaufman{Float64, Matrix{Float64}}
D factor:
3×3 Tridiagonal{Float64, Vector{Float64}}:
-1.64286 0.0 ⋅
0.0 -2.8 0.0
⋅ 0.0 5.0
U factor:
3×3 UnitUpperTriangular{Float64, Matrix{Float64}}:
1.0 0.142857 -0.8
⋅ 1.0 -0.6
⋅ ⋅ 1.0
permutation:
3-element Vector{Int64}:
1
2
3
```
在这里,Julia 能够发现 `B` 确实是对称矩阵,并且使用一种更适当的分解。针对一个具有某些属性的矩阵,比如一个对称或三对角矩阵,往往有可能写出更高效的代码。Julia 提供了一些特殊的类型好让你可以根据矩阵所具有的属性「标记」它们。例如:
```jldoctest
julia> B = [1.5 2 -4; 2 -1 -3; -4 -3 5]
3×3 Matrix{Float64}:
1.5 2.0 -4.0
2.0 -1.0 -3.0
-4.0 -3.0 5.0
julia> sB = Symmetric(B)
3×3 Symmetric{Float64, Matrix{Float64}}:
1.5 2.0 -4.0
2.0 -1.0 -3.0
-4.0 -3.0 5.0
```
`sB` 已经被标记成(实)对称矩阵,所以对于之后可能在它上面执行的操作,例如特征因子化或矩阵-向量乘积,只引用矩阵的一半可以提高效率。举个例子:
```jldoctest
julia> B = [1.5 2 -4; 2 -1 -3; -4 -3 5]
3×3 Matrix{Float64}:
1.5 2.0 -4.0
2.0 -1.0 -3.0
-4.0 -3.0 5.0
julia> sB = Symmetric(B)
3×3 Symmetric{Float64, Matrix{Float64}}:
1.5 2.0 -4.0
2.0 -1.0 -3.0
-4.0 -3.0 5.0
julia> x = [1; 2; 3]
3-element Vector{Int64}:
1
2
3
julia> sB\x
3-element Vector{Float64}:
-1.7391304347826084
-1.1086956521739126
-1.4565217391304346
```
`\` 运算在这里执行线性求解。左除运算符相当强大,很容易写出紧凑、可读的代码,它足够灵活,可以求解各种线性方程组。
## 特殊矩阵
[具有特殊对称性和结构的矩阵](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=3274)经常在线性代数中出现并且与各种矩阵分解相关。
Julia 具有丰富的特殊矩阵类型,可以快速计算专门为特定矩阵类型开发的专用例程。
下表总结了在 Julia 中已经实现的特殊矩阵类型,以及为它们提供各种优化方法的钩子在 LAPACK 中是否可用。
| 类型 | 描述 |
|:----------------------------- |:--------------------------------------------------------------------------------------------- |
| [`Symmetric`](@ref) | [Symmetric matrix](https://en.wikipedia.org/wiki/Symmetric_matrix) |
| [`Hermitian`](@ref) | [Hermitian matrix](https://en.wikipedia.org/wiki/Hermitian_matrix) |
| [`UpperTriangular`](@ref) | 上[三角矩阵](https://en.wikipedia.org/wiki/Triangular_matrix) |
| [`UnitUpperTriangular`](@ref) | 单位上[三角矩阵](https://en.wikipedia.org/wiki/Triangular_matrix) with unit diagonal |
| [`LowerTriangular`](@ref) | 下[三角矩阵](https://en.wikipedia.org/wiki/Triangular_matrix) | |
| [`UnitLowerTriangular`](@ref) | 单位下[三角矩阵](https://en.wikipedia.org/wiki/Triangular_matrix) |
| [`UpperHessenberg`](@ref) | Upper [Hessenberg matrix](https://en.wikipedia.org/wiki/Hessenberg_matrix)
| [`Tridiagonal`](@ref) | [Tridiagonal matrix](https://en.wikipedia.org/wiki/Tridiagonal_matrix) |
| [`SymTridiagonal`](@ref) | 对称三对角矩阵 |
| [`Bidiagonal`](@ref) | 上/下[双对角矩阵](https://en.wikipedia.org/wiki/Bidiagonal_matrix) |
| [`Diagonal`](@ref) | [Diagonal matrix](https://en.wikipedia.org/wiki/Diagonal_matrix) |
| [`UniformScaling`](@ref) | [Uniform scaling operator](https://en.wikipedia.org/wiki/Uniform_scaling) |
### 基本运算
| 矩阵类型 | `+` | `-` | `*` | `\` | 具有优化方法的其它函数 |
|:----------------------------- |:--- |:--- |:--- |:--- |:----------------------------------------------------------- |
| [`Symmetric`](@ref) | | | | MV | [`inv`](@ref), [`sqrt`](@ref), [`exp`](@ref) |
| [`Hermitian`](@ref) | | | | MV | [`inv`](@ref), [`sqrt`](@ref), [`exp`](@ref) |
| [`UpperTriangular`](@ref) | | | MV | MV | [`inv`](@ref), [`det`](@ref) |
| [`UnitUpperTriangular`](@ref) | | | MV | MV | [`inv`](@ref), [`det`](@ref) |
| [`LowerTriangular`](@ref) | | | MV | MV | [`inv`](@ref), [`det`](@ref) |
| [`UnitLowerTriangular`](@ref) | | | MV | MV | [`inv`](@ref), [`det`](@ref) |
| [`UpperHessenberg`](@ref) | | | | MM | [`inv`](@ref), [`det`](@ref) |
| [`SymTridiagonal`](@ref) | M | M | MS | MV | [`eigmax`](@ref), [`eigmin`](@ref) |
| [`Tridiagonal`](@ref) | M | M | MS | MV | |
| [`Bidiagonal`](@ref) | M | M | MS | MV | |
| [`Diagonal`](@ref) | M | M | MV | MV | [`inv`](@ref), [`det`](@ref), [`logdet`](@ref), [`/`](@ref) |
| [`UniformScaling`](@ref) | M | M | MVS | MVS | [`/`](@ref) |
Legend:
| Key | 说明 |
|:---------- |:------------------------------------------------------------- |
| M(矩阵) | 针对矩阵与矩阵运算的优化方法可用 |
| V(向量) | 针对矩阵与向量运算的优化方法可用 |
| S(标量) | 针对矩阵与标量运算的优化方法可用 |
### 矩阵分解
| 矩阵类型 | LAPACK | [`eigen`](@ref) | [`eigvals`](@ref) | [`eigvecs`](@ref) | [`svd`](@ref) | [`svdvals`](@ref) |
|:----------------------------- |:------ |:------------- |:----------------- |:----------------- |:------------- |:----------------- |
| [`Symmetric`](@ref) | SY | | ARI | | | |
| [`Hermitian`](@ref) | HE | | ARI | | | |
| [`UpperTriangular`](@ref) | TR | A | A | A | | |
| [`UnitUpperTriangular`](@ref) | TR | A | A | A | | |
| [`LowerTriangular`](@ref) | TR | A | A | A | | |
| [`UnitLowerTriangular`](@ref) | TR | A | A | A | | |
| [`SymTridiagonal`](@ref) | ST | A | ARI | AV | | |
| [`Tridiagonal`](@ref) | GT | | | | | |
| [`Bidiagonal`](@ref) | BD | | | | A | A |
| [`Diagonal`](@ref) | DI | | A | | | |
图例:
| 键名 | 说明 | 例子 |
|:------------ |:------------------------------------------------------------------------------------------------------------------------------- |:-------------------- |
| A (all) | 找到所有特征值和/或特征向量的优化方法可用 | e.g. `eigvals(M)` |
| R (range) | 通过第 `ih` 个特征值寻找第 `il` 个特征值的优化方法可用 | `eigvals(M, il, ih)` |
| I (interval) | 寻找在区间 [`vl`, `vh`] 内的特征值的优化方法可用 | `eigvals(M, vl, vh)` |
| V (vectors) | 寻找对应于特征值 `x=[x1, x2,...]` 的特征向量的优化方法可用 | `eigvecs(M, x)` |
### 均匀缩放运算符
[`UniformScaling`](@ref) 运算符代表一个标量乘以单位运算符,`λ*I`。
单位运算符 `I` 被定义为常量,是 `UniformScaling` 的实例。
这些运算符的大小是通用的,并且会在二元运算符 [`+`](@ref),[`-`](@ref),[`*`](@ref) 和 [`\`](@ref) 中与另一个矩阵相匹配。
对于 `A+I` 和 `A-I` ,这意味着 `A` 必须是个方阵。
与单位运算符 `I` 相乘是一个空操作(除了检查比例因子是一),因此几乎没有开销。
来查看 `UniformScaling` 运算符的运行结果:
```jldoctest
julia> U = UniformScaling(2);
julia> a = [1 2; 3 4]
2×2 Matrix{Int64}:
1 2
3 4
julia> a + U
2×2 Matrix{Int64}:
3 2
3 6
julia> a * U
2×2 Matrix{Int64}:
2 4
6 8
julia> [a U]
2×4 Matrix{Int64}:
1 2 2 0
3 4 0 2
julia> b = [1 2 3; 4 5 6]
2×3 Matrix{Int64}:
1 2 3
4 5 6
julia> b - U
ERROR: DimensionMismatch("matrix is not square: dimensions are (2, 3)")
Stacktrace:
[...]
```
If you need to solve many systems of the form `(A+μI)x = b` for the same `A` and different `μ`, it might be beneficial
to first compute the Hessenberg factorization `F` of `A` via the [`hessenberg`](@ref) function.
Given `F`, Julia employs an efficient algorithm for `(F+μ*I) \ b` (equivalent to `(A+μ*I)x \ b`) and related
operations like determinants.
## [Matrix factorizations](@id man-linalg-factorizations)
[Matrix factorizations (a.k.a. matrix decompositions)](https://en.wikipedia.org/wiki/Matrix_decomposition)
compute the factorization of a matrix into a product of matrices, and are one of the central concepts
in linear algebra.
The following table summarizes the types of matrix factorizations that have been implemented in
Julia. Details of their associated methods can be found in the [Standard functions](@ref) section
of the Linear Algebra documentation.
| Type | Description |
|:------------------ |:-------------------------------------------------------------------------------------------------------------- |
| `BunchKaufman` | Bunch-Kaufman factorization |
| `Cholesky` | [Cholesky factorization](https://en.wikipedia.org/wiki/Cholesky_decomposition) |
| `CholeskyPivoted` | [Pivoted](https://en.wikipedia.org/wiki/Pivot_element) Cholesky factorization |
| `LDLt` | [LDL(T) factorization](https://en.wikipedia.org/wiki/Cholesky_decomposition#LDL_decomposition) |
| `LU` | [LU factorization](https://en.wikipedia.org/wiki/LU_decomposition) |
| `QR` | [QR factorization](https://en.wikipedia.org/wiki/QR_decomposition) |
| `QRCompactWY` | Compact WY form of the QR factorization |
| `QRPivoted` | Pivoted [QR factorization](https://en.wikipedia.org/wiki/QR_decomposition) |
| `LQ` | [QR factorization](https://en.wikipedia.org/wiki/QR_decomposition) of `transpose(A)` |
| `Hessenberg` | [Hessenberg decomposition](http://mathworld.wolfram.com/HessenbergDecomposition.html) |
| `Eigen` | [Spectral decomposition](https://en.wikipedia.org/wiki/Eigendecomposition_of_a_matrix) |
| `GeneralizedEigen` | [Generalized spectral decomposition](https://en.wikipedia.org/wiki/Eigendecomposition_of_a_matrix#Generalized_eigenvalue_problem) |
| `SVD` | [Singular value decomposition](https://en.wikipedia.org/wiki/Singular_value_decomposition) |
| `GeneralizedSVD` | [Generalized SVD](https://en.wikipedia.org/wiki/Generalized_singular_value_decomposition#Higher_order_version) |
| `Schur` | [Schur decomposition](https://en.wikipedia.org/wiki/Schur_decomposition) |
| `GeneralizedSchur` | [Generalized Schur decomposition](https://en.wikipedia.org/wiki/Schur_decomposition#Generalized_Schur_decomposition) |
## Standard functions
Linear algebra functions in Julia are largely implemented by calling functions from [LAPACK](http://www.netlib.org/lapack/). Sparse matrix factorizations call functions from [SuiteSparse](http://suitesparse.com). Other sparse solvers are available as Julia packages.
```@docs
Base.:*(::AbstractMatrix, ::AbstractMatrix)
Base.:\(::AbstractMatrix, ::AbstractVecOrMat)
LinearAlgebra.SingularException
LinearAlgebra.PosDefException
LinearAlgebra.ZeroPivotException
LinearAlgebra.dot
LinearAlgebra.dot(::Any, ::Any, ::Any)
LinearAlgebra.cross
LinearAlgebra.factorize
LinearAlgebra.Diagonal
LinearAlgebra.Bidiagonal
LinearAlgebra.SymTridiagonal
LinearAlgebra.Tridiagonal
LinearAlgebra.Symmetric
LinearAlgebra.Hermitian
LinearAlgebra.LowerTriangular
LinearAlgebra.UpperTriangular
LinearAlgebra.UnitLowerTriangular
LinearAlgebra.UnitUpperTriangular
LinearAlgebra.UpperHessenberg
LinearAlgebra.UniformScaling
LinearAlgebra.I
LinearAlgebra.UniformScaling(::Integer)
LinearAlgebra.Factorization
LinearAlgebra.LU
LinearAlgebra.lu
LinearAlgebra.lu!
LinearAlgebra.Cholesky
LinearAlgebra.CholeskyPivoted
LinearAlgebra.cholesky
LinearAlgebra.cholesky!
LinearAlgebra.lowrankupdate
LinearAlgebra.lowrankdowndate
LinearAlgebra.lowrankupdate!
LinearAlgebra.lowrankdowndate!
LinearAlgebra.LDLt
LinearAlgebra.ldlt
LinearAlgebra.ldlt!
LinearAlgebra.QR
LinearAlgebra.QRCompactWY
LinearAlgebra.QRPivoted
LinearAlgebra.qr
LinearAlgebra.qr!
LinearAlgebra.LQ
LinearAlgebra.lq
LinearAlgebra.lq!
LinearAlgebra.BunchKaufman
LinearAlgebra.bunchkaufman
LinearAlgebra.bunchkaufman!
LinearAlgebra.Eigen
LinearAlgebra.GeneralizedEigen
LinearAlgebra.eigvals
LinearAlgebra.eigvals!
LinearAlgebra.eigmax
LinearAlgebra.eigmin
LinearAlgebra.eigvecs
LinearAlgebra.eigen
LinearAlgebra.eigen!
LinearAlgebra.Hessenberg
LinearAlgebra.hessenberg
LinearAlgebra.hessenberg!
LinearAlgebra.Schur
LinearAlgebra.GeneralizedSchur
LinearAlgebra.schur
LinearAlgebra.schur!
LinearAlgebra.ordschur
LinearAlgebra.ordschur!
LinearAlgebra.SVD
LinearAlgebra.GeneralizedSVD
LinearAlgebra.svd
LinearAlgebra.svd!
LinearAlgebra.svdvals
LinearAlgebra.svdvals!
LinearAlgebra.Givens
LinearAlgebra.givens
LinearAlgebra.triu
LinearAlgebra.triu!
LinearAlgebra.tril
LinearAlgebra.tril!
LinearAlgebra.diagind
LinearAlgebra.diag
LinearAlgebra.diagm
LinearAlgebra.rank
LinearAlgebra.norm
LinearAlgebra.opnorm
LinearAlgebra.normalize!
LinearAlgebra.normalize
LinearAlgebra.cond
LinearAlgebra.condskeel
LinearAlgebra.tr
LinearAlgebra.det
LinearAlgebra.logdet
LinearAlgebra.logabsdet
Base.inv(::AbstractMatrix)
LinearAlgebra.pinv
LinearAlgebra.nullspace
Base.kron
Base.kron!
LinearAlgebra.exp(::StridedMatrix{<:LinearAlgebra.BlasFloat})
Base.cis(::AbstractMatrix)
Base.:^(::AbstractMatrix, ::Number)
Base.:^(::Number, ::AbstractMatrix)
LinearAlgebra.log(::StridedMatrix)
LinearAlgebra.sqrt(::StridedMatrix{<:Real})
LinearAlgebra.cos(::StridedMatrix{<:Real})
LinearAlgebra.sin(::StridedMatrix{<:Real})
LinearAlgebra.sincos(::StridedMatrix{<:Real})
LinearAlgebra.tan(::StridedMatrix{<:Real})
LinearAlgebra.sec(::StridedMatrix)
LinearAlgebra.csc(::StridedMatrix)
LinearAlgebra.cot(::StridedMatrix)
LinearAlgebra.cosh(::StridedMatrix)
LinearAlgebra.sinh(::StridedMatrix)
LinearAlgebra.tanh(::StridedMatrix)
LinearAlgebra.sech(::StridedMatrix)
LinearAlgebra.csch(::StridedMatrix)
LinearAlgebra.coth(::StridedMatrix)
LinearAlgebra.acos(::StridedMatrix)
LinearAlgebra.asin(::StridedMatrix)
LinearAlgebra.atan(::StridedMatrix)
LinearAlgebra.asec(::StridedMatrix)
LinearAlgebra.acsc(::StridedMatrix)
LinearAlgebra.acot(::StridedMatrix)
LinearAlgebra.acosh(::StridedMatrix)
LinearAlgebra.asinh(::StridedMatrix)
LinearAlgebra.atanh(::StridedMatrix)
LinearAlgebra.asech(::StridedMatrix)
LinearAlgebra.acsch(::StridedMatrix)
LinearAlgebra.acoth(::StridedMatrix)
LinearAlgebra.lyap
LinearAlgebra.sylvester
LinearAlgebra.issuccess
LinearAlgebra.issymmetric
LinearAlgebra.isposdef
LinearAlgebra.isposdef!
LinearAlgebra.istril
LinearAlgebra.istriu
LinearAlgebra.isdiag
LinearAlgebra.ishermitian
Base.transpose
LinearAlgebra.transpose!
LinearAlgebra.Transpose
Base.adjoint
LinearAlgebra.adjoint!
LinearAlgebra.Adjoint
Base.copy(::Union{Transpose,Adjoint})
LinearAlgebra.stride1
LinearAlgebra.checksquare
LinearAlgebra.peakflops
```
## Low-level matrix operations
In many cases there are in-place versions of matrix operations that allow you to supply
a pre-allocated output vector or matrix. This is useful when optimizing critical code in order
to avoid the overhead of repeated allocations. These in-place operations are suffixed with `!`
below (e.g. `mul!`) according to the usual Julia convention.
```@docs
LinearAlgebra.mul!
LinearAlgebra.lmul!
LinearAlgebra.rmul!
LinearAlgebra.ldiv!
LinearAlgebra.rdiv!
```
## BLAS functions
In Julia (as in much of scientific computation), dense linear-algebra operations are based on
the [LAPACK library](http://www.netlib.org/lapack/), which in turn is built on top of basic linear-algebra
building-blocks known as the [BLAS](http://www.netlib.org/blas/). There are highly optimized
implementations of BLAS available for every computer architecture, and sometimes in high-performance
linear algebra routines it is useful to call the BLAS functions directly.
`LinearAlgebra.BLAS` provides wrappers for some of the BLAS functions. Those BLAS functions
that overwrite one of the input arrays have names ending in `'!'`. Usually, a BLAS function has
four methods defined, for [`Float64`](@ref), [`Float32`](@ref), `ComplexF64`, and `ComplexF32` arrays.
### [BLAS character arguments](@id stdlib-blas-chars)
Many BLAS functions accept arguments that determine whether to transpose an argument (`trans`),
which triangle of a matrix to reference (`uplo` or `ul`),
whether the diagonal of a triangular matrix can be assumed to
be all ones (`dA`) or which side of a matrix multiplication
the input argument belongs on (`side`). The possibilities are:
#### [Multiplication order](@id stdlib-blas-side)
| `side` | Meaning |
|:-------|:--------------------------------------------------------------------|
| `'L'` | The argument goes on the *left* side of a matrix-matrix operation. |
| `'R'` | The argument goes on the *right* side of a matrix-matrix operation. |
#### [Triangle referencing](@id stdlib-blas-uplo)
| `uplo`/`ul` | Meaning |
|:------------|:------------------------------------------------------|
| `'U'` | Only the *upper* triangle of the matrix will be used. |
| `'L'` | Only the *lower* triangle of the matrix will be used. |
#### [Transposition operation](@id stdlib-blas-trans)
| `trans`/`tX` | Meaning |
|:-------------|:--------------------------------------------------------|
| `'N'` | The input matrix `X` is not transposed or conjugated. |
| `'T'` | The input matrix `X` will be transposed. |
| `'C'` | The input matrix `X` will be conjugated and transposed. |
#### [Unit diagonal](@id stdlib-blas-diag)
| `diag`/`dX` | Meaning |
|:------------|:----------------------------------------------------------|
| `'N'` | The diagonal values of the matrix `X` will be read. |
| `'U'` | The diagonal of the matrix `X` is assumed to be all ones. |
```@docs
LinearAlgebra.BLAS
LinearAlgebra.BLAS.dot
LinearAlgebra.BLAS.dotu
LinearAlgebra.BLAS.dotc
LinearAlgebra.BLAS.blascopy!
LinearAlgebra.BLAS.nrm2
LinearAlgebra.BLAS.asum
LinearAlgebra.axpy!
LinearAlgebra.axpby!
LinearAlgebra.BLAS.scal!
LinearAlgebra.BLAS.scal
LinearAlgebra.BLAS.iamax
LinearAlgebra.BLAS.ger!
LinearAlgebra.BLAS.syr!
LinearAlgebra.BLAS.syrk!
LinearAlgebra.BLAS.syrk
LinearAlgebra.BLAS.syr2k!
LinearAlgebra.BLAS.syr2k
LinearAlgebra.BLAS.her!
LinearAlgebra.BLAS.herk!
LinearAlgebra.BLAS.herk
LinearAlgebra.BLAS.her2k!
LinearAlgebra.BLAS.her2k
LinearAlgebra.BLAS.gbmv!
LinearAlgebra.BLAS.gbmv
LinearAlgebra.BLAS.sbmv!
LinearAlgebra.BLAS.sbmv(::Any, ::Any, ::Any, ::Any, ::Any)
LinearAlgebra.BLAS.sbmv(::Any, ::Any, ::Any, ::Any)
LinearAlgebra.BLAS.gemm!
LinearAlgebra.BLAS.gemm(::Any, ::Any, ::Any, ::Any, ::Any)
LinearAlgebra.BLAS.gemm(::Any, ::Any, ::Any, ::Any)
LinearAlgebra.BLAS.gemv!
LinearAlgebra.BLAS.gemv(::Any, ::Any, ::Any, ::Any)
LinearAlgebra.BLAS.gemv(::Any, ::Any, ::Any)
LinearAlgebra.BLAS.symm!
LinearAlgebra.BLAS.symm(::Any, ::Any, ::Any, ::Any, ::Any)
LinearAlgebra.BLAS.symm(::Any, ::Any, ::Any, ::Any)
LinearAlgebra.BLAS.symv!
LinearAlgebra.BLAS.symv(::Any, ::Any, ::Any, ::Any)
LinearAlgebra.BLAS.symv(::Any, ::Any, ::Any)
LinearAlgebra.BLAS.hemm!
LinearAlgebra.BLAS.hemm(::Any, ::Any, ::Any, ::Any, ::Any)
LinearAlgebra.BLAS.hemm(::Any, ::Any, ::Any, ::Any)
LinearAlgebra.BLAS.hemv!
LinearAlgebra.BLAS.hemv(::Any, ::Any, ::Any, ::Any)
LinearAlgebra.BLAS.hemv(::Any, ::Any, ::Any)
LinearAlgebra.BLAS.trmm!
LinearAlgebra.BLAS.trmm
LinearAlgebra.BLAS.trsm!
LinearAlgebra.BLAS.trsm
LinearAlgebra.BLAS.trmv!
LinearAlgebra.BLAS.trmv
LinearAlgebra.BLAS.trsv!
LinearAlgebra.BLAS.trsv
LinearAlgebra.BLAS.set_num_threads
LinearAlgebra.BLAS.get_num_threads
```
## LAPACK functions
`LinearAlgebra.LAPACK` provides wrappers for some of the LAPACK functions for linear algebra.
Those functions that overwrite one of the input arrays have names ending in `'!'`.
Usually a function has 4 methods defined, one each for [`Float64`](@ref), [`Float32`](@ref),
`ComplexF64` and `ComplexF32` arrays.
Note that the LAPACK API provided by Julia can and will change in the future. Since this API is
not user-facing, there is no commitment to support/deprecate this specific set of functions in
future releases.
```@docs
LinearAlgebra.LAPACK
LinearAlgebra.LAPACK.gbtrf!
LinearAlgebra.LAPACK.gbtrs!
LinearAlgebra.LAPACK.gebal!
LinearAlgebra.LAPACK.gebak!
LinearAlgebra.LAPACK.gebrd!
LinearAlgebra.LAPACK.gelqf!
LinearAlgebra.LAPACK.geqlf!
LinearAlgebra.LAPACK.geqrf!
LinearAlgebra.LAPACK.geqp3!
LinearAlgebra.LAPACK.gerqf!
LinearAlgebra.LAPACK.geqrt!
LinearAlgebra.LAPACK.geqrt3!
LinearAlgebra.LAPACK.getrf!
LinearAlgebra.LAPACK.tzrzf!
LinearAlgebra.LAPACK.ormrz!
LinearAlgebra.LAPACK.gels!
LinearAlgebra.LAPACK.gesv!
LinearAlgebra.LAPACK.getrs!
LinearAlgebra.LAPACK.getri!
LinearAlgebra.LAPACK.gesvx!
LinearAlgebra.LAPACK.gelsd!
LinearAlgebra.LAPACK.gelsy!
LinearAlgebra.LAPACK.gglse!
LinearAlgebra.LAPACK.geev!
LinearAlgebra.LAPACK.gesdd!
LinearAlgebra.LAPACK.gesvd!
LinearAlgebra.LAPACK.ggsvd!
LinearAlgebra.LAPACK.ggsvd3!
LinearAlgebra.LAPACK.geevx!
LinearAlgebra.LAPACK.ggev!
LinearAlgebra.LAPACK.gtsv!
LinearAlgebra.LAPACK.gttrf!
LinearAlgebra.LAPACK.gttrs!
LinearAlgebra.LAPACK.orglq!
LinearAlgebra.LAPACK.orgqr!
LinearAlgebra.LAPACK.orgql!
LinearAlgebra.LAPACK.orgrq!
LinearAlgebra.LAPACK.ormlq!
LinearAlgebra.LAPACK.ormqr!
LinearAlgebra.LAPACK.ormql!
LinearAlgebra.LAPACK.ormrq!
LinearAlgebra.LAPACK.gemqrt!
LinearAlgebra.LAPACK.posv!
LinearAlgebra.LAPACK.potrf!
LinearAlgebra.LAPACK.potri!
LinearAlgebra.LAPACK.potrs!
LinearAlgebra.LAPACK.pstrf!
LinearAlgebra.LAPACK.ptsv!
LinearAlgebra.LAPACK.pttrf!
LinearAlgebra.LAPACK.pttrs!
LinearAlgebra.LAPACK.trtri!
LinearAlgebra.LAPACK.trtrs!
LinearAlgebra.LAPACK.trcon!
LinearAlgebra.LAPACK.trevc!
LinearAlgebra.LAPACK.trrfs!
LinearAlgebra.LAPACK.stev!
LinearAlgebra.LAPACK.stebz!
LinearAlgebra.LAPACK.stegr!
LinearAlgebra.LAPACK.stein!
LinearAlgebra.LAPACK.syconv!
LinearAlgebra.LAPACK.sysv!
LinearAlgebra.LAPACK.sytrf!
LinearAlgebra.LAPACK.sytri!
LinearAlgebra.LAPACK.sytrs!
LinearAlgebra.LAPACK.hesv!
LinearAlgebra.LAPACK.hetrf!
LinearAlgebra.LAPACK.hetri!
LinearAlgebra.LAPACK.hetrs!
LinearAlgebra.LAPACK.syev!
LinearAlgebra.LAPACK.syevr!
LinearAlgebra.LAPACK.sygvd!
LinearAlgebra.LAPACK.bdsqr!
LinearAlgebra.LAPACK.bdsdc!
LinearAlgebra.LAPACK.gecon!
LinearAlgebra.LAPACK.gehrd!
LinearAlgebra.LAPACK.orghr!
LinearAlgebra.LAPACK.gees!
LinearAlgebra.LAPACK.gges!
LinearAlgebra.LAPACK.trexc!
LinearAlgebra.LAPACK.trsen!
LinearAlgebra.LAPACK.tgsen!
LinearAlgebra.LAPACK.trsyl!
```
```@meta
DocTestSetup = nothing
```
| JuliaZH | https://github.com/JuliaCN/JuliaZH.jl.git |
|
[
"MIT"
] | 1.6.0 | a7dc7bfc2fc6638c18241bfcdb9d73c7dd256482 | docs | 12781 | # 日志记录
[`Logging`](@ref Logging.Logging) 模块提供了一个将历史和计算进度记录为事件的日志。事件通过在源代码里插入日志语句产生,例如:
```julia
@warn "Abandon printf debugging, all ye who enter here!"
┌ Warning: Abandon printf debugging, all ye who enter here!
└ @ Main REPL[1]:1
```
The system provides several advantages over peppering your source code with
calls to `println()`. First, it allows you to control the visibility and
presentation of messages without editing the source code. For example, in
contrast to the `@warn` above
```julia
@debug "The sum of some values $(sum(rand(100)))"
```
will produce no output by default. Furthermore, it's very cheap to leave debug
statements like this in the source code because the system avoids evaluating
the message if it would later be ignored. In this case `sum(rand(100))` and
the associated string processing will never be executed unless debug logging is
enabled.
Second, the logging tools allow you to attach arbitrary data to each event as a
set of key--value pairs. This allows you to capture local variables and other
program state for later analysis. For example, to attach the local array
variable `A` and the sum of a vector `v` as the key `s` you can use
```jldoctest
A = ones(Int, 4, 4)
v = ones(100)
@info "Some variables" A s=sum(v)
# output
┌ Info: Some variables
│ A =
│ 4×4 Matrix{Int64}:
│ 1 1 1 1
│ 1 1 1 1
│ 1 1 1 1
│ 1 1 1 1
└ s = 100.0
```
所有的日志宏如 `@debug`, `@info`, `@warn` 和 `@error` 有着共同的特征,
这些共同特征在更通用的宏 [`@logmsg`](@ref) 的文档里有细致说明。
## 日志事件结构
Each event generates several pieces of data, some provided by the user and some
automatically extracted. Let's examine the user-defined data first:
* The *log level* is a broad category for the message that is used for early
filtering. There are several standard levels of type [`LogLevel`](@ref);
user-defined levels are also possible.
Each is distinct in purpose:
- [`Logging.Debug`](@ref) (log level -1000) is information intended for the developer of
the program. These events are disabled by default.
- [`Logging.Info`](@ref) (log level 0) is for general information to the user.
Think of it as an alternative to using `println` directly.
- [`Logging.Warn`](@ref) (log level 1000) means something is wrong and action is likely
required but that for now the program is still working.
- [`Logging.Error`](@ref) (log level 2000) means something is wrong and it is unlikely to
be recovered, at least by this part of the code.
Often this log-level is unneeded as throwing an exception can convey
all the required information.
* The *message* is an object describing the event. By convention
`AbstractString`s passed as messages are assumed to be in markdown format.
Other types will be displayed using `print(io, obj)` or `string(obj)` for
text-based output and possibly `show(io,mime,obj)` for other multimedia
displays used in the installed logger.
* Optional *key--value pairs* allow arbitrary data to be attached to each event.
Some keys have conventional meaning that can affect the way an event is
interpreted (see [`@logmsg`](@ref)).
The system also generates some standard information for each event:
* The `module` in which the logging macro was expanded.
* The `file` and `line` where the logging macro occurs in the source code.
* A message `id` that is a unique, fixed identifier for the *source code
statement* where the logging macro appears. This identifier is designed to be
fairly stable even if the source code of the file changes, as long as the
logging statement itself remains the same.
* A `group` for the event, which is set to the base name of the file by default,
without extension. This can be used to group messages into categories more
finely than the log level (for example, all deprecation warnings have group
`:depwarn`), or into logical groupings across or within modules.
Notice that some useful information such as the event time is not included by
default. This is because such information can be expensive to extract and is
also *dynamically* available to the current logger. It's simple to define a
[custom logger](@ref AbstractLogger-interface) to augment event data with the
time, backtrace, values of global variables and other useful information as
required.
## Processing log events
As you can see in the examples, logging statements make no mention of
where log events go or how they are processed. This is a key design feature
that makes the system composable and natural for concurrent use. It does this
by separating two different concerns:
* *Creating* log events is the concern of the module author who needs to
decide where events are triggered and which information to include.
* *Processing* of log events — that is, display, filtering, aggregation and
recording — is the concern of the application author who needs to bring
multiple modules together into a cooperating application.
### Loggers
Processing of events is performed by a *logger*, which is the first piece of
user configurable code to see the event. All loggers must be subtypes of
[`AbstractLogger`](@ref).
When an event is triggered, the appropriate logger is found by looking for a
task-local logger with the global logger as fallback. The idea here is that
the application code knows how log events should be processed and exists
somewhere at the top of the call stack. So we should look up through the call
stack to discover the logger — that is, the logger should be *dynamically
scoped*. (This is a point of contrast with logging frameworks where the
logger is *lexically scoped*; provided explicitly by the module author or as a
simple global variable. In such a system it's awkward to control logging while
composing functionality from multiple modules.)
The global logger may be set with [`global_logger`](@ref), and task-local
loggers controlled using [`with_logger`](@ref). Newly spawned tasks inherit
the logger of the parent task.
There are three logger types provided by the library. [`ConsoleLogger`](@ref)
is the default logger you see when starting the REPL. It displays events in a
readable text format and tries to give simple but user friendly control over
formatting and filtering. [`NullLogger`](@ref) is a convenient way to drop all
messages where necessary; it is the logging equivalent of the [`devnull`](@ref)
stream. [`SimpleLogger`](@ref) is a very simplistic text formatting logger,
mainly useful for debugging the logging system itself.
Custom loggers should come with overloads for the functions described in the
[reference section](@ref AbstractLogger-interface).
### Early filtering and message handling
When an event occurs, a few steps of early filtering occur to avoid generating
messages that will be discarded:
1. The message log level is checked against a global minimum level (set via
[`disable_logging`](@ref)). This is a crude but extremely cheap global
setting.
2. The current logger state is looked up and the message level checked against the
logger's cached minimum level, as found by calling [`Logging.min_enabled_level`](@ref).
This behavior can be overridden via environment variables (more on this later).
3. The [`Logging.shouldlog`](@ref) function is called with the current logger, taking
some minimal information (level, module, group, id) which can be computed
statically. Most usefully, `shouldlog` is passed an event `id` which can be
used to discard events early based on a cached predicate.
If all these checks pass, the message and key--value pairs are evaluated in full
and passed to the current logger via the [`Logging.handle_message`](@ref) function.
`handle_message()` may perform additional filtering as required and display the
event to the screen, save it to a file, etc.
Exceptions that occur while generating the log event are captured and logged
by default. This prevents individual broken events from crashing the
application, which is helpful when enabling little-used debug events in a
production system. This behavior can be customized per logger type by
extending [`Logging.catch_exceptions`](@ref).
## Testing log events
Log events are a side effect of running normal code, but you might find
yourself wanting to test particular informational messages and warnings. The
`Test` module provides a [`@test_logs`](@ref) macro that can be used to
pattern match against the log event stream.
## Environment variables
Message filtering can be influenced through the `JULIA_DEBUG` environment
variable, and serves as an easy way to enable debug logging for a file or
module. For example, loading julia with `JULIA_DEBUG=loading` will activate
`@debug` log messages in `loading.jl`:
```
$ JULIA_DEBUG=loading julia -e 'using OhMyREPL'
┌ Debug: Rejecting cache file /home/user/.julia/compiled/v0.7/OhMyREPL.ji due to it containing an invalid cache header
└ @ Base loading.jl:1328
[ Info: Recompiling stale cache file /home/user/.julia/compiled/v0.7/OhMyREPL.ji for module OhMyREPL
┌ Debug: Rejecting cache file /home/user/.julia/compiled/v0.7/Tokenize.ji due to it containing an invalid cache header
└ @ Base loading.jl:1328
...
```
Similarly, the environment variable can be used to enable debug logging of
modules, such as `Pkg`, or module roots (see [`Base.moduleroot`](@ref)). To
enable all debug logging, use the special value `all`.
To turn debug logging on from the REPL, set `ENV["JULIA_DEBUG"]` to the
name of the module of interest. Functions defined in the REPL belong to
module `Main`; logging for them can be enabled like this:
```julia-repl
julia> foo() = @debug "foo"
foo (generic function with 1 method)
julia> foo()
julia> ENV["JULIA_DEBUG"] = Main
Main
julia> foo()
┌ Debug: foo
└ @ Main REPL[1]:1
```
## Examples
### Example: Writing log events to a file
Sometimes it can be useful to write log events to a file. Here is an example
of how to use a task-local and global logger to write information to a text
file:
```julia-repl
# Load the logging module
julia> using Logging
# Open a textfile for writing
julia> io = open("log.txt", "w+")
IOStream(<file log.txt>)
# Create a simple logger
julia> logger = SimpleLogger(io)
SimpleLogger(IOStream(<file log.txt>), Info, Dict{Any,Int64}())
# Log a task-specific message
julia> with_logger(logger) do
@info("a context specific log message")
end
# Write all buffered messages to the file
julia> flush(io)
# Set the global logger to logger
julia> global_logger(logger)
SimpleLogger(IOStream(<file log.txt>), Info, Dict{Any,Int64}())
# This message will now also be written to the file
julia> @info("a global log message")
# Close the file
julia> close(io)
```
### Example: Enable debug-level messages
Here is an example of creating a [`ConsoleLogger`](@ref) that lets through any messages
with log level higher than, or equal, to [`Logging.Debug`](@ref).
```julia-repl
julia> using Logging
# Create a ConsoleLogger that prints any log messages with level >= Debug to stderr
julia> debuglogger = ConsoleLogger(stderr, Logging.Debug)
# Enable debuglogger for a task
julia> with_logger(debuglogger) do
@debug "a context specific log message"
end
# Set the global logger
julia> global_logger(debuglogger)
```
## Reference
### Logging module
```@docs
Logging.Logging
```
### Creating events
```@docs
Logging.@logmsg
Logging.LogLevel
Logging.Debug
Logging.Info
Logging.Warn
Logging.Error
```
### [Processing events with AbstractLogger](@id AbstractLogger-interface)
Event processing is controlled by overriding functions associated with
`AbstractLogger`:
| Methods to implement | | Brief description |
|:----------------------------------- |:---------------------- |:---------------------------------------- |
| [`Logging.handle_message`](@ref) | | Handle a log event |
| [`Logging.shouldlog`](@ref) | | Early filtering of events |
| [`Logging.min_enabled_level`](@ref) | | Lower bound for log level of accepted events |
| **Optional methods** | **Default definition** | **Brief description** |
| [`Logging.catch_exceptions`](@ref) | `true` | Catch exceptions during event evaluation |
```@docs
Logging.AbstractLogger
Logging.handle_message
Logging.shouldlog
Logging.min_enabled_level
Logging.catch_exceptions
Logging.disable_logging
```
### Using Loggers
Logger installation and inspection:
```@docs
Logging.global_logger
Logging.with_logger
Logging.current_logger
```
Loggers that are supplied with the system:
```@docs
Logging.NullLogger
Logging.ConsoleLogger
Logging.SimpleLogger
```
| JuliaZH | https://github.com/JuliaCN/JuliaZH.jl.git |
|
[
"MIT"
] | 1.6.0 | a7dc7bfc2fc6638c18241bfcdb9d73c7dd256482 | docs | 11088 | # [Markdown](@id markdown_stdlib)
本节描述 Julia 的 markdown 语法,它是由 Markdown 标准库启用的。它支持以下的 Markdown 元素:
## 内联元素
此处的“内联”指可以在段落中找到的元素。包括下面的元素。
### 粗体
用两个 `**` 包围来将其内部的文本显示为粗体。
```
A paragraph containing a **bold** word.
```
### 斜体
用单个 `*` 包围来将其内部的文本显示为斜体。
```
A paragraph containing an *italicized* word.
```
### 文字
用一个重音符号 ``` ` ``` 包围的文本将会原封不动地显示出来。
```
A paragraph containing a `literal` word.
```
当文本指代变量名、函数名或者 Julia 程序的其他部分时,应当使用字面量。
!!! tip
为了在字面量中包含一个重音符,需要使用三个重音符而不是一个来包围文本。
```
A paragraph containing ``` `backtick` characters ```.
```
通过扩展,可以使用任何奇数个反引号来包围较少数量的反引号。
### ``\LaTeX``
使用两个重音符的 ``\LaTeX`` 语法来包围那些是数学表达式的文本,
``` `` ``` .
```
A paragraph containing some ``\LaTeX`` markup.
```
!!! tip
As with literals in the previous section, if literal backticks need to be written within double
backticks use an even number greater than two. Note that if a single literal backtick needs to
be included within ``\LaTeX`` markup then two enclosing backticks is sufficient.
!!! note
The `\` character should be escaped appropriately if the text is embedded in a Julia source code,
for example, ``` "``\\LaTeX`` syntax in a docstring." ```, since it is interpreted as a string
literal. Alternatively, in order to avoid escaping, it is possible to use the `raw` string macro
together with the `@doc` macro:
```
@doc raw"``\LaTeX`` syntax in a docstring." functionname
```
### Links
Links to either external or internal targets can be written using the following syntax, where
the text enclosed in square brackets, `[ ]`, is the name of the link and the text enclosed in
parentheses, `( )`, is the URL.
```
A paragraph containing a link to [Julia](http://www.julialang.org).
```
It's also possible to add cross-references to other documented functions/methods/variables within
the Julia documentation itself. For example:
```julia
"""
tryparse(type, str; base)
Like [`parse`](@ref), but returns either a value of the requested type,
or [`nothing`](@ref) if the string does not contain a valid number.
"""
```
This will create a link in the generated docs to the [`parse`](@ref) documentation
(which has more information about what this function actually does), and to the
[`nothing`](@ref) documentation. It's good to include cross references to mutating/non-mutating
versions of a function, or to highlight a difference between two similar-seeming functions.
!!! note
The above cross referencing is *not* a Markdown feature, and relies on
[Documenter.jl](https://github.com/JuliaDocs/Documenter.jl), which is
used to build base Julia's documentation.
### Footnote references
Named and numbered footnote references can be written using the following syntax. A footnote name
must be a single alphanumeric word containing no punctuation.
```
A paragraph containing a numbered footnote [^1] and a named one [^named].
```
!!! note
The text associated with a footnote can be written anywhere within the same page as the footnote
reference. The syntax used to define the footnote text is discussed in the [Footnotes](@ref) section
below.
## Toplevel elements
The following elements can be written either at the "toplevel" of a document or within another
"toplevel" element.
### Paragraphs
A paragraph is a block of plain text, possibly containing any number of inline elements defined
in the [Inline elements](@ref) section above, with one or more blank lines above and below it.
```
This is a paragraph.
And this is *another* paragraph containing some emphasized text.
A new line, but still part of the same paragraph.
```
### Headers
A document can be split up into different sections using headers. Headers use the following syntax:
```julia
# Level One
## Level Two
### Level Three
#### Level Four
##### Level Five
###### Level Six
```
A header line can contain any inline syntax in the same way as a paragraph can.
!!! tip
Try to avoid using too many levels of header within a single document. A heavily nested document
may be indicative of a need to restructure it or split it into several pages covering separate
topics.
### Code blocks
Source code can be displayed as a literal block using an indent of four spaces as shown in the
following example.
```
This is a paragraph.
function func(x)
# ...
end
Another paragraph.
```
Additionally, code blocks can be enclosed using triple backticks with an optional "language" to
specify how a block of code should be highlighted.
````
A code block without a "language":
```
function func(x)
# ...
end
```
and another one with the "language" specified as `julia`:
```julia
function func(x)
# ...
end
```
````
!!! note
"Fenced" code blocks, as shown in the last example, should be preferred over indented code blocks
since there is no way to specify what language an indented code block is written in.
### Block quotes
Text from external sources, such as quotations from books or websites, can be quoted using `>`
characters prepended to each line of the quote as follows.
```
Here's a quote:
> Julia is a high-level, high-performance dynamic programming language for
> technical computing, with syntax that is familiar to users of other
> technical computing environments.
```
Note that a single space must appear after the `>` character on each line. Quoted blocks may themselves
contain other toplevel or inline elements.
### Images
The syntax for images is similar to the link syntax mentioned above. Prepending a `!` character
to a link will display an image from the specified URL rather than a link to it.
```julia

```
### Lists
Unordered lists can be written by prepending each item in a list with either `*`, `+`, or `-`.
```
A list of items:
* item one
* item two
* item three
```
Note the two spaces before each `*` and the single space after each one.
Lists can contain other nested toplevel elements such as lists, code blocks, or quoteblocks. A
blank line should be left between each list item when including any toplevel elements within a
list.
```
Another list:
* item one
* item two
```
f(x) = x
```
* And a sublist:
+ sub-item one
+ sub-item two
```
!!! note
The contents of each item in the list must line up with the first line of the item. In the above
example the fenced code block must be indented by four spaces to align with the `i` in `item two`.
Ordered lists are written by replacing the "bullet" character, either `*`, `+`, or `-`, with a
positive integer followed by either `.` or `)`.
```
Two ordered lists:
1. item one
2. item two
3. item three
5) item five
6) item six
7) item seven
```
An ordered list may start from a number other than one, as in the second list of the above example,
where it is numbered from five. As with unordered lists, ordered lists can contain nested toplevel
elements.
### Display equations
Large ``\LaTeX`` equations that do not fit inline within a paragraph may be written as display
equations using a fenced code block with the "language" `math` as in the example below.
````julia
```math
f(a) = \frac{1}{2\pi}\int_{0}^{2\pi} (\alpha+R\cos(\theta))d\theta
```
````
### Footnotes
This syntax is paired with the inline syntax for [Footnote references](@ref). Make sure to read
that section as well.
Footnote text is defined using the following syntax, which is similar to footnote reference syntax,
aside from the `:` character that is appended to the footnote label.
```
[^1]: Numbered footnote text.
[^note]:
Named footnote text containing several toplevel elements.
* item one
* item two
* item three
```julia
function func(x)
# ...
end
```
```
!!! note
No checks are done during parsing to make sure that all footnote references have matching footnotes.
### Horizontal rules
The equivalent of an `<hr>` HTML tag can be achieved using three hyphens (`---`).
For example:
```
Text above the line.
---
And text below the line.
```
### Tables
Basic tables can be written using the syntax described below. Note that markdown tables have limited
features and cannot contain nested toplevel elements unlike other elements discussed above –
only inline elements are allowed. Tables must always contain a header row with column names. Cells
cannot span multiple rows or columns of the table.
```
| Column One | Column Two | Column Three |
|:---------- | ---------- |:------------:|
| Row `1` | Column `2` | |
| *Row* 2 | **Row** 2 | Column ``3`` |
```
!!! note
As illustrated in the above example each column of `|` characters must be aligned vertically.
A `:` character on either end of a column's header separator (the row containing `-` characters)
specifies whether the row is left-aligned, right-aligned, or (when `:` appears on both ends) center-aligned.
Providing no `:` characters will default to right-aligning the column.
### Admonitions
Specially formatted blocks, known as admonitions, can be used to highlight particular remarks.
They can be defined using the following `!!!` syntax:
```
!!! note
This is the content of the note.
!!! warning "Beware!"
And this is another one.
This warning admonition has a custom title: `"Beware!"`.
```
The first word after `!!!` declares the type of the admonition.
There are standard admonition types that should produce special styling.
Namely (in order of decreasing severity): `danger`, `warning`, `info`/`note`, and `tip`.
You can also use your own admonition types, as long as the type name only contains lowercase Latin characters (a-z).
For example, you could have a `terminology` block like this:
```
!!! terminology "julia vs Julia"
Strictly speaking, "Julia" refers to the language,
and "julia" to the standard implementation.
```
However, unless the code rendering the Markdown special-cases that particular admonition type, it will get the default styling.
A custom title for the box can be provided as a string (in double quotes) after the admonition type.
If no title text is specified after the admonition type, then the type name will be used as the title (e.g. `"Note"` for the `note` admonition).
Admonitions, like most other toplevel elements, can contain other toplevel elements (e.g. lists, images).
## Markdown Syntax Extensions
Julia's markdown supports interpolation in a very similar way to basic string literals, with the
difference that it will store the object itself in the Markdown tree (as opposed to converting
it to a string). When the Markdown content is rendered the usual `show` methods will be called,
and these can be overridden as usual. This design allows the Markdown to be extended with arbitrarily
complex features (such as references) without cluttering the basic syntax.
In principle, the Markdown parser itself can also be arbitrarily extended by packages, or an entirely
custom flavour of Markdown can be used, but this should generally be unnecessary.
| JuliaZH | https://github.com/JuliaCN/JuliaZH.jl.git |
|
[
"MIT"
] | 1.6.0 | a7dc7bfc2fc6638c18241bfcdb9d73c7dd256482 | docs | 61 | # 内存映射 I/O
```@docs
Mmap.Anonymous
Mmap.mmap
Mmap.sync!
```
| JuliaZH | https://github.com/JuliaCN/JuliaZH.jl.git |
|
[
"MIT"
] | 1.6.0 | a7dc7bfc2fc6638c18241bfcdb9d73c7dd256482 | docs | 72 | # [Printf](@id man-printf)
```@docs
Printf.@printf
Printf.@sprintf
```
| JuliaZH | https://github.com/JuliaCN/JuliaZH.jl.git |
|
[
"MIT"
] | 1.6.0 | a7dc7bfc2fc6638c18241bfcdb9d73c7dd256482 | docs | 237 | # [性能分析](@id lib-profiling)
```@docs
Profile.@profile
```
`Profile` 里的方法均未导出,需要通过 `Profile.print()` 的方式调用。
```@docs
Profile.clear
Profile.print
Profile.init
Profile.fetch
Profile.retrieve
Profile.callers
Profile.clear_malloc_data
```
| JuliaZH | https://github.com/JuliaCN/JuliaZH.jl.git |
|
[
"MIT"
] | 1.6.0 | a7dc7bfc2fc6638c18241bfcdb9d73c7dd256482 | docs | 25884 | # Julia REPL
Julia 附带了一个全功能的交互式命令行 REPL(read-eval-print loop),其内置于 `julia` 可执行文件中。它除了允许快速简便地执行 Julia 语句外,还具有可搜索的历史记录,tab 补全,许多有用的按键绑定以及专用的 help 和 shell 模式。只需不附带任何参数地调用 `julia` 或双击可执行文件即可启动 REPL:
```@eval
io = IOBuffer()
Base.banner(io)
banner = String(take!(io))
import Markdown
Markdown.parse("```\n\$ julia\n\n$(banner)\njulia>\n```")
```
要退出交互式会话,在空白行上键入 `^D`——control 键和 `d` 键,或者先键入 `quit()`,然后键入 return 或 enter 键。REPL 用横幅和 `julia>` 提示符欢迎你。
## 不同的提示符模式
### Julian 模式
The REPL has five main modes of operation. The first and most common is the Julian prompt. It
is the default mode of operation; each new line initially starts with `julia>`. It is here that
you can enter Julia expressions. Hitting return or enter after a complete expression has been
entered will evaluate the entry and show the result of the last expression.
```jldoctest
julia> string(1 + 2)
"3"
```
交互式运行有许多独特的实用功能。除了显示结果外,REPL 还将结果绑定到变量 `ans` 上。一行的尾随分号可用作禁止显示结果的标志。
```jldoctest
julia> string(3 * 4);
julia> ans
"12"
```
In Julia mode, the REPL supports something called *prompt pasting*. This activates when pasting
text that starts with `julia> ` into the REPL. In that case, only expressions starting with
`julia> ` are parsed, others are removed. This makes it possible to paste a chunk of code
that has been copied from a REPL session without having to scrub away prompts and outputs. This
feature is enabled by default but can be disabled or enabled at will with `REPL.enable_promptpaste(::Bool)`.
If it is enabled, you can try it out by pasting the code block above this paragraph straight into
the REPL. This feature does not work on the standard Windows command prompt due to its limitation
at detecting when a paste occurs.
Objects are printed at the REPL using the [`show`](@ref) function with a specific [`IOContext`](@ref).
In particular, the `:limit` attribute is set to `true`.
Other attributes can receive in certain `show` methods a default value if it's not already set,
like `:compact`.
It's possible, as an experimental feature, to specify the attributes used by the REPL via the
`Base.active_repl.options.iocontext` dictionary (associating values to attributes). For example:
```julia-repl
julia> rand(2, 2)
2×2 Array{Float64,2}:
0.8833 0.329197
0.719708 0.59114
julia> show(IOContext(stdout, :compact => false), "text/plain", rand(2, 2))
0.43540323669187075 0.15759787870609387
0.2540832269192739 0.4597637838786053
julia> Base.active_repl.options.iocontext[:compact] = false;
julia> rand(2, 2)
2×2 Array{Float64,2}:
0.2083967319174056 0.13330606013126012
0.6244375177790158 0.9777957560761545
```
In order to define automatically the values of this dictionary at startup time, one can use the
[`atreplinit`](@ref) function in the `~/.julia/config/startup.jl` file, for example:
```julia
atreplinit() do repl
repl.options.iocontext[:compact] = false
end
```
### 帮助模式
When the cursor is at the beginning of the line, the prompt can be changed to a help mode by typing
`?`. Julia will attempt to print help or documentation for anything entered in help mode:
```julia-repl
julia> ? # upon typing ?, the prompt changes (in place) to: help?>
help?> string
search: string String Cstring Cwstring RevString randstring bytestring SubString
string(xs...)
Create a string from any values using the print function.
```
Macros, types and variables can also be queried:
```
help?> @time
@time
A macro to execute an expression, printing the time it took to execute, the number of allocations,
and the total number of bytes its execution caused to be allocated, before returning the value of the
expression.
See also @timev, @timed, @elapsed, and @allocated.
help?> Int32
search: Int32 UInt32
Int32 <: Signed
32-bit signed integer type.
```
A string or regex literal searches all docstrings using [`apropos`](@ref):
```
help?> "aprop"
REPL.stripmd
Base.Docs.apropos
help?> r"ap..p"
Base.:∘
Base.shell_escape_posixly
Distributed.CachingPool
REPL.stripmd
Base.Docs.apropos
```
Help mode can be exited by pressing backspace at the beginning of the line.
### [Shell mode](@id man-shell-mode)
Just as help mode is useful for quick access to documentation, another common task is to use the
system shell to execute system commands. Just as `?` entered help mode when at the beginning
of the line, a semicolon (`;`) will enter the shell mode. And it can be exited by pressing backspace
at the beginning of the line.
```julia-repl
julia> ; # upon typing ;, the prompt changes (in place) to: shell>
shell> echo hello
hello
```
!!! note
For Windows users, Julia's shell mode does not expose windows shell commands.
Hence, this will fail:
```julia-repl
julia> ; # upon typing ;, the prompt changes (in place) to: shell>
shell> dir
ERROR: IOError: could not spawn `dir`: no such file or directory (ENOENT)
Stacktrace!
.......
```
However, you can get access to `PowerShell` like this:
```julia-repl
julia> ; # upon typing ;, the prompt changes (in place) to: shell>
shell> powershell
Windows PowerShell
Copyright (C) Microsoft Corporation. All rights reserved.
PS C:\Users\elm>
```
... and to `cmd.exe` like that (see the `dir` command):
```julia-repl
julia> ; # upon typing ;, the prompt changes (in place) to: shell>
shell> cmd
Microsoft Windows [version 10.0.17763.973]
(c) 2018 Microsoft Corporation. All rights reserved.
C:\Users\elm>dir
Volume in drive C has no label
Volume Serial Number is 1643-0CD7
Directory of C:\Users\elm
29/01/2020 22:15 <DIR> .
29/01/2020 22:15 <DIR> ..
02/02/2020 08:06 <DIR> .atom
```
### Pkg mode
The Package manager mode accepts specialized commands for loading and updating packages. It is entered
by pressing the `]` key at the Julian REPL prompt and exited by pressing CTRL-C or pressing the backspace key
at the beginning of the line. The prompt for this mode is `pkg>`. It supports its own help-mode, which is
entered by pressing `?` at the beginning of the line of the `pkg>` prompt. The Package manager mode is
documented in the Pkg manual, available at [https://julialang.github.io/Pkg.jl/v1/](https://julialang.github.io/Pkg.jl/v1/).
### Search modes
In all of the above modes, the executed lines get saved to a history file, which can be searched.
To initiate an incremental search through the previous history, type `^R` -- the control key
together with the `r` key. The prompt will change to ```(reverse-i-search)`':```, and as you
type the search query will appear in the quotes. The most recent result that matches the query
will dynamically update to the right of the colon as more is typed. To find an older result using
the same query, simply type `^R` again.
Just as `^R` is a reverse search, `^S` is a forward search, with the prompt ```(i-search)`':```.
The two may be used in conjunction with each other to move through the previous or next matching
results, respectively.
## Key bindings
The Julia REPL makes great use of key bindings. Several control-key bindings were already introduced
above (`^D` to exit, `^R` and `^S` for searching), but there are many more. In addition to the
control-key, there are also meta-key bindings. These vary more by platform, but most terminals
default to using alt- or option- held down with a key to send the meta-key (or can be configured
to do so), or pressing Esc and then the key.
| Keybinding | Description |
|:------------------- |:---------------------------------------------------------------------------------------------------------- |
| **Program control** | |
| `^D` | Exit (when buffer is empty) |
| `^C` | Interrupt or cancel |
| `^L` | Clear console screen |
| Return/Enter, `^J` | New line, executing if it is complete |
| meta-Return/Enter | Insert new line without executing it |
| `?` or `;` | Enter help or shell mode (when at start of a line) |
| `^R`, `^S` | Incremental history search, described above |
| **Cursor movement** | |
| Right arrow, `^F` | Move right one character |
| Left arrow, `^B` | Move left one character |
| ctrl-Right, `meta-F`| Move right one word |
| ctrl-Left, `meta-B` | Move left one word |
| Home, `^A` | Move to beginning of line |
| End, `^E` | Move to end of line |
| Up arrow, `^P` | Move up one line (or change to the previous history entry that matches the text before the cursor) |
| Down arrow, `^N` | Move down one line (or change to the next history entry that matches the text before the cursor) |
| Shift-Arrow Key | Move cursor according to the direction of the Arrow key, while activating the region ("shift selection") |
| Page-up, `meta-P` | Change to the previous history entry |
| Page-down, `meta-N` | Change to the next history entry |
| `meta-<` | Change to the first history entry (of the current session if it is before the current position in history) |
| `meta->` | Change to the last history entry |
| `^-Space` | Set the "mark" in the editing region (and de-activate the region if it's active) |
| `^-Space ^-Space` | Set the "mark" in the editing region and make the region "active", i.e. highlighted |
| `^G` | De-activate the region (i.e. make it not highlighted) |
| `^X^X` | Exchange the current position with the mark |
| **Editing** | |
| Backspace, `^H` | Delete the previous character, or the whole region when it's active |
| Delete, `^D` | Forward delete one character (when buffer has text) |
| meta-Backspace | Delete the previous word |
| `meta-d` | Forward delete the next word |
| `^W` | Delete previous text up to the nearest whitespace |
| `meta-w` | Copy the current region in the kill ring |
| `meta-W` | "Kill" the current region, placing the text in the kill ring |
| `^K` | "Kill" to end of line, placing the text in the kill ring |
| `^Y` | "Yank" insert the text from the kill ring |
| `meta-y` | Replace a previously yanked text with an older entry from the kill ring |
| `^T` | Transpose the characters about the cursor |
| `meta-Up arrow` | Transpose current line with line above |
| `meta-Down arrow` | Transpose current line with line below |
| `meta-u` | Change the next word to uppercase |
| `meta-c` | Change the next word to titlecase |
| `meta-l` | Change the next word to lowercase |
| `^/`, `^_` | Undo previous editing action |
| `^Q` | Write a number in REPL and press `^Q` to open editor at corresponding stackframe or method |
| `meta-Left Arrow` | indent the current line on the left |
| `meta-Right Arrow` | indent the current line on the right |
| `meta-.` | insert last word from previous history entry |
### Customizing keybindings
Julia's REPL keybindings may be fully customized to a user's preferences by passing a dictionary
to `REPL.setup_interface`. The keys of this dictionary may be characters or strings. The key
`'*'` refers to the default action. Control plus character `x` bindings are indicated with `"^x"`.
Meta plus `x` can be written `"\\M-x"` or `"\ex"`, and Control plus `x` can be written
`"\\C-x"` or `"^x"`.
The values of the custom keymap must be `nothing` (indicating
that the input should be ignored) or functions that accept the signature
`(PromptState, AbstractREPL, Char)`.
The `REPL.setup_interface` function must be called before the REPL is initialized, by registering
the operation with [`atreplinit`](@ref) . For example, to bind the up and down arrow keys to move through
history without prefix search, one could put the following code in `~/.julia/config/startup.jl`:
```julia
import REPL
import REPL.LineEdit
const mykeys = Dict{Any,Any}(
# Up Arrow
"\e[A" => (s,o...)->(LineEdit.edit_move_up(s) || LineEdit.history_prev(s, LineEdit.mode(s).hist)),
# Down Arrow
"\e[B" => (s,o...)->(LineEdit.edit_move_down(s) || LineEdit.history_next(s, LineEdit.mode(s).hist))
)
function customize_keys(repl)
repl.interface = REPL.setup_interface(repl; extra_repl_keymap = mykeys)
end
atreplinit(customize_keys)
```
Users should refer to `LineEdit.jl` to discover the available actions on key input.
## Tab completion
In both the Julian and help modes of the REPL, one can enter the first few characters of a function
or type and then press the tab key to get a list all matches:
```julia-repl
julia> stri[TAB]
stride strides string strip
julia> Stri[TAB]
StridedArray StridedMatrix StridedVecOrMat StridedVector String
```
The tab key can also be used to substitute LaTeX math symbols with their Unicode equivalents,
and get a list of LaTeX matches as well:
```julia-repl
julia> \pi[TAB]
julia> π
π = 3.1415926535897...
julia> e\_1[TAB] = [1,0]
julia> e₁ = [1,0]
2-element Array{Int64,1}:
1
0
julia> e\^1[TAB] = [1 0]
julia> e¹ = [1 0]
1×2 Array{Int64,2}:
1 0
julia> \sqrt[TAB]2 # √ is equivalent to the sqrt function
julia> √2
1.4142135623730951
julia> \hbar[TAB](h) = h / 2\pi[TAB]
julia> ħ(h) = h / 2π
ħ (generic function with 1 method)
julia> \h[TAB]
\hat \hermitconjmatrix \hkswarow \hrectangle
\hatapprox \hexagon \hookleftarrow \hrectangleblack
\hbar \hexagonblack \hookrightarrow \hslash
\heartsuit \hksearow \house \hspace
julia> α="\alpha[TAB]" # LaTeX completion also works in strings
julia> α="α"
```
A full list of tab-completions can be found in the [Unicode Input](@ref) section of the manual.
Completion of paths works for strings and julia's shell mode:
```julia-repl
julia> path="/[TAB]"
.dockerenv .juliabox/ boot/ etc/ lib/ media/ opt/ root/ sbin/ sys/ usr/
.dockerinit bin/ dev/ home/ lib64/ mnt/ proc/ run/ srv/ tmp/ var/
shell> /[TAB]
.dockerenv .juliabox/ boot/ etc/ lib/ media/ opt/ root/ sbin/ sys/ usr/
.dockerinit bin/ dev/ home/ lib64/ mnt/ proc/ run/ srv/ tmp/ var/
```
Tab completion can help with investigation of the available methods matching the input arguments:
```julia-repl
julia> max([TAB] # All methods are displayed, not shown here due to size of the list
julia> max([1, 2], [TAB] # All methods where `Vector{Int}` matches as first argument
max(x, y) in Base at operators.jl:215
max(a, b, c, xs...) in Base at operators.jl:281
julia> max([1, 2], max(1, 2), [TAB] # All methods matching the arguments.
max(x, y) in Base at operators.jl:215
max(a, b, c, xs...) in Base at operators.jl:281
```
Keywords are also displayed in the suggested methods after `;`, see below line where `limit`
and `keepempty` are keyword arguments:
```julia-repl
julia> split("1 1 1", [TAB]
split(str::AbstractString; limit, keepempty) in Base at strings/util.jl:302
split(str::T, splitter; limit, keepempty) where T<:AbstractString in Base at strings/util.jl:277
```
The completion of the methods uses type inference and can therefore see if the arguments match
even if the arguments are output from functions. The function needs to be type stable for the
completion to be able to remove non-matching methods.
Tab completion can also help completing fields:
```julia-repl
julia> import UUIDs
julia> UUIDs.uuid[TAB]
uuid1 uuid4 uuid_version
```
Fields for output from functions can also be completed:
```julia-repl
julia> split("","")[1].[TAB]
lastindex offset string
```
The completion of fields for output from functions uses type inference, and it can only suggest
fields if the function is type stable.
Dictionary keys can also be tab completed:
```julia-repl
julia> foo = Dict("qwer1"=>1, "qwer2"=>2, "asdf"=>3)
Dict{String,Int64} with 3 entries:
"qwer2" => 2
"asdf" => 3
"qwer1" => 1
julia> foo["q[TAB]
"qwer1" "qwer2"
julia> foo["qwer
```
## Customizing Colors
The colors used by Julia and the REPL can be customized, as well. To change the
color of the Julia prompt you can add something like the following to your
`~/.julia/config/startup.jl` file, which is to be placed inside your home directory:
```julia
function customize_colors(repl)
repl.prompt_color = Base.text_colors[:cyan]
end
atreplinit(customize_colors)
```
The available color keys can be seen by typing `Base.text_colors` in the help mode of the REPL.
In addition, the integers 0 to 255 can be used as color keys for terminals
with 256 color support.
You can also change the colors for the help and shell prompts and
input and answer text by setting the appropriate field of `repl` in the `customize_colors` function
above (respectively, `help_color`, `shell_color`, `input_color`, and `answer_color`). For the
latter two, be sure that the `envcolors` field is also set to false.
It is also possible to apply boldface formatting by using
`Base.text_colors[:bold]` as a color. For instance, to print answers in
boldface font, one can use the following as a `~/.julia/config/startup.jl`:
```julia
function customize_colors(repl)
repl.envcolors = false
repl.answer_color = Base.text_colors[:bold]
end
atreplinit(customize_colors)
```
You can also customize the color used to render warning and informational messages by
setting the appropriate environment variables. For instance, to render error, warning, and informational
messages respectively in magenta, yellow, and cyan you can add the following to your
`~/.julia/config/startup.jl` file:
```julia
ENV["JULIA_ERROR_COLOR"] = :magenta
ENV["JULIA_WARN_COLOR"] = :yellow
ENV["JULIA_INFO_COLOR"] = :cyan
```
## TerminalMenus
TerminalMenus is a submodule of the Julia REPL and enables small, low-profile interactive menus in the terminal.
### Examples
```julia
import REPL
using REPL.TerminalMenus
options = ["apple", "orange", "grape", "strawberry",
"blueberry", "peach", "lemon", "lime"]
```
#### RadioMenu
The RadioMenu allows the user to select one option from the list. The `request`
function displays the interactive menu and returns the index of the selected
choice. If a user presses 'q' or `ctrl-c`, `request` will return a `-1`.
```julia
# `pagesize` is the number of items to be displayed at a time.
# The UI will scroll if the number of options is greater
# than the `pagesize`
menu = RadioMenu(options, pagesize=4)
# `request` displays the menu and returns the index after the
# user has selected a choice
choice = request("Choose your favorite fruit:", menu)
if choice != -1
println("Your favorite fruit is ", options[choice], "!")
else
println("Menu canceled.")
end
```
Output:
```
Choose your favorite fruit:
^ grape
strawberry
> blueberry
v peach
Your favorite fruit is blueberry!
```
#### MultiSelectMenu
The MultiSelectMenu allows users to select many choices from a list.
```julia
# here we use the default `pagesize` 10
menu = MultiSelectMenu(options)
# `request` returns a `Set` of selected indices
# if the menu us canceled (ctrl-c or q), return an empty set
choices = request("Select the fruits you like:", menu)
if length(choices) > 0
println("You like the following fruits:")
for i in choices
println(" - ", options[i])
end
else
println("Menu canceled.")
end
```
Output:
```
Select the fruits you like:
[press: d=done, a=all, n=none]
[ ] apple
> [X] orange
[X] grape
[ ] strawberry
[ ] blueberry
[X] peach
[ ] lemon
[ ] lime
You like the following fruits:
- orange
- grape
- peach
```
### Customization / Configuration
#### ConfiguredMenu subtypes
Starting with Julia 1.6, the recommended way to configure menus is via the constructor.
For instance, the default multiple-selection menu
```
julia> menu = MultiSelectMenu(options, pagesize=5);
julia> request(menu) # ASCII is used by default
[press: d=done, a=all, n=none]
[ ] apple
[X] orange
[ ] grape
> [X] strawberry
v [ ] blueberry
```
can instead be rendered with Unicode selection and navigation characters with
```julia
julia> menu = MultiSelectMenu(options, pagesize=5, charset=:unicode);
julia> request(menu)
[press: d=done, a=all, n=none]
⬚ apple
✓ orange
⬚ grape
→ ✓ strawberry
↓ ⬚ blueberry
```
More fine-grained configuration is also possible:
```julia
julia> menu = MultiSelectMenu(options, pagesize=5, charset=:unicode, checked="YEP!", unchecked="NOPE", cursor='⧐');
julia> request(menu)
julia> request(menu)
[press: d=done, a=all, n=none]
NOPE apple
YEP! orange
NOPE grape
⧐ YEP! strawberry
↓ NOPE blueberry
```
Aside from the overall `charset` option, for `RadioMenu` the configurable options are:
- `cursor::Char='>'|'→'`: character to use for cursor
- `up_arrow::Char='^'|'↑'`: character to use for up arrow
- `down_arrow::Char='v'|'↓'`: character to use for down arrow
- `updown_arrow::Char='I'|'↕'`: character to use for up/down arrow in one-line page
- `scroll_wrap::Bool=false`: optionally wrap-around at the beginning/end of a menu
- `ctrl_c_interrupt::Bool=true`: If `false`, return empty on ^C, if `true` throw InterruptException() on ^C
`MultiSelectMenu` adds:
- `checked::String="[X]"|"✓"`: string to use for checked
- `unchecked::String="[ ]"|"⬚")`: string to use for unchecked
You can create new menu types of your own.
Types that are derived from `TerminalMenus.ConfiguredMenu` configure the menu options at construction time.
#### Legacy interface
Prior to Julia 1.6, and still supported throughout Julia 1.x, one can also configure menus by calling
`TerminalMenus.config()`.
## References
### REPL
```@docs
Base.atreplinit
```
### TerminalMenus
#### Configuration
```@docs
REPL.TerminalMenus.Config
REPL.TerminalMenus.MultiSelectConfig
REPL.TerminalMenus.config
```
#### User interaction
```@docs
REPL.TerminalMenus.request
```
#### AbstractMenu extension interface
Any subtype of `AbstractMenu` must be mutable, and must contain the fields `pagesize::Int` and
`pageoffset::Int`.
Any subtype must also implement the following functions:
```@docs
REPL.TerminalMenus.pick
REPL.TerminalMenus.cancel
REPL.TerminalMenus.writeline
```
It must also implement either `options` or `numoptions`:
```@docs
REPL.TerminalMenus.options
REPL.TerminalMenus.numoptions
```
If the subtype does not have a field named `selected`, it must also implement
```@docs
REPL.TerminalMenus.selected
```
The following are optional but can allow additional customization:
```@docs
REPL.TerminalMenus.header
REPL.TerminalMenus.keypress
```
| JuliaZH | https://github.com/JuliaCN/JuliaZH.jl.git |
|
[
"MIT"
] | 1.6.0 | a7dc7bfc2fc6638c18241bfcdb9d73c7dd256482 | docs | 17659 | # 随机数
```@meta
DocTestSetup = :(using Random)
```
Random number generation in Julia uses the [Xoshiro256++](https://prng.di.unimi.it/) algorithm
by default, with per-`Task` state.
Other RNG types can be plugged in by inheriting the `AbstractRNG` type; they can then be used to
obtain multiple streams of random numbers.
Besides the default `TaskLocalRNG` type, the `Random` package also provides `MersenneTwister`,
`RandomDevice` (which exposes OS-provided entropy), and `Xoshiro` (for explicitly-managed
Xoshiro256++ streams).
Most functions related to random generation accept an optional `AbstractRNG` object as first argument.
Some also accept dimension specifications `dims...` (which can also be given as a tuple) to generate
arrays of random values.
In a multi-threaded program, you should generally use different RNG objects from different threads
or tasks in order to be thread-safe. However, the default RNG is thread-safe as of Julia 1.3
(using a per-thread RNG up to version 1.6, and per-task thereafter).
The provided RNGs can generate uniform random numbers of the following types:
[`Float16`](@ref), [`Float32`](@ref), [`Float64`](@ref), [`BigFloat`](@ref), [`Bool`](@ref),
[`Int8`](@ref), [`UInt8`](@ref), [`Int16`](@ref), [`UInt16`](@ref), [`Int32`](@ref),
[`UInt32`](@ref), [`Int64`](@ref), [`UInt64`](@ref), [`Int128`](@ref), [`UInt128`](@ref),
[`BigInt`](@ref) (or complex numbers of those types).
Random floating point numbers are generated uniformly in ``[0, 1)``. As `BigInt` represents
unbounded integers, the interval must be specified (e.g. `rand(big.(1:6))`).
另外,正态和指数分布是针对某些 `AbstractFloat` 和 `Complex` 类型,详细内容见 [`randn`](@ref) 和 [`randexp`](@ref)。
!!! warning
Because the precise way in which random numbers are generated is considered an implementation detail, bug fixes and speed improvements may change the stream of numbers that are generated after a version change. Relying on a specific seed or generated stream of numbers during unit testing is thus discouraged - consider testing properties of the methods in question instead.
## Random numbers module
```@docs
Random.Random
```
## Random generation functions
```@docs
Random.rand
Random.rand!
Random.bitrand
Random.randn
Random.randn!
Random.randexp
Random.randexp!
Random.randstring
```
## Subsequences, permutations and shuffling
```@docs
Random.randsubseq
Random.randsubseq!
Random.randperm
Random.randperm!
Random.randcycle
Random.randcycle!
Random.shuffle
Random.shuffle!
```
## Generators (creation and seeding)
```@docs
Random.seed!
Random.AbstractRNG
Random.TaskLocalRNG
Random.Xoshiro
Random.MersenneTwister
Random.RandomDevice
```
## Hooking into the `Random` API
There are two mostly orthogonal ways to extend `Random` functionalities:
1) generating random values of custom types
2) creating new generators
The API for 1) is quite functional, but is relatively recent so it may still have to evolve in subsequent releases of the `Random` module.
For example, it's typically sufficient to implement one `rand` method in order to have all other usual methods work automatically.
The API for 2) is still rudimentary, and may require more work than strictly necessary from the implementor,
in order to support usual types of generated values.
### Generating random values of custom types
Generating random values for some distributions may involve various trade-offs. *Pre-computed* values, such as an [alias table](https://en.wikipedia.org/wiki/Alias_method) for discrete distributions, or [“squeezing” functions](https://en.wikipedia.org/wiki/Rejection_sampling) for univariate distributions, can speed up sampling considerably. How much information should be pre-computed can depend on the number of values we plan to draw from a distribution. Also, some random number generators can have certain properties that various algorithms may want to exploit.
The `Random` module defines a customizable framework for obtaining random values that can address these issues. Each invocation of `rand` generates a *sampler* which can be customized with the above trade-offs in mind, by adding methods to `Sampler`, which in turn can dispatch on the random number generator, the object that characterizes the distribution, and a suggestion for the number of repetitions. Currently, for the latter, `Val{1}` (for a single sample) and `Val{Inf}` (for an arbitrary number) are used, with `Random.Repetition` an alias for both.
The object returned by `Sampler` is then used to generate the random values. When implementing the random generation interface for a value `X` that can be sampled from, the implementor should define the method
```julia
rand(rng, sampler)
```
for the particular `sampler` returned by `Sampler(rng, X, repetition)`.
Samplers can be arbitrary values that implement `rand(rng, sampler)`, but for most applications the following predefined samplers may be sufficient:
1. `SamplerType{T}()` can be used for implementing samplers that draw from type `T` (e.g. `rand(Int)`). This is the default returned by `Sampler` for *types*.
2. `SamplerTrivial(self)` is a simple wrapper for `self`, which can be accessed with `[]`. This is the recommended sampler when no pre-computed information is needed (e.g. `rand(1:3)`), and is the default returned by `Sampler` for *values*.
3. `SamplerSimple(self, data)` also contains the additional `data` field, which can be used to store arbitrary pre-computed values, which should be computed in a *custom method* of `Sampler`.
We provide examples for each of these. We assume here that the choice of algorithm is independent of the RNG, so we use `AbstractRNG` in our signatures.
```@docs
Random.Sampler
Random.SamplerType
Random.SamplerTrivial
Random.SamplerSimple
```
Decoupling pre-computation from actually generating the values is part of the API, and is also available to the user. As an example, assume that `rand(rng, 1:20)` has to be called repeatedly in a loop: the way to take advantage of this decoupling is as follows:
```julia
rng = MersenneTwister()
sp = Random.Sampler(rng, 1:20) # or Random.Sampler(MersenneTwister, 1:20)
for x in X
n = rand(rng, sp) # similar to n = rand(rng, 1:20)
# use n
end
```
This is the mechanism that is also used in the standard library, e.g. by the default implementation of random array generation (like in `rand(1:20, 10)`).
#### Generating values from a type
Given a type `T`, it's currently assumed that if `rand(T)` is defined, an object of type `T` will be produced. `SamplerType` is the *default sampler for types*. In order to define random generation of values of type `T`, the `rand(rng::AbstractRNG, ::Random.SamplerType{T})` method should be defined, and should return values what `rand(rng, T)` is expected to return.
Let's take the following example: we implement a `Die` type, with a variable number `n` of sides, numbered from `1` to `n`. We want `rand(Die)` to produce a `Die` with a random number of up to 20 sides (and at least 4):
```jldoctest Die
struct Die
nsides::Int # number of sides
end
Random.rand(rng::AbstractRNG, ::Random.SamplerType{Die}) = Die(rand(rng, 4:20))
# output
```
Scalar and array methods for `Die` now work as expected:
```jldoctest Die; setup = :(Random.seed!(1))
julia> rand(Die)
Die(7)
julia> rand(MersenneTwister(0), Die)
Die(11)
julia> rand(Die, 3)
3-element Vector{Die}:
Die(13)
Die(8)
Die(20)
julia> a = Vector{Die}(undef, 3); rand!(a)
3-element Vector{Die}:
Die(4)
Die(14)
Die(10)
```
#### A simple sampler without pre-computed data
Here we define a sampler for a collection. If no pre-computed data is required, it can be implemented with a `SamplerTrivial` sampler, which is in fact the *default fallback for values*.
In order to define random generation out of objects of type `S`, the following method should be defined: `rand(rng::AbstractRNG, sp::Random.SamplerTrivial{S})`. Here, `sp` simply wraps an object of type `S`, which can be accessed via `sp[]`. Continuing the `Die` example, we want now to define `rand(d::Die)` to produce an `Int` corresponding to one of `d`'s sides:
```jldoctest Die; setup = :(Random.seed!(1))
julia> Random.rand(rng::AbstractRNG, d::Random.SamplerTrivial{Die}) = rand(rng, 1:d[].nsides);
julia> rand(Die(4))
1
julia> rand(Die(4), 3)
3-element Vector{Any}:
3
2
4
```
Given a collection type `S`, it's currently assumed that if `rand(::S)` is defined, an object of type `eltype(S)` will be produced. In the last example, a `Vector{Any}` is produced; the reason is that `eltype(Die) == Any`. The remedy is to define `Base.eltype(::Type{Die}) = Int`.
#### Generating values for an `AbstractFloat` type
`AbstractFloat` types are special-cased, because by default random values are not produced in the whole type domain, but rather in `[0,1)`. The following method should be implemented for `T <: AbstractFloat`: `Random.rand(::AbstractRNG, ::Random.SamplerTrivial{Random.CloseOpen01{T}})`
#### An optimized sampler with pre-computed data
Consider a discrete distribution, where numbers `1:n` are drawn with given probabilities that sum to one. When many values are needed from this distribution, the fastest method is using an [alias table](https://en.wikipedia.org/wiki/Alias_method). We don't provide the algorithm for building such a table here, but suppose it is available in `make_alias_table(probabilities)` instead, and `draw_number(rng, alias_table)` can be used to draw a random number from it.
Suppose that the distribution is described by
```julia
struct DiscreteDistribution{V <: AbstractVector}
probabilities::V
end
```
and that we *always* want to build an alias table, regardless of the number of values needed (we learn how to customize this below). The methods
```julia
Random.eltype(::Type{<:DiscreteDistribution}) = Int
function Random.Sampler(::Type{<:AbstractRNG}, distribution::DiscreteDistribution, ::Repetition)
SamplerSimple(disribution, make_alias_table(distribution.probabilities))
end
```
should be defined to return a sampler with pre-computed data, then
```julia
function rand(rng::AbstractRNG, sp::SamplerSimple{<:DiscreteDistribution})
draw_number(rng, sp.data)
end
```
will be used to draw the values.
#### Custom sampler types
The `SamplerSimple` type is sufficient for most use cases with precomputed data. However, in order to demonstrate how to use custom sampler types, here we implement something similar to `SamplerSimple`.
Going back to our `Die` example: `rand(::Die)` uses random generation from a range, so there is an opportunity for this optimization. We call our custom sampler `SamplerDie`.
```julia
import Random: Sampler, rand
struct SamplerDie <: Sampler{Int} # generates values of type Int
die::Die
sp::Sampler{Int} # this is an abstract type, so this could be improved
end
Sampler(RNG::Type{<:AbstractRNG}, die::Die, r::Random.Repetition) =
SamplerDie(die, Sampler(RNG, 1:die.nsides, r))
# the `r` parameter will be explained later on
rand(rng::AbstractRNG, sp::SamplerDie) = rand(rng, sp.sp)
```
It's now possible to get a sampler with `sp = Sampler(rng, die)`, and use `sp` instead of `die` in any `rand` call involving `rng`. In the simplistic example above, `die` doesn't need to be stored in `SamplerDie` but this is often the case in practice.
Of course, this pattern is so frequent that the helper type used above, namely `Random.SamplerSimple`, is available,
saving us the definition of `SamplerDie`: we could have implemented our decoupling with:
```julia
Sampler(RNG::Type{<:AbstractRNG}, die::Die, r::Random.Repetition) =
SamplerSimple(die, Sampler(RNG, 1:die.nsides, r))
rand(rng::AbstractRNG, sp::SamplerSimple{Die}) = rand(rng, sp.data)
```
Here, `sp.data` refers to the second parameter in the call to the `SamplerSimple` constructor
(in this case equal to `Sampler(rng, 1:die.nsides, r)`), while the `Die` object can be accessed
via `sp[]`.
Like `SamplerDie`, any custom sampler must be a subtype of `Sampler{T}` where `T` is the type
of the generated values. Note that `SamplerSimple(x, data) isa Sampler{eltype(x)}`,
so this constrains what the first argument to `SamplerSimple` can be
(it's recommended to use `SamplerSimple` like in the `Die` example, where
`x` is simply forwarded while defining a `Sampler` method).
Similarly, `SamplerTrivial(x) isa Sampler{eltype(x)}`.
Another helper type is currently available for other cases, `Random.SamplerTag`, but is
considered as internal API, and can break at any time without proper deprecations.
#### Using distinct algorithms for scalar or array generation
In some cases, whether one wants to generate only a handful of values or a large number of values
will have an impact on the choice of algorithm. This is handled with the third parameter of the
`Sampler` constructor. Let's assume we defined two helper types for `Die`, say `SamplerDie1`
which should be used to generate only few random values, and `SamplerDieMany` for many values.
We can use those types as follows:
```julia
Sampler(RNG::Type{<:AbstractRNG}, die::Die, ::Val{1}) = SamplerDie1(...)
Sampler(RNG::Type{<:AbstractRNG}, die::Die, ::Val{Inf}) = SamplerDieMany(...)
```
Of course, `rand` must also be defined on those types (i.e. `rand(::AbstractRNG, ::SamplerDie1)` and `rand(::AbstractRNG, ::SamplerDieMany)`). Note that, as usual, `SamplerTrivial` and `SamplerSimple` can be used if custom types are not necessary.
Note: `Sampler(rng, x)` is simply a shorthand for `Sampler(rng, x, Val(Inf))`, and
`Random.Repetition` is an alias for `Union{Val{1}, Val{Inf}}`.
### Creating new generators
The API is not clearly defined yet, but as a rule of thumb:
1) any `rand` method producing "basic" types (`isbitstype` integer and floating types in `Base`)
should be defined for this specific RNG, if they are needed;
2) other documented `rand` methods accepting an `AbstractRNG` should work out of the box,
(provided the methods from 1) what are relied on are implemented),
but can of course be specialized for this RNG if there is room for optimization;
3) `copy` for pseudo-RNGs should return an independent copy that generates the exact same random sequence as the
original from that point when called in the same way. When this is not feasible (e.g. hardware-based RNGs),
`copy` must not be implemented.
Concerning 1), a `rand` method may happen to work automatically, but it's not officially
supported and may break without warnings in a subsequent release.
To define a new `rand` method for an hypothetical `MyRNG` generator, and a value specification `s`
(e.g. `s == Int`, or `s == 1:10`) of type `S==typeof(s)` or `S==Type{s}` if `s` is a type,
the same two methods as we saw before must be defined:
1) `Sampler(::Type{MyRNG}, ::S, ::Repetition)`, which returns an object of type say `SamplerS`
2) `rand(rng::MyRNG, sp::SamplerS)`
It can happen that `Sampler(rng::AbstractRNG, ::S, ::Repetition)` is
already defined in the `Random` module. It would then be possible to
skip step 1) in practice (if one wants to specialize generation for
this particular RNG type), but the corresponding `SamplerS` type is
considered as internal detail, and may be changed without warning.
#### Specializing array generation
In some cases, for a given RNG type, generating an array of random
values can be more efficient with a specialized method than by merely
using the decoupling technique explained before. This is for example
the case for `MersenneTwister`, which natively writes random values in
an array.
To implement this specialization for `MyRNG`
and for a specification `s`, producing elements of type `S`,
the following method can be defined:
`rand!(rng::MyRNG, a::AbstractArray{S}, ::SamplerS)`,
where `SamplerS` is the type of the sampler returned by `Sampler(MyRNG, s, Val(Inf))`.
Instead of `AbstractArray`, it's possible to implement the functionality only for a subtype, e.g. `Array{S}`.
The non-mutating array method of `rand` will automatically call this specialization internally.
```@meta
DocTestSetup = nothing
```
# Reproducibility
By using an RNG parameter initialized with a given seed, you can reproduce the same pseudorandom
number sequence when running your program multiple times. However, a minor release of Julia (e.g.
1.3 to 1.4) *may change* the sequence of pseudorandom numbers generated from a specific seed, in
particular if `MersenneTwister` is used. (Even if the sequence produced by a low-level function like
[`rand`](@ref) does not change, the output of higher-level functions like [`randsubseq`](@ref) may
change due to algorithm updates.) Rationale: guaranteeing that pseudorandom streams never change
prohibits many algorithmic improvements.
If you need to guarantee exact reproducibility of random data, it is advisable to simply *save the
data* (e.g. as a supplementary attachment in a scientific publication). (You can also, of course,
specify a particular Julia version and package manifest, especially if you require bit
reproducibility.)
Software tests that rely on *specific* "random" data should also generally either save the data,
embed it into the test code, or use third-party packages like
[StableRNGs.jl](https://github.com/JuliaRandom/StableRNGs.jl). On the other hand, tests that should
pass for *most* random data (e.g. testing `A \ (A*x) ≈ x` for a random matrix `A = randn(n,n)`) can
use an RNG with a fixed seed to ensure that simply running the test many times does not encounter a
failure due to very improbable data (e.g. an extremely ill-conditioned matrix).
The statistical *distribution* from which random samples are drawn *is* guaranteed to be the same
across any minor Julia releases.
| JuliaZH | https://github.com/JuliaCN/JuliaZH.jl.git |
|
[
"MIT"
] | 1.6.0 | a7dc7bfc2fc6638c18241bfcdb9d73c7dd256482 | docs | 1641 | # SHA
用法非常直接:
```julia
julia> using SHA
julia> bytes2hex(sha256("test"))
"9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08"
```
Each exported function (at the time of this writing, SHA-1, SHA-2 224, 256, 384 and 512, and SHA-3 224, 256, 384 and 512 functions are implemented) takes in either an `AbstractVector{UInt8}`, an `AbstractString` or an `IO` object. This makes it trivial to checksum a file:
```julia
shell> cat /tmp/test.txt
test
julia> using SHA
julia> open("/tmp/test.txt") do f
sha2_256(f)
end
32-element Array{UInt8,1}:
0x9f
0x86
0xd0
0x81
0x88
0x4c
0x7d
0x65
⋮
0x5d
0x6c
0x15
0xb0
0xf0
0x0a
0x08
```
Due to the colloquial usage of `sha256` to refer to `sha2_256`, convenience functions are provided, mapping `shaxxx()` function calls to `sha2_xxx()`. For SHA-3, no such colloquialisms exist and the user must use the full `sha3_xxx()` names.
`shaxxx()` takes `AbstractString` and array-like objects (`NTuple` and `Array`) with elements of type `UInt8`.
To create a hash from multiple items the `SHAX_XXX_CTX()` types can be used to create a stateful hash object that
is updated with `update!` and finalized with `digest!`
```julia
julia> ctx = SHA2_256_CTX()
SHA2 256-bit hash state
julia> update!(ctx, b"some data")
0x0000000000000009
julia> update!(ctx, b"some more data")
0x0000000000000017
julia> digest!(ctx)
32-element Vector{UInt8}:
0xbe
0xcf
0x23
0xda
0xaf
0x02
⋮
0x25
0x52
0x19
0xa0
0x8b
0xc5
```
Note that, at the time of this writing, the SHA3 code is not optimized, and as such is roughly an order of magnitude slower than SHA2.
| JuliaZH | https://github.com/JuliaCN/JuliaZH.jl.git |
|
[
"MIT"
] | 1.6.0 | a7dc7bfc2fc6638c18241bfcdb9d73c7dd256482 | docs | 96 | # 序列化
```@docs
Serialization.serialize
Serialization.deserialize
Serialization.writeheader
```
| JuliaZH | https://github.com/JuliaCN/JuliaZH.jl.git |
|
[
"MIT"
] | 1.6.0 | a7dc7bfc2fc6638c18241bfcdb9d73c7dd256482 | docs | 200 | # 共享数组
```@docs
SharedArrays.SharedArray
SharedArrays.SharedVector
SharedArrays.SharedMatrix
SharedArrays.procs(::SharedArray)
SharedArrays.sdata
SharedArrays.indexpids
SharedArrays.localindices
```
| JuliaZH | https://github.com/JuliaCN/JuliaZH.jl.git |
|
[
"MIT"
] | 1.6.0 | a7dc7bfc2fc6638c18241bfcdb9d73c7dd256482 | docs | 574 | # 套接字
```@docs
Sockets.Sockets
Sockets.connect(::TCPSocket, ::Integer)
Sockets.connect(::AbstractString)
Sockets.listen(::Any)
Sockets.listen(::AbstractString)
Sockets.getaddrinfo
Sockets.getipaddr
Sockets.getipaddrs
Sockets.islinklocaladdr
Sockets.getalladdrinfo
Sockets.DNSError
Sockets.getnameinfo
Sockets.getsockname
Sockets.getpeername
Sockets.IPAddr
Sockets.IPv4
Sockets.IPv6
Sockets.@ip_str
Sockets.TCPSocket
Sockets.UDPSocket
Sockets.accept
Sockets.listenany
Sockets.bind
Sockets.send
Sockets.recv
Sockets.recvfrom
Sockets.setopt
Sockets.nagle
Sockets.quickack
```
| JuliaZH | https://github.com/JuliaCN/JuliaZH.jl.git |
|
[
"MIT"
] | 1.6.0 | a7dc7bfc2fc6638c18241bfcdb9d73c7dd256482 | docs | 8667 | # 稀疏数组
```@meta
DocTestSetup = :(using SparseArrays, LinearAlgebra)
```
Julia 在 `SparseArrays` 标准库模块中提供了对稀疏向量和[稀疏矩阵](https://en.wikipedia.org/wiki/Sparse_matrix)的支持。与稠密数组相比,包含足够多零值的稀疏数组在以特殊的数据结构存储时可以节省大量的空间和运算时间。
## [压缩稀疏列(CSC)稀疏矩阵存储](@id man-csc)
在 Julia 中,稀疏矩阵是按照[压缩稀疏列(CSC)格式](https://en.wikipedia.org/wiki/Sparse_matrix#Compressed_sparse_column_.28CSC_or_CCS.29)存储的。Julia 稀疏矩阵具有 [`SparseMatrixCSC{Tv,Ti}`](@ref) 类型,其中 `Tv` 是存储值的类型,`Ti` 是存储列指针和行索引的整型类型。`SparseMatrixCSC` 的内部表示如下所示:
```julia
struct SparseMatrixCSC{Tv,Ti<:Integer} <: AbstractSparseMatrixCSC{Tv,Ti}
m::Int # Number of rows
n::Int # Number of columns
colptr::Vector{Ti} # Column j is in colptr[j]:(colptr[j+1]-1)
rowval::Vector{Ti} # Row indices of stored values
nzval::Vector{Tv} # Stored values, typically nonzeros
end
```
压缩稀疏列存储格式使得访问稀疏矩阵的列元素非常简单快速,而访问稀疏矩阵的行会非常缓慢。在 CSC 稀疏矩阵中执行类似插入新元素的操作也会非常慢。这是由于在稀疏矩阵中插入新元素时,在插入点之后的所有元素都要向后移动一位。
All operations on sparse matrices are carefully implemented to exploit the CSC data structure
for performance, and to avoid expensive operations.
如果你有来自不同应用或库的 CSC 格式数据,并且想要将它导入 Julia,确保使用基于 1 的索引。每个列中的行索引都要是有序的。如果你的 `SparseMatrixCSC` 对象包含无序的行索引,一个快速将它们排序的方法是做一次二重转置。
In some applications, it is convenient to store explicit zero values in a `SparseMatrixCSC`. These
*are* accepted by functions in `Base` (but there is no guarantee that they will be preserved in
mutating operations). Such explicitly stored zeros are treated as structural nonzeros by many
routines. The [`nnz`](@ref) function returns the number of elements explicitly stored in the
sparse data structure, including non-structural zeros. In order to count the exact number of
numerical nonzeros, use [`count(!iszero, x)`](@ref), which inspects every stored element of a sparse
matrix. [`dropzeros`](@ref), and the in-place [`dropzeros!`](@ref), can be used to
remove stored zeros from the sparse matrix.
```jldoctest
julia> A = sparse([1, 1, 2, 3], [1, 3, 2, 3], [0, 1, 2, 0])
3×3 SparseMatrixCSC{Int64, Int64} with 4 stored entries:
0 ⋅ 1
⋅ 2 ⋅
⋅ ⋅ 0
julia> dropzeros(A)
3×3 SparseMatrixCSC{Int64, Int64} with 2 stored entries:
⋅ ⋅ 1
⋅ 2 ⋅
⋅ ⋅ ⋅
```
## 稀疏向量储存
Sparse vectors are stored in a close analog to compressed sparse column format for sparse
matrices. In Julia, sparse vectors have the type [`SparseVector{Tv,Ti}`](@ref) where `Tv`
is the type of the stored values and `Ti` the integer type for the indices. The internal
representation is as follows:
```julia
struct SparseVector{Tv,Ti<:Integer} <: AbstractSparseVector{Tv,Ti}
n::Int # Length of the sparse vector
nzind::Vector{Ti} # Indices of stored values
nzval::Vector{Tv} # Stored values, typically nonzeros
end
```
对于 [`SparseMatrixCSC`](@ref), `SparseVector` 类型也能包含显示存储的,零值。(见 [稀疏矩阵存储](@ref man-csc)。)
## 稀疏向量与矩阵构造函数
创建一个稀疏矩阵的最简单的方法是使用一个与 Julia 提供的用来处理稠密矩阵的[`zeros`](@ref) 等价的函数。要产生一个稀疏矩阵,你可以用同样的名字加上 `sp` 前缀:
```jldoctest
julia> spzeros(3)
3-element SparseVector{Float64, Int64} with 0 stored entries
```
[`sparse`](@ref) 函数通常是一个构建稀疏矩阵的便捷方法。例如,要构建一个稀疏矩阵,我们可以输入一个列索引向量 `I`,一个行索引向量 `J`,一个储存值的向量 `V`(这也叫作 [COO(坐标) 格式](https://en.wikipedia.org/wiki/Sparse_matrix#Coordinate_list_.28COO.29))。
然后 `sparse(I,J,V)` 创建一个满足 `S[I[k], J[k]] = V[k]` 的稀疏矩阵。等价的稀疏向量构建函数是 [`sparsevec`](@ref),它接受(行)索引向量 `I` 和储存值的向量 `V` 并创建一个满足 `R[I[k]] = V[k]` 的向量 `R`。
```jldoctest sparse_function
julia> I = [1, 4, 3, 5]; J = [4, 7, 18, 9]; V = [1, 2, -5, 3];
julia> S = sparse(I,J,V)
5×18 SparseMatrixCSC{Int64, Int64} with 4 stored entries:
⠀⠈⠀⡀⠀⠀⠀⠀⠠
⠀⠀⠀⠀⠁⠀⠀⠀⠀
julia> R = sparsevec(I,V)
5-element SparseVector{Int64, Int64} with 4 stored entries:
[1] = 1
[3] = -5
[4] = 2
[5] = 3
```
The inverse of the [`sparse`](@ref) and [`sparsevec`](@ref) functions is
[`findnz`](@ref), which retrieves the inputs used to create the sparse array.
[`findall(!iszero, x)`](@ref) returns the cartesian indices of non-zero entries in `x`
(including stored entries equal to zero).
```jldoctest sparse_function
julia> findnz(S)
([1, 4, 5, 3], [4, 7, 9, 18], [1, 2, 3, -5])
julia> findall(!iszero, S)
4-element Vector{CartesianIndex{2}}:
CartesianIndex(1, 4)
CartesianIndex(4, 7)
CartesianIndex(5, 9)
CartesianIndex(3, 18)
julia> findnz(R)
([1, 3, 4, 5], [1, -5, 2, 3])
julia> findall(!iszero, R)
4-element Vector{Int64}:
1
3
4
5
```
另一个创建稀疏数组的方法是使用 [`sparse`](@ref) 函数将一个稠密数组转化为稀疏数组:
```jldoctest
julia> sparse(Matrix(1.0I, 5, 5))
5×5 SparseMatrixCSC{Float64, Int64} with 5 stored entries:
1.0 ⋅ ⋅ ⋅ ⋅
⋅ 1.0 ⋅ ⋅ ⋅
⋅ ⋅ 1.0 ⋅ ⋅
⋅ ⋅ ⋅ 1.0 ⋅
⋅ ⋅ ⋅ ⋅ 1.0
julia> sparse([1.0, 0.0, 1.0])
3-element SparseVector{Float64, Int64} with 2 stored entries:
[1] = 1.0
[3] = 1.0
```
You can go in the other direction using the [`Array`](@ref) constructor. The [`issparse`](@ref)
function can be used to query if a matrix is sparse.
```jldoctest
julia> issparse(spzeros(5))
true
```
## 稀疏矩阵的操作
Arithmetic operations on sparse matrices also work as they do on dense matrices. Indexing of,
assignment into, and concatenation of sparse matrices work in the same way as dense matrices.
Indexing operations, especially assignment, are expensive, when carried out one element at a time.
In many cases it may be better to convert the sparse matrix into `(I,J,V)` format using [`findnz`](@ref),
manipulate the values or the structure in the dense vectors `(I,J,V)`, and then reconstruct
the sparse matrix.
## Correspondence of dense and sparse methods
The following table gives a correspondence between built-in methods on sparse matrices and their
corresponding methods on dense matrix types. In general, methods that generate sparse matrices
differ from their dense counterparts in that the resulting matrix follows the same sparsity pattern
as a given sparse matrix `S`, or that the resulting sparse matrix has density `d`, i.e. each matrix
element has a probability `d` of being non-zero.
Details can be found in the [Sparse Vectors and Matrices](@ref stdlib-sparse-arrays)
section of the standard library reference.
| 构造函数 | 密度 | 说明 |
|:-------------------------- |:---------------------- |:--------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| [`spzeros(m,n)`](@ref) | [`zeros(m,n)`](@ref) | Creates a *m*-by-*n* matrix of zeros. ([`spzeros(m,n)`](@ref) is empty.) |
| [`sparse(I,n,n)`](@ref) | [`Matrix(I,n,n)`](@ref)| Creates a *n*-by-*n* identity matrix. |
| [`sparse(A)`](@ref) | [`Array(S)`](@ref) | Interconverts between dense and sparse formats. |
| [`sprand(m,n,d)`](@ref) | [`rand(m,n)`](@ref) | Creates a *m*-by-*n* random matrix (of density *d*) with iid non-zero elements distributed uniformly on the half-open interval ``[0, 1)``. |
| [`sprandn(m,n,d)`](@ref) | [`randn(m,n)`](@ref) | Creates a *m*-by-*n* random matrix (of density *d*) with iid non-zero elements distributed according to the standard normal (Gaussian) distribution. |
| [`sprandn(rng,m,n,d)`](@ref) | [`randn(rng,m,n)`](@ref) | Creates a *m*-by-*n* random matrix (of density *d*) with iid non-zero elements generated with the `rng` random number generator |
# [Sparse Arrays](@id stdlib-sparse-arrays)
```@docs
SparseArrays.AbstractSparseArray
SparseArrays.AbstractSparseVector
SparseArrays.AbstractSparseMatrix
SparseArrays.SparseVector
SparseArrays.SparseMatrixCSC
SparseArrays.sparse
SparseArrays.sparsevec
SparseArrays.issparse
SparseArrays.nnz
SparseArrays.findnz
SparseArrays.spzeros
SparseArrays.spdiagm
SparseArrays.blockdiag
SparseArrays.sprand
SparseArrays.sprandn
SparseArrays.nonzeros
SparseArrays.rowvals
SparseArrays.nzrange
SparseArrays.droptol!
SparseArrays.dropzeros!
SparseArrays.dropzeros
SparseArrays.permute
permute!{Tv, Ti, Tp <: Integer, Tq <: Integer}(::SparseMatrixCSC{Tv,Ti}, ::SparseMatrixCSC{Tv,Ti}, ::AbstractArray{Tp,1}, ::AbstractArray{Tq,1})
```
```@meta
DocTestSetup = nothing
```
| JuliaZH | https://github.com/JuliaCN/JuliaZH.jl.git |
|
[
"MIT"
] | 1.6.0 | a7dc7bfc2fc6638c18241bfcdb9d73c7dd256482 | docs | 343 | # 统计
```@meta
DocTestSetup = :(using Statistics)
```
统计模块包含了基本的统计函数。
```@docs
Statistics.std
Statistics.stdm
Statistics.var
Statistics.varm
Statistics.cor
Statistics.cov
Statistics.mean!
Statistics.mean
Statistics.median!
Statistics.median
Statistics.middle
Statistics.quantile!
Statistics.quantile
```
```@meta
DocTestSetup = nothing
```
| JuliaZH | https://github.com/JuliaCN/JuliaZH.jl.git |
|
[
"MIT"
] | 1.6.0 | a7dc7bfc2fc6638c18241bfcdb9d73c7dd256482 | docs | 2421 | # TOML
TOML.jl is a Julia standard library for parsing and writing [TOML
v1.0](https://toml.io/en/) files.
## Parsing TOML data
```jldoctest
julia> using TOML
julia> data = """
[database]
server = "192.168.1.1"
ports = [ 8001, 8001, 8002 ]
""";
julia> TOML.parse(data)
Dict{String, Any} with 1 entry:
"database" => Dict{String, Any}("server"=>"192.168.1.1", "ports"=>[8001, 8001…
```
To parse a file, use [`TOML.parsefile`](@ref). If the file has a syntax error,
an exception is thrown:
```jldoctest
julia> using TOML
julia> TOML.parse("""
value = 0.0.0
""")
ERROR: TOML Parser error:
none:1:16 error: failed to parse value
value = 0.0.0
^
[...]
```
There are other versions of the parse functions ([`TOML.tryparse`](@ref)
and [`TOML.tryparsefile`]) that instead of throwing exceptions on parser error
returns a [`TOML.ParserError`](@ref) with information:
```jldoctest
julia> using TOML
julia> err = TOML.tryparse("""
value = 0.0.0
""");
julia> err.type
ErrGenericValueError::ErrorType = 14
julia> err.line
1
julia> err.column
16
```
## Exporting data to TOML file
The [`TOML.print`](@ref) function is used to print (or serialize) data into TOML
format.
```jldoctest
julia> using TOML
julia> data = Dict(
"names" => ["Julia", "Julio"],
"age" => [10, 20],
);
julia> TOML.print(data)
names = ["Julia", "Julio"]
age = [10, 20]
julia> fname = tempname();
julia> open(fname, "w") do io
TOML.print(io, data)
end
julia> TOML.parsefile(fname)
Dict{String, Any} with 2 entries:
"names" => ["Julia", "Julio"]
"age" => [10, 20]
```
Keys can be sorted according to some value
```jldoctest
julia> using TOML
julia> TOML.print(Dict(
"abc" => 1,
"ab" => 2,
"abcd" => 3,
); sorted=true, by=length)
ab = 2
abc = 1
abcd = 3
```
For custom structs, pass a function that converts the struct to a supported
type
```jldoctest
julia> using TOML
julia> struct MyStruct
a::Int
b::String
end
julia> TOML.print(Dict("foo" => MyStruct(5, "bar"))) do x
x isa MyStruct && return [x.a, x.b]
error("unhandled type $(typeof(x))")
end
foo = [5, "bar"]
```
## References
```@docs
TOML.parse
TOML.parsefile
TOML.tryparse
TOML.tryparsefile
TOML.print
TOML.Parser
TOML.ParserError
```
| JuliaZH | https://github.com/JuliaCN/JuliaZH.jl.git |
|
[
"MIT"
] | 1.6.0 | a7dc7bfc2fc6638c18241bfcdb9d73c7dd256482 | docs | 9069 | # 单元测试
```@meta
DocTestSetup = :(using Test)
```
## 测试 Julia Base 库
Julia 处于快速开发中,有着可以扩展的测试套件,用来跨平台测试功能。
如果你是通过源代码构建的 Julia ,你可以通过 `make test` 来运行这个测试套件。
如果是通过二进制包安装的,你可以通过 `Base.runtests()` 来运行这个测试套件。
```@docs
Base.runtests
```
## 基本的单元测试
The `Test` module provides simple *unit testing* functionality. Unit testing is a way to
see if your code is correct by checking that the results are what you expect. It can be helpful
to ensure your code still works after you make changes, and can be used when developing as a way
of specifying the behaviors your code should have when complete.
简单的单元测试可以通过 `@test` 和 `@test_throws` 宏来完成:
```@docs
Test.@test
Test.@test_throws
```
例如,假设我们想要测试新的函数 `foo(x)` 是否按照期望的方式工作:
```jldoctest testfoo
julia> using Test
julia> foo(x) = length(x)^2
foo (generic function with 1 method)
```
If the condition is true, a `Pass` is returned:
```jldoctest testfoo
julia> @test foo("bar") == 9
Test Passed
Expression: foo("bar") == 9
Evaluated: 9 == 9
julia> @test foo("fizz") >= 10
Test Passed
Expression: foo("fizz") >= 10
Evaluated: 16 >= 10
```
如果条件为假,则返回 `Fail` 并抛出异常。
```jldoctest testfoo
julia> @test foo("f") == 20
Test Failed at none:1
Expression: foo("f") == 20
Evaluated: 1 == 20
ERROR: There was an error during testing
```
If the condition could not be evaluated because an exception was thrown, which occurs in this
case because `length` is not defined for symbols, an `Error` object is returned and an exception
is thrown:
```julia-repl
julia> @test foo(:cat) == 1
Error During Test
Test threw an exception of type MethodError
Expression: foo(:cat) == 1
MethodError: no method matching length(::Symbol)
Closest candidates are:
length(::SimpleVector) at essentials.jl:256
length(::Base.MethodList) at reflection.jl:521
length(::MethodTable) at reflection.jl:597
...
Stacktrace:
[...]
ERROR: There was an error during testing
```
If we expect that evaluating an expression *should* throw an exception, then we can use `@test_throws`
to check that this occurs:
```jldoctest testfoo
julia> @test_throws MethodError foo(:cat)
Test Passed
Expression: foo(:cat)
Thrown: MethodError
```
## Working with Test Sets
Typically a large number of tests are used to make sure functions work correctly over a range
of inputs. In the event a test fails, the default behavior is to throw an exception immediately.
However, it is normally preferable to run the rest of the tests first to get a better picture
of how many errors there are in the code being tested.
!!! note
The `@testset` will create a local scope of its own when running the tests in it.
The `@testset` macro can be used to group tests into *sets*. All the tests in a test set will
be run, and at the end of the test set a summary will be printed. If any of the tests failed,
or could not be evaluated due to an error, the test set will then throw a `TestSetException`.
```@docs
Test.@testset
Test.TestSetException
```
We can put our tests for the `foo(x)` function in a test set:
```jldoctest testfoo
julia> @testset "Foo Tests" begin
@test foo("a") == 1
@test foo("ab") == 4
@test foo("abc") == 9
end;
Test Summary: | Pass Total
Foo Tests | 3 3
```
测试集可以嵌套:
```jldoctest testfoo
julia> @testset "Foo Tests" begin
@testset "Animals" begin
@test foo("cat") == 9
@test foo("dog") == foo("cat")
end
@testset "Arrays $i" for i in 1:3
@test foo(zeros(i)) == i^2
@test foo(fill(1.0, i)) == i^2
end
end;
Test Summary: | Pass Total
Foo Tests | 8 8
```
In the event that a nested test set has no failures, as happened here, it will be hidden in the
summary, unless the `verbose=true` option is passed:
```jldoctest testfoo
julia> @testset verbose = true "Foo Tests" begin
@testset "Animals" begin
@test foo("cat") == 9
@test foo("dog") == foo("cat")
end
@testset "Arrays $i" for i in 1:3
@test foo(zeros(i)) == i^2
@test foo(fill(1.0, i)) == i^2
end
end;
Test Summary: | Pass Total
Foo Tests | 8 8
Animals | 2 2
Arrays 1 | 2 2
Arrays 2 | 2 2
Arrays 3 | 2 2
```
If we do have a test failure, only the details for the failed test sets will be shown:
```julia-repl
julia> @testset "Foo Tests" begin
@testset "Animals" begin
@testset "Felines" begin
@test foo("cat") == 9
end
@testset "Canines" begin
@test foo("dog") == 9
end
end
@testset "Arrays" begin
@test foo(zeros(2)) == 4
@test foo(fill(1.0, 4)) == 15
end
end
Arrays: Test Failed
Expression: foo(fill(1.0, 4)) == 15
Evaluated: 16 == 15
[...]
Test Summary: | Pass Fail Total
Foo Tests | 3 1 4
Animals | 2 2
Arrays | 1 1 2
ERROR: Some tests did not pass: 3 passed, 1 failed, 0 errored, 0 broken.
```
## Other Test Macros
As calculations on floating-point values can be imprecise, you can perform approximate equality
checks using either `@test a ≈ b` (where `≈`, typed via tab completion of `\approx`, is the
[`isapprox`](@ref) function) or use [`isapprox`](@ref) directly.
```jldoctest
julia> @test 1 ≈ 0.999999999
Test Passed
Expression: 1 ≈ 0.999999999
Evaluated: 1 ≈ 0.999999999
julia> @test 1 ≈ 0.999999
Test Failed at none:1
Expression: 1 ≈ 0.999999
Evaluated: 1 ≈ 0.999999
ERROR: There was an error during testing
```
You can specify relative and absolute tolerances by setting the `rtol` and `atol` keyword arguments of `isapprox`, respectively,
after the `≈` comparison:
```jldoctest
julia> @test 1 ≈ 0.999999 rtol=1e-5
Test Passed
Expression: ≈(1, 0.999999, rtol = 1.0e-5)
Evaluated: ≈(1, 0.999999; rtol = 1.0e-5)
```
Note that this is not a specific feature of the `≈` but rather a general feature of the `@test` macro: `@test a <op> b key=val` is transformed by the macro into `@test op(a, b, key=val)`. It is, however, particularly useful for `≈` tests.
```@docs
Test.@inferred
Test.@test_logs
Test.@test_deprecated
Test.@test_warn
Test.@test_nowarn
```
## Broken Tests
If a test fails consistently it can be changed to use the `@test_broken` macro. This will denote
the test as `Broken` if the test continues to fail and alerts the user via an `Error` if the test
succeeds.
```@docs
Test.@test_broken
```
`@test_skip` is also available to skip a test without evaluation, but counting the skipped test
in the test set reporting. The test will not run but gives a `Broken` `Result`.
```@docs
Test.@test_skip
```
## Creating Custom `AbstractTestSet` Types
Packages can create their own `AbstractTestSet` subtypes by implementing the `record` and `finish`
methods. The subtype should have a one-argument constructor taking a description string, with
any options passed in as keyword arguments.
```@docs
Test.record
Test.finish
```
`Test` takes responsibility for maintaining a stack of nested testsets as they are executed,
but any result accumulation is the responsibility of the `AbstractTestSet` subtype. You can access
this stack with the `get_testset` and `get_testset_depth` methods. Note that these functions are
not exported.
```@docs
Test.get_testset
Test.get_testset_depth
```
`Test` also makes sure that nested `@testset` invocations use the same `AbstractTestSet`
subtype as their parent unless it is set explicitly. It does not propagate any properties of the
testset. Option inheritance behavior can be implemented by packages using the stack infrastructure
that `Test` provides.
Defining a basic `AbstractTestSet` subtype might look like:
```julia
import Test: Test, record, finish
using Test: AbstractTestSet, Result, Pass, Fail, Error
using Test: get_testset_depth, get_testset
struct CustomTestSet <: Test.AbstractTestSet
description::AbstractString
foo::Int
results::Vector
# constructor takes a description string and options keyword arguments
CustomTestSet(desc; foo=1) = new(desc, foo, [])
end
record(ts::CustomTestSet, child::AbstractTestSet) = push!(ts.results, child)
record(ts::CustomTestSet, res::Result) = push!(ts.results, res)
function finish(ts::CustomTestSet)
# just record if we're not the top-level parent
if get_testset_depth() > 0
record(get_testset(), ts)
end
ts
end
```
And using that testset looks like:
```julia
@testset CustomTestSet foo=4 "custom testset inner 2" begin
# this testset should inherit the type, but not the argument.
@testset "custom testset inner" begin
@test true
end
end
```
## Test utilities
```@docs
Test.GenericArray
Test.GenericDict
Test.GenericOrder
Test.GenericSet
Test.GenericString
Test.detect_ambiguities
Test.detect_unbound_args
```
```@meta
DocTestSetup = nothing
```
| JuliaZH | https://github.com/JuliaCN/JuliaZH.jl.git |
|
[
"MIT"
] | 1.6.0 | a7dc7bfc2fc6638c18241bfcdb9d73c7dd256482 | docs | 77 | # UUIDs
```@docs
UUIDs.uuid1
UUIDs.uuid4
UUIDs.uuid5
UUIDs.uuid_version
```
| JuliaZH | https://github.com/JuliaCN/JuliaZH.jl.git |
|
[
"MIT"
] | 1.6.0 | a7dc7bfc2fc6638c18241bfcdb9d73c7dd256482 | docs | 79 | # Unicode
```@docs
Unicode.isassigned
Unicode.normalize
Unicode.graphemes
```
| JuliaZH | https://github.com/JuliaCN/JuliaZH.jl.git |
|
[
"MIT"
] | 5.30.6 | 376aa3d800f4da32d232f2d9a1685e34e2911b4a | code | 4514 | push!(LOAD_PATH,"../src/")
using Documenter
using Genie, Genie.Assets, Genie.Commands, Genie.Configuration, Genie.Cookies
using Genie.Encryption, Genie.Exceptions
using Genie.FileTemplates, Genie.Generator
using Genie.Headers, Genie.HTTPUtils, Genie.Input, Genie.Loader, Genie.Logger
using Genie.Renderer, Genie.Repl, Genie.Requests, Genie.Responses, Genie.Router, Genie.Secrets, Genie.Server
using Genie.Toolbox, Genie.Util, Genie.Watch, Genie.WebChannels, Genie.WebThreads
push!(LOAD_PATH, "../../src", "../../src/renderers")
makedocs(
sitename = "Genie - The Highly Productive Julia Web Framework",
format = Documenter.HTML(prettyurls = false),
warnonly = true,
pages = [
"Home" => "index.md",
"Guides" => [
"Migrating Genie v4 apps to Genie v5" => "guides/Migrating_from_v4_to_v5.md",
"Working with Genie Apps" => "guides/Working_With_Genie_Apps.md",
"Working With Genie Apps: Intermediate Topics [WIP]" => "guides/Working_With_Genie_Apps_Intermediary_Topics.md",
"Using Genie in an interactive environment" => "guides/Interactive_environment.md",
"Developing an API backend" => "guides/Simple_API_backend.md",
"Using Genie Plugins" => "guides/Genie_Plugins.md",
"Deploying Genie Apps On AWS" => "guides/Deploying_Genie_Apps_On_AWS.md",
"Controlling Load Order of Genie Apps"=> "guides/Controlling_Load_Order_Of_Genie_Apps.md"
],
"Tutorials" => [
"Welcome to Genie" => "tutorials/1--Overview.md",
"Installing Genie" => "tutorials/2--Installing_Genie.md",
"Getting started" => "tutorials/3--Getting_Started.md",
"Creating a web service" => "tutorials/4--Developing_Web_Services.md",
"Developing MVC web applications" => "tutorials/4-1--Developing_MVC_Web_Apps.md",
"Handling URI/query params" => "tutorials/5--Handling_Query_Params.md",
"Working with forms and POST payloads" => "tutorials/6--Working_with_POST_Payloads.md",
"Using JSON payloads" => "tutorials/7--Using_JSON_Payloads.md",
"Uploading files" => "tutorials/8--Handling_File_Uploads.md",
"Adding your libraries into Genie" => "tutorials/9--Publishing_Your_Julia_Code_Online_With_Genie_Apps.md",
"Loading and starting Genie apps" => "tutorials/10--Loading_Genie_Apps.md",
"Managing Genie app's dependencies" => "tutorials/11--Managing_External_Packages.md",
"Advanced routing" => "tutorials/12--Advanced_Routing_Techniques.md",
"Auto-loading configuration code with initializers" => "tutorials/13--Initializers.md",
"The secrets file" => "tutorials/14--The_Secrets_File.md",
"Auto-loading user libraries" => "tutorials/15--The_Lib_Folder.md",
"Using Genie with Docker" => "tutorials/16--Using_Genie_With_Docker.md",
"Working with WebSockets" => "tutorials/17--Working_with_Web_Sockets.md",
"Deploying to Heroku with Buildpacks" => "tutorials/90--Deploying_With_Heroku_Buildpacks.md",
"Deploying to server with Nginx" => "tutorials/92--Deploying_Genie_Server_Apps_with_Nginx.md"
],
"API" => [
"Assets" => "API/assets.md",
"Commands" => "API/commands.md",
"Configuration" => "API/configuration.md",
"Cookies" => "API/cookies.md",
"Encryption" => "API/encryption.md",
"Exceptions" => "API/exceptions.md",
"FileTemplates" => "API/filetemplates.md",
"Generator" => "API/generator.md",
"Genie" => "API/genie.md",
"Headers" => "API/headers.md",
"HttpUtils" => "API/httputils.md",
"Input" => "API/input.md",
"Loader" => "API/loader.md",
"Logger" => "API/logger.md",
"Renderer" => "API/renderer.md",
"HTML Renderer" => "API/renderer-html.md",
"JS Renderer" => "API/renderer-js.md",
"JSON Renderer" => "API/renderer-json.md",
"Requests" => "API/requests.md",
"Responses" => "API/responses.md",
"Router" => "API/router.md",
"Secrets" => "API/secrets.md",
"Server" => "API/server.md",
"Toolbox" => "API/toolbox.md",
"Util" => "API/util.md",
"Watch" => "API/watch.md",
"WebChannels" => "API/webchannels.md",
"WebThreads" => "API/webthreads.md"
]
],
)
deploydocs(
repo = "github.com/GenieFramework/Genie.jl.git",
)
| Genie | https://github.com/GenieFramework/Genie.jl.git |
|
[
"MIT"
] | 5.30.6 | 376aa3d800f4da32d232f2d9a1685e34e2911b4a | code | 73 | using Genie.Router
route("/") do
serve_static_file("welcome.html")
end | Genie | https://github.com/GenieFramework/Genie.jl.git |
|
[
"MIT"
] | 5.30.6 | 376aa3d800f4da32d232f2d9a1685e34e2911b4a | code | 429 | module ValidationHelper
using Genie, SearchLight, SearchLight.Validation
export output_errors
function output_errors(m::T, field::Symbol)::String where {T<:SearchLight.AbstractModel}
v = ispayload() ? validate(m) : ModelValidator()
haserrorsfor(v, field) ?
"""
<div class="text-danger form-text">
$(errors_to_string(v, field, separator = "<br/>\n", uppercase_first = true))
</div>""" : ""
end
end | Genie | https://github.com/GenieFramework/Genie.jl.git |
|
[
"MIT"
] | 5.30.6 | 376aa3d800f4da32d232f2d9a1685e34e2911b4a | code | 478 | using Genie, Logging
Genie.Configuration.config!(
server_port = 8000,
server_host = "127.0.0.1",
log_level = Logging.Info,
log_to_file = false,
server_handle_static_files = true,
path_build = "build",
format_julia_builds = true,
format_html_output = true,
watch = true
)
ENV["JULIA_REVISE"] = "auto" | Genie | https://github.com/GenieFramework/Genie.jl.git |
|
[
"MIT"
] | 5.30.6 | 376aa3d800f4da32d232f2d9a1685e34e2911b4a | code | 100 | # Place here configuration options that will be set for all environments
# ENV["GENIE_ENV"] = "prod" | Genie | https://github.com/GenieFramework/Genie.jl.git |
|
[
"MIT"
] | 5.30.6 | 376aa3d800f4da32d232f2d9a1685e34e2911b4a | code | 819 | using Genie, Logging
Genie.Configuration.config!(
server_port = 8000,
server_host = (Sys.iswindows() ? "127.0.0.1" : "0.0.0.0"),
log_level = Logging.Error,
log_to_file = false,
server_handle_static_files = true, # for best performance set up Nginx or Apache web proxies and set this to false
path_build = "build",
format_julia_builds = false,
format_html_output = false
)
if Genie.config.server_handle_static_files
@warn("For performance reasons Genie should not serve static files (.css, .js, .jpg, .png, etc) in production.
It is recommended to set up Apache or Nginx as a reverse proxy and cache to serve static assets.")
end
ENV["JULIA_REVISE"] = "off" | Genie | https://github.com/GenieFramework/Genie.jl.git |
|
[
"MIT"
] | 5.30.6 | 376aa3d800f4da32d232f2d9a1685e34e2911b4a | code | 306 | using Genie, Logging
Genie.Configuration.config!(
server_port = 8000,
server_host = "127.0.0.1",
log_level = Logging.Debug,
log_to_file = true,
server_handle_static_files = true
)
ENV["JULIA_REVISE"] = "off" | Genie | https://github.com/GenieFramework/Genie.jl.git |
|
[
"MIT"
] | 5.30.6 | 376aa3d800f4da32d232f2d9a1685e34e2911b4a | code | 116 | # Optional flat/non-resource MVC folder structure
# Genie.Loader.autoload(abspath("models"), abspath("controllers")) | Genie | https://github.com/GenieFramework/Genie.jl.git |
|
[
"MIT"
] | 5.30.6 | 376aa3d800f4da32d232f2d9a1685e34e2911b4a | code | 267 | using Dates
import Base.convert
convert(::Type{Int}, v::SubString{String}) = parse(Int, v)
convert(::Type{Float64}, v::SubString{String}) = parse(Float64, v)
convert(::Type{Date}, s::String) = parse(Date, s)
convert(::Type{DateTime}, s::String) = parse(DateTime, s)
| Genie | https://github.com/GenieFramework/Genie.jl.git |
|
[
"MIT"
] | 5.30.6 | 376aa3d800f4da32d232f2d9a1685e34e2911b4a | code | 149 | import Inflector, Genie
if ! isempty(Genie.config.inflector_irregulars)
push!(Inflector.IRREGULAR_NOUNS, Genie.config.inflector_irregulars...)
end | Genie | https://github.com/GenieFramework/Genie.jl.git |
|
[
"MIT"
] | 5.30.6 | 376aa3d800f4da32d232f2d9a1685e34e2911b4a | code | 47 | import Genie
Genie.Logger.initialize_logging() | Genie | https://github.com/GenieFramework/Genie.jl.git |
|
[
"MIT"
] | 5.30.6 | 376aa3d800f4da32d232f2d9a1685e34e2911b4a | code | 405 | using SearchLight
using Genie
function Genie.Renderer.Json.JSON3.StructTypes.StructType(::Type{T}) where {T<:SearchLight.AbstractModel}
Genie.Renderer.Json.JSON3.StructTypes.Struct()
end
function Genie.Renderer.Json.JSON3.StructTypes.StructType(::Type{SearchLight.DbId})
Genie.Renderer.Json.JSON3.StructTypes.Struct()
end
SearchLight.Configuration.load(context = @__MODULE__)
SearchLight.connect()
| Genie | https://github.com/GenieFramework/Genie.jl.git |
|
[
"MIT"
] | 5.30.6 | 376aa3d800f4da32d232f2d9a1685e34e2911b4a | code | 19590 | """
Helper functions for working with frontend assets (including JS, CSS, etc files).
"""
module Assets
import Genie, Genie.Configuration, Genie.Router, Genie.WebChannels, Genie.WebThreads
import Genie.Renderer.Json
import Genie.Util.package_version
export include_asset, css_asset, js_asset, js_settings, css, js
export embedded, channels_script, channels_support, webthreads_script, webthreads_support
export favicon_support
### PUBLIC ###
"""
mutable struct AssetsConfig
Manages the assets configuration for the current package. Define your own instance of AssetsConfig if you want to
add support for asset management for your package through Genie.Assets.
"""
Base.@kwdef mutable struct AssetsConfig
host::String = Genie.config.base_path
package::String = "Genie.jl"
version::String = package_version(package)
end
const assets_config = AssetsConfig()
function __init__()::Nothing
# make sure the assets config is properly initialized
assets_config.host = Genie.config.base_path
assets_config.package = "Genie.jl"
assets_config.version = package_version(assets_config.package)
nothing
end
"""
assets_config!(packages::Vector{Module}; config...) :: Nothing
assets_config!(package::Module; config...) :: Nothing
Utility function which allows bulk configuration of the assets.
### Example
```julia
Genie.Assets.assets_config!([Genie, Stipple, StippleUI], host = "https://cdn.statically.io/gh/GenieFramework")
```
"""
function assets_config!(packages::Vector{Module}; config...) :: Nothing
for p in packages
package_config = getfield(p, :assets_config)
for (k,v) in config
setfield!(package_config, k, v)
end
end
nothing
end
function assets_config!(package::Module; config...) :: Nothing
assets_config!([package]; config...)
end
"""
assets_config!(; config...) :: Nothing
Updates the assets configuration for the current package.
"""
function assets_config!(; config...) :: Nothing
assets_config!([@__MODULE__]; config...)
end
"""
external_assets(host::String) :: Bool
external_assets(ac::AssetsConfig) :: Bool
external_assets() :: Bool
Returns true if the current package is using external assets.
"""
function external_assets(host::String) :: Bool
startswith(host, "http")
end
function external_assets(ac::AssetsConfig) :: Bool
external_assets(ac.host)
end
function external_assets() :: Bool
external_assets(assets_config)
end
"""
asset_path(; file::String, host::String = Genie.config.base_path, package::String = "", version::String = "",
prefix::String = "assets", type::String = "", path::String = "", min::Bool = false,
ext::String = "", skip_ext::Bool = false, query::String = "") :: String
asset_path(file::String; kwargs...) :: String
asset_path(ac::AssetsConfig, tp::Union{Symbol,String}; type::String = string(tp), path::String = "",
file::String = "", ext::String = "", skip_ext::Bool = false, query::String = "") :: String
Generates the path to an asset file.
"""
function asset_path(; file::String, host::String = Genie.config.base_path, package::String = "", version::String = "",
prefix::String = "assets", type::String = "$(split(file, '.')[end])", path::String = "", min::Bool = false,
ext::String = "$(endswith(file, type) ? "" : ".$type")", skip_ext::Bool = false, query::String = "") :: String
startswith(host, '/') && (host = host[2:end])
endswith(host, '/') && (host = host[1:end-1])
startswith(path, '/') && (path = path[2:end])
endswith(path, '/') && (path = path[1:end-1])
(
(external_assets(host) ? "" : "/") *
join(filter([host, package, version, prefix, type, path, file*(min ? ".min" : "")*(skip_ext ? "" : ext)]) do part
! isempty(part)
end, '/') *
query) |> lowercase
end
function asset_path(file::String; kwargs...) :: String
asset_path(; file, kwargs...)
end
function asset_path(ac::AssetsConfig, tp::Union{Symbol,String}; type::String = string(tp), path::String = "",
file::String = "", ext::String = ".$type", skip_ext::Bool = false, query::String = "") :: String
asset_path(host = ac.host, package = ac.package, version = ac.version, type = type, path = path, file = file,
ext = ext, skip_ext = skip_ext, query = query)
end
"""
asset_route(; file::String, package::String = "", version::String = "", prefix::String = "assets",
type::String = "", path::String = "", min::Bool = false,
ext::String = "", skip_ext::Bool = false, query::String = "") :: String
asset_route(file::String; kwargs...) :: String
asset_route(ac::AssetsConfig, tp::Union{Symbol,String}; type::String = string(tp), path::String = "",
file::String = "", ext::String = "", skip_ext::Bool = false, query::String = "") :: String
Generates the route to an asset file.
"""
function asset_route(; file::String, package::String = "", version::String = "", prefix::String = "assets",
type::String = "$(split(file, '.')[end])", path::String = "", min::Bool = false,
ext::String = "$(endswith(file, type) ? "" : ".$type")", skip_ext::Bool = false, query::String = "") :: String
startswith(path, '/') && (path = path[2:end])
endswith(path, '/') && (path = path[1:end-1])
('/' *
join(filter([package, version, prefix, type, path, file*(min ? ".min" : "")*(skip_ext ? "" : ext)]) do part
! isempty(part)
end, '/') *
query) |> lowercase
end
function asset_route(file::String; kwargs...) :: String
asset_route(; file, kwargs...)
end
function asset_route(ac::AssetsConfig, tp::Union{Symbol,String}; type::String = string(tp), path::String = "",
file::String = "", ext::String = ".$type", skip_ext::Bool = false, query::String = "",
kwds...) :: String
asset_route(; package = ac.package, version = ac.version, type = type, path = path, file = file,
ext = ext, skip_ext = skip_ext, query = query, kwds...)
end
"""
asset_file(; cwd = "", file::String, path::String = "", type::String = "", prefix::String = "assets",
ext::String = "", min::Bool = false, skip_ext::Bool = false) :: String
Generates the file system path to an asset file.
"""
function asset_file(; cwd = "", file::String, path::String = "", type::String = "$(split(file, '.')[end])", prefix::String = "assets",
ext::String = "$(endswith(file, type) ? "" : ".$type")", min::Bool = false, skip_ext::Bool = false) :: String
joinpath((filter([cwd, prefix, type, path, file*(min ? ".min" : "")*(skip_ext ? "" : ext)]) do part
! isempty(part)
end)...) |> normpath
end
"""
include_asset(asset_type::Union{String,Symbol}, file_name::Union{String,Symbol}) :: String
Returns the path to an asset. `asset_type` can be one of `:js`, `:css`. The `file_name` should not include the extension.
"""
function include_asset(asset_type::Union{String,Symbol}, file_name::Union{String,Symbol}; min::Bool = false) :: String
asset_path(type = string(asset_type), file = string(file_name); min)
end
"""
css_asset(file_name::String) :: String
Path to a css asset. The `file_name` should not include the extension.
"""
function css_asset(file_name::String; min::Bool = false) :: String
include_asset(:css, file_name; min)
end
const css = css_asset
"""
js_asset(file_name::String) :: String
Path to a js asset. `file_name` should not include the extension.
"""
function js_asset(file_name::String; min::Bool = false) :: String
include_asset(:js, file_name; min)
end
const js = js_asset
const js_literal = ["js:|", "|_"]
function jsliteral(val) :: String
"$(js_literal[1])$val$(js_literal[2])"
end
"""
js_settings(channel::String = Genie.config.webchannels_default_route) :: String
Sets up a `window.Genie.Settings` JavaScript object which exposes relevant Genie app settings from `Genie.config`
"""
function js_settings(channel::String = Genie.config.webchannels_default_route) :: String
settings = Json.JSONParser.json(Dict(
:server_host => Genie.config.server_host,
:server_port => Genie.config.server_port,
:websockets_protocol => Genie.config.websockets_protocol === nothing ? jsliteral("window.location.protocol.replace('http', 'ws')") : Genie.config.websockets_protocol,
:websockets_host => Genie.config.websockets_host,
:websockets_exposed_host => Genie.config.websockets_exposed_host === nothing ? jsliteral("window.location.hostname") : Genie.config.websockets_exposed_host,
:websockets_port => Genie.config.websockets_port,
:websockets_exposed_port => Genie.config.websockets_exposed_port === nothing ? jsliteral("window.location.port") : Genie.config.websockets_exposed_port,
:websockets_base_path => Genie.config.websockets_base_path,
:webchannels_default_route => channel,
:webchannels_subscribe_channel => Genie.config.webchannels_subscribe_channel,
:webchannels_unsubscribe_channel => Genie.config.webchannels_unsubscribe_channel,
:webchannels_autosubscribe => Genie.config.webchannels_autosubscribe,
:webchannels_eval_command => Genie.config.webchannels_eval_command,
:webchannels_base64_marker => Genie.config.webchannels_base64_marker,
:webchannels_timeout => Genie.config.webchannels_timeout,
:webchannels_keepalive_frequency => Genie.config.webchannels_keepalive_frequency,
:webchannels_server_gone_alert_timeout => Genie.config.webchannels_server_gone_alert_timeout,
:webchannels_connection_attempts => Genie.config.webchannels_connection_attempts,
:webchannels_reconnect_delay => Genie.config.webchannels_reconnect_delay,
:webchannels_subscription_trails => Genie.config.webchannels_subscription_trails,
:webthreads_default_route => channel,
:webthreads_js_file => Genie.config.webthreads_js_file,
:webthreads_pull_route => Genie.config.webthreads_pull_route,
:webthreads_push_route => Genie.config.webthreads_push_route,
:base_path => Genie.config.base_path,
:env => Genie.env(),
))
if contains(settings, js_literal[1])
settings = replace(settings, "\"$(js_literal[1])"=>"")
settings = replace(settings, "$(js_literal[2])\""=>"")
end
"""
window.Genie = {};
Genie.Settings = $settings;
"""
end
"""
embeded(path::String) :: String
Reads and outputs the file at `path`.
"""
function embedded(path::String) :: String
read(joinpath(path) |> normpath, String)
end
"""
embeded_path(path::String) :: String
Returns the path relative to Genie's root package dir.
"""
function embedded_path(path::String) :: String
joinpath(@__DIR__, "..", path) |> normpath
end
"""
add_fileroute(assets_config::Genie.Assets.AssetsConfig, filename::AbstractString;
basedir = pwd(),
type::Union{Nothing, String} = nothing,
content_type::Union{Nothing, Symbol} = nothing,
ext::Union{Nothing, String} = nothing, kwargs...)
Helper function to add a file route to the assets based on asset_config and filename.
# Example
```
add_fileroute(StippleUI.assets_config, "Sortable.min.js")
add_fileroute(StippleUI.assets_config, "vuedraggable.umd.min.js")
add_fileroute(StippleUI.assets_config, "vuedraggable.umd.min.js.map", type = "js")
add_fileroute(StippleUI.assets_config, "QSortableTree.js")
draggabletree_deps() = [
script(src = "/stippleui.jl/master/assets/js/sortable.min.js")
script(src = "/stippleui.jl/master/assets/js/vuedraggable.umd.min.js")
script(src = "/stippleui.jl/master/assets/js/qsortabletree.js")
]
Stipple.DEPS[:qdraggabletree] = draggabletree_deps
```
"""
function add_fileroute(assets_config::Genie.Assets.AssetsConfig, filename::AbstractString;
basedir = pwd(),
type::Union{Nothing, String} = nothing,
content_type::Union{Nothing, Symbol} = nothing,
ext::Union{Nothing, String} = nothing, named::Union{Symbol, Nothing} = nothing, kwargs...)
file, ex = splitext(filename)
ext = isnothing(ext) ? ex : ext
type = isnothing(type) ? ex[2:end] : type
content_type = isnothing(content_type) ? if type == "js"
:javascript
elseif type == "css"
:css
elseif type in ["jpg", "jpeg", "svg", "mov", "avi", "png", "gif", "tif", "tiff"]
imagetype = replace(type, Dict("jpg" => "jpeg", "mpg" => "mpeg", "tif" => "tiff")...)
Symbol("image/$imagetype")
else
Symbol("*.*")
end : content_type
Genie.Router.route(Genie.Assets.asset_path(assets_config, type; file, ext, kwargs...); named) do
Genie.Renderer.WebRenderable(
Genie.Assets.embedded(Genie.Assets.asset_file(cwd=basedir; type, file)),
content_type) |> Genie.Renderer.respond
end
end
"""
channels(channel::AbstractString = Genie.config.webchannels_default_route) :: String
Outputs the `channels.js` file included with the Genie package.
"""
function channels(channel::AbstractString = Genie.config.webchannels_default_route) :: String
string(js_settings(channel), embedded(Genie.Assets.asset_file(cwd=normpath(joinpath(@__DIR__, "..")), type = "js", file = "channels")))
end
"""
channels_script(channel::AbstractString = Genie.config.webchannels_default_route) :: String
Outputs the channels JavaScript content within `<script>...</script>` tags, for embedding into the page.
"""
function channels_script(channel::AbstractString = Genie.config.webchannels_default_route) :: String
"""
<script>
$(channels(channel))
</script>
"""
end
"""
channels_subscribe(channel::AbstractString = Genie.config.webchannels_default_route) :: Nothing
Registers subscription and unsubscription channels for `channel`.
"""
function channels_subscribe(channel::AbstractString = Genie.config.webchannels_default_route) :: Nothing
Router.channel("/$(channel)/$(Genie.config.webchannels_subscribe_channel)") do
WebChannels.subscribe(Genie.Requests.wsclient(), channel)
"Subscription: OK"
end
Router.channel("/$(channel)/$(Genie.config.webchannels_unsubscribe_channel)", named = Symbol(channel)) do
WebChannels.unsubscribe(Genie.Requests.wsclient(), channel)
WebChannels.unsubscribe_disconnected_clients()
Genie.Router.delete_channel!(Symbol(channel))
"Unsubscription: OK"
end
nothing
end
function assets_endpoint(f::Function = Genie.Assets.asset_path) :: String
f(assets_config, :js, file = Genie.config.webchannels_js_file, skip_ext = true)
end
function channels_route(channel::AbstractString = Genie.config.webchannels_default_route) :: Nothing
if ! external_assets()
Router.route(assets_endpoint(Genie.Assets.asset_route)) do
Genie.Renderer.Js.js(channels(channel))
end
end
nothing
end
function channels_script_tag(channel::AbstractString = Genie.config.webchannels_default_route) :: String
if ! external_assets()
Genie.Renderer.Html.script(src = assets_endpoint())
else
Genie.Renderer.Html.script([channels(channel)])
end
end
"""
channels_support(channel = Genie.config.webchannels_default_route) :: String
Provides full web channels support, setting up routes for loading support JS files, web sockets subscription and
returning the `<script>` tag for including the linked JS file into the web page.
"""
function channels_support(channel::AbstractString = Genie.config.webchannels_default_route) :: String
channels_route(channel)
channels_subscribe(channel)
channels_script_tag(channel)
end
######## WEB THREADS
"""
webthreads() :: String
Outputs the webthreads.js file included with the Genie package
"""
function webthreads(channel::String = Genie.config.webthreads_default_route) :: String
string(js_settings(channel),
embedded(Genie.Assets.asset_file(cwd=normpath(joinpath(@__DIR__, "..")), file="pollymer.js")),
embedded(Genie.Assets.asset_file(cwd=normpath(joinpath(@__DIR__, "..")), file="webthreads.js")))
end
"""
webthreads_script() :: String
Outputs the channels JavaScript content within `<script>...</script>` tags, for embedding into the page.
"""
function webthreads_script(channel::String = Genie.config.webthreads_default_route) :: String
"""
<script>
$(webthreads(channel))
</script>
"""
end
"""
function webthreads_subscribe(channel) :: Nothing
Registers subscription and unsubscription routes for `channel`.
"""
function webthreads_subscribe(channel::String = Genie.config.webthreads_default_route) :: Nothing
Router.route("/$(channel)/$(Genie.config.webchannels_subscribe_channel)", method = Router.GET) do
WebThreads.subscribe(Genie.Requests.wtclient(), channel)
"Subscription: OK"
end
Router.route("/$(channel)/$(Genie.config.webchannels_unsubscribe_channel)", method = Router.GET, named = Symbol(channel)) do
WebThreads.unsubscribe(Genie.Requests.wtclient(), channel)
WebThreads.unsubscribe_disconnected_clients()
Genie.Router.delete_channel!(Symbol(channel))
"Unsubscription: OK"
end
nothing
end
"""
function webthreads_push_pull(channel) :: Nothing
Registers push and pull routes for `channel`.
"""
function webthreads_push_pull(channel::String = Genie.config.webthreads_default_route) :: Nothing
Router.route("/$(channel)/$(Genie.config.webthreads_pull_route)", method = Router.POST) do
WebThreads.pull(Genie.Requests.wtclient(), channel)
end
Router.route("/$(channel)/$(Genie.config.webthreads_push_route)", method = Router.POST) do
WebThreads.push(Genie.Requests.wtclient(), channel, Router.params(Genie.Router.PARAMS_RAW_PAYLOAD))
end
nothing
end
function webthreads_endpoint(channel::String = Genie.config.webthreads_default_route) :: String
Genie.Assets.asset_path(assets_config, :js, file = Genie.config.webthreads_js_file, path = channel, skip_ext = true)
end
function webthreads_route(channel::String = Genie.config.webthreads_default_route) :: Nothing
if ! external_assets()
Router.route(webthreads_endpoint()) do
Genie.Renderer.Js.js(webthreads(channel))
end
end
nothing
end
function webthreads_script_tag(channel::String = Genie.config.webthreads_default_route) :: String
if ! external_assets()
Genie.Renderer.Html.script(src="$(Genie.config.base_path)$(webthreads_endpoint())")
else
Genie.Renderer.Html.script([webthreads(channel)])
end
end
"""
webthreads_support(channel = Genie.config.webthreads_default_route) :: String
Provides full web channels support, setting up routes for loading support JS files, web sockets subscription and
returning the `<script>` tag for including the linked JS file into the web page.
"""
function webthreads_support(channel::String = Genie.config.webthreads_default_route) :: String
webthreads_route(channel)
webthreads_subscribe(channel)
webthreads_push_pull(channel)
webthreads_script_tag(channel)
end
#######
"""
favicon_support() :: String
Outputs the `<link>` tag for referencing the favicon file embedded with Genie.
"""
function favicon_support() :: String
Router.route("/favicon.ico") do
Genie.Renderer.respond(
Genie.Renderer.WebRenderable(
body = embedded(joinpath(@__DIR__, "..", "files", "new_app", "public", "favicon.ico") |> normpath |> abspath),
content_type = :favicon
)
)
end
"<link rel=\"icon\" type=\"image/x-icon\" href=\"$(Genie.config.base_path)$(endswith(Genie.config.base_path, '/') ? "" : "/")favicon.ico\" />"
end
end
| Genie | https://github.com/GenieFramework/Genie.jl.git |
|
[
"MIT"
] | 5.30.6 | 376aa3d800f4da32d232f2d9a1685e34e2911b4a | code | 3704 | """
Handles command line arguments for the genie.jl script.
"""
module Commands
import Sockets
import ArgParse
import Genie
using Logging
"""
execute(config::Settings) :: Nothing
Runs the requested Genie app command, based on the `args` passed to the script.
"""
function execute(config::Genie.Configuration.Settings; server::Union{Sockets.TCPServer,Nothing} = nothing) :: Nothing
parsed_args = parse_commandline_args(config)::Dict{String,Any}
# overwrite env settings with command line arguments
Genie.config.server_port = parse(Int, parsed_args["p"])
Genie.config.websockets_port = lowercase(parsed_args["w"]) == "nothing" ? nothing : parse(Int, parsed_args["w"])
Genie.config.server_host = parsed_args["l"]
Genie.config.websockets_exposed_host = lowercase(parsed_args["x"]) == "nothing" ? nothing : parsed_args["x"]
Genie.config.websockets_exposed_port = lowercase(parsed_args["y"]) == "nothing" ? nothing : parse(Int, parsed_args["y"])
Genie.config.websockets_base_path = parsed_args["W"]
Genie.config.base_path = parsed_args["b"]
if (called_command(parsed_args, "s") && lowercase(get(parsed_args, "s", "false")) == "true") ||
(haskey(ENV, "STARTSERVER") && parse(Bool, ENV["STARTSERVER"])) ||
(haskey(ENV, "EARLYBIND") && lowercase(get(ENV, "STARTSERVER", "true")) != "false")
Genie.config.run_as_server = true
Base.invokelatest(Genie.up, Genie.config.server_port, Genie.config.server_host; server = server)
elseif called_command(parsed_args, "r")
endswith(parsed_args["r"], "Task") || (parsed_args["r"] *= "Task")
Genie.Toolbox.loadtasks()
taskname = parsed_args["r"] |> Symbol
task = getfield(Main.UserApp, taskname)
if parsed_args["a"] !== nothing
Base.@invokelatest task.runtask(parsed_args["a"])
else
Base.@invokelatest task.runtask()
end
end
nothing
end
"""
parse_commandline_args() :: Dict{String,Any}
Extracts the command line args passed into the app and returns them as a `Dict`, possibly setting up defaults.
Also, it is used by the ArgParse module to populate the command line help for the app `-h`.
"""
function parse_commandline_args(config::Genie.Configuration.Settings) :: Dict{String,Any}
settings = ArgParse.ArgParseSettings()
settings.description = "Genie web framework CLI"
settings.epilog = "Visit https://genieframework.com for more info"
settings.add_help = true
ArgParse.@add_arg_table! settings begin
"-s"
help = "Starts HTTP server"
default = "false"
"-p"
help = "Web server port"
default = "$(config.server_port)"
"-w"
help = "WebSockets server port"
default = "$(config.websockets_port)"
"-l"
help = "Host IP to listen on"
default = "$(config.server_host)"
"-x"
help = "WebSockets host used by the clients"
default = "$(config.websockets_exposed_host)"
"-y"
help = "WebSockets port used by the clients"
default = "$(config.websockets_exposed_port)"
"-W"
help = "Websockets base path, e.g. `websocket`, `stream`"
default = "$(config.websockets_base_path)"
"-b"
help = "Base path for serving assets and building links"
default = "$(config.base_path)"
"-r"
help = "runs Genie.Toolbox task"
default = nothing
"-a"
help = "additional arguments passed into the Genie.Toolbox `runtask` function"
default = nothing
end
ArgParse.parse_args(settings)
end
"""
called_command(args::Dict, key::String) :: Bool
Checks whether or not a certain command was invoked by looking at the command line args.
"""
function called_command(args::Dict{String,Any}, key::String) :: Bool
haskey(args, key) && args[key] !== nothing
end
end
| Genie | https://github.com/GenieFramework/Genie.jl.git |
|
[
"MIT"
] | 5.30.6 | 376aa3d800f4da32d232f2d9a1685e34e2911b4a | code | 12109 | """
Core genie configuration / settings functionality.
"""
module Configuration
import Pkg
import Dates
using Random
"""
pkginfo(pkg::String)
Returns installed package information for `pkg`
"""
pkginfo(pkg::String) = filter(x -> x.name == pkg && x.is_direct_dep, values(Pkg.dependencies()) |> collect)
import Logging
import Genie
export isdev, isprod, istest, env, basepath
export Settings, DEV, PROD, TEST
# app environments
const DEV = "dev"
const PROD = "prod"
const TEST = "test"
"""
isdev() :: Bool
Set of utility functions that return whether or not the current environment is development, production or testing.
# Examples
```julia
julia> Configuration.isdev()
true
julia> Configuration.isprod()
false
```
"""
isdev() :: Bool = (Genie.config.app_env == DEV)
"""
isprod() :: Bool
Set of utility functions that return whether or not the current environment is development, production or testing.
# Examples
```julia
julia> Configuration.isdev()
true
julia> Configuration.isprod()
false
```
"""
isprod()::Bool = (Genie.config.app_env == PROD)
"""
istest() :: Bool
Set of utility functions that return whether or not the current environment is development, production or testing.
# Examples
```julia
julia> Configuration.isdev()
true
julia> Configuration.isprod()
false
```
"""
istest()::Bool = (Genie.config.app_env == TEST)
"""
env() :: String
Returns the current Genie environment.
# Examples
```julia
julia> Configuration.env()
"dev"
```
"""
env()::String = Genie.config.app_env
"""
buildpath() :: String
Constructs the temp dir where Genie's view files are built.
"""
buildpath()::String = Base.Filesystem.mktempdir(prefix="jl_genie_build_")
"""
basepath(; prefix = "/") :: String
Returns the base path for the app. Optionally takes a prefix argument -- defaults to `/`.
"""
function basepath(; prefix = "/", ignore_empty = true)
# if base_path is not set (it's empty) then don't do anything (return empty string)
if ignore_empty && isempty(Genie.config.base_path)
return ""
end
# if base_path starts with "/" but the prefix is different, then remove the "/" from base_path
if prefix != "/" && startswith(Genie.config.base_path, "/")
return joinpath(prefix, Genie.config.base_path[2:end])
end
# if base_path already starts with the prefix, then return it as it is
if startswith(Genie.config.base_path, prefix)
return Genie.config.base_path
end
# otherwise, join the prefix with the base_path
return joinpath(prefix, Genie.config.base_path)
end
"""
config!(; kwargs...)
Updates Genie.config using the provided keyword arguments.
"""
function config!(; kwargs...)
for args in kwargs
setfield!(Genie.config, args[1], args[2])
end
Genie.config
end
"""
add_cors_header!(key, value)
Adds a new CORS header to the `Genie.config.cors_headers` collection as key => value pair.
# Examples
```julia
Genie.Configuration.add_cors_header!("Access-Control-Allow-Headers", "Genie-Session-Id")
```
"""
function add_cors_header!(key, value; config = Genie.config)
key = string(key)
value = string(value)
if ! haskey(config.cors_headers, key)
@warn "CORS header key $key does not exist. Creating."
config.cors_headers[key] = value
else
config.cors_headers[key] = join(push!([String(strip(h)) for h in split(config.cors_headers[key], ',')], value) |> unique!, ", ")
end
config
end
"""
mutable struct Settings
App configuration - sets up the app's defaults. Individual options are overwritten in the corresponding environment file.
# Arguments
- `server_port::Int`: the port for running the web server (default 8000)
- `server_host::String`: the host for running the web server (default "127.0.0.1")
- `server_document_root::String`: path to the document root (default "public/")
- `server_handle_static_files::Bool`: if `true`, Genie will also serve static files. In production, it is recommended to serve static files with a web server like Nginx.
- `server_signature::String`: Genie's signature used for tagging the HTTP responses. If empty, it will not be added.
- `app_env::String`: the environment in which the app is running (dev, test, or prod)
- `cors_headers::Dict{String,String}`: default `Access-Control-*` CORS settings
- `cors_allowed_origins::Vector{String}`: allowed origin hosts for CORS settings
- `log_level::Logging.LogLevel`: logging severity level
- `log_to_file::Bool`: if true, information will be logged to file besides REPL
- `log_requests::Bool`: if true, requests will be automatically logged
- `inflector_irregulars::Vector{Tuple{String,String}}`: additional irregular singular-plural forms to be used by the Inflector
- `run_as_server::Bool`: when true the server thread is launched synchronously to avoid that the script exits
- `websockets_server::Bool`: if true, the websocket server is also started together with the web server
- `websockets_port::Int`: the port for the websocket server (default `server_port`)
- `initializers_folder::String`: the folder where the initializers are located (default "initializers/")
- `path_config::String`: the path to the configurations folder (default "config/")
- `path_env::String`: the path to the environment files (default "<path_config>/env/")
- `path_app::String`: the path to the app files (default "app/")
- `html_parser_close_tag::String`: default " /". Can be changed to an empty string "" so the single tags would not be closed.
- `webchannels_keepalive_frequency::Int`: default `30000`. Frequency in milliseconds to send keepalive messages to webchannel/websocket to keep the connection alive. Set to `0` to disable keepalive messages.
"""
Base.@kwdef mutable struct Settings
server_port::Int = 8000 # default port for binding the web server
server_host::String = "127.0.0.1"
server_document_root::String = "public"
server_handle_static_files::Bool = true
server_signature::String = "Genie/Julia/$VERSION"
app_env::String = DEV
cors_headers::Dict{String,String} = Dict{String,String}(
"Access-Control-Allow-Origin" => "", # ex: "*" or "http://mozilla.org"
"Access-Control-Expose-Headers" => "", # ex: "X-My-Custom-Header, X-Another-Custom-Header"
"Access-Control-Max-Age" => "86400", # 24 hours
"Access-Control-Allow-Credentials" => "", # "true" or "false"
"Access-Control-Allow-Methods" => "", # ex: "POST, GET"
"Access-Control-Allow-Headers" => "Accept, Accept-Language, Content-Language, Content-Type", # CORS safelisted headers
)
cors_allowed_origins::Vector{String} = String[]
log_level::Logging.LogLevel = Logging.Info
log_to_file::Bool = false
log_requests::Bool = true
log_date_format::String = "yyyy-mm-dd HH:MM:SS"
inflector_irregulars::Vector{Tuple{String,String}} = Tuple{String,String}[]
run_as_server::Bool = false
base_path::String = ""
websockets_server::Bool = false
websockets_protocol::Union{String,Nothing} = nothing
websockets_port::Union{Int,Nothing} = nothing
websockets_host::String = server_host
websockets_exposed_port::Union{Int,Nothing} = nothing
websockets_exposed_host::Union{String,Nothing} = nothing
websockets_base_path::String = base_path
initializers_folder::String = "initializers"
path_config::String = "config"
path_env::String = joinpath(path_config, "env")
path_app::String = "app"
path_resources::String = joinpath(path_app, "resources")
path_lib::String = "lib"
path_helpers::String = joinpath(path_app, "helpers")
path_log::String = "log"
path_tasks::String = "tasks"
path_build::String = "build"
path_plugins::String = "plugins"
path_initializers::String = joinpath(path_config, initializers_folder)
path_db::String = "db"
path_bin::String = "bin"
path_src::String = "src"
webchannels_default_route::String = "____"
webchannels_js_file::String = "channels.js"
webchannels_subscribe_channel::String = "subscribe"
webchannels_unsubscribe_channel::String = "unsubscribe"
webchannels_autosubscribe::Bool = true
webchannels_eval_command::String = ">eval:"
webchannels_base64_marker::String = "base64:"
webchannels_timeout::Int = 1_000
webchannels_keepalive_frequency::Int = 30_000 # 30 seconds
webchannels_server_gone_alert_timeout::Int = 10_000 # 10 seconds
webchannels_connection_attempts = 10
webchannels_reconnect_delay = 500 # milliseconds
webchannels_subscription_trails = 4
webthreads_default_route::String = webchannels_default_route
webthreads_js_file::String = "webthreads.js"
webthreads_pull_route::String = "pull"
webthreads_push_route::String = "push"
webthreads_connection_threshold::Dates.Millisecond = Dates.Millisecond(60_000) # 1 minute
html_attributes_replacements::Dict{String,String} = Dict("v__on!" => "v-on:")
html_parser_close_tag::String = " /"
html_parser_char_at::String = "!!"
html_parser_char_dot::String = "!"
html_parser_char_column::String = "!"
html_parser_char_dash::String = "__"
html_registered_tags_only::Bool = false
features_peerinfo::Bool = false
format_julia_builds::Bool = false
format_html_output::Bool = true
format_html_indentation_string::String = " "
autoload::Vector{Symbol} = Symbol[:initializers, :helpers, :libs, :resources, :plugins, :routes, :app]
autoload_file::String = ".autoload"
autoload_ignore_file::String = ".autoload_ignore"
env_file::String = ".env"
watch::Bool = false
watch_extensions::Vector{String} = String["jl", "html", "md", "js", "css"]
watch_handlers::Dict{Any,Vector{Function}} = Dict()
watch_frequency::Int = 2_000 # 2 seconds
watch_exceptions::Vector{String} = String["bin/", "build/", "sessions/", "Project.toml", "Manifest.toml"]
cdn_enabled::Bool = true # if true, the CDN will be used for static assets in prod mode
cdn_url::String = "https://cdn.statically.io/gh/GenieFramework" # the URL of the CDN
end
end
| Genie | https://github.com/GenieFramework/Genie.jl.git |
|
[
"MIT"
] | 5.30.6 | 376aa3d800f4da32d232f2d9a1685e34e2911b4a | code | 6025 | """
Functionality for dealing with HTTP cookies.
"""
module Cookies
import HTTP
import Genie, Genie.Encryption, Genie.HTTPUtils
"""
get(payload::Union{HTTP.Response,HTTP.Request}, key::Union{String,Symbol}, default::T; encrypted::Bool = true)::T where T
Attempts to get the Cookie value stored at `key` within `payload`.
If the `key` is not set, the `default` value is returned.
# Arguments
- `payload::Union{HTTP.Response,HTTP.Request}`: the request or response object containing the Cookie headers
- `key::Union{String,Symbol}`: the name of the cookie value
- `default::T`: default value to be returned if no cookie value is set at `key`
- `encrypted::Bool`: if `true` the value stored on the cookie is automatically decrypted
"""
function get(payload::Union{HTTP.Response,HTTP.Request}, key::Union{String,Symbol}, default::T; encrypted::Bool = true)::T where T
val = get(payload, key, encrypted = encrypted)
val === nothing ? default : parse(T, val)
end
"""
get(res::HTTP.Response, key::Union{String,Symbol}) :: Union{Nothing,String}
Retrieves a value stored on the cookie as `key` from the `Respose` object.
# Arguments
- `payload::Union{HTTP.Response,HTTP.Request}`: the request or response object containing the Cookie headers
- `key::Union{String,Symbol}`: the name of the cookie value
- `encrypted::Bool`: if `true` the value stored on the cookie is automatically decrypted
"""
function get(res::HTTP.Response, key::Union{String,Symbol}; encrypted::Bool = true) :: Union{Nothing,String}
(haskey(HTTPUtils.Dict(res), "Set-Cookie") || haskey(HTTPUtils.Dict(res), "set-cookie")) ?
nullablevalue(res, key, encrypted = encrypted) :
nothing
end
"""
get(req::Request, key::Union{String,Symbol}) :: Union{Nothing,String}
Retrieves a value stored on the cookie as `key` from the `Request` object.
# Arguments
- `req::HTTP.Request`: the request or response object containing the Cookie headers
- `key::Union{String,Symbol}`: the name of the cookie value
- `encrypted::Bool`: if `true` the value stored on the cookie is automatically decrypted
"""
function get(req::HTTP.Request, key::Union{String,Symbol}; encrypted::Bool = true) :: Union{Nothing,String}
(haskey(HTTPUtils.Dict(req), "cookie") || haskey(HTTPUtils.Dict(req), "Cookie")) ?
nullablevalue(req, key, encrypted = encrypted) :
nothing
end
"""
set!(res::HTTP.Response, key::Union{String,Symbol}, value::Any, attributes::Dict; encrypted::Bool = true) :: HTTP.Response
Sets `value` under the `key` label on the `Cookie`.
# Arguments
- `res::HTTP.Response`: the HTTP.Response object
- `key::Union{String,Symbol}`: the key for storing the cookie value
- `value::Any`: the cookie value
- `attributes::Dict`: additional cookie attributes, such as `path`, `httponly`, `maxage`
- `encrypted::Bool`: if `true` the value is stored encoded
"""
function set!(res::HTTP.Response, key::Union{String,Symbol}, value::Any, attributes::Dict{String,<:Any} = Dict{String,Any}(); encrypted::Bool = true) :: HTTP.Response
r = Genie.Headers.normalize_headers(res)
normalized_attrs = Dict{Symbol,Any}()
for (k,v) in attributes
normalized_attrs[Symbol(lowercase(string(k)))] = v
end
if haskey(normalized_attrs, :samesite)
if lowercase(normalized_attrs[:samesite]) == "lax"
normalized_attrs[:samesite] = HTTP.Cookies.SameSiteLaxMode
elseif lowercase(normalized_attrs[:samesite]) == "none"
normalized_attrs[:samesite] = HTTP.Cookies.SameSiteLaxNone
elseif lowercase(normalized_attrs[:samesite]) == "strict"
normalized_attrs[:samesite] = HTTP.Cookies.SameSiteLaxStrict
end
end
value = string(value)
encrypted && (value = Genie.Encryption.encrypt(value))
cookie = HTTP.Cookies.Cookie(string(key), value; normalized_attrs...)
HTTP.Cookies.addcookie!(r, cookie)
r
end
"""
Dict(req::Request) :: Dict{String,String}
Extracts the `Cookie` and `Set-Cookie` data from the `Request` and `Response` objects and converts it into a Dict.
"""
function Base.Dict(r::Union{HTTP.Request,HTTP.Response}) :: Dict{String,String}
r = Genie.Headers.normalize_headers(r)
d = Dict{String,String}()
headers = Dict(r.headers)
h = if haskey(headers, "Cookie")
split(headers["Cookie"], ";")
elseif haskey(headers, "Set-Cookie")
split(headers["Set-Cookie"], ";")
else
[]
end
for cookie in h
cookie_parts = split(cookie, "=")
if length(cookie_parts) == 2
d[strip(cookie_parts[1])] = cookie_parts[2]
else
d[strip(cookie_parts[1])] = ""
end
end
d
end
### PRIVATE ###
"""
nullablevalue(payload::Union{HTTP.Response,HTTP.Request}, key::Union{String,Symbol}; encrypted::Bool = true)
Attempts to retrieve a cookie value stored at `key` in the `payload object` and returns a `Union{Nothing,String}`
# Arguments
- `payload::Union{HTTP.Response,HTTP.Request}`: the request or response object containing the Cookie headers
- `key::Union{String,Symbol}`: the name of the cookie value
- `encrypted::Bool`: if `true` the value stored on the cookie is automatically decrypted
"""
function nullablevalue(payload::Union{HTTP.Response,HTTP.Request}, key::Union{String,Symbol}; encrypted::Bool = true) :: Union{Nothing,String}
for cookie in split(Dict(payload)["cookie"], ';')
cookie = strip(cookie)
if startswith(lowercase(cookie), lowercase(string(key)))
value = split(cookie, '=')[2] |> String
encrypted && (value = Genie.Encryption.decrypt(value))
return string(value)
end
end
nothing
end
"""
getcookies(req::HTTP.Request) :: Vector{HTTP.Cookies.Cookie}
Extracts cookies from within `req`
"""
function getcookies(req::HTTP.Request) :: Vector{HTTP.Cookies.Cookie}
HTTP.Cookies.cookies(req)
end
"""
getcookies(req::HTTP.Request) :: Vector{HTTP.Cookies.Cookie}
Extracts cookies from within `req`, filtering them by `matching` name.
"""
function getcookies(req::HTTP.Request, matching::String) :: Vector{HTTP.Cookies.Cookie}
HTTP.Cookies.readcookies(req.headers, matching)
end
end
| Genie | https://github.com/GenieFramework/Genie.jl.git |
|
[
"MIT"
] | 5.30.6 | 376aa3d800f4da32d232f2d9a1685e34e2911b4a | code | 1551 | """
Provides Genie with encryption and decryption capabilities.
"""
module Encryption
import Genie, Nettle
const ENCRYPTION_METHOD = "AES256"
"""
encrypt{T}(s::T) :: String
Encrypts `s`.
"""
function encrypt(s::T)::String where T
(key32, iv16) = encryption_sauce()
encryptor = Nettle.Encryptor(ENCRYPTION_METHOD, key32)
Nettle.encrypt(encryptor, :CBC, iv16, Nettle.add_padding_PKCS5(Vector{UInt8}(s), 16)) |> bytes2hex
end
"""
decrypt(s::String) :: String
Decrypts `s` (a `string` previously encrypted by Genie).
"""
function decrypt(s::String) :: String
(key32, iv16) = encryption_sauce()
decryptor = Nettle.Decryptor(ENCRYPTION_METHOD, key32)
deciphertext = Nettle.decrypt(decryptor, :CBC, iv16, s |> hex2bytes)
try
String(Nettle.trim_padding_PKCS5(deciphertext))
catch ex
if Genie.Configuration.isprod()
@debug ex
@debug "Could not decrypt data"
end
""
end
end
"""
encryption_sauce() :: Tuple{Vector{UInt8},Vector{UInt8}}
Generates a pair of key32 and iv16 with salt for encryption/decryption
"""
function encryption_sauce() :: Tuple{Vector{UInt8},Vector{UInt8}}
if length(Genie.Secrets.secret_token()) < 64
if ! Genie.Configuration.isprod()
Genie.Secrets.secret_token!()
else
error("Can't encrypt - make sure that Genie.Secrets.secret_token!(token) is called in config/secrets.jl")
end
end
token = Genie.Secrets.secret_token()
passwd = token[1:32]
salt = hex2bytes(token[33:64])
Nettle.gen_key32_iv16(Vector{UInt8}(passwd), salt)
end
end
| Genie | https://github.com/GenieFramework/Genie.jl.git |
|
[
"MIT"
] | 5.30.6 | 376aa3d800f4da32d232f2d9a1685e34e2911b4a | code | 5197 | module Exceptions
import Genie
import HTTP
export ExceptionalResponse, RuntimeException, InternalServerException, NotFoundException, FileExistsException
export @log!!throw, @try!
"""
struct ExceptionalResponse <: Exception
A type of exception which wraps an HTTP Response object.
The thrown exception will propagate until it is caught up the app stack or ultimately by Genie
and the wrapped response is sent to the client.
### Example
If the user is not authenticated, an `ExceptionalResponse` is thrown - if the exception is not caught
in the app's stack, Genie will catch it and return the wrapped `Response` object, forcing an HTTP redirect to the login page.
```julia
isauthenticated() || throw(ExceptionalResponse(redirect(:show_login)))
```
"""
struct ExceptionalResponse <: Exception
response::HTTP.Response
end
function ExceptionalResponse(status, headers, body)
HTTP.Response(status, headers, body) |> ExceptionalResponse
end
Base.show(io::IO, ex::ExceptionalResponse) = print(io, "ExceptionalResponseException: $(ex.response.status) - $(Dict(ex.response.headers))")
###
"""
RuntimeException
Represents an unexpected and unhandled runtime exceptions. An error event will be logged and the
exception will be sent to the client, depending on the environment
(the error stack is dumped by default in dev mode or an error message is displayed in production).
It allows defining custom error message and info, as well as an error code, in addition to the exception object.
# Arguments
- `message::String`
- `info::String`
- `code::Int`
- `ex::Union{Nothing,Exception}`
"""
struct RuntimeException <: Exception
message::String
info::String
code::Int
ex::Union{Nothing,Exception}
end
"""
RuntimeException(message::String, code::Int)
`RuntimeException` constructor using `message` and `code`.
"""
RuntimeException(message::String, code::Int) = RuntimeException(message, "", code, nothing)
"""
RuntimeException(message::String, info::String, code::Int)
`RuntimeException` constructor using `message`, `info` and `code`.
"""
RuntimeException(message::String, info::String, code::Int) = RuntimeException(message, info, code, nothing)
"""
Base.show(io::IO, ex::RuntimeException)
Custom printing of `RuntimeException`
"""
Base.show(io::IO, ex::RuntimeException) = print(io, "RuntimeException: $(ex.code) - $(ex.info) - $(ex.message)")
###
"""
struct InternalServerException <: Exception
Dedicated exception type for server side exceptions. Results in a 500 error by default.
# Arguments
- `message::String`
- `info::String`
- `code::Int`
"""
struct InternalServerException <: Exception
message::String
info::String
code::Int
end
"""
InternalServerException(message::String)
External `InternalServerException` constructor accepting a custom message.
"""
InternalServerException(message::String) = InternalServerException(message, "", 500)
"""
InternalServerException()
External `InternalServerException` using default values.
"""
InternalServerException() = InternalServerException("Internal Server Error")
###
"""
struct NotFoundException <: Exception
Specialized exception representing a not found resources. Results in a 404 response being sent to the client.
# Arguments
- `message::String`
- `info::String`
- `code::Int`
- `resource::String`
"""
struct NotFoundException <: Exception
message::String
info::String
code::Int
resource::String
end
"""
NotFoundException(resource::String)
External constructor allowing to pass the name of the not found resource.
"""
NotFoundException(resource::String) = NotFoundException("$resource can not be found", "", 404, resource)
"""
NotFoundException()
External constructor using default arguments.
"""
NotFoundException() = NotFoundException("")
###
"""
struct FileExistsException <: Exception
Custom exception type for signaling that the requested file already exists.
"""
struct FileExistsException <: Exception
path::String
end
"""
Base.show(io::IO, ex::FileExistsException)
Custom printing for `FileExistsException`
"""
Base.show(io::IO, ex::FileExistsException) = print(io, "FileExistsException: $(ex.path)")
"""
@log!!throw(ex)
Macro to log an exception if the app is in production, and rethrow it if the app is in dev mode.
"""
macro log!!throw(ex)
quote
if Genie.Configuration.isprod()
@error $ex
else
rethrow($ex)
end
end
end
"""
@tried(ex1, ex2)
Macro to wrap a try/catch block and @log!!throw the exception.
# Example
```julia
julia> @tried(1+1, (ex) -> @warn(ex))
2
julia> @tried(error("wut?"), (ex) -> @warn(ex)) # in dev mode, exception is rethrown
ERROR: wut?
Stacktrace:
[1] error(s::String)
@ Base ./error.jl:35
[2] macro expansion
@ REPL[5]:4 [inlined]
[3] top-level scope
@ REPL[14]:1
julia> @tried(error("wut?"), (ex) -> @warn(ex)) # in prod mode, exception is logged
┌ Warning: 2024-03-15 13:04:43 ErrorException("wut?")
└ @ Main REPL[16]:1
```
"""
macro try!(ex1, ex2)
quote
try
$ex1
catch e
if Genie.Configuration.isprod()
@error e
else
rethrow(e)
end
$ex2(e)
end
end |> esc
end
end
| Genie | https://github.com/GenieFramework/Genie.jl.git |
|
[
"MIT"
] | 5.30.6 | 376aa3d800f4da32d232f2d9a1685e34e2911b4a | code | 1465 | """
Functionality for handling the defautl conent of the various Genie files (migrations, models, controllers, etc).
"""
module FileTemplates
import Inflector
"""
newtask(module_name::String) :: String
Default content for a new Genie Toolbox task.
"""
function newtask(module_name::String) :: String
"""
module $module_name
\"\"\"
Description of the task here
\"\"\"
function runtask()
# Build something great
end
end
"""
end
"""
newcontroller(controller_name::String) :: String
Default content for a new Genie controller.
"""
function newcontroller(controller_name::String) :: String
"""
module $(controller_name)Controller
# Build something great
end
"""
end
"""
newtest(plural_name::String, singular_name::String) :: String
Default content for a new test file.
"""
function newtest(plural_name::String, singular_name::String) :: String
"""
using Main.UserApp, Main.UserApp.$(plural_name)
### Your tests here
@test 1 == 1
"""
end
"""
appmodule(path::String)
Generates a custom app module when a new app is bootstrapped.
"""
function appmodule(path::String)
path = replace(path, '-'=>'_') |> strip
appname = split(path, '/', keepempty = false)[end] |> String |> Inflector.from_underscores
content = """
module $appname
using Genie
const up = Genie.up
export up
function main()
Genie.genie(; context = @__MODULE__)
end
end
"""
(appname, content)
end
end
| Genie | https://github.com/GenieFramework/Genie.jl.git |
|
[
"MIT"
] | 5.30.6 | 376aa3d800f4da32d232f2d9a1685e34e2911b4a | code | 29248 | """
Generates various Genie files.
"""
module Generator
import Dates, Pkg, Logging, UUIDs
import Inflector
import Genie
const NEW_APP_PATH = joinpath("files", "new_app")
function validname(name::String)
filter(! isempty, [x.match for x in collect(eachmatch(r"[0-9a-zA-Z_-]*", name))]) |> join
end
"""
newcontroller(controller_name::Union{String,Symbol}) :: Nothing
Creates a new `controller` file. If `pluralize` is `false`, the name of the controller is not automatically pluralized.
"""
function newcontroller(controller_name::Union{String,Symbol}; path::Union{String,Nothing} = nothing, pluralize::Bool = true, context::Union{Module,Nothing} = nothing) :: Nothing
Generator.newcontroller(string(controller_name), path = path, pluralize = pluralize)
Genie.Loader.load_resources(; context = Genie.Loader.default_context(context))
nothing
end
"""
newcontroller(resource_name::String) :: Nothing
Generates a new Genie controller file and persists it to the resources folder.
"""
function newcontroller(resource_name::String; path::Union{String,Nothing} = nothing, pluralize::Bool = true) :: Nothing
resource_name = validname(resource_name) |> Inflector.from_underscores |> Inflector.from_dashes
Inflector.is_singular(resource_name) && pluralize && (resource_name = Inflector.to_plural(resource_name))
resource_name = uppercasefirst(resource_name)
resource_path = path === nothing ? setup_resource_path(resource_name, path = ".") : (ispath(path) ? path : mkpath(path))
cfn = controller_file_name(resource_name)
write_resource_file(resource_path, cfn, resource_name, :controller, pluralize = pluralize) &&
@info "New controller created at $(abspath(joinpath(resource_path, cfn)))"
nothing
end
"""
newresource(resource_name::Union{String,Symbol}; pluralize::Bool = true, context::Union{Module,Nothing} = nothing) :: Nothing
Creates all the files associated with a new resource.
If `pluralize` is `false`, the name of the resource is not automatically pluralized.
"""
function newresource(resource_name::Union{String,Symbol}; path::String = ".", pluralize::Bool = true, context::Union{Module,Nothing} = nothing) :: Nothing
newresource(string(resource_name), path = path, pluralize = pluralize)
Genie.Loader.load_resources(; context = Genie.Loader.default_context(context))
nothing
end
"""
newresource(resource_name::String, config::Settings) :: Nothing
Generates all the files associated with a new resource and persists them to the resources folder.
"""
function newresource(resource_name::String; path::String = ".", pluralize::Bool = true) :: Nothing
resource_name = validname(resource_name) |> Inflector.from_underscores |> Inflector.from_dashes
Inflector.is_singular(resource_name) && pluralize &&
(resource_name = Inflector.to_plural(resource_name))
resource_path = setup_resource_path(resource_name, path = path)
for (resource_file, resource_type) in [(controller_file_name(resource_name), :controller)]
write_resource_file(resource_path, resource_file, resource_name, resource_type, pluralize = pluralize) &&
@info "New $resource_file created at $(abspath(joinpath(resource_path, resource_file)))"
end
views_path = joinpath(resource_path, "views")
isdir(views_path) || mkpath(views_path)
nothing
end
"""
newtask(task_name::Union{String,Symbol}) :: Nothing
Creates a new Genie `Task` file.
"""
function newtask(task_name::Union{String,Symbol}) :: Nothing
task_name = string(task_name)
endswith(task_name, "Task") || (task_name = task_name * "Task")
Toolbox.new(task_name)
nothing
end
###################################
"""
setup_resource_path(resource_name::String) :: String
Computes and creates the directories structure needed to persist a new resource.
"""
function setup_resource_path(resource_name::String; path::String = ".") :: String
isdir(Genie.config.path_app) || Genie.Generator.mvc_support(path)
resource_path = joinpath(path, Genie.config.path_resources, lowercase(resource_name))
if ! isdir(resource_path)
mkpath(resource_path)
push!(LOAD_PATH, resource_path)
end
resource_path
end
"""
write_resource_file(resource_path::String, file_name::String, resource_name::String) :: Bool
Generates all resource files and persists them to disk.
"""
function write_resource_file(resource_path::String, file_name::String, resource_name::String, resource_type::Symbol; pluralize::Bool = true) :: Bool
resource_name = (pluralize ? (Inflector.to_plural(resource_name)) : resource_name) |> Inflector.from_underscores |> Inflector.from_dashes
try
if resource_type == :controller
resource_does_not_exist(resource_path, file_name) || return true
open(joinpath(resource_path, file_name), "w") do f
write(f, Genie.FileTemplates.newcontroller(resource_name))
end
end
catch ex
@error ex
end
try
if resource_type == :test
resource_does_not_exist(resource_path, file_name) || return true
open(joinpath(resource_path, file_name), "w") do f
name = pluralize ? (Inflector.to_singular(resource_name)) : resource_name
write(f, Genie.FileTemplates.newtest(resource_name, name))
end
end
catch ex
@error ex
end
try
Genie.Loader.load_resources()
catch ex
@error ex
end
true
end
function binfolderpath(path::String) :: String
bin_folder_path = joinpath(path, Genie.config.path_bin)
isdir(bin_folder_path) || mkpath(bin_folder_path)
bin_folder_path
end
"""
setup_windows_bin_files(path::String = ".") :: Nothing
Creates the bin/server and bin/repl binaries for Windows
"""
function setup_windows_bin_files(path::String = ".") :: Nothing
JULIA_PATH = joinpath(Sys.BINDIR, "julia")
bin_folder_path = binfolderpath(path)
open(joinpath(bin_folder_path, "repl.bat"), "w") do f
write(f, "\"$JULIA_PATH\" --color=yes --depwarn=no --project=@. -q -i -- \"%~dp0..\\$(Genie.BOOTSTRAP_FILE_NAME)\" %*")
end
open(joinpath(bin_folder_path, "server.bat"), "w") do f
write(f, "\"$JULIA_PATH\" --color=yes --depwarn=no --project=@. -q -i -- \"%~dp0..\\$(Genie.BOOTSTRAP_FILE_NAME)\" -s=true %*")
end
open(joinpath(bin_folder_path, "runtask.bat"), "w") do f
write(f, "\"$JULIA_PATH\" --color=yes --depwarn=no --project=@. -q -- \"%~dp0..\\$(Genie.BOOTSTRAP_FILE_NAME)\" -r %*")
end
nothing
end
"""
setup_nix_bin_files(path::String = ".") :: Nothing
Creates the bin/server and bin/repl binaries for *nix systems
"""
function setup_nix_bin_files(path::String = ".") :: Nothing
bin_folder_path = binfolderpath(path)
open(joinpath(bin_folder_path, "repl"), "w") do f
write(f, "#!/bin/sh\n" * raw"julia --color=yes --depwarn=no --project=@. -q -L $(dirname $0)/../bootstrap.jl -- \"$@\"")
end
open(joinpath(bin_folder_path, "server"), "w") do f
write(f, "#!/bin/sh\n" * raw"julia --color=yes --depwarn=no --project=@. -q -i -- $(dirname $0)/../bootstrap.jl -s=true \"$@\"")
end
open(joinpath(bin_folder_path, "runtask"), "w") do f
write(f, "#!/bin/sh\n" * raw"julia --color=yes --depwarn=no --project=@. -q -- $(dirname $0)/../bootstrap.jl -r \"$@\"")
end
chmod(joinpath(bin_folder_path, "server"), 0o700)
chmod(joinpath(bin_folder_path, "repl"), 0o700)
chmod(joinpath(bin_folder_path, "runtask"), 0o700)
nothing
end
"""
resource_does_not_exist(resource_path::String, file_name::String) :: Bool
Returns `true` if the indicated resources does not exists - false otherwise.
"""
function resource_does_not_exist(resource_path::String, file_name::String) :: Bool
if isfile(joinpath(resource_path, file_name))
@warn "File already exists, $(joinpath(resource_path, file_name)) - skipping"
return false
end
true
end
"""
controller_file_name(resource_name::Union{String,Symbol})
Computes the controller file name based on the resource name.
"""
function controller_file_name(resource_name::Union{String,Symbol}) :: String
GENIE_CONTROLLER_FILE_POSTFIX = "Controller.jl"
uppercasefirst(string(resource_name)) * GENIE_CONTROLLER_FILE_POSTFIX
end
"""
write_secrets_file(app_path=".")
Generates a valid `config/secrets.jl` file with a random secret token.
"""
function write_secrets_file(app_path::String = ".") :: Nothing
secrets_path = joinpath(app_path, Genie.config.path_config)
ispath(secrets_path) || mkpath(secrets_path)
open(joinpath(secrets_path, Genie.Secrets.SECRETS_FILE_NAME), "w") do f
write(f, """try
Genie.Util.isprecompiling() || Genie.Secrets.secret_token!("$(Genie.Secrets.secret())")
catch ex
@error "Failed to generate secrets file: \$ex"
end
""")
end
nothing
end
"""
fullstack_app(app_name::String) :: Nothing
Writes the files necessary to create a full stack Genie app.
"""
function fullstack_app(app_name::String, app_path::String = ".") :: Nothing
cp(joinpath(@__DIR__, "..", NEW_APP_PATH), app_path)
scaffold(app_name, app_path)
nothing
end
"""
minimal(app_name::String, app_path::String = abspath(app_name), autostart::Bool = true) :: Nothing
Creates a minimal Genie app.
"""
function minimal(app_name::String, app_path::String = "", autostart::Bool = true) :: Nothing
app_name = validname(app_name)
app_path = abspath(app_name)
scaffold(app_name, app_path)
post_create(app_name, app_path, autostart = autostart)
nothing
end
"""
scaffold(app_name::String, app_path::String = "") :: Nothing
Writes the file necessary to scaffold a minimal Genie app.
"""
function scaffold(app_name::String, app_path::String = "") :: Nothing
GENIE_FILE_NAME = "genie.jl"
app_name = validname(app_name)
app_path = abspath(app_name)
isdir(app_path) || mkpath(app_path)
for f in [Genie.config.path_src, GENIE_FILE_NAME, Genie.ROUTES_FILE_NAME,
".gitattributes", ".gitignore", ".env.example"]
try
cp(joinpath(@__DIR__, "..", NEW_APP_PATH, f), joinpath(app_path, f))
catch ex
end
end
write_app_custom_files(app_name, app_path)
nothing
end
"""
microstack_app(app_name::String, app_path::String = ".") :: Nothing
Writes the file necessary to create a microstack app.
"""
function microstack_app(app_name::String, app_path::String = ".") :: Nothing
isdir(app_path) || mkpath(app_path)
for f in [Genie.config.path_bin, Genie.config.path_config, Genie.config.server_document_root]
cp(joinpath(@__DIR__, "..", NEW_APP_PATH, f), joinpath(app_path, f))
end
scaffold(app_name, app_path)
nothing
end
"""
mvc_support(app_path::String = ".") :: Nothing
Writes the files used for rendering resources using the MVC stack and the Genie templating system.
"""
function mvc_support(app_path::String = ".") :: Nothing
cp(joinpath(@__DIR__, "..", NEW_APP_PATH, Genie.config.path_app), joinpath(app_path, Genie.config.path_app))
nothing
end
"""
db_support(app_path::String = ".") :: Nothing
Writes files used for interacting with the SearchLight ORM.
"""
function db_support(app_path::String = ".", include_env::Bool = true, add_dependencies::Bool = true;
testmode::Bool = false, dbadapter::Union{String,Symbol,Nothing} = nothing, interactive::Bool = true)
cp(joinpath(@__DIR__, "..", NEW_APP_PATH, Genie.config.path_db), joinpath(app_path, Genie.config.path_db), force = true)
db_intializer(app_path, include_env)
add_dependencies ? install_db_dependencies(testmode = testmode, dbadapter = dbadapter, interactive = interactive) : dbadapter
end
function db_intializer(app_path::String = ".", include_env::Bool = false)
initializers_dir = joinpath(app_path, Genie.config.path_initializers)
initializer_path = joinpath(initializers_dir, Genie.SEARCHLIGHT_INITIALIZER_FILE_NAME)
source_path = joinpath(@__DIR__, "..", NEW_APP_PATH, Genie.config.path_initializers, Genie.SEARCHLIGHT_INITIALIZER_FILE_NAME) |> normpath
if !isfile(initializer_path)
ispath(initializers_dir) || mkpath(initializers_dir)
include_env && cp(joinpath(@__DIR__, "..", NEW_APP_PATH, Genie.config.path_env), joinpath(app_path, Genie.config.path_env), force = true)
cp(source_path, initializer_path)
end
end
"""
write_app_custom_files(path::String, app_path::String) :: Nothing
Writes the Genie app main module file.
"""
function write_app_custom_files(path::String, app_path::String) :: Nothing
moduleinfo = Genie.FileTemplates.appmodule(path)
open(joinpath(app_path, Genie.config.path_src, moduleinfo[1] * ".jl"), "w") do f
write(f, moduleinfo[2])
end
open(joinpath(app_path, Genie.BOOTSTRAP_FILE_NAME), "w") do f
write(f,
"""
(pwd() != @__DIR__) && cd(@__DIR__) # allow starting app from bin/ dir
using $(moduleinfo[1])
const UserApp = $(moduleinfo[1])
$(moduleinfo[1]).main()
""")
end
isdir(joinpath(app_path, "test")) || mkpath(joinpath(app_path, "test"))
open(joinpath(app_path, "test", "runtests.jl"), "w") do f
write(f,
"""
# This file is autogenerated to run all tests in the context of your Genie app.
# It is not necessary to edit this file.
# To create tests, simply add `.jl` test files in the `test/` folder.
# All `.jl` files in the `test/` folder will be automatically executed by running `\$ julia --project runtests.jl`
# If you want to selectively run tests, use `\$ julia --project runtests.jl test_file_1 test_file_2`
ENV["GENIE_ENV"] = "test"
push!(LOAD_PATH, abspath(normpath(joinpath("..", "src"))))
cd("..")
using Pkg
Pkg.activate(".")
using Genie
Genie.loadapp()
cd(@__DIR__)
Pkg.activate(".")
# !!! Main.UserApp is configured as an alias for Main.$(moduleinfo[1]) and you might encounter it in some tests
using Main.$(moduleinfo[1]), Test, TestSetExtensions, Logging
Logging.global_logger(NullLogger())
@testset ExtendedTestSet "$(moduleinfo[1]) tests" begin
@includetests ARGS
end
""")
end
nothing
end
"""
install_app_dependencies(app_path::String = ".") :: Nothing
Installs the application's dependencies using Julia's Pkg
"""
function install_app_dependencies(app_path::String = "."; testmode::Bool = false,
dbsupport::Bool = false, dbadapter::Union{String,Symbol,Nothing} = nothing,
interactive::Bool = true)
@info "Installing app dependencies"
Pkg.activate(".")
pkgs = ["Dates", "Logging", "Inflector"]
testmode ? Pkg.develop("Genie", io = devnull) : Pkg.add(Pkg.PackageSpec(; name="Genie", version="5"))
Pkg.add(pkgs, io = devnull)
result = dbsupport ? install_db_dependencies(testmode = testmode, dbadapter = dbadapter, interactive = interactive) : dbadapter
@info "Installing dependencies for unit tests"
Pkg.activate("test")
Pkg.add(Pkg.PackageSpec(; name="Genie", version="5"), io = devnull)
Pkg.add("Test", io = devnull)
Pkg.add("TestSetExtensions", io = devnull)
Pkg.add("Pkg", io = devnull)
Pkg.add("Logging", io = devnull)
Pkg.instantiate()
dbsupport ? install_db_dependencies(testmode = testmode, dbadapter = dbadapter, interactive = interactive) : dbadapter
Pkg.activate(".") # return to the main project
result
end
"""
generate_project(name)
Generate the `Project.toml` with a name and a uuid.
If this file already exists, generate `Project_sample.toml` as a reference instead.
"""
function generate_project(name::String) :: Nothing
name = Genie.FileTemplates.appmodule(name)[1] # convert to camel case
mktempdir() do tmpdir
tmp = joinpath(tmpdir, name, "Project.toml")
pkgproject(Pkg.API.Context(), name, tmpdir) # generate tmp
# Pkg.project(Pkg.stdout_f(), name, tmpdir) # generate tmp
if !isfile("Project.toml")
mv(tmp, "Project.toml") # move tmp here
@info "Project.toml has been generated"
else
mv(tmp, "Project_sample.toml"; force = true)
@warn "$(abspath("."))/Project.toml already exists and will not be replaced. " *
"Make sure that it specifies a name and a uuid, using Project_sample.toml as a reference."
end
end # remove tmpdir on completion
nothing
end
function pkgproject(ctx::Pkg.API.Context, pkg::String, dir::String) :: Nothing
name = email = nothing
gitname = Pkg.LibGit2.getconfig("user.name", "")
isempty(gitname) || (name = gitname)
gitmail = Pkg.LibGit2.getconfig("user.email", "")
isempty(gitmail) || (email = gitmail)
if name === nothing
for env in ["GIT_AUTHOR_NAME", "GIT_COMMITTER_NAME", "USER", "USERNAME", "NAME"]
name = get(ENV, env, nothing)
name !== nothing && break
end
end
name === nothing && (name = "Unknown")
if email === nothing
for env in ["GIT_AUTHOR_EMAIL", "GIT_COMMITTER_EMAIL", "EMAIL"];
email = get(ENV, env, nothing)
email !== nothing && break
end
end
authors = ["$name " * (email === nothing ? "" : "<$email>")]
uuid = UUIDs.uuid4()
pkggenfile(ctx, pkg, dir, "Project.toml") do io
toml = Dict{String,Any}("authors" => authors,
"name" => pkg,
"uuid" => string(uuid),
"version" => "0.1.0",
)
Pkg.TOML.print(io, toml, sorted=true, by=key -> (Pkg.Types.project_key_order(key), key))
end
end
function pkggenfile(f::Function, ctx::Pkg.API.Context, pkg::String, dir::String, file::String) :: Nothing
path = joinpath(dir, pkg, file)
println(ctx.io, " $(Base.contractuser(path))")
mkpath(dirname(path))
open(f, path, "w")
end
function install_db_dependencies(; testmode::Bool = false, dbadapter::Union{String,Symbol,Nothing} = nothing, interactive::Bool = true)
try
testmode ? Pkg.develop("SearchLight", io = devnull) : Pkg.add("SearchLight", io = devnull)
interactive || ! isnothing(dbadapter) ?
install_searchlight_dependencies(dbadapter, testmode = testmode) :
dbadapter
catch ex
@error ex
end
end
function install_searchlight_dependencies(dbadapter::Union{String,Symbol,Nothing} = nothing;
testmode::Bool = false) # TODO: move this to SearchLight post install
adapter::String = if dbadapter === nothing
backends = ["SQLite", "MySQL", "PostgreSQL"] # TODO: this should be dynamic somehow -- maybe by using the future plugins REST API
println()
println("Please choose the DB backend you want to use: ")
for i in 1:length(backends)
println("$i. $(backends[i])")
end
# println("$(length(backends)+1). Other")
println("$(length(backends)+1). Skip installing DB support at this time")
println( "
Input $(join([1:(length(backends)+1)...], ", ", " or ")) and press ENTER to confirm.
If you are not sure what to pick, choose 1 (SQLite). It is the simplest option to get you started right away.
You can add support for additional databases anytime later. ")
println()
choice = try
parse(Int, readline())
catch
return install_searchlight_dependencies(; testmode = testmode)
end
if choice == (length(backends)+1)
println("Skipping DB support installation")
println()
return
elseif choice > (length(backends)+1)
@warn "You must choose a number between 1 and $(length(backends)+1)"
return install_searchlight_dependencies(; testmode = testmode)
else
backends[choice]
end
else
string(dbadapter)
end
if adapter != "SQLite"
@warn "You need to edit the database configuration file at db/connection.yml to set your database connection info."
end
testmode ? Pkg.develop("SearchLight$adapter", io = devnull) : Pkg.add("SearchLight$adapter", io = devnull)
adapter
end
"""
write_db_config(connfile = joinpath("db", "connection.yml"))
Writes the default configuration for the selected SearchLight DB adapter.
"""
macro write_db_config(connfile = joinpath("db", "connection.yml"),
initfile = joinpath("config", "initializers", "searchlight.jl"))
quote
isfile($connfile) && chmod($connfile, 0o760)
open($connfile, "w") do f
write(f, SearchLight.Generator.FileTemplates.adapter_default_config(database = Genie.config.app_env, env = Genie.config.app_env))
end
include($initfile)
nothing
end |> esc
end
"""
autostart_app(path::String = "."; autostart::Bool = true) :: Nothing
If `autostart` is `true`, the newly generated Genie app will be automatically started.
"""
function autostart_app(path::String = "."; autostart::Bool = true, initdb::Bool = false, dbadapter::Union{Nothing,Symbol,String} = nothing) :: Nothing
if autostart
@info "Starting your brand new Genie app - hang tight!"
Genie.loadapp(abspath(path); autostart = autostart, dbadapter = string(dbadapter))
else
@info("Your new Genie app is ready!
Run \njulia> Genie.loadapp() \nto load the app's environment
and then \njulia> up() \nto start the web server on port 8000.")
end
nothing
end
"""
remove_searchlight_initializer(app_path::String = ".") :: Nothing
Removes the SearchLight initializer file if it's unused
"""
function remove_searchlight_initializer(app_path::String = ".") :: Nothing
rm(joinpath(app_path, Genie.config.path_initializers, Genie.SEARCHLIGHT_INITIALIZER_FILE_NAME), force = true)
nothing
end
"""
newapp(app_name::String; autostart::Bool = true, fullstack::Bool = false, dbsupport::Bool = false, mvcsupport::Bool = false) :: Nothing
Scaffolds a new Genie app, setting up the file structure indicated by the various arguments.
# Arguments
- `app_name::String`: the name of the app (can be the full path where the app should be created).
- `autostart::Bool`: automatically start the app once the file structure is created
- `fullstack::Bool`: the type of app to be bootstrapped. The fullstack app includes MVC structure, DB connection code, and asset pipeline files.
- `dbsupport::Bool`: bootstrap the files needed for DB connection setup via the SearchLight ORM
- `mvcsupport::Bool`: adds the files used for HTML+Julia view templates rendering and working with resources
- `dbadapter::Union{String,Symbol,Nothing} = nothing` : pass the SearchLight database adapter to be used by default
(one of :MySQL, :SQLite, or :PostgreSQL). If `dbadapter` is `nothing`, an adapter will have to be selected interactivel
at the REPL, during the app creation process.
# Examples
```julia-repl
julia> Genie.Generator.newapp("MyGenieApp")
2019-08-06 16:54:15:INFO:Main: Done! New app created at MyGenieApp
2019-08-06 16:54:15:DEBUG:Main: Changing active directory to MyGenieApp
2019-08-06 16:54:15:DEBUG:Main: Installing app dependencies
Resolving package versions...
Updating `~/Dropbox/Projects/GenieTests/MyGenieApp/Project.toml`
[c43c736e] + Genie v0.10.1
Updating `~/Dropbox/Projects/GenieTests/MyGenieApp/Manifest.toml`
2019-08-06 16:54:27:INFO:Main: Starting your brand new Genie app - hang tight!
_____ _
| __|___ ___|_|___
| | | -_| | | -_|
|_____|___|_|_|_|___|
┌ Info:
│ Starting Genie in >> DEV << mode
└
[ Info: Logging to file at MyGenieApp/log/dev.log
[ Info: Ready!
2019-08-06 16:54:32:DEBUG:Main: Web Server starting at http://127.0.0.1:8000
2019-08-06 16:54:32:DEBUG:Main: Web Server running at http://127.0.0.1:8000
```
"""
function newapp(app_name::String; autostart::Bool = true, fullstack::Bool = false,
dbsupport::Bool = false, mvcsupport::Bool = false, testmode::Bool = false,
dbadapter::Union{String,Symbol,Nothing} = nothing, interactive::Bool = true) :: Nothing
app_name = validname(app_name)
app_path = abspath(app_name)
fullstack ? fullstack_app(app_name, app_path) : microstack_app(app_name, app_path)
dbadapter = (dbsupport || fullstack) ?
db_support(app_path; testmode, dbadapter, interactive) :
remove_searchlight_initializer(app_path)
mvcsupport && (fullstack || mvc_support(app_path))
write_secrets_file(app_path)
try
setup_windows_bin_files(app_path)
catch ex
@error ex
end
try
setup_nix_bin_files(app_path)
catch ex
@error ex
end
post_create(app_name, app_path; autostart = autostart, testmode = testmode,
dbsupport = (dbsupport || fullstack), dbadapter = dbadapter, interactive = interactive)
nothing
end
function post_create(app_name::String, app_path::String; autostart::Bool = true, testmode::Bool = false,
dbsupport::Bool = false, dbadapter::Union{String,Symbol,Nothing} = nothing, interactive::Bool = true) :: Nothing
@info "Done! New app created at $app_path"
@info "Changing active directory to $app_path"
cd(app_path)
generate_project(app_name)
dbadapter = install_app_dependencies(app_path, testmode = testmode, dbsupport = dbsupport, dbadapter = dbadapter, interactive = interactive)
set_files_mod()
autostart_app(app_path, autostart = autostart, dbadapter = dbadapter)
nothing
end
function set_files_mod() :: Nothing
for f in vcat( # TODO: make this DRY
["Manifest.toml", "Project.toml", "routes.jl"],
(isdir("app") ? readdir("app") : []), (isdir("app/helpers") ? readdir("app/helpers"; join = true) : []),
(isdir("config") ? readdir("config") : []), (isdir("config/env") ? readdir("config/env"; join = true) : []), (isdir("config/initializers") ? readdir("config/initializers"; join = true) : []),
(isdir("db") ? readdir("db") : []),
(isdir("public") ? readdir("public") : []),
(isdir("test") ? readdir("test") : [])
)
try
isfile(f) && chmod(f, 0o760)
catch err
@error err
@warn "Can't change mod for $f. File might be read-only."
end
end
nothing
end
"""
newapp_webservice(name::String; autostart::Bool = true, dbsupport::Bool = false) :: Nothing
Template for scaffolding a new Genie app suitable for nimble web services.
# Arguments
- `name::String`: the name of the app
- `autostart::Bool`: automatically start the app once the file structure is created
- `dbsupport::Bool`: bootstrap the files needed for DB connection setup via the SearchLight ORM
- `dbadapter::Union{String,Symbol,Nothing} = nothing` : pass the SearchLight database adapter to be used by default
(one of :MySQL, :SQLite, or :PostgreSQL). If `dbadapter` is `nothing`, an adapter will have to be selected interactivel
at the REPL, during the app creation process.
"""
function newapp_webservice(name::String; autostart::Bool = true, dbsupport::Bool = false,
dbadapter::Union{String,Symbol,Nothing} = nothing, testmode::Bool = false,
interactive::Bool = true) :: Nothing
newapp(name, autostart = autostart, fullstack = false, dbsupport = dbsupport, mvcsupport = false,
dbadapter = dbadapter, testmode = testmode, interactive = interactive)
end
"""
newapp_mvc(name::String; autostart::Bool = true) :: Nothing
Template for scaffolding a new Genie app suitable for MVC web applications (includes MVC structure and DB support).
# Arguments
- `name::String`: the name of the app
- `autostart::Bool`: automatically start the app once the file structure is created
- `dbadapter::Union{String,Symbol,Nothing} = nothing` : pass the SearchLight database adapter to be used by default
(one of :MySQL, :SQLite, or :PostgreSQL). If `dbadapter` is `nothing`, an adapter will have to be selected interactivel
at the REPL, during the app creation process.
"""
function newapp_mvc(name::String; autostart::Bool = true, dbadapter::Union{String,Symbol,Nothing} = nothing,
testmode::Bool = false, interactive::Bool = true) :: Nothing
newapp(name, autostart = autostart, fullstack = false, dbsupport = true, mvcsupport = true, dbadapter = dbadapter,
testmode = testmode, interactive = interactive)
end
"""
newapp_fullstack(name::String; autostart::Bool = true) :: Nothing
Template for scaffolding a new Genie app suitable for full stack web applications (includes MVC structure, DB support, and frontend asset pipeline).
# Arguments
- `name::String`: the name of the app
- `autostart::Bool`: automatically start the app once the file structure is created
- `dbadapter::Union{String,Symbol,Nothing} = nothing` : pass the SearchLight database adapter to be used by default
(one of :MySQL, :SQLite, or :PostgreSQL). If `dbadapter` is `nothing`, an adapter will have to be selected interactivel
at the REPL, during the app creation process.
"""
function newapp_fullstack(name::String; autostart::Bool = true, dbadapter::Union{String,Symbol,Nothing} = nothing,
testmode::Bool = false, interactive::Bool = true) :: Nothing
newapp(name, autostart = autostart, fullstack = true, dbsupport = true, mvcsupport = true, dbadapter = dbadapter,
testmode = testmode, interactive = interactive)
end
function autoconfdb(dbadapter)
Core.eval(Main, Meta.parse("using SearchLight"))
Core.eval(Main, Meta.parse("using SearchLight$dbadapter"))
Core.eval(Main, Meta.parse("Genie.Generator.@write_db_config()"))
end
end
| Genie | https://github.com/GenieFramework/Genie.jl.git |
|
[
"MIT"
] | 5.30.6 | 376aa3d800f4da32d232f2d9a1685e34e2911b4a | code | 4100 | """
Loads dependencies and bootstraps a Genie app. Exposes core Genie functionality.
"""
module Genie
import Inflector
include("Configuration.jl")
using .Configuration
const config = Configuration.Settings()
include("constants.jl")
import Sockets
import Logging
using Reexport
using Revise
include("Util.jl")
include("HTTPUtils.jl")
include("Exceptions.jl")
include("Repl.jl")
include("Watch.jl")
include("Loader.jl")
include("Secrets.jl")
include("FileTemplates.jl")
include("Toolbox.jl")
include("Generator.jl")
include("Encryption.jl")
include("Cookies.jl")
include("Input.jl")
include("Router.jl")
include("Renderer.jl")
include("WebChannels.jl")
include("WebThreads.jl")
include("Headers.jl")
include("Assets.jl")
include("Server.jl")
include("Commands.jl")
include("Responses.jl")
include("Requests.jl")
include("Logger.jl")
# === #
export up, down
@reexport using .Router
@reexport using .Loader
const assets_config = Genie.Assets.assets_config
"""
loadapp(path::String = "."; autostart::Bool = false) :: Nothing
Loads an existing Genie app from the file system, within the current Julia REPL session.
# Arguments
- `path::String`: the path to the Genie app on the file system.
- `autostart::Bool`: automatically start the app upon loading it.
# Examples
```julia-repl
shell> tree -L 1
.
├── Manifest.toml
├── Project.toml
├── bin
├── bootstrap.jl
├── config
├── env.jl
├── genie.jl
├── log
├── public
├── routes.jl
└── src
5 directories, 6 files
julia> using Genie
julia> Genie.loadapp(".")
_____ _
| __|___ ___|_|___
| | | -_| | | -_|
|_____|___|_|_|_|___|
┌ Info:
│ Starting Genie in >> DEV << mode
└
[ Info: Logging to file at MyGenieApp/log/dev.log
```
"""
function loadapp( path::String = ".";
autostart::Bool = false,
dbadapter::Union{Nothing,Symbol,String} = nothing,
context = Main) :: Nothing
if ! isnothing(dbadapter) && dbadapter != "nothing"
Genie.Generator.autoconfdb(dbadapter)
end
path = normpath(path) |> abspath
if isfile(joinpath(path, Genie.BOOTSTRAP_FILE_NAME))
Revise.includet(context, joinpath(path, Genie.BOOTSTRAP_FILE_NAME))
Genie.config.watch && @async Genie.Watch.watch(path)
autostart && (Core.eval(context, :(up())))
elseif isfile(joinpath(path, Genie.ROUTES_FILE_NAME)) || isfile(joinpath(path, Genie.APP_FILE_NAME))
genie(context = context) # load the app
else
error("Couldn't find a Genie app file in $path (bootstrap.jl, routes.jl or app.jl).")
end
nothing
end
const go = loadapp
"""
up(port::Int = Genie.config.server_port, host::String = Genie.config.server_host;
ws_port::Int = Genie.config.websockets_port, async::Bool = ! Genie.config.run_as_server) :: Nothing
Starts the web server. Alias for `Server.up`
# Arguments
- `port::Int`: the port used by the web server
- `host::String`: the host used by the web server
- `ws_port::Int`: the port used by the Web Sockets server
- `async::Bool`: run the web server task asynchronously
# Examples
```julia-repl
julia> up(8000, "127.0.0.1", async = false)
[ Info: Ready!
Web Server starting at http://127.0.0.1:8000
```
"""
const up = Server.up
const down = Server.down
const isrunning = Server.isrunning
const down! = Server.down!
### PRIVATE ###
"""
run() :: Nothing
Runs the Genie app by parsing the command line args and invoking the corresponding actions.
Used internally to parse command line arguments.
"""
function run(; server::Union{Sockets.TCPServer,Nothing} = nothing) :: Nothing
Genie.config.app_env == "test" || Commands.execute(Genie.config, server = server)
nothing
end
"""
genie() :: Union{Nothing,Sockets.TCPServer}
"""
function genie(; context = @__MODULE__) :: Union{Nothing,Sockets.TCPServer}
EARLYBINDING = Loader.loadenv(context = context)
Secrets.load(context = context)
Loader.load(context = context)
Genie.config.watch && @async Watch.watch(pwd())
run(server = EARLYBINDING)
EARLYBINDING
end
const bootstrap = genie
function __init__()
config.path_build = Genie.Configuration.buildpath()
end
end
| Genie | https://github.com/GenieFramework/Genie.jl.git |
|
[
"MIT"
] | 5.30.6 | 376aa3d800f4da32d232f2d9a1685e34e2911b4a | code | 390 | """
Genie utilities for working over HTTP.
"""
module HTTPUtils
import HTTP
"""
Base.Dict(req::HTTP.Request) :: Dict{String,String}
Converts a `HTTP.Request` to a `Dict`.
"""
function Base.Dict(req::HTTP.Request) :: Dict{String,String}
result = Dict{String,String}()
for (k,v) in Dict(req.headers)
result[lowercase(string(k))] = lowercase(string(v))
end
result
end
end | Genie | https://github.com/GenieFramework/Genie.jl.git |
|
[
"MIT"
] | 5.30.6 | 376aa3d800f4da32d232f2d9a1685e34e2911b4a | code | 3424 | """
Provides functionality for working with HTTP headers in Genie.
"""
module Headers
import HTTP
import Genie
const NORMALIZED_HEADERS = ["access-control-allow-origin", "origin",
"access-control-allow-headers", "access-control-request-headers", "access-control-expose-headers",
"access-control-max-age", "access-control-allow-credentials", "access-control-allow-methods",
"cookie", "set-cookie",
"content-type", "content-disposition",
"server"]
"""
set_headers!(req::HTTP.Request, res::HTTP.Response, app_response::HTTP.Response) :: HTTP.Response
Configures the response headers.
"""
function set_headers!(req::HTTP.Request, res::HTTP.Response, app_response::HTTP.Response) :: HTTP.Response
app_response = set_access_control_allow_origin!(req, res, app_response)
app_response = set_access_control_allow_headers!(req, res, app_response)
headers = Pair{String,String}[]
header_names = Set{String}()
for h in Iterators.flatten(h for h in [app_response.headers, res.headers, ["Server" => Genie.config.server_signature]])
if !in(h.first, header_names) || h.first == "Set-Cookie" # do not remove multiple "Set-Cookie" headers
push!(headers, h)
push!(header_names, h.first)
end
end
app_response.headers = headers
app_response
end
function set_access_control_allow_origin!(req::HTTP.Request, res::HTTP.Response, app_response::HTTP.Response) :: HTTP.Response
request_origin = get(Dict(req.headers), "Origin", "")
if ! isempty(request_origin)
allowed_origin_dict = Dict("Access-Control-Allow-Origin" =>
occursin(request_origin |> lowercase, join(Genie.config.cors_allowed_origins, ',') |> lowercase) ||
in("*", Genie.config.cors_allowed_origins)
? request_origin
: strip(Genie.config.cors_headers["Access-Control-Allow-Origin"])
)
allowed_origin_dict["Vary"] = "Origin"
app_response.headers = [d for d in merge(Genie.config.cors_headers, allowed_origin_dict, Dict(res.headers), Dict(app_response.headers))]
end
app_response
end
function set_access_control_allow_headers!(req::HTTP.Request, res::HTTP.Response, app_response::HTTP.Response) :: HTTP.Response
request_headers = get(Dict(req.headers), "Access-Control-Request-Headers", "")
if ! isempty(request_headers)
for rqh in split(request_headers, ',')
if ! occursin(strip(rqh) |> lowercase, Genie.config.cors_headers["Access-Control-Allow-Headers"] |> lowercase)
app_response.status = 403 # Forbidden
throw(Genie.Exceptions.ExceptionalResponse(app_response))
end
end
end
app_response
end
"""
normalize_headers(req::HTTP.Request)
Makes request headers case insensitive.
"""
function normalize_headers(req::Union{HTTP.Request,HTTP.Response})
normalized_headers = Pair{String,String}[]
for (k,v) in req.headers
if string(k) in NORMALIZED_HEADERS
push!(normalized_headers, normalize_header_key(string(k)) => string(v))
else
push!(normalized_headers, string(k) => string(v))
end
end
req.headers = normalized_headers
req
end
"""
normalize_header_key(key::String) :: String
Brings header keys to standard casing.
"""
function normalize_header_key(key::String) :: String
join(map(x -> uppercasefirst(lowercase(x)), split(key, '-')), '-')
end
end
| Genie | https://github.com/GenieFramework/Genie.jl.git |
|
[
"MIT"
] | 5.30.6 | 376aa3d800f4da32d232f2d9a1685e34e2911b4a | code | 9411 | """
Handles input coming through Http server requests.
"""
module Input
import HttpCommon, HTTP
export post, files, HttpInput, HttpPostData, HttpFiles, HttpFile
"""
HttpFile
Represents a file sent over HTTP
"""
mutable struct HttpFile
name::String
mime::String
data::Array{UInt8}
end
HttpFile() = HttpFile("", "", UInt8[])
const HttpPostData = Dict{String, Union{String, Vector{String}}}
const HttpFiles = Dict{String,HttpFile}
mutable struct HttpInput
post::HttpPostData
files::HttpFiles
end
HttpInput() = HttpInput(HttpPostData(), HttpFiles())
###
mutable struct HttpFormPart
headers::Dict{String, Dict{String,String}}
data::Array{UInt8}
end
HttpFormPart() = HttpFormPart(Dict{String,Dict{String,String}}(), UInt8[])
###
function all(request::HTTP.Request) :: HttpInput
input::HttpInput = HttpInput()
post_from_request!(request, input)
input
end
function post(request::HTTP.Request)
input::HttpInput = all(request)
input.post
end
function files(request::HTTP.Request)
input::HttpInput = all(request)
input.files
end
###
function post_from_request!(request::HTTP.Request, input::HttpInput)
headers = Dict(request.headers)
if first(something(findfirst("application/x-www-form-urlencoded", get(headers, "Content-Type", "")), 0:-1)) != 0
post_url_encoded!(request.body, input.post)
elseif first(something(findfirst("multipart/form-data", get(headers, "Content-Type", "")), 0:-1)) != 0
post_multipart!(request, input.post, input.files)
end
nothing
end
function post_url_encoded!(http_data::Array{UInt8, 1}, post_data::HttpPostData)
if occursin("%5B%5D", String(copy(http_data))) || occursin("[]", String(copy(http_data))) # array values []
for query_part in split(String(http_data), "&")
qp = split(query_part, "=")
(size(qp)[1] == 1) && (push!(qp, ""))
k = HTTP.URIs.unescapeuri(HTTP.URIs.decodeplus(qp[1]))
v = HTTP.URIs.unescapeuri(HTTP.URIs.decodeplus(qp[2]))
# collect values like x[] in an array
if endswith(k, "[]")
if haskey(post_data, k)
push!(post_data[k], v)
else
post_data[k] = [v]
end
else
post_data[k] = v
end
end
else
params::Dict{String,String} = HTTP.URIs.queryparams(String(http_data))
for (key::String, value::String) in params
post_data[key] = value
end
end
end
function post_multipart!(request::HTTP.Request, post_data::HttpPostData, files::HttpFiles) :: Nothing
headers = Dict(request.headers)
boundary::String = headers["Content-Type"][(findfirst("boundary=", headers["Content-Type"])[end] + 1):end]
boundary_length::Int = length(boundary)
if boundary_length > 0
form_parts::Array{HttpFormPart} = HttpFormPart[]
get_multiform_parts!(request.body, form_parts, boundary, boundary_length)
### Process form parts
if length(form_parts) > 0
for part::HttpFormPart in form_parts
hasFile::Bool = false
file::HttpFile = HttpFile()
fileFieldName::String = ""
for (field::String, values::Dict{String,String}) in part.headers
if field == "Content-Disposition" && haskey(values, "form-data")
# Check to see whether this part is a file upload
# Otherwise, treat as basic POST data
if haskey(values, "filename")
if length(values["filename"]) > 0
fileFieldName = values["name"]
file.name = values["filename"]
hasFile = true
end
elseif haskey(values, "name")
k = values["name"]
v = String(part.data)
if endswith(k, "[]")
if haskey(post_data, k)
push!(post_data[k], v)
else
post_data[k] = [v]
end
else
post_data[k] = v
end
end
elseif field == "Content-Type"
(file.mime, mime) = first(values)
end
end # for
if hasFile
file.data = part.data
files[fileFieldName] = file
fileFieldName = ""
file = HttpFile()
hasFile = false
end # if
end # for
end # if
end
nothing
end
###
function get_multiform_parts!(http_data::Vector{UInt8}, formParts::Array{HttpFormPart}, boundary, boundaryLength::Int = length(boundary))
### Go through each byte of data, parsing it into POST data and files.
# According to the spec, the boundary chosen by the client must be a unique string
# i.e. there should be no conflicts with the data within - so it should be safe to just do a basic string search.
part::HttpFormPart = HttpFormPart()
headerRaw::Array{UInt8} = UInt8[]
captureAsData::Bool = false
crOn::Bool = false
hadLineEnding::Bool = false
foundBoundary::Bool = false
foundFinalBoundary::Bool = false
bytes::Int = length(http_data)
byteIndexOffset::Int = 0
testIndex::Int = 1
byteTestIndex::Int = 0
byte::UInt8 = 0x00
# Skip over the first boundary and CRLF
byteIndex::Int = boundaryLength + 5
while !foundFinalBoundary && byteIndex <= bytes
byte = http_data[byteIndex]
# Test for boundary.
if (
(byte == 0x0d && bytes >= byteIndex+3 && http_data[byteIndex + 1] == 0x0a && Char(http_data[byteIndex + 2]) == '-' && Char(http_data[byteIndex + 3]) == '-')
|| (byte == '-' && bytes >= byteIndex+1 && Char(http_data[byteIndex + 1]) == '-')
)
foundBoundary = true
end
if byte == 0x0d
byteIndexOffset = byteIndex + 3
else
byteIndexOffset = byteIndex + 1
end
byteTestIndex = byteIndexOffset
testIndex = 1;
# Find the position of the next char NOT in the boundary
if foundBoundary
while testIndex < boundaryLength
byteTestIndex = byteIndexOffset + testIndex
if byteTestIndex > bytes || Char(http_data[byteTestIndex]) != boundary[testIndex]
break
end
testIndex = testIndex + 1
end
end
# Check if this boundary is the final one
if foundBoundary
if Char(http_data[byteTestIndex + 2]) == '-'
foundFinalBoundary = true
byteIndex = byteTestIndex + 5
else
byteIndex = byteTestIndex + 3
end
end
## Otherwise, process data
if foundBoundary
captureAsData = false
crOn = false
hadLineEnding = false
foundBoundary = false
push!(formParts, part)
part = HttpFormPart()
else
if captureAsData
push!(part.data, byte)
else
## Check for CR
if byte == 0x0d
crOn = true
else
## Check for LF and previous CR
if byte == 0x0a && crOn
## Check for CRLFCRLF
if hadLineEnding
## End of headers
captureAsData = true
hadLineEnding = false
else
## End of single-line header
header::String = String(headerRaw)
if length(header) > 0
headerParts = split(header, ": "; limit=2)
valueDecoded = parse_semicolon_fields(String(headerParts[2]));
if length(valueDecoded) > 0
part.headers[headerParts[1]] = valueDecoded
end
end
headerRaw = UInt8[]
hadLineEnding = true
end
else
if hadLineEnding
hadLineEnding = false
end
push!(headerRaw, byte)
end
crOn = false
end
end
end
byteIndex = byteIndex + 1
end
end
###
function parse_semicolon_fields(dataString::String)
dataString = dataString * ";"
data = Dict{String,String}()
prevCharacter::Char = 0x00
inSingleQuotes::Bool = false
inDoubleQuotes::Bool = false
ignore::Bool = false
workingString::String = ""
dataStringLength::Int = length(dataString)
dataStringLengthLoop::Int = dataStringLength + 1
charIndex::Int = 1
utfIndex::Int = 1 # real index for uft-8
while charIndex < dataStringLengthLoop
# character = dataString[charIndex]
character = dataString[utfIndex]
if ! inSingleQuotes && character == '"' && prevCharacter != '\\'
inDoubleQuotes = ! inDoubleQuotes
ignore = true
end
if ! inDoubleQuotes && character == '\'' && prevCharacter != '\\'
inSingleQuotes = ! inSingleQuotes
ignore = true
end
if charIndex == dataStringLength || (character == ';' && !(inSingleQuotes || inDoubleQuotes))
workingString = strip(workingString)
if length(workingString) > 0
decoded = parse_quoted_params(workingString)
if decoded != nothing
(key, value) = decoded
data[key] = value
else
data[workingString] = workingString
end
workingString = ""
end
elseif ! ignore
workingString = workingString * string(character)
end
prevCharacter = character
charIndex = charIndex + 1
utfIndex = nextind(dataString, utfIndex) # real index for uft-8
ignore = false
end
return data
end
function parse_quoted_params(data::String)
tokens = split(data, "="; limit=2)
if length(tokens) == 2
return (tokens[1], tokens[2])
end
return nothing
end
###
end
| Genie | https://github.com/GenieFramework/Genie.jl.git |
|
[
"MIT"
] | 5.30.6 | 376aa3d800f4da32d232f2d9a1685e34e2911b4a | code | 14903 | """
Genie code loading functionality -- loading and managing app-wide components like configs, models, initializers, etc.
"""
module Loader
import Logging
import REPL, REPL.Terminals
import Revise
import Genie
import Sockets
using DotEnv
const post_load_hooks = Function[]
export @using
### PRIVATE ###
function importenv()
haskey(ENV, "WSPORT") && (! isempty(ENV["WSPORT"])) && (Genie.config.websockets_port = parse(Int, ENV["WSPORT"]))
haskey(ENV, "WSEXPPORT") && (! isempty(ENV["WSEXPPORT"])) && (Genie.config.websockets_exposed_port = parse(Int, ENV["WSEXPPORT"]))
haskey(ENV, "WSEXPHOST") && (! isempty(ENV["WSEXPHOST"])) && (Genie.config.websockets_exposed_host = ENV["WSEXPHOST"])
haskey(ENV, "WSBASEPATH") && (Genie.config.websockets_base_path = ENV["WSBASEPATH"])
haskey(ENV, "BASEPATH") && (Genie.config.base_path = ENV["BASEPATH"])
nothing
end
function loadenv(; context) :: Union{Sockets.TCPServer,Nothing}
haskey(ENV, "GENIE_ENV") || (ENV["GENIE_ENV"] = "dev")
bootstrap(context)
haskey(ENV, "GENIE_HOST") && (! isempty(ENV["GENIE_HOST"])) && (Genie.config.server_host = ENV["GENIE_HOST"])
haskey(ENV, "GENIE_HOST") || (ENV["GENIE_HOST"] = Genie.config.server_host)
haskey(ENV, "PORT") && (! isempty(ENV["PORT"])) && (Genie.config.server_port = parse(Int, ENV["PORT"]))
haskey(ENV, "PORT") || (ENV["PORT"] = Genie.config.server_port)
haskey(ENV, "WSPORT") && (! isempty(ENV["WSPORT"])) && (Genie.config.websockets_port = parse(Int, ENV["WSPORT"]))
### EARLY BIND TO PORT FOR HOSTS WITH TIMEOUT ###
EARLYBINDING = if haskey(ENV, "EARLYBIND") && strip(lowercase(ENV["EARLYBIND"])) == "true"
@info "Binding to host $(ENV["GENIE_HOST"]) and port $(ENV["PORT"]) \n"
try
Sockets.listen(parse(Sockets.IPAddr, ENV["GENIE_HOST"]), parse(Int, ENV["PORT"]))
catch ex
@error ex
@warn "Failed binding! \n"
nothing
end
else
nothing
end
end
"""
bootstrap(context::Union{Module,Nothing} = nothing) :: Nothing
Kickstarts the loading of a Genie app by loading the environment settings.
"""
function bootstrap(context::Union{Module,Nothing} = default_context(context); show_banner::Bool = true) :: Nothing
ENV_FILE_NAME = "env.jl"
GLOBAL_ENV_FILE_NAME = "global.jl"
load_dotenv()
if haskey(ENV, "GENIE_ENV")
Genie.config.app_env = ENV["GENIE_ENV"]
else
ENV["GENIE_ENV"] = Genie.config.app_env = "dev"
end
isfile(joinpath(Genie.config.path_env, GLOBAL_ENV_FILE_NAME)) && Base.include(context, joinpath(Genie.config.path_env, GLOBAL_ENV_FILE_NAME))
isfile(joinpath(Genie.config.path_env, ENV["GENIE_ENV"] * ".jl")) && Base.include(context, joinpath(Genie.config.path_env, ENV["GENIE_ENV"] * ".jl"))
Genie.config.app_env = ENV["GENIE_ENV"] # ENV might have changed
importenv()
get!(ENV, "GENIE_BANNER", "true") |> strip |> lowercase != "false" && show_banner && print_banner()
nothing
end
"""
Loads .env file if present
"""
function load_dotenv()
if isfile(Genie.config.env_file)
@static if VersionNumber(Genie.Util.package_version(DotEnv)) >= v"1.0"
DotEnv.load!(Genie.config.env_file; override = true)
else
DotEnv.config(; path = Genie.config.env_file, override = true)
end
end
nothing
end
function print_banner()
printstyled("""
██████╗ ███████╗███╗ ██╗██╗███████╗ ███████╗
██╔════╝ ██╔════╝████╗ ██║██║██╔════╝ ██╔════╝
██║ ███╗█████╗ ██╔██╗ ██║██║█████╗ ███████╗
██║ ██║██╔══╝ ██║╚██╗██║██║██╔══╝ ╚════██║
╚██████╔╝███████╗██║ ╚████║██║███████╗ ███████║
╚═════╝ ╚══════╝╚═╝ ╚═══╝╚═╝╚══════╝ ╚══════╝
""", color = :light_black, bold = true)
printstyled("| Website https://genieframework.com\n", color = :light_black, bold = true)
printstyled("| GitHub https://github.com/genieframework\n", color = :light_black, bold = true)
printstyled("| Docs https://learn.genieframework.com\n", color = :light_black, bold = true)
printstyled("| Discord https://discord.com/invite/9zyZbD6J7H\n", color = :light_black, bold = true)
printstyled("| Twitter https://twitter.com/essenciary\n\n", color = :light_black, bold = true)
printstyled("Active env: $(ENV["GENIE_ENV"] |> uppercase)\n\n", color = :light_blue, bold = true)
nothing
end
"""
load_libs(root_dir::String = Genie.config.path_lib) :: Nothing
Recursively includes files from `lib/` and subfolders.
The `lib/` folder, if present, is designed to host user code in the form of .jl files.
"""
function load_libs(root_dir::String = Genie.config.path_lib; context::Union{Module,Nothing} = nothing) :: Nothing
autoload(root_dir; context)
end
"""
load_resources(root_dir::String = Genie.config.path_resources) :: Nothing
Automatically recursively includes files from `resources/` and subfolders.
"""
function load_resources(root_dir::String = Genie.config.path_resources;
context::Union{Module,Nothing} = nothing) :: Nothing
skpdr = ["views"]
@debug "Auto loading validators"
autoload(root_dir; context, skipdirs = skpdr, namematch = r"Validator\.jl$") # validators first, used by models
@debug "Auto loading models"
autoload(root_dir; context, skipdirs = skpdr, skipmatch = r"Controller\.jl$|Validator\.jl$") # next models
@debug "Auto loading controllers"
autoload(root_dir; context, skipdirs = skpdr, namematch = r"Controller\.jl$") # finally controllers
end
"""
load_helpers(root_dir::String = Genie.config.path_helpers) :: Nothing
Automatically recursively includes files from `helpers/` and subfolders.
"""
function load_helpers(root_dir::String = Genie.config.path_helpers; context::Union{Module,Nothing} = nothing) :: Nothing
autoload(root_dir; context)
end
"""
load_initializers(root_dir::String = Genie.config.path_config; context::Union{Module,Nothing} = nothing) :: Nothing
Automatically recursively includes files from `initializers/` and subfolders.
"""
function load_initializers(root_dir::String = Genie.config.path_initializers; context::Union{Module,Nothing} = nothing) :: Nothing
autoload(root_dir; context)
end
"""
load_plugins(root_dir::String = Genie.config.path_plugins; context::Union{Module,Nothing} = nothing) :: Nothing
Automatically recursively includes files from `plugins/` and subfolders.
"""
function load_plugins(root_dir::String = Genie.config.path_plugins; context::Union{Module,Nothing} = nothing) :: Nothing
autoload(root_dir; context)
end
"""
load_routes(routes_file::String = Genie.ROUTES_FILE_NAME; context::Union{Module,Nothing} = nothing) :: Nothing
Loads the routes file.
"""
function load_routes(routes_file::String = Genie.ROUTES_FILE_NAME; context::Union{Module,Nothing} = nothing) :: Nothing
isfile(routes_file) && Revise.includet(default_context(context), routes_file)
nothing
end
"""
load_app(app_file::String = Genie.APP_FILE_NAME; context::Union{Module,Nothing} = nothing) :: Nothing
Loads the app file (`app.jl` can be used for single file apps, instead of `routes.jl`).
"""
function load_app(app_file::String = Genie.APP_FILE_NAME; context::Union{Module,Nothing} = nothing) :: Nothing
isfile(app_file) && Revise.includet(default_context(context), abspath(app_file))
nothing
end
"""
autoload
Automatically and recursively includes files from the indicated `root_dir` into the indicated `context` module,
skipping directories from `dir`.
The files are set up with `Revise` to be automatically reloaded when changed (in dev environment).
"""
function autoload(root_dir::String = Genie.config.path_lib;
context::Union{Module,Nothing} = nothing,
skipdirs::Vector{String} = String[],
namematch::Regex = r".*",
skipmatch::Union{Regex,Nothing} = nothing,
autoload_ignore_file::String = Genie.config.autoload_ignore_file,
autoload_file::String = Genie.config.autoload_file) :: Nothing
isdir(root_dir) || return nothing
validinclude(fi)::Bool = endswith(fi, ".jl") && match(namematch, fi) !== nothing &&
((skipmatch !== nothing && match(skipmatch, fi) === nothing) || skipmatch === nothing)
for i in sort_load_order(root_dir, readdir(root_dir))
(isfile(joinpath(root_dir, autoload_ignore_file)) || i == autoload_file ) && continue
fi = joinpath(root_dir, i)
@debug "Checking $fi"
if validinclude(fi)
@debug "Auto loading file: $fi"
Revise.includet(default_context(context), fi)
end
end
for (root, dirs, files) in walkdir(root_dir)
for dir in dirs
in(dir, skipdirs) && continue
p = joinpath(root, dir)
for i in readdir(p)
isfile(joinpath(p, autoload_ignore_file)) && continue
fi = joinpath(p, i)
@debug "Checking $fi"
if validinclude(fi)
@debug "Auto loading file: $fi"
Revise.includet(default_context(context), fi)
end
end
end
end
nothing
end
function autoload(dirs::Vector{String}; kwargs...)
for d in dirs
autoload(d; kwargs...)
end
end
function autoload(dirs...; kwargs...)
autoload([dirs...]; kwargs...)
end
"""
sort_load_order(root_dir::String, files::Vector{String}) :: Vector{String}
Returns a sorted list of files based on `.autoload` file. If `.autoload` file is a not present in `rootdir` return original output of `readdir()`.
"""
function sort_load_order(rootdir, lsdir::Vector{String})
autoloadfilepath = isfile(joinpath(pwd(), rootdir, Genie.config.autoload_file)) ? joinpath(pwd(), rootdir, Genie.config.autoload_file) : return lsdir
autoloadorder = open(f -> ([line for line in eachline(f)]), autoloadfilepath)
fn_loadorder = []
for file in autoloadorder
if file in lsdir
push!(fn_loadorder, file)
filter!(f -> f != file, lsdir)
elseif startswith(file, '-') && file[2:end] ∈ lsdir
filter!(f -> f != file[2:end], lsdir)
continue
else
continue
end
end
append!(fn_loadorder, lsdir)
end
"""
load(; context::Union{Module,Nothing} = nothing) :: Nothing
Main entry point to loading a Genie app.
"""
function load(; context::Union{Module,Nothing} = nothing) :: Nothing
context = default_context(context)
Genie.Configuration.isdev() && Core.eval(context, :(__revise_mode__ = :eval))
t = Terminals.TTYTerminal("", stdin, stdout, stderr)
for i in Genie.config.autoload
f = getproperty(@__MODULE__, Symbol("load_$i"))
Genie.Repl.replprint(string(i), t; prefix = "Loading ", clearline = 3, sleep_time = 0.0)
Base.@invokelatest f(; context)
Genie.Repl.replprint("$i ✅", t; prefix = "Loading ", clearline = 3, color = :green, sleep_time = 0.1)
end
if ! isempty(post_load_hooks)
Genie.Repl.replprint("Running post load hooks ✅", t; clearline = 3, color = :green, sleep_time = 0.1)
for f in unique(post_load_hooks)
f |> Base.invokelatest
end
end
Genie.Repl.replprint("\nReady! \n", t; clearline = 1, color = :green, bold = :true)
println()
nothing
end
"""
default_context(context::Union{Module,Nothing})
Sets the module in which the code is loaded (the app's module)
"""
function default_context(context::Union{Module,Nothing} = nothing)
try
userapp = isdefined(Main, :UserApp) ? Main.UserApp : @__MODULE__
context === nothing ? userapp : context
catch ex
@error ex
@__MODULE__
end
end
function expr_to_path(expr::Union{Expr, Symbol, String})::String
path = String[]
while expr isa Expr && expr.head == :call && expr.args[1] ∈ (:\, :/)
push!(path, String(expr.args[3]))
expr = expr.args[2]
end
push!(path, String(expr))
return join(reverse(path), '/')
end
function _findpackage(package::String)
orig_package = package
path, package = splitdir(package)
validpath = if path != ""
loadpath = copy(LOAD_PATH)
empty!(LOAD_PATH)
push!(LOAD_PATH, path)
true
else
false
end
p = Base.find_package(package)
if p === nothing
if isdir(orig_package)
pushfirst!(LOAD_PATH, orig_package)
p = Base.find_package(package)
popfirst!(LOAD_PATH)
end
end
if validpath
empty!(LOAD_PATH)
append!(LOAD_PATH, loadpath)
end
p === nothing && return
path, package = splitdir(p)
package = splitext(package)[1]
basedir, parentdir = splitdir(path)
# if it is a package structure prepend parent directory of the package as LOAD_PATH to path
if parentdir == "src" && basename(basedir) == package
path = "$(dirname(basedir));$path"
end
path, package
end
"""
@using(package_path)
Macro to simplify loading of modules taking advantage of precompilation.
When called from Main it temporarilty adds the path to LOAD_PATH and loads the module via `using`
When called from a different module it includes the module file and uses `using .MyModule`
`package_path` can be used in several ways
- as a path to a directory containing a module file of the same name
e.g '@using models/MyApp' to load 'models/MyApp/MyApp.jl'
- as a path to a module (without extension '.jl')
e.g. '@using models/MyApp' to load models/MyApp.jl'
- as a path to a package directory containing a 'src' directory and module file therein
e.g. '@using models/MyApp' to load 'models/MyApp/src/MyApp.jl'
### Examples
```julia
@using models/MyApp
@using StippleDemos/Vue3/Calendars
```
or explicitly
```julia
@using StippleDemos/Vue3/Calendars/Calendars
```
Note, directories containing special characters like colon (`':'`) or space (`' '`)
need to be escaped by double quotes.
```julia
@using "C:/Program Files/Julia/models/Calendars"
# or
@using "C:/Program Files"/Julia/models/Calendars
```
Caveat: Due to precompilation it is not possible to supply variables to the macro.
Calls need to supply explicit paths.
"""
macro _using(package)
# determine whether @using is called from Main or a different module
is_submodule = __module__ != Base.Main
package = expr_to_path(package)
fp = _findpackage(package)
if fp === nothing
@warn "package $package not found"
return nothing
end
path, package_name = fp
package_symbol = Symbol(package_name)
if is_submodule
# if called from submodule add module via `include()` and, `using .MyModule`
quote
include(joinpath($path, "$($package_name).jl"))
using .$(package_symbol)
end |> esc
else
# if called from Main add module via setting LOAD_PATH and `using MyModule`
quote
let pp = split($path, ';')
for p in reverse(pp)
pushfirst!(LOAD_PATH, p)
end
@debug "using $($package_name) (from '$($path)')"
try
using $package_symbol
catch e
error(e)
finally
for _ in pp
popfirst!(LOAD_PATH)
end
end
end
nothing
end
end
end
const var"@using" = var"@_using"
end | Genie | https://github.com/GenieFramework/Genie.jl.git |
|
[
"MIT"
] | 5.30.6 | 376aa3d800f4da32d232f2d9a1685e34e2911b4a | code | 2553 | module Logger
using Genie
using Logging, LoggingExtras
import Dates
"""
Collection of custom user defined handlers that will be called when a log message is received.
# Example
```julia
julia> f(args...) = println(args...)
julia> push!(Logger.HANDLERS, f)
julia> @info "hello"
[ Info: 2023-10-25 13:36:15 hello
Info2023-10-25 13:36:15 helloMainREPL[5]Main_0f6a5e07REPL[5]1
```
"""
const HANDLERS = Function[]
function timestamp_logger(logger)
date_format = Genie.config.log_date_format
LoggingExtras.TransformerLogger(logger) do log
merge(log, (; message = "$(Dates.format(Dates.now(), date_format)) $(log.message)"))
end
end
function default_log_name()
"$(Genie.config.app_env)-$(Dates.today()).log"
end
function initialize_logging(; log_name = default_log_name(), log_path = Genie.config.path_log)
logger = if Genie.config.log_to_file
log_path = abspath(log_path)
isdir(log_path) || mkpath(log_path)
LoggingExtras.TeeLogger(
LoggingExtras.FileLogger(joinpath(log_path, log_name), always_flush = true, append = true),
Logging.ConsoleLogger(stdout, Genie.config.log_level)
)
else
Logging.ConsoleLogger(stdout, Genie.config.log_level)
end
logger = LoggingExtras.TeeLogger(
logger,
GenieLogger() do lvl, msg, _mod, group, id, file, line
for handler in HANDLERS
try
handler(lvl, msg, _mod, group, id, file, line)
catch
end
end
end
)
LoggingExtras.MinLevelLogger(timestamp_logger(logger), Genie.config.log_level) |> global_logger
nothing
end
### custom logger
"""
GenieLogger is a custom logger that allows you to pass a function that will be called with the log message, level, module, group, id, file and line.
# Example
```julia
l = Genie.Logger.GenieLogger() do lvl, msg, _mod, group, id, file, line
uppercase(msg) |> println
end
with_logger(l) do
@info "hello"
@warn "watch out"
@error "oh noh"
end
```
"""
struct GenieLogger <: Logging.AbstractLogger
action::Function
io::IO
end
GenieLogger(action::Function) = GenieLogger(action, stderr)
Logging.min_enabled_level(logger::GenieLogger) = Logging.BelowMinLevel
Logging.shouldlog(logger::GenieLogger, level, _module, group, id) = true
Logging.catch_exceptions(logger::GenieLogger) = true
function Logging.handle_message(logger::GenieLogger, lvl, msg, _mod, group, id, file, line; kwargs...)
logger.action(lvl, msg, _mod, group, id, file, line)
nothing
end
end
| Genie | https://github.com/GenieFramework/Genie.jl.git |
|
[
"MIT"
] | 5.30.6 | 376aa3d800f4da32d232f2d9a1685e34e2911b4a | code | 15200 | module Renderer
export respond, redirect, render
import EzXML, FilePathsBase, HTTP, JuliaFormatter, Logging, Markdown, SHA
import Genie
const DEFAULT_CHARSET = "charset=utf-8"
const DEFAULT_CONTENT_TYPE = :html
const DEFAULT_LAYOUT_FILE = "app"
const VIEWS_FOLDER = "views"
const BUILD_NAME = "GenieViews"
"""
const CONTENT_TYPES = Dict{Symbol,String}
Collection of content-types mappings between user friendly short names and
MIME types plus charset.
"""
const CONTENT_TYPES = Dict{Symbol,String}(
:html => "text/html; $DEFAULT_CHARSET",
:text => "text/plain; $DEFAULT_CHARSET",
:json => "application/json; $DEFAULT_CHARSET",
:javascript => "application/javascript; $DEFAULT_CHARSET",
:xml => "text/xml; $DEFAULT_CHARSET",
:markdown => "text/markdown; $DEFAULT_CHARSET",
:css => "text/css; $DEFAULT_CHARSET",
:fontwoff2 => "font/woff2",
:favicon => "image/x-icon",
:png => "image/png",
:jpg => "image/jpeg",
:svg => "image/svg+xml"
)
const MIME_TYPES = Dict(
:html => MIME"text/html",
:text => MIME"text/plain",
:json => MIME"application/json",
:javascript => MIME"application/javascript",
:xml => MIME"text/xml",
:markdown => MIME"text/markdown",
:css => MIME"text/css",
:fontwoff2 => MIME"font/woff2",
)
const MAX_FILENAME_LENGTH = 1_000
push_content_type(s::Symbol, content_type::String, charset::String = DEFAULT_CHARSET) = (CONTENT_TYPES[s] = "$content_type; $charset")
const ResourcePath = Union{String,Symbol}
const HTTPHeaders = Dict{String,String}
const Path = FilePathsBase.Path
const FilePath = Union{FilePathsBase.PosixPath,FilePathsBase.WindowsPath}
const filepath = FilePathsBase.Path
macro path_str(s)
:(FilePathsBase.@p_str($s))
end
export FilePath, filepath, Path, @path_str
export vars
export WebRenderable
init_task_local_storage() = (haskey(task_local_storage(), :__vars) || task_local_storage(:__vars, Dict{Symbol,Any}()))
init_task_local_storage()
clear_task_storage() = task_local_storage(:__vars, Dict{Symbol,Any}())
"""
mutable struct WebRenderable
Represents an object that can be rendered on the web as a HTTP Response
"""
mutable struct WebRenderable
body::String
content_type::Symbol
status::Int
headers::HTTPHeaders
end
"""
WebRenderable(body::String)
Creates a new instance of `WebRenderable` with `body` as the body of the response and
default content type, no headers, and 200 status code.
#Examples
```jldoctest
julia> Genie.Renderer.WebRenderable("hello")
Genie.Renderer.WebRenderable("hello", :html, 200, Dict{String,String}())
```
"""
WebRenderable(body::String) = WebRenderable(body, DEFAULT_CONTENT_TYPE, 200, HTTPHeaders())
"""
WebRenderable(body::String, content_type::Symbol)
Creates a new instance of `WebRenderable` with `body` as the body of the response and
`content_type` as the content type, no headers, and 200 status code.
#Examples
```jldoctest
julia> Genie.Renderer.WebRenderable("hello", :json)
Genie.Renderer.WebRenderable("hello", :json, 200, Dict{String,String}())
```
"""
WebRenderable(body::String, content_type::Symbol) = WebRenderable(body, content_type, 200, HTTPHeaders())
"""
WebRenderable(; body::String = "", content_type::Symbol = DEFAULT_CONTENT_TYPE,
status::Int = 200, headers::HTTPHeaders = HTTPHeaders())
Creates a new instance of `WebRenderable` using the values passed as keyword arguments.
#Examples
```jldoctest
julia> Genie.Renderer.WebRenderable()
Genie.Renderer.WebRenderable("", :html, 200, Dict{String,String}())
julia> Genie.Renderer.WebRenderable(body = "bye", content_type = :javascript, status = 301, headers = Dict("Location" => "/bye"))
Genie.Renderer.WebRenderable("bye", :javascript, 301, Dict("Location" => "/bye"))
```
"""
WebRenderable(; body::String = "", content_type::Symbol = DEFAULT_CONTENT_TYPE,
status::Int = 200, headers::HTTPHeaders = HTTPHeaders()) = WebRenderable(body, content_type, status, headers)
"""
WebRenderable(wr::WebRenderable, status::Int, headers::HTTPHeaders)
Returns `wr` overwriting its `status` and `headers` fields with the passed arguments.
#Examples
```jldoctest
julia> Genie.Renderer.WebRenderable(Genie.Renderer.WebRenderable(body = "good morning", content_type = :javascript), 302, Dict("Location" => "/morning"))
Genie.Renderer.WebRenderable("good morning", :javascript, 302, Dict("Location" => "/morning"))
```
"""
function WebRenderable(wr::WebRenderable, status::Int, headers::HTTPHeaders)
wr.status = status
wr.headers = headers
wr
end
function WebRenderable(wr::WebRenderable, content_type::Symbol, status::Int, headers::HTTPHeaders)
wr.content_type = content_type
wr.status = status
wr.headers = headers
wr
end
function WebRenderable(f::Function, args...)
fr::String = Base.invokelatest(f) |> join
WebRenderable(fr, args...)
end
"""
render
Abstract function that needs to be specialized by individual renderers.
"""
function render end
### REDIRECT RESPONSES ###
"""
Sets redirect headers and prepares the `Response`.
It accepts 3 parameters:
1 - Label of a Route (to learn more, see the advanced routes section)
2 - Default HTTP 302 Found Status: indicates that the provided resource will be changed to a URL provided
3 - Tuples (key, value) to define the HTTP request header
Example:
julia> Genie.Renderer.redirect(:index, 302, Dict("Content-Type" => "application/json; charset=UTF-8"))
HTTP.Messages.Response:
HTTP/1.1 302 Moved Temporarily
Content-Type: application/json; charset=UTF-8
Location: /index
Redirecting you to /index
"""
function redirect(location::String, code::Int = 302, headers::HTTPHeaders = HTTPHeaders()) :: HTTP.Response
headers["Location"] = location
WebRenderable("Redirecting you to $location", :html, code, headers) |> respond
end
@noinline function redirect(named_route::Symbol, code::Int = 302, headers::HTTPHeaders = HTTPHeaders(); route_args...) :: HTTP.Response
redirect(Genie.Router.linkto(named_route; route_args...), code, headers)
end
"""
hasrequested(content_type::Symbol) :: Bool
Checks wheter or not the requested content type matches `content_type`.
"""
function hasrequested(content_type::Symbol) :: Bool
task_local_storage(:__params)[:response_type] == content_type
end
### RESPONSES ###
"""
Constructs a `Response` corresponding to the Content-Type of the request.
"""
function respond(r::WebRenderable) :: HTTP.Response
haskey(r.headers, "Content-Type") || (r.headers["Content-Type"] = CONTENT_TYPES[r.content_type])
HTTP.Response(r.status, [h for h in r.headers], body = r.body)
end
function respond(response::HTTP.Response) :: HTTP.Response
response
end
function respond(body::String, params::Dict{Symbol,T})::HTTP.Response where {T}
r = params[:RESPONSE]
r.data = body
r |> respond
end
function respond(err::T, content_type::Union{Symbol,String} = Genie.Router.responsetype(), code::Int = 500) :: T where {T<:Exception}
T
end
function respond(body::String, content_type::Union{Symbol,String} = Genie.Router.responsetype(), code::Int = 200) :: HTTP.Response
HTTP.Response(code,
(isa(content_type, Symbol) ? ["Content-Type" => CONTENT_TYPES[content_type]] : ["Content-Type" => content_type]),
body = body)
end
function respond(body, code::Int = 200, headers::HTTPHeaders = HTTPHeaders())
HTTP.Response(code, [h for h in headers], body = string(body))
end
function respond(f::Function, code::Int = 200, headers::HTTPHeaders = HTTPHeaders())
respond(f(), code, headers)
end
"""
registervars(vs...) :: Nothing
Loads the rendering vars into the task's scope
"""
function registervars(; context::Module = @__MODULE__, vs...) :: Nothing
task_local_storage(:__vars, merge(vars(), Dict{Symbol,Any}(vs), Dict{Symbol,Any}(:context => context)))
nothing
end
"""
injectkwvars() :: String
Sets up variables passed into the view, making them available in the
generated view function as kw arguments for the rendering function.
"""
function injectkwvars() :: String
output = String[]
for kv in vars()
push!(output, "$(kv[1]) = Genie.Renderer.vars($(repr(kv[1])))")
end
join(output, ',')
end
"""
view_file_info(path::String, supported_extensions::Vector{String}) :: Tuple{String,String}
Extracts path and extension info about a file
"""
function view_file_info(path::String, supported_extensions::Vector{String}) :: Tuple{String,String}
_path, _extension = "", ""
if isfile(path)
_path_without_extension, _extension = Base.Filesystem.splitext(path)
_path = _path_without_extension * _extension
else
for file_extension in supported_extensions
if isfile(path * file_extension)
_path, _extension = path * file_extension, file_extension
break
end
end
end
if ! isfile(_path)
error_message = length(supported_extensions) == 1 ?
"""Template file "$path$(supported_extensions[1])" does not exist""" :
"""Template file "$path" with extensions $supported_extensions does not exist"""
error(error_message)
end
return _path, _extension
end
"""
vars_signature() :: String
Collects the names of the view vars in order to create a unique hash/salt to identify
compiled views with different vars.
"""
function vars_signature() :: String
vars() |> keys |> collect |> sort |> string
end
"""
function_name(file_path::String)
Generates function name for generated HTML+Julia views.
"""
function function_name(file_path::String) :: String
"func_$(SHA.sha1( relpath(isempty(file_path) ? " " : file_path) * vars_signature() ) |> bytes2hex)"
end
"""
m_name(file_path::String)
Generates module name for generated HTML+Julia views.
"""
function m_name(file_path::String) :: String
string(SHA.sha1( relpath(isempty(file_path) ? " " : file_path) * vars_signature()) |> bytes2hex)
end
"""
build_is_stale(file_path::String, build_path::String) :: Bool
Checks if the view template has been changed since the last time the template was compiled.
"""
function build_is_stale(file_path::String, build_path::String) :: Bool
isfile(file_path) || return true
file_mtime = stat(file_path).mtime
build_mtime = stat(build_path).mtime
status = file_mtime > build_mtime
status
end
"""
build_module(content::String, path::String, mod_name::String) :: String
Persists compiled Julia view data to file and returns the path
"""
function build_module(content::S, path::T, mod_name::U; output_path::Bool = true)::String where {S<:AbstractString,T<:AbstractString,U<:AbstractString}
module_path = joinpath(Genie.config.path_build, BUILD_NAME, mod_name)
isdir(dirname(module_path)) || mkpath(dirname(module_path))
open(module_path, "w") do io
output_path && write(io, "# $path \n\n")
write(io,
Genie.config.format_julia_builds ?
(try
JuliaFormatter.format_text(content)
catch ex
@error ex
content
end) : content)
end
module_path
end
"""
preparebuilds() :: Bool
Sets up the build folder and the build module file for generating the compiled views.
"""
function preparebuilds(subfolder = BUILD_NAME) :: Bool
build_path = joinpath(Genie.config.path_build, subfolder)
isdir(build_path) || mkpath(build_path)
true
end
"""
purgebuilds(subfolder = BUILD_NAME) :: Bool
Removes the views builds folders with all the generated views.
"""
function purgebuilds(subfolder = BUILD_NAME) :: Bool
rm(joinpath(Genie.config.path_build, subfolder), force = true, recursive = true)
true
end
"""
changebuilds(subfolder = BUILD_NAME) :: Bool
Changes/creates a new builds folder.
"""
function changebuilds(subfolder = BUILD_NAME) :: Bool
Genie.config.path_build = Genie.Configuration.buildpath()
preparebuilds()
end
"""
function vars
Utility for accessing view vars
"""
function vars()
haskey(task_local_storage(), :__vars) ? task_local_storage(:__vars) : init_task_local_storage()
end
"""
function vars(key)
Utility for accessing view vars stored under `key`
"""
function vars(key)
vars()[key]
end
"""
function vars(key, value)
Utility for setting a new view var, as `key` => `value`
"""
function vars(key, value)
if haskey(task_local_storage(), :__vars)
vars()[key] = value
else
task_local_storage(:__vars, Dict(key => value))
end
end
"""
set_negotiated_content(req::HTTP.Request, res::HTTP.Response, params::Dict{Symbol,Any})
Configures the request, response, and params response content type based on the request and defaults.
"""
function set_negotiated_content(req::HTTP.Request, res::HTTP.Response, params::Dict{Symbol,Any})
req_type = Genie.Router.request_type(req)
params[:response_type] = req_type
params[Genie.Router.PARAMS_MIME_KEY] = get!(MIME_TYPES, params[:response_type], typeof(MIME(req_type)))
push!(res.headers, "Content-Type" => get!(CONTENT_TYPES, params[:response_type], string(MIME(req_type))))
req, res, params
end
"""
negotiate_content(req::Request, res::Response, params::Params) :: Response
Computes the content-type of the `Response`, based on the information in the `Request`.
"""
function negotiate_content(req::HTTP.Request, res::HTTP.Response, params::Dict{Symbol,Any}) :: Tuple{HTTP.Request,HTTP.Response,Dict{Symbol,Any}}
headers = Dict(res.headers)
if haskey(params, :response_type) && in(Symbol(params[:response_type]), collect(keys(CONTENT_TYPES)) )
params[:response_type] = Symbol(params[:response_type])
params[Genie.Router.PARAMS_MIME_KEY] = MIME_TYPES[params[:response_type]]
headers["Content-Type"] = CONTENT_TYPES[params[:response_type]]
res.headers = [k for k in headers]
return req, res, params
end
negotiation_header = haskey(headers, "Accept") ? "Accept" :
( haskey(headers, "Content-Type") ? "Content-Type" : "" )
if isempty(negotiation_header)
req, res, params = set_negotiated_content(req, res, params)
return req, res, params
end
accept_parts = split(headers[negotiation_header], ";")
if isempty(accept_parts)
req, res, params = set_negotiated_content(req, res, params)
return req, res, params
end
accept_order_parts = split(accept_parts[1], ",")
if isempty(accept_order_parts)
req, res, params = set_negotiated_content(req, res, params)
return req, res, params
end
for mime in accept_order_parts
if occursin('/', mime)
content_type = split(mime, '/')[2] |> lowercase |> Symbol
if haskey(CONTENT_TYPES, content_type)
params[:response_type] = content_type
params[Genie.Router.PARAMS_MIME_KEY] = MIME_TYPES[params[:response_type]]
headers["Content-Type"] = CONTENT_TYPES[params[:response_type]]
res.headers = [k for k in headers]
return req, res, params
end
end
end
req, res, params = set_negotiated_content(req, res, params)
return req, res, params
end
push!(Genie.Router.content_negotiation_hooks, negotiate_content)
include("renderers/Html.jl")
include("renderers/Json.jl")
include("renderers/Js.jl")
end
const Renderers = Renderer | Genie | https://github.com/GenieFramework/Genie.jl.git |
|
[
"MIT"
] | 5.30.6 | 376aa3d800f4da32d232f2d9a1685e34e2911b4a | code | 960 | module Repl
import REPL, REPL.Terminals
"""
replprint(output::String, terminal;
newline::Int = 0, clearline::Int = 1, color::Symbol = :white, bold::Bool = false, sleep_time::Float64 = 0.2,
prefix::String = "", prefix_color::Symbol = :green, prefix_bold::Bool = true)
Prints app customise messages to the console.
"""
function replprint(output::String, terminal;
newline::Int = 0, clearline::Int = newline + 1,
color::Symbol = :white, bold::Bool = false, sleep_time::Float64 = 0.2,
prefix::String = "", prefix_color::Symbol = :green, prefix_bold::Bool = true)
for i in newline:(clearline + newline)
REPL.Terminals.clear_line(terminal)
end
isempty(prefix) || printstyled(prefix, color = prefix_color, bold = prefix_bold)
printstyled(output, color = color, bold = bold)
for i in 1:newline
println()
end
sleep(sleep_time)
end
end | Genie | https://github.com/GenieFramework/Genie.jl.git |
|
[
"MIT"
] | 5.30.6 | 376aa3d800f4da32d232f2d9a1685e34e2911b4a | code | 8215 | """
Collection of utilities for working with Requests data
"""
module Requests
import Genie, Genie.Router, Genie.Input
import HTTP, Reexport
export jsonpayload, rawpayload, filespayload, postpayload, getpayload
export request, getrequest, matchedroute, matchedchannel, wsclient
export infilespayload, filename, payload, peer, currenturl
"""
jsonpayload()
Processes an `application/json` `POST` request.
If it fails to successfully parse the `JSON` data it returns `nothing`. The original payload can still be accessed invoking `rawpayload()`
"""
function jsonpayload()
haskey(Genie.Router.params(), Genie.Router.PARAMS_JSON_PAYLOAD) ? Genie.Router.params(Genie.Router.PARAMS_JSON_PAYLOAD) : nothing
end
"""
jsonpayload(v)
Processes an `application/json` `POST` request attempting to return value corresponding to key v.
"""
function jsonpayload(v)
jsonpayload()[v]
end
"""
rawpayload() :: String
Returns the raw `POST` payload as a `String`.
"""
function rawpayload() :: String
haskey(Genie.Router.params(), Genie.Router.PARAMS_RAW_PAYLOAD) ? Genie.Router.params(Genie.Router.PARAMS_RAW_PAYLOAD) : ""
end
"""
filespayload() :: Dict{String,HttpFile}
Collection of form uploaded files.
"""
function filespayload() :: Dict{String,Input.HttpFile}
haskey(Router.params(), Genie.Router.PARAMS_FILES) ? Router.params(Genie.Router.PARAMS_FILES) : Dict{String,Input.HttpFile}()
end
"""
filespayload(filename::Union{String,Symbol}) :: HttpFile
Returns the `HttpFile` uploaded through the `key` input name.
"""
function filespayload(key::Union{String,Symbol}) :: Input.HttpFile
Router.params(Genie.Router.PARAMS_FILES)[string(key)]
end
"""
infilespayload(key::Union{String,Symbol}) :: Bool
Checks if the collection of uploaded files contains a file stored under the `key` name.
"""
function infilespayload(key::Union{String,Symbol}) :: Bool
haskey(filespayload(), string(key))
end
"""
Base.write(filename::String = file.name; file::Input.HttpFile) :: IntBase.write(file::HttpFile, filename::String = file.name)
Writes uploaded `HttpFile` `file` to local storage under the `name` filename.
Returns number of bytes written.
"""
function Base.write(file::Input.HttpFile; filename::String = file.name) :: Int
write(filename, IOBuffer(file.data))
end
"""
read(file::HttpFile)
Returns the content of `file` as string.
"""
function Base.read(file::Input.HttpFile, ::Type{String}) :: String
file.data |> String
end
"""
filename(file::HttpFile) :: String
Original filename of the uploaded `HttpFile` `file`.
"""
function filename(file::Input.HttpFile) :: String
file.name
end
"""
postpayload() :: Dict{Symbol,Any}
A dict representing the POST variables payload of the request (corresponding to a `form-data` request)
"""
function postpayload() :: Dict{Symbol,Any}
haskey(Router.params(), Genie.Router.PARAMS_POST_KEY) ? Router.params(Genie.Router.PARAMS_POST_KEY) : Dict{Symbol,Any}()
end
"""
postpayload(key::Symbol) :: Any
Returns the value of the POST variables `key`.
"""
function postpayload(key::Symbol)
postpayload()[key]
end
"""
postpayload(key::Symbol, default::Any)
Returns the value of the POST variables `key` or the `default` value if `key` is not defined.
"""
function postpayload(key::Symbol, default::Any)
haskey(postpayload(), key) ? postpayload(key) : default
end
"""
getpayload() :: Dict{Symbol,Any}
A dict representing the GET/query variables payload of the request (the part corresponding to `?foo=bar&baz=moo`)
"""
function getpayload() :: Dict{Symbol,Any}
haskey(Router.params(), Genie.Router.PARAMS_GET_KEY) ? Router.params(Genie.Router.PARAMS_GET_KEY) : Dict{Symbol,Any}()
end
"""
getpayload(key::Symbol) :: Any
The value of the GET/query variable `key`, as in `?key=value`
"""
function getpayload(key::Symbol) :: Any
getpayload()[key]
end
"""
getpayload(key::Symbol, default::Any) :: Any
The value of the GET/query variable `key`, as in `?key=value`. If `key` is not defined, `default` is returned.
"""
function getpayload(key::Symbol, default::Any) :: Any
haskey(getpayload(), key) ? getpayload(key) : default
end
"""
request() :: HTTP.Request
Returns the raw HTTP.Request object associated with the request. If no request is available (not within a
request/response cycle) returns `nothing`.
"""
function request() :: Union{HTTP.Request,Nothing}
haskey(Router.params(), Genie.Router.PARAMS_REQUEST_KEY) ? Router.params(Genie.Router.PARAMS_REQUEST_KEY) : nothing
end
const getrequest = request
"""
payload() :: Any
Utility function for accessing the `params` collection, which holds the request variables.
"""
function payload() :: Dict
Router.params()
end
"""
payload(key::Symbol) :: Any
Utility function for accessing the `key` value within the `params` collection of request variables.
"""
function payload(key::Symbol) :: Any
Router.params()[key]
end
"""
payload(key::Symbol, default_value::T) :: Any
Utility function for accessing the `key` value within the `params` collection of request variables.
If `key` is not defined, `default_value` is returned.
"""
function payload(key::Symbol, default_value::T)::T where {T}
haskey(Router.params(), key) ? Router.params()[key] : default_value
end
"""
matchedroute() :: Route
Returns the `Route` object which was matched for the current request or `noting` if no route is available.
"""
function matchedroute() :: Union{Genie.Router.Route,Nothing}
haskey(Router.params(), Genie.Router.PARAMS_ROUTE_KEY) ? Router.params(Genie.Router.PARAMS_ROUTE_KEY) : nothing
end
"""
matchedchannel() :: Channel
Returns the `Channel` object which was matched for the current request or `nothing` if no channel is available.
"""
function matchedchannel() :: Union{Genie.Router.Channel,Nothing}
haskey(Router.params(), Genie.Router.PARAMS_CHANNELS_KEY) ? Router.params(Genie.Router.PARAMS_CHANNELS_KEY) : nothing
end
"""
wsclient() :: HTTP.WebSockets.WebSocket
The web sockets client for the current request or nothing if not available.
"""
function wsclient() :: Union{HTTP.WebSockets.WebSocket,Nothing}
haskey(Router.params(), Genie.Router.PARAMS_WS_CLIENT) ? Router.params(Genie.Router.PARAMS_WS_CLIENT) : nothing
end
"""
wtclient() :: HTTP.WebSockets.WebSocket
The web sockets client for the current request.
"""
function wtclient() :: UInt
Router.params(:wtclient) |> hash
end
function getheaders(req::HTTP.Request) :: Dict{String,String}
Dict{String,String}(req.headers)
end
function getheaders() :: Dict{String,String}
getheaders(getrequest())
end
"""
findheader(key::String, default::Any = nothing) :: Union{String,Nothing}
Case insensitive search for the header `key` in the request headers. If `key` is not found, `default` is returned.
"""
function findheader(key::String, default = nothing) :: Union{String,Nothing}
for (k, v) in getheaders()
if lowercase(k) == lowercase(key)
return v
end
end
default
end
"""
peer()
Returns information about the requesting client's IP address as a NamedTuple{(:ip,), Tuple{String}}
If the client IP address can not be retrieved, the `ip` field will return an empty string `""`.
"""
function peer() :: NamedTuple{(:ip,:port), Tuple{String,String}}
unset_peer = (ip = "", port = "")
if haskey(task_local_storage(), :peer)
try
(ip = string(task_local_storage(:peer)[1]), port = string(task_local_storage(:peer)[2]))
catch ex
@error ex
unset_peer
end
else
unset_peer
end
end
"""
isajax(req::HTTP.Request = getrequest()) :: Bool
Attempts to determine if a request is Ajax by sniffing the headers.
"""
function isajax(req::HTTP.Request = getrequest()) :: Bool
for (k,v) in getheaders(req)
k = replace(k, r"_|-"=>"") |> lowercase
occursin("requestedwith", k) && occursin("xmlhttp", lowercase(v)) && return true
end
return false
end
"""
currenturl() :: String
Returns the URL of the current page/request, starting from the path and including the query string.
### Example
```julia
currenturl()
"/products?promotions=yes"
```
"""
function currenturl(req::HTTP.Request = getrequest()) :: String
req.target
end
end
| Genie | https://github.com/GenieFramework/Genie.jl.git |
|
[
"MIT"
] | 5.30.6 | 376aa3d800f4da32d232f2d9a1685e34e2911b4a | code | 2987 | """
Collection of utilities for working with Responses data
"""
module Responses
import Genie, Genie.Router
import HTTP
export getresponse, getheaders, setheaders, setheaders!, getstatus, setstatus, setstatus!, getbody, setbody, setbody!
export @streamhandler, stream
function getresponse() :: HTTP.Response
Router.params(Genie.Router.PARAMS_RESPONSE_KEY)
end
function getheaders(res::HTTP.Response) :: Dict{String,String}
Dict{String,String}(res.headers)
end
function getheaders() :: Dict{String,String}
getheaders(getresponse())
end
function setheaders!(res::HTTP.Response, headers::Dict) :: HTTP.Response
push!(res.headers, [headers...]...)
res
end
function setheaders(headers::Dict) :: HTTP.Response
setheaders!(getresponse(), headers)
end
function setheaders(header::Pair{String,String}) :: HTTP.Response
setheaders(Dict(header))
end
function setheaders(headers::Vector{Pair{String,String}}) :: HTTP.Response
setheaders(Dict(headers...))
end
function getstatus(res::HTTP.Response) :: Int
res.status
end
function getstatus() :: Int
getstatus(getresponse())
end
function setstatus!(res::HTTP.Response, status::Int) :: HTTP.Response
res.status = status
res
end
function setstatus(status::Int) :: HTTP.Response
setstatus!(getresponse(), status)
end
function getbody(res::HTTP.Response) :: String
String(res.body)
end
function getbody() :: String
getbody(getresponse())
end
function setbody!(res::HTTP.Response, body::String) :: HTTP.Response
res.body = collect(body)
res
end
function setbody(body::String) :: HTTP.Response
setbody!(getresponse(), body)
end
"""
@streamhandler(body)
Macro for defining a stream handler for a route.
# Example
```julia
route("/test") do
@streamhandler begin
while true
stream("Hello")
sleep(1)
end
end
end
````
"""
macro streamhandler(body)
quote
Genie.HTTPUtils.HTTP.setheader(Genie.Router.params(:STREAM), "Content-Type" => "text/event-stream")
Genie.HTTPUtils.HTTP.setheader(Genie.Router.params(:STREAM), "Cache-Control" => "no-store")
if Genie.HTTPUtils.HTTP.method(Genie.Router.params(:STREAM).message) == "OPTIONS"
return nothing
end
response = try
$body
catch ex
@error ex
end
if response !== nothing
stream!(response.body |> String)
end
nothing
end |> esc
end
function stream!(message::String; eol::String = "\n\n") :: Nothing
Genie.HTTPUtils.HTTP.write(Genie.Router.params(:STREAM), message * eol)
nothing
end
function stream(data::String = ""; event::String = "", id::String = "", retry::Int = 0) :: Nothing
msg = ""
if ! isempty(data)
for line in split(data, "\n")
msg = "data: $line\n" * msg
end
end
if ! isempty(event)
msg = "event: $event\n" * msg
end
if ! isempty(id)
msg = "id: $id\n" * msg
end
if retry > 0
msg = "retry: $retry\n" * msg
end
stream!(msg * "\n"; eol = "")
nothing
end
end # module Responses
| Genie | https://github.com/GenieFramework/Genie.jl.git |
|
[
"MIT"
] | 5.30.6 | 376aa3d800f4da32d232f2d9a1685e34e2911b4a | code | 36229 | """
Parses requests and extracts parameters, setting up the call variables and invoking
the appropriate route handler function.
"""
module Router
import Revise
import Reexport, Logging
import HTTP, HttpCommon, Sockets, Millboard, Dates, OrderedCollections, JSON3, MIMEs
import Genie
export route, routes, channel, channels, download, serve_static_file, serve_file
export GET, POST, PUT, PATCH, DELETE, OPTIONS, HEAD
export tolink, linkto, responsetype, toroute
export params, query, post, headers, request, params!
export ispayload
export NOT_FOUND, INTERNAL_ERROR, BAD_REQUEST, CREATED, NO_CONTENT, OK
Reexport.@reexport using HttpCommon
const GET = "GET"
const POST = "POST"
const PUT = "PUT"
const PATCH = "PATCH"
const DELETE = "DELETE"
const OPTIONS = "OPTIONS"
const HEAD = "HEAD"
const PARAMS_REQUEST_KEY = :REQUEST
const PARAMS_RESPONSE_KEY = :RESPONSE
const PARAMS_POST_KEY = :POST
const PARAMS_GET_KEY = :GET
const PARAMS_WS_CLIENT = :WS_CLIENT
const PARAMS_JSON_PAYLOAD = :JSON_PAYLOAD
const PARAMS_RAW_PAYLOAD = :RAW_PAYLOAD
const PARAMS_FILES = :FILES
const PARAMS_ROUTE_KEY = :ROUTE
const PARAMS_CHANNELS_KEY = :CHANNEL
const PARAMS_MIME_KEY = :MIME
const OK = 200
const CREATED = 201
const ACCEPTED = 202
const NO_CONTENT = 204
const BAD_REQUEST = 400
const NOT_FOUND = 404
const INTERNAL_ERROR = 500
const ROUTE_CACHE = Dict{String,Tuple{String,Vector{String},Vector{Any}}}()
request_mappings() = Dict{Symbol,Vector{String}}(
:text => ["text/plain"],
:html => ["text/html"],
:json => ["application/json", "application/vnd.api+json"],
:javascript => ["application/javascript"],
:form => ["application/x-www-form-urlencoded"],
:multipart => ["multipart/form-data"],
:file => ["application/octet-stream"],
:xml => ["text/xml"]
)
const pre_match_hooks = Function[]
const pre_response_hooks = Function[]
const content_negotiation_hooks = Function[]
"""
mutable struct Route
Representation of a route object
"""
mutable struct Route
method::String
path::String
action::Function
name::Union{Symbol,Nothing}
context::Module
end
Route(; method::String = GET, path::String = "", action::Function = (() -> error("Route not set")),
name::Union{Symbol,Nothing} = nothing, context::Module = @__MODULE__) = Route(method, path, action, name, context)
"""
mutable struct Channel
Representation of a WebSocket Channel object
"""
mutable struct Channel
path::String
action::Function
name::Union{Symbol,Nothing}
Channel(; path = "", action = (() -> error("Channel not set")), name = nothing) = new(path, action, name)
end
function Base.show(io::IO, r::Route)
print(io, "[$(r.method)] $(r.path) => $(r.action) | :$(r.name)")
end
function Base.show(io::IO, c::Channel)
print(io, "[WS] $(c.path) => $(c.action) | :$(c.name)")
end
const _routes = OrderedCollections.LittleDict{Symbol,Route}()
const _channels = OrderedCollections.LittleDict{Symbol,Channel}()
"""
mutable struct Params{T}
Collection of key value pairs representing the parameters of the current request - response cycle.
"""
mutable struct Params{T}
collection::Dict{Symbol,T}
end
Params() = Params(setup_base_params())
Base.Dict(params::Params) = params.collection
Base.getindex(params::Params, keys...) = getindex(Dict(params), keys...)
Base.getindex(params::Pair, keys...) = getindex(Dict(params), keys...)
"""
ispayload(req::HTTP.Request)
True if the request can carry a payload - that is, it's a `POST`, `PUT`, or `PATCH` request
"""
ispayload(req::HTTP.Request) = req.method in [POST, PUT, PATCH]
"""
ispayload()
True if the request can carry a payload - that is, it's a `POST`, `PUT`, or `PATCH` request
"""
ispayload() = params()[:REQUEST].method in [POST, PUT, PATCH]
"""
route_request(req::Request, res::Response) :: Response
First step in handling a request: sets up params collection, handles query vars, negotiates content.
"""
function route_request(req::HTTP.Request, res::HTTP.Response; stream::Union{HTTP.Stream,Nothing} = nothing) :: HTTP.Response
params = Params()
params.collection[:STREAM] = stream
for f in unique(content_negotiation_hooks)
req, res, params.collection = f(req, res, params.collection)
end
unescaped_target = HTTP.URIs.unescapeuri(req.target)
if is_static_file(unescaped_target) && req.method == GET
if isroute(baptizer(unescaped_target, [lowercase(req.method)]))
@warn "Route matches static file: $(req.target) -- executing route"
elseif Genie.config.server_handle_static_files
return serve_static_file(unescaped_target)
else
return error(req.target, response_mime(), Val(404))
end
end
Genie.Configuration.isdev() && Revise.revise()
for f in unique(pre_match_hooks)
req, res, params.collection = f(req, res, params.collection)
end
matched_route = match_routes(req, res, params)
res = matched_route === nothing ?
error(req.target, response_mime(params.collection), Val(404)) :
run_route(matched_route)
if res.status == 404 && req.method == OPTIONS
res = preflight_response()
log_response(req, res)
return res
end
for f in unique(pre_response_hooks)
req, res, params.collection = f(req, res, params.collection)
end
log_response(req, res)
req.method == HEAD && (res.body = UInt8[])
res
end
function log_response(req::HTTP.Request, res::HTTP.Response) :: Nothing
if Genie.config.log_requests
reqstatus = "$(req.method) $(req.target) $(res.status)\n"
if res.status < 400
@info reqstatus
else
@error reqstatus
end
end
nothing
end
"""
route_ws_request(req::Request, msg::String, ws_client::HTTP.WebSockets.WebSocket) :: String
First step in handling a web socket request: sets up params collection, handles query vars.
"""
function route_ws_request(req, msg::Union{String,Vector{UInt8}}, ws_client) :: String
params = Params()
params.collection[PARAMS_WS_CLIENT] = ws_client
extract_get_params(HTTP.URIs.URI(req.target), params)
Genie.Configuration.isdev() && Revise.revise()
match_channels(req, msg, ws_client, params)
end
function Base.push!(collection, name::Symbol, item::Union{Route,Channel})
collection[name] = item
end
"""
Named Genie routes constructors.
"""
function route(action::Function, path::String; method = GET, named::Union{Symbol,Nothing} = nothing, context::Module = @__MODULE__) :: Route
route(path, action, method = method, named = named, context = context)
end
function route(path::String, action::Function; method = GET, named::Union{Symbol,Nothing} = nothing, context::Module = @__MODULE__) :: Route
Route(method = method, path = path, action = action, name = named, context = context) |> route
end
function route(r::Route) :: Route
r.name === nothing && (r.name = routename(r))
Router.push!(_routes, r.name, r)
end
function routes(args...; method::Vector{<:AbstractString}, kwargs...)
for m in method
route(args...; method = m, kwargs...)
end
end
"""
Named Genie channels constructors.
"""
function channel(action::Function, path::String; named::Union{Symbol,Nothing} = nothing) :: Channel
channel(path, action, named = named)
end
function channel(path::String, action::Function; named::Union{Symbol,Nothing} = nothing) :: Channel
c = Channel(path = path, action = action, name = named)
if named === nothing
c.name = channelname(c)
end
Router.push!(_channels, c.name, c)
end
"""
routename(params) :: Symbol
Computes the name of a route.
"""
function routename(params::Route) :: Symbol
baptizer(params, String[lowercase(params.method)])
end
"""
channelname(params) :: Symbol
Computes the name of a channel.
"""
function channelname(params::Union{Channel,String}) :: Symbol
baptizer(params, String[])
end
"""
baptizer(params::Union{Route,Channel}, parts::Vector{String}) :: Symbol
Generates default names for routes and channels.
"""
function baptizer(route_path::String, parts::Vector{String} = String[]) :: Symbol
for uri_part in split(route_path, '/', keepempty = false)
startswith(uri_part, ":") ?
push!(parts, "by", lowercase(uri_part)[2:end]) :
push!(parts, lowercase(uri_part))
end
join(parts, "_") |> Symbol
end
function baptizer(params::Union{Route,Channel}, parts::Vector{String} = String[]) :: Symbol
baptizer(params.path, parts)
end
"""
The list of the defined named routes.
"""
function named_routes() :: OrderedCollections.LittleDict{Symbol,Route}
_routes
end
const namedroutes = named_routes
function ischannel(channel_name::Symbol) :: Bool
haskey(named_channels(), channel_name)
end
"""
named_channels() :: Dict{Symbol,Any}
The list of the defined named channels.
"""
function named_channels() :: OrderedCollections.LittleDict{Symbol,Channel}
_channels
end
const namedchannels = named_channels
function isroute(route_name::Symbol) :: Bool
haskey(named_routes(), route_name)
end
"""
Gets the `Route` corresponding to `routename`
"""
function get_route(route_name::Symbol; default::Union{Route,Nothing} = Route()) :: Route
isroute(route_name) ?
named_routes()[route_name] :
(if default === nothing
Base.error("Route named `$route_name` is not defined")
else
Genie.Configuration.isdev() && @debug "Route named `$route_name` is not defined"
default
end)
end
const getroute = get_route
"""
routes() :: Vector{Route}
Returns a vector of defined routes.
"""
function routes(; reversed::Bool = true) :: Vector{Route}
collect(values(_routes)) |> (reversed ? reverse : identity)
end
"""
channels() :: Vector{Channel}
Returns a vector of defined channels.
"""
function channels() :: Vector{Channel}
collect(values(_channels)) |> reverse
end
"""
delete!(route_name::Symbol)
Removes the route with the corresponding name from the routes collection and returns the collection of remaining routes.
"""
function delete!(key::Symbol) :: Vector{Route}
OrderedCollections.delete!(_routes, key)
return routes()
end
"""
delete_channel!(channel_name::Symbol)
Removes the channel with the corresponding name from the channels collection and returns the collection of remaining channels.
"""
function delete_channel!(key::Symbol) :: Vector{Channel}
OrderedCollections.delete!(_channels, key)
return channels()
end
"""
Generates the HTTP link corresponding to `route_name` using the parameters in `d`.
"""
function to_link(route_name::Symbol, d::Dict{Symbol,T}; basepath::String = basepath, preserve_query::Bool = true, extra_query::Dict = Dict())::String where {T}
route = get_route(route_name)
newpath = isempty(basepath) ? route.path : basepath * route.path
result = String[]
for part in split(newpath, '/')
if occursin("#", part)
part = split(part, "#")[1] |> string
end
if startswith(part, ":")
var_name = split(part, "::")[1][2:end] |> Symbol
( isempty(d) || ! haskey(d, var_name) ) && Base.error("Route $route_name expects param $var_name")
push!(result, pathify(d[var_name]))
Base.delete!(d, var_name)
continue
end
push!(result, part)
end
query_vars = Dict{String,String}()
if preserve_query && haskey(task_local_storage(), :__params) && haskey(task_local_storage(:__params), :REQUEST)
query = HTTP.URIs.URI(task_local_storage(:__params)[:REQUEST].target).query
if ! isempty(query)
for pair in split(query, '&')
try
parts = split(pair, '=')
query_vars[parts[1]] = parts[2]
catch ex
# @error ex
end
end
end
end
for (k,v) in extra_query
query_vars[string(k)] = string(v)
end
qv = String[]
for (k,v) in query_vars
push!(qv, "$k=$v")
end
join(result, '/') * ( ! isempty(qv) ? '?' : "" ) * join(qv, '&')
end
"""
Generates the HTTP link corresponding to `route_name` using the parameters in `route_params`.
"""
function to_link(route_name::Symbol; basepath::String = Genie.config.base_path, preserve_query::Bool = true, extra_query::Dict = Dict(), route_params...) :: String
to_link(route_name, route_params_to_dict(route_params), basepath = basepath, preserve_query = preserve_query, extra_query = extra_query)
end
const link_to = to_link
const linkto = link_to
const tolink = to_link
const toroute = to_link
"""
route_params_to_dict(route_params)
Converts the route params to a `Dict`.
"""
function route_params_to_dict(route_params) :: Dict{Symbol,Any}
Dict{Symbol,Any}(route_params)
end
"""
action_controller_params(action::Function, params::Params) :: Nothing
Sets up the :action_controller, :action, and :controller key - value pairs of the `params` collection.
"""
function action_controller_params(action::Function, params::Params) :: Nothing
params.collection[:action_controller] = action |> string |> Symbol
params.collection[:action] = action
params.collection[:controller] = (action |> typeof).name.module
nothing
end
"""
match_routes(req::Request, res::Response, params::Params) :: Union{Route,Nothing}
Matches the invoked URL to the corresponding route, sets up the execution environment and invokes the controller method.
"""
function match_routes(req::HTTP.Request, res::HTTP.Response, params::Params) :: Union{Route,Nothing}
endswith(req.target, "/") && req.target != "/" && (req.target = req.target[1:end-1])
uri = HTTP.URIs.URI(HTTP.URIs.unescapeuri(req.target))
for r in routes()
# method must match but we can also handle HEAD requests with GET routes
(r.method == req.method) || (r.method == GET && req.method == HEAD) || continue
parsed_route, param_names, param_types = Genie.Configuration.isprod() ?
get!(ROUTE_CACHE, r.path, parse_route(r.path, context = r.context)) :
parse_route(r.path, context = r.context)
regex_route = try
Regex("^" * parsed_route * "\$")
catch
@error "Invalid route $parsed_route"
continue
end
ROUTE_CATCH_ALL = "/*"
occursin(regex_route, string(uri.path)) || parsed_route == ROUTE_CATCH_ALL || continue
params.collection = setup_base_params(req, res, params.collection)
task_local_storage(:__params, params.collection)
occursin("?", req.target) && extract_get_params(HTTP.URIs.URI(req.target), params)
extract_uri_params(uri.path |> string, regex_route, param_names, param_types, params) || continue
ispayload(req) && extract_post_params(req, params)
ispayload(req) && extract_request_params(req, params)
action_controller_params(r.action, params)
params.collection[PARAMS_ROUTE_KEY] = r
get!(params.collection, PARAMS_MIME_KEY, MIME(request_type(req)))
for f in unique(content_negotiation_hooks)
req, res, params.collection = f(req, res, params.collection)
end
return r
end
nothing
end
function run_route(r::Route) :: HTTP.Response
try
try
(r.action)() |> to_response
catch ex1
if isa(ex1, MethodError) && string(ex1.f) == string(r.action)
Base.invokelatest(r.action) |> to_response
else
rethrow(ex1)
end
end
catch ex
return handle_exception(ex)
end
end
function handle_exception(ex::Genie.Exceptions.ExceptionalResponse)
ex.response
end
function handle_exception(ex::Genie.Exceptions.RuntimeException)
rethrow(ex)
end
function handle_exception(ex::Genie.Exceptions.InternalServerException)
error(ex.message, response_mime(), Val(500))
end
function handle_exception(ex::Genie.Exceptions.NotFoundException)
error(ex.resource, response_mime(), Val(404))
end
function handle_exception(ex::Exception)
rethrow(ex)
end
function handle_exception(ex::Any)
Base.error(ex |> string)
end
"""
match_channels(req::Request, msg::String, ws_client::HTTP.WebSockets.WebSocket, params::Params) :: String
Matches the invoked URL to the corresponding channel, sets up the execution environment and invokes the channel controller method.
"""
function match_channels(req, msg::String, ws_client, params::Params) :: String
payload::Dict{String,Any} = try
JSON3.read(msg, Dict{String,Any})
catch ex
Dict{String,Any}()
end
uri = haskey(payload, "channel") ? '/' * payload["channel"] : '/'
uri = haskey(payload, "message") ? uri * '/' * payload["message"] : uri
uri = string(uri)
for c in channels()
parsed_channel, param_names, param_types = parse_channel(c.path)
haskey(payload, "payload") && (params.collection[:payload] = payload["payload"])
regex_channel = Regex("^" * parsed_channel * "\$")
(! occursin(regex_channel, uri)) && continue
params.collection = setup_base_params(req, nothing, params.collection)
task_local_storage(:__params, params.collection)
extract_uri_params(uri, regex_channel, param_names, param_types, params) || continue
action_controller_params(c.action, params)
params.collection[PARAMS_CHANNELS_KEY] = c
controller = (c.action |> typeof).name.module
return try
result = try
(c.action)() |> string
catch ex1
if isa(ex1, MethodError) && string(ex1.f) == string(c.action)
Base.invokelatest(c.action) |> string
else
rethrow(ex1)
end
end
result
catch ex
isa(ex, Exception) ? sprint(showerror, ex) : rethrow(ex)
end
end
string("ERROR : 404 - Not found")
end
"""
parse_route(route::String, context::Module = @__MODULE__) :: Tuple{String,Vector{String},Vector{Any}}
Parses a route and extracts its named params and types. `context` is used to access optional route parts types.
"""
function parse_route(route::String; context::Module = @__MODULE__) :: Tuple{String,Vector{String},Vector{Any}}
parts = String[]
param_names = String[]
param_types = Any[]
if occursin('#', route) || occursin(':', route)
validation_match = "[\\w\\-\\.\\+\\,\\s\\%\\:\\(\\)\\[\\]]+"
for rp in split(route, '/', keepempty = false)
if occursin("#", rp)
x = split(rp, "#")
rp = x[1] |> string
validation_match = x[2]
end
if startswith(rp, ":")
param_type = if occursin("::", rp)
x = split(rp, "::")
rp = x[1] |> string
getfield(context, Symbol(x[2]))
else
Any
end
param_name = rp[2:end] |> string
rp = """(?P<$param_name>$validation_match)"""
push!(param_names, param_name)
push!(param_types, param_type)
end
push!(parts, rp)
end
else
parts = split(route, '/', keepempty = false)
end
'/' * join(parts, '/'), param_names, param_types
end
"""
parse_channel(channel::String) :: Tuple{String,Vector{String},Vector{Any}}
Parses a channel and extracts its named parms and types.
"""
function parse_channel(channel::String) :: Tuple{String,Vector{String},Vector{Any}}
parts = String[]
param_names = String[]
param_types = Any[]
if occursin(':', channel)
for rp in split(channel, '/', keepempty = false)
if startswith(rp, ":")
param_type = if occursin("::", rp)
x = split(rp, "::")
rp = x[1] |> string
getfield(@__MODULE__, Symbol(x[2]))
else
Any
end
param_name = rp[2:end] |> string
rp = """(?P<$param_name>[\\w\\-]+)"""
push!(param_names, param_name)
push!(param_types, param_type)
end
push!(parts, rp)
end
else
parts = split(channel, '/', keepempty = false)
end
'/' * join(parts, '/'), param_names, param_types
end
parse_param(param_type::Type{<:Number}, param::AbstractString) = parse(param_type, param)
parse_param(param_type::Type{T}, param::S) where {T, S} = convert(param_type, param)
"""
extract_uri_params(uri::String, regex_route::Regex, param_names::Vector{String}, param_types::Vector{Any}, params::Params) :: Bool
Extracts params from request URI and sets up the `params` `Dict`.
"""
function extract_uri_params(uri::String, regex_route::Regex, param_names::Vector{String}, param_types::Vector{Any}, params::Params) :: Bool
matches = match(regex_route, uri)
i = 1
for param_name in param_names
try
params.collection[Symbol(param_name)] = parse_param(param_types[i], matches[param_name])
catch ex
@error ex
return false
end
i += 1
end
true # this must be bool cause it's used in bool context for chaining
end
"""
extract_get_params(uri::URI, params::Params) :: Bool
Extracts query vars and adds them to the execution `params` `Dict`.
"""
function extract_get_params(uri::HTTP.URIs.URI, params::Params) :: Bool
if ! isempty(uri.query)
if occursin("%5B%5D", uri.query) || occursin("[]", uri.query) # array values []
for query_part in split(uri.query, "&")
qp = split(query_part, "=")
(size(qp)[1] == 1) && (push!(qp, ""))
k = Symbol(HTTP.URIs.unescapeuri(qp[1]))
v = HTTP.URIs.unescapeuri(qp[2])
# collect values like x[] in an array
if endswith(string(k), "[]")
(haskey(params.collection, k) && isa(params.collection[k], Vector)) || (params.collection[k] = String[])
push!(params.collection[k], v)
params.collection[PARAMS_GET_KEY][k] = params.collection[k]
else
params.collection[k] = params.collection[PARAMS_GET_KEY][k] = v
end
end
else # no array values
for (k,v) in HTTP.URIs.queryparams(uri)
k = Symbol(k)
params.collection[k] = params.collection[PARAMS_GET_KEY][k] = v
end
end
end
true # this must be bool cause it's used in bool context for chaining
end
"""
extract_post_params(req::Request, params::Params) :: Nothing
Parses POST variables and adds the to the `params` `Dict`.
"""
function extract_post_params(req::HTTP.Request, params::Params) :: Nothing
ispayload(req) || return nothing
try
input = Genie.Input.all(req)
for (k, v) in input.post
nested_keys(k, v, params)
k = Symbol(k)
params.collection[k] = params.collection[PARAMS_POST_KEY][k] = v
end
params.collection[PARAMS_FILES] = input.files
catch ex
@error ex
end
nothing
end
"""
extract_request_params(req::HTTP.Request, params::Params) :: Nothing
Sets up the `params` key-value pairs corresponding to a JSON payload.
"""
function extract_request_params(req::HTTP.Request, params::Params) :: Nothing
ispayload(req) || return nothing
req_body = String(req.body)
params.collection[PARAMS_RAW_PAYLOAD] = req_body
if request_type_is(req, :json) && content_length(req) > 0
try
params.collection[PARAMS_JSON_PAYLOAD] = JSON3.read(req_body) |> stringdict
params.collection[PARAMS_POST_KEY][PARAMS_JSON_PAYLOAD] = params.collection[PARAMS_JSON_PAYLOAD]
catch ex
@error ex
@warn "Setting params(:JSON_PAYLOAD) to Nothing"
params.collection[PARAMS_JSON_PAYLOAD] = nothing
end
else
params.collection[PARAMS_JSON_PAYLOAD] = nothing
end
nothing
end
function stringdict(o::JSON3.Object) :: Dict{String,Any}
r = Dict{String,Any}()
for (k, v) in o
r[string(k)] = v
end
r
end
"""
content_type(req::HTTP.Request) :: String
Gets the content-type of the request.
"""
function content_type(req::HTTP.Request) :: String
get(Genie.HTTPUtils.Dict(req), "content-type", get(Genie.HTTPUtils.Dict(req), "accept", ""))
end
"""
content_length(req::HTTP.Request) :: Int
Gets the content-length of the request.
"""
function content_length(req::HTTP.Request) :: Int
parse(Int, get(Genie.HTTPUtils.Dict(req), "content-length", "0"))
end
function content_length() :: Int
content_length(params(PARAMS_REQUEST_KEY))
end
"""
request_type_is(req::HTTP.Request, request_type::Symbol) :: Bool
Checks if the request content-type is of a certain type.
"""
function request_type_is(req::HTTP.Request, reqtype::Symbol) :: Bool
! in(reqtype, keys(request_mappings()) |> collect) &&
error("Unknown request type $reqtype - expected one of $(keys(request_mappings()) |> collect).")
request_type(req) == reqtype
end
function request_type_is(reqtype::Symbol) :: Bool
request_type_is(params(PARAMS_REQUEST_KEY), reqtype)
end
"""
request_type(req::HTTP.Request) :: Symbol
Gets the request's content type.
"""
function request_type(req::HTTP.Request) :: Symbol
accepted_encodings = strip.(collect(Iterators.flatten(split.(strip.(split(content_type(req), ';')), ','))))
for accepted_encoding in accepted_encodings
for (k,v) in request_mappings()
if in(accepted_encoding, v)
return k
end
end
end
isempty(accepted_encodings[1]) ? Symbol(request_mappings()[:html]) : Symbol(accepted_encodings[1])
end
"""
nested_keys(k::String, v, params::Params) :: Nothing
Utility function to process nested keys and set them up in `params`.
"""
function nested_keys(k::String, v, params::Params) :: Nothing
if occursin(".", k)
parts = split(k, ".", limit = 2)
nested_val_key = Symbol(parts[1])
if haskey(params.collection, nested_val_key) && isa(params.collection[nested_val_key], Dict)
! haskey(params.collection[nested_val_key], Symbol(parts[2])) && (params.collection[nested_val_key][Symbol(parts[2])] = v)
elseif ! haskey(params.collection, nested_val_key)
params.collection[nested_val_key] = Dict()
params.collection[nested_val_key][Symbol(parts[2])] = v
end
end
nothing
end
"""
setup_base_params(req::Request, res::Response, params::Dict{Symbol,Any}) :: Dict{Symbol,Any}
Populates `params` with default environment vars.
"""
function setup_base_params(req::HTTP.Request = HTTP.Request(), res::Union{HTTP.Response,Nothing} = req.response,
params::Dict{Symbol,Any} = Dict{Symbol,Any}()) :: Dict{Symbol,Any}
params[PARAMS_REQUEST_KEY] = req
params[PARAMS_RESPONSE_KEY] = if res === nothing
req.response = HTTP.Response()
req.response
else
res
end
params[PARAMS_POST_KEY] = Dict{Symbol,Any}()
params[PARAMS_GET_KEY] = Dict{Symbol,Any}()
params[PARAMS_FILES] = Dict{String,Genie.Input.HttpFile}()
params
end
"""
to_response(action_result) :: Response
Converts the result of invoking the controller action to a `Response`.
"""
to_response(action_result::HTTP.Response)::HTTP.Response = action_result
to_response(action_result::Tuple)::HTTP.Response = HTTP.Response(action_result...)
to_response(action_result::Vector)::HTTP.Response = HTTP.Response(join(action_result))
to_response(action_result::Nothing)::HTTP.Response = HTTP.Response("")
to_response(action_result::String)::HTTP.Response = HTTP.Response(action_result)
to_response(action_result::Genie.Exceptions.ExceptionalResponse)::HTTP.Response = action_result.response
to_response(action_result::Exception)::HTTP.Response = throw(action_result)
to_response(action_result::Any)::HTTP.Response = HTTP.Response(string(action_result))
"""
function params()
The collection containing the request variables collection.
"""
function params()
haskey(task_local_storage(), :__params) ? task_local_storage(:__params) : task_local_storage(:__params, setup_base_params())
end
function params(key)
params()[key]
end
function params(key, default)
get(params(), key, default)
end
function params!(key, value)
params()
task_local_storage(:__params)[key] = value
end
"""
function query
The collection containing the query request variables collection (GET params).
"""
function query()
haskey(params(), PARAMS_GET_KEY) ? params(PARAMS_GET_KEY) : Dict()
end
function query(key)
query()[key]
end
function query(key, default)
get(query(), key, default)
end
"""
function post
The collection containing the POST request variables collection.
"""
function post()
haskey(params(), PARAMS_POST_KEY) ? params(PARAMS_POST_KEY) : Dict()
end
function post(key)
post()[key]
end
function post(key, default)
get(post(), key, default)
end
"""
function request()
The request object.
"""
function request()
params(PARAMS_REQUEST_KEY)
end
"""
function headers()
The current request's headers (as a Dict)
"""
function headers()
Dict{String,String}(request().headers)
end
"""
response_type{T}(params::Dict{Symbol,T}) :: Symbol
response_type(params::Params) :: Symbol
Returns the content-type of the current request-response cycle.
"""
function response_type(params::Dict{Symbol,T})::Symbol where {T}
get(params, :response_type, request_type(params[PARAMS_REQUEST_KEY]))
end
function response_type(params::Params) :: Symbol
response_type(params.collection)
end
function response_type() :: Symbol
response_type(params())
end
"""
response_type{T}(check::Symbol, params::Dict{Symbol,T}) :: Bool
Checks if the content-type of the current request-response cycle matches `check`.
"""
function response_type(check::Symbol, params::Dict{Symbol,T})::Bool where {T}
check == response_type(params)
end
const responsetype = response_type
"""
append_to_routes_file(content::String) :: Nothing
Appends `content` to the app's route file.
"""
function append_to_routes_file(content::String) :: Nothing
open(Genie.ROUTES_FILE_NAME, "a") do io
write(io, "\n" * content)
end
nothing
end
"""
is_static_file(resource::String) :: Bool
Checks if the requested resource is a static file.
"""
function is_static_file(resource::String) :: Bool
isfile(file_path(HTTP.URIs.URI(resource).path |> string))
end
"""
escape_resource_path(resource::String)
Cleans up paths to resources.
"""
function escape_resource_path(resource::String)
startswith(resource, '/') || return resource
resource = resource[2:end]
'/' * join(map(x -> HTTP.URIs.escapeuri(x), split(resource, '?')), '?')
end
"""
is_accessible_resource(resource::String) :: Bool
Checks if the requested resource is within the public/ folder.
"""
function is_accessible_resource(resource::String; root = Genie.config.server_document_root) :: Bool
startswith(abspath(resource), abspath(root)) # the file path includes the root path
end
function bundles_path() :: String
joinpath(@__DIR__, "..", "files", "static") |> normpath |> abspath
end
"""
serve_static_file(resource::String) :: Response
Reads the static file and returns the content as a `Response`.
"""
function serve_static_file(resource::String; root = Genie.config.server_document_root, download=false) :: HTTP.Response
startswith(resource, '/') || (resource = "/$(resource)")
resource_path = try
HTTP.URIs.URI(resource).path |> string
catch ex
resource
end
f = file_path(resource_path; root = root)
isempty(f) && (f = pwd() |> relpath)
fileheader = file_headers(f)
download && push!(fileheader, ("Content-Disposition" => """attachment; filename=$(basename(f))"""))
if (isfile(f) || isdir(f)) && ! is_accessible_resource(f; root)
@error "401 Unauthorised Access $f"
return error(resource, response_mime(), Val(401))
end
if isfile(f)
return HTTP.Response(200, fileheader, body = read(f, String))
elseif isdir(f)
for fn in ["index.html", "index.htm", "index.txt"]
isfile(joinpath(f, fn)) && return serve_static_file(joinpath(f, fn), root = root)
end
else
bundled_path = joinpath(bundles_path(), resource[2:end])
if ! is_accessible_resource(bundled_path; root = bundles_path())
@error "401 Unauthorised Access $f"
return error(resource, response_mime(), Val(401))
end
if isfile(bundled_path)
return HTTP.Response(200, file_headers(bundled_path), body = read(bundled_path, String))
end
end
@error "404 Not Found $f [$(abspath(f))]"
error(resource, response_mime(), Val(404))
end
function serve_file(f::String) :: HTTP.Response
fileheader = file_headers(f)
if isfile(f)
return HTTP.Response(200, fileheader, body = read(f, String))
else
@error "404 Not Found $f [$(abspath(f))]"
error(f, response_mime(), Val(404))
end
end
"""
download(filepath::String; root) :: HTTP.Response
Download an existing file from the server.
"""
function download(filepath::String; root)::HTTP.Response
return serve_static_file(filepath; root=root, download=true)
end
"""
download(data::Vector{UInt8}, filename::String, mimetype) :: HTTP.Response
Download file from generated stream of bytes
"""
function download(data::Vector{UInt8}, filename::String, mimetype::String)::HTTP.Response
if mimetype in values(MIMEs._ext2mime)
return HTTP.Response(200,
("Content-Type" => mimetype, "Content-Disposition" => """attachment; filename=$(filename)"""),
body=data)
end
@error "415 Unsupported Media Type $mimetype"
end
"""
preflight_response() :: HTTP.Response
Sets up the preflight CORS response header.
"""
function preflight_response() :: HTTP.Response
HTTP.Response(200, Genie.config.cors_headers, body = "Success")
end
"""
response_mime()
Returns the MIME type of the response.
"""
function response_mime(params::Dict{Symbol,Any} = params())
if isempty(get!(params, PARAMS_MIME_KEY, request_type(params[PARAMS_REQUEST_KEY])) |> string)
params[PARAMS_MIME_KEY] = request_type(params[PARAMS_REQUEST_KEY])
end
params[PARAMS_MIME_KEY]
end
"""
error
Not implemented function for error response.
"""
function error end
function trymime(mime::Any)
try
mime()
catch _
mime
end
end
function error(error_message::String, mime::Any, ::Val{500}; error_info::String = "") :: HTTP.Response
HTTP.Response(500, ["Content-Type" => string(trymime(mime))], body = "500 Internal Error - $error_message. $error_info")
end
function error(error_message::String, mime::Any, ::Val{401}; error_info::String = "") :: HTTP.Response
HTTP.Response(401, ["Content-Type" => string(trymime(mime))], body = "401 Unauthorised - $error_message. $error_info")
end
function error(error_message::String, mime::Any, ::Val{404}; error_info::String = "") :: HTTP.Response
HTTP.Response(404, ["Content-Type" => string(trymime(mime))], body = "404 Not Found - $error_message. $error_info")
end
function error(error_code::Int, error_message::String, mime::Any; error_info::String = "") :: HTTP.Response
HTTP.Response(error_code, ["Content-Type" => string(trymime(mime))], body = "$error_code Error - $error_message. $error_info")
end
"""
file_path(resource::String; within_doc_root = true, root = Genie.config.server_document_root) :: String
Returns the path to a resource file. If `within_doc_root` it will automatically prepend the document root to `resource`.
"""
function file_path(resource::String; within_doc_root = true, root = Genie.config.server_document_root) :: String
within_doc_root = (within_doc_root && root == Genie.config.server_document_root)
joinpath(within_doc_root ? Genie.config.server_document_root : root, resource[(startswith(resource, '/') ? 2 : 1):end])
end
const filepath = file_path
"""
pathify(x) :: String
Returns a proper URI path from a string `x`.
"""
pathify(x) :: String = replace(string(x), " "=>"-") |> lowercase |> HTTP.URIs.escapeuri
"""
file_extension(f) :: String
Returns the file extesion of `f`.
"""
file_extension(f) :: String = ormatch(match(r"(?<=\.)[^\.\\/]*$", f), "")
"""
file_headers(f) :: Dict{String,String}
Returns the file headers of `f`.
"""
function file_headers(f) :: Vector{Pair{String,String}}
["Content-Type" => get(MIMEs._ext2mime, file_extension(f), "application/octet-stream")]
end
ormatch(r::RegexMatch, x) = r.match
ormatch(r::Nothing, x) = x
end
| Genie | https://github.com/GenieFramework/Genie.jl.git |
|
[
"MIT"
] | 5.30.6 | 376aa3d800f4da32d232f2d9a1685e34e2911b4a | code | 3059 | module Secrets
import Dates
import SHA
import Logging
import Revise
import Genie
const SECRET_TOKEN = Ref{String}("") # global state
const SECRETS_FILE_NAME = "secrets.jl"
"""
secret_token(generate_if_missing=true) :: String
Return the secret token used in the app for encryption and salting.
Usually, this token is defined through `Genie.Secrets.secret_token!` in the `config/secrets.jl` file.
Here, a temporary one is generated for the current session if no other token is defined and
`generate_if_missing` is true.
"""
function secret_token(generate_if_missing::Bool = true; context::Union{Module,Nothing} = nothing)
if isempty(SECRET_TOKEN[])
isfile(joinpath(Genie.config.path_config, SECRETS_FILE_NAME)) &&
Revise.includet(Genie.Loader.default_context(context), joinpath(Genie.config.path_config, SECRETS_FILE_NAME))
if isempty(SECRET_TOKEN[]) && generate_if_missing && Genie.Configuration.isprod()
@warn "
No secret token is defined through `Genie.Secrets.secret_token!(\"token\")`. Such a token
is needed to hash and to encrypt/decrypt sensitive data in Genie, including cookie
and session data.
If your app relies on cookies or sessions make sure you generate a valid token,
otherwise the encrypted data will become unreadable between app restarts.
You can resolve this issue by generating a valid `config/secrets.jl` file with a
random token, calling `Genie.Generator.write_secrets_file()`.
"
secret_token!()
end
end
SECRET_TOKEN[]
end
"""
secret_token!(value = secret())
Define the secret token used in the app for encryption and salting.
"""
function secret_token!(value::AbstractString = secret())
SECRET_TOKEN[] = value
value
end
"""
load(root_dir::String = Genie.config.path_config; context::Union{Module,Nothing} = nothing) :: Nothing
Loads (includes) the framework's secrets.jl file into the app's module `context`.
The files are set up with `Revise` to be automatically reloaded.
"""
function load(root_dir::String = Genie.config.path_config; context::Union{Module,Nothing} = nothing) :: Nothing
secrets_path = secret_file_path(root_dir)
isfile(secrets_path) && Revise.includet(Genie.Loader.default_context(context), secrets_path)
# check that the secrets_path has called Genie.secret_token!
if isempty(secret_token(false)) # do not generate a temporary token in this check
secret_token() # emits a warning and re-generates the token if secrets_path is not valid
end
nothing
end
"""
secret() :: String
Generates a random secret token to be used for configuring the call to `Genie.Secrets.secret_token!`.
"""
function secret() :: String
SHA.sha256("$(randn()) $(Dates.now())") |> bytes2hex
end
function secret_file_exists(root_dir::String = Genie.config.path_config) :: Bool
secret_file_path(root_dir) |> isfile
end
function secret_file_path(root_dir::String = Genie.config.path_config) :: String
joinpath(root_dir, SECRETS_FILE_NAME)
end
end | Genie | https://github.com/GenieFramework/Genie.jl.git |
|
[
"MIT"
] | 5.30.6 | 376aa3d800f4da32d232f2d9a1685e34e2911b4a | code | 12639 | """
Handles Http server related functionality, manages requests and responses and their logging.
"""
module Server
using HTTP, Sockets, HTTP.WebSockets
import Millboard, Distributed, Logging
import Genie
import Distributed
import HTTP.Servers: Listener, forceclose
"""
ServersCollection(webserver::Union{Task,Nothing}, websockets::Union{Task,Nothing})
Represents a object containing references to Genie's web and websockets servers.
"""
Base.@kwdef mutable struct ServersCollection
webserver::Union{T,Nothing} where T <: HTTP.Server = nothing
websockets::Union{T,Nothing} where T <: HTTP.Server = nothing
end
"""
SERVERS
ServersCollection constant containing references to the current app's web and websockets servers.
"""
const SERVERS = ServersCollection[]
const Servers = SERVERS
function isrunning(server::ServersCollection, prop::Symbol = :webserver) :: Bool
isa(getfield(server, prop), Task) && ! istaskdone(getfield(server, prop))
end
function isrunning(prop::Symbol = :webserver) :: Bool
isempty(SERVERS) ? false : isrunning(SERVERS[1], prop)
end
function server_status(server::ServersCollection, prop::Symbol) :: Nothing
if isrunning(server, prop)
@info("✔️ server is running.")
else
@error("❌ $server is not running.")
isa(getfield(server, prop), Task) && fetch(getfield(server, prop))
end
nothing
end
"""
up(port::Int = Genie.config.server_port, host::String = Genie.config.server_host;
ws_port::Int = Genie.config.websockets_port, async::Bool = ! Genie.config.run_as_server) :: ServersCollection
Starts the web server.
# Arguments
- `port::Int`: the port used by the web server
- `host::String`: the host used by the web server
- `ws_port::Int`: the port used by the Web Sockets server
- `async::Bool`: run the web server task asynchronously
# Examples
```julia-repl
julia> up(8000, "127.0.0.1", async = false)
[ Info: Ready!
Web Server starting at http://127.0.0.1:8000
```
"""
function up(port::Int,
host::String = Genie.config.server_host;
ws_port::Union{Int,Nothing} = Genie.config.websockets_port,
async::Bool = ! Genie.config.run_as_server,
verbose::Bool = false,
ratelimit::Union{Rational{Int},Nothing} = nothing,
server::Union{Sockets.TCPServer,Nothing} = nothing,
wsserver::Union{Sockets.TCPServer,Nothing} = server,
open_browser::Bool = false,
reuseaddr::Bool = Distributed.nworkers() > 1,
updateconfig::Bool = true,
protocol::String = "http",
query::Dict = Dict(),
http_kwargs...) :: ServersCollection
if server !== nothing
try
socket_info = Sockets.getsockname(server)
port = Int(socket_info[2])
host = string(socket_info[1])
catch ex
@error "Failed parsing `server` parameter info."
@error ex
end
end
ws_port === nothing && (ws_port = port)
updateconfig && update_config(port, host, ws_port)
new_server = ServersCollection()
if Genie.config.websockets_server !== nothing && port !== ws_port
print_server_status("Web Sockets server starting at $host:$ws_port")
new_server.websockets = HTTP.listen!(host, ws_port; verbose = verbose, rate_limit = ratelimit, server = wsserver,
reuseaddr = reuseaddr, http_kwargs...) do http::HTTP.Stream
if HTTP.WebSockets.isupgrade(http.message)
HTTP.WebSockets.upgrade(http) do ws
setup_ws_handler(http, ws)
end
end
end
end
command = () -> begin
HTTP.listen!(parse(Sockets.IPAddr, host), port; verbose = verbose, rate_limit = ratelimit, server = server,
reuseaddr = reuseaddr, http_kwargs...) do stream::HTTP.Stream
try
if Genie.config.websockets_server !== nothing && port === ws_port && HTTP.WebSockets.isupgrade(stream.message)
HTTP.WebSockets.upgrade(stream) do ws
setup_ws_handler(stream, ws)
end
else
setup_http_streamer(stream)
end
catch ex
isa(ex, Base.IOError) || @error ex
nothing
end
end
end
server_url = "$protocol://$host:$port"
if ! isempty(query)
server_url *= ("?" * join(["$(k)=$(v)" for (k, v) in query], "&"))
end
if async
print_server_status("Web Server starting at $server_url")
else
print_server_status("Web Server starting at $server_url - press Ctrl/Cmd+C to stop the server.")
end
listener = try
command()
catch
nothing
end
if !async && !isnothing(listener)
try
wait(listener)
catch
nothing
finally
close(listener)
# close the corresponding websocket server
new_server.websockets !== nothing && isopen(new_server.websockets) && close(new_server.websockets)
end
end
if listener !== nothing && isopen(listener)
new_server.webserver = listener
try
open_browser && openbrowser(server_url)
catch ex
@error "Failed to open browser"
@error ex
end
end
push!(SERVERS, new_server)
new_server
end
function up(; port = Genie.config.server_port, ws_port = Genie.config.websockets_port, host = Genie.config.server_host, kwargs...) :: ServersCollection
up(port, host; ws_port = ws_port, kwargs...)
end
print_server_status(status::String) = @info "\n$status \n"
@static if Sys.isapple()
openbrowser(url::String) = run(`open $url`)
elseif Sys.islinux()
openbrowser(url::String) = run(`xdg-open $url`)
elseif Sys.iswindows()
openbrowser(url::String) = run(`cmd /C start $url`)
end
"""
serve(path::String = pwd(), params...; kwparams...)
Serves a folder of static files located at `path`. Allows Genie to be used as a static files web server.
The `params` and `kwparams` arguments are forwarded to `Genie.up()`.
# Arguments
- `path::String`: the folder of static files to be served by the server
- `params`: additional arguments which are passed to `Genie.up` to control the web server
- `kwparams`: additional keyword arguments which are passed to `Genie.up` to control the web server
# Examples
```julia-repl
julia> Genie.serve("public", 8888, async = false, verbose = true)
[ Info: Ready!
2019-08-06 16:39:20:DEBUG:Main: Web Server starting at http://127.0.0.1:8888
[ Info: Listening on: 127.0.0.1:8888
[ Info: Accept (1): 🔗 0↑ 0↓ 1s 127.0.0.1:8888:8888 ≣16
```
"""
function serve(path::String = pwd(), params...; kwparams...)
path = abspath(path)
Genie.config.server_document_root = path
Genie.Router.route("/") do
Genie.Router.serve_static_file(path; root = path)
end
Genie.Router.route(".*") do
Genie.Router.serve_static_file(Genie.Router.params(:REQUEST).target; root = path)
end
up(params...; kwparams...)
end
"""
update_config(port::Int, host::String, ws_port::Int) :: Nothing
Updates the corresponding Genie configurations to the corresponding values for
`port`, `host`, and `ws_port`, if these are passed as arguments when starting up the server.
"""
function update_config(port::Int, host::String, ws_port::Int) :: Nothing
if port !== Genie.config.server_port && ws_port === Genie.config.websockets_port
Genie.config.websockets_port = port
elseif ws_port !== Genie.config.websockets_port
Genie.config.websockets_port = ws_port
end
Genie.config.server_port = port
Genie.config.server_host = host
nothing
end
"""
down(; webserver::Bool = true, websockets::Bool = true) :: ServersCollection
Shuts down the servers optionally indicating which of the `webserver` and `websockets` servers to be stopped.
It does not remove the servers from the `SERVERS` collection. Returns the collection.
"""
function down(; webserver::Bool = true, websockets::Bool = true, force::Bool = true) :: Vector{ServersCollection}
for i in 1:length(SERVERS)
down(SERVERS[i]; webserver, websockets, force)
end
SERVERS
end
function down(server::ServersCollection; webserver::Bool = true, websockets::Bool = true, force::Bool = true) :: ServersCollection
close_cmd = force ? forceclose : close
webserver && !isnothing(server.webserver) && isopen(server.webserver) && close_cmd(server.webserver)
websockets && !isnothing(server.websockets) && isopen(server.websockets) && close_cmd(server.websockets)
server
end
"""
function down!(; webserver::Bool = true, websockets::Bool = true) :: Vector{ServersCollection}
Shuts down all the servers and empties the `SERVERS` collection. Returns the empty collection.
"""
function down!() :: Vector{ServersCollection}
down()
empty!(SERVERS)
SERVERS
end
"""
handle_request(req::HTTP.Request, res::HTTP.Response) :: HTTP.Response
Http server handler function - invoked when the server gets a request.
"""
function handle_request(req::HTTP.Request, res::HTTP.Response; stream::Union{HTTP.Stream,Nothing} = nothing) :: HTTP.Response
try
req = Genie.Headers.normalize_headers(req)
catch ex
@error ex
end
try
Genie.Headers.set_headers!(req, res, Genie.Router.route_request(req, res; stream))
catch ex
rethrow(ex)
end
end
function streamhandler(handler::Function)
return function(stream::HTTP.Stream)
request::HTTP.Request = stream.message
request.body = read(stream)
closeread(stream)
request.response::HTTP.Response = handler(request; stream)
request.response.request = request
startwrite(stream)
write(stream, request.response.body)
return
end
end
function setup_http_streamer(stream::HTTP.Stream)
if Genie.config.features_peerinfo
try
task_local_storage(:peer, Sockets.getpeername( HTTP.IOExtras.tcpsocket(HTTP.Streams.getrawstream(stream)) ))
catch ex
@error ex
end
end
streamhandler(setup_http_listener)(stream)
end
"""
setup_http_listener(req::HTTP.Request, res::HTTP.Response = HTTP.Response()) :: HTTP.Response
Configures the handler for the HTTP Request and handles errors.
"""
function setup_http_listener(req::HTTP.Request, res::HTTP.Response = HTTP.Response(); stream::Union{HTTP.Stream, Nothing} = nothing) :: HTTP.Response
try
Distributed.@fetch handle_request(req, res; stream)
catch ex # ex is a Distributed.RemoteException
if isa(ex, Distributed.RemoteException) &&
hasfield(typeof(ex), :captured) && isa(ex.captured, Distributed.CapturedException) &&
hasfield(typeof(ex.captured), :ex) && isa(ex.captured.ex, Genie.Exceptions.RuntimeException)
@error ex.captured.ex
return Genie.Router.error(ex.captured.ex.code, ex.captured.ex.message, Genie.Router.response_mime(),
error_info = string(ex.captured.ex.code, " ", ex.captured.ex.info))
end
error_message = string(sprint(showerror, ex), "\n\n")
@error error_message
message = Genie.Configuration.isprod() ?
"The error has been logged and we'll look into it ASAP." :
error_message
Genie.Router.error(message, Genie.Router.response_mime(), Val(500))
end
end
"""
setup_ws_handler(stream::HTTP.Stream, ws_client) :: Nothing
Configures the handler for WebSockets requests.
"""
function setup_ws_handler(stream::HTTP.Stream, ws_client) :: Nothing
req = stream.message
try
req = stream.message
while ! HTTP.WebSockets.isclosed(ws_client) && ! ws_client.writeclosed && isopen(ws_client.io)
Sockets.send(ws_client, Distributed.@fetch handle_ws_request(req; message = HTTP.WebSockets.receive(ws_client), client = ws_client))
end
catch ex
if isa(ex, Distributed.RemoteException) &&
hasfield(typeof(ex), :captured) && isa(ex.captured, Distributed.CapturedException) &&
hasfield(typeof(ex.captured), :ex) && isa(ex.captured.ex, HTTP.WebSockets.CloseFrameBody) # && ex.captured.ex.code == 1000
@info "WebSocket closed"
return nothing
elseif isa(ex, Distributed.RemoteException) &&
hasfield(typeof(ex), :captured) && isa(ex.captured, Distributed.CapturedException) &&
hasfield(typeof(ex.captured), :ex) && isa(ex.captured.ex, Genie.Exceptions.RuntimeException)
@error ex.captured.ex
return nothing
end
# rethrow(ex)
end
nothing
end
"""
handle_ws_request(req::HTTP.Request, msg::String, ws_client) :: String
Http server handler function - invoked when the server gets a request.
"""
function handle_ws_request(req::HTTP.Request; message::Union{String,Vector{UInt8}}, client::HTTP.WebSockets.WebSocket) :: String
isempty(message) && return "" # keep alive
Genie.Router.route_ws_request(req, message, client)
end
end | Genie | https://github.com/GenieFramework/Genie.jl.git |
|
[
"MIT"
] | 5.30.6 | 376aa3d800f4da32d232f2d9a1685e34e2911b4a | code | 4330 | module Toolbox
import Base.string
import Logging
import Inflector
import Genie, Genie.Util, Genie.FileTemplates, Genie.Configuration, Genie.Exceptions, Genie.Loader
import Millboard
import Revise
export TaskResult, VoidTaskResult
const TASK_SUFFIX = "Task"
mutable struct TaskInfo
file_name::String
module_name::Symbol
description::String
end
mutable struct TaskResult{T}
code::Int
message::String
result::T
end
"""
loadtasks(; filter_type_name = Symbol()) :: Vector{TaskInfo}
Returns a vector of all registered Genie tasks.
"""
function loadtasks(context::Module = Genie.Loader.default_context(); filter_type_name::Union{Symbol,Nothing} = nothing) :: Vector{TaskInfo}
tasks = TaskInfo[]
f = readdir(normpath(Genie.config.path_tasks))
for i in f
if ( endswith(i, "Task.jl") )
module_name = Genie.Util.file_name_without_extension(i) |> Symbol
Revise.includet(context, joinpath(Genie.config.path_tasks, i))
ti = TaskInfo(i, module_name, taskdocs(module_name, context = context))
if ( filter_type_name === nothing ) push!(tasks, ti)
elseif ( filter_type_name == module_name ) return TaskInfo[ti]
end
end
end
tasks
end
function VoidTaskResult()
TaskResult(0, "", nothing)
end
"""
validtaskname(task_name::String) :: String
Attempts to convert a potentially invalid (partial) `task_name` into a valid one.
"""
function validtaskname(task_name::String) :: String
task_name = replace(task_name, " "=>"_")
task_name = Inflector.from_underscores(task_name)
endswith(task_name, TASK_SUFFIX) || (task_name = task_name * TASK_SUFFIX)
task_name
end
"""
Prints a list of all the registered Genie tasks to the standard output.
"""
function printtasks(context::Module) :: Nothing
output = ""
arr_output = []
for t in loadtasks(context)
td = Genie.to_dict(t)
push!(arr_output, [td["module_name"], td["file_name"], td["description"]])
end
Millboard.table(arr_output, colnames = ["Task name \nFilename \nDescription "], rownames = []) |> println
end
"""
task_docs(module_name::Module) :: String
Retrieves the docstring of the runtask method and returns it as a string.
"""
function taskdocs(module_name::Symbol; context = @__MODULE__) :: String
try
docs = Base.doc(Base.Docs.Binding(getfield(context, module_name), :runtask)) |> string
startswith(docs, "No documentation found") && (docs = "No documentation found -- add docstring to `$(module_name).runtask()` to see it here.")
docs
catch ex
@error ex
""
end
end
"""
new(task_name::String) :: Nothing
Generates a new Genie task file.
"""
function new(task_name::String) :: Nothing
task_name = validtaskname(task_name)
tfn = taskfilename(task_name)
isfile(tfn) && throw(Genie.Exceptions.FileExistsException(tfn))
isdir(Genie.config.path_tasks) || mkpath(Genie.config.path_tasks)
open(tfn, "w") do io
write(io, Genie.FileTemplates.newtask(taskmodulename(task_name)))
end
@info "New task created at $tfn"
nothing
end
"""
task_file_name(cmd_args::Dict{String,Any}, config::Settings) :: String
Computes the name of a Genie task based on the command line input.
"""
function taskfilename(task_name::String) :: String
joinpath(Genie.config.path_tasks, "$task_name.jl")
end
"""
task_module_name(underscored_task_name::String) :: String
Computes the name of a Genie task based on the command line input.
"""
function taskmodulename(underscored_task_name::String) :: String
mapreduce( x -> uppercasefirst(x), *, split(replace(underscored_task_name, ".jl"=>""), "_") )
end
"""
isvalidtask!(parsed_args::Dict{String,Any}) :: Dict{String,Any}
Checks if the name of the task passed as the command line arg is valid task identifier -- if not, attempts to address it, by appending the TASK_SUFFIX suffix.
Returns the potentially modified `parsed_args` `Dict`.
"""
function isvalidtask!(parsed_args::Dict{String,Any}) :: Dict{String,Any}
haskey(parsed_args, "task:new") && isa(parsed_args["task:new"], String) && ! endswith(parsed_args["task:new"], TASK_SUFFIX) && (parsed_args["task:new"] *= TASK_SUFFIX)
haskey(parsed_args, "task:run") && isa(parsed_args["task:run"], String) &&! endswith(parsed_args["task:run"], TASK_SUFFIX) && (parsed_args["task:run"] *= TASK_SUFFIX)
parsed_args
end
end | Genie | https://github.com/GenieFramework/Genie.jl.git |
|
[
"MIT"
] | 5.30.6 | 376aa3d800f4da32d232f2d9a1685e34e2911b4a | code | 2780 | module Util
using Pkg
import Genie
"""
file_name_without_extension(file_name, extension = ".jl") :: String
Removes the file extension `extension` from `file_name`.
"""
function file_name_without_extension(file_name, extension = ".jl") :: String
file_name[1:end-length(extension)]
end
"""
function walk_dir(dir, paths = String[]; only_extensions = ["jl"], only_files = true, only_dirs = false) :: Vector{String}
Recursively walks dir and `produce`s non directories. If `only_files`, directories will be skipped. If `only_dirs`, files will be skipped.
"""
function walk_dir(dir, paths = String[];
only_extensions = ["jl"],
only_files = true,
only_dirs = false,
exceptions = Genie.config.watch_exceptions,
autoload_ignorefile = Genie.config.autoload_ignore_file) :: Vector{String}
f = readdir(dir)
exception = false
for i in f
full_path = joinpath(dir, i)
for ex in exceptions
if occursin(ex, full_path)
exception = true
break
end
end
if exception
exception = false
continue
end
if isdir(full_path)
isfile(joinpath(full_path, autoload_ignorefile)) && continue
(! only_files || only_dirs) && push!(paths, full_path)
Genie.Util.walk_dir(full_path, paths; only_extensions = only_extensions, only_files = only_files, only_dirs = only_dirs, exceptions = exceptions, autoload_ignorefile = autoload_ignorefile)
else
only_dirs && continue
((last(split(i, ['.'])) in only_extensions) || isempty(only_extensions)) && push!(paths, full_path)
end
end
paths
end
const walkdir = walk_dir
"""
filterwhitespace(s::String, allowed::Vector{Char} = Char[]) :: String
Removes whitespaces from `s`, with the exception of the characters in `allowed`.
"""
function filterwhitespace(s::S, allowed::Vector{Char} = Char[])::String where {S<:AbstractString}
filter(x -> (x in allowed) || ! isspace(x), string(s))
end
"""
isprecompiling() :: Bool
Returns `true` if the current process is precompiling.
"""
isprecompiling() = ccall(:jl_generating_output, Cint, ()) == 1
const fws = filterwhitespace
"""
package_version(package::Union{Module,String}) :: String
Returns the version of a package, or "master" if the package is not installed.
### Example
```julia
julia> package_version("Genie.jl")
"v0.23.0"
"""
function package_version(package::Union{Module,String}) :: String
isa(package, Module) && (package = String(nameof(package)))
endswith(package, ".jl") && (package = String(package[1:end-3]))
pkg_dict = filter(x -> x.second.name == package, Pkg.dependencies())
isempty(pkg_dict) ? "master" : ("v" * string(first(pkg_dict)[2].version))
end
end
| Genie | https://github.com/GenieFramework/Genie.jl.git |
|
[
"MIT"
] | 5.30.6 | 376aa3d800f4da32d232f2d9a1685e34e2911b4a | code | 3041 | module Watch
using Revise
using Genie
using Logging
using Dates
const WATCHED_FOLDERS = Ref{Vector{String}}(String[])
const WATCHING = Ref{Vector{UInt}}(UInt[])
const WATCH_HANDLERS = Ref{Dict{String,Vector{Function}}}(Genie.config.watch_handlers)
function collect_watched_files(files::Vector{S} = WATCHED_FOLDERS[], extensions::Vector{S} = Genie.config.watch_extensions)::Vector{S} where {S<:AbstractString}
result = String[]
for f in files
push!(result, Genie.Util.walk_dir(f, only_extensions = extensions)...)
end
result |> sort |> unique
end
function watchpath(path::Union{S,Vector{S}}) where {S<:AbstractString}
isa(path, Vector) || (path = String[path])
push!(WATCHED_FOLDERS[], path...)
unique!(WATCHED_FOLDERS[])
end
function delete_handlers(key::Any)
delete!(WATCH_HANDLERS[], string(key))
end
function add_handler!(key::S, handler::F) where {F<:Function, S<:AbstractString}
haskey(WATCH_HANDLERS[], key) || (WATCH_HANDLERS[][key] = Function[])
push!(WATCH_HANDLERS[][key], handler)
unique!(WATCH_HANDLERS[][key])
end
function handlers!(key::S, handlers::Vector{<: Function}) where {S<:AbstractString}
WATCH_HANDLERS[][key] = handlers
end
function handlers() :: Vector{<: Function}
WATCH_HANDLERS[] |> values |> collect |> Iterators.flatten |> collect
end
function watch(files::Vector{<: AbstractString},
extensions::Vector{<: AbstractString} = Genie.config.watch_extensions;
handlers::Vector{<: Function} = handlers()) :: Nothing
last_watched = now() - Millisecond(Genie.config.watch_frequency) # to trigger the first watch
Genie.Configuration.isdev() && Revise.revise()
# if ! (hash(handlers) in WATCHING[])
# push!(WATCHING[], hash(handlers))
# else
# Genie.Configuration.isdev() && @warn("Handlers already registered")
# return
# end
entr(collect_watched_files(WATCHED_FOLDERS[], extensions); all = true) do
now() - last_watched > Millisecond(Genie.config.watch_frequency) || return
last_watched = now()
try
for f in unique!(handlers)
Base.invokelatest(f)
end
catch ex
@error ex
end
last_watched = now()
end
nothing
end
function watch(handler::F, files::Union{A,Vector{A}}, extensions::Vector{A} = Genie.config.watch_extensions) where {F<:Function, A<:AbstractString}
isa(files, Vector) || (files = String[files])
watch(files, extensions; handlers = Function[handler])
end
watch(files::A, extensions::Vector{A} = Genie.config.watch_extensions; handlers::Vector{F} = handlers()) where {F<:Function, A<:AbstractString} = watch(String[files], extensions; handlers)
watch(files...; extensions::Vector{A} = Genie.config.watch_extensions, handlers::Vector{F} = handlers()) where {F<:Function, A<:AbstractString} = watch(String[files...], extensions; handlers)
watch() = watch(String[])
function unwatch(files::Vector{A})::Nothing where {A<:AbstractString}
filter!(e -> !(e in files), WATCHED_FOLDERS[])
nothing
end
unwatch(files...) = unwatch(String[files...])
end | Genie | https://github.com/GenieFramework/Genie.jl.git |
|
[
"MIT"
] | 5.30.6 | 376aa3d800f4da32d232f2d9a1685e34e2911b4a | code | 10135 | """
Handles WebSockets communication logic.
"""
module WebChannels
import HTTP, Distributed, Logging, JSON3, Sockets, Dates, Base64
import Genie, Genie.Renderer
const ClientId = UInt # web socket hash
const ChannelName = String
const MESSAGE_QUEUE = Dict{UInt, Tuple{
Channel{Tuple{String, Channel{Nothing}}},
Task}
}()
struct ChannelNotFoundException <: Exception
name::ChannelName
end
mutable struct ChannelClient
client::HTTP.WebSockets.WebSocket
channels::Vector{ChannelName}
end
const ChannelClientsCollection = Dict{ClientId,ChannelClient} # { id(ws) => { :client => ws, :channels => ["foo", "bar", "baz"] } }
const ChannelSubscriptionsCollection = Dict{ChannelName,Vector{ClientId}} # { "foo" => ["4", "12"] }
const MessagePayload = Union{Nothing,Dict}
mutable struct ChannelMessage
channel::ChannelName
client::ClientId
message::String
payload::MessagePayload
end
function JSON3.StructTypes.StructType(::Type{T}) where {T<:ChannelMessage}
JSON3.StructTypes.Struct()
end
const CLIENTS = ChannelClientsCollection()
const SUBSCRIPTIONS = ChannelSubscriptionsCollection()
clients() = collect(values(CLIENTS))
subscriptions() = SUBSCRIPTIONS
websockets() = map(c -> c.client, clients())
channels() = collect(keys(SUBSCRIPTIONS))
function connected_clients(channel::ChannelName) :: Vector{ChannelClient}
clients = ChannelClient[]
for client_id in SUBSCRIPTIONS[channel]
! HTTP.WebSockets.isclosed(CLIENTS[client_id].client) && push!(clients, CLIENTS[client_id])
end
clients
end
function connected_clients() :: Vector{ChannelClient}
clients = ChannelClient[]
for ch in channels()
clients = vcat(clients, connected_clients(ch))
end
clients
end
function disconnected_clients(channel::ChannelName) :: Vector{ChannelClient}
clients = ChannelClient[]
for client_id in SUBSCRIPTIONS[channel]
HTTP.WebSockets.isclosed(CLIENTS[client_id].client) && push!(clients, CLIENTS[client_id])
end
clients
end
function disconnected_clients() :: Vector{ChannelClient}
channel_clients = ChannelClient[]
for channel_client in clients()
HTTP.WebSockets.isclosed(channel_client.client) && push!(channel_clients, channel_client)
end
channel_clients
end
"""
Subscribes a web socket client `ws` to `channel`.
"""
function subscribe(ws::HTTP.WebSockets.WebSocket, channel::ChannelName) :: ChannelClientsCollection
if haskey(CLIENTS, id(ws))
in(channel, CLIENTS[id(ws)].channels) || push!(CLIENTS[id(ws)].channels, channel)
else
CLIENTS[id(ws)] = ChannelClient(ws, ChannelName[channel])
end
push_subscription(id(ws), channel)
@debug "Subscribed: $(id(ws)) ($(Dates.now()))"
CLIENTS
end
function id(ws::HTTP.WebSockets.WebSocket) :: UInt
hash(ws)
end
"""
Unsubscribes a web socket client `ws` from `channel`.
"""
function unsubscribe(ws::HTTP.WebSockets.WebSocket, channel::ChannelName) :: ChannelClientsCollection
client = id(ws)
haskey(CLIENTS, client) && deleteat!(CLIENTS[client].channels, CLIENTS[client].channels .== channel)
pop_subscription(client, channel)
delete_queue!(MESSAGE_QUEUE, client)
@debug "Unsubscribed: $(client) ($(Dates.now()))"
CLIENTS
end
function unsubscribe(channel_client::ChannelClient, channel::ChannelName) :: ChannelClientsCollection
unsubscribe(channel_client.client, channel)
end
"""
Unsubscribes a web socket client `ws` from all the channels.
"""
function unsubscribe_client(ws::HTTP.WebSockets.WebSocket) :: ChannelClientsCollection
if haskey(CLIENTS, id(ws))
for channel_id in CLIENTS[id(ws)].channels
pop_subscription(id(ws), channel_id)
end
delete!(CLIENTS, id(ws))
end
CLIENTS
end
function unsubscribe_client(client_id::ClientId) :: ChannelClientsCollection
unsubscribe_client(CLIENTS[client_id].client)
CLIENTS
end
function unsubscribe_client(channel_client::ChannelClient) :: ChannelClientsCollection
unsubscribe_client(channel_client.client)
CLIENTS
end
"""
unsubscribe_disconnected_clients() :: ChannelClientsCollection
Unsubscribes clients which are no longer connected.
"""
function unsubscribe_disconnected_clients() :: ChannelClientsCollection
for channel_client in disconnected_clients()
unsubscribe_client(channel_client)
end
CLIENTS
end
function unsubscribe_disconnected_clients(channel::ChannelName) :: ChannelClientsCollection
for channel_client in disconnected_clients(channel)
unsubscribe(channel_client, channel)
end
CLIENTS
end
"""
Adds a new subscription for `client` to `channel`.
"""
function push_subscription(client_id::ClientId, channel::ChannelName) :: ChannelSubscriptionsCollection
if haskey(SUBSCRIPTIONS, channel)
! in(client_id, SUBSCRIPTIONS[channel]) && push!(SUBSCRIPTIONS[channel], client_id)
else
SUBSCRIPTIONS[channel] = ClientId[client_id]
end
SUBSCRIPTIONS
end
function push_subscription(channel_client::ChannelClient, channel::ChannelName) :: ChannelSubscriptionsCollection
push_subscription(id(channel_client.client), channel)
end
"""
Removes the subscription of `client` to `channel`.
"""
function pop_subscription(client::ClientId, channel::ChannelName) :: ChannelSubscriptionsCollection
if haskey(SUBSCRIPTIONS, channel)
filter!(SUBSCRIPTIONS[channel]) do (client_id)
client_id != client
end
isempty(SUBSCRIPTIONS[channel]) && delete!(SUBSCRIPTIONS, channel)
end
SUBSCRIPTIONS
end
function pop_subscription(channel_client::ChannelClient, channel::ChannelName) :: ChannelSubscriptionsCollection
pop_subscription(id(channel_client.client), channel)
end
"""
Removes all subscriptions of `client`.
"""
function pop_subscription(channel::ChannelName) :: ChannelSubscriptionsCollection
if haskey(SUBSCRIPTIONS, channel)
delete!(SUBSCRIPTIONS, channel)
end
SUBSCRIPTIONS
end
"""
Pushes `msg` (and `payload`) to all the clients subscribed to the channels in `channels`, with the exception of `except`.
"""
function broadcast(channels::Union{ChannelName,Vector{ChannelName}},
msg::String,
payload::Union{Dict,Nothing} = nothing;
except::Union{Nothing,UInt,Vector{UInt}} = nothing,
restrict::Union{Nothing,UInt,Vector{UInt}} = nothing) :: Bool
isa(channels, Array) || (channels = ChannelName[channels])
isempty(SUBSCRIPTIONS) && return false
try
for channel in channels
haskey(SUBSCRIPTIONS, channel) || throw(ChannelNotFoundException(channel))
ids = restrict === nothing ? SUBSCRIPTIONS[channel] : intersect(SUBSCRIPTIONS[channel], restrict)
for client in ids
if except !== nothing
except isa UInt && client == except && continue
except isa Vector{UInt} && client ∈ except && continue
end
HTTP.WebSockets.isclosed(CLIENTS[client].client) && continue
try
payload !== nothing ?
message(client, ChannelMessage(channel, client, msg, payload) |> Renderer.Json.JSONParser.json) :
message(client, msg)
catch ex
if isa(ex, Base.IOError)
unsubscribe_disconnected_clients(channel)
else
@error ex
end
end
end
end
catch ex
@warn ex
end
true
end
"""
Pushes `msg` (and `payload`) to all the clients subscribed to the channels in `channels`, with the exception of `except`.
"""
function broadcast(msg::String;
channels::Union{Union{ChannelName,Vector{ChannelName}},Nothing} = nothing,
payload::Union{Dict,Nothing} = nothing,
except::Union{HTTP.WebSockets.WebSocket,Nothing,UInt} = nothing) :: Bool
try
channels === nothing && (channels = collect(keys(SUBSCRIPTIONS)))
broadcast(channels, msg, payload; except = except)
catch ex
@error ex
false
end
end
"""
Pushes `js_code` (a JavaScript piece of code) to be executed by all the clients subscribed to the channels in `channels`,
with the exception of `except`.
"""
function jscomm(js_code::String, channels::Union{Union{ChannelName,Vector{ChannelName}},Nothing} = nothing;
except::Union{HTTP.WebSockets.WebSocket,Nothing,UInt} = nothing)
broadcast(string(Genie.config.webchannels_eval_command, js_code); channels = channels, except = except)
end
"""
Writes `msg` to web socket for `client`.
"""
function message(client::ClientId, msg::String)
ws = Genie.WebChannels.CLIENTS[client].client
# setup a reply channel
myfuture = Channel{Nothing}(1)
# retrieve the message queue or set it up if not present
q, _ = get!(MESSAGE_QUEUE, client) do
queue = Channel{Tuple{String, Channel{Nothing}}}(10)
handler = @async while true
message, future = take!(queue)
try
Sockets.send(ws, message)
catch
@debug "Sending message to $(repr(client)) failed!"
finally
put!(future, nothing)
end
end
queue, handler
end
put!(q, (msg, myfuture))
take!(myfuture) # Wait until the message is processed
end
function message(client::ChannelClient, msg::String) :: Int
message(client.client, msg)
end
function message(ws::HTTP.WebSockets.WebSocket, msg::String) :: Int
message(id(ws), msg)
end
function message_unsafe(ws::HTTP.WebSockets.WebSocket, msg::String) :: Int
Sockets.send(ws, msg)
end
function message_unsafe(client::ClientId, msg::String) :: Int
message_unsafe(CLIENTS[client].client, msg)
end
function message_unsafe(client::ChannelClient, msg::String) :: Int
message_unsafe(client.client, msg)
end
function delete_queue!(d::Dict, client::UInt)
queue, handler = pop!(MESSAGE_QUEUE, client, (nothing, nothing))
if queue !== nothing
@async Base.throwto(handler, InterruptException())
end
end
"""
Encodes `msg` in Base64 and tags it with `Genie.config.webchannels_base64_marker`.
"""
function tagbase64encode(msg)
Genie.config.webchannels_base64_marker * Base64.base64encode(msg)
end
"""
Decodes `msg` from Base64 and removes the `Genie.config.webchannels_base64_marker` tag.
"""
function tagbase64decode(msg)
Base64.base64decode(msg[length(Genie.config.webchannels_base64_marker):end])
end
end
| Genie | https://github.com/GenieFramework/Genie.jl.git |
|
[
"MIT"
] | 5.30.6 | 376aa3d800f4da32d232f2d9a1685e34e2911b4a | code | 7978 | """
Handles Ajax communication logic.
"""
module WebThreads
import HTTP, Distributed, Logging, Dates
import Genie, Genie.Renderer
const MESSAGE_QUEUE = Dict{UInt,Vector{String}}()
const ClientId = UInt # session id
const ChannelName = String
mutable struct ChannelClient
client::UInt
channels::Vector{ChannelName}
last_active::Dates.DateTime
end
const ChannelClientsCollection = Dict{ClientId,ChannelClient} # { uint => { :client => ws, :channels => ["foo", "bar", "baz"] } }
const ChannelSubscriptionsCollection = Dict{ChannelName,Vector{ClientId}} # { "foo" => ["4", "12"] }
const MessagePayload = Union{Nothing,Dict}
mutable struct ChannelMessage
channel::ChannelName
client::ClientId
message::String
payload::MessagePayload
end
const CLIENTS = ChannelClientsCollection()
const SUBSCRIPTIONS = ChannelSubscriptionsCollection()
clients() = collect(values(CLIENTS))
subscriptions() = SUBSCRIPTIONS
webthreads() = map(c -> c.client, clients())
channels() = collect(keys(SUBSCRIPTIONS))
function connected_clients(channel::ChannelName) :: Vector{ChannelClient}
clients = ChannelClient[]
for client_id in SUBSCRIPTIONS[channel]
((Dates.now() - CLIENTS[client_id].last_active) <= Genie.config.webthreads_connection_threshold) && push!(clients, CLIENTS[client_id])
end
clients
end
function connected_clients() :: Vector{ChannelClient}
clients = ChannelClient[]
for ch in channels()
clients = vcat(clients, connected_clients(ch))
end
clients
end
function disconnected_clients(channel::ChannelName) :: Vector{ChannelClient}
clients = ChannelClient[]
for client_id in SUBSCRIPTIONS[channel]
((Dates.now() - CLIENTS[client_id].last_active) > Genie.config.webthreads_connection_threshold) && push!(clients, CLIENTS[client_id])
end
clients
end
function disconnected_clients() :: Vector{ChannelClient}
clients = ChannelClient[]
for ch in channels()
clients = vcat(clients, disconnected_clients(ch))
end
clients
end
"""
Subscribes a web thread client `wt` to `channel`.
"""
function subscribe(wt::UInt, channel::ChannelName) :: ChannelClientsCollection
if haskey(CLIENTS, wt)
in(channel, CLIENTS[wt].channels) || push!(CLIENTS[wt].channels, channel)
else
CLIENTS[wt] = ChannelClient(wt, ChannelName[channel], Dates.now())
end
push_subscription(wt, channel)
haskey(MESSAGE_QUEUE, wt) || (MESSAGE_QUEUE[wt] = String[])
CLIENTS
end
"""
Unsubscribes a web socket client `wt` from `channel`.
"""
function unsubscribe(wt::UInt, channel::ChannelName) :: ChannelClientsCollection
haskey(CLIENTS, wt) && deleteat!(CLIENTS[wt].channels, CLIENTS[wt].channels .== channel)
pop_subscription(wt, channel)
delete!(MESSAGE_QUEUE, wt)
CLIENTS
end
function unsubscribe(channel_client::ChannelClient, channel::ChannelName) :: ChannelClientsCollection
unsubscribe(channel_client.client, channel)
end
"""
Unsubscribes a web socket client `wt` from all the channels.
"""
function unsubscribe_client(wt::UInt) :: ChannelClientsCollection
if haskey(CLIENTS, wt)
for channel_id in CLIENTS[wt].channels
pop_subscription(wt, channel_id)
end
delete!(CLIENTS, wt)
end
CLIENTS
end
function unsubscribe_client(channel_client::ChannelClient) :: ChannelClientsCollection
unsubscribe_client(channel_client.client)
CLIENTS
end
"""
unsubscribe_disconnected_clients() :: ChannelClientsCollection
Unsubscribes clients which are no longer connected.
"""
function unsubscribe_disconnected_clients() :: ChannelClientsCollection
for channel_client in disconnected_clients()
unsubscribe_client(channel_client)
end
CLIENTS
end
function unsubscribe_disconnected_clients(channel::ChannelName) :: ChannelClientsCollection
for channel_client in disconnected_clients(channel)
unsubscribe(channel_client, channel)
end
CLIENTS
end
function unsubscribe_clients()
empty!(CLIENTS)
empty!(SUBSCRIPTIONS)
end
function timestamp_client(client_id::ClientId) :: Nothing
haskey(CLIENTS, client_id) && (CLIENTS[client_id].last_active = Dates.now())
nothing
end
"""
Adds a new subscription for `client` to `channel`.
"""
function push_subscription(client_id::ClientId, channel::ChannelName) :: ChannelSubscriptionsCollection
if haskey(SUBSCRIPTIONS, channel)
! in(client_id, SUBSCRIPTIONS[channel]) && push!(SUBSCRIPTIONS[channel], client_id)
else
SUBSCRIPTIONS[channel] = ClientId[client_id]
end
timestamp_client(client_id)
SUBSCRIPTIONS
end
function push_subscription(channel_client::ChannelClient, channel::ChannelName) :: ChannelSubscriptionsCollection
push_subscription(channel_client.client, channel)
end
"""
Removes the subscription of `client` to `channel`.
"""
function pop_subscription(client::ClientId, channel::ChannelName) :: ChannelSubscriptionsCollection
if haskey(SUBSCRIPTIONS, channel)
filter!(SUBSCRIPTIONS[channel]) do (client_id)
client_id != client
end
isempty(SUBSCRIPTIONS[channel]) && delete!(SUBSCRIPTIONS, channel)
end
timestamp_client(client)
SUBSCRIPTIONS
end
function pop_subscription(channel_client::ChannelClient, channel::ChannelName) :: ChannelSubscriptionsCollection
pop_subscription(channel_client.client, channel)
end
"""
Removes all subscriptions of `client`.
"""
function pop_subscription(channel::ChannelName) :: ChannelSubscriptionsCollection
if haskey(SUBSCRIPTIONS, channel)
delete!(SUBSCRIPTIONS, channel)
end
SUBSCRIPTIONS
end
"""
Pushes `msg` (and `payload`) to all the clients subscribed to the channels in `channels`.
"""
function broadcast(channels::Union{ChannelName,Vector{ChannelName}}, msg::String, payload::Union{Dict,Nothing} = nothing;
except::Union{Nothing,UInt,Vector{UInt}} = nothing,
restrict::Union{Nothing,UInt,Vector{UInt}} = nothing) :: Bool
isa(channels, Array) || (channels = [channels])
for channel in channels
if ! haskey(SUBSCRIPTIONS, channel)
@debug(Genie.WebChannels.ChannelNotFoundException(channel))
continue
end
ids = restrict === nothing ? SUBSCRIPTIONS[channel] : intersect(SUBSCRIPTIONS[channel], restrict)
for client in ids
if except !== nothing
except isa UInt && client == except && continue
except isa Vector{UInt} && client ∈ except && continue
end
try
payload !== nothing ?
message(client, ChannelMessage(channel, client, msg, payload) |> Renderer.Json.JSONParser.json) :
message(client, msg)
catch ex
@error ex
end
end
end
true
end
"""
Pushes `msg` (and `payload`) to all the clients subscribed to all the channels.
"""
function broadcast(msg::String, payload::Union{Dict,Nothing} = nothing;
except::Union{Nothing,UInt,Vector{UInt}} = nothing,
restrict::Union{Nothing,UInt,Vector{UInt}} = nothing) :: Bool
payload === nothing ?
broadcast(collect(keys(SUBSCRIPTIONS)), msg; except, restrict) :
broadcast(collect(keys(SUBSCRIPTIONS)), msg, payload; except, restrict)
end
"""
Pushes `msg` (and `payload`) to `channel`.
"""
function message(channel::ChannelName, msg::String, payload::Union{Dict,Nothing} = nothing) :: Bool
payload === nothing ?
broadcast(channel, msg) :
broadcast(channel, msg, payload)
end
"""
Writes `msg` to message queue for `client`.
"""
function message(wt::UInt, msg::String)
push!(MESSAGE_QUEUE[wt], msg)
end
function message(client::ChannelClient, msg::String)
message(client.client, msg)
end
function pull(wt::UInt, channel::ChannelName)
output = ""
if haskey(MESSAGE_QUEUE, wt) && ! isempty(MESSAGE_QUEUE[wt])
output = MESSAGE_QUEUE[wt] |> Renderer.Json.JSONParser.json
empty!(MESSAGE_QUEUE[wt])
end
timestamp_client(wt)
output
end
function push(wt::UInt, channel::ChannelName, message::String)
timestamp_client(wt)
Genie.Router.route_ws_request(Genie.Router.params(Genie.Router.PARAMS_REQUEST_KEY), message, wt)
end
end | Genie | https://github.com/GenieFramework/Genie.jl.git |
|
[
"MIT"
] | 5.30.6 | 376aa3d800f4da32d232f2d9a1685e34e2911b4a | code | 252 | const ROUTES_FILE_NAME = "routes.jl"
const APP_FILE_NAME = "app.jl"
const SEARCHLIGHT_INITIALIZER_FILE_NAME = "searchlight.jl"
const BOOTSTRAP_FILE_NAME = "bootstrap.jl" | Genie | https://github.com/GenieFramework/Genie.jl.git |
|
[
"MIT"
] | 5.30.6 | 376aa3d800f4da32d232f2d9a1685e34e2911b4a | code | 43904 | module Html
import EzXML, HTTP, Logging, Markdown, Millboard, OrderedCollections, Reexport, YAML
Reexport.@reexport using Genie
Reexport.@reexport using Genie.Renderer
Reexport.@reexport using HttpCommon
const DEFAULT_LAYOUT_FILE = :app
const LAYOUTS_FOLDER = "layouts"
const HTML_FILE_EXT = ".jl"
const TEMPLATE_EXT = [".jl.html", ".jl"]
const MARKDOWN_FILE_EXT = [".md", ".jl.md"]
const SUPPORTED_HTML_OUTPUT_FILE_FORMATS = TEMPLATE_EXT
const HTMLParser = EzXML
const NBSP_REPLACEMENT = (" "=>"!!nbsp;;")
const NORMAL_ELEMENTS = [ :html, :head, :body, :title, :style, :address, :article, :aside, :footer,
:header, :h1, :h2, :h3, :h4, :h5, :h6, :hgroup, :nav, :section,
:dd, :div, :d, :dl, :dt, :figcaption, :figure, :li, :main, :ol, :p, :pre, :ul, :span,
:a, :abbr, :b, :bdi, :bdo, :cite, :code, :data, :dfn, :em, :i, :kbd, :mark,
:q, :rp, :rt, :rtc, :ruby, :s, :samp, :small, :strong, :sub, :sup, :time,
:u, :var, :wrb, :audio, :void, :embed, :object, :canvas, :noscript, :script,
:del, :ins, :caption, :col, :colgroup, :table, :tbody, :td, :tfoot, :th, :thead, :tr,
:button, :datalist, :fieldset, :label, :legend, :meter,
:output, :progress, :select, :option, :textarea, :details, :dialog, :menu, :menuitem, :summary,
:slot, :template, :blockquote, :center, :iframe, :form]
const VOID_ELEMENTS = [:base, :link, :meta, :hr, :br, :area, :img, :track, :param, :source, :input]
const NON_EXPORTED = [:main, :map, :filter]
const SVG_ELEMENTS = [:animate, :circle, :animateMotion, :animateTransform, :clipPath, :defs, :desc, :discard,
:ellipse, :feComponentTransfer, :feComposite, :feDiffuseLighting, :feBlend, :feColorMatrix,
:feConvolveMatrix, :feDisplacementMap, :feDistantLight, :feDropShadow, :feFlood, :feFuncA, :feFuncB, :feFuncG,
:feFuncR, :feGaussianBlur, :feImage, :feMerge, :feMergeNode, :feMorphology, :feOffset, :fePointLight, :feSpecularLighting,
:feSpotLight, :feTile, :feTurbulence, :foreignObject, :g, :hatch, :hatchpath, :image, :line, :linearGradient,
:marker, :mask, :metadata, :mpath, :path, :pattern, :polygon, :polyline, :radialGradient, :rect, :set, :stop, :svg,
:switch, :symbol, :text, :textPath, :tspan, :use, :view]
const BOOL_ATTRS = [:allowfullscreen, :async, :autofocus, :autoplay, :checked, :controls, :default, :defer, :disabled,
:formnovalidate, :ismap, :itemscope, :loop, :multiple, :muted, :nomodule, :novalidate, :open,
:playsinline, :readonly, :required, :reversed, :selected, :truespeed]
const EMBEDDED_JULIA_PLACEHOLDER = "~~~~~|~~~~~"
const EMBED_JULIA_OPEN_TAG = "<%"
const EMBED_JULIA_CLOSE_TAG = "%>"
# ParsedHTMLStrings
struct ParsedHTMLString <: AbstractString
data::String
end
function ParsedHTMLString(v::Vector{T}) where {T}
join(v) |> ParsedHTMLString
end
Base.string(v::Vector{ParsedHTMLString}) = join(v)
ParsedHTMLString(args...) = ParsedHTMLString([args...])
Base.string(s::ParsedHTMLString) = s.data
Base.String(s::ParsedHTMLString) = string(s)
Base.iterate(s::ParsedHTMLString) = iterate(s.data)
Base.iterate(s::ParsedHTMLString, x::Int) = iterate(s.data, x)
Base.ncodeunits(s::ParsedHTMLString) = Base.ncodeunits(s.data)
Base.codeunit(s::ParsedHTMLString) = Base.codeunit(s.data)
Base.codeunit(s::ParsedHTMLString, i::Int) = Base.codeunit(s.data, i)
Base.isvalid(s::ParsedHTMLString, i::Int) = Base.isvalid(s.data, i)
Base.convert(::Type{ParsedHTMLString}, v::Vector{T}) where {T} = ParsedHTMLString(v)
import Base: (*)
(*)(s::ParsedHTMLString, t::ParsedHTMLString) = string(s.data, t.data)
# end ParsedHTMLStrings
# HTMLStrings
struct HTMLString <: AbstractString
data::String
end
function HTMLString(v::Vector{T}) where {T}
join(v) |> HTMLString
end
Base.string(v::Vector{HTMLString}) = join(v)
Base.string(v::Vector{AbstractString}) = join(v)
HTMLString(args...) = HTMLString([args...])
Base.string(s::HTMLString) = s.data
Base.String(s::HTMLString) = string(s)
Base.iterate(s::HTMLString) = iterate(s.data)
Base.iterate(s::HTMLString, x::Int) = iterate(s.data, x)
Base.ncodeunits(s::HTMLString) = Base.ncodeunits(s.data)
Base.codeunit(s::HTMLString) = Base.codeunit(s.data)
Base.codeunit(s::HTMLString, i::Int) = Base.codeunit(s.data, i)
Base.isvalid(s::HTMLString, i::Int) = Base.isvalid(s.data, i)
Base.convert(::Type{HTMLString}, v::Vector{T}) where {T} = HTMLString(v)
import Base: (*)
(*)(s::HTMLString, t::HTMLString) = string(s.data, t.data)
# end HTMLStrings
# const HTMLString = String
export HTMLString, html, doc, doctype, ParsedHTMLString, html!
export @yield, collection, view!, for_each, iif
export partial, template
task_local_storage(:__yield, "")
include("MdHtml.jl")
function contentargs(args...)
join(join.(filter((x -> isa(x, AbstractArray)), args)), ""), [filter((x -> !isa(x, AbstractArray)), args)...]
end
"""
normal_element(f::Function, elem::String, attrs::Vector{Pair{Symbol,Any}} = Pair{Symbol,Any}[]) :: HTMLString
Generates a HTML element in the form <...></...>
"""
function normal_element(f::Function, elem::Any, args::Vector = [], attrs::Vector{Pair{Symbol,Any}} = Pair{Symbol,Any}[]) :: HTMLString
try
normal_element(Base.invokelatest(f), string(elem), args, attrs...)
catch ex
@warn ex
if isa(ex, UndefVarError) && !Genie.config.html_registered_tags_only # tag function does not exist, let's register it
register_normal_element(ex.var |> string; context = @__MODULE__)
Genie.Renderer.purgebuilds()
try
normal_element(Base.invokelatest(f), string(elem), args, attrs...)
catch exx
# TODO: decide what to do -- normally this will be fixed on the next page reload with the element registered
"Error rendering element: $(ex.var) -- please reload the page to try again."
end
else
rethrow(ex)
end
end
end
function normal_element(children::Union{T,Vector{T}}, elem::Any, args::Vector, attrs::Pair{Symbol,Any})::HTMLString where {T<:AbstractString}
normal_element(children, string(elem), args, Pair{Symbol,Any}[attrs])
end
function normal_element(children::Tuple, elem::Any, args::Vector, attrs::Pair{Symbol,Any}) :: HTMLString
normal_element([children...], string(elem), args, Pair{Symbol,Any}[attrs])
end
function normal_element(children::Union{T,Vector{T}}, elem::Any, args::Vector, attrs...)::HTMLString where {T<:AbstractString}
normal_element(children, string(elem), args, Pair{Symbol,Any}[attrs...])
end
function normal_element(children::Union{T,Vector{T}}, elem::Any, args::Vector = [], attrs::Vector{Pair{Symbol,Any}} = Pair{Symbol,Any}[])::HTMLString where {T<:AbstractString}
content_args, args = contentargs(args...)
children = string(join(children), content_args)
idx = findfirst(x -> x == :inner, getindex.(attrs, 1))
if idx !== nothing
children *= join(attrs[idx][2])
deleteat!(attrs, idx)
end
ii = (x -> x isa Symbol && occursin(Genie.config.html_parser_char_dash, "$x")).(args)
args[ii] .= Symbol.(replace.(string.(args[ii]), Ref(Genie.config.html_parser_char_dash=>"-")))
htmlsourceindent = extractindent!(attrs)
elem = normalize_element(string(elem))
attribs = rstrip(attributes(attrs))
string(
htmlsourceindent, # indentation opening tag
"<", elem, (isempty(attribs) ? "" : " $attribs"), (isempty(args) ? "" : " $(join(args, " "))"), ">", # opening tag
prepare_template(children), (endswith(children, '>') ? htmlsourceindent : ""), # content/children
"</", elem, ">" # closing tag
)
end
function normal_element(elem::Any, attrs::Vector{Pair{Symbol,Any}} = Pair{Symbol,Any}[]) :: HTMLString
normal_element("", string(elem), attrs...)
end
function normal_element(elems::Vector, elem::Any, args = [], attrs...) :: HTMLString
io = IOBuffer()
for e in elems
e === nothing && continue
if isa(e, Vector)
print(io, join(e))
elseif isa(e, Function)
print(io, e())
else
print(io, e)
end
end
normal_element(String(take!(io)), string(elem), args, attrs...)
end
function normal_element(_::Nothing, __::Any) :: HTMLString
""
end
function normal_element(children::Vector{T}, elem::Any, args::Vector{T})::HTMLString where {T}
normal_element(join([(isa(f, Function) ? f() : string(f)) for f in children]), elem, args)
end
function extractindent!(attrs) :: String
indent = if Genie.config.format_html_output
htmlsidx = findfirst(x -> x == :htmlsourceindent, getindex.(attrs, 1))
if htmlsidx !== nothing
indent = Base.parse(Int, attrs[htmlsidx][2])
deleteat!(attrs, htmlsidx)
indent
else
0
end
else
0
end
if indent > 0
'\n' * repeat(Genie.config.format_html_indentation_string, indent)
else
""
end
end
"""
prepare_template(s::String)
prepare_template{T}(v::Vector{T})
Cleans up the template before rendering (ex by removing empty nodes).
"""
function prepare_template(s::String) :: String
s
end
function prepare_template(v::Vector{T})::String where {T}
filter!(v) do (x)
! isa(x, Nothing)
end
join(v)
end
"""
attributes(attrs::Vector{Pair{Symbol,String}} = Vector{Pair{Symbol,String}}()) :: Vector{String}
Parses HTML attributes.
"""
function attributes(attrs::Vector{Pair{Symbol,Any}} = Vector{Pair{Symbol,Any}}()) :: String
a = IOBuffer()
for (k,v) in attrs
v === nothing && continue # skip nothing values
v == "false" && (k in BOOL_ATTRS) && (v = false)
print(a, attrparser(k, v))
end
String(take!(a))
end
function attrparser(k::Symbol, v::Bool) :: String
v ? "$(k |> parseattr) " : ""
end
function attrparser(k::Symbol, v::Union{AbstractString,Symbol}) :: String
v = string(v)
isempty(v) && return attrparser(k, true)
"$(k |> parseattr)=\"$(v)\" "
end
function attrparser(k::Symbol, v::Any) :: String
default_attrparser(k, v)
end
function default_attrparser(k::Symbol, v::Any) :: String
"$(k |> parseattr)=$(v) "
end
"""
parseattr(attr) :: String
Converts Julia keyword arguments to HTML attributes with illegal Julia chars.
"""
function parseattr(attr) :: String
attr = string(attr)
for (k,v) in Genie.config.html_attributes_replacements
attr = replace(attr, k=>v)
end
endswith(attr, Genie.config.html_parser_char_at) && (attr = string("v-on:", attr[1:end-(length(Genie.config.html_parser_char_at))]))
endswith(attr, Genie.config.html_parser_char_column) && (attr = string(":", attr[1:end-(length(Genie.config.html_parser_char_column))]))
attr = replace(attr, Regex(Genie.config.html_parser_char_dash)=>"-")
attr = replace(attr, Regex(Genie.config.html_parser_char_column * Genie.config.html_parser_char_column)=>":")
replace(attr, Regex(Genie.config.html_parser_char_dot)=>".")
end
"""
normalize_element(elem::String)
Cleans up problematic characters or DOM elements.
"""
function normalize_element(elem::String) :: String
replace(elem, Genie.config.html_parser_char_dash=>"-")
end
"""
denormalize_element(elem::String)
Replaces `-` with the char defined to replace dashes, as Julia does not support them in names.
"""
function denormalize_element(elem::String) :: String
uppercase(elem) == elem && (elem = lowercase(elem))
elem = replace(elem, "-"=>Genie.config.html_parser_char_dash)
endswith(elem, "_") ? elem[1:end-1] : elem
end
"""
void_element(elem::String, attrs::Vector{Pair{Symbol,String}} = Vector{Pair{Symbol,String}}()) :: HTMLString
Generates a void HTML element in the form <...>
"""
function void_element(elem::String, args = [], attrs::Vector{Pair{Symbol,Any}} = Pair{Symbol,Any}[]) :: HTMLString
htmlsourceindent = extractindent!(attrs)
attribs = rstrip(attributes(attrs))
string(
htmlsourceindent, # tag indentation
"<", normalize_element(elem), (isempty(attribs) ? "" : " $attribs"), (isempty(args) ? "" : " $(join(args, " "))"), Genie.config.html_parser_close_tag, ">"
)
end
"""
get_template(path::String; partial::Bool = true, context::Module = @__MODULE__, vars...) :: Function
Resolves the inclusion and rendering of a template file
"""
function get_template(path::String; partial::Bool = true, context::Module = @__MODULE__, vars...) :: Function
path, extension = Genie.Renderer.view_file_info(path, SUPPORTED_HTML_OUTPUT_FILE_FORMATS)
f_name = Genie.Renderer.function_name(string(path, partial)) |> Symbol
mod_name = Genie.Renderer.m_name(string(path, partial)) * HTML_FILE_EXT
f_path = joinpath(Genie.config.path_build, Genie.Renderer.BUILD_NAME, mod_name)
f_stale = Genie.Renderer.build_is_stale(path, f_path)
if f_stale || ! isdefined(context, f_name)
if extension in MARKDOWN_FILE_EXT
path = MdHtml.md_to_html(path, context = context)
end
parsingfunction = (extension == HTML_FILE_EXT ? julia_to_julia : html_to_julia)
f_stale && Genie.Renderer.build_module(parsingfunction(path, partial = partial, extension = extension), path, mod_name)
return Base.include(context, joinpath(Genie.config.path_build, Genie.Renderer.BUILD_NAME, mod_name))
end
getfield(context, f_name)
end
"""
Outputs document's doctype.
"""
@inline function doctype(doctype::Symbol = :html) :: ParsedHTMLString
string("<!DOCTYPE $doctype>")
end
"""
Outputs document's doctype.
"""
function doc(html::AbstractString) :: ParsedHTMLString
string(doctype(), html)
end
function doc(doctype::Symbol, html::AbstractString) :: ParsedHTMLString
string(doctype(doctype), html)
end
"""
parseview(data::String; partial = false, context::Module = @__MODULE__) :: Function
Parses a view file, returning a rendering function. If necessary, the function is JIT-compiled, persisted and loaded into memory.
"""
function parseview(data::S; partial = false, context::Module = @__MODULE__, _...)::Function where {S<:AbstractString}
data_hash = hash(data)
path = "Genie_" * string(data_hash)
func_name = Genie.Renderer.function_name(string(data_hash, partial)) |> Symbol
mod_name = Genie.Renderer.m_name(string(path, partial)) * HTML_FILE_EXT
f_path = joinpath(Genie.config.path_build, Genie.Renderer.BUILD_NAME, mod_name)
f_stale = Genie.Renderer.build_is_stale(f_path, f_path)
if f_stale || ! isdefined(context, func_name)
if f_stale
Genie.Renderer.build_module(string_to_julia(data, partial = partial, f_name = func_name), path, mod_name)
end
return Base.include(context, joinpath(Genie.config.path_build, Genie.Renderer.BUILD_NAME, mod_name))
end
getfield(context, func_name)
end
"""
render(data::String; context::Module = @__MODULE__, layout::Union{String,Nothing} = nothing, vars...) :: Function
Renders the string as an HTML view.
"""
function render(data::S; context::Module = @__MODULE__, layout::Union{String,Nothing,Genie.Renderer.FilePath} = nothing, vars...)::Function where {S<:AbstractString}
Genie.Renderer.registervars(; context = context, vars...)
if layout !== nothing
task_local_storage(:__yield, data isa ParsedHTMLString ? () -> data : parseview(data, partial = true, context = context))
parselayout(layout, context)
else
data isa ParsedHTMLString ? () -> [data] : parseview(data, partial = false, context = context)
end
end
"""
render(viewfile::Genie.Renderer.FilePath; layout::Union{Nothing,Genie.Renderer.FilePath} = nothing, context::Module = @__MODULE__, vars...) :: Function
Renders the template file as an HTML view.
"""
function render(viewfile::Genie.Renderer.FilePath; layout::Union{Nothing,Genie.Renderer.FilePath,String} = nothing, context::Module = @__MODULE__, vars...) :: Function
Genie.Renderer.registervars(; context = context, vars...)
if layout !== nothing
task_local_storage(:__yield, get_template(string(viewfile); partial = true, context = context, vars...))
parselayout(layout, context; vars...)
else
get_template(string(viewfile); partial = false, context = context, vars...)
end
end
function parselayout(layout::String, context::Module; vars...)
parseview(layout; partial = false, context = context, vars...)
end
function parselayout(layout::Genie.Renderer.FilePath, context::Module; vars...)
get_template(string(layout); partial = false, context = context, vars...)
end
"""
parsehtml(input::String; partial::Bool = true) :: String
"""
function parsehtml(input::String; partial::Bool = true) :: String
content = replace(input, NBSP_REPLACEMENT)
isempty(content) && return ""
# let's get rid of the annoying xml parser warnings
Logging.with_logger(Logging.SimpleLogger(stdout, Logging.Error)) do
parsehtml(HTMLParser.parsehtml(content).root, partial = partial)
end
end
function Genie.Renderer.render(::Type{MIME"text/html"}, data::S; context::Module = @__MODULE__,
layout::Union{String,Nothing,Genie.Renderer.FilePath} = nothing, vars...)::Genie.Renderer.WebRenderable where {S<:AbstractString}
try
render(data; context = context, layout = layout, vars...) |> Genie.Renderer.WebRenderable
catch ex
isa(ex, KeyError) && Genie.Renderer.changebuilds() # it's a view error so don't reuse them
rethrow(ex)
end
end
function Genie.Renderer.render(::Type{MIME"text/html"}, viewfile::Genie.Renderer.FilePath;
layout::Union{Nothing,Genie.Renderer.FilePath,String} = nothing,
context::Module = @__MODULE__, vars...) :: Genie.Renderer.WebRenderable
try
render(viewfile; layout = layout, context = context, vars...) |> Genie.Renderer.WebRenderable
catch ex
isa(ex, KeyError) && Genie.Renderer.changebuilds() # it's a view error so don't reuse them
rethrow(ex)
end
end
const MAX_FILENAME_LENGTH = 500
function html(resource::Genie.Renderer.ResourcePath, action::Genie.Renderer.ResourcePath;
layout::Union{Genie.Renderer.ResourcePath,Nothing,String,Symbol} = DEFAULT_LAYOUT_FILE,
context::Module = @__MODULE__, status::Int = 200, headers::Genie.Renderer.HTTPHeaders = Genie.Renderer.HTTPHeaders(), vars...) :: Genie.Renderer.HTTP.Response
isa(layout, Symbol) && (layout = string(layout))
html(Genie.Renderer.Path(joinpath(Genie.config.path_resources, string(resource), Renderer.VIEWS_FOLDER, string(action)));
layout = (layout === nothing ? nothing :
isa(layout, String) && length(layout) < MAX_FILENAME_LENGTH ?
Genie.Renderer.Path(joinpath(Genie.config.path_app, LAYOUTS_FOLDER, string(layout))) : layout
),
context = context, status = status, headers = headers, vars...)
end
"""
html(data::String; context::Module = @__MODULE__, status::Int = 200, headers::HTTPHeaders = HTTPHeaders(), layout::Union{String,Nothing} = nothing, vars...) :: HTTP.Response
Parses the `data` input as HTML, returning a HTML HTTP Response.
# Arguments
- `data::String`: the HTML string to be rendered
- `context::Module`: the module in which the variables are evaluated (in order to provide the scope for vars). Usually the controller.
- `status::Int`: status code of the response
- `headers::HTTPHeaders`: HTTP response headers
- `layout::Union{String,Nothing}`: layout file for rendering `data`
# Example
```jldoctest
julia> html("<h1>Welcome \$(vars(:name))</h1>", layout = "<div><% @yield %></div>", name = "Adrian")
HTTP.Messages.Response:
"
HTTP/1.1 200 OK
Content-Type: text/html; charset=utf-8
<html><head></head><body><div><h1>Welcome Adrian</h1>
</div></body></html>"
```
"""
function html(data::String;
context::Module = @__MODULE__,
status::Int = 200,
headers::Genie.Renderer.HTTPHeaders = Genie.Renderer.HTTPHeaders(),
layout::Union{String,Nothing,Genie.Renderer.FilePath,Function} = nothing,
forceparse::Bool = false,
noparse::Bool = false,
vars...) :: Genie.Renderer.HTTP.Response
layout = if isa(layout, Genie.Renderer.FilePath)
read(layout, String)
elseif isa(layout, Function)
layout() |> string
else
layout
end
if (occursin(raw"$", data) || occursin(EMBED_JULIA_OPEN_TAG, data) || layout !== nothing || forceparse) && ! noparse
html(HTMLString(data); context = context, status = status, headers = headers, layout = layout, vars...)
else
html(ParsedHTMLString(data); context, status, headers, layout, vars...)
end
end
function html!(data::Function;
context::Module = @__MODULE__,
status::Int = 200,
headers::Genie.Renderer.HTTPHeaders = Genie.Renderer.HTTPHeaders(),
layout::Union{String,Nothing,Genie.Renderer.FilePath,Function} = nothing,
forceparse::Bool = false,
noparse::Bool = false,
vars...) :: Genie.Renderer.HTTP.Response
view = data()
view isa Vector{ParsedHTMLString} && (view = ParsedHTMLString(view))
html(view isa ParsedHTMLString ? view : join(view); context, status, headers, layout, forceparse, noparse, vars...)
end
function html(data::HTMLString;
context::Module = @__MODULE__,
status::Int = 200, headers::Genie.Renderer.HTTPHeaders = Genie.Renderer.HTTPHeaders(),
layout::Union{String,Nothing,Genie.Renderer.FilePath} = nothing,
forceparse::Bool = false,
noparse::Bool = false,
vars...) :: Genie.Renderer.HTTP.Response
Genie.Renderer.WebRenderable(Genie.Renderer.render(MIME"text/html", data; context = context, layout = layout, vars...), status, headers) |> Genie.Renderer.respond
end
function html(data::ParsedHTMLString;
context::Module = @__MODULE__,
status::Int = 200,
headers::Genie.Renderer.HTTPHeaders = Genie.Renderer.HTTPHeaders(),
layout::Union{String,Nothing,Genie.Renderer.FilePath} = nothing,
forceparse::Bool = false,
noparse::Bool = false,
vars...) :: Genie.Renderer.HTTP.Response
Genie.Renderer.WebRenderable(Genie.Renderer.render(MIME"text/html", data; context = context, layout = layout, vars...), status, headers) |> Genie.Renderer.respond
end
function html!(data::Union{S,Vector{S}};
status::Int = 200,
headers::Genie.Renderer.HTTPHeaders = Genie.Renderer.HTTPHeaders(),
vars...)::Genie.Renderer.HTTP.Response where {S<:AbstractString}
html(ParsedHTMLString(join(data)); headers, vars...)
end
"""
html(md::Markdown.MD; context::Module = @__MODULE__, status::Int = 200, headers::Genie.Renderer.HTTPHeaders = Genie.Renderer.HTTPHeaders(), layout::Union{String,Nothing} = nothing, forceparse::Bool = false, vars...) :: Genie.Renderer.HTTP.Response
Markdown view rendering
"""
function html(md::Markdown.MD;
context::Module = @__MODULE__,
status::Int = 200,
headers::Genie.Renderer.HTTPHeaders = Genie.Renderer.HTTPHeaders(),
layout::Union{String,Nothing,Genie.Renderer.FilePath} = nothing,
forceparse::Bool = false,
vars...) :: Genie.Renderer.HTTP.Response
data = MdHtml.eval_markdown(string(md)) |> Markdown.parse |> Markdown.html
for kv in vars
data = replace(data, ":" * string(kv[1]) => "\$" * string(kv[1]))
end
html(data; context, status, headers, layout, forceparse, vars...)
end
"""
html(viewfile::FilePath; layout::Union{Nothing,FilePath} = nothing,
context::Module = @__MODULE__, status::Int = 200, headers::HTTPHeaders = HTTPHeaders(), vars...) :: HTTP.Response
Parses and renders the HTML `viewfile`, optionally rendering it within the `layout` file. Valid file format is `.html.jl`.
# Arguments
- `viewfile::FilePath`: filesystem path to the view file as a `Renderer.FilePath`, ie `Renderer.filepath("/path/to/file.html.jl")` or `path"/path/to/file.html.jl"`
- `layout::FilePath`: filesystem path to the layout file as a `Renderer.FilePath`, ie `Renderer.FilePath("/path/to/file.html.jl")` or `path"/path/to/file.html.jl"`
- `context::Module`: the module in which the variables are evaluated (in order to provide the scope for vars). Usually the controller.
- `status::Int`: status code of the response
- `headers::HTTPHeaders`: HTTP response headers
"""
function html(viewfile::Genie.Renderer.FilePath;
layout::Union{Nothing,Genie.Renderer.FilePath,String} = nothing,
context::Module = @__MODULE__,
status::Int = 200,
headers::Genie.Renderer.HTTPHeaders = Genie.Renderer.HTTPHeaders(),
vars...) :: Genie.Renderer.HTTP.Response
Genie.Renderer.WebRenderable(Genie.Renderer.render(MIME"text/html", viewfile; layout, context, vars...), status, headers) |> Genie.Renderer.respond
end
"""
safe_attr(attr) :: String
Replaces illegal Julia characters from HTML attributes with safe ones, to be used as keyword arguments.
"""
function safe_attr(attr) :: String
attr = string(attr)
occursin("-", attr) && replace!(attr, "-"=>Genie.config.html_parser_char_dash)
occursin(":", attr) && replace!(attr, ":"=>Genie.config.html_parser_char_column)
occursin("@", attr) && replace!(attr, "@"=>Genie.config.html_parser_char_at)
occursin(".", attr) && replace!(attr, "."=>Genie.config.html_parser_char_dot)
attr
end
function matchbrackets(v::String, ob = "(", cb = ")")
positions = Int[]
substrings = Any[]
counter = 1
for x in v
if x == ob
push!(positions, counter)
end
if x == cb
px = try
pop!(positions)
catch
error("Parse error: possibly unmatched bracket in `$v`")
end
push!(substrings, px:counter)
end
counter += 1
end
substrings |> sort!
end
function matchjuliaexpr(v::String, ob = "(", cb = ")", dollar = true)
substrings = matchbrackets(v, ob, cb)
matches = String[]
for i in substrings
pii = prevind(v, i.start)
if ! dollar || (dollar && pii > 0 && v[pii] == '$')
push!(matches, v[i.start:i.stop])
end
end
matches
end
function parse_attributes!(elem_attributes, io::IOBuffer) :: IOBuffer
attributes = IOBuffer()
attributes_keys = String[]
attributes_values = String[]
for (k,v) in elem_attributes
# x = v
k = string(k) |> lowercase
if isa(v, AbstractString) && occursin("\"", v)
# we need to escape double quotes but only if it's not embedded Julia code
mx = vcat(matchjuliaexpr(v, '(', ')', true), matchjuliaexpr(v, EMBED_JULIA_OPEN_TAG, EMBED_JULIA_CLOSE_TAG, false))
if ! isempty(mx)
index = 1
for value in mx
label = "$(EMBEDDED_JULIA_PLACEHOLDER)_$(index)"
v = replace(v, value => label)
index += 1
end
if occursin("\"", v) # do we still need to escape double quotes?
v = replace(v, "\"" => "\\\"") # we need to escape " as this will be inside julia strings
end
# now we need to put back the embedded Julia
index = 1
for value in mx
label = "$(EMBEDDED_JULIA_PLACEHOLDER)_$(index)"
v = replace(v, label => value)
index += 1
end
elseif occursin("\"", v) # do we still need to escape double quotes?
v = replace(string(v), "\"" => "'") #
end
end
if startswith(k, raw"$") # do not process embedded julia code
print(attributes, k[2:end], ", ") # strip the $, this is rendered directly in Julia code
continue
end
if occursin("-", k) ||
occursin(":", k) ||
occursin("@", k) ||
occursin(".", k) ||
occursin("for", k)
push!(attributes_keys, Symbol(k) |> repr)
v = string(v) |> repr
occursin(raw"\$", v) && (v = replace(v, raw"\$"=>raw"$"))
push!(attributes_values, v)
else
print(attributes, """$k="$v" """, ", ")
end
end
attributes_string = String(take!(attributes))
endswith(attributes_string, ", ") && (attributes_string = attributes_string[1:end-2])
print(io, attributes_string)
! isempty(attributes_string) && ! isempty(attributes_keys) && print(io, ", ")
! isempty(attributes_keys) &&
print(io, "; NamedTuple{($(join(attributes_keys, ", "))$(length(attributes_keys) == 1 ? ", " : ""))}(($(join(attributes_values, ", "))$(length(attributes_keys) == 1 ? ", " : "")))...")
io
end
"""
parsehtml(elem, output; partial = true) :: String
Parses a HTML tree structure into a `string` of Julia code.
"""
function parsehtml(elem::HTMLParser.Node; partial::Bool = true, indent = 0) :: String
io = IOBuffer()
tag_name = denormalize_element(string(elem.name))
invalid_tag = partial && (tag_name == "html" || tag_name == "head" || tag_name == "body")
if tag_name == "script" && haskey(elem, "type") && elem["type"] == "julia/eval"
if ! isempty(HTMLParser.nodes(elem))
print(io, string(HTMLParser.nodes(elem)[1] |> HTMLParser.nodecontent), "\n")
end
else
mdl = isdefined(@__MODULE__, Symbol(tag_name)) ? string(@__MODULE__, ".") : ""
invalid_tag || print(io, "$mdl$(tag_name)(" )
if (elem.type == HTMLParser.ELEMENT_NODE)
attrs_dict = Dict{String,Any}()
for a in HTMLParser.attributes(elem)
try
attrs_dict[a.name] = elem[a.name]
catch ex
attr = string(a)
parts = split(attr, '=')
if length(parts) >= 2
val = attr[(findfirst(c->c.=='=', attr)+1):end]
(startswith(val, '"') || startswith(val, "'")) && (val = val[2:end])
(endswith(val, '"') || endswith(val, "'")) && (val = val[1:end-1])
attrs_dict[strip(parts[1])] = val
elseif length(parts) == 1
attrs_dict[strip(parts[1])] = strip(parts[1])
else
string(a)
end
end
end
! invalid_tag && Genie.config.format_html_output && (attrs_dict["htmlsourceindent"] = indent)
io = parse_attributes!(attrs_dict, io)
end
invalid_tag || print(io, " )")
inner = ""
if ! isempty(HTMLParser.nodes(elem))
children_count = HTMLParser.countnodes(elem)
invalid_tag ? print(io, "") : print(io, " do;[\n")
idx = 0
indent += 1
for child in HTMLParser.nodes(elem)
idx += 1
inner *= (child.type == HTMLParser.TEXT_NODE || child.type == HTMLParser.CDATA_SECTION_NODE ||
child.type == HTMLParser.COMMENT_NODE) ?
parsenode(child) :
parsehtml(child; partial = partial, indent = indent)
if idx < children_count
if ( child.type == HTMLParser.TEXT_NODE || child.type == HTMLParser.CDATA_SECTION_NODE ||
child.type == HTMLParser.COMMENT_NODE) ||
( child.type == HTMLParser.ELEMENT_NODE &&
( ! haskey(elem, "type") ||
( haskey(elem, "type") && (elem["type"] == "julia/eval") ) ) )
isempty(inner) || (inner = string(inner, "\n"))
end
end
end
if ! isempty(inner)
endswith(inner, "\n\n") && (inner = inner[1:end-2])
print(io, inner)
invalid_tag || print(io, " ; ")
end
invalid_tag ? print(io, "") : print(io, " ]end\n")
end
end
String(take!(io))
end
function parsehtml(::Nothing; kwargs...) :: String
""
end
function parsenode(elem::HTMLParser.Node; partial::Bool = true) :: String
content = elem |> HTMLParser.nodecontent
endswith(content, "\"") && (content *= Char(0x0))
content = replace(content, NBSP_REPLACEMENT[2]=>NBSP_REPLACEMENT[1])
isempty(strip(content)) && return ""
elem.type == HTMLParser.COMMENT_NODE && return string("\"\"\"<!-- $(content) -->\"\"\"")
string("\"\"\"$(content)\"\"\"")
end
"""
html_to_julia(file_path::String; partial = true) :: String
Converts a HTML document to Julia code.
"""
function html_to_julia(file_path::String; partial = true, extension = TEMPLATE_EXT) :: String
to_julia(file_path, parse_template; partial = partial, extension = extension)
end
"""
string_to_julia(content::String; partial = true, f_name::Union{Symbol,Nothing} = nothing, prepend = "") :: String
Converts string view data to Julia code
"""
function string_to_julia(content::S; partial = true, f_name::Union{Symbol,Nothing} = nothing, prepend::String = "\n")::String where {S<:AbstractString}
to_julia(content, parse_string, partial = partial, f_name = f_name, prepend = prepend)
end
function julia_to_julia(file_path::String; partial = true, extension = HTML_FILE_EXT) :: String
to_julia(read_template_file(file_path; extension = extension), nothing; partial = partial, extension = extension)
end
"""
to_julia(input::String, f::Function; partial = true, f_name::Union{Symbol,Nothing} = nothing, prepend = "") :: String
Converts an input file to Julia code
"""
function to_julia(input::S, f::Union{Function,Nothing};
partial = true, f_name::Union{Symbol,Nothing} = nothing,
prepend::String = "\n", extension = TEMPLATE_EXT)::ParsedHTMLString where {S<:AbstractString}
input = replace(input, raw"\$" => raw"\\\$") # escape $ signs -- in code, $ must be escaped twice, \\\$ is the correct way -- then we preserve the escape into the resulting HTML
f_name = (f_name === nothing) ? Genie.Renderer.function_name(string(input, partial)) : f_name
string("function $(f_name)(; $(Genie.Renderer.injectkwvars())) \n",
"
[
",
prepend,
(partial ? "" : "\nGenie.Renderer.Html.doctype() \n"),
f !== nothing ? f(input; partial = partial, extension = extension) : input,
"
]
end
")
end
"""
partial(path::String; context::Module = @__MODULE__, vars...) :: String
Renders (includes) a view partial within a larger view or layout file.
"""
function partial(path::String; context::Module = @__MODULE__, kwvars...) :: String
for (k,v) in kwvars
vars()[k] = v
end
template(path, partial = true, context = context)
end
function partial(path::Genie.Renderer.FilePath; context::Module = @__MODULE__, kwvars...)
partial(string(path); context = context, kwvars...)
end
function partial(resource::Genie.Renderer.ResourcePath, view::Genie.Renderer.ResourcePath, args...; kwargs...)
partial(joinpath(Genie.config.path_resources, string(resource), Renderer.VIEWS_FOLDER, string(view)), args...; kwargs...)
end
"""
template(path::String; partial::Bool = true, context::Module = @__MODULE__, vars...) :: String
Renders a template file.
"""
function template(path::String; partial::Bool = true, context::Module = @__MODULE__, vars...) :: String
try
get_template(path; partial = partial, context = context, vars...)() |> join
catch ex
if isa(ex, MethodError) && (string(ex.f) == "get_template" || startswith(string(ex.f), "func_"))
Base.invokelatest(get_template(path; partial = partial, context = context, vars...)) |> join
else
rethrow(ex)
end
end
end
"""
read_template_file(file_path::String) :: String
Reads `file_path` template from disk.
"""
function read_template_file(file_path::String; extension = TEMPLATE_EXT) :: String
io = IOBuffer()
open(file_path) do f
for line in eachline(f)
isempty(strip(line)) && continue
print(io, parse_embed_tags(line), "\n")
end
end
String(take!(io))
end
"""
parse_template(file_path::String; partial = true) :: String
Parses a HTML file into Julia code.
"""
function parse_template(file_path::S; partial::Bool = true, extension = TEMPLATE_EXT)::ParsedHTMLString where {S<:AbstractString}
parse(read_template_file(file_path; extension = extension)::String; partial = partial)
end
"""
parse_string(data::String; partial = true) :: String
Parses a HTML string into Julia code.
"""
function parse_string(data::S; partial::Bool = true, extension = TEMPLATE_EXT)::ParsedHTMLString where {S<:AbstractString}
parse(parse_embed_tags(data), partial = partial)
end
function parse(input::S; partial::Bool = true)::ParsedHTMLString where {S<:AbstractString}
parsehtml(input, partial = partial)
end
function parse_embed_tags(code::S)::String where {S<:AbstractString}
replace(
replace(code, EMBED_JULIA_OPEN_TAG=>"""<script type="julia/eval">"""),
EMBED_JULIA_CLOSE_TAG=>"""</script>""")
end
"""
register_elements() :: Nothing
Generated functions that represent Julia functions definitions corresponding to HTML elements.
"""
function register_elements(; context = @__MODULE__) :: Nothing
for elem in NORMAL_ELEMENTS
register_normal_element(elem)
end
for elem in VOID_ELEMENTS
register_void_element(elem)
end
for elem in SVG_ELEMENTS
register_normal_element(elem)
end
nothing
end
"""
register_element(elem::Union{Symbol,String}, elem_type::Union{Symbol,String} = :normal; context = @__MODULE__) :: Nothing
Generates a Julia function representing an HTML element.
"""
function register_element(elem::Union{Symbol,String}, elem_type::Union{Symbol,String} = :normal; context = @__MODULE__) :: Nothing
elem = string(elem)
occursin("-", elem) && (elem = denormalize_element(elem))
elem_type == :normal ? register_normal_element(elem) : register_void_element(elem)
end
"""
register_normal_element(elem::Union{Symbol,String}; context = @__MODULE__) :: Nothing
Generates a Julia function representing a "normal" HTML element: that is an element with a closing tag, <tag>...</tag>
"""
function register_normal_element(elem::Union{Symbol,String}; context = @__MODULE__) :: Nothing
Core.eval(context, """
function $elem(f::Function, args...; attrs...) :: ParsedHTMLString
\"\"\"\$(normal_element(f, "$(string(elem))", [args...], Pair{Symbol,Any}[attrs...]))\"\"\"
end
""" |> Meta.parse)
Core.eval(context, """
function $elem(children::Union{String,Vector{String}} = "", args...; attrs...) :: ParsedHTMLString
\"\"\"\$(normal_element(children, "$(string(elem))", [args...], Pair{Symbol,Any}[attrs...]))\"\"\"
end
""" |> Meta.parse)
Core.eval(context, """
function $elem(children::Any, args...; attrs...) :: ParsedHTMLString
\"\"\"\$(normal_element(string(children), "$(string(elem))", [args...], Pair{Symbol,Any}[attrs...]))\"\"\"
end
""" |> Meta.parse)
Core.eval(context, """
function $elem(children::Vector{Any}, args...; attrs...) :: ParsedHTMLString
\"\"\"\$(normal_element([string(c) for c in children], "$(string(elem))", [args...], Pair{Symbol,Any}[attrs...]))\"\"\"
end
""" |> Meta.parse)
elem in NON_EXPORTED || Core.eval(context, "export $elem" |> Meta.parse)
nothing
end
"""
register_void_element(elem::Union{Symbol,String}; context::Module = @__MODULE__) :: Nothing
Generates a Julia function representing a "void" HTML element: that is an element without a closing tag, <tag />
"""
function register_void_element(elem::Union{Symbol,String}; context::Module = @__MODULE__) :: Nothing
Core.eval(context, """
function $elem(args...; attrs...) :: HTMLString
\"\"\"\$(void_element("$(string(elem))", [args...], Pair{Symbol,Any}[attrs...]))\"\"\"
end
""" |> Meta.parse)
elem in NON_EXPORTED || Core.eval(context, "export $elem" |> Meta.parse)
nothing
end
"""
for_each(f::Function, v)
Iterates over the `v` Vector and applies function `f` for each element.
The results of each iteration are concatenated and the final string is returned.
"""
function for_each(f::Function, v)
[f(x) for x in v] |> join
end
"""
iif(f::Function, v)
Conditional rendering of a block of HTML code.
"""
function iif(f::Function, condition::Bool)
if condition
f() |> join
else
""
end
end
"""
collection(template::Function, collection::Vector{T})::String where {T}
Creates a view fragment by repeateadly applying a function to each element of the collection.
"""
function collection(template::Function, collection::Vector{T})::String where {T}
for_each(collection) do item
template(item) |> string
end
end
### === ###
### EXCEPTIONS ###
"""
Genie.Router.error(error_message::String, ::Type{MIME"text/html"}, ::Val{500}; error_info::String = "") :: HTTP.Response
Returns a 500 error response as an HTML doc.
"""
function Genie.Router.error(error_message::String, ::Type{MIME"text/html"}, ::Val{500}; error_info::String = "") :: HTTP.Response
serve_error_file(500, error_message, error_info = error_info)
end
"""
Genie.Router.error(error_message::String, ::Type{MIME"text/html"}, ::Val{404}; error_info::String = "") :: HTTP.Response
Returns a 404 error response as an HTML doc.
"""
function Genie.Router.error(error_message::String, ::Type{MIME"text/html"}, ::Val{404}; error_info::String = "") :: HTTP.Response
serve_error_file(404, error_message, error_info = error_info)
end
"""
Genie.Router.error(error_code::Int, error_message::String, ::Type{MIME"text/html"}; error_info::String = "") :: HTTP.Response
Returns an error response as an HTML doc.
"""
function Genie.Router.error(error_code::Int, error_message::String, ::Type{MIME"text/html"}; error_info::String = "") :: HTTP.Response
serve_error_file(error_code, error_message, error_info = error_info)
end
"""
serve_error_file(error_code::Int, error_message::String = "", params::Dict{Symbol,Any} = Dict{Symbol,Any}()) :: Response
Serves the error file correspoding to `error_code` and current environment.
"""
function serve_error_file(error_code::Int, error_message::String = ""; error_info::String = "") :: HTTP.Response
page_code = error_code in [404, 500] ? "$error_code" : "xxx"
try
error_page_file = isfile(joinpath(Genie.config.server_document_root, "error-$page_code.html")) ?
joinpath(Genie.config.server_document_root, "error-$page_code.html") :
joinpath(@__DIR__, "..", "..", "files", "static", "error-$page_code.html")
error_page = open(error_page_file) do f
read(f, String)
end
if error_code == 500
error_page = replace(error_page, "<error_description/>"=>split(error_message, "\n")[1])
error_message = if Genie.Configuration.isdev()
"""$("#" ^ 25) ERROR STACKTRACE $("#" ^ 25)\n$error_message $("\n" ^ 3)""" *
"""$("#" ^ 25) REQUEST PARAMS $("#" ^ 25)\n$(Millboard.table(Genie.Router.params())) $("\n" ^ 3)""" *
"""$("#" ^ 25) ROUTES $("#" ^ 25)\n$(Millboard.table(Genie.Router.named_routes() |> Dict)) $("\n" ^ 3)""" *
"""$("#" ^ 25) JULIA ENV $("#" ^ 25)\n$ENV $("\n" ^ 1)"""
else
""
end
error_page = replace(error_page, "<error_message/>"=>escapeHTML(error_message))
elseif error_code == 404
error_page = replace(error_page, "<error_message/>"=>error_message)
else
error_page = replace(replace(error_page, "<error_message/>"=>error_message), "<error_info/>"=>error_info)
end
HTTP.Response(error_code, ["Content-Type"=>"text/html"], body = error_page)
catch ex
@error ex
HTTP.Response(error_code, ["Content-Type"=>"text/html"], body = "Error $page_code: $error_message")
end
end
### === ###
"""
@yield
Outputs the rendering of the view within the template.
"""
macro yield()
:(view!()() |> join)
end
macro yield(value)
:(view!($value))
end
function view!()
haskey(task_local_storage(), :__yield) ? task_local_storage(:__yield) : task_local_storage(:__yield, String[])
end
function view!(value)
task_local_storage(:__yield, value)
end
function el(; vars...)
OrderedCollections.LittleDict(vars)
end
register_elements() # this doesn't work on __init__
end
| Genie | https://github.com/GenieFramework/Genie.jl.git |
|
[
"MIT"
] | 5.30.6 | 376aa3d800f4da32d232f2d9a1685e34e2911b4a | code | 5813 | module Js
import Logging, HTTP, Reexport
Reexport.@reexport using Genie
Reexport.@reexport using Genie.Renderer
const JS_FILE_EXT = ".jl"
const TEMPLATE_EXT = ".jl.js"
const SUPPORTED_JS_OUTPUT_FILE_FORMATS = [TEMPLATE_EXT]
const JSString = String
const NBSP_REPLACEMENT = (" "=>"!!nbsp;;")
export js
function get_template(path::String; context::Module = @__MODULE__, vars...) :: Function
orig_path = path
path, extension = Genie.Renderer.view_file_info(path, SUPPORTED_JS_OUTPUT_FILE_FORMATS)
if ! isfile(path)
error_message = length(SUPPORTED_JS_OUTPUT_FILE_FORMATS) == 1 ?
"""JS file "$orig_path$(SUPPORTED_JS_OUTPUT_FILE_FORMATS[1])" does not exist""" :
"""JS file "$orig_path" with extensions $SUPPORTED_JS_OUTPUT_FILE_FORMATS does not exist"""
error(error_message)
end
f_name = Genie.Renderer.function_name(path) |> Symbol
mod_name = Genie.Renderer.m_name(path) * ".jl"
f_path = joinpath(Genie.config.path_build, Genie.Renderer.BUILD_NAME, mod_name)
f_stale = Genie.Renderer.build_is_stale(path, f_path)
if f_stale || ! isdefined(context, f_name)
f_stale && Genie.Renderer.build_module(to_js(read(path, String), extension = extension), path, mod_name)
return Base.include(context, joinpath(Genie.config.path_build, Genie.Renderer.BUILD_NAME, mod_name))
end
getfield(context, f_name)
end
function to_js(data::String; prepend = "\n", extension = TEMPLATE_EXT) :: String
output = string("function $(Genie.Renderer.function_name(data))($(Genie.Renderer.injectkwvars())) :: String \n", prepend)
output *= if extension == TEMPLATE_EXT
"\"\"\"
$data
\"\"\""
elseif extension == JS_FILE_EXT
data
else
error("Unsuported template extension $extension")
end
string(output, "\nend \n")
end
function render(data::String; context::Module = @__MODULE__, vars...) :: Function
Genie.Renderer.registervars(; context = context, vars...)
data_hash = hash(data)
path = "Genie_" * string(data_hash)
func_name = Genie.Renderer.function_name(string(data_hash)) |> Symbol
mod_name = Genie.Renderer.m_name(path) * ".jl"
f_path = joinpath(Genie.config.path_build, Genie.Renderer.BUILD_NAME, mod_name)
f_stale = Genie.Renderer.build_is_stale(f_path, f_path)
if f_stale || ! isdefined(context, func_name)
f_stale && Genie.Renderer.build_module(to_js(data), path, mod_name)
return Base.include(context, joinpath(Genie.config.path_build, Genie.Renderer.BUILD_NAME, mod_name))
end
getfield(context, func_name)
end
function render(viewfile::Genie.Renderer.FilePath; context::Module = @__MODULE__, vars...) :: Function
Genie.Renderer.registervars(; context = context, vars...)
get_template(string(viewfile); partial = false, context = context, vars...)
end
function render(::Type{MIME"application/javascript"}, data::String; context::Module = @__MODULE__, vars...) :: Genie.Renderer.WebRenderable
try
Genie.Renderer.WebRenderable(render(data; context = context, vars...), :javascript)
catch ex
isa(ex, KeyError) && Genie.Renderer.changebuilds() # it's a view error so don't reuse them
rethrow(ex)
end
end
function render(::Type{MIME"application/javascript"}, viewfile::Genie.Renderer.FilePath; context::Module = @__MODULE__, vars...) :: Genie.Renderer.WebRenderable
try
Genie.Renderer.WebRenderable(render(viewfile; context = context, vars...), :javascript)
catch ex
isa(ex, KeyError) && Genie.Renderer.changebuilds() # it's a view error so don't reuse them
rethrow(ex)
end
end
function js(data::String; context::Module = @__MODULE__, status::Int = 200,
headers::Genie.Renderer.HTTPHeaders = Genie.Renderer.HTTPHeaders("Content-Type" => Genie.Renderer.CONTENT_TYPES[:javascript]),
forceparse::Bool = false, noparse::Bool = false, vars...) :: Genie.Renderer.HTTP.Response
if (occursin(raw"$", data) || forceparse) && ! noparse
Genie.Renderer.WebRenderable(render(MIME"application/javascript", data; context = context, vars...), :javascript, status, headers) |> Genie.Renderer.respond
else
js!(data; status, headers) |> Genie.Renderer.respond
end
end
function js!(data::S; status::Int = 200,
headers::Genie.Renderer.HTTPHeaders = Genie.Renderer.HTTPHeaders("Content-Type" => Genie.Renderer.CONTENT_TYPES[:javascript]))::Genie.Renderer.HTTP.Response where {S<:AbstractString}
Genie.Renderer.WebRenderable(data, :javascript, status, headers) |> Genie.Renderer.respond
end
function js(viewfile::Genie.Renderer.FilePath; context::Module = @__MODULE__, status::Int = 200,
headers::Genie.Renderer.HTTPHeaders = Genie.Renderer.HTTPHeaders("Content-Type" => Genie.Renderer.CONTENT_TYPES[:javascript]), vars...) :: Genie.Renderer.HTTP.Response
Genie.Renderer.WebRenderable(render(MIME"application/javascript", viewfile; context = context, vars...), :javascript, status, headers) |> Genie.Renderer.respond
end
### === ###
### EXCEPTIONS ###
function Genie.Router.error(error_message::String, ::Type{MIME"application/javascript"}, ::Val{500}; error_info::String = "") :: HTTP.Response
HTTP.Response(Dict("error" => "500 Internal Error - $error_message", "info" => error_info), status = 500) |> js
end
function Genie.Router.error(error_message::String, ::Type{MIME"application/javascript"}, ::Val{404}; error_info::String = "") :: HTTP.Response
HTTP.Response(Dict("error" => "404 Not Found - $error_message", "info" => error_info), status = 404) |> js
end
function Genie.Router.error(error_code::Int, error_message::String, ::Type{MIME"application/javascript"}; error_info::String = "") :: HTTP.Response
HTTP.Response(Dict("error" => "$error_code Error - $error_message", "info" => error_info), status = error_code) |> js
end
end
| Genie | https://github.com/GenieFramework/Genie.jl.git |
|
[
"MIT"
] | 5.30.6 | 376aa3d800f4da32d232f2d9a1685e34e2911b4a | code | 5013 | module Json
import JSON3, HTTP, Reexport
Reexport.@reexport using Genie
Reexport.@reexport using Genie.Renderer
module JSONParser
import JSON3
const parse = JSON3.read
const json = JSON3.write
# ugly but necessary
JSON3.StructTypes.StructType(::T) where {T<:DataType} = JSON3.StructTypes.Struct()
end
using .JSONParser
const JSON = JSONParser
const JSON_FILE_EXT = ".json.jl"
const JSONString = String
export JSONString, json, parse, JSONException
Base.@kwdef mutable struct JSONException <: Exception
status::Int
message::String
end
function render(viewfile::Genie.Renderer.FilePath; context::Module = @__MODULE__, vars...) :: Function
Genie.Renderer.registervars(; context = context, vars...)
path = viewfile |> string
partial = true
f_name = Genie.Renderer.function_name(string(path, partial)) |> Symbol
mod_name = Genie.Renderer.m_name(string(path, partial)) * ".jl"
f_path = joinpath(Genie.config.path_build, Genie.Renderer.BUILD_NAME, mod_name)
f_stale = Genie.Renderer.build_is_stale(path, f_path)
if f_stale || ! isdefined(context, f_name)
Genie.Renderer.build_module(
Genie.Renderer.Html.to_julia(read(path, String), nothing, partial = partial, f_name = f_name),
path,
mod_name,
output_path = false
)
Base.include(context, f_path)
end
() -> try
getfield(context, f_name)() |> first
catch ex
if isa(ex, MethodError) && string(ex.f) == string(f_name)
Base.invokelatest(getfield(context, f_name)) |> first
else
rethrow(ex)
end
end |> JSONParser.json
end
function render(data::Any; forceparse::Bool = false, context::Module = @__MODULE__) :: Function
() -> JSONParser.json(data)
end
function Genie.Renderer.render(::Type{MIME"application/json"}, datafile::Genie.Renderer.FilePath; context::Module = @__MODULE__, vars...) :: Genie.Renderer.WebRenderable
Genie.Renderer.WebRenderable(render(datafile; context = context, vars...), :json)
end
function Genie.Renderer.render(::Type{MIME"application/json"}, data::String; context::Module = @__MODULE__, vars...) :: Genie.Renderer.WebRenderable
Genie.Renderer.WebRenderable(render(data; context = context, vars...), :json)
end
function Genie.Renderer.render(::Type{MIME"application/json"}, data::Any; context::Module = @__MODULE__, vars...) :: Genie.Renderer.WebRenderable
Genie.Renderer.WebRenderable(render(data), :json)
end
### json API
function json(resource::Genie.Renderer.ResourcePath, action::Genie.Renderer.ResourcePath; context::Module = @__MODULE__,
status::Int = 200, headers::Genie.Renderer.HTTPHeaders = Genie.Renderer.HTTPHeaders(), vars...) :: Genie.Renderer.HTTP.Response
json(Genie.Renderer.Path(joinpath(Genie.config.path_resources, string(resource), Renderer.VIEWS_FOLDER, string(action) * JSON_FILE_EXT));
context = context, status = status, headers = headers, vars...)
end
function json(datafile::Genie.Renderer.FilePath; context::Module = @__MODULE__,
status::Int = 200, headers::Genie.Renderer.HTTPHeaders = Genie.Renderer.HTTPHeaders(), vars...) :: Genie.Renderer.HTTP.Response
Genie.Renderer.WebRenderable(Genie.Renderer.render(MIME"application/json", datafile; context = context, vars...), :json, status, headers) |> Genie.Renderer.respond
end
function json(data::String; context::Module = @__MODULE__,
status::Int = 200, headers::Genie.Renderer.HTTPHeaders = Genie.Renderer.HTTPHeaders(), vars...) :: Genie.Renderer.HTTP.Response
Genie.Renderer.WebRenderable(Genie.Renderer.render(MIME"application/json", data; context = context, vars...), :json, status, headers) |> Genie.Renderer.respond
end
function json(data::Any; status::Int = 200, headers::Genie.Renderer.HTTPHeaders = Genie.Renderer.HTTPHeaders()) :: Genie.Renderer.HTTP.Response
Genie.Renderer.WebRenderable(Genie.Renderer.render(MIME"application/json", data), :json, status, headers) |> Genie.Renderer.respond
end
function json(exception::JSONException; headers::Genie.Renderer.HTTPHeaders = Genie.Renderer.HTTPHeaders()) :: Genie.Renderer.HTTP.Response
Genie.Renderer.WebRenderable(Genie.Renderer.render(MIME"application/json", exception.message), :json, exception.status, headers) |> Genie.Renderer.respond
end
### === ###
### EXCEPTIONS ###
function Genie.Router.error(error_message::String, ::Type{MIME"application/json"}, ::Val{500}; error_info::String = "") :: HTTP.Response
json(Dict("error" => "500 Internal Error - $error_message", "info" => error_info), status = 500)
end
function Genie.Router.error(error_message::String, ::Type{MIME"application/json"}, ::Val{404}; error_info::String = "") :: HTTP.Response
json(Dict("error" => "404 Not Found - $error_message", "info" => error_info), status = 404)
end
function Genie.Router.error(error_code::Int, error_message::String, ::Type{MIME"application/json"}; error_info::String = "") :: HTTP.Response
json(Dict("error" => "$error_code Error - $error_message", "info" => error_info), status = error_code)
end
end | Genie | https://github.com/GenieFramework/Genie.jl.git |
|
[
"MIT"
] | 5.30.6 | 376aa3d800f4da32d232f2d9a1685e34e2911b4a | code | 1573 | module MdHtml
import Reexport, Markdown, YAML
Reexport.@reexport using Genie
Reexport.@reexport using Genie.Renderer
const MD_SEPARATOR_START = "---"
const MD_SEPARATOR_END = "---"
function md_to_html(path::String; context::Module = @__MODULE__) :: String
Genie.Renderer.build_module(
"""
<head></head>
<body>
$(Genie.Renderer.Html.EMBED_JULIA_OPEN_TAG)
Base.include_string(context,
\"\"\"
\\\"\\\"\\\"
$(eval_markdown(read(path, String), context = context))
\\\"\\\"\\\"
\"\"\") |> Markdown.parse |> Markdown.html
$(Genie.Renderer.Html.EMBED_JULIA_CLOSE_TAG)
</body>
""",
joinpath(Genie.config.path_build, Genie.Renderer.BUILD_NAME, path),
string(hash(path), ".html"),
output_path = false
)
end
"""
eval_markdown(md::String; context::Module = @__MODULE__) :: String
Converts the mardown `md` to HTML view code.
"""
function eval_markdown(md::String; context::Module = @__MODULE__) :: String
if startswith(md, string(MD_SEPARATOR_START))
close_sep_pos = findfirst(MD_SEPARATOR_END, md[length(MD_SEPARATOR_START)+1:end])
metadata = md[length(MD_SEPARATOR_START)+1:close_sep_pos[end]] |> YAML.load
isa(metadata, Dict) || (@warn "\nFound Markdown YAML metadata but it did not result in a `Dict` \n
Please check your markdown metadata \n$metadata")
try
for (k,v) in metadata
vars()[Symbol(k)] = v
end
catch ex
@error ex
end
md = replace((md[close_sep_pos[end]+length(MD_SEPARATOR_END)+1:end] |> strip), "\"\"\""=>"\\\"\\\"\\\"")
end
md
end
end | Genie | https://github.com/GenieFramework/Genie.jl.git |
|
[
"MIT"
] | 5.30.6 | 376aa3d800f4da32d232f2d9a1685e34e2911b4a | code | 197 | cd(@__DIR__)
using Pkg
using Test, TestSetExtensions, SafeTestsets, Logging
using Genie
Logging.global_logger(NullLogger())
@testset ExtendedTestSet "Genie tests" begin
@includetests ARGS
end | Genie | https://github.com/GenieFramework/Genie.jl.git |
|
[
"MIT"
] | 5.30.6 | 376aa3d800f4da32d232f2d9a1685e34e2911b4a | code | 1088 | @safetestset "App Config" begin
@safetestset "Custom server startup overwrites app config" begin
using Genie
@test Genie.config.server_port == 8000
@test Genie.config.server_host == "127.0.0.1"
@test Genie.config.websockets_port == nothing
@test Genie.config.run_as_server == false
server = up(9000, "0.0.0.0")
@test Genie.config.server_port == 9000
@test Genie.config.server_host == "0.0.0.0"
@test Genie.config.websockets_port == 9000
@test Genie.config.run_as_server == false
down()
sleep(1)
server = nothing
server = up(9000, "0.0.0.0", ws_port = 9999)
@test Genie.config.server_port == 9000
@test Genie.config.server_host == "0.0.0.0"
@test Genie.config.websockets_port == 9999
@test Genie.config.run_as_server == false
down()
sleep(1)
server = nothing
Genie.config.server_port = 8000
Genie.config.server_host = "127.0.0.1"
Genie.config.websockets_port = nothing
Genie.config.run_as_server = false
down()
sleep(1)
server = nothing
end;
end;
| Genie | https://github.com/GenieFramework/Genie.jl.git |
|
[
"MIT"
] | 5.30.6 | 376aa3d800f4da32d232f2d9a1685e34e2911b4a | code | 1328 | @safetestset "Server functionality" begin
@safetestset "Start/stop servers" begin
using Genie
using Genie.Server
Genie.Server.down!()
empty!(Genie.Server.SERVERS)
servers = Genie.Server.up()
@test isopen(servers.webserver)
servers = Genie.Server.down(servers)
sleep(1)
@test !isopen(servers.webserver)
@test !isopen(Genie.Server.SERVERS[1].webserver)
servers = Genie.Server.down!()
empty!(Genie.Server.SERVERS)
servers = Genie.Server.up(; open_browser = false)
Genie.Server.down(servers; webserver = false)
@test isopen(servers.webserver)
servers = Genie.Server.down(servers; webserver = true)
sleep(1)
@test !isopen(servers.webserver)
@test !isopen(Genie.Server.SERVERS[1].webserver)
servers = nothing
end;
@safetestset "Update config when custom startup args" begin
using Genie
using Genie.Server
port = Genie.config.server_port
ws_port = Genie.config.websockets_port
server = Genie.Server.up(port+1_000; ws_port = ws_port+1_000, open_browser = false)
@test Genie.config.server_port == port+1_000
@test Genie.config.websockets_port == ws_port+1_000
Genie.config.server_port = port
Genie.config.websockets_port = ws_port
Genie.Server.down()
sleep(1)
server = nothing
end;
end; | Genie | https://github.com/GenieFramework/Genie.jl.git |
|
[
"MIT"
] | 5.30.6 | 376aa3d800f4da32d232f2d9a1685e34e2911b4a | code | 2266 | @safetestset "Assets functionality" begin
@safetestset "Assets paths" begin
using Genie, Genie.Assets
@test include_asset(:css, "foo") == "/assets/css/foo.css"
@test include_asset(:js, "foo") == "/assets/js/foo.js"
@test css_asset("foo") == css("foo") == "/assets/css/foo.css"
@test js_asset("foo") == js("foo") == "/assets/js/foo.js"
end;
@safetestset "Expose settings" begin
using Genie, Genie.Assets
@test js_settings() == "window.Genie = {};\nGenie.Settings = {\"websockets_exposed_port\":window.location.port,\"server_host\":\"127.0.0.1\",\"webchannels_autosubscribe\":true,\"webchannels_reconnect_delay\":500,\"webchannels_subscription_trails\":4,\"env\":\"dev\",\"webchannels_eval_command\":\">eval:\",\"websockets_host\":\"127.0.0.1\",\"webthreads_js_file\":\"webthreads.js\",\"webchannels_base64_marker\":\"base64:\",\"webchannels_unsubscribe_channel\":\"unsubscribe\",\"webthreads_default_route\":\"____\",\"webchannels_subscribe_channel\":\"subscribe\",\"server_port\":8000,\"webchannels_keepalive_frequency\":30000,\"websockets_exposed_host\":window.location.hostname,\"webchannels_connection_attempts\":10,\"base_path\":\"\",\"websockets_protocol\":window.location.protocol.replace('http', 'ws'),\"webthreads_pull_route\":\"pull\",\"webchannels_default_route\":\"____\",\"webchannels_server_gone_alert_timeout\":10000,\"webchannels_timeout\":1000,\"webthreads_push_route\":\"push\",\"websockets_port\":8000,\"websockets_base_path\":\"\"};\n"
end
@safetestset "Embedded assets" begin
using Genie, Genie.Assets
@test Assets.channels()[1:18] == "window.Genie = {};"
@test channels_script()[1:27] == "<script>\nwindow.Genie = {};"
@test channels_support() == "<script src=\"/genie.jl/$(Genie.Assets.package_version("Genie"))/assets/js/channels.js\"></script>"
@test Genie.Router.routes()[1].path == "/genie.jl/$(Genie.Assets.package_version("Genie"))/assets/js/channels.js"
@test Genie.Router.channels()[1].path == "/$(Genie.config.webchannels_default_route)/unsubscribe"
@test Genie.Router.channels()[2].path == "/$(Genie.config.webchannels_default_route)/subscribe"
@test favicon_support() == "<link rel=\"icon\" type=\"image/x-icon\" href=\"/favicon.ico\" />"
end
end;
| Genie | https://github.com/GenieFramework/Genie.jl.git |
|
[
"MIT"
] | 5.30.6 | 376aa3d800f4da32d232f2d9a1685e34e2911b4a | code | 617 | @safetestset "Assets config" begin
using Genie, Genie.Assets
@test Genie.Assets.AssetsConfig().host == Genie.config.base_path
@test Genie.Assets.AssetsConfig().package == "Genie.jl"
@test Genie.Assets.AssetsConfig().version == Genie.Assets.package_version("Genie.jl")
@test Genie.Assets.AssetsConfig().host == Genie.Assets.assets_config.host
@test Genie.Assets.AssetsConfig().package == Genie.Assets.assets_config.package
@test Genie.Assets.AssetsConfig().version == Genie.Assets.assets_config.version
Genie.Assets.assets_config!(host = "foo")
@test Genie.Assets.assets_config.host == "foo"
end;
| Genie | https://github.com/GenieFramework/Genie.jl.git |
|
[
"MIT"
] | 5.30.6 | 376aa3d800f4da32d232f2d9a1685e34e2911b4a | code | 2068 | @safetestset "Assets functionality" begin
@safetestset "Assets paths" begin
using Genie, Genie.Assets
Genie.config.base_path = "/proxy/8000"
@test Genie.Assets.asset_path("s.js") == "/proxy/8000/assets/js/s.js"
@test Genie.Assets.asset_path("s.js", host = "") == "/assets/js/s.js"
@test Genie.Assets.asset_path("s.js", host = "/") == "/assets/js/s.js"
@test Genie.Assets.asset_path("s.js", host = "//") == "/assets/js/s.js"
@test Genie.Assets.asset_path("s.js", path = "/") == "/proxy/8000/assets/js/s.js"
@test Genie.Assets.asset_path("s.js", path = "//") == "/proxy/8000/assets/js/s.js"
@test Genie.Assets.asset_path("s.js", path = "foo") == "/proxy/8000/assets/js/foo/s.js"
@test Genie.Assets.asset_path("s.js", path = "foo/bar") == "/proxy/8000/assets/js/foo/bar/s.js"
@test Genie.Assets.asset_path("s.js", path = "foo/bar/baz") == "/proxy/8000/assets/js/foo/bar/baz/s.js"
@test Genie.Assets.asset_path("s.js", path = "/foo/bar/baz") == "/proxy/8000/assets/js/foo/bar/baz/s.js"
@test Genie.Assets.asset_path("s.js", path = "/foo/bar/baz/") == "/proxy/8000/assets/js/foo/bar/baz/s.js"
@test Genie.Assets.asset_path("s.js", host = "abc", path = "/foo/bar/baz/") == "/abc/assets/js/foo/bar/baz/s.js"
@test Genie.Assets.asset_path("s.js", host = "abc/def", path = "/foo/bar/baz/") == "/abc/def/assets/js/foo/bar/baz/s.js"
@test Genie.Assets.asset_path("s.js", host = "/abc/def", path = "/foo/bar/baz/") == "/abc/def/assets/js/foo/bar/baz/s.js"
@test Genie.Assets.asset_path("s.js", host = "/abc/def/", path = "/foo/bar/baz/") == "/abc/def/assets/js/foo/bar/baz/s.js"
Genie.config.base_path = "/proxy/8000/"
@test Genie.Assets.asset_path("s.js", path = "/foo/bar/baz/") == "/proxy/8000/assets/js/foo/bar/baz/s.js"
Genie.config.base_path = "proxy/8000"
@test Genie.Assets.asset_path("s.js", path = "/foo/bar/baz/") == "/proxy/8000/assets/js/foo/bar/baz/s.js"
@test Genie.Assets.asset_path("s.js") == "/proxy/8000/assets/js/s.js"
Genie.config.base_path = ""
end;
end;
| Genie | https://github.com/GenieFramework/Genie.jl.git |
|
[
"MIT"
] | 5.30.6 | 376aa3d800f4da32d232f2d9a1685e34e2911b4a | code | 338 | @safetestset "SVG API support in Renderer.Html" begin
@safetestset "SVG API is available" begin
using Genie
using Genie.Renderer.Html
import Genie.Util: fws
@test svg() |> fws == "<svg></svg>" |> fws
@test_throws UndefVarError clippath()
@test clipPath() |> fws == "<clipPath></clipPath>" |> fws
end;
end; | Genie | https://github.com/GenieFramework/Genie.jl.git |
|
[
"MIT"
] | 5.30.6 | 376aa3d800f4da32d232f2d9a1685e34e2911b4a | code | 2231 | @safetestset "Advanced rendering" begin
@safetestset "for_each renders local variables" begin
using Genie
using Genie.Renderer.Html
import Genie.Util: fws
view = raw"""
<ol>
<% for_each(["a", "b", "c"]) do letter %>
<li>$(letter)</li>
<% end %>
</ol>"""
r = html(view)
@test String(r.body) |> fws ==
"<!DOCTYPE html><html><body><ol><li>a</li><li>b</li><li>c</li></ol></body></html>" |> fws
end;
# TODO: this test doesn't seem to check the right things - and most likely was passing by accident
# disabled for now -- to review
# @safetestset "for_each can not access module variables" begin
# using Genie
# using Genie.Renderer.Html
# x = 100
# view = raw"""
# <ol>
# <% for_each(["a", "b", "c"]) do letter %>
# <li>$(letter) = $x</li>
# <% end %>
# </ol>"""
# @test_throws UndefVarError html(view)
# end;
@safetestset "for_each can access view variables" begin
using Genie
using Genie.Renderer.Html
import Genie.Util: fws
view = raw"""
<ol>
<% for_each(["a", "b", "c"]) do letter %>
<li>$(letter) = $(vars(:x))</li>
<% end %>
</ol>"""
r = html(view, x = 100)
@test String(r.body) |> fws ==
"<!DOCTYPE html><html><body><ol><li>a = 100</li><li>b = 100</li><li>c = 100</li></ol></body></html>" |> fws
end;
@safetestset "for_each can access context variables" begin
using Genie
using Genie.Renderer.Html
import Genie.Util: fws
view = raw"""
<ol>
<% for_each(["a", "b", "c"]) do letter %>
<li>$(letter) = $x</li>
<% end %>
</ol>"""
r = html(view, context = @__MODULE__, x = 200)
@test String(r.body) |> fws ==
"<!DOCTYPE html><html><body><ol><li>a = 200</li><li>b = 200</li><li>c = 200</li></ol></body></html>" |> fws
end;
@safetestset "non registered tags are rendered" begin
using Genie
using Genie.Renderer.Html
import Genie.Util: fws
view = raw"""
<div>
<custom-tag>
<p>hello $name</p>
</custom-tag>
</div>
"""
r = html(view, name = "Adrian")
@test String(r.body) |> fws ==
"<!DOCTYPE html><html><body><div><custom-tag><p>hello Adrian</p></custom-tag></div></body></html>" |> fws
end;
end; | Genie | https://github.com/GenieFramework/Genie.jl.git |
|
[
"MIT"
] | 5.30.6 | 376aa3d800f4da32d232f2d9a1685e34e2911b4a | code | 673 | @safetestset "<select> test" begin
using Genie
using Genie.Renderer.Html
import Genie.Util: fws
@test html(filepath("formview.jl.html")).body |> String |> fws ==
"""<!DOCTYPE html><html><body><form method="POST" enctype="multipart/form-data" action="/new">
<div class="form-group"><label for="exampleFormControlSelect1">Example select</label>
<select class="form-control" id="exampleFormControlSelect1"><option>1</option><option>2</option>
<option>3</option><option>4</option><option>5</option></select></div>
<button class="btn btn-primary" type="submit">Submit</button></form></body></html>""" |> fws
end | Genie | https://github.com/GenieFramework/Genie.jl.git |
|
[
"MIT"
] | 5.30.6 | 376aa3d800f4da32d232f2d9a1685e34e2911b4a | code | 2620 | @safetestset "Escaping quotes" begin
@safetestset "Double quoted arguments" begin
using Genie, Genie.Renderer
using Genie.Renderer.Html
@test Html.html("""<body onload="alert('Hello');"><p>Good morning</p></body>""").body |> String ==
"""<body onload="alert('Hello');"><p>Good morning</p></body>"""
@test Html.html("""<body onload="alert(\'Hello\');"><p>Good morning</p></body>""").body |> String ==
"""<body onload="alert('Hello');"><p>Good morning</p></body>"""
@test Html.html("""<body onload="alert("Hello");"><p>Good morning</p></body>""").body |> String ==
"""<body onload="alert("Hello");"><p>Good morning</p></body>"""
@test Html.html("""<body onload="alert(\"Hello\");"><p>Good morning</p></body>""").body |> String ==
"""<body onload="alert("Hello");"><p>Good morning</p></body>"""
end
@safetestset "Single quoted arguments" begin
using Genie, Genie.Renderer
using Genie.Renderer.Html
@test Html.html("""<body onload='alert(\'Hello\');'><p>Good morning</p></body>""").body |> String ==
"""<body onload='alert('Hello');'><p>Good morning</p></body>"""
@test Html.html("""<body onload='alert("Hello");'><p>Good morning</p></body>""").body |> String ==
"""<body onload='alert("Hello");'><p>Good morning</p></body>"""
@test Html.html("""<body onload='alert(\"Hello\");'><p>Good morning</p></body>""").body |> String ==
"""<body onload='alert("Hello");'><p>Good morning</p></body>"""
end
@safetestset "Arguments in templates" begin
using Genie, Genie.Renderer
using Genie.Renderer.Html
import Genie.Util: fws
@test Html.html(filepath("views/argsencoded1.jl.html")).body |> String |> fws ==
"""<!DOCTYPE html><html><body><p onclick="alert('Hello');">Greetings</p></body></html>""" |> fws
@test_throws LoadError Html.html(filepath("views/argsencoded2.jl.html")).body |> String ==
"""<!DOCTYPE html><html><body><p onclick="alert("Hello");">Greetings</p></body></html>"""
@test Html.html(filepath("views/argsencoded3.jl.html")).body |> String |> fws ==
"""<!DOCTYPE html><html><body><p onclick="alert('Hello');">Greetings</p></body></html>""" |> fws
@test Html.html(filepath("views/argsencoded1.jl.html"), layout=filepath("views/layoutargsencoding.jl.html")).body |> String |> fws ==
"""<!DOCTYPE html><html><body><div style="width: '100px'"><h1>Layout header</h1><section>
<p onclick="alert('Hello');">Greetings</p></section><footer><h4>Layout footer</h4></footer></div></body>
</html>""" |> fws
end
end | Genie | https://github.com/GenieFramework/Genie.jl.git |
|
[
"MIT"
] | 5.30.6 | 376aa3d800f4da32d232f2d9a1685e34e2911b4a | code | 799 | @safetestset "Parsing of route arguments with types" begin
using Genie, Dates, HTTP
Base.convert(::Type{Float64}, s::AbstractString) = parse(Float64, s)
Base.convert(::Type{Int}, s::AbstractString) = parse(Int, s)
Base.convert(::Type{Dates.Date}, s::AbstractString) = Date(s)
route("/getparams/:s::String/:f::Float64/:i::Int/:d::Date", context = @__MODULE__) do
"s = $(params(:s)) / f = $(params(:f)) / i = $(params(:i)) / $(params(:d))"
end
port = nothing
port = rand(8500:8900)
server = up(port; open_browser = false)
response = HTTP.get("http://localhost:$port/getparams/foo/23.43/18/2019-02-15")
@test response.status == 200
@test String(response.body) == "s = foo / f = 23.43 / i = 18 / 2019-02-15"
down()
sleep(1)
server = nothing
port = nothing
end | Genie | https://github.com/GenieFramework/Genie.jl.git |
|
[
"MIT"
] | 5.30.6 | 376aa3d800f4da32d232f2d9a1685e34e2911b4a | code | 471 | @safetestset "Assets rendering" begin
@safetestset "Embedded assets" begin
using Genie
using Genie.Renderer
using Genie.Assets
@test (Assets.js_settings() *
Assets.embedded(Genie.Assets.asset_file(cwd=normpath(joinpath(@__DIR__, "..")), type="js", file="channels"))) ==
Assets.channels()
@test Assets.channels()[1:18] == "window.Genie = {};"
@test Assets.channels_script()[1:28] == "<script>\nwindow.Genie = {};\n"
end;
end; | Genie | https://github.com/GenieFramework/Genie.jl.git |
|
[
"MIT"
] | 5.30.6 | 376aa3d800f4da32d232f2d9a1685e34e2911b4a | code | 4017 | @safetestset "basic rendering" begin
using Genie
using Genie.Renderer.Html
using Genie.Requests
import Genie.Util: fws
content = "abcd"
content2 = "efgh"
content3 = raw"\$hello\$"
@testset "Basic rendering" begin
r = Requests.HTTP.Response()
@testset "Empty string" begin
r = html("")
@test String(r.body) == ""
end;
# @testset "Empty string force parse" begin
# @test_throws ArgumentError html("", forceparse = true)
# end;
@testset "String no spaces" begin
r = html(content)
@test String(r.body) == "$content"
end;
@testset "String with backspace dollar" begin
r = html(content3)
@test String(r.body) |> fws == raw"<!DOCTYPE html><html><body><p>\$hello\$</p></body></html>" |> fws
end
@testset "String no spaces force parse" begin
r = html(content, forceparse = true)
@test String(r.body) |> fws == "<!DOCTYPE html><html><body><p>abcd</p></body></html>" |> fws
end;
@testset "String with 2 spaces" begin
r = html(" $content ")
@test String(r.body) == " abcd "
end;
@testset "String with 2 spaces force parse" begin
r = html(" $content ", forceparse = true)
@test String(r.body) |> fws == "<!DOCTYPE html><html><body><p>abcd </p></body></html>" |> fws
end;
@testset "String with " begin
r = html(" ")
@test String(r.body) == " "
end;
@testset "String with force parse" begin
r = html(" ", forceparse = true)
@test String(r.body) |> fws == "<!DOCTYPE html><html><body><p> </p></body></html>" |> fws
end;
@testset "String with 2 and 2 spaces" begin
r = html(" $content ")
@test String(r.body) == " abcd "
end;
@testset "String with 2 and 2 spaces force parse" begin
r = html(" $content ", forceparse = true)
@test String(r.body) |> fws == "<!DOCTYPE html><html><body><p> abcd </p></body></html>" |> fws
end;
@testset "String with newline" begin
r = html("$content \n $content2")
@test String(r.body) == "abcd \n efgh"
end;
@testset "String with newline force parse" begin
r = html("$content \n $content2", forceparse = true)
@test String(r.body) |> fws == "<!DOCTYPE html><html><body><p>abcd \n efgh</p></body></html>" |> fws
end;
@testset "String with quotes" begin
r = html("He said \"wow!\"")
@test String(r.body) == "He said \"wow!\""
end;
@testset "String with quotes force parse" begin
r = html("He said \"wow!\"", forceparse = true)
@test String(r.body) |> fws == "<!DOCTYPE html><html><body><p>He said \"wow!\"\0</p></body></html>" |> fws
end;
@testset "String with quotes" begin
r = html(""" "" """)
@test String(r.body) == " \"\" "
end;
@testset "String with quotes force parse" begin
r = html(""" "" """, forceparse = true)
@test String(r.body) |> fws == "<!DOCTYPE html><html><body><p>\"\" </p></body></html>" |> fws
end;
@testset "String with quotes" begin
r = html("\"\"")
@test String(r.body) == "\"\""
end;
@testset "String with quotes force parse" begin
r = html("\"\"", forceparse = true)
@test String(r.body) |> fws == "<!DOCTYPE html><html><body><p>\"\"\0</p></body></html>" |> fws
end;
@testset "String with interpolated vars" begin
r = html("$(reverse(content))")
@test String(r.body) == "dcba"
end;
@testset "String with interpolated vars force parse" begin
r = html("$(reverse(content))", forceparse = true)
@test String(r.body) |> fws == "<!DOCTYPE html><html><body><p>dcba</p></body></html>" |> fws
end;
@test r.status == 200
@test r.headers[1]["Content-Type"] == "text/html; charset=utf-8"
end;
end | Genie | https://github.com/GenieFramework/Genie.jl.git |
|
[
"MIT"
] | 5.30.6 | 376aa3d800f4da32d232f2d9a1685e34e2911b4a | code | 11334 | @safetestset "Content negotiation" begin
@safetestset "Response type matches request type" begin
@safetestset "Not found matches request type -- Content-Type -- custom HTML Genie page" begin
using Genie
using HTTP
port = nothing
port = rand(8500:8900)
server = up(port; open_browser = false)
response = HTTP.request("GET", "http://127.0.0.1:$port/notexisting", ["Content-Type" => "text/html"], status_exception = false)
@test response.status == 404
@test occursin("Sorry, we can not find", String(response.body)) == true
@test Dict(response.headers)["Content-Type"] == "text/html"
response = HTTP.request("GET", "http://127.0.0.1:$port/notexisting", ["COnTeNT-TyPe" => "text/html"], status_exception = false)
@test response.status == 404
@test occursin("Sorry, we can not find", String(response.body)) == true
@test Dict(response.headers)["Content-Type"] == "text/html"
down()
sleep(1)
server = nothing
port = nothing
end
@safetestset "Not found matches request type -- Accept -- custom HTML Genie page" begin
using Genie
using HTTP
port = nothing
port = rand(8500:8900)
server = up(port; open_browser = false)
response = HTTP.request("GET", "http://127.0.0.1:$port/notexisting", ["Accept" => "text/html"], status_exception = false)
@test response.status == 404
@test occursin("Sorry, we can not find", String(response.body)) == true
@test Dict(response.headers)["Content-Type"] == "text/html"
response = HTTP.request("GET", "http://127.0.0.1:$port/notexisting", ["AcCePt" => "text/html"], status_exception = false)
@test response.status == 404
@test occursin("Sorry, we can not find", String(response.body)) == true
@test Dict(response.headers)["Content-Type"] == "text/html"
down()
sleep(1)
server = nothing
port = nothing
end
@safetestset "Not found matches request type -- Content-Type -- custom JSON Genie handler" begin
using Genie
using HTTP
port = nothing
port = rand(8500:8900)
server = up(port; open_browser = false)
response = HTTP.request("GET", "http://127.0.0.1:$port/notexisting", ["Content-Type" => "application/json"], status_exception = false)
@test response.status == 404
@test occursin("404 Not Found", String(response.body)) == true
@test Dict(response.headers)["Content-Type"] == "application/json; charset=utf-8"
response = HTTP.request("GET", "http://127.0.0.1:$port/notexisting", ["CoNtEnt-TyPe" => "application/json"], status_exception = false)
@test response.status == 404
@test occursin("404 Not Found", String(response.body)) == true
@test Dict(response.headers)["Content-Type"] == "application/json; charset=utf-8"
down()
sleep(1)
server = nothing
port = nothing
end
@safetestset "Not found matches request type -- Accept -- custom JSON Genie handler" begin
using Genie
using HTTP
port = nothing
port = rand(8500:8900)
server = up(port; open_browser = false)
response = HTTP.request("GET", "http://127.0.0.1:$port/notexisting", ["Accept" => "application/json"], status_exception = false)
@test response.status == 404
@test occursin("404 Not Found", String(response.body)) == true
@test Dict(response.headers)["Content-Type"] == "application/json; charset=utf-8"
response = HTTP.request("GET", "http://127.0.0.1:$port/notexisting", ["acCepT" => "application/json"], status_exception = false)
@test response.status == 404
@test occursin("404 Not Found", String(response.body)) == true
@test Dict(response.headers)["Content-Type"] == "application/json; charset=utf-8"
down()
sleep(1)
server = nothing
port = nothing
end
@safetestset "Not found matches request type -- Content-Type -- custom text Genie handler" begin
using Genie
using HTTP
port = nothing
port = rand(8500:8900)
server = up(port; open_browser = false)
response = HTTP.request("GET", "http://127.0.0.1:$port/notexisting", ["Content-Type" => "text/plain"], status_exception = false)
@test response.status == 404
@test occursin("404 Not Found", String(response.body)) == true
@test Dict(response.headers)["Content-Type"] == "text/plain"
response = HTTP.request("GET", "http://127.0.0.1:$port/notexisting", ["conTeNT-tYPE" => "text/plain"], status_exception = false)
@test response.status == 404
@test occursin("404 Not Found", String(response.body)) == true
@test Dict(response.headers)["Content-Type"] == "text/plain"
down()
sleep(1)
server = nothing
port = nothing
end
end;
@safetestset "Not found matches request type -- Content-Type -- unknown content type get same response" begin
using Genie
using HTTP
port = nothing
port = rand(8500:8900)
server = up(port; open_browser = false)
response = HTTP.request("GET", "http://127.0.0.1:$port/notexisting", ["Content-Type" => "text/csv"], status_exception = false)
@test response.status == 404
@test occursin("404 Not Found", String(response.body)) == true
@test Dict(response.headers)["Content-Type"] == "text/csv"
response = HTTP.request("GET", "http://127.0.0.1:$port/notexisting", ["conTeNT-tYPE" => "text/csv"], status_exception = false)
@test response.status == 404
@test occursin("404 Not Found", String(response.body)) == true
@test Dict(response.headers)["Content-Type"] == "text/csv"
down()
sleep(1)
server = nothing
port = nothing
end
@safetestset "Not found matches request type -- Accept -- unknown content type get same response" begin
using Genie
using HTTP
port = nothing
port = rand(8500:8900)
server = up(port; open_browser = false)
response = HTTP.request("GET", "http://127.0.0.1:$port/notexisting", ["Accept" => "text/csv"], status_exception = false)
@test response.status == 404
@test occursin("404 Not Found", String(response.body)) == true
@test Dict(response.headers)["Content-Type"] == "text/csv"
response = HTTP.request("GET", "http://127.0.0.1:$port/notexisting", ["accEPT" => "text/csv"], status_exception = false)
@test response.status == 404
@test occursin("404 Not Found", String(response.body)) == true
@test Dict(response.headers)["Content-Type"] == "text/csv"
down()
sleep(1)
server = nothing
port = nothing
end
@safetestset "Custom error handler for unknown types" begin
using Genie
using HTTP
port = nothing
port = rand(8500:8900)
server = up(port; open_browser = false)
response = HTTP.request("GET", "http://127.0.0.1:$port/notexisting", ["Content-Type" => "text/csv"], status_exception = false)
@test response.status == 404
@test occursin("404 Not Found", String(response.body)) == true
@test Dict(response.headers)["Content-Type"] == "text/csv"
Genie.Router.error(error_message::String, ::Type{MIME"text/csv"}, ::Val{404}; error_info = "") = begin
HTTP.Response(401, ["Content-Type" => "text/csv"], body = "Search CSV and you shall find")
end
response = HTTP.request("GET", "http://127.0.0.1:$port/notexisting", ["conTeNT-tYPE" => "text/csv"], status_exception = false)
@test response.status == 401
@test occursin("Search CSV and you shall find", String(response.body)) == true
@test Dict(response.headers)["Content-Type"] == "text/csv"
response = HTTP.request("GET", "http://127.0.0.1:$port/notexisting", ["accept" => "text/csv"], status_exception = false)
@test response.status == 401
@test occursin("Search CSV and you shall find", String(response.body)) == true
@test Dict(response.headers)["Content-Type"] == "text/csv"
down()
sleep(1)
server = nothing
port = nothing
end
@safetestset "Custom error handler for known types" begin
using Genie
using HTTP
port = nothing
port = rand(8500:8900)
server = up(port; open_browser = false)
response = HTTP.request("GET", "http://127.0.0.1:$port/notexisting", ["Content-Type" => "application/json"], status_exception = false)
@test response.status == 404
@test occursin("404 Not Found", String(response.body)) == true
@test Dict(response.headers)["Content-Type"] == "application/json; charset=utf-8"
Genie.Router.error(error_message::String, ::Type{MIME"application/json"}, ::Val{404}; error_info = "") = begin
HTTP.Response(401, ["Content-Type" => "application/json"], body = "Search CSV and you shall find")
end
response = HTTP.request("GET", "http://127.0.0.1:$port/notexisting", ["conTeNT-tYPE" => "application/json"], status_exception = false)
@test response.status == 401
@test occursin("Search CSV and you shall find", String(response.body)) == true
@test Dict(response.headers)["Content-Type"] == "application/json"
response = HTTP.request("GET", "http://127.0.0.1:$port/notexisting", ["accept" => "application/json"], status_exception = false)
@test response.status == 401
@test occursin("Search CSV and you shall find", String(response.body)) == true
@test Dict(response.headers)["Content-Type"] == "application/json"
down()
sleep(1)
server = nothing
port = nothing
end
@safetestset "Order of accept preferences" begin
using Genie
using HTTP
port = nothing
port = rand(8500:8900)
server = up(port; open_browser = false)
response = HTTP.request("GET", "http://127.0.0.1:$port/notexisting", ["Accept" => "text/html, text/plain, application/json, text/csv"], status_exception = false)
@test Dict(response.headers)["Content-Type"] == "text/html"
response = HTTP.request("GET", "http://127.0.0.1:$port/notexisting", ["Accept" => "text/plain, application/json, text/csv, text/html"], status_exception = false)
@test Dict(response.headers)["Content-Type"] == "text/plain"
response = HTTP.request("GET", "http://127.0.0.1:$port/notexisting", ["Accept" => "application/json, text/csv, text/html, text/plain"], status_exception = false)
@test Dict(response.headers)["Content-Type"] == "application/json"
response = HTTP.request("GET", "http://127.0.0.1:$port/notexisting", ["Accept" => "text/csv, text/html, text/plain, application/json"], status_exception = false)
@test Dict(response.headers)["Content-Type"] == "text/html"
response = HTTP.request("GET", "http://127.0.0.1:$port/notexisting", ["Accept" => "text/csv, text/plain, application/json, text/html"], status_exception = false)
@test Dict(response.headers)["Content-Type"] == "text/plain"
response = HTTP.request("GET", "http://127.0.0.1:$port/notexisting", ["Accept" => "text/csv, application/json, text/html, text/plain"], status_exception = false)
@test Dict(response.headers)["Content-Type"] == "application/json"
response = HTTP.request("GET", "http://127.0.0.1:$port/notexisting", ["Accept" => "text/csv"], status_exception = false)
@test Dict(response.headers)["Content-Type"] == "text/csv"
down()
sleep(1)
server = nothing
port = nothing
end
end; | Genie | https://github.com/GenieFramework/Genie.jl.git |
|
[
"MIT"
] | 5.30.6 | 376aa3d800f4da32d232f2d9a1685e34e2911b4a | code | 846 | @safetestset "Content negotiation hooks" begin
using Genie, HTTP
custom_message = "Got you!"
original_message = "Hello!"
function hook(req, res, params)
if haskey(params, :ROUTE)
params[:ROUTE].action = () -> custom_message
end
req, res, params
end
route("/") do
original_message
end
port = nothing
port = rand(8500:8900)
server = up(port)
response = HTTP.request("GET", "http://localhost:$port")
@test response.status == 200
@test String(response.body) == original_message
push!(Genie.Router.content_negotiation_hooks, hook)
response = HTTP.request("GET", "http://localhost:$port")
@test response.status == 200
@test String(response.body) == custom_message
pop!(Genie.Router.content_negotiation_hooks)
Genie.Server.down!()
sleep(1)
server = nothing
port = nothing
end | Genie | https://github.com/GenieFramework/Genie.jl.git |
|
[
"MIT"
] | 5.30.6 | 376aa3d800f4da32d232f2d9a1685e34e2911b4a | code | 4546 | @safetestset "Files vars rendering" begin
using Genie
using Genie.Renderer.Html, Genie.Requests
using Random
import Base.Filesystem: mktemp
import Genie.Util: fws
greeting = "Welcome"
name = "Genie"
function htmlviewfile_withvars()
raw"
<h1>$(vars(:greeting))</h1>
<div>
<p>This is a $(vars(:name)) test</p>
</div>
<hr />
"
end
function htmltemplatefile_withvars()
raw"
<!DOCTYPE HTML>
<html>
<head>
<title>$(vars(:name)) test</title>
</head>
<body>
<div class=\"template\">
<% @yield %>
</div>
<footer>Just a footer</footer>
</body>
</html>
"
end
viewfile = mktemp()
write(viewfile[2], htmlviewfile_withvars())
close(viewfile[2])
templatefile = mktemp()
write(templatefile[2], htmltemplatefile_withvars())
close(templatefile[2])
@testset "HTML rendering with view files" begin
using Genie
using Genie.Renderer.Html, Genie.Requests
r = Requests.HTTP.Response()
@testset "HTML rendering with view file no layout with vars" begin
r = html(Genie.Renderer.Path(viewfile[1]), greeting = greeting, name = Genie)
@test String(r.body) |> fws ==
"<!DOCTYPE html><html><body><h1>$greeting</h1><div><p>This is a $name test</p></div>
<hr$(Genie.config.html_parser_close_tag)></body></html>" |> fws
end;
@testset "HTML rendering with view file and layout with vars" begin
r = html(Genie.Renderer.Path(viewfile[1]), layout = Genie.Renderer.Path(templatefile[1]), greeting = greeting, name = Genie)
@test String(r.body) |> fws ==
"<!DOCTYPE html><html><head><title>$name test</title></head><body><div class=\"template\">
<h1>$greeting</h1><div><p>This is a $name test</p></div><hr$(Genie.config.html_parser_close_tag)></div>
<footer>Just a footer</footer></body></html>" |> fws
end;
@test r.status == 200
@test r.headers[1]["Content-Type"] == "text/html; charset=utf-8"
@testset "HTML rendering with view file no layout with vars custom headers" begin
r = html(Genie.Renderer.Path(viewfile[1]), headers = Genie.Renderer.HTTPHeaders("Cache-Control" => "no-cache"), greeting = greeting, name = Genie)
@test String(r.body) |> fws ==
"<!DOCTYPE html><html><body><h1>$greeting</h1><div><p>This is a $name test</p></div>
<hr$(Genie.config.html_parser_close_tag)></body></html>" |> fws
@test r.headers[1]["Cache-Control"] == "no-cache"
end;
@testset "HTML rendering with view file and layout with vars custom headers" begin
r = html(Genie.Renderer.Path(viewfile[1]), layout = Genie.Renderer.Path(templatefile[1]), headers = Genie.Renderer.HTTPHeaders("Cache-Control" => "no-cache"), greeting = greeting, name = Genie)
@test String(r.body) |> fws ==
"<!DOCTYPE html><html><head><title>$name test</title></head><body><div class=\"template\">
<h1>$greeting</h1><div><p>This is a $name test</p></div><hr$(Genie.config.html_parser_close_tag)></div>
<footer>Just a footer</footer></body></html>" |> fws
@test r.headers[1]["Cache-Control"] == "no-cache"
end;
@testset "HTML rendering with view file no layout with vars custom headers custom status" begin
r = html(Genie.Renderer.Path(viewfile[1]), headers = Genie.Renderer.HTTPHeaders("Cache-Control" => "no-cache"), status = 500, greeting = greeting, name = Genie)
@test String(r.body) |> fws ==
"<!DOCTYPE html><html><body><h1>$greeting</h1><div><p>This is a $name test</p></div>
<hr$(Genie.config.html_parser_close_tag)></body></html>" |> fws
@test r.headers[1]["Cache-Control"] == "no-cache"
@test r.status == 500
end;
@testset "HTML rendering with view file and layout with vars custom headers custom status" begin
r = html(Genie.Renderer.Path(viewfile[1]), layout = Genie.Renderer.Path(templatefile[1]),
headers = Genie.Renderer.HTTPHeaders("Cache-Control" => "no-cache"), status = 404, greeting = greeting, name = Genie)
@test String(r.body) |> fws ==
"<!DOCTYPE html><html><head><title>$name test</title></head><body><div class=\"template\">
<h1>$greeting</h1><div><p>This is a $name test</p></div><hr$(Genie.config.html_parser_close_tag)></div>
<footer>Just a footer</footer></body></html>" |> fws
@test r.headers[1]["Cache-Control"] == "no-cache"
@test r.status == 404
end;
end;
end; | Genie | https://github.com/GenieFramework/Genie.jl.git |
|
[
"MIT"
] | 5.30.6 | 376aa3d800f4da32d232f2d9a1685e34e2911b4a | code | 3846 | #=
@safetestset "Create new app" begin
testdir = pwd()
using Pkg
@safetestset "Do not autostart app" begin
using Genie
workdir = Base.Filesystem.mktempdir()
cd(workdir)
Genie.Generator.newapp(workdir, autostart = false, testmode = true)
@test true === true
end;
# cd(testdir)
# Pkg.activate(".")
# @safetestset "Autostart app" begin
# using Genie
# workdir = Base.Filesystem.mktempdir()
# Genie.Generator.newapp(workdir, autostart = true, testmode = true)
# @test true === true
# end;
cd(testdir)
Pkg.activate(".")
@safetestset "Microstack file structure" begin
using Genie
workdir = Base.Filesystem.mktempdir()
cd(workdir)
Genie.Generator.newapp(workdir, autostart = false, testmode = true)
@test sort(readdir(workdir)) == sort([".gitattributes", ".gitignore", "Manifest.toml", "Project.toml", "bin",
"bootstrap.jl", "config", "genie.jl", "public", "routes.jl", "src"])
@test readdir(joinpath(workdir, Genie.config.path_initializers)) == ["autoload.jl", "converters.jl", "logging.jl", "ssl.jl"]
# TODO: add test for files in /src /config /public and /bin
end;
cd(testdir)
Pkg.activate(".")
@safetestset "DB support file structure" begin
using Genie
workdir = Base.Filesystem.mktempdir()
cd(workdir)
Genie.Generator.newapp(workdir, autostart = false, dbsupport = true, testmode = true)
@test sort(readdir(workdir)) == sort([".gitattributes", ".gitignore", "Manifest.toml", "Project.toml", "bin",
"bootstrap.jl", "config", "db", "genie.jl", "public", "routes.jl", "src"])
@test sort(readdir(joinpath(workdir, Genie.config.path_db))) == sort(["connection.yml", "migrations", "seeds"])
@test sort(readdir(joinpath(workdir, Genie.config.path_initializers))) == sort(["autoload.jl", "converters.jl", "logging.jl", "searchlight.jl", "ssl.jl"])
end;
cd(testdir)
Pkg.activate(".")
@safetestset "MVC support file structure" begin
using Genie
workdir = Base.Filesystem.mktempdir()
cd(workdir)
Genie.Generator.newapp(workdir, autostart = false, mvcsupport = true, testmode = true)
@test sort(readdir(workdir)) == sort([".gitattributes", ".gitignore", "Manifest.toml", "Project.toml", "app", "bin", "bootstrap.jl", "config", "genie.jl", "public", "routes.jl", "src"])
@test sort(readdir(joinpath(workdir, Genie.config.path_app))) == sort(["helpers", "layouts", "resources"])
@test sort(readdir(joinpath(workdir, Genie.config.path_initializers))) == sort(["autoload.jl", "converters.jl", "logging.jl", "ssl.jl"])
end;
cd(testdir)
Pkg.activate(".")
@safetestset "New controller" begin
using Genie
workdir = Base.Filesystem.mktempdir()
cd(workdir)
Genie.Generator.newcontroller("Yazoo")
@test isdir(joinpath(workdir, "app", "resources", "yazoo")) == true
@test isfile(joinpath(workdir, "app", "resources", "yazoo", "YazooController.jl")) == true
end;
cd(testdir)
Pkg.activate(".")
@safetestset "New resource" begin
using Genie
workdir = Base.Filesystem.mktempdir()
cd(workdir)
Genie.newresource("Kazoo")
@test isdir(joinpath(workdir, "app", "resources", "kazoo")) == true
@test isfile(joinpath(workdir, "app", "resources", "kazoo", "KazooController.jl")) == true
end;
cd(testdir)
Pkg.activate(".")
@safetestset "New task" begin
using Genie, Genie.Exceptions
workdir = Base.Filesystem.mktempdir()
cd(workdir)
Genie.newtask("Vavoom")
@test isdir(joinpath(workdir, "tasks")) == true
@test isfile(joinpath(workdir, "tasks", "VavoomTask.jl")) == true
@test_throws FileExistsException Genie.newtask("Vavoom")
end;
cd(testdir)
Pkg.activate(".")
end;
=# | Genie | https://github.com/GenieFramework/Genie.jl.git |
|
[
"MIT"
] | 5.30.6 | 376aa3d800f4da32d232f2d9a1685e34e2911b4a | code | 1146 | @safetestset "Setting and getting headers" begin
using Genie, HTTP
using Genie.Router, Genie.Responses
route("/headers") do
setheaders("X-Foo-Bar" => "Baz")
"OK"
end
route("/headers", method = OPTIONS) do
setheaders(["X-Foo-Bar" => "Bazinga", "Access-Control-Allow-Methods" => "GET, POST, OPTIONS"])
setstatus(200)
"OOKK"
end
port = nothing
port = rand(8500:8900)
up(port; open_browser = false, verbose = true)
response = HTTP.request("GET", "http://localhost:$port/headers") # unhandled, should get default response
@test response.status == 200
@test String(response.body) == "OK"
@test Dict(response.headers)["X-Foo-Bar"] == "Baz"
@test get(Dict(response.headers), "Access-Control-Allow-Methods", nothing) == nothing
response = HTTP.request("OPTIONS", "http://localhost:$port/headers") # handled
@test response.status == 200
@test String(response.body) == "OOKK"
@test Dict(response.headers)["X-Foo-Bar"] == "Bazinga"
@test get(Dict(response.headers), "Access-Control-Allow-Methods", nothing) == "GET, POST, OPTIONS"
down()
sleep(1)
server = nothing
port = nothing
end | Genie | https://github.com/GenieFramework/Genie.jl.git |
|
[
"MIT"
] | 5.30.6 | 376aa3d800f4da32d232f2d9a1685e34e2911b4a | code | 370 | @safetestset "Hello Genie" begin
using Genie, HTTP
message = "Welcome to Genie!"
route("/hello") do
message
end
port = nothing
port = rand(8500:8900)
up(port)
response = HTTP.get("http://localhost:$port/hello")
@test response.status == 200
@test String(response.body) == message
down()
sleep(1)
server = nothing
port = nothing
end | Genie | https://github.com/GenieFramework/Genie.jl.git |
|
[
"MIT"
] | 5.30.6 | 376aa3d800f4da32d232f2d9a1685e34e2911b4a | code | 8965 | @safetestset "HTML attributes rendering" begin
@safetestset "No attributes" begin
using Genie.Renderer.Html
r = html("<div></div>")
@test String(r.body) == "<div></div>"
end;
@safetestset "No attributes force parse" begin
using Genie.Renderer.Html
import Genie.Util: fws
r = html("<div></div>", forceparse = true)
@test String(r.body) |> fws == "<!DOCTYPE html><html><body><div></div></body></html>" |> fws
end;
@safetestset "Regular attribute" begin
using Genie.Renderer.Html
import Genie.Util: fws
r = html("""<div class="foo"></div>""")
@test String(r.body) |> fws == """<div class="foo"></div>""" |> fws
end;
@safetestset "Regular attribute force parse" begin
using Genie.Renderer.Html
import Genie.Util: fws
r = html("""<div class="foo"></div>""", forceparse = true)
@test String(r.body) |> fws == """<!DOCTYPE html><html><body><div class="foo"></div></body></html>""" |> fws
end;
@safetestset "Dashed attributes" begin
using Genie.Renderer.Html
import Genie.Util: fws
r = html("""<div data-arg="foo"></div>""")
@test String(r.body) |> fws == """<div data-arg="foo"></div>""" |> fws
end;
@safetestset "Dashed attributes force parse" begin
using Genie.Renderer.Html
import Genie.Util: fws
r = html("""<div data-arg="foo"></div>""", forceparse = true)
@test String(r.body) |> fws == """<!DOCTYPE html><html><body><div data-arg="foo"></div></body></html>""" |> fws
end;
@safetestset "Multiple dashed attributes" begin
using Genie.Renderer.Html
import Genie.Util: fws
r = html("""<div data-arg="foo bar" data-moo-hoo="123"></div>""")
@test String(r.body) |> fws == """<div data-arg="foo bar" data-moo-hoo="123"></div>""" |> fws
end;
@safetestset "Multiple dashed attributes force parse" begin
using Genie.Renderer.Html
import Genie.Util: fws
r = html("""<div data-arg="foo bar" data-moo-hoo="123"></div>""", forceparse = true)
@test String(r.body) |> fws == """<!DOCTYPE html><html><body><div data-arg="foo bar" data-moo-hoo="123"></div></body></html>""" |> fws
end;
@safetestset "Attribute value with `=` character" begin
using Genie.Renderer.Html
import Genie.Util: fws
r = html("""<div onclick="event = true"></div>""")
@test String(r.body) |> fws == """<div onclick="event = true"></div>""" |> fws
r = html("""<div onclick="event = true"></div>""", forceparse=true)
@test String(r.body) |> fws == """<!DOCTYPE html><html><body><div onclick="event = true"></div></body></html>""" |> fws
r = html("<div v-on:click='event = true'></div>")
@test String(r.body) |> fws == "<div v-on:click='event = true'></div>" |> fws
r = html("<div v-on:click='event = true'></div>", forceparse=true)
@test String(r.body) |> fws == """<!DOCTYPE html><html><body><div v-on:click="event = true"></div></body></html>""" |> fws
end;
@safetestset "Single quotes" begin
using Genie.Renderer.Html
import Genie.Util: fws
r = html("<div class='foo'></div>")
@test String(r.body) |> fws == """<div class='foo'></div>""" |> fws
end;
@safetestset "Single quotes force parse" begin
using Genie.Renderer.Html
import Genie.Util: fws
r = html("<div class='foo'></div>", forceparse = true)
@test String(r.body) |> fws == """<!DOCTYPE html><html><body><div class="foo"></div></body></html>""" |> fws
end;
@safetestset "Vue args force parse" begin
using Genie
using Genie.Renderer.Html
import Genie.Util: fws
r = html("""<span v-bind:title="message">
Hover your mouse over me for a few seconds
to see my dynamically bound title!
</span>""", forceparse = true)
@test String(r.body) |> fws == """<!DOCTYPE html><html><body><span v-bind:title="message"> Hover your mouse over me for a few seconds
to see my dynamically bound title!
</span></body></html>""" |> fws
r = html("""<div id="app-3">
<span v-if="seen">Now you see me</span>
</div>""", forceparse = true)
@test String(r.body) |> fws ==
"""<!DOCTYPE html><html><body><div id="app-3"><span v-if="seen">Now you see me</span></div></body></html>""" |> fws
r = html("""<div id="app-4">
<ol>
<li v-for="todo in todos">
{{ todo.text }}
</li>
</ol>
</div>""", forceparse = true)
@test String(r.body) |> fws ==
"""<!DOCTYPE html><html><body><div id="app-4"><ol><li v-for="todo in todos"> {{ todo.text }}
</li></ol></div></body></html>""" |> fws
r = html("""<div id="app-5">
<p>{{ message }}</p>
<button v-on:click="reverseMessage">Reverse Message</button>
</div>""", forceparse = true)
@test String(r.body) |> fws ==
"""<!DOCTYPE html><html><body><div id="app-5"><p>{{ message }}</p>
<button v-on:click="reverseMessage">Reverse Message</button></div></body></html>""" |> fws
r = html("""<div id="app-6">
<p>{{ message }}</p>
<input v-model="message">
</div>""", forceparse = true)
@test String(r.body) |> fws ==
"""<!DOCTYPE html><html><body><div id="app-6"><p>{{ message }}</p>
<input v-model="message"$(Genie.config.html_parser_close_tag)></div></body></html>""" |> fws
Genie.Renderer.Html.register_element("todo-item")
r = html("""<ol>
<!-- Create an instance of the todo-item component -->
<todo-item></todo-item>
</ol>""", forceparse = true)
@test String(r.body) |> fws ==
"""<!DOCTYPE html><html><body><ol><!-- Create an instance of the todo-item component --><todo-item></todo-item>
</ol></body></html>""" |> fws
r = html("""<div id="app-7">
<ol>
<!--
Now we provide each todo-item with the todo object
it's representing, so that its content can be dynamic.
We also need to provide each component with a "key",
which will be explained later.
-->
<todo-item
v-for="item in groceryList"
v-bind:todo="item"
v-bind:key="item.id"
></todo-item>
</ol>
</div>""", forceparse = true)
@test String(r.body) |> fws ==
"""<!DOCTYPE html><html><body><div id="app-7"><ol><!--
Now we provide each todo-item with the todo object
it's representing, so that its content can be dynamic.
We also need to provide each component with a "key",
which will be explained later.
--><todo-item v-for="item in groceryList" v-bind:todo="item" v-bind:key="item.id">
</todo-item></ol></div></body></html>""" |> fws
r = html("""<span v-on:click="upvote(submission.id)"></span>""", forceparse = true)
@test String(r.body) |> fws ==
"""<!DOCTYPE html><html><body><span v-on:click="upvote(submission.id)"></span></body></html>""" |> fws
r = html("""<span v-on:click="upvote(submission.id)"></span>""", forceparse = true)
@test String(r.body) |> fws ==
"""<!DOCTYPE html><html><body><span v-on:click="upvote(submission.id)"></span></body></html>""" |> fws
r = html("""<img v-bind:src="submission.submissionImage" />""", forceparse = true)
@test String(r.body) |> fws ==
"""<!DOCTYPE html><html><body><img v-bind:src="submission.submissionImage"$(Genie.config.html_parser_close_tag)>
</body></html>""" |> fws
r = html("""<img :src="submission.submissionImage" />""", forceparse = true)
@test String(r.body) |> fws ==
"""<!DOCTYPE html><html><body><img :src="submission.submissionImage"$(Genie.config.html_parser_close_tag)>
</body></html>""" |> fws
end;
@safetestset "Embedded Julia" begin
using Genie
using Genie.Renderer.Html
import Genie.Util: fws
id = 10
r = html(raw"""<span id="$id"></span>""", id = 10)
@test String(r.body) |> fws == """<!DOCTYPE html><html><body><span id="10"></span></body></html>""" |> fws
r = html(raw"""<span id="$(string(:moo))"></span>""", forceparse = true)
@test String(r.body) |> fws == """<!DOCTYPE html><html><body><span id="moo"></span></body></html>""" |> fws
r = html("""<span $(string(:disabled))></span>""", forceparse = true)
@test String(r.body) |> fws == """<!DOCTYPE html><html><body><span disabled="disabled"></span></body></html>""" |> fws
r = html("""<span $("foo=$(string(:disabled))")></span>""", forceparse = true)
@test String(r.body) |> fws == """<!DOCTYPE html><html><body><span foo="disabled"></span></body></html>""" |> fws
end;
end;
| Genie | https://github.com/GenieFramework/Genie.jl.git |
|
[
"MIT"
] | 5.30.6 | 376aa3d800f4da32d232f2d9a1685e34e2911b4a | code | 3755 | @safetestset "HTML rendering" begin
using Genie, Genie.Renderer.Html, Genie.Requests
greeting = "Welcome"
name = "Genie"
function htmlviewfile()
"
<h1>$greeting</h1>
<div>
<p>This is a $name test</p>
</div>
<hr />
"
end
function htmltemplatefile()
"
<!DOCTYPE HTML>
<html>
<head>
<title>$name test</title>
</head>
<body>
<div class=\"template\">
<% @yield %>
</div>
<footer>Just a footer</footer>
</body>
</html>
"
end
@testset "HTML Rendering" begin
using Genie, Genie.Renderer.Html, Genie.Requests
@testset "WebRenderable constructors" begin
using Genie, Genie.Renderer.Html, Genie.Requests
wr = Genie.Renderer.WebRenderable("hello")
@test wr.body == "hello"
@test wr.content_type == Genie.Renderer.DEFAULT_CONTENT_TYPE
@test wr.status == 200
@test wr.headers == Genie.Renderer.HTTPHeaders()
wr = Genie.Renderer.WebRenderable("hello", :json)
@test wr.body == "hello"
@test wr.content_type == :json
@test wr.status == 200
@test wr.headers == Genie.Renderer.HTTPHeaders()
wr = Genie.Renderer.WebRenderable()
@test wr.body == ""
@test wr.content_type == Genie.Renderer.DEFAULT_CONTENT_TYPE
@test wr.status == 200
@test wr.headers == Genie.Renderer.HTTPHeaders()
wr = Genie.Renderer.WebRenderable(body = "bye", content_type = :javascript, status = 301, headers = Genie.Renderer.HTTPHeaders("Location" => "/bye"))
@test wr.body == "bye"
@test wr.content_type == :javascript
@test wr.status == 301
@test wr.headers["Location"] == "/bye"
wr = Genie.Renderer.WebRenderable(Genie.Renderer.WebRenderable(body = "good morning", content_type = :javascript), 302, Genie.Renderer.HTTPHeaders("Location" => "/morning"))
@test wr.body == "good morning"
@test wr.content_type == :javascript
@test wr.status == 302
@test wr.headers["Location"] == "/morning"
end;
@testset "String HTML rendering" begin
using Genie, Genie.Renderer.Html, Genie.Requests
import Genie.Util: fws
r = Requests.HTTP.Response()
@testset "String no layout" begin
rm("build", force = true, recursive = true)
r = html(htmlviewfile(), forceparse = true)
@test String(r.body) |> fws ==
"<!DOCTYPE html><html><body><h1>$greeting</h1><div><p>This is a $name test</p></div>
<hr$(Genie.config.html_parser_close_tag)></body></html>" |> fws
end;
@testset "String with layout" begin
rm("build", force = true, recursive = true)
r = html(htmlviewfile(), layout = htmltemplatefile())
@test String(r.body) |> fws ==
"<!DOCTYPE html><html><head><title>$name test</title></head><body><div class=\"template\">
<h1>$greeting</h1><div><p>This is a $name test</p></div><hr$(Genie.config.html_parser_close_tag)></div>
<footer>Just a footer</footer></body></html>" |> fws
end;
@test r.status == 200
@test r.headers[1]["Content-Type"] == "text/html; charset=utf-8"
rm("build", force = true, recursive = true)
end;
@testset "Encoding Test" begin
using Genie.Renderer, Genie.Renderer.Html
path = mktempdir(cleanup=true)
fpath = joinpath(path, "welcome.jl.html")
write(fpath, "welcöme. 不一定要味道好,但一定要有用. äüö&%?#")
expected = "HTTP/1.1 200 OK\r\nContent-Type: text/html; charset=utf-8\r\n\r\n<!DOCTYPE html><html>\n <body>\n <p>welcöme. 不一定要味道好,但一定要有用. äüö&%?#\n</p>\n </body></html>"
decoded = String(html(filepath(fpath)))
@test decoded == expected
end
end;
end
| Genie | https://github.com/GenieFramework/Genie.jl.git |
|
[
"MIT"
] | 5.30.6 | 376aa3d800f4da32d232f2d9a1685e34e2911b4a | code | 1011 | @safetestset "JS rendering" begin
@safetestset "Plain JS rendering" begin
using Genie
using Genie.Renderer
using Genie.Renderer.Js
script = raw"var app = new Vue({el: '#app', data: { message: 'Hello Vue!' }})"
r = js(script)
@test String(r.body) == "var app = new Vue({el: '#app', data: { message: 'Hello Vue!' }})"
@test r.headers[1]["Content-Type"] == "application/javascript; charset=utf-8"
Genie.Renderer.clear_task_storage()
end;
@safetestset "Vars JS rendering" begin
using Genie
using Genie.Renderer
using Genie.Renderer.Js
using Genie.Renderer.Json.JSONParser
data = JSONParser.json(("message" => "Hi Vue"))
script = raw"var app = new Vue({el: '#app', data: $data})"
r = js(script, data = data)
@test String(r.body) == "var app = new Vue({el: '#app', data: {\"message\":\"Hi Vue\"}})\n"
@test r.headers[1]["Content-Type"] == "application/javascript; charset=utf-8"
Genie.Renderer.clear_task_storage()
end;
end; | Genie | https://github.com/GenieFramework/Genie.jl.git |
|
[
"MIT"
] | 5.30.6 | 376aa3d800f4da32d232f2d9a1685e34e2911b4a | code | 2646 | @safetestset "JSON payload correctly identified" begin
using Genie, HTTP
import Genie.Util: fws
route("/jsonpayload", method = POST) do
Genie.Requests.jsonpayload()
end
route("/jsongreeting", method = POST) do
Genie.Requests.jsonpayload("greeting")
end
port = nothing
port = rand(8500:8900)
server = up(port)
response = HTTP.request("POST", "http://localhost:$port/jsonpayload",
[("Content-Type", "application/json; charset=utf-8")], """{"greeting":"hello"}""")
@test response.status == 200
@test String(response.body) |> fws == """Dict{String, Any}("greeting" => "hello")""" |> fws
response = HTTP.request("POST", "http://localhost:$port/jsongreeting",
[("Content-Type", "application/json")], """{"greeting":"hello"}""")
@test response.status == 200
@test String(response.body) |> fws == """hello""" |> fws
response = HTTP.request("POST", "http://localhost:$port/jsonpayload",
[("Content-Type", "application/json")], """{"greeting":"hello"}""")
@test response.status == 200
@test String(response.body) |> fws == """Dict{String, Any}("greeting" => "hello")""" |> fws
response = HTTP.request("POST", "http://localhost:$port/jsongreeting",
[("Content-Type", "application/json; charset=utf-8")], """{"greeting":"hello"}""")
@test response.status == 200
@test String(response.body) |> fws == """hello""" |> fws
#===#
response = HTTP.request("POST", "http://localhost:$port/jsonpayload",
[("Content-Type", "application/vnd.api+json; charset=utf-8")], """{"greeting":"hello"}""")
@test response.status == 200
@test String(response.body) |> fws == """Dict{String, Any}("greeting" => "hello")""" |> fws
response = HTTP.request("POST", "http://localhost:$port/jsongreeting",
[("Content-Type", "application/vnd.api+json; charset=utf-8")], """{"greeting":"hello"}""")
@test response.status == 200
@test String(response.body) |> fws == """hello""" |> fws
response = HTTP.request("POST", "http://localhost:$port/jsonpayload",
[("Content-Type", "application/vnd.api+json")], """{"greeting":"hello"}""")
@test response.status == 200
@test String(response.body) |> fws == """Dict{String, Any}("greeting" => "hello")""" |> fws
response = HTTP.request("POST", "http://localhost:$port/jsongreeting",
[("Content-Type", "application/vnd.api+json")], """{"greeting":"hello"}""")
@test response.status == 200
@test String(response.body) |> fws == """hello""" |> fws
down()
sleep(1)
server = nothing
port = nothing
end; | Genie | https://github.com/GenieFramework/Genie.jl.git |
|
[
"MIT"
] | 5.30.6 | 376aa3d800f4da32d232f2d9a1685e34e2911b4a | code | 1693 | @safetestset "JSON payload" begin
using Genie, HTTP
import Genie.Util: fws
route("/jsonpayload", method = POST) do
Genie.Requests.jsonpayload()
end
route("/jsontest", method = POST) do
Genie.Requests.jsonpayload("test")
end
port = nothing
port = rand(8500:8900)
server = up(port)
response = HTTP.request("POST", "http://localhost:$port/jsonpayload",
[("Content-Type", "application/json; charset=utf-8")], """{"greeting":"hello"}""")
@test response.status == 200
@test String(response.body) |> fws == """Dict{String, Any}("greeting" => "hello")""" |> fws
response = HTTP.request("POST", "http://localhost:$port/jsontest",
[("Content-Type", "application/json; charset=utf-8")], """{"test":[1,2,3]}""")
@test response.status == 200
@test String(response.body) == "[1, 2, 3]"
response = HTTP.request("POST", "http://localhost:$port/jsonpayload",
[("Content-Type", "application/json")], """{"greeting":"hello"}""")
@test response.status == 200
@test String(response.body) |> fws == """Dict{String, Any}("greeting" => "hello")""" |> fws
response = HTTP.request("POST", "http://localhost:$port/jsontest",
[("Content-Type", "application/json")], """{"test":[1,2,3]}""")
@test response.status == 200
@test String(response.body) == "[1, 2, 3]"
route("/json-error", method = POST) do
error("500, sorry")
end
@test_throws HTTP.ExceptionRequest.StatusError HTTP.request("POST", "http://localhost:$port/json-error", [("Content-Type", "application/json; charset=utf-8")], """{"greeting":"hello"}""")
down()
sleep(1)
server = nothing
port = nothing
end; | Genie | https://github.com/GenieFramework/Genie.jl.git |
|
[
"MIT"
] | 5.30.6 | 376aa3d800f4da32d232f2d9a1685e34e2911b4a | code | 982 | @safetestset "JS rendering" begin
@safetestset "JSON rendering" begin
@safetestset "JSON view rendering with vars" begin
using Genie, Genie.Renderer, Genie.Renderer.Json
jsonview = raw"
Dict(vars(:root) => Dict(lang => greet for (lang,greet) in vars(:greetings)))
"
viewfile = mktemp()
write(viewfile[2], jsonview)
close(viewfile[2])
words = Dict(:en => "Hello", :es => "Hola", :pt => "Ola", :it => "Ciao")
r = json(Genie.Renderer.Path(viewfile[1]), root = "greetings", greetings = words)
@test String(r.body) == """{"greetings":{"en":"Hello","it":"Ciao","pt":"Ola","es":"Hola"}}"""
Genie.Renderer.clear_task_storage()
end;
@safetestset "JSON3 struct rendering" begin
struct Person
name::String
age::Int
end
p = Person("John Doe", 42)
using Genie.Renderers.Json
@test String(json(p).body) == """{"name":"John Doe","age":42}"""
end
end;
end; | Genie | https://github.com/GenieFramework/Genie.jl.git |
|
[
"MIT"
] | 5.30.6 | 376aa3d800f4da32d232f2d9a1685e34e2911b4a | code | 380 | @safetestset "Sort Load Order based on .autoload" begin
using Genie
order = Genie.Loader.sort_load_order("loader", readdir("loader"))
@test order == ["xyz.jl", "-my-test-file.jl", "def.jl", "Abc.jl", ".autoload", "Aaa.jl", "Abb.jl"]
@test get(ENV, "FOO", "") == ""
Genie.Loader.load_dotenv()
@test get(ENV, "FOO", "") == "bar"
delete!(ENV, "FOO")
end | Genie | https://github.com/GenieFramework/Genie.jl.git |
|
[
"MIT"
] | 5.30.6 | 376aa3d800f4da32d232f2d9a1685e34e2911b4a | code | 2399 | @safetestset "Markdown rendering" begin
@safetestset "String markdown rendering" begin
using Genie
using Genie.Renderer.Html
using Markdown
import Genie.Util: fws
view = raw"""
# Hello
## Welcome to Genie""" |> Markdown.parse
@test (Html.html(view, forceparse = true).body |> String |> fws) ==
"<!DOCTYPE html><html><body><h1>Hello</h1><h2>Welcome to Genie</h2></body></html>" |> fws
view = raw"""
# Hello
## Welcome to Genie, $name""" |> Markdown.parse
@test (Html.html(view, name = "John").body |> String |> fws) ==
"<!DOCTYPE html><html><body><h1>Hello</h1><h2>Welcome to Genie, John</h2></body></html>" |> fws
layout = raw"""
<div>
<h1>Layout header</h1>
<section>
<% @yield %>
</section>
<footer>
<h4>Layout footer</h4>
</footer>
</div>"""
@test (Html.html(view, layout = layout, name = "John").body |> String |> fws) ==
"<!DOCTYPE html><html><body><div><h1>Layout header</h1><section><h1>Hello</h1><h2>Welcome to Genie, John</h2>
</section><footer><h4>Layout footer</h4></footer></div></body></html>" |> fws
end;
@safetestset "Template markdown rendering" begin
using Genie, Genie.Renderer
using Genie.Renderer.Html
import Genie.Util: fws
@test Html.html(filepath("views/view.jl.md"), numbers = [1, 1, 2, 3, 5, 8, 13]).body |> String |> fws ==
"""
<!DOCTYPE html><html><head></head><body><h1>There are 7</h1>
<p>-> 1 -> 1 -> 2 -> 3 -> 5 -> 8 -> 13</p>
</body></html>""" |> fws
@test Html.html(filepath("views/view.jl.md"), layout = filepath("views/layout.jl.html"), numbers = [1, 1, 2, 3, 5, 8, 13]).body |> String |> fws ==
"""
<!DOCTYPE html><html><body><div><h1>Layout header</h1><section><h1>There are 7</h1>
<p>-> 1 -> 1 -> 2 -> 3 -> 5 -> 8 -> 13</p>
</section><footer><h4>Layout footer</h4></footer></div></body></html>""" |> fws
end
@safetestset "Markdown rendering with embedded variables" begin
using Genie, Genie.Renderer
using Genie.Renderer.Html
import Genie.Util: fws
@test Html.html(filepath("views/view-vars.jl.md")).body |> String |> fws ==
"""
<!DOCTYPE html><html><head></head><body><h1>There are 7</h1>
<p>-> 1 -> 1 -> 2 -> 3 -> 5 -> 8 -> 13</p>
</body></html>""" |> fws
end;
end; | Genie | https://github.com/GenieFramework/Genie.jl.git |
|
[
"MIT"
] | 5.30.6 | 376aa3d800f4da32d232f2d9a1685e34e2911b4a | code | 686 | @safetestset "OPTIONS requests" begin
using Genie, HTTP
route("/options", method = OPTIONS) do
push!(params(:RESPONSE).headers, "X-Foo-Bar" => "Baz")
end
port = nothing
port = rand(8500:8900)
server = up(port)
sleep(1)
response = HTTP.request("OPTIONS", "http://localhost:$port") # unhandled, should get default response
@test response.status == 200
@test get(Dict(response.headers), "X-Foo-Bar", nothing) == nothing
response = HTTP.request("OPTIONS", "http://localhost:$port/options") # handled
@test response.status == 200
@test get(Dict(response.headers), "X-Foo-Bar", nothing) == "Baz"
down()
sleep(1)
server = nothing
port = nothing
end | Genie | https://github.com/GenieFramework/Genie.jl.git |
|
[
"MIT"
] | 5.30.6 | 376aa3d800f4da32d232f2d9a1685e34e2911b4a | code | 2147 | @safetestset "Output <script> tags" begin
using Genie, Genie.Renderer
using Genie.Renderer.Html
import Genie.Util: fws
@test Html.html("""<body><p>Good morning</p><script>alert("Hello")</script></body>""").body |> String ==
"""<body><p>Good morning</p><script>alert("Hello")</script></body>"""
@test Html.html("""<body><p>Good morning</p><script type="text/javascript">alert("Hello")</script></body>""").body |> String ==
"""<body><p>Good morning</p><script type="text/javascript">alert("Hello")</script></body>"""
@test Html.html("""<body><p>Good morning</p><script src="foo.js"></script></body>""").body |> String ==
"""<body><p>Good morning</p><script src="foo.js"></script></body>"""
@test Html.html("""<body><p>Good morning</p><script type="text/javascript" src="foo.js"></script></body>""").body |> String ==
"""<body><p>Good morning</p><script type="text/javascript" src="foo.js"></script></body>"""
@test Html.html("""<body><p>Good morning</p><script type="text/vbscript" src="foo.vb"></script></body>""").body |> String ==
"""<body><p>Good morning</p><script type="text/vbscript" src="foo.vb"></script></body>"""
@test Html.html(filepath("views/outputscripttags.jl.html")).body |> String |> fws ==
"""<!DOCTYPE html><html><body><p>Greetings</p><script>alert("Hello")</script><script src="foo.js"></script>
<script type="text/javascript">alert("Hello")</script><script src="foo.js" type="text/javascript"></script></body></html>""" |> fws
@test Html.html(filepath("views/outputscripttags.jl.html"), layout=filepath("views/layoutscripttags.jl.html")).body |> String |> fws ==
"""<!DOCTYPE html><html><body><h1>Layout header</h1><section><p>Greetings</p><script>alert("Hello")</script>
<script src="foo.js"></script><script type="text/javascript">alert("Hello")</script><script src="foo.js" type="text/javascript">
</script></section><footer><h4>Layout footer</h4></footer><script>alert("Hello")</script><script src="foo.js"></script>
<script type="text/javascript">alert("Hello")</script><script src="foo.js" type="text/javascript"></script></body></html>""" |> fws
end | Genie | https://github.com/GenieFramework/Genie.jl.git |
|
[
"MIT"
] | 5.30.6 | 376aa3d800f4da32d232f2d9a1685e34e2911b4a | code | 1647 | @safetestset "Path traversal" begin
@safetestset "Returns 401 unauthorised" begin
using Genie
using HTTP
isdir(Genie.config.server_document_root) || mkdir(Genie.config.server_document_root)
port = rand(8000:10_000)
server = up(port)
req = HTTP.request("GET", "http://localhost:$port////etc/hosts"; status_exception = false)
@test req.status == (Sys.iswindows() ? 404 : 401)
# req = HTTP.request("GET", "http://localhost:$port/../../src/mimetypes.jl"; status_exception = false)
# @test req.status == 401
Genie.Server.down!()
server = nothing
end
# Tests pass OK but for some reason some state remains and breaks next batch of tests... :-(
# @safetestset "Authorised static server responses" begin
# using Genie
# using HTTP
# isdir(Genie.config.server_document_root) || mkdir(Genie.config.server_document_root)
# port = rand(8000:10_000)
# server = Genie.Server.serve(; port)
# req = HTTP.request("GET", "http://localhost:$port//etc/passwd"; status_exception = false)
# @test req.status == (Sys.iswindows() ? 404 : 401)
# req = HTTP.request("GET", "http://localhost:$port/../../src/mimetypes.jl"; status_exception = false)
# @test req.status == 401
# Genie.Server.down!()
# server = nothing
# end
@safetestset "serve_static_file does not serve unauthorised requests" begin
using Genie
response = Genie.Router.serve_static_file("//etc/passwd", root = "public")
@test response.status == 401
response = Genie.Router.serve_static_file("../../../../etc/passwd", root = "public")
@test response.status == 401
end
end
| Genie | https://github.com/GenieFramework/Genie.jl.git |
|
[
"MIT"
] | 5.30.6 | 376aa3d800f4da32d232f2d9a1685e34e2911b4a | code | 1119 | @safetestset "Peer info" begin
@safetestset "Peer info is disabled by default" begin
using Genie, Genie.Requests
using HTTP
port = rand(8500:8900)
route("/") do
"$(peer().ip)-$(peer().port)"
end
server = up(port)
response = try
HTTP.request("GET", "http://127.0.0.1:$port")
catch ex
ex.response
end
@test Genie.config.features_peerinfo == false
@test response.status == 200
@test String(response.body) == "-"
down()
sleep(1)
server = nothing
end;
@safetestset "Peer info can be activated" begin
using Genie, Genie.Requests
using HTTP
port = rand(8500:8900)
Genie.config.features_peerinfo = true
route("/") do
"$(peer().ip)-$(peer().port)"
end
server = up(port)
response = try
HTTP.request("GET", "http://127.0.0.1:$port")
catch ex
ex.response
end
@test Genie.config.features_peerinfo == true
@test response.status == 200
@test_broken String(response.body) == "127.0.0.1-$port"
down()
sleep(1)
server = nothing
port = nothing
end;
end | Genie | https://github.com/GenieFramework/Genie.jl.git |
|
[
"MIT"
] | 5.30.6 | 376aa3d800f4da32d232f2d9a1685e34e2911b4a | code | 1936 | @safetestset "POST form payload" begin
using Genie, HTTP, Genie.Router, Genie.Requests
route("/") do
"GET"
end
route("/", method = POST) do
params(:greeting)
end
route("/data", method = POST) do
fields = postpayload(Symbol("fields[]"))
fields[1] * fields[2] * postpayload(:single)
end
port = nothing
port = rand(8500:8900)
up(port; open_browser = false)
response = HTTP.request("POST", "http://localhost:$port/", ["Content-Type" => "application/x-www-form-urlencoded"], "greeting=Hello")
@test response.status == 200
@test String(response.body) == "Hello"
response = HTTP.request("POST", "http://localhost:$port/", ["Content-Type" => "application/x-www-form-urlencoded"], "greeting=Hey you there")
@test response.status == 200
@test String(response.body) == "Hey you there"
response = HTTP.request("GET", "http://localhost:$port/", ["Content-Type" => "application/x-www-form-urlencoded"], "greeting=Hello")
@test response.status == 200
@test String(response.body) == "GET"
response = HTTP.request("POST", "http://localhost:$port/data", ["Content-Type" => "application/x-www-form-urlencoded"], "fields%5B%5D=Hey you there&fields%5B%5D=&single=")
@test response.status == 200
@test String(response.body) == "Hey you there"
response = HTTP.request("POST", "http://localhost:$port/data", ["Content-Type" => "application/x-www-form-urlencoded"], "fields%5B%5D=1&fields%5B%5D=2&single=3")
@test response.status == 200
@test String(response.body) == "123"
response = HTTP.post("http://localhost:$port", [], HTTP.Form(Dict("greeting" => "Hello")))
@test response.status == 200
@test String(response.body) == "Hello"
response = HTTP.post("http://localhost:$port", [], HTTP.Form(Dict("greeting" => "Hey you there")))
@test response.status == 200
@test String(response.body) == "Hey you there"
down()
sleep(1)
server = nothing
port = nothing
end | Genie | https://github.com/GenieFramework/Genie.jl.git |
|
[
"MIT"
] | 5.30.6 | 376aa3d800f4da32d232f2d9a1685e34e2911b4a | code | 5117 | @safetestset "Query params" begin
@safetestset "No query params" begin
using Genie
using HTTP
port = nothing
port = rand(8500:8900)
route("/") do
isempty(query()) && return ""
isempty(params(:GET)) && return ""
"error"
end
server = up(port)
response = try
HTTP.request("GET", "http://127.0.0.1:$port", ["Content-Type" => "text/html"])
catch ex
ex.response
end
@test response.status == 200
@test isempty(String(response.body)) == true
down()
sleep(1)
server = nothing
port = nothing
end
@safetestset "No defaults errors out" begin
using Genie
using HTTP
port = nothing
port = rand(8500:8900)
route("/") do
query(:a)
end
server = up(port)
response = try
HTTP.request("GET", "http://127.0.0.1:$port", ["Content-Type" => "text/html"])
catch ex
ex.response
end
@test response.status == 500
down()
sleep(1)
server = nothing
port = nothing
end
@safetestset "Defaults when no query params" begin
using Genie
using HTTP
port = nothing
port = rand(8500:8900)
route("/") do
query(:x, "10") * query(:y, "20")
end
server = up(port)
# ====
response = try
HTTP.request("GET", "http://127.0.0.1:$port", ["Content-Type" => "text/html"])
catch ex
ex.response
end
@test response.status == 200
@test String(response.body) == "1020"
# ====
response = try
HTTP.request("GET", "http://127.0.0.1:$port/?", ["Content-Type" => "text/html"])
catch ex
ex.response
end
@test response.status == 200
@test String(response.body) == "1020"
# ====
response = try
HTTP.request("GET", "http://127.0.0.1:$port/?x", ["Content-Type" => "text/html"])
catch ex
ex.response
end
@test response.status == 200
@test String(response.body) == "20"
# ====
response = try
HTTP.request("GET", "http://127.0.0.1:$port/?x&a=3", ["Content-Type" => "text/html"])
catch ex
ex.response
end
@test response.status == 200
@test String(response.body) == "20"
# ====
response = try
HTTP.request("GET", "http://127.0.0.1:$port/?x&y", ["Content-Type" => "text/html"])
catch ex
ex.response
end
@test response.status == 200
@test isempty(String(response.body)) == true
down()
sleep(1)
server = nothing
port = nothing
end
@safetestset "Query params processing" begin
using Genie
using HTTP
port = nothing
port = rand(8500:8900)
route("/") do
query(:x)
end
server = up(port)
response = try
HTTP.request("GET", "http://127.0.0.1:$port?x=1", ["Content-Type" => "text/html"])
catch ex
ex.response
end
@test response.status == 200
@test String(response.body) == "1"
# ====
response = try
HTTP.request("GET", "http://127.0.0.1:$port?x=1&x=2", ["Content-Type" => "text/html"])
catch ex
ex.response
end
@test response.status == 200
@test String(response.body) == "2"
# ====
response = try
HTTP.request("GET", "http://127.0.0.1:$port?x=1&x=2&x=3", ["Content-Type" => "text/html"])
catch ex
ex.response
end
@test response.status == 200
@test String(response.body) == "3"
# ====
response = try
HTTP.request("GET", "http://127.0.0.1:$port?x=1&x=2&x=3&y=0", ["Content-Type" => "text/html"])
catch ex
ex.response
end
@test response.status == 200
@test String(response.body) == "3"
# ====
response = try
HTTP.request("GET", "http://127.0.0.1:$port?x=0&x[]=1&x[]=2", ["Content-Type" => "text/html"])
catch ex
ex.response
end
@test response.status == 200
@test String(response.body) == "0"
down()
sleep(1)
server = nothing
port = nothing
end
@safetestset "Array query params" begin
using Genie
using HTTP
port = nothing
port = rand(8500:8900)
route("/") do
query(:x, "10") * join(query(Symbol("x[]"), "100"))
end
server = up(port)
# ====
response = try
HTTP.request("GET", "http://127.0.0.1:$port", ["Content-Type" => "text/html"])
catch ex
ex.response
end
@test response.status == 200
@test String(response.body) == "10100"
# ====
response = try
HTTP.request("GET", "http://127.0.0.1:$port/?x&x[]=1000", ["Content-Type" => "text/html"])
catch ex
ex.response
end
@test response.status == 200
@test String(response.body) == "1000"
# ====
response = try
HTTP.request("GET", "http://127.0.0.1:$port/?x&x[]=1000&x[]=2000", ["Content-Type" => "text/html"])
catch ex
ex.response
end
@test response.status == 200
@test String(response.body) == "10002000"
# ====
response = try
HTTP.request("GET", "http://127.0.0.1:$port/?x=9&x[]=1000&x[]=2000", ["Content-Type" => "text/html"])
catch ex
ex.response
end
@test response.status == 200
@test String(response.body) == "910002000"
# ====
response = try
HTTP.request("GET", "http://127.0.0.1:$port/?x=9&x[]=1000&x[]=2000&y[]=8", ["Content-Type" => "text/html"])
catch ex
ex.response
end
@test response.status == 200
@test String(response.body) == "910002000"
down()
sleep(1)
server = nothing
port = nothing
end
end | Genie | https://github.com/GenieFramework/Genie.jl.git |
|
[
"MIT"
] | 5.30.6 | 376aa3d800f4da32d232f2d9a1685e34e2911b4a | code | 1912 | @safetestset "Special chars in GET params (query)" begin
@safetestset "<a+b> should be <a b>" begin
using Genie
using HTTP
port = nothing
port = rand(8500:8900)
route("/") do
params(:x)
end
server = up(port)
response = try
HTTP.request("GET", "http://127.0.0.1:$port/?x=foo+bar")
catch ex
ex.response
end
@test response.status == 200
@test String(response.body) == "foo bar"
down()
sleep(1)
server = nothing
port = nothing
end;
@safetestset "<a%20b> should be <a b>" begin
using Genie
using HTTP
port = nothing
port = rand(8500:8900)
route("/") do
params(:x)
end
server = up(port)
response = try
HTTP.request("GET", "http://127.0.0.1:$port/?x=foo%20bar")
catch ex
ex.response
end
@test response.status == 200
@test String(response.body) == "foo bar"
down()
sleep(1)
server = nothing
port = nothing
end;
@safetestset "<a%2Bb> should be <a+b>" begin
using Genie
using HTTP
port = nothing
port = rand(8500:8900)
route("/") do
params(:x)
end
server = up(port)
response = try
HTTP.request("GET", "http://127.0.0.1:$port/?x=foo%2Bbar")
catch ex
ex.response
end
@test response.status == 200
@test String(response.body) == "foo+bar"
down()
sleep(1)
server = nothing
port = nothing
end;
@safetestset "emoji support" begin
using Genie
using HTTP
port = nothing
port = rand(8500:8900)
route("/") do
params(:x)
end
server = up(port)
response = try
HTTP.request("GET", "http://127.0.0.1:$port/?x=✔+🧞+♥")
catch ex
ex.response
end
@test response.status == 200
@test String(response.body) == "✔ 🧞 ♥"
down()
sleep(1)
server = nothing
port = nothing
end;
end | Genie | https://github.com/GenieFramework/Genie.jl.git |
|
[
"MIT"
] | 5.30.6 | 376aa3d800f4da32d232f2d9a1685e34e2911b4a | code | 942 | @safetestset "Responses" begin
using Genie, HTTP, Genie.Responses
route("/responses", method = GET) do
setstatus(301)
setheaders(Dict("X-Foo-Bar" => "Baz"))
setheaders(Dict("X-A-B" => "C", "X-Moo" => "Cow"))
setbody("Hello")
end
route("/broken") do
omg!()
end
port = nothing
port = rand(8500:8900)
server = up(port)
response = HTTP.request("GET", "http://localhost:$port/responses")
@test response.status == 301
@test Dict(response.headers)["X-Foo-Bar"] == "Baz"
@test Dict(response.headers)["X-A-B"] == "C"
@test Dict(response.headers)["X-Moo"] == "Cow"
@test String(response.body) == "\0\0\0H\0\0\0e\0\0\0l\0\0\0l\0\0\0o" #"Hello" -- wth?!!!
@test_broken String(response.body) == "Hello"
@test_throws HTTP.ExceptionRequest.StatusError HTTP.request("GET", "http://localhost:$port/broken", ["Content-Type"=>"text/plain"])
down()
sleep(1)
server = nothing
port = nothing
end | Genie | https://github.com/GenieFramework/Genie.jl.git |
|
[
"MIT"
] | 5.30.6 | 376aa3d800f4da32d232f2d9a1685e34e2911b4a | code | 1042 | @safetestset "Router tests" begin
@safetestset "Basic routing" begin
using Genie, Genie.Router
route("/hello") do
"Hello"
end
end;
@safetestset "router_delete" begin
using Genie, Genie.Router
x = route("/caballo") do
"caballo"
end
@test (x in routes()) == true
Router.delete!(:get_caballo)
@test (x in routes()) == false
end;
@safetestset "isroute checks" begin
using Genie, Genie.Router
@test Router.isroute(:get_abcd) == false
route("/abcd", named = :get_abcd) do
"abcd"
end
@test Router.isroute(:get_abcd) == true
end;
@safetestset "test to_link" begin
using Genie, Genie.Router
route("/abcd", named = :get_abcd) do
"abcd"
end
@test Router.to_link(:get_abcd) == "/abcd"
end
@safetestset "test with basepath" begin
using Genie, Genie.Router
route("/abcd", named = :get_abcd) do
"abcd"
end
@test Router.to_link(:get_abcd, basepath = "/geniedev/9001") == "/geniedev/9001/abcd"
end
end; | Genie | https://github.com/GenieFramework/Genie.jl.git |
|
[
"MIT"
] | 5.30.6 | 376aa3d800f4da32d232f2d9a1685e34e2911b4a | code | 2014 | @safetestset "Routing edge cases" begin
@safetestset "Emoji routing" begin
using Genie
using HTTP
port = nothing
port = rand(8500:8900)
route("/✔/🧞/♥/❤") do
"/✔/🧞/♥/❤"
end
server = up(port)
response = try
HTTP.request("GET", "http://127.0.0.1:$port/✔/🧞/♥/❤")
catch ex
ex.response
end
@test response.status == 200
@test String(response.body) == "/✔/🧞/♥/❤"
down()
sleep(1)
server = nothing
end;
@safetestset "Emoji routing ✔" begin
using Genie
using HTTP
port = nothing
port = rand(8500:8900)
route("/✔") do
"All good"
end
server = up(port)
response = try
HTTP.request("GET", "http://127.0.0.1:$port/✔")
catch ex
ex.response
end
@test response.status == 200
@test String(response.body) == "All good"
down()
sleep(1)
server = nothing
port = nothing
end;
@safetestset "Encoded urls é" begin
using Genie
using HTTP
port = nothing
port = rand(8500:8900)
route("/réception") do
"Meet at réception"
end
server = up(port)
response = try
HTTP.request("GET", "http://127.0.0.1:$port/réception")
catch ex
ex.response
end
@test response.status == 200
@test String(response.body) == "Meet at réception"
down()
sleep(1)
server = nothing
port = nothing
end;
@safetestset "Emoji routing with params" begin
using Genie, Genie.Requests
using HTTP
port = nothing
port = rand(8500:8900)
route("/:check/:genie/:smallheart/:bigheart") do
"/$(payload(:check))/$(payload(:genie))/$(payload(:smallheart))/$(payload(:bigheart))"
end
server = up(port)
response = try
HTTP.request("GET", "http://127.0.0.1:$port/✔/🧞/♥/❤")
catch ex
ex.response
end
@test response.status == 200
@test String(response.body) == "/✔/🧞/♥/❤"
down()
sleep(1)
server = nothing
port = nothing
end;
end | Genie | https://github.com/GenieFramework/Genie.jl.git |
|
[
"MIT"
] | 5.30.6 | 376aa3d800f4da32d232f2d9a1685e34e2911b4a | code | 1713 | @safetestset "Vars rendering" begin
using Genie
using Genie.Renderer.Html, Genie.Requests
greeting = "Welcome"
name = "Genie"
function htmlviewfile_withvars()
raw"
<h1>$(vars(:greeting))</h1>
<div>
<p>This is a $(vars(:name)) test</p>
</div>
<hr />
"
end
function htmltemplatefile_withvars()
raw"
<!DOCTYPE HTML>
<html>
<head>
<title>$(vars(:name)) test</title>
</head>
<body>
<div class=\"template\">
<% @yield %>
</div>
<footer>Just a footer</footer>
</body>
</html>
"
end
@testset "String HTML rendering with vars" begin
using Genie
using Genie.Renderer.Html, Genie.Requests
import Genie.Util: fws
r = Requests.HTTP.Response()
@testset "String no layout with vars" begin
r = html(htmlviewfile_withvars(), greeting = greeting, name = name)
@test String(r.body) |> fws ==
"<!DOCTYPE html><html><body><h1>$greeting</h1><div><p>This is a $name test</p></div><hr$(Genie.config.html_parser_close_tag)>
</body></html>" |> fws
end;
@testset "String with layout with vars" begin
r = html(htmlviewfile_withvars(), layout = htmltemplatefile_withvars(), greeting = "Welcome", name = "Genie")
@test String(r.body) |> fws ==
"<!DOCTYPE html><html><head><title>$name test</title></head><body><div class=\"template\"><h1>$greeting</h1>
<div><p>This is a $name test</p></div><hr$(Genie.config.html_parser_close_tag)></div><footer>Just a footer</footer>
</body></html>" |> fws
end;
@test r.status == 200
@test r.headers[1]["Content-Type"] == "text/html; charset=utf-8"
end;
end; | Genie | https://github.com/GenieFramework/Genie.jl.git |
|
[
"MIT"
] | 5.30.6 | 376aa3d800f4da32d232f2d9a1685e34e2911b4a | code | 1120 | @safetestset "Control flow rendering" begin
@safetestset "IF conditional rendering" begin
@safetestset "IF true" begin
using Genie
using Genie.Renderer.Html
import Genie.Util: fws
view = raw"""
<section class='block'>
<% if true; [ %>
<h1>Hello</h1>
<p>Welcome</p>
<% ]end %>
</section>"""
@test String(html(view).body) |> fws ==
"""<!DOCTYPE html><html><body><section class="block"><h1>Hello</h1><p>Welcome</p></section></body></html>""" |> fws
end;
@safetestset "IF false" begin
using Genie
using Genie.Renderer.Html
import Genie.Util: fws
view = raw"""
<section class='block'>
<% if false; [ %>
<h1>Hello</h1>
<p>Welcome</p>
<% ]end %>
</section>"""
@test String(html(view).body) |> fws ==
"""<!DOCTYPE html><html><body><section class="block"></section></body></html>""" |> fws
end;
end;
end; | Genie | https://github.com/GenieFramework/Genie.jl.git |
Subsets and Splits