patx/gitman

Edit contributors in a saved chip field and gate repository deletion

Commit c7c7a36 · patx · Nov 4 at 2:58AM

Changeset
c7c7a36bcec8deea5169c12d3d397d5bf0db55e6
Parents
505526d957a99825f0b029f845d5cb0e7fb83352

View source at this commit

Comments

No comments yet.

Log in to comment

Diff

diff --git a/app.py b/app.py
index 5efd739..31c0243 100644
--- a/app.py
+++ b/app.py
@@ -2565,27 +2565,35 @@ def add_repo_contributor(repo, added_by, username):
     return add_repo_contributors(repo, added_by, [username])
 
 
-def add_repo_contributors(repo, added_by, usernames):
+def add_repo_contributors(repo, added_by, usernames, *, replace=False):
     usernames = list(dict.fromkeys(
         name.lstrip("@").lower()
         for value in usernames for name in re.split(r"[\s,]+", value.strip()) if name
     ))
-    if not usernames:
+    if not usernames and not replace:
         raise ValueError("Choose at least one contributor.")
     if len(usernames) > 50:
         raise ValueError("Add up to 50 contributors at a time.")
     now = utcnow()
     with db_connect() as conn:
         contributors = []
+        user_ids = []
         for username in usernames:
             contributor = conn.execute("SELECT id FROM users WHERE username = ?", (username,)).fetchone()
             if not contributor:
                 raise ValueError(f"User @{username} not found.")
             if contributor["id"] == repo["owner_id"]:
                 raise ValueError("The owner already has access.")
+            user_ids.append(contributor["id"])
             if conn.execute("SELECT 1 FROM repo_contributors WHERE repo_id = ? AND user_id = ?", (repo["id"], contributor["id"])).fetchone():
+                if replace:
+                    continue
                 raise ValueError(f"@{username} is already a contributor.")
             contributors.append((repo["id"], contributor["id"], added_by["id"], now))
+        if replace:
+            placeholders = ",".join("?" for _ in user_ids)
+            clause = f" AND user_id NOT IN ({placeholders})" if user_ids else ""
+            conn.execute("DELETE FROM repo_contributors WHERE repo_id = ?" + clause, [repo["id"], *user_ids])
         try:
             conn.executemany(
                 "INSERT INTO repo_contributors (repo_id, user_id, added_by_id, created_at) VALUES (?, ?, ?, ?)",
@@ -5496,6 +5504,14 @@ def repo_settings(owner, repo_name):
         delete_repository(repo, path)
         redirect(f"/{owner}")
 
+    if action == "save_contributors":
+        usernames = request.forms.getall("username")
+        try:
+            add_repo_contributors(repo, user, usernames, replace=True)
+            return render_repo_settings_page(repo, path, notice="Contributors updated.")
+        except ValueError as exc:
+            return render_repo_settings_page(repo, path, contributor_username=" ".join(usernames), error=str(exc))
+
     if action == "add_contributor":
         contributor_usernames = request.forms.getall("username")
         contributor_username = " ".join(contributor_usernames)
diff --git a/static/contributor-picker.js b/static/contributor-picker.js
index 79791f9..b3e219f 100644
--- a/static/contributor-picker.js
+++ b/static/contributor-picker.js
@@ -4,7 +4,7 @@
     const form = picker.closest('form');
     const status = form.querySelector('[data-username-picker-status]');
     const chips = new Map();
-    const existing = new Set([picker.dataset.owner, ...picker.dataset.existing.split(',')]);
+    const owner = picker.dataset.owner;
     let selected = null;
     const deselect = () => {
       selected?.classList.remove('chip-selected');
@@ -18,7 +18,7 @@
         status.textContent = 'Enter a username or choose a suggestion.';
         return false;
       }
-      if (existing.has(username)) {
+      if (username === owner) {
         status.textContent = `@${username} already has access.`;
         return false;
       }
@@ -42,6 +42,7 @@
           chips.delete(username);
           deselect();
           status.textContent = `Removed @${username} from the selection.`;
+          changed();
           input.focus();
         });
         chip.append(name, hidden, remove);
@@ -49,8 +50,8 @@
         chips.set(username, chip);
       }
       input.value = '';
+      status.textContent = `Unsaved changes. Choose Save contributors to apply them.`;
       changed();
-      status.textContent = `${chips.size} ${chips.size === 1 ? 'user' : 'users'} selected. Choose Add contributors to give them access.`;
       return true;
     };
     input.addEventListener('username-selected', (event) => add(event.detail));
@@ -84,13 +85,16 @@
       }
     });
     form.addEventListener('submit', (event) => {
-      if ((input.value.trim() && !add(input.value)) || !chips.size) {
+      if (input.value.trim() && !add(input.value)) {
         event.preventDefault();
-        if (!input.value.trim()) status.textContent = 'Choose at least one contributor.';
         input.focus();
       }
     });
     const initial = input.value.trim();
+    input.value = '';
+    picker.querySelectorAll('[data-initial-username]').forEach((chip) => chip.remove());
+    picker.dataset.existing.split(',').filter(Boolean).forEach(add);
+    status.textContent = '';
     if (initial) {
       input.value = '';
       initial.split(/[\s,]+/).forEach(add);
diff --git a/static/save-on-change.js b/static/save-on-change.js
index b8d1cbb..38e1506 100644
--- a/static/save-on-change.js
+++ b/static/save-on-change.js
@@ -1,6 +1,5 @@
 (() => {
   document.querySelectorAll('form[data-save-on-change]').forEach((form) => {
-    const controls = Array.from(form.elements).filter((field) => field.name && !['hidden', 'submit', 'button'].includes(field.type));
     const buttons = Array.from(form.querySelectorAll('button[type="submit"]'));
     const value = (field, initial = false) => {
       if (field.type === 'checkbox' || field.type === 'radio') return initial ? field.defaultChecked : field.checked;
@@ -10,10 +9,16 @@
       }
       return initial ? field.defaultValue : field.value;
     };
-    const initial = JSON.stringify(controls.map((field) => value(field, true)));
+    const snapshot = (initial = false) => JSON.stringify(Array.from(form.elements)
+      .filter((field) => field.name && !['submit', 'button'].includes(field.type))
+      .map((field) => [field.name, value(field, initial)])
+      .sort((a, b) => JSON.stringify(a).localeCompare(JSON.stringify(b))));
+    const initial = snapshot(true);
     const sync = () => {
-      const unchanged = JSON.stringify(controls.map((field) => value(field))) === initial;
+      const unchanged = snapshot() === initial;
       buttons.forEach((button) => { button.disabled = unchanged; });
+      const status = form.querySelector('[data-username-picker-status]');
+      if (unchanged && status) status.textContent = '';
     };
     form.addEventListener('input', sync);
     form.addEventListener('change', sync);
@@ -21,4 +26,13 @@
     window.addEventListener('pageshow', sync);
     sync();
   });
+  document.querySelectorAll('form[data-confirm-delete]').forEach((form) => {
+    const input = form.querySelector('input[name="confirm_name"]');
+    const button = form.querySelector('button[type="submit"]');
+    const sync = () => { button.disabled = input.value.trim() !== form.dataset.confirmDelete; };
+    input.addEventListener('input', sync);
+    input.addEventListener('change', sync);
+    window.addEventListener('pageshow', sync);
+    sync();
+  });
 })();
diff --git a/templates/base.tpl b/templates/base.tpl
index 9c43fe6..a0c6401 100644
--- a/templates/base.tpl
+++ b/templates/base.tpl
@@ -92,8 +92,8 @@
   </footer>
   <script src="/static/mentions.js?v=2" defer></script>
   % if user:
-    <script src="/static/contributor-picker.js?v=1" defer></script>
-    <script src="/static/save-on-change.js?v=1" defer></script>
+    <script src="/static/contributor-picker.js?v=2" defer></script>
+    <script src="/static/save-on-change.js?v=2" defer></script>
   % end
   % if user:
     <script src="/static/notifications.js?v=2" defer></script>
diff --git a/templates/repo_settings.tpl b/templates/repo_settings.tpl
index 5b728e1..7e10fb1 100644
--- a/templates/repo_settings.tpl
+++ b/templates/repo_settings.tpl
@@ -109,41 +109,27 @@
 
 <section class="settings-card" aria-labelledby="repo-contributors-title">
   <h3 id="repo-contributors-title">Contributors</h3>
-  % if contributors:
-    <ul class="clean-list">
-      % for contributor in contributors:
-        <li class="contributor-row">
-          <span><a href="/{{contributor['username']}}">{{contributor["username"]}}</a> <span class="muted">added {{contributor["contributor_since"]}}</span></span>
-          <form class="inline-form" method="post">
-            {{!csrf_field()}}
-            <input type="hidden" name="action" value="remove_contributor">
-            <input type="hidden" name="user_id" value="{{contributor['id']}}">
-            <button class="button secondary small" type="submit">Remove</button>
-          </form>
-        </li>
-      % end
-    </ul>
-  % else:
-    <p class="empty">No contributors yet.</p>
-  % end
-  <form method="post">
+  <form method="post" data-save-on-change>
     {{!csrf_field()}}
-    <input type="hidden" name="action" value="add_contributor">
-    <label for="contributor-usernames">Add contributors</label>
-    <p id="contributor-picker-help" class="muted">Search for users or enter usernames. Press Space or Enter to add a chip, then choose Add contributors. Press Backspace twice in the empty field to edit the last chip.</p>
+    <input type="hidden" name="action" value="save_contributors">
+    <label for="contributor-usernames">Contributors</label>
+    <p id="contributor-picker-help" class="muted">Search for users or press Space/Enter after each username. Double Backspace in the empty field edits the last chip. Save contributors applies your changes.</p>
     <div class="username-picker" data-username-picker data-owner="{{repo['owner_username']}}" data-existing="{{','.join(contributor['username'] for contributor in contributors)}}">
       <span class="username-chip owner-chip"><span>@{{repo['owner_username']}}</span><small>Owner</small></span>
+      % for contributor in contributors:
+        <span class="username-chip" data-initial-username="{{contributor['username']}}"><span>@{{contributor['username']}}</span><input type="hidden" name="username" value="{{contributor['username']}}"></span>
+      % end
       <input id="contributor-usernames" name="username" value="{{contributor_username}}" autocomplete="off" placeholder="Search usernames" aria-describedby="contributor-picker-help contributor-picker-status" data-username-autocomplete>
     </div>
     <p id="contributor-picker-status" class="muted" data-username-picker-status role="status"></p>
-    <button class="button" type="submit">Add contributors</button>
+    <button class="button" type="submit">Save contributors</button>
   </form>
 </section>
 
 <section class="settings-card" aria-labelledby="repo-delete-title">
   <h3 id="repo-delete-title">Delete repository</h3>
   <p>This permanently deletes the repository, its issues, pull requests, and Git data.</p>
-  <form method="post">
+  <form method="post" data-confirm-delete="{{repo['name']}}">
     {{!csrf_field()}}
     <input type="hidden" name="action" value="delete">
     <label>
@@ -154,7 +140,4 @@
   </form>
 </section>
   </div>
-  <nav class="settings-back" aria-label="Repository actions">
-    <a href="/{{repo['owner_username']}}/{{repo['name']}}">Back to repository</a>
-  </nav>
 </section>
diff --git a/tests/test_app.py b/tests/test_app.py
index 490d59b..3305c36 100644
--- a/tests/test_app.py
+++ b/tests/test_app.py
@@ -2461,7 +2461,7 @@ def test_bottle_profile_star_fork_and_repo_settings_flows(isolated_app):
     assert "Type &quot;demo&quot; to confirm deletion." in response.text
 
 
-def test_repository_settings_add_multiple_contributors_atomically(isolated_app):
+def test_repository_settings_updates_contributors_atomically(isolated_app):
     owner = create_user('alice')
     bob = create_user('bob')
     carol = create_user('carol')
@@ -2484,6 +2484,16 @@ def test_repository_settings_add_multiple_contributors_atomically(isolated_app):
     assert isolated_app.user_can_maintain_repo(bob, repo)
     assert isolated_app.user_can_maintain_repo(carol, repo)
     assert isolated_app.repo_contributor_usernames(repo['id']) == ['bob', 'carol']
+    invalid_save = client.post('/alice/demo/settings', {'action': 'save_contributors', 'username': ['carol', 'missing-user']})
+    assert 'not found' in invalid_save.text
+    assert isolated_app.repo_contributor_usernames(repo['id']) == ['bob', 'carol']
+    saved = client.post('/alice/demo/settings', {'action': 'save_contributors', 'username': ['carol']})
+    assert 'Contributors updated.' in saved.text
+    assert not isolated_app.user_can_maintain_repo(bob, repo)
+    assert isolated_app.user_can_maintain_repo(carol, repo)
+    client.post('/alice/demo/settings', {'action': 'save_contributors', 'username': ['']})
+    assert isolated_app.repo_contributor_usernames(repo['id']) == []
+    assert isolated_app.user_can_maintain_repo(owner, repo)
 
 
 def test_bottle_issue_routes_create_comment_close_and_reopen(isolated_app):