-
Notifications
You must be signed in to change notification settings - Fork 1
/
createbag.py
199 lines (171 loc) · 7.59 KB
/
createbag.py
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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
"""
GUI tool to create a Bag from a filesystem folder.
"""
import ConfigParser
import sys
import os
import shutil
import getpass
import bagit
import platform
if platform.system() != 'Darwin':
# We don't use Gtk on OSX.
from gi.repository import Gtk
else:
# Sets up Cocoadialog for error message popup on OSX.
class cocoaPopup:
# Change CD_BASE to reflect the location of Cocoadialog on your system.
CD_BASE = "~/.createbag/"
CD_PATH = os.path.join(CD_BASE, "CocoaDialog.app/Contents/MacOS/CocoaDialog")
def __init__(self, title, message, button):
template = "%s msgbox --title '%s' --text '%s' --button1 '%s'"
self.pipe = os.popen(template % (cocoaPopup.CD_PATH, title, message, button), "w")
def cocoaError():
if __name__ == "__main__":
popup = cocoaPopup("Error","Sorry, you can't create a bag here -- you may want to change the config file so that bags are always created in a different output directory, rather than in situ.","OK")
if popup == "1":
popup.close()
sys.exit()
def cocoaSuccess(bag_dir):
if __name__ == "__main__":
popup = cocoaPopup("Success!","Bag created at %s" % bag_dir,"OK")
if popup == "1":
popup.close()
# Under Linux and Windows, config file location is first command-line parameter.
# Under OSX, the input directory is the first, the config file is the second.
if platform.system() != 'Darwin':
if len(sys.argv) > 1:
config_file = sys.argv[1]
else:
config_file = './config.cfg'
else:
if len(sys.argv) > 2:
config_file = sys.argv[2]
else:
config_file = './config.cfg'
config = ConfigParser.ConfigParser()
config.optionxform = str
config.read(config_file)
# Get custom tags from config file.
bagit_tags = {}
tags = config.options('CustomTags')
for tag in tags:
bagit_tags[tag] = config.get('CustomTags', tag)
# Get shortcuts from config file.
if config.has_option('Shortcuts', 'shortcuts'):
filechooser_shortcuts = [shortcut.strip() for shortcut in config.get('Shortcuts', 'shortcuts').split(',')]
else:
filechooser_shortcuts = []
# Get checksum algorithms from config file.
bagit_checksum_algorithms = []
if config.has_option('Checksums', 'algorithms'):
checksums_string = config.get('Checksums', 'algorithms', 'md5')
bagit_checksum_algorithms = [algo.strip() for algo in checksums_string.split(',')]
else:
bagit_checksum_algorithms = ['md5']
def directory_check(chosen_folder):
"""Prevent the utility from creating a Bag in its own directory."""
if config.has_option('Output', 'create_bag_in'):
relativized_picker_path = os.path.relpath(chosen_folder, '/')
bag_dir = os.path.join(config.get('Output', 'create_bag_in'), relativized_picker_path)
if os.path.dirname(os.path.realpath(__file__)) == bag_dir:
if platform.system() != 'Darwin':
FolderChooserWindow.GtkError(win)
else:
cocoaError()
else:
if os.path.dirname(os.path.realpath(__file__)) == chosen_folder:
if platform.system() != 'Darwin':
FolderChooserWindow.GtkError(win)
else:
cocoaError()
def make_bag(chosen_folder):
"""Create a Bag from the files in chosen_folder, and return the directory
the Bag was created in.
"""
if config.getboolean('AutogeneratedTags', 'add_source_directory_tag'):
bagit_tags['Source-Directory'] = chosen_folder
if config.getboolean('AutogeneratedTags', 'add_source_user_id_tag'):
bagit_tags['Source-User'] = getpass.getuser()
# If the 'create_bag_in' config option is set, create the Bag from a
# copy of the selected folder.
if config.has_option('Output', 'create_bag_in'):
relativized_picker_path = os.path.relpath(chosen_folder, '/')
bag_dir = os.path.join(config.get('Output', 'create_bag_in'), relativized_picker_path)
try:
shutil.rmtree(bag_dir, True)
shutil.copytree(chosen_folder, bag_dir)
except (IOError, os.error) as shutilerror:
if platform.system() != 'Darwin':
FolderChooserWindow.GtkError(win)
else:
cocoaError()
# If 'create_bag_in' is not set, create the Bag in the selected directory.
else:
bag_dir = chosen_folder
# Create the Bag.
try:
bag = bagit.make_bag(bag_dir, bagit_tags, 1, bagit_checksum_algorithms)
except (bagit.BagError, Exception) as e:
if platform.system() != 'Darwin':
FolderChooserWindow.GtkError(win)
else:
cocoaError()
return bag_dir
# Code within this if block only applies to Linux and Windows, not OSX.
if platform.system() != 'Darwin':
class FolderChooserWindow(Gtk.Window):
def __init__(self):
Gtk.Window.__init__(self, title = config.get('UILabels', 'main_window_title', 'Create a Bag'))
self.set_border_width(10)
self.move(200, 200)
box = Gtk.Box(spacing=6)
self.add(box)
self.spinner = Gtk.Spinner()
choose_folder_button = Gtk.Button("Choose a folder to create Bag from")
choose_folder_button.connect("clicked", self.on_folder_clicked)
box.add(choose_folder_button)
quit_button = Gtk.Button("Quit")
quit_button.connect("clicked", Gtk.main_quit)
box.add(quit_button)
def GtkError(self):
not_allowed_message = "\n\nYou are not allowed to run the program on that directory."
error_dialog = Gtk.MessageDialog(self, 0, Gtk.MessageType.ERROR,
Gtk.ButtonsType.OK, "Sorry...")
error_dialog.format_secondary_text(not_allowed_message)
error_dialog.run()
error_dialog.destroy()
raise SystemExit
def on_folder_clicked(self, widget):
folder_picker_dialog = Gtk.FileChooserDialog(
config.get('UILabels', 'file_chooser_window_title', 'Create a Bag - Choose a folder to create Bag from'),
self, Gtk.FileChooserAction.SELECT_FOLDER)
folder_picker_dialog.set_default_size(800, 400)
folder_picker_dialog.set_create_folders(False)
folder_picker_dialog.add_button("Create Bag", -5)
folder_picker_dialog.add_button("Cancel", -6)
for filechooser_shortcut in filechooser_shortcuts:
folder_picker_dialog.add_shortcut_folder(filechooser_shortcut)
response = folder_picker_dialog.run()
if response == -5:
directory_check(folder_picker_dialog.get_filename())
bag_dir = make_bag(folder_picker_dialog.get_filename())
folder_picker_dialog.destroy()
if (bag_dir):
confirmation_dialog = Gtk.MessageDialog(self, 0, Gtk.MessageType.INFO,
Gtk.ButtonsType.OK, "Bag created")
confirmation_dialog.format_secondary_text(
"The Bag for folder %s has been created." % bag_dir)
confirmation_dialog.run()
confirmation_dialog.destroy()
if response == -6:
folder_picker_dialog.destroy()
win = FolderChooserWindow()
win.connect("delete-event", Gtk.main_quit)
win.show_all()
Gtk.main()
# OSX-specific code.
else:
directory_check(sys.argv[1])
bag_dir = make_bag(sys.argv[1])
cocoaSuccess(bag_dir)