-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsrc-ContextPack.xml
More file actions
1174 lines (982 loc) · 41.3 KB
/
src-ContextPack.xml
File metadata and controls
1174 lines (982 loc) · 41.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?xml version="1.0" encoding="UTF-8"?>
<project>
<context>
This XML file was automatically generated by ContextPack for project "src".
It consolidates all project files for analysis, documentation, and AI-assisted refactoring.
Binary files are listed in <structure> but excluded from <file> blocks.
</context>
<structure>
<path>evermod\main.py</path>
<path>evermod\commands\add.py</path>
<path>evermod\commands\contextpack.py</path>
<path>evermod\commands\create.py</path>
<path>evermod\commands\init.py</path>
<path>evermod\commands\update.py</path>
<path>evermod\commands\version.py</path>
<path>evermod\fs\builder.py</path>
<path>evermod\fs\environment.py</path>
<path>evermod\fs\io.py</path>
<path>evermod\fs\manifest.py</path>
<path>evermod\fs\paths.py</path>
<path>evermod\io\prompt.py</path>
<path>evermod\services\git.py</path>
<path>evermod\services\gradle.py</path>
<path>evermod\utils\sanitize.py</path>
</structure>
<file name="evermod\main.py">
import argparse
import sys
import os
if not getattr(sys, 'frozen', False):
src_path = os.path.dirname(os.path.dirname(__file__))
if src_path not in sys.path:
sys.path.insert(0, src_path)
from evermod.commands import init, create, add, contextpack, update, version
def main():
parser = argparse.ArgumentParser(
prog="evermod",
description="EverMod CLI — Modular Forge modding workspace manager"
)
parser.add_argument(
"-v", "--version",
action="store_true",
help="Show EverMod version information"
)
subparsers = parser.add_subparsers(dest="command")
# Init
init_parser = subparsers.add_parser("init", help="Create a new workspace")
init_parser.add_argument("-p", "--path", metavar="PATH", help="Workspace directory (defaults to current directory)")
# Create
create_parser = subparsers.add_parser("create", help="Create a new mod from a Forge MDK template")
create_parser.add_argument("-s", "--space", metavar="PATH", help="workspace where the mod will be created (defaults to current directory)")
# add
add_parser = subparsers.add_parser("add", help="Add EverMod to existing project")
add_parser.add_argument("-p", "--path", metavar="PATH", help="Target directory where EverMod will be added")
# contextpack
contextpack_parser = subparsers.add_parser("contextpack", help="Generate contextpack documentation for mods")
contextpack_parser.add_argument("target", nargs="?", default=".", help="Target project")
# update
update_parser = subparsers.add_parser("update", help="Update the EverMod templates")
update_parser.add_argument("--force", action="store_true", help="Force update even if versions are the same")
update_parser.add_argument("--silent", action="store_true", help="Run update in silent mode (no prompts)")
args = parser.parse_args()
if args.version:
version.show_full_version()
return
match args.command:
case "init": init.run(args.path)
case "create": create.run(args.space)
case "add": add.run(args.path)
case "contextpack": contextpack.run(args.target)
case "update": update.run(args.force, args.silent)
case _: parser.print_help()
if __name__ == "__main__":
main()
</file>
<file name="evermod\commands\add.py">
from pathlib import Path
from evermod.fs.paths import resolve_path
from evermod.services.gradle import version_context
from evermod.services.git import addSubmodule, git_init
from evermod.fs.environment import Environment, detect_environment
from evermod.fs.builder import render_evermod_setting, render_build
from evermod.fs.manifest import evermod_exists, write_manifest, get_sp_data, get_mc_data
def run(path: str | None):
print("🧩 EverMod — Add EverMod to existing environment")
print("---------------------------------------")
context_path = Path(path).resolve() if path else Path.cwd()
env = detect_environment(context_path, force_space=bool(path))
match env:
case Environment.MOD:
workspace = False
project_type = "mod"
case Environment.SPACE:
workspace = True
project_type = "space"
case _:
print("❌ Invalid destination")
print(f"📂 Route: {context_path}")
return
if evermod_exists(context_path):
print("⚠️ EverMod is already present in this project.")
return
data = get_sp_data(context_path) if workspace else get_mc_data(context_path)
if not data:
print("❌ Unable to resolve project data")
return
project_name, mc_data = data
setting_context = {
"project_name": project_name,
"include_evermod": True,
"includes": [],
"workspace": workspace
}
for data in mc_data:
context = version_context(data["version"]).copy()
context.update(setting_context.copy())
path_build = resolve_path(context_path, data["path"])
render_build(path_build, context)
if workspace:
setting_context["includes"].append(f"include('mods:{data['mod_name']}')")
render_evermod_setting(context_path, setting_context)
try:
git_init(context_path)
addSubmodule("wipodev", "EverMod", context_path)
except Exception as e:
print(f"❌ Failed to add EverMod: {e}")
return
write_manifest(path=context_path, project_name=project_name, type_=project_type, evermod=True, minecraft=mc_data)
print("✅ EverMod successfully added to the project.")
print(f"📂 Location: {context_path}")
print("---------------------------------------")
</file>
<file name="evermod\commands\contextpack.py">
import os
import json
from pathlib import Path
from xml.sax.saxutils import escape
import pathspec
import re
command = "ContextPack"
# ─────────────────────────────────────────────
# ⚙️ Utility functions
# ─────────────────────────────────────────────
def load_gitignore(base_path: Path):
"""Load patterns from .gitignore and compile with pathspec."""
gitignore_path = base_path / ".gitignore"
if not gitignore_path.exists():
return None
lines = gitignore_path.read_text(encoding="utf-8").splitlines()
return pathspec.PathSpec.from_lines("gitwildmatch", lines)
def load_config(base_path: Path) -> dict:
f"""Load {command} config file ({command}.config.json) or return defaults."""
config_path = base_path / f"{command}.config.json"
config = {
"exclude": [
".git",
".gitignore",
".gitattributes",
"build",
"dist",
"__pycache__",
"__init__.py",
"*.log",
"*.zip",
".idea",
".vscode"
],
"use_gitignore": True,
"output": None,
"follow_symlinks": False
}
if config_path.exists():
try:
user_data = json.loads(config_path.read_text(encoding="utf-8"))
if "exclude" in user_data:
config["exclude"] = list(set(config["exclude"] + user_data["exclude"]))
for key, value in user_data.items():
if key != "exclude":
config[key] = value
except Exception as e:
print(f"⚠️ Could not parse config: {e}")
return config
def is_binary_file(path: Path) -> bool:
"""Detect if a file is binary by inspecting its first bytes."""
try:
with open(path, "rb") as f:
chunk = f.read(1024)
if not chunk:
return False
if b"\0" in chunk:
return True
text_chars = bytearray({7,8,9,10,12,13,27} | set(range(0x20, 0x100)))
non_text = chunk.translate(None, text_chars)
return len(non_text) / len(chunk) > 0.2
except Exception:
return False
def count_tokens(text: str) -> int:
"""Estimate tokens by splitting words and symbols (approximation)."""
return len(re.findall(r"\w+|[^\w\s]", text))
# ─────────────────────────────────────────────
# 🧩 Main command
# ─────────────────────────────────────────────
def run(project_path: str = "."):
base_path = Path(project_path).resolve()
project_name = base_path.name
config = load_config(base_path)
gitignore_spec = load_gitignore(base_path) if config.get("use_gitignore", True) else None
exclude_patterns = config["exclude"]
output_name = config["output"] or f"{project_name}-{command}.xml"
output_file = base_path / output_name
follow_symlinks = config.get("follow_symlinks", False)
# helper: exclusion rules
def should_exclude(path: Path) -> bool:
from fnmatch import fnmatch
rel = str(path.relative_to(base_path))
if gitignore_spec and gitignore_spec.match_file(rel):
return True
for pattern in exclude_patterns:
if fnmatch(path.name, pattern) or fnmatch(rel, pattern):
return True
return False
# ─────────────────────────────
# Scan files
# ─────────────────────────────
print(f"📦 Generating {command} for {project_name} ...\n")
all_files, binary_files, total_chars, total_tokens = [], [], 0, 0
for root, dirs, files in os.walk(base_path, followlinks=follow_symlinks):
root_path = Path(root)
dirs[:] = [d for d in dirs if not should_exclude(root_path / d)]
for file in files:
full_path = root_path / file
if should_exclude(full_path):
continue
all_files.append(full_path)
if not all_files:
print("⚠️ No files found after filtering.")
return
print(f"🧩 Found {len(all_files)} total files. Processing...\n")
with open(output_name, "w", encoding="utf-8") as out:
out.write('<?xml version="1.0" encoding="UTF-8"?>\n<project>\n')
intro = f"""
<context>
This XML file was automatically generated by {command} for project "{project_name}".
It consolidates all project files for analysis, documentation, and AI-assisted refactoring.
Binary files are listed in <structure> but excluded from <file> blocks.
</context>
"""
out.write(intro)
out.write(" <structure>\n")
for path in all_files:
rel = path.relative_to(base_path)
if is_binary_file(path):
out.write(f' <path type="binary">{rel}</path>\n')
binary_files.append(rel)
else:
out.write(f" <path>{rel}</path>\n")
out.write(" </structure>\n\n")
# file contents
for path in all_files:
rel = path.relative_to(base_path)
if rel in binary_files:
continue
try:
content = path.read_text(encoding="utf-8", errors="ignore")
total_chars += len(content)
total_tokens += count_tokens(content)
except Exception as e:
print(f"⚠️ Could not read {path}: {e}")
continue
out.write(f' <file name="{rel}">\n{escape(content)}\n </file>\n')
out.write("</project>\n")
# ─────────────────────────────
# Output summary
# ─────────────────────────────
YELLOW = "\033[33m"
GREEN = "\033[92m"
RESET = "\033[0m"
print("✔ Packing completed successfully!\n")
if binary_files:
print("📄 Binary Files Detected:")
print("─────────────────────────")
print(f"{YELLOW}{len(binary_files)} files detected as binary by content inspection:{RESET}")
for i, f in enumerate(binary_files, 1):
print(f"{i}. {f}")
print()
print(f"{YELLOW}These files have been excluded from the output.{RESET}")
print(f"{YELLOW}Please review them if you expected them to contain text content.{RESET}\n")
print("📊 Pack Summary:")
print("────────────────")
print(f" Total Files: {len(all_files)} files")
print(f" Total Tokens: {total_tokens:,} tokens")
print(f" Total Chars: {total_chars:,} chars")
print(f" Output: {output_file.name}")
print(f" Security: ✔ No suspicious files detected\n")
print(f"{GREEN}🎉 All Done!{RESET}")
print("Your project has been successfully packed.")
</file>
<file name="evermod\commands\create.py">
from pathlib import Path
from evermod.io.prompt import ask, ask_bool
from evermod.services.gradle import get_versions_data
from evermod.services.git import addSubmodule, git_init
from evermod.fs.environment import Environment, detect_environment
from evermod.utils.sanitize import sanitize_string, sanitize_package
from evermod.fs.builder import create_mod_structure, render_evermod_setting
from evermod.fs.manifest import evermod_exists, write_manifest, get_sp_data
def run(space: str | None):
print("🧩 EverMod — Mod creation wizard")
print("--------------------------------")
context_path = Path(space).resolve() if space else Path.cwd()
env = detect_environment(context_path, force_space=bool(space))
match env:
case Environment.MOD:
print("❌ You are inside a mod project")
print(f"📂 Route: {context_path}")
return
case Environment.INVALID:
print("❌ Invalid destination")
print(f"📂 Route: {context_path}")
return
case Environment.SPACE:
workspace = True
case Environment.EMPTY_OR_NEW:
workspace = False
versions = get_versions_data()
if not versions:
print("❌ Unable to fetch version data")
return
mod_name = ask("Mod name", "NewMod")
mod_dir = context_path / "mods" / mod_name if workspace else context_path / mod_name
if mod_dir.exists():
print(f"⚠️ Folder '{mod_name}' already exists in {context_path}")
return
suggested_modid = sanitize_string(mod_name)
mod_id = sanitize_string(ask("Mod ID", suggested_modid))
print("\nAvailable Minecraft versions:")
for v in versions.keys(): print(f" - {v}")
mc_version = ask("Select Minecraft version", list(versions.keys())[0])
if mc_version not in versions:
print(f"❌ Unsupported version: {mc_version}")
return
author = ask("Author name", "WipoDev")
safe_author = sanitize_string(author)
package_default = f"net.{safe_author}.{mod_id}"
package_name = sanitize_package(ask("Package name", package_default))
package_parts = package_name.split(".")
mc_data: list[dict] = []
if workspace:
include_evermod = evermod_exists(context_path)
sp_data = get_sp_data(context_path)
if not sp_data:
print("❌ Unable to read workspace data")
return
project_name, mc_data = sp_data
root_path = context_path
relative_path = f"./mods/{mod_name}"
project_type = "space"
else:
include_evermod = ask_bool("Include EverMod as submodule?")
project_name = mod_name
root_path = mod_dir
relative_path = f"."
project_type = "mod"
context = versions[mc_version].copy()
context.update({
"minecraft_version": mc_version,
"mod_id": mod_id,
"mod_group": safe_author,
"mod_name": mod_name,
"mod_authors": author,
"package_name": package_name,
"project_name": project_name,
"include_evermod": include_evermod,
})
create_mod_structure(mod_dir, package_parts, context, workspace)
if not any(
entry["mod_name"] == mod_name or entry["path"] == relative_path
for entry in mc_data
):
mc_data.append({
"mod_name": mod_name,
"version": mc_version,
"path": relative_path
})
if workspace:
setting_context = {
"project_name": project_name,
"include_evermod": include_evermod,
"includes": [],
"workspace": workspace
}
for data in mc_data:
setting_context["includes"].append(f"include('mods:{data['mod_name']}')")
render_evermod_setting(context_path, setting_context)
if include_evermod and not workspace:
git_init(mod_dir)
include_evermod = addSubmodule("wipodev", "EverMod", mod_dir)
write_manifest(path=root_path, project_name=project_name, type_=project_type, evermod=include_evermod, minecraft=mc_data)
print(f"\n✅ Mod '{mod_name}' created successfully!")
print(f"📦 Minecraft {mc_version} (Forge {context['forge_version']})")
print(f"🔌 EverMod: {'Included as submodule' if include_evermod else 'Not included'}")
print(f"🏗️ Workspace mode: {'ON' if workspace else 'OFF'}")
print(f"📂 Location: {mod_dir}")
print("--------------------------------")
</file>
<file name="evermod\commands\init.py">
from pathlib import Path
from evermod.fs.manifest import write_manifest
from evermod.services.git import addSubmodule, git_init
from evermod.io.prompt import ask, ask_bool
from evermod.utils.sanitize import sanitize_string
from evermod.fs.environment import Environment, detect_new_space_environment
from evermod.fs.builder import create_space_structure
def run(path: str | None):
print("🧩 EverMod — Initialize workspace")
print("--------------------------------")
context_path = Path(path).resolve() if path else Path.cwd()
space_name = sanitize_string(ask("Space name", "NewSpace"))
space_dir = context_path / space_name
env = detect_new_space_environment(space_dir)
if not env == Environment.EMPTY_OR_NEW:
print("❌ Target directory already exists and is not empty.")
print("👉 Space initialization requires an empty directory.")
print(f"📂 Route: {space_dir}")
return
include_evermod = ask_bool("Include EverMod in this workspace?")
context = {
"project_name": space_name,
"include_evermod": include_evermod,
}
create_space_structure(space_dir, context)
if include_evermod:
git_init(space_dir)
include_evermod = addSubmodule("wipodev", "EverMod", space_dir)
write_manifest(path=space_dir, project_name=space_name, type_="space", evermod=include_evermod)
print("\n✅ Workspace initialized successfully!")
print(f"🔌 EverMod: {'Enabled' if include_evermod else 'Not included'}")
print(f"📂 Location: {space_dir}")
print("--------------------------------")
</file>
<file name="evermod\commands\update.py">
import json, shutil, tempfile, subprocess, urllib.request
from pathlib import Path
from packaging import version
from evermod.fs.paths import get_global_dir, get_templates_dir
MANIFEST_URL = "https://raw.githubusercontent.com/wipodev/evermod-templates/main/manifest.json"
REPO_URL = "https://github.com/wipodev/evermod-templates.git"
def run(force: bool = False, silent: bool = False):
global_dir = get_global_dir()
templates_dir = get_templates_dir()
local_manifest_path = global_dir / "manifest.json"
if not silent:
print("🔍 Checking for EverMod template updates...")
# === Fetch remote manifest ===
try:
with urllib.request.urlopen(MANIFEST_URL) as response:
remote_manifest = json.load(response)
except Exception as e:
if not silent:
print(f"❌ Unable to read remote manifest: {e}")
return
remote_version = remote_manifest.get("version", "0.0.0")
local_version = "0.0.0"
if local_manifest_path.exists():
try:
local_data = json.loads(local_manifest_path.read_text(encoding="utf-8"))
local_version = local_data.get("version", "0.0.0")
except Exception:
pass
remote_v = version.parse(remote_version)
local_v = version.parse(local_version)
# === Skip if already up to date ===
if not force and remote_v <= local_v:
if not silent:
print(f"✅ Templates are already up to date (v{local_version}).")
print("ℹ️ Use '--force' to reinstall templates anyway.")
return
# === Show changelog if interactive ===
if not silent:
print(f"🆕 New version available: v{remote_version} (current v{local_version})")
print(f"📅 Released: {remote_manifest.get('released', 'unknown date')}")
print("\n📋 Changelog:")
for line in remote_manifest.get("changelog", []):
print(f" • {line}")
print()
confirm = input("Would you like to update your local templates? (y/n): ").strip().lower()
if confirm != "y":
print("❎ Update cancelled.")
return
# === Clone and replace templates ===
with tempfile.TemporaryDirectory() as tmp:
tmp_path = Path(tmp)
if not silent:
print("⬇️ Downloading new templates...")
try:
subprocess.run(
["git", "clone", "--depth", "1", REPO_URL, str(tmp_path)],
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, check=True
)
except subprocess.CalledProcessError:
if not silent:
print("❌ Failed to clone the repository.")
return
remote_templates = tmp_path / "templates"
if not remote_templates.exists():
if not silent:
print("❌ Remote repository does not contain 'templates' folder.")
return
if templates_dir.exists():
shutil.rmtree(templates_dir)
shutil.copytree(remote_templates, templates_dir)
local_manifest_path.write_text(
json.dumps(remote_manifest, indent=2), encoding="utf-8"
)
if not silent:
print(f"✅ Templates updated successfully to version v{remote_version}.")
print(f"📁 Location: {templates_dir}")
</file>
<file name="evermod\commands\version.py">
from evermod.fs.io import read_json
from evermod.fs.paths import get_global_dir, get_cli_manifest_path, get_template_manifest
def show_full_version():
"""Display CLI version, framework compatibility, and templates info."""
# --- CLI Manifest (local root) ---
cli_manifest = read_json(get_cli_manifest_path())
if cli_manifest is None:
cli_version = "unknown"
else:
cli_version = cli_manifest.get("version", "unknown")
# --- Templates Manifest (global .evermod folder) ---
template_manifest = read_json(get_template_manifest())
if template_manifest is None:
templates_version = "not installed"
templates_date = "—"
else:
templates_version = template_manifest.get("version", "not installed")
templates_date = template_manifest.get("released", "unknown date")
# --- Output summary ---
print("🧩 EverMod CLI Information")
print("----------------------------")
print(f"CLI Version: v{cli_version}")
print(f"Installed Templates: v{templates_version}")
print(f"Templates Released: {templates_date}")
print(f"Global Path: {get_global_dir()}")
</file>
<file name="evermod\fs\builder.py">
import shutil
from pathlib import Path
from jinja2 import Template
from typing import Iterable
from evermod.fs.paths import get_templates_dir
#-----------------------------------------------------------
def create_mod_structure(mod_dir: Path, package_parts: list[str], context: dict, space: bool = False):
"""Create folder structure and copy static template files."""
src_main_java = mod_dir / "src" / "main" / "java"
src_main_java_mod = src_main_java / Path(*package_parts)
src_main_resources = mod_dir / "src" / "main" / "resources"
src_main_metainf = src_main_resources / "META-INF"
mod_dir.mkdir(parents=True, exist_ok=True)
src_main_java_mod.mkdir(parents=True, exist_ok=True)
src_main_resources.mkdir(parents=True, exist_ok=True)
src_main_metainf.mkdir(parents=True, exist_ok=True)
copy_files([("mods.toml", src_main_metainf / "mods.toml"),])
copy_extra(mod_dir)
if not space: copy_gradle(mod_dir)
render_mod(mod_dir, context, src_main_java_mod, src_main_resources, space)
#-----------------------------------------------------------
def create_space_structure(space_dir: Path, context: dict):
mods = space_dir / "mods"
space_dir.mkdir(parents=True, exist_ok=True)
mods.mkdir(parents=True, exist_ok=True)
copy_extra(space_dir)
copy_gradle(space_dir, True)
render_files([("template.settings.gradle.j2", space_dir / "settings.gradle"),], context)
#-----------------------------------------------------------
def copy_extra(path: Path):
copy_files([
(".gitignore", path / ".gitignore"),
(".gitattributes", path / ".gitattributes"),
("LICENSE.txt", path / "LICENSE.txt"),
])
#-----------------------------------------------------------
def copy_gradle(path: Path, space: bool = False):
gradle_dir = path / "gradle" / "wrapper"
gradle_dir.mkdir(parents=True, exist_ok=True)
copy_files([
("gradlew", path / "gradlew"),
("gradlew.bat", path / "gradlew.bat"),
("gradle/wrapper/gradle-wrapper.jar", gradle_dir / "gradle-wrapper.jar"),
("gradle/wrapper/gradle-wrapper.properties", gradle_dir / "gradle-wrapper.properties"),
])
if space:
copy_files([
("template.space.build.gradle.j2", path / "build.gradle"),
("template.space.gradle.properties.j2", path / "gradle.properties"),
])
#-----------------------------------------------------------
def render_mod(mod_dir: Path, context: dict, src_main_java: Path, src_main_resources: Path, space: bool = False) -> None:
render_files([
("template.build.gradle.j2", mod_dir / "build.gradle"),
("template.gradle.properties.j2", mod_dir / "gradle.properties"),
("template.MainMod.java.j2", src_main_java / "MainMod.java"),
("template.pack.mcmeta.j2", src_main_resources / "pack.mcmeta"),
], context)
if not space:
render_files([("template.settings.gradle.j2", mod_dir / "settings.gradle"),], context)
#-----------------------------------------------------------
def render_evermod_setting(path: Path, context: dict) -> None:
render_files([("template.settings.gradle.j2", path / "settings.gradle"),], context)
#-----------------------------------------------------------
def render_build(path: Path, context: dict) -> None:
render_files([("template.build.gradle.j2", path / "build.gradle"),], context)
#-----------------------------------------------------------
def copy_files(files: Iterable[tuple[Path, Path]]) -> None:
templates_dir = get_templates_dir()
for tpl_file, dst_file in files:
shutil.copy2(templates_dir / tpl_file, dst_file)
#-----------------------------------------------------------
def render_files(files: Iterable[tuple[Path, Path]], context: dict) -> None:
templates_dir = get_templates_dir()
for tpl, output in files:
render_template(templates_dir / tpl, context, output)
#-----------------------------------------------------------
def render_template(template_path: Path, context: dict, output_path: Path):
"""Render a Jinja2 template and write to destination."""
with open(template_path, encoding="utf-8") as f:
template = Template(f.read())
result = template.render(context)
output_path.write_text(result, encoding="utf-8")
</file>
<file name="evermod\fs\environment.py">
from enum import Enum
from pathlib import Path
from evermod.fs.paths import is_empty_dir
from evermod.fs.manifest import is_environment_mod, is_environment_space
#-----------------------------------------------------------
class Environment(Enum):
MOD = "mod"
SPACE = "space"
EMPTY_OR_NEW = "empty_or_new"
INVALID = "invalid"
#-----------------------------------------------------------
def detect_environment(context_path: Path, force_space: bool = False) -> Environment:
if not context_path.exists() or not context_path.is_dir():
return Environment.INVALID
if is_environment_mod(context_path):
return Environment.MOD
if is_environment_space(context_path):
return Environment.SPACE
if force_space:
return Environment.INVALID
return Environment.EMPTY_OR_NEW
#-----------------------------------------------------------
def detect_new_space_environment(context_path: Path) -> Environment:
if not context_path.exists():
return Environment.EMPTY_OR_NEW
if not is_empty_dir(context_path):
return Environment.INVALID
return Environment.EMPTY_OR_NEW
</file>
<file name="evermod\fs\io.py">
import json, re
from pathlib import Path
from typing import Iterable
#-----------------------------------------------------------
def read_text(path: Path) -> str | None:
if not path.exists():
return None
try:
return path.read_text(encoding="utf-8")
except Exception:
return None
#-----------------------------------------------------------
def write_text(path: Path, content: str):
path.write_text(content, encoding="utf-8")
#-----------------------------------------------------------
def read_json(path: Path) -> dict | None:
if not path.exists():
return None
try:
return json.loads(path.read_text(encoding="utf-8"))
except Exception:
return None
#-----------------------------------------------------------
def write_json(path: Path, data: dict):
path.write_text(
json.dumps(data, indent=2),
encoding="utf-8"
)
#-----------------------------------------------------------
def file_contains(path: Path, word: str) -> bool:
content = read_text(path)
return content is not None and word in content
#-----------------------------------------------------------
def file_contains_strict(path: Path, word: str) -> bool:
content = read_text(path)
return (
content is not None
and re.search(rf"\b{re.escape(word)}\b", content) is not None
)
#-----------------------------------------------------------
def read_key_values(path: Path, keys: Iterable[str], comment_prefixes=("#", "//")) -> dict[str, str]:
result = {}
content = read_text(path)
if content is None:
return result
keys = set(keys)
try:
for raw_line in content.splitlines():
line = raw_line.strip()
if not line: continue
if any(line.startswith(p) for p in comment_prefixes): continue
if "=" not in line: continue
key, value = line.split("=", 1)
key = key.strip()
if key not in keys: continue
value = value.strip()
if (
(value.startswith('"') and value.endswith('"')) or
(value.startswith("'") and value.endswith("'"))
):
value = value[1:-1]
result[key] = value
except Exception:
pass
return result
</file>
<file name="evermod\fs\manifest.py">
from pathlib import Path
from evermod.fs.io import read_key_values
from evermod.fs.io import read_json, write_json, file_contains
MANIFEST = "evermod.manifest.json"
#-----------------------------------------------------------
def write_manifest(path: Path, project_name: str, type_: str, evermod: bool, minecraft: list[dict] | None = None):
data = {
"project_name": project_name,
"type": type_,
"version": 1,
"evermod": evermod,
"minecraft": minecraft or [],
}
write_json(path / MANIFEST, data)
#-----------------------------------------------------------
def read_manifest(path: Path) -> dict | None:
return read_json(path / MANIFEST)
#-----------------------------------------------------------
def evermod_exists(path: Path) -> bool:
manifest = read_manifest(path)
if manifest and manifest.get("evermod") is True:
return True
if (path / "EverMod").exists() or (path / "evermod").exists():
return True
return file_contains(path / "settings.gradle", "EverMod")
#-----------------------------------------------------------
def is_environment_mod(path: Path) -> bool:
manifest = read_manifest(path)
if manifest:
return manifest.get("type") == "mod"
build_path = path / "build.gradle"
if not build_path.exists():
return False
if file_contains(build_path, "minecraftforge"):
return True
if (path / "src" / "main" / "java").exists() and (path / "src" / "main" / "resources").exists():
return True
return False
#-----------------------------------------------------------
def is_environment_space(path: Path) -> bool:
manifest = read_manifest(path)
if manifest:
return manifest.get("type") == "space"
build_path = path / "build.gradle"
if not build_path.exists():
return False
if not file_contains(build_path, "minecraftforge"):
return True
return False
#-----------------------------------------------------------
def get_manifest_minecraft_data(path: Path) -> tuple[str | None, list[dict] | None] | None:
manifest = read_manifest(path)
if manifest:
mc = manifest.get("minecraft")
name = manifest.get("project_name")
if mc or name:
return name, mc
return None
#-----------------------------------------------------------
def get_mc_data(path: Path) -> tuple[str | None, list[dict] | None] | None:
manifest_mc_data = get_manifest_minecraft_data(path)
if manifest_mc_data is not None:
return manifest_mc_data
mod_data = get_mod_data(path)
if mod_data is not None:
name, mc = mod_data
return (name, [mc])
return None
#-----------------------------------------------------------
def get_sp_data(path: Path) -> tuple[str | None, list[dict] | None] | None:
manifest_mc_data = get_manifest_minecraft_data(path)
if manifest_mc_data is not None:
return manifest_mc_data
data = read_key_values(path / "settings.gradle", keys=["rootProject.name"])
if data: name = data.get("rootProject.name")
mods_dir = path / "mods"
if not mods_dir.exists() or not mods_dir.is_dir():
return (name, [])
mc_data: list[dict] = []
seen_mods: set[str] = set()
seen_paths: set[str] = set()
for mod_dir in mods_dir.iterdir():
if not mod_dir.is_dir(): continue
mod_data = get_mod_data(mod_dir)
if not mod_data: continue
mod_name, mc_entry = mod_data
if not mc_entry: continue
mod_path = f"./mods/{mod_dir.name}"
if mod_name in seen_mods or mod_path in seen_paths: continue
mc_entry = mc_entry.copy()
mc_entry["path"] = mod_path
mc_data.append(mc_entry)
seen_mods.add(mod_name)
seen_paths.add(mod_path)
return (name, mc_data)
#-----------------------------------------------------------
def get_mod_data(path: Path) -> tuple[str | None, dict | None] | None:
data = read_key_values(path / "gradle.properties", keys=["minecraft_version", "mod_name"])
if not data: return None
mc = data.get("minecraft_version")
name = data.get("mod_name")
if not mc and not name:
return None
return (