Delminio — the client
Clonegit clone https://git.delminio.com/delminio-client2026.11.26-b027f1c · 26 Nov 2026

delminio-client / kit / it / copia-client

raw · sha256 1f9a859c4fe44d0534e216f5fac3e311742644b83e9375a3e0893a7dce4fdcdf

1#!/usr/bin/env python3
2# © 2026 Delminio — tutti i diritti riservati. Software proprietario: l'uso con Delminio è regolato dal contratto con cui si usa il servizio; la lettura e la verifica da LICENCE.
3"""La copia di sicurezza di ciò che c'era prima del collegamento (F777)."""
4import hashlib, json, os, re, shutil, sys, time
5exec(__import__('os').environ['DELMINIO_F_PY'])
6modo, radice, memoria, comune, url, gitdir = sys.argv[1:7]
7casa = os.path.expanduser('~')
8config = os.environ.get('CLAUDE_CONFIG_DIR') or os.path.join(casa, '.claude')
9memoria = os.path.realpath(memoria) if memoria else ''
10
11def leggi(p):
12    try:
13        with open(p, encoding='utf-8') as f:
14            return json.load(f)
15    except (OSError, ValueError):
16        return {}
17scelta, da = ('', '')
18for f, nome in ((os.path.join(radice, '.claude', 'settings.local.json'), '.claude/settings.local.json'), (os.path.join(radice, '.claude', 'settings.json'), '.claude/settings.json'), (os.path.join(config, 'settings.json'), os.path.join(config, 'settings.json'))):
19    v = leggi(f).get('autoMemoryDirectory')
20    v = os.path.realpath(os.path.expanduser(v)) if isinstance(v, str) and v else ''
21    if v and v != memoria:
22        scelta, da = (v, nome)
23        break
24progetto = os.environ.get('CLAUDE_CODE_PROJECT_DIR_NAME') or re.sub('[^A-Za-z0-9]', '-', comune)
25vecchia = scelta or os.path.join(config, 'projects', progetto, 'memory')
26if modo == 'controlla':
27    if scelta and memoria:
28        print(f'{scelta}\t{da}')
29    sys.exit(0)
30segno_backup = os.path.join(gitdir, 'delminio-backup')
31cartella = os.path.join(os.environ.get('XDG_DATA_HOME') or os.path.join(casa, '.local', 'share'), 'delminio', 'backup', (re.sub('[^A-Za-z0-9._-]', '-', os.path.basename(comune)) or 'repo') + '-' + hashlib.sha256(comune.encode()).hexdigest()[:12])
32try:
33    cartella = open(segno_backup, encoding='utf-8').read().strip() or cartella
34except OSError:
35    pass
36
37def una_copia_c_e():
38    for c in (cartella, os.path.join(radice, '.claude', 'delminio-prima')):
39        if os.path.isdir(c) and any((os.path.isfile(os.path.join(c, d, 'fatti.json')) for d in os.listdir(c))):
40            return True
41    return False
42if os.environ.get('DELMINIO_PRIMA_VOLTA') != 'si' and una_copia_c_e():
43    sys.exit(0)
44dest = os.path.join(cartella, time.strftime('%Y-%m-%d-%H%M%S'))
45copie = []
46copiati = []
47non_copiati = []
48peso = 0
49SEGRETO = re.compile('(^|/)(auth\\.json|\\.credentials\\.json|oauth_creds\\.json|credentials(\\.json)?|\\.env(\\.[^/]*)?|[^/]*\\.(token|pem|key|p12|pfx)|id_(rsa|ed25519|ecdsa|dsa)[^/]*|\\.netrc|\\.git-credentials)$', re.I)
50TETTO_FILE = 20 * 1024 * 1024
51TETTO = 200 * 1024 * 1024
52
53def mostra(p):
54    p = os.path.abspath(p)
55    if p == radice or p.startswith(radice + os.sep):
56        return os.path.relpath(p, radice)
57    return '~' + p[len(casa):] if p.startswith(casa + os.sep) else p
58
59def impronta(p):
60    h = hashlib.sha256()
61    with open(p, 'rb') as f:
62        for pezzo in iter(lambda: f.read(1 << 20), b''):
63            h.update(pezzo)
64    return h.hexdigest()
65
66def metti(sorgente, rel, gruppo):
67    global peso
68    if not os.path.isfile(sorgente):
69        return False
70    if SEGRETO.search(sorgente):
71        non_copiati.append({'da': mostra(sorgente), 'perche': 'credenziali'})
72        return False
73    n = os.path.getsize(sorgente)
74    if n > TETTO_FILE or peso + n > TETTO:
75        non_copiati.append({'da': mostra(sorgente), 'perche': 'grande', 'byte': n})
76        return False
77    p = os.path.join(dest, rel)
78    os.makedirs(os.path.dirname(p), exist_ok=True)
79    shutil.copy2(sorgente, p)
80    prima, dopo = (impronta(sorgente), impronta(p))
81    if prima != dopo:
82        print(F('prima_copia_diversa', file=mostra(sorgente)), file=sys.stderr)
83        sys.exit(1)
84    peso += n
85    copiati.append({'da': mostra(sorgente), 'copia': rel, 'sha256': prima, 'byte': n, 'gruppo': gruppo})
86    return True
87
88def metti_cartella(d, rel, gruppo):
89    if not os.path.isdir(d):
90        return
91    for su, cartelle, files in os.walk(d):
92        cartelle[:] = sorted((c for c in cartelle if c not in ('.git', 'node_modules')))
93        for f in sorted(files):
94            metti(os.path.join(su, f), os.path.join(rel, os.path.relpath(os.path.join(su, f), d)), gruppo)
95
96def nel_progetto(rel, gruppo):
97    p = os.path.join(radice, rel)
98    if os.path.isdir(p):
99        metti_cartella(p, rel, gruppo)
100    else:
101        metti(p, rel, gruppo)
102
103def in_casa(p, gruppo):
104    p = os.path.abspath(p)
105    rel = os.path.join('casa', os.path.relpath(p, casa)) if p.startswith(casa + os.sep) else os.path.join('fuori', p.lstrip(os.sep))
106    if os.path.isdir(p):
107        metti_cartella(p, rel, gruppo)
108    else:
109        metti(p, rel, gruppo)
110codex = os.environ.get('CODEX_HOME') or os.path.join(casa, '.codex')
111qwen_casa = os.path.join(casa, '.qwen')
112for rel in (os.environ.get('DELMINIO_KIT_FILE') or '').split() + ['.claude/mneme.sh', '.claude/commands/risveglio.md']:
113    nel_progetto(rel, 'collegamento')
114for g in ('commit-msg', 'post-commit', 'post-rewrite'):
115    metti(os.path.join(os.environ.get('DELMINIO_GANCI') or os.path.join(gitdir, 'hooks'), g), os.path.join('git', 'hooks', g), 'collegamento')
116metti(os.path.join(gitdir, 'info', 'exclude'), os.path.join('git', 'info', 'exclude'), 'collegamento')
117in_casa(os.path.join(os.environ.get('CLAUDE_CONFIG_DIR') or casa, '.claude.json'), 'collegamento')
118for rel in ('CLAUDE.md', '.claude/CLAUDE.md', 'CLAUDE.local.md', 'AGENTS.md', 'AGENTS.override.md', 'GEMINI.md', 'QWEN.md', '.cursorrules', '.windsurfrules', '.clinerules', '.github/copilot-instructions.md', '.github/instructions', '.cursor/rules', '.windsurf/rules', 'memory-bank', '.serena/memories', '.claude/agents', '.claude/skills'):
119    nel_progetto(rel, 'istruzioni')
120for p in (os.path.join(config, 'CLAUDE.md'), os.path.join(codex, 'AGENTS.md'), os.path.join(codex, 'AGENTS.override.md'), os.path.join(casa, '.gemini', 'GEMINI.md'), os.path.join(qwen_casa, 'QWEN.md')):
121    in_casa(p, 'istruzioni')
122for rel in ('.claude/settings.json', '.mcp.json', '.codex/config.toml', '.qwen/commands'):
123    nel_progetto(rel, 'impostazioni')
124for p in (os.path.join(config, 'settings.json'), os.path.join(codex, 'config.toml'), os.path.join(codex, 'hooks.json'), os.path.join(qwen_casa, 'settings.json')):
125    in_casa(p, 'impostazioni')
126chiesti = [r.strip() for r in re.split('[\\n:]', os.environ.get('DELMINIO_COPIA_ANCHE') or '') if r.strip()]
127for r in chiesti:
128    p = os.path.realpath(os.path.join(radice, os.path.expanduser(r)))
129    if not (p.startswith(radice + os.sep) or p.startswith(casa + os.sep)):
130        non_copiati.append({'da': r, 'perche': 'fuori'})
131    elif not os.path.exists(p):
132        non_copiati.append({'da': r, 'perche': 'assente'})
133    elif p.startswith(radice + os.sep):
134        nel_progetto(os.path.relpath(p, radice), 'chiesto')
135    else:
136        in_casa(p, 'chiesto')
137for rel in ('CLAUDE.md', '.claude/CLAUDE.md', 'CLAUDE.local.md', '.claude/settings.local.json', '.codex/hooks.json', '.qwen/settings.json'):
138    if os.path.isfile(os.path.join(radice, rel)):
139        copie.append(rel)
140for rel in ('.claude/commands/apertura.md', '.claude/commands/chiusura.md', '.qwen/commands/apertura.md', '.qwen/commands/chiusura.md'):
141    p = os.path.join(radice, rel)
142    segno = 'Delminio' if rel.startswith('.qwen/') else 'delminio.sh'
143    if os.path.isfile(p) and segno not in open(p, encoding='utf-8', errors='replace').read():
144        copie.append(rel)
145note = sorted((n for n in os.listdir(vecchia) if n.endswith('.md'))) if os.path.isdir(vecchia) and os.path.realpath(vecchia) != memoria else []
146if note:
147    metti_cartella(vecchia, 'memoria', 'note')
148mcp = (leggi(os.path.join(os.environ.get('CLAUDE_CONFIG_DIR') or casa, '.claude.json')).get('projects', {}).get(radice, {}).get('mcpServers') or {}).get('memoria')
149if mcp and (not str(mcp.get('url', '')).startswith(url)):
150    os.makedirs(dest, exist_ok=True)
151    with open(os.path.join(dest, 'mcp-memoria.json'), 'w', encoding='utf-8') as f:
152        json.dump(mcp, f, indent=2)
153    copie.append('mcp-memoria.json')
154else:
155    mcp = None
156
157def nostro(testo):
158    return 'delminio.sh' in str(testo)
159
160def hook_di(s):
161    out = {}
162    for ev, lista in (s.get('hooks') or {} if isinstance(s.get('hooks'), dict) else {}).items():
163        n = sum((1 for b in lista or [] if isinstance(b, dict) for h in b.get('hooks') or [] if isinstance(h, dict) and (not nostro(h.get('command', '')))))
164        if n:
165            out[ev] = n
166    return out
167
168def file_in(d, est='.md'):
169    if not os.path.isdir(d):
170        return []
171    out = []
172    for n in sorted(os.listdir(d)):
173        p = os.path.join(d, n)
174        if n.endswith(est) and os.path.isfile(p):
175            try:
176                if nostro(open(p, encoding='utf-8', errors='replace').read()):
177                    continue
178            except OSError:
179                pass
180            out.append(n[:-len(est)])
181    return out
182
183def cartelle_in(d):
184    return sorted((n for n in os.listdir(d) if os.path.isdir(os.path.join(d, n)))) if os.path.isdir(d) else []
185conf = {}
186
187def segna(dove, cosa, valore):
188    if valore:
189        conf.setdefault(dove, {})[cosa] = valore
190for f, dove in ((os.path.join(config, 'settings.json'), '~/.claude/settings.json'), (os.path.join(radice, '.claude', 'settings.json'), '.claude/settings.json'), (os.path.join(radice, '.claude', 'settings.local.json'), '.claude/settings.local.json')):
191    s = leggi(f)
192    if not isinstance(s, dict):
193        continue
194    segna(dove, 'hook', hook_di(s))
195    segna(dove, 'plugin', sorted((k for k, on in (s.get('enabledPlugins') or {}).items() if on)) if isinstance(s.get('enabledPlugins'), dict) else [])
196    segna(dove, 'stile', s.get('outputStyle') if isinstance(s.get('outputStyle'), str) else '')
197    segna(dove, 'permessi_negati', len((s.get('permissions') or {}).get('deny') or []) if isinstance(s.get('permissions'), dict) else 0)
198    segna(dove, 'hook_spenti', s.get('disableAllHooks') is True)
199for base, dove in ((config, '~/.claude'), (os.path.join(radice, '.claude'), '.claude')):
200    segna(dove + '/commands', 'comandi', file_in(os.path.join(base, 'commands')))
201    segna(dove + '/agents', 'agenti', file_in(os.path.join(base, 'agents')))
202    segna(dove + '/skills', 'skill', cartelle_in(os.path.join(base, 'skills')))
203    segna(dove + '/output-styles', 'stili', file_in(os.path.join(base, 'output-styles')))
204cj = leggi(os.path.join(os.environ.get('CLAUDE_CONFIG_DIR') or casa, '.claude.json'))
205
206def suoi_server(d):
207    return sorted((k for k, s in (d or {}).items() if not (k in ('memoria', 'delminio') and isinstance(s, dict) and str(s.get('url', '')).startswith(url))))
208if isinstance(cj, dict):
209    segna('~/.claude.json', 'mcp', suoi_server(cj.get('mcpServers')))
210    segna('~/.claude.json (' + F('prima_questo_progetto') + ')', 'mcp', suoi_server((cj.get('projects') or {}).get(radice, {}).get('mcpServers')))
211mj = leggi(os.path.join(radice, '.mcp.json'))
212if isinstance(mj, dict):
213    segna('.mcp.json', 'mcp', suoi_server(mj.get('mcpServers')))
214codex = os.environ.get('CODEX_HOME') or os.path.join(casa, '.codex')
215ct = os.path.join(codex, 'config.toml')
216if os.path.isfile(ct):
217    testo = open(ct, encoding='utf-8', errors='replace').read()
218    segna('~/.codex/config.toml', 'mcp', sorted(set((m for m in re.findall('^\\[mcp_servers\\.([A-Za-z0-9_-]+)\\]', testo, re.M) if m != 'delminio'))))
219    segna('~/.codex/config.toml', 'profili', sorted(set(re.findall('^\\[profiles\\.([A-Za-z0-9_-]+)\\]', testo, re.M))))
220segna('~/.codex/hooks.json', 'hook', hook_di(leggi(os.path.join(codex, 'hooks.json')) or {}))
221segna('~/.codex/prompts', 'comandi', file_in(os.path.join(codex, 'prompts')))
222altri = {}
223
224def righe_di(p):
225    try:
226        with open(p, encoding='utf-8', errors='replace') as f:
227            testo = f.read()
228    except OSError:
229        return (None, '')
230    return (None, '') if nostro(testo) else (len(testo.splitlines()), testo)
231
232def voci_qwen(testo):
233    m = re.search('^##\\s*Qwen Added Memories\\s*$(.*?)(?=^##\\s|\\Z)', testo, re.M | re.S)
234    return sum((1 for r in m.group(1).splitlines() if r.lstrip().startswith('- '))) if m else 0
235
236def file_altro(dove, p, cosa):
237    n, testo = righe_di(p)
238    if n:
239        v = {'cosa': cosa, 'righe': n}
240        if os.path.basename(p) == 'QWEN.md' and (q := voci_qwen(testo)):
241            v['memorie'] = q
242        altri[dove] = v
243
244def cartella_altro(dove, d, cosa):
245    if os.path.isdir(d):
246        n = sum((1 for _, _, fs in os.walk(d) for f in fs if f.endswith(('.md', '.mdc', '.txt'))))
247        if n:
248            altri[dove + '/'] = {'cosa': cosa, 'file': n}
249for rel in ('AGENTS.md', 'GEMINI.md', 'QWEN.md', '.cursorrules', '.windsurfrules', '.clinerules', '.github/copilot-instructions.md'):
250    if os.path.isfile(os.path.join(radice, rel)):
251        file_altro(rel, os.path.join(radice, rel), 'istruzioni')
252for rel in ('.cursor/rules', '.windsurf/rules', '.clinerules', '.github/instructions'):
253    cartella_altro(rel, os.path.join(radice, rel), 'istruzioni')
254for rel in ('memory-bank', '.serena/memories'):
255    cartella_altro(rel, os.path.join(radice, rel), 'memoria')
256for p, dove in ((os.path.join(config, 'CLAUDE.md'), '~/.claude/CLAUDE.md'), (os.path.join(codex, 'AGENTS.md'), '~/.codex/AGENTS.md'), (os.path.join(casa, '.gemini', 'GEMINI.md'), '~/.gemini/GEMINI.md'), (os.path.join(casa, '.qwen', 'QWEN.md'), '~/.qwen/QWEN.md')):
257    file_altro(dove, p, 'istruzioni personali')
258for v in altri.values():
259    if v.get('memorie'):
260        v['cosa'] += ' + memoria'
261da_ripassare = bool(copie or note or conf or altri or chiesti)
262os.makedirs(dest, exist_ok=True)
263with open(os.path.join(dest, 'fatti.json'), 'w', encoding='utf-8') as f:
264    json.dump({'radice': radice, 'copie': copie, 'memoria': {'cartella': vecchia, 'scelta_in': da, 'note': note}, 'configurazioni': conf, 'altri_strumenti': altri, 'file': copiati, 'non_copiati': non_copiati, 'chiesti': chiesti, 'aggancio_di_prima': os.path.isfile(os.path.join(radice, '.claude', 'delminio.sh'))}, f, indent=2, ensure_ascii=False)
265if not da_ripassare:
266    with open(os.path.join(dest, 'RIPASSATO'), 'w', encoding='utf-8') as f:
267        f.write(time.strftime('%Y-%m-%d %H:%M') + ' ' + F('prima_niente_da_ripassare') + '\n')
268with open(segno_backup, 'w', encoding='utf-8') as f:
269    f.write(cartella + '\n')
270DETTO = {'CLAUDE.md': F('prima_claude_md'), '.claude/CLAUDE.md': F('prima_claude_md'), 'CLAUDE.local.md': F('prima_claude_local'), '.claude/settings.local.json': F('prima_settings'), '.codex/hooks.json': F('prima_hook_codex'), '.qwen/settings.json': F('prima_qwen'), '.claude/commands/apertura.md': F('prima_apertura'), '.claude/commands/chiusura.md': F('prima_chiusura'), '.qwen/commands/apertura.md': F('prima_apertura'), '.qwen/commands/chiusura.md': F('prima_chiusura'), 'mcp-delminio.json': F('prima_mcp', nome='delminio'), 'mcp-memoria.json': F('prima_mcp', nome='memoria')}
271righe = [f'- `{c}` — {DETTO[c]}' for c in copie]
272if note:
273    righe.append(F('prima_note', n=len(note), cartella=vecchia))
274if conf:
275    righe.append(F('prima_configurazioni'))
276if altri:
277    righe.append(F('prima_altri', elenco=', '.join((f'`{k}`' for k in altri))))
278if chiesti:
279    righe.append(F('prima_chiesti', elenco=', '.join((f'`{k}`' for k in chiesti))))
280righe.append(F('prima_tutti', n=len(copiati)))
281PERCHE = {'credenziali': F('prima_perche_credenziali'), 'grande': F('prima_perche_grande'), 'fuori': F('prima_perche_fuori'), 'assente': F('prima_perche_assente')}
282for v in non_copiati:
283    righe.append(F('prima_non_copiato', file=v['da'], perche=PERCHE[v['perche']]))
284with open(os.path.join(dest, 'LEGGIMI.md'), 'w', encoding='utf-8') as f:
285    f.write('# ' + F('prima_leggimi_titolo') + '\n\n' + F('prima_leggimi_testa') + '\n\n' + '\n'.join(righe) + '\n\n' + F('prima_leggimi_note') + '\n\n' + F('prima_leggimi_tornare') + '\n')
286print(mostra(dest))