Skip to content

Instantly share code, notes, and snippets.

@commana
Created July 14, 2010 11:53
Show Gist options
  • Save commana/475331 to your computer and use it in GitHub Desktop.
Save commana/475331 to your computer and use it in GitHub Desktop.
eStudy pre commit hooks
#!/usr/bin/php
<?php
define('SVNLOOK', '/usr/bin/svnlook');
// 1 = TXN, 2 = REPO
$command = SVNLOOK." changed -t {$_SERVER['argv'][1]} {$_SERVER['argv'][2]} | awk '{print \$2}' | grep -i \\.php\$";
$handle = popen($command, 'r');
if ($handle === false) {
echo 'ERROR: Could not execute "'.$command.'"'.PHP_EOL.PHP_EOL;
exit(2);
}
$contents = stream_get_contents($handle);
fclose($handle);
$filesWithBOM = array();
// Ausgabe in einzelne Zeilen aufspalten, -1 == no limit
foreach (preg_split('/\v/', $contents, -1, PREG_SPLIT_NO_EMPTY) as $path) {
$command = SVNLOOK." cat -t {$_SERVER['argv'][1]} {$_SERVER['argv'][2]} ".$path." | grep -l \$'\\xEF\\xBB\\xBF'";
system($command, $ret);
if ($ret != 0) $filesWithBOM[] = $path;
}
if (empty($filesWithBOM)) exit(0);
echo "The following files are saved with UTF-8 BOM encoding, which is not allowed:", PHP_EOL;
foreach ($filesWithBOM as $file) {
echo $file, PHP_EOL;
}
exit(1);
#!/usr/bin/php
<?php
define('SVNLOOK', '/usr/bin/svnlook');
// Get list of files in this transaction, but only consider sql files in the 'SQL' folder.
// 1 = TXN, 2 = REPO
$command = SVNLOOK." changed -t {$_SERVER['argv'][1]} {$_SERVER['argv'][2]} | awk '{print \$2}' | grep /SQL/ | grep -i \\.sql\$";
// Wenn der Befehl eben nicht geht, dann SQL-Dateien per Hand raussuchen.
$handle = popen($command, 'r');
if ($handle === false) {
echo 'ERROR: Could not execute "'.$command.'"'.PHP_EOL.PHP_EOL;
exit(2);
}
$contents = stream_get_contents($handle);
fclose($handle);
$neededRollbacks = array();
$neededMigrations = array();
// Ausgabe in einzelne Zeilen aufspalten, -1 == no limit
foreach (preg_split('/\v/', $contents, -1, PREG_SPLIT_NO_EMPTY) as $path) {
$matches = array();
if (preg_match("/migration_([0-9]+)/", $path, $matches)) {
$neededRollbacks[$matches[1]] = $path;
} else if (preg_match("/rollback_([0-9]+)/", $path, $matches)) {
$neededMigrations[$matches[1]] = $path;
}
}
// Wir müssen jetzt vergleichen, ob es zu jeder migration_<num>.sql auch eine rollback_<num>.sql gibt.
$missingMigrations = array_diff_key($neededRollbacks, $neededMigrations);
$missingRollbacks = array_diff_key($neededMigrations, $neededRollbacks);
if (empty($missingMigrations) && empty($missingRollbacks)) {
exit(0);
}
echo "Each migration sql file must have a corresponding rollback sql file and vice versa:", PHP_EOL, PHP_EOL;
foreach ($missingMigrations as $rev => $file) {
echo $file, PHP_EOL;
}
foreach ($missingRollbacks as $rev => $file) {
echo $file, PHP_EOL;
}
echo PHP_EOL;
echo "If you absolutely cannot provide a rollback file, please insert @NO ROLLBACK@ into your commit comment.", PHP_EOL;
echo "This will allow your commit to pass.", PHP_EOL;
echo "See https://wiki.th-mittelhessen.de/index.php/Datenbankmigration for more information.", PHP_EOL;
exit(1);
#!/usr/bin/php
<?php
/**
* A commit hook for SVN.
*
* PHP version 5
*
* @category PHP
* @package PHP_CodeSniffer
* @author Jack Bates <ms419@freezone.co.uk>
* @author Greg Sherwood <gsherwood@squiz.net>
* @copyright 2006 Squiz Pty Ltd (ABN 77 084 670 600)
* @license http://matrix.squiz.net/developer/tools/php_cs/licence BSD Licence
* @version CVS: $Id: phpcs-svn-pre-commit,v 1.5 2009/01/14 02:44:18 squiz Exp $
* @link http://pear.php.net/package/PHP_CodeSniffer
*/
if (is_file(dirname(__FILE__).'/../CodeSniffer/CLI.php') === true) {
include_once dirname(__FILE__).'/../CodeSniffer/CLI.php';
} else {
include_once 'PHP/CodeSniffer/CLI.php';
}
define('PHP_CODESNIFFER_SVNLOOK', '/usr/bin/svnlook');
/**
* A class to process command line options.
*
* @category PHP
* @package PHP_CodeSniffer
* @author Jack Bates <ms419@freezone.co.uk>
* @author Greg Sherwood <gsherwood@squiz.net>
* @copyright 2006 Squiz Pty Ltd (ABN 77 084 670 600)
* @license http://matrix.squiz.net/developer/tools/php_cs/licence BSD Licence
* @version Release: @package_version@
* @link http://pear.php.net/package/PHP_CodeSniffer
*/
class PHP_CodeSniffer_SVN_Hook extends PHP_CodeSniffer_CLI
{
/**
* Get a list of default values for all possible command line arguments.
*
* @return array
*/
public function getDefaults()
{
$defaults = parent::getDefaults();
$defaults['svnArgs'] = array();
return $defaults;
}//end getDefaults()
/**
* Processes an unknown command line argument.
*
* All unkown args are sent to SVN commands.
*
* @param string $arg The command line argument.
* @param int $pos The position of the argument on the command line.
* @param array $values An array of values determined from CLI args.
*
* @return array The updated CLI values.
* @see getCommandLineValues()
*/
public function processUnknownArgument($arg, $pos, $values)
{
$values['svnArgs'][] = $arg;
return $values;
}//end processUnknownArgument()
/**
* Runs PHP_CodeSniffer over files are directories.
*
* @param array $values An array of values determined from CLI args.
*
* @return int The number of error and warning messages shown.
* @see getCommandLineValues()
*/
public function process($values=array())
{
if (empty($values) === true) {
$values = parent::getCommandLineValues();
}
// Get list of files in this transaction.
$command = PHP_CODESNIFFER_SVNLOOK.' changed '.implode(' ', $values['svnArgs']);
$handle = popen($command, 'r');
if ($handle === false) {
echo 'ERROR: Could not execute "'.$command.'"'.PHP_EOL.PHP_EOL;
exit(2);
}
$contents = stream_get_contents($handle);
fclose($handle);
// Do not check deleted paths.
$contents = preg_replace('/^D.*/m', null, $contents);
// Drop the four characters representing the action which precede the path on
// each line.
$contents = preg_replace('/^.{4}/m', null, $contents);
$values['standard'] = $this->validateStandard($values['standard']);
if (PHP_CodeSniffer::isInstalledStandard($values['standard']) === false) {
// They didn't select a valid coding standard, so help them
// out by letting them know which standards are installed.
echo 'ERROR: the "'.$values['standard'].'" coding standard is not installed. ';
$this->printInstalledStandards();
exit(2);
}
$phpcs = new PHP_CodeSniffer($values['verbosity'], $values['tabWidth']);
// Set file extensions if they were specified. Otherwise,
// let PHP_CodeSniffer decide on the defaults.
if (empty($values['extensions']) === false) {
$phpcs->setAllowedFileExtensions($values['extensions']);
}
// Set ignore patterns if they were specified.
if (empty($values['ignored']) === false) {
$phpcs->setIgnorePatterns($values['ignored']);
}
// Initialize PHP_CodeSniffer listeners but don't process any files.
$phpcs->process(array(), $values['standard'], $values['sniffs']);
foreach (preg_split('/\v/', $contents, -1, PREG_SPLIT_NO_EMPTY) as $path) {
// No need to process folders as each changed file is checked.
if (substr($path, -1) === '/') {
continue;
}
// Do not check non-php files
if (substr($path, -4) !== ".php") {
continue;
}
// Get the contents of each file, as it would be after this transaction.
$command = PHP_CODESNIFFER_SVNLOOK.' cat '.implode(' ', $values['svnArgs']).' '.$path;
$handle = popen($command, 'r');
if ($handle === false) {
echo 'ERROR: Could not execute "'.$command.'"'.PHP_EOL.PHP_EOL;
exit(2);
}
$contents = stream_get_contents($handle);
fclose($handle);
$phpcs->processFile($path, $contents);
}//end foreach
return parent::printErrorReport(
$phpcs,
$values['reports'],
$values['showSources'],
$values['reportFile'],
$values['reportWidth']
);
}//end process()
/**
* Prints out the usage information for this script.
*
* @return void
*/
public function printUsage()
{
parent::printUsage();
echo PHP_EOL;
echo ' Each additional argument is passed to the `svnlook changed ...`'.PHP_EOL;
echo ' and `svnlook cat ...` commands. The report is printed on standard output,'.PHP_EOL;
echo ' however Subversion displays only standard error to the user, so in a'.PHP_EOL;
echo ' pre-commit hook, this script should be invoked as follows:'.PHP_EOL;
echo PHP_EOL;
echo ' '.basename($_SERVER['argv'][0]).' ... "$REPOS" -t "$TXN" >&2 || exit 1'.PHP_EOL;
}//end printUsage()
}//end class
$phpcs = new PHP_CodeSniffer_SVN_Hook();
$phpcs->checkRequirements();
$numErrors = $phpcs->process();
if ($numErrors !== 0) {
exit(1);
}
?>
#!/bin/sh
# PRE-COMMIT HOOK
#
# The pre-commit hook is invoked before a Subversion txn is
# committed. Subversion runs this hook by invoking a program
# (script, executable, binary, etc.) named 'pre-commit' (for which
# this file is a template), with the following ordered arguments:
#
# [1] REPOS-PATH (the path to this repository)
# [2] TXN-NAME (the name of the txn about to be committed)
#
# The default working directory for the invocation is undefined, so
# the program should set one explicitly if it cares.
#
# If the hook program exits with success, the txn is committed; but
# if it exits with failure (non-zero), the txn is aborted, no commit
# takes place, and STDERR is returned to the client. The hook
# program can use the 'svnlook' utility to help it examine the txn.
#
# On a Unix system, the normal procedure is to have 'pre-commit'
# invoke other programs to do the real work, though it may do the
# work itself too.
#
# *** NOTE: THE HOOK PROGRAM MUST NOT MODIFY THE TXN, EXCEPT ***
# *** FOR REVISION PROPERTIES (like svn:log or svn:author). ***
#
# This is why we recommend using the read-only 'svnlook' utility.
# In the future, Subversion may enforce the rule that pre-commit
# hooks should not modify the versioned data in txns, or else come
# up with a mechanism to make it safe to do so (by informing the
# committing client of the changes). However, right now neither
# mechanism is implemented, so hook writers just have to be careful.
#
# Note that 'pre-commit' must be executable by the user(s) who will
# invoke it (typically the user httpd runs as), and that user must
# have filesystem-level permission to access the repository.
#
# On a Windows system, you should name the hook program
# 'pre-commit.bat' or 'pre-commit.exe',
# but the basic idea is the same.
#
# The hook program typically does not inherit the environment of
# its parent process. For example, a common problem is for the
# PATH environment variable to not be set to its usual value, so
# that subprograms fail to launch unless invoked via absolute path.
# If you're having unexpected problems with a hook program, the
# culprit may be unusual (or missing) environment variables.
#
# Here is an example hook script, for a Unix /bin/sh interpreter.
# For more examples and pre-written hooks, see those in
# the Subversion repository at
# http://svn.collab.net/repos/svn/trunk/tools/hook-scripts/ and
# http://svn.collab.net/repos/svn/trunk/contrib/hook-scripts/
REPOS="$1"
TXN="$2"
# Make sure that the log message contains some text.
SVNLOOK=/usr/bin/svnlook
$SVNLOOK log -t "$TXN" "$REPOS" | grep "[a-zA-Z0-9]" > /dev/null || exit 1
# Check that a migration file has corresponding rollback file.
# This check can be overridden with magic words.
$SVNLOOK log -t "$TXN" "$REPOS" | grep "@NO ROLLBACK@" > /dev/null
if [ $? -eq 1 ]
then
/usr/share/subversion/hook-scripts/migration-check.php "$TXN" "$REPOS" >&2 || exit 1
fi
# Check if file uses UTF-8 byte order mark and abort commit if BOM is present
/usr/share/subversion/hook-scripts/bom-check.php "$TXN" "$REPOS" >&2 || exit 1
#echo "Sorry, gerade kann man nicht committen. :o" 1>&2
#exit 1
# Check that the author of this commit has the rights to perform
# the commit on the files and directories being modified.
#/usr/share/subversion/hook-scripts/commit-access-control.pl "$REPOS" "$TXN" "$REPOS"/commit-access-control.cfg || exit 1
PHP="/usr/bin/php"
AWK="/usr/bin/awk"
GREP="/bin/egrep"
SED="/bin/sed"
CHANGED=`$SVNLOOK changed -t "$TXN" "$REPOS" | $AWK '{print $2}' | $GREP \\.php$`
for FILE in $CHANGED
do
MESSAGE=`$SVNLOOK cat -t "$TXN" "$REPOS" "$FILE" | $PHP -l`
if [ $? -ne 0 ]
then
echo 1>&2
echo "***********************************" 1>&2
echo "PHP error in: $FILE:" 1>&2
echo `echo "$MESSAGE" | $SED "s| -| $FILE|g"` 1>&2
echo "***********************************" 1>&2
exit 1
fi
done
# --ignore=\.txt$,\.TXT$,\.jpg$,\.JPG$,\.js$,\.css$,\.html$,\.mkf$,\.phar$,\.sql$,\.ttf$,\.png&,\.phtml$,\.gif$,\.GIF$,\.svg$,\.SVG$,\.xml$,\.dtd$,\.db$,\.xsd$
/usr/share/php/PHP/scripts/phpcs-svn-pre-commit --ignore=web/common/classes/jpgraph,web/common/classes/geshi,web/common/classes/tcpdf,web/xpweb/lib,web/phpids/classes/phpids_lib -t "$TXN" "$REPOS" >&2 || exit 1
# All checks passed, so allow the commit.
exit 0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment