/
Entity.swift
101 lines (79 loc) · 2.92 KB
/
Entity.swift
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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
//
// Entity.swift
// SwiftFilePath
//
// Created by nori0620 on 2015/01/08.
// Copyright (c) 2015年 Norihiro Sakamoto. All rights reserved.
//
public class Entity {
lazy var fileManager = NSFileManager.defaultManager()
public class func isDir(path:NSString) -> Bool {
var isDirectory: ObjCBool = false
let isFileExists = NSFileManager.defaultManager().fileExistsAtPath(path, isDirectory:&isDirectory)
return isDirectory ? true : false
}
public class func isExists(path:NSString) -> Bool {
return true
}
public let path:String
public var attributes:NSDictionary{
get { return self.loadAttributes() }
}
public init(_ p: String) {
self.path = p
}
public var toString : String{
return self.path
}
public var exists: Bool {
return fileManager.fileExistsAtPath(path)
}
public var isDir: Bool {
return false;
}
public var basename:NSString {
return path.lastPathComponent
}
public func remove() -> Result<Entity,String> {
assert(self.exists,"To remove file, file MUST be exists")
var error: NSError?
let result = fileManager.removeItemAtPath(path, error:&error)
return result
? Result(success: self)
: Result(failure: "Failed to remove file.<error:\(error?.localizedDescription) path:\(path)>");
}
public func copyTo(toPath:Entity) -> Result<Entity,String> {
assert(self.exists,"To copy file, file MUST be exists")
var error: NSError?
let result = fileManager.copyItemAtPath(path,
toPath: toPath.toString,
error: &error)
return result
? Result(success: self)
: Result(failure: "Failed to copy file.<error:\(error?.localizedDescription) from-path:\(path) to-path:\(toPath)>");
}
public func moveTo(toPath:Entity) -> Result<Entity,String> {
assert(self.exists,"To move file, file MUST be exists")
var error: NSError?
let result = fileManager.moveItemAtPath(path,
toPath: toPath.toString,
error: &error)
return result
? Result(success: self)
: Result(failure: "Failed to move file.<error:\(error?.localizedDescription) from-path:\(path) to-path:\(toPath)>");
}
private func loadAttributes() -> NSDictionary {
assert(self.exists,"File must be exists to load file.< \(path) >")
var loadError: NSError?
let result = self.fileManager.attributesOfItemAtPath(path, error: &loadError)
if let error = loadError {
println("Error< \(error.localizedDescription) >")
}
return result!
}
}
extension Entity: Printable {
public var description: String {
return "\(NSStringFromClass(self.dynamicType))<path:\(path)>"
}
}