Skip to content
This repository has been archived by the owner on Dec 1, 2024. It is now read-only.

Commit

Permalink
Don't attempt to migrate files that aren't hack
Browse files Browse the repository at this point in the history
fixes #9
  • Loading branch information
fredemmott committed Sep 29, 2017
1 parent 0f0acfe commit 0af658b
Showing 1 changed file with 65 additions and 2 deletions.
67 changes: 65 additions & 2 deletions src/__Private/MigrationCLI.php
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,12 @@
class MigrationCLI extends CLIWithRequiredArguments {
use CLIWithVerbosityTrait;

const VERBOSE_SKIP_BECAUSE_GIT = 2;
const VERBOSE_SKIP_BECAUSE_NOT_HACK = 1;
const VERBOSE_SKIP_BECAUSE_VENDOR = 1;
const VERBOSE_MIGRATE = 2;
const VERBOSE_MIGRATE_NOT_HACK = 1;

protected keyset<classname<BaseMigration>> $migrations = keyset[];
private bool $includeVendor = false;

Expand Down Expand Up @@ -63,7 +69,18 @@ protected function getSupportedOptions(): vec<CLIOptions\CLIOption> {
final private function migrateFile(
string $file,
): void {
$this->verbosePrintf(2, "Migrating file %s...\n", $file);
$this->verbosePrintf(
self::VERBOSE_MIGRATE,
"Migrating file %s...\n",
$file,
);
if (!self::isHackFile($file)) {
$this->verbosePrintf(
self::VERBOSE_MIGRATE_NOT_HACK,
"Migrating file %s despite it not looking like a Hack file\n",
$file,
);
}
$ast = ast_from_file($file);
foreach ($this->migrations as $migration) {
$ast = (new $migration())->migrateAst($ast);
Expand All @@ -81,14 +98,30 @@ final private function migrateDirectory(string $directory): void {
}
$file = $info->getPathname();
if (!$this->includeVendor) {
if (Str\contains($file, '/.git/')) {
$this->verbosePrintf(
self::VERBOSE_SKIP_BECAUSE_GIT,
"Skipping file '%s' because it is in .git/\n",
$file,
);
continue;
}
if (Str\contains($file, '/vendor/')) {
$this->verbosePrintf(
1,
self::VERBOSE_SKIP_BECAUSE_VENDOR,
"Skipping file '%s' because it is in vendor/\n",
$file,
);
continue;
}
if (!self::isHackFile($file)) {
$this->verbosePrintf(
self::VERBOSE_SKIP_BECAUSE_NOT_HACK,
"Skipping file '%s' because it is not a Hack file\n",
$file,
);
continue;
}
}
$this->migrateFile($file);
}
Expand Down Expand Up @@ -123,4 +156,34 @@ final private function migrateDirectory(string $directory): void {
}
return 0;
}

private static function isHackFile(string $file): bool {
static $cache = null;
if ($cache !== null) {
list($cache_file, $cache_result) = $cache;
if ($cache_file === $file) {
return $cache_result;
}
}

$f = fopen($file, 'r');
$prefix = fread($f, 4);
if ($prefix === '<?hh') {
$cache = tuple($file, true);
return true;
}

if (!Str\starts_with($prefix, '#!')) {
$cache = tuple($file, false);
return false;
}
rewind($f);
$_shebang = fgets($f);
$prefix = fread($f, 4);

$is_hh = $prefix === '<?hh';

$cache = tuple($file, $is_hh);
return $is_hh;
}
}

0 comments on commit 0af658b

Please sign in to comment.