Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
mikf
GitHub Repository: mikf/gallery-dl
Path: blob/master/scripts/util.py
5457 views
1
# -*- coding: utf-8 -*-
2
3
# This program is free software; you can redistribute it and/or modify
4
# it under the terms of the GNU General Public License version 2 as
5
# published by the Free Software Foundation.
6
7
import os
8
import io
9
import sys
10
import builtins
11
12
ROOTDIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
13
sys.path.insert(0, os.path.realpath(ROOTDIR))
14
15
16
def path(*segments):
17
result = os.path.join(ROOTDIR, *segments)
18
os.makedirs(os.path.dirname(result), exist_ok=True)
19
return result
20
21
22
def trim(path):
23
return path[len(ROOTDIR)+1:]
24
25
26
def open(path, mode="r"):
27
return builtins.open(path, mode, encoding="utf-8", newline="\n")
28
29
30
def git(command, *args):
31
import subprocess
32
return subprocess.Popen(
33
["git", command, *args],
34
stdout=subprocess.PIPE,
35
cwd=ROOTDIR,
36
).communicate()[0].strip().decode()
37
38
39
class lazy():
40
41
def __init__(self, path):
42
self.path = path
43
self.buffer = io.StringIO()
44
45
def __enter__(self):
46
return self.buffer
47
48
def __exit__(self, exc_type, exc_value, traceback):
49
# get content of old file
50
try:
51
with builtins.open(self.path, encoding="utf-8", newline="") as fp:
52
old = fp.read()
53
except Exception:
54
old = None
55
56
# get new content
57
new = self.buffer.getvalue()
58
59
if new != old:
60
# rewrite entire file
61
with builtins.open(
62
self.path, "w", encoding="utf-8", newline="") as fp:
63
fp.write(new)
64
else:
65
# only update atime and mtime
66
os.utime(self.path)
67
68
69
class lines():
70
71
def __init__(self, path, lazy=True):
72
self.path = path
73
self.lazy = lazy
74
self.lines = ()
75
76
def __enter__(self):
77
with open(self.path) as fp:
78
self.lines = lines = fp.readlines()
79
return lines
80
81
def __exit__(self, exc_type, exc_value, traceback):
82
ctx = lazy(self.path) if self.lazy else open(self.path, "w")
83
with ctx as fp:
84
fp.writelines(self.lines)
85
86