Hemanth.HM

A Computer Polyglot, CLI + WEB ♥'r.

Method Deprecated Warning in Nodejs

| Comments

Recently was tweaking a node module and had to warn users on deprecated methods, truns out it's damn easy with util module.

Pinch of code :

1
2
3
4
5
6
7
8
9
10
11
12
#!/usr/bin/env node
#__filename = hello.js

util=require('util');

exports.yo = function(){
    console.log("yo yo!");
};

exports.hello = util.deprecate(function() {
  return exports.yo();
}, '`hello` is depreciated, please use `yo` instead.');

Let's import hello.js and try invoking hello :

1
2
3
4
5
> greet = require("hello");
{ yo: [Function], hello: [Function: deprecated] }
> greet.hello()
`hello` is depreciated, please use `yo` instead.
yo yo!

Happy hacking!

Auto Syncing a Forked Git Repository With the Parent

| Comments

Syncing my forked repositories is the most common task I do! So wanted to automate it.

The bash script below helps me with syncing my forked code from github, without me worrying about the parent git url!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#!/usr/bin/env bash
# Author : Hemanth.HM 
# License : MIT
# Some JSON parsing logic from http://l-o-n-g.livejournal.com/146422.html

# Get the current repo URL
url=$(git config --get remote.origin.url)

# Get the user and repo part from the URL 
# Must be something like part=${url#*//*/}
# Sticking to github specific code as of now.

part=${url#*github.com*/}

# ZOMG parse JSON using the github api get the parent git_url.
# would suggest to use curl -s .. | jq -r '.parent.git_url'  
upstream=$(curl -s https://api.github.com/repos/${part%.git} | sed -e 's/[{}]/''/g' | awk -v k="text" '{n=split($0,a,","); for (i=1; i<=n; i++) print a[i]}' | grep '"git_url":' | sed 's/:/ /1' | awk -F" " '{ print $2 }' | uniq | tail -1)

# Rest of it...
git remote add upstream $upstream
git checkout master
git pull --rebase
git push origin master

Usage :

1
2
curl https://raw.github.com/hemanth/futhark/6cdbe8f14b9f1b12498a22473d398ee197327051/syncfork.bash > /usr/bin/sf
chmod a+x /usr/bin/sf

In any github git repo you want to sync, just run sf to sync your fork with the parent.

Hope this helps you, happy hacking! :)

Octopress Socialink Plugin

| Comments

I normally make a lot of refernce to lots of friends on social networks while blogging and was getting bored of adding hrefs for each reference, so made the socialink-plugin for octopress.

Installation

Place the socialink.rb in the porject link to your ~/octopress/plugin/ dir.

Usage

1
{% sl social handle %}
  • social can be any of : gh, fb, gp, tw, in, fl. [github, facebook, googleplus, twitter, linkdin, flickr respectivly]

Examples:

Input:

1
2
{% sl gh hemanth %}
gnumanth

Output:

1
2
<a href='https://github.com/hemanth'>hemanth</a>
<a href='https://twitter.com/gnumanth'>gnumanth</a>

Hope this is useful!

Sublime Text Build System Errno 2

| Comments

While working on yeoman-sublime-plugin I faced an issue with the build system :

issue

[Errno 2] No such file or directory for the same reason setpath was devised.

But later on a simpler method was suggest by @kevvayo :

1
2
3
4
5
{
    "working_dir": "${project_path:${folder}}",
    "path": "$HOME/bin:/usr/local/bin:$PATH",
    "cmd": ["sh","-c","npm install && bower install"]
}

The trick was all about starting the shell :-)

Auto Require Ruby Gems

| Comments

If you have coded some ruby you would have seen the LoadError : 'require': no such file to load -- rubygems (LoadError) in case of the required gem is missing (not installed) or the gem path is screwed up!

Here is a simple silly old trick :

1
2
3
4
5
6
7
8
alias old_require require
def load_gem(gem)
  old_require gem
  rescue LoadError => e
    print "'#{gem}' can't be found, trying to install it..."
    system("gem install  #{gem} --no-ri --no-rdoc") ;
    Gem.clear_paths() && require(gem) && puts("loading '#{gem}' ok!")
end

Using it :

1
2
3
4
5
6
7
8
1.9.2-p320 :020 > require 'xkcd'
'xkcd' can't be found, trying to install it..
Fetching: xkcd-1.0.1.gem (100%)
Successfully installed xkcd-1.0.1
Fetching: mini_portile-0.5.1.gem (100%)
Successfully installed mini_portile-0.5.1
2 gems installed
 => nil

Well something like Bundler must be used at any case! This is just some undocumented old code.

JSbin Octopress Plugin Test

| Comments

It was fun tweetcoding with @jsbin [ aka @rem ;) ]. This is a simple octopress jsbin plugin that helps to partial embed jsbins.

It all begin with :

And after two PRs it was all ready :-) The below is a simple embed :

JS Bin

Do checkout the plugin and contribute! Thanks to Remy Sharp.

HTTP Status Code as a Service

| Comments

There are few HTTP status serivce apps, /me pawed a bit with node to do the same. Do try HSCO.

The code is plain and simple :

1
2
3
4
5
6
7
8
var http = require('http');
var url = require("url");
http.createServer(function (req, res) {
  res.writeHead(200, {'Content-Type': 'text/plain'});
  var url_parts = url.parse(req.url, true);
  var status = url_parts.pathname.replace(/^\/([^\/]*).*$/, '$1');
  res.end(http.STATUS_CODES[status] || "Undefined status : "+ status || "Try /404");
}).listen(process.env.PORT || 5000);

Well, this can be improved futher...this is just the first cut.

Grunt Test Before Git Comit

| Comments

Avoid rewriting history with rebase or roll back and re-commit and use the below in your git/hooks/pre-commit

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#!/bin/bash

curBranch=$(git rev-parse --abbrev-ref HEAD)

# Ignore rebase, stash unstaged.
[[ $curBranch != '(no branch)' ]] &&
git stash -q --keep-index &&
grunt test

# Check the exit status of grunt.
[[ $? -ne 0 ]] &&
echo "Test failed, can't commit" &&
exit 1

# All is well, stage and restore stash.
git add .
git stash pop -q

In the Gruntfile.js (As of now I'm using mocha, so..)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
module.exports = function(grunt) {

  // Add the grunt-mocha-test tasks.
  grunt.loadNpmTasks('grunt-mocha-test');

  grunt.initConfig({
    // Configure a mochaTest task
    mochaTest: {
      test: {
        options: {
          reporter: 'spec'
        },
        src: ['test/**/*.js']
      }
    }
  });

  grunt.registerTask('test', 'mochaTest');

};

Well ofcourse, this can be imporved for release tasks as well :-)

Grunt Tweet Git Commit

| Comments

This is one of those fun time CLI hacks, it helps you to automatically tweet about every git commits that happen in the current repo.

I shall not say much about grunt.js or git hooks in the post, but rather will let the code do the talking.

Prereq :

1
2
npm install ntwitter
npm install -g grunt-cli

Keys listed below can be obtained from dev.twitter.com after setting up a new App

Custom grunt tweet task :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
grunt.registerTask('tweet', 'Tweet the commit info', function () {
     var twitter = require('twitter');
     var shell = require('shelljs');
     var commit_comment = shell.exec('git log -1 --pretty=%B').output.replace(/(\r\n|\n|\r)/gm,'');
     var repo = shell.exec(' basename $(git remote show -n origin | grep Fetch | cut -d: -f2-)').output.replace(/(\r\n|\n|\r)/gm,'');
     var author = shell.exec("git --no-pager show -s --format='%an'").output.replace(/(\r\n|\n|\r)/gm,'');
     var tweet = util.format('%s on %s by %s ', commit_comment, repo, author);

    var twit = new twitter({
      consumer_key: 'Twitter',
      consumer_secret: 'API',
      access_token_key: 'keys',
      access_token_secret: 'go here'
    });

    twit
      .verifyCredentials(function (err, data) {
          console.log(data);
      })
      .updateStatus(tweet,
           function (err, data) {
                  console.log(data);
       });

  });

Have a pre-commit hooks at .git/hooks/pre-commit as grunt tweet would tweet on every commit!

The tweet would be something like : 'jshint suggestions from @passy on yo.git by Hemanth.HM'