Skip to content

Commit 0384942

Browse files
committed
add recursive indexing by os.walk
1 parent ea4fea6 commit 0384942

File tree

4 files changed

+46
-61
lines changed

4 files changed

+46
-61
lines changed

index_generator/__main__.py

Lines changed: 34 additions & 51 deletions
Original file line numberDiff line numberDiff line change
@@ -5,19 +5,16 @@
55
import os
66
import jinja2
77
import argparse
8-
import os.path as path
98
from datetime import datetime
109

1110
from index_generator.models.entries import Entry
1211
from index_generator.models.exceptions import IndexGeneratorException
1312
from . import *
1413

15-
indexIgnore = ['index.html', 'templates']
14+
indexIgnore = ('index.html' 'images' 'favicon.ico')
1615

1716

1817
def main():
19-
global template
20-
global arguments
2118
parser = argparse.ArgumentParser()
2219
parser.add_argument('--version', '-V', action='store_true', default=False,
2320
help='Print version infomation and quit.')
@@ -27,7 +24,8 @@ def main():
2724
parser.add_argument('--name', '-n', type=str, default='index.html',
2825
help='Default output filename.')
2926
parser.add_argument('--print', '-P', action='store_true', default=False, help='Whether to print to stdout.')
30-
parser.add_argument('path', type=str, default='.', help='Path')
27+
parser.add_argument('path', type=str, default='', help='Path')
28+
parser.add_argument('--depth','-d', type=int, default=0, help='Set cutoff depth.')
3129
arguments = parser.parse_args(sys.argv[1:])
3230
app(arguments)
3331

@@ -37,22 +35,26 @@ def app(args):
3735
print(APP_NAME + ' ' + APP_VERSION + ' ' + APP_URL)
3836
sys.exit(0)
3937
if args.no_recursive:
40-
generate_once(args.template, args.path, args.name, args.print)
38+
generate_once(args.template, args.path, os.listdir(args.path), args.name, args.print)
4139
else:
42-
raise IndexGeneratorException(IndexGeneratorException.NOT_IMPLEMENTED)
40+
generate_recursively(args.template, args.path, args.name, args.print, args.depth)
4341

4442

45-
def generate_once(template_dir, path='.', name='index.html', if_print=False):
43+
def generate_once(template_dir, root, files, name, if_print):
4644
environment = jinja2.Environment(
4745
loader=jinja2.PackageLoader('index_generator', template_dir),
4846
autoescape=jinja2.select_autoescape(['html', 'htm'])
4947
)
5048
template = environment.get_template(name)
51-
entries = list(map(lambda f: Entry(f), os.listdir(path)))
52-
entries.sort(key=lambda x: x.isDir, reverse=True)
53-
files = []
49+
50+
entries = list(map(lambda f: Entry(f,root), files))
51+
#entries.sort(key=lambda x: x.isDir, reverse=True)
52+
53+
filelist=[]
5454
for entry in entries:
55-
files.append({
55+
if entry.name in indexIgnore:
56+
continue
57+
filelist.append({
5658
'path': entry.path,
5759
'name': entry.name,
5860
'size': entry.size,
@@ -61,52 +63,33 @@ def generate_once(template_dir, path='.', name='index.html', if_print=False):
6163
'isDir': entry.isDir
6264
})
6365
html = template.render(ig={
64-
'currentPath': '/',
65-
'files': files
66+
'root': '/'+root.lstrip('.*/'),
67+
'files': filelist
6668
})
69+
6770
if if_print:
6871
print(html)
6972
else:
70-
raise IndexGeneratorException(IndexGeneratorException.NOT_IMPLEMENTED)
71-
73+
with open(root+os.path.sep+name, 'w') as f:
74+
print(html, file=f)
7275

73-
def generate(currentDir=''):
74-
filelist=[]
75-
dirlist=[]
76-
for file in os.listdir():
77-
if file in indexIgnore:
76+
def generate_recursively(template_dir, path, name, if_print, max_depth=0):
77+
for root, dirs, files in os.walk(path):
78+
if max_depth != 0 and root.count(os.sep) >= max_depth:
79+
dirs.clear()
7880
continue
79-
if path.isdir(file):
80-
dirlist.append({
81-
'name': file,
82-
'modified': datetime.fromtimestamp(path.getmtime(file)).strftime('%Y-%m-%d %H:%M')
83-
})
84-
else:
85-
filelist.append({
86-
'name': file,
87-
'modified': datetime.fromtimestamp(path.getmtime(file)).strftime('%Y-%m-%d %H:%M'),
88-
'size': path.getsize(file)
89-
})
90-
91-
index = template.render(ig={
92-
'currentPath': currentDir,
93-
'dirs': dirlist,
94-
'files': filelist
95-
})
96-
if arguments.print:
97-
print(index)
98-
99-
with open('index.html', 'w') as f:
100-
print(index, file=f)
81+
82+
dirs.sort()
83+
files.sort()
10184

102-
if not arguments.no_recursive and dirlist:
103-
for file in dirlist:
104-
if arguments.print:
105-
print('------------------------------------------------')
106-
os.chdir(file['name'])
107-
generate(currentDir+'/'+file['name'])
108-
109-
os.chdir('..')
85+
if if_print:
86+
print('-----------------------------------------')
87+
print('Path: '+root)
88+
print('dirs: {}'.format(dirs))
89+
print('files: {}'.format(files))
90+
print('-----------------------------------------')
91+
92+
generate_once(template_dir, root, dirs+files, name, if_print)
11093

11194

11295
if __name__ == '__main__':

index_generator/models/entries.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,10 +3,11 @@
33

44

55
class Entry(object):
6-
def __init__(self, path, root='/'):
6+
def __init__(self, file, root):
7+
path = root + os.path.sep + file
8+
self.path = '/' + path.lstrip('.*/')
79
self.name = os.path.basename(path)
810
self.mime = mimetypes.guess_type(path)[0]
9-
self.path = root + path
1011
self.size = os.path.getsize(path)
1112
self.modified = os.path.getmtime(path)
1213
self.isDir = os.path.isdir(path)

index_generator/templates/default/index.html

Lines changed: 7 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -6,13 +6,13 @@
66
{% endblock %}
77
{% block files %}
88
<table>
9-
<col width="800">
10-
<col width="200">
11-
<col width="80">
9+
<col width="600">
10+
<col width="180">
11+
<col width="300">
1212
<tr>
1313
<th align="left">Filename</th>
14-
<th align="left">Last modified</th>
1514
<th align="left">Size</th>
15+
<th align="left">Last modified</th>
1616
</tr>
1717
<tr>
1818
<td><a href="../">Parent directory/</a></td>
@@ -21,13 +21,14 @@
2121
</tr>
2222
{% for file in ig.files %}
2323
<tr>
24-
<td><a href="{{ file.name }}">{{ file.name }}</a></td>
25-
<td>{{ file.modified }}</td>
2624
{% if file.isDir %}
25+
<td><a href="{{ file.path }}">{{ file.name }}/</a></td>
2726
<td>-</td>
2827
{% else %}
28+
<td><a href="{{ file.path }}">{{ file.name }}</a></td>
2929
<td>{{ file.size }}</td>
3030
{% endif %}
31+
<td>{{ file.modified }}</td>
3132
</tr>
3233
{% endfor %}
3334
</table>

index_generator/templates/default/layout.html

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,12 +2,12 @@
22
<html lang="en">
33
<head>
44
<meta charset="UTF-8">
5-
<title>{% block title %}Files: {{ ig.currentPath }}/{% endblock %}</title>
5+
<title>{% block title %}Index of: {{ ig.root }}{% endblock %}</title>
66
{% block extra %}{% endblock %}
77
</head>
88
<body>
99
{% block head %}
10-
<h1>Index of {{ ig.currentPath }}/</h1>
10+
<h1>Index of {{ ig.root }}</h1>
1111
<hr>
1212
{% block files %}
1313
{% endblock %}

0 commit comments

Comments
 (0)