antfu/magic-string-stack

Named commit and rollback to any named stage

XiLaiTL opened this issue · 2 comments

Clear and concise description of the problem

The function commit update the MagicString to the new one.
I wonder If it is possible that you can commit with name, and rollback the named stage to use the relative position of any committed one?

Suggested solution

Like this:

const s = new MagicStringStack('problems = 99') //now we named it `origin`

s.replace('problems', 'issues')
  .append('var ')

s.toString() 
s.original 

s.commit("Middle") // now we named the staged `Middle`

s.original
s.replace('issues', 'problems')
s.toString() 

//many named stage

s.rollback('Middle') //now we go back to 'Middle' stage

s.rollback('origin')  //now we go back the origin one
//...

s.generateMap()

Alternative

No response

Additional context

No response

Validations

antfu commented

While it's not hard to do, I wonder what's the use case of this? Using string names could make things complicated as we also need to handle the naming collisions. I feel that a linear .commit and .rollback might be enough already

We can maintain a string array as the stack while maintaining the MagicString stack.

Use nameStack= ["name"].concat(nameStack) to push the name.
Use nameStack.splice(0, 1) to pop the name.
Use nameStack.length - 1 - nameStack.indexOf("name") to get the index of target stage.

With maintaining the name stack, it handles the naming collisions by rollbacking to the newest named stage.