68 Commits
0.01 ... 0.15

Author SHA1 Message Date
Alberto Bertogli
cbb36e087c Implement a "patch" view
This commit implements a "patch" view, with a simple plain-text
representation of a commit, that can be used as a patch file.
2018-10-01 21:39:57 +01:00
Alberto Bertogli
722d765973 markdown: Handle local links
By default, the markdown generator creates links for local files
transparently. For example, "[text](link.md)" will generate
"<a href=link.md>text</a>".

This works fine for absolute and external links, but breaks for links
relative to the repository itself, as git-arr links are of the form
"dir/f=file.ext.html".

So this patch adds a markdown extension to rewrite the links. It uses a
heuristic to detect them, which should work for the vast majority of
common cases.
2018-03-04 20:53:35 +00:00
Alberto Bertogli
5e75a1e7a1 Tune markdown CSS to increase readability
The default CSS is not very comfortable for markdown, as for example the
links are hidden.

This patch makes the markdown CSS tunable by wrapping it into a div, and
then adjusting the default styles to increase readability.
2018-03-04 19:14:49 +00:00
Alberto Bertogli
e1349d418c views: In the summary, make the sections toggable
As an experiment, make the sections of the summary to be toggable. This
can help readability, although it's unclear if it's worth the additional
complexity and could be removed later.
2017-08-27 19:43:36 +01:00
Alberto Bertogli
5def4c9e01 views: Include the root tree in the summary
Including the tree as part of the summary gives a bit more information
and provides an easy path into the tree.

It does clutter things a bit, so this is an experiment and may be
removed later.
2017-08-27 19:17:26 +01:00
Alberto Bertogli
891a944381 git: Don't use an empty pathspec when listing
An empty string as a pathspec element matches all paths, but git has
recently started complaining about it, as it could be problematic for
some operations like rm. In the future, it will be considered an error.

So this patch uses "." instead of the empty pathspec, as recommended.

d426430e6e
2017-08-27 17:37:12 +01:00
Alberto Bertogli
d7f0e4a265 views: Change the "repository" line into "git clone"
We display the location of the repository, but the entire row is not
convenient for copy-pasting.

This patch changes the wording to "git clone" so the entire row can be
copied and pasted into a terminal.

There's a trick, because if we just changed the wording to:

  <td>git clone</td> <td>https://example.com/repo</td>

that would get copied as:

  git clone\thttps://example.com/repo

which does not work well when pasted into a terminal (as the \t gets
"eaten" in most cases).

So this patch changes the HTML to have a space after "clone":

  <td>git clone </td> <td>https://example.com/repo</td>

and the CSS to preserve the space, so the following gets copied:

  git clone \thttps://example.com/repo

which works when pasting on a terminal.
2017-08-27 16:16:56 +01:00
Alberto Bertogli
56b0b34930 style: In the index, make the project names explicit links
For readability, make the project names in the index to be explicit
links.
2017-08-27 15:29:24 +01:00
Alberto Bertogli
9b21bd6f19 style: Normal font sizes, and use monospace for listings
There's a significant amount of overrides to make the font sizes
smaller, but that can hurt readability in some cases. We should try to
use the "natural" sizes as much as possible.

This patch does that, removing a lot of the font sizes and bringing them
to be based on the normal sizes.

It also changes listings to use monospace, for readability.
2017-08-27 15:29:20 +01:00
Alberto Bertogli
c96d0dbea6 style: Make line numbers grey
When using pygments, make the line numbers grey.

This was the intention all along, but the <a> style overrides the <div>
style and the grey colour does not take effect.

This patch fixes the problem by setting the style specifically to <a>
within the line numbers div.
2017-08-27 15:29:10 +01:00
Alberto Bertogli
9c8a6d2408 Add a "prefix" configuration option
This patch adds a "prefix" configuration option, so repositories created
with recursion are named with a prefix.

This can be useful to disambiguate between repositories that are named
the same but live in different directories.
2017-07-30 20:33:37 +01:00
Alberto Bertogli
53155e566a markdown: Enable table and fenced code extensions
This patch enables the table and fenced code extensions in markdown
processing.

Signed-off-by: Alberto Bertogli <albertito@blitiri.com.ar>
2016-11-03 01:45:46 +00:00
Alberto Bertogli
c648cfb593 views: Improve display on mobile browsers
This patch moves the pages to HTML5, and adds some simple meta tags and CSS media
constraints so things render better on mobile browsers, while leaving the
desktop unaffected.

It's still not ideal, though.

Signed-off-by: Alberto Bertogli <albertito@blitiri.com.ar>
2015-11-18 00:29:34 +00:00
Alberto Bertogli
cacf2ee2cc git-arr: Implement an "ignore" option
When having symbolic links to the same repositories (e.g. if you have "repo"
and a "repo.git" linking to it), it can be useful to ignore based on regular
expressions to avoid having duplicates in the output.

Signed-off-by: Alberto Bertogli <albertito@blitiri.com.ar>
2015-11-07 12:04:09 +00:00
Alberto Bertogli
c4e6484bb0 git-arr: Always generate the top level index
The top level index contains a "last updated" field, but it doesn't get
updated if using the --only option, which is very common in post-update hooks,
and causes the date to be stale.

This patch fixes that by always generating the top level index, even if --only
was given.

Signed-off-by: Alberto Bertogli <albertito@blitiri.com.ar>
2015-11-07 12:04:09 +00:00
Eric Sunshine
88dd6fab76 views/tree: signify root directory in page title
The page title in a root tree displays as "git >> repo >> branch >>",
which looks odd and fails to convey the fact that the page represents a
tree. Appending a '/' (for example "git >> repo >> branch >> /") makes
it more obvious that the page shows a tree, in general, and the root
tree, in particular.

Signed-off-by: Eric Sunshine <sunshine@sunshineco.com>
Signed-off-by: Alberto Bertogli <albertito@blitiri.com.ar>
2015-01-24 19:23:18 +00:00
Eric Sunshine
84d628c690 views/blob: suppress double-slash in page title
For blobs in subdirectories, the page title always includes a double
slash between the final directory component and the filename (for
example, "git >> repo >> branch >> doc//readme.txt"). This is unsightly.

git-arr:blob() ensures that the directory passed to views/blob always
has a trailing slash, so we can drop the slash inserted by views/blob
between the directory and the filename.

As a side-effect, this also changes the page title for blobs in the root
directory. Instead of "git >> repo >> branch >> /readme.txt", the title
becomes "git >> repo >> branch >> readme.txt", which is slightly more
aesthetically pleasing.

Signed-off-by: Eric Sunshine <sunshine@sunshineco.com>
Signed-off-by: Alberto Bertogli <albertito@blitiri.com.ar>
2015-01-24 19:23:18 +00:00
Eric Sunshine
5568fd50c2 Repo: retire new_in_branch() and notion of "bound" branch
Binding (or "pegging") a Repo at a particular branch via new_in_branch()
increases the cognitive burden since the reader must maintain a mental
model of which Repo instances are pegged and which are not. This burden
outweighs whatever minor convenience (if any) is gained by pegging the
Repo at a particular branch. It is easier to reason about the code when
the branch name is passed to clients directly rather than indirectly via
a pegged Repo.

Preceding patches retired all callers of new_in_branch(), therefore
remove it.

Signed-off-by: Eric Sunshine <sunshine@sunshineco.com>
Signed-off-by: Alberto Bertogli <albertito@blitiri.com.ar>
2015-01-17 13:11:46 +00:00
Eric Sunshine
89a637660f branch: pass branch name view explicitly
Passing the branch name into the view indirectly via
Repo.new_in_branch() increases cognitive burden, thus outweighing
whatever minor convenience (if any) is gained by doing so. The code is
easier to reason about when the branch name is passed to the view
directly.

Signed-off-by: Eric Sunshine <sunshine@sunshineco.com>
Signed-off-by: Alberto Bertogli <albertito@blitiri.com.ar>
2015-01-17 13:11:43 +00:00
Eric Sunshine
37e731fc2e blob: pass branch name to view explicitly
Passing the branch name into the view indirectly via
Repo.new_in_branch() increases cognitive burden, thus outweighing
whatever minor convenience (if any) is gained by doing so. The code is
easier to reason about when the branch name is passed to the view
directly.

Signed-off-by: Eric Sunshine <sunshine@sunshineco.com>
Signed-off-by: Alberto Bertogli <albertito@blitiri.com.ar>
2015-01-17 13:11:39 +00:00
Eric Sunshine
e6099cf272 tree: pass branch name to view explicitly
Passing the branch name into the view indirectly via
Repo.new_in_branch() increases cognitive burden, thus outweighing
whatever minor convenience (if any) is gained by doing so. The code is
easier to reason about when the branch name is passed to the view
directly.

Signed-off-by: Eric Sunshine <sunshine@sunshineco.com>
Signed-off-by: Alberto Bertogli <albertito@blitiri.com.ar>
2015-01-17 13:11:27 +00:00
Eric Sunshine
46640c68b9 views: blob: render empty blobs specially
Empty (zero-length) blobs are currently rendered by 'pygments'
misleadingly as a single empty line, or, when 'pygments' is unavailable,
as "nothingness" preceding a horizontal rule. In either case, it is
somewhat difficult to glean concrete information about the blob.

Address this by instead rendering summary information about the blob: in
particular, its classification ("empty") and its size ("0 bytes"). This
is analogous to the summary information rendered for binary blobs
("binary" and size).

Signed-off-by: Eric Sunshine <sunshine@sunshineco.com>
Signed-off-by: Alberto Bertogli <albertito@blitiri.com.ar>
2015-01-13 19:51:45 +00:00
Eric Sunshine
c91beccdb0 blob: cap amount of rendered binary blob content
Although hexdump(1)-style rendering of binary blob content may reveal
some meaningful information about the data, it wastes even more storage
space than embedding the raw data itself. However, many binary files
have a "magic number" or other signature near the beginning of the file,
so it is often possible to glean useful information from just the
initial chunk of the file without having the entire content available.

Thus, limiting the rendered data to just an initial chunk saves storage
space while still potentially presenting useful information about the
binary content.

Signed-off-by: Eric Sunshine <sunshine@sunshineco.com>
Signed-off-by: Alberto Bertogli <albertito@blitiri.com.ar>
2015-01-13 19:51:45 +00:00
Eric Sunshine
6f3942ce38 blob: render hexdump(1)-style binary blob content
Raw binary blob content tends to look like "line noise" and is rarely,
if ever, meaningful. A hexdump(1)-style rendering (specifically,
"hexdump -C"), on the other hand, showing runs of hexadecimal byte
values along with an ASCII representation of those bytes can sometimes
reveal useful information about the data.

(A subsequent patch will add the ability to cap the amount of data
rendered in order to reduce storage space requirements.)

Signed-off-by: Eric Sunshine <sunshine@sunshineco.com>
Signed-off-by: Alberto Bertogli <albertito@blitiri.com.ar>
2015-01-13 19:51:44 +00:00
Eric Sunshine
09c2f33f5a blob: render binary blob summary information rather than raw content
Binary blobs are currently rendered as raw data directly into the HTML
output, looking much like "line noise". This is rarely, if ever,
meaningful, and consumes considerable storage space since the entire raw
blob content is embedded in the generated HTML file.

Address this issue by instead emitting summary information about the
blob, such as its classification ("binary") and its size. Other
information can be added as needed.

As in Git itself, a blob is considered binary if a NUL is present in the
first ~8KB.

Signed-off-by: Eric Sunshine <sunshine@sunshineco.com>
Signed-off-by: Alberto Bertogli <albertito@blitiri.com.ar>
2015-01-13 19:51:44 +00:00
Eric Sunshine
58037e57c5 Repo.blob: respect reported blob size
Batch output of git-cat-file has the form:

    <sha1> SP <type> SP <size> LF <contents> LF

It unconditionally includes a trailing line-feed which Repo.blob()
incorrectly returns as part of blob content. For textual blobs, this
extra character is often benign, however, for binary blobs, it can
easily change the meaning of the data in unexpected or disastrous ways.
Fix this by respecting the blob size reported by git-cat-file.

(The alternate approach of unconditionally dropping the final LF also
works, however, respecting the reported size is perhaps a bit more
robust and "correct".)

Signed-off-by: Eric Sunshine <sunshine@sunshineco.com>
Signed-off-by: Alberto Bertogli <albertito@blitiri.com.ar>
2015-01-13 19:51:44 +00:00
Eric Sunshine
50c004f8a5 embed_image_blob: retire reload of image blob
Historically, the 'blob' view was unconditionally handed cooked
(utf8-encoded) blob content, so embed_image_blob(), which requires raw
blob content, has been forced to reload the blob in raw form, which is
ugly and expensive. However, now that the Blob returned by Repo.blob()
is able to vend raw or cooked content, it is no longer necessary for
embed_image_blob() to reload the blob to gain access to the raw content.

Signed-off-by: Eric Sunshine <sunshine@sunshineco.com>
Signed-off-by: Alberto Bertogli <albertito@blitiri.com.ar>
2015-01-13 19:51:44 +00:00
Eric Sunshine
1d79988228 Blob: vend raw or cooked content
Some blob representations require raw blob content, however, the 'blob'
view is unconditionally handed cooked (utf8-encoded) content, thus
representations which need raw content are forced to reload the blob in
raw form, which is ugly and expensive.

The ultimate goal is to eliminate the wasteful blob reloading when raw
content is needed. Toward that end, teach Blob how to vend raw or cooked
content.

Signed-off-by: Eric Sunshine <sunshine@sunshineco.com>
Signed-off-by: Alberto Bertogli <albertito@blitiri.com.ar>
2015-01-13 19:51:44 +00:00
Eric Sunshine
0ba89d75e6 git.py: introduce Blob abstraction
Some blob representations (such as embedded images) require raw blob
content, however, the 'blob' view is unconditionally handed cooked
(utf8-encoded) content, thus representations which need raw content are
forced to reload the blob in raw form, which is ugly and expensive (due
to shelling out to git-cat-file a second time).

The ultimate goal is to eliminate the wasteful blob reloading when raw
content is needed. As a first step, introduce a Blob abstraction to be
returned by Repo.blob() rather than the cooked content. A subsequent
change will flesh out Blob, allowing it to return raw or cooked content
on demand without the client having to specify one or the other when
invoking Repo.blob().

Signed-off-by: Eric Sunshine <sunshine@sunshineco.com>
Signed-off-by: Alberto Bertogli <albertito@blitiri.com.ar>
2015-01-13 19:51:44 +00:00
Eric Sunshine
6b83e32bc1 Repo.blob: employ formal mechanism for requesting raw command output
Sneakily extracting the raw 'fd' from the utf8-encoding wrapper
returned by GitCommand.run() is ugly and fragile. Instead, take
advantage of the new formal API for requesting raw command output.

Signed-off-by: Eric Sunshine <sunshine@sunshineco.com>
Signed-off-by: Alberto Bertogli <albertito@blitiri.com.ar>
2015-01-13 19:51:44 +00:00
Eric Sunshine
43f4132bf1 GitCommand: teach run() how to return raw output stream
Currently, clients which want the raw output from a Git command must
sneakily extract the raw 'fd' from the utf8-encoding wrapper returned
by GitCommand.run(). This is ugly and fragile. Instead, provide a
formal mechanism for requesting raw output.

Signed-off-by: Eric Sunshine <sunshine@sunshineco.com>
Signed-off-by: Alberto Bertogli <albertito@blitiri.com.ar>
2015-01-13 19:51:44 +00:00
Eric Sunshine
66afd72d6d run_git: add option to return raw output stream
Currently, clients which want the raw output from a Git command must
sneakily extract the raw 'fd' from the utf8-encoding wrapper returned
by run_git(). This is ugly and fragile. Instead, provide a formal
mechanism for requesting raw output.

Signed-off-by: Eric Sunshine <sunshine@sunshineco.com>
Signed-off-by: Alberto Bertogli <albertito@blitiri.com.ar>
2015-01-13 19:51:44 +00:00
Eric Sunshine
bb9bad89d1 git-arr: increase default 'max_pages' value
The 'max_pages' default value of 5 is quite low. Coupled with
'commits_per_page' default 50, this allows for only 250 commits, which
is likely unsuitable for even relatively small projects. Options are to
remove the cap altogether or to raise the default limit. At this time,
choose the latter, which should be friendlier to larger projects, in
general, while still guarding against run-away storage space
consumption.

Signed-off-by: Eric Sunshine <sunshine@sunshineco.com>
Signed-off-by: Alberto Bertogli <albertito@blitiri.com.ar>
2015-01-12 09:00:18 +00:00
Eric Sunshine
56fcfd0278 route: recognize hierarchical branch names
Branch names in Git may be hierarchical (for example, "wip/parser/fix"),
however, git-arr's Bottle routing rules do not take this into account.
Fix this shortcoming.

Signed-off-by: Eric Sunshine <sunshine@sunshineco.com>
Signed-off-by: Alberto Bertogli <albertito@blitiri.com.ar>
2015-01-11 21:18:22 +00:00
Eric Sunshine
e930f9e4f7 route: prepare to fix routing of hierarchical branch names
Branch names in Git may be hierarchical (for example, "wip/parser/fix"),
however, git-arr does not take this into account in its Bottle routing
rules.

Unfortunately, when updated to recognize hierarchical branch names, the
rules become ambiguous in their present order since Bottle matches them
in the order registered. The ambiguity results in incorrect matches. For
instance, branch pages (/r/<repo>/b/<bname>/) are matched before tree
pages (/r/<repo>/b/<bname>/t/), however, when branch names can be
hierarchical, a tree path such as "/r/proj/b/branch/t/" also looks like
a branch named "branch/t", and thus undesirably matches the branch rule
rather than the tree rule. This problem can be resolved by adjusting the
order of rules.

Therefore, re-order the rules from most to least specific as a
preparatory step prior to actually fixing them to accept hierarchical
branch names. This is a purely textual relocation.  No functional
changes intended.

Signed-off-by: Eric Sunshine <sunshine@sunshineco.com>
Signed-off-by: Alberto Bertogli <albertito@blitiri.com.ar>
2015-01-11 21:18:22 +00:00
Eric Sunshine
93b161c23e views: fix broken URLs involving hierarchical branch names
Git branch names can be hierarchical (for example, "wip/parser/fix"),
however, git-arr does not take this into account when formulating URLs
on branch, tree, and blobs pages. These URLs are dysfunctional because
it is assumed incorrectly that a single "../" is sufficient to climb
over the branch name when computing relative paths to resources higher
in the hierarchy. This problem manifests as failure to load static
resources (stylesheet, etc.), broken links to commits on branch pages,
and malfunctioning breadcrumb trails.

Fix this problem by computing the the proper number of "../" based upon
the branch name, rather than assuming that a single "../" will work
unconditionally. (This is analogous to the treatment already given to
hierarchical pathnames in tree and blob views.)

Signed-off-by: Eric Sunshine <sunshine@sunshineco.com>
Signed-off-by: Alberto Bertogli <albertito@blitiri.com.ar>
2015-01-11 21:18:22 +00:00
Eric Sunshine
7f2f67629f views: branch/paginate: teach "next" link to respect 'max_pages'
Pagination link "next" does not respect 'max_pages', thus it incorrectly
remains enabled on the final page capped by 'max_pages'. When clicked,
the user is taken to a "404 Page not found" error page, which makes for
a poor user experience.

Fix this problem by teaching the "next" link to respect 'max_pages'.

(As a side-effect, this also causes 'serve' mode to respect 'max_pages',
which was not previously the case. This change of behavior is
appropriate since it brings 'serve' mode, which is intended primarily
for testing, more in line with 'generate' mode.)

Signed-off-by: Eric Sunshine <sunshine@sunshineco.com>
Signed-off-by: Alberto Bertogli <albertito@blitiri.com.ar>
2015-01-11 21:18:22 +00:00
Eric Sunshine
ac105c8383 views: branch/paginate: fix incorrectly enabled "next" link
When the number of commits on a branch page is less than
'commits_per_page', the pagination "next" link is disabled, indicating
correctly that this is the final page. However, if the number of commits
on the branch page is exactly 'commits_per_page', then the "next" link
is incorrectly enabled, even on the final page. When clicked, the user
is taken to a "404 Page not found" error page, which makes for a poor
user experience.

Fix this problem by reliably detecting when the branch page is the final
one. Do so by asking for (but not displaying) one commit more than
actually needed by the page. If the additional commit is successfully
retrieved, then another page definitely follows this one. If not
retrieved, then this is definitely the final page.

(Unfortunately, the seemingly more expedient approach of checking if the
final commit on the current page is a root commit -- has no parents --
is not a reliable indicator that this the final page since a branch may
have multiple root commits due to merging.)

Signed-off-by: Eric Sunshine <sunshine@sunshineco.com>
Signed-off-by: Alberto Bertogli <albertito@blitiri.com.ar>
2015-01-11 21:18:22 +00:00
Eric Sunshine
bebc7fa3f0 repo: diff: add option to show "creation event" diff for root commit
At its inception, Git did not show a "creation event" diff for a
project's root commit since early projects, such as the Linux kernel,
were already well established, and a large root diff was considered
uninteresting noise.

On the other hand, new projects adopting Git typically have small root
commits, and such a "creation event" is likely to have meaning, rather
than being pure noise. Consequently, git-diff-tree gained a --root flag
in dc26bd89 (diff-tree: add "--root" flag to show a root commit as a big
creation event, 2005-05-19), though it was disabled by default.

Displaying the root "creation event" diff, however, became the default
behavior when configuration option 'log.showroot' was added to git-log
in 0f03ca94 (config option log.showroot to show the diff of root
commits; 2006-11-23). And, gitk (belatedly) followed suit when it
learned to respect 'log.showroot' in b2b76d10 (gitk: Teach gitk to
respect log.showroot; 2011-10-04).

By default, these tools now all show the root diff as a "creation
event", however, git-arr suppresses it unconditionally. Resolve this
shortcoming by adding a new git-arr configuration option "rootdiff" to
control the behavior (enabled by default).

Signed-off-by: Eric Sunshine <sunshine@sunshineco.com>
Signed-off-by: Alberto Bertogli <albertito@blitiri.com.ar>
2015-01-11 21:18:22 +00:00
Eric Sunshine
9ef78aaffd git-arr: interpret 'max_pages = 0' as unlimited
By default, git-arr limits the number of pages of commits to 5, however,
it is reasonable to expect that some projects will want all commits to
be shown. Rather than forcing such projects to choose an arbitrarily
large number as the value of 'max_pages', provide a formal mechanism to
specify unlimited commit pages.

Signed-off-by: Eric Sunshine <sunshine@sunshineco.com>
Signed-off-by: Alberto Bertogli <albertito@blitiri.com.ar>
2015-01-11 21:18:18 +00:00
Eric Sunshine
d7604dab4d write_tree: suppress double-slash in blob HTML filename
When emitting a blob in the root tree of a commit, write_tree() composes
the blob's HTML filename with an extra slash before the "f=", like this:

    output/r/repo/b/master/t//f=README.txt.html

Although the double-slash is not harmful on Unix, it is unsightly, and
may be problematic for other platforms or filesystems which interpret
double-slash specially or disallow it. Therefore, suppress the extra
slash for blobs in the root tree.

Signed-off-by: Eric Sunshine <sunshine@sunshineco.com>
Signed-off-by: Alberto Bertogli <albertito@blitiri.com.ar>
2015-01-11 21:18:14 +00:00
Eric Sunshine
aaf2968538 route: commit: match only hexadecimal rather than digits + full alphabet
A human-readable representation of a Git SHA1 commit ID is composed
only of hexadecimal digits, thus there is no need to match against
the full alphabet.

Signed-off-by: Eric Sunshine <sunshine@sunshineco.com>
Signed-off-by: Alberto Bertogli <albertito@blitiri.com.ar>
2015-01-11 21:18:10 +00:00
Eric Sunshine
420afd3206 views: summary: suppress extra horizontal rule when no "master" branch
When a repository has a "master" branch, a short summary of its most
recent commits is shown, followed by a horizontal rule. If there is no
"master" branch, then the commit summary is suppressed, however, the
rule is shown unconditionally, which is ugly, particularly when there
is already a rule following the web_url/git_url block. Therefore,
suppress the "master" branch horizontal rule when not needed. (This is
analogous to how the rule following the web_url/git_url block is
suppressed when that information is not shown).

Signed-off-by: Eric Sunshine <sunshine@sunshineco.com>
Signed-off-by: Alberto Bertogli <albertito@blitiri.com.ar>
2015-01-11 21:18:06 +00:00
Eric Sunshine
605421f2d6 sample.conf: document embed_markdown and embed_images
These repo-specific options were added in 54026b75 (Make embedding
markdown and images configurable per-repo, 2013-11-02) but not
documented.

Signed-off-by: Eric Sunshine <sunshine@sunshineco.com>
Signed-off-by: Alberto Bertogli <albertito@blitiri.com.ar>
2015-01-11 21:18:00 +00:00
Alberto Bertogli
df00293a7c git: Add '--' to "git rev-list" runs to avoid ambiguous arguments
If there is a branch and a file with the same name, git-arr will fail to
generate, as git will complain when running git rev-list.

For example, if there is both a file and a branch called "hooks" in the
repository, git-arr would fail as follows:

=== git-arr running: ['git', '--git-dir=/some/repo', 'rev-list', '--max-count=1', '--header', u'hooks'])
fatal: ambiguous argument 'hooks': both revision and filename
Use '--' to separate paths from revisions, like this:
'git <command> [<revision>...] -- [<file>...]'
Traceback (most recent call last):
  File "./git-arr", line 457, in <module>
    main()
  File "./git-arr", line 452, in main
    skip_index = len(opts.only) > 0)
  File "./git-arr", line 388, in generate
    branch_mtime = r.commit(bn).committer_date.epoch
AttributeError: 'NoneType' object has no attribute 'committer_date'

To fix that, this patch appends a "--" as the last argument to rev-list, which
indicates that it has completed the revision list, which disambiguates the
argument.

While at it, a minor typo in a comment is also fixed.

Signed-off-by: Alberto Bertogli <albertito@blitiri.com.ar>
2014-12-31 17:07:38 +00:00
Alberto Bertogli
7898b2becd git.py: Parse timestamps from UTC, not from local time
The current parsing of dates from git incorrectly uses
datetime.fromtimestamp(), which returns the *local* date and time
corresponding to the given timestamp.

Instead, it should be using datetime.utcfromtimestamp() which returns the UTC
date and time, as the rest of the code expects.

Signed-off-by: Alberto Bertogli <albertito@blitiri.com.ar>
2014-10-05 22:15:54 +01:00
Alberto Bertogli
47d500715a views/tree.html: Fix lambda syntax
Some versions of bottle.py don't deal well with the "if" inside the lambda, so
work around it by just using comparison and simplifying the function.

Signed-off-by: Alberto Bertogli <albertito@blitiri.com.ar>
2014-07-28 23:46:50 +01:00
Vanya Sergeev
eb7cadd64f Enable line number anchors when using pygments HtmlFormatter
Signed-off-by: Vanya Sergeev <vsergeev@gmail.com>
2014-07-03 00:56:19 +01:00
Vanya Sergeev
48a00cb460 Fix one-line 'if' termination in tree, blob templates
The missing '% end' template keyword to these one-line if statements was
causing bottle 0.12.7 to incorrectly indent the following line, leading to an
IndentationError at runtime when the blob and tree templates are compiled.

Signed-off-by: Vanya Sergeev <vsergeev@gmail.com>
2014-06-30 08:45:36 +01:00
Alberto Bertogli
2f65291ef1 Fix committer field in the commit view
The commit view shows the author information in the committer field; this
patch fixes it by showing the appropriate fields.

Signed-off-by: Alberto Bertogli <albertito@blitiri.com.ar>
2013-11-03 10:57:54 +00:00
Alberto Bertogli
f6a75820e8 Work around HTTPError status code issues
It turned out that bottle.py is not backwards-compatible with the status code
change: older versions encode the status in e.status; newer ones use
e.status_code (and e.status became a string).

This patch works around that by trying to pick up which of the two variants we
have, and deciding accordingly.

Signed-off-by: Alberto Bertogli <albertito@blitiri.com.ar>
2013-11-02 23:32:43 +00:00
Alberto Bertogli
e49c69da2e Show the age of a repository in the index, via javascript
This patch adds the age of the repository to the index view, using javascript
to give a nice human string for the age.

When javascript is not available, the element remains hidden.

Signed-off-by: Alberto Bertogli <albertito@blitiri.com.ar>
2013-11-02 22:18:33 +00:00
Alberto Bertogli
6764bfcfd6 Use the status_code attribute to tell 404s appart
Newer versions of bottle have a string in the e.status attribute, and the
status code can be found in e.status_code, which should be backwards
compatible.

Signed-off-by: Alberto Bertogli <albertito@blitiri.com.ar>
2013-11-02 21:15:23 +00:00
Alberto Bertogli
54026b7585 Make embedding markdown and images configurable per-repo
This patch introduces the embed_markdown and embed_images configuration
options, so users can enable and disable those features on a per-repository
basis.

Signed-off-by: Alberto Bertogli <albertito@blitiri.com.ar>
2013-11-02 21:12:50 +00:00
Alberto Bertogli
a42d7da6a4 utils: Make the embedded image code use mimetypes
This patch makes minor changes to the code that handles embedded images,
mostly to make it use mimetypes, and to remove SVG support (at least for now)
due to security concerns.

Signed-off-by: Alberto Bertogli <albertito@blitiri.com.ar>
2013-11-02 19:14:36 +00:00
Vanya Sergeev
21522f8a3a Add embed data URI image blob support 2013-11-02 19:07:59 +00:00
Vanya Sergeev
f62ca211eb Add markdown blob support 2013-11-02 19:03:59 +00:00
Vanya Sergeev
d3bf98ea00 Fix parsing of empty commit messages 2013-10-12 01:19:57 +01:00
Alberto Bertogli
6f5f3c4aa5 Add a post-receive hook
This patch adds a post-receive hook that can be used to trigger a git-arr
update when there is a push to a repository.

Signed-off-by: Alberto Bertogli <albertito@blitiri.com.ar>
2013-03-12 22:09:25 +00:00
Alberto Bertogli
c72278c97c Allow calling the executable from any directory
When the tool is invoked like /path/to/git-arr, it currently fails because
both the serving of static files and bottle templates assume they're on the
current working directory.

This patch fixes that by computing the directories based on the executable
location.

Note this is assuming the static directory and the templates live next to the
executable, which will not always be the case, and eventually it should be
configurable; but it's ok for the time being.

Signed-off-by: Alberto Bertogli <albertito@blitiri.com.ar>
2013-03-10 00:55:56 +00:00
Alberto Bertogli
18e8599bfa Use "cloneurl" as a default for git_url
This patch makes git_url have the same default as gitweb.

Signed-off-by: Alberto Bertogli <albertito@blitiri.com.ar>
2013-03-09 23:23:52 +00:00
Alberto Bertogli
c303c30755 Fix the "--only" option
This patch fixes the --only option, and makes it avoid generating the
top-level index so we don't get a broken one with only the specified
repositories.

The intention is that this option is used in hooks to update the views after a
commit or push.

Signed-off-by: Alberto Bertogli <albertito@blitiri.com.ar>
2013-03-09 23:23:52 +00:00
Alberto Bertogli
9ec2bde5c4 Only guess the lexer if the file starts with "#!"
The lexer guesser based on content is often wrong; to minimize the chances of
that happening, we only use it on files that start with "#!", for which it
usually has smarter rules.

Signed-off-by: Alberto Bertogli <albertito@blitiri.com.ar>
2012-11-27 02:57:31 +00:00
Alberto Bertogli
36db9cc0ee Add a note about pygments in the README
Signed-off-by: Alberto Bertogli <albertito@blitiri.com.ar>
2012-11-21 00:29:43 +00:00
Alberto Bertogli
bad8c52ef2 Fall back to guess the lexer by content
If we can't guess the lexer by the file name, try to guess based on the
content.

This allows pygments to colorize extension-less files, usually scripts.

Signed-off-by: Alberto Bertogli <albertito@blitiri.com.ar>
2012-11-18 14:55:27 +00:00
Alberto Bertogli
62da3ebc08 Use heuristics to decide what to colorize
In practise pygments seems to have a very hard time processing large files and
files with long lines, so try to avoid using it in those cases.

Signed-off-by: Alberto Bertogli <albertito@blitiri.com.ar>
2012-11-18 14:55:22 +00:00
Alberto Bertogli
ba3b2132f5 Improve the way we find repo paths
This patch improves the way we find the path to the repositories, both in the
recursive and in the non-recursive cases.

We now support specifying non-bare repositories directly, and also recursing
on them.

Signed-off-by: Alberto Bertogli <albertito@blitiri.com.ar>
2012-11-11 13:43:02 +00:00
Alberto Bertogli
1c729578b2 Add dependencies and improve contact information to README
Signed-off-by: Alberto Bertogli <albertito@blitiri.com.ar>
2012-11-11 12:53:39 +00:00
19 changed files with 782 additions and 201 deletions

15
README
View File

@@ -19,6 +19,13 @@ information.
Getting started
---------------
You will need Python, and the bottle.py framework (the package is usually
called python-bottle in most distributions).
If pygments is available, it will be used for syntax highlighting, otherwise
everything will work fine, just in black and white.
First, create a configuration file for your repositories. You can start by
copying sample.conf, which has the list of the available options.
@@ -41,9 +48,9 @@ use, by running:
That can be useful when making changes to the software itself.
Where to report bugs
--------------------
Contact
-------
If you want to report bugs, or have any questions or comments, just let me
know at albertito@blitiri.com.ar.
If you want to report bugs, send patches, or have any questions or comments,
just let me know at albertito@blitiri.com.ar.

223
git-arr
View File

@@ -5,9 +5,11 @@ git-arr: A git web html generator.
from __future__ import print_function
import os
import math
import optparse
import os
import re
import sys
try:
import configparser
@@ -20,6 +22,18 @@ import git
import utils
# Tell bottle where to find the views.
# Note this assumes they live next to the executable, and that is not a good
# assumption; but it's good enough for now.
bottle.TEMPLATE_PATH.insert(
0, os.path.abspath(os.path.dirname(sys.argv[0])) + '/views/')
# The path to our static files.
# Note this assumes they live next to the executable, and that is not a good
# assumption; but it's good enough for now.
static_path = os.path.abspath(os.path.dirname(sys.argv[0])) + '/static/'
# The list of repositories is a global variable for convenience. It will be
# populated by load_config().
repos = {}
@@ -33,15 +47,21 @@ def load_config(path):
"""
defaults = {
'tree': 'yes',
'rootdiff': 'yes',
'desc': '',
'recursive': 'no',
'prefix': '',
'commits_in_summary': '10',
'commits_per_page': '50',
'max_pages': '5',
'max_pages': '250',
'web_url': '',
'web_url_file': 'web_url',
'git_url': '',
'git_url_file': 'git_url',
'git_url_file': 'cloneurl',
'embed_markdown': 'yes',
'embed_images': 'no',
'ignore': '',
'generate_patch': 'yes',
}
config = configparser.SafeConfigParser(defaults)
@@ -49,34 +69,43 @@ def load_config(path):
# Do a first pass for general sanity checking and recursive expansion.
for s in config.sections():
if not config.has_option(s, 'path'):
raise configparser.NoOptionError(
'%s is missing the mandatory path' % s)
if config.getboolean(s, 'recursive'):
for path in os.listdir(config.get(s, 'path')):
fullpath = config.get(s, 'path') + '/' + path
if not os.path.exists(fullpath + '/HEAD'):
root = config.get(s, 'path')
prefix = config.get(s, 'prefix')
for path in os.listdir(root):
fullpath = find_git_dir(root + '/' + path)
if not fullpath:
continue
if os.path.exists(fullpath + '/disable_gitweb'):
continue
if config.has_section(path):
section = prefix + path
if config.has_section(section):
continue
config.add_section(path)
config.add_section(section)
for opt, value in config.items(s, raw = True):
config.set(path, opt, value)
config.set(section, opt, value)
config.set(path, 'path', fullpath)
config.set(path, 'recursive', 'no')
config.set(section, 'path', fullpath)
config.set(section, 'recursive', 'no')
# This recursive section is no longer useful.
config.remove_section(s)
for s in config.sections():
fullpath = config.get(s, 'path')
if config.get(s, 'ignore') and re.search(config.get(s, 'ignore'), s):
continue
fullpath = find_git_dir(config.get(s, 'path'))
if not fullpath:
raise ValueError(
'%s: path %s is not a valid git repository' % (
s, config.get(s, 'path')))
config.set(s, 'path', fullpath)
config.set(s, 'name', s)
desc = config.get(s, 'desc')
@@ -88,7 +117,11 @@ def load_config(path):
r.info.commits_in_summary = config.getint(s, 'commits_in_summary')
r.info.commits_per_page = config.getint(s, 'commits_per_page')
r.info.max_pages = config.getint(s, 'max_pages')
if r.info.max_pages <= 0:
r.info.max_pages = sys.maxint
r.info.generate_tree = config.getboolean(s, 'tree')
r.info.root_diff = config.getboolean(s, 'rootdiff')
r.info.generate_patch = config.getboolean(s, 'generate_patch')
r.info.web_url = config.get(s, 'web_url')
web_url_file = fullpath + '/' + config.get(s, 'web_url_file')
@@ -100,8 +133,34 @@ def load_config(path):
if not r.info.git_url and os.path.isfile(git_url_file):
r.info.git_url = open(git_url_file).read()
r.info.embed_markdown = config.getboolean(s, 'embed_markdown')
r.info.embed_images = config.getboolean(s, 'embed_images')
repos[r.name] = r
def find_git_dir(path):
"""Returns the path to the git directory for the given repository.
This function takes a path to a git repository, and returns the path to
its git directory. If the repo is bare, it will be the same path;
otherwise it will be path + '.git/'.
An empty string is returned if the given path is not a valid repository.
"""
def check(p):
"""A dirty check for whether this is a git dir or not."""
# Note silent stderr because we expect this to fail and don't want the
# noise; and also we strip the final \n from the output.
return git.run_git(p,
['rev-parse', '--git-dir'],
silent_stderr = True).read()[:-1]
for p in [ path, path + '/.git' ]:
if check(p):
return p
return ''
def repo_filter(unused_conf):
"""Bottle route filter for repos."""
@@ -133,9 +192,15 @@ def with_utils(f):
"""
utilities = {
'shorten': utils.shorten,
'has_colorizer': utils.has_colorizer,
'can_colorize': utils.can_colorize,
'colorize_diff': utils.colorize_diff,
'colorize_blob': utils.colorize_blob,
'can_markdown': utils.can_markdown,
'markdown_blob': utils.markdown_blob,
'can_embed_image': utils.can_embed_image,
'embed_image_blob': utils.embed_image_blob,
'is_binary': utils.is_binary,
'hexdump': utils.hexdump,
'abort': bottle.abort,
'smstr': git.smstr,
}
@@ -163,14 +228,7 @@ def index():
def summary(repo):
return dict(repo = repo)
@bottle.route('/r/<repo:repo>/b/<bname>/')
@bottle.route('/r/<repo:repo>/b/<bname>/<offset:int>.html')
@bottle.view('branch')
@with_utils
def branch(repo, bname, offset = 0):
return dict(repo = repo.new_in_branch(bname), offset = offset)
@bottle.route('/r/<repo:repo>/c/<cid:re:[0-9a-z]{5,40}>/')
@bottle.route('/r/<repo:repo>/c/<cid:re:[0-9a-f]{5,40}>/')
@bottle.view('commit')
@with_utils
def commit(repo, cid):
@@ -180,8 +238,40 @@ def commit(repo, cid):
return dict(repo = repo, c=c)
@bottle.route('/r/<repo:repo>/b/<bname>/t/')
@bottle.route('/r/<repo:repo>/b/<bname>/t/<dirname:path>/')
@bottle.route('/r/<repo:repo>/c/<cid:re:[0-9a-f]{5,40}>.patch')
@bottle.view('patch',
# Output is text/plain, don't do HTML escaping.
template_settings={"noescape": True})
def patch(repo, cid):
c = repo.commit(cid)
if not c:
bottle.abort(404, 'Commit not found')
bottle.response.content_type = 'text/plain; charset=utf8'
return dict(repo = repo, c=c)
@bottle.route('/r/<repo:repo>/b/<bname:path>/t/f=<fname:path>.html')
@bottle.route('/r/<repo:repo>/b/<bname:path>/t/<dirname:path>/f=<fname:path>.html')
@bottle.view('blob')
@with_utils
def blob(repo, bname, fname, dirname = ''):
if dirname and not dirname.endswith('/'):
dirname = dirname + '/'
dirname = git.smstr.from_url(dirname)
fname = git.smstr.from_url(fname)
path = dirname.raw + fname.raw
content = repo.blob(path, bname)
if content is None:
bottle.abort(404, "File %r not found in branch %s" % (path, bname))
return dict(repo = repo, branch = bname, dirname = dirname, fname = fname,
blob = content)
@bottle.route('/r/<repo:repo>/b/<bname:path>/t/')
@bottle.route('/r/<repo:repo>/b/<bname:path>/t/<dirname:path>/')
@bottle.view('tree')
@with_utils
def tree(repo, bname, dirname = ''):
@@ -190,39 +280,36 @@ def tree(repo, bname, dirname = ''):
dirname = git.smstr.from_url(dirname)
r = repo.new_in_branch(bname)
return dict(repo = r, tree = r.tree(), dirname = dirname)
return dict(repo = repo, branch = bname, tree = repo.tree(bname),
dirname = dirname)
@bottle.route('/r/<repo:repo>/b/<bname>/t/f=<fname:path>.html')
@bottle.route('/r/<repo:repo>/b/<bname>/t/<dirname:path>/f=<fname:path>.html')
@bottle.view('blob')
@bottle.route('/r/<repo:repo>/b/<bname:path>/')
@bottle.route('/r/<repo:repo>/b/<bname:path>/<offset:int>.html')
@bottle.view('branch')
@with_utils
def blob(repo, bname, fname, dirname = ''):
r = repo.new_in_branch(bname)
if dirname and not dirname.endswith('/'):
dirname = dirname + '/'
dirname = git.smstr.from_url(dirname)
fname = git.smstr.from_url(fname)
path = dirname.raw + fname.raw
content = r.blob(path)
if content is None:
bottle.abort(404, "File %r not found in branch %s" % (path, bname))
return dict(repo = r, dirname = dirname, fname = fname, blob = content)
def branch(repo, bname, offset = 0):
return dict(repo = repo, branch = bname, offset = offset)
@bottle.route('/static/<path:path>')
def static(path):
return bottle.static_file(path, root = './static/')
return bottle.static_file(path, root = static_path)
#
# Static HTML generation
#
def generate(output):
def is_404(e):
"""True if e is an HTTPError with status 404, False otherwise."""
# We need this because older bottle.py versions put the status code in
# e.status as an integer, and newer versions make that a string, and using
# e.status_code for the code.
if isinstance(e.status, int):
return e.status == 404
else:
return e.status_code == 404
def generate(output, only = None):
"""Generate static html to the output directory."""
def write_to(path, func_or_str, args = (), mtime = None):
path = output + '/' + path
@@ -290,24 +377,32 @@ def generate(output):
dirname = git.smstr(os.path.dirname(oname.raw))
fname = git.smstr(os.path.basename(oname.raw))
write_to(
'r/%s/b/%s/t/%s/f=%s.html' %
(str(r.name), str(bn), dirname.raw, fname.raw),
'r/%s/b/%s/t/%s%sf=%s.html' %
(str(r.name), str(bn),
dirname.raw, '/' if dirname.raw else '', fname.raw),
blob, (r, bn, fname.url, dirname.url), mtime)
else:
write_to('r/%s/b/%s/t/%s/index.html' %
(str(r.name), str(bn), oname.raw),
tree, (r, bn, oname.url), mtime)
# Always generate the index, to keep the "last updated" time fresh.
write_to('index.html', index())
# We can't call static() because it relies on HTTP headers.
read_f = lambda f: open(f).read()
write_to('static/git-arr.css', read_f, ['static/git-arr.css'],
os.stat('static/git-arr.css').st_mtime)
write_to('static/syntax.css', read_f, ['static/syntax.css'],
os.stat('static/syntax.css').st_mtime)
write_to('static/git-arr.css', read_f, [static_path + '/git-arr.css'],
os.stat(static_path + '/git-arr.css').st_mtime)
write_to('static/git-arr.js', read_f, [static_path + '/git-arr.js'],
os.stat(static_path + '/git-arr.js').st_mtime)
write_to('static/syntax.css', read_f, [static_path + '/syntax.css'],
os.stat(static_path + '/syntax.css').st_mtime)
for r in sorted(repos.values(), key = lambda r: r.name):
rs = sorted(repos.values(), key = lambda r: r.name)
if only:
rs = [r for r in rs if r.name in only]
for r in rs:
write_to('r/%s/index.html' % r.name, summary(r))
for bn in r.branch_names():
commit_count = 0
@@ -316,11 +411,13 @@ def generate(output):
for cid in commit_ids:
write_to('r/%s/c/%s/index.html' % (r.name, cid),
commit, (r, cid))
if r.info.generate_patch:
write_to('r/%s/c/%s.patch' % (r.name, cid), patch, (r, cid))
commit_count += 1
# To avoid regenerating files that have not changed, we will
# instruct write_to() to set their mtime to the branch's committer
# date, and then compare against it to decide wether or not to
# date, and then compare against it to decide whether or not to
# write.
branch_mtime = r.commit(bn).committer_date.epoch
@@ -346,7 +443,7 @@ def generate(output):
# Some repos can have tags pointing to non-commits. This
# happens in the Linux Kernel's v2.6.11, which points directly
# to a tree. Ignore them.
if e.status == 404:
if is_404(e):
print('404 in tag %s (%s)' % (tag_name, obj_id))
else:
raise
@@ -359,6 +456,7 @@ def main():
parser.add_option('-o', '--output', metavar = 'DIR',
help = 'output directory (for generate)')
parser.add_option('', '--only', metavar = 'REPO', action = 'append',
default = [],
help = 'generate/serve only this repository')
opts, args = parser.parse_args()
@@ -367,22 +465,19 @@ def main():
try:
load_config(opts.config)
except configparser.NoOptionError as e:
except (configparser.NoOptionError, ValueError) as e:
print('Error parsing config:', e)
return
if not args:
parser.error('Must specify an action (serve|generate)')
if opts.only:
global repos
repos = [ r for r in repos if r.name in opts.only ]
if args[0] == 'serve':
bottle.run(host = 'localhost', port = 8008, reloader = True)
elif args[0] == 'generate':
if not opts.output:
parser.error('Must specify --output')
generate(output = opts.output)
generate(output = opts.output, only = opts.only)
else:
parser.error('Unknown action %s' % args[0])

93
git.py
View File

@@ -41,7 +41,7 @@ class EncodeWrapper:
return s.decode(self.encoding, errors = self.errors)
def run_git(repo_path, params, stdin = None):
def run_git(repo_path, params, stdin = None, silent_stderr = False, raw = False):
"""Invokes git with the given parameters.
This function invokes git with the given parameters, and returns a
@@ -49,14 +49,23 @@ def run_git(repo_path, params, stdin = None):
"""
params = [GIT_BIN, '--git-dir=%s' % repo_path] + list(params)
stderr = None
if silent_stderr:
stderr = subprocess.PIPE
if not stdin:
p = subprocess.Popen(params, stdin = None, stdout = subprocess.PIPE)
p = subprocess.Popen(params,
stdin = None, stdout = subprocess.PIPE, stderr = stderr)
else:
p = subprocess.Popen(params,
stdin = subprocess.PIPE, stdout = subprocess.PIPE)
stdin = subprocess.PIPE, stdout = subprocess.PIPE,
stderr = stderr)
p.stdin.write(stdin)
p.stdin.close()
if raw:
return p.stdout
# We need to wrap stdout if we want to decode it as utf8, subprocess
# doesn't support us telling it the encoding.
if sys.version_info.major == 3:
@@ -75,6 +84,7 @@ class GitCommand (object):
self._args = list(args)
self._kwargs = {}
self._stdin_buf = None
self._raw = False
self._override = False
for k, v in kwargs:
self.__setattr__(k, v)
@@ -90,6 +100,12 @@ class GitCommand (object):
"""Adds an argument."""
self._args.append(a)
def raw(self, b):
"""Request raw rather than utf8-encoded command output."""
self._override = True
self._raw = b
self._override = False
def stdin(self, s):
"""Sets the contents we will send in stdin."""
self._override = True
@@ -109,7 +125,7 @@ class GitCommand (object):
params.extend(self._args)
return run_git(self._path, params, self._stdin_buf)
return run_git(self._path, params, self._stdin_buf, raw = self._raw)
class SimpleNamespace (object):
@@ -189,11 +205,8 @@ def unquote(s):
class Repo:
"""A git repository."""
def __init__(self, path, branch = None, name = None, info = None):
def __init__(self, path, name = None, info = None):
self.path = path
self.branch = branch
# We don't need these, but provide them for the users' convenience.
self.name = name
self.info = info or SimpleNamespace()
@@ -201,11 +214,13 @@ class Repo:
"""Returns a GitCommand() on our path."""
return GitCommand(self.path, cmd)
def for_each_ref(self, pattern = None, sort = None):
def for_each_ref(self, pattern = None, sort = None, count = None):
"""Returns a list of references."""
cmd = self.cmd('for-each-ref')
if sort:
cmd.sort = sort
if count:
cmd.count = count
if pattern:
cmd.arg(pattern)
@@ -233,11 +248,6 @@ class Repo:
"""Get the names of the tags."""
return ( name for name, _ in self.tags() )
def new_in_branch(self, branch):
"""Returns a new Repo, but on the specific branch."""
return Repo(self.path, branch = branch, name = self.name,
info = self.info)
def commit_ids(self, ref, limit = None):
"""Generate commit ids."""
cmd = self.cmd('rev-list')
@@ -245,6 +255,7 @@ class Repo:
cmd.max_count = limit
cmd.arg(ref)
cmd.arg('--')
for l in cmd.run():
yield l.rstrip('\n')
@@ -265,6 +276,7 @@ class Repo:
cmd.header = None
cmd.arg(ref)
cmd.arg('--')
info_buffer = ''
count = 0
@@ -293,6 +305,8 @@ class Repo:
cmd.patch = None
cmd.numstat = None
cmd.find_renames = None
if (self.info.root_diff):
cmd.root = None
# Note we intentionally do not use -z, as the filename is just for
# reference, and it is safer to let git do the escaping.
@@ -313,18 +327,15 @@ class Repo:
return r
def tree(self, ref = None):
def tree(self, ref):
"""Returns a Tree instance for the given ref."""
if not ref:
ref = self.branch
return Tree(self, ref)
def blob(self, path, ref = None):
"""Returns the contents of the given path."""
if not ref:
ref = self.branch
def blob(self, path, ref):
"""Returns a Blob instance for the given path."""
cmd = self.cmd('cat-file')
cmd.batch = None
cmd.raw(True)
cmd.batch = '%(objectsize)'
if isinstance(ref, unicode):
ref = ref.encode('utf8')
@@ -335,7 +346,16 @@ class Repo:
if not head or head.strip().endswith('missing'):
return None
return out.read()
return Blob(out.read()[:int(head)])
def last_commit_timestamp(self):
"""Return the timestamp of the last commit."""
refs = self.for_each_ref(pattern = 'refs/heads/',
sort = '-committerdate', count = 1)
for obj_id, _, _ in refs:
commit = self.commit(obj_id)
return commit.committer_epoch
return -1
class Commit (object):
@@ -391,7 +411,12 @@ class Commit (object):
@staticmethod
def from_str(repo, buf):
"""Parses git rev-list output, returns a commit object."""
header, raw_message = buf.split('\n\n', 1)
if '\n\n' in buf:
# Header, commit message
header, raw_message = buf.split('\n\n', 1)
else:
# Header only, no commit message
header, raw_message = buf.rstrip(), ' '
header_lines = header.split('\n')
commit_id = header_lines.pop(0)
@@ -426,7 +451,7 @@ class Date:
def __init__(self, epoch, tz):
self.epoch = int(epoch)
self.tz = tz
self.utc = datetime.datetime.fromtimestamp(self.epoch)
self.utc = datetime.datetime.utcfromtimestamp(self.epoch)
self.tz_sec_offset_min = int(tz[1:3]) * 60 + int(tz[4:])
if tz[0] == '-':
@@ -500,7 +525,10 @@ class Tree:
cmd.t = None
cmd.arg(self.ref)
cmd.arg(path)
if not path:
cmd.arg(".")
else:
cmd.arg(path)
for l in cmd.run():
_mode, otype, _oid, size, name = l.split(None, 4)
@@ -520,3 +548,16 @@ class Tree:
# manipulate otherwise.
yield otype, smstr(name), size
class Blob:
"""A git blob."""
def __init__(self, raw_content):
self.raw_content = raw_content
self._utf8_content = None
@property
def utf8_content(self):
if not self._utf8_content:
self._utf8_content = self.raw_content.decode('utf8', 'replace')
return self._utf8_content

14
hooks/README Normal file
View File

@@ -0,0 +1,14 @@
You can use the post-receive hook to automatically generate the repository
view after a push.
To do so, configure in your target repository the following options:
$ git config hooks.git-arr-config /path/to/site.conf
$ git config hooks.git-arr-output /var/www/git/
# Only if the git-arr executable is not on your $PATH.
$ git config hooks.git-arr-path /path/to/git-arr
Then copy the post-receive file to the "hooks" directory in your repository.

58
hooks/post-receive Executable file
View File

@@ -0,0 +1,58 @@
#!/bin/sh
#
# git-arr post-receive hook
#
# This is a script intended to be used as a post-receive hook, which updates
# its git-arr view.
#
# You should place it /path/to/your/repository.git/hooks/.
# Config
# --------
#
# hooks.git-arr-config
# The git-arr configuration file to use. Mandatory.
# Example: /srv/git-arr/site.conf
#
# hooks.git-arr-output
# Directory for the generated output. Mandatory.
# Example: /srv/www/git/
#
# hooks.git-arr-path
# The path to the git-arr executable. Optional, defaults to "git-arr".
#
# hooks.git-arr-repo-name
# The git-arr repository name. Optional, defaults to the path name.
git_arr_config="$(git config --path hooks.git-arr-config)"
git_arr_output="$(git config --path hooks.git-arr-output)"
git_arr_path="$(git config --path hooks.git-arr-path 2> /dev/null)"
git_arr_repo_name="$(git config hooks.git-arr-repo-name 2> /dev/null)"
if [ -z "$git_arr_config" -o -z "$git_arr_output" ]; then
echo "Error: missing config options."
echo "Both hooks.git-arr-config and hooks.git-arr-output must be set."
exit 1
fi
if [ -z "$git_arr_path" ]; then
git_arr_path=git-arr
fi
if [ -z "$git_arr_repo_name" ]; then
PARENT_DIR=$(cd $(dirname "$0")/..; echo "$PWD")
git_arr_repo_name=$(basename "$PARENT_DIR")
fi
echo "Running git-arr"
$git_arr_path --config "$git_arr_config" generate \
--output "$git_arr_output" \
--only "$git_arr_repo_name" > /dev/null
RESULT=$?
if [ $RESULT -ne 0 ]; then
echo "Error running git-arr"
exit $RESULT
fi

View File

@@ -11,6 +11,15 @@ path = /srv/git/repo/
# Useful to disable an expensive operation in very large repositories.
#tree = yes
# Show a "creation event" diff for a root commit? (optional)
# For projects placed under revision control from inception, the root commit
# diff is often meaningful. However, in cases when a well established, large
# project is placed under revision control belatedly, the root commit may
# represent a lump import of the entire project, in which case such a
# "creation event" diff would likely be considered meaningless noise.
# Default: yes
#rootdiff = yes
# How many commits to show in the summary page (optional).
#commits_in_summary = 10
@@ -19,8 +28,9 @@ path = /srv/git/repo/
# Maximum number of per-branch pages for static generation (optional).
# When generating static html, this is the maximum number of pages we will
# generate for each branch's commit listings.
#max_pages = 5
# generate for each branch's commit listings. Zero (0) means unlimited.
# Default: 250
#max_pages = 250
# Project website (optional).
# URL to the project's website. %(name)s will be replaced with the current
@@ -38,8 +48,8 @@ path = /srv/git/repo/
# File name to get the git URLs from (optional).
# If git_url is not set, attempt to get its value from this file.
# Default: "git_url"
#git_url_file = git_url
# Default: "cloneurl" (same as gitweb).
#git_url_file = cloneurl
# Do we look for repositories within this path? (optional).
# This option enables a recursive, 1 level search for repositories within the
@@ -48,6 +58,22 @@ path = /srv/git/repo/
# excluded.
#recursive = no
# Render Markdown blobs (*.md) formatted rather than as raw text? (optional)
# Requires 'markdown' module.
# Default: yes
#embed_markdown = yes
# Render image blobs graphically rather than as raw binary data? (optional)
# Default: no
#embed_images = no
# Ignore repositories that match this regular expression.
# Generally used with recursive = yes, to ignore repeated repositories (for
# example, if using symlinks).
# For ignoring specific repositories, putting a "disable_gitweb" is a much
# better alternative.
# Default: empty (don't ignore)
#ignore = \.git$
# Another repository, we don't generate a tree for it because it's too big.
[linux]

View File

@@ -5,12 +5,10 @@
body {
font-family: sans-serif;
font-size: small;
padding: 0 1em 1em 1em;
}
h1 {
font-size: x-large;
background: #ddd;
padding: 0.3em;
}
@@ -49,13 +47,11 @@ a.explicit:hover, a.explicit:active {
/* Normal table, for listing things like repositories, branches, etc. */
table.nice {
text-align: left;
font-size: small;
}
table.nice td {
padding: 0.15em 0.5em;
}
table.nice td.links {
font-size: smaller;
}
table.nice td.main {
min-width: 10em;
@@ -69,8 +65,11 @@ table.commits td.date {
font-style: italic;
color: gray;
}
table.commits td.subject {
min-width: 32em;
@media (min-width: 600px) {
table.commits td.subject {
min-width: 32em;
}
}
table.commits td.author {
color: gray;
@@ -100,6 +99,37 @@ span.tag {
background-color: #ffff88;
}
/* Projects table */
table.projects td.name a {
color: #038;
}
/* Age of an object.
* Note this is hidden by default as we rely on javascript to show it. */
span.age {
display: none;
color: gray;
font-size: smaller;
}
span.age-band0 {
color: darkgreen;
}
span.age-band1 {
color: green;
}
span.age-band2 {
color: seagreen;
}
/* Toggable titles */
div.toggable-title {
font-weight: bold;
margin-bottom: 0.3em;
}
/* Commit message and diff. */
pre.commit-message {
font-size: large;
@@ -107,7 +137,9 @@ pre.commit-message {
}
pre.diff-body {
/* Note this is only used as a fallback if pygments is not available. */
font-size: medium;
}
table.changed-files {
font-family: monospace;
}
table.changed-files span.lines-added {
color: green;
@@ -126,8 +158,14 @@ div.paginate span.inactive {
}
/* Directory listing. */
table.ls td.name {
min-width: 20em;
@media (min-width: 600px) {
table.ls td.name {
min-width: 20em;
}
}
table.ls {
font-family: monospace;
font-size: larger;
}
table.ls tr.blob td.size {
color: gray;
@@ -136,18 +174,35 @@ table.ls tr.blob td.size {
/* Blob. */
pre.blob-body {
/* Note this is only used as a fallback if pygments is not available. */
font-size: medium;
}
table.blob-binary pre {
padding: 0;
margin: 0;
}
table.blob-binary .offset {
text-align: right;
font-size: x-small;
color: darkgray;
border-right: 1px solid #eee;
}
table.blob-binary tr.etc {
text-align: center;
}
/* Pygments overrides. */
div.linenodiv {
padding-right: 0.5em;
font-size: larger; /* must match div.source_code */
}
div.linenodiv a {
color: gray;
font-size: medium;
}
div.source_code {
background: inherit;
font-size: medium;
font-size: larger;
}
/* Repository information table. */
@@ -156,6 +211,10 @@ table.repo_info tr:hover {
}
table.repo_info td.category {
font-weight: bold;
/* So we can copy-paste rows and preserve spaces, useful for the row:
* git clone | url
*/
white-space: pre-wrap;
}
table.repo_info td {
vertical-align: top;
@@ -166,3 +225,20 @@ span.ctrlchr {
padding: 0 0.2ex 0 0.1ex;
margin: 0 0.2ex 0 0.1ex;
}
/*
* Markdown overrides
*/
/* Colored links (same as explicit links above) */
div.markdown a {
color: #038;
}
div.markdown a:hover, div.markdown a:active {
color: #880000;
}
/* Restrict max width for readability */
div.markdown {
max-width: 55em;
}

73
static/git-arr.js Normal file
View File

@@ -0,0 +1,73 @@
/* Miscellaneous javascript functions for git-arr. */
/* Return the current timestamp. */
function now() {
return (new Date().getTime() / 1000);
}
/* Return a human readable string telling "how long ago" for a timestamp. */
function how_long_ago(timestamp) {
if (timestamp < 0)
return "never";
var seconds = Math.floor(now() - timestamp);
var interval = Math.floor(seconds / (365 * 24 * 60 * 60));
if (interval > 1)
return interval + " years ago";
interval = Math.floor(seconds / (30 * 24 * 60 * 60));
if (interval > 1)
return interval + " months ago";
interval = Math.floor(seconds / (24 * 60 * 60));
if (interval > 1)
return interval + " days ago";
interval = Math.floor(seconds / (60 * 60));
if (interval > 1)
return interval + " hours ago";
interval = Math.floor(seconds / 60);
if (interval > 1)
return interval + " minutes ago";
if (seconds > 1)
return Math.floor(seconds) + " seconds ago";
return "about now";
}
/* Go through the document and replace the contents of the span.age elements
* with a human-friendly variant, and then show them. */
function replace_timestamps() {
var elements = document.getElementsByClassName("age");
for (var i = 0; i < elements.length; i++) {
var e = elements[i];
var timestamp = e.innerHTML;
e.innerHTML = how_long_ago(timestamp);
e.style.display = "inline";
if (timestamp > 0) {
var age = now() - timestamp;
if (age < (2 * 60 * 60))
e.className = e.className + " age-band0";
else if (age < (3 * 24 * 60 * 60))
e.className = e.className + " age-band1";
else if (age < (30 * 24 * 60 * 60))
e.className = e.className + " age-band2";
}
}
}
function toggle(id) {
var e = document.getElementById(id);
if (e.style.display == "") {
e.style.display = "none"
} else if (e.style.display == "none") {
e.style.display = ""
}
}

132
utils.py
View File

@@ -12,14 +12,62 @@ try:
except ImportError:
pygments = None
try:
import markdown
import markdown.treeprocessors
except ImportError:
markdown = None
import base64
import mimetypes
import string
import os.path
def shorten(s, width = 60):
if len(s) < 60:
return s
return s[:57] + "..."
def has_colorizer():
return pygments is not None
def can_colorize(s):
"""True if we can colorize the string, False otherwise."""
if pygments is None:
return False
# Pygments can take a huge amount of time with long files, or with very
# long lines; these are heuristics to try to avoid those situations.
if len(s) > (512 * 1024):
return False
# If any of the first 5 lines is over 300 characters long, don't colorize.
start = 0
for i in range(5):
pos = s.find('\n', start)
if pos == -1:
break
if pos - start > 300:
return False
start = pos + 1
return True
def can_markdown(repo, fname):
"""True if we can process file through markdown, False otherwise."""
if markdown is None:
return False
if not repo.info.embed_markdown:
return False
return fname.endswith(".md")
def can_embed_image(repo, fname):
"""True if we can embed image file in HTML, False otherwise."""
if not repo.info.embed_images:
return False
return (('.' in fname) and
(fname.split('.')[-1].lower() in [ 'jpg', 'jpeg', 'png', 'gif' ]))
def colorize_diff(s):
lexer = lexers.DiffLexer(encoding = 'utf-8')
@@ -30,12 +78,88 @@ def colorize_diff(s):
def colorize_blob(fname, s):
try:
lexer = lexers.guess_lexer_for_filename(fname, s)
lexer = lexers.guess_lexer_for_filename(fname, s, encoding = 'utf-8')
except lexers.ClassNotFound:
# Only try to guess lexers if the file starts with a shebang,
# otherwise it's likely a text file and guess_lexer() is prone to
# make mistakes with those.
lexer = lexers.TextLexer(encoding = 'utf-8')
if s.startswith('#!'):
try:
lexer = lexers.guess_lexer(s[:80], encoding = 'utf-8')
except lexers.ClassNotFound:
pass
formatter = HtmlFormatter(encoding = 'utf-8',
cssclass = 'source_code',
linenos = 'table')
linenos = 'table',
anchorlinenos = True,
lineanchors = 'line')
return highlight(s, lexer, formatter)
def markdown_blob(s):
extensions = [
"markdown.extensions.fenced_code",
"markdown.extensions.tables",
RewriteLocalLinksExtension(),
]
return markdown.markdown(s, extensions = extensions)
def embed_image_blob(fname, image_data):
mimetype = mimetypes.guess_type(fname)[0]
return '<img style="max-width:100%;" src="data:{0};base64,{1}" />'.format( \
mimetype, base64.b64encode(image_data))
def is_binary(s):
# Git considers a blob binary if NUL in first ~8KB, so do the same.
return '\0' in s[:8192]
def hexdump(s):
graph = string.ascii_letters + string.digits + string.punctuation + ' '
offset = 0
while s:
t = s[:16]
hexvals = ['%.2x' % ord(c) for c in t]
text = ''.join(c if c in graph else '.' for c in t)
yield offset, ' '.join(hexvals[:8]), ' '.join(hexvals[8:]), text
offset += 16
s = s[16:]
if markdown:
class RewriteLocalLinks(markdown.treeprocessors.Treeprocessor):
"""Rewrites relative links to files, to match git-arr's links.
A link of "[example](a/file.md)" will be rewritten such that it links to
"a/f=file.md.html".
Note that we're already assuming a degree of sanity in the HTML, so we
don't re-check that the path is reasonable.
"""
def run(self, root):
for child in root:
if child.tag == "a":
self.rewrite_href(child)
# Continue recursively.
self.run(child)
def rewrite_href(self, tag):
"""Rewrite an <a>'s href."""
target = tag.get("href")
if not target:
return
if "://" in target or target.startswith("/"):
return
head, tail = os.path.split(target)
new_target = os.path.join(head, "f=" + tail + ".html")
tag.set("href", new_target)
class RewriteLocalLinksExtension(markdown.Extension):
def extendMarkdown(self, md, md_globals):
md.treeprocessors.add(
"RewriteLocalLinks", RewriteLocalLinks(), "_end")

View File

@@ -1,46 +1,86 @@
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<!DOCTYPE html>
<html>
<head>
% if not dirname.raw:
% relroot = './'
% reltree = './'
% else:
% relroot = '../' * (len(dirname.split('/')) - 1)
% reltree = '../' * (len(dirname.split('/')) - 1)
% end
% relroot = reltree + '../' * (len(branch.split('/')) - 1)
<title>git &raquo; {{repo.name}} &raquo;
{{repo.branch}} &raquo; {{dirname.unicode}}/{{fname.unicode}}</title>
{{branch}} &raquo; {{dirname.unicode}}{{fname.unicode}}</title>
<link rel="stylesheet" type="text/css"
href="{{relroot}}../../../../../static/git-arr.css"/>
<link rel="stylesheet" type="text/css"
href="{{relroot}}../../../../../static/syntax.css"/>
<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
<meta name=viewport content="width=device-width, initial-scale=1">
</head>
<body class="tree">
<h1><a href="{{relroot}}../../../../../">git</a> &raquo;
<a href="{{relroot}}../../../">{{repo.name}}</a> &raquo;
<a href="{{relroot}}../">{{repo.branch}}</a> &raquo;
<a href="{{relroot}}">tree</a>
<a href="{{reltree}}../">{{branch}}</a> &raquo;
<a href="{{reltree}}">tree</a>
</h1>
<h3>
<a href="{{relroot}}">[{{repo.branch}}]</a> /
% base = smstr(relroot)
<a href="{{reltree}}">[{{branch}}]</a> /
% base = smstr(reltree)
% for c in dirname.split('/'):
% if not c.raw: continue
% if not c.raw:
% continue
% end
<a href="{{base.url}}{{c.url}}/">{{c.unicode}}</a> /
% base += c + '/'
% end
<a href="">{{!fname.html}}</a>
</h3>
% if has_colorizer():
{{!colorize_blob(fname.unicode, blob)}}
% if len(blob.raw_content) == 0:
<table class="nice">
<tr>
<td>empty &mdash; 0 bytes</td>
</tr>
</table>
% elif can_embed_image(repo, fname.unicode):
{{!embed_image_blob(fname.raw, blob.raw_content)}}
% elif is_binary(blob.raw_content):
<table class="nice blob-binary">
<tr>
<td colspan="4">
binary &mdash; {{'{:,}'.format(len(blob.raw_content))}} bytes
</td>
</tr>
% lim = 256
% for offset, hex1, hex2, text in hexdump(blob.raw_content[:lim]):
<tr>
<td class="offset">{{offset}}</td>
<td><pre>{{hex1}}</pre></td>
<td><pre>{{hex2}}</pre></td>
<td><pre>{{text}}</pre></td>
</tr>
% end
% if lim < len(blob.raw_content):
<tr class="etc">
<td></td>
<td>&hellip;</td>
<td>&hellip;</td>
<td>&hellip;</td>
</tr>
% end
</table>
% elif can_markdown(repo, fname.unicode):
<div class="markdown">
{{!markdown_blob(blob.utf8_content)}}
</div>
% elif can_colorize(blob.utf8_content):
{{!colorize_blob(fname.unicode, blob.utf8_content)}}
% else:
<pre class="blob-body">
{{blob}}
{{blob.utf8_content}}
</pre>
% end

View File

@@ -1,24 +1,27 @@
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<!DOCTYPE html>
<html>
<head>
<title>git &raquo; {{repo.name}} &raquo; {{repo.branch}}</title>
<link rel="stylesheet" type="text/css" href="../../../../static/git-arr.css"/>
% relroot = '../' * (len(branch.split('/')) - 1)
<title>git &raquo; {{repo.name}} &raquo; {{branch}}</title>
<link rel="stylesheet" type="text/css" href="{{relroot}}../../../../static/git-arr.css"/>
<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
<meta name=viewport content="width=device-width, initial-scale=1">
</head>
<body class="branch">
<h1><a href="../../../../">git</a> &raquo;
<a href="../../">{{repo.name}}</a> &raquo;
<a href="./">{{repo.branch}}</a>
<h1><a href="{{relroot}}../../../../">git</a> &raquo;
<a href="{{relroot}}../../">{{repo.name}}</a> &raquo;
<a href="./">{{branch}}</a>
</h1>
<p>
<a class="explicit" href="t/">Browse current source tree</a>
</p>
% commits = repo.commits("refs/heads/" + repo.branch,
% limit = repo.info.commits_per_page,
% commits = repo.commits("refs/heads/" + branch,
% limit = repo.info.commits_per_page + 1,
% offset = repo.info.commits_per_page * offset)
% commits = list(commits)
@@ -26,16 +29,21 @@
% abort(404, "No more commits")
% end
% more = len(commits) > repo.info.commits_per_page
% if more:
% commits = commits[:-1]
% end
% more = more and offset + 1 < repo.info.max_pages
% include paginate nelem = len(commits), max_per_page = repo.info.commits_per_page, offset = offset
% include paginate more = more, offset = offset
% kwargs = dict(repo=repo, commits=commits,
% shorten=shorten, repo_root="../..")
% shorten=shorten, repo_root=relroot + "../..")
% include commit-list **kwargs
<p/>
% include paginate nelem = len(commits), max_per_page = repo.info.commits_per_page, offset = offset
% include paginate more = more, offset = offset
</body>
</html>

View File

@@ -16,7 +16,7 @@
% end
% end
<table class="nice commits">
<table class="nice commits" id="commits">
% refs = repo.refs()
% if not defined("commits"):

View File

@@ -1,11 +1,11 @@
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<!DOCTYPE html>
<html>
<head>
<title>git &raquo; {{repo.name}} &raquo; commit {{c.id[:7]}}</title>
<link rel="stylesheet" type="text/css" href="../../../../static/git-arr.css"/>
<link rel="stylesheet" type="text/css" href="../../../../static/syntax.css"/>
<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
<meta name=viewport content="width=device-width, initial-scale=1">
</head>
<body class="commit">
@@ -22,10 +22,10 @@
<span class="date" title="{{c.author_date}}">
{{c.author_date.utc}} UTC</span></td></tr>
<tr><td>committer</td>
<td><span class="name">{{c.author_name}}</span>
<span class="email">&lt;{{c.author_email}}&gt;</span><br/>
<span class="date" title="{{c.author_date}}">
{{c.author_date.utc}} UTC</span></td></tr>
<td><span class="name">{{c.committer_name}}</span>
<span class="email">&lt;{{c.committer_email}}&gt;</span><br/>
<span class="date" title="{{c.committer_date}}">
{{c.committer_date.utc}} UTC</span></td></tr>
% for p in c.parents:
<tr><td>parent</td>
@@ -55,7 +55,7 @@
<hr/>
% if has_colorizer():
% if can_colorize(c.diff.body):
{{!colorize_diff(c.diff.body)}}
% else:
<pre class="diff-body">

View File

@@ -1,16 +1,17 @@
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<!DOCTYPE html>
<html>
<head>
<title>git</title>
<link rel="stylesheet" type="text/css" href="static/git-arr.css"/>
<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
<meta name=viewport content="width=device-width, initial-scale=1">
<script async src="static/git-arr.js"></script>
</head>
<body class="index">
<body class="index" onload="replace_timestamps()">
<h1>git</h1>
<table class="nice">
<table class="nice projects">
<tr>
<th>project</th>
<th>description</th>
@@ -18,8 +19,9 @@
% for repo in sorted(repos.values(), key = lambda r: r.name):
<tr>
<td><a href="r/{{repo.name}}/">{{repo.name}}</a></td>
<td><a href="r/{{repo.name}}/">{{repo.info.desc}}</a></td>
<td class="name"><a href="r/{{repo.name}}/">{{repo.name}}</a></td>
<td class="desc"><a href="r/{{repo.name}}/">{{repo.info.desc}}</a></td>
<td><span class="age">{{repo.last_commit_timestamp()}}</span></td>
</tr>
%end
</table>

View File

@@ -6,7 +6,7 @@
<span class="inactive">&larr; prev</span>
% end
<span class="sep">|</span>
% if nelem >= max_per_page:
% if more:
<a href="{{offset + 1}}.html">next &rarr;</a>
% else:
<span class="inactive">next &rarr;</span>

8
views/patch.tpl Normal file
View File

@@ -0,0 +1,8 @@
From: {{c.author_name}} <{{c.author_email}}>
Date: {{c.author_date}}
Subject: {{c.subject}}
{{c.body.strip()}}
---
{{c.diff.body}}

View File

@@ -1,10 +1,11 @@
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<!DOCTYPE html>
<html>
<head>
<title>git &raquo; {{repo.name}}</title>
<link rel="stylesheet" type="text/css" href="../../static/git-arr.css"/>
<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
<meta name=viewport content="width=device-width, initial-scale=1">
<script async src="../../static/git-arr.js"></script>
</head>
<body class="summary">
@@ -25,7 +26,7 @@
% end
% if repo.info.git_url:
<tr>
<td class="category">repository</td>
<td class="category">git clone </td>
<td>{{! '<br/>'.join(repo.info.git_url.split())}}</td>
</tr>
% end
@@ -35,19 +36,25 @@
% end
% if "master" in repo.branch_names():
<div class="toggable-title" onclick="toggle('commits')">
<a href="b/master/">commits (master)</a>
</div>
% kwargs = dict(repo = repo, start_ref = "refs/heads/master",
% limit = repo.info.commits_in_summary,
% shorten = shorten, repo_root = ".", offset = 0)
% include commit-list **kwargs
<hr/>
<div class="toggable-title" onclick="toggle('ls')">
<a href="b/master/t/">tree (master)</a>
</div>
% kwargs = dict(repo = repo, tree=repo.tree("master"),
% treeroot="b/master/t", dirname=smstr.from_url(""))
% include tree-list **kwargs
<hr/>
% end
<hr/>
<table class="nice">
<tr>
<th>branches</th>
</tr>
<div class="toggable-title" onclick="toggle('branches')">branches</div>
<table class="nice toggable" id="branches">
% for b in repo.branch_names():
<tr>
<td class="main"><a href="b/{{b}}/">{{b}}</a></td>
@@ -63,11 +70,8 @@
% tags = list(repo.tags())
% if tags:
<table class="nice">
<tr>
<th>tags</th>
</tr>
<div class="toggable-title" onclick="toggle('tags')">tags</div>
<table class="nice toggable" id="tags">
% for name, obj_id in tags:
<tr>
<td><a href="c/{{obj_id}}/">{{name}}</a></td>

16
views/tree-list.html Normal file
View File

@@ -0,0 +1,16 @@
<table class="nice toggable ls" id="ls">
% key_func = lambda (t, n, s): (t != 'tree', n.raw)
% for type, name, size in sorted(tree.ls(dirname.raw), key = key_func):
<tr class="{{type}}">
% if type == "blob":
<td class="name"><a href="{{treeroot}}/f={{name.url}}.html">
{{!name.html}}</a></td>
<td class="size">{{size}}</td>
% elif type == "tree":
<td class="name">
<a class="explicit" href="{{treeroot}}/{{name.url}}/">
{{!name.html}}/</a></td>
% end
</tr>
% end
</table>

View File

@@ -1,54 +1,43 @@
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<!DOCTYPE html>
<html>
<head>
% if not dirname.raw:
% relroot = './'
% reltree = './'
% else:
% relroot = '../' * (len(dirname.split('/')) - 1)
% reltree = '../' * (len(dirname.split('/')) - 1)
% end
% relroot = reltree + '../' * (len(branch.split('/')) - 1)
<title>git &raquo; {{repo.name}} &raquo;
{{repo.branch}} &raquo; {{dirname.unicode}}</title>
{{branch}} &raquo; {{dirname.unicode if dirname.unicode else '/'}}</title>
<link rel="stylesheet" type="text/css"
href="{{relroot}}../../../../../static/git-arr.css"/>
<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
<meta name=viewport content="width=device-width, initial-scale=1">
</head>
<body class="tree">
<h1><a href="{{relroot}}../../../../../">git</a> &raquo;
<a href="{{relroot}}../../../">{{repo.name}}</a> &raquo;
<a href="{{relroot}}../">{{repo.branch}}</a> &raquo;
<a href="{{relroot}}">tree</a>
<a href="{{reltree}}../">{{branch}}</a> &raquo;
<a href="{{reltree}}">tree</a>
</h1>
<h3>
<a href="{{relroot}}">[{{repo.branch}}]</a> /
% base = smstr(relroot)
<a href="{{reltree}}">[{{branch}}]</a> /
% base = smstr(reltree)
% for c in dirname.split('/'):
% if not c.raw: continue
% if not c.raw:
% continue
% end
<a href="{{base.url}}{{c.url}}/">{{c.unicode}}</a> /
% base += c + '/'
% end
</h3>
<table class="nice ls">
% key_func = lambda (t, n, s): (0 if t == 'tree' else 1, n.raw)
% for type, name, size in sorted(tree.ls(dirname.raw), key = key_func):
<tr class="{{type}}">
% if type == "blob":
<td class="name"><a href="./f={{name.url}}.html">
{{!name.html}}</a></td>
<td class="size">{{size}}</td>
% elif type == "tree":
<td class="name">
<a class="explicit" href="./{{name.url}}/">
{{!name.html}}/</a></td>
% end
</tr>
% end
</table>
% kwargs = dict(repo = repo, tree=tree, treeroot=".")
% include tree-list **kwargs
</body>
</html>