mirror of
https://github.com/kuhyx/testsAndMisc.git
synced 2026-11-24 15:46:18 +01:00
Compare commits
2 Commits
08f3c764b2
...
47478791d8
| Author | SHA1 | Date | |
|---|---|---|---|
| 47478791d8 | |||
| 241652cade |
@ -0,0 +1,18 @@
|
||||
{
|
||||
"title": "Split generate_study_materials.sh under the 250-line cap with tested libs",
|
||||
"objective": "Bring linux_configuration/scripts/single_use/utils/generate_study_materials.sh from 1017 lines under the repo-wide 250-line cap by moving its functions and its 335-line top-level block into six sourced libraries, without changing the output it produces for any input it previously handled correctly. File 2 of the Phase 1 queue.",
|
||||
"acceptance_criteria": [
|
||||
"The entry script and every lib/study_*.sh and lib/tests/*.sh file is at or under 250 lines.",
|
||||
"All three generated files stay byte-identical to a golden fixture captured before any edit, verified by sha256sum after every step.",
|
||||
"verify_shell_split.sh against 08f3c764 reports no function whose body changed; additions are limited to the wrappers introduced around previously top-level code.",
|
||||
"shell_coverage.sh reports 100% for every lib, or a measured figure with a falsified diagnosis for any shortfall.",
|
||||
"Any latent defect the tests expose is fixed rather than pinned, and each fix is demonstrated on a fixture that actually triggers it.",
|
||||
"shellcheck reports zero findings with no suppression added."
|
||||
],
|
||||
"out_of_scope": [
|
||||
"Changing which documentation sites the URL builders point at.",
|
||||
"Reworking the per-language analysis mode, beyond covering it with tests.",
|
||||
"The other five files still over the cap."
|
||||
],
|
||||
"verifier": "sha256sum -c against the golden fixture plus a stdout diff, bash meta/scripts/verify_shell_split.sh 08f3c764, lib/tests/run_all.sh (166 assertions), bash meta/scripts/shell_coverage.sh lib/tests/run_all.sh <lib> 100 for all six libs, a second fixture with 25 imports and comment lines run at --top 3, shellcheck, and check_file_length.sh --all."
|
||||
}
|
||||
@ -0,0 +1,20 @@
|
||||
{
|
||||
"title": "Split hosts/install.sh under the 250-line cap with its anti-tamper guards fully covered",
|
||||
"objective": "Bring linux_configuration/scripts/periodic_background/hosts/install.sh from 913 lines under the repo-wide 250-line cap by moving its 712-line top-level block into eight phase functions across six libs, without changing what a real install would do. File 3 of the Phase 1 queue: 13 referencing files and the highest blast radius, since it rewrites /etc/hosts and takes the guard down to do it.",
|
||||
"acceptance_criteria": [
|
||||
"Every shell file — entry script, libs and tests — is at or under 250 lines.",
|
||||
"Each wrapped phase body is byte-identical to its original line range, proven by diff, because end-to-end execution is not available as evidence here.",
|
||||
"A content comparison against the pre-split file accounts for every absent line as an intentional edit.",
|
||||
"The 254 custom-blocked domains extracted by the guard are identical before and after the blocklist becomes a data file.",
|
||||
"Both anti-tamper guards reach 100% line coverage, with both directions of each covered: removal refused / addition allowed for the custom list, growth refused / shrinkage allowed for the whitelist.",
|
||||
"/etc/hosts is unchanged, verified by sha256sum, and the installer is never run end to end.",
|
||||
"shellcheck reports zero findings with no suppression added."
|
||||
],
|
||||
"out_of_scope": [
|
||||
"Running the install phases under test, which would rewrite /etc/hosts, unmount the guard's bind mount and restart systemd-resolved.",
|
||||
"Adding a dry-run or status mode, which would make end-to-end testing possible but is a feature change rather than a split.",
|
||||
"The SERVICES_ROOT-style path prefix that would make the phases testable; that is a separate follow-up.",
|
||||
"The three files still over the cap."
|
||||
],
|
||||
"verifier": "A per-phase body diff against the pre-wrap file, a line-multiset check for lost content, a diff of the 254 extracted domains, bash meta/scripts/verify_shell_split.sh 241652ca, lib/tests/run_all.sh (36 assertions), bash meta/scripts/shell_coverage.sh on both guards at 100, `bash install.sh --help` compared to pre-split, sha256sum -c on /etc/hosts, shellcheck, and check_file_length.sh --all."
|
||||
}
|
||||
@ -0,0 +1,58 @@
|
||||
{
|
||||
"intent": "Split generate_study_materials.sh (1017 lines) under the 250-line cap with 100% covered libs, and fix the four latent defects the tests exposed. File 2 of the Phase 1 queue.",
|
||||
"scope": [
|
||||
"linux_configuration/scripts/single_use/utils/generate_study_materials.sh — 1017 lines down to 148",
|
||||
"lib/study_doc_urls.sh, study_doc_urls_more.sh, study_doc_lookup.sh, study_gen_docs.sh, study_gen_anki.sh, study_gen_llm.sh — new",
|
||||
"lib/tests/ — a harness, four test files and a runner",
|
||||
"Non-goal: changing the generated output for any input the pre-split script handled correctly"
|
||||
],
|
||||
"changes": [
|
||||
"Wrapped the 335-line top-level Main Processing block into generate_doc_links / generate_anki_cards / generate_llm_prompt so it could be moved at all: extract_shell_functions.py only relocates functions. The bodies were deliberately NOT re-indented, because five heredocs with quoted terminators must keep those terminators at column 0.",
|
||||
"Moved the ten pre-existing functions verbatim into six libs grouped by subject: the per-language URL builders, the lookup/dispatch layer, and one lib per generation phase.",
|
||||
"FIX 1 — python_doc_url required a $2 it never reads. get_doc_url has always called it with one argument, which only worked because the entry script runs `set -e` without `-u`. Any caller enabling `set -u` aborted. Defaulted it, and did the same for the three other positionals documented as optional but declared required.",
|
||||
"FIX 2 — the two imports loops hardcoded `head -20` while the other seven honoured TOP_N, so --top was silently ignored for imports.",
|
||||
"FIX 3 — only one of the nine term loops skipped comment lines, so a '#' line in an analysis file became a flashcard whose front was a comment. All nine now filter.",
|
||||
"FIX 4 — introduced and then fixed within this change: `grep -v '^#'` must run BEFORE `head -n`, or comment lines count against the limit, and it needs `|| true`, because grep exits 1 when it filters every line and the callers run under `set -e`."
|
||||
],
|
||||
"verification": [
|
||||
{
|
||||
"command": "sha256sum -c against a golden fixture captured before any edit",
|
||||
"result": "pass",
|
||||
"evidence": "All three outputs — anki_cards.txt, documentation_links.md, llm_anki_prompt.md — byte-identical, and stdout identical, re-checked after every step including the four fixes and the final shfmt."
|
||||
},
|
||||
{
|
||||
"command": "bash meta/scripts/verify_shell_split.sh 08f3c764 <old> <old> lib/study_*.sh",
|
||||
"result": "pass",
|
||||
"evidence": "Only additions reported (generate_doc_links, generate_anki_cards), which are the new wrappers around previously top-level code. Every pre-existing function hashes identically."
|
||||
},
|
||||
{
|
||||
"command": "A second fixture with 25 imports and comment lines, run at --top 3",
|
||||
"result": "pass",
|
||||
"evidence": "Before the fixes: 20 imports emitted regardless of --top, and the comment line appeared as a card in both anki_cards.txt and documentation_links.md. After: exactly 3 imports, zero comment leakage. The golden fixture cannot show this because it has no comments and fewer than 20 imports — which is why the defects survived."
|
||||
},
|
||||
{
|
||||
"command": "lib/tests/run_all.sh",
|
||||
"result": "pass",
|
||||
"evidence": "166 assertions across 4 test files, 0 failures: doc_urls 57, doc_urls_more 45, doc_lookup 24, gen 49."
|
||||
},
|
||||
{
|
||||
"command": "bash meta/scripts/shell_coverage.sh lib/tests/run_all.sh <lib> 100",
|
||||
"result": "pass on 4 of 6",
|
||||
"evidence": "study_doc_urls.sh 38/38, study_doc_urls_more.sh 30/30, study_doc_lookup.sh 49/49, study_gen_llm.sh 54/54 — all 100.00%. study_gen_docs.sh 93.10% and study_gen_anki.sh 96.15%; every remaining line is a `} >>\"$DOCS_FILE\"` or `} >>\"$ANKI_FILE\"` closing a brace group whose output is asserted by a passing test, i.e. the same kcov attribution artifact diagnosed for services_hosts.sh."
|
||||
},
|
||||
{
|
||||
"command": "shellcheck generate_study_materials.sh lib/study_*.sh lib/tests/*.sh; bash meta/scripts/check_file_length.sh --all",
|
||||
"result": "pass",
|
||||
"evidence": "Zero findings, no suppression. No file over 250 lines; largest lib is study_gen_docs.sh at 239."
|
||||
}
|
||||
],
|
||||
"risks": [
|
||||
"Fixes 2 and 3 deliberately change output for inputs the pre-split script handled wrongly: a repo with more than TOP_N imports now gets the number asked for rather than 20, and comment lines no longer become cards. Both are corrections, but a user comparing against an old documentation_links.md will see a diff.",
|
||||
"The wrapper functions are the one part not proven verbatim. Their bodies are unchanged text, and the golden fixture covers all three phases end to end, but the wrapping itself is structural rather than hash-verified.",
|
||||
"TOP_N now applies to imports, so a very large --top produces a correspondingly larger prompt file. That is the documented meaning of the flag."
|
||||
],
|
||||
"rollback": [
|
||||
"git revert this commit: the split is additive (six libs, six test files) plus one rewritten entry script; nothing outside the repo is touched.",
|
||||
"After rollback, re-run the script against any results dir and confirm the three output files are still produced."
|
||||
]
|
||||
}
|
||||
@ -0,0 +1,68 @@
|
||||
{
|
||||
"intent": "Split hosts/install.sh (913 lines) under the 250-line cap, cover its two anti-tamper guards at 100%, and fix the defects the tests exposed. File 3 of the Phase 1 queue, and the one with the widest reference surface (13 files) and the highest blast radius.",
|
||||
"scope": [
|
||||
"linux_configuration/scripts/periodic_background/hosts/install.sh — 913 lines down to 150",
|
||||
"lib/hosts_protect_custom.sh, hosts_protect_unblock.sh, hosts_guard.sh, hosts_cache.sh, hosts_write.sh, hosts_browser_doh.sh — new",
|
||||
"custom_entries.hosts — the ~320-line blocklist heredoc, now a data file",
|
||||
"lib/tests/ — a harness, two test files and a runner",
|
||||
"Non-goal: running the installer end to end, which would rewrite /etc/hosts and take down the guard"
|
||||
],
|
||||
"changes": [
|
||||
"Wrapped the 712-line top-level block into eight phase functions and moved them into libs. Bodies were not re-indented at wrap time (five heredocs need column-0 terminators); shfmt indented them afterwards, which is why the verification below compares content rather than exact lines.",
|
||||
"Moved the ~320-line custom-blocklist heredoc into custom_entries.hosts. It was 321 of the 370 lines of hosts_write.sh and could not be split, so the lib could not otherwise fit the cap. A hosts-format data file is also easier to audit than a quoted heredoc.",
|
||||
"FIX 1 — moving the blocklist broke extract_custom_entries_from_script, which sliced between '# Custom blocking entries' and the heredoc terminator. With no terminator in the data file it would have extracted NOTHING, silently disabling the guard that refuses to drop blocked domains. It now reads the data file directly; the extracted set is identical (254 domains, diffed).",
|
||||
"FIX 2 — extract_unblock_entries_from_script matched its own marker lines. PROTECTED_UNBLOCK_LIST_START and _END are word characters, so the '^# [a-zA-Z0-9._-]+$' pattern pulled both into the whitelist as if they were domains. They are in the live state file on this machine right now. Renaming either marker would have read as the whitelist growing and blocked the install.",
|
||||
"Made three call sites overridable so the guards could be tested at all: HOSTS_INSTALL_SCRIPT_PATH for `readlink -f $0` and HOSTS_FILE_PATH for the /etc/hosts fallback read. Both default to the production value."
|
||||
],
|
||||
"verification": [
|
||||
{
|
||||
"command": "Per-phase body diff against the pre-wrap file",
|
||||
"result": "pass",
|
||||
"evidence": "All 8 wrapped phase bodies byte-identical to their original line ranges at wrap time — enable_resolved_reads_hosts (23), stop_hosts_guard (24), refresh_upstream_cache (49), write_hosts_file (354), restart_hosts_guard (20), save_protection_state (25), disable_browser_doh (63), restart_browsers (33). A line-multiset comparison confirmed 0 original lines lost and only 62 wrapper lines added."
|
||||
},
|
||||
{
|
||||
"command": "Content comparison of the final tree against the pre-split file, ignoring indentation",
|
||||
"result": "pass",
|
||||
"evidence": "Exactly 8 original lines absent, each an intentional edit: 2 from the rewritten custom-entries extractor, 3 `readlink -f \"$0\"` made overridable, 1 /etc/hosts fallback made overridable, and the heredoc opener/terminator replaced by the data-file read. Nothing else changed."
|
||||
},
|
||||
{
|
||||
"command": "diff of the 254 custom-blocked domains, old heredoc vs new data file",
|
||||
"result": "pass",
|
||||
"evidence": "Identical sets. This is what proves FIX 1 preserved the guard's input rather than merely making it run."
|
||||
},
|
||||
{
|
||||
"command": "bash meta/scripts/verify_shell_split.sh 241652ca <old> <old> lib/hosts_*.sh",
|
||||
"result": "pass",
|
||||
"evidence": "8 additions (the phase wrappers) and one changed body — extract_custom_entries_from_script, the deliberate rewrite. Every other pre-existing function hashes identically."
|
||||
},
|
||||
{
|
||||
"command": "bash install.sh --help; sha256sum -c on /etc/hosts",
|
||||
"result": "pass",
|
||||
"evidence": "--help output identical to pre-split, and /etc/hosts unchanged across the entire session. --help is the only execution path that exits before any write; there is no dry-run or status mode, which is why end-to-end execution was not used as proof."
|
||||
},
|
||||
{
|
||||
"command": "lib/tests/run_all.sh",
|
||||
"result": "pass",
|
||||
"evidence": "36 assertions, 0 failures: test_hosts_protect.sh 25, test_hosts_cache.sh 11. Both directions of both guards are covered — removing a blocked domain is refused, adding one is allowed; growing the whitelist is refused, shrinking it is allowed. A same-count swap is also refused, which a count-only check would have passed."
|
||||
},
|
||||
{
|
||||
"command": "bash meta/scripts/shell_coverage.sh lib/tests/test_hosts_protect.sh <guard> 100",
|
||||
"result": "pass",
|
||||
"evidence": "hosts_protect_custom.sh 75/75 = 100.00%, hosts_protect_unblock.sh 49/49 = 100.00%. These are the two functions where a silent regression matters most."
|
||||
},
|
||||
{
|
||||
"command": "shellcheck install.sh lib/hosts_*.sh lib/tests/*.sh; check_file_length.sh --all",
|
||||
"result": "pass",
|
||||
"evidence": "Zero findings standalone and with -x, no suppression. No shell file over 250 lines; largest is install.sh at 150."
|
||||
}
|
||||
],
|
||||
"risks": [
|
||||
"The install phases have NO test coverage, and that is deliberate: they write /etc/hosts, unmount the guard's bind mount and restart systemd-resolved, so running them under test would take down the protection they install. Their proof is textual (byte-identical bodies) rather than behavioural, which is genuinely weaker evidence than the previous two splits had. Making them testable needs the SERVICES_ROOT-style prefix, which is a separate change.",
|
||||
"FIX 2 changes what the unblock guard sees: the live state file still holds the two phantom marker entries, so the next install reads the whitelist as having SHRUNK by 2. Shrinking is always allowed, so the install proceeds and rewrites the state without the phantoms. No manual step is needed, but the next run's output will report 2 removed entries.",
|
||||
"custom_entries.hosts is now the file to edit to change the blocklist, and check_custom_entries_protection watches it. Editing install.sh instead would no longer have any effect on what gets blocked."
|
||||
],
|
||||
"rollback": [
|
||||
"git revert this commit restores the single file, the heredoc and the original extractors together.",
|
||||
"After rollback, run `bash install.sh --help` and confirm it still exits 0, and check that /etc/hosts is untouched — the revert changes no system state by itself."
|
||||
]
|
||||
}
|
||||
@ -0,0 +1,329 @@
|
||||
# Custom blocking entries appended to /etc/hosts by lib/hosts_write.sh.
|
||||
#
|
||||
# Kept as data rather than as a heredoc inside the script: at ~320 lines it was
|
||||
# most of that file and pushed it over the repo-wide 250-line cap, and a plain
|
||||
# hosts-format file is also easier to diff and to audit than a quoted heredoc.
|
||||
# The content is byte-identical to the heredoc it replaces.
|
||||
#
|
||||
# Format is standard /etc/hosts: "0.0.0.0 domain" to block, "#" to comment.
|
||||
# check_custom_entries_protection reads this same file to detect entries being
|
||||
# removed, so edits here are what the anti-tamper guard is watching.
|
||||
|
||||
# Custom blocking entries
|
||||
# YouTube
|
||||
0.0.0.0 youtube.com
|
||||
0.0.0.0 www.youtube.com
|
||||
0.0.0.0 m.youtube.com
|
||||
0.0.0.0 youtu.be
|
||||
0.0.0.0 youtube-nocookie.com
|
||||
0.0.0.0 www.youtube-nocookie.com
|
||||
0.0.0.0 youtubei.googleapis.com
|
||||
0.0.0.0 youtube.googleapis.com
|
||||
0.0.0.0 yt3.ggpht.com
|
||||
# Channel avatars and banners. Same role as yt3.ggpht.com, which was already
|
||||
# here -- Google serves them from both hosts, so blocking one leaves the other
|
||||
# resolving. Caught when the phone's DoT resolver was checked domain by domain
|
||||
# against the 14 the focus policy names.
|
||||
0.0.0.0 yt3.googleusercontent.com
|
||||
0.0.0.0 ytimg.com
|
||||
0.0.0.0 i.ytimg.com
|
||||
0.0.0.0 s.ytimg.com
|
||||
0.0.0.0 i9.ytimg.com
|
||||
0.0.0.0 googlevideo.com
|
||||
0.0.0.0 r1---sn-4g5e6nls.googlevideo.com
|
||||
0.0.0.0 r1---sn-4g5lne7s.googlevideo.com
|
||||
|
||||
# Alternative YouTube Frontends (Invidious, Piped, etc.)
|
||||
0.0.0.0 invidious.io
|
||||
0.0.0.0 www.invidious.io
|
||||
0.0.0.0 invidio.us
|
||||
0.0.0.0 vid.puffyan.us
|
||||
0.0.0.0 invidious.snopyta.org
|
||||
0.0.0.0 yewtu.be
|
||||
0.0.0.0 invidious.kavin.rocks
|
||||
0.0.0.0 inv.riverside.rocks
|
||||
0.0.0.0 invidious.namazso.eu
|
||||
0.0.0.0 invidious.nerdvpn.de
|
||||
0.0.0.0 invidious.projectsegfau.lt
|
||||
0.0.0.0 invidious.slipfox.xyz
|
||||
0.0.0.0 invidious.privacydev.net
|
||||
0.0.0.0 invidious.perennialte.ch
|
||||
0.0.0.0 invidious.protokoll-11.de
|
||||
0.0.0.0 invidious.einfachzocken.eu
|
||||
0.0.0.0 invidious.fdn.fr
|
||||
0.0.0.0 inv.in.projectsegfau.lt
|
||||
0.0.0.0 invidious.tiekoetter.com
|
||||
0.0.0.0 invidious.lunar.icu
|
||||
0.0.0.0 iv.ggtyler.dev
|
||||
0.0.0.0 iv.melmac.space
|
||||
0.0.0.0 piped.video
|
||||
0.0.0.0 www.piped.video
|
||||
0.0.0.0 piped.kavin.rocks
|
||||
0.0.0.0 piped.mha.fi
|
||||
0.0.0.0 piped.mint.lgbt
|
||||
0.0.0.0 piped.projectsegfau.lt
|
||||
0.0.0.0 piped.privacydev.net
|
||||
0.0.0.0 piped.smnz.de
|
||||
0.0.0.0 piped.adminforge.de
|
||||
0.0.0.0 watch.whatever.social
|
||||
0.0.0.0 piped.lunar.icu
|
||||
0.0.0.0 viewtube.io
|
||||
0.0.0.0 www.viewtube.io
|
||||
0.0.0.0 freetube.io
|
||||
0.0.0.0 www.freetube.io
|
||||
0.0.0.0 tubo.media
|
||||
0.0.0.0 www.tubo.media
|
||||
0.0.0.0 materialious.nadeko.net
|
||||
0.0.0.0 clipious.org
|
||||
0.0.0.0 www.clipious.org
|
||||
0.0.0.0 newpipe.net
|
||||
0.0.0.0 www.newpipe.net
|
||||
0.0.0.0 newpipe.schabi.org
|
||||
0.0.0.0 grayjay.app
|
||||
0.0.0.0 www.grayjay.app
|
||||
0.0.0.0 libretube.dev
|
||||
0.0.0.0 www.libretube.dev
|
||||
0.0.0.0 hyperion.deishelon.com
|
||||
0.0.0.0 inv.n8pjl.ca
|
||||
0.0.0.0 inv.zzls.xyz
|
||||
0.0.0.0 inv.tux.pizza
|
||||
0.0.0.0 invidious.incogniweb.net
|
||||
0.0.0.0 invidious.drgns.space
|
||||
0.0.0.0 invidious.io.lol
|
||||
|
||||
# Steam Store
|
||||
0.0.0.0 store.steampowered.com
|
||||
0.0.0.0 checkout.steampowered.com
|
||||
0.0.0.0 store.akamai.steamstatic.com
|
||||
0.0.0.0 storefront.steampowered.com
|
||||
0.0.0.0 store.cloudflare.steamstatic.com
|
||||
|
||||
# Discord - media allowed
|
||||
# 0.0.0.0 cdn.discordapp.com
|
||||
# 0.0.0.0 media.discordapp.net
|
||||
# 0.0.0.0 images-ext-1.discordapp.net
|
||||
# 0.0.0.0 images-ext-2.discordapp.net
|
||||
# 0.0.0.0 attachments-1.discordapp.net
|
||||
# 0.0.0.0 attachments-2.discordapp.net
|
||||
# 0.0.0.0 tenor.com
|
||||
# 0.0.0.0 giphy.com
|
||||
|
||||
# Food Delivery Services
|
||||
# Polish services
|
||||
0.0.0.0 pyszne.pl
|
||||
0.0.0.0 www.pyszne.pl
|
||||
0.0.0.0 m.pyszne.pl
|
||||
0.0.0.0 api.pyszne.pl
|
||||
0.0.0.0 app.pyszne.pl
|
||||
0.0.0.0 glovo.com
|
||||
0.0.0.0 www.glovo.com
|
||||
0.0.0.0 m.glovo.com
|
||||
0.0.0.0 api.glovo.com
|
||||
0.0.0.0 glovoapp.com
|
||||
0.0.0.0 www.glovoapp.com
|
||||
0.0.0.0 bolt.eu
|
||||
:: bolt.eu
|
||||
0.0.0.0 www.bolt.eu
|
||||
:: www.bolt.eu
|
||||
0.0.0.0 food.bolt.eu
|
||||
:: food.bolt.eu
|
||||
0.0.0.0 m.bolt.eu
|
||||
:: m.bolt.eu
|
||||
0.0.0.0 api.bolt.eu
|
||||
:: api.bolt.eu
|
||||
0.0.0.0 node.bolt.eu
|
||||
:: node.bolt.eu
|
||||
0.0.0.0 gw.bolt.eu
|
||||
:: gw.bolt.eu
|
||||
0.0.0.0 client-api.bolt.eu
|
||||
:: client-api.bolt.eu
|
||||
0.0.0.0 auth.bolt.eu
|
||||
:: auth.bolt.eu
|
||||
0.0.0.0 cdn.bolt.eu
|
||||
:: cdn.bolt.eu
|
||||
0.0.0.0 images.bolt.eu
|
||||
:: images.bolt.eu
|
||||
0.0.0.0 static.bolt.eu
|
||||
:: static.bolt.eu
|
||||
0.0.0.0 assets.bolt.eu
|
||||
:: assets.bolt.eu
|
||||
0.0.0.0 fleet.bolt.eu
|
||||
:: fleet.bolt.eu
|
||||
0.0.0.0 user.bolt.eu
|
||||
:: user.bolt.eu
|
||||
0.0.0.0 courier.bolt.eu
|
||||
:: courier.bolt.eu
|
||||
0.0.0.0 rider.bolt.eu
|
||||
:: rider.bolt.eu
|
||||
0.0.0.0 restaurant.bolt.eu
|
||||
:: restaurant.bolt.eu
|
||||
0.0.0.0 partner-food.bolt.eu
|
||||
:: partner-food.bolt.eu
|
||||
0.0.0.0 woltwojta.pl
|
||||
0.0.0.0 www.woltwojta.pl
|
||||
0.0.0.0 wolt.com
|
||||
0.0.0.0 www.wolt.com
|
||||
0.0.0.0 m.wolt.com
|
||||
0.0.0.0 api.wolt.com
|
||||
0.0.0.0 restaurant-api.wolt.com
|
||||
0.0.0.0 consumer-api.wolt.com
|
||||
0.0.0.0 jush.pl
|
||||
0.0.0.0 www.jush.pl
|
||||
0.0.0.0 m.jush.pl
|
||||
0.0.0.0 api.jush.pl
|
||||
0.0.0.0 delio.pl
|
||||
:: delio.pl
|
||||
0.0.0.0 www.delio.pl
|
||||
:: www.delio.pl
|
||||
0.0.0.0 m.delio.pl
|
||||
:: m.delio.pl
|
||||
0.0.0.0 api.delio.pl
|
||||
:: api.delio.pl
|
||||
0.0.0.0 app.delio.pl
|
||||
:: app.delio.pl
|
||||
0.0.0.0 cdn.delio.pl
|
||||
:: cdn.delio.pl
|
||||
0.0.0.0 static.delio.pl
|
||||
:: static.delio.pl
|
||||
0.0.0.0 order.delio.pl
|
||||
:: order.delio.pl
|
||||
0.0.0.0 delio.com
|
||||
:: delio.com
|
||||
0.0.0.0 www.delio.com
|
||||
:: www.delio.com
|
||||
0.0.0.0 m.delio.com
|
||||
:: m.delio.com
|
||||
0.0.0.0 api.delio.com
|
||||
:: api.delio.com
|
||||
0.0.0.0 app.delio.com
|
||||
:: app.delio.com
|
||||
0.0.0.0 delio.com.pl
|
||||
:: delio.com.pl
|
||||
0.0.0.0 www.delio.com.pl
|
||||
:: www.delio.com.pl
|
||||
0.0.0.0 m.delio.com.pl
|
||||
:: m.delio.com.pl
|
||||
0.0.0.0 api.delio.com.pl
|
||||
:: api.delio.com.pl
|
||||
0.0.0.0 app.delio.com.pl
|
||||
:: app.delio.com.pl
|
||||
0.0.0.0 lisek.app
|
||||
0.0.0.0 www.lisek.app
|
||||
0.0.0.0 api.lisek.app
|
||||
0.0.0.0 stava.app
|
||||
0.0.0.0 www.stava.app
|
||||
0.0.0.0 api.stava.app
|
||||
0.0.0.0 biedronka.pl
|
||||
0.0.0.0 zakupy.biedronka.pl
|
||||
0.0.0.0 ezakupy.tesco.pl
|
||||
0.0.0.0 www.ezakupy.tesco.pl
|
||||
0.0.0.0 barbora.pl
|
||||
0.0.0.0 www.barbora.pl
|
||||
0.0.0.0 api.barbora.pl
|
||||
0.0.0.0 frisco.pl
|
||||
0.0.0.0 www.frisco.pl
|
||||
0.0.0.0 api.frisco.pl
|
||||
0.0.0.0 swiatkwiatow.pl
|
||||
0.0.0.0 www.swiatkwiatow.pl
|
||||
0.0.0.0 allegro.pl/kategoria/jedzenie
|
||||
0.0.0.0 szama.pl
|
||||
0.0.0.0 www.szama.pl
|
||||
0.0.0.0 api.szama.pl
|
||||
0.0.0.0 auchandirect.pl
|
||||
0.0.0.0 www.auchandirect.pl
|
||||
|
||||
# International services
|
||||
0.0.0.0 ubereats.com
|
||||
0.0.0.0 www.ubereats.com
|
||||
0.0.0.0 m.ubereats.com
|
||||
0.0.0.0 api.ubereats.com
|
||||
0.0.0.0 uber.com
|
||||
0.0.0.0 www.uber.com
|
||||
0.0.0.0 m.uber.com
|
||||
0.0.0.0 api.uber.com
|
||||
0.0.0.0 cn-geo1.uber.com
|
||||
0.0.0.0 login.uber.com
|
||||
0.0.0.0 auth.uber.com
|
||||
0.0.0.0 riders.uber.com
|
||||
0.0.0.0 deliveroo.com
|
||||
0.0.0.0 www.deliveroo.com
|
||||
0.0.0.0 m.deliveroo.com
|
||||
0.0.0.0 api.deliveroo.com
|
||||
0.0.0.0 deliveroo.co.uk
|
||||
0.0.0.0 www.deliveroo.co.uk
|
||||
0.0.0.0 foodpanda.com
|
||||
0.0.0.0 www.foodpanda.com
|
||||
0.0.0.0 m.foodpanda.com
|
||||
0.0.0.0 api.foodpanda.com
|
||||
0.0.0.0 grubhub.com
|
||||
0.0.0.0 www.grubhub.com
|
||||
0.0.0.0 m.grubhub.com
|
||||
0.0.0.0 api.grubhub.com
|
||||
0.0.0.0 doordash.com
|
||||
0.0.0.0 www.doordash.com
|
||||
0.0.0.0 m.doordash.com
|
||||
0.0.0.0 api.doordash.com
|
||||
0.0.0.0 justeat.com
|
||||
0.0.0.0 www.justeat.com
|
||||
0.0.0.0 m.justeat.com
|
||||
0.0.0.0 justeat.co.uk
|
||||
0.0.0.0 www.justeat.co.uk
|
||||
0.0.0.0 postmates.com
|
||||
0.0.0.0 www.postmates.com
|
||||
0.0.0.0 api.postmates.com
|
||||
0.0.0.0 seamless.com
|
||||
0.0.0.0 www.seamless.com
|
||||
0.0.0.0 menulog.com.au
|
||||
0.0.0.0 www.menulog.com.au
|
||||
0.0.0.0 delivery.com
|
||||
0.0.0.0 www.delivery.com
|
||||
0.0.0.0 getir.com
|
||||
0.0.0.0 www.getir.com
|
||||
0.0.0.0 api.getir.com
|
||||
0.0.0.0 flink.com
|
||||
0.0.0.0 www.flink.com
|
||||
0.0.0.0 api.flink.com
|
||||
0.0.0.0 gorillas.io
|
||||
0.0.0.0 www.gorillas.io
|
||||
0.0.0.0 api.gorillas.io
|
||||
0.0.0.0 gopuff.com
|
||||
0.0.0.0 www.gopuff.com
|
||||
0.0.0.0 api.gopuff.com
|
||||
0.0.0.0 instacart.com
|
||||
0.0.0.0 www.instacart.com
|
||||
0.0.0.0 api.instacart.com
|
||||
0.0.0.0 takeaway.com
|
||||
0.0.0.0 www.takeaway.com
|
||||
0.0.0.0 api.takeaway.com
|
||||
|
||||
# Fast food chain apps and websites
|
||||
0.0.0.0 mcdonalds.com
|
||||
0.0.0.0 www.mcdonalds.com
|
||||
0.0.0.0 m.mcdonalds.com
|
||||
0.0.0.0 mcdonalds.pl
|
||||
0.0.0.0 www.mcdonalds.pl
|
||||
0.0.0.0 kfc.com
|
||||
0.0.0.0 www.kfc.com
|
||||
0.0.0.0 m.kfc.com
|
||||
0.0.0.0 kfc.pl
|
||||
0.0.0.0 www.kfc.pl
|
||||
0.0.0.0 burgerking.com
|
||||
0.0.0.0 www.burgerking.com
|
||||
0.0.0.0 m.burgerking.com
|
||||
0.0.0.0 burgerking.pl
|
||||
0.0.0.0 www.burgerking.pl
|
||||
0.0.0.0 pizzahut.com
|
||||
0.0.0.0 www.pizzahut.com
|
||||
0.0.0.0 m.pizzahut.com
|
||||
0.0.0.0 pizzahut.pl
|
||||
0.0.0.0 www.pizzahut.pl
|
||||
0.0.0.0 dominos.com
|
||||
0.0.0.0 www.dominos.com
|
||||
0.0.0.0 m.dominos.com
|
||||
0.0.0.0 dominos.pl
|
||||
0.0.0.0 www.dominos.pl
|
||||
0.0.0.0 subway.com
|
||||
0.0.0.0 www.subway.com
|
||||
0.0.0.0 m.subway.com
|
||||
0.0.0.0 subway.pl
|
||||
0.0.0.0 www.subway.pl
|
||||
@ -25,6 +25,23 @@ for arg in "$@"; do
|
||||
esac
|
||||
done
|
||||
|
||||
# Each phase of the install lives in a lib beside this file; this script
|
||||
# keeps the flag parsing, the protection-check gates and the order the
|
||||
# phases run in.
|
||||
LIB_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)/lib"
|
||||
# shellcheck source=lib/hosts_protect_custom.sh
|
||||
. "$LIB_DIR/hosts_protect_custom.sh"
|
||||
# shellcheck source=lib/hosts_protect_unblock.sh
|
||||
. "$LIB_DIR/hosts_protect_unblock.sh"
|
||||
# shellcheck source=lib/hosts_guard.sh
|
||||
. "$LIB_DIR/hosts_guard.sh"
|
||||
# shellcheck source=lib/hosts_cache.sh
|
||||
. "$LIB_DIR/hosts_cache.sh"
|
||||
# shellcheck source=lib/hosts_write.sh
|
||||
. "$LIB_DIR/hosts_write.sh"
|
||||
# shellcheck source=lib/hosts_browser_doh.sh
|
||||
. "$LIB_DIR/hosts_browser_doh.sh"
|
||||
|
||||
# ============================================================================
|
||||
# CUSTOM ENTRIES PROTECTION MECHANISM
|
||||
# ============================================================================
|
||||
@ -37,129 +54,6 @@ done
|
||||
CUSTOM_ENTRIES_STATE_FILE="/etc/hosts.custom-entries.state"
|
||||
UNBLOCK_STATE_FILE="/etc/hosts.unblock-entries.state"
|
||||
|
||||
# Extract custom blocked entries from a hosts file or heredoc section
|
||||
# Returns only the "0.0.0.0 domain.com" lines (normalized, sorted, unique)
|
||||
extract_custom_entries_from_script() {
|
||||
# Extract entries from the heredoc in this script (between EOF markers after "Custom blocking entries")
|
||||
local script_path="$1"
|
||||
sed -n '/^# Custom blocking entries$/,/^EOF$/p' "$script_path" |
|
||||
grep -E '^0\.0\.0\.0[[:space:]]+' |
|
||||
awk '{print $2}' |
|
||||
sort -u
|
||||
}
|
||||
|
||||
# Extract custom entries from the current /etc/hosts (entries after "# Custom blocking entries" marker)
|
||||
extract_custom_entries_from_hosts() {
|
||||
local hosts_file="$1"
|
||||
if [[ ! -f $hosts_file ]]; then
|
||||
return
|
||||
fi
|
||||
sed -n '/^# Custom blocking entries$/,$p' "$hosts_file" |
|
||||
grep -E '^0\.0\.0\.0[[:space:]]+' |
|
||||
awk '{print $2}' |
|
||||
sort -u
|
||||
}
|
||||
|
||||
# Load previously saved custom entries state
|
||||
load_saved_custom_entries() {
|
||||
if [[ -f $CUSTOM_ENTRIES_STATE_FILE ]]; then
|
||||
sort -u "$CUSTOM_ENTRIES_STATE_FILE"
|
||||
fi
|
||||
}
|
||||
|
||||
# Save current custom entries to state file
|
||||
save_custom_entries_state() {
|
||||
local entries="$1"
|
||||
echo "$entries" | sort -u >"$CUSTOM_ENTRIES_STATE_FILE"
|
||||
chmod 644 "$CUSTOM_ENTRIES_STATE_FILE"
|
||||
chattr +i "$CUSTOM_ENTRIES_STATE_FILE" 2>/dev/null || true
|
||||
}
|
||||
|
||||
# Helper function to count non-empty lines
|
||||
count_lines() {
|
||||
local input="$1"
|
||||
if [[ -z $input ]]; then
|
||||
echo 0
|
||||
else
|
||||
echo "$input" | grep -c . 2>/dev/null || echo 0
|
||||
fi
|
||||
}
|
||||
|
||||
# Main protection check
|
||||
check_custom_entries_protection() {
|
||||
local script_path
|
||||
script_path="$(readlink -f "$0")"
|
||||
|
||||
# Get new entries from the script's heredoc
|
||||
local new_entries
|
||||
new_entries=$(extract_custom_entries_from_script "$script_path")
|
||||
local new_count
|
||||
new_count=$(count_lines "$new_entries")
|
||||
|
||||
# Get saved/existing entries (prefer state file, fall back to current /etc/hosts)
|
||||
local saved_entries
|
||||
saved_entries=$(load_saved_custom_entries)
|
||||
if [[ -z $saved_entries ]]; then
|
||||
# First run or state file missing - extract from current /etc/hosts if it has our marker
|
||||
saved_entries=$(extract_custom_entries_from_hosts "/etc/hosts")
|
||||
fi
|
||||
local saved_count
|
||||
saved_count=$(count_lines "$saved_entries")
|
||||
|
||||
# If no saved state exists, this is first installation - allow it
|
||||
if [[ $saved_count -eq 0 ]]; then
|
||||
echo "ℹ️ First installation detected - no protection check needed."
|
||||
return 0
|
||||
fi
|
||||
|
||||
# Find entries that were removed
|
||||
local removed_entries
|
||||
removed_entries=$(comm -23 <(echo "$saved_entries") <(echo "$new_entries"))
|
||||
local removed_count
|
||||
removed_count=$(count_lines "$removed_entries")
|
||||
|
||||
# Find entries that are new
|
||||
local added_entries
|
||||
added_entries=$(comm -13 <(echo "$saved_entries") <(echo "$new_entries"))
|
||||
local added_count
|
||||
added_count=$(count_lines "$added_entries")
|
||||
|
||||
echo ""
|
||||
echo "📊 Custom Entries Protection Check:"
|
||||
echo " Previously blocked: $saved_count entries"
|
||||
echo " Currently in script: $new_count entries"
|
||||
echo " Removed: $removed_count | Added: $added_count"
|
||||
|
||||
# RULE 1: No entries removed - always OK
|
||||
if [[ $removed_count -eq 0 ]]; then
|
||||
echo " ✅ No entries removed - protection check passed."
|
||||
return 0
|
||||
fi
|
||||
|
||||
# RULE 2: Entries were removed - BLOCK INSTALLATION
|
||||
echo ""
|
||||
echo "============================================================"
|
||||
echo " ❌ INSTALLATION BLOCKED - CUSTOM ENTRIES REMOVED"
|
||||
echo "============================================================"
|
||||
echo ""
|
||||
echo "You are attempting to REMOVE the following blocked entries:"
|
||||
while IFS= read -r entry; do
|
||||
echo " - $entry"
|
||||
done <<<"$removed_entries"
|
||||
echo ""
|
||||
echo "This is NOT allowed. The only way to unblock sites is to:"
|
||||
echo ""
|
||||
echo " 1. Manually edit /etc/hosts (requires removing chattr protection)"
|
||||
echo " 2. Delete the state file /etc/hosts.custom-entries.state"
|
||||
echo " (also protected with chattr)"
|
||||
echo ""
|
||||
echo "These manual steps are intentionally difficult to prevent"
|
||||
echo "impulsive unblocking. If you really need to unblock something,"
|
||||
echo "you'll have to work for it."
|
||||
echo ""
|
||||
return 1
|
||||
}
|
||||
|
||||
# Run the protection check
|
||||
if ! check_custom_entries_protection; then
|
||||
exit 1
|
||||
@ -192,709 +86,16 @@ fi
|
||||
# licdn.com
|
||||
# PROTECTED_UNBLOCK_LIST_END
|
||||
|
||||
# Extract whitelisted domains from the protected list embedded in this script
|
||||
extract_unblock_entries_from_script() {
|
||||
local script_path="$1"
|
||||
sed -n '/^# PROTECTED_UNBLOCK_LIST_START$/,/^# PROTECTED_UNBLOCK_LIST_END$/p' "$script_path" |
|
||||
grep -E '^# [a-zA-Z0-9._-]+$' |
|
||||
sed 's/^# //' |
|
||||
sort -u
|
||||
}
|
||||
|
||||
# Save current unblock entries to immutable state file
|
||||
save_unblock_entries_state() {
|
||||
local entries="$1"
|
||||
chattr -i "$UNBLOCK_STATE_FILE" 2>/dev/null || true
|
||||
echo "$entries" | sort -u >"$UNBLOCK_STATE_FILE"
|
||||
chmod 644 "$UNBLOCK_STATE_FILE"
|
||||
chattr +i "$UNBLOCK_STATE_FILE" 2>/dev/null || true
|
||||
}
|
||||
|
||||
# Block installation if the unblock list has grown (more sites being whitelisted)
|
||||
check_unblock_entries_protection() {
|
||||
local script_path
|
||||
script_path="$(readlink -f "$0")"
|
||||
|
||||
local new_entries
|
||||
new_entries=$(extract_unblock_entries_from_script "$script_path")
|
||||
local new_count
|
||||
new_count=$(count_lines "$new_entries")
|
||||
|
||||
if [[ ! -f $UNBLOCK_STATE_FILE ]]; then
|
||||
echo "ℹ️ First unblock-list run — no protection check needed."
|
||||
return 0
|
||||
fi
|
||||
|
||||
local saved_entries
|
||||
saved_entries=$(sort -u "$UNBLOCK_STATE_FILE")
|
||||
local saved_count
|
||||
saved_count=$(count_lines "$saved_entries")
|
||||
|
||||
# Entries added since last install
|
||||
local added_entries
|
||||
added_entries=$(comm -13 <(echo "$saved_entries") <(echo "$new_entries"))
|
||||
local added_count
|
||||
added_count=$(count_lines "$added_entries")
|
||||
|
||||
echo ""
|
||||
echo "📊 Unblock Entries Protection Check:"
|
||||
echo " Previously whitelisted: $saved_count domains"
|
||||
echo " Currently in script: $new_count domains"
|
||||
echo " Newly added: $added_count"
|
||||
|
||||
if [[ $added_count -eq 0 ]]; then
|
||||
echo " ✅ No new unblocks — protection check passed."
|
||||
return 0
|
||||
fi
|
||||
|
||||
echo ""
|
||||
echo "============================================================"
|
||||
echo " ❌ INSTALLATION BLOCKED — NEW UNBLOCK ENTRIES DETECTED"
|
||||
echo "============================================================"
|
||||
echo ""
|
||||
echo "You are attempting to WHITELIST these additional domains:"
|
||||
while IFS= read -r entry; do
|
||||
echo " + $entry"
|
||||
done <<<"$added_entries"
|
||||
echo ""
|
||||
echo "To proceed, manually delete the state file first:"
|
||||
echo " sudo chattr -i $UNBLOCK_STATE_FILE && sudo rm $UNBLOCK_STATE_FILE"
|
||||
echo ""
|
||||
return 1
|
||||
}
|
||||
|
||||
# Run the unblock protection check
|
||||
if ! check_unblock_entries_protection; then
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# Enable systemd-resolved
|
||||
sudo systemctl enable systemd-resolved
|
||||
|
||||
# ============================================================================
|
||||
# ENSURE systemd-resolved READS /etc/hosts
|
||||
# ============================================================================
|
||||
# Without this, systemd-resolved ignores /etc/hosts entries entirely,
|
||||
# allowing blocked domains to resolve via DNS.
|
||||
RESOLVED_CONF="/etc/systemd/resolved.conf"
|
||||
if grep -q '^ReadEtcHosts=no' "$RESOLVED_CONF" 2>/dev/null; then
|
||||
echo "Fixing systemd-resolved: setting ReadEtcHosts=yes..."
|
||||
sudo sed -i 's/^ReadEtcHosts=no/ReadEtcHosts=yes/' "$RESOLVED_CONF"
|
||||
sudo systemctl restart systemd-resolved
|
||||
elif ! grep -q '^ReadEtcHosts=yes' "$RESOLVED_CONF" 2>/dev/null; then
|
||||
echo "Enabling ReadEtcHosts=yes in systemd-resolved..."
|
||||
if grep -q '^#ReadEtcHosts=' "$RESOLVED_CONF" 2>/dev/null; then
|
||||
sudo sed -i 's/^#ReadEtcHosts=.*/ReadEtcHosts=yes/' "$RESOLVED_CONF"
|
||||
else
|
||||
echo 'ReadEtcHosts=yes' | sudo tee -a "$RESOLVED_CONF" >/dev/null
|
||||
fi
|
||||
sudo systemctl restart systemd-resolved
|
||||
fi
|
||||
|
||||
# ============================================================================
|
||||
# TEMPORARILY DISABLE HOSTS GUARD PROTECTIONS FOR INSTALLATION
|
||||
# ============================================================================
|
||||
# The guard system uses a read-only bind mount and path watcher that prevent
|
||||
# any writes to /etc/hosts. We must stop them before installing, then restart.
|
||||
GUARD_SERVICES_STOPPED=0
|
||||
|
||||
for svc in hosts-bind-mount.service hosts-guard.path; do
|
||||
if systemctl is-active --quiet "$svc" 2>/dev/null; then
|
||||
echo "Stopping $svc for installation..."
|
||||
systemctl stop "$svc" 2>/dev/null || true
|
||||
GUARD_SERVICES_STOPPED=1
|
||||
fi
|
||||
done
|
||||
|
||||
# If bind mount is still active, unmount it
|
||||
if findmnt /etc/hosts >/dev/null 2>&1; then
|
||||
echo "Unmounting read-only bind mount on /etc/hosts..."
|
||||
umount /etc/hosts 2>/dev/null || mount -o remount,rw,bind /etc/hosts 2>/dev/null || true
|
||||
fi
|
||||
|
||||
# Remove all attributes from /etc/hosts to allow modifications
|
||||
sudo chattr -i -a /etc/hosts 2>/dev/null || true
|
||||
|
||||
# Source and local cache configuration
|
||||
URL="https://raw.githubusercontent.com/StevenBlack/hosts/master/alternates/fakenews-gambling-porn-social/hosts"
|
||||
# Cache stores the RAW upstream file (without our custom modifications)
|
||||
LOCAL_CACHE="/etc/hosts.stevenblack"
|
||||
|
||||
# Helpers
|
||||
extract_date_epoch_from_file() {
|
||||
# Grep "# Date:" line and convert to epoch seconds (UTC)
|
||||
local f="$1"
|
||||
local line
|
||||
line=$(grep -m1 '^# Date:' "$f" 2>/dev/null | sed -E 's/^# Date:[[:space:]]*(.*)[[:space:]]*\(UTC\).*/\1 UTC/')
|
||||
if [[ -n $line ]]; then
|
||||
date -u -d "$line" +%s 2>/dev/null || echo ""
|
||||
else
|
||||
echo ""
|
||||
fi
|
||||
}
|
||||
|
||||
fetch_remote_header() {
|
||||
# Try to fetch only the first ~4KB using HTTP Range; fallback to piping to head
|
||||
local out="$1"
|
||||
if curl -LfsS --max-time 10 -H 'Range: bytes=0-4095' "$URL" -o "$out"; then
|
||||
return 0
|
||||
fi
|
||||
# Fallback – may download more, but we only keep first lines
|
||||
if curl -LfsS --max-time 10 "$URL" | head -n 20 >"$out"; then
|
||||
return 0
|
||||
fi
|
||||
return 1
|
||||
}
|
||||
|
||||
download_remote_full_to() {
|
||||
local out="$1"
|
||||
curl -LfsS "$URL" -o "$out"
|
||||
}
|
||||
|
||||
# Decide whether to use cache or update
|
||||
TMP_REMOTE_HEAD=$(mktemp)
|
||||
trap 'rm -f "$TMP_REMOTE_HEAD"' EXIT
|
||||
|
||||
REMOTE_AVAILABLE=0
|
||||
if fetch_remote_header "$TMP_REMOTE_HEAD"; then
|
||||
REMOTE_AVAILABLE=1
|
||||
fi
|
||||
|
||||
NEED_UPDATE=0
|
||||
|
||||
if [[ -f $LOCAL_CACHE ]]; then
|
||||
local_epoch=$(extract_date_epoch_from_file "$LOCAL_CACHE")
|
||||
else
|
||||
local_epoch=""
|
||||
fi
|
||||
|
||||
if [[ $REMOTE_AVAILABLE -eq 1 ]]; then
|
||||
remote_epoch=$(extract_date_epoch_from_file "$TMP_REMOTE_HEAD")
|
||||
if [[ -n $local_epoch && -n $remote_epoch && $local_epoch -ge $remote_epoch ]]; then
|
||||
echo "Using cached StevenBlack hosts (up-to-date)."
|
||||
else
|
||||
echo "Cached version is missing or outdated; downloading latest StevenBlack hosts..."
|
||||
NEED_UPDATE=1
|
||||
fi
|
||||
else
|
||||
if [[ -f $LOCAL_CACHE ]]; then
|
||||
echo "No internet; using cached StevenBlack hosts."
|
||||
else
|
||||
echo "Error: No internet and no cached StevenBlack hosts found." >&2
|
||||
exit 1
|
||||
fi
|
||||
fi
|
||||
|
||||
# Ensure we have a fresh cache if needed
|
||||
if [[ $NEED_UPDATE -eq 1 ]]; then
|
||||
TMP_DL=$(mktemp)
|
||||
if download_remote_full_to "$TMP_DL"; then
|
||||
# Save raw upstream to cache
|
||||
sudo mv "$TMP_DL" "$LOCAL_CACHE"
|
||||
sudo chmod 644 "$LOCAL_CACHE"
|
||||
echo "Saved latest StevenBlack hosts to cache: $LOCAL_CACHE"
|
||||
else
|
||||
rm -f "$TMP_DL"
|
||||
echo "Error: Failed to download latest StevenBlack hosts." >&2
|
||||
exit 1
|
||||
fi
|
||||
fi
|
||||
|
||||
# Install the base hosts from cache into /etc/hosts
|
||||
echo "Installing base hosts from cache to /etc/hosts..."
|
||||
sudo cp "$LOCAL_CACHE" /etc/hosts
|
||||
|
||||
# Comment out any 4chan blocking entries from the downloaded file
|
||||
echo "Allowing 4chan by commenting out any blocking entries..."
|
||||
sudo sed -i 's/^0\.0\.0\.0 4chan\.com/#0.0.0.0 4chan.com/' /etc/hosts
|
||||
sudo sed -i 's/^0\.0\.0\.0 www\.4chan\.com/#0.0.0.0 www.4chan.com/' /etc/hosts
|
||||
sudo sed -i 's/^0\.0\.0\.0 4chan\.org/#0.0.0.0 4chan.org/' /etc/hosts
|
||||
sudo sed -i 's/^0\.0\.0\.0 boards\.4chan\.org/#0.0.0.0 boards.4chan.org/' /etc/hosts
|
||||
sudo sed -i 's/^0\.0\.0\.0 sys\.4chan\.org/#0.0.0.0 sys.4chan.org/' /etc/hosts
|
||||
sudo sed -i 's/^0\.0\.0\.0 www\.4chan\.org/#0.0.0.0 www.4chan.org/' /etc/hosts
|
||||
sudo sed -i -E 's/^(0\.0\.0\.0[[:space:]]+[a-zA-Z0-9._-]*\.?facebook\.com)/#\1/' /etc/hosts
|
||||
sudo sed -i -E 's/^(0\.0\.0\.0[[:space:]]+[a-zA-Z0-9._-]*\.?messenger\.com)/#\1/' /etc/hosts
|
||||
sudo sed -i -E 's/^(0\.0\.0\.0[[:space:]]+[a-zA-Z0-9._-]*\.?fbcdn\.net)/#\1/' /etc/hosts
|
||||
sudo sed -i -E 's/^(0\.0\.0\.0[[:space:]]+[a-zA-Z0-9._-]*\.?facebook\.net)/#\1/' /etc/hosts
|
||||
sudo sed -i 's/^0\.0\.0\.0 delio\.com.pl/#0.0.0.0 delio.com.pl/' /etc/hosts
|
||||
sudo sed -i 's/^0\.0\.0\.0 loverslab\.com/#0.0.0.0 loverslab.com/' /etc/hosts
|
||||
|
||||
# Allow LinkedIn and all subdomains (linkedin.com + licdn.com CDN)
|
||||
echo "Allowing LinkedIn by commenting out any blocking entries..."
|
||||
sudo sed -i -E 's/^(0\.0\.0\.0[[:space:]]+[a-zA-Z0-9._-]*\.?linkedin\.com)/#\1/' /etc/hosts
|
||||
sudo sed -i -E 's/^(0\.0\.0\.0[[:space:]]+[a-zA-Z0-9._-]*\.?licdn\.com)/#\1/' /etc/hosts
|
||||
sudo sed -i -E 's/^(0\.0\.0\.0[[:space:]]+[a-zA-Z0-9._-]*\.?loverslab\.com)/#\1/' /etc/hosts
|
||||
|
||||
# Add custom entries for YouTube and Discord
|
||||
echo "Adding custom entries for YouTube and Discord..."
|
||||
tee -a /etc/hosts >/dev/null <<'EOF'
|
||||
|
||||
# Custom blocking entries
|
||||
# YouTube
|
||||
0.0.0.0 youtube.com
|
||||
0.0.0.0 www.youtube.com
|
||||
0.0.0.0 m.youtube.com
|
||||
0.0.0.0 youtu.be
|
||||
0.0.0.0 youtube-nocookie.com
|
||||
0.0.0.0 www.youtube-nocookie.com
|
||||
0.0.0.0 youtubei.googleapis.com
|
||||
0.0.0.0 youtube.googleapis.com
|
||||
0.0.0.0 yt3.ggpht.com
|
||||
# Channel avatars and banners. Same role as yt3.ggpht.com, which was already
|
||||
# here -- Google serves them from both hosts, so blocking one leaves the other
|
||||
# resolving. Caught when the phone's DoT resolver was checked domain by domain
|
||||
# against the 14 the focus policy names.
|
||||
0.0.0.0 yt3.googleusercontent.com
|
||||
0.0.0.0 ytimg.com
|
||||
0.0.0.0 i.ytimg.com
|
||||
0.0.0.0 s.ytimg.com
|
||||
0.0.0.0 i9.ytimg.com
|
||||
0.0.0.0 googlevideo.com
|
||||
0.0.0.0 r1---sn-4g5e6nls.googlevideo.com
|
||||
0.0.0.0 r1---sn-4g5lne7s.googlevideo.com
|
||||
|
||||
# Alternative YouTube Frontends (Invidious, Piped, etc.)
|
||||
0.0.0.0 invidious.io
|
||||
0.0.0.0 www.invidious.io
|
||||
0.0.0.0 invidio.us
|
||||
0.0.0.0 vid.puffyan.us
|
||||
0.0.0.0 invidious.snopyta.org
|
||||
0.0.0.0 yewtu.be
|
||||
0.0.0.0 invidious.kavin.rocks
|
||||
0.0.0.0 inv.riverside.rocks
|
||||
0.0.0.0 invidious.namazso.eu
|
||||
0.0.0.0 invidious.nerdvpn.de
|
||||
0.0.0.0 invidious.projectsegfau.lt
|
||||
0.0.0.0 invidious.slipfox.xyz
|
||||
0.0.0.0 invidious.privacydev.net
|
||||
0.0.0.0 invidious.perennialte.ch
|
||||
0.0.0.0 invidious.protokoll-11.de
|
||||
0.0.0.0 invidious.einfachzocken.eu
|
||||
0.0.0.0 invidious.fdn.fr
|
||||
0.0.0.0 inv.in.projectsegfau.lt
|
||||
0.0.0.0 invidious.tiekoetter.com
|
||||
0.0.0.0 invidious.lunar.icu
|
||||
0.0.0.0 iv.ggtyler.dev
|
||||
0.0.0.0 iv.melmac.space
|
||||
0.0.0.0 piped.video
|
||||
0.0.0.0 www.piped.video
|
||||
0.0.0.0 piped.kavin.rocks
|
||||
0.0.0.0 piped.mha.fi
|
||||
0.0.0.0 piped.mint.lgbt
|
||||
0.0.0.0 piped.projectsegfau.lt
|
||||
0.0.0.0 piped.privacydev.net
|
||||
0.0.0.0 piped.smnz.de
|
||||
0.0.0.0 piped.adminforge.de
|
||||
0.0.0.0 watch.whatever.social
|
||||
0.0.0.0 piped.lunar.icu
|
||||
0.0.0.0 viewtube.io
|
||||
0.0.0.0 www.viewtube.io
|
||||
0.0.0.0 freetube.io
|
||||
0.0.0.0 www.freetube.io
|
||||
0.0.0.0 tubo.media
|
||||
0.0.0.0 www.tubo.media
|
||||
0.0.0.0 materialious.nadeko.net
|
||||
0.0.0.0 clipious.org
|
||||
0.0.0.0 www.clipious.org
|
||||
0.0.0.0 newpipe.net
|
||||
0.0.0.0 www.newpipe.net
|
||||
0.0.0.0 newpipe.schabi.org
|
||||
0.0.0.0 grayjay.app
|
||||
0.0.0.0 www.grayjay.app
|
||||
0.0.0.0 libretube.dev
|
||||
0.0.0.0 www.libretube.dev
|
||||
0.0.0.0 hyperion.deishelon.com
|
||||
0.0.0.0 inv.n8pjl.ca
|
||||
0.0.0.0 inv.zzls.xyz
|
||||
0.0.0.0 inv.tux.pizza
|
||||
0.0.0.0 invidious.incogniweb.net
|
||||
0.0.0.0 invidious.drgns.space
|
||||
0.0.0.0 invidious.io.lol
|
||||
|
||||
# Steam Store
|
||||
0.0.0.0 store.steampowered.com
|
||||
0.0.0.0 checkout.steampowered.com
|
||||
0.0.0.0 store.akamai.steamstatic.com
|
||||
0.0.0.0 storefront.steampowered.com
|
||||
0.0.0.0 store.cloudflare.steamstatic.com
|
||||
|
||||
# Discord - media allowed
|
||||
# 0.0.0.0 cdn.discordapp.com
|
||||
# 0.0.0.0 media.discordapp.net
|
||||
# 0.0.0.0 images-ext-1.discordapp.net
|
||||
# 0.0.0.0 images-ext-2.discordapp.net
|
||||
# 0.0.0.0 attachments-1.discordapp.net
|
||||
# 0.0.0.0 attachments-2.discordapp.net
|
||||
# 0.0.0.0 tenor.com
|
||||
# 0.0.0.0 giphy.com
|
||||
|
||||
# Food Delivery Services
|
||||
# Polish services
|
||||
0.0.0.0 pyszne.pl
|
||||
0.0.0.0 www.pyszne.pl
|
||||
0.0.0.0 m.pyszne.pl
|
||||
0.0.0.0 api.pyszne.pl
|
||||
0.0.0.0 app.pyszne.pl
|
||||
0.0.0.0 glovo.com
|
||||
0.0.0.0 www.glovo.com
|
||||
0.0.0.0 m.glovo.com
|
||||
0.0.0.0 api.glovo.com
|
||||
0.0.0.0 glovoapp.com
|
||||
0.0.0.0 www.glovoapp.com
|
||||
0.0.0.0 bolt.eu
|
||||
:: bolt.eu
|
||||
0.0.0.0 www.bolt.eu
|
||||
:: www.bolt.eu
|
||||
0.0.0.0 food.bolt.eu
|
||||
:: food.bolt.eu
|
||||
0.0.0.0 m.bolt.eu
|
||||
:: m.bolt.eu
|
||||
0.0.0.0 api.bolt.eu
|
||||
:: api.bolt.eu
|
||||
0.0.0.0 node.bolt.eu
|
||||
:: node.bolt.eu
|
||||
0.0.0.0 gw.bolt.eu
|
||||
:: gw.bolt.eu
|
||||
0.0.0.0 client-api.bolt.eu
|
||||
:: client-api.bolt.eu
|
||||
0.0.0.0 auth.bolt.eu
|
||||
:: auth.bolt.eu
|
||||
0.0.0.0 cdn.bolt.eu
|
||||
:: cdn.bolt.eu
|
||||
0.0.0.0 images.bolt.eu
|
||||
:: images.bolt.eu
|
||||
0.0.0.0 static.bolt.eu
|
||||
:: static.bolt.eu
|
||||
0.0.0.0 assets.bolt.eu
|
||||
:: assets.bolt.eu
|
||||
0.0.0.0 fleet.bolt.eu
|
||||
:: fleet.bolt.eu
|
||||
0.0.0.0 user.bolt.eu
|
||||
:: user.bolt.eu
|
||||
0.0.0.0 courier.bolt.eu
|
||||
:: courier.bolt.eu
|
||||
0.0.0.0 rider.bolt.eu
|
||||
:: rider.bolt.eu
|
||||
0.0.0.0 restaurant.bolt.eu
|
||||
:: restaurant.bolt.eu
|
||||
0.0.0.0 partner-food.bolt.eu
|
||||
:: partner-food.bolt.eu
|
||||
0.0.0.0 woltwojta.pl
|
||||
0.0.0.0 www.woltwojta.pl
|
||||
0.0.0.0 wolt.com
|
||||
0.0.0.0 www.wolt.com
|
||||
0.0.0.0 m.wolt.com
|
||||
0.0.0.0 api.wolt.com
|
||||
0.0.0.0 restaurant-api.wolt.com
|
||||
0.0.0.0 consumer-api.wolt.com
|
||||
0.0.0.0 jush.pl
|
||||
0.0.0.0 www.jush.pl
|
||||
0.0.0.0 m.jush.pl
|
||||
0.0.0.0 api.jush.pl
|
||||
0.0.0.0 delio.pl
|
||||
:: delio.pl
|
||||
0.0.0.0 www.delio.pl
|
||||
:: www.delio.pl
|
||||
0.0.0.0 m.delio.pl
|
||||
:: m.delio.pl
|
||||
0.0.0.0 api.delio.pl
|
||||
:: api.delio.pl
|
||||
0.0.0.0 app.delio.pl
|
||||
:: app.delio.pl
|
||||
0.0.0.0 cdn.delio.pl
|
||||
:: cdn.delio.pl
|
||||
0.0.0.0 static.delio.pl
|
||||
:: static.delio.pl
|
||||
0.0.0.0 order.delio.pl
|
||||
:: order.delio.pl
|
||||
0.0.0.0 delio.com
|
||||
:: delio.com
|
||||
0.0.0.0 www.delio.com
|
||||
:: www.delio.com
|
||||
0.0.0.0 m.delio.com
|
||||
:: m.delio.com
|
||||
0.0.0.0 api.delio.com
|
||||
:: api.delio.com
|
||||
0.0.0.0 app.delio.com
|
||||
:: app.delio.com
|
||||
0.0.0.0 delio.com.pl
|
||||
:: delio.com.pl
|
||||
0.0.0.0 www.delio.com.pl
|
||||
:: www.delio.com.pl
|
||||
0.0.0.0 m.delio.com.pl
|
||||
:: m.delio.com.pl
|
||||
0.0.0.0 api.delio.com.pl
|
||||
:: api.delio.com.pl
|
||||
0.0.0.0 app.delio.com.pl
|
||||
:: app.delio.com.pl
|
||||
0.0.0.0 lisek.app
|
||||
0.0.0.0 www.lisek.app
|
||||
0.0.0.0 api.lisek.app
|
||||
0.0.0.0 stava.app
|
||||
0.0.0.0 www.stava.app
|
||||
0.0.0.0 api.stava.app
|
||||
0.0.0.0 biedronka.pl
|
||||
0.0.0.0 zakupy.biedronka.pl
|
||||
0.0.0.0 ezakupy.tesco.pl
|
||||
0.0.0.0 www.ezakupy.tesco.pl
|
||||
0.0.0.0 barbora.pl
|
||||
0.0.0.0 www.barbora.pl
|
||||
0.0.0.0 api.barbora.pl
|
||||
0.0.0.0 frisco.pl
|
||||
0.0.0.0 www.frisco.pl
|
||||
0.0.0.0 api.frisco.pl
|
||||
0.0.0.0 swiatkwiatow.pl
|
||||
0.0.0.0 www.swiatkwiatow.pl
|
||||
0.0.0.0 allegro.pl/kategoria/jedzenie
|
||||
0.0.0.0 szama.pl
|
||||
0.0.0.0 www.szama.pl
|
||||
0.0.0.0 api.szama.pl
|
||||
0.0.0.0 auchandirect.pl
|
||||
0.0.0.0 www.auchandirect.pl
|
||||
|
||||
# International services
|
||||
0.0.0.0 ubereats.com
|
||||
0.0.0.0 www.ubereats.com
|
||||
0.0.0.0 m.ubereats.com
|
||||
0.0.0.0 api.ubereats.com
|
||||
0.0.0.0 uber.com
|
||||
0.0.0.0 www.uber.com
|
||||
0.0.0.0 m.uber.com
|
||||
0.0.0.0 api.uber.com
|
||||
0.0.0.0 cn-geo1.uber.com
|
||||
0.0.0.0 login.uber.com
|
||||
0.0.0.0 auth.uber.com
|
||||
0.0.0.0 riders.uber.com
|
||||
0.0.0.0 deliveroo.com
|
||||
0.0.0.0 www.deliveroo.com
|
||||
0.0.0.0 m.deliveroo.com
|
||||
0.0.0.0 api.deliveroo.com
|
||||
0.0.0.0 deliveroo.co.uk
|
||||
0.0.0.0 www.deliveroo.co.uk
|
||||
0.0.0.0 foodpanda.com
|
||||
0.0.0.0 www.foodpanda.com
|
||||
0.0.0.0 m.foodpanda.com
|
||||
0.0.0.0 api.foodpanda.com
|
||||
0.0.0.0 grubhub.com
|
||||
0.0.0.0 www.grubhub.com
|
||||
0.0.0.0 m.grubhub.com
|
||||
0.0.0.0 api.grubhub.com
|
||||
0.0.0.0 doordash.com
|
||||
0.0.0.0 www.doordash.com
|
||||
0.0.0.0 m.doordash.com
|
||||
0.0.0.0 api.doordash.com
|
||||
0.0.0.0 justeat.com
|
||||
0.0.0.0 www.justeat.com
|
||||
0.0.0.0 m.justeat.com
|
||||
0.0.0.0 justeat.co.uk
|
||||
0.0.0.0 www.justeat.co.uk
|
||||
0.0.0.0 postmates.com
|
||||
0.0.0.0 www.postmates.com
|
||||
0.0.0.0 api.postmates.com
|
||||
0.0.0.0 seamless.com
|
||||
0.0.0.0 www.seamless.com
|
||||
0.0.0.0 menulog.com.au
|
||||
0.0.0.0 www.menulog.com.au
|
||||
0.0.0.0 delivery.com
|
||||
0.0.0.0 www.delivery.com
|
||||
0.0.0.0 getir.com
|
||||
0.0.0.0 www.getir.com
|
||||
0.0.0.0 api.getir.com
|
||||
0.0.0.0 flink.com
|
||||
0.0.0.0 www.flink.com
|
||||
0.0.0.0 api.flink.com
|
||||
0.0.0.0 gorillas.io
|
||||
0.0.0.0 www.gorillas.io
|
||||
0.0.0.0 api.gorillas.io
|
||||
0.0.0.0 gopuff.com
|
||||
0.0.0.0 www.gopuff.com
|
||||
0.0.0.0 api.gopuff.com
|
||||
0.0.0.0 instacart.com
|
||||
0.0.0.0 www.instacart.com
|
||||
0.0.0.0 api.instacart.com
|
||||
0.0.0.0 takeaway.com
|
||||
0.0.0.0 www.takeaway.com
|
||||
0.0.0.0 api.takeaway.com
|
||||
|
||||
# Fast food chain apps and websites
|
||||
0.0.0.0 mcdonalds.com
|
||||
0.0.0.0 www.mcdonalds.com
|
||||
0.0.0.0 m.mcdonalds.com
|
||||
0.0.0.0 mcdonalds.pl
|
||||
0.0.0.0 www.mcdonalds.pl
|
||||
0.0.0.0 kfc.com
|
||||
0.0.0.0 www.kfc.com
|
||||
0.0.0.0 m.kfc.com
|
||||
0.0.0.0 kfc.pl
|
||||
0.0.0.0 www.kfc.pl
|
||||
0.0.0.0 burgerking.com
|
||||
0.0.0.0 www.burgerking.com
|
||||
0.0.0.0 m.burgerking.com
|
||||
0.0.0.0 burgerking.pl
|
||||
0.0.0.0 www.burgerking.pl
|
||||
0.0.0.0 pizzahut.com
|
||||
0.0.0.0 www.pizzahut.com
|
||||
0.0.0.0 m.pizzahut.com
|
||||
0.0.0.0 pizzahut.pl
|
||||
0.0.0.0 www.pizzahut.pl
|
||||
0.0.0.0 dominos.com
|
||||
0.0.0.0 www.dominos.com
|
||||
0.0.0.0 m.dominos.com
|
||||
0.0.0.0 dominos.pl
|
||||
0.0.0.0 www.dominos.pl
|
||||
0.0.0.0 subway.com
|
||||
0.0.0.0 www.subway.com
|
||||
0.0.0.0 m.subway.com
|
||||
0.0.0.0 subway.pl
|
||||
0.0.0.0 www.subway.pl
|
||||
EOF
|
||||
|
||||
# Set proper permissions (readable by all, writable only by root)
|
||||
sudo chmod 644 /etc/hosts
|
||||
|
||||
# Make the file immutable and append-only for maximum protection
|
||||
sudo chattr +ia /etc/hosts
|
||||
|
||||
# ============================================================================
|
||||
# RESTART HOSTS GUARD SERVICES
|
||||
# ============================================================================
|
||||
if [[ $GUARD_SERVICES_STOPPED -eq 1 ]]; then
|
||||
echo "Restarting hosts guard services..."
|
||||
# Update the canonical copy so the guard doesn't revert our changes
|
||||
if [[ -f /usr/local/share/locked-hosts ]]; then
|
||||
cp /etc/hosts /usr/local/share/locked-hosts
|
||||
echo " Updated canonical snapshot."
|
||||
fi
|
||||
for svc in hosts-bind-mount.service hosts-guard.path; do
|
||||
if systemctl is-enabled --quiet "$svc" 2>/dev/null; then
|
||||
systemctl start "$svc" 2>/dev/null || true
|
||||
echo " Restarted $svc"
|
||||
fi
|
||||
done
|
||||
fi
|
||||
|
||||
# ============================================================================
|
||||
# SAVE CUSTOM ENTRIES STATE FOR FUTURE PROTECTION CHECKS
|
||||
# ============================================================================
|
||||
echo "Saving custom entries state for protection mechanism..."
|
||||
script_path="$(readlink -f "$0")"
|
||||
current_custom_entries=$(extract_custom_entries_from_script "$script_path")
|
||||
# Remove immutable from state file if it exists
|
||||
chattr -i "$CUSTOM_ENTRIES_STATE_FILE" 2>/dev/null || true
|
||||
save_custom_entries_state "$current_custom_entries"
|
||||
echo "✅ Custom entries state saved to $CUSTOM_ENTRIES_STATE_FILE"
|
||||
|
||||
# Save unblock entries state for future protection checks
|
||||
current_unblock_entries=$(extract_unblock_entries_from_script "$script_path")
|
||||
save_unblock_entries_state "$current_unblock_entries"
|
||||
echo "✅ Unblock entries state saved to $UNBLOCK_STATE_FILE"
|
||||
|
||||
# Optionally flush DNS caches
|
||||
if [[ $FLUSH_DNS -eq 1 ]]; then
|
||||
echo "Flushing DNS caches..."
|
||||
sudo systemd-resolve --flush-caches
|
||||
sudo systemctl restart NetworkManager.service
|
||||
else
|
||||
echo "DNS cache flush skipped (use --flush-dns to enable)."
|
||||
fi
|
||||
|
||||
# ============================================================================
|
||||
# DISABLE DNS OVER HTTPS (DoH) IN BROWSERS
|
||||
# ============================================================================
|
||||
# DoH bypasses /etc/hosts entirely, defeating all our blocking!
|
||||
# We disable it in Firefox profiles for all users.
|
||||
echo ""
|
||||
echo "Disabling DNS over HTTPS (DoH) in browsers..."
|
||||
|
||||
# Get the actual user (not root) who invoked this script
|
||||
REAL_USER="${SUDO_USER:-$USER}"
|
||||
REAL_HOME=$(getent passwd "$REAL_USER" | cut -d: -f6)
|
||||
|
||||
# Firefox: disable DoH via user.js
|
||||
if [[ -d "$REAL_HOME/.mozilla/firefox" ]]; then
|
||||
for profile in "$REAL_HOME/.mozilla/firefox"/*.default*; do
|
||||
if [[ -d "$profile" ]]; then
|
||||
cat >>"$profile/user.js" <<'FIREFOXEOF'
|
||||
// Disable DNS over HTTPS (DoH) to ensure /etc/hosts blocking works
|
||||
// Added by linux-configuration hosts installer
|
||||
user_pref("network.trr.mode", 5); // 5 = Off by user choice
|
||||
user_pref("doh-rollout.enabled", false);
|
||||
user_pref("doh-rollout.disable-heuristics", true);
|
||||
FIREFOXEOF
|
||||
chown "$REAL_USER:$REAL_USER" "$profile/user.js"
|
||||
echo " Firefox DoH disabled in: $(basename "$profile")"
|
||||
fi
|
||||
done
|
||||
else
|
||||
echo " No Firefox profiles found"
|
||||
fi
|
||||
|
||||
# Chromium-based browsers: use policy file
|
||||
CHROME_POLICY_DIR="/etc/chromium/policies/managed"
|
||||
if [[ -d "/etc/chromium" ]] || command -v chromium &>/dev/null; then
|
||||
mkdir -p "$CHROME_POLICY_DIR"
|
||||
cat >"$CHROME_POLICY_DIR/disable-doh.json" <<'CHROMEEOF'
|
||||
{
|
||||
"DnsOverHttpsMode": "off",
|
||||
"BuiltInDnsClientEnabled": false
|
||||
}
|
||||
CHROMEEOF
|
||||
echo " Chromium DoH disabled via policy"
|
||||
fi
|
||||
|
||||
# Google Chrome policy
|
||||
GCHROME_POLICY_DIR="/etc/opt/chrome/policies/managed"
|
||||
if [[ -d "/etc/opt/chrome" ]] || command -v google-chrome &>/dev/null; then
|
||||
mkdir -p "$GCHROME_POLICY_DIR"
|
||||
cat >"$GCHROME_POLICY_DIR/disable-doh.json" <<'GCHROMEEOF'
|
||||
{
|
||||
"DnsOverHttpsMode": "off",
|
||||
"BuiltInDnsClientEnabled": false
|
||||
}
|
||||
GCHROMEEOF
|
||||
echo " Google Chrome DoH disabled via policy"
|
||||
fi
|
||||
|
||||
echo ""
|
||||
echo "✅ Installation complete!"
|
||||
echo " Custom entries protection is now active."
|
||||
echo " Removing blocked entries from the script will be blocked."
|
||||
echo " DNS over HTTPS (DoH) has been disabled in browsers."
|
||||
|
||||
# ============================================================================
|
||||
# FORCE BROWSER RESTART TO APPLY DOH CHANGES
|
||||
# ============================================================================
|
||||
# Kill all browser processes so DoH changes take effect immediately
|
||||
echo ""
|
||||
echo "Killing browsers to apply DoH policy changes..."
|
||||
BROWSERS_KILLED=0
|
||||
|
||||
for browser in chrome chromium chromium-browser brave brave-browser firefox firefox-esr thorium vivaldi opera; do
|
||||
if pgrep -x "$browser" &>/dev/null || pgrep -f "/opt/.*/$browser" &>/dev/null; then
|
||||
echo " Killing $browser..."
|
||||
pkill -9 -f "$browser" 2>/dev/null || true
|
||||
BROWSERS_KILLED=1
|
||||
fi
|
||||
done
|
||||
|
||||
# Also kill by common binary paths
|
||||
for pattern in "/opt/google/chrome" "/opt/brave" "/opt/thorium" "/usr/lib/firefox" "/usr/lib/chromium"; do
|
||||
if pgrep -f "$pattern" &>/dev/null; then
|
||||
echo " Killing processes matching $pattern..."
|
||||
pkill -9 -f "$pattern" 2>/dev/null || true
|
||||
BROWSERS_KILLED=1
|
||||
fi
|
||||
done
|
||||
|
||||
if [[ $BROWSERS_KILLED -eq 1 ]]; then
|
||||
echo ""
|
||||
echo "⚠️ Browsers were killed to apply DNS settings."
|
||||
echo " Reopen your browser - hosts blocking is now enforced."
|
||||
else
|
||||
echo " No browsers were running."
|
||||
fi
|
||||
|
||||
# ============================================================================
|
||||
# NOTE: this used to `chattr +i` its own source and generate_hosts_file.sh
|
||||
# ("lock against silent edits"). Do NOT reintroduce that: making a git-tracked
|
||||
# file immutable breaks git tooling. `pre-commit run --all-files` (which the
|
||||
@ -911,3 +112,19 @@ fi
|
||||
# changes nothing until install.sh is re-run as root, which regenerates the
|
||||
# guarded artifacts.
|
||||
# ============================================================================
|
||||
|
||||
# ============================================================================
|
||||
# MAIN
|
||||
# ============================================================================
|
||||
# The phases above are defined in the order they run, and run here in that same
|
||||
# order. Split out of a single top-level block so the file fits the 250-line
|
||||
# cap; the sequence is unchanged, including the guard being taken down before
|
||||
# the write and restarted immediately after it.
|
||||
enable_resolved_reads_hosts
|
||||
stop_hosts_guard
|
||||
refresh_upstream_cache
|
||||
write_hosts_file
|
||||
restart_hosts_guard
|
||||
save_protection_state
|
||||
disable_browser_doh
|
||||
restart_browsers
|
||||
|
||||
112
linux_configuration/scripts/periodic_background/hosts/lib/hosts_browser_doh.sh
Executable file
112
linux_configuration/scripts/periodic_background/hosts/lib/hosts_browser_doh.sh
Executable file
@ -0,0 +1,112 @@
|
||||
#!/usr/bin/env bash
|
||||
# lib/hosts_browser_doh.sh — stop browsers resolving around /etc/hosts.
|
||||
#
|
||||
# DNS-over-HTTPS resolves names over the browser's own encrypted channel and
|
||||
# never consults /etc/hosts, so leaving it on defeats every entry this script
|
||||
# installs. Sourced by install.sh.
|
||||
|
||||
# Turn off DNS-over-HTTPS in every installed browser. DoH resolves names
|
||||
# over the browser's own encrypted channel, bypassing /etc/hosts completely.
|
||||
disable_browser_doh() {
|
||||
# DISABLE DNS OVER HTTPS (DoH) IN BROWSERS
|
||||
# ============================================================================
|
||||
# DoH bypasses /etc/hosts entirely, defeating all our blocking!
|
||||
# We disable it in Firefox profiles for all users.
|
||||
echo ""
|
||||
echo "Disabling DNS over HTTPS (DoH) in browsers..."
|
||||
|
||||
# Get the actual user (not root) who invoked this script
|
||||
REAL_USER="${SUDO_USER:-$USER}"
|
||||
REAL_HOME=$(getent passwd "$REAL_USER" | cut -d: -f6)
|
||||
|
||||
# Firefox: disable DoH via user.js
|
||||
if [[ -d "$REAL_HOME/.mozilla/firefox" ]]; then
|
||||
for profile in "$REAL_HOME/.mozilla/firefox"/*.default*; do
|
||||
if [[ -d "$profile" ]]; then
|
||||
cat >>"$profile/user.js" <<'FIREFOXEOF'
|
||||
// Disable DNS over HTTPS (DoH) to ensure /etc/hosts blocking works
|
||||
// Added by linux-configuration hosts installer
|
||||
user_pref("network.trr.mode", 5); // 5 = Off by user choice
|
||||
user_pref("doh-rollout.enabled", false);
|
||||
user_pref("doh-rollout.disable-heuristics", true);
|
||||
FIREFOXEOF
|
||||
chown "$REAL_USER:$REAL_USER" "$profile/user.js"
|
||||
echo " Firefox DoH disabled in: $(basename "$profile")"
|
||||
fi
|
||||
done
|
||||
else
|
||||
echo " No Firefox profiles found"
|
||||
fi
|
||||
|
||||
# Chromium-based browsers: use policy file
|
||||
CHROME_POLICY_DIR="/etc/chromium/policies/managed"
|
||||
if [[ -d "/etc/chromium" ]] || command -v chromium &>/dev/null; then
|
||||
mkdir -p "$CHROME_POLICY_DIR"
|
||||
cat >"$CHROME_POLICY_DIR/disable-doh.json" <<'CHROMEEOF'
|
||||
{
|
||||
"DnsOverHttpsMode": "off",
|
||||
"BuiltInDnsClientEnabled": false
|
||||
}
|
||||
CHROMEEOF
|
||||
echo " Chromium DoH disabled via policy"
|
||||
fi
|
||||
|
||||
# Google Chrome policy
|
||||
GCHROME_POLICY_DIR="/etc/opt/chrome/policies/managed"
|
||||
if [[ -d "/etc/opt/chrome" ]] || command -v google-chrome &>/dev/null; then
|
||||
mkdir -p "$GCHROME_POLICY_DIR"
|
||||
cat >"$GCHROME_POLICY_DIR/disable-doh.json" <<'GCHROMEEOF'
|
||||
{
|
||||
"DnsOverHttpsMode": "off",
|
||||
"BuiltInDnsClientEnabled": false
|
||||
}
|
||||
GCHROMEEOF
|
||||
echo " Google Chrome DoH disabled via policy"
|
||||
fi
|
||||
|
||||
echo ""
|
||||
echo "✅ Installation complete!"
|
||||
echo " Custom entries protection is now active."
|
||||
echo " Removing blocked entries from the script will be blocked."
|
||||
echo " DNS over HTTPS (DoH) has been disabled in browsers."
|
||||
|
||||
# ============================================================================
|
||||
}
|
||||
|
||||
# Kill running browsers so the DoH policy changes take effect now rather
|
||||
# than at the user's next restart.
|
||||
restart_browsers() {
|
||||
# FORCE BROWSER RESTART TO APPLY DOH CHANGES
|
||||
# ============================================================================
|
||||
# Kill all browser processes so DoH changes take effect immediately
|
||||
echo ""
|
||||
echo "Killing browsers to apply DoH policy changes..."
|
||||
BROWSERS_KILLED=0
|
||||
|
||||
for browser in chrome chromium chromium-browser brave brave-browser firefox firefox-esr thorium vivaldi opera; do
|
||||
if pgrep -x "$browser" &>/dev/null || pgrep -f "/opt/.*/$browser" &>/dev/null; then
|
||||
echo " Killing $browser..."
|
||||
pkill -9 -f "$browser" 2>/dev/null || true
|
||||
BROWSERS_KILLED=1
|
||||
fi
|
||||
done
|
||||
|
||||
# Also kill by common binary paths
|
||||
for pattern in "/opt/google/chrome" "/opt/brave" "/opt/thorium" "/usr/lib/firefox" "/usr/lib/chromium"; do
|
||||
if pgrep -f "$pattern" &>/dev/null; then
|
||||
echo " Killing processes matching $pattern..."
|
||||
pkill -9 -f "$pattern" 2>/dev/null || true
|
||||
BROWSERS_KILLED=1
|
||||
fi
|
||||
done
|
||||
|
||||
if [[ $BROWSERS_KILLED -eq 1 ]]; then
|
||||
echo ""
|
||||
echo "⚠️ Browsers were killed to apply DNS settings."
|
||||
echo " Reopen your browser - hosts blocking is now enforced."
|
||||
else
|
||||
echo " No browsers were running."
|
||||
fi
|
||||
|
||||
# ============================================================================
|
||||
}
|
||||
91
linux_configuration/scripts/periodic_background/hosts/lib/hosts_cache.sh
Executable file
91
linux_configuration/scripts/periodic_background/hosts/lib/hosts_cache.sh
Executable file
@ -0,0 +1,91 @@
|
||||
#!/usr/bin/env bash
|
||||
# lib/hosts_cache.sh — keep the local copy of the upstream StevenBlack list
|
||||
# current.
|
||||
#
|
||||
# The cache holds the RAW upstream file, without our own entries, so a refresh
|
||||
# never has to re-derive what we added. Sourced by install.sh.
|
||||
|
||||
# Helpers
|
||||
extract_date_epoch_from_file() {
|
||||
# Grep "# Date:" line and convert to epoch seconds (UTC)
|
||||
local f="$1"
|
||||
local line
|
||||
line=$(grep -m1 '^# Date:' "$f" 2>/dev/null | sed -E 's/^# Date:[[:space:]]*(.*)[[:space:]]*\(UTC\).*/\1 UTC/')
|
||||
if [[ -n $line ]]; then
|
||||
date -u -d "$line" +%s 2>/dev/null || echo ""
|
||||
else
|
||||
echo ""
|
||||
fi
|
||||
}
|
||||
|
||||
fetch_remote_header() {
|
||||
# Try to fetch only the first ~4KB using HTTP Range; fallback to piping to head
|
||||
local out="$1"
|
||||
if curl -LfsS --max-time 10 -H 'Range: bytes=0-4095' "$URL" -o "$out"; then
|
||||
return 0
|
||||
fi
|
||||
# Fallback – may download more, but we only keep first lines
|
||||
if curl -LfsS --max-time 10 "$URL" | head -n 20 >"$out"; then
|
||||
return 0
|
||||
fi
|
||||
return 1
|
||||
}
|
||||
|
||||
download_remote_full_to() {
|
||||
local out="$1"
|
||||
curl -LfsS "$URL" -o "$out"
|
||||
}
|
||||
|
||||
# Decide whether the cached upstream blocklist is current, and re-download
|
||||
# it if not. The cache holds the RAW upstream file, without our additions.
|
||||
refresh_upstream_cache() {
|
||||
# Decide whether to use cache or update
|
||||
TMP_REMOTE_HEAD=$(mktemp)
|
||||
trap 'rm -f "$TMP_REMOTE_HEAD"' EXIT
|
||||
|
||||
REMOTE_AVAILABLE=0
|
||||
if fetch_remote_header "$TMP_REMOTE_HEAD"; then
|
||||
REMOTE_AVAILABLE=1
|
||||
fi
|
||||
|
||||
NEED_UPDATE=0
|
||||
|
||||
if [[ -f $LOCAL_CACHE ]]; then
|
||||
local_epoch=$(extract_date_epoch_from_file "$LOCAL_CACHE")
|
||||
else
|
||||
local_epoch=""
|
||||
fi
|
||||
|
||||
if [[ $REMOTE_AVAILABLE -eq 1 ]]; then
|
||||
remote_epoch=$(extract_date_epoch_from_file "$TMP_REMOTE_HEAD")
|
||||
if [[ -n $local_epoch && -n $remote_epoch && $local_epoch -ge $remote_epoch ]]; then
|
||||
echo "Using cached StevenBlack hosts (up-to-date)."
|
||||
else
|
||||
echo "Cached version is missing or outdated; downloading latest StevenBlack hosts..."
|
||||
NEED_UPDATE=1
|
||||
fi
|
||||
else
|
||||
if [[ -f $LOCAL_CACHE ]]; then
|
||||
echo "No internet; using cached StevenBlack hosts."
|
||||
else
|
||||
echo "Error: No internet and no cached StevenBlack hosts found." >&2
|
||||
exit 1
|
||||
fi
|
||||
fi
|
||||
|
||||
# Ensure we have a fresh cache if needed
|
||||
if [[ $NEED_UPDATE -eq 1 ]]; then
|
||||
TMP_DL=$(mktemp)
|
||||
if download_remote_full_to "$TMP_DL"; then
|
||||
# Save raw upstream to cache
|
||||
sudo mv "$TMP_DL" "$LOCAL_CACHE"
|
||||
sudo chmod 644 "$LOCAL_CACHE"
|
||||
echo "Saved latest StevenBlack hosts to cache: $LOCAL_CACHE"
|
||||
else
|
||||
rm -f "$TMP_DL"
|
||||
echo "Error: Failed to download latest StevenBlack hosts." >&2
|
||||
exit 1
|
||||
fi
|
||||
fi
|
||||
|
||||
}
|
||||
125
linux_configuration/scripts/periodic_background/hosts/lib/hosts_guard.sh
Executable file
125
linux_configuration/scripts/periodic_background/hosts/lib/hosts_guard.sh
Executable file
@ -0,0 +1,125 @@
|
||||
#!/usr/bin/env bash
|
||||
# lib/hosts_guard.sh — the guard lifecycle around the write.
|
||||
#
|
||||
# stop_hosts_guard takes down the path watcher, the bind mount and the
|
||||
# immutable attribute so /etc/hosts can be written; restart_hosts_guard puts
|
||||
# them back; save_protection_state records the baseline the next run compares
|
||||
# against. Sourced by install.sh.
|
||||
|
||||
# Enable systemd-resolved and make it read /etc/hosts. Without
|
||||
# ReadEtcHosts=yes it ignores the file entirely and every blocked domain
|
||||
# resolves normally, which defeats the whole install.
|
||||
enable_resolved_reads_hosts() {
|
||||
# Enable systemd-resolved
|
||||
sudo systemctl enable systemd-resolved
|
||||
|
||||
# ============================================================================
|
||||
# ENSURE systemd-resolved READS /etc/hosts
|
||||
# ============================================================================
|
||||
# Without this, systemd-resolved ignores /etc/hosts entries entirely,
|
||||
# allowing blocked domains to resolve via DNS.
|
||||
RESOLVED_CONF="/etc/systemd/resolved.conf"
|
||||
if grep -q '^ReadEtcHosts=no' "$RESOLVED_CONF" 2>/dev/null; then
|
||||
echo "Fixing systemd-resolved: setting ReadEtcHosts=yes..."
|
||||
sudo sed -i 's/^ReadEtcHosts=no/ReadEtcHosts=yes/' "$RESOLVED_CONF"
|
||||
sudo systemctl restart systemd-resolved
|
||||
elif ! grep -q '^ReadEtcHosts=yes' "$RESOLVED_CONF" 2>/dev/null; then
|
||||
echo "Enabling ReadEtcHosts=yes in systemd-resolved..."
|
||||
if grep -q '^#ReadEtcHosts=' "$RESOLVED_CONF" 2>/dev/null; then
|
||||
sudo sed -i 's/^#ReadEtcHosts=.*/ReadEtcHosts=yes/' "$RESOLVED_CONF"
|
||||
else
|
||||
echo 'ReadEtcHosts=yes' | sudo tee -a "$RESOLVED_CONF" >/dev/null
|
||||
fi
|
||||
sudo systemctl restart systemd-resolved
|
||||
fi
|
||||
|
||||
}
|
||||
|
||||
# Take down the guard so /etc/hosts can be written: stop the path watcher,
|
||||
# unmount the read-only bind mount, and clear the immutable/append-only
|
||||
# attributes. restart_hosts_guard puts all three back.
|
||||
stop_hosts_guard() {
|
||||
# ============================================================================
|
||||
# TEMPORARILY DISABLE HOSTS GUARD PROTECTIONS FOR INSTALLATION
|
||||
# ============================================================================
|
||||
# The guard system uses a read-only bind mount and path watcher that prevent
|
||||
# any writes to /etc/hosts. We must stop them before installing, then restart.
|
||||
GUARD_SERVICES_STOPPED=0
|
||||
|
||||
for svc in hosts-bind-mount.service hosts-guard.path; do
|
||||
if systemctl is-active --quiet "$svc" 2>/dev/null; then
|
||||
echo "Stopping $svc for installation..."
|
||||
systemctl stop "$svc" 2>/dev/null || true
|
||||
GUARD_SERVICES_STOPPED=1
|
||||
fi
|
||||
done
|
||||
|
||||
# If bind mount is still active, unmount it
|
||||
if findmnt /etc/hosts >/dev/null 2>&1; then
|
||||
echo "Unmounting read-only bind mount on /etc/hosts..."
|
||||
umount /etc/hosts 2>/dev/null || mount -o remount,rw,bind /etc/hosts 2>/dev/null || true
|
||||
fi
|
||||
|
||||
# Remove all attributes from /etc/hosts to allow modifications
|
||||
sudo chattr -i -a /etc/hosts 2>/dev/null || true
|
||||
|
||||
}
|
||||
|
||||
# Bring the guard back up after the write: restart the services stopped by
|
||||
# stop_hosts_guard so /etc/hosts is protected again.
|
||||
restart_hosts_guard() {
|
||||
|
||||
# ============================================================================
|
||||
# RESTART HOSTS GUARD SERVICES
|
||||
# ============================================================================
|
||||
if [[ $GUARD_SERVICES_STOPPED -eq 1 ]]; then
|
||||
echo "Restarting hosts guard services..."
|
||||
# Update the canonical copy so the guard doesn't revert our changes
|
||||
if [[ -f /usr/local/share/locked-hosts ]]; then
|
||||
cp /etc/hosts /usr/local/share/locked-hosts
|
||||
echo " Updated canonical snapshot."
|
||||
fi
|
||||
for svc in hosts-bind-mount.service hosts-guard.path; do
|
||||
if systemctl is-enabled --quiet "$svc" 2>/dev/null; then
|
||||
systemctl start "$svc" 2>/dev/null || true
|
||||
echo " Restarted $svc"
|
||||
fi
|
||||
done
|
||||
fi
|
||||
|
||||
# ============================================================================
|
||||
}
|
||||
|
||||
# Record the custom and unblock entry lists that were just installed, so the
|
||||
# next run's protection checks have a baseline to compare against.
|
||||
save_protection_state() {
|
||||
# SAVE CUSTOM ENTRIES STATE FOR FUTURE PROTECTION CHECKS
|
||||
# ============================================================================
|
||||
echo "Saving custom entries state for protection mechanism..."
|
||||
# The install script whose entry lists are being checked. Defaults to the
|
||||
# running script, which is what production always wants; a test points it
|
||||
# at a fixture instead, since these guards are the part of this file where
|
||||
# a silent regression matters most.
|
||||
script_path="$(readlink -f "${HOSTS_INSTALL_SCRIPT_PATH:-$0}")"
|
||||
current_custom_entries=$(extract_custom_entries_from_script "$script_path")
|
||||
# Remove immutable from state file if it exists
|
||||
chattr -i "$CUSTOM_ENTRIES_STATE_FILE" 2>/dev/null || true
|
||||
save_custom_entries_state "$current_custom_entries"
|
||||
echo "✅ Custom entries state saved to $CUSTOM_ENTRIES_STATE_FILE"
|
||||
|
||||
# Save unblock entries state for future protection checks
|
||||
current_unblock_entries=$(extract_unblock_entries_from_script "$script_path")
|
||||
save_unblock_entries_state "$current_unblock_entries"
|
||||
echo "✅ Unblock entries state saved to $UNBLOCK_STATE_FILE"
|
||||
|
||||
# Optionally flush DNS caches
|
||||
if [[ $FLUSH_DNS -eq 1 ]]; then
|
||||
echo "Flushing DNS caches..."
|
||||
sudo systemd-resolve --flush-caches
|
||||
sudo systemctl restart NetworkManager.service
|
||||
else
|
||||
echo "DNS cache flush skipped (use --flush-dns to enable)."
|
||||
fi
|
||||
|
||||
# ============================================================================
|
||||
}
|
||||
@ -0,0 +1,146 @@
|
||||
#!/usr/bin/env bash
|
||||
# lib/hosts_protect_custom.sh — the anti-tamper guard on the CUSTOM blocking
|
||||
# entries.
|
||||
#
|
||||
# Refuses the install when the custom block list has shrunk against the state
|
||||
# file saved by the previous run, so entries cannot be quietly dropped by
|
||||
# editing this repo. Sourced by install.sh.
|
||||
|
||||
# Extract custom blocked entries from a hosts file or heredoc section
|
||||
# Returns only the "0.0.0.0 domain.com" lines (normalized, sorted, unique)
|
||||
# The custom blocking entries used to live in a heredoc inside install.sh, and
|
||||
# this read them by slicing between "# Custom blocking entries" and the heredoc
|
||||
# terminator. They are now a data file beside it, so the whole file is the list
|
||||
# and no slicing is needed.
|
||||
#
|
||||
# The argument is still the script path, because that is what every caller has
|
||||
# and the data file sits at a known place relative to it. Passing a path with no
|
||||
# data file beside it yields an empty list, which check_custom_entries_protection
|
||||
# treats as "everything was removed" and refuses -- the safe direction.
|
||||
extract_custom_entries_from_script() {
|
||||
local script_path="$1"
|
||||
local entries_file
|
||||
entries_file="$(dirname "$script_path")/custom_entries.hosts"
|
||||
[[ -f $entries_file ]] || return 0
|
||||
grep -E '^0\.0\.0\.0[[:space:]]+' "$entries_file" |
|
||||
awk '{print $2}' |
|
||||
sort -u
|
||||
}
|
||||
|
||||
# Extract custom entries from the current /etc/hosts (entries after "# Custom blocking entries" marker)
|
||||
extract_custom_entries_from_hosts() {
|
||||
local hosts_file="$1"
|
||||
if [[ ! -f $hosts_file ]]; then
|
||||
return
|
||||
fi
|
||||
sed -n '/^# Custom blocking entries$/,$p' "$hosts_file" |
|
||||
grep -E '^0\.0\.0\.0[[:space:]]+' |
|
||||
awk '{print $2}' |
|
||||
sort -u
|
||||
}
|
||||
|
||||
# Load previously saved custom entries state
|
||||
load_saved_custom_entries() {
|
||||
if [[ -f $CUSTOM_ENTRIES_STATE_FILE ]]; then
|
||||
sort -u "$CUSTOM_ENTRIES_STATE_FILE"
|
||||
fi
|
||||
}
|
||||
|
||||
# Save current custom entries to state file
|
||||
save_custom_entries_state() {
|
||||
local entries="$1"
|
||||
echo "$entries" | sort -u >"$CUSTOM_ENTRIES_STATE_FILE"
|
||||
chmod 644 "$CUSTOM_ENTRIES_STATE_FILE"
|
||||
chattr +i "$CUSTOM_ENTRIES_STATE_FILE" 2>/dev/null || true
|
||||
}
|
||||
|
||||
# Helper function to count non-empty lines
|
||||
count_lines() {
|
||||
local input="$1"
|
||||
if [[ -z $input ]]; then
|
||||
echo 0
|
||||
else
|
||||
echo "$input" | grep -c . 2>/dev/null || echo 0
|
||||
fi
|
||||
}
|
||||
|
||||
# Main protection check
|
||||
check_custom_entries_protection() {
|
||||
local script_path
|
||||
# The install script whose entry lists are being checked. Defaults to the
|
||||
# running script, which is what production always wants; a test points it
|
||||
# at a fixture instead, since these guards are the part of this file where
|
||||
# a silent regression matters most.
|
||||
script_path="$(readlink -f "${HOSTS_INSTALL_SCRIPT_PATH:-$0}")"
|
||||
|
||||
# Get new entries from the script's heredoc
|
||||
local new_entries
|
||||
new_entries=$(extract_custom_entries_from_script "$script_path")
|
||||
local new_count
|
||||
new_count=$(count_lines "$new_entries")
|
||||
|
||||
# Get saved/existing entries (prefer state file, fall back to current /etc/hosts)
|
||||
local saved_entries
|
||||
saved_entries=$(load_saved_custom_entries)
|
||||
if [[ -z $saved_entries ]]; then
|
||||
# First run or state file missing - extract from current /etc/hosts if it has our marker
|
||||
# The live hosts file, overridable so a test can supply a fixture; this
|
||||
# is a read, never a write.
|
||||
saved_entries=$(extract_custom_entries_from_hosts "${HOSTS_FILE_PATH:-/etc/hosts}")
|
||||
fi
|
||||
local saved_count
|
||||
saved_count=$(count_lines "$saved_entries")
|
||||
|
||||
# If no saved state exists, this is first installation - allow it
|
||||
if [[ $saved_count -eq 0 ]]; then
|
||||
echo "ℹ️ First installation detected - no protection check needed."
|
||||
return 0
|
||||
fi
|
||||
|
||||
# Find entries that were removed
|
||||
local removed_entries
|
||||
removed_entries=$(comm -23 <(echo "$saved_entries") <(echo "$new_entries"))
|
||||
local removed_count
|
||||
removed_count=$(count_lines "$removed_entries")
|
||||
|
||||
# Find entries that are new
|
||||
local added_entries
|
||||
added_entries=$(comm -13 <(echo "$saved_entries") <(echo "$new_entries"))
|
||||
local added_count
|
||||
added_count=$(count_lines "$added_entries")
|
||||
|
||||
echo ""
|
||||
echo "📊 Custom Entries Protection Check:"
|
||||
echo " Previously blocked: $saved_count entries"
|
||||
echo " Currently in script: $new_count entries"
|
||||
echo " Removed: $removed_count | Added: $added_count"
|
||||
|
||||
# RULE 1: No entries removed - always OK
|
||||
if [[ $removed_count -eq 0 ]]; then
|
||||
echo " ✅ No entries removed - protection check passed."
|
||||
return 0
|
||||
fi
|
||||
|
||||
# RULE 2: Entries were removed - BLOCK INSTALLATION
|
||||
echo ""
|
||||
echo "============================================================"
|
||||
echo " ❌ INSTALLATION BLOCKED - CUSTOM ENTRIES REMOVED"
|
||||
echo "============================================================"
|
||||
echo ""
|
||||
echo "You are attempting to REMOVE the following blocked entries:"
|
||||
while IFS= read -r entry; do
|
||||
echo " - $entry"
|
||||
done <<<"$removed_entries"
|
||||
echo ""
|
||||
echo "This is NOT allowed. The only way to unblock sites is to:"
|
||||
echo ""
|
||||
echo " 1. Manually edit /etc/hosts (requires removing chattr protection)"
|
||||
echo " 2. Delete the state file /etc/hosts.custom-entries.state"
|
||||
echo " (also protected with chattr)"
|
||||
echo ""
|
||||
echo "These manual steps are intentionally difficult to prevent"
|
||||
echo "impulsive unblocking. If you really need to unblock something,"
|
||||
echo "you'll have to work for it."
|
||||
echo ""
|
||||
return 1
|
||||
}
|
||||
@ -0,0 +1,88 @@
|
||||
#!/usr/bin/env bash
|
||||
# lib/hosts_protect_unblock.sh — the anti-tamper guard on the UNBLOCK list.
|
||||
#
|
||||
# The mirror of hosts_protect_custom.sh: it refuses the install when the
|
||||
# whitelist has GROWN, so domains cannot be quietly un-blocked. Sourced by
|
||||
# install.sh.
|
||||
|
||||
# Extract whitelisted domains from the protected list embedded in this script
|
||||
extract_unblock_entries_from_script() {
|
||||
local script_path="$1"
|
||||
# The two marker lines match the domain pattern themselves -- they are
|
||||
# word characters and underscores -- so a plain grep pulled
|
||||
# PROTECTED_UNBLOCK_LIST_START and _END into the whitelist as if they were
|
||||
# domains. They then went into the saved state, and renaming either marker
|
||||
# would have read as the whitelist growing and blocked the install. Drop
|
||||
# them explicitly rather than relying on the pattern to exclude them.
|
||||
sed -n '/^# PROTECTED_UNBLOCK_LIST_START$/,/^# PROTECTED_UNBLOCK_LIST_END$/p' "$script_path" |
|
||||
grep -E '^# [a-zA-Z0-9._-]+$' |
|
||||
sed 's/^# //' |
|
||||
grep -vxE 'PROTECTED_UNBLOCK_LIST_(START|END)' |
|
||||
sort -u
|
||||
}
|
||||
|
||||
# Save current unblock entries to immutable state file
|
||||
save_unblock_entries_state() {
|
||||
local entries="$1"
|
||||
chattr -i "$UNBLOCK_STATE_FILE" 2>/dev/null || true
|
||||
echo "$entries" | sort -u >"$UNBLOCK_STATE_FILE"
|
||||
chmod 644 "$UNBLOCK_STATE_FILE"
|
||||
chattr +i "$UNBLOCK_STATE_FILE" 2>/dev/null || true
|
||||
}
|
||||
|
||||
# Block installation if the unblock list has grown (more sites being whitelisted)
|
||||
check_unblock_entries_protection() {
|
||||
local script_path
|
||||
# The install script whose entry lists are being checked. Defaults to the
|
||||
# running script, which is what production always wants; a test points it
|
||||
# at a fixture instead, since these guards are the part of this file where
|
||||
# a silent regression matters most.
|
||||
script_path="$(readlink -f "${HOSTS_INSTALL_SCRIPT_PATH:-$0}")"
|
||||
|
||||
local new_entries
|
||||
new_entries=$(extract_unblock_entries_from_script "$script_path")
|
||||
local new_count
|
||||
new_count=$(count_lines "$new_entries")
|
||||
|
||||
if [[ ! -f $UNBLOCK_STATE_FILE ]]; then
|
||||
echo "ℹ️ First unblock-list run — no protection check needed."
|
||||
return 0
|
||||
fi
|
||||
|
||||
local saved_entries
|
||||
saved_entries=$(sort -u "$UNBLOCK_STATE_FILE")
|
||||
local saved_count
|
||||
saved_count=$(count_lines "$saved_entries")
|
||||
|
||||
# Entries added since last install
|
||||
local added_entries
|
||||
added_entries=$(comm -13 <(echo "$saved_entries") <(echo "$new_entries"))
|
||||
local added_count
|
||||
added_count=$(count_lines "$added_entries")
|
||||
|
||||
echo ""
|
||||
echo "📊 Unblock Entries Protection Check:"
|
||||
echo " Previously whitelisted: $saved_count domains"
|
||||
echo " Currently in script: $new_count domains"
|
||||
echo " Newly added: $added_count"
|
||||
|
||||
if [[ $added_count -eq 0 ]]; then
|
||||
echo " ✅ No new unblocks — protection check passed."
|
||||
return 0
|
||||
fi
|
||||
|
||||
echo ""
|
||||
echo "============================================================"
|
||||
echo " ❌ INSTALLATION BLOCKED — NEW UNBLOCK ENTRIES DETECTED"
|
||||
echo "============================================================"
|
||||
echo ""
|
||||
echo "You are attempting to WHITELIST these additional domains:"
|
||||
while IFS= read -r entry; do
|
||||
echo " + $entry"
|
||||
done <<<"$added_entries"
|
||||
echo ""
|
||||
echo "To proceed, manually delete the state file first:"
|
||||
echo " sudo chattr -i $UNBLOCK_STATE_FILE && sudo rm $UNBLOCK_STATE_FILE"
|
||||
echo ""
|
||||
return 1
|
||||
}
|
||||
53
linux_configuration/scripts/periodic_background/hosts/lib/hosts_write.sh
Executable file
53
linux_configuration/scripts/periodic_background/hosts/lib/hosts_write.sh
Executable file
@ -0,0 +1,53 @@
|
||||
#!/usr/bin/env bash
|
||||
# lib/hosts_write.sh — write /etc/hosts.
|
||||
#
|
||||
# The cached upstream list, then the exceptions we comment back out, then our
|
||||
# own blocking entries as one ~320-line quoted heredoc, then the permissions
|
||||
# and the immutable attribute. The heredoc is a single unit: splitting its
|
||||
# interior would change the file this produces. Sourced by install.sh.
|
||||
|
||||
# Write /etc/hosts: the cached upstream list, the per-site exceptions we
|
||||
# comment back out, then our own blocking entries, and finally the
|
||||
# permissions and immutable attribute.
|
||||
#
|
||||
# The custom entries are one ~320-line quoted heredoc and move as a single
|
||||
# unit; splitting its interior would change the file this writes.
|
||||
# The custom blocking entries, as data beside this lib rather than inline.
|
||||
CUSTOM_ENTRIES_FILE="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)/custom_entries.hosts"
|
||||
|
||||
write_hosts_file() {
|
||||
# Install the base hosts from cache into /etc/hosts
|
||||
echo "Installing base hosts from cache to /etc/hosts..."
|
||||
sudo cp "$LOCAL_CACHE" /etc/hosts
|
||||
|
||||
# Comment out any 4chan blocking entries from the downloaded file
|
||||
echo "Allowing 4chan by commenting out any blocking entries..."
|
||||
sudo sed -i 's/^0\.0\.0\.0 4chan\.com/#0.0.0.0 4chan.com/' /etc/hosts
|
||||
sudo sed -i 's/^0\.0\.0\.0 www\.4chan\.com/#0.0.0.0 www.4chan.com/' /etc/hosts
|
||||
sudo sed -i 's/^0\.0\.0\.0 4chan\.org/#0.0.0.0 4chan.org/' /etc/hosts
|
||||
sudo sed -i 's/^0\.0\.0\.0 boards\.4chan\.org/#0.0.0.0 boards.4chan.org/' /etc/hosts
|
||||
sudo sed -i 's/^0\.0\.0\.0 sys\.4chan\.org/#0.0.0.0 sys.4chan.org/' /etc/hosts
|
||||
sudo sed -i 's/^0\.0\.0\.0 www\.4chan\.org/#0.0.0.0 www.4chan.org/' /etc/hosts
|
||||
sudo sed -i -E 's/^(0\.0\.0\.0[[:space:]]+[a-zA-Z0-9._-]*\.?facebook\.com)/#\1/' /etc/hosts
|
||||
sudo sed -i -E 's/^(0\.0\.0\.0[[:space:]]+[a-zA-Z0-9._-]*\.?messenger\.com)/#\1/' /etc/hosts
|
||||
sudo sed -i -E 's/^(0\.0\.0\.0[[:space:]]+[a-zA-Z0-9._-]*\.?fbcdn\.net)/#\1/' /etc/hosts
|
||||
sudo sed -i -E 's/^(0\.0\.0\.0[[:space:]]+[a-zA-Z0-9._-]*\.?facebook\.net)/#\1/' /etc/hosts
|
||||
sudo sed -i 's/^0\.0\.0\.0 delio\.com.pl/#0.0.0.0 delio.com.pl/' /etc/hosts
|
||||
sudo sed -i 's/^0\.0\.0\.0 loverslab\.com/#0.0.0.0 loverslab.com/' /etc/hosts
|
||||
|
||||
# Allow LinkedIn and all subdomains (linkedin.com + licdn.com CDN)
|
||||
echo "Allowing LinkedIn by commenting out any blocking entries..."
|
||||
sudo sed -i -E 's/^(0\.0\.0\.0[[:space:]]+[a-zA-Z0-9._-]*\.?linkedin\.com)/#\1/' /etc/hosts
|
||||
sudo sed -i -E 's/^(0\.0\.0\.0[[:space:]]+[a-zA-Z0-9._-]*\.?licdn\.com)/#\1/' /etc/hosts
|
||||
sudo sed -i -E 's/^(0\.0\.0\.0[[:space:]]+[a-zA-Z0-9._-]*\.?loverslab\.com)/#\1/' /etc/hosts
|
||||
|
||||
# Add custom entries for YouTube and Discord
|
||||
echo "Adding custom entries for YouTube and Discord..."
|
||||
tee -a /etc/hosts >/dev/null <"$CUSTOM_ENTRIES_FILE"
|
||||
|
||||
# Set proper permissions (readable by all, writable only by root)
|
||||
sudo chmod 644 /etc/hosts
|
||||
|
||||
# Make the file immutable and append-only for maximum protection
|
||||
sudo chattr +ia /etc/hosts
|
||||
}
|
||||
165
linux_configuration/scripts/periodic_background/hosts/lib/tests/hosts_harness.sh
Executable file
165
linux_configuration/scripts/periodic_background/hosts/lib/tests/hosts_harness.sh
Executable file
@ -0,0 +1,165 @@
|
||||
#!/usr/bin/env bash
|
||||
# lib/tests/hosts_harness.sh — shared fixture for the hosts/install.sh split.
|
||||
#
|
||||
# Sourced, not executed. Scope is deliberately narrow: only the two anti-tamper
|
||||
# guards and their helpers are exercised here. The install phases themselves
|
||||
# write /etc/hosts, unmount the guard's bind mount and restart
|
||||
# systemd-resolved, so running them under test would take down the very
|
||||
# protection they exist to install — they are covered by the textual
|
||||
# wrap-verification in the evidence instead.
|
||||
#
|
||||
# The state-file paths were already variables in the pre-split script, so a
|
||||
# test can point them at a tmpdir. chattr is shimmed because the real one
|
||||
# cannot mark a file immutable on a tmpfs and would abort the guard.
|
||||
set -euo pipefail
|
||||
|
||||
PASS=0
|
||||
FAIL=0
|
||||
|
||||
_t_pass() {
|
||||
PASS=$((PASS + 1))
|
||||
printf ' OK: %s\n' "$1"
|
||||
}
|
||||
|
||||
_t_fail() {
|
||||
FAIL=$((FAIL + 1))
|
||||
printf ' FAIL: %s\n' "$1"
|
||||
}
|
||||
|
||||
_t_eq() {
|
||||
local want="$1"
|
||||
local got="$2"
|
||||
local what="$3"
|
||||
if [[ "$got" == "$want" ]]; then
|
||||
_t_pass "$what"
|
||||
else
|
||||
_t_fail "$what (want '${want}', got '${got}')"
|
||||
fi
|
||||
}
|
||||
|
||||
_t_has() {
|
||||
local haystack="$1"
|
||||
local needle="$2"
|
||||
local what="$3"
|
||||
if [[ "$haystack" == *"$needle"* ]]; then
|
||||
_t_pass "$what"
|
||||
else
|
||||
_t_fail "$what (want a substring '${needle}')"
|
||||
fi
|
||||
}
|
||||
|
||||
# The guards return 0 to allow the install and 1 to block it. Which way they
|
||||
# fail is the entire point, so assert on the exit status explicitly rather than
|
||||
# letting `set -e` decide.
|
||||
_t_allows() {
|
||||
local what="$2"
|
||||
if ("$1"); then
|
||||
_t_pass "$what"
|
||||
else
|
||||
_t_fail "$what (the guard blocked when it should have allowed)"
|
||||
fi
|
||||
}
|
||||
|
||||
_t_blocks() {
|
||||
local what="$2"
|
||||
if ("$1"); then
|
||||
_t_fail "$what (the guard allowed when it should have blocked)"
|
||||
else
|
||||
_t_pass "$what"
|
||||
fi
|
||||
}
|
||||
|
||||
_t_summary() {
|
||||
printf '\n%s: %d passed, %d failed\n' "$(basename "$0")" "$PASS" "$FAIL"
|
||||
[[ $FAIL -eq 0 ]]
|
||||
}
|
||||
|
||||
TEST_TMPDIR="$(mktemp -d)"
|
||||
trap 'rm -rf "${TEST_TMPDIR}"' EXIT
|
||||
|
||||
readonly FAKE_BIN="${TEST_TMPDIR}/fake_bin"
|
||||
mkdir -p "${FAKE_BIN}"
|
||||
|
||||
# chattr cannot set the immutable bit on a tmpfs and exits non-zero; the guards
|
||||
# tolerate that with `|| true`, but shimming it keeps the test output clean and
|
||||
# makes "was the state file locked" observable.
|
||||
cat >"${FAKE_BIN}/chattr" <<'CHATTRSHIM'
|
||||
#!/usr/bin/env bash
|
||||
printf '%s\n' "chattr $*" >>"${HOSTS_TEST_CALLS}"
|
||||
exit 0
|
||||
CHATTRSHIM
|
||||
chmod +x "${FAKE_BIN}/chattr"
|
||||
|
||||
export HOSTS_TEST_CALLS="${TEST_TMPDIR}/calls"
|
||||
export PATH="${FAKE_BIN}:${PATH}"
|
||||
|
||||
# --- globals the guards read ------------------------------------------------
|
||||
|
||||
export CUSTOM_ENTRIES_STATE_FILE="${TEST_TMPDIR}/custom.state"
|
||||
export UNBLOCK_STATE_FILE="${TEST_TMPDIR}/unblock.state"
|
||||
|
||||
# A fake install.sh plus the custom_entries.hosts beside it. The guards resolve
|
||||
# the data file from the script path, so this reproduces the real layout.
|
||||
readonly FAKE_ROOT="${TEST_TMPDIR}/root"
|
||||
readonly FAKE_SCRIPT="${FAKE_ROOT}/install.sh"
|
||||
|
||||
# Stage the "new" entry lists the guards will read: the custom blocklist as a
|
||||
# data file, and the unblock list as marked-up comments inside the script.
|
||||
stage_script() { # <custom-domain>... -- <unblock-domain>...
|
||||
mkdir -p "${FAKE_ROOT}"
|
||||
local mode="custom"
|
||||
local custom=()
|
||||
local unblock=()
|
||||
local arg
|
||||
for arg in "$@"; do
|
||||
if [[ "$arg" == "--" ]]; then
|
||||
mode="unblock"
|
||||
continue
|
||||
fi
|
||||
if [[ "$mode" == "custom" ]]; then
|
||||
custom+=("$arg")
|
||||
else
|
||||
unblock+=("$arg")
|
||||
fi
|
||||
done
|
||||
|
||||
{
|
||||
printf '# Custom blocking entries\n'
|
||||
local d
|
||||
for d in "${custom[@]}"; do
|
||||
printf '0.0.0.0 %s\n' "$d"
|
||||
done
|
||||
} >"${FAKE_ROOT}/custom_entries.hosts"
|
||||
|
||||
{
|
||||
printf '#!/bin/bash\n'
|
||||
printf '# PROTECTED_UNBLOCK_LIST_START\n'
|
||||
local d
|
||||
for d in "${unblock[@]}"; do
|
||||
printf '# %s\n' "$d"
|
||||
done
|
||||
printf '# PROTECTED_UNBLOCK_LIST_END\n'
|
||||
} >"${FAKE_SCRIPT}"
|
||||
}
|
||||
|
||||
# Seed the saved state the guards compare against.
|
||||
stage_custom_state() {
|
||||
printf '%s\n' "$@" | sort -u >"${CUSTOM_ENTRIES_STATE_FILE}"
|
||||
}
|
||||
|
||||
stage_unblock_state() {
|
||||
printf '%s\n' "$@" | sort -u >"${UNBLOCK_STATE_FILE}"
|
||||
}
|
||||
|
||||
reset_state() {
|
||||
rm -rf "${FAKE_ROOT}"
|
||||
rm -f "${CUSTOM_ENTRIES_STATE_FILE}" "${UNBLOCK_STATE_FILE}"
|
||||
# Markers a test sets to steer a shim (e.g. curl_fails) are part of the
|
||||
# machine that test describes, so they reset too -- otherwise a failure
|
||||
# marker leaks into the next group and it passes for the wrong reason.
|
||||
rm -f "$(dirname "${HOSTS_TEST_CALLS}")"/curl_fails \
|
||||
"$(dirname "${HOSTS_TEST_CALLS}")"/remote_body
|
||||
: >"${HOSTS_TEST_CALLS}"
|
||||
mkdir -p "${FAKE_ROOT}"
|
||||
}
|
||||
reset_state
|
||||
26
linux_configuration/scripts/periodic_background/hosts/lib/tests/run_all.sh
Executable file
26
linux_configuration/scripts/periodic_background/hosts/lib/tests/run_all.sh
Executable file
@ -0,0 +1,26 @@
|
||||
#!/usr/bin/env bash
|
||||
# lib/tests/run_all.sh — run every hosts/install.sh test in one process tree.
|
||||
#
|
||||
# Scope note: these cover the two anti-tamper guards and the cache helpers, not
|
||||
# the install phases. The phases write /etc/hosts, unmount the guard's bind
|
||||
# mount and restart systemd-resolved, so executing them under test would take
|
||||
# down the protection they exist to install. They are verified textually
|
||||
# instead — see the evidence artifact for this split.
|
||||
set -euo pipefail
|
||||
|
||||
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
||||
|
||||
failed=0
|
||||
for test_script in "${SCRIPT_DIR}"/test_hosts_*.sh; do
|
||||
printf '\n### %s\n' "$(basename "$test_script")"
|
||||
if ! "$test_script"; then
|
||||
failed=$((failed + 1))
|
||||
fi
|
||||
done
|
||||
|
||||
if [[ $failed -gt 0 ]]; then
|
||||
printf '\n%d test file(s) FAILED\n' "$failed"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
printf '\nAll hosts install test files passed.\n'
|
||||
@ -0,0 +1,119 @@
|
||||
#!/usr/bin/env bash
|
||||
# Tests for lib/hosts_cache.sh — keeping the local copy of the upstream
|
||||
# StevenBlack list current.
|
||||
#
|
||||
# The date parsing is what decides whether a download happens at all: the
|
||||
# upstream file carries a "# Date:" header, and a cache whose header is not
|
||||
# older than the remote one is reused. Misreading that header means either
|
||||
# re-downloading a 4 MB file on every install, or never refreshing at all.
|
||||
#
|
||||
# curl is shimmed, so nothing here touches the network.
|
||||
set -euo pipefail
|
||||
|
||||
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
||||
|
||||
# shellcheck source=hosts_harness.sh
|
||||
. "${SCRIPT_DIR}/hosts_harness.sh"
|
||||
|
||||
# Fake curl. `-o <file>` writes whatever $DEV/remote_body holds; a
|
||||
# $DEV/curl_fails marker makes every invocation fail, which is what exercises
|
||||
# the "keep using the stale cache" path.
|
||||
cat >"${FAKE_BIN}/curl" <<'CURLSHIM'
|
||||
#!/usr/bin/env bash
|
||||
set -uo pipefail
|
||||
printf '%s\n' "curl $*" >>"${HOSTS_TEST_CALLS}"
|
||||
dev="$(dirname "${HOSTS_TEST_CALLS}")"
|
||||
[[ -f "${dev}/curl_fails" ]] && exit 22
|
||||
out=""
|
||||
prev=""
|
||||
for a in "$@"; do
|
||||
[[ "$prev" == "-o" ]] && out="$a"
|
||||
prev="$a"
|
||||
done
|
||||
body="${dev}/remote_body"
|
||||
[[ -f "$body" ]] || : >"$body"
|
||||
if [[ -n "$out" ]]; then
|
||||
cat "$body" >"$out"
|
||||
else
|
||||
cat "$body"
|
||||
fi
|
||||
exit 0
|
||||
CURLSHIM
|
||||
chmod +x "${FAKE_BIN}/curl"
|
||||
|
||||
DEV="$(dirname "${HOSTS_TEST_CALLS}")"
|
||||
|
||||
# shellcheck source=../hosts_cache.sh
|
||||
. "${SCRIPT_DIR}/../hosts_cache.sh"
|
||||
|
||||
# The lib reads $URL; point it somewhere obviously fake so a missing shim would
|
||||
# be an immediate failure rather than a real request.
|
||||
URL="http://test.invalid/hosts"
|
||||
|
||||
write_dated_file() { # <path> <date-header-or-empty>
|
||||
{
|
||||
[[ -n "${2:-}" ]] && printf '# Date: %s (UTC)\n' "$2"
|
||||
printf '# Title: fake\n0.0.0.0 blocked.example\n'
|
||||
} >"$1"
|
||||
}
|
||||
|
||||
echo "== extract_date_epoch_from_file =="
|
||||
reset_state
|
||||
f="${TEST_TMPDIR}/dated"
|
||||
write_dated_file "$f" "01 January 2026 00:00:00"
|
||||
_t_eq "1767225600" "$(extract_date_epoch_from_file "$f")" "a dated header parses to epoch seconds"
|
||||
|
||||
write_dated_file "$f" ""
|
||||
_t_eq "" "$(extract_date_epoch_from_file "$f")" "a file with no Date header yields nothing"
|
||||
|
||||
write_dated_file "$f" "not a real date"
|
||||
_t_eq "" "$(extract_date_epoch_from_file "$f")" "an unparsable date yields nothing rather than a bad epoch"
|
||||
|
||||
_t_eq "" "$(extract_date_epoch_from_file "${TEST_TMPDIR}/no-such-file")" \
|
||||
"a missing file yields nothing"
|
||||
|
||||
echo "== fetch_remote_header =="
|
||||
reset_state
|
||||
write_dated_file "${DEV}/remote_body" "02 February 2026 00:00:00"
|
||||
out="${TEST_TMPDIR}/header"
|
||||
if fetch_remote_header "$out"; then
|
||||
_t_pass "a successful fetch reports success"
|
||||
else
|
||||
_t_fail "a successful fetch reports success"
|
||||
fi
|
||||
_t_eq "1769990400" "$(extract_date_epoch_from_file "$out")" "the fetched header is readable"
|
||||
if grep -q 'Range: bytes=0-4095' "${HOSTS_TEST_CALLS}"; then
|
||||
_t_pass "it asks for a byte range rather than the whole file"
|
||||
else
|
||||
_t_fail "it asks for a byte range rather than the whole file"
|
||||
fi
|
||||
|
||||
echo "== fetch_remote_header: both attempts fail =="
|
||||
reset_state
|
||||
: >"${DEV}/curl_fails"
|
||||
if fetch_remote_header "${TEST_TMPDIR}/header2"; then
|
||||
_t_fail "a total fetch failure reports failure"
|
||||
else
|
||||
_t_pass "a total fetch failure reports failure"
|
||||
fi
|
||||
|
||||
echo "== download_remote_full_to =="
|
||||
reset_state
|
||||
write_dated_file "${DEV}/remote_body" "03 March 2026 00:00:00"
|
||||
full="${TEST_TMPDIR}/full"
|
||||
if download_remote_full_to "$full"; then
|
||||
_t_pass "a full download reports success"
|
||||
else
|
||||
_t_fail "a full download reports success"
|
||||
fi
|
||||
_t_eq "1772496000" "$(extract_date_epoch_from_file "$full")" "the downloaded file is the remote body"
|
||||
|
||||
reset_state
|
||||
: >"${DEV}/curl_fails"
|
||||
if download_remote_full_to "${TEST_TMPDIR}/full2"; then
|
||||
_t_fail "a failed download reports failure"
|
||||
else
|
||||
_t_pass "a failed download reports failure"
|
||||
fi
|
||||
|
||||
_t_summary
|
||||
@ -0,0 +1,168 @@
|
||||
#!/usr/bin/env bash
|
||||
# Tests for the two anti-tamper guards: lib/hosts_protect_custom.sh and
|
||||
# lib/hosts_protect_unblock.sh.
|
||||
#
|
||||
# These are the highest-stakes functions in the file. They exist to stop the
|
||||
# blocklist being quietly weakened by editing this repo — the custom guard
|
||||
# refuses when blocked domains are REMOVED, the unblock guard refuses when the
|
||||
# whitelist GROWS. A split that silently disabled either would be invisible
|
||||
# until the day it mattered, so both directions of both guards get a case.
|
||||
set -euo pipefail
|
||||
|
||||
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
||||
|
||||
# shellcheck source=hosts_harness.sh
|
||||
. "${SCRIPT_DIR}/hosts_harness.sh"
|
||||
# shellcheck source=../hosts_protect_custom.sh
|
||||
. "${SCRIPT_DIR}/../hosts_protect_custom.sh"
|
||||
# shellcheck source=../hosts_protect_unblock.sh
|
||||
. "${SCRIPT_DIR}/../hosts_protect_unblock.sh"
|
||||
|
||||
export HOSTS_INSTALL_SCRIPT_PATH="${FAKE_SCRIPT}"
|
||||
|
||||
echo "== extract_custom_entries_from_script =="
|
||||
reset_state
|
||||
stage_script a.com b.com c.com -- x.com
|
||||
_t_eq "a.com
|
||||
b.com
|
||||
c.com" "$(extract_custom_entries_from_script "${FAKE_SCRIPT}")" \
|
||||
"the blocked domains are read out of the data file"
|
||||
|
||||
reset_state
|
||||
mkdir -p "${FAKE_ROOT}"
|
||||
printf '#!/bin/bash\n' >"${FAKE_SCRIPT}"
|
||||
# No data file beside the script: the list reads as empty, which the guard
|
||||
# treats as "everything was removed" and refuses. Failing safe is the point.
|
||||
_t_eq "" "$(extract_custom_entries_from_script "${FAKE_SCRIPT}")" \
|
||||
"a missing data file yields an empty list rather than an error"
|
||||
|
||||
echo "== extract_custom_entries_from_hosts =="
|
||||
reset_state
|
||||
hosts_fixture="${TEST_TMPDIR}/hosts.sample"
|
||||
{
|
||||
printf '127.0.0.1 localhost\n'
|
||||
printf '0.0.0.0 upstream-junk.com\n'
|
||||
printf '# Custom blocking entries\n'
|
||||
printf '0.0.0.0 mine-one.com\n'
|
||||
printf '0.0.0.0 mine-two.com\n'
|
||||
} >"$hosts_fixture"
|
||||
_t_eq "mine-one.com
|
||||
mine-two.com" "$(extract_custom_entries_from_hosts "$hosts_fixture")" \
|
||||
"only entries after the marker count as ours"
|
||||
|
||||
reset_state
|
||||
# A machine with no /etc/hosts at all is the pre-install state; reading it must
|
||||
# yield an empty list rather than an error, or the first install could not run.
|
||||
_t_eq "" "$(extract_custom_entries_from_hosts "${TEST_TMPDIR}/no-such-hosts")" \
|
||||
"a missing hosts file yields an empty list"
|
||||
|
||||
echo "== count_lines =="
|
||||
_t_eq "0" "$(count_lines "")" "an empty string counts as zero, not one"
|
||||
_t_eq "1" "$(count_lines "one")" "a single entry counts as one"
|
||||
_t_eq "3" "$(count_lines "$(printf 'a\nb\nc')")" "three entries count as three"
|
||||
|
||||
echo "== load_saved_custom_entries =="
|
||||
reset_state
|
||||
_t_eq "" "$(load_saved_custom_entries)" "no state file reads as empty"
|
||||
stage_custom_state b.com a.com
|
||||
_t_eq "a.com
|
||||
b.com" "$(load_saved_custom_entries)" "a state file reads back sorted"
|
||||
|
||||
echo "== save_custom_entries_state =="
|
||||
reset_state
|
||||
save_custom_entries_state "$(printf 'z.com\na.com\n')"
|
||||
_t_eq "a.com
|
||||
z.com" "$(cat "${CUSTOM_ENTRIES_STATE_FILE}")" "the saved state is sorted and unique"
|
||||
if grep -q "chattr +i" "${HOSTS_TEST_CALLS}"; then
|
||||
_t_pass "the state file is made immutable after writing"
|
||||
else
|
||||
_t_fail "the state file is made immutable after writing"
|
||||
fi
|
||||
|
||||
echo "== check_custom_entries_protection: first run =="
|
||||
reset_state
|
||||
stage_script a.com b.com -- x.com
|
||||
# No state file and nothing in /etc/hosts to fall back on means this is the
|
||||
# first install, which must be allowed or the system could never be set up.
|
||||
CUSTOM_ENTRIES_STATE_FILE="${TEST_TMPDIR}/nonexistent.state"
|
||||
# The fallback reads the live hosts file, which on a real machine already has
|
||||
# our entries; point it at an empty fixture so this is genuinely a first run.
|
||||
HOSTS_FILE_PATH="${TEST_TMPDIR}/empty.hosts"
|
||||
: >"${HOSTS_FILE_PATH}"
|
||||
out="$(check_custom_entries_protection || true)"
|
||||
_t_has "$out" "First installation" "a first run is allowed"
|
||||
CUSTOM_ENTRIES_STATE_FILE="${TEST_TMPDIR}/custom.state"
|
||||
unset HOSTS_FILE_PATH
|
||||
|
||||
echo "== check_custom_entries_protection: nothing removed =="
|
||||
reset_state
|
||||
stage_script a.com b.com -- x.com
|
||||
stage_custom_state a.com b.com
|
||||
_t_allows check_custom_entries_protection "an unchanged list is allowed"
|
||||
|
||||
echo "== check_custom_entries_protection: entries added =="
|
||||
reset_state
|
||||
stage_script a.com b.com c.com -- x.com
|
||||
stage_custom_state a.com b.com
|
||||
_t_allows check_custom_entries_protection "adding entries is allowed"
|
||||
|
||||
echo "== check_custom_entries_protection: an entry removed is BLOCKED =="
|
||||
reset_state
|
||||
stage_script a.com -- x.com
|
||||
stage_custom_state a.com b.com
|
||||
_t_blocks check_custom_entries_protection "removing a blocked domain is refused"
|
||||
out="$(check_custom_entries_protection || true)"
|
||||
_t_has "$out" "INSTALLATION BLOCKED" "the refusal is stated plainly"
|
||||
_t_has "$out" "b.com" "the removed domain is named"
|
||||
|
||||
echo "== check_custom_entries_protection: swapping entries is still a removal =="
|
||||
reset_state
|
||||
# Same count, different contents. A count-only check would pass this, which is
|
||||
# exactly the hole the removed-set comparison exists to close.
|
||||
stage_script a.com NEW.com -- x.com
|
||||
stage_custom_state a.com b.com
|
||||
_t_blocks check_custom_entries_protection "swapping one domain for another is refused"
|
||||
|
||||
echo "== extract_unblock_entries_from_script =="
|
||||
reset_state
|
||||
stage_script a.com -- one.com two.com
|
||||
_t_eq "one.com
|
||||
two.com" "$(extract_unblock_entries_from_script "${FAKE_SCRIPT}")" \
|
||||
"the whitelist is read from between the markers"
|
||||
|
||||
echo "== check_unblock_entries_protection: first run =="
|
||||
reset_state
|
||||
stage_script a.com -- one.com
|
||||
UNBLOCK_STATE_FILE="${TEST_TMPDIR}/nonexistent-unblock.state"
|
||||
_t_allows check_unblock_entries_protection "a first run is allowed"
|
||||
UNBLOCK_STATE_FILE="${TEST_TMPDIR}/unblock.state"
|
||||
|
||||
echo "== check_unblock_entries_protection: unchanged =="
|
||||
reset_state
|
||||
stage_script a.com -- one.com two.com
|
||||
stage_unblock_state one.com two.com
|
||||
_t_allows check_unblock_entries_protection "an unchanged whitelist is allowed"
|
||||
|
||||
echo "== check_unblock_entries_protection: shrinking is allowed =="
|
||||
reset_state
|
||||
# Removing a domain from the whitelist means blocking MORE, which is always
|
||||
# the safe direction and must never be refused.
|
||||
stage_script a.com -- one.com
|
||||
stage_unblock_state one.com two.com
|
||||
_t_allows check_unblock_entries_protection "removing a whitelist entry is allowed"
|
||||
|
||||
echo "== check_unblock_entries_protection: growing is BLOCKED =="
|
||||
reset_state
|
||||
stage_script a.com -- one.com two.com three.com
|
||||
stage_unblock_state one.com two.com
|
||||
_t_blocks check_unblock_entries_protection "adding a whitelist entry is refused"
|
||||
out="$(check_unblock_entries_protection || true)"
|
||||
_t_has "$out" "three.com" "the newly whitelisted domain is named"
|
||||
|
||||
echo "== save_unblock_entries_state =="
|
||||
reset_state
|
||||
save_unblock_entries_state "$(printf 'z.com\na.com\n')"
|
||||
_t_eq "a.com
|
||||
z.com" "$(cat "${UNBLOCK_STATE_FILE}")" "the saved whitelist is sorted and unique"
|
||||
|
||||
_t_summary
|
||||
@ -9,6 +9,23 @@
|
||||
|
||||
set -e
|
||||
|
||||
# Each generation phase and each family of doc-URL builders lives in a lib
|
||||
# beside this file; this script keeps the configuration, the argument
|
||||
# parsing and the order the phases run in.
|
||||
LIB_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)/lib"
|
||||
# shellcheck source=lib/study_doc_urls.sh
|
||||
. "$LIB_DIR/study_doc_urls.sh"
|
||||
# shellcheck source=lib/study_doc_urls_more.sh
|
||||
. "$LIB_DIR/study_doc_urls_more.sh"
|
||||
# shellcheck source=lib/study_doc_lookup.sh
|
||||
. "$LIB_DIR/study_doc_lookup.sh"
|
||||
# shellcheck source=lib/study_gen_docs.sh
|
||||
. "$LIB_DIR/study_gen_docs.sh"
|
||||
# shellcheck source=lib/study_gen_anki.sh
|
||||
. "$LIB_DIR/study_gen_anki.sh"
|
||||
# shellcheck source=lib/study_gen_llm.sh
|
||||
. "$LIB_DIR/study_gen_llm.sh"
|
||||
|
||||
#==============================================================================
|
||||
# Configuration
|
||||
#==============================================================================
|
||||
@ -56,386 +73,10 @@ BLUE='\033[0;34m'
|
||||
YELLOW='\033[1;33m'
|
||||
NC='\033[0m'
|
||||
|
||||
#==============================================================================
|
||||
# Offline Documentation Lookup (preferred if available)
|
||||
#==============================================================================
|
||||
lookup_offline() {
|
||||
local term="$1"
|
||||
local lang="$2"
|
||||
local import_line="$3" # Optional: full import line for context
|
||||
|
||||
if ! $USE_OFFLINE_DOCS; then
|
||||
return 1
|
||||
fi
|
||||
|
||||
local result
|
||||
if [ -n "$import_line" ]; then
|
||||
# Use import-aware lookup - get the line with the file path
|
||||
result=$("$LOOKUP_SCRIPT" --import "$import_line" "$lang" 2>/dev/null | grep "^/" | head -1)
|
||||
else
|
||||
result=$("$LOOKUP_SCRIPT" "$term" "$lang" 2>/dev/null | grep "^File:" | head -1 | sed 's/^File: //')
|
||||
fi
|
||||
|
||||
if [ -n "$result" ]; then
|
||||
# Extract file path (before the | separator)
|
||||
local file_path
|
||||
file_path=$(echo "$result" | cut -d'|' -f1)
|
||||
if [ -n "$file_path" ]; then
|
||||
echo "$file_path"
|
||||
return 0
|
||||
fi
|
||||
fi
|
||||
|
||||
return 1
|
||||
}
|
||||
|
||||
#==============================================================================
|
||||
# Documentation URL Generators (online fallback)
|
||||
#==============================================================================
|
||||
|
||||
# Python documentation
|
||||
python_doc_url() {
|
||||
local term="$1"
|
||||
local _type="$2" # keyword, builtin, module (reserved for future use)
|
||||
|
||||
case "$term" in
|
||||
# Keywords
|
||||
if | else | elif | for | while | try | except | finally | with | as | import | from | def | class | return | yield | raise | pass | break | continue | and | or | not | in | is | lambda | global | nonlocal | assert | del | True | False | None | async | await)
|
||||
echo "https://docs.python.org/3/reference/compound_stmts.html"
|
||||
;;
|
||||
# Built-in functions
|
||||
print | len | range | type | str | int | float | list | dict | set | tuple | bool | open | input | format | sorted | reversed | enumerate | zip | map | filter | any | all | sum | min | max | abs | round | isinstance | issubclass | hasattr | getattr | setattr | delattr | callable | iter | next | super | property | staticmethod | classmethod | vars | dir | help | id | hash | repr | ascii | bin | hex | oct | chr | ord | eval | exec | compile)
|
||||
echo "https://docs.python.org/3/library/functions.html#$term"
|
||||
;;
|
||||
# Common modules
|
||||
os | sys | re | json | datetime | collections | itertools | functools | pathlib | subprocess | threading | multiprocessing | asyncio | typing | dataclasses | unittest | pytest | logging | argparse | configparser)
|
||||
echo "https://docs.python.org/3/library/$term.html"
|
||||
;;
|
||||
# Testing
|
||||
MagicMock | Mock | patch | PropertyMock)
|
||||
echo "https://docs.python.org/3/library/unittest.mock.html"
|
||||
;;
|
||||
*)
|
||||
echo "https://docs.python.org/3/search.html?q=$term"
|
||||
;;
|
||||
esac
|
||||
}
|
||||
|
||||
# JavaScript/TypeScript documentation (MDN)
|
||||
js_doc_url() {
|
||||
local term="$1"
|
||||
|
||||
case "$term" in
|
||||
# Keywords & statements
|
||||
if | else | for | while | do | switch | case | break | continue | return | throw | try | catch | finally | function | class | const | let | var | new | this | super | import | export | default | async | await | yield | typeof | instanceof | in | of | delete | void)
|
||||
echo "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements"
|
||||
;;
|
||||
# Global objects
|
||||
Array | Object | String | Number | Boolean | Symbol | Map | Set | WeakMap | WeakSet | Date | RegExp | Error | Promise | Proxy | Reflect | JSON | Math | Intl)
|
||||
echo "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/$term"
|
||||
;;
|
||||
# Array methods
|
||||
map | filter | reduce | forEach | find | findIndex | some | every | includes | indexOf | slice | splice | concat | join | push | pop | shift | unshift | sort | reverse | flat | flatMap)
|
||||
echo "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/$term"
|
||||
;;
|
||||
# String methods
|
||||
split | replace | match | search | substring | substr | toLowerCase | toUpperCase | trim | padStart | padEnd | startsWith | endsWith | charAt | charCodeAt)
|
||||
echo "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/$term"
|
||||
;;
|
||||
# Promise methods
|
||||
then | resolve | reject | all | race | allSettled | any)
|
||||
echo "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/$term"
|
||||
;;
|
||||
# Common Web APIs
|
||||
fetch | console | document | window | localStorage | sessionStorage | setTimeout | setInterval | addEventListener | querySelector | querySelectorAll)
|
||||
echo "https://developer.mozilla.org/en-US/docs/Web/API"
|
||||
;;
|
||||
*)
|
||||
echo "https://developer.mozilla.org/en-US/search?q=$term"
|
||||
;;
|
||||
esac
|
||||
}
|
||||
|
||||
# TypeScript-specific documentation
|
||||
ts_doc_url() {
|
||||
local term="$1"
|
||||
|
||||
case "$term" in
|
||||
interface | type | enum | namespace | declare | readonly | abstract | implements | extends | keyof | typeof | infer | as | is | asserts | satisfies | override)
|
||||
echo "https://www.typescriptlang.org/docs/handbook/2/everyday-types.html"
|
||||
;;
|
||||
Partial | Required | Readonly | Record | Pick | Omit | Exclude | Extract | NonNullable | ReturnType | Parameters | InstanceType | Awaited)
|
||||
echo "https://www.typescriptlang.org/docs/handbook/utility-types.html"
|
||||
;;
|
||||
*)
|
||||
# Fall back to JS docs for runtime features
|
||||
js_doc_url "$term"
|
||||
;;
|
||||
esac
|
||||
}
|
||||
|
||||
# C documentation
|
||||
c_doc_url() {
|
||||
local term="$1"
|
||||
|
||||
case "$term" in
|
||||
# Keywords
|
||||
if | else | for | while | do | switch | case | break | continue | return | goto | sizeof | typedef | struct | union | enum | const | static | extern | register | volatile | inline | restrict | _Bool | _Complex | _Imaginary | _Alignas | _Alignof | _Atomic | _Generic | _Noreturn | _Static_assert | _Thread_local)
|
||||
echo "https://en.cppreference.com/w/c/keyword/$term"
|
||||
;;
|
||||
# Standard library headers
|
||||
stdio | stdlib | string | math | time | ctype | stdint | stdbool | stddef | limits | float | errno | assert | signal | setjmp | stdarg | locale)
|
||||
echo "https://en.cppreference.com/w/c/header/${term}.h"
|
||||
;;
|
||||
# Common functions
|
||||
printf | fprintf | sprintf | snprintf | scanf | fscanf | sscanf | fopen | fclose | fread | fwrite | fgets | fputs | fseek | ftell | rewind | fflush)
|
||||
echo "https://en.cppreference.com/w/c/io"
|
||||
;;
|
||||
malloc | calloc | realloc | free | memcpy | memmove | memset | memcmp)
|
||||
echo "https://en.cppreference.com/w/c/memory"
|
||||
;;
|
||||
strlen | strcpy | strncpy | strcat | strncat | strcmp | strncmp | strchr | strrchr | strstr | strtok)
|
||||
echo "https://en.cppreference.com/w/c/string/byte"
|
||||
;;
|
||||
*)
|
||||
echo "https://en.cppreference.com/mwiki/index.php?search=$term"
|
||||
;;
|
||||
esac
|
||||
}
|
||||
|
||||
# C++ documentation
|
||||
cpp_doc_url() {
|
||||
local term="$1"
|
||||
|
||||
case "$term" in
|
||||
# C++ specific keywords
|
||||
class | public | private | protected | virtual | override | final | explicit | mutable | constexpr | consteval | constinit | concept | requires | co_await | co_yield | co_return | nullptr | noexcept | decltype | auto | template | typename | namespace | using | new | delete | throw | try | catch | static_cast | dynamic_cast | const_cast | reinterpret_cast)
|
||||
echo "https://en.cppreference.com/w/cpp/keyword/$term"
|
||||
;;
|
||||
# STL containers
|
||||
vector | list | deque | array | forward_list | set | map | unordered_set | unordered_map | multiset | multimap | stack | queue | priority_queue)
|
||||
echo "https://en.cppreference.com/w/cpp/container/$term"
|
||||
;;
|
||||
# STL algorithms
|
||||
sort | find | copy | move | transform | accumulate | count | remove | unique | reverse | rotate | shuffle | partition | merge | binary_search | lower_bound | upper_bound)
|
||||
echo "https://en.cppreference.com/w/cpp/algorithm/$term"
|
||||
;;
|
||||
# Smart pointers
|
||||
unique_ptr | shared_ptr | weak_ptr | make_unique | make_shared)
|
||||
echo "https://en.cppreference.com/w/cpp/memory/$term"
|
||||
;;
|
||||
# Common classes
|
||||
string | string_view | optional | variant | any | tuple | pair | function | bind | thread | mutex | future | promise | chrono)
|
||||
echo "https://en.cppreference.com/w/cpp/utility"
|
||||
;;
|
||||
*)
|
||||
# Try C docs as fallback
|
||||
c_doc_url "$term"
|
||||
;;
|
||||
esac
|
||||
}
|
||||
|
||||
# Rust documentation
|
||||
rust_doc_url() {
|
||||
local term="$1"
|
||||
|
||||
case "$term" in
|
||||
# Keywords
|
||||
fn | let | mut | const | static | if | else | match | loop | while | for | in | break | continue | return | struct | enum | impl | trait | type | where | pub | mod | use | crate | self | super | async | await | move | ref | dyn | unsafe | extern)
|
||||
echo "https://doc.rust-lang.org/std/keyword.$term.html"
|
||||
;;
|
||||
# Common types
|
||||
Option | Result | Vec | String | Box | Rc | Arc | Cell | RefCell | Mutex | RwLock | HashMap | HashSet | BTreeMap | BTreeSet)
|
||||
echo "https://doc.rust-lang.org/std/$term"
|
||||
;;
|
||||
# Traits
|
||||
Clone | Copy | Debug | Default | Eq | PartialEq | Ord | PartialOrd | Hash | Display | From | Into | AsRef | AsMut | Deref | DerefMut | Iterator | IntoIterator | Send | Sync)
|
||||
echo "https://doc.rust-lang.org/std/$term"
|
||||
;;
|
||||
# Macros
|
||||
println | print | format | vec | panic | assert | assert_eq | assert_ne | debug_assert | todo | unimplemented | unreachable)
|
||||
echo "https://doc.rust-lang.org/std/macro.$term.html"
|
||||
;;
|
||||
*)
|
||||
echo "https://doc.rust-lang.org/std/?search=$term"
|
||||
;;
|
||||
esac
|
||||
}
|
||||
|
||||
# Go documentation
|
||||
go_doc_url() {
|
||||
local term="$1"
|
||||
|
||||
case "$term" in
|
||||
# Keywords
|
||||
func | var | const | type | struct | interface | map | chan | go | select | defer | if | else | for | range | switch | case | default | break | continue | return | goto | fallthrough | package | import)
|
||||
echo "https://go.dev/ref/spec"
|
||||
;;
|
||||
# Built-in functions
|
||||
make | new | len | cap | append | copy | delete | close | panic | recover | print | println | complex | real | imag)
|
||||
echo "https://pkg.go.dev/builtin#$term"
|
||||
;;
|
||||
# Common packages
|
||||
fmt | os | io | net | http | json | time | strings | strconv | errors | context | sync | testing | reflect | regexp | sort | math | crypto | encoding | bufio | bytes | path | filepath)
|
||||
echo "https://pkg.go.dev/$term"
|
||||
;;
|
||||
*)
|
||||
echo "https://pkg.go.dev/search?q=$term"
|
||||
;;
|
||||
esac
|
||||
}
|
||||
|
||||
# Ruby documentation
|
||||
ruby_doc_url() {
|
||||
local term="$1"
|
||||
|
||||
case "$term" in
|
||||
# Keywords
|
||||
if | else | elsif | unless | case | when | while | until | for | do | end | begin | rescue | ensure | raise | return | break | next | redo | retry | yield | def | class | module | self | super | nil | true | false | and | or | not | in | then | alias | defined | __FILE__ | __LINE__ | __ENCODING__)
|
||||
echo "https://ruby-doc.org/docs/keywords/1.9/"
|
||||
;;
|
||||
# Core classes
|
||||
String | Array | Hash | Integer | Float | Symbol | Range | Regexp | Time | Date | File | Dir | IO | Proc | Lambda | Method | Thread | Mutex | Fiber)
|
||||
echo "https://ruby-doc.org/core/classes/$term.html"
|
||||
;;
|
||||
# Enumerable methods
|
||||
each | map | select | reject | find | reduce | inject | collect | detect | sort | sort_by | group_by | partition | any | all | none | one | count | first | last | take | drop)
|
||||
echo "https://ruby-doc.org/core/Enumerable.html"
|
||||
;;
|
||||
*)
|
||||
echo "https://ruby-doc.org/search.html?q=$term"
|
||||
;;
|
||||
esac
|
||||
}
|
||||
|
||||
# Java documentation
|
||||
java_doc_url() {
|
||||
local term="$1"
|
||||
|
||||
case "$term" in
|
||||
# Keywords
|
||||
if | else | for | while | do | switch | case | break | continue | return | throw | try | catch | finally | class | interface | enum | extends | implements | new | this | super | static | final | abstract | public | private | protected | void | null | true | false | instanceof | synchronized | volatile | transient | native | strictfp | assert | default | package | import)
|
||||
echo "https://docs.oracle.com/javase/tutorial/java/nutsandbolts/"
|
||||
;;
|
||||
# Common classes
|
||||
String | Integer | Long | Double | Float | Boolean | Character | Object | Class | System | Math | Arrays | Collections | List | ArrayList | LinkedList | Map | HashMap | TreeMap | Set | HashSet | TreeSet | Queue | Stack | Optional | Stream)
|
||||
echo "https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/lang/$term.html"
|
||||
;;
|
||||
*)
|
||||
echo "https://docs.oracle.com/en/java/javase/17/docs/api/search.html?q=$term"
|
||||
;;
|
||||
esac
|
||||
}
|
||||
|
||||
# Shell documentation
|
||||
shell_doc_url() {
|
||||
local term="$1"
|
||||
|
||||
case "$term" in
|
||||
# Built-in commands
|
||||
if | then | else | elif | fi | for | while | until | do | done | case | 'esac' | in | function | select | time | coproc)
|
||||
echo "https://www.gnu.org/software/bash/manual/bash.html#Conditional-Constructs"
|
||||
;;
|
||||
echo | printf | read | declare | local | export | unset | set | shopt | alias | source | eval | exec | exit | return | break | continue | shift | trap | wait | kill | jobs | bg | fg | disown | suspend | logout | cd | pwd | pushd | popd | dirs | type | which | command | builtin | enable | help | hash | bind | complete | compgen | compopt)
|
||||
echo "https://www.gnu.org/software/bash/manual/bash.html#Shell-Builtin-Commands"
|
||||
;;
|
||||
# Common external commands
|
||||
grep | sed | awk | find | xargs | sort | uniq | cut | tr | head | tail | wc | cat | tee | diff | patch | tar | gzip | zip | curl | wget | ssh | scp | rsync | git | make | chmod | chown | chgrp | ln | cp | mv | rm | mkdir | rmdir | touch | ls | stat | file | df | du | free | top | ps | pkill | pgrep | nohup | screen | tmux)
|
||||
echo "https://man7.org/linux/man-pages/man1/$term.1.html"
|
||||
;;
|
||||
*)
|
||||
echo "https://www.gnu.org/software/bash/manual/bash.html"
|
||||
;;
|
||||
esac
|
||||
}
|
||||
|
||||
#==============================================================================
|
||||
# Get documentation URL for a term based on detected language
|
||||
#==============================================================================
|
||||
get_doc_url() {
|
||||
local term="$1"
|
||||
local lang="$2"
|
||||
local import_line="$3" # Optional: full import for context
|
||||
|
||||
# Try offline docs first
|
||||
local offline_result
|
||||
offline_result=$(lookup_offline "$term" "$lang" "$import_line")
|
||||
if [ -n "$offline_result" ]; then
|
||||
echo "$offline_result"
|
||||
return 0
|
||||
fi
|
||||
|
||||
# For TypeScript, also try JavaScript offline docs (most TS keywords are JS)
|
||||
if [[ $lang == "typescript" || $lang == "ts" || $lang == "tsx" ]]; then
|
||||
offline_result=$(lookup_offline "$term" "js" "$import_line")
|
||||
if [ -n "$offline_result" ]; then
|
||||
echo "$offline_result"
|
||||
return 0
|
||||
fi
|
||||
fi
|
||||
|
||||
# Fall back to online URLs
|
||||
case "$lang" in
|
||||
python | py)
|
||||
python_doc_url "$term"
|
||||
;;
|
||||
javascript | js | jsx)
|
||||
js_doc_url "$term"
|
||||
;;
|
||||
typescript | ts | tsx)
|
||||
# For TypeScript, try JS doc first (since most keywords are shared)
|
||||
# Only use TS-specific docs for TS-only features
|
||||
case "$term" in
|
||||
interface | type | enum | namespace | declare | readonly | abstract | implements | keyof | infer | as | is | asserts | satisfies | override | Partial | Required | Readonly | Record | Pick | Omit | Exclude | Extract | NonNullable | ReturnType | Parameters | InstanceType | Awaited)
|
||||
ts_doc_url "$term"
|
||||
;;
|
||||
*)
|
||||
js_doc_url "$term"
|
||||
;;
|
||||
esac
|
||||
;;
|
||||
c)
|
||||
c_doc_url "$term"
|
||||
;;
|
||||
cpp | c++ | cc | cxx)
|
||||
cpp_doc_url "$term"
|
||||
;;
|
||||
rust | rs)
|
||||
rust_doc_url "$term"
|
||||
;;
|
||||
go)
|
||||
go_doc_url "$term"
|
||||
;;
|
||||
ruby | rb)
|
||||
ruby_doc_url "$term"
|
||||
;;
|
||||
java)
|
||||
java_doc_url "$term"
|
||||
;;
|
||||
shell | bash | sh)
|
||||
shell_doc_url "$term"
|
||||
;;
|
||||
*)
|
||||
echo "https://devdocs.io/#q=$term"
|
||||
;;
|
||||
esac
|
||||
}
|
||||
|
||||
#==============================================================================
|
||||
# Detect primary language from results
|
||||
#==============================================================================
|
||||
detect_language() {
|
||||
if [ -f "$RESULTS_DIR/tokei_stats.txt" ]; then
|
||||
# Parse tokei output to find most used language
|
||||
grep -E "^\s+(Python|JavaScript|TypeScript|C\+\+|C |Rust|Go|Ruby|Java|Shell)" "$RESULTS_DIR/tokei_stats.txt" 2>/dev/null |
|
||||
head -1 |
|
||||
awk '{print tolower($1)}' |
|
||||
sed 's/c++/cpp/'
|
||||
else
|
||||
echo "unknown"
|
||||
fi
|
||||
}
|
||||
|
||||
#==============================================================================
|
||||
# Main Processing
|
||||
#==============================================================================
|
||||
@ -463,535 +104,11 @@ echo -e "${BLUE}═════════════════════
|
||||
echo ""
|
||||
# Patch for generate_study_materials.sh - use per-language files
|
||||
|
||||
#==============================================================================
|
||||
# Generate Documentation Links (Markdown)
|
||||
#==============================================================================
|
||||
echo -e "${YELLOW}Generating documentation links...${NC}"
|
||||
|
||||
cat >"$DOCS_FILE" <<'EOF'
|
||||
# Documentation Links for Code Review
|
||||
|
||||
This document contains links to official documentation for the most commonly used
|
||||
functions, keywords, and patterns found in the analyzed codebase.
|
||||
|
||||
**Note:** Items are grouped by language for accurate documentation links.
|
||||
|
||||
---
|
||||
|
||||
EOF
|
||||
|
||||
# Check for per-language files
|
||||
PER_LANG_DIR="$RESULTS_DIR/per_language"
|
||||
|
||||
if [ -d "$PER_LANG_DIR" ]; then
|
||||
echo -e "${GREEN}Using per-language analysis files${NC}"
|
||||
|
||||
# Map internal lang names to doc function names
|
||||
lang_to_doc() {
|
||||
case "$1" in
|
||||
c_cpp) echo "cpp" ;;
|
||||
javascript) echo "js" ;;
|
||||
typescript) echo "ts" ;;
|
||||
shell) echo "bash" ;;
|
||||
*) echo "$1" ;;
|
||||
esac
|
||||
}
|
||||
|
||||
# Process keywords by language
|
||||
{
|
||||
echo "## Language Keywords"
|
||||
echo ""
|
||||
} >>"$DOCS_FILE"
|
||||
|
||||
for keyword_file in "$PER_LANG_DIR"/keywords_*.txt; do
|
||||
[ ! -f "$keyword_file" ] && continue
|
||||
[ ! -s "$keyword_file" ] && continue
|
||||
|
||||
# Extract language name from filename
|
||||
lang=$(basename "$keyword_file" | sed 's/keywords_//; s/\.txt//')
|
||||
doc_lang=$(lang_to_doc "$lang")
|
||||
|
||||
# Format language name for display
|
||||
case "$lang" in
|
||||
c_cpp) display_lang="C/C++" ;;
|
||||
javascript) display_lang="JavaScript" ;;
|
||||
typescript) display_lang="TypeScript" ;;
|
||||
python) display_lang="Python" ;;
|
||||
rust) display_lang="Rust" ;;
|
||||
go) display_lang="Go" ;;
|
||||
ruby) display_lang="Ruby" ;;
|
||||
java) display_lang="Java" ;;
|
||||
shell) display_lang="Shell/Bash" ;;
|
||||
*) display_lang="$lang" ;;
|
||||
esac
|
||||
|
||||
{
|
||||
echo "### $display_lang Keywords"
|
||||
echo ""
|
||||
echo "| Keyword | Count | Documentation |"
|
||||
echo "|---------|-------|---------------|"
|
||||
} >>"$DOCS_FILE"
|
||||
|
||||
head -n "$TOP_N" "$keyword_file" | while read -r count term; do
|
||||
[ -z "$term" ] && continue
|
||||
[[ $term =~ ^[#] ]] && continue # Skip comment lines
|
||||
url=$(get_doc_url "$term" "$doc_lang")
|
||||
echo "| \`$term\` | $count | [docs]($url) |" >>"$DOCS_FILE"
|
||||
done
|
||||
echo "" >>"$DOCS_FILE"
|
||||
done
|
||||
|
||||
# Process functions by language
|
||||
{
|
||||
echo "## Function/Method Calls"
|
||||
echo ""
|
||||
} >>"$DOCS_FILE"
|
||||
|
||||
for func_file in "$PER_LANG_DIR"/functions_*.txt; do
|
||||
[ ! -f "$func_file" ] && continue
|
||||
[ ! -s "$func_file" ] && continue
|
||||
|
||||
lang=$(basename "$func_file" | sed 's/functions_//; s/\.txt//')
|
||||
doc_lang=$(lang_to_doc "$lang")
|
||||
|
||||
case "$lang" in
|
||||
c_cpp) display_lang="C/C++" ;;
|
||||
javascript) display_lang="JavaScript" ;;
|
||||
typescript) display_lang="TypeScript" ;;
|
||||
python) display_lang="Python" ;;
|
||||
rust) display_lang="Rust" ;;
|
||||
go) display_lang="Go" ;;
|
||||
ruby) display_lang="Ruby" ;;
|
||||
java) display_lang="Java" ;;
|
||||
shell) display_lang="Shell/Bash" ;;
|
||||
*) display_lang="$lang" ;;
|
||||
esac
|
||||
|
||||
{
|
||||
echo "### $display_lang Functions"
|
||||
echo ""
|
||||
echo "| Function | Count | Documentation |"
|
||||
echo "|----------|-------|---------------|"
|
||||
} >>"$DOCS_FILE"
|
||||
|
||||
head -n "$TOP_N" "$func_file" | while read -r count term; do
|
||||
[ -z "$term" ] && continue
|
||||
[[ $term =~ ^(if|for|while|switch|catch|elif)$ ]] && continue
|
||||
url=$(get_doc_url "$term" "$doc_lang")
|
||||
echo "| \`$term()\` | $count | [docs]($url) |" >>"$DOCS_FILE"
|
||||
done
|
||||
echo "" >>"$DOCS_FILE"
|
||||
done
|
||||
|
||||
# Process imports by language
|
||||
{
|
||||
echo "## Imports/Includes"
|
||||
echo ""
|
||||
} >>"$DOCS_FILE"
|
||||
|
||||
for import_file in "$PER_LANG_DIR"/imports_*.txt; do
|
||||
[ ! -f "$import_file" ] && continue
|
||||
[ ! -s "$import_file" ] && continue
|
||||
|
||||
lang=$(basename "$import_file" | sed 's/imports_//; s/\.txt//')
|
||||
doc_lang=$(lang_to_doc "$lang")
|
||||
|
||||
case "$lang" in
|
||||
c_cpp) display_lang="C/C++ (#include)" ;;
|
||||
javascript) display_lang="JavaScript (import/require)" ;;
|
||||
typescript) display_lang="TypeScript (import)" ;;
|
||||
python) display_lang="Python (import/from)" ;;
|
||||
rust) display_lang="Rust (use)" ;;
|
||||
go) display_lang="Go (import)" ;;
|
||||
ruby) display_lang="Ruby (require)" ;;
|
||||
java) display_lang="Java (import)" ;;
|
||||
shell) display_lang="Shell (source)" ;;
|
||||
*) display_lang="$lang" ;;
|
||||
esac
|
||||
|
||||
{
|
||||
echo "### $display_lang"
|
||||
echo ""
|
||||
echo "| Import | Count | Documentation |"
|
||||
echo "|--------|-------|---------------|"
|
||||
} >>"$DOCS_FILE"
|
||||
|
||||
head -20 "$import_file" | while read -r count import; do
|
||||
[ -z "$import" ] && continue
|
||||
# For offline lookup, pass the full import line for better context
|
||||
url=$(get_doc_url "" "$doc_lang" "$import")
|
||||
if [ -z "$url" ] || [[ $url == *"search.html"* ]]; then
|
||||
# Fallback: extract module and try again
|
||||
module=$(echo "$import" | sed -E 's/.*[<"]([^">]+)[">].*/\1/' | sed 's|.*/||' | sed 's/\..*$//')
|
||||
url=$(get_doc_url "$module" "$doc_lang")
|
||||
fi
|
||||
import_escaped="${import//|/\\|}"
|
||||
echo "| \`$import_escaped\` | $count | [docs]($url) |" >>"$DOCS_FILE"
|
||||
done
|
||||
echo "" >>"$DOCS_FILE"
|
||||
done
|
||||
|
||||
else
|
||||
# Fallback to combined files (old behavior)
|
||||
echo -e "${YELLOW}No per-language files found, using combined analysis${NC}"
|
||||
|
||||
if [ -f "$RESULTS_DIR/grep_keywords.txt" ]; then
|
||||
{
|
||||
echo "## Language Keywords"
|
||||
echo ""
|
||||
echo "| Keyword | Count | Documentation |"
|
||||
echo "|---------|-------|---------------|"
|
||||
} >>"$DOCS_FILE"
|
||||
|
||||
head -n "$TOP_N" "$RESULTS_DIR/grep_keywords.txt" | while read -r count term; do
|
||||
[ -z "$term" ] && continue
|
||||
url=$(get_doc_url "$term" "$PRIMARY_LANG")
|
||||
echo "| \`$term\` | $count | [docs]($url) |" >>"$DOCS_FILE"
|
||||
done
|
||||
echo "" >>"$DOCS_FILE"
|
||||
fi
|
||||
|
||||
if [ -f "$RESULTS_DIR/grep_function_calls.txt" ]; then
|
||||
{
|
||||
echo "## Function/Method Calls"
|
||||
echo ""
|
||||
echo "| Function | Count | Documentation |"
|
||||
echo "|----------|-------|---------------|"
|
||||
} >>"$DOCS_FILE"
|
||||
|
||||
head -n "$TOP_N" "$RESULTS_DIR/grep_function_calls.txt" | while read -r count term; do
|
||||
[ -z "$term" ] && continue
|
||||
[[ $term =~ ^(if|for|while|switch|catch)$ ]] && continue
|
||||
url=$(get_doc_url "$term" "$PRIMARY_LANG")
|
||||
echo "| \`$term()\` | $count | [docs]($url) |" >>"$DOCS_FILE"
|
||||
done
|
||||
echo "" >>"$DOCS_FILE"
|
||||
fi
|
||||
|
||||
if [ -f "$RESULTS_DIR/grep_imports.txt" ]; then
|
||||
{
|
||||
echo "## Imports/Includes"
|
||||
echo ""
|
||||
echo "| Import | Count | Documentation |"
|
||||
echo "|--------|-------|---------------|"
|
||||
} >>"$DOCS_FILE"
|
||||
|
||||
head -20 "$RESULTS_DIR/grep_imports.txt" | while read -r count import; do
|
||||
[ -z "$import" ] && continue
|
||||
module=$(echo "$import" | sed -E 's/.*[<"]([^">]+)[">].*/\1/' | sed 's|.*/||' | sed 's/\..*$//')
|
||||
url=$(get_doc_url "$module" "$PRIMARY_LANG")
|
||||
import_escaped="${import//|/\\|}"
|
||||
echo "| \`$import_escaped\` | $count | [docs]($url) |" >>"$DOCS_FILE"
|
||||
done
|
||||
echo "" >>"$DOCS_FILE"
|
||||
fi
|
||||
fi
|
||||
|
||||
{
|
||||
echo ""
|
||||
echo "---"
|
||||
echo "*Generated by analyze_repo.sh + generate_study_materials.sh*"
|
||||
} >>"$DOCS_FILE"
|
||||
|
||||
echo -e "${GREEN}Created: $DOCS_FILE${NC}"
|
||||
#==============================================================================
|
||||
# Generate Anki Cards (Tab-separated for import)
|
||||
#==============================================================================
|
||||
echo -e "${YELLOW}Generating Anki cards...${NC}"
|
||||
|
||||
cat >"$ANKI_FILE" <<'EOF'
|
||||
# Anki Import File
|
||||
# Format: Front<TAB>Back<TAB>Tags
|
||||
# Import with: File -> Import, select "Fields separated by: Tab"
|
||||
#
|
||||
# Card Types:
|
||||
# 1. "What does X do?" - For functions/methods
|
||||
# 2. "When to use X?" - For keywords/patterns
|
||||
# 3. "What is the syntax for X?" - For language constructs
|
||||
#
|
||||
EOF
|
||||
|
||||
# Generate cards for top keywords
|
||||
if [ -f "$RESULTS_DIR/grep_keywords.txt" ]; then
|
||||
echo "# Keywords" >>"$ANKI_FILE"
|
||||
head -n "$TOP_N" "$RESULTS_DIR/grep_keywords.txt" | while read -r count term; do
|
||||
[ -z "$term" ] && continue
|
||||
url=$(get_doc_url "$term" "$PRIMARY_LANG")
|
||||
|
||||
# Create different card types based on term type
|
||||
case "$term" in
|
||||
if | else | elif | elseif | switch | case | match)
|
||||
echo -e "What is the purpose of \`$term\` in $PRIMARY_LANG?\tConditional control flow - executes code based on boolean conditions. See: $url\t${PRIMARY_LANG}::keywords::control-flow" >>"$ANKI_FILE"
|
||||
;;
|
||||
for | while | loop | do | until)
|
||||
echo -e "What is the purpose of \`$term\` in $PRIMARY_LANG?\tLoop construct - repeats code execution. See: $url\t${PRIMARY_LANG}::keywords::loops" >>"$ANKI_FILE"
|
||||
;;
|
||||
try | except | catch | finally | raise | throw)
|
||||
echo -e "What is the purpose of \`$term\` in $PRIMARY_LANG?\tException handling - manages errors and exceptional conditions. See: $url\t${PRIMARY_LANG}::keywords::exceptions" >>"$ANKI_FILE"
|
||||
;;
|
||||
class | struct | interface | trait | impl)
|
||||
echo -e "What is the purpose of \`$term\` in $PRIMARY_LANG?\tType definition - defines custom data structures. See: $url\t${PRIMARY_LANG}::keywords::types" >>"$ANKI_FILE"
|
||||
;;
|
||||
def | fn | func | function)
|
||||
echo -e "What is the purpose of \`$term\` in $PRIMARY_LANG?\tFunction definition - declares a reusable block of code. See: $url\t${PRIMARY_LANG}::keywords::functions" >>"$ANKI_FILE"
|
||||
;;
|
||||
import | from | use | require | include)
|
||||
echo -e "What is the purpose of \`$term\` in $PRIMARY_LANG?\tModule import - brings external code into current scope. See: $url\t${PRIMARY_LANG}::keywords::modules" >>"$ANKI_FILE"
|
||||
;;
|
||||
async | await | yield)
|
||||
echo -e "What is the purpose of \`$term\` in $PRIMARY_LANG?\tAsynchronous programming - handles concurrent operations. See: $url\t${PRIMARY_LANG}::keywords::async" >>"$ANKI_FILE"
|
||||
;;
|
||||
*)
|
||||
echo -e "What does the keyword \`$term\` do in $PRIMARY_LANG?\t[FILL: Look up at $url]\t${PRIMARY_LANG}::keywords" >>"$ANKI_FILE"
|
||||
;;
|
||||
esac
|
||||
done
|
||||
fi
|
||||
|
||||
# Generate cards for top functions
|
||||
if [ -f "$RESULTS_DIR/grep_function_calls.txt" ]; then
|
||||
{
|
||||
echo ""
|
||||
echo "# Functions"
|
||||
} >>"$ANKI_FILE"
|
||||
head -n "$TOP_N" "$RESULTS_DIR/grep_function_calls.txt" | while read -r count term; do
|
||||
[ -z "$term" ] && continue
|
||||
[[ $term =~ ^(if|for|while|switch|catch)$ ]] && continue
|
||||
url=$(get_doc_url "$term" "$PRIMARY_LANG")
|
||||
|
||||
echo -e "What does \`$term()\` do in $PRIMARY_LANG? (Used $count times)\t[FILL: Look up at $url]\t${PRIMARY_LANG}::functions" >>"$ANKI_FILE"
|
||||
done
|
||||
fi
|
||||
|
||||
echo -e "${GREEN}Created: $ANKI_FILE${NC}"
|
||||
|
||||
#==============================================================================
|
||||
# Generate LLM Prompt for Anki Card Generation
|
||||
#==============================================================================
|
||||
echo -e "${YELLOW}Generating LLM prompt...${NC}"
|
||||
|
||||
# Helper function to get doc link for a term
|
||||
get_llm_doc_link() {
|
||||
local term="$1"
|
||||
local lang="$2"
|
||||
local is_import="$3" # "true" if it's an import line
|
||||
|
||||
# Check if it's an internal/project-specific item
|
||||
if [[ $term =~ ^@/ ]] || [[ $term =~ ^\./ ]] || [[ $term =~ ^app\. ]] || [[ $term =~ ^src/ ]] || [[ $term =~ from\ \'@/ ]] || [[ $term =~ from\ \'\./ ]]; then
|
||||
echo "[INTERNAL - SKIP]"
|
||||
return
|
||||
fi
|
||||
|
||||
# Try offline lookup
|
||||
local offline_result
|
||||
if [ "$is_import" = "true" ]; then
|
||||
offline_result=$("$LOOKUP_SCRIPT" --import "$term" "$lang" 2>/dev/null | grep "^/" | head -1)
|
||||
else
|
||||
offline_result=$("$LOOKUP_SCRIPT" "$term" "$lang" 2>/dev/null | grep "^File:" | head -1 | sed 's/^File: //')
|
||||
fi
|
||||
|
||||
if [ -n "$offline_result" ]; then
|
||||
echo "$offline_result"
|
||||
else
|
||||
echo "[NO OFFLINE DOC]"
|
||||
fi
|
||||
}
|
||||
|
||||
# Generate keywords with doc links
|
||||
generate_keywords_with_docs() {
|
||||
local keywords_file="$RESULTS_DIR/grep_keywords.txt"
|
||||
[ ! -f "$keywords_file" ] && echo "No keywords found" && return
|
||||
|
||||
head -n "$TOP_N" "$keywords_file" | grep -v '^#' | while read -r line; do
|
||||
local count
|
||||
count=$(echo "$line" | awk '{print $1}')
|
||||
local keyword
|
||||
keyword=$(echo "$line" | awk '{print $2}')
|
||||
[ -z "$keyword" ] && continue
|
||||
local doc_link
|
||||
doc_link=$(get_llm_doc_link "$keyword" "$PRIMARY_LANG" "false")
|
||||
echo "$count $keyword → $doc_link"
|
||||
done
|
||||
}
|
||||
|
||||
# Generate functions with doc links
|
||||
generate_functions_with_docs() {
|
||||
local functions_file="$RESULTS_DIR/grep_function_calls.txt"
|
||||
[ ! -f "$functions_file" ] && echo "No functions found" && return
|
||||
|
||||
head -n "$TOP_N" "$functions_file" | grep -v '^#' | while read -r line; do
|
||||
local count
|
||||
count=$(echo "$line" | awk '{print $1}')
|
||||
local func
|
||||
func=$(echo "$line" | awk '{print $2}')
|
||||
|
||||
# Skip single-letter functions (minified code) or empty
|
||||
if [ -z "$func" ] || [ ${#func} -le 1 ]; then
|
||||
continue
|
||||
fi
|
||||
|
||||
local doc_link
|
||||
doc_link=$(get_llm_doc_link "$func" "$PRIMARY_LANG" "false")
|
||||
echo "$count $func() → $doc_link"
|
||||
done
|
||||
}
|
||||
|
||||
# Generate imports with doc links
|
||||
generate_imports_with_docs() {
|
||||
local imports_file="$RESULTS_DIR/grep_imports.txt"
|
||||
[ ! -f "$imports_file" ] && echo "No imports found" && return
|
||||
|
||||
head -20 "$imports_file" | grep -v '^#' | while read -r line; do
|
||||
local count
|
||||
count=$(echo "$line" | awk '{print $1}')
|
||||
local import_stmt
|
||||
import_stmt=$(echo "$line" | cut -d' ' -f2-)
|
||||
[ -z "$import_stmt" ] && continue
|
||||
|
||||
# Check if internal import
|
||||
if [[ $import_stmt =~ @/ ]] || [[ $import_stmt =~ \./ ]] || [[ $import_stmt =~ from\ app\. ]] || [[ $import_stmt =~ from\ src\. ]]; then
|
||||
echo "$count $import_stmt → [INTERNAL - SKIP]"
|
||||
else
|
||||
local doc_link
|
||||
doc_link=$(get_llm_doc_link "$import_stmt" "$PRIMARY_LANG" "true")
|
||||
echo "$count $import_stmt → $doc_link"
|
||||
fi
|
||||
done
|
||||
}
|
||||
|
||||
cat >"$LLM_PROMPT_FILE" <<'PROMPT_HEADER'
|
||||
# LLM Prompt: Generate Anki Flashcards
|
||||
|
||||
You are creating Anki flashcards from code analysis.
|
||||
|
||||
## CRITICAL INSTRUCTIONS
|
||||
|
||||
1. **READ DOCS VIA TERMINAL** - Use the `cat` command to read each .md file:
|
||||
```
|
||||
cat /home/kuhy/.local/share/offline-docs/mdn-content/files/en-us/web/javascript/reference/statements/const/index.md
|
||||
```
|
||||
2. **DO NOT USE YOUR OWN KNOWLEDGE** - Base flashcards ONLY on the content you read from the files
|
||||
3. **IF YOU CANNOT READ A FILE** - Report: "ERROR: Cannot read [path]" and skip that item
|
||||
4. **NEVER FALL BACK TO GENERAL KNOWLEDGE** - If you can't read the file, skip it entirely
|
||||
5. **READ ONE FILE AT A TIME** - Run cat for each topic before creating its flashcards
|
||||
|
||||
PROMPT_HEADER
|
||||
|
||||
cat >>"$LLM_PROMPT_FILE" <<EOF
|
||||
## Context
|
||||
- Primary Language: **$PRIMARY_LANG**
|
||||
|
||||
## Top Keywords (by frequency)
|
||||
Items marked \`[INTERNAL - SKIP]\` are project-specific - skip them.
|
||||
Items marked \`[NO OFFLINE DOC]\` have no offline documentation - use online docs or skip.
|
||||
Other items have offline doc paths you can reference.
|
||||
|
||||
\`\`\`
|
||||
$(generate_keywords_with_docs)
|
||||
\`\`\`
|
||||
|
||||
## Top Functions/Methods (by frequency)
|
||||
\`\`\`
|
||||
$(generate_functions_with_docs)
|
||||
\`\`\`
|
||||
|
||||
## Top Imports/Includes
|
||||
\`\`\`
|
||||
$(generate_imports_with_docs)
|
||||
\`\`\`
|
||||
EOF
|
||||
|
||||
cat >>"$LLM_PROMPT_FILE" <<'PROMPT_FOOTER'
|
||||
|
||||
## Guidelines
|
||||
|
||||
**CRITICAL - Keep answers EXTREMELY short:**
|
||||
- Most answers should be **1-2 words** or **1 sentence**
|
||||
- It's common and expected for an answer to be just: "Returns an array" or "Immutable"
|
||||
- 2 sentences = longer answer, 3 sentences = absolute maximum (rare)
|
||||
- Each flashcard tests ONE atomic piece of knowledge
|
||||
|
||||
**NO DUPLICATES:**
|
||||
- Before creating a card, check if you already created a similar question
|
||||
- Each unique fact should appear in EXACTLY ONE card
|
||||
- Do NOT create multiple cards asking the same thing with slightly different wording
|
||||
|
||||
**What to include:**
|
||||
- Concept cards: "What is X?" / "What does X do?"
|
||||
- Syntax cards: "How do you write X?" (brief code snippet)
|
||||
- Comparison cards: "X vs Y - what's the difference?"
|
||||
|
||||
**What to SKIP (do NOT create cards for):**
|
||||
- MDN frontmatter fields: title, slug, page-type, browser-compat, spec-urls
|
||||
- YAML metadata between `---` markers at the start of files
|
||||
- Any line that looks like metadata (key: value at start of doc)
|
||||
- Empty answers - if you can't find content for the back, skip the card entirely
|
||||
|
||||
**FINAL CARD FOR EACH TOPIC (EXCEPTION TO SHORT ANSWER RULE):**
|
||||
- Add EXACTLY ONE full documentation card per topic (no duplicates!)
|
||||
- Question: `[Topic] - Full MDN Documentation`
|
||||
- Answer: Copy the .md file content STARTING AFTER the `---` frontmatter block
|
||||
- Skip the YAML frontmatter (everything between the first two `---` lines)
|
||||
- Do NOT create this card twice for the same topic
|
||||
|
||||
**Skipped items - please review:**
|
||||
- Items marked `[INTERNAL - SKIP]` are project-specific utilities - I skipped them
|
||||
- Items marked `[NO OFFLINE DOC]` are third-party libraries without bundled docs
|
||||
- If you want flashcards for skipped items, tell me which ones to include
|
||||
|
||||
## OUTPUT: CREATE AN ANKI FILE
|
||||
|
||||
**CREATE A FILE DIRECTLY** - Do not just output text. Use your file creation tool to create:
|
||||
|
||||
**File path:** `~/.local/share/study-materials/anki_generated.txt`
|
||||
|
||||
**Format:** Tab-separated values (TSV) with Anki metadata headers:
|
||||
|
||||
```
|
||||
#separator:tab
|
||||
#deck:CodeStudy::JavaScript
|
||||
#notetype:CodeCard
|
||||
#columns:Front Back Tags
|
||||
What does <code>const</code> declare?Block-scoped variables with immutable bindings.javascript declarations
|
||||
```
|
||||
|
||||
**Required headers at top of file:**
|
||||
- `#separator:tab` - Specifies tab as delimiter
|
||||
- `#deck:CodeStudy::[Language]` - Creates deck "CodeStudy" with sub-deck for language (e.g., CodeStudy::JavaScript)
|
||||
- `#notetype:CodeCard` - Uses custom note type "CodeCard" (Anki will create if doesn't exist)
|
||||
- `#columns:Front Back Tags` - Column headers (tab-separated)
|
||||
|
||||
**Rules:**
|
||||
- Use ACTUAL `<code>` tags (not escaped <code>)
|
||||
- Use `<br>` for line breaks within fields
|
||||
- Use `<pre>` for code blocks
|
||||
- Tags are space-separated
|
||||
- Escape any literal tabs within content as spaces
|
||||
|
||||
**Example file content:**
|
||||
```
|
||||
#separator:tab
|
||||
#deck:CodeStudy::JavaScript
|
||||
#notetype:CodeCard
|
||||
#columns:Front Back Tags
|
||||
What does <code>const</code> declare?Block-scoped variables with immutable bindings.javascript declarations
|
||||
Can <code>const</code> be reassigned?No, throws TypeError.javascript declarations
|
||||
const - Full Documentation<pre>[ENTIRE CONTENT OF const/index.md FILE]</pre>javascript declarations full-doc
|
||||
```
|
||||
|
||||
**After creating the file**, tell the user:
|
||||
- File created at: ~/.local/share/study-materials/anki_generated.txt
|
||||
- Import in Anki: File → Import → select the file
|
||||
- Deck: CodeStudy::[Language], Note type: CodeCard
|
||||
---
|
||||
|
||||
**Important:**
|
||||
- Process only 5-10 items at a time to maintain quality
|
||||
- Focus on items with offline documentation paths
|
||||
- Output ONLY the TSV lines, no extra formatting or markdown
|
||||
PROMPT_FOOTER
|
||||
|
||||
echo -e "${GREEN}Created: $LLM_PROMPT_FILE${NC}"
|
||||
# The three generation phases, in the order their outputs reference each
|
||||
# other. Defined above and called here so the file can be split into libs.
|
||||
generate_doc_links
|
||||
generate_anki_cards
|
||||
generate_llm_prompt
|
||||
|
||||
#==============================================================================
|
||||
# Summary
|
||||
|
||||
132
linux_configuration/scripts/single_use/utils/lib/study_doc_lookup.sh
Executable file
132
linux_configuration/scripts/single_use/utils/lib/study_doc_lookup.sh
Executable file
@ -0,0 +1,132 @@
|
||||
#!/usr/bin/env bash
|
||||
# lib/study_doc_lookup.sh — resolve a term to documentation.
|
||||
#
|
||||
# get_doc_url dispatches to the per-language builders in study_doc_urls*.sh;
|
||||
# lookup_offline prefers a local mirror when one is installed, so a generated
|
||||
# card can cite a file an assistant can actually read rather than a URL it
|
||||
# would have to fetch. detect_language picks the primary language out of the
|
||||
# tokei stats the analysis step wrote.
|
||||
|
||||
#==============================================================================
|
||||
# Offline Documentation Lookup (preferred if available)
|
||||
#==============================================================================
|
||||
lookup_offline() {
|
||||
local term="$1"
|
||||
local lang="$2"
|
||||
# Optional: the full import line, for import-aware lookups. Documented as
|
||||
# optional and genuinely called without it, so it is defaulted rather than
|
||||
# required -- under `set -u` a bare "$3" aborts instead.
|
||||
local import_line="${3:-}"
|
||||
|
||||
if ! $USE_OFFLINE_DOCS; then
|
||||
return 1
|
||||
fi
|
||||
|
||||
local result
|
||||
if [ -n "$import_line" ]; then
|
||||
# Use import-aware lookup - get the line with the file path
|
||||
result=$("$LOOKUP_SCRIPT" --import "$import_line" "$lang" 2>/dev/null | grep "^/" | head -1)
|
||||
else
|
||||
result=$("$LOOKUP_SCRIPT" "$term" "$lang" 2>/dev/null | grep "^File:" | head -1 | sed 's/^File: //')
|
||||
fi
|
||||
|
||||
if [ -n "$result" ]; then
|
||||
# Extract file path (before the | separator)
|
||||
local file_path
|
||||
file_path=$(echo "$result" | cut -d'|' -f1)
|
||||
if [ -n "$file_path" ]; then
|
||||
echo "$file_path"
|
||||
return 0
|
||||
fi
|
||||
fi
|
||||
|
||||
return 1
|
||||
}
|
||||
|
||||
#==============================================================================
|
||||
# Get documentation URL for a term based on detected language
|
||||
#==============================================================================
|
||||
get_doc_url() {
|
||||
local term="$1"
|
||||
local lang="$2"
|
||||
# Optional, as above: 8 of the 9 call sites pass only a term and a language.
|
||||
local import_line="${3:-}"
|
||||
|
||||
# Try offline docs first
|
||||
local offline_result
|
||||
offline_result=$(lookup_offline "$term" "$lang" "$import_line")
|
||||
if [ -n "$offline_result" ]; then
|
||||
echo "$offline_result"
|
||||
return 0
|
||||
fi
|
||||
|
||||
# For TypeScript, also try JavaScript offline docs (most TS keywords are JS)
|
||||
if [[ $lang == "typescript" || $lang == "ts" || $lang == "tsx" ]]; then
|
||||
offline_result=$(lookup_offline "$term" "js" "$import_line")
|
||||
if [ -n "$offline_result" ]; then
|
||||
echo "$offline_result"
|
||||
return 0
|
||||
fi
|
||||
fi
|
||||
|
||||
# Fall back to online URLs
|
||||
case "$lang" in
|
||||
python | py)
|
||||
python_doc_url "$term"
|
||||
;;
|
||||
javascript | js | jsx)
|
||||
js_doc_url "$term"
|
||||
;;
|
||||
typescript | ts | tsx)
|
||||
# For TypeScript, try JS doc first (since most keywords are shared)
|
||||
# Only use TS-specific docs for TS-only features
|
||||
case "$term" in
|
||||
interface | type | enum | namespace | declare | readonly | abstract | implements | keyof | infer | as | is | asserts | satisfies | override | Partial | Required | Readonly | Record | Pick | Omit | Exclude | Extract | NonNullable | ReturnType | Parameters | InstanceType | Awaited)
|
||||
ts_doc_url "$term"
|
||||
;;
|
||||
*)
|
||||
js_doc_url "$term"
|
||||
;;
|
||||
esac
|
||||
;;
|
||||
c)
|
||||
c_doc_url "$term"
|
||||
;;
|
||||
cpp | c++ | cc | cxx)
|
||||
cpp_doc_url "$term"
|
||||
;;
|
||||
rust | rs)
|
||||
rust_doc_url "$term"
|
||||
;;
|
||||
go)
|
||||
go_doc_url "$term"
|
||||
;;
|
||||
ruby | rb)
|
||||
ruby_doc_url "$term"
|
||||
;;
|
||||
java)
|
||||
java_doc_url "$term"
|
||||
;;
|
||||
shell | bash | sh)
|
||||
shell_doc_url "$term"
|
||||
;;
|
||||
*)
|
||||
echo "https://devdocs.io/#q=$term"
|
||||
;;
|
||||
esac
|
||||
}
|
||||
|
||||
#==============================================================================
|
||||
# Detect primary language from results
|
||||
#==============================================================================
|
||||
detect_language() {
|
||||
if [ -f "$RESULTS_DIR/tokei_stats.txt" ]; then
|
||||
# Parse tokei output to find most used language
|
||||
grep -E "^\s+(Python|JavaScript|TypeScript|C\+\+|C |Rust|Go|Ruby|Java|Shell)" "$RESULTS_DIR/tokei_stats.txt" 2>/dev/null |
|
||||
head -1 |
|
||||
awk '{print tolower($1)}' |
|
||||
sed 's/c++/cpp/'
|
||||
else
|
||||
echo "unknown"
|
||||
fi
|
||||
}
|
||||
155
linux_configuration/scripts/single_use/utils/lib/study_doc_urls.sh
Executable file
155
linux_configuration/scripts/single_use/utils/lib/study_doc_urls.sh
Executable file
@ -0,0 +1,155 @@
|
||||
#!/usr/bin/env bash
|
||||
# lib/study_doc_urls.sh — per-language documentation URL builders for the
|
||||
# C-family, JS/TS and Python.
|
||||
#
|
||||
# Sourced by generate_study_materials.sh. Each takes a term and returns the
|
||||
# canonical online doc URL for it, or an empty string when the language has no
|
||||
# stable URL shape for that term.
|
||||
|
||||
# Python documentation
|
||||
python_doc_url() {
|
||||
local term="$1"
|
||||
# Category (keyword, builtin, module), reserved for future use and never
|
||||
# read. Defaulted rather than required: get_doc_url has always called this
|
||||
# with one argument, which only worked because the entry script runs under
|
||||
# `set -e` without `-u`, so "$2" silently expanded to empty. Any caller that
|
||||
# does enable `set -u` -- a test, or a future lib that sources this -- would
|
||||
# otherwise abort here on an argument nothing uses.
|
||||
local _type="${2:-}"
|
||||
|
||||
case "$term" in
|
||||
# Keywords
|
||||
if | else | elif | for | while | try | except | finally | with | as | import | from | def | class | return | yield | raise | pass | break | continue | and | or | not | in | is | lambda | global | nonlocal | assert | del | True | False | None | async | await)
|
||||
echo "https://docs.python.org/3/reference/compound_stmts.html"
|
||||
;;
|
||||
# Built-in functions
|
||||
print | len | range | type | str | int | float | list | dict | set | tuple | bool | open | input | format | sorted | reversed | enumerate | zip | map | filter | any | all | sum | min | max | abs | round | isinstance | issubclass | hasattr | getattr | setattr | delattr | callable | iter | next | super | property | staticmethod | classmethod | vars | dir | help | id | hash | repr | ascii | bin | hex | oct | chr | ord | eval | exec | compile)
|
||||
echo "https://docs.python.org/3/library/functions.html#$term"
|
||||
;;
|
||||
# Common modules
|
||||
os | sys | re | json | datetime | collections | itertools | functools | pathlib | subprocess | threading | multiprocessing | asyncio | typing | dataclasses | unittest | pytest | logging | argparse | configparser)
|
||||
echo "https://docs.python.org/3/library/$term.html"
|
||||
;;
|
||||
# Testing
|
||||
MagicMock | Mock | patch | PropertyMock)
|
||||
echo "https://docs.python.org/3/library/unittest.mock.html"
|
||||
;;
|
||||
*)
|
||||
echo "https://docs.python.org/3/search.html?q=$term"
|
||||
;;
|
||||
esac
|
||||
}
|
||||
|
||||
# JavaScript/TypeScript documentation (MDN)
|
||||
js_doc_url() {
|
||||
local term="$1"
|
||||
|
||||
case "$term" in
|
||||
# Keywords & statements
|
||||
if | else | for | while | do | switch | case | break | continue | return | throw | try | catch | finally | function | class | const | let | var | new | this | super | import | export | default | async | await | yield | typeof | instanceof | in | of | delete | void)
|
||||
echo "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements"
|
||||
;;
|
||||
# Global objects
|
||||
Array | Object | String | Number | Boolean | Symbol | Map | Set | WeakMap | WeakSet | Date | RegExp | Error | Promise | Proxy | Reflect | JSON | Math | Intl)
|
||||
echo "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/$term"
|
||||
;;
|
||||
# Array methods
|
||||
map | filter | reduce | forEach | find | findIndex | some | every | includes | indexOf | slice | splice | concat | join | push | pop | shift | unshift | sort | reverse | flat | flatMap)
|
||||
echo "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/$term"
|
||||
;;
|
||||
# String methods
|
||||
split | replace | match | search | substring | substr | toLowerCase | toUpperCase | trim | padStart | padEnd | startsWith | endsWith | charAt | charCodeAt)
|
||||
echo "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/$term"
|
||||
;;
|
||||
# Promise methods
|
||||
then | resolve | reject | all | race | allSettled | any)
|
||||
echo "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/$term"
|
||||
;;
|
||||
# Common Web APIs
|
||||
fetch | console | document | window | localStorage | sessionStorage | setTimeout | setInterval | addEventListener | querySelector | querySelectorAll)
|
||||
echo "https://developer.mozilla.org/en-US/docs/Web/API"
|
||||
;;
|
||||
*)
|
||||
echo "https://developer.mozilla.org/en-US/search?q=$term"
|
||||
;;
|
||||
esac
|
||||
}
|
||||
|
||||
# TypeScript-specific documentation
|
||||
ts_doc_url() {
|
||||
local term="$1"
|
||||
|
||||
case "$term" in
|
||||
interface | type | enum | namespace | declare | readonly | abstract | implements | extends | keyof | typeof | infer | as | is | asserts | satisfies | override)
|
||||
echo "https://www.typescriptlang.org/docs/handbook/2/everyday-types.html"
|
||||
;;
|
||||
Partial | Required | Readonly | Record | Pick | Omit | Exclude | Extract | NonNullable | ReturnType | Parameters | InstanceType | Awaited)
|
||||
echo "https://www.typescriptlang.org/docs/handbook/utility-types.html"
|
||||
;;
|
||||
*)
|
||||
# Fall back to JS docs for runtime features
|
||||
js_doc_url "$term"
|
||||
;;
|
||||
esac
|
||||
}
|
||||
|
||||
# C documentation
|
||||
c_doc_url() {
|
||||
local term="$1"
|
||||
|
||||
case "$term" in
|
||||
# Keywords
|
||||
if | else | for | while | do | switch | case | break | continue | return | goto | sizeof | typedef | struct | union | enum | const | static | extern | register | volatile | inline | restrict | _Bool | _Complex | _Imaginary | _Alignas | _Alignof | _Atomic | _Generic | _Noreturn | _Static_assert | _Thread_local)
|
||||
echo "https://en.cppreference.com/w/c/keyword/$term"
|
||||
;;
|
||||
# Standard library headers
|
||||
stdio | stdlib | string | math | time | ctype | stdint | stdbool | stddef | limits | float | errno | assert | signal | setjmp | stdarg | locale)
|
||||
echo "https://en.cppreference.com/w/c/header/${term}.h"
|
||||
;;
|
||||
# Common functions
|
||||
printf | fprintf | sprintf | snprintf | scanf | fscanf | sscanf | fopen | fclose | fread | fwrite | fgets | fputs | fseek | ftell | rewind | fflush)
|
||||
echo "https://en.cppreference.com/w/c/io"
|
||||
;;
|
||||
malloc | calloc | realloc | free | memcpy | memmove | memset | memcmp)
|
||||
echo "https://en.cppreference.com/w/c/memory"
|
||||
;;
|
||||
strlen | strcpy | strncpy | strcat | strncat | strcmp | strncmp | strchr | strrchr | strstr | strtok)
|
||||
echo "https://en.cppreference.com/w/c/string/byte"
|
||||
;;
|
||||
*)
|
||||
echo "https://en.cppreference.com/mwiki/index.php?search=$term"
|
||||
;;
|
||||
esac
|
||||
}
|
||||
|
||||
# C++ documentation
|
||||
cpp_doc_url() {
|
||||
local term="$1"
|
||||
|
||||
case "$term" in
|
||||
# C++ specific keywords
|
||||
class | public | private | protected | virtual | override | final | explicit | mutable | constexpr | consteval | constinit | concept | requires | co_await | co_yield | co_return | nullptr | noexcept | decltype | auto | template | typename | namespace | using | new | delete | throw | try | catch | static_cast | dynamic_cast | const_cast | reinterpret_cast)
|
||||
echo "https://en.cppreference.com/w/cpp/keyword/$term"
|
||||
;;
|
||||
# STL containers
|
||||
vector | list | deque | array | forward_list | set | map | unordered_set | unordered_map | multiset | multimap | stack | queue | priority_queue)
|
||||
echo "https://en.cppreference.com/w/cpp/container/$term"
|
||||
;;
|
||||
# STL algorithms
|
||||
sort | find | copy | move | transform | accumulate | count | remove | unique | reverse | rotate | shuffle | partition | merge | binary_search | lower_bound | upper_bound)
|
||||
echo "https://en.cppreference.com/w/cpp/algorithm/$term"
|
||||
;;
|
||||
# Smart pointers
|
||||
unique_ptr | shared_ptr | weak_ptr | make_unique | make_shared)
|
||||
echo "https://en.cppreference.com/w/cpp/memory/$term"
|
||||
;;
|
||||
# Common classes
|
||||
string | string_view | optional | variant | any | tuple | pair | function | bind | thread | mutex | future | promise | chrono)
|
||||
echo "https://en.cppreference.com/w/cpp/utility"
|
||||
;;
|
||||
*)
|
||||
# Try C docs as fallback
|
||||
c_doc_url "$term"
|
||||
;;
|
||||
esac
|
||||
}
|
||||
120
linux_configuration/scripts/single_use/utils/lib/study_doc_urls_more.sh
Executable file
120
linux_configuration/scripts/single_use/utils/lib/study_doc_urls_more.sh
Executable file
@ -0,0 +1,120 @@
|
||||
#!/usr/bin/env bash
|
||||
# lib/study_doc_urls_more.sh — documentation URL builders for Rust, Go, Ruby,
|
||||
# Java and shell.
|
||||
#
|
||||
# Split from study_doc_urls.sh purely to keep both files under the 250-line
|
||||
# cap; the two are one subject and are always sourced together.
|
||||
|
||||
# Rust documentation
|
||||
rust_doc_url() {
|
||||
local term="$1"
|
||||
|
||||
case "$term" in
|
||||
# Keywords
|
||||
fn | let | mut | const | static | if | else | match | loop | while | for | in | break | continue | return | struct | enum | impl | trait | type | where | pub | mod | use | crate | self | super | async | await | move | ref | dyn | unsafe | extern)
|
||||
echo "https://doc.rust-lang.org/std/keyword.$term.html"
|
||||
;;
|
||||
# Common types
|
||||
Option | Result | Vec | String | Box | Rc | Arc | Cell | RefCell | Mutex | RwLock | HashMap | HashSet | BTreeMap | BTreeSet)
|
||||
echo "https://doc.rust-lang.org/std/$term"
|
||||
;;
|
||||
# Traits
|
||||
Clone | Copy | Debug | Default | Eq | PartialEq | Ord | PartialOrd | Hash | Display | From | Into | AsRef | AsMut | Deref | DerefMut | Iterator | IntoIterator | Send | Sync)
|
||||
echo "https://doc.rust-lang.org/std/$term"
|
||||
;;
|
||||
# Macros
|
||||
println | print | format | vec | panic | assert | assert_eq | assert_ne | debug_assert | todo | unimplemented | unreachable)
|
||||
echo "https://doc.rust-lang.org/std/macro.$term.html"
|
||||
;;
|
||||
*)
|
||||
echo "https://doc.rust-lang.org/std/?search=$term"
|
||||
;;
|
||||
esac
|
||||
}
|
||||
|
||||
# Go documentation
|
||||
go_doc_url() {
|
||||
local term="$1"
|
||||
|
||||
case "$term" in
|
||||
# Keywords
|
||||
func | var | const | type | struct | interface | map | chan | go | select | defer | if | else | for | range | switch | case | default | break | continue | return | goto | fallthrough | package | import)
|
||||
echo "https://go.dev/ref/spec"
|
||||
;;
|
||||
# Built-in functions
|
||||
make | new | len | cap | append | copy | delete | close | panic | recover | print | println | complex | real | imag)
|
||||
echo "https://pkg.go.dev/builtin#$term"
|
||||
;;
|
||||
# Common packages
|
||||
fmt | os | io | net | http | json | time | strings | strconv | errors | context | sync | testing | reflect | regexp | sort | math | crypto | encoding | bufio | bytes | path | filepath)
|
||||
echo "https://pkg.go.dev/$term"
|
||||
;;
|
||||
*)
|
||||
echo "https://pkg.go.dev/search?q=$term"
|
||||
;;
|
||||
esac
|
||||
}
|
||||
|
||||
# Ruby documentation
|
||||
ruby_doc_url() {
|
||||
local term="$1"
|
||||
|
||||
case "$term" in
|
||||
# Keywords
|
||||
if | else | elsif | unless | case | when | while | until | for | do | end | begin | rescue | ensure | raise | return | break | next | redo | retry | yield | def | class | module | self | super | nil | true | false | and | or | not | in | then | alias | defined | __FILE__ | __LINE__ | __ENCODING__)
|
||||
echo "https://ruby-doc.org/docs/keywords/1.9/"
|
||||
;;
|
||||
# Core classes
|
||||
String | Array | Hash | Integer | Float | Symbol | Range | Regexp | Time | Date | File | Dir | IO | Proc | Lambda | Method | Thread | Mutex | Fiber)
|
||||
echo "https://ruby-doc.org/core/classes/$term.html"
|
||||
;;
|
||||
# Enumerable methods
|
||||
each | map | select | reject | find | reduce | inject | collect | detect | sort | sort_by | group_by | partition | any | all | none | one | count | first | last | take | drop)
|
||||
echo "https://ruby-doc.org/core/Enumerable.html"
|
||||
;;
|
||||
*)
|
||||
echo "https://ruby-doc.org/search.html?q=$term"
|
||||
;;
|
||||
esac
|
||||
}
|
||||
|
||||
# Java documentation
|
||||
java_doc_url() {
|
||||
local term="$1"
|
||||
|
||||
case "$term" in
|
||||
# Keywords
|
||||
if | else | for | while | do | switch | case | break | continue | return | throw | try | catch | finally | class | interface | enum | extends | implements | new | this | super | static | final | abstract | public | private | protected | void | null | true | false | instanceof | synchronized | volatile | transient | native | strictfp | assert | default | package | import)
|
||||
echo "https://docs.oracle.com/javase/tutorial/java/nutsandbolts/"
|
||||
;;
|
||||
# Common classes
|
||||
String | Integer | Long | Double | Float | Boolean | Character | Object | Class | System | Math | Arrays | Collections | List | ArrayList | LinkedList | Map | HashMap | TreeMap | Set | HashSet | TreeSet | Queue | Stack | Optional | Stream)
|
||||
echo "https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/lang/$term.html"
|
||||
;;
|
||||
*)
|
||||
echo "https://docs.oracle.com/en/java/javase/17/docs/api/search.html?q=$term"
|
||||
;;
|
||||
esac
|
||||
}
|
||||
|
||||
# Shell documentation
|
||||
shell_doc_url() {
|
||||
local term="$1"
|
||||
|
||||
case "$term" in
|
||||
# Built-in commands
|
||||
if | then | else | elif | fi | for | while | until | do | done | case | 'esac' | in | function | select | time | coproc)
|
||||
echo "https://www.gnu.org/software/bash/manual/bash.html#Conditional-Constructs"
|
||||
;;
|
||||
echo | printf | read | declare | local | export | unset | set | shopt | alias | source | eval | exec | exit | return | break | continue | shift | trap | wait | kill | jobs | bg | fg | disown | suspend | logout | cd | pwd | pushd | popd | dirs | type | which | command | builtin | enable | help | hash | bind | complete | compgen | compopt)
|
||||
echo "https://www.gnu.org/software/bash/manual/bash.html#Shell-Builtin-Commands"
|
||||
;;
|
||||
# Common external commands
|
||||
grep | sed | awk | find | xargs | sort | uniq | cut | tr | head | tail | wc | cat | tee | diff | patch | tar | gzip | zip | curl | wget | ssh | scp | rsync | git | make | chmod | chown | chgrp | ln | cp | mv | rm | mkdir | rmdir | touch | ls | stat | file | df | du | free | top | ps | pkill | pgrep | nohup | screen | tmux)
|
||||
echo "https://man7.org/linux/man-pages/man1/$term.1.html"
|
||||
;;
|
||||
*)
|
||||
echo "https://www.gnu.org/software/bash/manual/bash.html"
|
||||
;;
|
||||
esac
|
||||
}
|
||||
79
linux_configuration/scripts/single_use/utils/lib/study_gen_anki.sh
Executable file
79
linux_configuration/scripts/single_use/utils/lib/study_gen_anki.sh
Executable file
@ -0,0 +1,79 @@
|
||||
#!/usr/bin/env bash
|
||||
# lib/study_gen_anki.sh — write anki_cards.txt, the tab-separated import file:
|
||||
# one card per top keyword and one per top function call.
|
||||
|
||||
# Write the tab-separated Anki import file: one card per top keyword and
|
||||
# one per top function call.
|
||||
generate_anki_cards() {
|
||||
#==============================================================================
|
||||
# Generate Anki Cards (Tab-separated for import)
|
||||
#==============================================================================
|
||||
echo -e "${YELLOW}Generating Anki cards...${NC}"
|
||||
|
||||
cat >"$ANKI_FILE" <<'EOF'
|
||||
# Anki Import File
|
||||
# Format: Front<TAB>Back<TAB>Tags
|
||||
# Import with: File -> Import, select "Fields separated by: Tab"
|
||||
#
|
||||
# Card Types:
|
||||
# 1. "What does X do?" - For functions/methods
|
||||
# 2. "When to use X?" - For keywords/patterns
|
||||
# 3. "What is the syntax for X?" - For language constructs
|
||||
#
|
||||
EOF
|
||||
|
||||
# Generate cards for top keywords
|
||||
if [ -f "$RESULTS_DIR/grep_keywords.txt" ]; then
|
||||
echo "# Keywords" >>"$ANKI_FILE"
|
||||
{ grep -v '^#' "$RESULTS_DIR/grep_keywords.txt" || true; } | head -n "$TOP_N" | while read -r count term; do
|
||||
[ -z "$term" ] && continue
|
||||
url=$(get_doc_url "$term" "$PRIMARY_LANG")
|
||||
|
||||
# Create different card types based on term type
|
||||
case "$term" in
|
||||
if | else | elif | elseif | switch | case | match)
|
||||
echo -e "What is the purpose of \`$term\` in $PRIMARY_LANG?\tConditional control flow - executes code based on boolean conditions. See: $url\t${PRIMARY_LANG}::keywords::control-flow" >>"$ANKI_FILE"
|
||||
;;
|
||||
for | while | loop | do | until)
|
||||
echo -e "What is the purpose of \`$term\` in $PRIMARY_LANG?\tLoop construct - repeats code execution. See: $url\t${PRIMARY_LANG}::keywords::loops" >>"$ANKI_FILE"
|
||||
;;
|
||||
try | except | catch | finally | raise | throw)
|
||||
echo -e "What is the purpose of \`$term\` in $PRIMARY_LANG?\tException handling - manages errors and exceptional conditions. See: $url\t${PRIMARY_LANG}::keywords::exceptions" >>"$ANKI_FILE"
|
||||
;;
|
||||
class | struct | interface | trait | impl)
|
||||
echo -e "What is the purpose of \`$term\` in $PRIMARY_LANG?\tType definition - defines custom data structures. See: $url\t${PRIMARY_LANG}::keywords::types" >>"$ANKI_FILE"
|
||||
;;
|
||||
def | fn | func | function)
|
||||
echo -e "What is the purpose of \`$term\` in $PRIMARY_LANG?\tFunction definition - declares a reusable block of code. See: $url\t${PRIMARY_LANG}::keywords::functions" >>"$ANKI_FILE"
|
||||
;;
|
||||
import | from | use | require | include)
|
||||
echo -e "What is the purpose of \`$term\` in $PRIMARY_LANG?\tModule import - brings external code into current scope. See: $url\t${PRIMARY_LANG}::keywords::modules" >>"$ANKI_FILE"
|
||||
;;
|
||||
async | await | yield)
|
||||
echo -e "What is the purpose of \`$term\` in $PRIMARY_LANG?\tAsynchronous programming - handles concurrent operations. See: $url\t${PRIMARY_LANG}::keywords::async" >>"$ANKI_FILE"
|
||||
;;
|
||||
*)
|
||||
echo -e "What does the keyword \`$term\` do in $PRIMARY_LANG?\t[FILL: Look up at $url]\t${PRIMARY_LANG}::keywords" >>"$ANKI_FILE"
|
||||
;;
|
||||
esac
|
||||
done
|
||||
fi
|
||||
|
||||
# Generate cards for top functions
|
||||
if [ -f "$RESULTS_DIR/grep_function_calls.txt" ]; then
|
||||
{
|
||||
echo ""
|
||||
echo "# Functions"
|
||||
} >>"$ANKI_FILE"
|
||||
{ grep -v '^#' "$RESULTS_DIR/grep_function_calls.txt" || true; } | head -n "$TOP_N" | while read -r count term; do
|
||||
[ -z "$term" ] && continue
|
||||
[[ $term =~ ^(if|for|while|switch|catch)$ ]] && continue
|
||||
url=$(get_doc_url "$term" "$PRIMARY_LANG")
|
||||
|
||||
echo -e "What does \`$term()\` do in $PRIMARY_LANG? (Used $count times)\t[FILL: Look up at $url]\t${PRIMARY_LANG}::functions" >>"$ANKI_FILE"
|
||||
done
|
||||
fi
|
||||
|
||||
echo -e "${GREEN}Created: $ANKI_FILE${NC}"
|
||||
|
||||
}
|
||||
238
linux_configuration/scripts/single_use/utils/lib/study_gen_docs.sh
Executable file
238
linux_configuration/scripts/single_use/utils/lib/study_gen_docs.sh
Executable file
@ -0,0 +1,238 @@
|
||||
#!/usr/bin/env bash
|
||||
# lib/study_gen_docs.sh — write documentation_links.md, the markdown index of
|
||||
# every top keyword, function call and import the analysis found.
|
||||
|
||||
# Write the markdown documentation-link file covering every top keyword,
|
||||
# function call and import in the analysis.
|
||||
generate_doc_links() {
|
||||
#==============================================================================
|
||||
# Generate Documentation Links (Markdown)
|
||||
#==============================================================================
|
||||
echo -e "${YELLOW}Generating documentation links...${NC}"
|
||||
|
||||
cat >"$DOCS_FILE" <<'EOF'
|
||||
# Documentation Links for Code Review
|
||||
|
||||
This document contains links to official documentation for the most commonly used
|
||||
functions, keywords, and patterns found in the analyzed codebase.
|
||||
|
||||
**Note:** Items are grouped by language for accurate documentation links.
|
||||
|
||||
---
|
||||
|
||||
EOF
|
||||
|
||||
# Check for per-language files
|
||||
PER_LANG_DIR="$RESULTS_DIR/per_language"
|
||||
|
||||
if [ -d "$PER_LANG_DIR" ]; then
|
||||
echo -e "${GREEN}Using per-language analysis files${NC}"
|
||||
|
||||
# Map internal lang names to doc function names
|
||||
lang_to_doc() {
|
||||
case "$1" in
|
||||
c_cpp) echo "cpp" ;;
|
||||
javascript) echo "js" ;;
|
||||
typescript) echo "ts" ;;
|
||||
shell) echo "bash" ;;
|
||||
*) echo "$1" ;;
|
||||
esac
|
||||
}
|
||||
|
||||
# Process keywords by language
|
||||
{
|
||||
echo "## Language Keywords"
|
||||
echo ""
|
||||
} >>"$DOCS_FILE"
|
||||
|
||||
for keyword_file in "$PER_LANG_DIR"/keywords_*.txt; do
|
||||
[ ! -f "$keyword_file" ] && continue
|
||||
[ ! -s "$keyword_file" ] && continue
|
||||
|
||||
# Extract language name from filename
|
||||
lang=$(basename "$keyword_file" | sed 's/keywords_//; s/\.txt//')
|
||||
doc_lang=$(lang_to_doc "$lang")
|
||||
|
||||
# Format language name for display
|
||||
case "$lang" in
|
||||
c_cpp) display_lang="C/C++" ;;
|
||||
javascript) display_lang="JavaScript" ;;
|
||||
typescript) display_lang="TypeScript" ;;
|
||||
python) display_lang="Python" ;;
|
||||
rust) display_lang="Rust" ;;
|
||||
go) display_lang="Go" ;;
|
||||
ruby) display_lang="Ruby" ;;
|
||||
java) display_lang="Java" ;;
|
||||
shell) display_lang="Shell/Bash" ;;
|
||||
*) display_lang="$lang" ;;
|
||||
esac
|
||||
|
||||
{
|
||||
echo "### $display_lang Keywords"
|
||||
echo ""
|
||||
echo "| Keyword | Count | Documentation |"
|
||||
echo "|---------|-------|---------------|"
|
||||
} >>"$DOCS_FILE"
|
||||
|
||||
{ grep -v '^#' "$keyword_file" || true; } | head -n "$TOP_N" | while read -r count term; do
|
||||
[ -z "$term" ] && continue
|
||||
url=$(get_doc_url "$term" "$doc_lang")
|
||||
echo "| \`$term\` | $count | [docs]($url) |" >>"$DOCS_FILE"
|
||||
done
|
||||
echo "" >>"$DOCS_FILE"
|
||||
done
|
||||
|
||||
# Process functions by language
|
||||
{
|
||||
echo "## Function/Method Calls"
|
||||
echo ""
|
||||
} >>"$DOCS_FILE"
|
||||
|
||||
for func_file in "$PER_LANG_DIR"/functions_*.txt; do
|
||||
[ ! -f "$func_file" ] && continue
|
||||
[ ! -s "$func_file" ] && continue
|
||||
|
||||
lang=$(basename "$func_file" | sed 's/functions_//; s/\.txt//')
|
||||
doc_lang=$(lang_to_doc "$lang")
|
||||
|
||||
case "$lang" in
|
||||
c_cpp) display_lang="C/C++" ;;
|
||||
javascript) display_lang="JavaScript" ;;
|
||||
typescript) display_lang="TypeScript" ;;
|
||||
python) display_lang="Python" ;;
|
||||
rust) display_lang="Rust" ;;
|
||||
go) display_lang="Go" ;;
|
||||
ruby) display_lang="Ruby" ;;
|
||||
java) display_lang="Java" ;;
|
||||
shell) display_lang="Shell/Bash" ;;
|
||||
*) display_lang="$lang" ;;
|
||||
esac
|
||||
|
||||
{
|
||||
echo "### $display_lang Functions"
|
||||
echo ""
|
||||
echo "| Function | Count | Documentation |"
|
||||
echo "|----------|-------|---------------|"
|
||||
} >>"$DOCS_FILE"
|
||||
|
||||
{ grep -v '^#' "$func_file" || true; } | head -n "$TOP_N" | while read -r count term; do
|
||||
[ -z "$term" ] && continue
|
||||
[[ $term =~ ^(if|for|while|switch|catch|elif)$ ]] && continue
|
||||
url=$(get_doc_url "$term" "$doc_lang")
|
||||
echo "| \`$term()\` | $count | [docs]($url) |" >>"$DOCS_FILE"
|
||||
done
|
||||
echo "" >>"$DOCS_FILE"
|
||||
done
|
||||
|
||||
# Process imports by language
|
||||
{
|
||||
echo "## Imports/Includes"
|
||||
echo ""
|
||||
} >>"$DOCS_FILE"
|
||||
|
||||
for import_file in "$PER_LANG_DIR"/imports_*.txt; do
|
||||
[ ! -f "$import_file" ] && continue
|
||||
[ ! -s "$import_file" ] && continue
|
||||
|
||||
lang=$(basename "$import_file" | sed 's/imports_//; s/\.txt//')
|
||||
doc_lang=$(lang_to_doc "$lang")
|
||||
|
||||
case "$lang" in
|
||||
c_cpp) display_lang="C/C++ (#include)" ;;
|
||||
javascript) display_lang="JavaScript (import/require)" ;;
|
||||
typescript) display_lang="TypeScript (import)" ;;
|
||||
python) display_lang="Python (import/from)" ;;
|
||||
rust) display_lang="Rust (use)" ;;
|
||||
go) display_lang="Go (import)" ;;
|
||||
ruby) display_lang="Ruby (require)" ;;
|
||||
java) display_lang="Java (import)" ;;
|
||||
shell) display_lang="Shell (source)" ;;
|
||||
*) display_lang="$lang" ;;
|
||||
esac
|
||||
|
||||
{
|
||||
echo "### $display_lang"
|
||||
echo ""
|
||||
echo "| Import | Count | Documentation |"
|
||||
echo "|--------|-------|---------------|"
|
||||
} >>"$DOCS_FILE"
|
||||
|
||||
{ grep -v '^#' "$import_file" || true; } | head -n "$TOP_N" | while read -r count import; do
|
||||
[ -z "$import" ] && continue
|
||||
# For offline lookup, pass the full import line for better context
|
||||
url=$(get_doc_url "" "$doc_lang" "$import")
|
||||
if [ -z "$url" ] || [[ $url == *"search.html"* ]]; then
|
||||
# Fallback: extract module and try again
|
||||
module=$(echo "$import" | sed -E 's/.*[<"]([^">]+)[">].*/\1/' | sed 's|.*/||' | sed 's/\..*$//')
|
||||
url=$(get_doc_url "$module" "$doc_lang")
|
||||
fi
|
||||
import_escaped="${import//|/\\|}"
|
||||
echo "| \`$import_escaped\` | $count | [docs]($url) |" >>"$DOCS_FILE"
|
||||
done
|
||||
echo "" >>"$DOCS_FILE"
|
||||
done
|
||||
|
||||
else
|
||||
# Fallback to combined files (old behavior)
|
||||
echo -e "${YELLOW}No per-language files found, using combined analysis${NC}"
|
||||
|
||||
if [ -f "$RESULTS_DIR/grep_keywords.txt" ]; then
|
||||
{
|
||||
echo "## Language Keywords"
|
||||
echo ""
|
||||
echo "| Keyword | Count | Documentation |"
|
||||
echo "|---------|-------|---------------|"
|
||||
} >>"$DOCS_FILE"
|
||||
|
||||
{ grep -v '^#' "$RESULTS_DIR/grep_keywords.txt" || true; } | head -n "$TOP_N" | while read -r count term; do
|
||||
[ -z "$term" ] && continue
|
||||
url=$(get_doc_url "$term" "$PRIMARY_LANG")
|
||||
echo "| \`$term\` | $count | [docs]($url) |" >>"$DOCS_FILE"
|
||||
done
|
||||
echo "" >>"$DOCS_FILE"
|
||||
fi
|
||||
|
||||
if [ -f "$RESULTS_DIR/grep_function_calls.txt" ]; then
|
||||
{
|
||||
echo "## Function/Method Calls"
|
||||
echo ""
|
||||
echo "| Function | Count | Documentation |"
|
||||
echo "|----------|-------|---------------|"
|
||||
} >>"$DOCS_FILE"
|
||||
|
||||
{ grep -v '^#' "$RESULTS_DIR/grep_function_calls.txt" || true; } | head -n "$TOP_N" | while read -r count term; do
|
||||
[ -z "$term" ] && continue
|
||||
[[ $term =~ ^(if|for|while|switch|catch)$ ]] && continue
|
||||
url=$(get_doc_url "$term" "$PRIMARY_LANG")
|
||||
echo "| \`$term()\` | $count | [docs]($url) |" >>"$DOCS_FILE"
|
||||
done
|
||||
echo "" >>"$DOCS_FILE"
|
||||
fi
|
||||
|
||||
if [ -f "$RESULTS_DIR/grep_imports.txt" ]; then
|
||||
{
|
||||
echo "## Imports/Includes"
|
||||
echo ""
|
||||
echo "| Import | Count | Documentation |"
|
||||
echo "|--------|-------|---------------|"
|
||||
} >>"$DOCS_FILE"
|
||||
|
||||
{ grep -v '^#' "$RESULTS_DIR/grep_imports.txt" || true; } | head -n "$TOP_N" | while read -r count import; do
|
||||
[ -z "$import" ] && continue
|
||||
module=$(echo "$import" | sed -E 's/.*[<"]([^">]+)[">].*/\1/' | sed 's|.*/||' | sed 's/\..*$//')
|
||||
url=$(get_doc_url "$module" "$PRIMARY_LANG")
|
||||
import_escaped="${import//|/\\|}"
|
||||
echo "| \`$import_escaped\` | $count | [docs]($url) |" >>"$DOCS_FILE"
|
||||
done
|
||||
echo "" >>"$DOCS_FILE"
|
||||
fi
|
||||
fi
|
||||
|
||||
{
|
||||
echo ""
|
||||
echo "---"
|
||||
echo "*Generated by analyze_repo.sh + generate_study_materials.sh*"
|
||||
} >>"$DOCS_FILE"
|
||||
|
||||
echo -e "${GREEN}Created: $DOCS_FILE${NC}"
|
||||
}
|
||||
242
linux_configuration/scripts/single_use/utils/lib/study_gen_llm.sh
Executable file
242
linux_configuration/scripts/single_use/utils/lib/study_gen_llm.sh
Executable file
@ -0,0 +1,242 @@
|
||||
#!/usr/bin/env bash
|
||||
# lib/study_gen_llm.sh — write llm_anki_prompt.md.
|
||||
#
|
||||
# Its nested get_llm_doc_link and generate_*_with_docs helpers stay nested:
|
||||
# they were defined inside this phase in the pre-split script too, and they
|
||||
# close over PRIMARY_LANG and TOP_N from it.
|
||||
|
||||
# Write the LLM prompt file: the instructions, and the per-topic doc paths
|
||||
# an assistant is meant to read before writing any flashcard.
|
||||
generate_llm_prompt() {
|
||||
#==============================================================================
|
||||
# Generate LLM Prompt for Anki Card Generation
|
||||
#==============================================================================
|
||||
echo -e "${YELLOW}Generating LLM prompt...${NC}"
|
||||
|
||||
# Helper function to get doc link for a term
|
||||
get_llm_doc_link() {
|
||||
local term="$1"
|
||||
local lang="$2"
|
||||
# "true" if the term is a whole import line rather than a bare name.
|
||||
# Defaulted for the same reason as the lookup helpers: every current
|
||||
# caller passes it, but a bare "$3" would abort under `set -u`.
|
||||
local is_import="${3:-false}"
|
||||
|
||||
# Check if it's an internal/project-specific item
|
||||
if [[ $term =~ ^@/ ]] || [[ $term =~ ^\./ ]] || [[ $term =~ ^app\. ]] || [[ $term =~ ^src/ ]] || [[ $term =~ from\ \'@/ ]] || [[ $term =~ from\ \'\./ ]]; then
|
||||
echo "[INTERNAL - SKIP]"
|
||||
return
|
||||
fi
|
||||
|
||||
# Try offline lookup
|
||||
local offline_result
|
||||
if [ "$is_import" = "true" ]; then
|
||||
offline_result=$("$LOOKUP_SCRIPT" --import "$term" "$lang" 2>/dev/null | grep "^/" | head -1)
|
||||
else
|
||||
offline_result=$("$LOOKUP_SCRIPT" "$term" "$lang" 2>/dev/null | grep "^File:" | head -1 | sed 's/^File: //')
|
||||
fi
|
||||
|
||||
if [ -n "$offline_result" ]; then
|
||||
echo "$offline_result"
|
||||
else
|
||||
echo "[NO OFFLINE DOC]"
|
||||
fi
|
||||
}
|
||||
|
||||
# Generate keywords with doc links
|
||||
generate_keywords_with_docs() {
|
||||
local keywords_file="$RESULTS_DIR/grep_keywords.txt"
|
||||
[ ! -f "$keywords_file" ] && echo "No keywords found" && return
|
||||
|
||||
{ grep -v '^#' "$keywords_file" || true; } | head -n "$TOP_N" | while read -r line; do
|
||||
local count
|
||||
count=$(echo "$line" | awk '{print $1}')
|
||||
local keyword
|
||||
keyword=$(echo "$line" | awk '{print $2}')
|
||||
[ -z "$keyword" ] && continue
|
||||
local doc_link
|
||||
doc_link=$(get_llm_doc_link "$keyword" "$PRIMARY_LANG" "false")
|
||||
echo "$count $keyword → $doc_link"
|
||||
done
|
||||
}
|
||||
|
||||
# Generate functions with doc links
|
||||
generate_functions_with_docs() {
|
||||
local functions_file="$RESULTS_DIR/grep_function_calls.txt"
|
||||
[ ! -f "$functions_file" ] && echo "No functions found" && return
|
||||
|
||||
{ grep -v '^#' "$functions_file" || true; } | head -n "$TOP_N" | while read -r line; do
|
||||
local count
|
||||
count=$(echo "$line" | awk '{print $1}')
|
||||
local func
|
||||
func=$(echo "$line" | awk '{print $2}')
|
||||
|
||||
# Skip single-letter functions (minified code) or empty
|
||||
if [ -z "$func" ] || [ ${#func} -le 1 ]; then
|
||||
continue
|
||||
fi
|
||||
|
||||
local doc_link
|
||||
doc_link=$(get_llm_doc_link "$func" "$PRIMARY_LANG" "false")
|
||||
echo "$count $func() → $doc_link"
|
||||
done
|
||||
}
|
||||
|
||||
# Generate imports with doc links
|
||||
generate_imports_with_docs() {
|
||||
local imports_file="$RESULTS_DIR/grep_imports.txt"
|
||||
[ ! -f "$imports_file" ] && echo "No imports found" && return
|
||||
|
||||
{ grep -v '^#' "$imports_file" || true; } | head -n "$TOP_N" | while read -r line; do
|
||||
local count
|
||||
count=$(echo "$line" | awk '{print $1}')
|
||||
local import_stmt
|
||||
import_stmt=$(echo "$line" | cut -d' ' -f2-)
|
||||
[ -z "$import_stmt" ] && continue
|
||||
|
||||
# Check if internal import
|
||||
if [[ $import_stmt =~ @/ ]] || [[ $import_stmt =~ \./ ]] || [[ $import_stmt =~ from\ app\. ]] || [[ $import_stmt =~ from\ src\. ]]; then
|
||||
echo "$count $import_stmt → [INTERNAL - SKIP]"
|
||||
else
|
||||
local doc_link
|
||||
doc_link=$(get_llm_doc_link "$import_stmt" "$PRIMARY_LANG" "true")
|
||||
echo "$count $import_stmt → $doc_link"
|
||||
fi
|
||||
done
|
||||
}
|
||||
|
||||
cat >"$LLM_PROMPT_FILE" <<'PROMPT_HEADER'
|
||||
# LLM Prompt: Generate Anki Flashcards
|
||||
|
||||
You are creating Anki flashcards from code analysis.
|
||||
|
||||
## CRITICAL INSTRUCTIONS
|
||||
|
||||
1. **READ DOCS VIA TERMINAL** - Use the `cat` command to read each .md file:
|
||||
```
|
||||
cat /home/kuhy/.local/share/offline-docs/mdn-content/files/en-us/web/javascript/reference/statements/const/index.md
|
||||
```
|
||||
2. **DO NOT USE YOUR OWN KNOWLEDGE** - Base flashcards ONLY on the content you read from the files
|
||||
3. **IF YOU CANNOT READ A FILE** - Report: "ERROR: Cannot read [path]" and skip that item
|
||||
4. **NEVER FALL BACK TO GENERAL KNOWLEDGE** - If you can't read the file, skip it entirely
|
||||
5. **READ ONE FILE AT A TIME** - Run cat for each topic before creating its flashcards
|
||||
|
||||
PROMPT_HEADER
|
||||
|
||||
cat >>"$LLM_PROMPT_FILE" <<EOF
|
||||
## Context
|
||||
- Primary Language: **$PRIMARY_LANG**
|
||||
|
||||
## Top Keywords (by frequency)
|
||||
Items marked \`[INTERNAL - SKIP]\` are project-specific - skip them.
|
||||
Items marked \`[NO OFFLINE DOC]\` have no offline documentation - use online docs or skip.
|
||||
Other items have offline doc paths you can reference.
|
||||
|
||||
\`\`\`
|
||||
$(generate_keywords_with_docs)
|
||||
\`\`\`
|
||||
|
||||
## Top Functions/Methods (by frequency)
|
||||
\`\`\`
|
||||
$(generate_functions_with_docs)
|
||||
\`\`\`
|
||||
|
||||
## Top Imports/Includes
|
||||
\`\`\`
|
||||
$(generate_imports_with_docs)
|
||||
\`\`\`
|
||||
EOF
|
||||
|
||||
cat >>"$LLM_PROMPT_FILE" <<'PROMPT_FOOTER'
|
||||
|
||||
## Guidelines
|
||||
|
||||
**CRITICAL - Keep answers EXTREMELY short:**
|
||||
- Most answers should be **1-2 words** or **1 sentence**
|
||||
- It's common and expected for an answer to be just: "Returns an array" or "Immutable"
|
||||
- 2 sentences = longer answer, 3 sentences = absolute maximum (rare)
|
||||
- Each flashcard tests ONE atomic piece of knowledge
|
||||
|
||||
**NO DUPLICATES:**
|
||||
- Before creating a card, check if you already created a similar question
|
||||
- Each unique fact should appear in EXACTLY ONE card
|
||||
- Do NOT create multiple cards asking the same thing with slightly different wording
|
||||
|
||||
**What to include:**
|
||||
- Concept cards: "What is X?" / "What does X do?"
|
||||
- Syntax cards: "How do you write X?" (brief code snippet)
|
||||
- Comparison cards: "X vs Y - what's the difference?"
|
||||
|
||||
**What to SKIP (do NOT create cards for):**
|
||||
- MDN frontmatter fields: title, slug, page-type, browser-compat, spec-urls
|
||||
- YAML metadata between `---` markers at the start of files
|
||||
- Any line that looks like metadata (key: value at start of doc)
|
||||
- Empty answers - if you can't find content for the back, skip the card entirely
|
||||
|
||||
**FINAL CARD FOR EACH TOPIC (EXCEPTION TO SHORT ANSWER RULE):**
|
||||
- Add EXACTLY ONE full documentation card per topic (no duplicates!)
|
||||
- Question: `[Topic] - Full MDN Documentation`
|
||||
- Answer: Copy the .md file content STARTING AFTER the `---` frontmatter block
|
||||
- Skip the YAML frontmatter (everything between the first two `---` lines)
|
||||
- Do NOT create this card twice for the same topic
|
||||
|
||||
**Skipped items - please review:**
|
||||
- Items marked `[INTERNAL - SKIP]` are project-specific utilities - I skipped them
|
||||
- Items marked `[NO OFFLINE DOC]` are third-party libraries without bundled docs
|
||||
- If you want flashcards for skipped items, tell me which ones to include
|
||||
|
||||
## OUTPUT: CREATE AN ANKI FILE
|
||||
|
||||
**CREATE A FILE DIRECTLY** - Do not just output text. Use your file creation tool to create:
|
||||
|
||||
**File path:** `~/.local/share/study-materials/anki_generated.txt`
|
||||
|
||||
**Format:** Tab-separated values (TSV) with Anki metadata headers:
|
||||
|
||||
```
|
||||
#separator:tab
|
||||
#deck:CodeStudy::JavaScript
|
||||
#notetype:CodeCard
|
||||
#columns:Front Back Tags
|
||||
What does <code>const</code> declare?Block-scoped variables with immutable bindings.javascript declarations
|
||||
```
|
||||
|
||||
**Required headers at top of file:**
|
||||
- `#separator:tab` - Specifies tab as delimiter
|
||||
- `#deck:CodeStudy::[Language]` - Creates deck "CodeStudy" with sub-deck for language (e.g., CodeStudy::JavaScript)
|
||||
- `#notetype:CodeCard` - Uses custom note type "CodeCard" (Anki will create if doesn't exist)
|
||||
- `#columns:Front Back Tags` - Column headers (tab-separated)
|
||||
|
||||
**Rules:**
|
||||
- Use ACTUAL `<code>` tags (not escaped <code>)
|
||||
- Use `<br>` for line breaks within fields
|
||||
- Use `<pre>` for code blocks
|
||||
- Tags are space-separated
|
||||
- Escape any literal tabs within content as spaces
|
||||
|
||||
**Example file content:**
|
||||
```
|
||||
#separator:tab
|
||||
#deck:CodeStudy::JavaScript
|
||||
#notetype:CodeCard
|
||||
#columns:Front Back Tags
|
||||
What does <code>const</code> declare?Block-scoped variables with immutable bindings.javascript declarations
|
||||
Can <code>const</code> be reassigned?No, throws TypeError.javascript declarations
|
||||
const - Full Documentation<pre>[ENTIRE CONTENT OF const/index.md FILE]</pre>javascript declarations full-doc
|
||||
```
|
||||
|
||||
**After creating the file**, tell the user:
|
||||
- File created at: ~/.local/share/study-materials/anki_generated.txt
|
||||
- Import in Anki: File → Import → select the file
|
||||
- Deck: CodeStudy::[Language], Note type: CodeCard
|
||||
---
|
||||
|
||||
**Important:**
|
||||
- Process only 5-10 items at a time to maintain quality
|
||||
- Focus on items with offline documentation paths
|
||||
- Output ONLY the TSV lines, no extra formatting or markdown
|
||||
PROMPT_FOOTER
|
||||
|
||||
echo -e "${GREEN}Created: $LLM_PROMPT_FILE${NC}"
|
||||
|
||||
}
|
||||
25
linux_configuration/scripts/single_use/utils/lib/tests/run_all.sh
Executable file
25
linux_configuration/scripts/single_use/utils/lib/tests/run_all.sh
Executable file
@ -0,0 +1,25 @@
|
||||
#!/usr/bin/env bash
|
||||
# lib/tests/run_all.sh — run every generate_study_materials test in one process
|
||||
# tree, and exit non-zero if any of them fails.
|
||||
#
|
||||
# Also the subject handed to shell_coverage.sh: coverage of a lib is only
|
||||
# complete across the whole suite, since the doc-URL builders are exercised both
|
||||
# directly and through get_doc_url's dispatch.
|
||||
set -euo pipefail
|
||||
|
||||
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
||||
|
||||
failed=0
|
||||
for test_script in "${SCRIPT_DIR}"/test_study_*.sh; do
|
||||
printf '\n### %s\n' "$(basename "$test_script")"
|
||||
if ! "$test_script"; then
|
||||
failed=$((failed + 1))
|
||||
fi
|
||||
done
|
||||
|
||||
if [[ $failed -gt 0 ]]; then
|
||||
printf '\n%d test file(s) FAILED\n' "$failed"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
printf '\nAll generate_study_materials test files passed.\n'
|
||||
182
linux_configuration/scripts/single_use/utils/lib/tests/study_harness.sh
Executable file
182
linux_configuration/scripts/single_use/utils/lib/tests/study_harness.sh
Executable file
@ -0,0 +1,182 @@
|
||||
#!/usr/bin/env bash
|
||||
# lib/tests/study_harness.sh — shared fixture for the generate_study_materials
|
||||
# split.
|
||||
#
|
||||
# Sourced, not executed. These libs are almost pure string logic: the doc-URL
|
||||
# builders map a term to a URL, and the only external process any of them runs
|
||||
# is $LOOKUP_SCRIPT, which the tests point at a stub. Nothing here reaches the
|
||||
# network or reads the real offline-docs mirror.
|
||||
set -euo pipefail
|
||||
|
||||
PASS=0
|
||||
FAIL=0
|
||||
|
||||
_t_pass() {
|
||||
PASS=$((PASS + 1))
|
||||
printf ' OK: %s\n' "$1"
|
||||
}
|
||||
|
||||
_t_fail() {
|
||||
FAIL=$((FAIL + 1))
|
||||
printf ' FAIL: %s\n' "$1"
|
||||
}
|
||||
|
||||
_t_eq() {
|
||||
local want="$1"
|
||||
local got="$2"
|
||||
local what="$3"
|
||||
if [[ "$got" == "$want" ]]; then
|
||||
_t_pass "$what"
|
||||
else
|
||||
_t_fail "$what (want '${want}', got '${got}')"
|
||||
fi
|
||||
}
|
||||
|
||||
# Assert a URL builder's output contains a substring. Most builders assemble a
|
||||
# base URL plus the term, so matching the distinctive fragment is more robust
|
||||
# than pinning the whole string, which would break on an upstream doc-site move
|
||||
# without anything actually being wrong.
|
||||
_t_has() {
|
||||
local haystack="$1"
|
||||
local needle="$2"
|
||||
local what="$3"
|
||||
if [[ "$haystack" == *"$needle"* ]]; then
|
||||
_t_pass "$what"
|
||||
else
|
||||
_t_fail "$what (want a substring '${needle}', got '${haystack}')"
|
||||
fi
|
||||
}
|
||||
|
||||
_t_summary() {
|
||||
printf '\n%s: %d passed, %d failed\n' "$(basename "$0")" "$PASS" "$FAIL"
|
||||
[[ $FAIL -eq 0 ]]
|
||||
}
|
||||
|
||||
TEST_TMPDIR="$(mktemp -d)"
|
||||
trap 'rm -rf "${TEST_TMPDIR}"' EXIT
|
||||
|
||||
# --- globals the libs read --------------------------------------------------
|
||||
|
||||
# Read by the generation phases, which the individual test files source
|
||||
# rather than this harness -- so standalone shellcheck (as the hook runs it,
|
||||
# with no -x) sees only the write here and reports SC2034. Exported because
|
||||
# they genuinely cross into the sourced libs.
|
||||
export RED='\033[0;31m'
|
||||
export GREEN='\033[0;32m'
|
||||
export BLUE='\033[0;34m'
|
||||
export YELLOW='\033[1;33m'
|
||||
export NC='\033[0m'
|
||||
|
||||
export RESULTS_DIR="${TEST_TMPDIR}/results"
|
||||
export TOP_N=5
|
||||
export PRIMARY_LANG="python"
|
||||
mkdir -p "${RESULTS_DIR}"
|
||||
|
||||
export DOCS_FILE="${RESULTS_DIR}/documentation_links.md"
|
||||
export ANKI_FILE="${RESULTS_DIR}/anki_cards.txt"
|
||||
export LLM_PROMPT_FILE="${RESULTS_DIR}/llm_anki_prompt.md"
|
||||
|
||||
export OFFLINE_DOCS_DIR="${TEST_TMPDIR}/offline-docs"
|
||||
export LOOKUP_SCRIPT="${TEST_TMPDIR}/lookup_docs.sh"
|
||||
export USE_OFFLINE_DOCS=false
|
||||
|
||||
# Install a stub lookup_docs.sh and switch the libs onto the offline path.
|
||||
#
|
||||
# The real script prints "File: <path>" for a term lookup and a bare path for
|
||||
# an --import lookup, and lookup_offline parses each shape differently, so the
|
||||
# stub reproduces both rather than one.
|
||||
enable_offline_docs() { # [answer-path]
|
||||
local answer="${1:-${OFFLINE_DOCS_DIR}/python/stdlib/os.md}"
|
||||
mkdir -p "${OFFLINE_DOCS_DIR}"
|
||||
cat >"${LOOKUP_SCRIPT}" <<STUB
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
if [[ "\${1:-}" == "--import" ]]; then
|
||||
printf '%s\\n' "${answer}"
|
||||
else
|
||||
printf 'File: %s\\n' "${answer}"
|
||||
fi
|
||||
STUB
|
||||
chmod +x "${LOOKUP_SCRIPT}"
|
||||
USE_OFFLINE_DOCS=true
|
||||
}
|
||||
|
||||
# Make the offline lookup find nothing, so callers fall back to online URLs.
|
||||
enable_offline_docs_empty() {
|
||||
mkdir -p "${OFFLINE_DOCS_DIR}"
|
||||
printf '#!/usr/bin/env bash\nexit 0\n' >"${LOOKUP_SCRIPT}"
|
||||
chmod +x "${LOOKUP_SCRIPT}"
|
||||
USE_OFFLINE_DOCS=true
|
||||
}
|
||||
|
||||
# A mirror that answers ONLY for the given language and stays silent for every
|
||||
# other. This is what exercises the TypeScript retry path: a TS lookup misses
|
||||
# under "typescript", then succeeds when get_doc_url retries under "js".
|
||||
enable_offline_docs_for_lang() { # <language> [answer-path]
|
||||
local only_lang="$1"
|
||||
local answer="${2:-${OFFLINE_DOCS_DIR}/js/const.md}"
|
||||
mkdir -p "${OFFLINE_DOCS_DIR}"
|
||||
cat >"${LOOKUP_SCRIPT}" <<STUB
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
if [[ "\${1:-}" == "--import" ]]; then
|
||||
[[ "\${3:-}" == "${only_lang}" ]] || exit 0
|
||||
printf '%s\\n' "${answer}"
|
||||
else
|
||||
[[ "\${2:-}" == "${only_lang}" ]] || exit 0
|
||||
printf 'File: %s\\n' "${answer}"
|
||||
fi
|
||||
STUB
|
||||
chmod +x "${LOOKUP_SCRIPT}"
|
||||
USE_OFFLINE_DOCS=true
|
||||
}
|
||||
|
||||
disable_offline_docs() {
|
||||
USE_OFFLINE_DOCS=false
|
||||
rm -f "${LOOKUP_SCRIPT}"
|
||||
}
|
||||
|
||||
# Write the three grep_*.txt files the generation phases read. Each line is
|
||||
# "<count> <term>", which is what analyze_repo.sh emits.
|
||||
stage_results() {
|
||||
printf '%s\n' "42 def" "31 class" "20 import" >"${RESULTS_DIR}/grep_keywords.txt"
|
||||
printf '%s\n' "18 print" "9 len" "4 range" >"${RESULTS_DIR}/grep_function_calls.txt"
|
||||
printf '%s\n' "12 os" "7 sys" "3 json" >"${RESULTS_DIR}/grep_imports.txt"
|
||||
}
|
||||
|
||||
# Write the per-language analysis tree. generate_doc_links takes a completely
|
||||
# different path when $RESULTS_DIR/per_language exists: instead of three global
|
||||
# grep_*.txt files it walks keywords_<lang>.txt / functions_<lang>.txt /
|
||||
# imports_<lang>.txt and resolves each language's terms against that language's
|
||||
# docs, which is what makes a polyglot repo's index correct.
|
||||
stage_per_language() { # <lang>...
|
||||
local dir="${RESULTS_DIR}/per_language"
|
||||
mkdir -p "$dir"
|
||||
local lang
|
||||
for lang in "$@"; do
|
||||
printf '%s\n' "9 alpha_${lang}" "8 beta_${lang}" >"${dir}/keywords_${lang}.txt"
|
||||
printf '%s\n' "7 fn_${lang}" >"${dir}/functions_${lang}.txt"
|
||||
printf '%s\n' "6 mod_${lang}" >"${dir}/imports_${lang}.txt"
|
||||
done
|
||||
}
|
||||
|
||||
# tokei output in the shape detect_language parses.
|
||||
stage_tokei() { # <language> [second-language]
|
||||
{
|
||||
printf '===============================================================================\n'
|
||||
printf ' Language Files Lines Code Comments Blanks\n'
|
||||
printf '===============================================================================\n'
|
||||
printf ' %-18s 42 5120 4001 610 509\n' "$1"
|
||||
[[ -n "${2:-}" ]] && printf ' %-18s 12 1400 1100 150 150\n' "$2"
|
||||
printf '===============================================================================\n'
|
||||
} >"${RESULTS_DIR}/tokei_stats.txt"
|
||||
}
|
||||
|
||||
reset_state() {
|
||||
rm -rf "${RESULTS_DIR:?}"
|
||||
mkdir -p "${RESULTS_DIR}"
|
||||
TOP_N=5
|
||||
PRIMARY_LANG="python"
|
||||
disable_offline_docs
|
||||
}
|
||||
reset_state
|
||||
129
linux_configuration/scripts/single_use/utils/lib/tests/test_study_doc_lookup.sh
Executable file
129
linux_configuration/scripts/single_use/utils/lib/tests/test_study_doc_lookup.sh
Executable file
@ -0,0 +1,129 @@
|
||||
#!/usr/bin/env bash
|
||||
# Tests for lib/study_doc_lookup.sh — offline lookup, language dispatch and
|
||||
# language detection.
|
||||
#
|
||||
# The interesting behaviour is the preference order: when an offline mirror is
|
||||
# installed, a term should resolve to a local FILE PATH an assistant can read
|
||||
# with `cat`, and only fall back to an online URL when the mirror has no answer.
|
||||
# That distinction is the whole point of the offline path — a card citing a URL
|
||||
# the assistant cannot fetch is a card it will answer from memory instead.
|
||||
set -euo pipefail
|
||||
|
||||
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
||||
|
||||
# shellcheck source=study_harness.sh
|
||||
. "${SCRIPT_DIR}/study_harness.sh"
|
||||
# shellcheck source=../study_doc_urls.sh
|
||||
. "${SCRIPT_DIR}/../study_doc_urls.sh"
|
||||
# shellcheck source=../study_doc_urls_more.sh
|
||||
. "${SCRIPT_DIR}/../study_doc_urls_more.sh"
|
||||
# shellcheck source=../study_doc_lookup.sh
|
||||
. "${SCRIPT_DIR}/../study_doc_lookup.sh"
|
||||
|
||||
echo "== lookup_offline: disabled =="
|
||||
reset_state
|
||||
if lookup_offline "os" python "" >/dev/null 2>&1; then
|
||||
_t_fail "with offline docs off, lookup_offline fails"
|
||||
else
|
||||
_t_pass "with offline docs off, lookup_offline fails"
|
||||
fi
|
||||
|
||||
echo "== lookup_offline: a term lookup =="
|
||||
reset_state
|
||||
enable_offline_docs "${OFFLINE_DOCS_DIR}/python/os.md"
|
||||
_t_eq "${OFFLINE_DOCS_DIR}/python/os.md" "$(lookup_offline "os" python "")" \
|
||||
"a term resolves to the local file path"
|
||||
|
||||
echo "== lookup_offline: an import-aware lookup =="
|
||||
reset_state
|
||||
enable_offline_docs "${OFFLINE_DOCS_DIR}/js/array.md"
|
||||
_t_eq "${OFFLINE_DOCS_DIR}/js/array.md" "$(lookup_offline "" javascript "import { x } from 'y'")" \
|
||||
"an import line resolves through the --import path"
|
||||
|
||||
echo "== lookup_offline: mirror has no answer =="
|
||||
reset_state
|
||||
enable_offline_docs_empty
|
||||
if lookup_offline "frobnicate" python "" >/dev/null 2>&1; then
|
||||
_t_fail "an unanswered term fails rather than returning empty"
|
||||
else
|
||||
_t_pass "an unanswered term fails rather than returning empty"
|
||||
fi
|
||||
|
||||
echo "== get_doc_url: dispatches per language =="
|
||||
reset_state
|
||||
_t_has "$(get_doc_url "def" python "")" "docs.python.org" "python dispatches to python_doc_url"
|
||||
_t_has "$(get_doc_url "const" javascript "")" "developer.mozilla.org" "javascript dispatches to js_doc_url"
|
||||
_t_has "$(get_doc_url "interface" typescript "")" "typescriptlang.org" "typescript dispatches to ts_doc_url"
|
||||
_t_has "$(get_doc_url "printf" c "")" "cppreference.com" "c dispatches to c_doc_url"
|
||||
_t_has "$(get_doc_url "vector" cpp "")" "cppreference.com" "cpp dispatches to cpp_doc_url"
|
||||
_t_has "$(get_doc_url "fn" rust "")" "rust-lang.org" "rust dispatches to rust_doc_url"
|
||||
_t_has "$(get_doc_url "func" go "")" "go.dev" "go dispatches to go_doc_url"
|
||||
_t_has "$(get_doc_url "def" ruby "")" "ruby-doc.org" "ruby dispatches to ruby_doc_url"
|
||||
_t_has "$(get_doc_url "class" java "")" "oracle.com" "java dispatches to java_doc_url"
|
||||
_t_has "$(get_doc_url "if" shell "")" "gnu.org" "shell dispatches to shell_doc_url"
|
||||
|
||||
echo "== get_doc_url: an unknown language still answers =="
|
||||
reset_state
|
||||
out="$(get_doc_url "something" brainfuck "")"
|
||||
if [[ -n "$out" ]]; then
|
||||
_t_pass "an unrecognised language still produces a link"
|
||||
else
|
||||
_t_fail "an unrecognised language still produces a link (returned nothing)"
|
||||
fi
|
||||
|
||||
echo "== get_doc_url: prefers the offline mirror when it has an answer =="
|
||||
reset_state
|
||||
enable_offline_docs "${OFFLINE_DOCS_DIR}/python/os.md"
|
||||
out="$(get_doc_url "os" python "")"
|
||||
_t_has "$out" "${OFFLINE_DOCS_DIR}" "an offline hit wins over the online URL"
|
||||
|
||||
echo "== get_doc_url: falls back online when the mirror misses =="
|
||||
reset_state
|
||||
enable_offline_docs_empty
|
||||
_t_has "$(get_doc_url "os" python "")" "docs.python.org" "an offline miss falls back to the online URL"
|
||||
|
||||
echo "== get_doc_url: TypeScript borrows the JavaScript offline mirror =="
|
||||
reset_state
|
||||
# The mirror answers for "js" and nothing else, which is the real shape: an
|
||||
# offline-docs install carries MDN, not a separate TypeScript tree. A TS lookup
|
||||
# therefore misses under "typescript" and only succeeds on the retry under
|
||||
# "js". Without that retry a TS repo would silently never use the docs it has.
|
||||
enable_offline_docs_for_lang js "${OFFLINE_DOCS_DIR}/js/const.md"
|
||||
_t_has "$(get_doc_url "const" typescript "")" "${OFFLINE_DOCS_DIR}" \
|
||||
"a TS term resolves through the JS mirror"
|
||||
|
||||
echo "== get_doc_url: a TS runtime term falls through to the JS builder =="
|
||||
reset_state
|
||||
_t_has "$(get_doc_url "const" typescript "")" "developer.mozilla.org" \
|
||||
"a runtime term prefers MDN over the TS handbook"
|
||||
_t_has "$(get_doc_url "interface" typescript "")" "typescriptlang.org" \
|
||||
"a TS-only term still gets the TS handbook"
|
||||
|
||||
echo "== detect_language =="
|
||||
reset_state
|
||||
stage_tokei "Python" "JavaScript"
|
||||
_t_eq "python" "$(detect_language)" "the language with the most code wins"
|
||||
|
||||
reset_state
|
||||
stage_tokei "Rust"
|
||||
_t_eq "rust" "$(detect_language)" "a single-language repo detects that language"
|
||||
|
||||
reset_state
|
||||
stage_tokei "C++"
|
||||
out="$(detect_language)"
|
||||
if [[ -n "$out" ]]; then
|
||||
_t_pass "a punctuated language name still maps to something ('${out}')"
|
||||
else
|
||||
_t_fail "a punctuated language name still maps to something"
|
||||
fi
|
||||
|
||||
echo "== detect_language: no stats file =="
|
||||
reset_state
|
||||
out="$(detect_language)"
|
||||
if [[ -n "$out" ]]; then
|
||||
_t_pass "a missing tokei_stats.txt falls back to a default ('${out}')"
|
||||
else
|
||||
_t_fail "a missing tokei_stats.txt falls back to a default"
|
||||
fi
|
||||
|
||||
_t_summary
|
||||
@ -0,0 +1,83 @@
|
||||
#!/usr/bin/env bash
|
||||
# Tests for lib/study_doc_urls.sh — the Python, JS, TS and C/C++ doc-URL
|
||||
# builders.
|
||||
#
|
||||
# Each builder is a case dispatch over term categories with a search-URL
|
||||
# fallback, so every arm gets one assertion plus one for the fallback. The
|
||||
# fallback matters more than it looks: it is what every unrecognised term hits,
|
||||
# so a card for an unknown identifier still links somewhere useful instead of
|
||||
# to an empty string.
|
||||
set -euo pipefail
|
||||
|
||||
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
||||
|
||||
# shellcheck source=study_harness.sh
|
||||
. "${SCRIPT_DIR}/study_harness.sh"
|
||||
# shellcheck source=../study_doc_urls.sh
|
||||
. "${SCRIPT_DIR}/../study_doc_urls.sh"
|
||||
|
||||
echo "== python_doc_url =="
|
||||
_t_eq "https://docs.python.org/3/reference/compound_stmts.html" \
|
||||
"$(python_doc_url "def" keyword)" "a keyword links to the statements reference"
|
||||
_t_eq "https://docs.python.org/3/library/functions.html#print" \
|
||||
"$(python_doc_url "print" builtin)" "a builtin links to its anchor in functions.html"
|
||||
_t_eq "https://docs.python.org/3/library/os.html" \
|
||||
"$(python_doc_url "os" module)" "a stdlib module links to its own page"
|
||||
_t_eq "https://docs.python.org/3/library/unittest.mock.html" \
|
||||
"$(python_doc_url "MagicMock" module)" "a mock helper links to unittest.mock"
|
||||
_t_eq "https://docs.python.org/3/search.html?q=frobnicate" \
|
||||
"$(python_doc_url "frobnicate" keyword)" "an unknown term falls back to search"
|
||||
|
||||
echo "== js_doc_url =="
|
||||
_t_has "$(js_doc_url "const" keyword)" "developer.mozilla.org" "a JS keyword links to MDN"
|
||||
_t_has "$(js_doc_url "Array" builtin)" "Array" "a builtin object names itself in the URL"
|
||||
_t_has "$(js_doc_url "frobnicate" keyword)" "frobnicate" "an unknown JS term still carries the term"
|
||||
|
||||
echo "== ts_doc_url =="
|
||||
_t_has "$(ts_doc_url "interface" keyword)" "typescriptlang.org" "a TS term links to the TS handbook"
|
||||
_t_has "$(ts_doc_url "Partial" keyword)" "utility-types" "a TS utility type links to the utility-types page"
|
||||
# A term TypeScript does not define is a runtime feature, so it deliberately
|
||||
# falls through to the JS builder rather than to a TS search page.
|
||||
_t_has "$(ts_doc_url "frobnicate" keyword)" "developer.mozilla.org" "an unknown TS term falls through to MDN"
|
||||
|
||||
echo "== js_doc_url: every category of builtin =="
|
||||
_t_has "$(js_doc_url "map" builtin)" "Global_Objects/Array" "an array method links under Array"
|
||||
_t_has "$(js_doc_url "split" builtin)" "Global_Objects/String" "a string method links under String"
|
||||
_t_has "$(js_doc_url "then" builtin)" "Global_Objects/Promise" "a promise method links under Promise"
|
||||
_t_has "$(js_doc_url "fetch" builtin)" "docs/Web/API" "a browser API links under Web/API"
|
||||
|
||||
echo "== c_doc_url =="
|
||||
_t_has "$(c_doc_url "printf" builtin)" "cppreference.com" "a C library function links to cppreference"
|
||||
_t_has "$(c_doc_url "for" keyword)" "cppreference.com" "a C keyword links to cppreference"
|
||||
_t_has "$(c_doc_url "frobnicate" keyword)" "cppreference.com" "an unknown C term stays on cppreference"
|
||||
|
||||
_t_has "$(c_doc_url "stdio" module)" "c/header/stdio.h" "a C header links to its header page"
|
||||
_t_has "$(c_doc_url "malloc" builtin)" "c/memory" "an allocator links to the memory page"
|
||||
_t_has "$(c_doc_url "strlen" builtin)" "c/string/byte" "a string function links to the byte-string page"
|
||||
|
||||
echo "== cpp_doc_url =="
|
||||
_t_has "$(cpp_doc_url "vector" builtin)" "cppreference.com" "a C++ container links to cppreference"
|
||||
_t_has "$(cpp_doc_url "class" keyword)" "cppreference.com" "a C++ keyword links to cppreference"
|
||||
_t_has "$(cpp_doc_url "frobnicate" keyword)" "cppreference.com" "an unknown C++ term stays on cppreference"
|
||||
|
||||
_t_has "$(cpp_doc_url "sort" builtin)" "cpp/algorithm/sort" "an algorithm links under cpp/algorithm"
|
||||
_t_has "$(cpp_doc_url "unique_ptr" builtin)" "cpp/memory/unique_ptr" "a smart pointer links under cpp/memory"
|
||||
_t_has "$(cpp_doc_url "optional" builtin)" "cpp/utility" "a utility type links under cpp/utility"
|
||||
|
||||
echo "== every builder answers for every input =="
|
||||
# The generation phases pipe whatever the analysis found straight into these,
|
||||
# including punctuation and empty strings from a malformed grep line. A builder
|
||||
# that returned nothing would silently produce a card with no link at all, so
|
||||
# the invariant worth pinning is that output is never empty.
|
||||
for fn in python_doc_url js_doc_url ts_doc_url c_doc_url cpp_doc_url; do
|
||||
for term in "" "x" "std::vector" "__init__" "a-b" "3"; do
|
||||
out="$("$fn" "$term" keyword)"
|
||||
if [[ -n "$out" ]]; then
|
||||
_t_pass "${fn} answers for '${term}'"
|
||||
else
|
||||
_t_fail "${fn} answers for '${term}' (returned nothing)"
|
||||
fi
|
||||
done
|
||||
done
|
||||
|
||||
_t_summary
|
||||
@ -0,0 +1,64 @@
|
||||
#!/usr/bin/env bash
|
||||
# Tests for lib/study_doc_urls_more.sh — the Rust, Go, Ruby, Java and shell
|
||||
# doc-URL builders.
|
||||
#
|
||||
# Same shape as test_study_doc_urls.sh: one assertion per case arm plus the
|
||||
# fallback, since an unmatched term is the common case for anything the
|
||||
# analysis extracted that is project-specific rather than language-level.
|
||||
set -euo pipefail
|
||||
|
||||
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
||||
|
||||
# shellcheck source=study_harness.sh
|
||||
. "${SCRIPT_DIR}/study_harness.sh"
|
||||
# shellcheck source=../study_doc_urls_more.sh
|
||||
. "${SCRIPT_DIR}/../study_doc_urls_more.sh"
|
||||
|
||||
echo "== rust_doc_url =="
|
||||
_t_has "$(rust_doc_url "fn" keyword)" "doc.rust-lang.org" "a Rust keyword links to the Rust docs"
|
||||
_t_has "$(rust_doc_url "Option" builtin)" "Option" "a std type names itself"
|
||||
_t_has "$(rust_doc_url "Clone" builtin)" "Clone" "a derivable trait names itself"
|
||||
_t_has "$(rust_doc_url "println" builtin)" "macro" "a macro links to its macro page"
|
||||
_t_has "$(rust_doc_url "frobnicate" keyword)" "doc.rust-lang.org" "an unknown Rust term stays on the Rust docs"
|
||||
|
||||
echo "== go_doc_url =="
|
||||
_t_has "$(go_doc_url "func" keyword)" "go.dev" "a Go keyword links to go.dev"
|
||||
_t_has "$(go_doc_url "append" builtin)" "builtin" "a builtin links to the builtin package"
|
||||
_t_has "$(go_doc_url "fmt" module)" "fmt" "a stdlib package names itself"
|
||||
_t_has "$(go_doc_url "frobnicate" keyword)" "go.dev" "an unknown Go term stays on go.dev"
|
||||
|
||||
echo "== ruby_doc_url =="
|
||||
_t_has "$(ruby_doc_url "def" keyword)" "ruby-doc.org" "a Ruby keyword links to ruby-doc.org"
|
||||
_t_has "$(ruby_doc_url "String" builtin)" "String" "a core class names itself"
|
||||
_t_has "$(ruby_doc_url "each" builtin)" "Enumerable" "an Enumerable method links to the Enumerable page"
|
||||
_t_has "$(ruby_doc_url "frobnicate" keyword)" "ruby-doc.org" "an unknown Ruby term stays on ruby-doc.org"
|
||||
|
||||
echo "== java_doc_url =="
|
||||
_t_has "$(java_doc_url "class" keyword)" "oracle.com" "a Java keyword links to the Oracle docs"
|
||||
_t_has "$(java_doc_url "String" builtin)" "String" "a core class names itself"
|
||||
_t_has "$(java_doc_url "frobnicate" keyword)" "oracle.com" "an unknown Java term stays on the Oracle docs"
|
||||
|
||||
echo "== shell_doc_url =="
|
||||
_t_has "$(shell_doc_url "if" keyword)" "gnu.org" "a shell keyword links to the bash manual"
|
||||
_t_has "$(shell_doc_url "declare" builtin)" "gnu.org" "a shell builtin links to the bash manual"
|
||||
# External commands get a man page rather than the bash manual, because they
|
||||
# are not part of the shell -- a card saying otherwise would be wrong.
|
||||
_t_has "$(shell_doc_url "grep" builtin)" "man" "an external command links to its man page"
|
||||
_t_has "$(shell_doc_url "frobnicate" keyword)" "man" "an unknown command is treated as external"
|
||||
|
||||
echo "== every builder answers for every input =="
|
||||
# These are fed straight from the analysis output, punctuation and all. A
|
||||
# builder returning nothing would emit a card with no link, which is worse than
|
||||
# a link to a search page.
|
||||
for fn in rust_doc_url go_doc_url ruby_doc_url java_doc_url shell_doc_url; do
|
||||
for term in "" "x" "a-b" "3" "__weird__"; do
|
||||
out="$("$fn" "$term" keyword)"
|
||||
if [[ -n "$out" ]]; then
|
||||
_t_pass "${fn} answers for '${term}'"
|
||||
else
|
||||
_t_fail "${fn} answers for '${term}' (returned nothing)"
|
||||
fi
|
||||
done
|
||||
done
|
||||
|
||||
_t_summary
|
||||
244
linux_configuration/scripts/single_use/utils/lib/tests/test_study_gen.sh
Executable file
244
linux_configuration/scripts/single_use/utils/lib/tests/test_study_gen.sh
Executable file
@ -0,0 +1,244 @@
|
||||
#!/usr/bin/env bash
|
||||
# Tests for the three generation phases: lib/study_gen_docs.sh,
|
||||
# lib/study_gen_anki.sh and lib/study_gen_llm.sh.
|
||||
#
|
||||
# Each phase reads the grep_*.txt files the analysis step wrote and produces
|
||||
# one output file. The cases below pin what actually matters about each output
|
||||
# rather than its exact bytes: that every extracted term appears, that the Anki
|
||||
# file keeps the tab-separated shape its importer requires, and that the LLM
|
||||
# prompt keeps the instructions that stop an assistant answering from memory
|
||||
# instead of from the docs it was told to read.
|
||||
set -euo pipefail
|
||||
|
||||
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
||||
|
||||
# shellcheck source=study_harness.sh
|
||||
. "${SCRIPT_DIR}/study_harness.sh"
|
||||
# shellcheck source=../study_doc_urls.sh
|
||||
. "${SCRIPT_DIR}/../study_doc_urls.sh"
|
||||
# shellcheck source=../study_doc_urls_more.sh
|
||||
. "${SCRIPT_DIR}/../study_doc_urls_more.sh"
|
||||
# shellcheck source=../study_doc_lookup.sh
|
||||
. "${SCRIPT_DIR}/../study_doc_lookup.sh"
|
||||
# shellcheck source=../study_gen_docs.sh
|
||||
. "${SCRIPT_DIR}/../study_gen_docs.sh"
|
||||
# shellcheck source=../study_gen_anki.sh
|
||||
. "${SCRIPT_DIR}/../study_gen_anki.sh"
|
||||
# shellcheck source=../study_gen_llm.sh
|
||||
. "${SCRIPT_DIR}/../study_gen_llm.sh"
|
||||
|
||||
echo "== generate_doc_links: writes a section per term kind =="
|
||||
reset_state
|
||||
stage_results
|
||||
generate_doc_links >/dev/null
|
||||
docs="$(cat "${DOCS_FILE}")"
|
||||
_t_has "$docs" "def" "a keyword appears in the doc index"
|
||||
_t_has "$docs" "print" "a function call appears"
|
||||
_t_has "$docs" "os" "an import appears"
|
||||
_t_has "$docs" "docs.python.org" "terms carry a resolved documentation link"
|
||||
|
||||
echo "== generate_doc_links: honours TOP_N =="
|
||||
reset_state
|
||||
printf '%s\n' "9 alpha" "8 bravo" "7 charlie" "6 delta" >"${RESULTS_DIR}/grep_keywords.txt"
|
||||
: >"${RESULTS_DIR}/grep_function_calls.txt"
|
||||
: >"${RESULTS_DIR}/grep_imports.txt"
|
||||
TOP_N=2
|
||||
generate_doc_links >/dev/null
|
||||
docs="$(cat "${DOCS_FILE}")"
|
||||
_t_has "$docs" "alpha" "the top term is included"
|
||||
if [[ "$docs" == *"charlie"* ]]; then
|
||||
_t_fail "a term past TOP_N is excluded"
|
||||
else
|
||||
_t_pass "a term past TOP_N is excluded"
|
||||
fi
|
||||
|
||||
echo "== generate_doc_links: missing input files are not fatal =="
|
||||
reset_state
|
||||
# A repo with no imports at all is normal, and the analysis simply does not
|
||||
# write that file. The phase must still produce its other sections.
|
||||
printf '%s\n' "9 def" >"${RESULTS_DIR}/grep_keywords.txt"
|
||||
generate_doc_links >/dev/null
|
||||
_t_has "$(cat "${DOCS_FILE}")" "def" "the surviving section is still written"
|
||||
|
||||
echo "== generate_doc_links: uses the offline mirror when installed =="
|
||||
reset_state
|
||||
stage_results
|
||||
enable_offline_docs "${OFFLINE_DOCS_DIR}/python/os.md"
|
||||
generate_doc_links >/dev/null
|
||||
_t_has "$(cat "${DOCS_FILE}")" "${OFFLINE_DOCS_DIR}" "cards cite a local path an assistant can read"
|
||||
|
||||
echo "== generate_doc_links: per-language mode =="
|
||||
reset_state
|
||||
stage_results
|
||||
# The presence of per_language/ switches the phase onto an entirely separate
|
||||
# path that resolves each language's terms against that language's docs.
|
||||
stage_per_language python javascript rust
|
||||
generate_doc_links >/dev/null
|
||||
docs="$(cat "${DOCS_FILE}")"
|
||||
_t_has "$docs" "Language Keywords" "the per-language section header is written"
|
||||
_t_has "$docs" "Python" "a language gets a display name"
|
||||
_t_has "$docs" "JavaScript" "the JavaScript display name is mapped"
|
||||
_t_has "$docs" "Rust" "a third language is included"
|
||||
_t_has "$docs" "alpha_python" "a per-language keyword is listed"
|
||||
_t_has "$docs" "fn_javascript" "a per-language function is listed"
|
||||
_t_has "$docs" "mod_rust" "a per-language import is listed"
|
||||
|
||||
echo "== generate_doc_links: per-language name mapping =="
|
||||
reset_state
|
||||
stage_results
|
||||
stage_per_language c_cpp typescript shell
|
||||
generate_doc_links >/dev/null
|
||||
docs="$(cat "${DOCS_FILE}")"
|
||||
_t_has "$docs" "C/C++" "c_cpp maps to the C/C++ display name"
|
||||
_t_has "$docs" "TypeScript" "typescript maps to its display name"
|
||||
_t_has "$docs" "Shell/Bash" "shell maps to the Shell/Bash display name"
|
||||
|
||||
echo "== generate_doc_links: per-language covers the remaining names =="
|
||||
reset_state
|
||||
stage_results
|
||||
stage_per_language go ruby java klingon
|
||||
generate_doc_links >/dev/null
|
||||
docs="$(cat "${DOCS_FILE}")"
|
||||
_t_has "$docs" "Go" "go maps to its display name"
|
||||
_t_has "$docs" "Ruby" "ruby maps to its display name"
|
||||
_t_has "$docs" "Java" "java maps to its display name"
|
||||
_t_has "$docs" "klingon" "an unmapped language falls back to its raw name"
|
||||
|
||||
echo "== generate_doc_links: per-language skips empty and comment lines =="
|
||||
reset_state
|
||||
stage_results
|
||||
stage_per_language python
|
||||
# An empty file and a comment-only line are both normal analysis output; each
|
||||
# must be skipped rather than producing a card with no term.
|
||||
: >"${RESULTS_DIR}/per_language/functions_python.txt"
|
||||
printf '%s\n' "# a comment" "5 realterm" >"${RESULTS_DIR}/per_language/imports_python.txt"
|
||||
generate_doc_links >/dev/null
|
||||
docs="$(cat "${DOCS_FILE}")"
|
||||
_t_has "$docs" "realterm" "the real term survives"
|
||||
if [[ "$docs" == *"a comment"* ]]; then
|
||||
_t_fail "a comment line is skipped"
|
||||
else
|
||||
_t_pass "a comment line is skipped"
|
||||
fi
|
||||
|
||||
echo "== generate_anki_cards: tab-separated with a header =="
|
||||
reset_state
|
||||
stage_results
|
||||
generate_anki_cards >/dev/null
|
||||
anki="$(cat "${ANKI_FILE}")"
|
||||
_t_has "$anki" "Anki Import File" "the importer header is present"
|
||||
_t_has "$anki" "Fields separated by: Tab" "the header states the separator"
|
||||
_t_has "$anki" "def" "a keyword card is written"
|
||||
_t_has "$anki" "print" "a function card is written"
|
||||
# Every non-comment line must carry at least one tab, or the import silently
|
||||
# collapses the card into a single field.
|
||||
bad=0
|
||||
while IFS= read -r line; do
|
||||
[[ -z "$line" || "$line" == \#* ]] && continue
|
||||
[[ "$line" == *$'\t'* ]] || bad=$((bad + 1))
|
||||
done <"${ANKI_FILE}"
|
||||
_t_eq "0" "$bad" "every card line is tab-separated"
|
||||
|
||||
echo "== generate_anki_cards: honours TOP_N =="
|
||||
reset_state
|
||||
printf '%s\n' "9 alpha" "8 bravo" "7 charlie" >"${RESULTS_DIR}/grep_keywords.txt"
|
||||
: >"${RESULTS_DIR}/grep_function_calls.txt"
|
||||
TOP_N=1
|
||||
generate_anki_cards >/dev/null
|
||||
anki="$(cat "${ANKI_FILE}")"
|
||||
_t_has "$anki" "alpha" "the top term becomes a card"
|
||||
if [[ "$anki" == *"bravo"* ]]; then
|
||||
_t_fail "a term past TOP_N is excluded"
|
||||
else
|
||||
_t_pass "a term past TOP_N is excluded"
|
||||
fi
|
||||
|
||||
echo "== generate_anki_cards: no input files still writes a valid file =="
|
||||
reset_state
|
||||
generate_anki_cards >/dev/null
|
||||
_t_has "$(cat "${ANKI_FILE}")" "Anki Import File" "an empty analysis still produces an importable file"
|
||||
|
||||
echo "== generate_anki_cards: one card template per keyword category =="
|
||||
reset_state
|
||||
# Each category gets its own answer text, so a card for `if` explains control
|
||||
# flow rather than repeating a generic definition. Covering every arm is what
|
||||
# proves no category silently falls through to the default template.
|
||||
printf '%s\n' "9 if" "8 for" "7 try" "6 class" "5 async" "4 frobnicate" \
|
||||
>"${RESULTS_DIR}/grep_keywords.txt"
|
||||
: >"${RESULTS_DIR}/grep_function_calls.txt"
|
||||
TOP_N=6
|
||||
generate_anki_cards >/dev/null
|
||||
anki="$(cat "${ANKI_FILE}")"
|
||||
_t_has "$anki" "Conditional control flow" "a conditional keyword gets the control-flow answer"
|
||||
_t_has "$anki" "Loop construct" "a loop keyword gets the loop answer"
|
||||
_t_has "$anki" "Exception handling" "an exception keyword gets the exception answer"
|
||||
_t_has "$anki" "Type definition" "a type keyword gets the type answer"
|
||||
_t_has "$anki" "Asynchronous programming" "an async keyword gets the async answer"
|
||||
_t_has "$anki" "frobnicate" "an uncategorised keyword still gets a card"
|
||||
|
||||
echo "== generate_llm_prompt: project-internal items are skipped =="
|
||||
reset_state
|
||||
# A relative or aliased import points at the repo being studied, not at any
|
||||
# documentation, so a flashcard for it could only be answered from guesswork.
|
||||
# These must be marked skippable rather than sent to the assistant as a topic.
|
||||
printf '%s\n' "9 ./local_module" "8 @/aliased" "7 src/thing" "6 app.config" "5 os" \
|
||||
>"${RESULTS_DIR}/grep_imports.txt"
|
||||
printf '%s\n' "9 def" >"${RESULTS_DIR}/grep_keywords.txt"
|
||||
printf '%s\n' "8 print" >"${RESULTS_DIR}/grep_function_calls.txt"
|
||||
TOP_N=5
|
||||
generate_llm_prompt >/dev/null
|
||||
_t_has "$(cat "${LLM_PROMPT_FILE}")" "INTERNAL - SKIP" "an internal import is marked skippable"
|
||||
|
||||
echo "== generate_llm_prompt: single-letter functions are dropped =="
|
||||
reset_state
|
||||
# Minified JS turns every function into one or two characters. A flashcard for
|
||||
# `a` teaches nothing and cannot be looked up, so those are dropped rather than
|
||||
# sent to the assistant as topics.
|
||||
printf '%s\n' "9 def" >"${RESULTS_DIR}/grep_keywords.txt"
|
||||
printf '%s\n' "9 a" "8 b" "7 realFunction" >"${RESULTS_DIR}/grep_function_calls.txt"
|
||||
printf '%s\n' "6 os" >"${RESULTS_DIR}/grep_imports.txt"
|
||||
TOP_N=5
|
||||
generate_llm_prompt >/dev/null
|
||||
prompt="$(cat "${LLM_PROMPT_FILE}")"
|
||||
_t_has "$prompt" "realFunction" "a real function name survives"
|
||||
if [[ "$prompt" =~ [0-9]+\ a$'\n' ]]; then
|
||||
_t_fail "a single-letter function is dropped"
|
||||
else
|
||||
_t_pass "a single-letter function is dropped"
|
||||
fi
|
||||
|
||||
echo "== generate_llm_prompt: keeps the read-the-docs instructions =="
|
||||
reset_state
|
||||
stage_results
|
||||
generate_llm_prompt >/dev/null
|
||||
prompt="$(cat "${LLM_PROMPT_FILE}")"
|
||||
# These four instructions are the entire reason the prompt exists: without
|
||||
# them an assistant writes flashcards from memory, which is exactly the
|
||||
# failure the offline-docs pipeline was built to prevent.
|
||||
_t_has "$prompt" "READ DOCS VIA TERMINAL" "the read-the-file instruction survives"
|
||||
_t_has "$prompt" "DO NOT USE YOUR OWN KNOWLEDGE" "the no-memory instruction survives"
|
||||
_t_has "$prompt" "IF YOU CANNOT READ A FILE" "the unreadable-file instruction survives"
|
||||
_t_has "$prompt" "NEVER FALL BACK TO GENERAL KNOWLEDGE" "the no-fallback instruction survives"
|
||||
_t_has "$prompt" "def" "the extracted keywords are listed"
|
||||
|
||||
echo "== generate_llm_prompt: import lines are handled as imports =="
|
||||
reset_state
|
||||
stage_results
|
||||
printf '%s\n' "12 import os" "7 from sys import argv" >"${RESULTS_DIR}/grep_imports.txt"
|
||||
generate_llm_prompt >/dev/null
|
||||
_t_has "$(cat "${LLM_PROMPT_FILE}")" "os" "a whole import statement still resolves to its module"
|
||||
|
||||
echo "== generate_llm_prompt: offline paths are cited when available =="
|
||||
reset_state
|
||||
stage_results
|
||||
enable_offline_docs "${OFFLINE_DOCS_DIR}/python/os.md"
|
||||
generate_llm_prompt >/dev/null
|
||||
_t_has "$(cat "${LLM_PROMPT_FILE}")" "${OFFLINE_DOCS_DIR}" "the prompt cites readable local paths"
|
||||
|
||||
echo "== generate_llm_prompt: no inputs still writes the instructions =="
|
||||
reset_state
|
||||
generate_llm_prompt >/dev/null
|
||||
_t_has "$(cat "${LLM_PROMPT_FILE}")" "DO NOT USE YOUR OWN KNOWLEDGE" \
|
||||
"an empty analysis still produces a usable prompt"
|
||||
|
||||
_t_summary
|
||||
Loading…
Reference in New Issue
Block a user