Squashed 'src/deps/src/lua-resty-env/' content from commit adb294def

git-subtree-dir: src/deps/src/lua-resty-env
git-subtree-split: adb294def823dd910ffa11972d2c61eab7cfce3e
This commit is contained in:
Théophile Diot 2023-06-30 15:38:32 -04:00
commit 1a7d4e58be
13 changed files with 707 additions and 0 deletions

12
.circleci/config.yml Normal file
View File

@ -0,0 +1,12 @@
version: 2
jobs:
build:
docker:
- image: quay.io/3scale/s2i-openresty-centos7:luarocks-build
working_directory: /opt/app-root/lua-resty-env
steps:
- checkout
- run: luarocks make rockspecs/*.rockspec
- run: luarocks build rockspecs/*.rockspec
- run: luarocks install busted
- run: bin/busted

12
.codeclimate.yml Normal file
View File

@ -0,0 +1,12 @@
---
engines:
fixme:
enabled: true
luacheck:
enabled: true
channel: beta
ratings:
paths:
- "**/*.lua"
exclude_paths:
- .idea

2
.gitignore vendored Normal file
View File

@ -0,0 +1,2 @@
/lua-resty-env-*
!*.rockspec

3
.luacheckrc Normal file
View File

@ -0,0 +1,3 @@
std = 'ngx_lua+lua52' -- lua52 has table.pack
files["spec"] = {std = "+busted"}

201
LICENSE Normal file
View File

@ -0,0 +1,201 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "{}"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright {yyyy} {name of copyright owner}
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

2
Makefile Normal file
View File

@ -0,0 +1,2 @@
test:
@resty -e "require('busted.runner')({ standalone = false })"

154
README.md Normal file
View File

@ -0,0 +1,154 @@
Name
====
lua-resty-env - Lua cache for calls to `os.getenv`.
Table of Contents
=================
* [Name](#name)
* [Status](#status)
* [Description](#description)
* [Synopsis](#synopsis)
* [Methods](#methods)
* [get](#get)
* [set](#set)
* [value](#value)
* [enabled](#enabled)
* [reset](#reset)
* [Installation](#installation)
* [TODO](#todo)
* [Community](#community)
* [Bugs and Patches](#bugs-and-patches)
* [Author](#author)
* [Copyright and License](#copyright-and-license)
* [See Also](#see-also)
Status
======
This library is considered production ready.
Description
===========
This Lua library is a cache for calls to `os.getenv`.
This library acts as a mediator between other libraries and the environment variables.
Variables can not only be get but also set.
Synopsis
========
```lua
env SOME_VARIABLE;
http {
server {
location /test {
content_by_lua_block {
local resty_env = require 'resty.env'
ngx.say("SOME_VARIABLE: ", resty_env.get('SOME_VARIABLE'))
}
}
}
```
[Back to TOC](#table-of-contents)
Methods
=======
All the methods are expected to be called on the module without self.
[Back to TOC](#table-of-contents)
get
---
`syntax: val = env.get(name)`
Returns environment value from the cache or uses `os.getenv` to get it.
[Back to TOC](#table-of-contents)
set
-------
`syntax: prev = env.set(name, value)`
Sets the the `value` to the cache and returns the previous value in the cache.
[Back to TOC](#table-of-contents)
list
-------
`syntax: table = env.list()`
Returns a table with all environment variables. Names are keys and values are values.
[Back to TOC](#table-of-contents)
enabled
----------
`syntax: ok = env.enabled(name)`
Returns true if the environment variable has truthy value (`1`, `true`), false (`0`, `false`) or `nil`.
[Back to TOC](#table-of-contents)
reset
------------
`syntax: env = env.reset()`
Resets the internal cache.
[Back to TOC](#table-of-contents)
Installation
============
If you are using the OpenResty bundle (http://openresty.org ), then
you can use [opm](https://github.com/openresty/opm#synopsis) to install this package.
```shell
opm get 3scale/lua-resty-env
```
[Back to TOC](#table-of-contents)
Bugs and Patches
================
Please report bugs or submit patches by
1. creating a ticket on the [GitHub Issue Tracker](http://github.com/3scale/lua-resty-env/issues),
[Back to TOC](#table-of-contents)
Author
======
Michal "mikz" Cichra <mcichra@redhat.com>, Red Hat Inc.
[Back to TOC](#table-of-contents)
Copyright and License
=====================
This module is licensed under the Apache License Version 2.0.
Copyright (C) 2016-2017, Red Hat Inc.
All rights reserved.
See [LICENSE](LICENSE) for the full license.
[Back to TOC](#table-of-contents)
See Also
========
* the APIcast API Gateway: https://github.com/3scale/apicast/#readme
[Back to TOC](#table-of-contents)

9
bin/busted Executable file
View File

@ -0,0 +1,9 @@
#!/usr/bin/env resty
if ngx ~= nil then
ngx.exit = function()end
end
-- Busted command-line runner
require 'busted.runner'({ standalone = false })

11
dist.ini Normal file
View File

@ -0,0 +1,11 @@
# distribution config for opm packaging
name = lua-resty-env
abstract = Cache for os.getenv calls
author = Michal Cichra (mikz)
is_original = yes
license = apache2
lib_dir = src
doc_dir = .
repo_link = https://github.com/3scale/lua-resty-env
main_module = src/resty/env.lua
requires = ngx_http_lua

View File

@ -0,0 +1,21 @@
package = "lua-resty-env"
version = "0.3.0-1"
source = {
url = "https://github.com/3scale/lua-resty-env/archive/v0.3.0.tar.gz",
md5 = "00c05a22173d0b06927118b85c98e029",
dir = "lua-resty-env-0.3.0",
}
description = {
summary = "lua-resty-env - Lua cache for calls to `os.getenv`.",
detailed = "lua-resty-env - Lua cache for calls to `os.getenv`.",
homepage = "https://github.com/3scale/lua-resty-env",
license = "Apache License 2.0"
}
dependencies = {
}
build = {
type = "builtin",
modules = {
["resty.env"] = "src/resty/env.lua"
}
}

View File

@ -0,0 +1,19 @@
package = "lua-resty-env"
version = "scm-1"
source = {
url = "git+https://github.com/3scale/lua-resty-env.git"
}
description = {
summary = "lua-resty-env - Lua cache for calls to `os.getenv`.",
detailed = "lua-resty-env - Lua cache for calls to `os.getenv`.",
homepage = "https://github.com/3scale/lua-resty-env",
license = "Apache License 2.0"
}
dependencies = {
}
build = {
type = "builtin",
modules = {
["resty.env"] = "src/resty/env.lua"
}
}

89
spec/resty/env_spec.lua Normal file
View File

@ -0,0 +1,89 @@
local _M = require 'resty.env'
describe('env', function()
local env
before_each(function() env = _M.env end)
after_each(function() _M.env = env end)
describe('.list', function()
it('returns contents of the ENV variable', function()
local list = _M.list()
assert.truthy(list.PATH)
assert.truthy(list.HOME)
assert.truthy(list.PWD)
end)
end)
describe('.get', function()
local path = os.getenv("PATH")
it('returns contents of the ENV variable', function()
assert.equal(path, _M.get('PATH'))
end)
it('caches the result', function()
_M.get('PATH')
assert.equal(path, _M.env.PATH)
end)
it('reads from the cache first', function()
_M.env = { ['SOME_MISSING_ENV_VAR'] = 'somevalue' }
assert.equal('somevalue', _M.get("SOME_MISSING_ENV_VAR"))
end)
end)
describe('.value', function()
it('returns false instead of empty value', function()
_M.set('KEY', '')
assert.equal(false, _M.value('KEY'))
end)
it('returns the value if not emptu', function()
_M.set('KEY', 'value')
assert.equal('value', _M.value('KEY'))
end)
end)
describe('.set', function()
it('saves value to the cache', function()
_M.set('SOME_MISSING_KEY', 'val')
assert.equal('val', _M.env.SOME_MISSING_KEY)
end)
it('calls setenv', function()
local key = 'SOME_UNUSED_KEY'
assert.falsy(os.getenv(key))
_M.set(key, 'value')
assert.equal('value', os.getenv(key))
end)
it('converts the value to string', function()
_M.set('NUMERIC_VALUE', 1234)
assert.equal('1234', _M.env.NUMERIC_VALUE)
end)
it('works with nil', function()
assert.truthy(_M.get('_'))
_M.set('_', nil)
assert.equal(nil, os.getenv('_'))
end)
end)
describe('.reset', function()
it('cleans the cache', function()
_M.env.SOMETHING_EMPTY = 'foo'
_M.reset()
assert.same(nil, _M.env.SOMETHING_EMPTY)
end)
end)
end)

172
src/resty/env.lua Normal file
View File

@ -0,0 +1,172 @@
------------
-- Resty ENV
-- OpenResty module for working with ENV variables.
--
-- @module resty.env
-- @author mikz
-- @license Apache License Version 2.0
local _M = {
_VERSION = '0.4.0'
}
local tostring = tostring
local sub = string.sub
local find = string.find
local pairs = pairs
local getenv = os.getenv
local ffi = require('ffi')
ffi.cdef([=[
int setenv(const char*, const char*, int);
int unsetenv(const char*);
extern char **environ;
]=])
local C = ffi.C
local function ffi_error()
return C.strerror(ffi.errno())
end
local function unsetenv(name)
if C.unsetenv(name) == -1 then
return nil, ffi_error()
else
return true
end
end
local function setenv(name, value, overwrite)
local overwrite_flag = overwrite and 1 or 0
if not value then
return nil, 'missing value'
end
if C.setenv(name, value, overwrite_flag) == -1 then
return nil, C.strerror(ffi.errno())
else
return value
end
end
local function environ() -- return whole environment as table
local env = C.environ
if not env then return nil end
local ret = {}
local i = 0
while env[i] ~= nil do
local e = ffi.string(env[i])
local eq = find(e, '=')
if eq then
ret[sub(e, 1, eq - 1)] = sub(e, eq + 1)
end
i = i + 1
end
for name, value in pairs(_M.env) do
ret[name] = value
end
return ret
end
local cached = {}
local function fetch(name)
local value
if cached[name] then
value = _M.env[name]
else
value = getenv(name)
ngx.log(ngx.DEBUG, 'env: ', name, ' = ', value)
_M.env[name] = value
cached[name] = true
end
return value
end
--- Return a table with all environment variables.
function _M.list()
return environ()
end
--- Return the raw value from ENV. Uses local cache.
-- @tparam string name name of the environment variable
function _M.get(name)
return _M.env[name] or fetch(name)
end
local value_mapping = {
[''] = false
}
--- Return value from ENV.
--- Returns false if it is empty. Uses @{get} internally.
-- @tparam string name name of the environment variable
function _M.value(name)
local value = _M.get(name)
local mapped = value_mapping[value]
if mapped == nil then
return value
else
return mapped
end
end
local env_mapping = {
['true'] = true,
['false'] = false,
['1'] = true,
['0'] = false,
[''] = false
}
--- Returns true/false from ENV variable.
--- Converts 0 to false and 1 to true.
-- @tparam string name name of the environment variable
function _M.enabled(name)
return env_mapping[_M.get(name)]
end
--- Sets value to the local cache.
-- @tparam string name name of the environment variable
-- @tparam string value value to be cached
-- @see resty.env.get
function _M.set(name, value)
local env = _M.env
local val = value and tostring(value)
local ok, err
if val then
ok, err = setenv(name, val, true)
else
ok, err = unsetenv(name)
end
local previous = env[name]
if ok then
env[name] = val
cached[name] = nil
end
return previous, err
end
--- Reset local cache.
function _M.reset()
_M.env = {}
cached = {}
return _M
end
return _M.reset()