|
1298 | 1298 | "test_eq(expand_wildcards(inp), exp)" |
1299 | 1299 | ] |
1300 | 1300 | }, |
| 1301 | + { |
| 1302 | + "cell_type": "code", |
| 1303 | + "execution_count": null, |
| 1304 | + "id": "15c2b62c", |
| 1305 | + "metadata": {}, |
| 1306 | + "outputs": [], |
| 1307 | + "source": [ |
| 1308 | + "#| export\n", |
| 1309 | + "@patch\n", |
| 1310 | + "def mkdir_perms(self:Path, mode=0o777, parents=False, exist_ok=False, uid=-1, gid=-1):\n", |
| 1311 | + " \"Create directory like Path.mkdir but optionally set uid/gid on newly created dirs\"\n", |
| 1312 | + " if self.exists() and not exist_ok: raise FileExistsError(self)\n", |
| 1313 | + " to_create = []\n", |
| 1314 | + " p = self\n", |
| 1315 | + " while not p.exists():\n", |
| 1316 | + " to_create.append(p)\n", |
| 1317 | + " if parents: p = p.parent\n", |
| 1318 | + " else: break\n", |
| 1319 | + " for d in reversed(to_create):\n", |
| 1320 | + " try: d.mkdir(mode=mode)\n", |
| 1321 | + " except FileExistsError:\n", |
| 1322 | + " if d==self and not exist_ok: raise\n", |
| 1323 | + " continue\n", |
| 1324 | + " if uid>-1 or gid>-1: os.chown(d, uid, gid)" |
| 1325 | + ] |
| 1326 | + }, |
| 1327 | + { |
| 1328 | + "cell_type": "code", |
| 1329 | + "execution_count": null, |
| 1330 | + "id": "5c6c3416", |
| 1331 | + "metadata": {}, |
| 1332 | + "outputs": [], |
| 1333 | + "source": [ |
| 1334 | + "import tempfile\n", |
| 1335 | + "from fastcore.test import test_fail\n", |
| 1336 | + "\n", |
| 1337 | + "with tempfile.TemporaryDirectory() as tmpdir:\n", |
| 1338 | + " base = Path(tmpdir)\n", |
| 1339 | + " p1 = base/'test1'\n", |
| 1340 | + " p1.mkdir_perms()\n", |
| 1341 | + " assert p1.exists() and p1.is_dir()\n", |
| 1342 | + " \n", |
| 1343 | + " p2 = base/'a'/'b'/'c'\n", |
| 1344 | + " p2.mkdir_perms(parents=True)\n", |
| 1345 | + " assert p2.exists() and (base/'a').exists()\n", |
| 1346 | + " \n", |
| 1347 | + " p1.mkdir_perms(exist_ok=True)\n", |
| 1348 | + " assert p1.exists()\n", |
| 1349 | + " \n", |
| 1350 | + " test_fail(p1.mkdir_perms, exc=FileExistsError)\n", |
| 1351 | + " test_fail((base/'missing'/'child').mkdir_perms, exc=FileNotFoundError)" |
| 1352 | + ] |
| 1353 | + }, |
1301 | 1354 | { |
1302 | 1355 | "cell_type": "code", |
1303 | 1356 | "execution_count": null, |
|
1311 | 1364 | " \"Context manager for writing a file atomically via a temp file that is renamed on close\"\n", |
1312 | 1365 | " from tempfile import NamedTemporaryFile as ntf\n", |
1313 | 1366 | " fn = Path(fn)\n", |
| 1367 | + " fn.parent.mkdir_perms(parents=True, exist_ok=True, uid=uid, gid=gid)\n", |
1314 | 1368 | " with ntf(mode=mode, dir=fn.parent, delete=False, suffix=fn.suffix, **kwargs) as f:\n", |
1315 | 1369 | " try: yield f\n", |
1316 | 1370 | " except:\n", |
|
0 commit comments