コード例 #1
0
ファイル: SummaryPage.java プロジェクト: nhuray/gitblit
  private void insertActivityGraph(List<Metric> metrics) {
    if ((metrics != null)
        && (metrics.size() > 0)
        && GitBlit.getBoolean(Keys.web.generateActivityGraph, true)) {
      IChartData data = WicketUtils.getChartData(metrics);

      ChartProvider provider = new ChartProvider(new Dimension(400, 100), ChartType.LINE, data);
      ChartAxis dateAxis = new ChartAxis(ChartAxisType.BOTTOM);
      dateAxis.setLabels(
          new String[] {
            metrics.get(0).name,
            metrics.get(metrics.size() / 2).name,
            metrics.get(metrics.size() - 1).name
          });
      provider.addAxis(dateAxis);

      ChartAxis commitAxis = new ChartAxis(ChartAxisType.LEFT);
      commitAxis.setLabels(new String[] {"", String.valueOf((int) WicketUtils.maxValue(metrics))});
      provider.addAxis(commitAxis);
      provider.setLineStyles(new LineStyle[] {new LineStyle(2, 4, 0), new LineStyle(0, 4, 1)});
      provider.addShapeMarker(new ShapeMarker(MarkerType.CIRCLE, Color.BLUE, 1, -1, 5));

      add(new Chart("commitsChart", provider));
    } else {
      add(WicketUtils.newBlankImage("commitsChart"));
    }
  }
コード例 #2
0
ファイル: CommitHeaderPanel.java プロジェクト: nhuray/gitblit
 public CommitHeaderPanel(String id, String repositoryName, RevCommit c) {
   super(id);
   add(
       new LinkPanel(
           "shortmessage",
           "title",
           c.getShortMessage(),
           CommitPage.class,
           WicketUtils.newObjectParameter(repositoryName, c.getName())));
   add(new Label("commitid", "(" + c.getName().substring(0, 8) + ")"));
   add(new Label("author", c.getAuthorIdent().getName()));
   add(WicketUtils.createDateLabel("date", c.getAuthorIdent().getWhen(), getTimeZone()));
 }
コード例 #3
0
ファイル: LinkPanel.java プロジェクト: stephlag/gitblit
 public LinkPanel(
     String wicketId,
     String bootstrapIcon,
     String linkCssClass,
     IModel<String> model,
     Class<? extends WebPage> clazz,
     PageParameters parameters,
     boolean newWindow) {
   super(wicketId);
   this.labelModel = model;
   Link<Void> link = null;
   if (parameters == null) {
     link = new BookmarkablePageLink<Void>("link", clazz);
   } else {
     link = new BookmarkablePageLink<Void>("link", clazz, parameters);
   }
   if (newWindow) {
     link.add(new SimpleAttributeModifier("target", "_blank"));
   }
   if (linkCssClass != null) {
     link.add(new SimpleAttributeModifier("class", linkCssClass));
   }
   Label icon = new Label("icon");
   if (StringUtils.isEmpty(bootstrapIcon)) {
     link.add(icon.setVisible(false));
   } else {
     WicketUtils.setCssClass(icon, bootstrapIcon);
     link.add(icon);
   }
   link.add(new Label("label", labelModel).setRenderBodyOnly(true));
   add(link);
 }
コード例 #4
0
 public EditRepositoryPage(PageParameters params) {
   // edit constructor
   super(params);
   isCreate = false;
   String name = WicketUtils.getRepositoryName(params);
   RepositoryModel model = GitBlit.self().getRepositoryModel(name);
   setupPage(model);
 }
コード例 #5
0
ファイル: EditTeamPage.java プロジェクト: kazesberger/gitblit
 public EditTeamPage(PageParameters params) {
   // edit constructor
   super(params);
   isCreate = false;
   String name = WicketUtils.getTeamname(params);
   TeamModel model = app().users().getTeamModel(name);
   setupPage(model);
   setStatelessHint(false);
   setOutputMarkupId(true);
 }
コード例 #6
0
  public GravatarImage(String id, PersonIdent person, int width) {
    super(id);

    String email =
        person.getEmailAddress() == null
            ? person.getName().toLowerCase()
            : person.getEmailAddress().toLowerCase();
    String hash = StringUtils.getMD5(email);
    Link<Void> link =
        new BookmarkablePageLink<Void>(
            "link", GravatarProfilePage.class, WicketUtils.newObjectParameter(hash));
    link.add(new SimpleAttributeModifier("target", "_blank"));
    String url = ActivityUtils.getGravatarThumbnailUrl(email, width);
    ExternalImage image = new ExternalImage("image", url);
    WicketUtils.setCssClass(image, "gravatar");
    link.add(image);
    WicketUtils.setHtmlTooltip(
        link, MessageFormat.format("View Gravatar profile for {0}", person.getName()));
    add(link);
    setVisible(GitBlit.getBoolean(Keys.web.allowGravatar, true));
  }
コード例 #7
0
 @Override
 protected void setLastModified() {
   if (getClass().isAnnotationPresent(CacheControl.class)) {
     CacheControl cacheControl = getClass().getAnnotation(CacheControl.class);
     switch (cacheControl.value()) {
       case PROJECT:
         String projectName = WicketUtils.getProjectName(getPageParameters());
         if (!StringUtils.isEmpty(projectName)) {
           ProjectModel project = getProjectModel(projectName);
           if (project != null) {
             setLastModified(project.lastChange);
           }
         }
         break;
       default:
         super.setLastModified();
     }
   }
 }
コード例 #8
0
ファイル: BasePage.java プロジェクト: yueyaquanBoy/gitblit
  protected void setupPage(String repositoryName, String pageName) {
    add(new Label("title", getPageTitle(repositoryName)));

    String rootLinkUrl =
        app()
            .settings()
            .getString(
                Keys.web.rootLink, urlFor(GitBlitWebApp.get().getHomePage(), null).toString());
    ExternalLink rootLink = new ExternalLink("rootLink", rootLinkUrl);
    WicketUtils.setHtmlTooltip(
        rootLink, app().settings().getString(Keys.web.siteName, Constants.NAME));
    add(rootLink);

    // Feedback panel for info, warning, and non-fatal error messages
    add(new FeedbackPanel("feedback"));

    add(new Label("gbVersion", "v" + Constants.getVersion()));
    if (app().settings().getBoolean(Keys.web.aggressiveHeapManagement, false)) {
      System.gc();
    }
  }
コード例 #9
0
  @Override
  protected void addDropDownMenus(List<PageRegistration> pages) {
    PageParameters params = getPageParameters();

    DropDownMenuRegistration menu = new DropDownMenuRegistration("gb.filters", ProjectPage.class);
    // preserve time filter option on repository choices
    menu.menuItems.addAll(getRepositoryFilterItems(params));

    // preserve repository filter option on time choices
    menu.menuItems.addAll(getTimeFilterItems(params));

    if (menu.menuItems.size() > 0) {
      // Reset Filter
      menu.menuItems.add(
          new DropDownMenuItem(getString("gb.reset"), "p", WicketUtils.getProjectName(params)));
    }

    pages.add(menu);

    DropDownMenuRegistration projects =
        new DropDownMenuRegistration("gb.projects", ProjectPage.class);
    projects.menuItems.addAll(getProjectsMenu());
    pages.add(projects);
  }
コード例 #10
0
ファイル: UserPage.java プロジェクト: LemonKL/gitblit
  private void setup(PageParameters params) {
    setupPage("", "");
    // check to see if we should display a login message
    boolean authenticateView = app().settings().getBoolean(Keys.web.authenticateViewPages, true);
    if (authenticateView && !GitBlitWebSession.get().isLoggedIn()) {
      authenticationError("Please login");
      return;
    }

    String userName = WicketUtils.getUsername(params);
    if (StringUtils.isEmpty(userName)) {
      throw new GitblitRedirectException(GitBlitWebApp.get().getHomePage());
    }

    UserModel user = app().users().getUserModel(userName);
    if (user == null) {
      // construct a temporary user model
      user = new UserModel(userName);
    }

    add(new UserTitlePanel("userTitlePanel", user, user.username));

    UserModel sessionUser = GitBlitWebSession.get().getUser();
    boolean isMyProfile = sessionUser != null && sessionUser.equals(user);

    if (isMyProfile) {
      addPreferences(user);

      if (app().services().isServingSSH()) {
        // show the SSH key management tab
        addSshKeys(user);
      } else {
        // SSH daemon is disabled, hide keys tab
        add(new Label("sshKeysLink").setVisible(false));
        add(new Label("sshKeysTab").setVisible(false));
      }
    } else {
      // visiting user
      add(new Label("preferencesLink").setVisible(false));
      add(new Label("preferencesTab").setVisible(false));

      add(new Label("sshKeysLink").setVisible(false));
      add(new Label("sshKeysTab").setVisible(false));
    }

    List<RepositoryModel> repositories = getRepositories(params);

    Collections.sort(
        repositories,
        new Comparator<RepositoryModel>() {
          @Override
          public int compare(RepositoryModel o1, RepositoryModel o2) {
            // reverse-chronological sort
            return o2.lastChange.compareTo(o1.lastChange);
          }
        });

    final ListDataProvider<RepositoryModel> dp =
        new ListDataProvider<RepositoryModel>(repositories);
    DataView<RepositoryModel> dataView =
        new DataView<RepositoryModel>("repositoryList", dp) {
          private static final long serialVersionUID = 1L;

          @Override
          public void populateItem(final Item<RepositoryModel> item) {
            final RepositoryModel entry = item.getModelObject();

            ProjectRepositoryPanel row =
                new ProjectRepositoryPanel(
                    "repository", getLocalizer(), this, showAdmin, entry, getAccessRestrictions());
            item.add(row);
          }
        };
    add(dataView);
  }
コード例 #11
0
  public HistoryPanel(
      String wicketId,
      final String repositoryName,
      final String objectId,
      final String path,
      Repository r,
      int limit,
      int pageOffset,
      boolean showRemoteRefs) {
    super(wicketId);
    boolean pageResults = limit <= 0;
    int itemsPerPage = GitBlit.getInteger(Keys.web.itemsPerPage, 50);
    if (itemsPerPage <= 1) {
      itemsPerPage = 50;
    }

    RevCommit commit = JGitUtils.getCommit(r, objectId);
    List<PathChangeModel> paths = JGitUtils.getFilesInCommit(r, commit);

    Map<String, SubmoduleModel> submodules = new HashMap<String, SubmoduleModel>();
    for (SubmoduleModel model : JGitUtils.getSubmodules(r, commit.getTree())) {
      submodules.put(model.path, model);
    }

    PathModel matchingPath = null;
    for (PathModel p : paths) {
      if (p.path.equals(path)) {
        matchingPath = p;
        break;
      }
    }
    if (matchingPath == null) {
      // path not in commit
      // manually locate path in tree
      TreeWalk tw = new TreeWalk(r);
      tw.reset();
      tw.setRecursive(true);
      try {
        tw.addTree(commit.getTree());
        tw.setFilter(PathFilterGroup.createFromStrings(Collections.singleton(path)));
        while (tw.next()) {
          if (tw.getPathString().equals(path)) {
            matchingPath =
                new PathChangeModel(
                    tw.getPathString(),
                    tw.getPathString(),
                    0,
                    tw.getRawMode(0),
                    tw.getObjectId(0).getName(),
                    commit.getId().getName(),
                    ChangeType.MODIFY);
          }
        }
      } catch (Exception e) {
      } finally {
        tw.release();
      }
    }

    final boolean isTree = matchingPath == null ? true : matchingPath.isTree();
    final boolean isSubmodule = matchingPath == null ? true : matchingPath.isSubmodule();

    // submodule
    SubmoduleModel submodule = getSubmodule(submodules, repositoryName, matchingPath.path);
    final String submodulePath;
    final boolean hasSubmodule;
    if (submodule != null) {
      submodulePath = submodule.gitblitPath;
      hasSubmodule = submodule.hasSubmodule;
    } else {
      submodulePath = "";
      hasSubmodule = false;
    }

    final Map<ObjectId, List<RefModel>> allRefs = JGitUtils.getAllRefs(r, showRemoteRefs);
    List<RevCommit> commits;
    if (pageResults) {
      // Paging result set
      commits = JGitUtils.getRevLog(r, objectId, path, pageOffset * itemsPerPage, itemsPerPage);
    } else {
      // Fixed size result set
      commits = JGitUtils.getRevLog(r, objectId, path, 0, limit);
    }

    // inaccurate way to determine if there are more commits.
    // works unless commits.size() represents the exact end.
    hasMore = commits.size() >= itemsPerPage;

    add(new CommitHeaderPanel("commitHeader", repositoryName, commit));

    // breadcrumbs
    add(new PathBreadcrumbsPanel("breadcrumbs", repositoryName, path, objectId));

    final int hashLen = GitBlit.getInteger(Keys.web.shortCommitIdLength, 6);
    ListDataProvider<RevCommit> dp = new ListDataProvider<RevCommit>(commits);
    DataView<RevCommit> logView =
        new DataView<RevCommit>("commit", dp) {
          private static final long serialVersionUID = 1L;
          int counter;

          public void populateItem(final Item<RevCommit> item) {
            final RevCommit entry = item.getModelObject();
            final Date date = JGitUtils.getCommitDate(entry);

            item.add(
                WicketUtils.createDateLabel("commitDate", date, getTimeZone(), getTimeUtils()));

            // author search link
            String author = entry.getAuthorIdent().getName();
            LinkPanel authorLink =
                new LinkPanel(
                    "commitAuthor",
                    "list",
                    author,
                    GitSearchPage.class,
                    WicketUtils.newSearchParameter(
                        repositoryName, objectId, author, Constants.SearchType.AUTHOR));
            setPersonSearchTooltip(authorLink, author, Constants.SearchType.AUTHOR);
            item.add(authorLink);

            // merge icon
            if (entry.getParentCount() > 1) {
              item.add(WicketUtils.newImage("commitIcon", "commit_merge_16x16.png"));
            } else {
              item.add(WicketUtils.newBlankImage("commitIcon"));
            }

            String shortMessage = entry.getShortMessage();
            String trimmedMessage = shortMessage;
            if (allRefs.containsKey(entry.getId())) {
              trimmedMessage = StringUtils.trimString(shortMessage, Constants.LEN_SHORTLOG_REFS);
            } else {
              trimmedMessage = StringUtils.trimString(shortMessage, Constants.LEN_SHORTLOG);
            }
            LinkPanel shortlog =
                new LinkPanel(
                    "commitShortMessage",
                    "list subject",
                    trimmedMessage,
                    CommitPage.class,
                    WicketUtils.newObjectParameter(repositoryName, entry.getName()));
            if (!shortMessage.equals(trimmedMessage)) {
              WicketUtils.setHtmlTooltip(shortlog, shortMessage);
            }
            item.add(shortlog);

            item.add(new RefsPanel("commitRefs", repositoryName, entry, allRefs));

            if (isTree) {
              // tree
              item.add(new Label("hashLabel", getString("gb.tree") + "@"));
              LinkPanel commitHash =
                  new LinkPanel(
                      "hashLink",
                      null,
                      entry.getName().substring(0, hashLen),
                      TreePage.class,
                      WicketUtils.newObjectParameter(repositoryName, entry.getName()));
              WicketUtils.setCssClass(commitHash, "shortsha1");
              WicketUtils.setHtmlTooltip(commitHash, entry.getName());
              item.add(commitHash);

              Fragment links = new Fragment("historyLinks", "treeLinks", this);
              links.add(
                  new BookmarkablePageLink<Void>(
                      "commitdiff",
                      CommitDiffPage.class,
                      WicketUtils.newObjectParameter(repositoryName, entry.getName())));
              item.add(links);
            } else if (isSubmodule) {
              // submodule
              item.add(new Label("hashLabel", submodulePath + "@"));
              Repository repository = GitBlit.self().getRepository(repositoryName);
              String submoduleId = JGitUtils.getSubmoduleCommitId(repository, path, entry);
              repository.close();
              LinkPanel commitHash =
                  new LinkPanel(
                      "hashLink",
                      null,
                      submoduleId.substring(0, hashLen),
                      TreePage.class,
                      WicketUtils.newObjectParameter(submodulePath, submoduleId));
              WicketUtils.setCssClass(commitHash, "shortsha1");
              WicketUtils.setHtmlTooltip(commitHash, submoduleId);
              item.add(commitHash.setEnabled(hasSubmodule));

              Fragment links = new Fragment("historyLinks", "treeLinks", this);
              links.add(
                  new BookmarkablePageLink<Void>(
                      "commitdiff",
                      CommitDiffPage.class,
                      WicketUtils.newObjectParameter(repositoryName, entry.getName())));
              item.add(links);
            } else {
              // commit
              item.add(new Label("hashLabel", getString("gb.blob") + "@"));
              LinkPanel commitHash =
                  new LinkPanel(
                      "hashLink",
                      null,
                      entry.getName().substring(0, hashLen),
                      BlobPage.class,
                      WicketUtils.newPathParameter(repositoryName, entry.getName(), path));
              WicketUtils.setCssClass(commitHash, "sha1");
              WicketUtils.setHtmlTooltip(commitHash, entry.getName());
              item.add(commitHash);

              Fragment links = new Fragment("historyLinks", "blobLinks", this);
              links.add(
                  new BookmarkablePageLink<Void>(
                      "commitdiff",
                      CommitDiffPage.class,
                      WicketUtils.newObjectParameter(repositoryName, entry.getName())));
              links.add(
                  new BookmarkablePageLink<Void>(
                          "difftocurrent",
                          BlobDiffPage.class,
                          WicketUtils.newBlobDiffParameter(
                              repositoryName, entry.getName(), objectId, path))
                      .setEnabled(counter > 0));
              item.add(links);
            }

            WicketUtils.setAlternatingBackground(item, counter);
            counter++;
          }
        };
    add(logView);

    // determine to show pager, more, or neither
    if (limit <= 0) {
      // no display limit
      add(new Label("moreHistory", "").setVisible(false));
    } else {
      if (pageResults) {
        // paging
        add(new Label("moreHistory", "").setVisible(false));
      } else {
        // more
        if (commits.size() == limit) {
          // show more
          add(
              new LinkPanel(
                  "moreHistory",
                  "link",
                  new StringResourceModel("gb.moreHistory", this, null),
                  HistoryPage.class,
                  WicketUtils.newPathParameter(repositoryName, objectId, path)));
        } else {
          // no more
          add(new Label("moreHistory", "").setVisible(false));
        }
      }
    }
  }
コード例 #12
0
ファイル: BranchesPanel.java プロジェクト: trygvis/gitblit
  public BranchesPanel(
      String wicketId, final RepositoryModel model, Repository r, final int maxCount) {
    super(wicketId);

    // branches
    List<RefModel> branches = new ArrayList<RefModel>();
    branches.addAll(JGitUtils.getLocalBranches(r, false, maxCount));
    if (model.showRemoteBranches) {
      branches.addAll(JGitUtils.getRemoteBranches(r, false, maxCount));
    }
    Collections.sort(branches);
    Collections.reverse(branches);
    if (maxCount > 0 && branches.size() > maxCount) {
      branches = new ArrayList<RefModel>(branches.subList(0, maxCount));
    }

    if (maxCount > 0) {
      // summary page
      // show branches page link
      add(
          new LinkPanel(
              "branches",
              "title",
              new StringResourceModel("gb.branches", this, null),
              BranchesPage.class,
              WicketUtils.newRepositoryParameter(model.name)));
    } else {
      // branches page
      // show repository summary page link
      add(
          new LinkPanel(
              "branches",
              "title",
              model.name,
              SummaryPage.class,
              WicketUtils.newRepositoryParameter(model.name)));
    }

    ListDataProvider<RefModel> branchesDp = new ListDataProvider<RefModel>(branches);
    DataView<RefModel> branchesView =
        new DataView<RefModel>("branch", branchesDp) {
          private static final long serialVersionUID = 1L;
          int counter;

          public void populateItem(final Item<RefModel> item) {
            final RefModel entry = item.getModelObject();

            item.add(WicketUtils.createDateLabel("branchDate", entry.getDate(), getTimeZone()));

            item.add(
                new LinkPanel(
                    "branchName",
                    "list name",
                    StringUtils.trimString(entry.displayName, 28),
                    LogPage.class,
                    WicketUtils.newObjectParameter(model.name, entry.getName())));

            String author = entry.getAuthorIdent().getName();
            LinkPanel authorLink =
                new LinkPanel(
                    "branchAuthor",
                    "list",
                    author,
                    SearchPage.class,
                    WicketUtils.newSearchParameter(
                        model.name, entry.getName(), author, SearchType.AUTHOR));
            setPersonSearchTooltip(authorLink, author, SearchType.AUTHOR);
            item.add(authorLink);

            // short message
            String shortMessage = entry.getShortMessage();
            String trimmedMessage = StringUtils.trimShortLog(shortMessage);
            LinkPanel shortlog =
                new LinkPanel(
                    "branchLog",
                    "list subject",
                    trimmedMessage,
                    CommitPage.class,
                    WicketUtils.newObjectParameter(model.name, entry.getName()));
            if (!shortMessage.equals(trimmedMessage)) {
              WicketUtils.setHtmlTooltip(shortlog, shortMessage);
            }
            item.add(shortlog);

            if (maxCount <= 0) {
              Fragment fragment = new Fragment("branchLinks", "branchPageLinks", this);
              fragment.add(
                  new BookmarkablePageLink<Void>(
                      "log",
                      LogPage.class,
                      WicketUtils.newObjectParameter(model.name, entry.getName())));
              fragment.add(
                  new BookmarkablePageLink<Void>(
                      "tree",
                      TreePage.class,
                      WicketUtils.newObjectParameter(model.name, entry.getName())));
              fragment.add(
                  new BookmarkablePageLink<Void>(
                      "metrics",
                      MetricsPage.class,
                      WicketUtils.newObjectParameter(model.name, entry.getName())));
              fragment.add(
                  new ExternalLink(
                      "syndication",
                      SyndicationServlet.asLink(
                          getRequest().getRelativePathPrefixToContextRoot(),
                          model.name,
                          entry.getName(),
                          0)));
              item.add(fragment);
            } else {
              Fragment fragment = new Fragment("branchLinks", "branchPanelLinks", this);
              fragment.add(
                  new BookmarkablePageLink<Void>(
                      "log",
                      LogPage.class,
                      WicketUtils.newObjectParameter(model.name, entry.getName())));
              fragment.add(
                  new BookmarkablePageLink<Void>(
                      "tree",
                      TreePage.class,
                      WicketUtils.newObjectParameter(model.name, entry.getName())));
              item.add(fragment);
            }
            WicketUtils.setAlternatingBackground(item, counter);
            counter++;
          }
        };
    add(branchesView);
    if (branches.size() < maxCount || maxCount <= 0) {
      add(new Label("allBranches", "").setVisible(false));
    } else {
      add(
          new LinkPanel(
              "allBranches",
              "link",
              new StringResourceModel("gb.allBranches", this, null),
              BranchesPage.class,
              WicketUtils.newRepositoryParameter(model.name)));
    }
    // We always have 1 branch
    hasBranches =
        (branches.size() > 1)
            || ((branches.size() == 1) && !branches.get(0).displayName.equalsIgnoreCase("master"));
  }
コード例 #13
0
ファイル: LuceneSearchPage.java プロジェクト: LemonKL/gitblit
  private void setup(PageParameters params) {
    setupPage("", "");

    // default values
    ArrayList<String> repositories = new ArrayList<String>();
    String query = "";
    int page = 1;
    int pageSize = app().settings().getInteger(Keys.web.itemsPerPage, 50);

    // display user-accessible selections
    UserModel user = GitBlitWebSession.get().getUser();
    List<String> availableRepositories = new ArrayList<String>();
    for (RepositoryModel model : app().repositories().getRepositoryModels(user)) {
      if (model.hasCommits && !ArrayUtils.isEmpty(model.indexedBranches)) {
        availableRepositories.add(model.name);
      }
    }

    if (params != null) {
      String repository = WicketUtils.getRepositoryName(params);
      if (!StringUtils.isEmpty(repository)) {
        repositories.add(repository);
      }

      page = WicketUtils.getPage(params);

      if (params.containsKey("repositories")) {
        String value = params.getString("repositories", "");
        List<String> list = StringUtils.getStringsFromValue(value);
        repositories.addAll(list);
      }

      if (params.containsKey("allrepos")) {
        repositories.addAll(availableRepositories);
      }

      if (params.containsKey("query")) {
        query = params.getString("query", "");
      } else {
        String value = WicketUtils.getSearchString(params);
        String type = WicketUtils.getSearchType(params);
        com.gitblit.Constants.SearchType searchType =
            com.gitblit.Constants.SearchType.forName(type);
        if (!StringUtils.isEmpty(value)) {
          if (searchType == SearchType.COMMIT) {
            query = "type:" + searchType.name().toLowerCase() + " AND \"" + value + "\"";
          } else {
            query = searchType.name().toLowerCase() + ":\"" + value + "\"";
          }
        }
      }
    }

    boolean luceneEnabled = app().settings().getBoolean(Keys.web.allowLuceneIndexing, true);
    if (luceneEnabled) {
      if (availableRepositories.size() == 0) {
        info(getString("gb.noIndexedRepositoriesWarning"));
      }
    } else {
      error(getString("gb.luceneDisabled"));
    }

    // enforce user-accessible repository selections
    Set<String> uniqueRepositories = new LinkedHashSet<String>();
    for (String selectedRepository : repositories) {
      if (availableRepositories.contains(selectedRepository)) {
        uniqueRepositories.add(selectedRepository);
      }
    }
    ArrayList<String> searchRepositories = new ArrayList<String>(uniqueRepositories);

    // search form
    final Model<String> queryModel = new Model<String>(query);
    final Model<ArrayList<String>> repositoriesModel =
        new Model<ArrayList<String>>(searchRepositories);
    final Model<Boolean> allreposModel =
        new Model<Boolean>(params != null && params.containsKey("allrepos"));
    SessionlessForm<Void> form =
        new SessionlessForm<Void>("searchForm", getClass()) {

          private static final long serialVersionUID = 1L;

          @Override
          public void onSubmit() {
            String q = queryModel.getObject();
            if (StringUtils.isEmpty(q)) {
              error(getString("gb.undefinedQueryWarning"));
              return;
            }
            if (repositoriesModel.getObject().size() == 0 && !allreposModel.getObject()) {
              error(getString("gb.noSelectedRepositoriesWarning"));
              return;
            }
            PageParameters params = new PageParameters();
            params.put("repositories", StringUtils.flattenStrings(repositoriesModel.getObject()));
            params.put("query", queryModel.getObject());
            params.put("allrepos", allreposModel.getObject());
            LuceneSearchPage page = new LuceneSearchPage(params);
            setResponsePage(page);
          }
        };

    ListMultipleChoice<String> selections =
        new ListMultipleChoice<String>(
            "repositories", repositoriesModel, availableRepositories, new StringChoiceRenderer());
    selections.setMaxRows(8);
    form.add(selections.setEnabled(luceneEnabled));
    form.add(new TextField<String>("query", queryModel).setEnabled(luceneEnabled));
    form.add(new CheckBox("allrepos", allreposModel));
    add(form.setEnabled(luceneEnabled));

    // execute search
    final List<SearchResult> results = new ArrayList<SearchResult>();
    if (!ArrayUtils.isEmpty(searchRepositories) && !StringUtils.isEmpty(query)) {
      results.addAll(app().repositories().search(query, page, pageSize, searchRepositories));
    }

    // results header
    if (results.size() == 0) {
      if (!ArrayUtils.isEmpty(searchRepositories) && !StringUtils.isEmpty(query)) {
        add(new Label("resultsHeader", query).setRenderBodyOnly(true));
        add(new Label("resultsCount", getString("gb.noHits")).setRenderBodyOnly(true));
      } else {
        add(new Label("resultsHeader").setVisible(false));
        add(new Label("resultsCount").setVisible(false));
      }
    } else {
      add(new Label("resultsHeader", query).setRenderBodyOnly(true));
      add(
          new Label(
                  "resultsCount",
                  MessageFormat.format(
                      getString("gb.queryResults"),
                      results.get(0).hitId,
                      results.get(results.size() - 1).hitId,
                      results.get(0).totalHits))
              .setRenderBodyOnly(true));
    }

    // search results view
    ListDataProvider<SearchResult> resultsDp = new ListDataProvider<SearchResult>(results);
    final DataView<SearchResult> resultsView =
        new DataView<SearchResult>("searchResults", resultsDp) {
          private static final long serialVersionUID = 1L;

          @Override
          public void populateItem(final Item<SearchResult> item) {
            final SearchResult sr = item.getModelObject();
            switch (sr.type) {
              case commit:
                {
                  Label icon = WicketUtils.newIcon("type", "icon-refresh");
                  WicketUtils.setHtmlTooltip(icon, "commit");
                  item.add(icon);
                  item.add(
                      new LinkPanel(
                          "summary",
                          null,
                          sr.summary,
                          CommitPage.class,
                          WicketUtils.newObjectParameter(sr.repository, sr.commitId)));
                  // show tags
                  Fragment fragment = new Fragment("tags", "tagsPanel", LuceneSearchPage.this);
                  List<String> tags = sr.tags;
                  if (tags == null) {
                    tags = new ArrayList<String>();
                  }
                  ListDataProvider<String> tagsDp = new ListDataProvider<String>(tags);
                  final DataView<String> tagsView =
                      new DataView<String>("tag", tagsDp) {
                        private static final long serialVersionUID = 1L;

                        @Override
                        public void populateItem(final Item<String> item) {
                          String tag = item.getModelObject();
                          Component c =
                              new LinkPanel(
                                  "tagLink",
                                  null,
                                  tag,
                                  TagPage.class,
                                  WicketUtils.newObjectParameter(
                                      sr.repository, Constants.R_TAGS + tag));
                          WicketUtils.setCssClass(c, "tagRef");
                          item.add(c);
                        }
                      };
                  fragment.add(tagsView);
                  item.add(fragment);
                  break;
                }
              case blob:
                {
                  Label icon = WicketUtils.newIcon("type", "icon-file");
                  WicketUtils.setHtmlTooltip(icon, "blob");
                  item.add(icon);
                  item.add(
                      new LinkPanel(
                          "summary",
                          null,
                          sr.path,
                          BlobPage.class,
                          WicketUtils.newPathParameter(sr.repository, sr.branch, sr.path)));
                  item.add(new Label("tags").setVisible(false));
                  break;
                }
            }
            item.add(
                new Label("fragment", sr.fragment)
                    .setEscapeModelStrings(false)
                    .setVisible(!StringUtils.isEmpty(sr.fragment)));
            item.add(
                new LinkPanel(
                    "repository",
                    null,
                    sr.repository,
                    SummaryPage.class,
                    WicketUtils.newRepositoryParameter(sr.repository)));
            if (StringUtils.isEmpty(sr.branch)) {
              item.add(new Label("branch", "null"));
            } else {
              item.add(
                  new LinkPanel(
                      "branch",
                      "branch",
                      StringUtils.getRelativePath(Constants.R_HEADS, sr.branch),
                      LogPage.class,
                      WicketUtils.newObjectParameter(sr.repository, sr.branch)));
            }
            item.add(new Label("author", sr.author));
            item.add(
                WicketUtils.createDatestampLabel("date", sr.date, getTimeZone(), getTimeUtils()));
          }
        };
    add(resultsView.setVisible(results.size() > 0));

    PageParameters pagerParams = new PageParameters();
    pagerParams.put("repositories", StringUtils.flattenStrings(repositoriesModel.getObject()));
    pagerParams.put("query", queryModel.getObject());

    boolean showPager = false;
    int totalPages = 0;
    if (results.size() > 0) {
      totalPages =
          (results.get(0).totalHits / pageSize) + (results.get(0).totalHits % pageSize > 0 ? 1 : 0);
      showPager = results.get(0).totalHits > pageSize;
    }

    add(
        new PagerPanel("topPager", page, totalPages, LuceneSearchPage.class, pagerParams)
            .setVisible(showPager));
    add(
        new PagerPanel("bottomPager", page, totalPages, LuceneSearchPage.class, pagerParams)
            .setVisible(showPager));
  }
コード例 #14
0
ファイル: SummaryPage.java プロジェクト: nhuray/gitblit
  public SummaryPage(PageParameters params) {
    super(params);

    int numberCommits = GitBlit.getInteger(Keys.web.summaryCommitCount, 20);
    if (numberCommits <= 0) {
      numberCommits = 20;
    }
    int numberRefs = GitBlit.getInteger(Keys.web.summaryRefsCount, 5);

    Repository r = getRepository();
    RepositoryModel model = getRepositoryModel();

    List<Metric> metrics = null;
    Metric metricsTotal = null;
    if (!model.skipSummaryMetrics && GitBlit.getBoolean(Keys.web.generateActivityGraph, true)) {
      metrics = GitBlit.self().getRepositoryDefaultMetrics(model, r);
      metricsTotal = metrics.remove(0);
    }

    addSyndicationDiscoveryLink();

    // repository description
    add(new Label("repositoryDescription", getRepositoryModel().description));
    add(new Label("repositoryOwner", getRepositoryModel().owner));

    add(
        WicketUtils.createTimestampLabel(
            "repositoryLastChange", JGitUtils.getLastChange(r), getTimeZone()));
    if (metricsTotal == null) {
      add(new Label("branchStats", ""));
    } else {
      add(
          new Label(
              "branchStats",
              MessageFormat.format(
                  "{0} commits and {1} tags in {2}",
                  metricsTotal.count,
                  metricsTotal.tag,
                  TimeUtils.duration(metricsTotal.duration))));
    }
    add(
        new BookmarkablePageLink<Void>(
            "metrics", MetricsPage.class, WicketUtils.newRepositoryParameter(repositoryName)));

    List<String> repositoryUrls = new ArrayList<String>();

    if (GitBlit.getBoolean(Keys.git.enableGitServlet, true)) {
      AccessRestrictionType accessRestriction = getRepositoryModel().accessRestriction;
      switch (accessRestriction) {
        case NONE:
          add(WicketUtils.newClearPixel("accessRestrictionIcon").setVisible(false));
          break;
        case PUSH:
          add(
              WicketUtils.newImage(
                  "accessRestrictionIcon",
                  "lock_go_16x16.png",
                  getAccessRestrictions().get(accessRestriction)));
          break;
        case CLONE:
          add(
              WicketUtils.newImage(
                  "accessRestrictionIcon",
                  "lock_pull_16x16.png",
                  getAccessRestrictions().get(accessRestriction)));
          break;
        case VIEW:
          add(
              WicketUtils.newImage(
                  "accessRestrictionIcon",
                  "shield_16x16.png",
                  getAccessRestrictions().get(accessRestriction)));
          break;
        default:
          add(WicketUtils.newClearPixel("accessRestrictionIcon").setVisible(false));
      }
      // add the Gitblit repository url
      repositoryUrls.add(getRepositoryUrl(getRepositoryModel()));
    } else {
      add(WicketUtils.newClearPixel("accessRestrictionIcon").setVisible(false));
    }
    repositoryUrls.addAll(GitBlit.self().getOtherCloneUrls(repositoryName));

    String primaryUrl = ArrayUtils.isEmpty(repositoryUrls) ? "" : repositoryUrls.remove(0);
    add(new RepositoryUrlPanel("repositoryCloneUrl", primaryUrl));

    add(
        new Label("otherUrls", StringUtils.flattenStrings(repositoryUrls, "<br/>"))
            .setEscapeModelStrings(false));

    add(
        new LogPanel(
            "commitsPanel", repositoryName, getRepositoryModel().HEAD, r, numberCommits, 0));
    add(new TagsPanel("tagsPanel", repositoryName, r, numberRefs).hideIfEmpty());
    add(new BranchesPanel("branchesPanel", getRepositoryModel(), r, numberRefs).hideIfEmpty());

    if (getRepositoryModel().showReadme) {
      String htmlText = null;
      String readme = null;
      try {
        RevCommit head = JGitUtils.getCommit(r, null);
        List<String> markdownExtensions = GitBlit.getStrings(Keys.web.markdownExtensions);
        List<PathModel> paths = JGitUtils.getFilesInPath(r, null, head);
        for (PathModel path : paths) {
          if (!path.isTree()) {
            String name = path.name.toLowerCase();

            if (name.startsWith("readme")) {
              if (name.indexOf('.') > -1) {
                String ext = name.substring(name.lastIndexOf('.') + 1);
                if (markdownExtensions.contains(ext)) {
                  readme = path.name;
                  break;
                }
              }
            }
          }
        }
        if (!StringUtils.isEmpty(readme)) {
          String markdownText = JGitUtils.getStringContent(r, head.getTree(), readme);
          htmlText = MarkdownUtils.transformMarkdown(markdownText);
        }
      } catch (ParseException p) {
        error(p.getMessage());
      }
      Fragment fragment = new Fragment("readme", "markdownPanel");
      fragment.add(new Label("readmeFile", readme));
      // Add the html to the page
      Component content = new Label("readmeContent", htmlText).setEscapeModelStrings(false);
      fragment.add(content.setVisible(!StringUtils.isEmpty(htmlText)));
      add(fragment);
    } else {
      add(new Label("readme").setVisible(false));
    }

    // Display an activity line graph
    insertActivityGraph(metrics);
  }
コード例 #15
0
  private void setup(PageParameters params) {
    setupPage("", "");
    // check to see if we should display a login message
    boolean authenticateView = GitBlit.getBoolean(Keys.web.authenticateViewPages, true);
    if (authenticateView && !GitBlitWebSession.get().isLoggedIn()) {
      authenticationError("Please login");
      return;
    }

    String projectName = WicketUtils.getProjectName(params);
    if (StringUtils.isEmpty(projectName)) {
      throw new GitblitRedirectException(GitBlitWebApp.get().getHomePage());
    }

    ProjectModel project = getProjectModel(projectName);
    if (project == null) {
      throw new GitblitRedirectException(GitBlitWebApp.get().getHomePage());
    }

    add(new Label("projectTitle", project.getDisplayName()));
    add(new Label("projectDescription", project.description));

    String feedLink =
        SyndicationServlet.asLink(
            getRequest().getRelativePathPrefixToContextRoot(), projectName, null, 0);
    add(new ExternalLink("syndication", feedLink));

    add(
        WicketUtils.syndicationDiscoveryLink(
            SyndicationServlet.getTitle(project.getDisplayName(), null), feedLink));

    // project markdown message
    String pmessage = transformMarkdown(project.projectMarkdown);
    Component projectMessage =
        new Label("projectMessage", pmessage)
            .setEscapeModelStrings(false)
            .setVisible(pmessage.length() > 0);
    add(projectMessage);

    // markdown message above repositories list
    String rmessage = transformMarkdown(project.repositoriesMarkdown);
    Component repositoriesMessage =
        new Label("repositoriesMessage", rmessage)
            .setEscapeModelStrings(false)
            .setVisible(rmessage.length() > 0);
    add(repositoriesMessage);

    UserModel user = GitBlitWebSession.get().getUser();
    if (user == null) {
      user = UserModel.ANONYMOUS;
    }
    int daysBack = params == null ? 0 : WicketUtils.getDaysBack(params);
    if (daysBack < 1) {
      daysBack = GitBlit.getInteger(Keys.web.activityDuration, 7);
    }
    // reset the daysback parameter so that we have a complete project
    // repository list.  the recent activity will be built up by the
    // reflog utils.
    params.remove("db");

    List<RepositoryModel> repositories = getRepositories(params);
    Collections.sort(
        repositories,
        new Comparator<RepositoryModel>() {
          @Override
          public int compare(RepositoryModel o1, RepositoryModel o2) {
            // reverse-chronological sort
            return o2.lastChange.compareTo(o1.lastChange);
          }
        });

    addActivity(user, repositories, getString("gb.recentActivity"), daysBack);

    if (repositories.isEmpty()) {
      add(new Label("repositoryList").setVisible(false));
    } else {
      FilterableRepositoryList repoList =
          new FilterableRepositoryList("repositoryList", repositories);
      repoList.setAllowCreate(user.canCreate(project.name + "/"));
      add(repoList);
    }
  }
コード例 #16
0
ファイル: BasePage.java プロジェクト: yueyaquanBoy/gitblit
  protected List<ProjectModel> getProjects(PageParameters params) {
    if (params == null) {
      return getProjectModels();
    }

    boolean hasParameter = false;
    String regex = WicketUtils.getRegEx(params);
    String team = WicketUtils.getTeam(params);
    int daysBack = params.getInt("db", 0);
    int maxDaysBack = app().settings().getInteger(Keys.web.activityDurationMaximum, 30);

    List<ProjectModel> availableModels = getProjectModels();
    Set<ProjectModel> models = new HashSet<ProjectModel>();

    if (!StringUtils.isEmpty(regex)) {
      // filter the projects by the regex
      hasParameter = true;
      Pattern pattern = Pattern.compile(regex);
      for (ProjectModel model : availableModels) {
        if (pattern.matcher(model.name).find()) {
          models.add(model);
        }
      }
    }

    if (!StringUtils.isEmpty(team)) {
      // filter the projects by the specified teams
      hasParameter = true;
      List<String> teams = StringUtils.getStringsFromValue(team, ",");

      // need TeamModels first
      List<TeamModel> teamModels = new ArrayList<TeamModel>();
      for (String name : teams) {
        TeamModel teamModel = app().users().getTeamModel(name);
        if (teamModel != null) {
          teamModels.add(teamModel);
        }
      }

      // brute-force our way through finding the matching models
      for (ProjectModel projectModel : availableModels) {
        for (String repositoryName : projectModel.repositories) {
          for (TeamModel teamModel : teamModels) {
            if (teamModel.hasRepositoryPermission(repositoryName)) {
              models.add(projectModel);
            }
          }
        }
      }
    }

    if (!hasParameter) {
      models.addAll(availableModels);
    }

    // time-filter the list
    if (daysBack > 0) {
      if (maxDaysBack > 0 && daysBack > maxDaysBack) {
        daysBack = maxDaysBack;
      }
      Calendar cal = Calendar.getInstance();
      cal.set(Calendar.HOUR_OF_DAY, 0);
      cal.set(Calendar.MINUTE, 0);
      cal.set(Calendar.SECOND, 0);
      cal.set(Calendar.MILLISECOND, 0);
      cal.add(Calendar.DATE, -1 * daysBack);
      Date threshold = cal.getTime();
      Set<ProjectModel> timeFiltered = new HashSet<ProjectModel>();
      for (ProjectModel model : models) {
        if (model.lastChange.after(threshold)) {
          timeFiltered.add(model);
        }
      }
      models = timeFiltered;
    }

    List<ProjectModel> list = new ArrayList<ProjectModel>(models);
    Collections.sort(list);
    return list;
  }
コード例 #17
0
ファイル: OverviewPage.java プロジェクト: jijamw/gitblit
  public OverviewPage(PageParameters params) {
    super(params);

    int numberRefs = GitBlit.getInteger(Keys.web.summaryRefsCount, 5);

    Repository r = getRepository();
    final RepositoryModel model = getRepositoryModel();
    UserModel user = GitBlitWebSession.get().getUser();
    if (user == null) {
      user = UserModel.ANONYMOUS;
    }

    List<Metric> metrics = null;
    Metric metricsTotal = null;
    if (!model.skipSummaryMetrics && GitBlit.getBoolean(Keys.web.generateActivityGraph, true)) {
      metrics = GitBlit.self().getRepositoryDefaultMetrics(model, r);
      metricsTotal = metrics.remove(0);
    }

    addSyndicationDiscoveryLink();

    // repository description
    add(new Label("repositoryDescription", getRepositoryModel().description));

    // owner links
    final List<String> owners = new ArrayList<String>(getRepositoryModel().owners);
    ListDataProvider<String> ownersDp = new ListDataProvider<String>(owners);
    DataView<String> ownersView =
        new DataView<String>("repositoryOwners", ownersDp) {
          private static final long serialVersionUID = 1L;
          int counter = 0;

          public void populateItem(final Item<String> item) {
            String ownername = item.getModelObject();
            UserModel ownerModel = GitBlit.self().getUserModel(ownername);
            if (ownerModel != null) {
              item.add(
                  new LinkPanel(
                          "owner",
                          null,
                          ownerModel.getDisplayName(),
                          UserPage.class,
                          WicketUtils.newUsernameParameter(ownerModel.username))
                      .setRenderBodyOnly(true));
            } else {
              Label owner = new Label("owner", ownername);
              WicketUtils.setCssStyle(owner, "text-decoration: line-through;");
              WicketUtils.setHtmlTooltip(
                  owner, MessageFormat.format(getString("gb.failedToFindAccount"), ownername));
              item.add(owner);
            }
            counter++;
            item.add(new Label("comma", ",").setVisible(counter < owners.size()));
            item.setRenderBodyOnly(true);
          }
        };
    ownersView.setRenderBodyOnly(true);
    add(ownersView);

    add(
        WicketUtils.createTimestampLabel(
            "repositoryLastChange",
            JGitUtils.getLastChange(r).when,
            getTimeZone(),
            getTimeUtils()));
    add(new Label("repositorySize", model.size));

    if (metricsTotal == null) {
      add(new Label("branchStats", ""));
    } else {
      add(
          new Label(
              "branchStats",
              MessageFormat.format(
                  getString("gb.branchStats"),
                  metricsTotal.count,
                  metricsTotal.tag,
                  getTimeUtils().duration(metricsTotal.duration))));
    }
    add(
        new BookmarkablePageLink<Void>(
            "metrics", MetricsPage.class, WicketUtils.newRepositoryParameter(repositoryName)));

    add(new RepositoryUrlPanel("repositoryUrlPanel", false, user, model));

    int reflogCount = GitBlit.getInteger(Keys.web.overviewReflogCount, 5);
    ReflogPanel reflog = new ReflogPanel("reflogPanel", getRepositoryModel(), r, reflogCount, 0);
    add(reflog);
    add(new TagsPanel("tagsPanel", repositoryName, r, numberRefs).hideIfEmpty());
    add(
        new BranchesPanel("branchesPanel", getRepositoryModel(), r, numberRefs, false)
            .hideIfEmpty());

    // Display an activity line graph
    insertActivityGraph(metrics);
  }
コード例 #18
0
ファイル: MyDashboardPage.java プロジェクト: ryuhon/gitblit
  private void setup(PageParameters params) {
    setupPage("", "");
    // check to see if we should display a login message
    boolean authenticateView = GitBlit.getBoolean(Keys.web.authenticateViewPages, true);
    if (authenticateView && !GitBlitWebSession.get().isLoggedIn()) {
      String messageSource = GitBlit.getString(Keys.web.loginMessage, "gitblit");
      String message = readMarkdown(messageSource, "login.mkd");
      Component repositoriesMessage = new Label("repositoriesMessage", message);
      add(repositoriesMessage.setEscapeModelStrings(false));
      add(new Label("activity").setVisible(false));
      add(new Label("repositoryTabs").setVisible(false));
      return;
    }

    // Load the markdown welcome message
    String messageSource = GitBlit.getString(Keys.web.repositoriesMessage, "gitblit");
    String message = readMarkdown(messageSource, "welcome.mkd");
    Component repositoriesMessage =
        new Label("repositoriesMessage", message)
            .setEscapeModelStrings(false)
            .setVisible(message.length() > 0);
    add(repositoriesMessage);

    UserModel user = GitBlitWebSession.get().getUser();
    if (user == null) {
      user = UserModel.ANONYMOUS;
    }

    // parameters
    int daysBack = params == null ? 0 : WicketUtils.getDaysBack(params);
    if (daysBack < 1) {
      daysBack = GitBlit.getInteger(Keys.web.activityDuration, 7);
    }
    Calendar c = Calendar.getInstance();
    c.add(Calendar.DATE, -1 * daysBack);
    Date minimumDate = c.getTime();

    // build repo lists
    List<RepositoryModel> starred = new ArrayList<RepositoryModel>();
    List<RepositoryModel> owned = new ArrayList<RepositoryModel>();
    List<RepositoryModel> active = new ArrayList<RepositoryModel>();

    for (RepositoryModel model : getRepositoryModels()) {
      if (model.isUsersPersonalRepository(user.username) || model.isOwner(user.username)) {
        owned.add(model);
      }

      if (user.getPreferences().isStarredRepository(model.name)) {
        starred.add(model);
      }

      if (model.isShowActivity() && model.lastChange.after(minimumDate)) {
        active.add(model);
      }
    }

    Comparator<RepositoryModel> lastUpdateSort =
        new Comparator<RepositoryModel>() {
          @Override
          public int compare(RepositoryModel o1, RepositoryModel o2) {
            return o2.lastChange.compareTo(o1.lastChange);
          }
        };

    Collections.sort(owned, lastUpdateSort);
    Collections.sort(starred, lastUpdateSort);
    Collections.sort(active, lastUpdateSort);

    String activityTitle;
    Set<RepositoryModel> feed = new HashSet<RepositoryModel>();
    feed.addAll(starred);
    feed.addAll(owned);
    if (feed.isEmpty()) {
      // no starred or owned, go with recent activity
      activityTitle = getString("gb.recentActivity");
      feed.addAll(active);
    } else if (starred.isEmpty()) {
      // no starred, owned repos feed
      activityTitle = getString("gb.owned");
    } else if (owned.isEmpty()) {
      // no owned, starred repos feed
      activityTitle = getString("gb.starred");
    } else {
      // starred and owned repositories
      activityTitle = getString("gb.starredAndOwned");
    }

    addActivity(user, feed, activityTitle, daysBack);

    Fragment repositoryTabs;
    if (UserModel.ANONYMOUS.equals(user)) {
      repositoryTabs = new Fragment("repositoryTabs", "anonymousTabsFragment", this);
    } else {
      repositoryTabs = new Fragment("repositoryTabs", "authenticatedTabsFragment", this);
    }

    add(repositoryTabs);

    // projects list
    List<ProjectModel> projects = GitBlit.self().getProjectModels(getRepositoryModels(), false);
    repositoryTabs.add(new FilterableProjectList("projects", projects));

    // active repository list
    if (active.isEmpty()) {
      repositoryTabs.add(new Label("active").setVisible(false));
    } else {
      FilterableRepositoryList repoList = new FilterableRepositoryList("active", active);
      repoList.setTitle(getString("gb.activeRepositories"), "icon-time");
      repositoryTabs.add(repoList);
    }

    // starred repository list
    if (ArrayUtils.isEmpty(starred)) {
      repositoryTabs.add(new Label("starred").setVisible(false));
    } else {
      FilterableRepositoryList repoList = new FilterableRepositoryList("starred", starred);
      repoList.setTitle(getString("gb.starredRepositories"), "icon-star");
      repositoryTabs.add(repoList);
    }

    // owned repository list
    if (ArrayUtils.isEmpty(owned)) {
      repositoryTabs.add(new Label("owned").setVisible(false));
    } else {
      FilterableRepositoryList repoList = new FilterableRepositoryList("owned", owned);
      repoList.setTitle(getString("gb.myRepositories"), "icon-user");
      repoList.setAllowCreate(user.canCreate() || user.canAdmin());
      repositoryTabs.add(repoList);
    }
  }
コード例 #19
0
ファイル: ComparePage.java プロジェクト: noelmac/gitblit
  public ComparePage(PageParameters params) {
    super(params);
    Repository r = getRepository();
    RepositoryModel repository = getRepositoryModel();

    if (StringUtils.isEmpty(objectId)) {
      // seleciton form
      add(new Label("comparison").setVisible(false));
    } else {
      // active comparison
      Fragment comparison = new Fragment("comparison", "comparisonFragment", this);
      add(comparison);

      RevCommit fromCommit;
      RevCommit toCommit;

      String[] parts = objectId.split("\\.\\.");
      if (parts[0].startsWith("refs/") && parts[1].startsWith("refs/")) {
        // set the ref models
        fromRefId.setObject(parts[0]);
        toRefId.setObject(parts[1]);

        fromCommit = getCommit(r, fromRefId.getObject());
        toCommit = getCommit(r, toRefId.getObject());
      } else {
        // set the id models
        fromCommitId.setObject(parts[0]);
        toCommitId.setObject(parts[1]);

        fromCommit = getCommit(r, fromCommitId.getObject());
        toCommit = getCommit(r, toCommitId.getObject());
      }

      // prepare submodules
      getSubmodules(toCommit);

      final String startId = fromCommit.getId().getName();
      final String endId = toCommit.getId().getName();

      // commit ids
      fromCommitId.setObject(startId);
      toCommitId.setObject(endId);

      final DiffOutput diff = DiffUtils.getDiff(r, fromCommit, toCommit, DiffOutputType.HTML);

      // add compare diffstat
      int insertions = 0;
      int deletions = 0;
      for (PathChangeModel pcm : diff.stat.paths) {
        insertions += pcm.insertions;
        deletions += pcm.deletions;
      }
      comparison.add(new DiffStatPanel("diffStat", insertions, deletions));

      // compare page links
      //			comparison.add(new BookmarkablePageLink<Void>("patchLink", PatchPage.class,
      //					WicketUtils.newRangeParameter(repositoryName, fromCommitId.toString(),
      // toCommitId.getObject())));

      // display list of commits
      comparison.add(
          new LogPanel(
              "commitList", repositoryName, objectId, r, 0, 0, repository.showRemoteBranches));

      // changed paths list
      comparison.add(new CommitLegendPanel("commitLegend", diff.stat.paths));
      ListDataProvider<PathChangeModel> pathsDp =
          new ListDataProvider<PathChangeModel>(diff.stat.paths);
      DataView<PathChangeModel> pathsView =
          new DataView<PathChangeModel>("changedPath", pathsDp) {
            private static final long serialVersionUID = 1L;
            int counter;

            @Override
            public void populateItem(final Item<PathChangeModel> item) {
              final PathChangeModel entry = item.getModelObject();
              Label changeType = new Label("changeType", "");
              WicketUtils.setChangeTypeCssClass(changeType, entry.changeType);
              setChangeTypeTooltip(changeType, entry.changeType);
              item.add(changeType);
              item.add(new DiffStatPanel("diffStat", entry.insertions, entry.deletions, true));

              boolean hasSubmodule = false;
              String submodulePath = null;
              if (entry.isTree()) {
                // tree
                item.add(
                    new LinkPanel(
                        "pathName",
                        null,
                        entry.path,
                        TreePage.class,
                        WicketUtils.newPathParameter(repositoryName, endId, entry.path)));
              } else if (entry.isSubmodule()) {
                // submodule
                String submoduleId = entry.objectId;
                SubmoduleModel submodule = getSubmodule(entry.path);
                submodulePath = submodule.gitblitPath;
                hasSubmodule = submodule.hasSubmodule;

                // add relative link
                item.add(
                    new LinkPanel(
                        "pathName",
                        "list",
                        entry.path + " @ " + getShortObjectId(submoduleId),
                        "#" + entry.path));
              } else {
                // add relative link
                item.add(new LinkPanel("pathName", "list", entry.path, "#" + entry.path));
              }

              // quick links
              if (entry.isSubmodule()) {
                // submodule
                item.add(new ExternalLink("patch", "").setEnabled(false));
                item.add(
                    new BookmarkablePageLink<Void>(
                            "view",
                            CommitPage.class,
                            WicketUtils.newObjectParameter(submodulePath, entry.objectId))
                        .setEnabled(hasSubmodule));
                item.add(new ExternalLink("blame", "").setEnabled(false));
                item.add(
                    new BookmarkablePageLink<Void>(
                            "history",
                            HistoryPage.class,
                            WicketUtils.newPathParameter(repositoryName, endId, entry.path))
                        .setEnabled(!entry.changeType.equals(ChangeType.ADD)));
              } else {
                // tree or blob
                item.add(
                    new BookmarkablePageLink<Void>(
                            "patch",
                            PatchPage.class,
                            WicketUtils.newBlobDiffParameter(
                                repositoryName, startId, endId, entry.path))
                        .setEnabled(!entry.changeType.equals(ChangeType.DELETE)));
                item.add(
                    new BookmarkablePageLink<Void>(
                            "view",
                            BlobPage.class,
                            WicketUtils.newPathParameter(repositoryName, endId, entry.path))
                        .setEnabled(!entry.changeType.equals(ChangeType.DELETE)));
                item.add(
                    new BookmarkablePageLink<Void>(
                            "raw",
                            RawPage.class,
                            WicketUtils.newPathParameter(repositoryName, endId, entry.path))
                        .setEnabled(!entry.changeType.equals(ChangeType.DELETE)));
                item.add(
                    new BookmarkablePageLink<Void>(
                            "blame",
                            BlamePage.class,
                            WicketUtils.newPathParameter(repositoryName, endId, entry.path))
                        .setEnabled(
                            !entry.changeType.equals(ChangeType.ADD)
                                && !entry.changeType.equals(ChangeType.DELETE)));
                item.add(
                    new BookmarkablePageLink<Void>(
                            "history",
                            HistoryPage.class,
                            WicketUtils.newPathParameter(repositoryName, endId, entry.path))
                        .setEnabled(!entry.changeType.equals(ChangeType.ADD)));
              }
              WicketUtils.setAlternatingBackground(item, counter);
              counter++;
            }
          };
      comparison.add(pathsView);
      comparison.add(new Label("diffText", diff.content).setEscapeModelStrings(false));
    }

    //
    // ref selection form
    //
    SessionlessForm<Void> refsForm =
        new SessionlessForm<Void>("compareRefsForm", getClass(), getPageParameters()) {

          private static final long serialVersionUID = 1L;

          @Override
          public void onSubmit() {
            String from = ComparePage.this.fromRefId.getObject();
            String to = ComparePage.this.toRefId.getObject();

            PageParameters params = WicketUtils.newRangeParameter(repositoryName, from, to);
            String relativeUrl = urlFor(ComparePage.class, params).toString();
            String absoluteUrl = RequestUtils.toAbsolutePath(relativeUrl);
            getRequestCycle().setRequestTarget(new RedirectRequestTarget(absoluteUrl));
          }
        };

    List<String> refs = new ArrayList<String>();
    for (RefModel ref : JGitUtils.getLocalBranches(r, true, -1)) {
      refs.add(ref.getName());
    }
    if (repository.showRemoteBranches) {
      for (RefModel ref : JGitUtils.getRemoteBranches(r, true, -1)) {
        refs.add(ref.getName());
      }
    }
    for (RefModel ref : JGitUtils.getTags(r, true, -1)) {
      refs.add(ref.getName());
    }
    refsForm.add(
        new DropDownChoice<String>("fromRef", fromRefId, refs).setEnabled(refs.size() > 0));
    refsForm.add(new DropDownChoice<String>("toRef", toRefId, refs).setEnabled(refs.size() > 0));
    add(refsForm);

    //
    // manual ids form
    //
    SessionlessForm<Void> idsForm =
        new SessionlessForm<Void>("compareIdsForm", getClass(), getPageParameters()) {

          private static final long serialVersionUID = 1L;

          @Override
          public void onSubmit() {
            String from = ComparePage.this.fromCommitId.getObject();
            String to = ComparePage.this.toCommitId.getObject();

            PageParameters params = WicketUtils.newRangeParameter(repositoryName, from, to);
            String relativeUrl = urlFor(ComparePage.class, params).toString();
            String absoluteUrl = RequestUtils.toAbsolutePath(relativeUrl);
            getRequestCycle().setRequestTarget(new RedirectRequestTarget(absoluteUrl));
          }
        };

    TextField<String> fromIdField = new TextField<String>("fromId", fromCommitId);
    WicketUtils.setInputPlaceholder(fromIdField, getString("gb.from") + "...");
    idsForm.add(fromIdField);

    TextField<String> toIdField = new TextField<String>("toId", toCommitId);
    WicketUtils.setInputPlaceholder(toIdField, getString("gb.to") + "...");
    idsForm.add(toIdField);
    add(idsForm);

    r.close();
  }
コード例 #20
0
  public CommitDiffPage(PageParameters params) {
    super(params);

    Repository r = getRepository();

    final RevCommit commit = getCommit();

    final List<String> parents = new ArrayList<String>();
    if (commit.getParentCount() > 0) {
      for (RevCommit parent : commit.getParents()) {
        parents.add(parent.name());
      }
    }

    // commit page links
    if (parents.size() == 0) {
      add(new Label("parentLink", getString("gb.none")));
    } else {
      add(
          new LinkPanel(
              "parentLink",
              null,
              parents.get(0).substring(0, 8),
              CommitDiffPage.class,
              newCommitParameter(parents.get(0))));
    }
    add(
        new BookmarkablePageLink<Void>(
            "patchLink",
            PatchPage.class,
            WicketUtils.newObjectParameter(repositoryName, objectId)));
    add(
        new BookmarkablePageLink<Void>(
            "commitLink",
            CommitPage.class,
            WicketUtils.newObjectParameter(repositoryName, objectId)));

    add(new CommitHeaderPanel("commitHeader", repositoryName, commit));

    final List<String> imageExtensions = app().settings().getStrings(Keys.web.imageExtensions);
    final ImageDiffHandler handler =
        new ImageDiffHandler(
            this,
            repositoryName,
            parents.isEmpty() ? null : parents.get(0),
            commit.getName(),
            imageExtensions);
    final DiffOutput diff = DiffUtils.getCommitDiff(r, commit, DiffOutputType.HTML, handler);
    if (handler.getImgDiffCount() > 0) {
      addBottomScript("scripts/imgdiff.js"); // Tiny support script for image diffs
    }

    // add commit diffstat
    int insertions = 0;
    int deletions = 0;
    for (PathChangeModel pcm : diff.stat.paths) {
      insertions += pcm.insertions;
      deletions += pcm.deletions;
    }
    add(new DiffStatPanel("diffStat", insertions, deletions));

    addFullText("fullMessage", commit.getFullMessage());

    // git notes
    List<GitNote> notes = JGitUtils.getNotesOnCommit(r, commit);
    ListDataProvider<GitNote> notesDp = new ListDataProvider<GitNote>(notes);
    DataView<GitNote> notesView =
        new DataView<GitNote>("notes", notesDp) {
          private static final long serialVersionUID = 1L;

          @Override
          public void populateItem(final Item<GitNote> item) {
            GitNote entry = item.getModelObject();
            item.add(new RefsPanel("refName", repositoryName, Arrays.asList(entry.notesRef)));
            item.add(
                createPersonPanel(
                    "authorName", entry.notesRef.getAuthorIdent(), Constants.SearchType.AUTHOR));
            item.add(new GravatarImage("noteAuthorAvatar", entry.notesRef.getAuthorIdent()));
            item.add(
                WicketUtils.createTimestampLabel(
                    "authorDate",
                    entry.notesRef.getAuthorIdent().getWhen(),
                    getTimeZone(),
                    getTimeUtils()));
            item.add(
                new Label(
                        "noteContent",
                        bugtraqProcessor()
                            .processPlainCommitMessage(
                                getRepository(), repositoryName, entry.content))
                    .setEscapeModelStrings(false));
          }
        };
    add(notesView.setVisible(notes.size() > 0));

    // changed paths list
    add(new CommitLegendPanel("commitLegend", diff.stat.paths));
    ListDataProvider<PathChangeModel> pathsDp =
        new ListDataProvider<PathChangeModel>(diff.stat.paths);
    DataView<PathChangeModel> pathsView =
        new DataView<PathChangeModel>("changedPath", pathsDp) {
          private static final long serialVersionUID = 1L;
          int counter;

          @Override
          public void populateItem(final Item<PathChangeModel> item) {
            final PathChangeModel entry = item.getModelObject();
            Label changeType = new Label("changeType", "");
            WicketUtils.setChangeTypeCssClass(changeType, entry.changeType);
            setChangeTypeTooltip(changeType, entry.changeType);
            item.add(changeType);
            item.add(new DiffStatPanel("diffStat", entry.insertions, entry.deletions, true));

            boolean hasSubmodule = false;
            String submodulePath = null;
            if (entry.isTree()) {
              // tree
              item.add(
                  new LinkPanel(
                      "pathName",
                      null,
                      entry.path,
                      TreePage.class,
                      WicketUtils.newPathParameter(repositoryName, entry.commitId, entry.path)));
            } else if (entry.isSubmodule()) {
              // submodule
              String submoduleId = entry.objectId;
              SubmoduleModel submodule = getSubmodule(entry.path);
              submodulePath = submodule.gitblitPath;
              hasSubmodule = submodule.hasSubmodule;

              // add relative link
              item.add(
                  new LinkPanel(
                      "pathName",
                      "list",
                      entry.path + " @ " + getShortObjectId(submoduleId),
                      "#n" + entry.objectId));
            } else {
              // add relative link
              item.add(new LinkPanel("pathName", "list", entry.path, "#n" + entry.objectId));
            }

            // quick links
            if (entry.isSubmodule()) {
              item.add(new ExternalLink("raw", "").setEnabled(false));
              // submodule
              item.add(new ExternalLink("patch", "").setEnabled(false));
              item.add(
                  new BookmarkablePageLink<Void>(
                          "view",
                          CommitPage.class,
                          WicketUtils.newObjectParameter(submodulePath, entry.objectId))
                      .setEnabled(hasSubmodule));
              item.add(new ExternalLink("blame", "").setEnabled(false));
              item.add(
                  new BookmarkablePageLink<Void>(
                          "history",
                          HistoryPage.class,
                          WicketUtils.newPathParameter(repositoryName, entry.commitId, entry.path))
                      .setEnabled(!entry.changeType.equals(ChangeType.ADD)));
            } else {
              // tree or blob
              item.add(
                  new BookmarkablePageLink<Void>(
                          "patch",
                          PatchPage.class,
                          WicketUtils.newPathParameter(repositoryName, entry.commitId, entry.path))
                      .setEnabled(
                          !entry.changeType.equals(ChangeType.ADD)
                              && !entry.changeType.equals(ChangeType.DELETE)));
              item.add(
                  new BookmarkablePageLink<Void>(
                          "view",
                          BlobPage.class,
                          WicketUtils.newPathParameter(repositoryName, entry.commitId, entry.path))
                      .setEnabled(!entry.changeType.equals(ChangeType.DELETE)));
              String rawUrl =
                  RawServlet.asLink(getContextUrl(), repositoryName, entry.commitId, entry.path);
              item.add(
                  new ExternalLink("raw", rawUrl)
                      .setEnabled(!entry.changeType.equals(ChangeType.DELETE)));
              item.add(
                  new BookmarkablePageLink<Void>(
                          "blame",
                          BlamePage.class,
                          WicketUtils.newPathParameter(repositoryName, entry.commitId, entry.path))
                      .setEnabled(
                          !entry.changeType.equals(ChangeType.ADD)
                              && !entry.changeType.equals(ChangeType.DELETE)));
              item.add(
                  new BookmarkablePageLink<Void>(
                          "history",
                          HistoryPage.class,
                          WicketUtils.newPathParameter(repositoryName, entry.commitId, entry.path))
                      .setEnabled(!entry.changeType.equals(ChangeType.ADD)));
            }

            WicketUtils.setAlternatingBackground(item, counter);
            counter++;
          }
        };
    add(pathsView);
    add(new Label("diffText", diff.content).setEscapeModelStrings(false));
  }