-
-
Notifications
You must be signed in to change notification settings - Fork 73
/
Copy pathcreate_hard_link.php
62 lines (53 loc) · 1.82 KB
/
create_hard_link.php
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
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
<?php
declare(strict_types=1);
namespace Psl\Filesystem;
use Psl\Internal;
use Psl\Str;
use function link;
/**
* Create a hard link for $source.
*
* @param non-empty-string $source The file to create a hard link for.
* @param non-empty-string $destination
*
* @throws Exception\RuntimeException If unable to create the hard link.
* @throws Exception\NotFoundException If $source does not exist.
* @throws Exception\NotFileException If $source is not a file.
* @throws Exception\NotReadableException If $destination is a non-empty directory, and is non-readable {@see delete_directory()}.
*
* @mago-expect best-practices/no-boolean-literal-comparison
* @mago-expect best-practices/no-else-clause
*/
function create_hard_link(string $source, string $destination): void
{
if (!namespace\exists($source)) {
throw Exception\NotFoundException::forFile($source);
}
if (!namespace\is_file($source)) {
throw Exception\NotFileException::for($source);
}
if (namespace\exists($destination)) {
if (namespace\get_inode($destination) === namespace\get_inode($source)) {
// already exists.
return;
}
try {
namespace\delete_directory($destination, true);
} catch (Exception\NotDirectoryException) {
namespace\delete_file($destination);
}
} else {
namespace\create_directory_for_file($destination);
}
[$result, $error_message] = Internal\box(static fn(): bool => link($source, $destination));
// @codeCoverageIgnoreStart
if (false === $result) {
throw new Exception\RuntimeException(Str\format(
'Failed to create hard link "%s" from "%s": %s.',
$destination,
$source,
$error_message ?? 'internal error',
));
}
// @codeCoverageIgnoreEnd
}