Tuesday, July 12, 2016

Escape JSON string

std::string EscapeJson(const char* text)
{
    std::string string;
    
    int length = strlen(text);
    for (int i = 0; i < length; i++)
    {
        switch (text[i])
        {
            case '\\':
                string.append("\\\\");
                break;
            case '"':
                string.append("\\\"");
                break;
            case '/':
                string.append("\\/");
                break;
            case '\b':
                string.append("\\b");
                break;
            case '\f':
                string.append("\\f");
                break;
            case '\n':
                string.append("\\n");
                break;
            case '\r':
                string.append("\\r");
                break;
            case '\t':
                string.append("\\t");
                break;
            default:
                char c = text[i];
                string.append(1, c < 32 ? '?' : c);
                break;
        }
    }

    return string;
}

Thursday, June 30, 2016

Rename Git user in pushed commits

#!/bin/sh

git filter-branch --env-filter '
OLD_EMAIL="wrong@gmail.com"
CORRECT_NAME="vurdalakov"
CORRECT_EMAIL="vurdalakov@gmail.com"
if [ "$GIT_COMMITTER_EMAIL" = "$OLD_EMAIL" ]
then
    export GIT_COMMITTER_NAME="$CORRECT_NAME"
    export GIT_COMMITTER_EMAIL="$CORRECT_EMAIL"
fi
if [ "$GIT_AUTHOR_EMAIL" = "$OLD_EMAIL" ]
then
    export GIT_AUTHOR_NAME="$CORRECT_NAME"
    export GIT_AUTHOR_EMAIL="$CORRECT_EMAIL"
fi
' --tag-name-filter cat -- --branches --tags

Monday, June 27, 2016

Trim function for std::string

std::string stdtrim(std::string& str)
{
    size_t first = str.find_first_not_of(' ');
    size_t last = str.find_last_not_of(' ');
    return (std::string::npos == first) || (std::string::npos == last) ? "" : str.substr(first, (last - first + 1));
}

Wednesday, June 22, 2016

Detect 64- and 32-bit Windows in a batch file

@echo off

set bitness=64
if /I %PROCESSOR_ARCHITECTURE% == x86 (
    if not defined PROCESSOR_ARCHITEW6432 (
        set bitness=32
    )
)

echo Operating System is %bitness% bit

if %bitness% == 32 (
    echo Operating System is 32 bit
) else (
    echo Operating System is 64 bit
)

Tuesday, June 21, 2016

Batch file to clone/pull all GitHub repositories for a given user

@echo off
@setlocal enableextensions enabledelayedexpansion

set gituser=vurdalakov

set curl=curl.exe
set git=git.exe

for /f "delims=" %%a in ('%curl% -i -s https://api.github.com/users/%gituser%/repos') do (
        set line=%%a
        if not !line!==!line:"name"=! (
            set line=!line:"=!
            set line=!line:name:=!
            set line=!line:,=!
            set name=!line: =!
            if exist !name!\nul (
                cd !name!
                %git% pull
                cd ..
            ) else (
                %git% clone https://github.com/%gituser%/!name!.git
            )
        )
    )
)