Showing posts with label linux. Show all posts
Showing posts with label linux. Show all posts

Wednesday, 28 February 2018

Converting CRLF to LF for all files in a git repository

At work we currently have people who do their dev on linux laptops, linux VMs, windows and the WSL which means that we need to be careful about the compatibility of files in git. We deploy to centos in all our production and pre-prod environments so we always check-in linux line endings.

But recently when I was looking through some codez I found a bit of a mix of files with LF and CRLF line endings and so wanted make them all consistent with the LF linux standard.

git config


I don’t know how this happened exactly and didn’t narrow it down to any one commit but just wanted it fixed. We should all have our git clients set to convert and check in linux line endings which you can check with the command:

git config --list --global
git config --list


You are looking for the setting core.autocrlf. This can take three values: true, false and input. Depending on the OS that you are using you need to ensure that you use the correct setting.

On windows it should be set to true. That is check out windows style (CRLF) but check in linux style (LF).

On linux it needs to set to false or input as you don’t want files to contain windows line endings during development so you chekout with LF. You can also leave as default which is false.

I make heavy use of WSL (windows subsystem for linux) as well as centos VMs running on virtualbox. WSL behaves like linux so I have the default set which is not to change the line endings going in or out. But you do have to be careful. If you change the files or create files using a windows editor (I use webstorm and sublime) then you could inadvertently check in windows line endings, so it might be best to use input. Input will checkout as is from the repo but on check in will convert all line endings to LF, just in case a CRLF file was introduced.

By the way I love the WSL I use it every day and do prefer it to using a VM running linux, it works great for node dev.

Converting CRLF to LF


Anyway back to the main point of this post. We have some files with windows line endings mixed in with files with linux line endings. How to make them consistent? In particular how to make them all have linux line endings?

The difference is \r\n (windows) vs \n (linux) the tool sed is very good at finding strings in a file and replacing them with another

sed is a stream editor for filtering and transforming text it takes we can make it take a regex replacement and run that against a file to remove any carriage returns from it '\r'

sed -i 's/\r//g' myfilename.js

-i tells sed to do an in place substitution, 's/\r//g' is a regex that searches for carriage return '\r' and replaces them with nothing '//' globally for that file.

But we have hundreds of files across tens of nested directories. So we need to find all the files we want to 'fix' using the find command.

find . -type f -not -path './.git*' -not -path './node_modules*'

This will recursively list all files from the current directory excluding any files in the .git or node_modules folders. Do remember to exclude your .git folders as you will corrupt it if you run the substitution against files in there. Also remove any package folders or binary folders, this depends on the environment you are working in, I'm currently doing node dev so excluding the node_modules is good enough for me.

All that remains is to put them together using the standard unix pipe operator and the xargs command which allows you to build and execute command lines, it will take the output of the find space separate the file names and append them to the next command, we would use it thus:

find . -type f -not -path './.git*' -not -path './node_modules*' | xargs sed -i 's/\r//g'

If the folder contained 2 files xargs would build a command that looked like this:

sed -i 's/\r//g' ./file1.js ./file2.js

Voila!

All CRLF line endings are replaced with LF. You should be able to check this by using git diff to see the changes. You should see all line endings in the unified diff like this:

diff --git a/file1.js b/file1.js
index 01ce825..f5f8e58 100644
--- a/file1.js
+++ b/file1.js
-old line with windows line endings^M
+old line with windows line endings


If you don’t see the ^M but just two lines that look the same then there are a couple of tricks you can try.
git diff -R This reverses the output, apparently git does not always highlight removed white space, but will highlight added white space.
git diff | cat -v This will pipe the raw patch output from the git diff to cat. cat with a -v echoes the input including all non-display characters (like a carriage return) to the console.

Appendix

https://git-scm.com/docs/git-config
https://git-scm.com/docs/git-diff
https://manpages.debian.org/stretch/sed/sed.1.en.html
https://manpages.debian.org/stretch/findutils/xargs.1.en.html
https://manpages.debian.org/stretch/findutils/find.1.en.html

Saturday, 27 January 2018

git shortcuts

I've just recently had to set up my git environment again. One thing came to my attention, that I've not got them all written down anywhere. This post is documentation so next time I have to do this I will have them easily to hand.

$git config --global --list

alias.cm=commit -m
alias.co=checkout
alias.d=diff
alias.ds=diff --staged
alias.l=log --oneline --decorate --graph --all
alias.s=status --short


This can be set up by either adding it to your git config ~/.gitconfig
[alias]
  cm = commit -m
  co = checkout
  d  = diff
  ds = diff --staged
  l  = log --oneline --decorate --graph --all
  s  = status --short


Or you can use the console to set the alias'

git config --global alias.cm commit -m
git config --global alias.co checkout
git config --global alias.d  diff
git config --global alias.ds diff --staged
git config --global alias.l  log --oneline --decorate --graph --all
git config --global alias.s  status --short


Also I use ZSH as my console of choice which has many built in shortcuts for practically all git commands. But to be honest I find them a little cryptic even for me. Be my guest to check it out https://github.com/robbyrussell/oh-my-zsh/wiki/Cheatsheet

Tuesday, 24 January 2017

Using beyond compare with Git on Linux (and windows)

EDIT - See footer for more info and an alternative to the main body of this post.


I'm a massive fan of Beyond compare, I use it a lot. It's brilliant for all the tasks related to file and folder diffs, either on the file system or in source control when viewing changes between revisions or branches.

Using git diff is ok when you are looking at a small set of changes but if there are many changes across many files I much prefer to use beyond compare to visualise the change set.

Git / Beyond Compare integration

The following code snippets are taken from a centos linux build, but there is no reason that with a little tweak this wont work on a windows machine. (In fact the little tweak is shown in the appendix at the bottom).

Edit your ~/.gitconfig (c:/users/UserName on windows) by adding the following:

[diff]
  tool = bcompare
[difftool "bcompare"]
  cmd = bcompare \"$LOCAL\" \"$REMOTE\"
  prompt = false
[merge]
  tool = bcompare
[mergetool "bcompare"]
  cmd = bcompare \"$LOCAL\" \"$REMOTE\" \"$BASE\" \"$MERGED\"
  keepBackup = false
  trustExitCode = false
[alias]
  diffdir = difftool -dir-diff -tool=bcompare -no-prompt


The above assumes that you have installed beyond compare and it is now accessible from the terminal as bcompare. In fact you can see how I install beyond compare in my vagrant bash scripts here: https://github.com/DamianStanger/centos-node-developer-build/blob/master/scripts/beyondcompare.sh

Usage - launching beyond compare from the git command line:

#View all un-staged differences one by one
git difftool

#View all committed differences between the current HEAD and the penultimate commit one by one
git difftool HEAD HEAD~1

#View all differences between master branch and bugfix branch in beyond compares directory view
git diffdir master bugfix

#View all differences between two change sets (SHA-1 ) in beyond compares directory view
git diffdir 6b6aa87 4f7d15d

#View the diff of one un-staged file, note the use of -no-prompt to stop the prompt on the terminal
git difftool -no-prompt myfile.txt

#View all changes both staged and modified one by one.
#As soon as you close beyond compare the next change will pop open (due to the -no-prompt flag)
git difftool HEAD -no-prompt


You might notice that when you use the diffdir command that the files are not editable, where as if you use the more interactive difftool command that the local files are available for changing and saving in beyond compare. This is because behind the scenes when you use the -dir-diff flag, git copies the modified files to a temporary location and then performs a directory diff on them. So if you do want to modify the files as you do a comparison you must use the more interactive difftool command.

references:

https://git-scm.com/docs/git-config
https://git-scm.com/docs/git-diff
https://git-scm.com/docs/git-difftool
https://git-scm.com/docs/git-mergetool

Windows

On windows its just as easy. The users gitconfig is located at c:\users\UserName\.gitconfig

Just replace the difftool and mergetool commands from the above code snippets with the following:
cmd = "'c:\\Program Files\\Beyond Compare 4\\BCompare.exe' $LOCAL $REMOTE"
cmd = "'c:\\Program Files\\Beyond Compare 4\\BCompare.exe' $LOCAL $REMOTE $BASE $MERGED"


EDIT

Since writing this post I’ve done more playing with git, difftool and beyond compare and have made the following revelations. Which I've only tested on linux centos 7.0 with git 1.8.3.1:
  • Out of the box you can use beyond compare as your difftool
    • Use 'git difftool -tool-help' to show all the options you have, do you see bc3 in the list? if so you are set to go.
    • Use 'git difftool -tool bc3' to open your diffs in beyond compare
  • Same with the mergetool
    • git mergetool --tool-help
    • git mergetool --tool bc3
I’ve also found that you can actually edit and save files whilst using the diffdir commaand, here’s how/why:

As I said before when using the -dir-diff command git makes copies of the files into a temp location. Well if one of the sides contains the modified (current working directory) files then the copy is not a hard file copy it’s a simlink to the file in the working directory. So, that means that if you have the option ‘Handling -> follow symbolic links’ in the ‘session settings – folder compare’ dialogue of beyond compare (I recommend that you save this as a session default) then any editing of files that you do WILL be in the working folder of your git repo. Bonza.

So what does all this mean to me? Do I actually need to edit my .gitconfig then?

Well, no, and yes. Beyond compare integration is there out of the box but I would create some alias entries so you don’t have to type in the full command as that would be painful.
[alias]
  bc3 = difftool -tool=bc3
  bc33 = difftool -no-prompt -tool=bc3
  bc3dir = difftool -dir-diff -tool=bc3


You now can issue the same commands as outlines above but with 'git bc3' or 'git bc3dir' rather than 'git difftool' and 'git diffdir'

Notice that I’ve made a distinction between bc3 and bc33. bc33 will not prompt you for opening the changes and so if you use it with a large change set you will have to cancel through a lot of files until the process ends. But I guess you could always ctrl+c on the terminal to kill the process, either way I find the distinction useful for just one extra character to type.

Monday, 14 November 2016

Connecting to a mongod instance from a different VM

I've got two CentOS installations running within Virtual Box. I want to run mongodb on one which will be optimised for this purpose, the other for developing and running my node apps.

VM1. CentOS full desktop install as documented here

This is the environment that I'm doing my development, running node etc.

VM2. CentOS minimal install, command line only

I've followed the instructions as documented in my other post to install mongod here.

Connect

Now I want to connect from VM1 to the mongod service running in VM2.

First change the network adapter of VM2 away from 'NAT' (the default) to 'Bridged Adapter' this will make this VM a full citizen of the network, it will get its own IP address and can be accessed on it from any other machine on the network.
Next amend the mongod.conf file in /ect/ by adding in the new IP address.

$ ip addr show
1: lo: mtu 65536 qdisc noqueue state UNKNOWN
    link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
    inet 127.0.0.1/8 scope host lo
       valid_lft forever preferred_lft forever
    inet6 ::1/128 scope host
       valid_lft forever preferred_lft forever
2: enp0s3: mtu 1500 qdisc pfifo_fast state UP qlen 1000
    link/ether 08:00:27:5c:41:9c brd ff:ff:ff:ff:ff:ff
    inet 192.168.0.10/24 brd 10.0.2.255 scope global dynamic enp0s3
       valid_lft 85748sec preferred_lft 85748sec
    inet6 fe80::a00:27ff:fe5c:419c/64 scope link
       valid_lft forever preferred_lft forever

 
$ su -c 'vi /etc/mongod.conf'
 
# Listen to local and LAN interface.
bind_ip = 127.0.0.1,192.168.0.10


This will allow remote access to the service as documented here

once this is done restart the mongod service on VM1 and connect from the remote VM thus:
$ mongo 192.168.0.10

Wednesday, 26 October 2016

Node development on CentOS for .Net devs

I'm about to start a new role which entails Node, Angular, Mongo and linux (CentOS) so ive set about learning the above. Quite a bit of a shift from the previous number of years which have been pretty much exclusively Microsoft and .Net. But im really excited about it and the new learning I need to embark upon. Today it was the turn of getting a CentOS development environment up and running on virtual box with npm, node and webstorm.

Creating the development environment

Install virtual box (5.1 at time of writing)
https://www.virtualbox.org/
download the dvd image of centOS (7 at time of writing)
https://www.centos.org/download/

Create a VM of the image,
On software selection i used KDE Plasma with internet tools and 
i used the KDE desktop with internet and KDE applications and development Tools
enable the network
create a user as well as set the super user password

To enable higher resolution
once set up, from the VM menu: device > insert guest additions CD image
this will act as if a cd was inserted into the VM
in the VBOXADDITIONS drive double click autorun.sh and enter your superuser password
reboot

Installing npm, node and webstorm

Within a terminal window
su -
yum install epel-release
yum install npm
npm --version
3.10.3
node --version
v6.7.0
exit

Download webstorm
http://www.jetbrains.com/webstorm/
Extract the folder to the place you want to install webstorm
double click webstorm.sh to install
remember to chose a dark theme ;-)

Create your first hello world node app with express

In a terminal (not as root)
cd /home/username/
mkdir code
cd code
mkdir express01
cd express01

npm init
take all the defaults
npm install express --save

Im not going to go into the the how to create a basic express app to echo something to the console and to the browser, there are so many tutorials about that out there.

Enjoy your new development environment.

Major learnings. I.e. Don't do this at work...


When you enter sudo for the first time you get the apt warning:

We trust you have received the usual lecture from the local System
Administrator. It usually boils down to these three things:

    #1) Respect the privacy of others.
    #2) Think before you type.
    #3) With great power comes great responsibility.


The first time I created the hello world app from the guide above I used su for everything, including creating the folders and npm init. This resulted in files and folders that i could not write to from webstorm so i tried to fix the permissions with chmod. But I used it very very wrongly and the interwebs advised me to reinstall everything. Which as it happens, this time was not a big deal for me.
So what did i do?
Whilst i was su i think i ran:
chmod 777 /. -R
In powershell .\ is the current directory, I thought ./ would be the same in linux but i did a typo and so i ended up making all the files and folders (on the whole VM) 777 rather than just the new code folders. Apparently this is very hard to fix.
The symptom is you type the command su - you get the error:
su -
su: cannot set groups: Operation not permitted

It can make things rather difficult if you cant get root access anymore.

Should it be this easy to screw your entire VM? or was there actually an easy fix? if you know id love to hear about it.




Wednesday, 18 December 2013

Search the whole SVN repository for a given filename

The SVN repository at work is huge, and I don't have the disk space to checkout the whole thing with the branches and everything on my small (but very fast) laptop SSD. But I needed to search through the whole repo for a file, the following command line can help out.

Windows

svn list -R https://subversion-repo/subfolder | findstr filename

Nix

svn list -R file:///subversion-repo/subfolder | grep filename

These commands don't look through the history but will find things at the current HEAD of the repository.

If you want to look for a particular point in time you can specify the revision thus:

svn list -r 1234 -R https://subversion-repo/subfolder | findstr filename

where 1234 is the revision to search though.

If you want to search the entire history you could script the search to look though every revision from 1 to n and list the files that match the search at each revision, then remove duplicates to get a single list. How about getting even fancier by recording the revision the file was first found and the revision it was deleted at. I have no requirement to do this right now but sounds like an interesting little project to try.

If you want to search for text in files I find searching the diffs useful. Just pipe the following into a file and search that in your favorite editor (Sublime text :-)

svn log -r1234:HEAD --diff https://subversion-repo/subfolder

this can be rather verbose but with a bit of tweaking and targeting of the repo/folder you can get some accurate results on text search in history

Wednesday, 8 May 2013

Developing node modules, npm and git. how to publish npm packages from a windows machine whilst preserving the unix style line endings

I recently had a problem whilst publishing a new node.js module id written that is designed to run jshint recursively against a number of directories and or files.

I develop on windows and so the line endings are dos based (crlf) but the file to run your app as stored in the bin folder needs to have unix line endings (lf) for it to run on a mac or nix systems.

i save code in git and github with unix line endings turned on in the repository but on my working directory the file system is dos line endings. So when i publish using 'npm publish' the file in my bin is published with dos line endings.

this means that when you do an npm install -g on a mac or linux you get the error
env: node\r: No such file or directory

To fix this i developed a little batch script that i use to do the publishing of new versions its really simple and will change the line endings just before publishing.

dos2unix --d2u bin\jshintRunner
npm publish


it uses the built in dos2unix (im running windows 8 ultimate) to change the line endings. I hope this helps someone else out with a similar issue.

Link to the project on github : https://github.com/DamianStanger/jshintRunner and on npm https://npmjs.org/package/jshintrunner