All files / fs / unstable_chown.ts

33.33% Branches 1/3
53.33% Lines 16/30
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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
 
 
x1
x1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
x1
x1
x1
x1
 
x6
x6
 
 
 
 
 
 
 
x6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
x1
x1
x1
x1
 
x6
x6
 
 
 
 
 
 
 
x6
































I




































I






// Copyright 2018-2025 the Deno authors. MIT license.

import { getNodeFs, isDeno } from "./_utils.ts";
import { mapError } from "./_map_error.ts";

/**
 * Change owner of a regular file or directory.
 *
 * This functionality is not available on Windows.
 *
 * Requires `allow-write` permission.
 *
 * Throws Error (not implemented) if executed on Windows.
 *
 * @example Usage
 * ```ts ignore
 * import { chown } from "@std/fs/unstable-chown";
 * await chown("README.md", 1000, 1002);
 * ```
 *
 * @tags allow-write
 *
 * @param path The path to the file/directory.
 * @param uid The user id (UID) of the new owner, or `null` for no change.
 * @param gid The group id (GID) of the new owner, or `null` for no change.
 */
export async function chown(
  path: string | URL,
  uid: number | null,
  gid: number | null,
): Promise<void> {
  if (isDeno) {
    await Deno.chown(path, uid, gid);
  } else {
    try {
      await getNodeFs().promises.chown(path, uid ?? -1, gid ?? -1);
    } catch (error) {
      throw mapError(error);
    }
  }
}

/**
 * Synchronously change owner of a regular file or directory.
 *
 * This functionality is not available on Windows.
 *
 * Requires `allow-write` permission.
 *
 * Throws Error (not implemented) if executed on Windows.
 *
 * @example Usage
 * ```ts ignore
 * import { chownSync } from "@std/fs/unstable-chown";
 * chownSync("README.md", 1000, 1002);
 * ```
 *
 * @tags allow-write
 *
 * @param path The path to the file/directory.
 * @param uid The user id (UID) of the new owner, or `null` for no change.
 * @param gid The group id (GID) of the new owner, or `null` for no change.
 */
export function chownSync(
  path: string | URL,
  uid: number | null,
  gid: number | null,
): void {
  if (isDeno) {
    Deno.chownSync(path, uid, gid);
  } else {
    try {
      getNodeFs().chownSync(path, uid ?? -1, gid ?? -1);
    } catch (error) {
      throw mapError(error);
    }
  }
}