-
-
Notifications
You must be signed in to change notification settings - Fork 72
/
Copy pathcreate_hard_link.php
55 lines (46 loc) · 1.47 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
<?php
declare(strict_types=1);
namespace Psl\Filesystem;
use Psl;
use Psl\Internal;
use Psl\Str;
use function link;
/**
* Create a hard link for $source.
*
* @param string $source The file to create a hard link for.
*
* @throws Psl\Exception\InvariantViolationException If $source is not a file, or does not exist.
* @throws Exception\RuntimeException If unable to create a hard file.
*/
function create_hard_link(string $source, string $destination): void
{
Psl\invariant(exists($source), '$source file does not exist.');
Psl\invariant(is_file($source), '$source is not a file.');
$destination_directory = get_directory($destination);
if (!is_directory($destination_directory)) {
create_directory($destination_directory);
}
if (exists($destination)) {
if (get_inode($destination) === get_inode($source)) {
// already exists.
return;
}
if (is_directory($destination)) {
delete_directory($destination, true);
} else {
delete_file($destination);
}
}
[$result, $error_message] = Internal\box(static fn() => 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
}