diff --git a/CHANGELOG.md b/CHANGELOG.md index 9ff9221..0e69b33 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,24 @@ # Changelog +## 0.7.0 + +- Contributors view in the Source Control panel: everyone who committed to the current branch, by number of commits + (one person per email, even with several names). Expand someone to see their commits and click one for its files. + The same commit menu as File History: copy the SHA, open it on the remote. +- Visual File History: the SHA in the tooltip no longer has extra background on its left, and counts of one say + "1 commit" and "1 author". +- Commit graph: commit details open instantly the second time (they are kept while the graph is open), without the + expand animation, and the loading placeholder only shows if loading takes a moment. +- Commit graph: easier to find where you are among many branches. Commits that are not in the history of your HEAD + are dimmed (toggle it with the target button in the toolbar), and when your commit scrolls out of view a "↑ main" + / "↓ main" button takes you back to it, loading more commits if needed. +- Fix: on tall screens the rows of the commit graph no longer pop in all at once halfway down while it draws. + +- The commit graph redraws by itself when any branch, remote branch, tag or stash moves: VS Code's background + auto-fetch (`git.autofetch`), a fetch or push from the terminal, or branches, tags and stashes made outside it. + Before, it only noticed changes to the current branch and to uncommitted files. +- Fix: hovering a row no longer clips the ring of the current branch badge or the node of the leftmost lane. + ## 0.6.0 - Step through a file's revisions from the editor title: ← opens the diff of the previous commit to the file, → the diff --git a/README.md b/README.md index 25bfa73..3b3cc53 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,7 @@ # Git Lore -Free and open-source Git superpowers for VS Code: blame, file and line history, a commit graph and branch comparison. +Free and open-source Git superpowers for VS Code: blame, file and line history, a visual file history, revision +navigation, a commit graph you can work from (branches, checkout, merge, cherry-pick, stash…) and branch comparison. No account, no sign-in, no trial, no paywall, no telemetry. MIT licensed. ![Git Lore](images/icon.png) @@ -16,26 +17,39 @@ No account, no sign-in, no trial, no paywall, no telemetry. MIT licensed. - **File history and line history.** A *File History* view in the Source Control panel follows the active editor and lists every commit that touched the file, renames included. Select some lines and run `Show Line History` (editor context menu) to see only the commits that changed them. Click a commit to open its diff. +- **Contributors.** A *Contributors* view in the Source Control panel lists everyone who committed to the current + branch, by number of commits. Expand a person to see their commits; click one for its files and diffs. - **Visual file history.** `Show Visual File History` (editor context menu, Explorer, or the icon in the File History view) puts every commit to a file on a timeline: one row per author, dots sized by the lines changed, and added and - deleted lines underneath. Hover a dot for the commit, click it for its diff. + deleted lines underneath. Hover a dot for the commit, click it for its diff, or move between commits with the arrow + keys. Hover an author to highlight their commits. - **Revision navigation.** The ← and → buttons in the editor title step through the commits that changed the file, each as a diff; → from the newest commit returns to the working file. -- **Commit graph.** `Show Commit Graph` (the Graph button in the status bar, or the merge icon in the Source Control title) draws every branch, local and remote, - with branch and tag badges, in a full editor tab. Click a commit to open its details inline: full message, author, - parents and the changed files, each one opening its diff. A row above HEAD shows your uncommitted changes, and you can - show all branches, local branches only or the current branch. It loads more commits as you scroll and filters by - message, author, ref or SHA. Works the same on public and private repositories. - Right-click a commit (or press Shift+F10 on it) to create a branch or tag there, check it out, cherry-pick it, revert it - or reset the current branch to it. Right-click a branch or tag badge to check it out, merge it into the current - branch or delete it; checking out a remote branch creates the local branch that tracks it. - Right-click a file in the commit details to open its changes, open it at that revision, compare it with the working - file, open the working file, copy its path or restore it to that revision. The download button in the - graph toolbar fetches from all remotes. Deleting and `reset --hard` ask first. - Stashes appear as rows on the commit they were made on (apply, pop or drop them from their menu), and branches - checked out in other worktrees are marked, with an option to open that worktree in a new window. -- **Compare.** `Compare Branches or Refs…` (the compare icon in the Source Control title) lists the files that differ between two branches, tags or commits (you can - type any SHA), or between a ref and your working tree. Click a file for its diff; swap the sides from the view title. +- **Commit graph.** `Show Commit Graph` (the Graph button in the status bar, or the merge icon in the Source Control + title) draws every branch, local and remote, in a full editor tab, in the spirit of Git Graph. + - *Reading it:* colored lanes, with branch and tag badges in the color of their lane (local branches filled, remote + ones tinted, tags neutral). Hover a message, author or badge for the full text. A row above HEAD shows your + uncommitted changes. Choose all branches, local branches or the current branch, filter by message, author, ref or + SHA, and scroll to load more. Drag the graph's edge to make it wider (double-click to reset). + With many branches, commits outside the history of your HEAD are dimmed (toggle it from the toolbar) and a floating + button takes you back to your commit when it is out of view. + - *Commit details:* click a commit (or press Enter; arrows move between rows) to open its message, author, parents and + changed files inline. Each file opens its diff; right-click it to open it at that revision, compare it with the + working file, open the working file, copy its path or restore it to that revision. + - *Working from it:* right-click a commit (or Shift+F10) to create a branch or tag on it, check it out, cherry-pick + it, revert it or reset the current branch to it. Right-click a badge to check out, merge into the current branch or + delete it; checking out a remote branch creates the local branch that tracks it. The toolbar button fetches from + all remotes. Deleting and `reset --hard` ask first. + - *Stashes and worktrees:* stashes are rows on the commit they were made on (apply, pop or drop them from their + menu). Branches checked out in another worktree carry a folder icon, a detached worktree gets its own badge, and + you can open any of them in a new window. + - *Always current:* it redraws by itself when HEAD, your uncommitted files or any branch, tag or stash changes, + including fetches, pushes and branches made from the terminal. Turn on VS Code's `git.autofetch` to keep remote + branches fresh in the background. + + Works the same on public and private repositories. +- **Compare.** `Compare Branches or Refs…` (the compare icon in the Source Control title) lists the files that differ + between two branches, tags or commits (you can type any SHA), or between a ref and your working tree. Click a file for its diff; swap the sides from the view title. Everything is localized in English and Spanish. @@ -47,6 +61,8 @@ Everything is localized in English and Spanish. The colors are themeable: `gitLore.currentLineForeground`, `gitLore.fileBlameForeground`, `gitLore.fileBlameBackground`. +For a commit graph that keeps remote branches fresh, enable VS Code's `git.autofetch` (and `git.autofetchPeriod`). + If you also enable VS Code's own blame (`git.blame.editorDecoration.enabled`), you will see the blame twice; keep one. ## Requirements @@ -56,8 +72,10 @@ It works in local folders and remote workspaces (SSH, WSL, containers). ## How it works -Git Lore only runs read-only git commands (`blame`, `log`, `show`, `diff`, `for-each-ref`) in your repository. It never -changes your repository, sends nothing anywhere and has no telemetry. +Git Lore runs `git` in your repository with the binary of the built-in Git extension. On its own it only reads (`blame`, +`log`, `show`, `diff`, `for-each-ref`, `stash list`, `worktree list`). It only changes your repository when you pick an +action in the commit graph (checkout, branch, tag, merge, cherry-pick, revert, reset, stash, restore a file, fetch), +and the destructive ones ask first. It sends nothing anywhere and has no telemetry. ## Contributing diff --git a/extension.js b/extension.js index dabbbad..2aa879a 100644 --- a/extension.js +++ b/extension.js @@ -8,6 +8,7 @@ const comparar = require('./src/comparar'); const grafo = require('./src/grafo-vista'); const historia = require('./src/historia-vista'); const revisiones = require('./src/revisiones'); +const contribuidores = require('./src/contribuidores'); const t = vscode.l10n.t; let salida; @@ -61,6 +62,7 @@ function activate(context) { grafo.registrar(context, protegido); historia.registrar(context, protegido, ficheroDelHistorial); revisiones.registrar(context, protegido); + contribuidores.registrar(context, log); } function deactivate() { } diff --git a/l10n/bundle.l10n.es.json b/l10n/bundle.l10n.es.json index 7139132..327ed97 100644 --- a/l10n/bundle.l10n.es.json +++ b/l10n/bundle.l10n.es.json @@ -3,6 +3,8 @@ "{0} commits": "{0} commits", "{0} has no older revisions": "{0} no tiene revisiones más antiguas", "{0} no longer exists in the working tree": "{0} ya no existe en el árbol de trabajo", + "1 author": "1 autor", + "1 commit": "1 commit", "All branches": "Todas las ramas", "binary": "binario", "Branch {0} is not fully merged. Delete it anyway?": "La rama {0} no está fusionada del todo. ¿Borrarla igualmente?", @@ -31,8 +33,10 @@ "Files": "Ficheros", "Filter by message, author, ref or SHA": "Filtrar por mensaje, autor, ref o SHA", "Filter commits": "Filtrar commits", + "Go to the current commit": "Ir al commit actual", "Graph": "Grafo", "Graph width": "Ancho del grafo", + "Highlight the history of the current branch": "Resaltar la historia de la rama actual", "Its changes can only be recovered by hand from git fsck.": "Sus cambios solo se podrán recuperar a mano con git fsck.", "Its commits that are on no other branch can only be recovered from the reflog.": "Sus commits que no estén en otra rama solo se podrán recuperar del reflog.", "Keep the changes staged": "Conserva los cambios en el índice", @@ -65,6 +69,7 @@ "Restore": "Restaurar", "Restore {0} to its version in {1}?": "¿Restaurar {0} a su versión de {1}?", "Show commit": "Ver commit", + "Show Commit Files": "Ver ficheros del commit", "Show Commit Graph": "Ver grafo de commits", "Show in Source Control": "Ver en Control de código fuente", "Show output": "Ver salida", diff --git a/media/grafo.css b/media/grafo.css index 81395ba..a201104 100644 --- a/media/grafo.css +++ b/media/grafo.css @@ -100,6 +100,41 @@ body { #fetch:active svg { transform: translateY(2px); } #fetch svg { transition: transform .2s var(--muelle); } .boton:disabled { opacity: .5; cursor: default; } +#resaltar[aria-pressed="true"] { color: var(--vscode-focusBorder); background: var(--vscode-toolbar-activeBackground, var(--vscode-toolbar-hoverBackground)); } + +/* lo que no es historia de HEAD queda en segundo plano; las líneas no, que son las que llevan a tu rama */ +.fila > .texto, .fila > .autor, .fila > .fecha, .fila > .sha, .nodo { transition: opacity .2s ease-out; } +.resaltar .fila.ajena > .texto, .resaltar .fila.ajena > .autor, .resaltar .fila.ajena > .fecha, +.resaltar .fila.ajena > .sha, .resaltar .fila.ajena .nodo { opacity: .45; } +.resaltar .fila.ajena:hover > *, .resaltar .fila.ajena.seleccionada > * { opacity: 1; } + +.aqui { + position: fixed; + right: 16px; + bottom: 16px; + z-index: 3; + max-width: min(60vw, 280px); + min-height: 32px; + padding: 0 14px; + overflow: hidden; + color: var(--vscode-button-foreground); + background: var(--vscode-button-background); + border: 0; + border-radius: 16px; + box-shadow: 0 4px 14px rgba(0, 0, 0, .3); + font: inherit; + font-weight: 600; + text-overflow: ellipsis; + white-space: nowrap; + cursor: pointer; + animation: aparecer .2s var(--salida); + transition: background .15s ease-out, transform .2s var(--muelle); +} +.aqui:hover { background: var(--vscode-button-hoverBackground); } +.aqui:active { transform: scale(.95); } +.aqui:focus-visible { outline: 2px solid var(--vscode-focusBorder); outline-offset: 2px; } +.fila.destello { animation: destello 1.2s var(--salida); } +@keyframes destello { 0%, 30% { background: color-mix(in srgb, var(--vscode-focusBorder) 35%, transparent); } } .lista { padding-bottom: 8px; } @@ -175,7 +210,8 @@ body { .c7 { stroke: var(--c7); --tinta: var(--c7); } .nodo.c7 { fill: var(--c7); } .nodo.head { stroke: var(--vscode-foreground); } -.texto { display: flex; align-items: center; gap: 6px; min-width: 0; overflow: hidden; } +/* holgura de 3px con margen negativo: el aro de la rama actual sobresale del chip y el overflow lo cortaría */ +.texto { display: flex; align-items: center; gap: 6px; min-width: 0; margin: -3px; padding: 3px; overflow: hidden; } .resumen { flex: 1 1 0; min-width: 8em; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } .autor, .fecha { overflow: hidden; color: var(--suave); text-overflow: ellipsis; white-space: nowrap; } .seleccionada .autor, .seleccionada .fecha { color: inherit; opacity: .85; } @@ -260,9 +296,9 @@ body { padding: 0 12px 0 8px; background: color-mix(in srgb, var(--vscode-list-activeSelectionBackground) 12%, var(--vscode-editor-background)); border-bottom: 1px solid var(--borde); - animation: desplegar .22s var(--salida) both; } -@keyframes desplegar { from { opacity: 0; clip-path: inset(0 0 100% 0); } to { clip-path: inset(0 0 0 0); } } +/* el detalle sale de golpe; la carga solo se ve si tarda: un commit ya visto o rápido no parpadea */ +.cuerpo.cargando { animation: aparecer .2s var(--salida) .15s both; } .carriles { display: block; height: 100%; } .carriles line { stroke-width: 2; stroke-linecap: round; } diff --git a/media/grafo.js b/media/grafo.js index abcb6f9..7c97267 100644 --- a/media/grafo.js +++ b/media/grafo.js @@ -15,6 +15,13 @@ const fin = document.getElementById('fin'); const refrescar = document.getElementById('refrescar'); const traer = document.getElementById('fetch'); + const botonResaltar = document.getElementById('resaltar'); + const aqui = document.getElementById('aqui'); + /** @type {{sha: string, nombre: string} | null} */ + let actual = null; + let resaltar = (vscode.getState() || {}).resaltar !== false; + let buscandoHead = 0; // páginas que quedan por pedir buscando la fila de HEAD + let headInalcanzable = false; // se buscó y no está en este alcance: no se ofrece hasta la próxima recarga let filas = []; const porSha = new Map(); let hayMas = false; @@ -26,7 +33,9 @@ /** @type {HTMLElement | null} */ let detalle = null; - const x = c => c * CARRIL + CARRIL / 2; + // 1px de margen a la izquierda: el nodo del carril 0 crece al pasar el ratón y el grafo recorta lo que sale + const x = c => 1 + c * CARRIL + CARRIL / 2; + const anchoGrafo = () => anchoMax * CARRIL + 2; const y = v => v * ALTO; const esFila = n => n && n.classList.contains('fila') && !n.classList.contains('esqueleto'); @@ -40,7 +49,7 @@ function svg(clase, alto) { const s = document.createElementNS(NS, 'svg'); s.setAttribute('class', clase); - s.setAttribute('width', String(anchoMax * CARRIL)); + s.setAttribute('width', String(anchoGrafo())); if (alto) { s.setAttribute('height', String(alto)); } s.setAttribute('aria-hidden', 'true'); return s; @@ -120,7 +129,10 @@ r.setAttribute('role', 'listitem'); r.tabIndex = 0; r.dataset.sha = f.sha; - r.style.setProperty('--retardo', `${Math.min(i, 20) * 30}ms`); + // la persiana cubre justo las filas que caben en pantalla (unos 450 ms en total); con un tope fijo de filas, en + // una pantalla alta todas las de debajo del tope entraban de golpe a media altura + const visibles = Math.ceil(innerHeight / ALTO) + 1; + r.style.setProperty('--retardo', `${Math.round(Math.min(i, visibles) * Math.min(30, 450 / visibles))}ms`); if (f.head) { r.classList.add('es-head'); } const texto = el('div', 'texto'); f.refs.forEach(ref => texto.appendChild(insignia(ref, f.sha, f.col))); @@ -170,6 +182,10 @@ document.body.classList.toggle('filtrando', !!buscar.value.trim()); filtrar(); pedirMas(); + // observe() sobre lo que ya se observa no vuelve a medir: se suelta y se vuelve a coger + if (observada) { vigia.unobserve(observada); } + observada = null; + vigilarHead(); }); alcance.addEventListener('change', () => { @@ -210,6 +226,10 @@ detalle = null; } + // un commit no cambia: lo ya cargado se reutiliza mientras viva la vista (con tope, por memoria) + const detallesVistos = new Map(); + const TOPE_DETALLES = 200; + function abrirDetalle(r) { const abierto = detalle && detalle.dataset.sha === r.dataset.sha; cerrarDetalle(); @@ -228,6 +248,8 @@ detalle.append(carrilesDe(porSha.get(r.dataset.sha)), espera); r.after(detalle); r.setAttribute('aria-expanded', 'true'); + const visto = detallesVistos.get(r.dataset.sha); + if (visto) { return pintarDetalle(visto); } vscode.postMessage({ tipo: 'detalle', sha: r.dataset.sha }); } @@ -282,7 +304,14 @@ lista.replaceChildren(el('p', 'aviso', m.mensaje)); return; } - if (m.tipo === 'detalle') { return pintarDetalle(m); } + if (m.tipo === 'detalle') { + if (!m.error) { + detallesVistos.delete(m.sha); // reinsertar lo deja el último en salir + detallesVistos.set(m.sha, m); + if (detallesVistos.size > TOPE_DETALLES) { detallesVistos.delete(detallesVistos.keys().next().value); } + } + return pintarDetalle(m); + } if (m.tipo === 'pendientes') { const r = lista.querySelector('.fila.pendiente .resumen'); if (r) { r.textContent = m.texto; } @@ -309,7 +338,7 @@ } if (anchoMax !== antes && !m.reiniciar) { // carriles nuevos: todas las filas comparten ancho de grafo para que las columnas cuadren - lista.querySelectorAll('svg.grafo, svg.carriles').forEach(s => s.setAttribute('width', String(anchoMax * CARRIL))); + lista.querySelectorAll('svg.grafo, svg.carriles').forEach(s => s.setAttribute('width', String(anchoGrafo()))); } ajustarAncho(); filas = filas.concat(m.filas.filter(f => !f.pendiente && !f.stash)); // la cuenta es de commits @@ -323,10 +352,89 @@ abierta.classList.add('seleccionada'); abrirDetalle(abierta); } + if (m.reiniciar) { actual = m.actual; headInalcanzable = false; } + marcarAjenas(); filtrar(); + if (buscandoHead) { seguirBuscandoHead(); } + vigilarHead(); requestAnimationFrame(pedirMas); // una página que no llena la pantalla pide la siguiente }); + // Con muchas ramas cuesta ver dónde estás: lo que no es historia de HEAD se atenúa (como el «mute» de Git Graph) + function marcarAjenas() { + const dentro = new Set(); + const pila = actual ? [actual.sha] : []; + while (pila.length) { + const s = pila.pop(); + if (dentro.has(s)) { continue; } + dentro.add(s); + const f = porSha.get(s); + if (f && f.padres) { pila.push(...f.padres); } + } + for (const r of lista.querySelectorAll('.fila:not(.esqueleto)')) { + const e = /** @type {HTMLElement} */ (r); + e.classList.toggle('ajena', !!actual && !e.dataset.pendiente && !dentro.has(e.dataset.sha)); + } + } + + function aplicarResaltado() { + document.body.classList.toggle('resaltar', resaltar); + botonResaltar.setAttribute('aria-pressed', String(resaltar)); + } + botonResaltar.addEventListener('click', () => { + resaltar = !resaltar; + vscode.setState({ ...(vscode.getState() || {}), resaltar }); + aplicarResaltado(); + }); + aplicarResaltado(); + + // píldora «estás aquí»: sale cuando la fila de HEAD no se ve, con la flecha hacia donde está + const filaHead = () => /** @type {HTMLElement | null} */ (lista.querySelector('.fila.es-head')); + let observada = null; + const vigia = new IntersectionObserver(([e]) => mostrarAqui(!e.isIntersecting, e.boundingClientRect.top < 0)); + function vigilarHead() { + const r = filaHead(); + if (r === observada) { return; } + if (observada) { vigia.unobserve(observada); } + observada = r; + if (r) { vigia.observe(r); } else { mostrarAqui(!!actual, false); } + } + function mostrarAqui(si, arriba) { + aqui.hidden = !si || !actual || headInalcanzable || !!buscar.value.trim(); + if (aqui.hidden) { return; } + aqui.textContent = `${arriba ? '↑' : '↓'} ${actual.nombre}`; + aqui.title = T.irAqui; + } + function irAHead() { + const r = filaHead(); + if (!r) { + buscandoHead = 20; // no está cargada: se piden páginas hasta dar con ella + return seguirBuscandoHead(); + } + buscandoHead = 0; + const quieto = matchMedia('(prefers-reduced-motion: reduce)').matches; + r.scrollIntoView({ block: 'center', behavior: quieto ? 'auto' : 'smooth' }); + r.classList.remove('destello'); + void r.offsetWidth; + r.classList.add('destello'); + r.focus({ preventScroll: true }); + } + function seguirBuscandoHead() { + if (filaHead()) { return irAHead(); } + if (!hayMas || buscandoHead <= 0) { + // sin más páginas no va a salir (un HEAD separado con «Ramas locales», por ejemplo) + if (!hayMas) { headInalcanzable = true; mostrarAqui(false, false); } + buscandoHead = 0; + return; + } + if (pidiendo) { return; } + buscandoHead--; + pidiendo = true; + fin.replaceChildren(...esqueletos(3)); + vscode.postMessage({ tipo: 'mas' }); + } + aqui.addEventListener('click', irAHead); + function avisarCopiado(boton) { boton.classList.remove('copiado'); void boton.offsetWidth; @@ -384,15 +492,15 @@ // Con muchas ramas el grafo se comería la fila: se recorta a un tope y el borde se arrastra, como en Git Graph function ajustarAncho() { - const total = anchoMax * CARRIL; - const visible = Math.min(total, anchoUsuario || Math.max(6 * CARRIL, Math.round(innerWidth * 0.15))); + const total = anchoGrafo(); + const visible = Math.min(total, anchoUsuario || Math.max(6 * CARRIL + 2, Math.round(innerWidth * 0.15))); document.body.style.setProperty('--grafo', `${visible}px`); document.body.classList.toggle('recortado', visible < total); tirador.setAttribute('aria-valuenow', String(visible)); } function fijarAncho(px) { - anchoUsuario = px && Math.max(2 * CARRIL, Math.min(anchoMax * CARRIL, Math.round(px))); + anchoUsuario = px && Math.max(2 * CARRIL, Math.min(anchoGrafo(), Math.round(px))); ajustarAncho(); vscode.setState({ ...(vscode.getState() || {}), anchoGrafo: anchoUsuario }); } diff --git a/media/historia.css b/media/historia.css index d29b8b5..f66b314 100644 --- a/media/historia.css +++ b/media/historia.css @@ -135,7 +135,7 @@ body { } .globo strong { overflow-wrap: anywhere; } .globo .quien, .globo .cuando { color: var(--suave); } -.globo code { color: var(--vscode-textLink-foreground); font-family: var(--vscode-editor-font-family); } +.globo code { margin-left: 6px; color: var(--vscode-textLink-foreground); font-family: var(--vscode-editor-font-family); } @keyframes aparecer { from { opacity: 0; } } .aviso { color: var(--suave); } diff --git a/media/historia.js b/media/historia.js index 35083e8..eab07fb 100644 --- a/media/historia.js +++ b/media/historia.js @@ -21,6 +21,7 @@ let anchoPintado = 0; const fmt = (s, ...v) => v.reduce((r, x, i) => r.replace(`{${i}}`, String(x)), s); + const cuantos = (n, uno, varios) => (n === 1 ? uno : fmt(varios, n)); const lengua = document.documentElement.lang || undefined; function el(tag, clase, texto) { @@ -82,7 +83,7 @@ fila.dataset.fila = String(i); const nombre = a.color === null ? fmt(T.otros, a.otros) : a.nombre; fila.append(el('span', 'muestra'), el('span', 'nombre', nombre), el('span', 'cuenta', String(a.commits))); - fila.title = `${nombre} · ${fmt(T.commits, a.commits)}`; + fila.title = `${nombre} · ${cuantos(a.commits, T.unCommit, T.commits)}`; etiquetas.appendChild(fila); }); const leyenda = el('div', 'autor leyenda-lineas'); @@ -157,7 +158,7 @@ ); const lineas = el('span', 'lineas'); if (c.binario && !c.mas && !c.menos) { lineas.textContent = T.binario; } else { lineas.append(el('b', 'mas', `+${c.mas}`), el('b', 'menos', ` −${c.menos}`)); } - lineas.appendChild(el('code', '', ` ${c.sha.slice(0, 7)}`)); + lineas.appendChild(el('code', '', c.sha.slice(0, 7))); // sin espacio dentro: VS Code le da fondo a code globo.appendChild(lineas); globo.hidden = false; const caja = ancla.getBoundingClientRect(); @@ -252,7 +253,8 @@ datos = m; titulo.textContent = m.fichero; const desde = m.commits.length ? new Date(Math.min(...m.commits.map(c => c.fecha))).toLocaleDateString(lengua, { year: 'numeric', month: 'short' }) : ''; - const partes = [fmt(T.commits, m.commits.length), fmt(T.autores, m.autores.reduce((n, a) => n + (a.otros || 1), 0))]; + const personas = m.autores.reduce((n, a) => n + (a.otros || 1), 0); + const partes = [cuantos(m.commits.length, T.unCommit, T.commits), cuantos(personas, T.unAutor, T.autores)]; if (desde) { partes.push(fmt(T.desde, desde)); } if (m.limitado) { partes.push(fmt(T.limite, m.commits.length)); } resumen.textContent = partes.join(' · '); diff --git a/package-lock.json b/package-lock.json index 227da3e..bd23c3a 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "git-lore", - "version": "0.6.0", + "version": "0.7.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "git-lore", - "version": "0.6.0", + "version": "0.7.0", "license": "MIT", "devDependencies": { "@vscode/vsce": "^4.1.1", diff --git a/package.json b/package.json index 5bbc741..8ee6768 100644 --- a/package.json +++ b/package.json @@ -2,7 +2,7 @@ "name": "git-lore", "displayName": "%displayName%", "description": "%description%", - "version": "0.6.0", + "version": "0.7.0", "publisher": "jlopez", "license": "MIT", "repository": { @@ -30,7 +30,12 @@ "history", "file history", "line history", + "visual history", "commit graph", + "contributors", + "git graph", + "stash", + "worktree", "compare", "open source" ], @@ -254,6 +259,12 @@ "title": "%command.nextRevision%", "category": "Git Lore", "icon": "$(arrow-right)" + }, + { + "command": "gitLore.refreshContributors", + "title": "%command.refresh%", + "category": "Git Lore", + "icon": "$(refresh)" } ], "menus": { @@ -385,6 +396,10 @@ { "command": "gitLore.nextRevision", "when": "resourceScheme == git" + }, + { + "command": "gitLore.refreshContributors", + "when": "false" } ], "editor/title": [ @@ -477,27 +492,32 @@ "command": "gitLore.compareRefs", "when": "view == gitLore.compare", "group": "navigation@2" + }, + { + "command": "gitLore.refreshContributors", + "when": "view == gitLore.contributors", + "group": "navigation" } ], "view/item/context": [ { "command": "gitLore.showCommit", - "when": "view == gitLore.history && viewItem == commit", + "when": "view =~ /^gitLore\\.(history|contributors)$/ && viewItem == commit", "group": "inline@1" }, { "command": "gitLore.showCommit", - "when": "view == gitLore.history && viewItem == commit", + "when": "view =~ /^gitLore\\.(history|contributors)$/ && viewItem == commit", "group": "1_commit@1" }, { "command": "gitLore.copySha", - "when": "view == gitLore.history && viewItem == commit", + "when": "view =~ /^gitLore\\.(history|contributors)$/ && viewItem == commit", "group": "1_commit@2" }, { "command": "gitLore.openOnRemote", - "when": "view == gitLore.history && viewItem == commit", + "when": "view =~ /^gitLore\\.(history|contributors)$/ && viewItem == commit", "group": "1_commit@3" } ], @@ -636,6 +656,11 @@ "name": "%view.history%", "icon": "$(history)" }, + { + "id": "gitLore.contributors", + "name": "%view.contributors%", + "icon": "$(organization)" + }, { "id": "gitLore.compare", "name": "%view.compare%", diff --git a/package.nls.es.json b/package.nls.es.json index fedb3dd..391f891 100644 --- a/package.nls.es.json +++ b/package.nls.es.json @@ -1,6 +1,6 @@ { "displayName": "Git Lore", - "description": "Blame de Git, historial de fichero y de líneas, grafo de commits y comparación de ramas, libres y gratis. Sin cuenta ni muro de pago.", + "description": "Blame de Git, historial de fichero y de líneas, historial visual, navegación por revisiones, grafo de commits con acciones de ramas, stash y worktrees, y comparación de ramas, libres y gratis. Sin cuenta ni muro de pago.", "command.toggleFileBlame": "Alternar blame del fichero", "command.toggleCurrentLine": "Alternar blame de la línea actual", "command.fileHistory": "Ver historial del fichero", @@ -42,5 +42,6 @@ "command.graph.dropStash": "Descartar stash…", "command.graph.openWorktree": "Abrir worktree en una ventana nueva", "command.previousRevision": "Abrir la revisión anterior", - "command.nextRevision": "Abrir la revisión siguiente" + "command.nextRevision": "Abrir la revisión siguiente", + "view.contributors": "Colaboradores" } diff --git a/package.nls.json b/package.nls.json index 323e6d5..9df1c7f 100644 --- a/package.nls.json +++ b/package.nls.json @@ -1,6 +1,6 @@ { "displayName": "Git Lore", - "description": "Free and open-source Git blame, file and line history, commit graph and branch comparison. No account, no paywall.", + "description": "Free and open-source Git blame, file and line history, visual file history, revision navigation, a commit graph with branch actions, stashes and worktrees, and branch comparison. No account, no paywall.", "command.toggleFileBlame": "Toggle File Blame", "command.toggleCurrentLine": "Toggle Current Line Blame", "command.fileHistory": "Show File History", @@ -42,5 +42,6 @@ "command.graph.dropStash": "Drop Stash…", "command.graph.openWorktree": "Open Worktree in New Window", "command.previousRevision": "Open Previous Revision", - "command.nextRevision": "Open Next Revision" + "command.nextRevision": "Open Next Revision", + "view.contributors": "Contributors" } diff --git a/src/contribuidores.js b/src/contribuidores.js new file mode 100644 index 0000000..60b6a53 --- /dev/null +++ b/src/contribuidores.js @@ -0,0 +1,106 @@ +'use strict'; +// Vista «Contributors» en el panel de Source Control: quién ha hecho commits en la rama actual y cuáles. +const path = require('path'); +const vscode = require('vscode'); +const git = require('./git'); +const { relativa, corto } = require('./acciones'); + +const t = vscode.l10n.t; + +class Contribuidores { + constructor() { + this.repo = null; + this.alFallar = () => { }; + this.cambio = new vscode.EventEmitter(); + this.onDidChangeTreeData = this.cambio.event; + } + + // HEAD cambia al cambiar de rama, hacer commit o hacer pull, y al arrancar llega después de abrir el repo + fijar(repo) { + this.repo = repo; + if (this.vigia) { this.vigia.dispose(); } + const firma = () => repo && repo.state.HEAD && `${repo.state.HEAD.name}@${repo.state.HEAD.commit}`; + let vista = firma(); + this.vigia = repo && repo.state.onDidChange(() => { + if (firma() === vista) { return; } + vista = firma(); + this.cambio.fire(); + }); + this.cambio.fire(); + } + + getTreeItem(e) { + // «persona» y no «autor»: los commits ya traen un campo autor (texto) + if (e.persona) { + const a = e.persona; + const item = new vscode.TreeItem(a.nombre, vscode.TreeItemCollapsibleState.Collapsed); + // dos personas con el mismo nombre (o una con dos correos) solo se distinguen por el correo + const n = a.commits === 1 ? t('1 commit') : t('{0} commits', a.commits); + item.description = e.repetido ? `${n} · ${a.correo}` : n; + item.tooltip = `${a.nombre} <${a.correo}>`; + item.iconPath = new vscode.ThemeIcon('person'); + item.contextValue = 'autor'; + return item; + } + const c = e; + const item = new vscode.TreeItem(c.resumen || corto(c.sha)); + item.description = relativa(c.fecha); + item.iconPath = new vscode.ThemeIcon('git-commit'); + item.contextValue = 'commit'; // los mismos menús que en File History: ficheros, copiar SHA, abrir en remoto + const tip = new vscode.MarkdownString(); + tip.appendMarkdown(`\`${corto(c.sha)}\` · `); + tip.appendText(`${new Date(c.fecha).toLocaleString(vscode.env.language)}\n\n${c.resumen}`); + item.tooltip = tip; + item.command = { command: 'gitLore.showCommit', title: t('Show Commit Files'), arguments: [c] }; + return item; + } + + async getChildren(e) { + const repo = this.repo; + if (!repo) { return []; } + const raiz = repo.rootUri.fsPath; + try { + if (!e) { + this.alFallar(undefined); + const personas = await git.autores(repo); + const veces = new Map(); + personas.forEach(p => veces.set(p.nombre, (veces.get(p.nombre) || 0) + 1)); + return personas.map(persona => ({ persona, repetido: veces.get(persona.nombre) > 1 })); + } + if (!e.persona) { return []; } + return (await git.commitsDeAutor(repo, e.persona)).map(c => ({ ...c, raiz })); + } catch (err) { + this.alFallar(err.message); // un error en getChildren dejaría la vista vacía sin decir por qué + return []; + } + } +} + +function registrar(context, log) { + const proveedor = new Contribuidores(); + const vista = vscode.window.createTreeView('gitLore.contributors', { treeDataProvider: proveedor }); + proveedor.alFallar = mensaje => { vista.message = mensaje; }; + let api = null; + // el repo del editor activo; sin editor de un repo, el primero que haya + const elegir = () => { + if (!api) { return; } + const ed = vscode.window.activeTextEditor; + const repo = (ed && api.getRepository(ed.document.uri)) || api.repositories[0] || null; + if (repo === proveedor.repo) { return; } + proveedor.fijar(repo); + vista.description = repo ? path.basename(repo.rootUri.fsPath) : ''; + }; + git.obtenerApi().then(a => { + api = a; + context.subscriptions.push(a.onDidOpenRepository(elegir), a.onDidCloseRepository(elegir)); + elegir(); + }, e => log(`contributors: ${e.message}`)); + context.subscriptions.push( + vista, + { dispose: () => proveedor.vigia && proveedor.vigia.dispose() }, + vscode.window.onDidChangeActiveTextEditor(elegir), + vscode.commands.registerCommand('gitLore.refreshContributors', () => proveedor.cambio.fire()), + ); +} + +module.exports = { registrar }; diff --git a/src/git.js b/src/git.js index 40e1023..17b5c01 100644 --- a/src/git.js +++ b/src/git.js @@ -5,7 +5,7 @@ const fs = require('fs'); const path = require('path'); const vscode = require('vscode'); const { - parsearBlame, parsearLog, parsearDiff, parsearNumstat, parsearStash, parsearWorktrees, FORMATO_LOG, FORMATO_SHA, FORMATO_STASH, + parsearBlame, parsearLog, parsearShortlog, parsearDiff, parsearNumstat, parsearStash, parsearWorktrees, FORMATO_LOG, FORMATO_SHA, FORMATO_STASH, } = require('./nucleo/parseo'); const { webDeRemoto, elegirRemoto } = require('./nucleo/remotos'); @@ -137,6 +137,41 @@ async function resolverRef(repo, ref) { } } +// todas las refs con su commit: si cambia, algo se movió (fetch, push, ramas o tags creados fuera, un stash). +// repo.state.refs no sirve: las versiones recientes de VS Code lo dejan vacío y cargan las refs bajo demanda +// refs/stash es solo el de arriba: descartar uno intermedio solo se ve en la lista completa +async function firmaDeRefs(repo) { + const raiz = repo.rootUri.fsPath; + const [refs, stash] = await Promise.all([ + ejecutar(raiz, ['for-each-ref', '--format=%(refname) %(objectname)', 'refs/heads', 'refs/remotes', 'refs/tags']), + ejecutar(raiz, ['stash', 'list', '--format=%H']), + ]); + return `${refs}\n${stash}`; +} + +// el .git compartido por todos los worktrees: ahí viven las refs +async function dirComun(repo) { + const salida = (await ejecutar(repo.rootUri.fsPath, ['rev-parse', '--git-common-dir'])).trim(); + return path.resolve(repo.rootUri.fsPath, salida); +} + +// HEAD explícito: sin revisión y sin terminal, shortlog se queda leyendo de la entrada estándar +async function autores(repo) { + if (!repo.state.HEAD || !repo.state.HEAD.commit) { return []; } + return parsearShortlog(await ejecutar(repo.rootUri.fsPath, ['shortlog', '-sne', 'HEAD'])); +} + +// con correo: «» literal (--fixed-strings: un «+» no es regex), sin distinguir mayúsculas como al agrupar. +// sin correo git guarda «Nombre <>»: se ancla entera con regex escapada, o «Anabel» casaría con «Ana Anabel <>» +async function commitsDeAutor(repo, autor, limite = 200) { + const escapar = s => s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); + const patron = autor.correo + ? ['--fixed-strings', `--author=<${autor.correo}>`] + : ['--extended-regexp', `--author=^${escapar(autor.nombre)} <>$`]; + return parsearLog(await ejecutar(repo.rootUri.fsPath, + ['log', 'HEAD', '--regexp-ignore-case', ...patron, `-n${limite}`, `--format=${FORMATO_LOG}`])); +} + async function stashes(repo) { return parsearStash(await ejecutar(repo.rootUri.fsPath, ['stash', 'list', `--format=${FORMATO_STASH}`])); } @@ -220,5 +255,5 @@ function uriEnRevision(repo, ruta, ref) { module.exports = { ALCANCES, obtenerApi, repoDe, rutaRelativa, resolverRef, blame, mensaje, historial, lineasDeFichero, ficherosDeCommit, grafo, refs, diferencias, webDe, - uriEnRevision, cherryPick, revertir, resetear, crearTag, restaurarFichero, stashes, worktrees, usarStash, ErrorGit, + uriEnRevision, cherryPick, revertir, resetear, crearTag, restaurarFichero, stashes, worktrees, usarStash, firmaDeRefs, dirComun, autores, commitsDeAutor, ErrorGit, }; diff --git a/src/grafo-vista.js b/src/grafo-vista.js index 67158a8..14add64 100644 --- a/src/grafo-vista.js +++ b/src/grafo-vista.js @@ -24,7 +24,7 @@ function html(webview, raizExt, nonce, id) { const recurso = f => webview.asWebviewUri(vscode.Uri.joinPath(raizExt, 'media', f)); const textos = { copiado: t('Copied'), sinCommits: t('No commits'), copiar: t('Copy SHA'), ficheros: t('Files'), padres: t('Parents'), - verCambios: t('Show in Source Control'), enWorktree: t('Checked out in worktree {0}'), + verCambios: t('Show in Source Control'), irAqui: t('Go to the current commit'), enWorktree: t('Checked out in worktree {0}'), }; return ` @@ -43,11 +43,13 @@ function html(webview, raizExt, nonce, id) { +
+ @@ -117,10 +119,12 @@ function abrir(context, repo) { try { // stash y worktrees se leen al recargar; las páginas siguientes tiran de lo leído if (reiniciar) { - const [st, wts] = await Promise.all([git.stashes(repo).catch(() => []), git.worktrees(repo).catch(() => [])]); + const [st, wts, refs] = await Promise.all([git.stashes(repo).catch(() => []), git.worktrees(repo).catch(() => []), + git.firmaDeRefs(repo).catch(() => null)]); if (mia !== generacion || cerrado) { return; } stashSinColocar = st; otrosWorktrees = wts; + firmaRefs = refs; // lo que se pinta ahora: un cambio posterior lo detecta comprobarRefs } const extra = otrosWorktrees.filter(w => !w.rama).map(w => w.head); // un HEAD separado no sale con --branches const commits = await git.grafo(repo, { saltar: desde, limite, alcance, extra }); @@ -153,9 +157,12 @@ function abrir(context, repo) { refs, stash: !!c.stash, head: !c.stash && c.sha === head, + padres: c.padres, // para saber en el webview qué es historia de HEAD }; }); - enviar({ tipo: 'filas', filas, reiniciar, alcance, hayMas: commits.length === limite }); + const h = repo.state.HEAD; + const actual = h && h.commit ? { sha: h.commit, nombre: h.name || h.commit.slice(0, 7) } : null; + enviar({ tipo: 'filas', filas, reiniciar, alcance, actual, hayMas: commits.length === limite }); } catch (e) { if (mia === generacion) { enviar({ tipo: 'error', mensaje: e.message }); } } finally { @@ -170,6 +177,22 @@ function abrir(context, repo) { }; let firma = firmaActual(); let temporizador; + let firmaRefs = null; + let esperaRefs; + // con retardo: onDidChange llega a ráfagas (cada guardado refresca el estado) y esto lanza un git + const comprobarRefs = () => { + clearTimeout(esperaRefs); + esperaRefs = setTimeout(async () => { + if (firmaRefs === null || cerrado) { return; } + // la recarga en curso leyó las refs al empezar: lo que se mueva después se mira cuando acabe + if (recargando) { return comprobarRefs(); } + const ahora = await git.firmaDeRefs(repo).catch(() => null); + if (recargando) { return comprobarRefs(); } + if (ahora === null || ahora === firmaRefs) { return; } + firmaRefs = ahora; + cargar(true, true); + }, 400); + }; // la acción ya recarga: que el cambio de HEAD que provoca no dispare una segunda recarga const recargar = () => { firma = firmaActual(); @@ -180,7 +203,10 @@ function abrir(context, repo) { const suscripciones = [ repo.state.onDidChange(() => { const ahora = firmaActual(); - if (ahora === firma) { return enviar({ tipo: 'pendientes', texto: textoPendientes(pendientes(repo)) }); } + if (ahora === firma) { + comprobarRefs(); // un fetch en segundo plano mueve remotas sin tocar HEAD + return enviar({ tipo: 'pendientes', texto: textoPendientes(pendientes(repo)) }); + } firma = ahora; clearTimeout(temporizador); temporizador = setTimeout(() => cargar(true), 500); @@ -212,12 +238,24 @@ function abrir(context, repo) { }), ]; + // crear una rama o un tag desde la terminal no dispara onDidChange: se vigilan los ficheros de refs + git.dirComun(repo).then(dir => { + if (cerrado) { return; } + const vigia = vscode.workspace.createFileSystemWatcher( + new vscode.RelativePattern(vscode.Uri.file(dir), '{refs/**,packed-refs,FETCH_HEAD,logs/refs/stash}')); + vigia.onDidCreate(comprobarRefs); + vigia.onDidChange(comprobarRefs); + vigia.onDidDelete(comprobarRefs); + suscripciones.push(vigia); + }, () => { }); // sin vigía el grafo sigue recargando con los cambios de HEAD y el botón de refrescar + panel.onDidDispose(() => { cerrado = true; paneles.delete(raiz); vistas.delete(id); suscripciones.forEach(d => d.dispose()); clearTimeout(temporizador); + clearTimeout(esperaRefs); }); panel.webview.html = html(panel.webview, context.extensionUri, crypto.randomBytes(16).toString('base64'), id); diff --git a/src/historia-vista.js b/src/historia-vista.js index 27947bb..4862b6b 100644 --- a/src/historia-vista.js +++ b/src/historia-vista.js @@ -14,7 +14,7 @@ const paneles = new Map(); // fsPath → { panel, cargar } function html(webview, raizExt, nonce) { const recurso = f => webview.asWebviewUri(vscode.Uri.joinPath(raizExt, 'media', f)); const textos = { - commits: t('{0} commits'), autores: t('{0} authors'), otros: t('Others ({0})'), sinCommits: t('No commits'), + commits: t('{0} commits'), unCommit: t('1 commit'), autores: t('{0} authors'), unAutor: t('1 author'), otros: t('Others ({0})'), sinCommits: t('No commits'), lineas: t('Lines changed'), desde: t('since {0}'), binario: t('binary'), limite: t('Showing the last {0} commits'), }; return ` diff --git a/src/nucleo/parseo.js b/src/nucleo/parseo.js index 92c755e..29d7fd2 100644 --- a/src/nucleo/parseo.js +++ b/src/nucleo/parseo.js @@ -146,7 +146,25 @@ function parsearWorktrees(texto) { }).filter(w => w.ruta && !w.bare && !w.huerfano); } +// git shortlog -sne → autores por correo (la misma persona con dos nombres cuenta una vez, con el que más usa) +function parsearShortlog(texto) { + const porCorreo = new Map(); + for (const l of texto.split('\n')) { + const m = /^\s*(\d+)\t(.*?)\s*<([^>]*)>\s*$/.exec(l); + if (!m) { continue; } + const [, n, nombre, correo] = m; + const clave = correo.toLowerCase() || nombre; + const a = porCorreo.get(clave) || { nombre, correo, commits: 0, maxNombre: 0 }; + a.commits += Number(n); + if (Number(n) > a.maxNombre) { a.nombre = nombre; a.maxNombre = Number(n); } + porCorreo.set(clave, a); + } + return [...porCorreo.values()].map(({ nombre, correo, commits }) => ({ nombre, correo, commits })) + .sort((a, b) => b.commits - a.commits || a.nombre.localeCompare(b.nombre)); +} + module.exports = { + parsearShortlog, desentrecomillar, parsearBlame, parsearLog, parsearDiff, parsearNumstat, parsearStash, parsearWorktrees, FORMATO_LOG, FORMATO_SHA, FORMATO_STASH, }; diff --git a/test/nucleo.test.js b/test/nucleo.test.js index 76da98a..6834c20 100644 --- a/test/nucleo.test.js +++ b/test/nucleo.test.js @@ -245,3 +245,12 @@ test('historia: un merge sin name-status toma la ruta del commit anterior, no la assert.strictEqual(c.get('c2').rutaAnterior, 'viejo.txt'); assert.strictEqual(c.get('c0').refAnterior, null); }); + +test('contribuidores: shortlog agrupado por correo, con el nombre más usado', () => { + const { parsearShortlog } = require('../src/nucleo/parseo'); + const a = parsearShortlog(' 10\tAna López \n 3\tBea \n 2\tana \n'); + assert.deepStrictEqual(a, [{ nombre: 'Ana López', correo: 'ana@x.com', commits: 12 }, { nombre: 'Bea', correo: 'bea@x.com', commits: 3 }]); + // real: en el repo de prueba Ana (2) y Bea (1) firman con el mismo correo, así que son una persona: Ana + const real = parsearShortlog(git('shortlog', '-sne', 'HEAD')); + assert.deepStrictEqual(real.map(x => [x.nombre, x.commits]), [['Ana', 3]]); +});