diff --git a/docs/uri-scheme-browse-origin.rst b/docs/uri-scheme-browse-origin.rst index 731d67544..2c071e012 100644 --- a/docs/uri-scheme-browse-origin.rst +++ b/docs/uri-scheme-browse-origin.rst @@ -1,351 +1,363 @@ Origin ^^^^^^ Origin metadata """"""""""""""" .. http:get:: /browse/origin/(origin_type)/url/(origin_url)/ HTML view that displays a SWH origin identified by its type and url. The view displays the origin metadata and contains links for browsing its directories and contents for each SWH visit. :param string origin_type: the type of the SWH origin (*git*, *svn*, *deb* ...) :param string origin_url: the url of the origin (e.g. https://github.com/user/repo) :statuscode 200: no error :statuscode 404: requested origin can not be found in the SWH archive **Examples:** .. parsed-literal:: :swh_web_browse:`origin/git/url/https://github.com/torvalds/linux/` :swh_web_browse:`origin/git/url/https://github.com/python/cpython/` :swh_web_browse:`origin/deb/url/deb://Debian-Security/packages/mediawiki/` :swh_web_browse:`origin/git/url/https://gitorious.org/qt/qtbase.git` Origin directory """""""""""""""" .. http:get:: /browse/origin/(origin_type)/url/(origin_url)/directory/[(path)/] HTML view for browsing the content of a directory reachable from the root directory (including itself) associated to the latest visit of a SWH origin. The content of the directory is first sorted in lexicographical order and the sub-directories are displayed before the regular files. The view enables to navigate from the requested directory to directories reachable from it in a recursive way but also up to the origin root directory. A breadcrumb located in the top part of the view allows to keep track of the paths navigated so far. The view also enables to easily switch between the origin branches through a dropdown menu. The origin branch (default to master) from which to retrieve the directory content can also be specified by using the branch query parameter. :param string origin_type: the type of the SWH origin (*git*, *svn*, *deb* ...) :param string origin_url: the url of the origin (e.g. https://github.com/user/repo) :param string path: optional parameter used to specify the path of a directory reachable from the origin root one - :query string branch: specify the origin branch from which + :query string branch: specify the origin branch name from which + to retrieve the directory + :query string release: specify the origin release name from which to retrieve the directory :query string revision: specify the origin revision, identified by the hexadecimal representation of its *sha1_git* value, from which to retrieve the directory :query int visit_id: specify a SWH visit id to retrieve the directory from instead of using the latest visit by default :statuscode 200: no error :statuscode 404: requested origin can not be found in the SWH archive or the provided path does not exist from the origin root directory **Examples:** .. parsed-literal:: :swh_web_browse:`origin/git/url/https://github.com/torvalds/linux/directory/` :swh_web_browse:`origin/git/url/https://github.com/torvalds/linux/directory/net/ethernet/` :swh_web_browse:`origin/git/url/https://github.com/python/cpython/directory/` :swh_web_browse:`origin/git/url/https://github.com/python/cpython/directory/Python/` :swh_web_browse:`origin/git/url/https://github.com/python/cpython/directory/?branch=refs/heads/2.7` .. http:get:: /browse/origin/(origin_type)/url/(origin_url)/visit/(timestamp)/directory/[(path)/] HTML view for browsing the content of a directory reachable from the root directory (including itself) associated to a visitof a SWH origin closest to a provided timestamp. The content of the directory is first sorted in lexicographical order and the sub-directories are displayed before the regular files. The view enables to navigate from the requested directory to directories reachable from it in a recursive way but also up to the origin root directory. A breadcrumb located in the top part of the view allows to keep track of the paths navigated so far. The view also enables to easily switch between the origin branches through a dropdown menu. The origin branch (default to master) from which to retrieve the directory content can also be specified by using the branch query parameter. :param string origin_type: the type of the SWH origin (*git*, *svn*, *deb* ...) :param string origin_url: the url of the origin (e.g. https://github.com/user/repo) :param string timestamp: a date string (any format parsable by `dateutil.parser.parse`_) or Unix timestamp to parse in order to find the closest SWH visit. :param path: optional parameter used to specify the path of a directory reachable from the origin root one :type path: string - :query string branch: specify the origin branch from which + :query string branch: specify the origin branch name from which + to retrieve the directory + :query string revision: specify the origin release name from which to retrieve the directory :query string revision: specify the origin revision, identified by the hexadecimal representation of its *sha1_git* value, from which to retrieve the directory :query int visit_id: specify a SWH visit id to retrieve the directory from instead of using the provided timestamp :statuscode 200: no error :statuscode 404: requested origin can not be found in the SWH archive, requested visit timestamp does not exist or the provided path does not exist from the origin root directory **Examples:** .. parsed-literal:: :swh_web_browse:`origin/git/url/https://github.com/torvalds/linux/visit/1493926809/directory/` :swh_web_browse:`origin/git/url/https://github.com/torvalds/linux/visit/2016-09-14T10:36:21/directory/net/ethernet/` :swh_web_browse:`origin/git/url/https://github.com/python/cpython/visit/1474620651/directory/` :swh_web_browse:`origin/git/url/https://github.com/python/cpython/visit/2017-05-05/directory/Python/` :swh_web_browse:`origin/git/url/https://github.com/python/cpython/visit/2015-08/directory/?branch=refs/heads/2.7` Origin content """""""""""""" .. http:get:: /browse/origin/(origin_type)/url/(origin_url)/content/(path)/ HTML view that produces a display of a SWH content associated to the latest visit of a SWH origin. If the content to display is textual, it will be highlighted client-side if possible using highlightjs_. The procedure to perform that task is described in :http:get:`/browse/content/[(algo_hash):](hash)/`. It is also possible to highlight specific lines of a textual content (not in terms of syntax highlighting but to emphasize some relevant content part) by either: * clicking on line numbers (holding shift to highlight a lines range) * using an url fragment in the form '#Ln' or '#Lm-Ln' The view displays a breadcrumb on top of the rendered content in order to easily navigate up to the origin root directory. The view also enables to easily switch between the origin branches through a dropdown menu. The origin branch (default to master) from which to retrieve the content can also be specified by using the branch query parameter. :param string origin_type: the type of the SWH origin (*git*, *svn*, *deb* ...) :param string origin_url: the url of the origin (e.g. https://github.com/user/repo) :param string path: path of a content reachable from the origin root directory - :query string branch: specify the origin branch from which + :query string branch: specify the origin branch name from which + to retrieve the content + :query string release: specify the origin release name from which to retrieve the content :query string revision: specify the origin revision, identified by the hexadecimal representation of its *sha1_git* value, from which to retrieve the content :query int visit_id: specify a SWH visit id to retrieve the content from instead of using the latest visit by default :statuscode 200: no error :statuscode 404: requested origin can not be found in the SWH archive, or the provided content path does not exist from the origin root directory **Examples:** .. parsed-literal:: :swh_web_browse:`origin/git/url/https://github.com/git/git/content/git.c/` :swh_web_browse:`origin/git/url/https://github.com/git/git/content/git.c/` :swh_web_browse:`origin/git/url/https://github.com/mozilla/gecko-dev/content/js/src/json.cpp/` :swh_web_browse:`origin/git/url/https://github.com/git/git/content/git.c/?branch=refs/heads/next` .. http:get:: /browse/origin/(origin_type)/url/(origin_url)/visit/(timestamp)/content/(path)/ HTML view that produces a display of a SWH content associated to a visit of a SWH origin closest to a provided timestamp. If the content to display is textual, it will be highlighted client-side if possible using highlightjs_. The procedure to perform that task is described in :http:get:`/browse/content/[(algo_hash):](hash)/`. It is also possible to highlight specific lines of a textual content (not in terms of syntax highlighting but to emphasize some relevant content part) by either: * clicking on line numbers (holding shift to highlight a lines range) * using an url fragment in the form '#Ln' or '#Lm-Ln' The view displays a breadcrumb on top of the rendered content in order to easily navigate up to the origin root directory. The view also enables to easily switch between the origin branches through a dropdown menu. The origin branch (default to master) from which to retrieve the content can also be specified by using the branch query parameter. :param string origin_type: the type of the SWH origin (*git*, *svn*, *deb* ...) :param string origin_url: the url of the origin (e.g. https://github.com/user/repo) :param string timestamp: a date string (any format parsable by `dateutil.parser.parse`_) or Unix timestamp to parse in order to find the closest SWH visit. :param string path: path of a content reachable from the origin root directory - :query string branch: specify the origin branch from which + :query string branch: specify the origin branch name from which + to retrieve the content + :query string release: specify the origin release name from which to retrieve the content :query string revision: specify the origin revision, identified by the hexadecimal representation of its *sha1_git* value, from which to retrieve the content :query int visit_id: specify a SWH visit id to retrieve the content from instead of using the provided timestamp :statuscode 200: no error :statuscode 404: requested origin can not be found in the SWH archive, requested visit timestamp does not exist or the provided content path does not exist from the origin root directory **Examples:** .. parsed-literal:: :swh_web_browse:`origin/git/url/https://github.com/git/git/visit/1473933564/content/git.c/` :swh_web_browse:`origin/git/url/https://github.com/git/git/visit/2016-05-05T00:0:00+00:00/content/git.c/` :swh_web_browse:`origin/git/url/https://github.com/mozilla/gecko-dev/visit/1490126182/content/js/src/json.cpp/` :swh_web_browse:`origin/git/url/https://github.com/mozilla/gecko-dev/visit/2017-03-21/content/js/src/json.cpp/#L904-L931` :swh_web_browse:`origin/git/url/https://github.com/git/git/visit/2017-09-15/content/git.c/?branch=refs/heads/next` Origin history """""""""""""" .. http:get:: /browse/origin/(origin_type)/url/(origin_url)/log/ HTML view that produces a display of revisions history heading to the last revision found during the latest visit of a SWH origin. In other words, it shows the commit log associated to the latest visit of a SWH origin. The following data are displayed for each log entry: * author of the revision * link to the revision metadata * message associated the revision * date of the revision * link to browse the associated source tree in the origin context N log entries are displayed per page (default is 20). In order to navigate in a large history, two buttons are present at the bottom of the view: * *Newer*: fetch and display if available the N more recent log entries than the ones currently displayed * *Older*: fetch and display if available the N older log entries than the ones currently displayed The view also enables to easily switch between the origin branches through a dropdown menu. The origin branch (default to master) from which to retrieve the content can also be specified by using the branch query parameter. :param string origin_type: the type of the SWH origin (*git*, *svn*, *deb* ...) :param string origin_url: the url of the origin (e.g. https://github.com/user/repo) :query string revs_breadcrumb: used internally to store the navigation breadcrumbs (i.e. the list of descendant revisions visited so far). It must be a string in the form "(rev_1)[/(rev_2)/.../(rev_n)]" where rev_i corresponds to a revision sha1_git. :query int per_page: the number of log entries to display per page (default is 20, max is 50) - :query string branch: specify the origin branch from which + :query string branch: specify the origin branch name from which + to retrieve the commit log + :query string release: specify the origin release name from which to retrieve the commit log :query string revision: specify the origin revision, identified by the hexadecimal representation of its *sha1_git* value, from which to retrieve the commit log :query int visit_id: specify a SWH visit id to retrieve the history log from instead of using the latest visit by default :statuscode 200: no error :statuscode 404: requested origin can not be found in the SWH archive **Examples:** .. parsed-literal:: :swh_web_browse:`origin/git/url/https://github.com/videolan/vlc/log/` :swh_web_browse:`origin/git/url/https://github.com/Kitware/CMake/log/` :swh_web_browse:`origin/git/url/https://github.com/Kitware/CMake/log/?branch=refs/heads/release` .. http:get:: /browse/origin/(origin_type)/url/(origin_url)/visit/(timestamp)/log/ HTML view that produces a display of revisions history heading to the last revision found during a visit of a SWH origin closest to the provided timestamp. In other words, it shows the commit log associated to a visit of a SWH origin closest to a provided timestamp. The following data are displayed for each log entry: * author of the revision * link to the revision metadata * message associated the revision * date of the revision * link to browse the associated source tree in the origin context N log entries are displayed per page (default is 20). In order to navigate in a large history, two buttons are present at the bottom of the view: * *Newer*: fetch and display if available the N more recent log entries than the ones currently displayed * *Older*: fetch and display if available the N older log entries than the ones currently displayed The view also enables to easily switch between the origin branches through a dropdown menu. The origin branch (default to master) from which to retrieve the content can also be specified by using the branch query parameter. :param string origin_type: the type of the SWH origin (*git*, *svn*, *deb* ...) :param string origin_url: the url of the origin (e.g. https://github.com/user/repo) :param string timestamp: a date string (any format parsable by `dateutil.parser.parse`_) or Unix timestamp to parse in order to find the closest SWH visit. :query string revs_breadcrumb: used internally to store the navigation breadcrumbs (i.e. the list of descendant revisions visited so far). It must be a string in the form "(rev_1)[/(rev_2)/.../(rev_n)]" where rev_i corresponds to a revision sha1_git. :query int per_page: the number of log entries to display per page (default is 20, max is 50) - :query string branch: specify the origin branch from which + :query string branch: specify the origin branch name from which + to retrieve the commit log + :query string release: specify the origin release name from which to retrieve the commit log :query string revision: specify the origin revision, identified by the hexadecimal representation of its *sha1_git* value, from which to retrieve the commit log :query int visit_id: specify a SWH visit id to retrieve the history log from instead of using the provided timestamp :statuscode 200: no error :statuscode 404: requested origin can not be found in the SWH archive **Examples:** .. parsed-literal:: :swh_web_browse:`origin/git/url/https://github.com/videolan/vlc/visit/1459651262/log/` :swh_web_browse:`origin/git/url/https://github.com/Kitware/CMake/visit/2016-04-01/log/` :swh_web_browse:`origin/git/url/https://github.com/Kitware/CMake/visit/1438116814/log/?branch=refs/heads/release` :swh_web_browse:`origin/git/url/https://github.com/Kitware/CMake/visit/2017-05-05T03:14:23/log/?branch=refs/heads/release` .. _highlightjs: https://highlightjs.org/ .. _dateutil.parser.parse: http://dateutil.readthedocs.io/en/stable/parser.html diff --git a/swh/web/browse/utils.py b/swh/web/browse/utils.py index b29cad4ca..41df77c5d 100644 --- a/swh/web/browse/utils.py +++ b/swh/web/browse/utils.py @@ -1,531 +1,555 @@ # Copyright (C) 2017-2018 The Software Heritage developers # See the AUTHORS file at the top-level directory of this distribution # License: GNU General Public License version 3, or any later version # See top-level LICENSE file for more information import base64 import dateutil import magic import math import stat import textwrap from django.core.cache import cache from django.utils.safestring import mark_safe from swh.web.common import highlightjs, service from swh.web.common.exc import NotFoundExc from swh.web.common.utils import ( reverse, format_utc_iso_date, parse_timestamp ) def get_directory_entries(sha1_git): """Function that retrieves the content of a SWH directory from the SWH archive. The directories entries are first sorted in lexicographical order. Sub-directories and regular files are then extracted. Args: sha1_git: sha1_git identifier of the directory Returns: A tuple whose first member corresponds to the sub-directories list and second member the regular files list Raises: NotFoundExc if the directory is not found """ cache_entry_id = 'directory_entries_%s' % sha1_git cache_entry = cache.get(cache_entry_id) if cache_entry: return cache_entry entries = list(service.lookup_directory(sha1_git)) entries = sorted(entries, key=lambda e: e['name']) for entry in entries: entry['perms'] = stat.filemode(entry['perms']) dirs = [e for e in entries if e['type'] == 'dir'] files = [e for e in entries if e['type'] == 'file'] cache.set(cache_entry_id, (dirs, files)) return dirs, files def get_mimetype_and_encoding_for_content(content): """Function that returns the mime type and the encoding associated to a content buffer using the magic module under the hood. Args: content (bytes): a content buffer Returns: A tuple (mimetype, encoding), for instance ('text/plain', 'us-ascii'), associated to the provided content. """ magic_result = magic.detect_from_content(content) return magic_result.mime_type, magic_result.encoding def request_content(query_string): """Function that retrieves a SWH content from the SWH archive. Raw bytes content is first retrieved, then the content mime type. If the mime type is not stored in the archive, it will be computed using Python magic module. Args: query_string: a string of the form "[ALGO_HASH:]HASH" where optional ALGO_HASH can be either *sha1*, *sha1_git*, *sha256*, or *blake2s256* (default to *sha1*) and HASH the hexadecimal representation of the hash value Returns: A tuple whose first member corresponds to the content raw bytes and second member the content mime type Raises: NotFoundExc if the content is not found """ content_data = service.lookup_content(query_string) content_raw = service.lookup_content_raw(query_string) content_data['raw_data'] = content_raw['data'] filetype = service.lookup_content_filetype(query_string) language = service.lookup_content_language(query_string) license = service.lookup_content_license(query_string) if filetype: mimetype = filetype['mimetype'] encoding = filetype['encoding'] else: mimetype, encoding = \ get_mimetype_and_encoding_for_content(content_data['raw_data']) content_data['mimetype'] = mimetype content_data['encoding'] = encoding # encode textual content to utf-8 if needed if mimetype.startswith('text/') and 'ascii' not in encoding \ and 'utf-8' not in encoding: content_data['raw_data'] = \ content_data['raw_data'].decode(encoding).encode('utf-8') if language: content_data['language'] = language['lang'] else: content_data['language'] = 'not detected' if license: content_data['licenses'] = ', '.join(license['licenses']) else: content_data['licenses'] = 'not detected' return content_data _browsers_supported_image_mimes = set(['image/gif', 'image/png', 'image/jpeg', 'image/bmp', 'image/webp']) def prepare_content_for_display(content_data, mime_type, path): """Function that prepares a content for HTML display. The function tries to associate a programming language to a content in order to perform syntax highlighting client-side using highlightjs. The language is determined using either the content filename or its mime type. If the mime type corresponds to an image format supported by web browsers, the content will be encoded in base64 for displaying the image. Args: content_data (bytes): raw bytes of the content mime_type (string): mime type of the content path (string): path of the content including filename Returns: A dict containing the content bytes (possibly different from the one provided as parameter if it is an image) under the key 'content_data and the corresponding highlightjs language class under the key 'language'. """ language = highlightjs.get_hljs_language_from_filename(path) if not language: language = highlightjs.get_hljs_language_from_mime_type(mime_type) if not language: language = 'nohighlight-swh' elif mime_type.startswith('application/'): mime_type = mime_type.replace('application/', 'text/') if mime_type.startswith('image/'): if mime_type in _browsers_supported_image_mimes: content_data = base64.b64encode(content_data) else: content_data = None return {'content_data': content_data, 'language': language} def get_origin_visits(origin_info): """Function that returns the list of visits for a swh origin. That list is put in cache in order to speedup the navigation in the swh web browse ui. Args: origin_id (int): the id of the swh origin to fetch visits from Returns: A list of dict describing the origin visits:: [{'date': , 'origin': , 'status': <'full' | 'partial'>, 'visit': }, ... ] Raises: NotFoundExc if the origin is not found """ cache_entry_id = 'origin_%s_visits' % origin_info['id'] cache_entry = cache.get(cache_entry_id) if cache_entry: return cache_entry origin_visits = [] per_page = service.MAX_LIMIT last_visit = None while 1: visits = list(service.lookup_origin_visits(origin_info['id'], last_visit=last_visit, per_page=per_page)) origin_visits += visits if len(visits) < per_page: break else: if not last_visit: last_visit = per_page else: last_visit += per_page def _visit_sort_key(visit): ts = dateutil.parser.parse(visit['date']).timestamp() return ts + (float(visit['visit']) / 10e3) for v in origin_visits: del v['metadata'] origin_visits = [dict(t) for t in set([tuple(d.items()) for d in origin_visits])] origin_visits = sorted(origin_visits, key=lambda v: _visit_sort_key(v)) cache.set(cache_entry_id, origin_visits) return origin_visits def get_origin_visit(origin_info, visit_ts=None, visit_id=None): """Function that returns information about a SWH visit for a given origin. The visit is retrieved from a provided timestamp. The closest visit from that timestamp is selected. Args: origin_info (dict): a dict filled with origin information (id, url, type) visit_ts (int or str): an ISO date string or Unix timestamp to parse Returns: A dict containing the visit info as described below:: {'origin': 2, 'date': '2017-10-08T11:54:25.582463+00:00', 'metadata': {}, 'visit': 25, 'status': 'full'} """ visits = get_origin_visits(origin_info) if not visits: raise NotFoundExc('No SWH visit associated to origin with' ' type %s and url %s!' % (origin_info['type'], origin_info['url'])) if visit_id: visit = [v for v in visits if v['visit'] == int(visit_id)] if len(visit) == 0: raise NotFoundExc( 'Visit with id %s for origin with type %s' ' and url %s not found!' % (visit_id, origin_info['type'], origin_info['url'])) return visit[0] if not visit_ts: return visits[-1] parsed_visit_ts = math.floor(parse_timestamp(visit_ts).timestamp()) visit_idx = None for i, visit in enumerate(visits): ts = math.floor(parse_timestamp(visit['date']).timestamp()) if i == 0 and parsed_visit_ts <= ts: return visit elif i == len(visits) - 1: if parsed_visit_ts >= ts: return visit else: next_ts = math.floor( parse_timestamp(visits[i+1]['date']).timestamp()) if parsed_visit_ts >= ts and parsed_visit_ts < next_ts: if (parsed_visit_ts - ts) < (next_ts - parsed_visit_ts): visit_idx = i break else: visit_idx = i+1 break if visit_idx: visit = visits[visit_idx] while visit_idx < len(visits) - 1 and \ visit['date'] == visits[visit_idx+1]['date']: visit_idx = visit_idx + 1 visit = visits[visit_idx] return visit else: raise NotFoundExc( 'Visit with timestamp %s for origin with type %s and url %s not found!' % # noqa (visit_ts, origin_info['type'], origin_info['url'])) -def get_origin_visit_branches(origin_info, visit_ts=None, visit_id=None): - """Function that returns the list of branches associated to - a swh origin for a given visit. +def get_origin_visit_occurrences(origin_info, visit_ts=None, visit_id=None): + """Function that returns the lists of branches and releases + associated to a swh origin for a given visit. The visit is expressed by a timestamp. In the latter case, the closest visit from the provided timestamp will be used. If no visit parameter is provided, it returns the list of branches found for the latest visit. That list is put in cache in order to speedup the navigation in the swh web browse ui. Args: origin_info (dict): a dict filled with origin information (id, url, type) visit_ts (int or str): an ISO date string or Unix timestamp to parse + visit_id (int): optional visit id for desambiguation in case + several visits have the same timestamp Returns: A tuple with two members. The first one is a list of dict describing the origin branches for the given visit:: [{'name': , 'revision': , 'directory': }, ... ] - The second one is the ISO date string corresponding to the associated - SWH visit. + The second one is a list of dict describing the origin branches + for the given visit. Raises: NotFoundExc if the origin or its visit are not found """ visit_info = get_origin_visit(origin_info, visit_ts, visit_id) visit_id = visit_info['visit'] - cache_entry_id = 'origin_%s_visit_%s_branches' % (origin_info['id'], - visit_id) + cache_entry_id = 'origin_%s_visit_%s_occurrences' % (origin_info['id'], + visit_id) cache_entry = cache.get(cache_entry_id) if cache_entry: - return cache_entry + return cache_entry['branches'], cache_entry['releases'] origin_visit_data = service.lookup_origin_visit(origin_info['id'], visit_id) branches = [] + releases = [] revision_ids = [] + releases_ids = [] occurrences = origin_visit_data['occurrences'] for key in sorted(occurrences.keys()): if occurrences[key]['target_type'] == 'revision': branches.append({'name': key, 'revision': occurrences[key]['target']}) revision_ids.append(occurrences[key]['target']) + elif occurrences[key]['target_type'] == 'release': + releases_ids.append(occurrences[key]['target']) + + releases_info = service.lookup_release_multiple(releases_ids) + for release in releases_info: + releases.append({'name': release['name'], + 'release': release['id'], + 'revision': release['target']}) + revision_ids.append(release['target']) revisions = service.lookup_revision_multiple(revision_ids) branches_to_remove = [] + releases_to_remove = [] for idx, revision in enumerate(revisions): - if revision: - branches[idx]['directory'] = revision['directory'] + if idx < len(branches): + if revision: + branches[idx]['directory'] = revision['directory'] + else: + branches_to_remove.append(branches[idx]) else: - branches_to_remove.append(branches[idx]) + rel_idx = idx - len(branches) + if revision: + releases[rel_idx]['directory'] = revision['directory'] + else: + releases_to_remove.append(releases[rel_idx]) for b in branches_to_remove: branches.remove(b) - cache.set(cache_entry_id, branches) + for b in releases_to_remove: + releases.remove(b) + + cache.set(cache_entry_id, {'branches': branches, 'releases': releases}) - return branches + return branches, releases def gen_link(url, link_text): """ Utility function for generating an HTML link to insert in Django templates. Args: url (str): an url link_text (str): the text for the produced link Returns: An HTML link in the form 'link_text' """ link = '%s' % (url, link_text) return mark_safe(link) def gen_person_link(person_id, person_name): """ Utility function for generating a link to a SWH person HTML view to insert in Django templates. Args: person_id (int): a SWH person id person_name (str): the associated person name Returns: An HTML link in the form 'person_name' """ person_url = reverse('browse-person', kwargs={'person_id': person_id}) return gen_link(person_url, person_name) def gen_revision_link(revision_id, shorten_id=False, origin_info=None): """ Utility function for generating a link to a SWH revision HTML view to insert in Django templates. Args: revision_id (int): a SWH revision id shorten_id (boolean): wheter to shorten the revision id to 7 characters for the link text Returns: An HTML link in the form 'revision_id' """ query_params = None if origin_info: query_params = {'origin_type': origin_info['type'], 'origin_url': origin_info['url']} revision_url = reverse('browse-revision', kwargs={'sha1_git': revision_id}, query_params=query_params) if shorten_id: return gen_link(revision_url, revision_id[:7]) else: return gen_link(revision_url, revision_id) def gen_origin_link(origin_info): """ Utility function for generating a link to a SWH origin HTML view to insert in Django templates. Args: origin_info (dict): a dicted filled with origin information (id, type, url) Returns: An HTML link in the form 'Origin: origin_url' """ # noqa origin_browse_url = reverse('browse-origin', kwargs={'origin_type': origin_info['type'], 'origin_url': origin_info['url']}) return gen_link(origin_browse_url, 'Origin: ' + origin_info['url']) def _format_log_entries(revision_log, per_page, origin_info=None): revision_log_data = [] for i, log in enumerate(revision_log): if i == per_page: break revision_log_data.append( {'author': gen_person_link(log['author']['id'], log['author']['name']), 'revision': gen_revision_link(log['id'], True, origin_info), 'message': log['message'], 'message_shorten': textwrap.shorten(log['message'], width=80, placeholder='...'), 'date': format_utc_iso_date(log['date']), 'directory': log['directory']}) return revision_log_data def prepare_revision_log_for_display(revision_log, per_page, revs_breadcrumb, origin_context=False, origin_info=None): """ Utility functions that process raw revision log data for HTML display. Its purpose is to: * add links to relevant SWH browse views * format date in human readable format * truncate the message log It also computes the data needed to generate the links for navigating back and forth in the history log. Args: revision_log (list): raw revision log as returned by the SWH web api per_page (int): number of log entries per page revs_breadcrumb (str): breadcrumbs of revisions navigated so far, in the form 'rev1[/rev2/../revN]'. Each revision corresponds to the first one displayed in the HTML view for history log. origin_context (boolean): wheter or not the revision log is browsed from an origin view. """ current_rev = revision_log[0]['id'] next_rev = None prev_rev = None next_revs_breadcrumb = None prev_revs_breadcrumb = None if len(revision_log) == per_page + 1: prev_rev = revision_log[-1]['id'] prev_rev_bc = current_rev if origin_context: prev_rev_bc = prev_rev if revs_breadcrumb: revs = revs_breadcrumb.split('/') next_rev = revs[-1] if len(revs) > 1: next_revs_breadcrumb = '/'.join(revs[:-1]) if len(revision_log) == per_page + 1: prev_revs_breadcrumb = revs_breadcrumb + '/' + prev_rev_bc else: prev_revs_breadcrumb = prev_rev_bc return {'revision_log_data': _format_log_entries(revision_log, per_page, origin_info), 'prev_rev': prev_rev, 'prev_revs_breadcrumb': prev_revs_breadcrumb, 'next_rev': next_rev, 'next_revs_breadcrumb': next_revs_breadcrumb} diff --git a/swh/web/browse/views/origin.py b/swh/web/browse/views/origin.py index 588f5cece..28632a4a4 100644 --- a/swh/web/browse/views/origin.py +++ b/swh/web/browse/views/origin.py @@ -1,716 +1,736 @@ # Copyright (C) 2017-2018 The Software Heritage developers # See the AUTHORS file at the top-level directory of this distribution # License: GNU General Public License version 3, or any later version # See top-level LICENSE file for more information import dateutil import json from distutils.util import strtobool from django.http import HttpResponse from django.shortcuts import render from django.utils.safestring import mark_safe from django.template.defaultfilters import filesizeformat from swh.web.common import service from swh.web.common.utils import ( gen_path_info, reverse, format_utc_iso_date ) from swh.web.common.exc import NotFoundExc, handle_view_exception from swh.web.browse.utils import ( - get_origin_visits, get_origin_visit, get_origin_visit_branches, + get_origin_visits, get_origin_visit, get_origin_visit_occurrences, get_directory_entries, request_content, prepare_content_for_display, gen_link, prepare_revision_log_for_display, gen_origin_link ) from swh.web.browse.browseurls import browse_route -def _get_origin_branches_and_url_args(origin_info, timestamp, visit_id): - branches = get_origin_visit_branches(origin_info, timestamp, visit_id) +def _get_origin_url_args(origin_info, timestamp): url_args = {'origin_type': origin_info['type'], 'origin_url': origin_info['url']} if timestamp: url_args['timestamp'] = format_utc_iso_date(timestamp, '%Y-%m-%dT%H:%M:%S') + return url_args - return branches, url_args +def _occurrence_not_found(origin_info, timestamp, + branch_type, occurrence, occurrences, + visit_id=None): + """ + Utility function to raise an exception when a specified branch/release + can not be found. + """ + if branch_type: + occ_type = 'Branch' + occ_type_plural = 'branches' + else: + occ_type = 'Release' + occ_type_plural = 'releases' -def _raise_exception_if_branch_not_found(origin_info, timestamp, - branch, branches, visit_id=None): if visit_id: - if len(branches) == 0: - raise NotFoundExc('Origin with type %s and url %s is empty' - ' for visit with id %s! No existing branches' - ' were found!' % (origin_info['type'], - origin_info['url'], visit_id)) + if len(occurrences) == 0: + raise NotFoundExc('Origin with type %s and url %s' + ' for visit with id %s has an empty list' + ' of %s!' % (origin_info['type'], + origin_info['url'], visit_id, + occ_type_plural)) else: - raise NotFoundExc('Branch %s associated to visit with' + raise NotFoundExc('%s %s associated to visit with' ' id %s for origin with type %s and url %s' - ' not found!' % (branch, visit_id, + ' not found!' % (occ_type, occurrence, visit_id, origin_info['type'], origin_info['url'])) else: - if len(branches) == 0: - raise NotFoundExc('Origin with type %s and url %s is empty' - ' for visit with timestamp %s! No existing' - ' branches were found!' % (origin_info['type'], - origin_info['url'], - timestamp)) + if len(occurrences) == 0: + raise NotFoundExc('Origin with type %s and url %s' + ' for visit with timestamp %s has an empty list' + ' of %s!' % (origin_info['type'], + origin_info['url'], + timestamp, occ_type_plural)) else: - raise NotFoundExc('Branch %s associated to visit with' + raise NotFoundExc('%s %s associated to visit with' ' timestamp %s for origin with type %s' - ' and url %s not found!' % (branch, timestamp, + ' and url %s not found!' % (occ_type, occurrence, + timestamp, origin_info['type'], origin_info['url'])) def _get_branch(branches, branch_name): """ Utility function to get a specific branch from an origin branches list. Its purpose is to get the default HEAD branch as some SWH origin (e.g those with svn type) does not have it. In that latter case, check if there is a master branch instead and returns it. """ filtered_branches = \ [b for b in branches if b['name'].endswith(branch_name)] if len(filtered_branches) > 0: return filtered_branches[0] elif branch_name == 'HEAD': filtered_branches = \ [b for b in branches if b['name'].endswith('master')] if len(filtered_branches) > 0: return filtered_branches[0] elif len(branches) > 0: return branches[0] return None +def _get_release(releases, release_name): + filtered_releases = \ + [r for r in releases if r['name'] == release_name] + if len(filtered_releases) > 0: + return filtered_releases[0] + else: + return None + + +def _process_origin_request(request, origin_type, origin_url, + timestamp, path, browse_view_name): + """ + Utility function to perform common input request processing + for origin context views. + """ + + request_data = {} + + origin_info = service.lookup_origin({ + 'type': origin_type, + 'url': origin_url + }) + + visit_id = request.GET.get('visit_id', None) + + visit_info = get_origin_visit(origin_info, timestamp, visit_id) + + if timestamp: + timestamp = visit_info['date'] + + branches, releases = \ + get_origin_visit_occurrences(origin_info, timestamp, visit_id) + + url_args = _get_origin_url_args(origin_info, timestamp) + + for b in branches: + branch_url_args = dict(url_args) + if path: + b['path'] = path + branch_url_args['path'] = path + b['url'] = reverse(browse_view_name, + kwargs=branch_url_args, + query_params={'branch': b['name'], + 'visit_id': visit_id}) + + for r in releases: + release_url_args = dict(url_args) + if path: + r['path'] = path + release_url_args['path'] = path + r['url'] = reverse(browse_view_name, + kwargs=release_url_args, + query_params={'release': r['name'], + 'visit_id': visit_id}) + + root_sha1_git = None + query_params = {'visit_id': visit_id} + revision_id = request.GET.get('revision', None) + release_name = request.GET.get('release', None) + branch_name = None + + if revision_id: + revision = service.lookup_revision(revision_id) + root_sha1_git = revision['directory'] + branches.append({'name': revision_id, + 'revision': revision_id, + 'directory': root_sha1_git, + 'url': None}) + branch_name = revision_id + query_params['revision'] = revision_id + elif release_name: + release = _get_release(releases, release_name) + if release: + root_sha1_git = release['directory'] + query_params['release'] = release_name + revision_id = release['revision'] + else: + _occurrence_not_found(origin_info, timestamp, False, + release_name, releases, visit_id) + else: + branch_name = request.GET.get('branch', 'HEAD') + branch = _get_branch(branches, branch_name) + if branch: + branch_name = branch['name'] + root_sha1_git = branch['directory'] + query_params['branch'] = branch_name + revision_id = branch['revision'] + else: + _occurrence_not_found(origin_info, timestamp, True, + branch_name, branches, visit_id) + + request_data['origin_info'] = origin_info + request_data['visit_info'] = visit_info + request_data['root_sha1_git'] = root_sha1_git + request_data['url_args'] = url_args + request_data['query_params'] = query_params + request_data['revision_id'] = revision_id + request_data['branches'] = branches + request_data['branch_name'] = branch_name + request_data['releases'] = releases + request_data['release_name'] = release_name + + return request_data + + @browse_route(r'origin/(?P[a-z]+)/url/(?P.+)/visit/(?P.+)/directory/', # noqa r'origin/(?P[a-z]+)/url/(?P.+)/visit/(?P.+)/directory/(?P.+)/', # noqa r'origin/(?P[a-z]+)/url/(?P.+)/directory/', # noqa r'origin/(?P[a-z]+)/url/(?P.+)/directory/(?P.+)/', # noqa view_name='browse-origin-directory') def origin_directory_browse(request, origin_type, origin_url, timestamp=None, path=None): """Django view for browsing the content of a swh directory associated to an origin for a given visit. The url scheme that points to it is the following: * :http:get:`/browse/origin/(origin_type)/url/(origin_url)/directory/[(path)/]` * :http:get:`/browse/origin/(origin_type)/url/(origin_type)/visit/(timestamp)/directory/[(path)/]` Args: request: input django http request origin_type: the type of swh origin (git, svn, hg, ...) origin_url: the url of the swh origin timestamp: optional swh visit timestamp parameter (the last one will be used by default) path: optional path parameter used to navigate in directories reachable from the origin root one branch: optional query parameter that specifies the origin branch from which to retrieve the directory + release: optional query parameter that specifies the origin release + from which to retrieve the directory revision: optional query parameter to specify the origin revision from which to retrieve the directory Returns: The HTML rendering for the content of the directory associated to the provided origin and visit. """ # noqa try: - origin_info = service.lookup_origin({ - 'type': origin_type, - 'url': origin_url - }) - - visit_id = request.GET.get('visit_id', None) - - visit_info = get_origin_visit(origin_info, timestamp, visit_id) - - if timestamp: - timestamp = visit_info['date'] - - branches, url_args = \ - _get_origin_branches_and_url_args(origin_info, timestamp, visit_id) - - for b in branches: - branch_url_args = dict(url_args) - if path: - b['path'] = path - branch_url_args['path'] = path - b['url'] = reverse('browse-origin-directory', - kwargs=branch_url_args, - query_params={'branch': b['name'], - 'visit_id': visit_id}) - - query_params = {'visit_id': visit_id} - - revision_id = request.GET.get('revision', None) - - if revision_id: - revision = service.lookup_revision(revision_id) - root_sha1_git = revision['directory'] - branches.append({'name': revision_id, - 'revision': revision_id, - 'directory': root_sha1_git, - 'url': None}) - branch_name = revision_id - query_params['revision'] = revision_id - else: - branch_name = request.GET.get('branch', 'HEAD') - branch = _get_branch(branches, branch_name) - if branch: - branch_name = branch['name'] - root_sha1_git = branch['directory'] - query_params['branch'] = branch_name - revision_id = branch['revision'] - else: - _raise_exception_if_branch_not_found(origin_info, timestamp, - branch_name, branches, - visit_id) + request_data = _process_origin_request( + request, origin_type, origin_url, timestamp, path, + 'browse-origin-directory') + root_sha1_git = request_data['root_sha1_git'] sha1_git = root_sha1_git if path: dir_info = service.lookup_directory_with_path(root_sha1_git, path) sha1_git = dir_info['target'] dirs, files = get_directory_entries(sha1_git) except Exception as exc: return handle_view_exception(request, exc) + origin_info = request_data['origin_info'] + visit_info = request_data['visit_info'] + url_args = request_data['url_args'] + query_params = request_data['query_params'] + revision_id = request_data['revision_id'] + path_info = gen_path_info(path) breadcrumbs = [] breadcrumbs.append({'name': root_sha1_git[:7], 'url': reverse('browse-origin-directory', kwargs=url_args, query_params=query_params)}) for pi in path_info: bc_url_args = dict(url_args) bc_url_args['path'] = pi['path'] breadcrumbs.append({'name': pi['name'], 'url': reverse('browse-origin-directory', kwargs=bc_url_args, query_params=query_params)}) path = '' if path is None else (path + '/') for d in dirs: bc_url_args = dict(url_args) bc_url_args['path'] = path + d['name'] d['url'] = reverse('browse-origin-directory', kwargs=bc_url_args, query_params=query_params) sum_file_sizes = 0 readme_name = None readme_url = None for f in files: bc_url_args = dict(url_args) bc_url_args['path'] = path + f['name'] f['url'] = reverse('browse-origin-content', kwargs=bc_url_args, query_params=query_params) sum_file_sizes += f['length'] f['length'] = filesizeformat(f['length']) if f['name'].lower().startswith('readme'): readme_name = f['name'] readme_sha1 = f['checksums']['sha1'] readme_url = reverse('browse-content-raw', kwargs={'query_string': readme_sha1}) history_url = reverse('browse-origin-log', kwargs=url_args, query_params=query_params) sum_file_sizes = filesizeformat(sum_file_sizes) browse_dir_url = reverse('browse-directory', kwargs={'sha1_git': sha1_git}) browse_rev_url = reverse('browse-revision', kwargs={'sha1_git': revision_id}, query_params={'origin_type': origin_info['type'], 'origin_url': origin_info['url']}) dir_metadata = {'id': sha1_git, 'browse directory url': browse_dir_url, 'number of regular files': len(files), 'number of subdirectories': len(dirs), 'sum of regular file sizes': sum_file_sizes, 'origin id': origin_info['id'], 'origin type': origin_info['type'], 'origin url': origin_info['url'], 'origin visit date': format_utc_iso_date(visit_info['date']), # noqa 'origin visit id': visit_info['visit'], 'path': '/' + path, 'revision id': revision_id, 'browse revision url': browse_rev_url} return render(request, 'directory.html', {'empty_browse': False, 'heading': 'Directory information', 'top_panel_visible': True, 'top_panel_collapsible': True, 'top_panel_text_left': 'SWH object: Directory', 'top_panel_text_right': gen_origin_link(origin_info), 'swh_object_metadata': dir_metadata, 'main_panel_visible': True, 'dirs': dirs, 'files': files, 'breadcrumbs': breadcrumbs, - 'branches': branches, - 'branch': branch_name, + 'branches': request_data['branches'], + 'branch': request_data['branch_name'], + 'releases': request_data['releases'], + 'release': request_data['release_name'], 'top_right_link': history_url, 'top_right_link_text': mark_safe( '' 'History' ), 'readme_name': readme_name, 'readme_url': readme_url}) @browse_route(r'origin/(?P[a-z]+)/url/(?P.+)/visit/(?P.+)/content/(?P.+)/', # noqa r'origin/(?P[a-z]+)/url/(?P.+)/content/(?P.+)/', # noqa view_name='browse-origin-content') def origin_content_display(request, origin_type, origin_url, path, timestamp=None): """Django view that produces an HTML display of a swh content associated to an origin for a given visit. The url scheme that points to it is the following: * :http:get:`/browse/origin/(origin_type)/url/(origin_url)/content/(path)/` * :http:get:`/browse/origin/(origin_type)/url/(origin_url)/visit/(timestamp)/content/(path)/` Args: request: input django http request origin_type: the type of swh origin (git, svn, hg, ...) origin_url: the url of the swh origin path: path of the content relative to the origin root directory timestamp: optional swh visit timestamp parameter (the last one will be used by default) branch: optional query parameter that specifies the origin branch from which to retrieve the content + release: optional query parameter that specifies the origin release + from which to retrieve the content revision: optional query parameter to specify the origin revision from which to retrieve the content Returns: The HTML rendering of the requested content associated to the provided origin and visit. """ # noqa try: - origin_info = service.lookup_origin({ - 'type': origin_type, - 'url': origin_url - }) - - visit_id = request.GET.get('visit_id', None) - - visit_info = get_origin_visit(origin_info, timestamp, visit_id) - if timestamp: - timestamp = visit_info['date'] - - branches, url_args = \ - _get_origin_branches_and_url_args(origin_info, timestamp, visit_id) - - for b in branches: - bc_url_args = dict(url_args) - bc_url_args['path'] = path - b['url'] = reverse('browse-origin-content', - kwargs=bc_url_args, - query_params={'branch': b['name'], - 'visit_id': visit_id}) - - query_params = {'visit_id': visit_id} - - revision_id = request.GET.get('revision', None) - - if revision_id: - revision = service.lookup_revision(revision_id) - root_sha1_git = revision['directory'] - branches.append({'name': revision_id, - 'revision': revision_id, - 'directory': root_sha1_git, - 'url': None}) - branch_name = revision_id - query_params['revision'] = revision_id - else: - branch_name = request.GET.get('branch', 'HEAD') - branch = _get_branch(branches, branch_name) - if branch: - branch_name = branch['name'] - root_sha1_git = branch['directory'] - query_params['branch'] = branch_name - revision_id = branch['revision'] - else: - _raise_exception_if_branch_not_found(origin_info, timestamp, - branch_name, branches, - visit_id) + request_data = _process_origin_request( + request, origin_type, origin_url, timestamp, path, + 'browse-origin-content') + root_sha1_git = request_data['root_sha1_git'] content_info = service.lookup_directory_with_path(root_sha1_git, path) sha1_git = content_info['target'] query_string = 'sha1_git:' + sha1_git content_data = request_content(query_string) except Exception as exc: return handle_view_exception(request, exc) + url_args = request_data['url_args'] + query_params = request_data['query_params'] + revision_id = request_data['revision_id'] + origin_info = request_data['origin_info'] + visit_info = request_data['visit_info'] + content_display_data = prepare_content_for_display( content_data['raw_data'], content_data['mimetype'], path) filename = None path_info = None breadcrumbs = [] split_path = path.split('/') filename = split_path[-1] path = path.replace(filename, '') path_info = gen_path_info(path) breadcrumbs.append({'name': root_sha1_git[:7], 'url': reverse('browse-origin-directory', kwargs=url_args, query_params=query_params)}) for pi in path_info: bc_url_args = dict(url_args) bc_url_args['path'] = pi['path'] breadcrumbs.append({'name': pi['name'], 'url': reverse('browse-origin-directory', kwargs=bc_url_args, query_params=query_params)}) breadcrumbs.append({'name': filename, 'url': None}) browse_content_url = reverse('browse-content', kwargs={'query_string': query_string}) content_raw_url = reverse('browse-content-raw', kwargs={'query_string': query_string}, query_params={'filename': filename}) browse_rev_url = reverse('browse-revision', kwargs={'sha1_git': revision_id}, query_params={'origin_type': origin_info['type'], 'origin_url': origin_info['url']}) content_metadata = { 'browse content url': browse_content_url, 'sha1 checksum': content_data['checksums']['sha1'], 'sha1_git checksum': content_data['checksums']['sha1_git'], 'sha256 checksum': content_data['checksums']['sha256'], 'blake2s256 checksum': content_data['checksums']['blake2s256'], 'mime type': content_data['mimetype'], 'encoding': content_data['encoding'], 'size': filesizeformat(content_data['length']), 'language': content_data['language'], 'licenses': content_data['licenses'], 'origin id': origin_info['id'], 'origin type': origin_info['type'], 'origin url': origin_info['url'], 'origin visit date': format_utc_iso_date(visit_info['date']), 'origin visit id': visit_info['visit'], 'path': '/' + path, 'filename': filename, 'revision id': revision_id, 'browse revision url': browse_rev_url } return render(request, 'content.html', {'empty_browse': False, 'heading': 'Content information', 'top_panel_visible': True, 'top_panel_collapsible': True, 'top_panel_text_left': 'SWH object: Content', 'top_panel_text_right': gen_origin_link(origin_info), 'swh_object_metadata': content_metadata, 'main_panel_visible': True, 'content': content_display_data['content_data'], 'mimetype': content_data['mimetype'], 'language': content_display_data['language'], 'breadcrumbs': breadcrumbs, - 'branches': branches, - 'branch': branch_name, + 'branches': request_data['branches'], + 'branch': request_data['branch_name'], + 'releases': request_data['releases'], + 'release': request_data['release_name'], 'top_right_link': content_raw_url, 'top_right_link_text': mark_safe( 'Raw File') }) def _gen_directory_link(url_args, query_params, link_text): directory_url = reverse('browse-origin-directory', kwargs=url_args, query_params=query_params) return gen_link(directory_url, link_text) NB_LOG_ENTRIES = 20 @browse_route(r'origin/(?P[a-z]+)/url/(?P.+)/visit/(?P.+)/log/', # noqa r'origin/(?P[a-z]+)/url/(?P.+)/log/', view_name='browse-origin-log') def origin_log_browse(request, origin_type, origin_url, timestamp=None): """Django view that produces an HTML display of revisions history (aka the commit log) associated to a SWH origin. The url scheme that points to it is the following: * :http:get:`/browse/origin/(origin_type)/url/(origin_url)/log/` * :http:get:`/browse/origin/(origin_type)/url/(origin_url)/visit/(timestamp)/log/` Args: request: input django http request origin_type: the type of swh origin (git, svn, hg, ...) origin_url: the url of the swh origin - timestamp: optionnal visit timestamp parameter + timestamp: optional visit timestamp parameter (the last one will be used by default) revs_breadcrumb: query parameter used internally to store the navigation breadcrumbs (i.e. the list of descendant revisions visited so far). - per_page: optionnal query parameter used to specify the number of + per_page: optional query parameter used to specify the number of log entries per page - branch: optionnal query parameter that specifies the origin branch - from which to retrieve the content + branch: optional query parameter that specifies the origin branch + from which to retrieve the commit log + release: optional query parameter that specifies the origin release + from which to retrieve the commit log revision: optional query parameter to specify the origin revision - from which to retrieve the directory + from which to retrieve the commit log Returns: The HTML rendering of revisions history for a given SWH visit. """ # noqa try: - origin_info = service.lookup_origin({ - 'type': origin_type, - 'url': origin_url - }) - - visit_id = request.GET.get('visit_id', None) - - visit_info = get_origin_visit(origin_info, timestamp, visit_id) - if timestamp: - timestamp = visit_info['date'] - - branches, url_args = \ - _get_origin_branches_and_url_args(origin_info, timestamp, visit_id) - - for b in branches: - b['url'] = reverse('browse-origin-log', - kwargs=url_args, - query_params={'branch': b['name'], - 'visit_id': visit_id}) - - revision_id = request.GET.get('revision', None) - revs_breadcrumb = request.GET.get('revs_breadcrumb', None) - branch_name = request.GET.get('branch', 'HEAD') - - if revision_id: - revision = service.lookup_revision(revision_id) - branches.append({'name': revision_id, - 'revision': revision_id, - 'directory': revision['directory'], - 'url': None}) - revision = revision_id - branch_name = revision_id - elif revs_breadcrumb: - revs = revs_breadcrumb.split('/') - revision = revs[-1] - else: - branch = _get_branch(branches, branch_name) - if branch: - branch_name = branch['name'] - revision = branch['revision'] - else: - _raise_exception_if_branch_not_found(origin_info, timestamp, - branch_name, branches, - visit_id) + request_data = _process_origin_request( + request, origin_type, origin_url, timestamp, None, + 'browse-origin-log') + revision_id = request_data['revision_id'] per_page = int(request.GET.get('per_page', NB_LOG_ENTRIES)) - revision_log = service.lookup_revision_log(revision, + revision_log = service.lookup_revision_log(revision_id, limit=per_page+1) revision_log = list(revision_log) except Exception as exc: return handle_view_exception(request, exc) + origin_info = request_data['origin_info'] + visit_info = request_data['visit_info'] + url_args = request_data['url_args'] + query_params = request_data['query_params'] + + query_params['per_page'] = per_page + + revs_breadcrumb = request.GET.get('revs_breadcrumb', None) + + if revs_breadcrumb: + revision_id = revs_breadcrumb.split('/')[-1] + revision_log_display_data = prepare_revision_log_for_display( revision_log, per_page, revs_breadcrumb, origin_context=True, origin_info=origin_info) prev_rev = revision_log_display_data['prev_rev'] prev_revs_breadcrumb = revision_log_display_data['prev_revs_breadcrumb'] prev_log_url = None + query_params['revs_breadcrumb'] = prev_revs_breadcrumb if prev_rev: prev_log_url = \ reverse('browse-origin-log', kwargs=url_args, - query_params={'revs_breadcrumb': prev_revs_breadcrumb, - 'per_page': per_page, - 'branch': branch_name, - 'visit_id': visit_id}) + query_params=query_params) next_rev = revision_log_display_data['next_rev'] next_revs_breadcrumb = revision_log_display_data['next_revs_breadcrumb'] next_log_url = None + query_params['revs_breadcrumb'] = next_revs_breadcrumb if next_rev: next_log_url = \ reverse('browse-origin-log', kwargs=url_args, - query_params={'revs_breadcrumb': next_revs_breadcrumb, - 'per_page': per_page, - 'branch': branch_name, - 'visit_id': visit_id}) + query_params=query_params) revision_log_data = revision_log_display_data['revision_log_data'] for i, log in enumerate(revision_log_data): query_params = { 'revision': revision_log[i]['id'], - 'visit_id': visit_id + 'visit_id': visit_info['visit'] } log['directory'] = _gen_directory_link(url_args, query_params, 'Tree') browse_log_url = reverse('browse-revision-log', - kwargs={'sha1_git': revision}) + kwargs={'sha1_git': revision_id}) revision_metadata = { 'browse revision history url': browse_log_url, 'origin id': origin_info['id'], 'origin type': origin_info['type'], 'origin url': origin_info['url'], 'origin visit date': format_utc_iso_date(visit_info['date']), 'origin visit id': visit_info['visit'] } return render(request, 'revision-log.html', {'empty_browse': False, 'heading': 'Revision history information', 'top_panel_visible': True, 'top_panel_collapsible': True, 'top_panel_text_left': 'SWH object: Revision history', 'top_panel_text_right': gen_origin_link(origin_info), 'swh_object_metadata': revision_metadata, 'main_panel_visible': True, 'revision_log': revision_log_data, 'next_log_url': next_log_url, 'prev_log_url': prev_log_url, 'breadcrumbs': None, - 'branches': branches, - 'branch': branch_name, + 'branches': request_data['branches'], + 'branch': request_data['branch_name'], + 'releases': request_data['releases'], + 'release': request_data['release_name'], 'top_right_link': None, 'top_right_link_text': None, 'include_top_navigation': True, 'no_origin_context': False}) @browse_route(r'origin/(?P[a-z]+)/url/(?P.+)/', view_name='browse-origin') def origin_browse(request, origin_type=None, origin_url=None): """Django view that produces an HTML display of a swh origin identified by its id or its url. The url scheme that points to it is :http:get:`/browse/origin/(origin_type)/url/(origin_url)/`. Args: request: input django http request origin_type: type of origin (git, svn, ...) origin_url: url of the origin (e.g. https://github.com//) Returns: The HMTL rendering for the metadata of the provided origin. """ # noqa try: origin_info = service.lookup_origin({ 'type': origin_type, 'url': origin_url }) origin_visits = get_origin_visits(origin_info) origin_visits.reverse() except Exception as exc: return handle_view_exception(request, exc) origin_info['last swh visit browse url'] = \ reverse('browse-origin-directory', kwargs={'origin_type': origin_type, 'origin_url': origin_url}) origin_visits_data = [] visits_splitted = [] visits_by_year = {} for i, visit in enumerate(origin_visits): visit_date = dateutil.parser.parse(visit['date']) visit_year = str(visit_date.year) url_date = format_utc_iso_date(visit['date'], '%Y-%m-%dT%H:%M:%S') visit['fmt_date'] = format_utc_iso_date(visit['date']) query_params = {} if i < len(origin_visits) - 1: if visit['date'] == origin_visits[i+1]['date']: query_params = {'visit_id': visit['visit']} if i > 0: if visit['date'] == origin_visits[i-1]['date']: query_params = {'visit_id': visit['visit']} visit['browse_url'] = reverse('browse-origin-directory', kwargs={'origin_type': origin_type, 'origin_url': origin_url, 'timestamp': url_date}, query_params=query_params) origin_visits_data.insert(0, {'date': visit_date.timestamp()}) if visit_year not in visits_by_year: # display 3 years by row in visits list view if len(visits_by_year) == 3: visits_splitted.insert(0, visits_by_year) visits_by_year = {} visits_by_year[visit_year] = [] visits_by_year[visit_year].append(visit) if len(visits_by_year) > 0: visits_splitted.insert(0, visits_by_year) return render(request, 'origin.html', {'empty_browse': False, 'heading': 'Origin information', 'top_panel_visible': True, 'top_panel_collapsible': True, 'top_panel_text_left': 'SWH object: Origin', 'top_panel_text_right': 'Url: ' + origin_info['url'], 'swh_object_metadata': origin_info, 'main_panel_visible': True, 'origin_visits_data': origin_visits_data, 'visits_splitted': visits_splitted, 'browse_url_base': '/browse/origin/%s/url/%s/' % (origin_type, origin_url)}) @browse_route(r'origin/search/(?P.+)/', view_name='browse-origin-search') def origin_search(request, url_pattern): """Search for origins whose urls contain a provided string pattern or match a provided regular expression. The search is performed in a case insensitive way. """ offset = int(request.GET.get('offset', '0')) limit = int(request.GET.get('limit', '50')) regexp = request.GET.get('regexp', 'false') results = service.search_origin(url_pattern, offset, limit, bool(strtobool(regexp))) results = json.dumps(list(results), sort_keys=True, indent=4, separators=(',', ': ')) return HttpResponse(results, content_type='application/json') diff --git a/swh/web/static/css/style.css b/swh/web/static/css/style.css index 4925dd1fe..aab6f1859 100644 --- a/swh/web/static/css/style.css +++ b/swh/web/static/css/style.css @@ -1,537 +1,561 @@ /* version: 0.1 date: 21/09/15 author: swh email: swh website: softwareheritage.org version history: /style.css */ @import url(https://fonts.googleapis.com/css?family=Alegreya:400,400italic,700,700italic); @import url(https://fonts.googleapis.com/css?family=Alegreya+Sans:400,400italic,500,500italic,700,700italic,100,300,100italic,300italic); html { height: 100%; } body { font-family: 'Alegreya Sans', sans-serif; font-size: 1.7rem; line-height: 1.5; color: rgba(0, 0, 0, 0.55); padding-bottom: 120px; min-height: 100%; margin: 0; position: relative; } .heading { font-family: 'Alegreya', serif; } .shell, .text { font-size: 0.7em; } .logo img { max-height: 40px; } .logo .navbar-brand { padding: 5px; } .logo .sitename { padding: 15px 5px; } .jumbotron { padding: 0; background-color: rgba(0, 0, 0, 0); position: fixed; top: 0; width: 100%; z-index: 10; } #swh-navbar-collapse { border-top-style: none; border-left-style: none; border-right-style: none; border-bottom: 5px solid; border-image: linear-gradient(to right, rgb(226, 0, 38) 0%, rgb(254, 205, 27) 100%) 1 1 1 1; width: 100%; padding: 5px; } .nav-horizontal { float: right; } h3[id], h4[id], a[id] { /* avoid in-page links covered by navbar */ padding-top: 80px; margin-top: -70px; } h1, h2, h3, h4 { margin: 0; color: #e20026; padding-bottom: 10px; } h1 { font-size: 1.8em; } h2 { font-size: 1.2em; } h3 { font-size: 1.1em; } a { color: rgba(0, 0, 0, 0.75); border-bottom-style: dotted; border-bottom-width: 1px; border-bottom-color: rgb(91, 94, 111); } a:hover { color: black; } ul.dropdown-menu a, .navbar-header a, ul.navbar-nav a { /* No decoration on links in dropdown menu */ border-bottom-style: none; color: #323232; font-weight: 700; } .navbar-header a:hover, ul.navbar-nav a:hover { color: #8f8f8f; } .sitename .first-word, .sitename .second-word { color: rgba(0, 0, 0, 0.75); font-weight: normal; font-size: 1.8rem; } .sitename .first-word { font-family: 'Alegreya Sans', sans-serif; } .sitename .second-word { font-family: 'Alegreya', serif; } ul.dropdown-menu > li, ul.dropdown-menu > li > ul > li { /* No decoration on bullet points in dropdown menu */ list-style-type: none; } .page { margin: 2em auto; width: 35em; border: 5px solid #ccc; padding: 0.8em; background: white; } .entries { list-style: none; margin: 0; padding: 0; } .entries li { margin: 0.8em 1.2em; } .entries li h2 { margin-left: -1em; } .add-entry { font-size: 0.9em; border-bottom: 1px solid #ccc; } .add-entry dl { font-weight: bold; } .metanav { text-align: right; font-size: 0.8em; padding: 0.3em; margin-bottom: 1em; background: #fafafa; } .flash { background: #cee5F5; padding: 0.5em; border: 1px solid #aacbe2; } .error { background: #f0d6d6; padding: 0.5em; } .file-found { color: #23BA49; } .file-notfound { color: #FF4747; } /* Bootstrap custom styling to correctly render multiple * form-controls in an input-group: * github.com/twbs/bootstrap/issues/12732 */ .input-group-field { display: table-cell; vertical-align: middle; border-radius:4px; min-width:1%; white-space: nowrap; } .input-group-field .form-control { border-radius: inherit !important; } .input-group-field:not(:first-child):not(:last-child) { border-radius:0; } .input-group-field:not(:first-child):not(:last-child) .form-control { border-left-width: 0; border-right-width: 0; } .input-group-field:last-child { border-top-left-radius:0; border-bottom-left-radius:0; } .input-group > span:not(:last-child) > button { border-radius: 0; } .multi-input-group > .input-group-btn { vertical-align: bottom; padding: 0; } .dataTables_filter { margin-top: 15px; } .dataTables_filter input { width: 70%; float: right; } tr.api-doc-route-upcoming > td, tr.api-doc-route-upcoming > td > a { font-size: 90%; } tr.api-doc-route-deprecated > td, tr.api-doc-route-deprecated > td > a { color: red; } #back-to-top { display: initial; position: fixed; bottom: 30px; right: 30px; z-index: 10; } #back-to-top a img { display: block; width: 32px; height: 32px; background-size: 32px 32px; text-indent: -999px; overflow: hidden; } .table > thead > tr > th { border-bottom: 1px solid #e20026; } .table > tbody > tr > td { border-style: none; } pre { background-color: #f5f5f5; } .dataTables_wrapper { position: static; } /* breadcrumbs */ .bread-crumbs{ display: inline-block; overflow: hidden; color: rgba(0, 0, 0, 0.55); } bread-crumbs ul { list-style-type: none; } .bread-crumbs li { float: left; list-style-type: none; } .bread-crumbs a { color: rgba(0, 0, 0, 0.75); border-bottom-style: none; } .bread-crumbs a:hover { color: rgba(0, 0, 0, 0.85); text-decoration: underline; } .title-small .bread-crumbs{ margin: -30px 0 25px; } #footer { background-color: #262626; color: hsl(0, 0%, 100%); font-size: 1.2rem; text-align: center; padding-top: 20px; padding-bottom: 20px; position: absolute; bottom: 0; left: 0; right: 0; } #footer a, #footer a:visited { color: hsl(0, 0%, 100%); } #footer a:hover { text-decoration: underline; } .highlightjs pre { background-color: transparent; border-radius: 0px; border-color: transparent; } .hljs { background-color: transparent; white-space: pre; } .scrollable-menu { max-height: 180px; overflow-x: hidden; } .swh-browse-top-navigation { border-bottom: 1px solid #ddd; min-height: 42px; padding: 4px 5px 0px 5px; } .swh-browse-bread-crumbs { font-size: inherit; vertical-align: text-top; margin-bottom: 1px; } .swh-browse-bread-crumbs li:nth-child(n+2)::before { content: ""; display: inline-block; margin: 0 2px; } .swh-metadata-table-row { border-top: 1px solid #ddd !important; } /* for block of numbers */ td.hljs-ln-numbers { -webkit-touch-callout: none; -webkit-user-select: none; -khtml-user-select: none; -moz-user-select: none; -ms-user-select: none; user-select: none; text-align: center; color: #ccc; border-right: 1px solid #CCC; vertical-align: top; padding-right: 5px; /* your custom style here */ } /* for block of code */ td.hljs-ln-code { padding-left: 10px; } .btn-swh { color: #6C6C6C; background-color: #EAEAEA; border-color: #ddd; background-image: linear-gradient(to bottom,#f5f5f5 0,#e8e8e8 100%); background-repeat: repeat-x; outline: none; } .btn-swh:hover, .btn-swh:focus, .btn-swh:active, .btn-swh.active, .open .dropdown-toggle.btn-swh { background-color: #e6ebf1; background-image: linear-gradient(to bottom,#f1f1f1 0,#e6e6e6 100%); border-color: rgb(197, 197, 197); } .btn-swh.disabled, .btn-swh[disabled], fieldset[disabled] .btn-swh, .btn-swh.disabled:hover, .btn-swh[disabled]:hover, fieldset[disabled] .btn-swh:hover, .btn-swh.disabled:focus, .btn-swh[disabled]:focus, fieldset[disabled] .btn-swh:focus, .btn-swh.disabled:active, .btn-swh[disabled]:active, fieldset[disabled] .btn-swh:active, .btn-swh.disabled.active, .btn-swh[disabled].active, fieldset[disabled] .btn-swh.active { background-color: #EAEAEA; border-color: #EAEAEA; } .btn-swh .badge { color: #EAEAEA; background-color: #6C6C6C; } .swh-http-error { margin: 0 auto; text-align: center; } .swh-http-error-head { color: #2d353c; font-size: 30px; } .swh-http-error-code { bottom: 60%; color: #2d353c; font-size: 96px; line-height: 80px; margin-bottom: 10px!important; } .swh-http-error-desc { font-size: 12px; color: #647788; text-align: center; } .swh-http-error-desc pre { display: inline-block; text-align: left; max-width: 800px; white-space: pre-wrap; } .swh-table { border-bottom: none !important; } .swh-counter { font-size: 150%; } .swh-loading { display : none; } .swh-loading.show { display:inline-block; position: fixed; background: white; border: 1px solid black; top: 50%; left: 50%; margin: -50px 0px 0px -50px; text-align: center; z-index:100; } .swh-readme a { outline: none; border: none; } .swh-readme table { border-collapse: collapse; } .swh-readme table, .swh-readme table th, .swh-readme table td { padding: 6px 13px; border: 1px solid #dfe2e5; } .swh-readme table tr:nth-child(even) { background-color: #f2f2f2; } .swh-web-app-link:hover { background-color: #efeff2; } .swh-web-app-link a { text-decoration: none; outline: none; border: none; } .pager a { outline: none; } .swh-content { background-image: none; border: none; background-color: white; } .swh-visit-full { color: green; position: relative; } .swh-visit-full:before { content: "\f00c"; font-family: FontAwesome; left:-20px; position:absolute; top:-2px; } .swh-visit-partial { color: #edc344; position: relative; } .swh-visit-partial:before { content: "\f071"; font-family: FontAwesome; left:-20px; position:absolute; top:-2px; - } \ No newline at end of file + } + + .swh-branches-releases { + min-width: 200px; + } + + .swh-branches-switch, + .swh-releases-switch { + padding: 5px 15px !important; + } + + li.swh-branch:hover, + li.swh-release:hover { + background-color: #e8e8e8; + } + + .swh-branch a, + .swh-release a { + outline:none; + } + + .swh-branch a:hover, + .swh-release a:hover { + text-decoration: none; +} diff --git a/swh/web/templates/browse.html b/swh/web/templates/browse.html index ad192d0d5..cd9017efb 100644 --- a/swh/web/templates/browse.html +++ b/swh/web/templates/browse.html @@ -1,152 +1,152 @@ {% extends "layout.html" %} {% load swh_templatetags %} {% block title %}{{ heading }} – Software Heritage archive {% endblock %} {% block navbar-content %} -