Category: Git


Git tree view in CLI

Easy. Create an alias:

git config --global alias.tree "log --graph --pretty=format:'%Cred%h%Creset -%C(yellow)%d%Creset %s %Cgreen(%cr) %C(bold blue)<%an>%Creset%n' --abbrev-commit --date=relative —branches”

then just run

git tree

Screen Shot 2016-02-09 at 15.49.21

Updating a forked GitHub Repo

At the PHPNW 2014 conference, they had a ‘Hackathon’, where everyone got together and started hacking away at projects. I had a shot at the JoindIn website.

Anyway, I forked the repositories so I could work on my own branch. Now though, my fork is outdated, and needs updating. So in order to remedy this, we add another remote.

From your local machine’s cloned repo, you simply say:

git remote add upstream https://github.com/joindin/joindin-web2.git
git checkout master
git pull upstream master
git push origin master

Thanks to Derick Rethans of XDebug fame for this info 😀

Learn all the Git features

Ok, so maybe you can commit, push, pull, branch, and maybe have even set up some post-hookery! But Git has lots more I haven’t even touched yet!

This looks really nice, so I thought I’d share it with you all! Check it out!

http://pcottle.github.io/learnGitBranching/

Fixing Git Submodule Issues

If you’ve set up a Git ‘Push to Deploy’ setup for your site based on my earlier post, you may or may not have run into some anomalous behaviour! Namely, when you run git submodule init, you get a message similar to this:

No submodule mapping found in .gitmodules for path 'js/jquery-browser-fingerprint'

Or even :

fatal: reference is not a tree: 48d1407779fb1e8dc6d3c6c6fb87df4c1cbc65ed
Unable to checkout '48d1407779fb1e8dc6d3c6c6fb87df4c1cbc65ed' in submodule path 'cms/js/flipswitch'

Thankfully, these issues are easily fixed. modules should be listed in a file in your root .gitmodules, and look like this:

[submodule "jquery-browser-fingerprint"]
 path = /js/jquery-browser-fingerprint
 url = git://github.com/carlo/jquery-browser-fingerprint.git

Listing your submodules in here will fix your first problem. The second issue is caused by referencing a commit that hasn’t been pushed! Did you copy project files from somewhere else? Try pushing the commit from your other project.

A clearer way to sort these issues however, is to clear whatever cache git has for those submodules. Typing this clears it.

git rm --cached js/jquery-browser-fingerprint

This should allow you to run git submodule init, and git submodule update. One last point. You don’t remember ever having to create this .gitmodules file before, so why now? Basically it allows you to set custom folders etc for the submodule. If you’re happy with the defaults, you should theoretically be able to skip the submodules file, and  can combine both git commands into this:

git submodule update --init

This updates everything and initialises in one! So to sum up, try removing the cached stuff in git, then run the combined update init file! Happy pushing, pulling, and deploying!

Using Git Push to Deploy your websites

If you’re STILL using some sort of FTP to deploy your website, you are falling behind! FTP sucks for a variety of reasons. My Favourite FTP client? I dobn’t have one! Dreamweavers file manager/ftp client was quite good, but thats the only thing I used dreamweaver for, the Sync site button. And even that left horrible _notes folders lying around everywhere. The one thing I liked was the cloak file ability, so only certain files/folders were uploaded. But Dreamweaver is sh*t. And will forget what it had previously done. So using Filezilla and manually uploading the things you wanted was your only option. And the setting ftp rules thing was more hassle than its worth. So it’s time to move on.

If your project isn’t big enough to be requiring Continuous Integration software from the likes of Jenkins, then a Git ‘push to deploy’ setup might be exactly what you are looking for. Make changes, commit, and push, which sets off the deployment process using a git hook, which is nothing more fancy than a bash script. So lets get started! I assume you have a live server with SSH access, and a development server which you will be working on.

SSH into your live server as root (or sudo su once logged in). We will be creating a user group for every user that will be pushing should be added to, and creating a folder for keeping your repositories in.

groupadd geeks
usermod -a -G geeks myusername
usermod -a -G geeks otherusernameetc
mkdir /var/git
chmod 775 /var/git
chgrp geeks /var/git

Now exit from being root and be logged in as whatever your normal ssh username is. We will be initialising a Git repository in the sites document root.

cd /home/myusername/www
git init
git add .
git commit -a

Now we will create a bare repository which will be the origin. This is what our dev copies will push to, which will set off a hook deploying to the web doc root. Once we create it, we’ll push whatever is in the sites doc folder already to it.

cd /var/git
mkdir yourprojectname.git
cd yourprojectname.git
git init --bare
cd /home/myusername/www/
git push /var/git/yourproject.git master

Now we add the live’s ‘origin’ repository as a remote for the live. Edit /home/myusername/www/.git/config, add add the following:

[remote "origin"]
    url = /var/git/yourprojectname.git 
    fetch = +refs/heads/*:refs/remotes/origin/*

Great. Now all that’s required is to set up what we call a ‘Git Hook’, a bash script which will trigger when we push to the master repository.
Edit /var/git/myproject.git/hooks/post-update :

echo
echo "*********************************"
echo "*** Deploying Website LIVE ***"
echo "*********************************"
echo
cd /home/myusername/www || exit
unset GIT_DIR
git pull origin master
git submodule init
git submodule update
exec git update-server-info

Save the file, and edit its permissions to make it an executable:

chmod +x /var/git/yourprojectname.git/hooks/post-update

You’re all set! The last stage is to clone your repository to your testing server, so, on your testing server:

cd ~/Sites
git clone myusername@myliveserverIP:/var/git/yourprojectname.git yourprojectname

And Bob is indeed your uncle! Test it out! If you have an index page (be it PHP or HTML, whatever) :

nano index.php
    <h1>My Groovy new Website</h1>
git add .
git commit -a
git push origin master

Now go check your live site! You should see your changes reflected on your production server 🙂 Have fun people!

Setup Github and Packagist on Mac

Well, I think I’m going to try making an open source zf2 module, to see if I can 🙂
Essentially a basic static page module for sorting out all your boring non-dynamic pages! (about us, privacy policy, terms and conditions, that kind of thing!)

Okay, so first up you need a github account. Github is free so long as any code you put up there is open source. Activate your account and create a repository. In my case it was https://github.com/delboy1978uk/static-content.

Now you need to set up git. The instructions on the website didn’t quite work and I had to IRC some guys at #github to get pointed in the right direction. But for the most part it worked, so follow these instructions: https://help.github.com/articles/set-up-git

Next thing we clone the repository to your machine. go to whichever folder you want to keep your work in, and type the equivalent of this:

git clone git://github.com/delboy1978uk/static-content static-content
cd static-content

And we’re in our project. In order to use composer with our repository, we need a packagist account, so sign up at https://packagist.org. And we create a composer.json file :

{
    "name": "delboy1978uk/static-content",
    "description": "Module for serving up static pages",
    "type": "library",
    "keywords": [
        "zf2",
        "static",
        "content"
    ],
    "homepage": "https://github.com/delboy1978uk/static-content",
    "authors": [
    {
        "name": "Derek Stephen McLean",
        "email": "delboy1978uk@gmail.com"
    }
    ],
    "require":
    {
        "php": ">=5.3.3",
        "zendframework/zendframework": "2.*"
    },
    "autoload": 
    {
        "psr-0": 
        {
            "StaticContent": "src/"
        },
        "classmap": [
            "./"
        ]
    }
}
So we add that file, and commit, and push.
git add .
git commit -a
git push origin master
If you get some error about cannot push, (I did, it said: You can’t push to git://github.com/delboy1978uk/static-content.git) then you need to go to your github page. You will see a text box with an https:// address. Copy the address, and then edit your .git/config replacing the git:// one with the https:// one you just copied. Then try pushing again, and it should work.
Go to your packagist account, and paste the repo address in there (click submit package). Once it’s been added you’ll see it doesn’t auto update. Click on your user name at the top right, it will take you to a page with an API key. Copy this key and go back to your github repo, and click admin at the top right. On the following page, click service hooks in the left hand side column. Enter http://packagist.org as the host, your packagist user name, and the pi token you copied. Once thats done, packagist will now update when you push to github.
Okay, so now to test!
Go into one of your projects that use composer (in my case a Zend Framework 2 Application), and in the composer.json add the following (or similar) in the require part:
"delboy1978uk/static-content": "dev-master"
Finally, type in
php composer.phar update
And lo and behold, my package is auto installed into our application!! Awesome! Now I just need to make this package worth adding in the first place lol!
Have fun!

ZF2 is totally redefining PHP development, I love the direction they are going! Anyway, those who have shown interest will no doubt have played with Akrabats tutorial on the zf2 site. I for one have, and I also went and met the guys themselves at the PHPNW2012 Conference in Manchester at the start of this month! The ZF2 tutorial day was great! Thanks Evan & Rob! Anyway, i’m straying off topic here.

It’s all about the modules! Most sites have a login! A blog! A contact form! Facebook? Twitter? Whatever! Why reinvent the wheel? http://modules.zendframework.com allows you to choose from a growing number of modules, and installing them is a piece of cake (i should stop saying that, this is zend!) using the PHP Composer. So let’s have a look!

Completely starting from scratch, bung this in your Apache’s VirtualHosts config, tweaking the path to wherever your site is:

<VirtualHost *:80>
 ServerName zf2
 DocumentRoot /path/to/my-site/public/
 SetEnv APPLICATION_ENV "development" 
 <Directory /path/to/my-site/public/>
 DirectoryIndex index.php
 AllowOverride All
 Order allow,deny
 Allow from all
 </Directory>
</VirtualHost>

Now you’ve done that, time to install the Zend Framework Skeleton Application, by cloning it from the Git repository. Go into your sites folder, and say:

git clone git:/github.com/zendframework/ZendSkeletonApplication.git my-site
cd my-site
ls

You’ll notice a composer.json in there. Open this up, and you’ll see it depends on PHP and zendframework. In the command prompt:

php composer.phar self-update

This updates composer to the latest version, since it has updated its version since the SkeletonApplication was released. Then:

php composer.phar install

Composer kicks in, and downloads our dependency (zf2), after having made sure you have a sufficient version of PHP (>=5.3).

What’s this? ZF2 recommends installing more modules? Fine, lets do that, but first, lets choose even more modules to add! Change your composer.json to look like this:

{
 "name": "zendframework/skeleton-application",
 "description": "Skeleton Application for ZF2",
 "license": "BSD-3-Clause",
 "keywords": [
 "framework",
 "zf2"
 ],
 "homepage": "http://framework.zend.com/",
 "minimum-stability": "alpha",
 "repositories":[
{
 "type": "composer",
 "url": "http://packages.zendframework.com/"
 }],
 "require": {
 "php": ">=5.3.3",
 "zendframework/zendframework": "2.*",
 "doctrine/doctrine-orm-module": "dev-master",
 "doctrine/doctrine-module": "dev-master",
 "zendframework/zendpdf": "2.*",
 "zendframework/zendservice-recaptcha": "2.*",
 "symfony/yaml": "dev-master",
 "zendframework/zend-developer-tools": "dev-master"
 }
}

I’ve deliberately left two of ZF2s recommendations out of this, as they’re actually pecl extensions, not models, and I ain’t covering that just now, but I added Doctrine functionality. So, to get all this new stuff, we tell Composer to go update itself!

php composer.phar update

And bang, we now have the modules downloaded into the vendor folder. So! How to use them, I hear you cry? Well, the example I’ll show you is probably the best example to start with, and indeed, was the module we were shown at Evan & Rob’s ZF2 Tutorial day at PHPNW2012! ZfcUser.

Goto http://modules.zendframework.com
Scroll down to ZfcUser (formerly EdpUser) (that’s Evan btw) and click, which will take you to the github page.
Scroll down to Requirements. You’ll see you also need ZF2 and ZfcBase to use this module. We have ZF2, but not the ZFCommons base use Classes, so we’ll install both of these. Again, a simple case of adding the lines, then running php composer.phar update. Watch out for unnecessary tabs, brackets, and commas, or the json parser will take a fit!

"zf-commons/zfc-base": "dev-master",
 "zf-commons/zfc-user": "dev-master"

Great! All running smoothly I see! So jump in the ZfcUser module in the vendor folder and go into data, there you’ll get the sql for creating your user table. Run that on your MySQL in your database server, and you’re ready to rock! Now we just need to enable the modules (I’ll only show the relevent ones for the example, so I won’t be using the Doctrine stuff for now) and set up our db connection.

Stick your DB parameters in the config autoload local php file:

return array(
 'db' => array(
 'username' => 'user',
 'password' => 'pass',
 ),
);

and in the global file, we’ll put the meat and bones (the local php file is in .gitignore, which is why we keep the credentials there):

return array(
 'db' => array(
 'driver' => 'Pdo',
 'dsn' => 'mysql:dbname=my-site-db-here;host=localhost',
 'driver_options' => array(
 PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES \'UTF8\''
 ),
 ),
 'service_manager' => array(
 'factories' => array(
 'Zend\Db\Adapter\Adapter'
 => 'Zend\Db\Adapter\AdapterServiceFactory',
 ),
 ),
);

Now if you open the application config you’ll see an array called modules, where we register the modules our application uses. Change it to this:

'modules' => array(
        'Application',
'ZfcBase', 
'ZfcUser'
    ),

And that’s literally it! try browsing to /user/login! register and login! with Gravatars and everything!

The really great thing about all of these modules is that they are extensible. Is something not happening in a module quite the way you would like it? Write a module extending it!
For instance, my first thought about ZfcUser was ‘what about activating your account by email when you register? Well, guess what? There’s a module for that. Evan told me to go check out CdliTwoStageSignup! (extending ZfcUser)

Working in this manner really is getting to the stage where functionality is literally drag, drop, ‘n’ tell your app! And by studying a module’s code, especially a module extending another module, we can start to see how it all connects up through the service and event managers, and how it’s all tied together! But that’s for you to mess around with! Have fun!

Default editor for Git

Just created a new site, and went to perform my initial commit to my Git repository, and yuk! Vi, or Vim, appeared! :-s Don’t get me wrong, Vi/Vim is powerful and can do all sorts, but I like Nano, or Pico! Last time this happened I type in a command to change the editor, but what I forgot to add was to make it the GLOBAL  default. A slight tweak, and the command looks like this. No more Vi! Awesome 🙂

git config --global core.editor "nano"