You are here

function _drush_coder_write_file in Coder 7.2

Helper function to write a file with error checking.

1 call to _drush_coder_write_file()
_drush_coder_review_git in coder_review/coder_review.drush.inc
Install coder as a git pre-commit hook.

File

coder_review/coder_review.drush.inc, line 195
Command line utility support for Coder_review module.

Code

function _drush_coder_write_file($file, $contents, $perms = 0644, $uninstall = FALSE) {
  $contents .= "\n";
  $args = array(
    '@file' => $file,
  );
  if (file_exists($file)) {
    $existing = file_get_contents($file);
    if ($existing == $contents) {
      if ($uninstall) {
        drush_print(dt('removing @file', $args));
        return unlink($file);
      }
      if ($perms && (fileperms($file) & 0777) != $perms) {
        drush_print(dt('correcting permissions @file', $args));
        chmod($file, $perms);
      }
      else {
        drush_print(dt('ignore @file, already up to date.', $args));
      }
      return 1;
    }

    // Only print the question when not using --yes.
    if (!drush_get_context('DRUSH_AFFIRMATIVE')) {
      if (!drush_confirm(dt($uninstall ? 'remove @file possibly from another source' : 'overwrite @file with new contents', $args))) {
        return drush_error(dt('user aborted'));
      }
    }

    // Remove existing files.
    if ($uninstall) {
      drush_print(dt('removing @file', $args));
      return unlink($file);
    }
  }
  elseif ($uninstall) {
    return 1;
  }
  if (file_put_contents($file, $contents)) {
    if ($perms) {
      chmod($file, $perms);
    }
    drush_print(dt('writing @file', $args));
    return 1;
  }
  return drush_error(dt('error writing @file', $args));
}