Run yapf on list of files from git-diff output - python

I want to add a pre-commit hook to run yapf on changed changed in a commit. I use
git diff --name-only --line-prefix=`git rev-parse --show-toplevel`
to get the list of full file names modified in a commit.
I am not sure on how to run yapf on the list of files produced by the above command as part of git pre-commit hook. I tried executing in bash
git diff --name-only --line-prefix=`git rev-parse --show-toplevel` | yapf -i
but it says yapf: error: cannot use --in-place or --diff flags when reading from stdin. My question here is there a way to run yapf on a list of changed files?

Related

How to exclude Jupyter notebook checkpoints from git [duplicate]

I put a file that was previously being tracked by Git onto the .gitignore list. However, the file still shows up in git status after it is edited. How do I force Git to completely forget the file?
.gitignore will prevent untracked files from being added (without an add -f) to the set of files tracked by Git. However, Git will continue to track any files that are already being tracked.
To stop tracking a file, we must remove it from the index:
git rm --cached <file>
To remove a folder and all files in the folder recursively:
git rm -r --cached <folder>
The removal of the file from the head revision will happen on the next commit.
WARNING: While this will not remove the physical file from your local machine, it will remove the files from other developers' machines on their next git pull.
The series of commands below will remove all of the items from the Git index (not from the working directory or local repository), and then will update the Git index, while respecting Git ignores. PS. Index = Cache
First:
git rm -r --cached .
git add .
Then:
git commit -am "Remove ignored files"
Or as a one-liner:
git rm -r --cached . && git add . && git commit -am "Remove ignored files"
git update-index does the job for me:
git update-index --assume-unchanged <file>
Note: This solution is actually independent of .gitignore as gitignore is only for untracked files.
Update, a better option
Since this answer was posted, a new option has been created and that should be preferred. You should use --skip-worktree which is for modified tracked files that the user don't want to commit anymore and keep --assume-unchanged for performance to prevent git to check status of big tracked files. See https://stackoverflow.com/a/13631525/717372 for more details...
git update-index --skip-worktree <file>
To cancel
git update-index --no-skip-worktree <file>
git ls-files -c --ignored --exclude-standard -z | xargs -0 git rm --cached
git commit -am "Remove ignored files"
This takes the list of the ignored files, removes them from the index, and commits the changes.
Move it out, commit, and then move it back in.
This has worked for me in the past, but there is probably a 'gittier' way to accomplish this.
I always use this command to remove those untracked files.
One-line, Unix-style, clean output:
git ls-files --ignored --exclude-standard | sed 's/.*/"&"/' | xargs git rm -r --cached
It lists all your ignored files, replaces every output line with a quoted line instead to handle paths with spaces inside, and passes everything to git rm -r --cached to remove the paths/files/directories from the index.
The copy/paste (one-liner) answer is:
git rm --cached -r .; git add .; git status; git commit -m "Ignore unwanted files"
This command will NOT change the content of the .gitignore file. It will just ignore the files that have already been committed to a Git repository, but now we have added them to .gitignore.
The command git status; is to review the changes and could be dropped.
Ultimately, it will immediately commit the changes with the message "Ignore unwanted files".
If you don't want to commit the changes, drop the last part of the command (git commit -m "Ignore unwanted files")
Use this when:
You want to untrack a lot of files, or
You updated your .gitignore file
Source: Untrack files already added to Git repository based on .gitignore
Let’s say you have already added/committed some files to your Git repository and you then add them to your .gitignore file; these files will still be present in your repository index. This article we will see how to get rid of them.
Step 1: Commit all your changes
Before proceeding, make sure all your changes are committed, including your .gitignore file.
Step 2: Remove everything from the repository
To clear your repository, use:
git rm -r --cached .
rm is the remove command
-r will allow recursive removal
–cached will only remove files from the index. Your files will still be there.
The rm command can be unforgiving. If you wish to try what it does beforehand, add the -n or --dry-run flag to test things out.
Step 3: Readd everything
git add .
Step 4: Commit
git commit -m ".gitignore fix"
Your repository is clean :)
Push the changes to your remote to see the changes effective there as well.
If you cannot git rm a tracked file because other people might need it (warning, even if you git rm --cached, when someone else gets this change, their files will be deleted in their filesystem). These are often done due to config file overrides, authentication credentials, etc. Please look at https://gist.github.com/1423106 for ways people have worked around the problem.
To summarize:
Have your application look for an ignored file config-overide.ini and use that over the committed file config.ini (or alternately, look for ~/.config/myapp.ini, or $MYCONFIGFILE)
Commit file config-sample.ini and ignore file config.ini, have a script or similar copy the file as necessary if necessary.
Try to use gitattributes clean/smudge magic to apply and remove the changes for you, for instance smudge the config file as a checkout from an alternate branch and clean the config file as a checkout from HEAD. This is tricky stuff, I don't recommend it for the novice user.
Keep the config file on a deploy branch dedicated to it that is never merged to master. When you want to deploy/compile/test you merge to that branch and get that file. This is essentially the smudge/clean approach except using human merge policies and extra-git modules.
Anti-recommentation: Don't use assume-unchanged, it will only end in tears (because having git lie to itself will cause bad things to happen, like your change being lost forever).
I accomplished this by using git filter-branch. The exact command I used was taken from the man page:
WARNING: this will delete the file from your entire history
git filter-branch --index-filter 'git rm --cached --ignore-unmatch filename' HEAD
This command will recreate the entire commit history, executing git rm before each commit and so will get rid of the specified file. Don't forget to back it up before running the command as it will be lost.
What didn't work for me
(Under Linux), I wanted to use the posts here suggesting the ls-files --ignored --exclude-standard | xargs git rm -r --cached approach. However, (some of) the files to be removed had an embedded newline/LF/\n in their names. Neither of the solutions:
git ls-files --ignored --exclude-standard | xargs -d"\n" git rm --cached
git ls-files --ignored --exclude-standard | sed 's/.*/"&"/' | xargs git rm -r --cached
cope with this situation (get errors about files not found).
So I offer
git ls-files -z --ignored --exclude-standard | xargs -0 git rm -r --cached
git commit -am "Remove ignored files"
This uses the -z argument to ls-files, and the -0 argument to xargs to cater safely/correctly for "nasty" characters in filenames.
In the manual page git-ls-files(1), it states:
When -z option is not used, TAB, LF, and backslash characters in
pathnames are represented as \t, \n, and \\, respectively.
so I think my solution is needed if filenames have any of these characters in them.
Do the following steps for a file/folder:
Remove a File:
need to add that file to .gitignore.
need to remove that file using the command (git rm --cached file name).
need to run (git add .).
need to (commit -m) "file removed".
and finally, (git push).
For example:
I want to delete the test.txt file. I accidentally pushed to GitHub and want to remove it. Commands will be as follows:
First, add "test.txt" in file .gitignore
git rm --cached test.txt
git add .
git commit -m "test.txt removed"
git push
Remove Folder:
need to add that folder to file .gitignore.
need to remove that folder using the command (git rm -r --cached folder name).
need to run (git add .).
need to (commit -m) "folder removed".
and finally, (git push).
For example:
I want to delete the .idea folder/directory. I accidentally pushed to GitHub and want to remove it. The commands will be as follows:
First, add .idea in file .gitignore
git rm -r --cached .idea
git add .
git commit -m ".idea removed"
git push
Update your .gitignore file – for instance, add a folder you don't want to track to .gitignore.
git rm -r --cached . – Remove all tracked files, including wanted and unwanted. Your code will be safe as long as you have saved locally.
git add . – All files will be added back in, except those in .gitignore.
Hat tip to #AkiraYamamoto for pointing us in the right direction.
Do the following steps serially, and you will be fine.
Remove the mistakenly added files from the directory/storage. You can use the "rm -r" (for Linux) command or delete them by browsing the directories. Or move them to another location on your PC. (You maybe need to close the IDE if running for moving/removing.)
Add the files / directories to the .gitignore file now and save it.
Now remove them from the Git cache by using these commands (if there is more than one directory, remove them one by one by repeatedly issuing this command)
git rm -r --cached path-to-those-files
Now do a commit and push by using the following commands. This will remove those files from Git remote and make Git stop tracking those files.
git add .
git commit -m "removed unnecessary files from Git"
git push origin
I think, that maybe Git can't totally forget about a file because of its conception (section "Snapshots, Not Differences").
This problem is absent, for example, when using CVS. CVS stores information as a list of file-based changes. Information for CVS is a set of files and the changes made to each file over time.
But in Git every time you commit, or save the state of your project, it basically takes a picture of what all your files look like at that moment and stores a reference to that snapshot. So, if you added file once, it will always be present in that snapshot.
These two articles were helpful for me:
git assume-unchanged vs skip-worktree and How to ignore changes in tracked files with Git
Basing on it I do the following, if the file is already tracked:
git update-index --skip-worktree <file>
From this moment all local changes in this file will be ignored and will not go to remote. If the file is changed on remote, conflict will occur, when git pull. Stash won't work. To resolve it, copy the file content to the safe place and follow these steps:
git update-index --no-skip-worktree <file>
git stash
git pull
The file content will be replaced by the remote content. Paste your changes from the safe place to the file and perform again:
git update-index --skip-worktree <file>
If everyone, who works with the project, will perform git update-index --skip-worktree <file>, problems with pull should be absent. This solution is OK for configurations files, when every developer has their own project configuration.
It is not very convenient to do this every time, when the file has been changed on remote, but it can protect it from overwriting by remote content.
Using the git rm --cached command does not answer the original question:
How do you force git to completely forget about [a file]?
In fact, this solution will cause the file to be deleted in every other instance of the repository when executing a git pull!
The correct way to force Git to forget about a file is documented by GitHub here.
I recommend reading the documentation, but basically:
git fetch --all
git filter-branch --force --index-filter 'git rm --cached --ignore-unmatch full/path/to/file' --prune-empty --tag-name-filter cat -- --all
git push origin --force --all
git push origin --force --tags
git for-each-ref --format='delete %(refname)' refs/original | git update-ref --stdin
git reflog expire --expire=now --all
git gc --prune=now
Just replace full/path/to/file with the full path of the file. Make sure you've added the file to your .gitignore file.
You'll also need to (temporarily) allow non-fast-forward pushes to your repository, since you're changing your Git history.
Move or copy the file to a safe location, so you don't lose it. Then 'git rm' the file and commit.
The file will still show up if you revert to one of those earlier commits, or another branch where it has not been removed. However, in all future commits, you will not see the file again. If the file is in the Git ignore, then you can move it back into the folder, and Git won't see it.
The answer from Matt Frear was the most effective IMHO. The following is just a PowerShell script for those on Windows to only remove files from their Git repository that matches their exclusion list.
# Get files matching exclusionsfrom .gitignore
# Excluding comments and empty lines
$ignoreFiles = gc .gitignore | ?{$_ -notmatch "#"} | ?{$_ -match "\S"} | % {
$ignore = "*" + $_ + "*"
(gci -r -i $ignore).FullName
}
$ignoreFiles = $ignoreFiles| ?{$_ -match "\S"}
# Remove each of these file from Git
$ignoreFiles | % { git rm $_}
git add .
The accepted answer does not "make Git "forget" about a file..." (historically). It only makes Git ignore the file in the present/future.
This method makes Git completely forget ignored files (past/present/future), but it does not delete anything from the working directory (even when re-pulled from remote).
This method requires usage of file /.git/info/exclude (preferred) or a pre-existing .gitignore in all the commits that have files to be ignored/forgotten. 1
All methods of enforcing Git ignore behavior after-the-fact effectively rewrite history and thus have significant ramifications for any public/shared/collaborative repositories that might be pulled after this process. 2
General advice: start with a clean repository - everything committed, nothing pending in working directory or index, and make a backup!
Also, the comments/revision history of this answer (and revision history of this question) may be useful/enlightening.
#Commit up-to-date .gitignore (if not already existing)
#This command must be run on each branch
git add .gitignore
git commit -m "Create .gitignore"
#Apply standard Git ignore behavior only to the current index, not the working directory (--cached)
#If this command returns nothing, ensure /.git/info/exclude AND/OR .gitignore exist
#This command must be run on each branch
git ls-files -z --ignored --exclude-standard | xargs -0 git rm --cached
#Commit to prevent working directory data loss!
#This commit will be automatically deleted by the --prune-empty flag in the following command
#This command must be run on each branch
git commit -m "ignored index"
#Apply standard git ignore behavior RETROACTIVELY to all commits from all branches (--all)
#This step WILL delete ignored files from working directory UNLESS they have been dereferenced from the index by the commit above
#This step will also delete any "empty" commits. If deliberate "empty" commits should be kept, remove --prune-empty and instead run git reset HEAD^ immediately after this command
git filter-branch --tree-filter 'git ls-files -z --ignored --exclude-standard | xargs -0 git rm -f --ignore-unmatch' --prune-empty --tag-name-filter cat -- --all
#List all still-existing files that are now ignored properly
#If this command returns nothing, it's time to restore from backup and start over
#This command must be run on each branch
git ls-files --other --ignored --exclude-standard
Finally, follow the rest of this GitHub guide (starting at step 6) which includes important warnings/information about the commands below.
git push origin --force --all
git push origin --force --tags
git for-each-ref --format="delete %(refname)" refs/original | git update-ref --stdin
git reflog expire --expire=now --all
git gc --prune=now
Other developers that pull from the now-modified remote repository should make a backup and then:
#fetch modified remote
git fetch --all
#"Pull" changes WITHOUT deleting newly-ignored files from working directory
#This will overwrite local tracked files with remote - ensure any local modifications are backed-up/stashed
git reset FETCH_HEAD
Footnotes
1 Because /.git/info/exclude can be applied to all historical commits using the instructions above, perhaps details about getting a .gitignore file into the historical commit(s) that need it is beyond the scope of this answer. I wanted a proper .gitignore file to be in the root commit, as if it was the first thing I did. Others may not care since /.git/info/exclude can accomplish the same thing regardless where the .gitignore file exists in the commit history, and clearly rewriting history is a very touchy subject, even when aware of the ramifications.
FWIW, potential methods may include git rebase or a git filter-branch that copies an external .gitignore into each commit, like the answers to this question.
2 Enforcing Git ignore behavior after-the-fact by committing the results of a stand-alone git rm --cached command may result in newly-ignored file deletion in future pulls from the force-pushed remote. The --prune-empty flag in the following git filter-branch command avoids this problem by automatically removing the previous "delete all ignored files" index-only commit. Rewriting Git history also changes commit hashes, which will wreak havoc on future pulls from public/shared/collaborative repositories. Please understand the ramifications fully before doing this to such a repository. This GitHub guide specifies the following:
Tell your collaborators to rebase, not merge, any branches they created off of your old (tainted) repository history. One merge commit could reintroduce some or all of the tainted history that you just went to the trouble of purging.
Alternative solutions that do not affect the remote repository are git update-index --assume-unchanged </path/file> or git update-index --skip-worktree <file>, examples of which can be found here.
In my case I needed to put ".envrc" in the .gitignore file.
And then I used:
git update-index --skip-worktree .envrc
git rm --cached .envrc
And the file was removed.
Then I committed again, telling that the file was removed.
But when I used the command git log -p, the content of the file (which was secret credentials of the Amazon S3) was showing the content which was removed and I don't want to show this content ever on the history of the Git repository.
Then I used this command:
git filter-branch --index-filter 'git rm --cached --ignore-unmatch .envrc' HEAD
And I don't see the content again.
I liked JonBrave's answer, but I have messy enough working directories that commit -a scares me a bit, so here's what I've done:
git config --global alias.exclude-ignored '!git ls-files -z --ignored --exclude-standard | xargs -0 git rm -r --cached && git ls-files -z --ignored --exclude-standard | xargs -0 git stage && git stage .gitignore && git commit -m "new gitignore and remove ignored files from index"'
Breaking it down:
git ls-files -z --ignored --exclude-standard | xargs -0 git rm -r --cached
git ls-files -z --ignored --exclude-standard | xargs -0 git stage
git stage .gitignore
git commit -m "new gitignore and remove ignored files from index"
remove ignored files from the index
stage .gitignore and the files you just removed
commit
The BFG is specifically designed for removing unwanted data like big files or passwords from Git repositories, so it has a simple flag that will remove any large historical (not-in-your-current-commit) files: '--strip-blobs-bigger-than'
java -jar bfg.jar --strip-blobs-bigger-than 100M
If you'd like to specify files by name, you can do that too:
java -jar bfg.jar --delete-files *.mp4
The BFG is 10-1000x faster than git filter-branch and is generally much easier to use - check the full usage instructions and examples for more details.
Source: Reduce repository size
If you don't want to use the CLI and are working on Windows, a very simple solution is to use TortoiseGit. It has the "Delete (keep local)" Action in the menu which works fine.
This is no longer an issue in the latest Git (v2.17.1 at the time of writing).
The .gitignore file finally ignores tracked-but-deleted files. You can test this for yourself by running the following script. The final git status statement should report "nothing to commit".
# Create an empty repository
mkdir gitignore-test
cd gitignore-test
git init
# Create a file and commit it
echo "hello" > file
git add file
git commit -m initial
# Add the file to gitignore and commit
echo "file" > .gitignore
git add .gitignore
git commit -m gitignore
# Remove the file and commit
git rm file
git commit -m "removed file"
# Reintroduce the file and check status.
# .gitignore is now respected - status reports "nothing to commit".
echo "hello" > file
git status
This is how I solved my issue:
git filter-branch --tree-filter 'rm -rf path/to/your/file' HEAD
git push
In this, we are basically trying to rewrite the history of that particular file in previous commits also.
For more information, you can refer to the man page of filter-branch here.
Source: Removing sensitive data from a repository - using filter-branch
Source: Git: How to remove a big file wrongly committed
In case of already committed DS_Store:
find . -name .DS_Store -print0 | xargs -0 git rm --ignore-unmatch
Ignore them by:
echo ".DS_Store" >> ~/.gitignore_global
echo "._.DS_Store" >> ~/.gitignore_global
echo "**/.DS_Store" >> ~/.gitignore_global
echo "**/._.DS_Store" >> ~/.gitignore_global
git config --global core.excludesfile ~/.gitignore_global
Finally, make a commit!
Especially for the IDE-based files, I use this:
For instance, for the slnx.sqlite file, I just got rid off it completely like the following:
git rm {PATH_OF_THE_FILE}/slnx.sqlite -f
git commit -m "remove slnx.sqlite"
Just keep that in mind that some of those files store some local user settings and preferences for projects (like what files you had open). So every time you navigate or do some changes in your IDE, that file is changed and therefore it checks it out and show as uncommitted changes.
If anyone is having a hard time on Windows and you want to ignore the entire folder, go to the desired 'folder' on file explorer, right click and do 'Git Bash Here' (Git for Windows should have been installed).
Run this command:
git ls-files -z | xargs -0 git update-index --assume-unchanged
For me, the file was still available in the history and I first needed to squash the commits that added the removed files: https://gist.github.com/patik/b8a9dc5cd356f9f6f980
Combine the commits. The example below combines the last 3 commits
git reset --soft HEAD~3
git commit -m "New message for the combined commit"
Push the squashed commit
If the commits have been pushed to the remote:
git push origin +name-of-branch
In my case here, I had several .lock files in several directories that I needed to remove. I ran the following and it worked without having to go into each directory to remove them:
git rm -r --cached **/*.lock
Doing this went into each folder under the 'root' of where I was at and excluded all files that matched the pattern.

Git pre-commit get all Python files

I'd like to run black to format all the staged .py files on a commit. Unfortunately due to employer network VPN and restrictions I'm unable to use the pre-commit package because it times out when trying to load the repo.
So I decided to write my own pre-commit hook. Currently I have this
#!/bin/sh
# Check if this is the initial commit
if git rev-parse --verify HEAD >/dev/null 2>&1
then
echo "pre-commit: About to create a new commit..."
against=HEAD
else
echo "pre-commit: About to create the first commit..."
against=4b825dc642cb6eb9a060e54bf8d69288fbee4904
fi
# Autoformat with black
echo "pre-commit: Autoformatting Python code with black"
black $(git diff-index --cached --name-only --diff-filter=d $against)
The first part I found from Atlassian. The second part needs a filter of some sort to only take the .py files from the column which is returned by diff-index. How to get only the .py files from the list?
Also: I'm quite new to git hooks. Is this a robust way for me and my colleagues to make sure all code is formatted with black?
If you're looking for a way to do this in bash, the missing piece to the puzzle there is the filter to git diff-index.
in your case, you can diff against HEAD which will limit it to the filenames being committed:
$ git diff --staged --name-only --diff-filter=d -- '*.py'
t.py
the expression as written in your original post is also a bit problematic due to files potentially containing spaces in them -- usually the fix for this is to use -z with the output and xargs -0 to run the tool (this will cause filenames to be '\0' delimited):
git diff --staged --name-only --diff-filter=d -z -- '*.py' |
xargs -0 black
note that this will potentially miss some files that the pre-commit framework will find -- for example extensionless executables with a python shebang, or other files which are conventionally python such as a .pdbrc
for what it's worth, with pre-commit you can use the local+system escape hatch to avoid downloading tools (if you have them already installed)
for example:
repos:
- repo: local
hooks:
- id: black-system
name: black (system)
entry: black
types: [python]
language: system
require_serial: true
that said, this largely defeats the main purposes of the framework in that it no longer is managing the installation of the tools (so you'll have to set them up manually yourself)
notably, if you don't have black installed you'll see something like:
$ pre-commit run --all-files
black (system)...........................................................Failed
- hook id: black-system
- exit code: 1
Executable `black` not found
disclaimer, I'm the maintainer of pre-commit

How does one .gitignore pickle files in python? [duplicate]

How can I delete "file1.txt" from my repository?
Use git rm.
If you want to remove the file from the Git repository and the filesystem, use:
git rm file1.txt
git commit -m "remove file1.txt"
But if you want to remove the file only from the Git repository and not remove it from the filesystem, use:
git rm --cached file1.txt
git commit -m "remove file1.txt"
And to push changes to remote repo
git push origin branch_name
git rm file.txt removes the file from the repo but also deletes it from the local file system.
To remove the file from the repo and not delete it from the local file system use:
git rm --cached file.txt
The below exact situation is where I use git to maintain version control for my business's website, but the "mickey" directory was a tmp folder to share private content with a CAD developer. When he needed HUGE files, I made a private, unlinked directory and ftpd the files there for him to fetch via browser. Forgetting I did this, I later performed a git add -A from the website's base directory. Subsequently, git status showed the new files needing committing. Now I needed to delete them from git's tracking and version control...
Sample output below is from what just happened to me, where I unintentionally deleted the .003 file. Thankfully, I don't care what happened to the local copy to .003, but some of the other currently changed files were updates I just made to the website and would be epic to have been deleted on the local file system! "Local file system" = the live website (not a great practice, but is reality).
[~/www]$ git rm shop/mickey/mtt_flange_SCN.7z.003
error: 'shop/mickey/mtt_flange_SCN.7z.003' has local modifications
(use --cached to keep the file, or -f to force removal)
[~/www]$ git rm -f shop/mickey/mtt_flange_SCN.7z.003
rm 'shop/mickey/mtt_flange_SCN.7z.003'
[~/www]$
[~/www]$ git status
# On branch master
# Changes to be committed:
# (use "git reset HEAD <file>..." to unstage)
#
# deleted: shop/mickey/mtt_flange_SCN.7z.003
#
# Changed but not updated:
# (use "git add <file>..." to update what will be committed)
# (use "git checkout -- <file>..." to discard changes in working directory)
#
# modified: shop/mickey/mtt_flange_SCN.7z.001
# modified: shop/mickey/mtt_flange_SCN.7z.002
[~/www]$ ls shop/mickey/mtt_flange_S*
shop/mickey/mtt_flange_SCN.7z.001 shop/mickey/mtt_flange_SCN.7z.002
[~/www]$
[~/www]$
[~/www]$ git rm --cached shop/mickey/mtt_flange_SCN.7z.002
rm 'shop/mickey/mtt_flange_SCN.7z.002'
[~/www]$ ls shop/mickey/mtt_flange_S*
shop/mickey/mtt_flange_SCN.7z.001 shop/mickey/mtt_flange_SCN.7z.002
[~/www]$
[~/www]$
[~/www]$ git status
# On branch master
# Changes to be committed:
# (use "git reset HEAD <file>..." to unstage)
#
# deleted: shop/mickey/mtt_flange_SCN.7z.002
# deleted: shop/mickey/mtt_flange_SCN.7z.003
#
# Changed but not updated:
# modified: shop/mickey/mtt_flange_SCN.7z.001
[~/www]$
Update: This answer is getting some traffic, so I thought I'd mention my other Git answer shares a couple of great resources: This page has a graphic that help demystify Git for me. The "Pro Git" book is online and helps me a lot.
First, if you are using git rm, especially for multiple files, consider any wildcard will be resolved by the shell, not by the git command.
git rm -- *.anExtension
git commit -m "remove multiple files"
But, if your file is already on GitHub, you can (since July 2013) directly delete it from the web GUI!
Simply view any file in your repository, click the trash can icon at the top, and commit the removal just like any other web-based edit.
Then "git pull" on your local repo, and that will delete the file locally too.
Which makes this answer a (roundabout) way to delete a file from git repo?
(Not to mention that a file on GitHub is in a "git repo")
(the commit will reflect the deletion of that file):
And just like that, it’s gone.
For help with these features, be sure to read our help articles on creating, moving, renaming, and deleting files.
Note: Since it’s a version control system, Git always has your back if you need to recover the file later.
The last sentence means that the deleted file is still part of the history, and you can restore it easily enough (but not yet through the GitHub web interface):
See "Restore a deleted file in a Git repo".
This is the only option that worked for me.
git filter-branch -f --index-filter 'git rm --cached --ignore-unmatch *.sql'
Note: Replace *.sql with your file name or file type. Be very careful because this will go through every commit and rip this file type out.
EDIT:
pay attention - after this command you will not be able to push or pull - you will see the reject of 'unrelated history' you can use 'git push --force -u origin master' to push or pull
Additionally, if it's a folder to be removed and it's subsequent child folders or files, use:
git rm -r foldername
More generally, git help will help with at least simple questions like this:
zhasper#berens:/media/Kindle/documents$ git help
usage: git [--version] [--exec-path[=GIT_EXEC_PATH]] [--html-path] [-p|--paginate|--no-pager] [--bare] [--git-dir=GIT_DIR] [--work-tree=GIT_WORK_TREE] [--help] COMMAND [ARGS]
The most commonly used git commands are:
add Add file contents to the index
:
rm Remove files from the working tree and from the index
If you want to delete the file from the repo, but leave it in the the file system (will be untracked):
bykov#gitserver:~/temp> git rm --cached file1.txt
bykov#gitserver:~/temp> git commit -m "remove file1.txt from the repo"
If you want to delete the file from the repo and from the file system then there are two options:
If the file has no changes staged in the index:
bykov#gitserver:~/temp> git rm file1.txt
bykov#gitserver:~/temp> git commit -m "remove file1.txt"
If the file has changes staged in the index:
bykov#gitserver:~/temp> git rm -f file1.txt
bykov#gitserver:~/temp> git commit -m "remove file1.txt"
git rm will only remove the file on this branch from now on, but it remains in history and git will remember it.
The right way to do it is with git filter-branch, as others have mentioned here. It will rewrite every commit in the history of the branch to delete that file.
But, even after doing that, git can remember it because there can be references to it in reflog, remotes, tags and such.
If you want to completely obliterate it in one step, I recommend you to use git forget-blob
https://ownyourbits.com/2017/01/18/completely-remove-a-file-from-a-git-repository-with-git-forget-blob/
It is easy, just do git forget-blob file1.txt.
This will remove every reference, do git filter-branch, and finally run the git garbage collector git gc to completely get rid of this file in your repo.
Note: if you want to delete file only from git use below:
git rm --cached file1.txt
If you want to delete also from hard disk:
git rm file1.txt
If you want to remove a folder(the folder may contain few files) so, you should remove using recursive command, as below:
git rm -r foldername
If you want to remove a folder inside another folder
git rm -r parentFolder/childFolder
Then, you can commit and push as usual. However, if you want to recover deleted folder, you can follow this: recover deleted files from git is possible.
From doc:
git rm [-f | --force] [-n] [-r] [--cached] [--ignore-unmatch] [--quiet] [--] <file>…​
OPTIONS
<file>…​
Files to remove. Fileglobs (e.g. *.c) can be given to remove all matching files. If you want Git to expand file glob characters, you
may need to shell-escape them. A leading directory name (e.g. dir to
remove dir/file1 and dir/file2) can be given to remove all files in
the directory, and recursively all sub-directories, but this requires
the -r option to be explicitly given.
-f
--force
Override the up-to-date check.
-n
--dry-run
Don’t actually remove any file(s). Instead, just show if they exist in the index and would otherwise be removed by the command.
-r
Allow recursive removal when a leading directory name is given.
--
This option can be used to separate command-line options from the list of files, (useful when filenames might be mistaken for
command-line options).
--cached
Use this option to unstage and remove paths only from the index. Working tree files, whether modified or not, will be left alone.
--ignore-unmatch
Exit with a zero status even if no files matched.
-q
--quiet
git rm normally outputs one line (in the form of an rm command) for each file removed. This option suppresses that output.
Read more on official doc.
The answer by Greg Hewgill, that was edited by Johannchopin helped me, as I did not care about removing the file from the history completely.
In my case, it was a directory, so the only change I did was using:
git rm -r --cached myDirectoryName
instead of "git rm --cached file1.txt"
..followed by:
git commit -m "deleted myDirectoryName from git"
git push origin branch_name
Thanks Greg Hewgill and Johannchopin!
Another way if you want to delete the file from your local folder using rm command and then push the changes to the remote server.
rm file1.txt
git commit -a -m "Deleting files"
git push origin master
According to the documentation.
git rm --cached file1.txt
When it comes to sensitive data—better not say that you removed the file but rather just include it in the last known commit:
0. Amend last commit
git commit --amend -CHEAD
If you want to delete the file from all git history, according to the documentation you should do the following:
1. Remove it from your local history
git filter-branch --force --index-filter \ "git rm --cached --ignore-unmatch PATH-TO-YOUR-FILE-WITH-SENSITIVE-DATA" \ --prune-empty --tag-name-filter cat -- --all
# Replace PATH-TO-YOUR-FILE-WITH-SENSITIVE-DATA with the path to the file you want to remove, not just its filename
Don't forget to include this file in .gitignore (If it's a file you never want to share (such as passwords...):
echo "YOUR-FILE-WITH-SENSITIVE-DATA" >> .gitignore
git add .gitignore
git commit -m "Add YOUR-FILE-WITH-SENSITIVE-DATA to .gitignore"
3. If you need to remove from the remote
git push origin --force --all
4. If you also need to remove it from tag releases:
git push origin --force --tags
In my case I tried to remove file on github after few commits but save on computer
git filter-branch -f --index-filter 'git rm --cached --ignore-unmatch file_name_with_path' HEAD
git push --force -u origin master
and later this file was ignored
To delete a specific file
git rm filename
To clean all the untracked files from a directory recursively in single shot
git clean -fdx
If you have the GitHub for Windows application, you can delete a file in 5 easy steps:
Click Sync.
Click on the directory where the file is located and select your latest version of the file.
Click on tools and select "Open a shell here."
In the shell, type: "rm {filename}" and hit enter.
Commit the change and resync.
First,Remove files from local repository.
git rm -r File-Name
or, remove files only from local repository but from filesystem
git rm --cached File-Name
Secondly, Commit changes into local repository.
git commit -m "unwanted files or some inline comments"
Finally, update/push local changes into remote repository.
git push
go to your project dir and type:
git filter-branch --tree-filter 'rm -f <deleted-file>' HEAD
after that push --force for delete file from all commits.
git push origin --force --all
https://stackoverflow.com/a/2047477/14508423
https://stackoverflow.com/a/19666677/14508423
Quite similar, tried both. Nothing. Git keeps tracking the file. (I use vscode so the file got instantly marked as U(untracked) or A(added))
Doing this https://stackoverflow.com/a/53431148/14508423 to whole category solves the problem.
Do this to delete a file from git and make git forget about it:
**manually add the file name to .gitignore**
git rm --cached settings.py
git commit -m "remove settings.py"
git push origin master
git rm -r --cached .
git add .
git commit -m "Untrack files in .gitignore"
ps: every time it failed I tried to delete file with sensitive info like tokens (.env and settings.py files). But it works fine with random files oO
For the case where git rm doesn't suffice and the file needs to be removed from history: As the git filter-branch manual page now itself suggests using git-filter-repo, and I had to do this today, here's an example using that tool. It uses the example repo https://example/eguser/eg.git
Clone the repository into a new directory git clone https://example/eguser/eg.git
Keep everything except the unwanted file. git-filter-repo --path file1.txt --invert-paths
Add the remote repository origin back :
git remote add origin https://example/eguser/eg.git.
The git-filter-repo tool removes remote remote info by design and suggests a new remote repo (see point 4). This makes sense for big shared repos but might be overkill for getting rid a single newly added file as in this example.
When happy with the contents of local, replace remote with it.
git push --force -u origin master. Forcing is required due to the changed history.
Also note the useful --dry-run option and a good discussion in the linked manual on team and project dynamics before charging in and changing repository history.
I tried a lot of the suggested options and none appeared to work (I won't list the various problems).
What I ended up doing, which worked, was simple and intuitive (to me) was:
move the whole local repo elsewhere
clone the repo again from master to your local drive
copy back the files/folder from your original copy in #1 back into the new clone from #2
make sure that the problem large file is either not there or excluded in the .gitignore file
do the usual git add/git commit/git push
After you have removed the file from the repo with git rm you can use BFG Repo-Cleaner to completely and easily obliterate the file from the repo history.
Just by going on the file in your github repository you can see the delete icon beside Raw|Blame and don't forget to click on commit changes button. And you can see that your file has been deleted.
New answer that works in 2022.
Do not use:
git filter-branch
this command might not change the remote repo after pushing. If you clone after using it, you will see that nothing has changed and the repo still has a large size. This command is old now. For example, if you use the steps in https://github.com/18F/C2/issues/439, this won't work.
You need to use
git filter-repo
Steps:
(1) Find the largest files in .git:
git rev-list --objects --all | grep -f <(git verify-pack -v .git/objects/pack/*.idx| sort -k 3 -n | cut -f 1 -d " " | tail -10)
(2) Strat filtering these large files:
git filter-repo --path-glob '../../src/../..' --invert-paths --force
or
git filter-repo --path-glob '*.zip' --invert-paths --force
or
git filter-repo --path-glob '*.a' --invert-paths --force
or
whatever you find in step 1.
(3)
git remote add origin git#github.com:.../...git
(4)
git push --all --force
git push --tags --force
DONE!
I have obj and bin files that accidentally made it into the repo that I don't want polluting my 'changed files' list
After I noticed they went to the remote, I ignored them by adding this to .gitignore
/*/obj
/*/bin
Problem is they are already in the remote, and when they get changed, they pop up as changed and pollute the changed file list.
To stop seeing them, you need to delete the whole folder from the remote repository.
In a command prompt:
CD to the repo folder (i.e. C:\repos\MyRepo)
I want to delete SSIS\obj. It seems you can only delete at the top level, so you now need to CD into SSIS: (i.e. C:\repos\MyRepo\SSIS)
Now type the magic incantation git rm -r -f obj
rm=remove
-r = recursively remove
-f = means force, cause you really mean it
obj is the folder
Now run git commit -m "remove obj folder"
I got an alarming message saying 13 files changed 315222 deletions
Then because I didn't want to have to look up the CMD line, I went into Visual Sstudio and did a Sync to apply it to the remote
if your file is sensitive (for example, settings or keys you accidently added and committed) then you can remove it from all versions.
To remove from all versions use the command below (warning: careful because you won't be able to restore the removed file in the repo if do not have a copy):
Using Git
git filter-branch --index-filter 'git rm -rf --cached --ignore-unmatch file.ext' HEAD
Using git-filter-repo (get it here, new recommended way by Git)
git filter-repo --path file.ext
If you need to remove files from a determined extension (for example, compiled files) you could do the following to remove them all at once:
git remove -f *.pyc
Incase if you don't file in your local repo but in git repo, then simply open file in git repo through web interface and find Delete button at right corner in interface.
Click Here, To view interface Delete Option

How to do versioning of .ipynb by removing output and converting?

I want to do versioning of ipynb notebooks such that, when I add the notebooks to git, the scripts that remove output and convert it to python script are called. Is there any way that I can automate this, so that when I put in the git add . command, it starts running the required scripts?
What you are describing is a git clean filter:
echo '*.ipynb filter=notebook2python' >> .gitattributes
git config --global filter.notebook2python.clean /path/to/notebook2python/script
git config --global filter.notebook2python.smudge cat
More documentation in Customizing Git - Git Attributes
You can write a git hook for this: https://git-scm.com/book/en/v2/Customizing-Git-Git-Hooks

Check style on git server

Is there any way to set up Python source checking on git server side?
Something like this (this is pre-commit hook):
#!/bin/sh
FILES=$(git diff --cached --name-only --diff-filter=ACM | grep -e '\.py$')
if [ -n "$FILES" ]; then
flake8 -r $FILES
fi
but on the server side(perhaps with update hook).
You can add an update hook, that will be getting input file in format of ${ref} ${oldrev} ${newrev}, e.g. something like refs/heads/master ddf343f635fe4440cad528e12f96f28bd50aa099 f59abbf28696389c91c2697c7db31f20cfa91d8a.
Armed with this knowledge, you can then make a diff between those two commits, list files that are there, check them for syntax, and fail in case you don't like them. If there is an entirely new branch pushed, the ${oldrev} will be 40 zeroes, so you'd have to probably check all the files in the new commit.

Categories