Skip to content
This repository was archived by the owner on Aug 16, 2024. It is now read-only.

Commit 275fe5c

Browse files
committed
Initial commit (v1.0.0)
0 parents  commit 275fe5c

File tree

6 files changed

+819
-0
lines changed

6 files changed

+819
-0
lines changed

.gitignore

+3
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
*.egg-info/
2+
dist/
3+
tests/

LICENSE

+661
Large diffs are not rendered by default.

README.md

+45
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
# Ensure File
2+
An easy way to manage file creation
3+
4+
Example usage:
5+
```py
6+
from ensure_file import ensure_file as ef
7+
8+
# This will create a file in the user directory under the `.example` folder
9+
# if the file doesn't already exist. If the file does exist, nothing happens.
10+
# Along with that, it will return true if a file is created, and false if
11+
# nothing happens. This applies to everything else going forward.
12+
ef("~/.example/foo.txt")
13+
14+
# Using the `default_value` parameter, you can set the default value to be
15+
# written to the file. If the file already exists, nothing happens.
16+
import json
17+
ef("./bar.json", default_value=json.dumps({
18+
"foo": "bar"
19+
}))
20+
21+
# If you want to create a folder, you can set the `folder` parameter to true.
22+
ef("/tmp/foo", folder=True)
23+
24+
# If there is already a folder with the same name as a file you want to create,
25+
# the folder will be deleted and overwritten. This can be disabled by setting
26+
# the `auto_correct_type` to false. In this function call, nothing would happen
27+
# because of the folder created on the previous line.
28+
ef("/tmp/foo", folder=False, auto_correct_type=False)
29+
30+
# If you want to not actually create any files or folders and instead throw an
31+
# error if a file or folder doesn't exist, you can easily do so by setting the
32+
# `throw_error` parameter to true. By default, this will also throw an error
33+
# if the file or folder is the wrong type, such as checking if the file you're
34+
# checking has the same name as a folder in the same directory. The type
35+
# checking can be disabled by setting the `throw_check_type` parameter to
36+
# false.
37+
try:
38+
ef("./some/file.css", folder=False, throw_error=True)
39+
print("The file exists!")
40+
41+
except FileNotFoundError:
42+
print("The file doesn't exist!")
43+
except FileExistsError:
44+
print("A folder exists where there should be a file!")
45+
```

build.sh

+9
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
# Building
2+
python3 -m build
3+
4+
# Pushing (requires user input)
5+
python3 -m twine upload --repository pypi dist/*
6+
7+
# Remove excess files
8+
rm -r dist/*
9+
rm -r src/*.egg-info

pyproject.toml

+18
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
[project]
2+
name = "ensure_file"
3+
version = "1.0.0"
4+
authors = [
5+
{ name="Hazel", email="[email protected]" },
6+
]
7+
description = "An easy way to manage file creation."
8+
readme = "README.md"
9+
requires-python = ">=3.6"
10+
classifiers = [
11+
"Programming Language :: Python :: 3",
12+
"License :: OSI Approved :: GNU Affero General Public License v3",
13+
"Operating System :: OS Independent",
14+
]
15+
16+
[project.urls]
17+
Homepage = "https://github.com/trinkey/ensure-file"
18+
Issues = "https://github.com/trinkey/ensure-file/issues"

src/ensure_file/__init__.py

+83
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,83 @@
1+
import os
2+
3+
from typing import Union
4+
5+
def ensure_file(
6+
path: Union[str, bytes], *,
7+
folder: bool = False,
8+
default_value: Union[str, bytes] = b"",
9+
auto_correct_type: bool = True,
10+
throw_error: bool = False,
11+
throw_check_type: bool = True
12+
) -> bool:
13+
'''Creates a file or folder if it doesn't exist.
14+
15+
path: string - The file/folder path
16+
folder: boolean - Whether or not to create a folder instead of a file.
17+
default_value: string | bytes - The default value to put into a created file (assuming folder is false).
18+
auto_correct_type: boolean - Whether or not to delete the file and recreate it if it is a folder instead of a file or vice versa.
19+
throw_error: boolean - Throws an error if the file doesn't exist, instead of creating a new one.
20+
throw_check_type: boolean - Requires throw_error to be true. This also throws an error if a folder is meant to be a file or vice versa.
21+
22+
Returns true if a file was created or the file type was swapped and false if the file wasn't created.'''
23+
24+
# Type checking
25+
if isinstance(path, bytes):
26+
path: str = bytes.decode(path)
27+
if not isinstance(path, str):
28+
raise TypeError(f"'path' should be str or bytes, not {type(path)}")
29+
if not isinstance(folder, bool):
30+
folder: bool = bool(folder)
31+
if isinstance(default_value, str):
32+
default_value: bytes = str.encode(default_value)
33+
if not isinstance(default_value, bytes):
34+
default_value: bytes = str.encode(str(default_value))
35+
if not isinstance(auto_correct_type, bool):
36+
auto_correct_type: bool = bool(auto_correct_type)
37+
if not isinstance(throw_error, bool):
38+
throw_error: bool = bool(throw_error)
39+
if not isinstance(throw_check_type, bool):
40+
throw_check_type: bool = bool(throw_check_type)
41+
42+
# Expand the user part of a path
43+
if path and path[0] == "~":
44+
path: str = os.path.expanduser(path)
45+
46+
# Throws the errors if needed
47+
if throw_error:
48+
if not os.path.exists(path):
49+
raise FileNotFoundError(f"The {'folder' if folder else 'file'} at {path} doesn't exist.")
50+
51+
if throw_check_type and ((os.path.isdir(path) and not folder) or (not os.path.isdir(path) and folder)):
52+
raise FileExistsError(f"The {'file' if folder else 'folder'} at {path} should be a {'folder' if folder else 'file'}.")
53+
54+
return False
55+
56+
if os.path.exists(path):
57+
# File: exists; Type: Folder; Should be: File
58+
if auto_correct_type and os.path.isdir(path) and not folder:
59+
os.rmdir(path)
60+
f = open(path, "wb")
61+
f.write(default_value)
62+
f.close()
63+
return True
64+
65+
# File: exists; Type: File; Should be: Fplder
66+
if auto_correct_type and not os.path.isdir(path) and folder:
67+
os.remove(path)
68+
os.mkdir(path)
69+
return True
70+
71+
# File: exists; Type: File | Folder; Should be: File | Folder
72+
return False
73+
74+
if folder:
75+
# File: doesn't exist; Should be: Folder
76+
os.mkdir(path)
77+
else:
78+
# File: doesn't exist; Should be: File
79+
f = open(path, "wb")
80+
f.write(default_value)
81+
f.close()
82+
83+
return True

0 commit comments

Comments
 (0)