From e301fefe660f3cb1f27f924e04d25db5db9f28a6 Mon Sep 17 00:00:00 2001 From: kitsunyan Date: Sat, 19 May 2018 07:46:13 +0300 Subject: Add user cache dir --- src/common.nim | 52 ++++++++++++++++++++++++++++++++++++++++------------ 1 file changed, 40 insertions(+), 12 deletions(-) (limited to 'src/common.nim') diff --git a/src/common.nim b/src/common.nim index 11f6aef..bd9573a 100644 --- a/src/common.nim +++ b/src/common.nim @@ -4,6 +4,9 @@ import "wrapper/alpm" type + CacheKind* {.pure.} = enum + repositories + SyncFoundPackageInfo* = tuple[ base: string, version: string, @@ -245,21 +248,46 @@ proc `$`*[T: PackageTarget](target: T): string = template tmpRoot(config: Config, dropPrivileges: bool): string = if dropPrivileges: config.tmpRootInitial else: config.tmpRootCurrent -proc ensureTmpOrError*(config: Config, dropPrivileges: bool): Option[string] = - let tmpRootExists = try: - discard config.tmpRoot(dropPrivileges).existsOrCreateDir() - if dropPrivileges: - let user = initialUser.get(currentUser) - discard chown(config.tmpRoot(dropPrivileges), (Uid) user.uid, (Gid) user.gid) - true - except: - false - - if not tmpRootExists: - some(tr"failed to create tmp directory '$#'" % [config.tmpRoot(dropPrivileges)]) +template userCache(config: Config, dropPrivileges: bool): string = + if dropPrivileges: config.userCacheInitial else: config.userCacheCurrent + +template cache*(userCache: string, cacheKind: CacheKind): string = + userCache & "/" & $cacheKind + +proc createDirRecursive(dir: string, chownUser: Option[User]): bool = + let segments = dir.split("/").filter(x => not (x.len == 0 or x == ".")) + + proc createDirIndex(index: int): bool = + if index < segments.len: + let path = (if dir.len > 0 and dir[0] == '/': "/" else: "") & + segments[0 .. index].join("/") + try: + let exists = path.existsOrCreateDir() + if chownUser.isSome and (not exists or index == segments.len - 1): + discard chown(path, (Uid) chownUser.unsafeGet.uid, (Gid) chownUser.unsafeGet.gid) + createDirIndex(index + 1) + except: + false + else: + true + + createDirIndex(0) + +proc ensureDirOrError(dir: string, dropPrivileges: bool): Option[string] = + let user = if dropPrivileges: some(initialUser.get(currentUser)) else: none(User) + + if not createDirRecursive(dir, user): + some(tr"failed to create directory '$#'" % [dir]) else: none(string) +proc ensureTmpOrError*(config: Config, dropPrivileges: bool): Option[string] = + ensureDirOrError(config.tmpRoot(dropPrivileges), dropPrivileges) + +proc ensureUserCacheOrError*(config: Config, cacheKind: CacheKind, + dropPrivileges: bool): Option[string] = + ensureDirOrError(config.userCache(dropPrivileges).cache(cacheKind), dropPrivileges) + proc getGitFiles*(repoPath: string, gitSubdir: Option[string], dropPrivileges: bool): seq[string] = if gitSubdir.isSome: -- cgit v1.2.3-70-g09d2