Skip to content

Commit 8841732

Browse files
zeripathsapk6543
authored andcommitted
Add contrib/environment-to-ini (#9519)
* Add contrib/environment-to-ini This contrib command provides a mechanism to allow arbitrary setting of ini values using the environment variable in a more docker standard fashion. Environment variable keys should be structured as: "GITEA__SECTION_NAME__KEY_NAME" Use of the command is explained in the README. Partial fix for #350 Closes #7287 * Update contrib/environment-to-ini/environment-to-ini.go Co-Authored-By: 6543 <[email protected]> Co-authored-by: Antoine GIRARD <[email protected]> Co-authored-by: 6543 <[email protected]>
1 parent 4ee9746 commit 8841732

File tree

2 files changed

+290
-0
lines changed

2 files changed

+290
-0
lines changed

contrib/environment-to-ini/README

Lines changed: 66 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
1+
Environment To Ini
2+
==================
3+
4+
Multiple docker users have requested that the Gitea docker is changed
5+
to permit arbitrary configuration via environment variables.
6+
7+
Gitea needs to use an ini file for configuration because the running
8+
environment that starts the docker may not be the same as that used
9+
by the hooks. An ini file also gives a good default and means that
10+
users do not have to completely provide a full environment.
11+
12+
With those caveats above, this command provides a generic way of
13+
converting suitably structured environment variables into any ini
14+
value.
15+
16+
To use the command is very simple just run it and the default gitea
17+
app.ini will be rewritten to take account of the variables provided,
18+
however there are various options to give slightly different
19+
behavior and these can be interrogated with the `-h` option.
20+
21+
The environment variables should be of the form:
22+
23+
GITEA__SECTION_NAME__KEY_NAME
24+
25+
Environment variables are usually restricted to a reduced character
26+
set "0-9A-Z_" - in order to allow the setting of sections with
27+
characters outside of that set, they should be escaped as following:
28+
"_0X2E_" for ".". The entire section and key names can be escaped as
29+
a UTF8 byte string if necessary. E.g. to configure:
30+
31+
"""
32+
...
33+
[log.console]
34+
COLORIZE=false
35+
STDERR=true
36+
...
37+
"""
38+
39+
You would set the environment variables: "GITEA__LOG_0x2E_CONSOLE__COLORIZE=false"
40+
and "GITEA__LOG_0x2E_CONSOLE__STDERR=false". Other examples can be found
41+
on the configuration cheat sheet.
42+
43+
To plug this command in to the docker, you simply compile the provided go file using:
44+
45+
go build environment-to-ini.go
46+
47+
And copy the resulting `environment-to-ini` command to /app/gitea in the docker.
48+
49+
Apply the below patch to /etc/s6/gitea.setup to wire this in.
50+
51+
If you find this useful please comment on #7287
52+
53+
54+
diff --git a/docker/root/etc/s6/gitea/setup b/docker/root/etc/s6/gitea/setup
55+
index f87ce9115..565bfcba9 100755
56+
--- a/docker/root/etc/s6/gitea/setup
57+
+++ b/docker/root/etc/s6/gitea/setup
58+
@@ -44,6 +44,8 @@ if [ ! -f ${GITEA_CUSTOM}/conf/app.ini ]; then
59+
SECRET_KEY=${SECRET_KEY:-""} \
60+
envsubst < /etc/templates/app.ini > ${GITEA_CUSTOM}/conf/app.ini
61+
62+
+ /app/gitea/environment-to-ini -c ${GITEA_CUSTOM}/conf/app.ini
63+
+
64+
chown ${USER}:git ${GITEA_CUSTOM}/conf/app.ini
65+
fi
66+
Lines changed: 224 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,224 @@
1+
// Copyright 2019 The Gitea Authors. All rights reserved.
2+
// Use of this source code is governed by a MIT-style
3+
// license that can be found in the LICENSE file.
4+
5+
package main
6+
7+
import (
8+
"os"
9+
"regexp"
10+
"strconv"
11+
"strings"
12+
13+
"code.gitea.io/gitea/modules/log"
14+
"code.gitea.io/gitea/modules/setting"
15+
16+
"github.com/unknwon/com"
17+
"github.com/urfave/cli"
18+
ini "gopkg.in/ini.v1"
19+
)
20+
21+
// EnvironmentPrefix environment variables prefixed with this represent ini values to write
22+
const EnvironmentPrefix = "GITEA"
23+
24+
func main() {
25+
app := cli.NewApp()
26+
app.Name = "environment-to-ini"
27+
app.Usage = "Use provided environment to update configuration ini"
28+
app.Description = `As a helper to allow docker users to update the gitea configuration
29+
through the environment, this command allows environment variables to
30+
be mapped to values in the ini.
31+
32+
Environment variables of the form "GITEA__SECTION_NAME__KEY_NAME"
33+
will be mapped to the ini section "[section_name]" and the key
34+
"KEY_NAME" with the value as provided.
35+
36+
Environment variables are usually restricted to a reduced character
37+
set "0-9A-Z_" - in order to allow the setting of sections with
38+
characters outside of that set, they should be escaped as following:
39+
"_0X2E_" for ".". The entire section and key names can be escaped as
40+
a UTF8 byte string if necessary. E.g. to configure:
41+
42+
"""
43+
...
44+
[log.console]
45+
COLORIZE=false
46+
STDERR=true
47+
...
48+
"""
49+
50+
You would set the environment variables: "GITEA__LOG_0x2E_CONSOLE__COLORIZE=false"
51+
and "GITEA__LOG_0x2E_CONSOLE__STDERR=false". Other examples can be found
52+
on the configuration cheat sheet.`
53+
app.Flags = []cli.Flag{
54+
cli.StringFlag{
55+
Name: "custom-path, C",
56+
Value: setting.CustomPath,
57+
Usage: "Custom path file path",
58+
},
59+
cli.StringFlag{
60+
Name: "config, c",
61+
Value: setting.CustomConf,
62+
Usage: "Custom configuration file path",
63+
},
64+
cli.StringFlag{
65+
Name: "work-path, w",
66+
Value: setting.AppWorkPath,
67+
Usage: "Set the gitea working path",
68+
},
69+
cli.StringFlag{
70+
Name: "out, o",
71+
Value: "",
72+
Usage: "Destination file to write to",
73+
},
74+
cli.BoolFlag{
75+
Name: "clear",
76+
Usage: "Clears the matched variables from the environment",
77+
},
78+
cli.StringFlag{
79+
Name: "prefix, p",
80+
Value: EnvironmentPrefix,
81+
Usage: "Environment prefix to look for - will be suffixed by __ (2 underscores)",
82+
},
83+
}
84+
app.Action = runEnvironmentToIni
85+
setting.SetCustomPathAndConf("", "", "")
86+
87+
err := app.Run(os.Args)
88+
if err != nil {
89+
log.Fatal("Failed to run app with %s: %v", os.Args, err)
90+
}
91+
}
92+
93+
func runEnvironmentToIni(c *cli.Context) error {
94+
providedCustom := c.String("custom-path")
95+
providedConf := c.String("config")
96+
providedWorkPath := c.String("work-path")
97+
setting.SetCustomPathAndConf(providedCustom, providedConf, providedWorkPath)
98+
99+
cfg := ini.Empty()
100+
if com.IsFile(setting.CustomConf) {
101+
if err := cfg.Append(setting.CustomConf); err != nil {
102+
log.Fatal("Failed to load custom conf '%s': %v", setting.CustomConf, err)
103+
}
104+
} else {
105+
log.Warn("Custom config '%s' not found, ignore this if you're running first time", setting.CustomConf)
106+
}
107+
cfg.NameMapper = ini.AllCapsUnderscore
108+
109+
prefix := c.String("prefix") + "__"
110+
111+
for _, kv := range os.Environ() {
112+
idx := strings.IndexByte(kv, '=')
113+
if idx < 0 {
114+
continue
115+
}
116+
eKey := kv[:idx]
117+
value := kv[idx+1:]
118+
if !strings.HasPrefix(eKey, prefix) {
119+
continue
120+
}
121+
eKey = eKey[len(prefix):]
122+
sectionName, keyName := DecodeSectionKey(eKey)
123+
if len(keyName) == 0 {
124+
continue
125+
}
126+
section, err := cfg.GetSection(sectionName)
127+
if err != nil {
128+
section, err = cfg.NewSection(sectionName)
129+
if err != nil {
130+
log.Error("Error creating section: %s : %v", sectionName, err)
131+
continue
132+
}
133+
}
134+
key := section.Key(keyName)
135+
if key == nil {
136+
key, err = section.NewKey(keyName, value)
137+
if err != nil {
138+
log.Error("Error creating key: %s in section: %s with value: %s : %v", keyName, sectionName, value, err)
139+
continue
140+
}
141+
}
142+
key.SetValue(value)
143+
}
144+
destination := c.String("out")
145+
if len(destination) == 0 {
146+
destination = setting.CustomConf
147+
}
148+
err := cfg.SaveTo(destination)
149+
if err != nil {
150+
return err
151+
}
152+
if c.Bool("clear") {
153+
for _, kv := range os.Environ() {
154+
idx := strings.IndexByte(kv, '=')
155+
if idx < 0 {
156+
continue
157+
}
158+
eKey := kv[:idx]
159+
if strings.HasPrefix(eKey, prefix) {
160+
_ = os.Unsetenv(eKey)
161+
}
162+
}
163+
}
164+
return nil
165+
}
166+
167+
const escapeRegexpString = "_0[xX](([0-9a-fA-F][0-9a-fA-F])+)_"
168+
169+
var escapeRegex = regexp.MustCompile(escapeRegexpString)
170+
171+
// DecodeSectionKey will decode a portable string encoded Section__Key pair
172+
// Portable strings are considered to be of the form [A-Z0-9_]*
173+
// We will encode a disallowed value as the UTF8 byte string preceded by _0X and
174+
// followed by _. E.g. _0X2C_ for a '-' and _0X2E_ for '.'
175+
// Section and Key are separated by a plain '__'.
176+
// The entire section can be encoded as a UTF8 byte string
177+
func DecodeSectionKey(encoded string) (string, string) {
178+
section := ""
179+
key := ""
180+
181+
inKey := false
182+
last := 0
183+
escapeStringIndices := escapeRegex.FindAllStringIndex(encoded, -1)
184+
for _, unescapeIdx := range escapeStringIndices {
185+
preceding := encoded[last:unescapeIdx[0]]
186+
if !inKey {
187+
if splitter := strings.Index(preceding, "__"); splitter > -1 {
188+
section += preceding[:splitter]
189+
inKey = true
190+
key += preceding[splitter+2:]
191+
} else {
192+
section += preceding
193+
}
194+
} else {
195+
key += preceding
196+
}
197+
toDecode := encoded[unescapeIdx[0]+3 : unescapeIdx[1]-1]
198+
decodedBytes := make([]byte, len(toDecode)/2)
199+
for i := 0; i < len(toDecode)/2; i++ {
200+
// Can ignore error here as we know these should be hexadecimal from the regexp
201+
byteInt, _ := strconv.ParseInt(toDecode[2*i:2*i+2], 16, 0)
202+
decodedBytes[i] = byte(byteInt)
203+
}
204+
if inKey {
205+
key += string(decodedBytes)
206+
} else {
207+
section += string(decodedBytes)
208+
}
209+
last = unescapeIdx[1]
210+
}
211+
remaining := encoded[last:]
212+
if !inKey {
213+
if splitter := strings.Index(remaining, "__"); splitter > -1 {
214+
section += remaining[:splitter]
215+
inKey = true
216+
key += remaining[splitter+2:]
217+
} else {
218+
section += remaining
219+
}
220+
} else {
221+
key += remaining
222+
}
223+
return section, key
224+
}

0 commit comments

Comments
 (0)