ci: tests, build, and FTP deploy of build/ without --delete
Master runs unit tests, builds game.js, then uploads build/ via lftp.
The job expands \$timftproot / \${timftproot} inside projectftp itself,
normalizes double slashes, and refuses a target that is the FTP root,
not named meteors, or already holds foreign files. Feature branches
run tests and build only. README covers how to play, how to build,
and the architecture.
@@ -1,5 +1,65 @@
1
1
# Meteors
2
2
3
A Meteos-inspired puzzle game for the web, built on [frameworkv3](https://git.timfalken.com/timfa/frameworkv3).
3
Puzzelspel voor het web, zwaar geïnspireerd door *Meteos* (Nintendo DS). Gebouwd op
4
[frameworkv3](https://git.timfalken.com/timfa/frameworkv3) (WebGL). Speelbaar met
5
muis op desktop en met touch op mobiel, ook in portretstand.
4
6
5
This repository is new; the game itself is not here yet.
7
Live (na de eerste deploy): https://projects.timfalken.com/meteors/
8
9
## Spelen
10
11
1. Open `build/index.html` (lokaal of live) en druk op **Spelen**.
12
2. Elke seconde valt er een blokje van één van vijf kleuren in een willekeurige kolom.
13
3. In een stilliggende kolom sleep je blokjes verticaal; ze wisselen om met de blokjes waar je langs gaat.
14
4. Drie of meer blokjes van dezelfde kleur op een rij (horizontaal of verticaal) worden donkergrijs, krijgen een vlam en springen omhoog. Alles wat erop stond, vliegt mee.
15
5. Blokjes die boven de bovenrand van het veld (10×13) verdwijnen, leveren punten op.
16
6. Trek een blokje naar de top van zijn kolom en dan nóg verder omhoog: het springt tot net onder de bovenrand. Komt het tegen een vliegend cluster aan, dan duwt het die kolom één tegel omhoog. Vormt dat een nieuwe drie-op-een-rij, dan springt het hele cluster opnieuw.
17
7. Een kolom die van onder tot boven vol ligt, gaat op slot (donkergrijs, geen interactie, geen nieuwe val). Zitten alle tien kolommen vast, dan is het spel voorbij en ga je terug naar het menu.
18
19
Het standaardveld is de planeet **Terra** (volk: Terrans), met middelmatige zwaartekracht, luchtweerstand en massa. Die drie waarden, plus de Power, staan in de HUD; later (stage 3) kies je zelf een planeet.
20
21
## Lokaal bouwen en draaien
22
23
```bash
24
# Eenmalig / bij een framework-update: bundel frameworkv3 en kopieer hem.
25
# cd /pad/naar/frameworkv3 && ./glbuild.sh
26
# cp js/framework.js /pad/naar/meteors/build/framework.js
27
28
# Tests
29
node --test test/*.test.js
30
31
# Game-bundel (src/ → build/game.js)
32
./src/build.sh
33
# of: npm run build
34
35
# Placeholder-plaatjes opnieuw maken (optioneel; Tim kan ze zelf vervangen)
36
python3 scripts/make-placeholders.py
37
38
# Statische server
39
python3 -m http.server 8080 --directory build
40
# spel: http://localhost:8080/
41
```
42
43
## Architectuur
44
45
De spelkern is deterministisch en staat los van tekenen en invoer, zodat stage 2
46
(multiplayer) dezelfde simulatie kan hergebruiken.
47
48
| Pad | Rol |
49
| --- | --- |
50
| `src/planet.js` | Planeet: zwaartekracht, luchtweerstand, massa, kleuren/vormen, spronghoogte, Power |
51
| `src/rng.js` | Seedable RNG (tests en later replays) |
52
| `src/gameCore.js` | Simulatie: vallen, wisselen, match-3, raketsprong, linken, push-up + her-sprong, landen + 3 s wachten, kolom-slot, game over, punten |
53
| `src/main.js` | Menu, HUD, frameworkv3-scene, muis/touch, schaal naar het scherm |
54
| `src/build.sh` | Concateneert de bronnen naar `build/game.js` (zelfde patroon als de raytracer) |
55
| `build/` | Speelbare output: `index.html`, `style.css`, `framework.js`, `game.js`, `images/` |
56
| `test/` | Unit tests (`node --test`) voor de kern en de deploy-guard |
57
| `ci/` | FTP-deploy, **zonder** `--delete`. Expandeert `$timftproot` zelf. Weigert een map die niet leeg is of niet van Meteors is. |
58
59
Sprongfysica is parametrisch. Een horizontale match van 3 springt `13 / jumpsToClear` tegels hoog; een verticale match van 3 krijgt 120 % daarvan, en elk extra blokje +5 % (wordt nergens in het spel uitgelegd). De massa bepaalt hoe lang de sprong omhoog duurt (onafhankelijk van de hoogte); de luchtweerstand bepaalt de constante valsnelheid daarna.
60
61
## Deploy
62
63
BlueGit CI (`blue-ci-cd.yml`) draait tests en een build op feature-branches en op `master`. Op `master` volgt daarna `ftp_upload`: `build/` gaat via FTP naar `projectftp` (secret: `$timftproot/meteors`; de job expandeert `$timftproot` zelf en normaliseert dubbele slashes). **Geen `--delete`**. De eerste deploy weigert te schrijven als de doelmap al vreemde bestanden bevat.
64
65
Secrets: `timftphost` / `timftpuser` / `timftppassword` / `timftproot` (groep), `projectftp` (dit project).
@@ -1,5 +1,65 @@1
# Meteors1
# Meteors2
2
3
A Meteos-inspired puzzle game for the web, built on [frameworkv3](https://git.timfalken.com/timfa/frameworkv3).3
Puzzelspel voor het web, zwaar geïnspireerd door *Meteos* (Nintendo DS). Gebouwd op4
[frameworkv3](https://git.timfalken.com/timfa/frameworkv3) (WebGL). Speelbaar met5
muis op desktop en met touch op mobiel, ook in portretstand.4
6
5
This repository is new; the game itself is not here yet.7
Live (na de eerste deploy): https://projects.timfalken.com/meteors/8
9
## Spelen10
11
1. Open `build/index.html` (lokaal of live) en druk op **Spelen**.12
2. Elke seconde valt er een blokje van één van vijf kleuren in een willekeurige kolom.13
3. In een stilliggende kolom sleep je blokjes verticaal; ze wisselen om met de blokjes waar je langs gaat.14
4. Drie of meer blokjes van dezelfde kleur op een rij (horizontaal of verticaal) worden donkergrijs, krijgen een vlam en springen omhoog. Alles wat erop stond, vliegt mee.15
5. Blokjes die boven de bovenrand van het veld (10×13) verdwijnen, leveren punten op.16
6. Trek een blokje naar de top van zijn kolom en dan nóg verder omhoog: het springt tot net onder de bovenrand. Komt het tegen een vliegend cluster aan, dan duwt het die kolom één tegel omhoog. Vormt dat een nieuwe drie-op-een-rij, dan springt het hele cluster opnieuw.17
7. Een kolom die van onder tot boven vol ligt, gaat op slot (donkergrijs, geen interactie, geen nieuwe val). Zitten alle tien kolommen vast, dan is het spel voorbij en ga je terug naar het menu.18
19
Het standaardveld is de planeet **Terra** (volk: Terrans), met middelmatige zwaartekracht, luchtweerstand en massa. Die drie waarden, plus de Power, staan in de HUD; later (stage 3) kies je zelf een planeet.20
21
## Lokaal bouwen en draaien22
23
```bash24
# Eenmalig / bij een framework-update: bundel frameworkv3 en kopieer hem.25
# cd /pad/naar/frameworkv3 && ./glbuild.sh26
# cp js/framework.js /pad/naar/meteors/build/framework.js27
28
# Tests29
node --test test/*.test.js30
31
# Game-bundel (src/ → build/game.js)32
./src/build.sh33
# of: npm run build34
35
# Placeholder-plaatjes opnieuw maken (optioneel; Tim kan ze zelf vervangen)36
python3 scripts/make-placeholders.py37
38
# Statische server39
python3 -m http.server 8080 --directory build40
# spel: http://localhost:8080/41
```42
43
## Architectuur44
45
De spelkern is deterministisch en staat los van tekenen en invoer, zodat stage 246
(multiplayer) dezelfde simulatie kan hergebruiken.47
48
| Pad | Rol |49
| --- | --- |50
| `src/planet.js` | Planeet: zwaartekracht, luchtweerstand, massa, kleuren/vormen, spronghoogte, Power |51
| `src/rng.js` | Seedable RNG (tests en later replays) |52
| `src/gameCore.js` | Simulatie: vallen, wisselen, match-3, raketsprong, linken, push-up + her-sprong, landen + 3 s wachten, kolom-slot, game over, punten |53
| `src/main.js` | Menu, HUD, frameworkv3-scene, muis/touch, schaal naar het scherm |54
| `src/build.sh` | Concateneert de bronnen naar `build/game.js` (zelfde patroon als de raytracer) |55
| `build/` | Speelbare output: `index.html`, `style.css`, `framework.js`, `game.js`, `images/` |56
| `test/` | Unit tests (`node --test`) voor de kern en de deploy-guard |57
| `ci/` | FTP-deploy, **zonder** `--delete`. Expandeert `$timftproot` zelf. Weigert een map die niet leeg is of niet van Meteors is. |58
59
Sprongfysica is parametrisch. Een horizontale match van 3 springt `13 / jumpsToClear` tegels hoog; een verticale match van 3 krijgt 120 % daarvan, en elk extra blokje +5 % (wordt nergens in het spel uitgelegd). De massa bepaalt hoe lang de sprong omhoog duurt (onafhankelijk van de hoogte); de luchtweerstand bepaalt de constante valsnelheid daarna.60
61
## Deploy62
63
BlueGit CI (`blue-ci-cd.yml`) draait tests en een build op feature-branches en op `master`. Op `master` volgt daarna `ftp_upload`: `build/` gaat via FTP naar `projectftp` (secret: `$timftproot/meteors`; de job expandeert `$timftproot` zelf en normaliseert dubbele slashes). **Geen `--delete`**. De eerste deploy weigert te schrijven als de doelmap al vreemde bestanden bevat.64
65
Secrets: `timftphost` / `timftpuser` / `timftppassword` / `timftproot` (groep), `projectftp` (dit project).@@ -0,0 +1,57 @@
1
# BlueGit CI for Meteors: unit tests, build of build/, FTP deploy of build/.
2
# Group secrets: timftphost, timftpuser, timftppassword, timftproot (protected).
3
# Repo secret: projectftp (protected; Tim set this to $timftproot/meteors).
4
# GEEN mirror --delete: live files mogen niet verdwijnen.
5
# Deployt map build/ (NIET de repo-root).
6
stages: [test, build, deploy]
7
8
workflow:
9
rules:
10
- if: $CI_COMMIT_TAG != ""
11
when: never
12
- if: $CI_PIPELINE_SOURCE == "merge_request_event"
13
- if: $CI_COMMIT_BRANCH == "master"
14
- if: $CI_COMMIT_BRANCH =~ /^feature\//
15
16
unit_tests:
17
stage: test
18
image: node:20-bookworm
19
script:
20
- node --test test/*.test.js
21
22
build_game:
23
stage: build
24
image: debian:bookworm-slim
25
needs: [unit_tests]
26
script:
27
- apt-get update -qq && apt-get install -y -qq bash ca-certificates >/dev/null
28
- chmod +x src/build.sh
29
- ./src/build.sh
30
- test -f build/game.js
31
- test -f build/framework.js
32
- test -f build/index.html
33
- test -f build/style.css
34
- test -d build/images
35
- test -f build/images/block-ember.png
36
- test -f build/images/flame.png
37
artifacts:
38
paths:
39
- build/
40
expire_in: 7d
41
42
ftp_upload:
43
stage: deploy
44
image: debian:bookworm-slim
45
needs: [build_game]
46
resource_group: production
47
environment:
48
name: production
49
url: https://projects.timfalken.com/meteors/
50
rules:
51
# Alleen master push (protected secrets). Geen feature/MR-deploys.
52
- if: $CI_COMMIT_BRANCH == "master" && $CI_PIPELINE_SOURCE != "merge_request_event"
53
script:
54
- apt-get update -qy
55
- apt-get install -y --no-install-recommends lftp python3 ca-certificates
56
- python3 ci/deploy_guard.py
57
- python3 ci/deploy.py
@@ -0,0 +1,57 @@1
# BlueGit CI for Meteors: unit tests, build of build/, FTP deploy of build/.2
# Group secrets: timftphost, timftpuser, timftppassword, timftproot (protected).3
# Repo secret: projectftp (protected; Tim set this to $timftproot/meteors).4
# GEEN mirror --delete: live files mogen niet verdwijnen.5
# Deployt map build/ (NIET de repo-root).6
stages: [test, build, deploy]7
8
workflow:9
rules:10
- if: $CI_COMMIT_TAG != ""11
when: never12
- if: $CI_PIPELINE_SOURCE == "merge_request_event"13
- if: $CI_COMMIT_BRANCH == "master"14
- if: $CI_COMMIT_BRANCH =~ /^feature\//15
16
unit_tests:17
stage: test18
image: node:20-bookworm19
script:20
- node --test test/*.test.js21
22
build_game:23
stage: build24
image: debian:bookworm-slim25
needs: [unit_tests]26
script:27
- apt-get update -qq && apt-get install -y -qq bash ca-certificates >/dev/null28
- chmod +x src/build.sh29
- ./src/build.sh30
- test -f build/game.js31
- test -f build/framework.js32
- test -f build/index.html33
- test -f build/style.css34
- test -d build/images35
- test -f build/images/block-ember.png36
- test -f build/images/flame.png37
artifacts:38
paths:39
- build/40
expire_in: 7d41
42
ftp_upload:43
stage: deploy44
image: debian:bookworm-slim45
needs: [build_game]46
resource_group: production47
environment:48
name: production49
url: https://projects.timfalken.com/meteors/50
rules:51
# Alleen master push (protected secrets). Geen feature/MR-deploys.52
- if: $CI_COMMIT_BRANCH == "master" && $CI_PIPELINE_SOURCE != "merge_request_event"53
script:54
- apt-get update -qy55
- apt-get install -y --no-install-recommends lftp python3 ca-certificates56
- python3 ci/deploy_guard.py57
- python3 ci/deploy.py@@ -0,0 +1,162 @@
1
#!/usr/bin/env python3
2
"""FTP-upload of build/. Never --delete. Refuses a non-empty foreign folder."""
3
import os
4
import subprocess
5
import sys
6
from pathlib import Path
7
from urllib.parse import urlsplit
8
9
sys.path.insert(0, str(Path(__file__).resolve().parent))
10
from deploy_guard import DeployGuardError, project_dir # noqa: E402
11
12
ROOT = Path(__file__).resolve().parents[1]
13
14
# Files we ourselves publish; a first deploy may only land in an empty/new
15
# folder, or a folder that already only contains a previous Meteors deploy.
16
OURS = {
17
'index.html', 'game.js', 'framework.js', 'style.css', 'images',
18
'.', '..',
19
}
20
21
22
def quoted(value):
23
if any(c in value for c in '\r\n\x00'):
24
raise ValueError('Deployment variables must not contain line breaks or NUL bytes.')
25
return '"' + value.replace('\\', '\\\\').replace('"', '\\"') + '"'
26
27
28
def host_url(environ):
29
for key in ['timftphost', 'timftpuser', 'timftppassword']:
30
if not environ.get(key):
31
raise ValueError(f'CI variable {key} is not set.')
32
host = environ['timftphost']
33
if '://' not in host:
34
host = 'ftp://' + host
35
parsed = urlsplit(host)
36
if parsed.scheme not in ['ftp', 'ftps', 'sftp'] or not parsed.hostname:
37
raise ValueError('timftphost must be an FTP, FTPS or SFTP host URL.')
38
if parsed.username or parsed.password or parsed.query or parsed.fragment:
39
raise ValueError('Keep login credentials in timftpuser/timftppassword; use a plain host URL.')
40
return host
41
42
43
def lftp_preamble(environ, host):
44
return [
45
'set cmd:fail-exit yes',
46
'set net:timeout 20',
47
'set net:max-retries 2',
48
'set net:reconnect-interval-base 3',
49
'set ssl:verify-certificate no',
50
'set ftp:list-options -a',
51
'set sftp:connect-program "ssh -a -x -o StrictHostKeyChecking=accept-new"',
52
'set sftp:auto-confirm yes',
53
'set xfer:use-temp-file yes',
54
f'open --user {quoted(environ["timftpuser"])} --env-password {quoted(host)}',
55
]
56
57
58
def run_lftp(commands, environ):
59
subprocess.run(
60
['lftp', '--norc'],
61
input='\n'.join(commands) + '\n',
62
text=True,
63
env={**environ, 'LFTP_PASSWORD': environ['timftppassword']},
64
check=True,
65
)
66
67
68
def list_remote(environ, target):
69
"""Return (exists, names). exists=False means the folder is not there yet."""
70
host = host_url(environ)
71
# Probe with cls; a missing folder makes `cd` fail.
72
probe = lftp_preamble(environ, host) + [
73
'set cmd:fail-exit no',
74
f'cd {quoted(target)} && cls -1 && echo __METEORS_DIR_OK__ || echo __METEORS_DIR_MISSING__',
75
'bye',
76
]
77
result = subprocess.run(
78
['lftp', '--norc'],
79
input='\n'.join(probe) + '\n',
80
text=True,
81
env={**environ, 'LFTP_PASSWORD': environ['timftppassword']},
82
check=True,
83
capture_output=True,
84
)
85
out = (result.stdout or '') + (result.stderr or '')
86
if '__METEORS_DIR_MISSING__' in out and '__METEORS_DIR_OK__' not in out:
87
return False, []
88
names = []
89
for line in out.splitlines():
90
name = line.strip().rstrip('/')
91
if not name or name.startswith('__METEORS_') or name.startswith('lftp'):
92
continue
93
# lftp may print status; keep path-like tokens
94
if ' ' in name and not name.startswith('.'):
95
# long listing leftover; take the last field
96
name = name.split()[-1]
97
names.append(posix_basename(name))
98
return True, names
99
100
101
def posix_basename(name):
102
return name.rstrip('/').split('/')[-1]
103
104
105
def assert_safe_target(exists, names):
106
if not exists:
107
print('Remote meteors folder does not exist yet; it will be created.')
108
return
109
unexpected = []
110
for name in names:
111
leaf = posix_basename(name)
112
if leaf in OURS or leaf == '':
113
continue
114
unexpected.append(leaf)
115
if unexpected:
116
raise ValueError(
117
'DEPLOY GEBLOKKEERD: de map meteors op de FTP-server is niet leeg '
118
'en bevat bestanden die niet bij dit project horen: '
119
+ ', '.join(sorted(set(unexpected))[:12])
120
+ '. Niets overschreven.'
121
)
122
if names:
123
print('Remote meteors folder already holds a previous Meteors deploy; updating.')
124
else:
125
print('Remote meteors folder is empty; deploying.')
126
127
128
def deploy_commands(environ, target, webroot):
129
host = host_url(environ)
130
return lftp_preamble(environ, host) + [
131
f'mkdir -p {quoted(target)} || echo "Using existing project directory"',
132
f'cd {quoted(target)}',
133
# GEEN --delete. Excludes only keep CI/docs out if they were ever placed in build/.
134
'mirror --reverse --no-perms --no-symlinks --max-errors=1 '
135
'--exclude-glob ".git/" --exclude-glob ".git/**" '
136
'--exclude-glob "blue-ci-cd.yml" --exclude-glob "README.md" '
137
f'{quoted(str(webroot))} .',
138
'bye',
139
]
140
141
142
def main():
143
environ = os.environ
144
try:
145
target = project_dir(environ)
146
webroot = ROOT / 'build'
147
if not (webroot / 'index.html').is_file() or not (webroot / 'game.js').is_file():
148
raise ValueError('build/ is incomplete (need index.html and game.js).')
149
if not (webroot / 'framework.js').is_file() or not (webroot / 'images').is_dir():
150
raise ValueError('build/ is incomplete (need framework.js and images/).')
151
exists, names = list_remote(environ, target)
152
assert_safe_target(exists, names)
153
run_lftp(deploy_commands(environ, target, webroot), environ)
154
print('Deploy complete (no --delete).')
155
return 0
156
except (ValueError, DeployGuardError, subprocess.CalledProcessError) as error:
157
print(str(error), file=sys.stderr)
158
return 1
159
160
161
if __name__ == '__main__':
162
sys.exit(main())
@@ -0,0 +1,162 @@1
#!/usr/bin/env python32
"""FTP-upload of build/. Never --delete. Refuses a non-empty foreign folder."""3
import os4
import subprocess5
import sys6
from pathlib import Path7
from urllib.parse import urlsplit8
9
sys.path.insert(0, str(Path(__file__).resolve().parent))10
from deploy_guard import DeployGuardError, project_dir # noqa: E40211
12
ROOT = Path(__file__).resolve().parents[1]13
14
# Files we ourselves publish; a first deploy may only land in an empty/new15
# folder, or a folder that already only contains a previous Meteors deploy.16
OURS = {17
'index.html', 'game.js', 'framework.js', 'style.css', 'images',18
'.', '..',19
}20
21
22
def quoted(value):23
if any(c in value for c in '\r\n\x00'):24
raise ValueError('Deployment variables must not contain line breaks or NUL bytes.')25
return '"' + value.replace('\\', '\\\\').replace('"', '\\"') + '"'26
27
28
def host_url(environ):29
for key in ['timftphost', 'timftpuser', 'timftppassword']:30
if not environ.get(key):31
raise ValueError(f'CI variable {key} is not set.')32
host = environ['timftphost']33
if '://' not in host:34
host = 'ftp://' + host35
parsed = urlsplit(host)36
if parsed.scheme not in ['ftp', 'ftps', 'sftp'] or not parsed.hostname:37
raise ValueError('timftphost must be an FTP, FTPS or SFTP host URL.')38
if parsed.username or parsed.password or parsed.query or parsed.fragment:39
raise ValueError('Keep login credentials in timftpuser/timftppassword; use a plain host URL.')40
return host41
42
43
def lftp_preamble(environ, host):44
return [45
'set cmd:fail-exit yes',46
'set net:timeout 20',47
'set net:max-retries 2',48
'set net:reconnect-interval-base 3',49
'set ssl:verify-certificate no',50
'set ftp:list-options -a',51
'set sftp:connect-program "ssh -a -x -o StrictHostKeyChecking=accept-new"',52
'set sftp:auto-confirm yes',53
'set xfer:use-temp-file yes',54
f'open --user {quoted(environ["timftpuser"])} --env-password {quoted(host)}',55
]56
57
58
def run_lftp(commands, environ):59
subprocess.run(60
['lftp', '--norc'],61
input='\n'.join(commands) + '\n',62
text=True,63
env={**environ, 'LFTP_PASSWORD': environ['timftppassword']},64
check=True,65
)66
67
68
def list_remote(environ, target):69
"""Return (exists, names). exists=False means the folder is not there yet."""70
host = host_url(environ)71
# Probe with cls; a missing folder makes `cd` fail.72
probe = lftp_preamble(environ, host) + [73
'set cmd:fail-exit no',74
f'cd {quoted(target)} && cls -1 && echo __METEORS_DIR_OK__ || echo __METEORS_DIR_MISSING__',75
'bye',76
]77
result = subprocess.run(78
['lftp', '--norc'],79
input='\n'.join(probe) + '\n',80
text=True,81
env={**environ, 'LFTP_PASSWORD': environ['timftppassword']},82
check=True,83
capture_output=True,84
)85
out = (result.stdout or '') + (result.stderr or '')86
if '__METEORS_DIR_MISSING__' in out and '__METEORS_DIR_OK__' not in out:87
return False, []88
names = []89
for line in out.splitlines():90
name = line.strip().rstrip('/')91
if not name or name.startswith('__METEORS_') or name.startswith('lftp'):92
continue93
# lftp may print status; keep path-like tokens94
if ' ' in name and not name.startswith('.'):95
# long listing leftover; take the last field96
name = name.split()[-1]97
names.append(posix_basename(name))98
return True, names99
100
101
def posix_basename(name):102
return name.rstrip('/').split('/')[-1]103
104
105
def assert_safe_target(exists, names):106
if not exists:107
print('Remote meteors folder does not exist yet; it will be created.')108
return109
unexpected = []110
for name in names:111
leaf = posix_basename(name)112
if leaf in OURS or leaf == '':113
continue114
unexpected.append(leaf)115
if unexpected:116
raise ValueError(117
'DEPLOY GEBLOKKEERD: de map meteors op de FTP-server is niet leeg '118
'en bevat bestanden die niet bij dit project horen: '119
+ ', '.join(sorted(set(unexpected))[:12])120
+ '. Niets overschreven.'121
)122
if names:123
print('Remote meteors folder already holds a previous Meteors deploy; updating.')124
else:125
print('Remote meteors folder is empty; deploying.')126
127
128
def deploy_commands(environ, target, webroot):129
host = host_url(environ)130
return lftp_preamble(environ, host) + [131
f'mkdir -p {quoted(target)} || echo "Using existing project directory"',132
f'cd {quoted(target)}',133
# GEEN --delete. Excludes only keep CI/docs out if they were ever placed in build/.134
'mirror --reverse --no-perms --no-symlinks --max-errors=1 '135
'--exclude-glob ".git/" --exclude-glob ".git/**" '136
'--exclude-glob "blue-ci-cd.yml" --exclude-glob "README.md" '137
f'{quoted(str(webroot))} .',138
'bye',139
]140
141
142
def main():143
environ = os.environ144
try:145
target = project_dir(environ)146
webroot = ROOT / 'build'147
if not (webroot / 'index.html').is_file() or not (webroot / 'game.js').is_file():148
raise ValueError('build/ is incomplete (need index.html and game.js).')149
if not (webroot / 'framework.js').is_file() or not (webroot / 'images').is_dir():150
raise ValueError('build/ is incomplete (need framework.js and images/).')151
exists, names = list_remote(environ, target)152
assert_safe_target(exists, names)153
run_lftp(deploy_commands(environ, target, webroot), environ)154
print('Deploy complete (no --delete).')155
return 0156
except (ValueError, DeployGuardError, subprocess.CalledProcessError) as error:157
print(str(error), file=sys.stderr)158
return 1159
160
161
if __name__ == '__main__':162
sys.exit(main())@@ -0,0 +1,92 @@
1
#!/usr/bin/env python3
2
"""Deploy guard: expand $timftproot, refuse a deploy that would hit the FTP root."""
3
import posixpath
4
import re
5
import sys
6
7
ROOT_VAR = 'timftproot'
8
PROJECT_VAR = 'projectftp'
9
ALLOWED_LEAF = 'meteors'
10
11
12
class DeployGuardError(ValueError):
13
pass
14
15
16
def _expand(value, environ):
17
"""Expand $timftproot / ${timftproot} (BlueGit secrets do not)."""
18
root = environ.get(ROOT_VAR) or ''
19
return re.sub(r'\$\{?' + ROOT_VAR + r'\}?', lambda _m: root, value)
20
21
22
def _norm(path):
23
path = (path or '').strip()
24
if not path:
25
return ''
26
# Collapse duplicate slashes before and after normpath.
27
path = re.sub(r'/+', '/', path.replace('\\', '/'))
28
norm = posixpath.normpath(path)
29
return '/' if norm in ('/', '//', '.') else norm.rstrip('/') or '/'
30
31
32
def project_dir(environ):
33
raw = environ.get(PROJECT_VAR)
34
if raw is None:
35
raise DeployGuardError(
36
f'DEPLOY GEBLOKKEERD: CI-variabele {PROJECT_VAR} is niet gezet. '
37
f'Zet de projectmap als project-secret, bijvoorbeeld $timftproot/{ALLOWED_LEAF}.'
38
)
39
if any(c in raw for c in '\r\n\x00'):
40
raise DeployGuardError(f'DEPLOY GEBLOKKEERD: {PROJECT_VAR} bevat een regeleinde of NUL-byte.')
41
leftover_dollar = raw.replace('$' + ROOT_VAR, '').replace('${' + ROOT_VAR + '}', '')
42
if '$' in leftover_dollar:
43
raise DeployGuardError(f'DEPLOY GEBLOKKEERD: {PROJECT_VAR} bevat een onbekende $-verwijzing.')
44
if (('$' + ROOT_VAR) in raw or ('${' + ROOT_VAR + '}') in raw) and not (environ.get(ROOT_VAR) or '').strip():
45
raise DeployGuardError(
46
f'DEPLOY GEBLOKKEERD: {PROJECT_VAR} verwijst naar {ROOT_VAR}, maar die is niet gezet.'
47
)
48
value = _expand(raw, environ).strip()
49
if not value:
50
raise DeployGuardError(f'DEPLOY GEBLOKKEERD: CI-variabele {PROJECT_VAR} is leeg.')
51
parts = [p for p in value.replace('\\', '/').split('/') if p]
52
if '..' in parts:
53
raise DeployGuardError(f'DEPLOY GEBLOKKEERD: {PROJECT_VAR} mag geen ".." bevatten.')
54
if value.startswith('~'):
55
raise DeployGuardError(f'DEPLOY GEBLOKKEERD: {PROJECT_VAR} mag niet de thuismap (~) zijn.')
56
norm = _norm(value)
57
if norm in ('/', '.', ''):
58
raise DeployGuardError(
59
f'DEPLOY GEBLOKKEERD: {PROJECT_VAR} wijst naar de root ("/" of "."); '
60
'dat zou de hele website overschrijven.'
61
)
62
root = _norm(environ.get(ROOT_VAR) or '')
63
if root and norm == root:
64
raise DeployGuardError(
65
f'DEPLOY GEBLOKKEERD: {PROJECT_VAR} is gelijk aan {ROOT_VAR} (de FTP-root van de site); '
66
'dat zou de hele website overschrijven.'
67
)
68
if root and root not in ('/', '.') and norm.startswith('/') and not norm.startswith(root + '/'):
69
raise DeployGuardError(f'DEPLOY GEBLOKKEERD: {PROJECT_VAR} ligt niet onder {ROOT_VAR}.')
70
leaf = parts[-1].lower() if parts else ''
71
if leaf != ALLOWED_LEAF:
72
raise DeployGuardError(
73
f'DEPLOY GEBLOKKEERD: {PROJECT_VAR} moet op "{ALLOWED_LEAF}" eindigen (leaf={leaf!r}).'
74
)
75
return norm
76
77
78
def main(environ=None):
79
import os
80
try:
81
path = project_dir(os.environ if environ is None else environ)
82
except DeployGuardError as error:
83
print(str(error), file=sys.stderr)
84
return 1
85
print('Deploy guard: projectmap ok.')
86
# Path itself is not printed (secrets). Length only.
87
print('projectftp length=%d' % len(path))
88
return 0
89
90
91
if __name__ == '__main__':
92
sys.exit(main())
@@ -0,0 +1,92 @@1
#!/usr/bin/env python32
"""Deploy guard: expand $timftproot, refuse a deploy that would hit the FTP root."""3
import posixpath4
import re5
import sys6
7
ROOT_VAR = 'timftproot'8
PROJECT_VAR = 'projectftp'9
ALLOWED_LEAF = 'meteors'10
11
12
class DeployGuardError(ValueError):13
pass14
15
16
def _expand(value, environ):17
"""Expand $timftproot / ${timftproot} (BlueGit secrets do not)."""18
root = environ.get(ROOT_VAR) or ''19
return re.sub(r'\$\{?' + ROOT_VAR + r'\}?', lambda _m: root, value)20
21
22
def _norm(path):23
path = (path or '').strip()24
if not path:25
return ''26
# Collapse duplicate slashes before and after normpath.27
path = re.sub(r'/+', '/', path.replace('\\', '/'))28
norm = posixpath.normpath(path)29
return '/' if norm in ('/', '//', '.') else norm.rstrip('/') or '/'30
31
32
def project_dir(environ):33
raw = environ.get(PROJECT_VAR)34
if raw is None:35
raise DeployGuardError(36
f'DEPLOY GEBLOKKEERD: CI-variabele {PROJECT_VAR} is niet gezet. '37
f'Zet de projectmap als project-secret, bijvoorbeeld $timftproot/{ALLOWED_LEAF}.'38
)39
if any(c in raw for c in '\r\n\x00'):40
raise DeployGuardError(f'DEPLOY GEBLOKKEERD: {PROJECT_VAR} bevat een regeleinde of NUL-byte.')41
leftover_dollar = raw.replace('$' + ROOT_VAR, '').replace('${' + ROOT_VAR + '}', '')42
if '$' in leftover_dollar:43
raise DeployGuardError(f'DEPLOY GEBLOKKEERD: {PROJECT_VAR} bevat een onbekende $-verwijzing.')44
if (('$' + ROOT_VAR) in raw or ('${' + ROOT_VAR + '}') in raw) and not (environ.get(ROOT_VAR) or '').strip():45
raise DeployGuardError(46
f'DEPLOY GEBLOKKEERD: {PROJECT_VAR} verwijst naar {ROOT_VAR}, maar die is niet gezet.'47
)48
value = _expand(raw, environ).strip()49
if not value:50
raise DeployGuardError(f'DEPLOY GEBLOKKEERD: CI-variabele {PROJECT_VAR} is leeg.')51
parts = [p for p in value.replace('\\', '/').split('/') if p]52
if '..' in parts:53
raise DeployGuardError(f'DEPLOY GEBLOKKEERD: {PROJECT_VAR} mag geen ".." bevatten.')54
if value.startswith('~'):55
raise DeployGuardError(f'DEPLOY GEBLOKKEERD: {PROJECT_VAR} mag niet de thuismap (~) zijn.')56
norm = _norm(value)57
if norm in ('/', '.', ''):58
raise DeployGuardError(59
f'DEPLOY GEBLOKKEERD: {PROJECT_VAR} wijst naar de root ("/" of "."); '60
'dat zou de hele website overschrijven.'61
)62
root = _norm(environ.get(ROOT_VAR) or '')63
if root and norm == root:64
raise DeployGuardError(65
f'DEPLOY GEBLOKKEERD: {PROJECT_VAR} is gelijk aan {ROOT_VAR} (de FTP-root van de site); '66
'dat zou de hele website overschrijven.'67
)68
if root and root not in ('/', '.') and norm.startswith('/') and not norm.startswith(root + '/'):69
raise DeployGuardError(f'DEPLOY GEBLOKKEERD: {PROJECT_VAR} ligt niet onder {ROOT_VAR}.')70
leaf = parts[-1].lower() if parts else ''71
if leaf != ALLOWED_LEAF:72
raise DeployGuardError(73
f'DEPLOY GEBLOKKEERD: {PROJECT_VAR} moet op "{ALLOWED_LEAF}" eindigen (leaf={leaf!r}).'74
)75
return norm76
77
78
def main(environ=None):79
import os80
try:81
path = project_dir(os.environ if environ is None else environ)82
except DeployGuardError as error:83
print(str(error), file=sys.stderr)84
return 185
print('Deploy guard: projectmap ok.')86
# Path itself is not printed (secrets). Length only.87
print('projectftp length=%d' % len(path))88
return 089
90
91
if __name__ == '__main__':92
sys.exit(main())@@ -0,0 +1,98 @@
1
'use strict';
2
3
const { describe, it } = require('node:test');
4
const assert = require('node:assert/strict');
5
const { spawnSync } = require('node:child_process');
6
const path = require('node:path');
7
8
const GUARD = path.join(__dirname, '..', 'ci', 'deploy_guard.py');
9
10
function run (env)
11
{
12
return spawnSync('python3', [GUARD], {
13
env: { ...process.env, ...env },
14
encoding: 'utf8'
15
});
16
}
17
18
function projectDir (env)
19
{
20
const py = [
21
'import os,sys',
22
'sys.path.insert(0, "ci")',
23
'from deploy_guard import project_dir',
24
'print(project_dir(os.environ))'
25
].join('; ');
26
return spawnSync('python3', ['-c', py], {
27
cwd: path.join(__dirname, '..'),
28
env: { ...process.env, ...env },
29
encoding: 'utf8'
30
});
31
}
32
33
describe('deploy_guard', () =>
34
{
35
it('expands $timftproot and ${timftproot} and collapses double slashes', () =>
36
{
37
let r = projectDir({ timftproot: '/var/www/', projectftp: '$timftproot/meteors' });
38
assert.equal(r.status, 0, r.stderr);
39
assert.equal(r.stdout.trim(), '/var/www/meteors');
40
41
r = projectDir({ timftproot: '/var/www', projectftp: '${timftproot}/meteors' });
42
assert.equal(r.status, 0, r.stderr);
43
assert.equal(r.stdout.trim(), '/var/www/meteors');
44
45
r = projectDir({ timftproot: '/var/www/', projectftp: '${timftproot}/meteors' });
46
assert.equal(r.status, 0, r.stderr);
47
assert.equal(r.stdout.trim(), '/var/www/meteors');
48
});
49
50
it('refuses the FTP root, a missing secret, and a non-meteors leaf', () =>
51
{
52
let r = projectDir({ timftproot: '/var/www', projectftp: '$timftproot' });
53
assert.notEqual(r.status, 0);
54
assert.match(r.stderr, /GEBLOKKEERD/);
55
56
r = projectDir({ timftproot: '/var/www', projectftp: '$timftproot/other' });
57
assert.notEqual(r.status, 0);
58
assert.match(r.stderr, /meteors/);
59
60
r = projectDir({ timftproot: '/var/www' });
61
assert.notEqual(r.status, 0);
62
});
63
64
it('the CLI exits 0 for a good path and does not print the path', () =>
65
{
66
const r = run({ timftproot: '/var/www', projectftp: '$timftproot/meteors' });
67
assert.equal(r.status, 0, r.stderr);
68
assert.match(r.stdout, /ok/i);
69
assert.doesNotMatch(r.stdout + r.stderr, /\/var\/www/);
70
});
71
});
72
73
describe('assert_safe_target', () =>
74
{
75
it('allows a new or empty folder, and a previous Meteors deploy, but not foreign files', () =>
76
{
77
const py = [
78
'import sys',
79
'sys.path.insert(0, "ci")',
80
'from deploy import assert_safe_target',
81
'assert_safe_target(False, [])',
82
'assert_safe_target(True, [])',
83
'assert_safe_target(True, ["index.html", "game.js", "framework.js", "style.css", "images"])',
84
'try:',
85
' assert_safe_target(True, ["index.php", "wp-config.php"])',
86
' raise SystemExit("should have refused")',
87
'except ValueError as e:',
88
' assert "GEBLOKKEERD" in str(e)',
89
'print("safe-target ok")'
90
].join('\n');
91
const r = spawnSync('python3', ['-c', py], {
92
cwd: path.join(__dirname, '..'),
93
encoding: 'utf8'
94
});
95
assert.equal(r.status, 0, r.stdout + r.stderr);
96
assert.match(r.stdout, /safe-target ok/);
97
});
98
});
@@ -0,0 +1,98 @@1
'use strict';2
3
const { describe, it } = require('node:test');4
const assert = require('node:assert/strict');5
const { spawnSync } = require('node:child_process');6
const path = require('node:path');7
8
const GUARD = path.join(__dirname, '..', 'ci', 'deploy_guard.py');9
10
function run (env)11
{12
return spawnSync('python3', [GUARD], {13
env: { ...process.env, ...env },14
encoding: 'utf8'15
});16
}17
18
function projectDir (env)19
{20
const py = [21
'import os,sys',22
'sys.path.insert(0, "ci")',23
'from deploy_guard import project_dir',24
'print(project_dir(os.environ))'25
].join('; ');26
return spawnSync('python3', ['-c', py], {27
cwd: path.join(__dirname, '..'),28
env: { ...process.env, ...env },29
encoding: 'utf8'30
});31
}32
33
describe('deploy_guard', () =>34
{35
it('expands $timftproot and ${timftproot} and collapses double slashes', () =>36
{37
let r = projectDir({ timftproot: '/var/www/', projectftp: '$timftproot/meteors' });38
assert.equal(r.status, 0, r.stderr);39
assert.equal(r.stdout.trim(), '/var/www/meteors');40
41
r = projectDir({ timftproot: '/var/www', projectftp: '${timftproot}/meteors' });42
assert.equal(r.status, 0, r.stderr);43
assert.equal(r.stdout.trim(), '/var/www/meteors');44
45
r = projectDir({ timftproot: '/var/www/', projectftp: '${timftproot}/meteors' });46
assert.equal(r.status, 0, r.stderr);47
assert.equal(r.stdout.trim(), '/var/www/meteors');48
});49
50
it('refuses the FTP root, a missing secret, and a non-meteors leaf', () =>51
{52
let r = projectDir({ timftproot: '/var/www', projectftp: '$timftproot' });53
assert.notEqual(r.status, 0);54
assert.match(r.stderr, /GEBLOKKEERD/);55
56
r = projectDir({ timftproot: '/var/www', projectftp: '$timftproot/other' });57
assert.notEqual(r.status, 0);58
assert.match(r.stderr, /meteors/);59
60
r = projectDir({ timftproot: '/var/www' });61
assert.notEqual(r.status, 0);62
});63
64
it('the CLI exits 0 for a good path and does not print the path', () =>65
{66
const r = run({ timftproot: '/var/www', projectftp: '$timftproot/meteors' });67
assert.equal(r.status, 0, r.stderr);68
assert.match(r.stdout, /ok/i);69
assert.doesNotMatch(r.stdout + r.stderr, /\/var\/www/);70
});71
});72
73
describe('assert_safe_target', () =>74
{75
it('allows a new or empty folder, and a previous Meteors deploy, but not foreign files', () =>76
{77
const py = [78
'import sys',79
'sys.path.insert(0, "ci")',80
'from deploy import assert_safe_target',81
'assert_safe_target(False, [])',82
'assert_safe_target(True, [])',83
'assert_safe_target(True, ["index.html", "game.js", "framework.js", "style.css", "images"])',84
'try:',85
' assert_safe_target(True, ["index.php", "wp-config.php"])',86
' raise SystemExit("should have refused")',87
'except ValueError as e:',88
' assert "GEBLOKKEERD" in str(e)',89
'print("safe-target ok")'90
].join('\n');91
const r = spawnSync('python3', ['-c', py], {92
cwd: path.join(__dirname, '..'),93
encoding: 'utf8'94
});95
assert.equal(r.status, 0, r.stdout + r.stderr);96
assert.match(r.stdout, /safe-target ok/);97
});98
});