355

I found a useful Git one liner buried in leaked CIA developer docs

Here's my take on the one-liner that I use via a `git tidy` alias[1]. A few points:

* It ensures the default branch is not deleted (main, master)

* It does not touch the current branch

* It does not touch the branch in a different worktree[2]

* It also works with non-merge repos by deleting the local branches that are gone on the remote

    git branch --merged "$(git config init.defaultBranch)" \
    | grep -Fv "$(git config init.defaultBranch)" \
    | grep -vF '*' \
    | grep -vF '+' \
    | xargs git branch -d \
    && git fetch \
    && git remote prune origin \
    && git branch -v \
    | grep -F '[gone]' \
    | grep -vF '*' \
    | grep -vF '+' \
    | awk '{print $1}' \
    | xargs git branch -D

[1]: https://github.com/fphilipe/dotfiles/blob/ba9187d7c895e44c35...

[2]: https://git-scm.com/docs/git-worktree

an hour agofphilipe

I have a cleanup command that integrates with fzf. It pre selects every merged branch, so I can just hit return to delete them all. But it gives me the opportunity to deselect to preserve any branches if I want. It also prunes any remote branches

    # remove merged branches (local and remote)
    cleanup = "!git branch -vv | grep ': gone]' | awk '{print $1}' | fzf --multi --sync --bind start:select-all | xargs git branch -D; git remote prune origin;"
https://github.com/WickyNilliams/dotfiles/blob/c4154dd9b6980...

I've got a few aliases that integrate with fzf like an interactive cherry pick (choose branch, choose 1 or more commits), or a branch selector with a preview panel showing commits to the side. Super useful

The article also mentions that master has changed to main mostly, but some places use develop and other names as their primary branch. For that reason I always use a git config variable to reference such branches. In my global git config it's main. Then I override where necessary in any repo's local config eg here's an update command that updates primary and rebases the current branch on top:

    # switch to primary branch, pull, switch back, rebase
    update = !"git switch ${1:-$(git config user.primaryBranch)}; git pull; git switch -; git rebase -;"
https://github.com/WickyNilliams/dotfiles/blob/c4154dd9b6980...
2 hours agoWickyNilliams

> For that reason I always use a git config variable to reference such branches. In my global git config it's main

    $(git config user.primaryBranch)
What about using git's own `init.defaultBranch`?

I mean, while useless in terms of `git init` because the repo's already init'd, this works:

    git config --local init.defaultBranch main
And if you have `init.defaultBranch` set up already globally for `git init` then it all just works
2 hours agolloeki

Hmm that might be nice actually. I like not conflating those two things, but as you say if the repo is already init'd then there's no chance it'll be used for the wrong purpose.

In any case the main thrust was just to avoid embeddings assumptions about branch names in your scripts :)

2 hours agoWickyNilliams

You can pull another branch without switching first:

  git switch my-test-branch
  ...
  git pull origin main:main
  git rebase main
2 hours agoMathiasPius

You can also rebase directly on the remote branch

    git fetch
    git rebase origin/main
44 minutes agohiccuphippo

Likewise with the other way around, just switch pull with push.

an hour agomroche

Nice. That'll make things a bit smoother. Changing branches often trips me up when I would later `git switch -`.

an hour agoWickyNilliams

I have always done `git pull origin main -r`

an hour agohuntervang

I use `master` in all my repos because I've been using it since forever and it never has once occurred to me "oh shit I better change it to `main` this time in case `master` may offend somebody some day. Unfortunately, that's the last thing on my mind when I'm in programming mode. Now that everything is `master`, maybe it is just a simple git command to change it to `main`. But, my fear is it'll subtly break something and I just don't have enough hours left in my life to accept yet unknown risk that it'll cost me even more hours, just to make some random sensitive developer not get offended one day.

an hour agobobjordan

Also, git's "master" branch is named after a master recording or master copy, the canonical original from which duplicates are made. There is literally no reason for it be offensive except for those who retroactively associate the word with slavery.

an hour agojoshuamcginnis

Yeah, with replica it made a little sense. Was still silly, but at least the official master/slave terminology actually didn't fully make sense either... So the replica rebrand felt justified to me.

With git it was basically entirely driven by SJW that felt empowered by people accepting the replica rebrand

an hour agoffsm8

imo the `main` thing was mostly driven by people trying to appease the social justice crowd without understanding much about the movement. Its a bit of woo in my mind because there are still systemic injustices out there that are left uncontested, and using main doesn't really contest anything substantial.

I don't really care what the default branch is called tho so I'm willing to play along.

41 minutes agor14c

I'll change my default branches to main when Masterclass change their name to Mainclass

an hour agoimdsm

At Meta, when this mass push for the rename happened across the industry, a few people spent nearly the full year just shepherding the renaming of master to main, and white box/black box to allowlist/blocklist.

This let them claim huge diff counts and major contributions to DEI and get promos.

an hour agokridsdale1

Same at my org at the time, blacklist was nixed, no matter how many times the question, "What color is ink on a page?" was brought up.

an hour agojihadjihad

The colour of the ink is not where "blacklist" comes from though? It's not from supposed skin colour either...

Blocklist makes more sense in most scenarios.

2 minutes agopbhjpbhj

> What color is ink on a page?

Middle gray, according to modern UX designers. ;)

21 minutes agolayer8

They measure LoC contributions at FB?

an hour agotucnak

> But, my fear is it'll subtly break something and I just don't have enough hours left in my life to accept yet unknown risk that it'll cost me even more hours,

Yeah, it's not like 99% of the world has already switched from master to main already (without any major problems) ...

15 minutes agohungryhobbit

> I use `master` in all my repos because I've been using it since forever and it never has once occurred to me "oh shit I better change it to `main` this time in case `master` may offend somebody some day.

As a white person from slavic origins (my mother had an Ukrainian name and we're originally from the ukrainian city of Kyiv), my ancestors were OG slaves. It's literally where the word "slave" comes from: same etymology. We, white people, have been traded as slaves by many (including other whites) since times immemorial.

And yet I really literally don't care if people name their main branch "master" or "main". I like "trunk" but I'm sure some people with a political agenda could find a way to explain how "truck" is offensive.

You have my blessings and I hope the blessings from many people with slavic origins.

36 minutes agoTacticalCoder

I keep a command `git-remove-merged`, which uses `git ls-remote` to see if the branch is set up to track a remote branch, and if it is then whether the remote branch still exists. On the assumption that branches which have had remote tracking but no longer do are either merged or defunct.

https://gist.github.com/andrewaylett/27c6a33bd2fc8c99eada605...

But actually nowadays I use JJ and don't worry about named branches :).

10 minutes agoandrewaylett

I've had essentially that - if a bit fancier to accept an optional argument as well as handle common "mainline" branch names - aliased as `git lint` for a while:

    [alias]
        lint = !git branch --merged ${1-} | grep -v -E -e '^[*]?[ ]*(main|master|[0-9]+[.]([0-9]+|x)-stable)$' -e '^[*][ ]+' | xargs -r -n 1 git branch --delete
so:

    git pull --prune && git lint
sits very high in my history stats
3 hours agolloeki
[deleted]
2 hours ago

The main issue with `git branch --merged` is that if the repo enforces squash merges, it obviously won't work, because SHA of squash-merged commit in main != SHA of the original branch HEAD.

What tools are the best to do the equivalent but for squash-merged branches detections?

Note: this problem is harder than it seems to do safely, because e.g. I can have a branch `foo` locally that was squash-merged on remote, but before it happened, I might have added a few more commits locally and forgot to push. So naively deleting `foo` locally may make me lose data.

3 hours agojakub_g

I have the same issue. Changes get pushed to gerrit and rebased on the server. This is what I have, though not perfected yet.

  prunable = "!f() { \
  : git log ; \
  target=\"$1\"; \
  [ -z \"$target\" ] && target=$(git for-each-ref --format=\"%(refname:short)\" --count=1 refs/remotes/m/); \
  if [ -z \"$target\" ]; then echo \"No remote branches found in refs/remotes/m/\"; return 1; fi; \
  echo \"# git branch --merged shows merged if same commit ID only\" ;\
  echo \"# if rebased, git cherry can show branch HEAD is merged\"  ;\
  echo \"# git log grep will check latest commit subject only.  if amended, this status won't be accurate\" ;\
  echo \"# Comparing against $target...\"; \
  echo \"# git branch --merged:\"; \
  git branch --merged $target  ;\
  echo \" ,- git cherry\" ; \
  echo \" |  ,- git log grep latest message\"; \
  for branch in $(git for-each-ref --format='%(refname:short)' refs/heads/); do \
   if git cherry \"$target\" \"$branch\" | tail -n 1 | grep -q \"^-\"; then \
    cr=""; \
   else \
    cr=""; \
   fi ; \
   c=$(git rev-parse --short $branch) ; \
   subject=$(git log -1 --format=%s \"$branch\" | sed 's/[][(){}.^$\*+?|\\/]/\\\\&/g') ; \
   if git log --grep=\"^$subject$\" --oneline \"$target\" | grep -q .; then \
    printf \"$cr  $c %-20s $subject\\n\"  $branch; \
   else \
    printf \"$cr  \\033[0;33m$c \\033[0;32m%-20s\\033[0m $subject\\n\"  $branch; \
   fi; \
  done; \
  }; f"
(some emojis missing in above. see gist) https://gist.github.com/lawm/8087252b4372759b2fe3b4052bf7e45...

It prints the results of 3 methods:

1. git branch --merged

2. git cherry

3. grep upstream git log for a commit with the same commit subject

Has some caveats, like if upstream's commit was amended or the actual code change is different, it can have a false positive, or if there are multiple commits on your local branch, only the top commit is checked

an hour agolaksdjf

Mine's this-ish (nushell, but easily bashified or pwshd) for finding all merged, including squashed:

    let t = "origin/dev"; git for-each-ref refs/heads/ --format="%(refname:short)" | lines | where {|b| $b !~ 'dev' and (git merge-tree --write-tree $t $b | lines | first) == (git rev-parse $"($t)^{tree}") }
Does a 3-way in-mem merge against (in my case) dev. If there's code in the branch that isn't in the target it won't show up.

Pipe right to deletion if brave, or to a choice-thingy if prudent :)

29 minutes agode46le

This is my PowerShell variant for squash merge repos:

    function Rename-GitBranches {
        git branch --list "my-branch-prefix/*" | Out-GridView -Title "Branches to Zoo?" -OutputMode Multiple | % { git branch -m $_.Trim() "zoo/$($_.Trim())" }
    }
`Out-GridView` gives a very simple dialog box to (multi) select branch names I want to mark finished.

I'm a branch hoarder in a squash merge repo and just prepend a `zoo/` prefix. `zoo/` generally sorts to the bottom of branch lists and I can collapse it as a folder in many UIs. I have found this useful in several ways:

1) It makes `git rebase --interactive` much easier when working with stacked branches by taking advantage of `--update-refs`. Merges do all that work for you by finding their common base/ancestor. Squash merging you have to remember which commits already merged to drop from your branch. With `--update-refs` if I find it trying to update a `zoo/` branch I know I can drop/delete every commit up to that update-ref line and also delete the update-ref.

2) I sometimes do want to find code in intermediate commits that never made it into the squashed version. Maybe I tried an experiment in a commit in a branch, then deleted that experiment in switching directions in a later commit. Squashing removes all evidence of that deleted experiment, but I can still find it if I remember the `zoo/` branch name.

All this extra work for things that merge commits gives you for free/simpler just makes me dislike squash merging repos more.

2 hours agoWorldMaker

Not just squash merges, rebase-merges also don't work.

> What tools are the best to do the equivalent but for squash-merged branches detections?

Hooking on remote branch deletion is what most people do, under the assumption that you tend to clean out the branches of your PRs after a while. But of course if you don't do that it doesn't work.

3 hours agomasklinn

Depends on your workflow, I guess. I don't need to handle that case you noted and we delete the branch on remote after it's merged. So, it's good enough for me to delete my local branch if the upstream branch is gone. This is the alias I use for that, which I picked up from HN.

    # ~/.gitconfig
    [alias]
        gone = ! "git fetch -p && git for-each-ref --format '%(refname:short) %(upstream:track)' | awk '$2 == \"[gone]\" {print $1}' | xargs -r git branch -D"
Then you just `git gone` every once in a while, when you're between features.
2 hours agosamhclark

If something this natural requires several lines of bash, something is just not right. Maybe branches should go sorted by default, either chronologically or topologically? git's LoC budget is 20x LevelDBs or 30% of PostgreSQL or 3 SQLites. It must be able to do these things out of the box, isn't it?

https://replicated.wiki/blog/partII.html

2 hours agogritzko

I currently have a TUI addiction. Each time I want something to be easier, I open claude-code and ask for a TUI. Now I have a git worktree manager where I can add/rebase/delete. As TUI library I use Textual which claude handles quite well, especially as it can test-run quite some Python code.

4 hours agowhazor

how do you trust the code claude wrote? don't you get anxiety "what if there's an error in tui code and it would mess up my git repo"?

3 hours agorw_panic0_0

I'm not GP, but I have backups, plus I always make sure I've committed and pushed all code I care about to the remote. I do this even when running a prompt in an agent. That goes for running most things actually, not just CC. If claude code runs a git push -f then that could really hurt, but I have enough confidence from working with the agents that they aren't going to do that that it's worth it to me to take the risk in exchange for the convenience of using the agent.

2 hours agofreedomben

I push my branches daily, so I wouldn't lose that much work. If it breaks then I ask it to fix it.

But I do quickly check the output what it does, and especially the commands it runs. Sometimes it throws all code in a single file, so I ask for 'good architecture with abstractions'.

an hour agowhazor

I see this regularly: "I use GitHub to backup my local repos."

If `gh repo ...` commands get run you can lose everything instantly. You can force push and be left with a single blank commit on both sides. The agent has full control of everything, not just your local data.

Just set up Rclone/restic and get your stuff into a system with some immutability.

24 minutes agozenoprax

> how do you trust the code claude wrote?

If that's something you're worried about, review the code before running it.

> don't you get anxiety "what if there's an error in tui code and it would mess up my git repo"?

I think you might want to not run untrusted programs in an environment like that, alternatively find a way of start being able to trust the program. Either approaches work, and works best depending on what you're trying to do.

2 hours agoembedding-shape

> If that's something you're worried about, review the code before running it.

It takes more, not less, time to thoroughly review code you didn't write.

an hour agokaoD

Depends. If I was the one coming up with the implementation anyways, it's basically just the "coding" part that was replaced with "fingers hitting keyboard" and "agents writing to disk", so reviewing the code certainly is faster, you just have to "check" it, not understand it from scratch.

If we're talking receiving random patches where first you have to understand the context, background and so on, then yeah I agree, it'll take longer time probably than what it took for someone to hammer with their fingers. But again, I'm not sure that's how professionals use LLMs right now, vibe-coding is a small hyped world mostly non-programmers seem to engage in.

an hour agoembedding-shape

> you just have to "check" it, not understand it from scratch.

How can you "check" that which you don't "understand"?

> I'm not sure that's how professionals use LLMs right now

I'm a professional and I can tell you how I use LLMs: I write code with their assistance, they don't write code for me.

The few times I let Claude or Copilot loose, the results were heartbreaking and I spent more time reviewing (and then discarding) the code than what it took me to later write it from scratch.

38 minutes agokaoD

Isn't it this case no matter who wrote the code? How do you ever run anything if you're worried about bugs?

3 hours agosclangdon

It makes a difference whether an AI or a human wrote it. AIs make more random, inconsistent errors or omissions that a human wouldn’t make. AIs also don’t dog-feed their code the way human developers of tools usually do, catching more errors or unfit/missing logic that way.

15 minutes agolayer8

When I write the code myself, I'm not worried that I snuck a `git reset --hard` somewhere.

3 hours agophailhaus

Different type of creator, different type of bugs. I'd assume a human giving me a way to delete merged branches has probably had the same issue, solved the same problem and understands unspecified context around the problem (e.g protect local data). They probably run it themselves so bugs are most likely to occur in edge cases around none standard use as it works for them.

Ais are giving you what they get from common patterns, parsing documentation etc. Depending what you're asking this might be an entirely novel combination of commands never run before. And depending on the model/prompt it might solve in a way any human would balk at (push main to origin, delete .git, re-clone from origin. Merged local branches are gone!)

It's like the ai art issues - people struggle with relative proportions and tones and making it look real. Ai has no issues with tones, but will add extra fingers or arms etc that humans rarely struggle with. You have to look for different things, and Ai bugs are definitely more dangerous than (most) human bugs.

(Depends a little, it's pretty easy to tell if a human knows what they're talking about. There's for sure humans who could write super destructive code, but other elements usually make you suspicious and worried about the code before that)

2 hours agohennell

I assume that whatever I type can be also flawed and take precautions like backups etc

2 hours agoithkuil

Tig is a nice and long-maintained git tui you might enjoy, then!

If nothing else maybe for inspiration

3 hours agoeulers_secret

In the case of Git, I can warmly recommend Magit as a TUI. Not only does it make frequent operations easier and rare operations doable -- it also teaches you Git!

I have a draft here about one aspect of Magit I enjoy: https://entropicthoughts.com/rebasing-in-magit

2 hours agokqr

Can you explain TUI? I have never heard this before

3 hours agofiresteelrain

Terminal User Interface, contrasting with a Graphical User Interface (GUI). Most often applied to programs that use the terminal as a pseudo-graphical canvas that they draw on with characters to provide an interactive page that can be navigated around with the keyboard.

Really, they're just a GUI drawn with Unicode instead of drawing primitives.

Like many restrictions, limiting oneself to just a fixed grid of colored Unicode characters for drawing lends itself to more creative solutions to problems. Some people prefer such UIs, some people don't.

3 hours agoBjartr

I prefer tui's for two reasons. 1. Very used to vi keybindings 2. I like low resources software. I love the ability to open the software in less than a second in a second do what I needed using vi motions. And close it less than a second.

Some people will be like you save two seconds trying to do something simple. You lose more time building the tool than you will use it in your life.

It's not about saving time. It's about eliminating the mental toll from having to context switch(i know it sounds ai, reading so much ai text has gotten to me)

3 hours agoMuvasa

That’s an excellent way to explain it. I’m already in the shell doing stuff. Whenever I can stay there without sacrificing usability, it’s a big boost.

an hour agokstrauser

"It's not about saving time, it's about eliminating the mental toll from having to context switch"

This broke my brain! Woah!

2 hours agoirl_zebra

> an interactive page that can be navigated around with the keyboard

Or mouse / trackpad.

I really haven't seen anything better for making TUIs than Borland's Turbo Vision framework from 35ish years ago.

3 hours agocriddell

Eg: lazygit https://github.com/jesseduffield/lazygit?tab=readme-ov-file#... https://github.com/sxyazi/yazi https://github.com/darrenburns/posting or I guess Vim would be a prominent example.

Peoples definitions will be on a gradient, but its somewhere between CLI (type into a terminal to use) and GUI (use your mouse in a windowing system), TUI runs in your terminal like a CLI but probably supports "graphical widgets" like buttons, bars, hotkeys, panes, etc.

3 hours agoGCUMstlyHarmls

So the acronym is for Terrible User Interface? ;)

3 hours agogiglamesh

TUI is peak UI, anyone who disagrees just don't get it. Every program listens to the same keybindings, looks the same and are composable to work together. You don't get that clicking buttons with the mouse. It's built to get the work done not look pretty.

2 hours agoworksonmine

No it's not.

3 hours agoallarm

Terminal UI.

3 hours agoses1984

It's definitely an acronym that got popular in the last year or so, though I'm sure there are people out there who will pretend otherwise. I've been in the industry 15+ years now and never heard it before. Previously it was just UI, GUI, or CLI.

3 hours agobooleandilemma

It's gotten more popular for sure, but it's definitely been around a long time. Even just on HN there have been conversation about gdb tui ever since I've been here (starting browsing HN around 2011). For anyone who works in embedded systems it's a very common term and has been since I got into it in 2008-ish. I would guess it was much more of a linux/unix user thing until recently though, so people on windows and mac probably rarely if ever intersected with the term, so that's definitely a change. Just my observations.

2 hours agofreedomben

My friends and I have been actively in the "CLI/TUI" since middle school. Anyone tinkering on linux that used tiling window managers is already very familiar with the domain.

35 minutes ago0x1ch

As someone who came up using Borland's Turbo Pascal, Turbo C, and Turbo Vision (their OOP UI framework), it was called CUI (character-based user interface) to distinguish from GUI, which became relevant as Windows became dominant.

I never heard "TUI" until the last few years, but it may be due to my background being Microsoft-oriented.

One of the only references I can find is the PC Magazine encyclopedia: https://www.pcmag.com/encyclopedia/term/cui

2 hours agosnozolli

it's the name gen Z and gen alpha puppyn00bs have given to what us old heads have always called CLIs

on tik too young folks are always discovering "revolutionary" things and giving them names, ignoring they're either super mundane, or already have a name

on one hand, i absolutely LOVE the passion for discovery and invention

on the other hand, if you're 19yo you probably didn't discover something revolutionary

(Edit: I've seen some people online suggest a CLI is only when you manually type the command yourself, while a TUI incorporates text-based graphical elements, but that's something invented by young people; everything before GUIs was called a CLI until pretty recently. A terminal is /literally/ a command-line interface.)

3 hours agoKPGv2

They aren’t the same thing. TUI refers to interactive ncurses-like interfaces. Vim has a TUI, ls does not

I’m fairly certain this terminology has been around since at least the early aughts.

3 hours agoTarqDirtyToMe

Sorry, but this 65 yo grey-beard disagrees. A TUI to me, back in the 80s/90s, was something that ran in the terminal and was almost always ncurses-based. This was back when I was still using ADM-3A serial terminals, none of that new-fangled PCs stuff.

3 hours agophiliplu

Exactly. A CLI is a single line - like edlin. A TUI takes over all or most of the screen, like edit or vi or emacs.

Norton Commander (or Midnight Commander) is probably the quintessential example of a powerful TUI; it can do things that would be quite hard to replicate as easily in a CLI.

2 hours agobombcar

We might've been caught on different parts of the wave. I checked Ngrams out of curiosity

https://books.google.com/ngrams/graph?content=TUI&year_start...

Basically it was never used, then it was heavily used, and then never used, and then in the early 00s it took off again.

That'd explain why you used it, I never did, and now young kids are.

2 hours agoKPGv2

I don't think that search is very valid - the TUI group travel companies are likely much more mentioned than Terminal User Interface. They are pretty big around the world and have an airline, cruises, hotels etc.

27 minutes agorjmunro

Thanks for looking that up! It makes sense, of course - the line starts to drop in 1984, with the release of the Macintosh, and hits a trough around the launch of Windows 95.

It's not a term I recall hearing at all when I started using computers in the mid-'80s - all that mattered back then was "shiny new GUI, or the clunky old thing?" I really thought it was a retroneologism when I first heard it, maybe twenty years ago.

2 hours agomarssaxman

[dead]

2 hours agojohn_strinlai

The amount of little tools I'm creating for myself is incredible, 4.6 seems like it can properly one/two shot it now without my attention.

Did you open source that one? I was thinking of this exact same thing but wanted to think a little about how to share deps, i.e. if I do quick worktree to try a branch I don't wanna npm i that takes forever.

Also, if you share it with me, there's obviously no expectations, even it's a half backed vibecoded mess.

3 hours agoTrufa

I’ve been wanting similar but have instead been focused on GUI. My #1 issue with TUI is that I’ve never liked code jumps very smooth high fps fast scrolling. Between that and terminal lacking variable font sizes, I’d vastly prefer TUIs, but I just struggle to get over those two issues.

I’ve been entirely terminal based for 20 years now and those issues have just worn me down. Yet I still love terminal for its simplicity. Rock and a hard place I guess.

2 hours agounshavedyak

What's the point of open sourcing something you one shot with an LLM? At that point just open source the prompt you used to generate it.

2 hours agoSauntSolaire

Testing. If you share something you've tested and know works, that's way better than sharing a prompt which will generate untested code which then has to be tested. On top of that it seems wasteful to burn inference compute (and $) repeating the same thing when the previous output would be superior anyway.

That said, I do think it would be awesome if including prompts/history in the repos somehow became a thing. Not only would it help people learn and improve, but it would allow tweaking.

2 hours agofreedomben

To save time and energy?

2 hours agoNetOpWibby

The deps question is huge, let me know if you solve it.

3 hours agoelliotbnvl

If I'm understanding the problem correctly, this should be solved by pnpm [1]. It stores packages in a global cache, and hardlinks to the local node_packages. So running install in a new worktree should be instant.

[1]: https://pnpm.io/motivation

2 hours agoCalebJohn

What are some examples of useful TUI you made? I'm generally opposed to the concept

3 hours agohattmall

That sounds like a complete waste of time and tokens to me, what is the benefit? So each time you do something, you let Claude one shot a tui? This seems like a waste of compute and your time

4 hours agolionkor

They said each time they want something to be easier, not each time they do something. And they didn’t mention it has to be one-shot. You might have read too quickly and you’ve responded to something that didn’t actually exist.

3 hours agohtnthrow11220

On the contrary. Once these tools exist they exist forever, independently of Claude or a Claude Code subscription. IMO this is the best way to use AI for personal use.

3 hours agoMarsIronPI

Now that I think about it, if Claude can put most useful functions in a TUI and make them discoverable (show them in a list), than this could be better than asking for one-liners (and forgetting them) every single time.

Maybe I'll try using small TUI too.

3 hours agobmacho

yeah! they should focus on more productive pursuits, like telling people online what to do with their time and resources.

3 hours agoduneisagoodbook

And these are things outside of our control.

3 hours agomorissette

I have something similar, but open fzf to select the branches to delete [1].

    function fcleanb -d "fzf git select branches to delete where the upstream has disappeared"
        set -l branches_to_delete (
            git for-each-ref --sort=committerdate --format='%(refname:lstrip=2) %(upstream:track)' refs/heads/ | \
            egrep '\[gone\]$' | grep -v "master" | \
            awk '{print $1}' | $_FZF_BINARY --multi --exit-0 \
        )

        for branch in $branches_to_delete
            git branch -D "$branch"
        end
    end
[1]: https://github.com/jo-m/dotfiles/blob/29d4cab4ba6a18dc44dcf9...
3 hours agojo-m

I use this alias:

    prune-local = "!git fetch -p && for branch in $(git branch -vv | awk '/: gone]/{if ($1!=\"\*\") print $1}'); do git branch -d $branch; done"
1. Fetch the latest from my remote, removing any remote tracking branches that no longer exist

2. Enumerate local branches, selecting each that has been marked as no longer having a remote version (ignoring the current branch)

3. Delete the local branch safely

3 hours agoarusahni

So effectively "I just discovered xargs"? Not to disparage OP but there isn't anything particularly novel here.

4 hours agoparliament32

This feels like gatekeeping someone sharing something cool they've recently learned.

I personally lean more towards the "let's share cool little productivity tips and tricks with one another" instead of the "in order to share this you have to meet [entirely arbitrary line of novelty/cleverness/originality]."

But each to their own I suppose. I wonder how you learned about using xargs? Maybe a blog-post or article not dissimilar to this one?

3 hours agoSomeone1234

I don't think there's anything wrong with sharing something cool, even if it's trivial to other people. The problem is framing a blog post with "ooh this was buried in the secret leaked CIA material".. and then the reader opens it to find out it's just xargs. It feels very clickbaity. Akin to "here's one simple trick to gain a treasure trove of information about all the secret processes running on your system!!" and it's just ps.

2 hours agoparliament32

No I agree with you. This whole aura of "well IIIII knew this and YOUUUUU didnt" needs to die. I get that it's sometimes redundant and frustrating to encounter the same question a few times... but there's always new people learning in this world, and they deserve a chance to learn too.

Why do people constantly have to be looking for any way to justify their sense of superiority over others? Collaborative attitudes are so much better for all involved.

2 hours agosuperxpro12

And they have to learn that from cia?

That says so much about the generation we are in, just don’t go to school but learn math from mafia

3 hours agojimmydoe

Where else would you learn about triple-entry bookkeeping?

3 hours agovntok

People really do need to read the “Unix Power Tools” book and realize their problem has been solved for decades.

3 hours agoskydhash

"People just need to find the info they don't know about, so then they'll know it."

3 hours agogosub100

I don't find that the insinuation of the parent comment at all.

Saying "If you read X book, you'll realize it's a solved problem" IS the information -- the name of the book you need to read

an hour agogavinray

People need to be curious. Then they seek out the info they don't know about.

an hour agoSoftTalker

[dead]

3 hours agocgfjtynzdrfht

gh-poi plugin is a must if you manage a lot of github pr and want to easily clean the branch attached to it when pr is merged https://github.com/seachicken/gh-poi

17 minutes agosamtrack2019
[deleted]
4 hours ago

We all have something similar, it seems! I stole mine from https://stackoverflow.com/questions/7726949/remove-tracking-....

I also set mine up to run on `git checkout master` so that I don't really have to think about it too hard -- it just runs automagically. `gcm` has now become muscle memory for me.

  alias gcm=$'git checkout master || git checkout main && git pull && git remote prune origin && git branch -vv | grep \': gone]\'|  grep -v "\*" | awk \'{ print $1; }\' | xargs -r git branch -D'
3 hours agoCherub0774

Same using a git alias rather than shell, and without the network bits, it just cleans up branches which have an upstream that has been deleted:

    '!f() { git branch --format '%(refname:short) %(upstream:track,nobracket)'  | awk '$2~/^gone$/{print $1}'  | xargs git branch -D; }; f'
3 hours agomasklinn

    DEFAULT_BRANCH=$(git remote show origin | sed -n '/HEAD branch/s/.*: //p')

    git branch --merged "origin/$DEFAULT_BRANCH" \
      | grep -vE "^\s*(\*|$DEFAULT_BRANCH)" \
      | xargs -r -n 1 git branch -d
This is the version I'd want in my $EMPLOYER's codebase that has a mix of default branches
2 hours agomaerF0x0

I’ve been using something similar for years with Nushell.

git branch | lines | where ($it !~ '^*') | each {|br| git branch -D ($br | str trim)} | str trim

34 minutes agomicroflash

Using grep and xargs is worth a whole blog post now? hmmmmm

36 minutes agobobabob

Much more complicated than necessary. I just use

git branch | xargs git branch -d

Don't quote me, that's off the top of my head.

It won't delete unmerged branches by default. The line with the marker for the current branch throws an error but it does no harm. And I just run it with `develop` checked out. If I delete develop by accident I can recreate it from origin/develop.

Sometimes I intentionally delete develop if my develop branch is far behind the feature branch I'm on. If I don't and I have to switch to a really old develop and pull before merging in my feature branch, it creates unnecessary churn on my files and makes my IDE waste time trying to build the obsolete stuff. And depending how obsolete it is and what files have changed, it can be disruptive to the IDE.

2 hours agoEricRiese

Speaking of user friendliness of git UI. I am working on a revision control system that (ideally) should be as user friendly as Ctrl+S Ctrl+Z in most common cases. Spent almost a week on design docs, looking for feedback (so far it was very valuable, btw)

https://replicated.wiki/blog/partII.html#navigating-the-hist...

3 hours agogritzko

Have you tried Jujutsu? If you want to make a better VCS, your baseline should be that, in my opinion, because it already deals with a lot of the Git pain points whilst be able to read and publish to Git repositories.

3 hours agooniony

The idea of using git as a blob storage and building entire new machinery on top is definitely a worthy one. At this point though, the de-facto baseline is no doubt git. If git as a store withstands the abuse of jj and jj becomes the industry standard, then I would agree with you. Also, at that point they may drop git backend entirely just because of price/performance discrepancy. git is overweight for what it does, if they make it do only the bottom 20%, then things will get funny.

Still, many oddities of git are inevitable due to its underlying storage model, so it makes sense to explore other models too.

3 hours agogritzko

This looks loosely like something already present in git-extras[1].

    [1]: https://github.com/tj/git-extras/blob/main/Commands.md#git-delete-merged-branches
an hour agojldugger

I use this PowerShell variant:

    function Remove-GitBranches {
        git branch --merged | Out-GridView -Title "Branches to Remove?" -OutputMode Multiple | % { git branch -d $_.Trim() }
    }
`Out-GridView` gives you a quick popup dialog with all the branch names that supports easy multi-select. That way you get a quick preview of what you are cleaning up and can skip work in progress branch names that you haven't committed anything to yet.
2 hours agoWorldMaker

I have an image of running his command, 'ciaclean', and a black van turnes up with a bunch of agents in coveralls, brandishing rolls of polyethylene sheeting and drums of acid.

2 hours agojimnotgym

IIRC, you can do git branch -D $(git branch) and git will refuse to delete your current branch. Kind of the lazy way. I never work off of master/main, and usually when I need to look at them I checkout the remote branches instead.

3 hours agod0liver

I needed that exact functionality and Claude code and ChatGPT consistently showing this same exact combo CLI receipt with the simple prompt "how to do use CLI to remove merged branch locally."

an hour agodevy

It's hardly a profound insight. If you're fluent at the command line, xargs enables all sorts of conveniences.

an hour agoSoftTalker

I use

    #!/bin/sh
    
    git checkout main
    git fetch --prune
    git branch | grep -v main | xargs --no-run-if-empty git branch -D
    git pull
Save that next to your git binary, call it whatever you want. It's destructive on purpose.
4 hours ago1a527dd5

I've had this command as 'git drop-merged' for a few years now (put as a script in your path named git-drop-merged:

  #!/bin/sh
  git branch --merged | egrep -v "(^\*|master|main|dev)" | xargs --no-run-if-empty
  git branch -d
4 hours agosigio

I've had this in my ~/.bash_aliases for awhile:

  alias git-wipe-merged-branches='git branch --merged | grep -v \* | xargs git branch -D'
Trying to remember where I got that one, as I had commented the following version out:

  alias git-wipe-all-branches='git for-each-ref --format '%(refname:short)' refs/heads | grep -v master | xargs git branch -D'
3 hours agotaude

> Since most projects now use main instead of master…

I see that even the CIA, a federal government office, has not fully used DEI approved, inclusive language yet :-)

2 hours agomrbonner

The leaked material from which this came was described as being from 2017, which makes that the latest this could have been written - GitHub only changed the default for new repos in October of 2020, and there had only been consensus building around the switch for a couple of years beforehand.

2 hours agojen20

Missed opportunity to call it `git ciao`

3 hours agostabbles

I don't delete branches, I just work with the top several most recently modified.

3 hours agopassword4321

How to list those? Is there a flag for git branch to sort by recently modified?

(not on my computer right now to check)

3 hours agothe_real_cher

This isn't exactly the same but I've been using git-recent [0] (with `gr` alias) for many years. It sorts branches based on checkout order (which is what I usually need when switching between branches) and allows to easily choose a branch to checkout to.

[0] https://github.com/paulirish/git-recent

2 hours agorpozarickij

I do `gb` (probably "git branch" when I set that up) which apparently is an alias to `git for-each-ref --sort=-committerdate refs/heads/ --format='%(refname:short)' | tac`, displays a list with the latest changed branch at the bottom. Remove the `| tac` for the reverse order.

2 hours agoembedding-shape

Anyone else "vibe git-ing” lately? I just ask Claude Opus to clean it up and it does really well. Same for build commands and test harnesses.

2 hours agocowlby

It does a pretty good job, but I still don't completely trust it with keys to the kingdom.

I have replaced my standard ddg of, "git <the thing i need>" with asking Claude to give me the commands I need to run.

2 hours agomywittyname

Dont most git instances, like github, delete branch after a PR was merged, by default?

I am not sure under what usecases, you will end up with a lot of stale branches. And git fetch -pa should fix it locally

3 hours agoihsoy

`--prune` will delete your local copies of the origin's branches (e.g. `origin/whatever`). But it won't delete your local branches (e.g. `whatever` itself). So PRs that you've worked on or checked out locally will never get deleted.

3 hours agonightpool

> Dont most git instances, like github, delete branch after a PR was merged, by default?

By default, I don't think so. And even if the branch is deleted, objects can still be there. I think GitLab has a "Clean stale objects" thing you can trigger, I don't seem to recall ever seeing any "Git Maintenance" UI actions on GitHub so not sure how it works there.

2 hours agoembedding-shape

In Github it needs to be explicitly configured (Settings > General > Delete head branches after merging), Gitlab is the same.

A lot of my developer colleagues don't know how git works, so they have no idea that "I merged the PR" != "I deleted the feature branch". I once had to cleanup a couple repositories that had hundreds of branches spanning back 5+ years.

Nowadays I enforce it as the default project setting.

3 hours agoplqbfbv

I cleanup branches interactively with a few lines of bash, which takes a bit more time but is less likely to destroy active work.

2 hours agoblock_dagger

If you squash your PR before merging, then this alternative worked really well for me:

  git fetch --prune && git branch -vv | awk '/: gone]/{print $1}' | xargs git branch -D
3 hours agotrashymctrash

Almost identical to mine, but you've got smarter awk use: `git prune origin && git branch -vv | grep 'origin/.*: gone]' | awk '{print $1}' | xargs git branch -D`

I think I probably copied this from Stack Overflow close to a decade ago. Seems like a lot of people have very similar variations.

an hour agolkbm

Oh this is what ChatGPT told me when I asked "How to remove all local branch except main"...

2 hours agomarkus_zhang

I recently let copilot create a document with a few helpful git commands and that particular one was the one it came with as solution for exactly this case.

3 hours agomicw

Wait, why would the update for the silly master->main change be swapping the excluded regex instead of just excluding both?

3 hours agodietr1ch

coz OP has agenda and

> Since most projects now use main instead of master

some delusions to boot

3 hours agoPunchyHamster

You probably want git-dmb (dmb = delete merged branches) for a safe and more comprehensive way of dealing with this.

3 hours agoSesse__
[deleted]
3 hours ago

The git plugin in oh-my-zsh has an alias for this: gbda

It also has one for squash-merged branches: gbds

Very useful I've been using them for years

4 hours agogalbar

That's handy! I just started using oh-my-zsh and I feel like I know about 4% of useful things it can do so far.

4 hours agoblakesterz

"trapd00r" is the theme you want, if only because the name is cool

3 hours agogjvc

I change themes just often enough to completely forget how to do it and also forget whatever other adjustments I had to make to it all work. And like... is my config versioned somehow? This is a long way to say, Thank You for inspiring me to look at all that stuff again!

3 hours agogiglamesh

Unfortunately doesn't work if the project you work on squashes everything :(

3 hours agoArch-TK

"ciaclean" is a nice touch.

I assume CIA stands for Clean It All.

3 hours agoschiffern

"Clean It All, Clean" :P

3 hours agosammyteee

I assume it means mess up commit history and install ”our” BDFL.

3 hours agoplufz
[deleted]
3 hours ago

honestly my go to is kind of similar, but I prefer using --format vs. straight grep. just feels like the plumbing is cleaner out of the box:

    git branch --merged origin/main --format="%(refname:short)" \ | grep -vE "^(main|develop)$" \ | xargs -r git branch -d

that said... pretty hilarious a dev was just like "uhh yeah ciaclean..." curious what... other aliases they might have??
2 hours agorickknowlton
[deleted]
3 hours ago

don't forget to fetch first

2 hours agodevhouse
[deleted]
2 hours ago

[dead]

2 hours agobgfjhgghhhg

[flagged]

3 hours agomorissette

agree, this just seems click-baity. if you're familiar with the UNIX Way, this is a one-liner you'd naturally write. CIA leaked docs mention and a blog post for this?

3 hours agosidsud

the Clandestine allure for clicks for sure but you know what - the comments have been pretty interesting.