id
int64
0
458k
file_name
stringlengths
4
119
file_path
stringlengths
14
227
content
stringlengths
24
9.96M
size
int64
24
9.96M
language
stringclasses
1 value
extension
stringclasses
14 values
total_lines
int64
1
219k
avg_line_length
float64
2.52
4.63M
max_line_length
int64
5
9.91M
alphanum_fraction
float64
0
1
repo_name
stringlengths
7
101
repo_stars
int64
100
139k
repo_forks
int64
0
26.4k
repo_open_issues
int64
0
2.27k
repo_license
stringclasses
12 values
repo_extraction_date
stringclasses
433 values
12,200
util.py
SirVer_ultisnips/test/util.py
import platform try: import unidecode UNIDECODE_IMPORTED = True except ImportError: UNIDECODE_IMPORTED = False def running_on_windows(): if platform.system() == "Windows": return "Does not work on Windows." def no_unidecode_available(): if not UNIDECODE_IMPORTED: return "unidecode is not available."
343
Python
.py
12
24.083333
44
0.72
SirVer/ultisnips
7,501
688
112
GPL-3.0
9/5/2024, 5:11:34 PM (Europe/Amsterdam)
12,201
test_SnippetActions.py
SirVer_ultisnips/test/test_SnippetActions.py
from test.vim_test_case import VimTestCase as _VimTest from test.constant import * class SnippetActions_PreActionModifiesBuffer(_VimTest): files = { "us/all.snippets": r""" pre_expand "snip.buffer[snip.line:snip.line] = ['\n']" snippet a "desc" "True" e abc endsnippet """ } keys = "a" + EX wanted = "\nabc" class SnippetActions_PostActionModifiesBuffer(_VimTest): files = { "us/all.snippets": r""" post_expand "snip.buffer[snip.line+1:snip.line+1] = ['\n']" snippet a "desc" "True" e abc endsnippet """ } keys = "a" + EX wanted = "abc\n" class SnippetActions_ErrorOnBufferModificationThroughCommand(_VimTest): files = { "us/all.snippets": r""" pre_expand "vim.command('normal O')" snippet a "desc" "True" e abc endsnippet """ } keys = "a" + EX expected_error = "changes are untrackable" class SnippetActions_ErrorOnModificationSnippetLine(_VimTest): files = { "us/all.snippets": r""" post_expand "vim.command('normal dd')" snippet i "desc" "True" e if: $1 endsnippet """ } keys = "i" + EX expected_error = "line under the cursor was modified" class SnippetActions_EnsureIndent(_VimTest): files = { "us/all.snippets": r""" pre_expand "snip.buffer[snip.line] = ' '*4; snip.cursor[1] = 4" snippet i "desc" "True" e if: $1 endsnippet """ } keys = "\ni" + EX + "i" + EX + "x" wanted = """ if: if: x""" class SnippetActions_PostActionCanUseSnippetRange(_VimTest): files = { "us/all.snippets": r""" global !p def ensure_newlines(start, end): snip.buffer[start[0]:start[0]] = ['\n'] * 2 snip.buffer[end[0]+1:end[0]+1] = ['\n'] * 1 endglobal post_expand "ensure_newlines(snip.snippet_start, snip.snippet_end)" snippet i "desc" if $1 else $2 end endsnippet """ } keys = "\ni" + EX + "x" + JF + "y" wanted = """ if x else y end """ class SnippetActions_CanModifyParentBody(_VimTest): files = { "us/all.snippets": r""" global !p def ensure_newlines(start, end): snip.buffer[start[0]:start[0]] = ['\n'] * 2 endglobal post_expand "ensure_newlines(snip.snippet_start, snip.snippet_end)" snippet i "desc" if $1 else $2 end endsnippet """ } keys = "\ni" + EX + "i" + EX + "x" + JF + "y" + JF + JF + "z" wanted = """ if if x else y end else z end""" class SnippetActions_MoveParentSnippetFromChildInPreAction(_VimTest): files = { "us/all.snippets": r""" global !p def insert_import(): snip.buffer[2:2] = ['import smthing', ''] endglobal pre_expand "insert_import()" snippet p "desc" print(smthing.traceback()) endsnippet snippet i "desc" if $1 else $2 end endsnippet """ } keys = "i" + EX + "p" + EX + JF + "z" wanted = """import smthing if print(smthing.traceback()) else z end""" class SnippetActions_CanExpandSnippetInDifferentPlace(_VimTest): files = { "us/all.snippets": r""" global !p def expand_after_if(snip): snip.buffer[snip.line] = snip.buffer[snip.line][:snip.column] + \ snip.buffer[snip.line][snip.column+1:] snip.cursor[1] = snip.buffer[snip.line].index('if ')+3 endglobal pre_expand "expand_after_if(snip)" snippet n "append not to if" w not $0 endsnippet snippet i "if cond" w if $1: $2 endsnippet """ } keys = "i" + EX + "blah" + JF + "n" + EX + JF + "pass" wanted = """if not blah: pass""" class SnippetActions_MoveVisual(_VimTest): files = { "us/all.snippets": r""" global !p def extract_method(snip): del snip.buffer[snip.line] snip.buffer[len(snip.buffer)-1:len(snip.buffer)-1] = [''] snip.cursor.set(len(snip.buffer)-2, 0) endglobal pre_expand "extract_method(snip)" snippet n "append not to if" w def $1: ${VISUAL} endsnippet """ } keys = ( """ def a: x() y() z()""" + ESC + "kVk" + EX + "n" + EX + "b" ) wanted = """ def a: z() def b: x() y()""" class SnippetActions_CanMirrorTabStopsOutsideOfSnippet(_VimTest): files = { "us/all.snippets": r""" post_jump "snip.buffer[2] = 'debug({})'.format(snip.tabstops[1].current_text)" snippet i "desc" if $1: $2 endsnippet """ } keys = ( """ --- i""" + EX + "test(some(complex(cond(a))))" + JF + "x" ) wanted = """debug(test(some(complex(cond(a))))) --- if test(some(complex(cond(a)))): x""" class SnippetActions_CanExpandAnonSnippetInJumpAction(_VimTest): files = { "us/all.snippets": r""" global !p def expand_anon(snip): if snip.tabstop == 0: snip.expand_anon("a($2, $1)") endglobal post_jump "expand_anon(snip)" snippet i "desc" if ${1:cond}: $0 endsnippet """ } keys = "i" + EX + "x" + JF + "1" + JF + "2" + JF + ";" wanted = """if x: a(2, 1);""" class SnippetActions_CanExpandAnonSnippetInJumpActionWhileSelected(_VimTest): files = { "us/all.snippets": r""" global !p def expand_anon(snip): if snip.tabstop == 0: snip.expand_anon(" // a($2, $1)") endglobal post_jump "expand_anon(snip)" snippet i "desc" if ${1:cond}: ${2:pass} endsnippet """ } keys = "i" + EX + "x" + JF + JF + "1" + JF + "2" + JF + ";" wanted = """if x: pass // a(2, 1);""" class SnippetActions_CanUseContextFromContextMatch(_VimTest): files = { "us/all.snippets": r""" pre_expand "snip.buffer[snip.line:snip.line] = [snip.context]" snippet i "desc" "'some context'" e body endsnippet """ } keys = "i" + EX wanted = """some context body""" class SnippetActions_CanExpandAnonSnippetOnFirstJump(_VimTest): files = { "us/all.snippets": r""" global !p def expand_new_snippet_on_first_jump(snip): if snip.tabstop == 1: snip.expand_anon("some_check($1, $2, $3)") endglobal post_jump "expand_new_snippet_on_first_jump(snip)" snippet "test" "test new features" "True" bwre if $1: $2 endsnippet """ } keys = "test" + EX + "1" + JF + "2" + JF + "3" + JF + " or 4" + JF + "5" wanted = """if some_check(1, 2, 3) or 4: 5""" class SnippetActions_CanExpandAnonOnPreExpand(_VimTest): files = { "us/all.snippets": r""" pre_expand "snip.buffer[snip.line] = ''; snip.expand_anon('totally_different($2, $1)')" snippet test "test new features" wb endsnippet """ } keys = "test" + EX + "1" + JF + "2" + JF + "3" wanted = """totally_different(2, 1)3""" class SnippetActions_CanEvenWrapSnippetInPreAction(_VimTest): files = { "us/all.snippets": r""" pre_expand "snip.buffer[snip.line] = ''; snip.expand_anon('some_wrapper($1): $2')" snippet test "test new features" wb wrapme($2, $1) endsnippet """ } keys = "test" + EX + "1" + JF + "2" + JF + "3" + JF + "4" wanted = """some_wrapper(wrapme(2, 1)3): 4""" class SnippetActions_CanVisuallySelectFirstPlaceholderInAnonSnippetInPre(_VimTest): files = { "us/all.snippets": r""" pre_expand "snip.buffer[snip.line] = ''; snip.expand_anon('${1:asd}, ${2:blah}')" snippet test "test new features" wb endsnippet """ } keys = "test" + EX + "1" + JF + "2" wanted = """1, 2""" class SnippetActions_UseCorrectJumpActions(_VimTest): files = { "us/all.snippets": r""" post_jump "snip.buffer[-2:-2]=['a' + str(snip.tabstop)]" snippet a "a" wb $1 { $2 } endsnippet snippet b "b" wb bbb endsnippet post_jump "snip.buffer[-2:-2]=['c' + str(snip.tabstop)]" snippet c "c" w $1 : $2 : $3 endsnippet """ } keys = ( "a" + EX + "1" + JF + "b" + EX + " c" + EX + "2" + JF + "3" + JF + "4" + JF + JF ) wanted = """1 { bbb 2 : 3 : 4 } a1 a2 c1 c2 c3 c0 a0""" class SnippetActions_PostActionModifiesCharAfterSnippet(_VimTest): files = { "us/all.snippets": r""" post_expand "snip.buffer[snip.snippet_end[0]] = snip.buffer[snip.snippet_end[0]][:-1]" snippet a "desc" i ($1) endsnippet """ } keys = "[]" + ARR_L + "a" + EX + "1" + JF + "2" wanted = "[(1)2" class SnippetActions_PostActionModifiesLineAfterSnippet(_VimTest): files = { "us/all.snippets": r""" post_expand "snip.buffer[snip.snippet_end[0]+1:snip.snippet_end[0]+2] = []" snippet a "desc" 1: $1 $0 endsnippet """ } keys = "\n3" + ARR_U + "a" + EX + "1" + JF + "2" wanted = "1: 1\n2" class SnippetActions_DoNotBreakCursorOnSingleLikeChange(_VimTest): files = { "us/all.snippets": r""" post_expand "snip.buffer[snip.snippet_end[0]] = 'def'; snip.cursor.preserve()" snippet a "desc" asd endsnippet """ } keys = "a" + EX + "123" wanted = "def123"
10,116
Python
.py
381
19.265092
95
0.517998
SirVer/ultisnips
7,501
688
112
GPL-3.0
9/5/2024, 5:11:34 PM (Europe/Amsterdam)
12,202
test_Choices.py
SirVer_ultisnips/test/test_Choices.py
from test.vim_test_case import VimTestCase as _VimTest from test.constant import * class Choices_WillBeExpandedToInlineSelection(_VimTest): snippets = ("test", "${1|red,gray|}") keys = "test" + EX wanted = "1.red|2.gray" class Choices_ExpectCorrectResult(_VimTest): snippets = ("test", "${1|red,gray|}") keys = "test" + EX + "2" wanted = "gray" class Choices_WillAbandonSelection_If_CharTyped(_VimTest): snippets = ("test", "${1|red,green|}") keys = "test" + EX + "char" wanted = "char" class Choices_WillAbandonSelection_If_InputIsGreaterThanMaxSelectionIndex(_VimTest): snippets = ("test", "${1|red,green|}") keys = "test" + EX + "3" wanted = "3" class Choices_WilNotMessWithTabstopsAfterIt(_VimTest): snippets = ("test", "${1|red,gray|} is ${2:color}\nline 2") keys = "test" + EX + "2" wanted = "gray is color\nline 2" class Choices_MoreThan9Candidates_ShouldWaitForInputs(_VimTest): snippets = ("test", "${1|a,b,c,d,e,f,g,h,i,j,k,l,m,n|} is ${2:a char}") keys = "test" + EX + "1" wanted = "1 is a char" class Choices_MoreThan9Candidates_ShouldTerminateWithSpace(_VimTest): snippets = ("test", "${1|a,b,c,d,e,f,g,h,i,j,k,l,m,n|} is ${2:a char}") keys = "test" + EX + "1 " wanted = "a is a char" class Choices_EmptyChoiceWillBeDiscarded(_VimTest): snippets = ("test", "${1|a,,c|}") keys = "test" + EX wanted = "1.a|2.c" class Choices_WillNotExpand_If_ChoiceListIsEmpty(_VimTest): snippets = ("test", "${1||}") keys = "test" + EX wanted = "||" class Choices_CanTakeNonAsciiCharacters(_VimTest): snippets = ("test", "${1|Русский язык,中文,한국어,öääö|}") keys = "test" + EX wanted = "1.Русский язык|2.中文|3.한국어|4.öääö" class Choices_AsNestedElement_ShouldOverwriteDefaultText(_VimTest): snippets = ("test", "${1:outer ${2|foo,blah|}}") keys = "test" + EX wanted = "outer 1.foo|2.blah" class Choices_AsNestedElement_ShallNotTakeActionIfParentInput(_VimTest): snippets = ("test", "${1:outer ${2|foo,blah|}}") keys = "test" + EX + "input" wanted = "input" class Choices_AsNestedElement_CanBeTabbedInto(_VimTest): snippets = ("test", "${1:outer ${2|foo,blah|}}") keys = "test" + EX + JF + "1" wanted = "outer foo" class Choices_AsNestedElement_CanBeTabbedThrough(_VimTest): snippets = ("test", "${1:outer ${2|foo,blah|}} ${3}") keys = "test" + EX + JF + JF + "input" wanted = "outer 1.foo|2.blah input" class Choices_With_Mirror(_VimTest): snippets = ("test", "${1|cyan,magenta|}, mirror: $1") keys = "test" + EX + "1" wanted = "cyan, mirror: cyan" class Choices_With_Mirror_ContinueMirroring_EvenAfterSelectionDone(_VimTest): snippets = ("test", "${1|cyan,magenta|}, mirror: $1") keys = "test" + EX + "1 is a color" wanted = "cyan is a color, mirror: cyan is a color" class Choices_ShouldThrowErrorWithZeroTabstop(_VimTest): snippets = ("test", "${0|red,blue|}") keys = "test" + EX expected_error = "Choices selection is not supported on \$0" class Choices_CanEscapeCommaInsideChoiceItem(_VimTest): snippets = ( "test", r"${1|fun1(,fun2(param1\, ,fun3(param1\, param2\, |}param_end) result: $1", ) keys = "test" + EX + "2" wanted = "fun2(param1, param_end) result: fun2(param1, "
3,393
Python
.py
77
38.883117
84
0.641176
SirVer/ultisnips
7,501
688
112
GPL-3.0
9/5/2024, 5:11:34 PM (Europe/Amsterdam)
12,203
test_Visual.py
SirVer_ultisnips/test/test_Visual.py
from test.vim_test_case import VimTestCase as _VimTest from test.constant import * class Visual_NoVisualSelection_Ignore(_VimTest): snippets = ("test", "h${VISUAL}b") keys = "test" + EX + "abc" wanted = "hbabc" class Visual_SelectOneWord(_VimTest): snippets = ("test", "h${VISUAL}b") keys = "blablub" + ESC + "0v6l" + EX + "test" + EX wanted = "hblablubb" class Visual_SelectOneWordInclusive(_VimTest): snippets = ("test", "h${VISUAL}b", "", "i") keys = "xxxyyyyxxx" + ESC + "4|vlll" + EX + "test" + EX wanted = "xxxhyyyybxxx" class Visual_SelectOneWordExclusive(_VimTest): snippets = ("test", "h${VISUAL}b", "", "i") keys = "xxxyyyyxxx" + ESC + "4|vlll" + EX + "test" + EX wanted = "xxxhyyybyxxx" def _extra_vim_config(self, vim_config): vim_config.append("set selection=exclusive") class Visual_SelectOneWord_ProblemAfterTab(_VimTest): snippets = ("test", "h${VISUAL}b", "", "i") keys = "\tblablub" + ESC + "5hv3l" + EX + "test" + EX wanted = "\tbhlablbub" class VisualWithDefault_ExpandWithoutVisual(_VimTest): snippets = ("test", "h${VISUAL:world}b") keys = "test" + EX + "hi" wanted = "hworldbhi" class VisualWithDefaultWithSlashes_ExpandWithoutVisual(_VimTest): snippets = ("test", r"h${VISUAL:\/\/ body}b") keys = "test" + EX + "hi" wanted = "h// bodybhi" class VisualWithDefault_ExpandWithVisual(_VimTest): snippets = ("test", "h${VISUAL:world}b") keys = "blablub" + ESC + "0v6l" + EX + "test" + EX wanted = "hblablubb" class Visual_ExpandTwice(_VimTest): snippets = ("test", "h${VISUAL}b") keys = "blablub" + ESC + "0v6l" + EX + "test" + EX + "\ntest" + EX wanted = "hblablubb\nhb" class Visual_SelectOneWord_TwiceVisual(_VimTest): snippets = ("test", "h${VISUAL}b${VISUAL}a") keys = "blablub" + ESC + "0v6l" + EX + "test" + EX wanted = "hblablubbblabluba" class Visual_SelectOneWord_Inword(_VimTest): snippets = ("test", "h${VISUAL}b", "Description", "i") keys = "blablub" + ESC + "0lv4l" + EX + "test" + EX wanted = "bhlablubb" class Visual_SelectOneWord_TillEndOfLine(_VimTest): snippets = ("test", "h${VISUAL}b", "Description", "i") keys = "blablub" + ESC + "0v$" + EX + "test" + EX + ESC + "o" wanted = "hblablub\nb" class Visual_SelectOneWordWithTabstop_TillEndOfLine(_VimTest): snippets = ("test", "h${2:ahh}${VISUAL}${1:ups}b", "Description", "i") keys = ( "blablub" + ESC + "0v$" + EX + "test" + EX + "mmm" + JF + "n" + JF + "done" + ESC + "o" ) wanted = "hnblablub\nmmmbdone" class Visual_InDefaultText_SelectOneWord_NoOverwrite(_VimTest): snippets = ("test", "h${1:${VISUAL}}b") keys = "blablub" + ESC + "0v6l" + EX + "test" + EX + JF + "hello" wanted = "hblablubbhello" class Visual_InDefaultText_SelectOneWord(_VimTest): snippets = ("test", "h${1:${VISUAL}}b") keys = "blablub" + ESC + "0v6l" + EX + "test" + EX + "hello" wanted = "hhellob" class Visual_CrossOneLine(_VimTest): snippets = ("test", "h${VISUAL}b") keys = "bla blub\n helloi" + ESC + "0k4lvjll" + EX + "test" + EX wanted = "bla hblub\n hellobi" class Visual_LineSelect_Simple(_VimTest): snippets = ("test", "h${VISUAL}b") keys = "hello\nnice\nworld" + ESC + "Vkk" + EX + "test" + EX wanted = "hhello\n nice\n worldb" class Visual_InDefaultText_LineSelect_NoOverwrite(_VimTest): snippets = ("test", "h${1:bef${VISUAL}aft}b") keys = "hello\nnice\nworld" + ESC + "Vkk" + EX + "test" + EX + JF + "hi" wanted = "hbefhello\n nice\n worldaftbhi" class Visual_InDefaultText_LineSelect_Overwrite(_VimTest): snippets = ("test", "h${1:bef${VISUAL}aft}b") keys = "hello\nnice\nworld" + ESC + "Vkk" + EX + "test" + EX + "jup" + JF + "hi" wanted = "hjupbhi" class Visual_LineSelect_CheckIndentSimple(_VimTest): snippets = ("test", "beg\n\t${VISUAL}\nend") keys = "hello\nnice\nworld" + ESC + "Vkk" + EX + "test" + EX wanted = "beg\n\thello\n\tnice\n\tworld\nend" class Visual_LineSelect_CheckIndentTwice(_VimTest): snippets = ("test", "beg\n\t${VISUAL}\nend") keys = " hello\n nice\n\tworld" + ESC + "Vkk" + EX + "test" + EX wanted = "beg\n\t hello\n\t nice\n\t\tworld\nend" class Visual_InDefaultText_IndentSpacesToTabstop_NoOverwrite(_VimTest): snippets = ("test", "h${1:beforea${VISUAL}aft}b") keys = "hello\nnice\nworld" + ESC + "Vkk" + EX + "test" + EX + JF + "hi" wanted = "hbeforeahello\n\tnice\n\tworldaftbhi" class Visual_InDefaultText_IndentSpacesToTabstop_Overwrite(_VimTest): snippets = ("test", "h${1:beforea${VISUAL}aft}b") keys = "hello\nnice\nworld" + ESC + "Vkk" + EX + "test" + EX + "ups" + JF + "hi" wanted = "hupsbhi" class Visual_InDefaultText_IndentSpacesToTabstop_NoOverwrite1(_VimTest): snippets = ("test", "h${1:beforeaaa${VISUAL}aft}b") keys = "hello\nnice\nworld" + ESC + "Vkk" + EX + "test" + EX + JF + "hi" wanted = "hbeforeaaahello\n\t nice\n\t worldaftbhi" class Visual_InDefaultText_IndentBeforeTabstop_NoOverwrite(_VimTest): snippets = ("test", "hello\n\t ${1:${VISUAL}}\nend") keys = "hello\nnice\nworld" + ESC + "Vkk" + EX + "test" + EX + JF + "hi" wanted = "hello\n\t hello\n\t nice\n\t world\nendhi" class Visual_LineSelect_WithTabStop(_VimTest): snippets = ("test", "beg\n\t${VISUAL}\n\t${1:here_we_go}\nend") keys = "hello\nnice\nworld" + ESC + "Vkk" + EX + "test" + EX + "super" + JF + "done" wanted = "beg\n\thello\n\tnice\n\tworld\n\tsuper\nenddone" class Visual_LineSelect_CheckIndentWithTS_NoOverwrite(_VimTest): snippets = ("test", "beg\n\t${0:${VISUAL}}\nend") keys = "hello\nnice\nworld" + ESC + "Vkk" + EX + "test" + EX wanted = "beg\n\thello\n\tnice\n\tworld\nend" class Visual_LineSelect_DedentLine(_VimTest): snippets = ("if", "if {\n\t${VISUAL}$0\n}") keys = ( "if" + EX + "one\n\ttwo\n\tthree" + ESC + ARR_U * 2 + "V" + ARR_D + EX + "\tif" + EX ) wanted = "if {\n\tif {\n\t\tone\n\t\ttwo\n\t}\n\tthree\n}" class VisualTransformation_SelectOneWord(_VimTest): snippets = ("test", r"h${VISUAL/./\U$0\E/g}b") keys = "blablub" + ESC + "0v6l" + EX + "test" + EX wanted = "hBLABLUBb" class VisualTransformationWithDefault_ExpandWithoutVisual(_VimTest): snippets = ("test", r"h${VISUAL:world/./\U$0\E/g}b") keys = "test" + EX + "hi" wanted = "hWORLDbhi" class VisualTransformationWithDefault_ExpandWithVisual(_VimTest): snippets = ("test", r"h${VISUAL:world/./\U$0\E/g}b") keys = "blablub" + ESC + "0v6l" + EX + "test" + EX wanted = "hBLABLUBb" class VisualTransformation_LineSelect_Simple(_VimTest): snippets = ("test", r"h${VISUAL/./\U$0\E/g}b") keys = "hello\nnice\nworld" + ESC + "Vkk" + EX + "test" + EX wanted = "hHELLO\n NICE\n WORLDb" class VisualTransformation_InDefaultText_LineSelect_NoOverwrite(_VimTest): snippets = ("test", r"h${1:bef${VISUAL/./\U$0\E/g}aft}b") keys = "hello\nnice\nworld" + ESC + "Vkk" + EX + "test" + EX + JF + "hi" wanted = "hbefHELLO\n NICE\n WORLDaftbhi" class VisualTransformation_InDefaultText_LineSelect_Overwrite(_VimTest): snippets = ("test", r"h${1:bef${VISUAL/./\U$0\E/g}aft}b") keys = "hello\nnice\nworld" + ESC + "Vkk" + EX + "test" + EX + "jup" + JF + "hi" wanted = "hjupbhi"
7,548
Python
.py
165
40.618182
88
0.616079
SirVer/ultisnips
7,501
688
112
GPL-3.0
9/5/2024, 5:11:34 PM (Europe/Amsterdam)
12,204
test_Autocommands.py
SirVer_ultisnips/test/test_Autocommands.py
# encoding: utf-8 from test.vim_test_case import VimTestCase as _VimTest from test.constant import * class Autocommands(_VimTest): snippets = ("test", "[ ${1:foo} ]") args = "" keys = ( "test" + EX + "test" + EX + "bar" + JF + JF + " done " + ESC + ':execute "normal aM" . g:mapper_call_count . "\<Esc>"' + "\n" + ':execute "normal aU" . g:unmapper_call_count . "\<Esc>"' + "\n" ) wanted = "[ [ bar ] ] done M1U1" def _extra_vim_config(self, vim_config): vim_config.append("let g:mapper_call_count = 0") vim_config.append("function! CustomMapper()") vim_config.append(" let g:mapper_call_count += 1") vim_config.append("endfunction") vim_config.append("let g:unmapper_call_count = 0") vim_config.append("function! CustomUnmapper()") vim_config.append(" let g:unmapper_call_count += 1") vim_config.append("endfunction") vim_config.append("autocmd! User UltiSnipsEnterFirstSnippet") vim_config.append("autocmd User UltiSnipsEnterFirstSnippet call CustomMapper()") vim_config.append("autocmd! User UltiSnipsExitLastSnippet") vim_config.append("autocmd User UltiSnipsExitLastSnippet call CustomUnmapper()")
1,334
Python
.py
35
30.571429
88
0.601236
SirVer/ultisnips
7,501
688
112
GPL-3.0
9/5/2024, 5:11:34 PM (Europe/Amsterdam)
12,205
vim_interface.py
SirVer_ultisnips/test/vim_interface.py
# encoding: utf-8 import os import re import shutil import subprocess import tempfile import textwrap import time from test.constant import ARR_D, ARR_L, ARR_R, ARR_U, BS, ESC, SEQUENCES def wait_until_file_exists(file_path, times=None, interval=0.01): while times is None or times: if os.path.exists(file_path): return True time.sleep(interval) if times is not None: times -= 1 return False def _read_text_file(filename): """Reads the content of a text file.""" with open(filename, "r", encoding="utf-8") as to_read: return to_read.read() def is_process_running(pid): """Returns true if a process with pid is running, false otherwise.""" # from # http://stackoverflow.com/questions/568271/how-to-check-if-there-exists-a-process-with-a-given-pid try: os.kill(pid, 0) except OSError: return False else: return True def create_directory(dirname): """Creates 'dirname' and its parents if it does not exist.""" try: os.makedirs(dirname) except OSError: pass class TempFileManager: def __init__(self, name=""): self._temp_dir = tempfile.mkdtemp(prefix="UltiSnipsTest_" + name) def name_temp(self, file_path): return os.path.join(self._temp_dir, file_path) def write_temp(self, file_path, content): abs_path = self.name_temp(file_path) create_directory(os.path.dirname(abs_path)) with open(abs_path, "w", encoding="utf-8") as f: f.write(content) return abs_path def unique_name_temp(self, suffix="", prefix=""): file_handler, abspath = tempfile.mkstemp(suffix, prefix, self._temp_dir) os.close(file_handler) os.remove(abspath) return abspath def clear_temp(self): shutil.rmtree(self._temp_dir) create_directory(self._temp_dir) class VimInterface(TempFileManager): def __init__(self, vim_executable, name): TempFileManager.__init__(self, name) self._vim_executable = vim_executable @property def vim_executable(self): return self._vim_executable def has_version(self, major, minor, patchlevel): cmd = [ self._vim_executable, "-e", "-c", "if has('patch-%d.%d.%d') | quit | else | cquit | endif" % (major, minor, patchlevel), ] return not subprocess.call(cmd, stdout=subprocess.DEVNULL) def get_buffer_data(self): buffer_path = self.unique_name_temp(prefix="buffer_") self.send_to_vim(ESC + ":w! %s\n" % buffer_path) if wait_until_file_exists(buffer_path, 50): return _read_text_file(buffer_path)[:-1] def send_to_terminal(self, s): """Types 's' into the terminal.""" raise NotImplementedError() def send_to_vim(self, s): """Types 's' into the vim instance under test.""" raise NotImplementedError() def launch(self, config=[]): """Returns the python version in Vim as a string, e.g. '3.7'""" pid_file = self.name_temp("vim.pid") version_file = self.name_temp("vim_version") if os.path.exists(version_file): os.remove(version_file) done_file = self.name_temp("loading_done") if os.path.exists(done_file): os.remove(done_file) post_config = [] post_config.append("py3 << EOF") post_config.append("import vim, sys") post_config.append( "with open('%s', 'w') as pid_file: pid_file.write(vim.eval('getpid()'))" % pid_file ) post_config.append("with open('%s', 'w') as version_file:" % version_file) post_config.append(" version_file.write('%i.%i.%i' % sys.version_info[:3])") post_config.append("with open('%s', 'w') as done_file:" % done_file) post_config.append(" done_file.write('all_done!')") post_config.append("EOF") config_path = self.write_temp( "vim_config.vim", textwrap.dedent(os.linesep.join(config + post_config) + "\n"), ) # Note the space to exclude it from shell history. Also we always set # NVIM_LISTEN_ADDRESS, even when running vanilla Vim, because it will # just not care. self.send_to_terminal( """ NVIM_LISTEN_ADDRESS=/tmp/nvim %s -u %s\r\n""" % (self._vim_executable, config_path) ) wait_until_file_exists(done_file) self._vim_pid = int(_read_text_file(pid_file)) return _read_text_file(version_file).strip() def leave_with_wait(self): self.send_to_vim(3 * ESC + ":qa!\n") while is_process_running(self._vim_pid): time.sleep(0.01) class VimInterfaceTmux(VimInterface): def __init__(self, vim_executable, session): VimInterface.__init__(self, vim_executable, "Tmux") self.session = session self._check_version() def _send(self, s): # I did not find any documentation on what needs escaping when sending # to tmux, but it seems like this is all that is needed for now. s = s.replace(";", r"\;") if len(s) == 1: subprocess.check_call( ["tmux", "send-keys", "-t", self.session, hex(ord(s))] ) else: subprocess.check_call(["tmux", "send-keys", "-t", self.session, "-l", s]) def send_to_terminal(self, s): return self._send(s) def send_to_vim(self, s): return self._send(s) def _check_version(self): stdout, _ = subprocess.Popen( ["tmux", "-V"], stdout=subprocess.PIPE, stderr=subprocess.PIPE ).communicate() stdout = stdout.decode("utf-8") m = re.match(r"tmux (\d+).(\d+)", stdout) if not m or not (int(m.group(1)), int(m.group(2))) >= (1, 8): raise RuntimeError("Need at least tmux 1.8, you have %s." % stdout.strip()) class VimInterfaceTmuxNeovim(VimInterfaceTmux): def __init__(self, vim_executable, session): VimInterfaceTmux.__init__(self, vim_executable, session) self._nvim = None def send_to_vim(self, s): if s == ARR_L: s = "<Left>" elif s == ARR_R: s = "<Right>" elif s == ARR_U: s = "<Up>" elif s == ARR_D: s = "<Down>" elif s == BS: s = "<bs>" elif s == ESC: s = "<esc>" elif s == "<": s = "<lt>" self._nvim.input(s) def launch(self, config=[]): import neovim rv = VimInterfaceTmux.launch(self, config) self._nvim = neovim.attach("socket", path="/tmp/nvim") return rv class VimInterfaceWindows(VimInterface): BRACES = re.compile("([}{])") WIN_ESCAPES = ["+", "^", "%", "~", "[", "]", "<", ">", "(", ")"] WIN_REPLACES = [ (BS, "{BS}"), (ARR_L, "{LEFT}"), (ARR_R, "{RIGHT}"), (ARR_U, "{UP}"), (ARR_D, "{DOWN}"), ("\t", "{TAB}"), ("\n", "~"), (ESC, "{ESC}"), # On my system ` waits for a second keystroke, so `+SPACE = "`". On # most systems, `+Space = "` ". I work around this, by sending the host # ` as `+_+BS. Awkward, but the only way I found to get this working. ("`", "`_{BS}"), ("´", "´_{BS}"), ("{^}", "{^}_{BS}"), ] def __init__(self): # import windows specific modules import win32com.client import win32gui self.win32gui = win32gui self.shell = win32com.client.Dispatch("WScript.Shell") def is_focused(self, title=None): cur_title = self.win32gui.GetWindowText(self.win32gui.GetForegroundWindow()) if (title or "- GVIM") in cur_title: return True return False def focus(self, title=None): if not self.shell.AppActivate(title or "- GVIM"): raise Exception("Failed to switch to GVim window") time.sleep(1) def convert_keys(self, keys): keys = self.BRACES.sub(r"{\1}", keys) for k in self.WIN_ESCAPES: keys = keys.replace(k, "{%s}" % k) for f, r in self.WIN_REPLACES: keys = keys.replace(f, r) return keys def send(self, keys): keys = self.convert_keys(keys) if not self.is_focused(): time.sleep(2) self.focus() if not self.is_focused(): # This is the only way I can find to stop test execution raise KeyboardInterrupt("Failed to focus GVIM") self.shell.SendKeys(keys)
8,664
Python
.py
222
30.531532
103
0.573421
SirVer/ultisnips
7,501
688
112
GPL-3.0
9/5/2024, 5:11:34 PM (Europe/Amsterdam)
12,206
test_ContextSnippets.py
SirVer_ultisnips/test/test_ContextSnippets.py
from test.constant import * from test.vim_test_case import VimTestCase as _VimTest class ContextSnippets_SimpleSnippet(_VimTest): files = { "us/all.snippets": r""" snippet a "desc" "True" e abc endsnippet """ } keys = "a" + EX wanted = "abc" class ContextSnippets_ExpandOnTrue(_VimTest): files = { "us/all.snippets": r""" global !p def check_context(): return True endglobal snippet a "desc" "check_context()" e abc endsnippet """ } keys = "a" + EX wanted = "abc" class ContextSnippets_DoNotExpandOnFalse(_VimTest): files = { "us/all.snippets": r""" global !p def check_context(): return False endglobal snippet a "desc" "check_context()" e abc endsnippet """ } keys = "a" + EX wanted = keys class ContextSnippets_Before(_VimTest): files = { "us/all.snippets": r""" context "len(snip.before) >= 5 and snip.before" snippet dup "desc" i [`!p snip.rv = snip.context[:-3]`] endsnippet """ } word = "Süßölgefäß" keys = "adup" + EX + "\n" + word + "dup" + EX wanted = "adup" + EX + "\n" + word + "[" + word + "]" class ContextSnippets_UseContext(_VimTest): files = { "us/all.snippets": r""" global !p def wrap(ins): return "< " + ins + " >" endglobal snippet a "desc" "wrap(snip.buffer[snip.line])" e { `!p snip.rv = context` } endsnippet """ } keys = "a" + EX wanted = "{ < a > }" class ContextSnippets_SnippetPriority(_VimTest): files = { "us/all.snippets": r""" snippet i "desc" "re.search('err :=', snip.buffer[snip.line-1])" e if err != nil { ${1:// pass} } endsnippet snippet i if ${1:true} { ${2:// pass} } endsnippet """ } keys = ( r""" err := some_call() i""" + EX + JF + """ i""" + EX ) wanted = r""" err := some_call() if err != nil { // pass } if true { // pass }""" class ContextSnippets_PriorityKeyword(_VimTest): files = { "us/all.snippets": r""" snippet i "desc" "True" e a endsnippet priority 100 snippet i b endsnippet """ } keys = "i" + EX wanted = "b" class ContextSnippets_ReportError(_VimTest): files = { "us/all.snippets": r""" snippet e "desc" "Tru" e error endsnippet """ } keys = "e" + EX wanted = "e" + EX expected_error = r"NameError: name 'Tru' is not defined" class ContextSnippets_ReportErrorOnIndexOutOfRange(_VimTest): # Working around: https://github.com/neovim/python-client/issues/128. skip_if = lambda self: "Bug in Neovim." if self.vim_flavor == "neovim" else None files = { "us/all.snippets": r""" snippet e "desc" "snip.buffer[123]" e error endsnippet """ } keys = "e" + EX wanted = "e" + EX expected_error = r"IndexError: line number out of range" class ContextSnippets_CursorIsZeroBased(_VimTest): files = { "us/all.snippets": r""" snippet e "desc" "snip.cursor" e `!p snip.rv = str(snip.context)` endsnippet """ } keys = "e" + EX wanted = "(2, 1)" class ContextSnippets_ContextIsClearedBeforeExpand(_VimTest): files = { "us/all.snippets": r""" pre_expand "snip.context = 1 if snip.context is None else 2" snippet e "desc" w `!p snip.rv = str(snip.context)` endsnippet """ } keys = "e" + EX + " " + "e" + EX wanted = "1 1" class ContextSnippets_ContextHasAccessToVisual(_VimTest): files = { "us/all.snippets": r""" snippet test "desc" "snip.visual_text == '123'" we Yes endsnippet snippet test "desc" w No endsnippet """ } keys = ( "123" + ESC + "vhh" + EX + "test" + EX + " zzz" + ESC + "vhh" + EX + "test" + EX ) wanted = "Yes No" class ContextSnippets_Header_ExpandOnTrue(_VimTest): files = { "us/all.snippets": r""" global !p def check_context(): return True endglobal context "check_context()" snippet a "desc" e abc endsnippet """ } keys = "a" + EX wanted = "abc" class ContextSnippets_Header_DoNotExpandOnFalse(_VimTest): files = { "us/all.snippets": r""" global !p def check_context(): return False endglobal context "check_context()" snippet a "desc" e abc endsnippet """ } keys = "a" + EX wanted = keys class ContextSnippets_ContextHasAccessToReMatch(_VimTest): files = { "us/all.snippets": r""" context "match.group(1) != 'no'" snippet "(\w*) xxx" "desc" r HERE endsnippet """ } negative = "no xxx" positive = "yes xxx" keys = negative + EX + positive + EX wanted = negative + EX + "HERE"
5,438
Python
.py
216
17.685185
88
0.514114
SirVer/ultisnips
7,501
688
112
GPL-3.0
9/5/2024, 5:11:34 PM (Europe/Amsterdam)
12,207
test_Selection.py
SirVer_ultisnips/test/test_Selection.py
from test.vim_test_case import VimTestCase as _VimTest from test.constant import * # Test for bug 427298 # class _SelectModeMappings(_VimTest): snippets = ("test", "${1:World}") keys = "test" + EX + "Hello" wanted = "Hello" maps = ("", "") buffer_maps = ("", "") do_unmapping = True ignores = [] def _extra_vim_config(self, vim_config): vim_config.append( ":let g:UltiSnipsRemoveSelectModeMappings=%i" % int(self.do_unmapping) ) vim_config.append(":let g:UltiSnipsMappingsToIgnore=%s" % repr(self.ignores)) if not isinstance(self.maps[0], tuple): self.maps = (self.maps,) if not isinstance(self.buffer_maps[0], tuple): self.buffer_maps = (self.buffer_maps,) for key, m in self.maps: if not len(key): continue vim_config.append(":smap %s %s" % (key, m)) for key, m in self.buffer_maps: if not len(key): continue vim_config.append(":smap <buffer> %s %s" % (key, m)) class SelectModeMappings_RemoveBeforeSelecting_ECR(_SelectModeMappings): maps = ("H", "x") wanted = "Hello" class SelectModeMappings_DisableRemoveBeforeSelecting_ECR(_SelectModeMappings): do_unmapping = False maps = ("H", "x") wanted = "xello" class SelectModeMappings_IgnoreMappings_ECR(_SelectModeMappings): ignores = ["e"] maps = ("H", "x"), ("e", "l") wanted = "Hello" class SelectModeMappings_IgnoreMappings1_ECR(_SelectModeMappings): ignores = ["H"] maps = ("H", "x"), ("e", "l") wanted = "xello" class SelectModeMappings_IgnoreMappings2_ECR(_SelectModeMappings): ignores = ["e", "H"] maps = ("e", "l"), ("H", "x") wanted = "xello" class SelectModeMappings_BufferLocalMappings_ECR(_SelectModeMappings): buffer_maps = ("H", "blah") wanted = "Hello" class _ES_Base(_VimTest): def _extra_vim_config(self, vim_config): vim_config.append("set selection=exclusive") class ExclusiveSelection_SimpleTabstop_Test(_ES_Base): snippets = ("test", "h${1:blah}w $1") keys = "test" + EX + "ui" + JF wanted = "huiw ui" class ExclusiveSelection_RealWorldCase_Test(_ES_Base): snippets = ( "for", """for ($${1:i} = ${2:0}; $$1 < ${3:count}; $$1${4:++}) { ${5:// code} }""", ) keys = "for" + EX + "k" + JF wanted = """for ($k = 0; $k < count; $k++) { // code }""" class _OS_Base(_VimTest): def _extra_vim_config(self, vim_config): vim_config.append("set selection=old") class OldSelection_SimpleTabstop_Test(_OS_Base): snippets = ("test", "h${1:blah}w $1") keys = "test" + EX + "ui" + JF wanted = "huiw ui" class OldSelection_RealWorldCase_Test(_OS_Base): snippets = ( "for", """for ($${1:i} = ${2:0}; $$1 < ${3:count}; $$1${4:++}) { ${5:// code} }""", ) keys = "for" + EX + "k" + JF wanted = """for ($k = 0; $k < count; $k++) { // code }"""
3,006
Python
.py
86
29.139535
85
0.584083
SirVer/ultisnips
7,501
688
112
GPL-3.0
9/5/2024, 5:11:34 PM (Europe/Amsterdam)
12,208
test_Fixes.py
SirVer_ultisnips/test/test_Fixes.py
import unittest from test.vim_test_case import VimTestCase as _VimTest from test.constant import * class Bug1251994(_VimTest): snippets = ("test", "${2:#2} ${1:#1};$0") keys = " test" + EX + "hello" + JF + "world" + JF + "blub" wanted = " world hello;blub" # Test for https://github.com/SirVer/ultisnips/issues/157 (virtualedit) class VirtualEdit(_VimTest): snippets = ("pd", "padding: ${1:0}px") keys = "\t\t\tpd" + EX + "2" wanted = "\t\t\tpadding: 2px" def _extra_vim_config(self, vim_config): vim_config.append("set virtualedit=all") vim_config.append("set noexpandtab") # End: 1251994 # Test for Github Pull Request #134 - Retain unnamed register class RetainsTheUnnamedRegister(_VimTest): snippets = ("test", "${1:hello} ${2:world} ${0}") keys = "yank" + ESC + "by4lea test" + EX + "HELLO" + JF + JF + ESC + "p" wanted = "yank HELLO world yank" class RetainsTheUnnamedRegister_ButOnlyOnce(_VimTest): snippets = ("test", "${1:hello} ${2:world} ${0}") keys = ( "blahfasel" + ESC + "v" + 4 * ARR_L + "xotest" + EX + ESC + ARR_U + "v0xo" + ESC + "p" ) wanted = "\nblah\nhello world " # End: Github Pull Request # 134 # Test to ensure that shiftwidth follows tabstop when it's set to zero post # version 7.3.693. Prior to that version a shiftwidth of zero effectively # removes tabs. class ShiftWidthZero(_VimTest): def _extra_vim_config(self, vim_config): vim_config += ["if exists('*shiftwidth')", " set shiftwidth=0", "endif"] snippets = ("test", "\t${1}${0}") keys = "test" + EX + "foo" wanted = "\tfoo" # Test for https://github.com/SirVer/ultisnips/issues/171 # Make sure that we don't crash when trying to save and restore the clipboard # when it contains data that we can't coerce into Unicode. class NonUnicodeDataInUnnamedRegister(_VimTest): snippets = ("test", "hello") keys = ( "test" + EX + ESC + "\n".join( [ ":redir @a", ":messages", ":redir END", ( ":if match(@a, 'Error') != -1 | " + "call setline('.', 'error detected') | " + "3put a | " + "endif" ), "", ] ) ) wanted = "hello" def _before_test(self): # The string below was the one a user had on their clipboard when # encountering the UnicodeDecodeError and could not be coerced into # unicode. self.vim.send_to_vim( ':let @" = "\\x80kdI{\\x80@7 1},' + '\\x80kh\\x80kh\\x80kd\\x80kdq\\x80kb\\x1b"\n' ) # End: #171 # Test for #1184 # UltiSnips should pass through any mapping that it currently can't execute as # the trigger key class PassThroughNonexecutedTrigger(_VimTest): snippets = ("text", "Expand me!", "", "") keys = ( "tex" + EX + "more\n" # this should be passed through + "text" + EX # this should be expanded ) wanted = "tex" + EX + "more\nExpand me!" # End: #1184 # Tests for https://github.com/SirVer/ultisnips/issues/1386 (embedded null byte) NULL_BYTE = CTRL_V + "000" class NullByte_ListSnippets(_VimTest): snippets = ("word", "never expanded", "", "w") keys = "foobar" + NULL_BYTE + LS + "\n" wanted = "foobar\x00\n" class NullByte_ExpandAfter(_VimTest): snippets = ("test", "Expand me!", "", "w") keys = "foobar " + NULL_BYTE + "test" + EX wanted = "foobar \x00Expand me!" # End: #1386
3,712
Python
.py
106
28.056604
81
0.571308
SirVer/ultisnips
7,501
688
112
GPL-3.0
9/5/2024, 5:11:34 PM (Europe/Amsterdam)
12,209
test_Completion.py
SirVer_ultisnips/test/test_Completion.py
from test.vim_test_case import VimTestCase as _VimTest from test.constant import * class Completion_SimpleExample_ECR(_VimTest): snippets = ("test", "$1 ${1:blah}") keys = ( "superkallifragilistik\ntest" + EX + "sup" + COMPL_KW + COMPL_ACCEPT + " some more" ) wanted = ( "superkallifragilistik\nsuperkallifragilistik some more " "superkallifragilistik some more" ) # We need >2 different words with identical starts to create the # popup-menu: COMPLETION_OPTIONS = "completion1\ncompletion2\n" class Completion_ForwardsJumpWithoutCOMPL_ACCEPT(_VimTest): # completions should not be truncated when JF is activated without having # pressed COMPL_ACCEPT (Bug #598903) snippets = ("test", "$1 $2") keys = COMPLETION_OPTIONS + "test" + EX + "com" + COMPL_KW + JF + "foo" wanted = COMPLETION_OPTIONS + "completion1 foo" class Completion_BackwardsJumpWithoutCOMPL_ACCEPT(_VimTest): # completions should not be truncated when JB is activated without having # pressed COMPL_ACCEPT (Bug #598903) snippets = ("test", "$1 $2") keys = COMPLETION_OPTIONS + "test" + EX + "foo" + JF + "com" + COMPL_KW + JB + "foo" wanted = COMPLETION_OPTIONS + "foo completion1"
1,280
Python
.py
31
36.032258
88
0.679291
SirVer/ultisnips
7,501
688
112
GPL-3.0
9/5/2024, 5:11:34 PM (Europe/Amsterdam)
12,210
test_Mirror.py
SirVer_ultisnips/test/test_Mirror.py
from test.vim_test_case import VimTestCase as _VimTest from test.constant import * class TextTabStopTextAfterTab_ExpectCorrectResult(_VimTest): snippets = ("test", "$1 Hinten\n$1") keys = "test" + EX + "hallo" wanted = "hallo Hinten\nhallo" class TextTabStopTextBeforeTab_ExpectCorrectResult(_VimTest): snippets = ("test", "Vorne $1\n$1") keys = "test" + EX + "hallo" wanted = "Vorne hallo\nhallo" class TextTabStopTextSurroundedTab_ExpectCorrectResult(_VimTest): snippets = ("test", "Vorne $1 Hinten\n$1") keys = "test" + EX + "hallo test" wanted = "Vorne hallo test Hinten\nhallo test" class TextTabStopTextBeforeMirror_ExpectCorrectResult(_VimTest): snippets = ("test", "$1\nVorne $1") keys = "test" + EX + "hallo" wanted = "hallo\nVorne hallo" class TextTabStopAfterMirror_ExpectCorrectResult(_VimTest): snippets = ("test", "$1\n$1 Hinten") keys = "test" + EX + "hallo" wanted = "hallo\nhallo Hinten" class TextTabStopSurroundMirror_ExpectCorrectResult(_VimTest): snippets = ("test", "$1\nVorne $1 Hinten") keys = "test" + EX + "hallo welt" wanted = "hallo welt\nVorne hallo welt Hinten" class TextTabStopAllSurrounded_ExpectCorrectResult(_VimTest): snippets = ("test", "ObenVorne $1 ObenHinten\nVorne $1 Hinten") keys = "test" + EX + "hallo welt" wanted = "ObenVorne hallo welt ObenHinten\nVorne hallo welt Hinten" class MirrorBeforeTabstopLeave_ExpectCorrectResult(_VimTest): snippets = ("test", "$1 ${1:this is it} $1") keys = "test" + EX wanted = "this is it this is it this is it" class MirrorBeforeTabstopOverwrite_ExpectCorrectResult(_VimTest): snippets = ("test", "$1 ${1:this is it} $1") keys = "test" + EX + "a" wanted = "a a a" class TextTabStopSimpleMirrorMultiline_ExpectCorrectResult(_VimTest): snippets = ("test", "$1\n$1") keys = "test" + EX + "hallo" wanted = "hallo\nhallo" class SimpleMirrorMultilineMany_ExpectCorrectResult(_VimTest): snippets = ("test", " $1\n$1\na$1b\n$1\ntest $1 mich") keys = "test" + EX + "hallo" wanted = " hallo\nhallo\nahallob\nhallo\ntest hallo mich" class MultilineTabStopSimpleMirrorMultiline_ExpectCorrectResult(_VimTest): snippets = ("test", "$1\n\n$1\n\n$1") keys = "test" + EX + "hallo Du\nHi" wanted = "hallo Du\nHi\n\nhallo Du\nHi\n\nhallo Du\nHi" class MultilineTabStopSimpleMirrorMultiline1_ExpectCorrectResult(_VimTest): snippets = ("test", "$1\n$1\n$1") keys = "test" + EX + "hallo Du\nHi" wanted = "hallo Du\nHi\nhallo Du\nHi\nhallo Du\nHi" class MultilineTabStopSimpleMirrorDeleteInLine_ExpectCorrectResult(_VimTest): snippets = ("test", "$1\n$1\n$1") keys = "test" + EX + "hallo Du\nHi\b\bAch Blah" wanted = "hallo Du\nAch Blah\nhallo Du\nAch Blah\nhallo Du\nAch Blah" class TextTabStopSimpleMirrorMultilineMirrorInFront_ECR(_VimTest): snippets = ("test", "$1\n${1:sometext}") keys = "test" + EX + "hallo\nagain" wanted = "hallo\nagain\nhallo\nagain" class SimpleMirrorDelete_ExpectCorrectResult(_VimTest): snippets = ("test", "$1\n$1") keys = "test" + EX + "hallo\b\b" wanted = "hal\nhal" class SimpleMirrorSameLine_ExpectCorrectResult(_VimTest): snippets = ("test", "$1 $1") keys = "test" + EX + "hallo" wanted = "hallo hallo" class SimpleMirrorSameLineNoSpace_ExpectCorrectResult(_VimTest): snippets = ("test", "$1$1") keys = "test" + EX + "hallo" wanted = "hallohallo" class SimpleMirrorSameLineNoSpaceInsideOther_ExpectCorrectResult(_VimTest): snippets = (("test", "$1$1"), ("outer", "$1")) keys = "outer" + EX + "test" + EX + "hallo" wanted = "hallohallo" class SimpleMirrorSameLineNoSpaceSpaceAfter_ExpectCorrectResult(_VimTest): snippets = ("test", "$1$1 ") keys = "test" + EX + "hallo" wanted = "hallohallo " class SimpleMirrorSameLineNoSpaceInsideOtherSpaceAfter_ExpectCorrectResult(_VimTest): snippets = (("test", "$1$1 "), ("outer", "$1")) keys = "outer" + EX + "test" + EX + "hallo" wanted = "hallohallo " class SimpleMirrorSameLine_InText_ExpectCorrectResult(_VimTest): snippets = ("test", "$1 $1") keys = "ups test blah" + ESC + "02f i" + EX + "hallo" wanted = "ups hallo hallo blah" class SimpleMirrorSameLineBeforeTabDefVal_ECR(_VimTest): snippets = ("test", "$1 ${1:replace me}") keys = "test" + EX + "hallo foo" wanted = "hallo foo hallo foo" class SimpleMirrorSameLineBeforeTabDefVal_DelB4Typing_ECR(_VimTest): snippets = ("test", "$1 ${1:replace me}") keys = "test" + EX + BS + "hallo foo" wanted = "hallo foo hallo foo" class SimpleMirrorSameLineMany_ExpectCorrectResult(_VimTest): snippets = ("test", "$1 $1 $1 $1") keys = "test" + EX + "hallo du" wanted = "hallo du hallo du hallo du hallo du" class SimpleMirrorSameLineManyMultiline_ExpectCorrectResult(_VimTest): snippets = ("test", "$1 $1 $1 $1") keys = "test" + EX + "hallo du\nwie gehts" wanted = ( "hallo du\nwie gehts hallo du\nwie gehts hallo du\nwie gehts" " hallo du\nwie gehts" ) class SimpleMirrorDeleteSomeEnterSome_ExpectCorrectResult(_VimTest): snippets = ("test", "$1\n$1") keys = "test" + EX + "hallo\b\bhups" wanted = "halhups\nhalhups" class SimpleTabstopWithDefaultSimpelType_ExpectCorrectResult(_VimTest): snippets = ("test", "ha ${1:defa}\n$1") keys = "test" + EX + "world" wanted = "ha world\nworld" class SimpleTabstopWithDefaultComplexType_ExpectCorrectResult(_VimTest): snippets = ("test", "ha ${1:default value} $1\nanother: $1 mirror") keys = "test" + EX + "world" wanted = "ha world world\nanother: world mirror" class SimpleTabstopWithDefaultSimpelKeep_ExpectCorrectResult(_VimTest): snippets = ("test", "ha ${1:defa}\n$1") keys = "test" + EX wanted = "ha defa\ndefa" class SimpleTabstopWithDefaultComplexKeep_ExpectCorrectResult(_VimTest): snippets = ("test", "ha ${1:default value} $1\nanother: $1 mirror") keys = "test" + EX wanted = "ha default value default value\nanother: default value mirror" class TabstopWithMirrorManyFromAll_ExpectCorrectResult(_VimTest): snippets = ("test", "ha $5 ${1:blub} $4 $0 ${2:$1.h} $1 $3 ${4:More}") keys = ( "test" + EX + "hi" + JF + "hu" + JF + "hub" + JF + "hulla" + JF + "blah" + JF + "end" ) wanted = "ha blah hi hulla end hu hi hub hulla" class TabstopWithMirrorInDefaultNoType_ExpectCorrectResult(_VimTest): snippets = ("test", "ha ${1:blub} ${2:$1.h}") keys = "test" + EX wanted = "ha blub blub.h" class TabstopWithMirrorInDefaultNoType1_ExpectCorrectResult(_VimTest): snippets = ("test", "ha ${1:blub} ${2:$1}") keys = "test" + EX wanted = "ha blub blub" class TabstopWithMirrorInDefaultTwiceAndExtra_ExpectCorrectResult(_VimTest): snippets = ("test", "ha $1 ${2:$1.h $1.c}\ntest $1") keys = "test" + EX + "stdin" wanted = "ha stdin stdin.h stdin.c\ntest stdin" class TabstopWithMirrorInDefaultMultipleLeave_ExpectCorrectResult(_VimTest): snippets = ("test", "ha $1 ${2:snip} ${3:$1.h $2}") keys = "test" + EX + "stdin" wanted = "ha stdin snip stdin.h snip" class TabstopWithMirrorInDefaultMultipleOverwrite_ExpectCorrectResult(_VimTest): snippets = ("test", "ha $1 ${2:snip} ${3:$1.h $2}") keys = "test" + EX + "stdin" + JF + "do snap" wanted = "ha stdin do snap stdin.h do snap" class TabstopWithMirrorInDefaultOverwrite_ExpectCorrectResult(_VimTest): snippets = ("test", "ha $1 ${2:$1.h}") keys = "test" + EX + "stdin" + JF + "overwritten" wanted = "ha stdin overwritten" class TabstopWithMirrorInDefaultOverwrite1_ExpectCorrectResult(_VimTest): snippets = ("test", "ha $1 ${2:$1}") keys = "test" + EX + "stdin" + JF + "overwritten" wanted = "ha stdin overwritten" class TabstopWithMirrorInDefaultNoOverwrite1_ExpectCorrectResult(_VimTest): snippets = ("test", "ha $1 ${2:$1}") keys = "test" + EX + "stdin" + JF + JF + "end" wanted = "ha stdin stdinend" class MirrorRealLifeExample_ExpectCorrectResult(_VimTest): snippets = ( ( "for", "for(size_t ${2:i} = 0; $2 < ${1:count}; ${3:++$2})" "\n{\n\t${0:/* code */}\n}", ), ) keys = ( "for" + EX + "100" + JF + "avar\b\b\b\ba_variable" + JF + "a_variable *= 2" + JF + "// do nothing" ) wanted = """for(size_t a_variable = 0; a_variable < 100; a_variable *= 2) { \t// do nothing }""" class Mirror_TestKill_InsertBefore_NoKill(_VimTest): snippets = "test", "$1 $1_" keys = "hallo test" + EX + "auch" + ESC + "wihi" + ESC + "bb" + "ino" + JF + "end" wanted = "hallo noauch hinoauch_end" class Mirror_TestKill_InsertAfter_NoKill(_VimTest): snippets = "test", "$1 $1_" keys = "hallo test" + EX + "auch" + ESC + "eiab" + ESC + "bb" + "ino" + JF + "end" wanted = "hallo noauch noauchab_end" class Mirror_TestKill_InsertBeginning_Kill(_VimTest): snippets = "test", "$1 $1_" keys = "hallo test" + EX + "auch" + ESC + "wahi" + ESC + "bb" + "ino" + JF + "end" wanted = "hallo noauch ahiuch_end" class Mirror_TestKill_InsertEnd_Kill(_VimTest): snippets = "test", "$1 $1_" keys = "hallo test" + EX + "auch" + ESC + "ehihi" + ESC + "bb" + "ino" + JF + "end" wanted = "hallo noauch auchih_end" class Mirror_TestKillTabstop_Kill(_VimTest): snippets = "test", "welt${1:welt${2:welt}welt} $2" keys = "hallo test" + EX + "elt" wanted = "hallo weltelt "
9,709
Python
.py
222
38.662162
87
0.647259
SirVer/ultisnips
7,501
688
112
GPL-3.0
9/5/2024, 5:11:34 PM (Europe/Amsterdam)
12,211
test_SnippetPriorities.py
SirVer_ultisnips/test/test_SnippetPriorities.py
from test.vim_test_case import VimTestCase as _VimTest from test.constant import EX, ESC class SnippetPriorities_MultiWordTriggerOverwriteExisting(_VimTest): snippets = ( ("test me", "${1:Hallo}", "Types Hallo"), ("test me", "${1:World}", "Types World"), ("test me", "We overwrite", "Overwrite the two", "", 1), ) keys = "test me" + EX wanted = "We overwrite" class SnippetPriorities_DoNotCareAboutNonMatchings(_VimTest): snippets = ( ("test1", "Hallo", "Types Hallo"), ("test2", "We overwrite", "Overwrite the two", "", 1), ) keys = "test1" + EX wanted = "Hallo" class SnippetPriorities_OverwriteExisting(_VimTest): snippets = ( ("test", "${1:Hallo}", "Types Hallo"), ("test", "${1:World}", "Types World"), ("test", "We overwrite", "Overwrite the two", "", 1), ) keys = "test" + EX wanted = "We overwrite" class SnippetPriorities_OverwriteTwice_ECR(_VimTest): snippets = ( ("test", "${1:Hallo}", "Types Hallo"), ("test", "${1:World}", "Types World"), ("test", "We overwrite", "Overwrite the two", "", 1), ("test", "again", "Overwrite again", "", 2), ) keys = "test" + EX wanted = "again" class SnippetPriorities_OverwriteThenChoose_ECR(_VimTest): snippets = ( ("test", "${1:Hallo}", "Types Hallo"), ("test", "${1:World}", "Types World"), ("test", "We overwrite", "Overwrite the two", "", 1), ("test", "No overwrite", "Not overwritten", "", 1), ) keys = "test" + EX + "1\n\n" + "test" + EX + "2\n" wanted = "We overwrite\nNo overwrite" class SnippetPriorities_AddedHasHigherThanFile(_VimTest): files = { "us/all.snippets": r""" snippet test "Test Snippet" b This is a test snippet endsnippet """ } snippets = (("test", "We overwrite", "Overwrite the two", "", 1),) keys = "test" + EX wanted = "We overwrite" class SnippetPriorities_FileHasHigherThanAdded(_VimTest): files = { "us/all.snippets": r""" snippet test "Test Snippet" b This is a test snippet endsnippet """ } snippets = (("test", "We do not overwrite", "Overwrite the two", "", -1),) keys = "test" + EX wanted = "This is a test snippet" class SnippetPriorities_FileHasHigherThanAdded_neg_prio(_VimTest): files = { "us/all.snippets": r""" priority -3 snippet test "Test Snippet" b This is a test snippet endsnippet """ } snippets = (("test", "We overwrite", "Overwrite the two", "", -5),) keys = "test" + EX wanted = "This is a test snippet" class SnippetPriorities_SimpleClear(_VimTest): files = { "us/all.snippets": r""" priority 1 clearsnippets priority -1 snippet test "Test Snippet" Should not expand to this. endsnippet """ } keys = "test" + EX wanted = "test" + EX class SnippetPriorities_SimpleClear2(_VimTest): files = { "us/all.snippets": r""" clearsnippets snippet test "Test snippet" Should not expand to this. endsnippet """ } keys = "test" + EX wanted = "test" + EX class SnippetPriorities_ClearedByParent(_VimTest): files = { "us/p.snippets": r""" clearsnippets """, "us/c.snippets": r""" extends p snippet test "Test snippets" Should not expand to this. endsnippet """, } keys = ESC + ":set ft=c\n" + "itest" + EX wanted = "test" + EX class SnippetPriorities_ClearedByChild(_VimTest): files = { "us/p.snippets": r""" snippet test "Test snippets" Should only expand in p. endsnippet """, "us/c.snippets": r""" extends p clearsnippets """, } keys = ( ESC + ":set ft=p\n" + "itest" + EX + "\n" + ESC + ":set ft=c\n" + "itest" + EX + ESC + ":set ft=p" ) wanted = "Should only expand in p.\ntest" + EX
4,205
Python
.py
141
22.921986
78
0.552475
SirVer/ultisnips
7,501
688
112
GPL-3.0
9/5/2024, 5:11:34 PM (Europe/Amsterdam)
12,212
test_Movement.py
SirVer_ultisnips/test/test_Movement.py
from test.vim_test_case import VimTestCase as _VimTest from test.constant import * class CursorMovement_Multiline_ECR(_VimTest): snippets = ("test", r"$1 ${1:a tab}") keys = "test" + EX + "this is something\nvery nice\nnot" + JF + "more text" wanted = ( "this is something\nvery nice\nnot " "this is something\nvery nice\nnotmore text" ) class CursorMovement_BS_InEditMode(_VimTest): def _extra_vim_config(self, vim_config): vim_config.append("set backspace=eol,indent,start") snippets = ("<trh", "<tr>\n\t<th>$1</th>\n\t$2\n</tr>\n$3") keys = "<trh" + EX + "blah" + JF + BS + BS + JF + "end" wanted = "<tr>\n\t<th>blah</th>\n</tr>\nend" class IMMoving_CursorsKeys_ECR(_VimTest): snippets = ("test", "${1:Some}") keys = "test" + EX + "text" + 3 * ARR_U + 6 * ARR_D wanted = "text" class IMMoving_AcceptInputWhenMoved_ECR(_VimTest): snippets = ("test", r"$1 ${1:a tab}") keys = "test" + EX + "this" + 2 * ARR_L + "hallo\nwelt" wanted = "thhallo\nweltis thhallo\nweltis" class IMMoving_NoExiting_ECR(_VimTest): snippets = ("test", r"$1 ${2:a tab} ${1:Tab}") keys = "hello test this" + ESC + "02f i" + EX + "tab" + 7 * ARR_L + JF + "hallo" wanted = "hello tab hallo tab this" class IMMoving_NoExitingEventAtEnd_ECR(_VimTest): snippets = ("test", r"$1 ${2:a tab} ${1:Tab}") keys = "hello test this" + ESC + "02f i" + EX + "tab" + JF + "hallo" wanted = "hello tab hallo tab this" class IMMoving_ExitWhenOutsideRight_ECR(_VimTest): snippets = ("test", r"$1 ${2:blub} ${1:Tab}") keys = "hello test this" + ESC + "02f i" + EX + "tab" + ARR_R + JF + "hallo" wanted = "hello tab blub tab " + JF + "hallothis" class IMMoving_NotExitingWhenBarelyOutsideLeft_ECR(_VimTest): snippets = ("test", r"${1:Hi} ${2:blub}") keys = "hello test this" + ESC + "02f i" + EX + "tab" + 3 * ARR_L + JF + "hallo" wanted = "hello tab hallo this" class IMMoving_ExitWhenOutsideLeft_ECR(_VimTest): snippets = ("test", r"${1:Hi} ${2:blub}") keys = "hello test this" + ESC + "02f i" + EX + "tab" + 4 * ARR_L + JF + "hallo" wanted = "hello" + JF + "hallo tab blub this" class IMMoving_ExitWhenOutsideAbove_ECR(_VimTest): snippets = ("test", "${1:Hi}\n${2:blub}") keys = ( "hello test this" + ESC + "02f i" + EX + "tab" + 1 * ARR_U + "\n" + JF + "hallo" ) wanted = JF + "hallo\nhello tab\nblub this" class IMMoving_ExitWhenOutsideBelow_ECR(_VimTest): snippets = ("test", "${1:Hi}\n${2:blub}") keys = ( "hello test this" + ESC + "02f i" + EX + "tab" + 2 * ARR_D + JF + "testhallo\n" ) wanted = "hello tab\nblub this\n" + JF + "testhallo"
2,712
Python
.py
55
44.472727
88
0.599468
SirVer/ultisnips
7,501
688
112
GPL-3.0
9/5/2024, 5:11:34 PM (Europe/Amsterdam)
12,213
test_Recursive.py
SirVer_ultisnips/test/test_Recursive.py
from test.vim_test_case import VimTestCase as _VimTest from test.constant import * class RecTabStops_SimpleCase_ExpectCorrectResult(_VimTest): snippets = ("m", "[ ${1:first} ${2:sec} ]") keys = "m" + EX + "m" + EX + "hello" + JF + "world" + JF + "ups" + JF + "end" wanted = "[ [ hello world ]ups end ]" class RecTabStops_SimpleCaseLeaveSecondSecond_ExpectCorrectResult(_VimTest): snippets = ("m", "[ ${1:first} ${2:sec} ]") keys = "m" + EX + "m" + EX + "hello" + JF + "world" + JF + JF + JF + "end" wanted = "[ [ hello world ] sec ]end" class RecTabStops_SimpleCaseLeaveFirstSecond_ExpectCorrectResult(_VimTest): snippets = ("m", "[ ${1:first} ${2:sec} ]") keys = "m" + EX + "m" + EX + "hello" + JF + JF + JF + "world" + JF + "end" wanted = "[ [ hello sec ] world ]end" class RecTabStops_InnerWOTabStop_ECR(_VimTest): snippets = (("m1", "Just some Text"), ("m", "[ ${1:first} ${2:sec} ]")) keys = "m" + EX + "m1" + EX + "hi" + JF + "two" + JF + "end" wanted = "[ Just some Texthi two ]end" class RecTabStops_InnerWOTabStopTwiceDirectly_ECR(_VimTest): snippets = (("m1", "JST"), ("m", "[ ${1:first} ${2:sec} ]")) keys = "m" + EX + "m1" + EX + " m1" + EX + "hi" + JF + "two" + JF + "end" wanted = "[ JST JSThi two ]end" class RecTabStops_InnerWOTabStopTwice_ECR(_VimTest): snippets = (("m1", "JST"), ("m", "[ ${1:first} ${2:sec} ]")) keys = "m" + EX + "m1" + EX + JF + "m1" + EX + "hi" + JF + "end" wanted = "[ JST JSThi ]end" class RecTabStops_OuterOnlyWithZeroTS_ECR(_VimTest): snippets = (("m", "A $0 B"), ("m1", "C $1 D $0 E")) keys = "m" + EX + "m1" + EX + "CD" + JF + "DE" wanted = "A C CD D DE E B" class RecTabStops_OuterOnlyWithZero_ECR(_VimTest): snippets = (("m", "A $0 B"), ("m1", "C $1 D $0 E")) keys = "m" + EX + "m1" + EX + "CD" + JF + "DE" wanted = "A C CD D DE E B" class RecTabStops_ExpandedInZeroTS_ECR(_VimTest): snippets = (("m", "A $0 B $1"), ("m1", "C $1 D $0 E")) keys = "m" + EX + "hi" + JF + "m1" + EX + "CD" + JF + "DE" wanted = "A C CD D DE E B hi" class RecTabStops_ExpandedInZeroTSTwice_ECR(_VimTest): snippets = (("m", "A $0 B $1"), ("m1", "C $1 D $0 E")) keys = "m" + EX + "hi" + JF + "m" + EX + "again" + JF + "m1" + EX + "CD" + JF + "DE" wanted = "A A C CD D DE E B again B hi" class RecTabStops_ExpandedInZeroTSSecondTime_ECR(_VimTest): snippets = (("m", "A $0 B $1"), ("m1", "C $1 D $0 E")) keys = "m" + EX + "hi" + JF + "m" + EX + "m1" + EX + "CD" + JF + "DE" + JF + "AB" wanted = "A A AB B C CD D DE E B hi" class RecTabsStops_TypeInZero_ECR(_VimTest): snippets = ( ("v", r"\vec{$1}", "Vector", "w"), ("frac", r"\frac{${1:one}}${0:zero}{${2:two}}", "Fractio", "w"), ) keys = ( "v" + EX + "frac" + EX + "a" + JF + "b" + JF + "frac" + EX + "aa" + JF + JF + "cc" + JF + "hello frac" + EX + JF + JF + "world" ) wanted = r"\vec{\frac{a}\frac{aa}cc{two}{b}}hello \frac{one}world{two}" class RecTabsStops_TypeInZero2_ECR(_VimTest): snippets = (("m", r"_${0:explicit zero}", "snip", "i"),) keys = "m" + EX + "hello m" + EX + "world m" + EX + "end" wanted = r"_hello _world _end" class RecTabsStops_BackspaceZero_ECR(_VimTest): snippets = (("m", r"${1:one}${0:explicit zero}${2:two}", "snip", "i"),) keys = "m" + EX + JF + JF + BS + "m" + EX wanted = r"oneoneexplicit zerotwotwo" class RecTabStops_MirrorInnerSnippet_ECR(_VimTest): snippets = (("m", "[ $1 $2 ] $1"), ("m1", "ASnip $1 ASnip $2 ASnip")) keys = ( "m" + EX + "m1" + EX + "Hallo" + JF + "Hi" + JF + "endone" + JF + "two" + JF + "totalend" ) wanted = "[ ASnip Hallo ASnip Hi ASnipendone two ] ASnip Hallo ASnip Hi ASnipendonetotalend" class RecTabStops_NotAtBeginningOfTS_ExpectCorrectResult(_VimTest): snippets = ("m", "[ ${1:first} ${2:sec} ]") keys = ( "m" + EX + "hello m" + EX + "hi" + JF + "two" + JF + "ups" + JF + "three" + JF + "end" ) wanted = "[ hello [ hi two ]ups three ]end" class RecTabStops_InNewlineInTabstop_ExpectCorrectResult(_VimTest): snippets = ("m", "[ ${1:first} ${2:sec} ]") keys = ( "m" + EX + "hello\nm" + EX + "hi" + JF + "two" + JF + "ups" + JF + "three" + JF + "end" ) wanted = "[ hello\n[ hi two ]ups three ]end" class RecTabStops_InNewlineInTabstopNotAtBeginOfLine_ECR(_VimTest): snippets = ("m", "[ ${1:first} ${2:sec} ]") keys = ( "m" + EX + "hello\nhello again m" + EX + "hi" + JF + "two" + JF + "ups" + JF + "three" + JF + "end" ) wanted = "[ hello\nhello again [ hi two ]ups three ]end" class RecTabStops_InNewlineMultiline_ECR(_VimTest): snippets = ("m", "M START\n$0\nM END") keys = "m" + EX + "m" + EX wanted = "M START\nM START\n\nM END\nM END" class RecTabStops_InNewlineManualIndent_ECR(_VimTest): snippets = ("m", "M START\n$0\nM END") keys = "m" + EX + " m" + EX + "hi" wanted = "M START\n M START\n hi\n M END\nM END" class RecTabStops_InNewlineManualIndentTextInFront_ECR(_VimTest): snippets = ("m", "M START\n$0\nM END") keys = "m" + EX + " hallo m" + EX + "hi" wanted = "M START\n hallo M START\n hi\n M END\nM END" class RecTabStops_InNewlineMultilineWithIndent_ECR(_VimTest): snippets = ("m", "M START\n $0\nM END") keys = "m" + EX + "m" + EX + "hi" wanted = "M START\n M START\n hi\n M END\nM END" class RecTabStops_InNewlineMultilineWithNonZeroTS_ECR(_VimTest): snippets = ("m", "M START\n $1\nM END -> $0") keys = "m" + EX + "m" + EX + "hi" + JF + "hallo" + JF + "end" wanted = "M START\n M START\n hi\n M END -> hallo\n" "M END -> end" class RecTabStops_BarelyNotLeavingInner_ECR(_VimTest): snippets = (("m", "[ ${1:first} ${2:sec} ]"),) keys = ( "m" + EX + "m" + EX + "a" + 3 * ARR_L + JF + "hallo" + JF + "ups" + JF + "world" + JF + "end" ) wanted = "[ [ a hallo ]ups world ]end" class RecTabStops_LeavingInner_ECR(_VimTest): snippets = (("m", "[ ${1:first} ${2:sec} ]"),) keys = "m" + EX + "m" + EX + "a" + 4 * ARR_L + JF + "hallo" + JF + "world" wanted = "[ [ a sec ] hallo ]world" class RecTabStops_LeavingInnerInner_ECR(_VimTest): snippets = (("m", "[ ${1:first} ${2:sec} ]"),) keys = ( "m" + EX + "m" + EX + "m" + EX + "a" + 4 * ARR_L + JF + "hallo" + JF + "ups" + JF + "world" + JF + "end" ) wanted = "[ [ [ a sec ] hallo ]ups world ]end" class RecTabStops_LeavingInnerInnerTwo_ECR(_VimTest): snippets = (("m", "[ ${1:first} ${2:sec} ]"),) keys = "m" + EX + "m" + EX + "m" + EX + "a" + 6 * ARR_L + JF + "hallo" + JF + "end" wanted = "[ [ [ a sec ] sec ] hallo ]end" class RecTabStops_ZeroTSisNothingSpecial_ECR(_VimTest): snippets = (("m1", "[ ${1:first} $0 ${2:sec} ]"), ("m", "[ ${1:first} ${2:sec} ]")) keys = ( "m" + EX + "m1" + EX + "one" + JF + "two" + JF + "three" + JF + "four" + JF + "end" ) wanted = "[ [ one three two ] four ]end" class RecTabStops_MirroredZeroTS_ECR(_VimTest): snippets = ( ("m1", "[ ${1:first} ${0:Year, some default text} $0 ${2:sec} ]"), ("m", "[ ${1:first} ${2:sec} ]"), ) keys = ( "m" + EX + "m1" + EX + "one" + JF + "two" + JF + "three" + JF + "four" + JF + "end" ) wanted = "[ [ one three three two ] four ]end" class RecTabStops_ChildTriggerContainsParentTextObjects(_VimTest): # https://bugs.launchpad.net/bugs/1191617 files = { "us/all.snippets": r""" global !p def complete(t, opts): if t: opts = [ q[len(t):] for q in opts if q.startswith(t) ] if len(opts) == 0: return '' return opts[0] if len(opts) == 1 else "(" + '|'.join(opts) + ')' def autocomplete_options(t, string, attr=None): return complete(t[1], [opt for opt in attr if opt not in string]) endglobal snippet /form_for(.*){([^|]*)/ "form_for html options" rw! `!p auto = autocomplete_options(t, match.group(2), attr=["id: ", "class: ", "title: "]) snip.rv = "form_for" + match.group(1) + "{"`$1`!p if (snip.c != auto) : snip.rv=auto` endsnippet """ } keys = "form_for user, namespace: some_namespace, html: {i" + EX + "i" + EX wanted = ( "form_for user, namespace: some_namespace, html: {(id: |class: |title: )d: " )
9,313
Python
.py
286
26.108392
96
0.49013
SirVer/ultisnips
7,501
688
112
GPL-3.0
9/5/2024, 5:11:34 PM (Europe/Amsterdam)
12,214
test_Editing.py
SirVer_ultisnips/test/test_Editing.py
from test.vim_test_case import VimTestCase as _VimTest from test.constant import * class Undo_RemoveMultilineSnippet(_VimTest): snippets = ("test", "Hello\naaa ${1} bbb\nWorld") keys = "test" + EX + ESC + "u" wanted = "test" class Undo_RemoveEditInTabstop(_VimTest): snippets = ("test", "$1 Hello\naaa ${1} bbb\nWorld") keys = "hello test" + EX + "upsi" + ESC + "hh" + "iabcdef" + ESC + "u" wanted = "hello upsi Hello\naaa upsi bbb\nWorld" class Undo_RemoveWholeSnippet(_VimTest): snippets = ("test", "Hello\n${1:Hello}World") keys = "first line\n\n\n\n\n\nthird line" + ESC + "3k0itest" + EX + ESC + "u6j" wanted = "first line\n\n\ntest\n\n\nthird line" class Undo_RemoveOneSnippetByTime(_VimTest): snippets = ("i", "if:\n\t$1") keys = "i" + EX + "i" + EX + ESC + "u" wanted = "if:\n\ti" class Undo_RemoveOneSnippetByTime2(_VimTest): snippets = ("i", "if:\n\t$1") keys = "i" + EX + "i" + EX + ESC + "uu" wanted = "if:\n\t" class Undo_ChangesInPlaceholder(_VimTest): snippets = ("i", "if $1:\n\t$2") keys = "i" + EX + "asd" + JF + ESC + "u" wanted = "if :\n\t" class Undo_CompletelyUndoSnippet(_VimTest): snippets = ("i", "if $1:\n\t$2") # undo 'feh' # undo 'asd' # undo snippet expansion # undo entering of 'i' keys = "i" + EX + "asd" + JF + "feh" + ESC + "uuuu" wanted = "" class JumpForward_DefSnippet(_VimTest): snippets = ("test", "${1}\n`!p snip.rv = '\\n'.join(t[1].split())`\n\n${0:pass}") keys = "test" + EX + "a b c" + JF + "shallnot" wanted = "a b c\na\nb\nc\n\nshallnot" class DeleteSnippetInsertion0(_VimTest): snippets = ("test", "${1:hello} $1") keys = "test" + EX + ESC + "Vkx" + "i\nworld\n" wanted = "world" class DeleteSnippetInsertion1(_VimTest): snippets = ("test", r"$1${1/(.*)/(?0::.)/}") keys = "test" + EX + ESC + "u" wanted = "test" class DoNotCrashOnUndoAndJumpInNestedSnippet(_VimTest): snippets = ("test", r"if $1: $2") keys = "test" + EX + "a" + JF + "test" + EX + ESC + "u" + JF wanted = "if a: test" # Test for bug #927844 class DeleteLastTwoLinesInSnippet(_VimTest): snippets = ("test", "$1hello\nnice\nworld") keys = "test" + EX + ESC + "j2dd" wanted = "hello" class DeleteCurrentTabStop1_JumpBack(_VimTest): snippets = ("test", "${1:hi}\nend") keys = "test" + EX + ESC + "ddi" + JB wanted = "end" class DeleteCurrentTabStop2_JumpBack(_VimTest): snippets = ("test", "${1:hi}\n${2:world}\nend") keys = "test" + EX + JF + ESC + "ddi" + JB + "hello" wanted = "hello\nend" class DeleteCurrentTabStop3_JumpAround(_VimTest): snippets = ("test", "${1:hi}\n${2:world}\nend") keys = "test" + EX + JF + ESC + "ddkji" + JB + "hello" + JF + "world" wanted = "hello\nendworld" # Test for Bug #774917 class Backspace_TabStop_Zero(_VimTest): snippets = ("test", "A${1:C} ${0:DDD}", "This is Case 1") keys = "test" + EX + "A" + JF + BS + "BBB" wanted = "AA BBB" class Backspace_TabStop_NotZero(_VimTest): snippets = ("test", "A${1:C} ${2:DDD}", "This is Case 1") keys = "test" + EX + "A" + JF + BS + "BBB" wanted = "AA BBB" class UpdateModifiedSnippetWithoutCursorMove1(_VimTest): snippets = ("test", "${1:one}(${2:xxx})${3:three}") keys = "test" + EX + "aaaaa" + JF + BS + JF + "3333" wanted = "aaaaa()3333" class UpdateModifiedSnippetWithoutCursorMove2(_VimTest): snippets = ( "test", """\ private function ${1:functionName}(${2:arguments}):${3:Void} { ${VISUAL}$0 }""", ) keys = "test" + EX + "a" + JF + BS + JF + "Int" + JF + "body" wanted = """\ private function a():Int { body }"""
3,718
Python
.py
95
34.852632
85
0.588613
SirVer/ultisnips
7,501
688
112
GPL-3.0
9/5/2024, 5:11:34 PM (Europe/Amsterdam)
12,215
test_Interpolation.py
SirVer_ultisnips/test/test_Interpolation.py
# encoding: utf-8 import os from test.vim_test_case import VimTestCase as _VimTest from test.constant import EX, JF, ESC from test.util import running_on_windows class TabStop_Shell_SimpleExample(_VimTest): skip_if = lambda self: running_on_windows() snippets = ("test", "hi `echo hallo` you!") keys = "test" + EX + "and more" wanted = "hi hallo you!and more" class TabStop_Shell_WithUmlauts(_VimTest): skip_if = lambda self: running_on_windows() snippets = ("test", "hi `echo höüäh` you!") keys = "test" + EX + "and more" wanted = "hi höüäh you!and more" class TabStop_Shell_TextInNextLine(_VimTest): skip_if = lambda self: running_on_windows() snippets = ("test", "hi `echo hallo`\nWeiter") keys = "test" + EX + "and more" wanted = "hi hallo\nWeiterand more" class TabStop_Shell_InDefValue_Leave(_VimTest): skip_if = lambda self: running_on_windows() snippets = ("test", "Hallo ${1:now `echo fromecho`} end") keys = "test" + EX + JF + "and more" wanted = "Hallo now fromecho endand more" class TabStop_Shell_InDefValue_Overwrite(_VimTest): skip_if = lambda self: running_on_windows() snippets = ("test", "Hallo ${1:now `echo fromecho`} end") keys = "test" + EX + "overwrite" + JF + "and more" wanted = "Hallo overwrite endand more" class TabStop_Shell_TestEscapedChars_Overwrite(_VimTest): skip_if = lambda self: running_on_windows() snippets = ("test", r"""`echo \`echo "\\$hi"\``""") keys = "test" + EX wanted = "$hi" class TabStop_Shell_TestEscapedCharsAndShellVars_Overwrite(_VimTest): skip_if = lambda self: running_on_windows() snippets = ("test", r"""`hi="blah"; echo \`echo "$hi"\``""") keys = "test" + EX wanted = "blah" class TabStop_Shell_ShebangPython(_VimTest): skip_if = lambda self: running_on_windows() snippets = ( "test", """Hallo ${1:now `#!/usr/bin/env %s print("Hallo Welt") `} end""" % os.environ.get("PYTHON", "python3"), ) keys = "test" + EX + JF + "and more" wanted = "Hallo now Hallo Welt endand more" class TabStop_VimScriptInterpolation_SimpleExample(_VimTest): snippets = ("test", """hi `!v indent(".")` End""") keys = " test" + EX wanted = " hi 4 End" class PythonCodeOld_SimpleExample(_VimTest): snippets = ("test", """hi `!p res = "Hallo"` End""") keys = "test" + EX wanted = "hi Hallo End" class PythonCodeOld_ReferencePlaceholderAfter(_VimTest): snippets = ("test", """${1:hi} `!p res = t[1]+".blah"` End""") keys = "test" + EX + "ho" wanted = "ho ho.blah End" class PythonCodeOld_ReferencePlaceholderBefore(_VimTest): snippets = ("test", """`!p res = len(t[1])*"#"`\n${1:some text}""") keys = "test" + EX + "Hallo Welt" wanted = "##########\nHallo Welt" class PythonCodeOld_TransformedBeforeMultiLine(_VimTest): snippets = ( "test", """${1/.+/egal/m} ${1:`!p res = "Hallo"`} End""", ) keys = "test" + EX wanted = "egal Hallo End" class PythonCodeOld_IndentedMultiline(_VimTest): snippets = ( "test", """start `!p a = 1 b = 2 if b > a: res = "b isbigger a" else: res = "a isbigger b"` end""", ) keys = " test" + EX wanted = " start b isbigger a end" class PythonCode_UseNewOverOld(_VimTest): snippets = ( "test", """hi `!p res = "Old" snip.rv = "New"` End""", ) keys = "test" + EX wanted = "hi New End" class PythonCode_SimpleExample(_VimTest): snippets = ("test", """hi `!p snip.rv = "Hallo"` End""") keys = "test" + EX wanted = "hi Hallo End" class PythonCode_SimpleExample_ReturnValueIsEmptyString(_VimTest): snippets = ("test", """hi`!p snip.rv = ""`End""") keys = "test" + EX wanted = "hiEnd" class PythonCode_ReferencePlaceholder(_VimTest): snippets = ("test", """${1:hi} `!p snip.rv = t[1]+".blah"` End""") keys = "test" + EX + "ho" wanted = "ho ho.blah End" class PythonCode_ReferencePlaceholderBefore(_VimTest): snippets = ("test", """`!p snip.rv = len(t[1])*"#"`\n${1:some text}""") keys = "test" + EX + "Hallo Welt" wanted = "##########\nHallo Welt" class PythonCode_TransformedBeforeMultiLine(_VimTest): snippets = ( "test", """${1/.+/egal/m} ${1:`!p snip.rv = "Hallo"`} End""", ) keys = "test" + EX wanted = "egal Hallo End" class PythonCode_MultilineIndented(_VimTest): snippets = ( "test", """start `!p a = 1 b = 2 if b > a: snip.rv = "b isbigger a" else: snip.rv = "a isbigger b"` end""", ) keys = " test" + EX wanted = " start b isbigger a end" class PythonCode_SimpleAppend(_VimTest): snippets = ( "test", """hi `!p snip.rv = "Hallo1" snip += "Hallo2"` End""", ) keys = "test" + EX wanted = "hi Hallo1\nHallo2 End" class PythonCode_MultiAppend(_VimTest): snippets = ( "test", """hi `!p snip.rv = "Hallo1" snip += "Hallo2" snip += "Hallo3"` End""", ) keys = "test" + EX wanted = "hi Hallo1\nHallo2\nHallo3 End" class PythonCode_MultiAppendSimpleIndent(_VimTest): snippets = ( "test", """hi `!p snip.rv="Hallo1" snip += "Hallo2" snip += "Hallo3"` End""", ) keys = ( """ test""" + EX ) wanted = """ hi Hallo1 Hallo2 Hallo3 End""" class PythonCode_SimpleMkline(_VimTest): snippets = ( "test", r"""hi `!p snip.rv="Hallo1\n" snip.rv += snip.mkline("Hallo2") + "\n" snip.rv += snip.mkline("Hallo3")` End""", ) keys = ( """ test""" + EX ) wanted = """ hi Hallo1 Hallo2 Hallo3 End""" class PythonCode_MultiAppendShift(_VimTest): snippets = ( "test", r"""hi `!p snip.rv="i1" snip += "i1" snip >> 1 snip += "i2" snip << 2 snip += "i0" snip >> 3 snip += "i3"` End""", ) keys = ( """ test""" + EX ) wanted = """ hi i1 i1 i2 i0 i3 End""" class PythonCode_MultiAppendShiftMethods(_VimTest): snippets = ( "test", r"""hi `!p snip.rv="i1\n" snip.rv += snip.mkline("i1\n") snip.shift(1) snip.rv += snip.mkline("i2\n") snip.unshift(2) snip.rv += snip.mkline("i0\n") snip.shift(3) snip.rv += snip.mkline("i3")` End""", ) keys = ( """ test""" + EX ) wanted = """ hi i1 i1 i2 i0 i3 End""" class PythonCode_ResetIndent(_VimTest): snippets = ( "test", r"""hi `!p snip.rv="i1" snip >> 1 snip += "i2" snip.reset_indent() snip += "i1" snip << 1 snip += "i0" snip.reset_indent() snip += "i1"` End""", ) keys = ( """ test""" + EX ) wanted = """ hi i1 i2 i1 i0 i1 End""" class PythonCode_IndentEtSw(_VimTest): def _extra_vim_config(self, vim_config): vim_config.append("set sw=3") vim_config.append("set expandtab") snippets = ( "test", r"""hi `!p snip.rv = "i1" snip >> 1 snip += "i2" snip << 2 snip += "i0" snip >> 1 snip += "i1" ` End""", ) keys = """ test""" + EX wanted = """ hi i1 i2 i0 i1 End""" class PythonCode_IndentEtSwOffset(_VimTest): def _extra_vim_config(self, vim_config): vim_config.append("set sw=3") vim_config.append("set expandtab") snippets = ( "test", r"""hi `!p snip.rv = "i1" snip >> 1 snip += "i2" snip << 2 snip += "i0" snip >> 1 snip += "i1" ` End""", ) keys = """ test""" + EX wanted = """ hi i1 i2 i0 i1 End""" class PythonCode_IndentNoetSwTs(_VimTest): def _extra_vim_config(self, vim_config): vim_config.append("set sw=3") vim_config.append("set ts=4") snippets = ( "test", r"""hi `!p snip.rv = "i1" snip >> 1 snip += "i2" snip << 2 snip += "i0" snip >> 1 snip += "i1" ` End""", ) keys = """ test""" + EX wanted = """ hi i1 \t i2 i0 i1 End""" # Test using 'opt' class PythonCode_OptExists(_VimTest): def _extra_vim_config(self, vim_config): vim_config.append('let g:UStest="yes"') snippets = ("test", r"""hi `!p snip.rv = snip.opt("g:UStest") or "no"` End""") keys = """test""" + EX wanted = """hi yes End""" class PythonCode_OptNoExists(_VimTest): snippets = ("test", r"""hi `!p snip.rv = snip.opt("g:UStest") or "no"` End""") keys = """test""" + EX wanted = """hi no End""" class PythonCode_IndentProblem(_VimTest): # A test case which is likely related to bug 719649 snippets = ( "test", r"""hi `!p snip.rv = "World" ` End""", ) keys = " " * 8 + "test" + EX # < 8 works. wanted = """ hi World End""" class PythonCode_TrickyReferences(_VimTest): snippets = ("test", r"""${2:${1/.+/egal/}} ${1:$3} ${3:`!p snip.rv = "hi"`}""") keys = "ups test" + EX wanted = "ups egal hi hi" # locals class PythonCode_Locals(_VimTest): snippets = ( "test", r"""hi `!p a = "test" snip.rv = "nothing"` `!p snip.rv = a ` End""", ) keys = """test""" + EX wanted = """hi nothing test End""" class PythonCode_LongerTextThanSource_Chars(_VimTest): snippets = ("test", r"""hi`!p snip.rv = "a" * 100`end""") keys = """test""" + EX + "ups" wanted = "hi" + 100 * "a" + "endups" class PythonCode_LongerTextThanSource_MultiLine(_VimTest): snippets = ("test", r"""hi`!p snip.rv = "a" * 100 + '\n'*100 + "a"*100`end""") keys = """test""" + EX + "ups" wanted = "hi" + 100 * "a" + 100 * "\n" + 100 * "a" + "endups" class PythonCode_AccessKilledTabstop_OverwriteSecond(_VimTest): snippets = ( "test", r"`!p snip.rv = t[2].upper()`${1:h${2:welt}o}`!p snip.rv = t[2].upper()`", ) keys = "test" + EX + JF + "okay" wanted = "OKAYhokayoOKAY" class PythonCode_AccessKilledTabstop_OverwriteFirst(_VimTest): snippets = ( "test", r"`!p snip.rv = t[2].upper()`${1:h${2:welt}o}`!p snip.rv = t[2].upper()`", ) keys = "test" + EX + "aaa" wanted = "aaa" class PythonCode_CanOverwriteTabstop(_VimTest): snippets = ( "test", """$1`!p if len(t[1]) > 3 and len(t[2]) == 0: t[2] = t[1][2:]; t[1] = t[1][:2] + '-\\n\\t'; vim.command('call feedkeys("\<End>", "n")'); `$2""", ) keys = "test" + EX + "blah" + ", bah" wanted = "bl-\n\tah, bah" class PythonVisual_NoVisualSelection_Ignore(_VimTest): snippets = ("test", "h`!p snip.rv = snip.v.mode + snip.v.text`b") keys = "test" + EX + "abc" wanted = "hbabc" class PythonVisual_SelectOneWord(_VimTest): snippets = ("test", "h`!p snip.rv = snip.v.mode + snip.v.text`b") keys = "blablub" + ESC + "0v6l" + EX + "test" + EX wanted = "hvblablubb" class PythonVisual_LineSelect_Simple(_VimTest): snippets = ("test", "h`!p snip.rv = snip.v.mode + snip.v.text`b") keys = "hello\nnice\nworld" + ESC + "Vkk" + EX + "test" + EX wanted = "hVhello\nnice\nworld\nb" class PythonVisual_HasAccessToSelectedPlaceholders(_VimTest): snippets = ( "test", """${1:first} ${2:second} (`!p snip.rv = "placeholder: " + snip.p.current_text`)""", ) keys = "test" + EX + ESC + "otest" + EX + JF + ESC wanted = """first second (placeholder: first) first second (placeholder: second)""" class PythonVisual_HasAccessToZeroPlaceholders(_VimTest): snippets = ( "test", """${1:first} ${2:second} (`!p snip.rv = "placeholder: " + snip.p.current_text`)""", ) keys = "test" + EX + ESC + "otest" + EX + JF + JF + JF + JF wanted = """first second (placeholder: first second (placeholder: )) first second (placeholder: )""" class Python_SnipRvCanBeNonText(_VimTest): # Test for https://github.com/SirVer/ultisnips/issues/1132 snippets = ("test", "`!p snip.rv = 5`") keys = "test" + EX wanted = "5"
11,984
Python
.py
445
22.476404
83
0.569641
SirVer/ultisnips
7,501
688
112
GPL-3.0
9/5/2024, 5:11:34 PM (Europe/Amsterdam)
12,216
test_Expand.py
SirVer_ultisnips/test/test_Expand.py
from test.vim_test_case import VimTestCase as _VimTest from test.constant import * class _SimpleExpands(_VimTest): snippets = ("hallo", "Hallo Welt!") class SimpleExpand_ExpectCorrectResult(_SimpleExpands): keys = "hallo" + EX wanted = "Hallo Welt!" class SimpleExpandTwice_ExpectCorrectResult(_SimpleExpands): keys = "hallo" + EX + "\nhallo" + EX wanted = "Hallo Welt!\nHallo Welt!" class SimpleExpandNewLineAndBackspae_ExpectCorrectResult(_SimpleExpands): keys = "hallo" + EX + "\nHallo Welt!\n\n\b\b\b\b\b" wanted = "Hallo Welt!\nHallo We" def _extra_vim_config(self, vim_config): vim_config.append("set backspace=eol,start") class SimpleExpandTypeAfterExpand_ExpectCorrectResult(_SimpleExpands): keys = "hallo" + EX + "and again" wanted = "Hallo Welt!and again" class SimpleExpandTypeAndDelete_ExpectCorrectResult(_SimpleExpands): keys = "na du hallo" + EX + "and again\b\b\b\b\bblub" wanted = "na du Hallo Welt!and blub" class DoNotExpandAfterSpace_ExpectCorrectResult(_SimpleExpands): keys = "hallo " + EX wanted = "hallo " + EX class ExitSnippetModeAfterTabstopZero(_VimTest): snippets = ("test", "SimpleText") keys = "test" + EX + EX wanted = "SimpleText" + EX class ExpandInTheMiddleOfLine_ExpectCorrectResult(_SimpleExpands): keys = "Wie hallo gehts" + ESC + "bhi" + EX wanted = "Wie Hallo Welt! gehts" class MultilineExpand_ExpectCorrectResult(_VimTest): snippets = ("hallo", "Hallo Welt!\nUnd Wie gehts") keys = "Wie hallo gehts" + ESC + "bhi" + EX wanted = "Wie Hallo Welt!\nUnd Wie gehts gehts" class MultilineExpandTestTyping_ExpectCorrectResult(_VimTest): snippets = ("hallo", "Hallo Welt!\nUnd Wie gehts") wanted = "Wie Hallo Welt!\nUnd Wie gehtsHuiui! gehts" keys = "Wie hallo gehts" + ESC + "bhi" + EX + "Huiui!" class SimpleExpandEndingWithNewline_ExpectCorrectResult(_VimTest): snippets = ("hallo", "Hallo Welt\n") keys = "hallo" + EX + "\nAnd more" wanted = "Hallo Welt\n\nAnd more" class SimpleExpand_DoNotClobberDefaultRegister(_VimTest): snippets = ("hallo", "Hallo ${1:Welt}") keys = "hallo" + EX + BS + ESC + "o" + ESC + "P" wanted = "Hallo \n" def _extra_vim_config(self, vim_config): vim_config.append('let @"=""') class SimpleExpand_Issue1343(_VimTest): snippets = ("test", r"${1:\Safe\\}") keys = "test" + EX + JF + "foo" wanted = r"\Safe\foo" class SimpleExpandJumpOrExpand_Expand(_VimTest): snippets = ("hallo", "Hallo Welt!") keys = "hallo" + EX wanted = "Hallo Welt!" def _extra_vim_config(self, vim_config): vim_config.append('let g:UltiSnipsJumpOrExpandTrigger="<tab>"') class SimpleExpandJumpOrExpand_Ambiguity(_VimTest): snippets = ("test", r"test$1 foo$0") keys = "test" + EX + EX + "foo" wanted = "test foofoo" def _extra_vim_config(self, vim_config): vim_config.append('let g:UltiSnipsJumpOrExpandTrigger="<tab>"') class SimpleExpandExpandOrJump_Expand(_VimTest): snippets = ("hallo", "Hallo Welt!") keys = "hallo" + EX wanted = "Hallo Welt!" def _extra_vim_config(self, vim_config): vim_config.append('let g:UltiSnipsExpandOrJumpTrigger="<tab>"') class SimpleExpandExpandOrJump_Ambiguity(_VimTest): snippets = ("test", r"test$1 foo$0") keys = "test" + EX + EX + "foo" wanted = "testfoo foo foo" def _extra_vim_config(self, vim_config): vim_config.append('let g:UltiSnipsExpandOrJumpTrigger="<tab>"')
3,548
Python
.py
77
41.116883
73
0.684903
SirVer/ultisnips
7,501
688
112
GPL-3.0
9/5/2024, 5:11:34 PM (Europe/Amsterdam)
12,217
test_ParseSnippets.py
SirVer_ultisnips/test/test_ParseSnippets.py
from test.vim_test_case import VimTestCase as _VimTest from test.constant import * class ParseSnippets_SimpleSnippet(_VimTest): files = { "us/all.snippets": r""" snippet testsnip "Test Snippet" b! This is a test snippet! endsnippet """ } keys = "testsnip" + EX wanted = "This is a test snippet!" class ParseSnippets_MissingEndSnippet(_VimTest): files = { "us/all.snippets": r""" snippet testsnip "Test Snippet" b! This is a test snippet! """ } keys = "testsnip" + EX wanted = "testsnip" + EX expected_error = r"Missing 'endsnippet' for 'testsnip' in \S+:4" class ParseSnippets_UnknownDirective(_VimTest): files = { "us/all.snippets": r""" unknown directive """ } keys = "testsnip" + EX wanted = "testsnip" + EX expected_error = r"Invalid line 'unknown directive' in \S+:2" class ParseSnippets_InvalidPriorityLine(_VimTest): files = { "us/all.snippets": r""" priority - 50 """ } keys = "testsnip" + EX wanted = "testsnip" + EX expected_error = r"Invalid priority '- 50' in \S+:2" class ParseSnippets_InvalidPriorityLine1(_VimTest): files = { "us/all.snippets": r""" priority """ } keys = "testsnip" + EX wanted = "testsnip" + EX expected_error = r"Invalid priority '' in \S+:2" class ParseSnippets_ExtendsWithoutFiletype(_VimTest): files = { "us/all.snippets": r""" extends """ } keys = "testsnip" + EX wanted = "testsnip" + EX expected_error = r"'extends' without file types in \S+:2" class ParseSnippets_ClearAll(_VimTest): files = { "us/all.snippets": r""" snippet testsnip "Test snippet" This is a test. endsnippet clearsnippets """ } keys = "testsnip" + EX wanted = "testsnip" + EX class ParseSnippets_ClearOne(_VimTest): files = { "us/all.snippets": r""" clearsnippets toclear snippet testsnip "Test snippet" This is a test. endsnippet snippet toclear "Snippet to clear" Do not expand. endsnippet """ } keys = "toclear" + EX + "\n" + "testsnip" + EX wanted = "toclear" + EX + "\n" + "This is a test." class ParseSnippets_ClearTwo(_VimTest): files = { "us/all.snippets": r""" clearsnippets testsnip toclear snippet testsnip "Test snippet" This is a test. endsnippet snippet toclear "Snippet to clear" Do not expand. endsnippet """ } keys = "toclear" + EX + "\n" + "testsnip" + EX wanted = "toclear" + EX + "\n" + "testsnip" + EX class _ParseSnippets_MultiWord(_VimTest): files = { "us/all.snippets": r""" snippet /test snip/ This is a test. endsnippet snippet !snip test! "Another snippet" This is another test. endsnippet snippet "snippet test" "Another snippet" b This is yet another test. endsnippet """ } class ParseSnippets_MultiWord_Simple(_ParseSnippets_MultiWord): keys = "test snip" + EX wanted = "This is a test." class ParseSnippets_MultiWord_Description(_ParseSnippets_MultiWord): keys = "snip test" + EX wanted = "This is another test." class ParseSnippets_MultiWord_Description_Option(_ParseSnippets_MultiWord): keys = "snippet test" + EX wanted = "This is yet another test." class _ParseSnippets_MultiWord_RE(_VimTest): files = { "us/all.snippets": r""" snippet /[d-f]+/ "" r az test endsnippet snippet !^(foo|bar)$! "" r foo-bar test endsnippet snippet "(test ?)+" "" r re-test endsnippet """ } class ParseSnippets_MultiWord_RE1(_ParseSnippets_MultiWord_RE): keys = "abc def" + EX wanted = "abc az test" class ParseSnippets_MultiWord_RE2(_ParseSnippets_MultiWord_RE): keys = "foo" + EX + " bar" + EX + "\nbar" + EX wanted = "foo-bar test bar\t\nfoo-bar test" class ParseSnippets_MultiWord_RE3(_ParseSnippets_MultiWord_RE): keys = "test test test" + EX wanted = "re-test" class ParseSnippets_MultiWord_Quotes(_VimTest): files = { "us/all.snippets": r""" snippet "test snip" This is a test. endsnippet """ } keys = "test snip" + EX wanted = "This is a test." class ParseSnippets_MultiWord_WithQuotes(_VimTest): files = { "us/all.snippets": r""" snippet !"test snip"! This is a test. endsnippet """ } keys = '"test snip"' + EX wanted = "This is a test." class ParseSnippets_MultiWord_NoContainer(_VimTest): files = { "us/all.snippets": r""" snippet test snip This is a test. endsnippet """ } keys = "test snip" + EX wanted = keys expected_error = "Invalid multiword trigger: 'test snip' in \S+:2" class ParseSnippets_MultiWord_UnmatchedContainer(_VimTest): files = { "us/all.snippets": r""" snippet !inv snip/ This is a test. endsnippet """ } keys = "inv snip" + EX wanted = keys expected_error = "Invalid multiword trigger: '!inv snip/' in \S+:2" class ParseSnippets_Global_Python_After(_VimTest): files = { "us/all.snippets": r""" snippet ab x `!p snip.rv = tex("bob")` y endsnippet context "always()" snippet ac x `!p snip.rv = tex("jon")` y endsnippet global !p def tex(ins): return "a " + ins + " b" def always(): return True endglobal """ } keys = "ab" + EX + "\nac" + EX wanted = "x a bob b y\nx a jon b y" class ParseSnippets_Global_Python(_VimTest): files = { "us/all.snippets": r""" global !p def tex(ins): return "a " + ins + " b" endglobal snippet ab x `!p snip.rv = tex("bob")` y endsnippet snippet ac x `!p snip.rv = tex("jon")` y endsnippet """ } keys = "ab" + EX + "\nac" + EX wanted = "x a bob b y\nx a jon b y" class ParseSnippets_Global_Local_Python(_VimTest): files = { "us/all.snippets": r""" global !p def tex(ins): return "a " + ins + " b" endglobal snippet ab x `!p first = tex("bob") snip.rv = "first"` `!p snip.rv = first` y endsnippet """ } keys = "ab" + EX wanted = "x first a bob b y" class ParseSnippets_PrintPythonStacktrace(_VimTest): files = { "us/all.snippets": r""" snippet test `!p abc()` endsnippet """ } keys = "test" + EX wanted = keys expected_error = " > abc" class ParseSnippets_PrintPythonStacktraceMultiline(_VimTest): files = { "us/all.snippets": r""" snippet test `!p if True: qwe()` endsnippet """ } keys = "test" + EX wanted = keys expected_error = " > \s+qwe" class ParseSnippets_PrintErroneousSnippet(_VimTest): files = { "us/all.snippets": r""" snippet test "asd()" e endsnippet """ } keys = "test" + EX wanted = keys expected_error = "Trigger: test" class ParseSnippets_PrintErroneousSnippetContext(_VimTest): files = { "us/all.snippets": r""" snippet test "asd()" e endsnippet """ } keys = "test" + EX wanted = keys expected_error = "Context: asd" class ParseSnippets_PrintErroneousSnippetPreAction(_VimTest): files = { "us/all.snippets": r""" pre_expand "asd()" snippet test endsnippet """ } keys = "test" + EX wanted = keys expected_error = "Pre-expand: asd" class ParseSnippets_PrintErroneousSnippetPostAction(_VimTest): files = { "us/all.snippets": r""" post_expand "asd()" snippet test endsnippet """ } keys = "test" + EX wanted = keys expected_error = "Post-expand: asd" class ParseSnippets_PrintErroneousSnippetLocation(_VimTest): files = { "us/all.snippets": r""" post_expand "asd()" snippet test endsnippet """ } keys = "test" + EX wanted = keys expected_error = "Defined in: .*/all.snippets"
8,557
Python
.py
313
20.635783
75
0.573528
SirVer/ultisnips
7,501
688
112
GPL-3.0
9/5/2024, 5:11:34 PM (Europe/Amsterdam)
12,218
test_Transformation.py
SirVer_ultisnips/test/test_Transformation.py
# encoding: utf-8 from test.vim_test_case import VimTestCase as _VimTest from test.constant import * from test.util import no_unidecode_available class Transformation_SimpleCase_ExpectCorrectResult(_VimTest): snippets = ("test", "$1 ${1/foo/batzl/}") keys = "test" + EX + "hallo foo boy" wanted = "hallo foo boy hallo batzl boy" class Transformation_SimpleCaseNoTransform_ExpectCorrectResult(_VimTest): snippets = ("test", "$1 ${1/foo/batzl/}") keys = "test" + EX + "hallo" wanted = "hallo hallo" class Transformation_SimpleCaseTransformInFront_ExpectCorrectResult(_VimTest): snippets = ("test", "${1/foo/batzl/} $1") keys = "test" + EX + "hallo foo" wanted = "hallo batzl hallo foo" class Transformation_SimpleCaseTransformInFrontDefVal_ECR(_VimTest): snippets = ("test", "${1/foo/batzl/} ${1:replace me}") keys = "test" + EX + "hallo foo" wanted = "hallo batzl hallo foo" class Transformation_MultipleTransformations_ECR(_VimTest): snippets = ("test", "${1:Some Text}${1/.+/\\U$0\E/}\n${1/.+/\L$0\E/}") keys = "test" + EX + "SomE tExt " wanted = "SomE tExt SOME TEXT \nsome text " class Transformation_TabIsAtEndAndDeleted_ECR(_VimTest): snippets = ("test", "${1/.+/is something/}${1:some}") keys = "hallo test" + EX + "some\b\b\b\b\b" wanted = "hallo " class Transformation_TabIsAtEndAndDeleted1_ECR(_VimTest): snippets = ("test", "${1/.+/is something/}${1:some}") keys = "hallo test" + EX + "some\b\b\b\bmore" wanted = "hallo is somethingmore" class Transformation_TabIsAtEndNoTextLeave_ECR(_VimTest): snippets = ("test", "${1/.+/is something/}${1}") keys = "hallo test" + EX wanted = "hallo " class Transformation_TabIsAtEndNoTextType_ECR(_VimTest): snippets = ("test", "${1/.+/is something/}${1}") keys = "hallo test" + EX + "b" wanted = "hallo is somethingb" class Transformation_InsideTabLeaveAtDefault_ECR(_VimTest): snippets = ("test", r"$1 ${2:${1/.+/(?0:defined $0)/}}") keys = "test" + EX + "sometext" + JF wanted = "sometext defined sometext" class Transformation_InsideTabOvertype_ECR(_VimTest): snippets = ("test", r"$1 ${2:${1/.+/(?0:defined $0)/}}") keys = "test" + EX + "sometext" + JF + "overwrite" wanted = "sometext overwrite" class Transformation_Backreference_ExpectCorrectResult(_VimTest): snippets = ("test", "$1 ${1/([ab])oo/$1ull/}") keys = "test" + EX + "foo boo aoo" wanted = "foo boo aoo foo bull aoo" class Transformation_BackreferenceTwice_ExpectCorrectResult(_VimTest): snippets = ("test", r"$1 ${1/(dead) (par[^ ]*)/this $2 is a bit $1/}") keys = "test" + EX + "dead parrot" wanted = "dead parrot this parrot is a bit dead" class Transformation_CleverTransformUpercaseChar_ExpectCorrectResult(_VimTest): snippets = ("test", "$1 ${1/(.)/\\u$1/}") keys = "test" + EX + "hallo" wanted = "hallo Hallo" class Transformation_CleverTransformLowercaseChar_ExpectCorrectResult(_VimTest): snippets = ("test", "$1 ${1/(.*)/\l$1/}") keys = "test" + EX + "Hallo" wanted = "Hallo hallo" class Transformation_CleverTransformLongUpper_ExpectCorrectResult(_VimTest): snippets = ("test", "$1 ${1/(.*)/\\U$1\E/}") keys = "test" + EX + "hallo" wanted = "hallo HALLO" class Transformation_CleverTransformLongLower_ExpectCorrectResult(_VimTest): snippets = ("test", "$1 ${1/(.*)/\L$1\E/}") keys = "test" + EX + "HALLO" wanted = "HALLO hallo" class Transformation_SimpleCaseAsciiResult(_VimTest): skip_if = lambda self: no_unidecode_available() snippets = ("ascii", "$1 ${1/(.*)/$1/a}") keys = "ascii" + EX + "éèàçôïÉÈÀÇÔÏ€" wanted = "éèàçôïÉÈÀÇÔÏ€ eeacoiEEACOIEUR" class Transformation_LowerCaseAsciiResult(_VimTest): skip_if = lambda self: no_unidecode_available() snippets = ("ascii", "$1 ${1/(.*)/\L$1\E/a}") keys = "ascii" + EX + "éèàçôïÉÈÀÇÔÏ€" wanted = "éèàçôïÉÈÀÇÔÏ€ eeacoieeacoieur" class Transformation_ConditionalInsertionSimple_ExpectCorrectResult(_VimTest): snippets = ("test", "$1 ${1/(^a).*/(?0:began with an a)/}") keys = "test" + EX + "a some more text" wanted = "a some more text began with an a" class Transformation_CIBothDefinedNegative_ExpectCorrectResult(_VimTest): snippets = ("test", "$1 ${1/(?:(^a)|(^b)).*/(?1:yes:no)/}") keys = "test" + EX + "b some" wanted = "b some no" class Transformation_CIBothDefinedPositive_ExpectCorrectResult(_VimTest): snippets = ("test", "$1 ${1/(?:(^a)|(^b)).*/(?1:yes:no)/}") keys = "test" + EX + "a some" wanted = "a some yes" class Transformation_ConditionalInsertRWEllipsis_ECR(_VimTest): snippets = ("test", r"$1 ${1/(\w+(?:\W+\w+){,7})\W*(.+)?/$1(?2:...)/}") keys = "test" + EX + "a b c d e f ghhh h oha" wanted = "a b c d e f ghhh h oha a b c d e f ghhh h..." class Transformation_ConditionalInConditional_ECR(_VimTest): snippets = ("test", r"$1 ${1/^.*?(-)?(>)?$/(?2::(?1:>:.))/}") keys = ( "test" + EX + "hallo" + ESC + "$a\n" + "test" + EX + "hallo-" + ESC + "$a\n" + "test" + EX + "hallo->" ) wanted = "hallo .\nhallo- >\nhallo-> " class Transformation_CINewlines_ECR(_VimTest): snippets = ("test", r"$1 ${1/, */\n/}") keys = "test" + EX + "test, hallo" wanted = "test, hallo test\nhallo" class Transformation_CITabstop_ECR(_VimTest): snippets = ("test", r"$1 ${1/, */\t/}") keys = "test" + EX + "test, hallo" wanted = "test, hallo test\thallo" class Transformation_CIEscapedParensinReplace_ECR(_VimTest): snippets = ("test", r"$1 ${1/hal((?:lo)|(?:ul))/(?1:ha\($1\))/}") keys = "test" + EX + "test, halul" wanted = "test, halul test, ha(ul)" class Transformation_OptionIgnoreCase_ECR(_VimTest): snippets = ("test", r"$1 ${1/test/blah/i}") keys = "test" + EX + "TEST" wanted = "TEST blah" class Transformation_OptionMultiline_ECR(_VimTest): snippets = ("test", r"${VISUAL/^/* /mg}") keys = "test\ntest\ntest" + ESC + "V2k" + EX + "test" + EX wanted = "* test\n* test\n* test" class Transformation_OptionReplaceGlobal_ECR(_VimTest): snippets = ("test", r"$1 ${1/, */-/g}") keys = "test" + EX + "a, nice, building" wanted = "a, nice, building a-nice-building" class Transformation_OptionReplaceGlobalMatchInReplace_ECR(_VimTest): snippets = ("test", r"$1 ${1/, */, /g}") keys = "test" + EX + "a, nice, building" wanted = "a, nice, building a, nice, building" class TransformationUsingBackspaceToDeleteDefaultValueInFirstTab_ECR(_VimTest): snippets = ( "test", "snip ${1/.+/(?0:m1)/} ${2/.+/(?0:m2)/} " "${1:default} ${2:def}", ) keys = "test" + EX + BS + JF + "hi" wanted = "snip m2 hi" class TransformationUsingBackspaceToDeleteDefaultValueInSecondTab_ECR(_VimTest): snippets = ( "test", "snip ${1/.+/(?0:m1)/} ${2/.+/(?0:m2)/} " "${1:default} ${2:def}", ) keys = "test" + EX + "hi" + JF + BS wanted = "snip m1 hi " class TransformationUsingBackspaceToDeleteDefaultValueTypeSomethingThen_ECR(_VimTest): snippets = ("test", "snip ${1/.+/(?0:matched)/} ${1:default}") keys = "test" + EX + BS + "hallo" wanted = "snip matched hallo" class TransformationUsingBackspaceToDeleteDefaultValue_ECR(_VimTest): snippets = ("test", "snip ${1/.+/(?0:matched)/} ${1:default}") keys = "test" + EX + BS wanted = "snip " class Transformation_TestKill_InsertBefore_NoKill(_VimTest): snippets = "test", r"$1 ${1/.*/\L$0$0\E/}_" keys = "hallo test" + EX + "AUCH" + ESC + "wihi" + ESC + "bb" + "ino" + JF + "end" wanted = "hallo noAUCH hinoauchnoauch_end" class Transformation_TestKill_InsertAfter_NoKill(_VimTest): snippets = "test", r"$1 ${1/.*/\L$0$0\E/}_" keys = "hallo test" + EX + "AUCH" + ESC + "eiab" + ESC + "bb" + "ino" + JF + "end" wanted = "hallo noAUCH noauchnoauchab_end" class Transformation_TestKill_InsertBeginning_Kill(_VimTest): snippets = "test", r"$1 ${1/.*/\L$0$0\E/}_" keys = "hallo test" + EX + "AUCH" + ESC + "wahi" + ESC + "bb" + "ino" + JF + "end" wanted = "hallo noAUCH ahiuchauch_end" class Transformation_TestKill_InsertEnd_Kill(_VimTest): snippets = "test", r"$1 ${1/.*/\L$0$0\E/}_" keys = "hallo test" + EX + "AUCH" + ESC + "ehihi" + ESC + "bb" + "ino" + JF + "end" wanted = "hallo noAUCH auchauchih_end" class Transformation_ConditionalWithEscapedDelimiter(_VimTest): snippets = "test", r"$1 ${1/(aa)|.*/(?1:yes\:no\))/}" keys = "test" + EX + "aa" wanted = "aa yes:no)" class Transformation_ConditionalWithBackslashBeforeDelimiter(_VimTest): snippets = "test", r"$1 ${1/(aa)|.*/(?1:yes\\:no)/}" keys = "test" + EX + "aa" wanted = "aa yes\\" class Transformation_ConditionalWithBackslashBeforeDelimiter1(_VimTest): snippets = "test", r"$1 ${1/(aa)|.*/(?1:yes:no\\)/}" keys = "test" + EX + "ab" wanted = "ab no\\"
9,114
Python
.py
194
41.85567
87
0.617084
SirVer/ultisnips
7,501
688
112
GPL-3.0
9/5/2024, 5:11:34 PM (Europe/Amsterdam)
12,219
test_TabStop.py
SirVer_ultisnips/test/test_TabStop.py
from test.vim_test_case import VimTestCase as _VimTest from test.constant import * class TabStopSimpleReplace_ExpectCorrectResult(_VimTest): snippets = ("hallo", "hallo ${0:End} ${1:Beginning}") keys = "hallo" + EX + "na" + JF + "Du Nase" wanted = "hallo Du Nase na" class TabStopSimpleReplaceZeroLengthTabstops_ExpectCorrectResult(_VimTest): snippets = ("test", r":latex:\`$1\`$0") keys = "test" + EX + "Hello" + JF + "World" wanted = ":latex:`Hello`World" class TabStopSimpleReplaceReversed_ExpectCorrectResult(_VimTest): snippets = ("hallo", "hallo ${1:End} ${0:Beginning}") keys = "hallo" + EX + "na" + JF + "Du Nase" wanted = "hallo na Du Nase" class TabStopSimpleReplaceSurrounded_ExpectCorrectResult(_VimTest): snippets = ("hallo", "hallo ${0:End} a small feed") keys = "hallo" + EX + "Nase" wanted = "hallo Nase a small feed" class TabStopSimpleReplaceSurrounded1_ExpectCorrectResult(_VimTest): snippets = ("hallo", "hallo $0 a small feed") keys = "hallo" + EX + "Nase" wanted = "hallo Nase a small feed" class TabStop_Exit_ExpectCorrectResult(_VimTest): snippets = ("echo", "$0 run") keys = "echo" + EX + "test" wanted = "test run" class TabStopNoReplace_ExpectCorrectResult(_VimTest): snippets = ("echo", "echo ${1:Hallo}") keys = "echo" + EX wanted = "echo Hallo" class TabStop_EscapingCharsBackticks(_VimTest): snippets = ("test", r"snip \` literal") keys = "test" + EX wanted = "snip ` literal" class TabStop_EscapingCharsDollars(_VimTest): snippets = ("test", r"snip \$0 $$0 end") keys = "test" + EX + "hi" wanted = "snip $0 $hi end" class TabStop_EscapingCharsDollars1(_VimTest): snippets = ("test", r"a\${1:literal}") keys = "test" + EX wanted = "a${1:literal}" class TabStop_EscapingCharsDollars_BeginningOfLine(_VimTest): snippets = ("test", "\n\\${1:literal}") keys = "test" + EX wanted = "\n${1:literal}" class TabStop_EscapingCharsDollars_BeginningOfDefinitionText(_VimTest): snippets = ("test", "\\${1:literal}") keys = "test" + EX wanted = "${1:literal}" class TabStop_EscapingChars_Backslash(_VimTest): snippets = ("test", r"This \ is a backslash!") keys = "test" + EX wanted = "This \\ is a backslash!" class TabStop_EscapingChars_Backslash2(_VimTest): snippets = ("test", r"This is a backslash \\ done") keys = "test" + EX wanted = r"This is a backslash \ done" class TabStop_EscapingChars_Backslash3(_VimTest): snippets = ("test", r"These are two backslashes \\\\ done") keys = "test" + EX wanted = r"These are two backslashes \\ done" class TabStop_EscapingChars_Backslash4(_VimTest): # Test for bug 746446 snippets = ("test", r"\\$1{$2}") keys = "test" + EX + "hello" + JF + "world" wanted = r"\hello{world}" class TabStop_EscapingChars_RealLife(_VimTest): snippets = ("test", r"usage: \`basename \$0\` ${1:args}") keys = "test" + EX + "[ -u -v -d ]" wanted = "usage: `basename $0` [ -u -v -d ]" class TabStopEscapingWhenSelected_ECR(_VimTest): snippets = ("test", "snip ${1:default}") keys = "test" + EX + ESC + "0ihi" wanted = "hisnip default" class TabStopEscapingWhenSelectedSingleCharTS_ECR(_VimTest): snippets = ("test", "snip ${1:i}") keys = "test" + EX + ESC + "0ihi" wanted = "hisnip i" class TabStopEscapingWhenSelectedNoCharTS_ECR(_VimTest): snippets = ("test", "snip $1") keys = "test" + EX + ESC + "0ihi" wanted = "hisnip " class TabStopWithOneChar_ExpectCorrectResult(_VimTest): snippets = ("hallo", "nothing ${1:i} hups") keys = "hallo" + EX + "ship" wanted = "nothing ship hups" class TabStopTestJumping_ExpectCorrectResult(_VimTest): snippets = ("hallo", "hallo ${2:End} mitte ${1:Beginning}") keys = "hallo" + EX + JF + "Test" + JF + "Hi" wanted = "hallo Test mitte BeginningHi" class TabStopTestJumping2_ExpectCorrectResult(_VimTest): snippets = ("hallo", "hallo $2 $1") keys = "hallo" + EX + JF + "Test" + JF + "Hi" wanted = "hallo Test Hi" class TabStopTestJumpingRLExampleWithZeroTab_ExpectCorrectResult(_VimTest): snippets = ("test", "each_byte { |${1:byte}| $0 }") keys = "test" + EX + JF + "Blah" wanted = "each_byte { |byte| Blah }" class TabStopTestJumpingDontJumpToEndIfThereIsTabZero_ExpectCorrectResult(_VimTest): snippets = ("hallo", "hallo $0 $1") keys = "hallo" + EX + "Test" + JF + "Hi" + JF + JF + "du" wanted = "hallo Hi" + 2 * JF + "du Test" class TabStopTestBackwardJumping_ExpectCorrectResult(_VimTest): snippets = ("hallo", "hallo ${2:End} mitte${1:Beginning}") keys = ( "hallo" + EX + "Somelengthy Text" + JF + "Hi" + JB + "Lets replace it again" + JF + "Blah" + JF + JB * 2 + JF ) wanted = "hallo Blah mitteLets replace it again" + JB * 2 + JF class TabStopTestBackwardJumping2_ExpectCorrectResult(_VimTest): snippets = ("hallo", "hallo $2 $1") keys = ( "hallo" + EX + "Somelengthy Text" + JF + "Hi" + JB + "Lets replace it again" + JF + "Blah" + JF + JB * 2 + JF ) wanted = "hallo Blah Lets replace it again" + JB * 2 + JF class TabStopTestMultilineExpand_ExpectCorrectResult(_VimTest): snippets = ("hallo", "hallo $0\nnice $1 work\n$3 $2\nSeem to work") keys = ( "test hallo World" + ESC + "02f i" + EX + "world" + JF + "try" + JF + "test" + JF + "one more" + JF ) wanted = ( "test hallo one more" + JF + "\nnice world work\n" "test try\nSeem to work World" ) class TabStop_TSInDefaultTextRLExample_OverwriteNone_ECR(_VimTest): snippets = ("test", """<div${1: id="${2:some_id}"}>\n $0\n</div>""") keys = "test" + EX wanted = """<div id="some_id">\n \n</div>""" class TabStop_TSInDefaultTextRLExample_OverwriteFirst_NoJumpBack(_VimTest): snippets = ("test", """<div${1: id="${2:some_id}"}>\n $0\n</div>""") keys = "test" + EX + " blah" + JF + "Hallo" wanted = """<div blah>\n Hallo\n</div>""" class TabStop_TSInDefaultTextRLExample_DeleteFirst(_VimTest): snippets = ("test", """<div${1: id="${2:some_id}"}>\n $0\n</div>""") keys = "test" + EX + BS + JF + "Hallo" wanted = """<div>\n Hallo\n</div>""" class TabStop_TSInDefaultTextRLExample_OverwriteFirstJumpBack(_VimTest): snippets = ("test", """<div${1: id="${2:some_id}"}>\n $3 $0\n</div>""") keys = ( "test" + EX + "Hi" + JF + "Hallo" + JB + "SomethingElse" + JF + "Nupl" + JF + "Nox" ) wanted = """<divSomethingElse>\n Nupl Nox\n</div>""" class TabStop_TSInDefaultTextRLExample_OverwriteSecond(_VimTest): snippets = ("test", """<div${1: id="${2:some_id}"}>\n $0\n</div>""") keys = "test" + EX + JF + "no" + JF + "End" wanted = """<div id="no">\n End\n</div>""" class TabStop_TSInDefaultTextRLExample_OverwriteSecondTabBack(_VimTest): snippets = ("test", """<div${1: id="${2:some_id}"}>\n $3 $0\n</div>""") keys = "test" + EX + JF + "no" + JF + "End" + JB + "yes" + JF + "Begin" + JF + "Hi" wanted = """<div id="yes">\n Begin Hi\n</div>""" class TabStop_TSInDefaultTextRLExample_OverwriteSecondTabBackTwice(_VimTest): snippets = ("test", """<div${1: id="${2:some_id}"}>\n $3 $0\n</div>""") keys = ( "test" + EX + JF + "no" + JF + "End" + JB + "yes" + JB + " allaway" + JF + "Third" + JF + "Last" ) wanted = """<div allaway>\n Third Last\n</div>""" class TabStop_TSInDefaultText_ZeroLengthNested_OverwriteSecond(_VimTest): snippets = ("test", """h${1:a$2b}l""") keys = "test" + EX + JF + "ups" + JF + "End" wanted = """haupsblEnd""" class TabStop_TSInDefaultText_ZeroLengthZerothTabstop(_VimTest): snippets = ( "test", """Test: ${1:snippet start\nNested tabstop: $0\nsnippet end}\nTrailing text""", ) keys = "test" + EX + JF + "hello" wanted = "Test: snippet start\nNested tabstop: hello\nsnippet end\nTrailing text" class TabStop_TSInDefaultText_ZeroLengthZerothTabstop_Override(_VimTest): snippets = ( "test", """Test: ${1:snippet start\nNested tabstop: $0\nsnippet end}\nTrailing text""", ) keys = "test" + EX + "blub" + JF + "hello" wanted = "Test: blub\nTrailing texthello" class TabStop_TSInDefaultText_ZeroLengthNested_OverwriteFirst(_VimTest): snippets = ("test", """h${1:a$2b}l""") keys = "test" + EX + "ups" + JF + "End" wanted = """hupslEnd""" class TabStop_TSInDefaultText_ZeroLengthNested_OverwriteSecondJumpBackOverwrite( _VimTest ): snippets = ("test", """h${1:a$2b}l""") keys = "test" + EX + JF + "longertext" + JB + "overwrite" + JF + "End" wanted = """hoverwritelEnd""" class TabStop_TSInDefaultText_ZeroLengthNested_OverwriteSecondJumpBackAndForward0( _VimTest ): snippets = ("test", """h${1:a$2b}l""") keys = "test" + EX + JF + "longertext" + JB + JF + "overwrite" + JF + "End" wanted = """haoverwriteblEnd""" class TabStop_TSInDefaultText_ZeroLengthNested_OverwriteSecondJumpBackAndForward1( _VimTest ): snippets = ("test", """h${1:a$2b}l""") keys = "test" + EX + JF + "longertext" + JB + JF + JF + "End" wanted = """halongertextblEnd""" class TabStop_TSInDefaultNested_OverwriteOneJumpBackToOther(_VimTest): snippets = ("test", "hi ${1:this ${2:second ${3:third}}} $4") keys = "test" + EX + JF + "Hallo" + JF + "Ende" wanted = "hi this Hallo Ende" class TabStop_TSInDefaultNested_OverwriteOneJumpToThird(_VimTest): snippets = ("test", "hi ${1:this ${2:second ${3:third}}} $4") keys = "test" + EX + JF + JF + "Hallo" + JF + "Ende" wanted = "hi this second Hallo Ende" class TabStop_TSInDefaultNested_OverwriteOneJumpAround(_VimTest): snippets = ("test", "hi ${1:this ${2:second ${3:third}}} $4") keys = "test" + EX + JF + JF + "Hallo" + JB + JB + "Blah" + JF + "Ende" wanted = "hi Blah Ende" class TabStop_TSInDefault_MirrorsOutside_DoNothing(_VimTest): snippets = ("test", "hi ${1:this ${2:second}} $2") keys = "test" + EX wanted = "hi this second second" class TabStop_TSInDefault_MirrorsOutside_OverwriteSecond(_VimTest): snippets = ("test", "hi ${1:this ${2:second}} $2") keys = "test" + EX + JF + "Hallo" wanted = "hi this Hallo Hallo" class TabStop_TSInDefault_MirrorsOutside_Overwrite0(_VimTest): snippets = ("test", "hi ${1:this ${2:second}} $2") keys = "test" + EX + "Hallo" wanted = "hi Hallo " class TabStop_TSInDefault_MirrorsOutside_Overwrite1(_VimTest): snippets = ("test", "$1: ${1:'${2:second}'} $2") keys = "test" + EX + "Hallo" wanted = "Hallo: Hallo " class TabStop_TSInDefault_MirrorsOutside_OverwriteSecond1(_VimTest): snippets = ("test", "$1: ${1:'${2:second}'} $2") keys = "test" + EX + JF + "Hallo" wanted = "'Hallo': 'Hallo' Hallo" class TabStop_TSInDefault_MirrorsOutside_OverwriteFirstSwitchNumbers(_VimTest): snippets = ("test", "$2: ${2:'${1:second}'} $1") keys = "test" + EX + "Hallo" wanted = "'Hallo': 'Hallo' Hallo" class TabStop_TSInDefault_MirrorsOutside_OverwriteFirst_RLExample(_VimTest): snippets = ( "test", """`!p snip.rv = t[1].split('/')[-1].lower().strip("'")` = require(${1:'${2:sys}'})""", ) keys = "test" + EX + "WORLD" + JF + "End" wanted = "world = require(WORLD)End" class TabStop_TSInDefault_MirrorsOutside_OverwriteSecond_RLExample(_VimTest): snippets = ( "test", """`!p snip.rv = t[1].split('/')[-1].lower().strip("'")` = require(${1:'${2:sys}'})""", ) keys = "test" + EX + JF + "WORLD" + JF + "End" wanted = "world = require('WORLD')End" class TabStop_Multiline_Leave(_VimTest): snippets = ("test", "hi ${1:first line\nsecond line} world") keys = "test" + EX wanted = "hi first line\nsecond line world" class TabStop_Multiline_Overwrite(_VimTest): snippets = ("test", "hi ${1:first line\nsecond line} world") keys = "test" + EX + "Nothing" wanted = "hi Nothing world" class TabStop_Multiline_MirrorInFront_Leave(_VimTest): snippets = ("test", "hi $1 ${1:first line\nsecond line} world") keys = "test" + EX wanted = "hi first line\nsecond line first line\nsecond line world" class TabStop_Multiline_MirrorInFront_Overwrite(_VimTest): snippets = ("test", "hi $1 ${1:first line\nsecond line} world") keys = "test" + EX + "Nothing" wanted = "hi Nothing Nothing world" class TabStop_Multiline_DelFirstOverwriteSecond_Overwrite(_VimTest): snippets = ("test", "hi $1 $2 ${1:first line\nsecond line} ${2:Hi} world") keys = "test" + EX + BS + JF + "Nothing" wanted = "hi Nothing Nothing world" class TabStopNavigatingInInsertModeSimple_ExpectCorrectResult(_VimTest): snippets = ("hallo", "Hallo ${1:WELT} ups") keys = "hallo" + EX + "haselnut" + 2 * ARR_L + "hips" + JF + "end" wanted = "Hallo haselnhipsut upsend" class TabStop_CROnlyOnSelectedNear(_VimTest): snippets = ("test", "t$1t${2: }t{\n\t$0\n}") keys = "test" + EX + JF + "\n" + JF + "t" wanted = "tt\nt{\n\tt\n}" class TabStop_AdjacentTabStopAddText_ExpectCorrectResult(_VimTest): snippets = ("test", "[ $1$2 ] $1") keys = "test" + EX + "Hello" + JF + "World" + JF wanted = "[ HelloWorld ] Hello" class TabStop_KeepCorrectJumpListOnOverwriteOfPartOfSnippet(_VimTest): files = { "us/all.snippets": r""" snippet i ia$1: $2 endsnippet snippet ia ia($1, $2) endsnippet""" } keys = "i" + EX + EX + "1" + JF + "2" + JF + " after" + JF + "3" wanted = "ia(1, 2) after: 3" class TabStop_KeepCorrectJumpListOnOverwriteOfPartOfSnippetRE(_VimTest): files = { "us/all.snippets": r""" snippet i ia$1: $2 endsnippet snippet "^ia" "regexp" r ia($1, $2) endsnippet""" } keys = "i" + EX + EX + "1" + JF + "2" + JF + " after" + JF + "3" wanted = "ia(1, 2) after: 3"
14,443
Python
.py
358
34.796089
95
0.603425
SirVer/ultisnips
7,501
688
112
GPL-3.0
9/5/2024, 5:11:34 PM (Europe/Amsterdam)
12,220
test_ListSnippets.py
SirVer_ultisnips/test/test_ListSnippets.py
from test.vim_test_case import VimTestCase as _VimTest from test.constant import * class _ListAllSnippets(_VimTest): snippets = ( ("testblah", "BLAAH", "Say BLAH"), ("test", "TEST ONE", "Say tst one"), ("aloha", "OHEEEE", "Say OHEE"), ) class ListAllAvailable_NothingTyped_ExpectCorrectResult(_ListAllSnippets): keys = "" + LS + "3\n" wanted = "BLAAH" class ListAllAvailable_SpaceInFront_ExpectCorrectResult(_ListAllSnippets): keys = " " + LS + "3\n" wanted = " BLAAH" class ListAllAvailable_BraceInFront_ExpectCorrectResult(_ListAllSnippets): keys = "} " + LS + "3\n" wanted = "} BLAAH" class ListAllAvailable_testtyped_ExpectCorrectResult(_ListAllSnippets): keys = "hallo test" + LS + "2\n" wanted = "hallo BLAAH" class ListAllAvailable_testtypedSecondOpt_ExpectCorrectResult(_ListAllSnippets): keys = "hallo test" + LS + "1\n" wanted = "hallo TEST ONE" class ListAllAvailable_NonDefined_NoExpectionShouldBeRaised(_ListAllSnippets): keys = "hallo qualle" + LS + "Hi" wanted = "hallo qualleHi" class ListAllAvailable_Disabled_ExpectCorrectResult(_ListAllSnippets): keys = "hallo test" + LS + "2\n" wanted = "hallo test" + LS + "2\n" def _extra_vim_config(self, vim_config): vim_config.append('let g:UltiSnipsListSnippets=""')
1,344
Python
.py
31
38.580645
80
0.695216
SirVer/ultisnips
7,501
688
112
GPL-3.0
9/5/2024, 5:11:34 PM (Europe/Amsterdam)
12,221
constant.py
SirVer_ultisnips/test/constant.py
# Some constants for better reading BS = "\x7f" ESC = "\x1b" ARR_L = "\x1bOD" ARR_R = "\x1bOC" ARR_U = "\x1bOA" ARR_D = "\x1bOB" # multi-key sequences generating a single key press SEQUENCES = [ARR_L, ARR_R, ARR_U, ARR_D] # Defined Constants JF = "?" # Jump forwards JB = "+" # Jump backwards LS = "@" # List snippets EX = "\t" # EXPAND EA = "#" # Expand anonymous COMPL_KW = chr(24) + chr(14) COMPL_ACCEPT = chr(25) CTRL_V = chr(22)
443
Python
.py
18
23.388889
51
0.643705
SirVer/ultisnips
7,501
688
112
GPL-3.0
9/5/2024, 5:11:34 PM (Europe/Amsterdam)
12,222
test_SnippetOptions.py
SirVer_ultisnips/test/test_SnippetOptions.py
# encoding: utf-8 from test.vim_test_case import VimTestCase as _VimTest from test.constant import * from test.util import running_on_windows class SnippetOptions_OnlyExpandWhenWSInFront_Expand(_VimTest): snippets = ("test", "Expand me!", "", "b") keys = "test" + EX wanted = "Expand me!" class SnippetOptions_OnlyExpandWhenWSInFront_Expand2(_VimTest): snippets = ("test", "Expand me!", "", "b") keys = " test" + EX wanted = " Expand me!" class SnippetOptions_OnlyExpandWhenWSInFront_DontExpand(_VimTest): snippets = ("test", "Expand me!", "", "b") keys = "a test" + EX wanted = "a test" + EX class SnippetOptions_OnlyExpandWhenWSInFront_OneWithOneWO(_VimTest): snippets = (("test", "Expand me!", "", "b"), ("test", "not at beginning", "", "")) keys = "a test" + EX wanted = "a not at beginning" class SnippetOptions_OnlyExpandWhenWSInFront_OneWithOneWOChoose(_VimTest): snippets = (("test", "Expand me!", "", "b"), ("test", "not at beginning", "", "")) keys = " test" + EX + "1\n" wanted = " Expand me!" class SnippetOptions_ExpandInwordSnippets_SimpleExpand(_VimTest): snippets = (("test", "Expand me!", "", "i"),) keys = "atest" + EX wanted = "aExpand me!" class SnippetOptions_ExpandInwordSnippets_ExpandSingle(_VimTest): snippets = (("test", "Expand me!", "", "i"),) keys = "test" + EX wanted = "Expand me!" class SnippetOptions_ExpandInwordSnippetsWithOtherChars_Expand(_VimTest): snippets = (("test", "Expand me!", "", "i"),) keys = "$test" + EX wanted = "$Expand me!" class SnippetOptions_ExpandInwordSnippetsWithOtherChars_Expand2(_VimTest): snippets = (("test", "Expand me!", "", "i"),) keys = "-test" + EX wanted = "-Expand me!" class SnippetOptions_ExpandInwordSnippetsWithOtherChars_Expand3(_VimTest): skip_if = lambda self: running_on_windows() snippets = (("test", "Expand me!", "", "i"),) keys = "ßßtest" + EX wanted = "ßßExpand me!" class _SnippetOptions_ExpandWordSnippets(_VimTest): snippets = (("test", "Expand me!", "", "w"),) class SnippetOptions_ExpandWordSnippets_NormalExpand( _SnippetOptions_ExpandWordSnippets ): keys = "test" + EX wanted = "Expand me!" class SnippetOptions_ExpandWordSnippets_NoExpand(_SnippetOptions_ExpandWordSnippets): keys = "atest" + EX wanted = "atest" + EX class SnippetOptions_ExpandWordSnippets_ExpandSuffix( _SnippetOptions_ExpandWordSnippets ): keys = "a-test" + EX wanted = "a-Expand me!" class SnippetOptions_ExpandWordSnippets_ExpandSuffix2( _SnippetOptions_ExpandWordSnippets ): keys = "a(test" + EX wanted = "a(Expand me!" class SnippetOptions_ExpandWordSnippets_ExpandSuffix3( _SnippetOptions_ExpandWordSnippets ): keys = "[[test" + EX wanted = "[[Expand me!" class _No_Tab_Expand(_VimTest): snippets = ("test", "\t\tExpand\tme!\t", "", "t") class No_Tab_Expand_Simple(_No_Tab_Expand): keys = "test" + EX wanted = "\t\tExpand\tme!\t" class No_Tab_Expand_Leading_Spaces(_No_Tab_Expand): keys = " test" + EX wanted = " \t\tExpand\tme!\t" class No_Tab_Expand_Leading_Tabs(_No_Tab_Expand): keys = "\ttest" + EX wanted = "\t\t\tExpand\tme!\t" class No_Tab_Expand_No_TS(_No_Tab_Expand): def _extra_vim_config(self, vim_config): vim_config.append("set sw=3") vim_config.append("set sts=3") keys = "test" + EX wanted = "\t\tExpand\tme!\t" class No_Tab_Expand_ET(_No_Tab_Expand): def _extra_vim_config(self, vim_config): vim_config.append("set sw=3") vim_config.append("set expandtab") keys = "test" + EX wanted = "\t\tExpand\tme!\t" class No_Tab_Expand_ET_Leading_Spaces(_No_Tab_Expand): def _extra_vim_config(self, vim_config): vim_config.append("set sw=3") vim_config.append("set expandtab") keys = " test" + EX wanted = " \t\tExpand\tme!\t" class No_Tab_Expand_ET_SW(_No_Tab_Expand): def _extra_vim_config(self, vim_config): vim_config.append("set sw=8") vim_config.append("set expandtab") keys = "test" + EX wanted = "\t\tExpand\tme!\t" class No_Tab_Expand_ET_SW_TS(_No_Tab_Expand): def _extra_vim_config(self, vim_config): vim_config.append("set sw=3") vim_config.append("set sts=3") vim_config.append("set ts=3") vim_config.append("set expandtab") keys = "test" + EX wanted = "\t\tExpand\tme!\t" class _TabExpand_RealWorld: snippets = ( "hi", r"""hi `!p snip.rv="i1\n" snip.rv += snip.mkline("i1\n") snip.shift(1) snip.rv += snip.mkline("i2\n") snip.unshift(2) snip.rv += snip.mkline("i0\n") snip.shift(3) snip.rv += snip.mkline("i3")` snip.rv = repr(snip.rv) End""", ) class No_Tab_Expand_RealWorld(_TabExpand_RealWorld, _VimTest): def _extra_vim_config(self, vim_config): vim_config.append("set noexpandtab") keys = "\t\thi" + EX wanted = """\t\thi \t\ti1 \t\ti1 \t\t\ti2 \ti0 \t\t\t\ti3 \t\tsnip.rv = repr(snip.rv) \t\tEnd""" class SnippetOptions_Regex_Expand(_VimTest): snippets = ("(test)", "Expand me!", "", "r") keys = "test" + EX wanted = "Expand me!" class SnippetOptions_Regex_WithSpace(_VimTest): snippets = ("test ", "Expand me!", "", "r") keys = "test " + EX wanted = "Expand me!" class SnippetOptions_Regex_Multiple(_VimTest): snippets = ("(test *)+", "Expand me!", "", "r") keys = "test test test" + EX wanted = "Expand me!" class _Regex_Self(_VimTest): snippets = ("((?<=\W)|^)(\.)", "self.", "", "r") class SnippetOptions_Regex_Self_Start(_Regex_Self): keys = "." + EX wanted = "self." class SnippetOptions_Regex_Self_Space(_Regex_Self): keys = " ." + EX wanted = " self." class SnippetOptions_Regex_Self_TextAfter(_Regex_Self): keys = " .a" + EX wanted = " .a" + EX class SnippetOptions_Regex_Self_TextBefore(_Regex_Self): keys = "a." + EX wanted = "a." + EX class SnippetOptions_Regex_PythonBlockMatch(_VimTest): snippets = ( r"([abc]+)([def]+)", r"""`!p m = match snip.rv += m.group(2) snip.rv += m.group(1) `""", "", "r", ) keys = "test cabfed" + EX wanted = "test fedcab" class SnippetOptions_Regex_PythonBlockNoMatch(_VimTest): snippets = (r"cabfed", r"""`!p snip.rv = match or "No match"`""") keys = "test cabfed" + EX wanted = "test No match" # Tests for Bug #691575 class SnippetOptions_Regex_SameLine_Long_End(_VimTest): snippets = ("(test.*)", "Expand me!", "", "r") keys = "test test abc" + EX wanted = "Expand me!" class SnippetOptions_Regex_SameLine_Long_Start(_VimTest): snippets = ("(.*test)", "Expand me!", "", "r") keys = "abc test test" + EX wanted = "Expand me!" class SnippetOptions_Regex_SameLine_Simple(_VimTest): snippets = ("(test)", "Expand me!", "", "r") keys = "abc test test" + EX wanted = "abc test Expand me!" class MultiWordSnippet_Simple(_VimTest): snippets = ("test me", "Expand me!") keys = "test me" + EX wanted = "Expand me!" class MultiWord_SnippetOptions_OnlyExpandWhenWSInFront_Expand(_VimTest): snippets = ("test it", "Expand me!", "", "b") keys = "test it" + EX wanted = "Expand me!" class MultiWord_SnippetOptions_OnlyExpandWhenWSInFront_Expand2(_VimTest): snippets = ("test it", "Expand me!", "", "b") keys = " test it" + EX wanted = " Expand me!" class MultiWord_SnippetOptions_OnlyExpandWhenWSInFront_DontExpand(_VimTest): snippets = ("test it", "Expand me!", "", "b") keys = "a test it" + EX wanted = "a test it" + EX class MultiWord_SnippetOptions_OnlyExpandWhenWSInFront_OneWithOneWO(_VimTest): snippets = ( ("test it", "Expand me!", "", "b"), ("test it", "not at beginning", "", ""), ) keys = "a test it" + EX wanted = "a not at beginning" class MultiWord_SnippetOptions_OnlyExpandWhenWSInFront_OneWithOneWOChoose(_VimTest): snippets = ( ("test it", "Expand me!", "", "b"), ("test it", "not at beginning", "", ""), ) keys = " test it" + EX + "1\n" wanted = " Expand me!" class MultiWord_SnippetOptions_ExpandInwordSnippets_SimpleExpand(_VimTest): snippets = (("test it", "Expand me!", "", "i"),) keys = "atest it" + EX wanted = "aExpand me!" class MultiWord_SnippetOptions_ExpandInwordSnippets_ExpandSingle(_VimTest): snippets = (("test it", "Expand me!", "", "i"),) keys = "test it" + EX wanted = "Expand me!" class _MultiWord_SnippetOptions_ExpandWordSnippets(_VimTest): snippets = (("test it", "Expand me!", "", "w"),) class MultiWord_SnippetOptions_ExpandWordSnippets_NormalExpand( _MultiWord_SnippetOptions_ExpandWordSnippets ): keys = "test it" + EX wanted = "Expand me!" class MultiWord_SnippetOptions_ExpandWordSnippets_NoExpand( _MultiWord_SnippetOptions_ExpandWordSnippets ): keys = "atest it" + EX wanted = "atest it" + EX class MultiWord_SnippetOptions_ExpandWordSnippets_ExpandSuffix( _MultiWord_SnippetOptions_ExpandWordSnippets ): keys = "a-test it" + EX wanted = "a-Expand me!"
9,210
Python
.py
250
32.352
86
0.643035
SirVer/ultisnips
7,501
688
112
GPL-3.0
9/5/2024, 5:11:34 PM (Europe/Amsterdam)
12,223
test_Format.py
SirVer_ultisnips/test/test_Format.py
from test.vim_test_case import VimTestCase as _VimTest from test.constant import * from test.util import running_on_windows class _ExpandTabs(_VimTest): def _extra_vim_config(self, vim_config): vim_config.append("set sw=3") vim_config.append("set expandtab") class RecTabStopsWithExpandtab_SimpleExample_ECR(_ExpandTabs): snippets = ("m", "\tBlaahblah \t\t ") keys = "m" + EX wanted = " Blaahblah \t\t " class RecTabStopsWithExpandtab_SpecialIndentProblem_ECR(_ExpandTabs): # Windows indents the Something line after pressing return, though it # shouldn't because it contains a manual indent. All other vim versions do # not do this. Windows vim does not interpret the changes made by :py as # changes made 'manually', while the other vim version seem to do so. Since # the fault is not with UltiSnips, we simply skip this test on windows # completely. skip_if = lambda self: running_on_windows() snippets = (("m1", "Something"), ("m", "\t$0")) keys = "m" + EX + "m1" + EX + "\nHallo" wanted = " Something\n Hallo" def _extra_vim_config(self, vim_config): _ExpandTabs._extra_vim_config(self, vim_config) vim_config.append("set indentkeys=o,O,*<Return>,<>>,{,}") vim_config.append("set indentexpr=8") class ProperIndenting_SimpleCase_ECR(_VimTest): snippets = ("test", "for\n blah") keys = " test" + EX + "Hui" wanted = " for\n blahHui" class ProperIndenting_SingleLineNoReindenting_ECR(_VimTest): snippets = ("test", "hui") keys = " test" + EX + "blah" wanted = " huiblah" class ProperIndenting_AutoIndentAndNewline_ECR(_VimTest): snippets = ("test", "hui") keys = " test" + EX + "\n" + "blah" wanted = " hui\n blah" def _extra_vim_config(self, vim_config): vim_config.append("set autoindent") # Test for bug 1073816 class ProperIndenting_FirstLineInFile_ECR(_VimTest): text_before = "" text_after = "" files = { "us/all.snippets": r""" global !p def complete(t, opts): if t: opts = [ m[len(t):] for m in opts if m.startswith(t) ] if len(opts) == 1: return opts[0] elif len(opts) > 1: return "(" + "|".join(opts) + ")" else: return "" endglobal snippet '^#?inc' "#include <>" !r #include <$1`!p snip.rv = complete(t[1], ['cassert', 'cstdio', 'cstdlib', 'cstring', 'fstream', 'iostream', 'sstream'])`> endsnippet """ } keys = "inc" + EX + "foo" wanted = "#include <foo>" class ProperIndenting_FirstLineInFileComplete_ECR(ProperIndenting_FirstLineInFile_ECR): keys = "inc" + EX + "cstdl" wanted = "#include <cstdlib>" class _FormatoptionsBase(_VimTest): def _extra_vim_config(self, vim_config): vim_config.append("set tw=20") vim_config.append("set fo=lrqntc") class FOSimple_Break_ExpectCorrectResult(_FormatoptionsBase): snippets = ("test", "${1:longer expand}\n$1\n$0", "", "f") keys = ( "test" + EX + "This is a longer text that should wrap as formatoptions are enabled" + JF + "end" ) wanted = ( "This is a longer\ntext that should\nwrap as\nformatoptions are\nenabled\n" + "This is a longer\ntext that should\nwrap as\nformatoptions are\nenabled\n" + "end" ) class FOTextBeforeAndAfter_ExpectCorrectResult(_FormatoptionsBase): snippets = ("test", "Before${1:longer expand}After\nstart$1end") keys = "test" + EX + "This is a longer text that should wrap" wanted = """BeforeThis is a longer text that should wrapAfter startThis is a longer text that should wrapend""" # Tests for https://bugs.launchpad.net/bugs/719998 class FOTextAfter_ExpectCorrectResult(_FormatoptionsBase): snippets = ("test", "${1:longer expand}after\nstart$1end") keys = ( "test" + EX + "This is a longer snippet that should wrap properly " "and the mirror below should work as well" ) wanted = """This is a longer snippet that should wrap properly and the mirror below should work as wellafter startThis is a longer snippet that should wrap properly and the mirror below should work as wellend""" class FOWrapOnLongWord_ExpectCorrectResult(_FormatoptionsBase): snippets = ("test", "${1:longer expand}after\nstart$1end") keys = "test" + EX + "This is a longersnippet that should wrap properly" wanted = """This is a longersnippet that should wrap properlyafter startThis is a longersnippet that should wrap properlyend"""
4,553
Python
.py
120
33.516667
121
0.67015
SirVer/ultisnips
7,501
688
112
GPL-3.0
9/5/2024, 5:11:34 PM (Europe/Amsterdam)
12,224
test_Chars.py
SirVer_ultisnips/test/test_Chars.py
# encoding: utf-8 from test.vim_test_case import VimTestCase as _VimTest from test.constant import * from test.util import running_on_windows def _snip_quote(qt): return ( ("te" + qt + "st", "Expand me" + qt + "!", "test: " + qt), ("te", "Bad", ""), ) class Snippet_With_SingleQuote(_VimTest): snippets = _snip_quote("'") keys = "te'st" + EX wanted = "Expand me'!" class Snippet_With_SingleQuote_List(_VimTest): snippets = _snip_quote("'") keys = "te" + LS + "2\n" wanted = "Expand me'!" class Snippet_With_DoubleQuote(_VimTest): snippets = _snip_quote('"') keys = 'te"st' + EX wanted = 'Expand me"!' class Snippet_With_DoubleQuote_List(_VimTest): snippets = _snip_quote('"') keys = "te" + LS + "2\n" wanted = 'Expand me"!' class RemoveTrailingWhitespace(_VimTest): snippets = ("test", """Hello\t ${1:default}\n$2""", "", "s") wanted = """Hello\nGoodbye""" keys = "test" + EX + BS + JF + "Goodbye" class TrimSpacesAtEndOfLines(_VimTest): snippets = ("test", """next line\n\nshould be empty""", "", "m") wanted = """\tnext line\n\n\tshould be empty""" keys = "\ttest" + EX class DoNotTrimSpacesAtEndOfLinesByDefault(_VimTest): snippets = ("test", """next line\n\nshould be empty""", "", "") wanted = """\tnext line\n\t\n\tshould be empty""" keys = "\ttest" + EX class LeaveTrailingWhitespace(_VimTest): snippets = ("test", """Hello \t ${1:default}\n$2""") wanted = """Hello \t \nGoodbye""" keys = "test" + EX + BS + JF + "Goodbye" # Tests for bug 616315 # class TrailingNewline_TabStop_NLInsideStuffBehind(_VimTest): snippets = ( "test", r""" x${1: }<-behind1 $2<-behind2""", ) keys = "test" + EX + "j" + JF + "k" wanted = """ xj<-behind1 k<-behind2""" class TrailingNewline_TabStop_JustNL(_VimTest): snippets = ( "test", r""" x${1: } $2""", ) keys = "test" + EX + "j" + JF + "k" wanted = """ xj k""" class TrailingNewline_TabStop_EndNL(_VimTest): snippets = ( "test", r""" x${1:a } $2""", ) keys = "test" + EX + "j" + JF + "k" wanted = """ xj k""" class TrailingNewline_TabStop_StartNL(_VimTest): snippets = ( "test", r""" x${1: a} $2""", ) keys = "test" + EX + "j" + JF + "k" wanted = """ xj k""" class TrailingNewline_TabStop_EndStartNL(_VimTest): snippets = ( "test", r""" x${1: a } $2""", ) keys = "test" + EX + "j" + JF + "k" wanted = """ xj k""" class TrailingNewline_TabStop_NotEndStartNL(_VimTest): snippets = ( "test", r""" x${1:a a} $2""", ) keys = "test" + EX + "j" + JF + "k" wanted = """ xj k""" class TrailingNewline_TabStop_ExtraNL_ECR(_VimTest): snippets = ( "test", r""" x${1:a a} $2 """, ) keys = "test" + EX + "j" + JF + "k" wanted = """ xj k """ class _MultiLineDefault(_VimTest): snippets = ( "test", r""" x${1:a b c d e f} $2""", ) class MultiLineDefault_Jump(_MultiLineDefault): keys = "test" + EX + JF + "y" wanted = """ xa b c d e f y""" class MultiLineDefault_Type(_MultiLineDefault): keys = "test" + EX + "z" + JF + "y" wanted = """ xz y""" class MultiLineDefault_BS(_MultiLineDefault): keys = "test" + EX + BS + JF + "y" wanted = """ x y""" class _UmlautsBase(_VimTest): # SendKeys can't send UTF characters skip_if = lambda self: running_on_windows() class Snippet_With_Umlauts_List(_UmlautsBase): snippets = _snip_quote("ü") keys = "te" + LS + "2\n" wanted = "Expand meü!" class Snippet_With_Umlauts(_UmlautsBase): snippets = _snip_quote("ü") keys = "teüst" + EX wanted = "Expand meü!" class Snippet_With_Umlauts_TypeOn(_UmlautsBase): snippets = ("ül", "üüüüüßßßß") keys = "te ül" + EX + "more text" wanted = "te üüüüüßßßßmore text" class Snippet_With_Umlauts_OverwriteFirst(_UmlautsBase): snippets = ("ül", "üü ${1:world} üü ${2:hello}ßß\nüüüü") keys = "te ül" + EX + "more text" + JF + JF + "end" wanted = "te üü more text üü helloßß\nüüüüend" class Snippet_With_Umlauts_OverwriteSecond(_UmlautsBase): snippets = ("ül", "üü ${1:world} üü ${2:hello}ßß\nüüüü") keys = "te ül" + EX + JF + "more text" + JF + "end" wanted = "te üü world üü more textßß\nüüüüend" class Snippet_With_Umlauts_OverwriteNone(_UmlautsBase): snippets = ("ül", "üü ${1:world} üü ${2:hello}ßß\nüüüü") keys = "te ül" + EX + JF + JF + "end" wanted = "te üü world üü helloßß\nüüüüend" class Snippet_With_Umlauts_Mirrors(_UmlautsBase): snippets = ("ül", "üü ${1:world} üü $1") keys = "te ül" + EX + "hello" wanted = "te üü hello üü hello" class Snippet_With_Umlauts_Python(_UmlautsBase): snippets = ("ül", 'üü ${1:world} üü `!p snip.rv = len(t[1])*"a"`') keys = "te ül" + EX + "hüüll" wanted = "te üü hüüll üü aaaaa" class UmlautsBeforeTriggerAndCharsAfter(_UmlautsBase): snippets = ("trig", "success") keys = "ööuu trig b" + 2 * ARR_L + EX wanted = "ööuu success b" class NoUmlautsBeforeTriggerAndCharsAfter(_UmlautsBase): snippets = ("trig", "success") keys = "oouu trig b" + 2 * ARR_L + EX wanted = "oouu success b"
5,420
Python
.py
204
22.122549
70
0.590503
SirVer/ultisnips
7,501
688
112
GPL-3.0
9/5/2024, 5:11:34 PM (Europe/Amsterdam)
12,225
test_UltiSnipFunc.py
SirVer_ultisnips/test/test_UltiSnipFunc.py
# encoding: utf-8 from test.vim_test_case import VimTestCase as _VimTest from test.constant import * from test.util import running_on_windows class _AddFuncBase(_VimTest): args = "" def _before_test(self): self.vim.send_to_vim(":call UltiSnips#AddSnippetWithPriority(%s)\n" % self.args) class AddFunc_Simple(_AddFuncBase): args = '"test", "simple expand", "desc", "", "all", 0' keys = "abc test" + EX wanted = "abc simple expand" class AddFunc_Opt(_AddFuncBase): args = '".*test", "simple expand", "desc", "r", "all", 0' keys = "abc test" + EX wanted = "simple expand" # Test for bug 501727 # class TestNonEmptyLangmap_ExpectCorrectResult(_VimTest): snippets = ( "testme", """my snipped ${1:some_default} and a mirror: $1 $2...$3 $0""", ) keys = "testme" + EX + "hi1" + JF + "hi2" + JF + "hi3" + JF + "hi4" wanted = """my snipped hi1 and a mirror: hi1 hi2...hi3 hi4""" def _extra_vim_config(self, vim_config): vim_config.append("set langmap=dj,rk,nl,ln,jd,kr,DJ,RK,NL,LN,JD,KR") # Test for https://bugs.launchpad.net/bugs/501727 # class TestNonEmptyLangmapWithSemi_ExpectCorrectResult(_VimTest): snippets = ( "testme", """my snipped ${1:some_default} and a mirror: $1 $2...$3 $0""", ) keys = "testme" + EX + "hi;" + JF + "hi2" + JF + "hi3" + JF + "hi4" + ESC + ";Hello" wanted = """my snipped hi; and a mirror: hi; hi2...hi3 hi4Hello""" def _before_test(self): self.vim.send_to_vim(":set langmap=\\\\;;A\n") # Test for bug 871357 # class TestLangmapWithUtf8_ExpectCorrectResult(_VimTest): # SendKeys can't send UTF characters skip_if = lambda self: running_on_windows() snippets = ( "testme", """my snipped ${1:some_default} and a mirror: $1 $2...$3 $0""", ) keys = "testme" + EX + "hi1" + JF + "hi2" + JF + "hi3" + JF + "hi4" wanted = """my snipped hi1 and a mirror: hi1 hi2...hi3 hi4""" def _before_test(self): self.vim.send_to_vim( ":set langmap=йq,цw,уe,кr,еt,нy,гu,шi,щo,зp,х[,ъ],фa,ыs,вd,аf,пg,рh,оj,лk,дl,ж\\;,э',яz,чx,сc,мv,иb,тn,ьm,ю.,ё',ЙQ,ЦW,УE,КR,ЕT,НY,ГU,ШI,ЩO,ЗP,Х\{,Ъ\},ФA,ЫS,ВD,АF,ПG,РH,ОJ,ЛK,ДL,Ж\:,Э\",ЯZ,ЧX,СC,МV,ИB,ТN,ЬM,Б\<,Ю\>\n" ) class VerifyVimDict1(_VimTest): """check: correct type (4 means vim dictionary) correct length of dictionary (in this case we have on element if the use same prefix, dictionary should have 1 element) correct description (including the apostrophe) if the prefix is mismatched no resulting dict should have 0 elements """ snippets = ("testâ", "abc123ά", "123'êabc") keys = ( "test=(type(UltiSnips#SnippetsInCurrentScope()) . len(UltiSnips#SnippetsInCurrentScope()) . " + 'UltiSnips#SnippetsInCurrentScope()["testâ"]' + ")\n" + "=len(UltiSnips#SnippetsInCurrentScope())\n" ) wanted = "test41123'êabc0" class VerifyVimDict2(_VimTest): """check: can use " in trigger """ snippets = ('te"stâ', "abc123ά", "123êabc") akey = "'te{}stâ'".format('"') keys = 'te"=(UltiSnips#SnippetsInCurrentScope()[{}]'.format(akey) + ")\n" wanted = 'te"123êabc' class VerifyVimDict3(_VimTest): """check: can use ' in trigger """ snippets = ("te'stâ", "abc123ά", "123êabc") akey = '"te{}stâ"'.format("'") keys = "te'=(UltiSnips#SnippetsInCurrentScope()[{}]".format(akey) + ")\n" wanted = "te'123êabc" class AddNewSnippetSource(_VimTest): keys = ( "blumba" + EX + ESC + ":py3 UltiSnips_Manager.register_snippet_source(" + "'temp', MySnippetSource())\n" + "oblumba" + EX + ESC + ":py3 UltiSnips_Manager.unregister_snippet_source('temp')\n" + "oblumba" + EX ) wanted = "blumba" + EX + "\n" + "this is a dynamic snippet" + "\n" + "blumba" + EX def _extra_vim_config(self, vim_config): self._create_file( "snippet_source.py", """ from UltiSnips.snippet.source import SnippetSource from UltiSnips.snippet.definition import UltiSnipsSnippetDefinition class MySnippetSource(SnippetSource): def get_snippets(self, filetypes, before, possible, autotrigger_only, visual_content): if before.endswith('blumba') and autotrigger_only == False: return [ UltiSnipsSnippetDefinition( -100, "blumba", "this is a dynamic snippet", "", "", {}, "blub", None, {}) ] return [] """, ) vim_config.append("py3file %s" % (self.name_temp("snippet_source.py")))
4,743
Python
.py
133
29.556391
228
0.611086
SirVer/ultisnips
7,501
688
112
GPL-3.0
9/5/2024, 5:11:34 PM (Europe/Amsterdam)
12,226
test_MultipleMatches.py
SirVer_ultisnips/test/test_MultipleMatches.py
from test.vim_test_case import VimTestCase as _VimTest from test.constant import * class _MultipleMatches(_VimTest): snippets = ( ("test", "Case1", "This is Case 1"), ("test", "Case2", "This is Case 2"), ) class Multiple_SimpleCaseSelectFirst_ECR(_MultipleMatches): keys = "test" + EX + "1\n" wanted = "Case1" class Multiple_SimpleCaseSelectSecond_ECR(_MultipleMatches): keys = "test" + EX + "2\n" wanted = "Case2" class Multiple_SimpleCaseSelectTooHigh_ESelectLast(_MultipleMatches): keys = "test" + EX + "5\n" wanted = "Case2" class Multiple_SimpleCaseSelectZero_EEscape(_MultipleMatches): keys = "test" + EX + "0\n" + "hi" wanted = "testhi" class Multiple_SimpleCaseEscapeOut_ECR(_MultipleMatches): keys = "test" + EX + ESC + "hi" wanted = "testhi" class Multiple_ManySnippetsOneTrigger_ECR(_VimTest): snippets = ( ("test", "Case1", "This is Case 1"), ("test", "Case2", "This is Case 2"), ("test", "Case3", "This is Case 3"), ("test", "Case4", "This is Case 4"), ("test", "Case5", "This is Case 5"), ("test", "Case6", "This is Case 6"), ("test", "Case7", "This is Case 7"), ("test", "Case8", "This is Case 8"), ("test", "Case9", "This is Case 9"), ("test", "Case10", "This is Case 10"), ("test", "Case11", "This is Case 11"), ("test", "Case12", "This is Case 12"), ("test", "Case13", "This is Case 13"), ("test", "Case14", "This is Case 14"), ("test", "Case15", "This is Case 15"), ("test", "Case16", "This is Case 16"), ("test", "Case17", "This is Case 17"), ("test", "Case18", "This is Case 18"), ("test", "Case19", "This is Case 19"), ("test", "Case20", "This is Case 20"), ("test", "Case21", "This is Case 21"), ("test", "Case22", "This is Case 22"), ("test", "Case23", "This is Case 23"), ("test", "Case24", "This is Case 24"), ("test", "Case25", "This is Case 25"), ("test", "Case26", "This is Case 26"), ("test", "Case27", "This is Case 27"), ("test", "Case28", "This is Case 28"), ("test", "Case29", "This is Case 29"), ) keys = "test" + EX + " " + ESC + ESC + "ahi" wanted = "testhi"
2,322
Python
.py
56
34.642857
69
0.550622
SirVer/ultisnips
7,501
688
112
GPL-3.0
9/5/2024, 5:11:34 PM (Europe/Amsterdam)
12,227
test_AnonymousExpansion.py
SirVer_ultisnips/test/test_AnonymousExpansion.py
from test.vim_test_case import VimTestCase as _VimTest from test.constant import * class _AnonBase(_VimTest): args = "" def _extra_vim_config(self, vim_config): vim_config.append( "inoremap <silent> %s <C-R>=UltiSnips#Anon(%s)<cr>" % (EA, self.args) ) class Anon_NoTrigger_Simple(_AnonBase): args = '"simple expand"' keys = "abc" + EA wanted = "abcsimple expand" class Anon_NoTrigger_AfterSpace(_AnonBase): args = '"simple expand"' keys = "abc " + EA wanted = "abc simple expand" class Anon_NoTrigger_BeginningOfLine(_AnonBase): args = r"':latex:\`$1\`$0'" keys = EA + "Hello" + JF + "World" wanted = ":latex:`Hello`World" class Anon_NoTrigger_FirstCharOfLine(_AnonBase): args = r"':latex:\`$1\`$0'" keys = " " + EA + "Hello" + JF + "World" wanted = " :latex:`Hello`World" class Anon_NoTrigger_Multi(_AnonBase): args = '"simple $1 expand $1 $0"' keys = "abc" + EA + "123" + JF + "456" wanted = "abcsimple 123 expand 123 456" class Anon_Trigger_Multi(_AnonBase): args = '"simple $1 expand $1 $0", "abc"' keys = "123 abc" + EA + "123" + JF + "456" wanted = "123 simple 123 expand 123 456" class Anon_Trigger_Simple(_AnonBase): args = '"simple expand", "abc"' keys = "abc" + EA wanted = "simple expand" class Anon_Trigger_Twice(_AnonBase): args = '"simple expand", "abc"' keys = "abc" + EA + "\nabc" + EX wanted = "simple expand\nabc" + EX class Anon_Trigger_Opts(_AnonBase): args = '"simple expand", ".*abc", "desc", "r"' keys = "blah blah abc" + EA wanted = "simple expand"
1,638
Python
.py
44
32.477273
81
0.617292
SirVer/ultisnips
7,501
688
112
GPL-3.0
9/5/2024, 5:11:34 PM (Europe/Amsterdam)
12,228
test_Autotrigger.py
SirVer_ultisnips/test/test_Autotrigger.py
from test.vim_test_case import VimTestCase as _VimTest from test.constant import * class Autotrigger_CanMatchSimpleTrigger(_VimTest): files = { "us/all.snippets": r""" snippet a "desc" A autotriggered endsnippet """ } keys = "a" wanted = "autotriggered" class Autotrigger_CanMatchContext(_VimTest): files = { "us/all.snippets": r""" snippet a "desc" "snip.line == 2" Ae autotriggered endsnippet """ } keys = "a\na" wanted = "autotriggered\na" class Autotrigger_CanExpandOnTriggerWithLengthMoreThanOne(_VimTest): files = { "us/all.snippets": r""" snippet abc "desc" A autotriggered endsnippet """ } keys = "abc" wanted = "autotriggered" class Autotrigger_CanMatchPreviouslySelectedPlaceholder(_VimTest): files = { "us/all.snippets": r""" snippet if "desc" if ${1:var}: pass endsnippet snippet = "desc" "snip.last_placeholder" Ae `!p snip.rv = snip.context.current_text` == nil endsnippet """ } keys = "if" + EX + "=" + ESC + "o=" wanted = "if var == nil: pass\n=" class Autotrigger_GlobalDisable(_VimTest): def _extra_vim_config(self, vim_config): vim_config.append("let g:UltiSnipsAutoTrigger=0") files = { "us/all.snippets": r""" snippet a "desc" A autotriggered endsnippet """ } keys = "a" wanted = "a" class Autotrigger_CanToggle(_VimTest): files = { "us/all.snippets": r""" snippet a "desc" A autotriggered endsnippet """ } keys = ( "a" + ESC + ":call UltiSnips#ToggleAutoTrigger()\n" + "o" + "a" + ESC + ":call UltiSnips#ToggleAutoTrigger()\n" + "o" + "a" ) wanted = "autotriggered\na\nautotriggered" class Autotrigger_GlobalDisableThenToggle(_VimTest): def _extra_vim_config(self, vim_config): vim_config.append("let g:UltiSnipsAutoTrigger=0") files = { "us/all.snippets": r""" snippet a "desc" A autotriggered endsnippet """ } keys = ( "a" + ESC + ":call UltiSnips#ToggleAutoTrigger()\n" + "o" + "a" ) wanted = "a\nautotriggered"
2,361
Python
.py
89
19.640449
68
0.569912
SirVer/ultisnips
7,501
688
112
GPL-3.0
9/5/2024, 5:11:34 PM (Europe/Amsterdam)
12,229
test_SnipMate.py
SirVer_ultisnips/test/test_SnipMate.py
# encoding: utf-8 from test.vim_test_case import VimTestCase as _VimTest from test.constant import * class snipMate_SimpleSnippet(_VimTest): files = { "snippets/_.snippets": """ snippet hello \tThis is a test snippet \t# With a comment""" } keys = "hello" + EX wanted = "This is a test snippet\n# With a comment" class snipMate_Disabled(_VimTest): files = { "snippets/_.snippets": """ snippet hello \tThis is a test snippet \t# With a comment""" } keys = "hello" + EX wanted = "hello" + EX def _extra_vim_config(self, vim_config): vim_config.append("let g:UltiSnipsEnableSnipMate=0") class snipMate_OtherFiletype(_VimTest): files = { "snippets/blubi.snippets": """ snippet hello \tworked""" } keys = "hello" + EX + ESC + ":set ft=blubi\nohello" + EX wanted = "hello" + EX + "\nworked" class snipMate_MultiMatches(_VimTest): files = { "snippets/_.snippets": """ snippet hello The first snippet." \tone snippet hello The second snippet. \ttwo""" } keys = "hello" + EX + "2\n" wanted = "two" class snipMate_SimpleSnippetSubDirectory(_VimTest): files = { "snippets/_/blub.snippets": """ snippet hello \tThis is a test snippet""" } keys = "hello" + EX wanted = "This is a test snippet" class snipMate_SimpleSnippetInSnippetFile(_VimTest): files = { "snippets/_/hello.snippet": """This is a stand alone snippet""", "snippets/_/hello1.snippet": """This is two stand alone snippet""", "snippets/_/hello2/this_is_my_cool_snippet.snippet": """Three""", } keys = "hello" + EX + "\nhello1" + EX + "\nhello2" + EX wanted = "This is a stand alone snippet\nThis is two stand alone snippet\nThree" class snipMate_Interpolation(_VimTest): files = { "snippets/_.snippets": """ snippet test \tla`printf('c%02d', 3)`lu""" } keys = "test" + EX wanted = "lac03lu" class snipMate_InterpolationWithSystem(_VimTest): files = { "snippets/_.snippets": """ snippet test \tla`system('echo -ne öäü')`lu""" } keys = "test" + EX wanted = "laöäülu" class snipMate_TestMirrors(_VimTest): files = { "snippets/_.snippets": """ snippet for \tfor (${2:i}; $2 < ${1:count}; $1++) { \t\t${4} \t}""" } keys = "for" + EX + "blub" + JF + "j" + JF + "hi" wanted = "for (j; j < blub; blub++) {\n\thi\n}" class snipMate_TestNoBraceTabstops(_VimTest): files = { "snippets/_.snippets": """ snippet test \t$1 is $2""" } keys = "test" + EX + "blub" + JF + "blah" wanted = "blub is blah" class snipMate_TestNoBraceTabstopsAndMirrors(_VimTest): files = { "snippets/_.snippets": """ snippet test \t$1 is $1, $2 is ${2}""" } keys = "test" + EX + "blub" + JF + "blah" wanted = "blub is blub, blah is blah" class snipMate_TestMirrorsInPlaceholders(_VimTest): files = { "snippets/_.snippets": """ snippet opt \t<option value="${1:option}">${2:$1}</option>""" } keys = "opt" + EX + "some" + JF + JF + "ende" wanted = """<option value="some">some</option>ende""" class snipMate_TestMirrorsInPlaceholders_Overwrite(_VimTest): files = { "snippets/_.snippets": """ snippet opt \t<option value="${1:option}">${2:$1}</option>""" } keys = "opt" + EX + "some" + JF + "not" + JF + "ende" wanted = """<option value="some">not</option>ende""" class snipMate_Visual_Simple(_VimTest): files = { "snippets/_.snippets": """ snippet v \th${VISUAL}b""" } keys = "blablub" + ESC + "0v6l" + EX + "v" + EX wanted = "hblablubb" class snipMate_NoNestedTabstops(_VimTest): files = { "snippets/_.snippets": """ snippet test \th$${1:${2:blub}}$$""" } keys = "test" + EX + JF + "hi" wanted = "h$${2:blub}$$hi" class snipMate_Extends(_VimTest): files = { "snippets/a.snippets": """ extends b snippet test \tblub""", "snippets/b.snippets": """ snippet test1 \tblah""", } keys = ESC + ":set ft=a\n" + "itest1" + EX wanted = "blah" class snipMate_EmptyLinesContinueSnippets(_VimTest): files = { "snippets/_.snippets": """ snippet test \tblub \tblah snippet test1 \ta""" } keys = "test" + EX wanted = "blub\n\nblah\n" class snipMate_OverwrittenByRegExpTrigger(_VimTest): files = { "snippets/_.snippets": """ snippet def \tsnipmate """, "us/all.snippets": r""" snippet "(de)?f" "blub" r ultisnips endsnippet """, } keys = "def" + EX wanted = "ultisnips" class snipMate_Issue658(_VimTest): files = { "snippets/_.snippets": """ snippet /* \t/* \t * ${0} \t */ """ } keys = ESC + ":set fo=r\n" + "i/*" + EX + "1\n2" wanted = """/* * 1 * 2 */ """ class snipMate_Issue1325(_VimTest): # https://github.com/SirVer/ultisnips/issues/1325 files = { "snippets/_.snippets": """ snippet frac \\frac{}{} \t\\\\frac{${1:num}}{${2:denom}} ${0} """.rstrip() } keys = "$frac" + EX + JF + JF + "blub" wanted = r"$\frac{num}{denom} blub" class snipMate_Issue1344(_VimTest): # https://github.com/SirVer/ultisnips/issues/144 files = { "snippets/_.snippets": """ snippet . \tself. """.rstrip() } keys = "os." + EX + "foo\n." + EX wanted = "os.\tfoo\nself."
5,354
Python
.py
203
22.369458
84
0.598431
SirVer/ultisnips
7,501
688
112
GPL-3.0
9/5/2024, 5:11:34 PM (Europe/Amsterdam)
12,230
compatibility.py
SirVer_ultisnips/pythonx/UltiSnips/compatibility.py
#!/usr/bin/env python3 # encoding: utf-8 """This file contains compatibility code to stay compatible with as many python versions as possible.""" import vim def _vim_dec(string): """Decode 'string' using &encoding.""" # We don't have the luxury here of failing, everything # falls apart if we don't return a bytearray from the # passed in string return string.decode(vim.eval("&encoding"), "replace") def _vim_enc(bytearray): """Encode 'string' using &encoding.""" # We don't have the luxury here of failing, everything # falls apart if we don't return a string from the passed # in bytearray return bytearray.encode(vim.eval("&encoding"), "replace") def col2byte(line, col): """Convert a valid column index into a byte index inside of vims buffer.""" # We pad the line so that selecting the +1 st column still works. pre_chars = (vim.current.buffer[line - 1] + " ")[:col] return len(_vim_enc(pre_chars)) def byte2col(line, nbyte): """Convert a column into a byteidx suitable for a mark or cursor position inside of vim.""" line = vim.current.buffer[line - 1] raw_bytes = _vim_enc(line)[:nbyte] return len(_vim_dec(raw_bytes))
1,218
Python
.py
29
37.896552
79
0.693808
SirVer/ultisnips
7,501
688
112
GPL-3.0
9/5/2024, 5:11:34 PM (Europe/Amsterdam)
12,231
error.py
SirVer_ultisnips/pythonx/UltiSnips/error.py
#!/usr/bin/env python # encoding: utf-8 class PebkacError(RuntimeError): """An error that was caused by a misconfiguration or error in a snippet, i.e. caused by the user. Hence: "Problem exists between keyboard and chair". """ pass
255
Python
.py
8
28
76
0.709016
SirVer/ultisnips
7,501
688
112
GPL-3.0
9/5/2024, 5:11:34 PM (Europe/Amsterdam)
12,232
snippet_manager.py
SirVer_ultisnips/pythonx/UltiSnips/snippet_manager.py
#!/usr/bin/env python3 # encoding: utf-8 """Contains the SnippetManager facade used by all Vim Functions.""" from collections import defaultdict from contextlib import contextmanager import os from typing import Set from pathlib import Path import vim from UltiSnips import vim_helper from UltiSnips import err_to_scratch_buffer from UltiSnips.diff import diff, guess_edit from UltiSnips.position import Position, JumpDirection from UltiSnips.snippet.definition import UltiSnipsSnippetDefinition from UltiSnips.snippet.source import ( AddedSnippetsSource, SnipMateFileSource, UltiSnipsFileSource, find_all_snippet_directories, find_all_snippet_files, find_snippet_files, ) from UltiSnips.snippet.source.file.common import ( normalize_file_path, ) from UltiSnips.text import escape from UltiSnips.vim_state import VimState, VisualContentPreserver from UltiSnips.buffer_proxy import use_proxy_buffer, suspend_proxy_edits def _ask_user(a, formatted): """Asks the user using inputlist() and returns the selected element or None.""" try: rv = vim_helper.eval("inputlist(%s)" % vim_helper.escape(formatted)) if rv is None or rv == "0": return None rv = int(rv) if rv > len(a): rv = len(a) return a[rv - 1] except vim_helper.error: # Likely "invalid expression", but might be translated. We have no way # of knowing the exact error, therefore, we ignore all errors silently. return None except KeyboardInterrupt: return None def _show_user_warning(msg): """Shows a Vim warning message to the user.""" vim_helper.command("echohl WarningMsg") vim_helper.command('echom "%s"' % msg.replace('"', '\\"')) vim_helper.command("echohl None") def _ask_snippets(snippets): """Given a list of snippets, ask the user which one they want to use, and return it.""" display = [ "%i: %s (%s)" % (i + 1, escape(s.description, "\\"), escape(s.location, "\\")) for i, s in enumerate(snippets) ] return _ask_user(snippets, display) def _select_and_create_file_to_edit(potentials: Set[str]) -> str: assert len(potentials) >= 1 file_to_edit = "" if len(potentials) > 1: files = sorted(potentials) exists = [os.path.exists(f) for f in files] formatted = [ "%s %i: %s" % ("*" if exists else " ", i, escape(fn, "\\")) for i, (fn, exists) in enumerate(zip(files, exists), 1) ] file_to_edit = _ask_user(files, formatted) if file_to_edit is None: return "" else: file_to_edit = potentials.pop() dirname = os.path.dirname(file_to_edit) if not os.path.exists(dirname): os.makedirs(dirname) return file_to_edit def _get_potential_snippet_filenames_to_edit( snippet_dir: str, filetypes: str ) -> Set[str]: potentials = set() for ft in filetypes: ft_snippets_files = find_snippet_files(ft, snippet_dir) potentials.update(ft_snippets_files) if not ft_snippets_files: # If there is no snippet file yet, we just default to `ft.snippets`. fpath = os.path.join(snippet_dir, ft + ".snippets") fpath = normalize_file_path(fpath) potentials.add(fpath) return potentials # TODO(sirver): This class is still too long. It should only contain public # facing methods, most of the private methods should be moved outside of it. class SnippetManager: """The main entry point for all UltiSnips functionality. All Vim functions call methods in this class. """ def __init__(self, expand_trigger, forward_trigger, backward_trigger): self.expand_trigger = expand_trigger self.forward_trigger = forward_trigger self.backward_trigger = backward_trigger self._inner_state_up = False self._supertab_keys = None self._active_snippets = [] self._added_buffer_filetypes = defaultdict(lambda: []) self._vstate = VimState() self._visual_content = VisualContentPreserver() self._snippet_sources = [] self._filetypes = [] self._snip_expanded_in_action = False self._inside_action = False self._last_change = ("", Position(-1, -1)) self._added_snippets_source = AddedSnippetsSource() self.register_snippet_source("ultisnips_files", UltiSnipsFileSource()) self.register_snippet_source("added", self._added_snippets_source) enable_snipmate = "1" if vim_helper.eval("exists('g:UltiSnipsEnableSnipMate')") == "1": enable_snipmate = vim_helper.eval("g:UltiSnipsEnableSnipMate") if enable_snipmate == "1": self.register_snippet_source("snipmate_files", SnipMateFileSource()) self._autotrigger = True if vim_helper.eval("exists('g:UltiSnipsAutoTrigger')") == "1": self._autotrigger = vim_helper.eval("g:UltiSnipsAutoTrigger") == "1" self._should_update_textobjects = False self._should_reset_visual = False self._reinit() @err_to_scratch_buffer.wrap def jump_forwards(self): """Jumps to the next tabstop.""" vim_helper.command("let g:ulti_jump_forwards_res = 1") vim_helper.command("let &g:undolevels = &g:undolevels") if not self._jump(JumpDirection.FORWARD): vim_helper.command("let g:ulti_jump_forwards_res = 0") return self._handle_failure(self.forward_trigger) return None @err_to_scratch_buffer.wrap def jump_backwards(self): """Jumps to the previous tabstop.""" vim_helper.command("let g:ulti_jump_backwards_res = 1") vim_helper.command("let &g:undolevels = &g:undolevels") if not self._jump(JumpDirection.BACKWARD): vim_helper.command("let g:ulti_jump_backwards_res = 0") return self._handle_failure(self.backward_trigger) return None @err_to_scratch_buffer.wrap def expand(self): """Try to expand a snippet at the current position.""" vim_helper.command("let g:ulti_expand_res = 1") if not self._try_expand(): vim_helper.command("let g:ulti_expand_res = 0") self._handle_failure(self.expand_trigger, True) @err_to_scratch_buffer.wrap def expand_or_jump(self): """This function is used for people who want to have the same trigger for expansion and forward jumping. It first tries to expand a snippet, if this fails, it tries to jump forward. """ vim_helper.command("let g:ulti_expand_or_jump_res = 1") rv = self._try_expand() if not rv: vim_helper.command("let g:ulti_expand_or_jump_res = 2") rv = self._jump(JumpDirection.FORWARD) if not rv: vim_helper.command("let g:ulti_expand_or_jump_res = 0") self._handle_failure(self.expand_trigger, True) @err_to_scratch_buffer.wrap def jump_or_expand(self): """This function is used for people who want to have the same trigger for expansion and forward jumping. It first tries to jump forward, if this fails, it tries to expand a snippet. """ vim_helper.command("let g:ulti_expand_or_jump_res = 2") rv = self._jump(JumpDirection.FORWARD) if not rv: vim_helper.command("let g:ulti_expand_or_jump_res = 1") rv = self._try_expand() if not rv: vim_helper.command("let g:ulti_expand_or_jump_res = 0") self._handle_failure(self.expand_trigger, True) @err_to_scratch_buffer.wrap def snippets_in_current_scope(self, search_all): """Returns the snippets that could be expanded to Vim as a global variable.""" before = "" if search_all else vim_helper.buf.line_till_cursor snippets = self._snips(before, True) # Sort snippets alphabetically snippets.sort(key=lambda x: x.trigger) for snip in snippets: description = snip.description[ snip.description.find(snip.trigger) + len(snip.trigger) + 2 : ] location = snip.location if snip.location else "" key = snip.trigger # remove surrounding "" or '' in snippet description if it exists if len(description) > 2: if description[0] == description[-1] and description[0] in "'\"": description = description[1:-1] vim_helper.command( "let g:current_ulti_dict['{key}'] = '{val}'".format( key=key.replace("'", "''"), val=description.replace("'", "''") ) ) if search_all: vim_helper.command( ( "let g:current_ulti_dict_info['{key}'] = {{" "'description': '{description}'," "'location': '{location}'," "}}" ).format( key=key.replace("'", "''"), location=location.replace("'", "''"), description=description.replace("'", "''"), ) ) @err_to_scratch_buffer.wrap def list_snippets(self): """Shows the snippets that could be expanded to the User and let her select one.""" before = vim_helper.buf.line_till_cursor snippets = self._snips(before, True) if len(snippets) == 0: self._handle_failure(vim.eval("g:UltiSnipsListSnippets")) return True # Sort snippets alphabetically snippets.sort(key=lambda x: x.trigger) if not snippets: return True snippet = _ask_snippets(snippets) if not snippet: return True self._do_snippet(snippet, before) return True @err_to_scratch_buffer.wrap def add_snippet( self, trigger, value, description, options, ft="all", priority=0, context=None, actions=None, ): """Add a snippet to the list of known snippets of the given 'ft'.""" self._added_snippets_source.add_snippet( ft, UltiSnipsSnippetDefinition( priority, trigger, value, description, options, {}, "added", context, actions, ), ) @err_to_scratch_buffer.wrap def expand_anon( self, value, trigger="", description="", options="", context=None, actions=None ): """Expand an anonymous snippet right here.""" before = vim_helper.buf.line_till_cursor snip = UltiSnipsSnippetDefinition( 0, trigger, value, description, options, {}, "", context, actions ) if not trigger or snip.matches(before, self._visual_content): self._do_snippet(snip, before) return True return False def register_snippet_source(self, name, snippet_source): """Registers a new 'snippet_source' with the given 'name'. The given class must be an instance of SnippetSource. This source will be queried for snippets. """ self._snippet_sources.append((name, snippet_source)) def unregister_snippet_source(self, name): """Unregister the source with the given 'name'. Does nothing if it is not registered. """ for index, (source_name, _) in enumerate(self._snippet_sources): if name == source_name: self._snippet_sources = ( self._snippet_sources[:index] + self._snippet_sources[index + 1 :] ) break def get_buffer_filetypes(self): return ( self._added_buffer_filetypes[vim_helper.buf.number] + vim_helper.buf.filetypes + ["all"] ) def add_buffer_filetypes(self, filetypes: str): """'filetypes' is a dotted filetype list, for example 'cuda.cpp'""" buf_fts = self._added_buffer_filetypes[vim_helper.buf.number] idx = -1 for ft in filetypes.split("."): ft = ft.strip() if not ft: continue try: idx = buf_fts.index(ft) except ValueError: self._added_buffer_filetypes[vim_helper.buf.number].insert(idx + 1, ft) idx += 1 @err_to_scratch_buffer.wrap def _cursor_moved(self): """Called whenever the cursor moved.""" self._should_update_textobjects = False self._vstate.remember_position() if vim_helper.eval("mode()") not in "in": return if self._ignore_movements: self._ignore_movements = False return if self._active_snippets: cstart = self._active_snippets[0].start.line cend = ( self._active_snippets[0].end.line + self._vstate.diff_in_buffer_length ) ct = vim_helper.buf[cstart : cend + 1] lt = self._vstate.remembered_buffer pos = vim_helper.buf.cursor lt_span = [0, len(lt)] ct_span = [0, len(ct)] initial_line = cstart # Cut down on lines searched for changes. Start from behind and # remove all equal lines. Then do the same from the front. if lt and ct: while ( lt[lt_span[1] - 1] == ct[ct_span[1] - 1] and self._vstate.ppos.line < initial_line + lt_span[1] - 1 and pos.line < initial_line + ct_span[1] - 1 and (lt_span[0] < lt_span[1]) and (ct_span[0] < ct_span[1]) ): ct_span[1] -= 1 lt_span[1] -= 1 while ( lt_span[0] < lt_span[1] and ct_span[0] < ct_span[1] and lt[lt_span[0]] == ct[ct_span[0]] and self._vstate.ppos.line >= initial_line and pos.line >= initial_line ): ct_span[0] += 1 lt_span[0] += 1 initial_line += 1 ct_span[0] = max(0, ct_span[0] - 1) lt_span[0] = max(0, lt_span[0] - 1) initial_line = max(cstart, initial_line - 1) lt = lt[lt_span[0] : lt_span[1]] ct = ct[ct_span[0] : ct_span[1]] try: rv, es = guess_edit(initial_line, lt, ct, self._vstate) if not rv: lt = "\n".join(lt) ct = "\n".join(ct) es = diff(lt, ct, initial_line) self._active_snippets[0].replay_user_edits(es, self._ctab) except IndexError: # Rather do nothing than throwing an error. It will be correct # most of the time pass self._check_if_still_inside_snippet() if self._active_snippets: self._active_snippets[0].update_textobjects(vim_helper.buf) self._vstate.remember_buffer(self._active_snippets[0]) def _setup_inner_state(self): """Map keys and create autocommands that should only be defined when a snippet is active.""" if self._inner_state_up: return if self.expand_trigger != self.forward_trigger: vim_helper.command( "inoremap <buffer><nowait><silent> " + self.forward_trigger + " <C-R>=UltiSnips#JumpForwards()<cr>" ) vim_helper.command( "snoremap <buffer><nowait><silent> " + self.forward_trigger + " <Esc>:call UltiSnips#JumpForwards()<cr>" ) vim_helper.command( "inoremap <buffer><nowait><silent> " + self.backward_trigger + " <C-R>=UltiSnips#JumpBackwards()<cr>" ) vim_helper.command( "snoremap <buffer><nowait><silent> " + self.backward_trigger + " <Esc>:call UltiSnips#JumpBackwards()<cr>" ) # Setup the autogroups. vim_helper.command("augroup UltiSnips") vim_helper.command("autocmd!") vim_helper.command("autocmd CursorMovedI * call UltiSnips#CursorMoved()") vim_helper.command("autocmd CursorMoved * call UltiSnips#CursorMoved()") vim_helper.command("autocmd InsertLeave * call UltiSnips#LeavingInsertMode()") vim_helper.command("autocmd BufEnter * call UltiSnips#LeavingBuffer()") vim_helper.command("autocmd CmdwinEnter * call UltiSnips#LeavingBuffer()") vim_helper.command("autocmd CmdwinLeave * call UltiSnips#LeavingBuffer()") # Also exit the snippet when we enter a unite complete buffer. vim_helper.command("autocmd Filetype unite call UltiSnips#LeavingBuffer()") vim_helper.command("augroup END") vim_helper.command( "silent doautocmd <nomodeline> User UltiSnipsEnterFirstSnippet" ) self._inner_state_up = True def _teardown_inner_state(self): """Reverse _setup_inner_state.""" if not self._inner_state_up: return try: vim_helper.command( "silent doautocmd <nomodeline> User UltiSnipsExitLastSnippet" ) if self.expand_trigger != self.forward_trigger: vim_helper.command("iunmap <buffer> %s" % self.forward_trigger) vim_helper.command("sunmap <buffer> %s" % self.forward_trigger) vim_helper.command("iunmap <buffer> %s" % self.backward_trigger) vim_helper.command("sunmap <buffer> %s" % self.backward_trigger) vim_helper.command("augroup UltiSnips") vim_helper.command("autocmd!") vim_helper.command("augroup END") except vim_helper.error: # This happens when a preview window was opened. This issues # CursorMoved, but not BufLeave. We have no way to unmap, until we # are back in our buffer pass finally: self._inner_state_up = False @err_to_scratch_buffer.wrap def _save_last_visual_selection(self): """This is called when the expand trigger is pressed in visual mode. Our job is to remember everything between '< and '> and pass it on to. ${VISUAL} in case it will be needed. """ self._visual_content.conserve() def _leaving_buffer(self): """Called when the user switches tabs/windows/buffers. It basically means that all snippets must be properly terminated. """ while self._active_snippets: self._current_snippet_is_done() self._reinit() def _reinit(self): """Resets transient state.""" self._ctab = None self._ignore_movements = False def _check_if_still_inside_snippet(self): """Checks if the cursor is outside of the current snippet.""" if self._current_snippet and ( not self._current_snippet.start <= vim_helper.buf.cursor <= self._current_snippet.end ): self._current_snippet_is_done() self._reinit() self._check_if_still_inside_snippet() def _current_snippet_is_done(self): """The current snippet should be terminated.""" self._active_snippets.pop() if not self._active_snippets: self._teardown_inner_state() def _jump(self, jump_direction: JumpDirection): """Helper method that does the actual jump.""" if self._should_update_textobjects: self._should_reset_visual = False self._cursor_moved() # we need to set 'onemore' there, because of limitations of the vim # API regarding cursor movements; without that test # 'CanExpandAnonSnippetInJumpActionWhileSelected' will fail with vim_helper.option_set_to("ve", "onemore"): jumped = False # We need to remember current snippets stack here because of # post-jump action on the last tabstop should be able to access # snippet instance which is ended just now. stack_for_post_jump = self._active_snippets[:] # If next tab has length 1 and the distance between itself and # self._ctab is 1 then there is 1 less CursorMove events. We # cannot ignore next movement in such case. ntab_short_and_near = False if self._current_snippet: snippet_for_action = self._current_snippet elif stack_for_post_jump: snippet_for_action = stack_for_post_jump[-1] else: snippet_for_action = None if self._current_snippet: ntab = self._current_snippet.select_next_tab(jump_direction) if ntab: if self._current_snippet.snippet.has_option("s"): lineno = vim_helper.buf.cursor.line vim_helper.buf[lineno] = vim_helper.buf[lineno].rstrip() vim_helper.select(ntab.start, ntab.end) jumped = True if ( self._ctab is not None and ntab.start - self._ctab.end == Position(0, 1) and ntab.end - ntab.start == Position(0, 1) ): ntab_short_and_near = True self._ctab = ntab # Run interpolations again to update new placeholder # values, binded to currently newly jumped placeholder. self._visual_content.conserve_placeholder(self._ctab) self._current_snippet.current_placeholder = ( self._visual_content.placeholder ) self._should_reset_visual = False self._active_snippets[0].update_textobjects(vim_helper.buf) # Open any folds this might have created vim_helper.command("normal! zv") self._vstate.remember_buffer(self._active_snippets[0]) if ntab.number == 0 and self._active_snippets: self._current_snippet_is_done() else: # This really shouldn't happen, because a snippet should # have been popped when its final tabstop was used. # Cleanup by removing current snippet and recursing. self._current_snippet_is_done() jumped = self._jump(jump_direction) if jumped: if self._ctab: self._vstate.remember_position() self._vstate.remember_unnamed_register(self._ctab.current_text) if not ntab_short_and_near: self._ignore_movements = True if len(stack_for_post_jump) > 0 and ntab is not None: with use_proxy_buffer(stack_for_post_jump, self._vstate): snippet_for_action.snippet.do_post_jump( ntab.number, -1 if jump_direction == JumpDirection.BACKWARD else 1, stack_for_post_jump, snippet_for_action, ) return jumped def _leaving_insert_mode(self): """Called whenever we leave the insert mode.""" self._vstate.restore_unnamed_register() def _handle_failure(self, trigger, pass_through=False): """Mainly make sure that we play well with SuperTab.""" if trigger.lower() == "<tab>": feedkey = "\\" + trigger elif trigger.lower() == "<s-tab>": feedkey = "\\" + trigger elif pass_through: # pass through the trigger key if it did nothing feedkey = "\\" + trigger else: feedkey = None mode = "n" if not self._supertab_keys: if vim_helper.eval("exists('g:SuperTabMappingForward')") != "0": self._supertab_keys = ( vim_helper.eval("g:SuperTabMappingForward"), vim_helper.eval("g:SuperTabMappingBackward"), ) else: self._supertab_keys = ["", ""] for idx, sttrig in enumerate(self._supertab_keys): if trigger.lower() == sttrig.lower(): if idx == 0: feedkey = r"\<Plug>SuperTabForward" mode = "n" elif idx == 1: feedkey = r"\<Plug>SuperTabBackward" mode = "p" # Use remap mode so SuperTab mappings will be invoked. break if feedkey in (r"\<Plug>SuperTabForward", r"\<Plug>SuperTabBackward"): vim_helper.command("return SuperTab(%s)" % vim_helper.escape(mode)) elif feedkey: vim_helper.command("return %s" % vim_helper.escape(feedkey)) def _snips(self, before, partial, autotrigger_only=False): """Returns all the snippets for the given text before the cursor. If partial is True, then get also return partial matches. """ filetypes = self.get_buffer_filetypes()[::-1] matching_snippets = defaultdict(list) clear_priority = None cleared = {} for _, source in self._snippet_sources: source.ensure(filetypes) # Collect cleared information from sources. for _, source in self._snippet_sources: sclear_priority = source.get_clear_priority(filetypes) if sclear_priority is not None and ( clear_priority is None or sclear_priority > clear_priority ): clear_priority = sclear_priority for key, value in source.get_cleared(filetypes).items(): if key not in cleared or value > cleared[key]: cleared[key] = value for _, source in self._snippet_sources: possible_snippets = source.get_snippets( filetypes, before, partial, autotrigger_only, self._visual_content ) for snippet in possible_snippets: if (clear_priority is None or snippet.priority > clear_priority) and ( snippet.trigger not in cleared or snippet.priority > cleared[snippet.trigger] ): matching_snippets[snippet.trigger].append(snippet) if not matching_snippets: return [] # Now filter duplicates and only keep the one with the highest # priority. snippets = [] for snippets_with_trigger in matching_snippets.values(): highest_priority = max(s.priority for s in snippets_with_trigger) snippets.extend( s for s in snippets_with_trigger if s.priority == highest_priority ) # For partial matches we are done, but if we want to expand a snippet, # we have to go over them again and only keep those with the maximum # priority. if partial: return snippets highest_priority = max(s.priority for s in snippets) return [s for s in snippets if s.priority == highest_priority] def _do_snippet(self, snippet, before): """Expands the given snippet, and handles everything that needs to be done with it.""" self._setup_inner_state() self._snip_expanded_in_action = False self._should_update_textobjects = False # Adjust before, maybe the trigger is not the complete word text_before = before if snippet.matched: text_before = before[: -len(snippet.matched)] with use_proxy_buffer(self._active_snippets, self._vstate): with self._action_context(): cursor_set_in_action = snippet.do_pre_expand( self._visual_content.text, self._active_snippets ) if cursor_set_in_action: text_before = vim_helper.buf.line_till_cursor before = vim_helper.buf.line_till_cursor with suspend_proxy_edits(): start = Position(vim_helper.buf.cursor.line, len(text_before)) end = Position(vim_helper.buf.cursor.line, len(before)) parent = None if self._current_snippet: # If cursor is set in pre-action, then action was modified # cursor line, in that case we do not need to do any edits, it # can break snippet if not cursor_set_in_action: # It could be that our trigger contains the content of # TextObjects in our containing snippet. If this is indeed # the case, we have to make sure that those are properly # killed. We do this by pretending that the user deleted # and retyped the text that our trigger matched. edit_actions = [ ("D", start.line, start.col, snippet.matched), ("I", start.line, start.col, snippet.matched), ] self._active_snippets[0].replay_user_edits(edit_actions) parent = self._current_snippet.find_parent_for_new_to(start) snippet_instance = snippet.launch( text_before, self._visual_content, parent, start, end ) # Open any folds this might have created vim_helper.command("normal! zv") self._visual_content.reset() self._active_snippets.append(snippet_instance) with use_proxy_buffer(self._active_snippets, self._vstate): with self._action_context(): snippet.do_post_expand( snippet_instance.start, snippet_instance.end, self._active_snippets, ) self._vstate.remember_buffer(self._active_snippets[0]) if not self._snip_expanded_in_action: self._jump(JumpDirection.FORWARD) elif self._current_snippet.current_text != "": self._jump(JumpDirection.FORWARD) else: self._current_snippet_is_done() if self._inside_action: self._snip_expanded_in_action = True def _can_expand(self, autotrigger_only=False): before = vim_helper.buf.line_till_cursor return before, self._snips(before, False, autotrigger_only) def _try_expand(self, autotrigger_only=False): """Try to expand a snippet in the current place.""" before, snippets = self._can_expand(autotrigger_only) if snippets: # prefer snippets with context if any snippets_with_context = [s for s in snippets if s.context] if snippets_with_context: snippets = snippets_with_context if not snippets: # No snippet found return False vim_helper.command("let &g:undolevels = &g:undolevels") if len(snippets) == 1: snippet = snippets[0] else: snippet = _ask_snippets(snippets) if not snippet: return True self._do_snippet(snippet, before) vim_helper.command("let &g:undolevels = &g:undolevels") return True def can_expand(self, autotrigger_only=False): """Check if we would be able to successfully find a snippet in the current position.""" return bool(self._can_expand(autotrigger_only)[1]) def can_jump(self, direction): if self._current_snippet == None: return False return self._current_snippet.has_next_tab(direction) def can_jump_forwards(self): return self.can_jump(JumpDirection.FORWARD) def can_jump_backwards(self): return self.can_jump(JumpDirection.BACKWARD) def _toggle_autotrigger(self): self._autotrigger = not self._autotrigger return self._autotrigger @property def _current_snippet(self): """The current snippet or None.""" if not self._active_snippets: return None return self._active_snippets[-1] def _file_to_edit(self, requested_ft, bang): """Returns a file to be edited for the given requested_ft. If 'bang' is empty a reasonable first choice is opened (see docs), otherwise all files are considered and the user gets to choose. """ filetypes = [] if requested_ft: filetypes.append(requested_ft) else: if bang: filetypes.extend(self.get_buffer_filetypes()) else: filetypes.append(self.get_buffer_filetypes()[0]) potentials = set() dot_vim_dirs = vim_helper.get_dot_vim() all_snippet_directories = find_all_snippet_directories() has_storage_dir = ( vim_helper.eval( "exists('g:UltiSnipsSnippetStorageDirectoryForUltiSnipsEdit')" ) == "1" ) if has_storage_dir: snippet_storage_dir = vim_helper.eval( "g:UltiSnipsSnippetStorageDirectoryForUltiSnipsEdit" ) full_path = os.path.expanduser(snippet_storage_dir) potentials.update( _get_potential_snippet_filenames_to_edit(full_path, filetypes) ) if len(all_snippet_directories) == 1: # Most likely the user has set g:UltiSnipsSnippetDirectories to a # single absolute path. potentials.update( _get_potential_snippet_filenames_to_edit( all_snippet_directories[0], filetypes ) ) if (len(all_snippet_directories) != 1 and not has_storage_dir) or ( has_storage_dir and bang ): # Likely the array contains things like ["UltiSnips", # "mycoolsnippets"] There is no more obvious way to edit than in # the users vim config directory. for snippet_dir in all_snippet_directories: for dot_vim_dir in dot_vim_dirs: if Path(dot_vim_dir) != Path(snippet_dir).parent: continue potentials.update( _get_potential_snippet_filenames_to_edit(snippet_dir, filetypes) ) if bang: for ft in filetypes: potentials.update(find_all_snippet_files(ft)) else: if not potentials: _show_user_warning( "UltiSnips was not able to find a default directory for snippets. " "Do any of " + dot_vim_dirs.__str__() + " exist AND contain " "any of the folders in g:UltiSnipsSnippetDirectories ? " "With default vim settings that would be: ~/.vim/UltiSnips " "Try :UltiSnipsEdit! instead of :UltiSnipsEdit." ) return "" return _select_and_create_file_to_edit(potentials) @contextmanager def _action_context(self): try: old_flag = self._inside_action self._inside_action = True yield finally: self._inside_action = old_flag @err_to_scratch_buffer.wrap def _track_change(self): self._should_update_textobjects = True try: inserted_char = vim_helper.eval("v:char") except UnicodeDecodeError: return if isinstance(inserted_char, bytes): return try: if inserted_char == "": before = vim_helper.buf.line_till_cursor if ( self._autotrigger and before and self._last_change[0] != "" and before[-1] == self._last_change[0] ): self._try_expand(autotrigger_only=True) finally: self._last_change = (inserted_char, vim_helper.buf.cursor) if self._should_reset_visual and self._visual_content.mode == "": self._visual_content.reset() self._should_reset_visual = True @err_to_scratch_buffer.wrap def _refresh_snippets(self): for _, source in self._snippet_sources: source.refresh() @err_to_scratch_buffer.wrap def _check_filetype(self, ft): """Ensure snippets are loaded for the current filetype.""" if ft not in self._filetypes: self._filetypes.append(ft) for _, source in self._snippet_sources: source.must_ensure = True UltiSnips_Manager = SnippetManager( # pylint:disable=invalid-name vim.eval("g:UltiSnipsExpandTrigger"), vim.eval("g:UltiSnipsJumpForwardTrigger"), vim.eval("g:UltiSnipsJumpBackwardTrigger"), )
37,641
Python
.py
846
32.425532
95
0.574454
SirVer/ultisnips
7,501
688
112
GPL-3.0
9/5/2024, 5:11:34 PM (Europe/Amsterdam)
12,233
err_to_scratch_buffer.py
SirVer_ultisnips/pythonx/UltiSnips/err_to_scratch_buffer.py
# coding=utf8 from functools import wraps import traceback import re import sys import time from bdb import BdbQuit from UltiSnips import vim_helper from UltiSnips.error import PebkacError from UltiSnips.remote_pdb import RemotePDB def _report_exception(self, msg, e): if hasattr(e, "snippet_info"): msg += "\nSnippet, caused error:\n" msg += re.sub(r"^(?=\S)", " ", e.snippet_info, flags=re.MULTILINE) # snippet_code comes from _python_code.py, it's set manually for # providing error message with stacktrace of failed python code # inside of the snippet. if hasattr(e, "snippet_code"): _, _, tb = sys.exc_info() tb_top = traceback.extract_tb(tb)[-1] msg += "\nExecuted snippet code:\n" lines = e.snippet_code.split("\n") for number, line in enumerate(lines, 1): msg += str(number).rjust(3) prefix = " " if line else "" if tb_top[1] == number: prefix = " > " msg += prefix + line + "\n" # Vim sends no WinLeave msg here. if hasattr(self, "_leaving_buffer"): self._leaving_buffer() # pylint:disable=protected-access vim_helper.new_scratch_buffer(msg) def wrap(func): """Decorator that will catch any Exception that 'func' throws and displays it in a new Vim scratch buffer.""" @wraps(func) def wrapper(self, *args, **kwds): try: return func(self, *args, **kwds) except BdbQuit: pass # A debugger stopped, but it's not really an error except PebkacError as e: if RemotePDB.is_enable(): RemotePDB.pm() msg = "UltiSnips Error:\n\n" msg += str(e).strip() if RemotePDB.is_enable(): host, port = RemotePDB.get_host_port() msg += "\nUltisnips' post mortem debug server caught the error. Run `telnet {}:{}` to inspect it with pdb\n".format( host, port ) _report_exception(self, msg, e) except Exception as e: # pylint: disable=bare-except if RemotePDB.is_enable(): RemotePDB.pm() msg = """An error occured. This is either a bug in UltiSnips or a bug in a snippet definition. If you think this is a bug, please report it to https://github.com/SirVer/ultisnips/issues/new Please read and follow: https://github.com/SirVer/ultisnips/blob/master/CONTRIBUTING.md#reproducing-bugs Following is the full stack trace: """ msg += traceback.format_exc() if RemotePDB.is_enable(): host, port = RemotePDB.get_host_port() msg += "\nUltisnips' post mortem debug server caught the error. Run `telnet {}:{}` to inspect it with pdb\n".format( host, port ) _report_exception(self, msg, e) return wrapper
2,919
Python
.py
70
33.057143
132
0.606765
SirVer/ultisnips
7,501
688
112
GPL-3.0
9/5/2024, 5:11:34 PM (Europe/Amsterdam)
12,234
test_position.py
SirVer_ultisnips/pythonx/UltiSnips/test_position.py
#!/usr/bin/env python3 # encoding: utf-8 # pylint: skip-file import unittest from position import Position class _MPBase: def runTest(self): obj = Position(*self.obj) for pivot, delta, wanted in self.steps: obj.move(Position(*pivot), Position(*delta)) self.assertEqual(Position(*wanted), obj) class MovePosition_DelSameLine(_MPBase, unittest.TestCase): # hello wor*ld -> h*ld -> hl*ld obj = (0, 9) steps = (((0, 1), (0, -8), (0, 1)), ((0, 1), (0, 1), (0, 2))) class MovePosition_DelSameLine1(_MPBase, unittest.TestCase): # hel*lo world -> hel*world -> hel*worl obj = (0, 3) steps = (((0, 4), (0, -3), (0, 3)), ((0, 8), (0, -1), (0, 3))) class MovePosition_InsSameLine1(_MPBase, unittest.TestCase): # hel*lo world -> hel*woresld obj = (0, 3) steps = ( ((0, 4), (0, -3), (0, 3)), ((0, 6), (0, 2), (0, 3)), ((0, 8), (0, -1), (0, 3)), ) class MovePosition_InsSameLine2(_MPBase, unittest.TestCase): # hello wor*ld -> helesdlo wor*ld obj = (0, 9) steps = (((0, 3), (0, 3), (0, 12)),) class MovePosition_DelSecondLine(_MPBase, unittest.TestCase): # hello world. sup hello world.*a, was # *a, was ach nix # ach nix obj = (1, 0) steps = (((0, 12), (0, -4), (1, 0)), ((0, 12), (-1, 0), (0, 12))) class MovePosition_DelSecondLine1(_MPBase, unittest.TestCase): # hello world. sup # a, *was # ach nix # hello world.a*was # ach nix obj = (1, 3) steps = ( ((0, 12), (0, -4), (1, 3)), ((0, 12), (-1, 0), (0, 15)), ((0, 12), (0, -3), (0, 12)), ((0, 12), (0, 1), (0, 13)), ) if __name__ == "__main__": unittest.main()
1,740
Python
.py
52
28.096154
69
0.524865
SirVer/ultisnips
7,501
688
112
GPL-3.0
9/5/2024, 5:11:34 PM (Europe/Amsterdam)
12,235
buffer_proxy.py
SirVer_ultisnips/pythonx/UltiSnips/buffer_proxy.py
# coding=utf8 import vim from UltiSnips import vim_helper from UltiSnips.diff import diff from UltiSnips.error import PebkacError from UltiSnips.position import Position from contextlib import contextmanager @contextmanager def use_proxy_buffer(snippets_stack, vstate): """ Forward all changes made in the buffer to the current snippet stack while function call. """ buffer_proxy = VimBufferProxy(snippets_stack, vstate) old_buffer = vim_helper.buf try: vim_helper.buf = buffer_proxy yield finally: vim_helper.buf = old_buffer buffer_proxy.validate_buffer() @contextmanager def suspend_proxy_edits(): """ Prevents changes being applied to the snippet stack while function call. """ if not isinstance(vim_helper.buf, VimBufferProxy): yield else: try: vim_helper.buf._disable_edits() yield finally: vim_helper.buf._enable_edits() class VimBufferProxy(vim_helper.VimBuffer): """ Proxy object used for tracking changes that made from snippet actions. Unfortunately, vim by itself lacks of the API for changing text in trackable maner. Vim marks offers limited functionality for tracking line additions and deletions, but nothing offered for tracking changes withing single line. Instance of this class is passed to all snippet actions and behaves as internal vim.current.window.buffer. All changes that are made by user passed to diff algorithm, and resulting diff applied to internal snippet structures to ensure they are in sync with actual buffer contents. """ def __init__(self, snippets_stack, vstate): """ Instantiate new object. snippets_stack is a slice of currently active snippets. """ self._snippets_stack = snippets_stack self._buffer = vim.current.buffer self._change_tick = int(vim.eval("b:changedtick")) self._forward_edits = True self._vstate = vstate def is_buffer_changed_outside(self): """ Returns true, if buffer was changed without using proxy object, like with vim.command() or through internal vim.current.window.buffer. """ return self._change_tick < int(vim.eval("b:changedtick")) def validate_buffer(self): """ Raises exception if buffer is changes beyound proxy object. """ if self.is_buffer_changed_outside(): raise PebkacError( "buffer was modified using vim.command or " + "vim.current.buffer; that changes are untrackable and leads to " + "errors in snippet expansion; use special variable `snip.buffer` " "for buffer modifications.\n\n" + "See :help UltiSnips-buffer-proxy for more info." ) def __setitem__(self, key, value): """ Behaves as vim.current.window.buffer.__setitem__ except it tracks changes and applies them to the current snippet stack. """ if isinstance(key, slice): value = [line for line in value] changes = list(self._get_diff(key.start, key.stop, value)) self._buffer[key.start : key.stop] = [line.strip("\n") for line in value] else: value = value changes = list(self._get_line_diff(key, self._buffer[key], value)) self._buffer[key] = value self._change_tick += 1 if self._forward_edits: for change in changes: self._apply_change(change) if self._snippets_stack: self._vstate.remember_buffer(self._snippets_stack[0]) def __setslice__(self, i, j, text): """ Same as __setitem__. """ self.__setitem__(slice(i, j), text) def __getitem__(self, key): """ Just passing call to the vim.current.window.buffer.__getitem__. """ return self._buffer[key] def __getslice__(self, i, j): """ Same as __getitem__. """ return self.__getitem__(slice(i, j)) def __len__(self): """ Same as len(vim.current.window.buffer). """ return len(self._buffer) def append(self, line, line_number=-1): """ Same as vim.current.window.buffer.append(), but with tracking changes. """ if line_number < 0: line_number = len(self) if not isinstance(line, list): line = [line] self[line_number:line_number] = [l for l in line] def __delitem__(self, key): if isinstance(key, slice): self.__setitem__(key, []) else: self.__setitem__(slice(key, key + 1), []) def _get_diff(self, start, end, new_value): """ Very fast diffing algorithm when changes are across many lines. """ for line_number in range(start, end): if line_number < 0: line_number = len(self._buffer) + line_number yield ("D", line_number, 0, self._buffer[line_number], True) if start < 0: start = len(self._buffer) + start for line_number in range(0, len(new_value)): yield ("I", start + line_number, 0, new_value[line_number], True) def _get_line_diff(self, line_number, before, after): """ Use precise diffing for tracking changes in single line. """ if before == "": for change in self._get_diff(line_number, line_number + 1, [after]): yield change else: for change in diff(before, after): yield (change[0], line_number, change[2], change[3]) def _apply_change(self, change): """ Apply changeset to current snippets stack, correctly moving around snippet itself or its child. """ if not self._snippets_stack: return change_type, line_number, column_number, change_text = change[0:4] line_before = line_number <= self._snippets_stack[0]._start.line column_before = column_number <= self._snippets_stack[0]._start.col if line_before and column_before: direction = 1 if change_type == "D": direction = -1 diff = Position(direction, 0) if len(change) != 5: diff = Position(0, direction * len(change_text)) self._snippets_stack[0]._move(Position(line_number, column_number), diff) else: if line_number > self._snippets_stack[0]._end.line: return if column_number >= self._snippets_stack[0]._end.col: return self._snippets_stack[0]._do_edit(change[0:4]) def _disable_edits(self): """ Temporary disable applying changes to snippets stack. Should be done while expanding anonymous snippet in the middle of jump to prevent double tracking. """ self._forward_edits = False def _enable_edits(self): """ Enables changes forwarding back. """ self._forward_edits = True
7,234
Python
.py
186
29.811828
85
0.601027
SirVer/ultisnips
7,501
688
112
GPL-3.0
9/5/2024, 5:11:34 PM (Europe/Amsterdam)
12,236
remote_pdb.py
SirVer_ultisnips/pythonx/UltiSnips/remote_pdb.py
import sys import threading from bdb import BdbQuit from UltiSnips import vim_helper class RemotePDB(object): """ Launch a pdb instance listening on (host, port). Used to provide debug facilities you can access with netcat or telnet. """ singleton = None def __init__(self, host, port): self.host = host self.port = port self._pdb = None def start_server(self): """ Create an instance of Pdb bound to a socket """ if self._pdb is not None: return import pdb import socket self.server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, True) self.server.bind((self.host, self.port)) self.server.listen(1) self.connection, address = self.server.accept() io = self.connection.makefile("rw") parent = self class Pdb(pdb.Pdb): """Patch quit to close the connection""" def set_quit(self): parent._shutdown() super().set_quit() self._pdb = Pdb(stdin=io, stdout=io) def _pm(self, tb): """ Launch the server as post mortem on the currently handled exception """ try: self._pdb.interaction(None, tb) except: # Ignore all exceptions part of debugger shutdown (and bugs... https://bugs.python.org/issue44461 ) pass def set_trace(self, frame): self._pdb.set_trace(frame) def _shutdown(self): if self._pdb is not None: import socket self.connection.shutdown(socket.SHUT_RDWR) self.connection.close() self.server.close() self._pdb = None @staticmethod def get_host_port(host=None, port=None): if host is None: host = vim_helper.eval("g:UltiSnipsDebugHost") if port is None: port = int(vim_helper.eval("g:UltiSnipsDebugPort")) return host, port @staticmethod def is_enable(): return bool(int(vim_helper.eval("g:UltiSnipsDebugServerEnable"))) @staticmethod def is_blocking(): return bool(int(vim_helper.eval("g:UltiSnipsPMDebugBlocking"))) @classmethod def _create(cls): if cls.singleton is None: cls.singleton = cls(*cls.get_host_port()) @classmethod def breakpoint(cls, host=None, port=None): if cls.singleton is None and not cls.is_enable(): return cls._create() cls.singleton.start_server() cls.singleton.set_trace(sys._getframe().f_back) @classmethod def pm(cls): """ Launch the server as post mortem on the currently handled exception """ if cls.singleton is None and not cls.is_enable(): return cls._create() t, val, tb = sys.exc_info() def _thread_run(): cls.singleton.start_server() cls.singleton._pm(tb) if cls.is_blocking(): _thread_run() else: thread = threading.Thread(target=_thread_run) thread.start()
3,199
Python
.py
93
25.505376
116
0.595331
SirVer/ultisnips
7,501
688
112
GPL-3.0
9/5/2024, 5:11:34 PM (Europe/Amsterdam)
12,237
position.py
SirVer_ultisnips/pythonx/UltiSnips/position.py
#!/usr/bin/env python3 # encoding: utf-8 from enum import Enum class JumpDirection(Enum): FORWARD = 1 BACKWARD = 2 class Position: """Represents a Position in a text file: (0 based line index, 0 based column index) and provides methods for moving them around.""" def __init__(self, line, col): self.line = line self.col = col def move(self, pivot, delta): """'pivot' is the position of the first changed character, 'delta' is how text after it moved.""" if self < pivot: return if delta.line == 0: if self.line == pivot.line: self.col += delta.col elif delta.line > 0: if self.line == pivot.line: self.col += delta.col - pivot.col self.line += delta.line else: self.line += delta.line if self.line == pivot.line: self.col += -delta.col + pivot.col def delta(self, pos): """Returns the difference that the cursor must move to come from 'pos' to us.""" assert isinstance(pos, Position) if self.line == pos.line: return Position(0, self.col - pos.col) if self > pos: return Position(self.line - pos.line, self.col) return Position(self.line - pos.line, pos.col) def __add__(self, pos): assert isinstance(pos, Position) return Position(self.line + pos.line, self.col + pos.col) def __sub__(self, pos): assert isinstance(pos, Position) return Position(self.line - pos.line, self.col - pos.col) def __eq__(self, other): return (self.line, self.col) == (other.line, other.col) def __ne__(self, other): return (self.line, self.col) != (other.line, other.col) def __lt__(self, other): return (self.line, self.col) < (other.line, other.col) def __le__(self, other): return (self.line, self.col) <= (other.line, other.col) def __repr__(self): return "(%i,%i)" % (self.line, self.col) def __getitem__(self, index): if index > 1: raise IndexError("position can be indexed only 0 (line) and 1 (column)") if index == 0: return self.line else: return self.col
2,308
Python
.py
60
29.733333
84
0.572581
SirVer/ultisnips
7,501
688
112
GPL-3.0
9/5/2024, 5:11:34 PM (Europe/Amsterdam)
12,238
vim_helper.py
SirVer_ultisnips/pythonx/UltiSnips/vim_helper.py
#!/usr/bin/env python3 # encoding: utf-8 """Wrapper functionality around the functions we need from Vim.""" from contextlib import contextmanager import os import platform from UltiSnips.compatibility import col2byte, byte2col from UltiSnips.error import PebkacError from UltiSnips.position import Position from UltiSnips.snippet.source.file.common import normalize_file_path from vim import error # pylint:disable=import-error,unused-import import vim # pylint:disable=import-error class VimBuffer: """Wrapper around the current Vim buffer.""" def __getitem__(self, idx): return vim.current.buffer[idx] def __setitem__(self, idx, text): vim.current.buffer[idx] = text def __len__(self): return len(vim.current.buffer) @property def line_till_cursor(self): # pylint:disable=no-self-use """Returns the text before the cursor.""" _, col = self.cursor return vim.current.line[:col] @property def number(self): # pylint:disable=no-self-use """The bufnr() of the current buffer.""" return vim.current.buffer.number @property def filetypes(self): return [ft for ft in vim.eval("&filetype").split(".") if ft] @property def cursor(self): # pylint:disable=no-self-use """The current windows cursor. Note that this is 0 based in col and 0 based in line which is different from Vim's cursor. """ line, nbyte = vim.current.window.cursor col = byte2col(line, nbyte) return Position(line - 1, col) @cursor.setter def cursor(self, pos): # pylint:disable=no-self-use """See getter.""" nbyte = col2byte(pos.line + 1, pos.col) vim.current.window.cursor = pos.line + 1, nbyte buf = VimBuffer() # pylint:disable=invalid-name @contextmanager def option_set_to(name, new_value): old_value = vim.eval("&" + name) command("set {0}={1}".format(name, new_value)) try: yield finally: command("set {0}={1}".format(name, old_value)) @contextmanager def save_mark(name): old_pos = get_mark_pos(name) try: yield finally: if _is_pos_zero(old_pos): delete_mark(name) else: set_mark_from_pos(name, old_pos) def escape(inp): """Creates a vim-friendly string from a group of dicts, lists and strings.""" def conv(obj): """Convert obj.""" if isinstance(obj, list): rv = "[" + ",".join(conv(o) for o in obj) + "]" elif isinstance(obj, dict): rv = ( "{" + ",".join( [ "%s:%s" % (conv(key), conv(value)) for key, value in obj.iteritems() ] ) + "}" ) else: rv = '"%s"' % obj.replace('"', '\\"') return rv return conv(inp) def command(cmd): """Wraps vim.command.""" return vim.command(cmd) def eval(text): """Wraps vim.eval.""" # Replace null bytes with newlines, as vim raises a ValueError and neovim # treats it as a terminator for the entire command. text = text.replace("\x00", "\n") return vim.eval(text) def bindeval(text): """Wraps vim.bindeval.""" rv = vim.bindeval(text) if not isinstance(rv, (dict, list)): return rv.decode(vim.eval("&encoding"), "replace") return rv def feedkeys(keys, mode="n"): """Wrapper around vim's feedkeys function. Mainly for convenience. """ if eval("mode()") == "n": if keys == "a": cursor_pos = get_cursor_pos() cursor_pos[2] = int(cursor_pos[2]) + 1 set_cursor_from_pos(cursor_pos) if keys in "ai": keys = "startinsert" if keys == "startinsert": command("startinsert") else: command(r'call feedkeys("%s", "%s")' % (keys, mode)) def new_scratch_buffer(text): """Create a new scratch buffer with the text given.""" vim.command("botright new") vim.command("set ft=") vim.command("set buftype=nofile") vim.current.buffer[:] = text.splitlines() feedkeys(r"\<Esc>") # Older versions of Vim always jumped the cursor to a new window, no matter # how it was generated. Newer versions of Vim seem to not jump if the # window is generated while in insert mode. Our tests rely that the cursor # jumps when an error is thrown. Instead of doing the right thing of fixing # how our test get the information about an error, we do the quick thing # and make sure we always end up with the cursor in the scratch buffer. feedkeys(r"\<c-w>\<down>") def virtual_position(line, col): """Runs the position through virtcol() and returns the result.""" nbytes = col2byte(line, col) return line, int(eval("virtcol([%d, %d])" % (line, nbytes))) def select(start, end): """Select the span in Select mode.""" _unmap_select_mode_mapping() selection = eval("&selection") col = col2byte(start.line + 1, start.col) buf.cursor = start mode = eval("mode()") move_cmd = "" if mode != "n": move_cmd += r"\<Esc>" if start == end: # Zero Length Tabstops, use 'i' or 'a'. if col == 0 or mode not in "i" and col < len(buf[start.line]): move_cmd += "i" else: move_cmd += "a" else: # Non zero length, use Visual selection. move_cmd += "v" if "inclusive" in selection: if end.col == 0: move_cmd += "%iG$" % end.line else: move_cmd += "%iG%i|" % virtual_position(end.line + 1, end.col) elif "old" in selection: move_cmd += "%iG%i|" % virtual_position(end.line + 1, end.col) else: move_cmd += "%iG%i|" % virtual_position(end.line + 1, end.col + 1) move_cmd += "o%iG%i|o\\<c-g>" % virtual_position(start.line + 1, start.col + 1) feedkeys(move_cmd) def get_dot_vim(): """Returns the likely places for ~/.vim for the current setup.""" home = vim.eval("$HOME") candidates = [] if platform.system() == "Windows": candidates.append(os.path.join(home, "vimfiles")) if vim.eval("has('nvim')") == "1": xdg_home_config = vim.eval("$XDG_CONFIG_HOME") or os.path.join(home, ".config") candidates.append(os.path.join(xdg_home_config, "nvim")) candidates.append(os.path.join(home, ".vim")) # Note: this potentially adds a duplicate on nvim # I assume nvim sets the MYVIMRC env variable (to beconfirmed) if "MYVIMRC" in os.environ: my_vimrc = os.path.expandvars(os.environ["MYVIMRC"]) candidates.append(normalize_file_path(os.path.dirname(my_vimrc))) candidates_normalized = [] for candidate in candidates: if os.path.isdir(candidate): candidates_normalized.append(normalize_file_path(candidate)) if candidates_normalized: # We remove duplicates on return return sorted(set(candidates_normalized)) raise PebkacError( "Unable to find user configuration directory. I tried '%s'." % candidates ) def set_mark_from_pos(name, pos): return _set_pos("'" + name, pos) def get_mark_pos(name): return _get_pos("'" + name) def set_cursor_from_pos(pos): return _set_pos(".", pos) def get_cursor_pos(): return _get_pos(".") def delete_mark(name): try: return command("delma " + name) except: return False def _set_pos(name, pos): return eval('setpos("{0}", {1})'.format(name, pos)) def _get_pos(name): return eval('getpos("{0}")'.format(name)) def _is_pos_zero(pos): return ["0"] * 4 == pos or [0] == pos def _unmap_select_mode_mapping(): """This function unmaps select mode mappings if so wished by the user. Removes select mode mappings that can actually be typed by the user (ie, ignores things like <Plug>). """ if int(eval("g:UltiSnipsRemoveSelectModeMappings")): ignores = eval("g:UltiSnipsMappingsToIgnore") + ["UltiSnips"] for option in ("<buffer>", ""): # Put all smaps into a var, and then read the var command(r"redir => _tmp_smaps | silent smap %s " % option + "| redir END") # Check if any mappings where found if hasattr(vim, "bindeval"): # Safer to use bindeval, if it exists, because it can deal with # non-UTF-8 characters in mappings; see GH #690. all_maps = bindeval(r"_tmp_smaps") else: all_maps = eval(r"_tmp_smaps") all_maps = list(filter(len, all_maps.splitlines())) if len(all_maps) == 1 and all_maps[0][0] not in " sv": # "No maps found". String could be localized. Hopefully # it doesn't start with any of these letters in any # language continue # Only keep mappings that should not be ignored maps = [ m for m in all_maps if not any(i in m for i in ignores) and len(m.strip()) ] for map in maps: # The first three chars are the modes, that might be listed. # We are not interested in them here. trig = map[3:].split()[0] if len(map[3:].split()) != 0 else None if trig is None: continue # The bar separates commands if trig[-1] == "|": trig = trig[:-1] + "<Bar>" # Special ones if trig[0] == "<": add = False # Only allow these for valid in ["Tab", "NL", "CR", "C-Tab", "BS"]: if trig == "<%s>" % valid: add = True if not add: continue # UltiSnips remaps <BS>. Keep this around. if trig == "<BS>": continue # Actually unmap it try: command("silent! sunmap %s %s" % (option, trig)) except: # pylint:disable=bare-except # Bug 908139: ignore unmaps that fail because of # unprintable characters. This is not ideal because we # will not be able to unmap lhs with any unprintable # character. If the lhs stats with a printable # character this will leak to the user when he tries to # type this character as a first in a selected tabstop. # This case should be rare enough to not bother us # though. pass
10,908
Python
.py
272
30.834559
87
0.573974
SirVer/ultisnips
7,501
688
112
GPL-3.0
9/5/2024, 5:11:34 PM (Europe/Amsterdam)
12,239
indent_util.py
SirVer_ultisnips/pythonx/UltiSnips/indent_util.py
#!/usr/bin/env python3 # encoding: utf-8 """See module doc.""" from UltiSnips import vim_helper class IndentUtil: """Utility class for dealing properly with indentation.""" def __init__(self): self.reset() def reset(self): """Gets the spacing properties from Vim.""" self.shiftwidth = int( vim_helper.eval("exists('*shiftwidth') ? shiftwidth() : &shiftwidth") ) self._expandtab = vim_helper.eval("&expandtab") == "1" self._tabstop = int(vim_helper.eval("&tabstop")) def ntabs_to_proper_indent(self, ntabs): """Convert 'ntabs' number of tabs to the proper indent prefix.""" line_ind = ntabs * self.shiftwidth * " " line_ind = self.indent_to_spaces(line_ind) line_ind = self.spaces_to_indent(line_ind) return line_ind def indent_to_spaces(self, indent): """Converts indentation to spaces respecting Vim settings.""" indent = indent.expandtabs(self._tabstop) right = (len(indent) - len(indent.rstrip(" "))) * " " indent = indent.replace(" ", "") indent = indent.replace("\t", " " * self._tabstop) return indent + right def spaces_to_indent(self, indent): """Converts spaces to proper indentation respecting Vim settings.""" if not self._expandtab: indent = indent.replace(" " * self._tabstop, "\t") return indent
1,428
Python
.py
33
35.666667
81
0.616606
SirVer/ultisnips
7,501
688
112
GPL-3.0
9/5/2024, 5:11:34 PM (Europe/Amsterdam)
12,240
vim_state.py
SirVer_ultisnips/pythonx/UltiSnips/vim_state.py
#!/usr/bin/env python3 # encoding: utf-8 """Some classes to conserve Vim's state for comparing over time.""" from collections import deque, namedtuple from UltiSnips import vim_helper from UltiSnips.compatibility import byte2col from UltiSnips.position import Position _Placeholder = namedtuple("_FrozenPlaceholder", ["current_text", "start", "end"]) class VimPosition(Position): """Represents the current position in the buffer, together with some status variables that might change our decisions down the line.""" def __init__(self): pos = vim_helper.buf.cursor self._mode = vim_helper.eval("mode()") Position.__init__(self, pos.line, pos.col) @property def mode(self): """Returns the mode() this position was created.""" return self._mode class VimState: """Caches some state information from Vim to better guess what editing tasks the user might have done in the last step.""" def __init__(self): self._poss = deque(maxlen=5) self._lvb = None self._text_to_expect = "" self._unnamed_reg_cached = False # We store the cached value of the unnamed register in Vim directly to # avoid any Unicode issues with saving and restoring the unnamed # register across the Python bindings. The unnamed register can contain # data that cannot be coerced to Unicode, and so a simple vim.eval('@"') # fails badly. Keeping the cached value in Vim directly, sidesteps the # problem. vim_helper.command('let g:_ultisnips_unnamed_reg_cache = ""') def remember_unnamed_register(self, text_to_expect): """Save the unnamed register. 'text_to_expect' is text that we expect to be contained in the register the next time this method is called - this could be text from the tabstop that was selected and might have been overwritten. We will not cache that then. """ self._unnamed_reg_cached = True escaped_text = self._text_to_expect.replace("'", "''") res = int(vim_helper.eval('@" != ' + "'" + escaped_text + "'")) if res: vim_helper.command('let g:_ultisnips_unnamed_reg_cache = @"') self._text_to_expect = text_to_expect def restore_unnamed_register(self): """Restores the unnamed register and forgets what we cached.""" if not self._unnamed_reg_cached: return vim_helper.command('let @" = g:_ultisnips_unnamed_reg_cache') self._unnamed_reg_cached = False def remember_position(self): """Remember the current position as a previous pose.""" self._poss.append(VimPosition()) def remember_buffer(self, to): """Remember the content of the buffer and the position.""" self._lvb = vim_helper.buf[to.start.line : to.end.line + 1] self._lvb_len = len(vim_helper.buf) self.remember_position() @property def diff_in_buffer_length(self): """Returns the difference in the length of the current buffer compared to the remembered.""" return len(vim_helper.buf) - self._lvb_len @property def pos(self): """The last remembered position.""" return self._poss[-1] @property def ppos(self): """The second to last remembered position.""" return self._poss[-2] @property def remembered_buffer(self): """The content of the remembered buffer.""" return self._lvb[:] class VisualContentPreserver: """Saves the current visual selection and the selection mode it was done in (e.g. line selection, block selection or regular selection.)""" def __init__(self): self.reset() def reset(self): """Forget the preserved state.""" self._mode = "" self._text = "" self._placeholder = None def conserve(self): """Save the last visual selection and the mode it was made in.""" sl, sbyte = map( int, (vim_helper.eval("""line("'<")"""), vim_helper.eval("""col("'<")""")) ) el, ebyte = map( int, (vim_helper.eval("""line("'>")"""), vim_helper.eval("""col("'>")""")) ) sc = byte2col(sl, sbyte - 1) ec = byte2col(el, ebyte - 1) self._mode = vim_helper.eval("visualmode()") # When 'selection' is 'exclusive', the > mark is one column behind the # actual content being copied, but never before the < mark. if vim_helper.eval("&selection") == "exclusive": if not (sl == el and sbyte == ebyte): ec -= 1 _vim_line_with_eol = lambda ln: vim_helper.buf[ln] + "\n" if sl == el: text = _vim_line_with_eol(sl - 1)[sc : ec + 1] else: text = _vim_line_with_eol(sl - 1)[sc:] for cl in range(sl, el - 1): text += _vim_line_with_eol(cl) text += _vim_line_with_eol(el - 1)[: ec + 1] self._text = text def conserve_placeholder(self, placeholder): if placeholder: self._placeholder = _Placeholder( placeholder.current_text, placeholder.start, placeholder.end ) else: self._placeholder = None @property def text(self): """The conserved text.""" return self._text @property def mode(self): """The conserved visualmode().""" return self._mode @property def placeholder(self): """Returns latest selected placeholder.""" return self._placeholder
5,616
Python
.py
132
34.348485
86
0.613294
SirVer/ultisnips
7,501
688
112
GPL-3.0
9/5/2024, 5:11:34 PM (Europe/Amsterdam)
12,241
text.py
SirVer_ultisnips/pythonx/UltiSnips/text.py
#!/usr/bin/env python3 # encoding: utf-8 """Utilities to deal with text.""" def unescape(text): """Removes '\\' escaping from 'text'.""" rv = "" i = 0 while i < len(text): if i + 1 < len(text) and text[i] == "\\": rv += text[i + 1] i += 1 else: rv += text[i] i += 1 return rv def escape(text, chars): """Escapes all characters in 'chars' in text using backspaces.""" rv = "" for char in text: if char in chars: rv += "\\" rv += char return rv def fill_in_whitespace(text): """Returns 'text' with escaped whitespace replaced through whitespaces.""" text = text.replace(r"\n", "\n") text = text.replace(r"\t", "\t") text = text.replace(r"\r", "\r") text = text.replace(r"\a", "\a") text = text.replace(r"\b", "\b") return text def head_tail(line): """Returns the first word in 'line' and the rest of 'line' or None if the line is too short.""" generator = (t.strip() for t in line.split(None, 1)) head = next(generator).strip() tail = "" try: tail = next(generator).strip() except StopIteration: pass return head, tail class LineIterator: """Convenience class that keeps track of line numbers in files.""" def __init__(self, text): self._line_index = -1 self._lines = list(text.splitlines(True)) def __iter__(self): return self def __next__(self): """Returns the next line.""" if self._line_index + 1 < len(self._lines): self._line_index += 1 return self._lines[self._line_index] raise StopIteration() @property def line_index(self): """The 1 based line index in the current file.""" return self._line_index + 1 def peek(self): """Returns the next line (if there is any, otherwise None) without advancing the iterator.""" try: return self._lines[self._line_index + 1] except IndexError: return None
2,086
Python
.py
66
24.712121
78
0.565652
SirVer/ultisnips
7,501
688
112
GPL-3.0
9/5/2024, 5:11:34 PM (Europe/Amsterdam)
12,242
__init__.py
SirVer_ultisnips/pythonx/UltiSnips/__init__.py
#!/usr/bin/env python3 # encoding: utf-8 """Entry point for all things UltiSnips.""" from UltiSnips.snippet_manager import UltiSnips_Manager
143
Python
.py
4
34.25
55
0.788321
SirVer/ultisnips
7,501
688
112
GPL-3.0
9/5/2024, 5:11:34 PM (Europe/Amsterdam)
12,243
test_diff.py
SirVer_ultisnips/pythonx/UltiSnips/test_diff.py
#!/usr/bin/env python3 # encoding: utf-8 # pylint: skip-file import unittest from diff import diff, guess_edit from position import Position from typing import List def transform(a, cmds): buf = a.split("\n") for cmd in cmds: ctype, line, col, char = cmd if ctype == "D": if char != "\n": buf[line] = buf[line][:col] + buf[line][col + len(char) :] else: buf[line] = buf[line] + buf[line + 1] del buf[line + 1] elif ctype == "I": buf[line] = buf[line][:col] + char + buf[line][col:] buf = "\n".join(buf).split("\n") return "\n".join(buf) class _BaseGuessing: def runTest(self): rv, es = guess_edit( self.initial_line, self.a, self.b, Position(*self.ppos), Position(*self.pos) ) self.assertEqual(rv, True) self.assertEqual(self.wanted, es) class TestGuessing_Noop0(_BaseGuessing, unittest.TestCase): a: List[str] = [] b: List[str] = [] initial_line = 0 ppos, pos = (0, 6), (0, 7) wanted = () class TestGuessing_InsertOneChar(_BaseGuessing, unittest.TestCase): a, b = ["Hello World"], ["Hello World"] initial_line = 0 ppos, pos = (0, 6), (0, 7) wanted = (("I", 0, 6, " "),) class TestGuessing_InsertOneChar1(_BaseGuessing, unittest.TestCase): a, b = ["Hello World"], ["Hello World"] initial_line = 0 ppos, pos = (0, 7), (0, 8) wanted = (("I", 0, 7, " "),) class TestGuessing_BackspaceOneChar(_BaseGuessing, unittest.TestCase): a, b = ["Hello World"], ["Hello World"] initial_line = 0 ppos, pos = (0, 7), (0, 6) wanted = (("D", 0, 6, " "),) class TestGuessing_DeleteOneChar(_BaseGuessing, unittest.TestCase): a, b = ["Hello World"], ["Hello World"] initial_line = 0 ppos, pos = (0, 5), (0, 5) wanted = (("D", 0, 5, " "),) class _Base: def runTest(self): es = diff(self.a, self.b) tr = transform(self.a, es) self.assertEqual(self.b, tr) self.assertEqual(self.wanted, es) class TestEmptyString(_Base, unittest.TestCase): a, b = "", "" wanted = () class TestAllMatch(_Base, unittest.TestCase): a, b = "abcdef", "abcdef" wanted = () class TestLotsaNewlines(_Base, unittest.TestCase): a, b = "Hello", "Hello\nWorld\nWorld\nWorld" wanted = ( ("I", 0, 5, "\n"), ("I", 1, 0, "World"), ("I", 1, 5, "\n"), ("I", 2, 0, "World"), ("I", 2, 5, "\n"), ("I", 3, 0, "World"), ) class TestCrash(_Base, unittest.TestCase): a = "hallo Blah mitte=sdfdsfsd\nhallo kjsdhfjksdhfkjhsdfkh mittekjshdkfhkhsdfdsf" b = "hallo Blah mitte=sdfdsfsd\nhallo b mittekjshdkfhkhsdfdsf" wanted = (("D", 1, 6, "kjsdhfjksdhfkjhsdfkh"), ("I", 1, 6, "b")) class TestRealLife(_Base, unittest.TestCase): a = "hallo End Beginning" b = "hallo End t" wanted = (("D", 0, 10, "Beginning"), ("I", 0, 10, "t")) class TestRealLife1(_Base, unittest.TestCase): a = "Vorne hallo Hinten" b = "Vorne hallo Hinten" wanted = (("I", 0, 11, " "),) class TestWithNewline(_Base, unittest.TestCase): a = "First Line\nSecond Line" b = "n" wanted = ( ("D", 0, 0, "First Line"), ("D", 0, 0, "\n"), ("D", 0, 0, "Second Line"), ("I", 0, 0, "n"), ) class TestCheapDelete(_Base, unittest.TestCase): a = "Vorne hallo Hinten" b = "Vorne Hinten" wanted = (("D", 0, 5, " hallo"),) class TestNoSubstring(_Base, unittest.TestCase): a, b = "abc", "def" wanted = (("D", 0, 0, "abc"), ("I", 0, 0, "def")) class TestCommonCharacters(_Base, unittest.TestCase): a, b = "hasomelongertextbl", "hol" wanted = (("D", 0, 1, "asomelongertextb"), ("I", 0, 1, "o")) class TestUltiSnipsProblem(_Base, unittest.TestCase): a = "this is it this is it this is it" b = "this is it a this is it" wanted = (("D", 0, 11, "this is it"), ("I", 0, 11, "a")) class MatchIsTooCheap(_Base, unittest.TestCase): a = "stdin.h" b = "s" wanted = (("D", 0, 1, "tdin.h"),) class MultiLine(_Base, unittest.TestCase): a = "hi first line\nsecond line first line\nsecond line world" b = "hi first line\nsecond line k world" wanted = ( ("D", 1, 12, "first line"), ("D", 1, 12, "\n"), ("D", 1, 12, "second line"), ("I", 1, 12, "k"), ) if __name__ == "__main__": unittest.main() # k = TestEditScript() # unittest.TextTestRunner().run(k)
4,539
Python
.py
128
29.640625
88
0.564649
SirVer/ultisnips
7,501
688
112
GPL-3.0
9/5/2024, 5:11:34 PM (Europe/Amsterdam)
12,244
debug.py
SirVer_ultisnips/pythonx/UltiSnips/debug.py
#!/usr/bin/env python3 # encoding: utf-8 """Convenience methods that help with debugging. They should never be used in production code. """ import sys DUMP_FILENAME = ( "/tmp/file.txt" if not sys.platform.lower().startswith("win") else "C:/windows/temp/ultisnips.txt" ) with open(DUMP_FILENAME, "w"): pass # clears the file def echo_to_hierarchy(text_object): """Outputs the given 'text_object' and its children hierarchically.""" # pylint:disable=protected-access orig = text_object parent = text_object while parent._parent: parent = parent._parent def _do_print(text_object, indent=""): """prints recursively.""" debug(indent + ("MAIN: " if text_object == orig else "") + str(text_object)) try: for child in text_object._children: _do_print(child, indent=indent + " ") except AttributeError: pass _do_print(parent) def debug(msg): """Dumb 'msg' into the debug file.""" with open(DUMP_FILENAME, "ab") as dump_file: dump_file.write((msg + "\n").encode("utf-8")) def print_stack(): """Dump a stack trace into the debug file.""" import traceback with open(DUMP_FILENAME, "a") as dump_file: traceback.print_stack(file=dump_file)
1,303
Python
.py
38
28.710526
84
0.644285
SirVer/ultisnips
7,501
688
112
GPL-3.0
9/5/2024, 5:11:34 PM (Europe/Amsterdam)
12,245
diff.py
SirVer_ultisnips/pythonx/UltiSnips/diff.py
#!/usr/bin/env python3 # encoding: utf-8 """Commands to compare text objects and to guess how to transform from one to another.""" from collections import defaultdict import sys from UltiSnips import vim_helper from UltiSnips.position import Position def is_complete_edit(initial_line, original, wanted, cmds): """Returns true if 'original' is changed to 'wanted' with the edit commands in 'cmds'. Initial line is to change the line numbers in 'cmds'. """ buf = original[:] for cmd in cmds: ctype, line, col, char = cmd line -= initial_line if ctype == "D": if char != "\n": buf[line] = buf[line][:col] + buf[line][col + len(char) :] else: if line + 1 < len(buf): buf[line] = buf[line] + buf[line + 1] del buf[line + 1] else: del buf[line] elif ctype == "I": buf[line] = buf[line][:col] + char + buf[line][col:] buf = "\n".join(buf).split("\n") return len(buf) == len(wanted) and all(j == k for j, k in zip(buf, wanted)) def guess_edit(initial_line, last_text, current_text, vim_state): """Try to guess what the user might have done by heuristically looking at cursor movement, number of changed lines and if they got longer or shorter. This will detect most simple movements like insertion, deletion of a line or carriage return. 'initial_text' is the index of where the comparison starts, 'last_text' is the last text of the snippet, 'current_text' is the current text of the snippet and 'vim_state' is the cached vim state. Returns (True, edit_cmds) when the edit could be guessed, (False, None) otherwise. """ if not len(last_text) and not len(current_text): return True, () pos = vim_state.pos ppos = vim_state.ppos # All text deleted? if len(last_text) and ( not current_text or (len(current_text) == 1 and not current_text[0]) ): es = [] if not current_text: current_text = [""] for i in last_text: es.append(("D", initial_line, 0, i)) es.append(("D", initial_line, 0, "\n")) es.pop() # Remove final \n because it is not really removed if is_complete_edit(initial_line, last_text, current_text, es): return True, es if ppos.mode == "v": # Maybe selectmode? sv = list(map(int, vim_helper.eval("""getpos("'<")"""))) sv = Position(sv[1] - 1, sv[2] - 1) ev = list(map(int, vim_helper.eval("""getpos("'>")"""))) ev = Position(ev[1] - 1, ev[2] - 1) if "exclusive" in vim_helper.eval("&selection"): ppos.col -= 1 # We want to be inclusive, sorry. ev.col -= 1 es = [] if sv.line == ev.line: es.append( ( "D", sv.line, sv.col, last_text[sv.line - initial_line][sv.col : ev.col + 1], ) ) if sv != pos and sv.line == pos.line: es.append( ( "I", sv.line, sv.col, current_text[sv.line - initial_line][sv.col : pos.col + 1], ) ) if is_complete_edit(initial_line, last_text, current_text, es): return True, es if pos.line == ppos.line: if len(last_text) == len(current_text): # Movement only in one line llen = len(last_text[ppos.line - initial_line]) clen = len(current_text[pos.line - initial_line]) if ppos < pos and clen > llen: # maybe only chars have been added es = ( ( "I", ppos.line, ppos.col, current_text[ppos.line - initial_line][ppos.col : pos.col], ), ) if is_complete_edit(initial_line, last_text, current_text, es): return True, es if clen < llen: if ppos == pos: # 'x' or DEL or dt or something es = ( ( "D", pos.line, pos.col, last_text[ppos.line - initial_line][ ppos.col : ppos.col + (llen - clen) ], ), ) if is_complete_edit(initial_line, last_text, current_text, es): return True, es if pos < ppos: # Backspacing or dT dF? es = ( ( "D", pos.line, pos.col, last_text[pos.line - initial_line][ pos.col : pos.col + llen - clen ], ), ) if is_complete_edit(initial_line, last_text, current_text, es): return True, es elif len(current_text) < len(last_text): # were some lines deleted? (dd or so) es = [] for i in range(len(last_text) - len(current_text)): es.append(("D", pos.line, 0, last_text[pos.line - initial_line + i])) es.append(("D", pos.line, 0, "\n")) if is_complete_edit(initial_line, last_text, current_text, es): return True, es else: # Movement in more than one line if ppos.line + 1 == pos.line and pos.col == 0: # Carriage return? es = (("I", ppos.line, ppos.col, "\n"),) if is_complete_edit(initial_line, last_text, current_text, es): return True, es return False, None def diff(a, b, sline=0): """ Return a list of deletions and insertions that will turn 'a' into 'b'. This is done by traversing an implicit edit graph and searching for the shortest route. The basic idea is as follows: - Matching a character is free as long as there was no deletion/insertion before. Then, matching will be seen as delete + insert [1]. - Deleting one character has the same cost everywhere. Each additional character costs only have of the first deletion. - Insertion is cheaper the earlier it happens. The first character is more expensive that any later [2]. [1] This is that world -> aolsa will be "D" world + "I" aolsa instead of "D" w , "D" rld, "I" a, "I" lsa [2] This is that "hello\n\n" -> "hello\n\n\n" will insert a newline after hello and not after \n """ d = defaultdict(list) # pylint:disable=invalid-name seen = defaultdict(lambda: sys.maxsize) d[0] = [(0, 0, sline, 0, ())] cost = 0 deletion_cost = len(a) + len(b) insertion_cost = len(a) + len(b) while True: while len(d[cost]): x, y, line, col, what = d[cost].pop() if a[x:] == b[y:]: return what if x < len(a) and y < len(b) and a[x] == b[y]: ncol = col + 1 nline = line if a[x] == "\n": ncol = 0 nline += 1 lcost = cost + 1 if ( what and what[-1][0] == "D" and what[-1][1] == line and what[-1][2] == col and a[x] != "\n" ): # Matching directly after a deletion should be as costly as # DELETE + INSERT + a bit lcost = (deletion_cost + insertion_cost) * 1.5 if seen[x + 1, y + 1] > lcost: d[lcost].append((x + 1, y + 1, nline, ncol, what)) seen[x + 1, y + 1] = lcost if y < len(b): # INSERT ncol = col + 1 nline = line if b[y] == "\n": ncol = 0 nline += 1 if ( what and what[-1][0] == "I" and what[-1][1] == nline and what[-1][2] + len(what[-1][-1]) == col and b[y] != "\n" and seen[x, y + 1] > cost + (insertion_cost + ncol) // 2 ): seen[x, y + 1] = cost + (insertion_cost + ncol) // 2 d[cost + (insertion_cost + ncol) // 2].append( ( x, y + 1, line, ncol, what[:-1] + (("I", what[-1][1], what[-1][2], what[-1][-1] + b[y]),), ) ) elif seen[x, y + 1] > cost + insertion_cost + ncol: seen[x, y + 1] = cost + insertion_cost + ncol d[cost + ncol + insertion_cost].append( (x, y + 1, nline, ncol, what + (("I", line, col, b[y]),)) ) if x < len(a): # DELETE if ( what and what[-1][0] == "D" and what[-1][1] == line and what[-1][2] == col and a[x] != "\n" and what[-1][-1] != "\n" and seen[x + 1, y] > cost + deletion_cost // 2 ): seen[x + 1, y] = cost + deletion_cost // 2 d[cost + deletion_cost // 2].append( ( x + 1, y, line, col, what[:-1] + (("D", line, col, what[-1][-1] + a[x]),), ) ) elif seen[x + 1, y] > cost + deletion_cost: seen[x + 1, y] = cost + deletion_cost d[cost + deletion_cost].append( (x + 1, y, line, col, what + (("D", line, col, a[x]),)) ) cost += 1
10,562
Python
.py
247
27.174089
86
0.435218
SirVer/ultisnips
7,501
688
112
GPL-3.0
9/5/2024, 5:11:34 PM (Europe/Amsterdam)
12,246
lexer.py
SirVer_ultisnips/pythonx/UltiSnips/snippet/parsing/lexer.py
#!/usr/bin/env python3 # encoding: utf-8 """Not really a lexer in the classical sense, but code to convert snippet definitions into logical units called Tokens.""" import string import re from UltiSnips.error import PebkacError from UltiSnips.position import Position from UltiSnips.text import unescape class _TextIterator: """Helper class to make iterating over text easier.""" def __init__(self, text, offset): self._text = text self._line = offset.line self._col = offset.col self._idx = 0 def __iter__(self): """Iterator interface.""" return self def __next__(self): """Returns the next character.""" if self._idx >= len(self._text): raise StopIteration rv = self._text[self._idx] if self._text[self._idx] in ("\n", "\r\n"): self._line += 1 self._col = 0 else: self._col += 1 self._idx += 1 return rv def peek(self, count=1): """Returns the next 'count' characters without advancing the stream.""" if count > 1: # This might return '' if nothing is found return self._text[self._idx : self._idx + count] try: return self._text[self._idx] except IndexError: return None @property def pos(self): """Current position in the text.""" return Position(self._line, self._col) def _parse_number(stream): """Expects the stream to contain a number next, returns the number without consuming any more bytes.""" rv = "" while stream.peek() and stream.peek() in string.digits: rv += next(stream) return int(rv) def _parse_till_closing_brace(stream): """ Returns all chars till a non-escaped } is found. Other non escaped { are taken into account and skipped over. Will also consume the closing }, but not return it """ rv = "" in_braces = 1 while True: if EscapeCharToken.starts_here(stream, "\\{}"): rv += next(stream) + next(stream) else: char = next(stream) if char == "{": in_braces += 1 elif char == "}": in_braces -= 1 if in_braces == 0: break rv += char return rv def _parse_till_unescaped_char(stream, chars): """ Returns all chars till a non-escaped char is found. Will also consume the closing char, but and return it as second return value """ rv = "" while True: escaped = False for char in chars: if EscapeCharToken.starts_here(stream, char): rv += next(stream) + next(stream) escaped = True if not escaped: char = next(stream) if char in chars: break rv += char return rv, char class Token: """Represents a Token as parsed from a snippet definition.""" def __init__(self, gen, indent): self.initial_text = "" self.start = gen.pos self._parse(gen, indent) self.end = gen.pos def _parse(self, stream, indent): """Parses the token from 'stream' with the current 'indent'.""" pass # Does nothing class TabStopToken(Token): """${1:blub}""" CHECK = re.compile(r"^\${\d+[:}]") @classmethod def starts_here(cls, stream): """Returns true if this token starts at the current position in 'stream'.""" return cls.CHECK.match(stream.peek(10)) is not None def _parse(self, stream, indent): next(stream) # $ next(stream) # { self.number = _parse_number(stream) if stream.peek() == ":": next(stream) self.initial_text = _parse_till_closing_brace(stream) def __repr__(self): return "TabStopToken(%r,%r,%r,%r)" % ( self.start, self.end, self.number, self.initial_text, ) class VisualToken(Token): """${VISUAL}""" CHECK = re.compile(r"^\${VISUAL[:}/]") @classmethod def starts_here(cls, stream): """Returns true if this token starts at the current position in 'stream'.""" return cls.CHECK.match(stream.peek(10)) is not None def _parse(self, stream, indent): for _ in range(8): # ${VISUAL next(stream) if stream.peek() == ":": next(stream) self.alternative_text, char = _parse_till_unescaped_char(stream, "/}") self.alternative_text = unescape(self.alternative_text) if char == "/": # Transformation going on try: self.search = _parse_till_unescaped_char(stream, "/")[0] self.replace = _parse_till_unescaped_char(stream, "/")[0] self.options = _parse_till_closing_brace(stream) except StopIteration: raise PebkacError( "Invalid ${VISUAL} transformation! Forgot to escape a '/'?" ) else: self.search = None self.replace = None self.options = None def __repr__(self): return "VisualToken(%r,%r)" % (self.start, self.end) class TransformationToken(Token): """${1/match/replace/options}""" CHECK = re.compile(r"^\${\d+\/") @classmethod def starts_here(cls, stream): """Returns true if this token starts at the current position in 'stream'.""" return cls.CHECK.match(stream.peek(10)) is not None def _parse(self, stream, indent): next(stream) # $ next(stream) # { self.number = _parse_number(stream) next(stream) # / self.search = _parse_till_unescaped_char(stream, "/")[0] self.replace = _parse_till_unescaped_char(stream, "/")[0] self.options = _parse_till_closing_brace(stream) def __repr__(self): return "TransformationToken(%r,%r,%r,%r,%r)" % ( self.start, self.end, self.number, self.search, self.replace, ) class MirrorToken(Token): """$1.""" CHECK = re.compile(r"^\$\d+") @classmethod def starts_here(cls, stream): """Returns true if this token starts at the current position in 'stream'.""" return cls.CHECK.match(stream.peek(10)) is not None def _parse(self, stream, indent): next(stream) # $ self.number = _parse_number(stream) def __repr__(self): return "MirrorToken(%r,%r,%r)" % (self.start, self.end, self.number) class ChoicesToken(Token): """${1|o1,o2,o3|} P.S. This is not a subclass of TabStop, so its content will not be parsed recursively. """ CHECK = re.compile(r"^\${\d+\|") @classmethod def starts_here(cls, stream): """Returns true if this token starts at the current position in 'stream'.""" return cls.CHECK.match(stream.peek(10)) is not None def _parse(self, stream, indent): next(stream) # $ next(stream) # { self.number = _parse_number(stream) if self.number == 0: raise PebkacError("Choices selection is not supported on $0") next(stream) # | choices_text = _parse_till_unescaped_char(stream, "|")[0] choice_list = [] # inside choice item, comma can be escaped by "\," # we need to do a little bit smarter parsing than simply splitting choice_stream = _TextIterator(choices_text, Position(0, 0)) while True: cur_col = choice_stream.pos.col try: result = _parse_till_unescaped_char(choice_stream, ",")[0] if not result: continue choice_list.append(self._get_unescaped_choice_item(result)) except: last_choice_item = self._get_unescaped_choice_item( choices_text[cur_col:] ) if last_choice_item: choice_list.append(last_choice_item) break self.choice_list = choice_list self.initial_text = "|{0}|".format(",".join(choice_list)) _parse_till_closing_brace(stream) def _get_unescaped_choice_item(self, escaped_choice_item): """unescape common inside choice item""" return escaped_choice_item.replace(r"\,", ",") def __repr__(self): return "ChoicesToken(%r,%r,%r,|%r|)" % ( self.start, self.end, self.number, self.initial_text, ) class EscapeCharToken(Token): """\\n.""" @classmethod def starts_here(cls, stream, chars=r"{}\$`"): """Returns true if this token starts at the current position in 'stream'.""" cs = stream.peek(2) if len(cs) == 2 and cs[0] == "\\" and cs[1] in chars: return True def _parse(self, stream, indent): next(stream) # \ self.initial_text = next(stream) def __repr__(self): return "EscapeCharToken(%r,%r,%r)" % (self.start, self.end, self.initial_text) class ShellCodeToken(Token): """`echo "hi"`""" @classmethod def starts_here(cls, stream): """Returns true if this token starts at the current position in 'stream'.""" return stream.peek(1) == "`" def _parse(self, stream, indent): next(stream) # ` self.code = _parse_till_unescaped_char(stream, "`")[0] def __repr__(self): return "ShellCodeToken(%r,%r,%r)" % (self.start, self.end, self.code) class PythonCodeToken(Token): """`!p snip.rv = "Hi"`""" CHECK = re.compile(r"^`!p\s") @classmethod def starts_here(cls, stream): """Returns true if this token starts at the current position in 'stream'.""" return cls.CHECK.match(stream.peek(4)) is not None def _parse(self, stream, indent): for _ in range(3): next(stream) # `!p if stream.peek() in "\t ": next(stream) code = _parse_till_unescaped_char(stream, "`")[0] # Strip the indent if any if len(indent): lines = code.splitlines() self.code = lines[0] + "\n" self.code += "\n".join([l[len(indent) :] for l in lines[1:]]) else: self.code = code self.indent = indent def __repr__(self): return "PythonCodeToken(%r,%r,%r)" % (self.start, self.end, self.code) class VimLCodeToken(Token): """`!v g:hi`""" CHECK = re.compile(r"^`!v\s") @classmethod def starts_here(cls, stream): """Returns true if this token starts at the current position in 'stream'.""" return cls.CHECK.match(stream.peek(4)) is not None def _parse(self, stream, indent): for _ in range(4): next(stream) # `!v self.code = _parse_till_unescaped_char(stream, "`")[0] def __repr__(self): return "VimLCodeToken(%r,%r,%r)" % (self.start, self.end, self.code) class EndOfTextToken(Token): """Appears at the end of the text.""" def __repr__(self): return "EndOfText(%r)" % self.end def tokenize(text, indent, offset, allowed_tokens): """Returns an iterator of tokens of 'text'['offset':] which is assumed to have 'indent' as the whitespace of the begging of the lines. Only 'allowed_tokens' are considered to be valid tokens.""" stream = _TextIterator(text, offset) try: while True: done_something = False for token in allowed_tokens: if token.starts_here(stream): yield token(stream, indent) done_something = True break if not done_something: next(stream) except StopIteration: yield EndOfTextToken(stream, indent)
11,998
Python
.py
324
28.070988
86
0.56918
SirVer/ultisnips
7,501
688
112
GPL-3.0
9/5/2024, 5:11:34 PM (Europe/Amsterdam)
12,247
ulti_snips.py
SirVer_ultisnips/pythonx/UltiSnips/snippet/parsing/ulti_snips.py
#!/usr/bin/env python3 # encoding: utf-8 """Parses a UltiSnips snippet definition and launches it into Vim.""" from UltiSnips.snippet.parsing.base import ( tokenize_snippet_text, finalize, resolve_ambiguity, ) from UltiSnips.snippet.parsing.lexer import ( EscapeCharToken, VisualToken, TransformationToken, ChoicesToken, TabStopToken, MirrorToken, PythonCodeToken, VimLCodeToken, ShellCodeToken, ) from UltiSnips.text_objects import ( EscapedChar, Mirror, PythonCode, ShellCode, TabStop, Transformation, VimLCode, Visual, Choices, ) from UltiSnips.error import PebkacError _TOKEN_TO_TEXTOBJECT = { EscapeCharToken: EscapedChar, VisualToken: Visual, ShellCodeToken: ShellCode, PythonCodeToken: PythonCode, VimLCodeToken: VimLCode, ChoicesToken: Choices, } __ALLOWED_TOKENS = [ EscapeCharToken, VisualToken, TransformationToken, ChoicesToken, TabStopToken, MirrorToken, PythonCodeToken, VimLCodeToken, ShellCodeToken, ] def _create_transformations(all_tokens, seen_ts): """Create the objects that need to know about tabstops.""" for parent, token in all_tokens: if isinstance(token, TransformationToken): if token.number not in seen_ts: raise PebkacError( "Tabstop %i is not known but is used by a Transformation" % token.number ) Transformation(parent, seen_ts[token.number], token) def parse_and_instantiate(parent_to, text, indent): """Parses a snippet definition in UltiSnips format from 'text' assuming the current 'indent'. Will instantiate all the objects and link them as children to parent_to. Will also put the initial text into Vim. """ all_tokens, seen_ts = tokenize_snippet_text( parent_to, text, indent, __ALLOWED_TOKENS, __ALLOWED_TOKENS, _TOKEN_TO_TEXTOBJECT, ) resolve_ambiguity(all_tokens, seen_ts) _create_transformations(all_tokens, seen_ts) finalize(all_tokens, seen_ts, parent_to)
2,155
Python
.py
77
22.38961
79
0.688588
SirVer/ultisnips
7,501
688
112
GPL-3.0
9/5/2024, 5:11:34 PM (Europe/Amsterdam)
12,248
snipmate.py
SirVer_ultisnips/pythonx/UltiSnips/snippet/parsing/snipmate.py
#!/usr/bin/env python3 # encoding: utf-8 """Parses a snipMate snippet definition and launches it into Vim.""" from UltiSnips.snippet.parsing.base import ( tokenize_snippet_text, finalize, resolve_ambiguity, ) from UltiSnips.snippet.parsing.lexer import ( EscapeCharToken, VisualToken, TabStopToken, MirrorToken, ShellCodeToken, ) from UltiSnips.text_objects import EscapedChar, Mirror, VimLCode, Visual _TOKEN_TO_TEXTOBJECT = { EscapeCharToken: EscapedChar, VisualToken: Visual, ShellCodeToken: VimLCode, # `` is VimL in snipMate } __ALLOWED_TOKENS = [ EscapeCharToken, VisualToken, TabStopToken, MirrorToken, ShellCodeToken, ] __ALLOWED_TOKENS_IN_TABSTOPS = [ EscapeCharToken, VisualToken, MirrorToken, ShellCodeToken, ] def parse_and_instantiate(parent_to, text, indent): """Parses a snippet definition in snipMate format from 'text' assuming the current 'indent'. Will instantiate all the objects and link them as children to parent_to. Will also put the initial text into Vim. """ all_tokens, seen_ts = tokenize_snippet_text( parent_to, text, indent, __ALLOWED_TOKENS, __ALLOWED_TOKENS_IN_TABSTOPS, _TOKEN_TO_TEXTOBJECT, ) resolve_ambiguity(all_tokens, seen_ts) finalize(all_tokens, seen_ts, parent_to)
1,381
Python
.py
50
23.16
78
0.711044
SirVer/ultisnips
7,501
688
112
GPL-3.0
9/5/2024, 5:11:34 PM (Europe/Amsterdam)
12,249
base.py
SirVer_ultisnips/pythonx/UltiSnips/snippet/parsing/base.py
#!/usr/bin/env python3 # encoding: utf-8 """Common functionality of the snippet parsing codes.""" from UltiSnips.position import Position from UltiSnips.snippet.parsing.lexer import tokenize, TabStopToken from UltiSnips.text_objects import TabStop from UltiSnips.text_objects import Mirror from UltiSnips.snippet.parsing.lexer import MirrorToken def resolve_ambiguity(all_tokens, seen_ts): """$1 could be a Mirror or a TabStop. This figures this out. """ for parent, token in all_tokens: if isinstance(token, MirrorToken): if token.number not in seen_ts: seen_ts[token.number] = TabStop(parent, token) else: Mirror(parent, seen_ts[token.number], token) def tokenize_snippet_text( snippet_instance, text, indent, allowed_tokens_in_text, allowed_tokens_in_tabstops, token_to_textobject, ): """Turns 'text' into a stream of tokens and creates the text objects from those tokens that are mentioned in 'token_to_textobject' assuming the current 'indent'. The 'allowed_tokens_in_text' define which tokens will be recognized in 'text' while 'allowed_tokens_in_tabstops' are the tokens that will be recognized in TabStop placeholder text. """ seen_ts = {} all_tokens = [] def _do_parse(parent, text, allowed_tokens): """Recursive function that actually creates the objects.""" tokens = list(tokenize(text, indent, parent.start, allowed_tokens)) for token in tokens: all_tokens.append((parent, token)) if isinstance(token, TabStopToken): ts = TabStop(parent, token) seen_ts[token.number] = ts _do_parse(ts, token.initial_text, allowed_tokens_in_tabstops) else: klass = token_to_textobject.get(token.__class__, None) if klass is not None: text_object = klass(parent, token) # TabStop has some subclasses (e.g. Choices) if isinstance(text_object, TabStop): seen_ts[text_object.number] = text_object _do_parse(snippet_instance, text, allowed_tokens_in_text) return all_tokens, seen_ts def finalize(all_tokens, seen_ts, snippet_instance): """Adds a tabstop 0 if non is in 'seen_ts' and brings the text of the snippet instance into Vim.""" if 0 not in seen_ts: mark = all_tokens[-1][1].end # Last token is always EndOfText m1 = Position(mark.line, mark.col) TabStop(snippet_instance, 0, mark, m1)
2,612
Python
.py
60
35.4
77
0.655757
SirVer/ultisnips
7,501
688
112
GPL-3.0
9/5/2024, 5:11:34 PM (Europe/Amsterdam)
12,250
ulti_snips.py
SirVer_ultisnips/pythonx/UltiSnips/snippet/definition/ulti_snips.py
#!/usr/bin/env python3 # encoding: utf-8 """A UltiSnips snippet after parsing.""" from UltiSnips.snippet.definition.base import SnippetDefinition from UltiSnips.snippet.parsing.ulti_snips import parse_and_instantiate class UltiSnipsSnippetDefinition(SnippetDefinition): """See module doc.""" def instantiate(self, snippet_instance, initial_text, indent): return parse_and_instantiate(snippet_instance, initial_text, indent)
446
Python
.py
9
46.111111
76
0.793503
SirVer/ultisnips
7,501
688
112
GPL-3.0
9/5/2024, 5:11:34 PM (Europe/Amsterdam)
12,251
__init__.py
SirVer_ultisnips/pythonx/UltiSnips/snippet/definition/__init__.py
"""In memory representation of snippet definitions.""" from UltiSnips.snippet.definition.ulti_snips import UltiSnipsSnippetDefinition from UltiSnips.snippet.definition.snipmate import SnipMateSnippetDefinition
211
Python
.py
3
69
78
0.879227
SirVer/ultisnips
7,501
688
112
GPL-3.0
9/5/2024, 5:11:34 PM (Europe/Amsterdam)
12,252
snipmate.py
SirVer_ultisnips/pythonx/UltiSnips/snippet/definition/snipmate.py
#!/usr/bin/env python3 # encoding: utf-8 """A snipMate snippet after parsing.""" from UltiSnips.snippet.definition.base import SnippetDefinition from UltiSnips.snippet.parsing.snipmate import parse_and_instantiate class SnipMateSnippetDefinition(SnippetDefinition): """See module doc.""" SNIPMATE_SNIPPET_PRIORITY = -1000 def __init__(self, trigger, value, description, location): SnippetDefinition.__init__( self, self.SNIPMATE_SNIPPET_PRIORITY, trigger, value, description, "w", {}, location, None, {}, ) def instantiate(self, snippet_instance, initial_text, indent): parse_and_instantiate(snippet_instance, initial_text, indent)
800
Python
.py
23
26.478261
69
0.637191
SirVer/ultisnips
7,501
688
112
GPL-3.0
9/5/2024, 5:11:34 PM (Europe/Amsterdam)
12,253
base.py
SirVer_ultisnips/pythonx/UltiSnips/snippet/definition/base.py
#!/usr/bin/env python3 # encoding: utf-8 """Snippet representation after parsing.""" import re import vim import textwrap from UltiSnips import vim_helper from UltiSnips.error import PebkacError from UltiSnips.indent_util import IndentUtil from UltiSnips.position import Position from UltiSnips.text import escape from UltiSnips.text_objects import SnippetInstance from UltiSnips.text_objects.python_code import SnippetUtilForAction, cached_compile __WHITESPACE_SPLIT = re.compile(r"\s") class _SnippetUtilCursor: def __init__(self, cursor): self._cursor = [cursor[0] - 1, cursor[1]] self._set = False def preserve(self): self._set = True self._cursor = [vim_helper.buf.cursor[0], vim_helper.buf.cursor[1]] def is_set(self): return self._set def set(self, line, column): self.__setitem__(0, line) self.__setitem__(1, column) def to_vim_cursor(self): return (self._cursor[0] + 1, self._cursor[1]) def __getitem__(self, index): return self._cursor[index] def __setitem__(self, index, value): self._set = True self._cursor[index] = value def __len__(self): return 2 def __str__(self): return str((self._cursor[0], self._cursor[1])) def split_at_whitespace(string): """Like string.split(), but keeps empty words as empty words.""" return re.split(__WHITESPACE_SPLIT, string) def _words_for_line(trigger, before, num_words=None): """Gets the final 'num_words' words from 'before'. If num_words is None, then use the number of words in 'trigger'. """ if num_words is None: num_words = len(split_at_whitespace(trigger)) word_list = split_at_whitespace(before) if len(word_list) <= num_words: return before.strip() else: before_words = before for i in range(-1, -(num_words + 1), -1): left = before_words.rfind(word_list[i]) before_words = before_words[:left] return before[len(before_words) :].strip() class SnippetDefinition: """Represents a snippet as parsed from a file.""" _INDENT = re.compile(r"^[ \t]*") _TABS = re.compile(r"^\t*") def __init__( self, priority, trigger, value, description, options, globals, location, context, actions, ): self._priority = int(priority) self._trigger = trigger self._value = value self._description = description self._opts = options self._matched = "" self._last_re = None self._globals = globals self._compiled_globals = None self._location = location # Make sure that we actually match our trigger in case we are # immediately expanded. At this point we don't take into # account a any context code self._context_code = None self.matches(self._trigger) self._context_code = context if context: self._compiled_context_code = cached_compile( "snip.context = " + context, "<context-code>", "exec" ) self._context = None self._actions = actions or {} self._compiled_actions = { action: cached_compile(source, "<action-code>", "exec") for action, source in self._actions.items() } def __repr__(self): return "_SnippetDefinition(%r,%s,%s,%s)" % ( self._priority, self._trigger, self._description, self._opts, ) def _re_match(self, trigger): """Test if a the current regex trigger matches `trigger`. If so, set _last_re and _matched. """ for match in re.finditer(self._trigger, trigger): if match.end() != len(trigger): continue else: self._matched = trigger[match.start() : match.end()] self._last_re = match return match return False def _context_match(self, visual_content, before): # skip on empty buffer if len(vim.current.buffer) == 1 and vim.current.buffer[0] == "": return locals = { "context": None, "visual_mode": "", "visual_text": "", "last_placeholder": None, "before": before, } if visual_content: locals["visual_mode"] = visual_content.mode locals["visual_text"] = visual_content.text locals["last_placeholder"] = visual_content.placeholder return self._eval_code( "snip.context = " + self._context_code, locals, self._compiled_context_code ).context def _eval_code(self, code, additional_locals={}, compiled_code=None): current = vim.current locals = { "window": current.window, "buffer": current.buffer, "line": current.window.cursor[0] - 1, "column": current.window.cursor[1] - 1, "cursor": _SnippetUtilCursor(current.window.cursor), } locals.update(additional_locals) snip = SnippetUtilForAction(locals) try: if self._compiled_globals is None: self._precompile_globals() glob = {"snip": snip, "match": self._last_re} exec(self._compiled_globals, glob) exec(compiled_code or code, glob) except Exception as e: code = "\n".join( [ "import re, os, vim, string, random", "\n".join(self._globals.get("!p", [])).replace("\r\n", "\n"), code, ] ) self._make_debug_exception(e, code) raise return snip def _execute_action( self, action, context, additional_locals={}, compiled_action=None ): mark_to_use = "`" with vim_helper.save_mark(mark_to_use): vim_helper.set_mark_from_pos(mark_to_use, vim_helper.get_cursor_pos()) cursor_line_before = vim_helper.buf.line_till_cursor locals = {"context": context} locals.update(additional_locals) snip = self._eval_code(action, locals, compiled_action) if snip.cursor.is_set(): vim_helper.buf.cursor = Position( snip.cursor._cursor[0], snip.cursor._cursor[1] ) else: new_mark_pos = vim_helper.get_mark_pos(mark_to_use) cursor_invalid = False if vim_helper._is_pos_zero(new_mark_pos): cursor_invalid = True else: vim_helper.set_cursor_from_pos(new_mark_pos) if cursor_line_before != vim_helper.buf.line_till_cursor: cursor_invalid = True if cursor_invalid: raise PebkacError( "line under the cursor was modified, but " + '"snip.cursor" variable is not set; either set set ' + '"snip.cursor" to new cursor position, or do not ' + "modify cursor line" ) return snip def _make_debug_exception(self, e, code=""): e.snippet_info = textwrap.dedent( """ Defined in: {} Trigger: {} Description: {} Context: {} Pre-expand: {} Post-expand: {} """ ).format( self._location, self._trigger, self._description, self._context_code if self._context_code else "<none>", self._actions["pre_expand"] if "pre_expand" in self._actions else "<none>", self._actions["post_expand"] if "post_expand" in self._actions else "<none>", code, ) e.snippet_code = code def _precompile_globals(self): self._compiled_globals = cached_compile( "\n".join( [ "import re, os, vim, string, random", "\n".join(self._globals.get("!p", [])).replace("\r\n", "\n"), ] ), "<global-snippets>", "exec", ) def has_option(self, opt): """Check if the named option is set.""" return opt in self._opts @property def description(self): """Descriptive text for this snippet.""" return ("(%s) %s" % (self._trigger, self._description)).strip() @property def priority(self): """The snippets priority, which defines which snippet will be preferred over others with the same trigger.""" return self._priority @property def trigger(self): """The trigger text for the snippet.""" return self._trigger @property def matched(self): """The last text that matched this snippet in match() or could_match().""" return self._matched @property def location(self): """Where this snippet was defined.""" return self._location @property def context(self): """The matched context.""" return self._context def matches(self, before, visual_content=None): """Returns True if this snippet matches 'before'.""" # If user supplies both "w" and "i", it should perhaps be an # error, but if permitted it seems that "w" should take precedence # (since matching at word boundary and within a word == matching at word # boundary). self._matched = "" words = _words_for_line(self._trigger, before) if "r" in self._opts: try: match = self._re_match(before) except Exception as e: self._make_debug_exception(e) raise elif "w" in self._opts: words_len = len(self._trigger) words_prefix = words[:-words_len] words_suffix = words[-words_len:] match = words_suffix == self._trigger if match and words_prefix: # Require a word boundary between prefix and suffix. boundary_chars = escape(words_prefix[-1:] + words_suffix[:1], r"\"") match = vim_helper.eval('"%s" =~# "\\\\v.<."' % boundary_chars) != "0" elif "i" in self._opts: match = words.endswith(self._trigger) else: match = words == self._trigger # By default, we match the whole trigger if match and not self._matched: self._matched = self._trigger # Ensure the match was on a word boundry if needed if "b" in self._opts and match: text_before = before.rstrip()[: -len(self._matched)] if text_before.strip(" \t") != "": self._matched = "" return False self._context = None if match and self._context_code: self._context = self._context_match(visual_content, before) if not self.context: match = False return match def could_match(self, before): """Return True if this snippet could match the (partial) 'before'.""" self._matched = "" # List all on whitespace. if before and before[-1] in (" ", "\t"): before = "" if before and before.rstrip() is not before: return False words = _words_for_line(self._trigger, before) if "r" in self._opts: # Test for full match only match = self._re_match(before) elif "w" in self._opts: # Trim non-empty prefix up to word boundary, if present. qwords = escape(words, r"\"") words_suffix = vim_helper.eval( 'substitute("%s", "\\\\v^.+<(.+)", "\\\\1", "")' % qwords ) match = self._trigger.startswith(words_suffix) self._matched = words_suffix # TODO: list_snippets() function cannot handle partial-trigger # matches yet, so for now fail if we trimmed the prefix. if words_suffix != words: match = False elif "i" in self._opts: # TODO: It is hard to define when a inword snippet could match, # therefore we check only for full-word trigger. match = self._trigger.startswith(words) else: match = self._trigger.startswith(words) # By default, we match the words from the trigger if match and not self._matched: self._matched = words # Ensure the match was on a word boundry if needed if "b" in self._opts and match: text_before = before.rstrip()[: -len(self._matched)] if text_before.strip(" \t") != "": self._matched = "" return False return match def instantiate(self, snippet_instance, initial_text, indent): """Parses the content of this snippet and brings the corresponding text objects alive inside of Vim.""" raise NotImplementedError() def do_pre_expand(self, visual_content, snippets_stack): if "pre_expand" in self._actions: locals = {"buffer": vim_helper.buf, "visual_content": visual_content} snip = self._execute_action( self._actions["pre_expand"], self._context, locals, self._compiled_actions["pre_expand"], ) self._context = snip.context return snip.cursor.is_set() else: return False def do_post_expand(self, start, end, snippets_stack): if "post_expand" in self._actions: locals = { "snippet_start": start, "snippet_end": end, "buffer": vim_helper.buf, } snip = self._execute_action( self._actions["post_expand"], snippets_stack[-1].context, locals, self._compiled_actions["post_expand"], ) snippets_stack[-1].context = snip.context return snip.cursor.is_set() else: return False def do_post_jump( self, tabstop_number, jump_direction, snippets_stack, current_snippet ): if "post_jump" in self._actions: start = current_snippet.start end = current_snippet.end locals = { "tabstop": tabstop_number, "jump_direction": jump_direction, "tabstops": current_snippet.get_tabstops(), "snippet_start": start, "snippet_end": end, "buffer": vim_helper.buf, } snip = self._execute_action( self._actions["post_jump"], current_snippet.context, locals, self._compiled_actions["post_jump"], ) current_snippet.context = snip.context return snip.cursor.is_set() else: return False def launch(self, text_before, visual_content, parent, start, end): """Launch this snippet, overwriting the text 'start' to 'end' and keeping the 'text_before' on the launch line. 'Parent' is the parent snippet instance if any. """ indent = self._INDENT.match(text_before).group(0) lines = (self._value + "\n").splitlines() ind_util = IndentUtil() # Replace leading tabs in the snippet definition via proper indenting initial_text = [] for line_num, line in enumerate(lines): if "t" in self._opts: tabs = 0 else: tabs = len(self._TABS.match(line).group(0)) line_ind = ind_util.ntabs_to_proper_indent(tabs) if line_num != 0: line_ind = indent + line_ind result_line = line_ind + line[tabs:] if "m" in self._opts: result_line = result_line.rstrip() initial_text.append(result_line) initial_text = "\n".join(initial_text) if self._compiled_globals is None: self._precompile_globals() snippet_instance = SnippetInstance( self, parent, initial_text, start, end, visual_content, last_re=self._last_re, globals=self._globals, context=self._context, _compiled_globals=self._compiled_globals, ) self.instantiate(snippet_instance, initial_text, indent) snippet_instance.replace_initial_text(vim_helper.buf) snippet_instance.update_textobjects(vim_helper.buf) return snippet_instance
17,050
Python
.py
436
27.961009
87
0.548592
SirVer/ultisnips
7,501
688
112
GPL-3.0
9/5/2024, 5:11:34 PM (Europe/Amsterdam)
12,254
added.py
SirVer_ultisnips/pythonx/UltiSnips/snippet/source/added.py
#!/usr/bin/env python3 # encoding: utf-8 """Handles manually added snippets UltiSnips_Manager.add_snippet().""" from UltiSnips.snippet.source.base import SnippetSource class AddedSnippetsSource(SnippetSource): """See module docstring.""" def add_snippet(self, ft, snippet): """Adds the given 'snippet' for 'ft'.""" self._snippets[ft].add_snippet(snippet)
385
Python
.py
9
38.444444
70
0.721622
SirVer/ultisnips
7,501
688
112
GPL-3.0
9/5/2024, 5:11:34 PM (Europe/Amsterdam)
12,255
snippet_dictionary.py
SirVer_ultisnips/pythonx/UltiSnips/snippet/source/snippet_dictionary.py
#!/usr/bin/env python3 # encoding: utf-8 """Implements a container for parsed snippets.""" class SnippetDictionary: """See module docstring.""" def __init__(self): self._snippets = [] self._cleared = {} self._clear_priority = float("-inf") def add_snippet(self, snippet): """Add 'snippet' to this dictionary.""" self._snippets.append(snippet) def get_matching_snippets( self, trigger, potentially, autotrigger_only, visual_content ): """Returns all snippets matching the given trigger. If 'potentially' is true, returns all that could_match(). If 'autotrigger_only' is true, function will return only snippets which are marked with flag 'A' (should be automatically expanded without trigger key press). It's handled specially to avoid walking down the list of all snippets, which can be very slow, because function will be called on each change made in insert mode. """ all_snippets = self._snippets if autotrigger_only: all_snippets = [s for s in all_snippets if s.has_option("A")] if not potentially: return [s for s in all_snippets if s.matches(trigger, visual_content)] else: return [s for s in all_snippets if s.could_match(trigger)] def clear_snippets(self, priority, triggers): """Clear the snippets by mark them as cleared. If trigger is None, it updates the value of clear priority instead. """ if not triggers: if self._clear_priority is None or priority > self._clear_priority: self._clear_priority = priority else: for trigger in triggers: if trigger not in self._cleared or priority > self._cleared[trigger]: self._cleared[trigger] = priority def __len__(self): return len(self._snippets) def __iter__(self): return iter(self._snippets)
2,026
Python
.py
47
34.106383
85
0.62863
SirVer/ultisnips
7,501
688
112
GPL-3.0
9/5/2024, 5:11:34 PM (Europe/Amsterdam)
12,256
__init__.py
SirVer_ultisnips/pythonx/UltiSnips/snippet/source/__init__.py
#!/usr/bin/env python3 # encoding: utf-8 """Sources of snippet definitions.""" from UltiSnips.snippet.source.base import SnippetSource from UltiSnips.snippet.source.added import AddedSnippetsSource from UltiSnips.snippet.source.file.snipmate import SnipMateFileSource from UltiSnips.snippet.source.file.ulti_snips import ( UltiSnipsFileSource, find_all_snippet_directories, find_all_snippet_files, find_snippet_files, )
438
Python
.py
12
34
69
0.816038
SirVer/ultisnips
7,501
688
112
GPL-3.0
9/5/2024, 5:11:34 PM (Europe/Amsterdam)
12,257
base.py
SirVer_ultisnips/pythonx/UltiSnips/snippet/source/base.py
#!/usr/bin/env python3 # encoding: utf-8 """Base class for snippet sources.""" from collections import defaultdict from UltiSnips.snippet.source.snippet_dictionary import SnippetDictionary class SnippetSource: """See module docstring.""" def __init__(self): self._snippets = defaultdict(SnippetDictionary) self._extends = defaultdict(set) self.must_ensure = True def ensure(self, filetypes): """Ensures that snippets are loaded.""" def refresh(self): """Resets all snippets, so that they are reloaded on the next call to ensure. """ def _get_existing_deep_extends(self, base_filetypes): """Helper for get all existing filetypes extended by base filetypes.""" deep_extends = self.get_deep_extends(base_filetypes) return [ft for ft in deep_extends if ft in self._snippets] def get_snippets( self, filetypes, before, possible, autotrigger_only, visual_content ): """Returns the snippets for all 'filetypes' (in order) and their parents matching the text 'before'. If 'possible' is true, a partial match is enough. Base classes can override this method to provide means of creating snippets on the fly. Returns a list of SnippetDefinition s. """ result = [] for ft in self._get_existing_deep_extends(filetypes): snips = self._snippets[ft] result.extend( snips.get_matching_snippets( before, possible, autotrigger_only, visual_content ) ) return result def get_clear_priority(self, filetypes): """Get maximum clearsnippets priority without arguments for specified filetypes, if any. It returns None if there are no clearsnippets. """ pri = None for ft in self._get_existing_deep_extends(filetypes): snippets = self._snippets[ft] if pri is None or snippets._clear_priority > pri: pri = snippets._clear_priority return pri def get_cleared(self, filetypes): """Get a set of cleared snippets marked by clearsnippets with arguments for specified filetypes.""" cleared = {} for ft in self._get_existing_deep_extends(filetypes): snippets = self._snippets[ft] for key, value in snippets._cleared.items(): if key not in cleared or value > cleared[key]: cleared[key] = value return cleared def update_extends(self, child_ft, parent_fts): """Update the extending relation by given child filetype and its parent filetypes.""" self._extends[child_ft].update(parent_fts) def get_deep_extends(self, base_filetypes): """Get a list of filetypes that is either directed or indirected extended by given base filetypes. Note that the returned list include the root filetype itself. """ seen = set(base_filetypes) todo_fts = list(set(base_filetypes)) while todo_fts: todo_ft = todo_fts.pop() unseen_extends = set(ft for ft in self._extends[todo_ft] if ft not in seen) seen.update(unseen_extends) todo_fts.extend(unseen_extends) return seen
3,359
Python
.py
77
34.246753
87
0.636308
SirVer/ultisnips
7,501
688
112
GPL-3.0
9/5/2024, 5:11:34 PM (Europe/Amsterdam)
12,258
ulti_snips.py
SirVer_ultisnips/pythonx/UltiSnips/snippet/source/file/ulti_snips.py
#!/usr/bin/env python3 # encoding: utf-8 """Parsing of snippet files.""" from collections import defaultdict import glob import os from typing import Set, List from UltiSnips import vim_helper from UltiSnips.error import PebkacError from UltiSnips.snippet.definition import UltiSnipsSnippetDefinition from UltiSnips.snippet.source.file.base import SnippetFileSource from UltiSnips.snippet.source.file.common import ( handle_action, handle_context, handle_extends, normalize_file_path, ) from UltiSnips.text import LineIterator, head_tail def find_snippet_files(ft, directory: str) -> Set[str]: """Returns all matching snippet files for 'ft' in 'directory'.""" patterns = ["%s.snippets", "%s_*.snippets", os.path.join("%s", "*")] ret = set() directory = os.path.expanduser(directory) for pattern in patterns: for fn in glob.glob(os.path.join(directory, pattern % ft)): ret.add(normalize_file_path(fn)) return ret def find_all_snippet_directories() -> List[str]: """Returns a list of the absolute path of all potential snippet directories, no matter if they exist or not.""" if vim_helper.eval("exists('b:UltiSnipsSnippetDirectories')") == "1": snippet_dirs = vim_helper.eval("b:UltiSnipsSnippetDirectories") else: snippet_dirs = vim_helper.eval("g:UltiSnipsSnippetDirectories") if len(snippet_dirs) == 1: # To reduce confusion and increase consistency with # `UltiSnipsSnippetsDir`, we expand ~ here too. full_path = os.path.expanduser(snippet_dirs[0]) if os.path.isabs(full_path): return [full_path] all_dirs = [] check_dirs = vim_helper.eval("&runtimepath").split(",") for rtp in check_dirs: for snippet_dir in snippet_dirs: if snippet_dir == "snippets": raise PebkacError( "You have 'snippets' in UltiSnipsSnippetDirectories. This " "directory is reserved for snipMate snippets. Use another " "directory for UltiSnips snippets." ) pth = normalize_file_path( os.path.expanduser(os.path.join(rtp, snippet_dir)) ) # Runtimepath entries may contain wildcards. all_dirs.extend(glob.glob(pth)) return all_dirs def find_all_snippet_files(ft) -> Set[str]: """Returns all snippet files matching 'ft' in the given runtime path directory.""" patterns = ["%s.snippets", "%s_*.snippets", os.path.join("%s", "*")] ret = set() for directory in find_all_snippet_directories(): if not os.path.isdir(directory): continue for pattern in patterns: for fn in glob.glob(os.path.join(directory, pattern % ft)): ret.add(fn) return ret def _handle_snippet_or_global( filename, line, lines, python_globals, priority, pre_expand, context ): """Parses the snippet that begins at the current line.""" start_line_index = lines.line_index descr = "" opts = "" # Ensure this is a snippet snip = line.split()[0] # Get and strip options if they exist remain = line[len(snip) :].strip() words = remain.split() if len(words) > 2: # second to last word ends with a quote if '"' not in words[-1] and words[-2][-1] == '"': opts = words[-1] remain = remain[: -len(opts) - 1].rstrip() if "e" in opts and not context: left = remain[:-1].rfind('"') if left != -1 and left != 0: context, remain = remain[left:].strip('"'), remain[:left] # Get and strip description if it exists remain = remain.strip() if len(remain.split()) > 1 and remain[-1] == '"': left = remain[:-1].rfind('"') if left != -1 and left != 0: descr, remain = remain[left:], remain[:left] # The rest is the trigger trig = remain.strip() if len(trig.split()) > 1 or "r" in opts: if trig[0] != trig[-1]: return "error", ("Invalid multiword trigger: '%s'" % trig, lines.line_index) trig = trig[1:-1] end = "end" + snip content = "" found_end = False for line in lines: if line.rstrip() == end: content = content[:-1] # Chomp the last newline found_end = True break content += line if not found_end: return "error", ("Missing 'endsnippet' for %r" % trig, lines.line_index) if snip == "global": python_globals[trig].append(content) elif snip == "snippet": definition = UltiSnipsSnippetDefinition( priority, trig, content, descr, opts, python_globals, "%s:%i" % (filename, start_line_index), context, pre_expand, ) return "snippet", (definition,) else: return "error", ("Invalid snippet type: '%s'" % snip, lines.line_index) def _parse_snippets_file(data, filename): """Parse 'data' assuming it is a snippet file. Yields events in the file. """ python_globals = defaultdict(list) lines = LineIterator(data) current_priority = 0 actions = {} context = None for line in lines: if not line.strip(): continue head, tail = head_tail(line) if head in ("snippet", "global"): snippet = _handle_snippet_or_global( filename, line, lines, python_globals, current_priority, actions, context, ) actions = {} context = None if snippet is not None: yield snippet elif head == "extends": yield handle_extends(tail, lines.line_index) elif head == "clearsnippets": yield "clearsnippets", (current_priority, tail.split()) elif head == "context": ( head, context, ) = handle_context(tail, lines.line_index) if head == "error": yield (head, tail) elif head == "priority": try: current_priority = int(tail.split()[0]) except (ValueError, IndexError): yield "error", ("Invalid priority %r" % tail, lines.line_index) elif head in ["pre_expand", "post_expand", "post_jump"]: head, tail = handle_action(head, tail, lines.line_index) if head == "error": yield (head, tail) else: (actions[head],) = tail elif head and not head.startswith("#"): yield "error", ("Invalid line %r" % line.rstrip(), lines.line_index) class UltiSnipsFileSource(SnippetFileSource): """Manages all snippets definitions found in rtp for ultisnips.""" def _get_all_snippet_files_for(self, ft): return find_all_snippet_files(ft) def _parse_snippet_file(self, filedata, filename): for event, data in _parse_snippets_file(filedata, filename): yield event, data
7,199
Python
.py
187
29.609626
88
0.588648
SirVer/ultisnips
7,501
688
112
GPL-3.0
9/5/2024, 5:11:34 PM (Europe/Amsterdam)
12,259
snipmate.py
SirVer_ultisnips/pythonx/UltiSnips/snippet/source/file/snipmate.py
#!/usr/bin/env python3 # encoding: utf-8 """Parses snipMate files.""" import os import glob from UltiSnips import vim_helper from UltiSnips.snippet.definition import SnipMateSnippetDefinition from UltiSnips.snippet.source.file.base import SnippetFileSource from UltiSnips.snippet.source.file.common import handle_extends, normalize_file_path from UltiSnips.text import LineIterator, head_tail def _splitall(path): """Split 'path' into all its components.""" # From http://my.safaribooksonline.com/book/programming/ # python/0596001673/files/pythoncook-chp-4-sect-16 allparts = [] while True: parts = os.path.split(path) if parts[0] == path: # sentinel for absolute paths allparts.insert(0, parts[0]) break elif parts[1] == path: # sentinel for relative paths allparts.insert(0, parts[1]) break else: path = parts[0] allparts.insert(0, parts[1]) return allparts def _snipmate_files_for(ft): """Returns all snipMate files we need to look at for 'ft'.""" if ft == "all": ft = "_" patterns = [ "%s.snippets" % ft, os.path.join(ft, "*.snippets"), os.path.join(ft, "*.snippet"), os.path.join(ft, "*/*.snippet"), ] ret = set() for rtp in vim_helper.eval("&runtimepath").split(","): path = normalize_file_path(os.path.expanduser(os.path.join(rtp, "snippets"))) for pattern in patterns: for fn in glob.glob(os.path.join(path, pattern)): ret.add(fn) return ret def _parse_snippet_file(content, full_filename): """Parses 'content' assuming it is a .snippet file and yields events.""" filename = full_filename[: -len(".snippet")] # strip extension segments = _splitall(filename) segments = segments[segments.index("snippets") + 1 :] assert len(segments) in (2, 3) trigger = segments[1] description = segments[2] if 2 < len(segments) else "" # Chomp \n if any. if content and content.endswith(os.linesep): content = content[: -len(os.linesep)] yield "snippet", ( SnipMateSnippetDefinition(trigger, content, description, full_filename), ) def _parse_snippet(line, lines, filename): """Parse a snippet defintions.""" start_line_index = lines.line_index trigger, description = head_tail(line[len("snippet") :].lstrip()) content = "" while True: next_line = lines.peek() if next_line is None: break if next_line.strip() and not next_line.startswith("\t"): break line = next(lines) if line[0] == "\t": line = line[1:] content += line content = content[:-1] # Chomp the last newline return ( "snippet", ( SnipMateSnippetDefinition( trigger, content, description, "%s:%i" % (filename, start_line_index) ), ), ) def _parse_snippets_file(data, filename): """Parse 'data' assuming it is a .snippets file. Yields events in the file. """ lines = LineIterator(data) for line in lines: if not line.strip(): continue head, tail = head_tail(line) if head == "extends": yield handle_extends(tail, lines.line_index) elif head in "snippet": snippet = _parse_snippet(line, lines, filename) if snippet is not None: yield snippet elif head and not head.startswith("#"): yield "error", ("Invalid line %r" % line.rstrip(), lines.line_index) class SnipMateFileSource(SnippetFileSource): """Manages all snipMate snippet definitions found in rtp.""" def _get_all_snippet_files_for(self, ft): return _snipmate_files_for(ft) def _parse_snippet_file(self, filedata, filename): if filename.lower().endswith("snippet"): for event, data in _parse_snippet_file(filedata, filename): yield event, data else: for event, data in _parse_snippets_file(filedata, filename): yield event, data
4,173
Python
.py
110
30.290909
85
0.619554
SirVer/ultisnips
7,501
688
112
GPL-3.0
9/5/2024, 5:11:34 PM (Europe/Amsterdam)
12,260
base.py
SirVer_ultisnips/pythonx/UltiSnips/snippet/source/file/base.py
#!/usr/bin/env python3 # encoding: utf-8 """Code to provide access to UltiSnips files from disk.""" from collections import defaultdict import os from UltiSnips import compatibility from UltiSnips import vim_helper from UltiSnips.error import PebkacError from UltiSnips.snippet.source.base import SnippetSource class SnippetSyntaxError(PebkacError): """Thrown when a syntax error is found in a file.""" def __init__(self, filename, line_index, msg): RuntimeError.__init__(self, "%s in %s:%d" % (msg, filename, line_index)) class SnippetFileSource(SnippetSource): """Base class that abstracts away 'extends' info and file hashes.""" def __init__(self): SnippetSource.__init__(self) def ensure(self, filetypes): if self.must_ensure: for ft in self.get_deep_extends(filetypes): if self._needs_update(ft): self._load_snippets_for(ft) self.must_ensure = False def refresh(self): self.__init__() def _get_all_snippet_files_for(self, ft): """Returns a set of all files that define snippets for 'ft'.""" raise NotImplementedError() def _parse_snippet_file(self, filedata, filename): """Parses 'filedata' as a snippet file and yields events.""" raise NotImplementedError() def _needs_update(self, ft): """Returns true if any files for 'ft' have changed and must be reloaded.""" return not (ft in self._snippets) def _load_snippets_for(self, ft): """Load all snippets for the given 'ft'.""" assert ft not in self._snippets for fn in self._get_all_snippet_files_for(ft): self._parse_snippets(ft, fn) # Now load for the parents for parent_ft in self.get_deep_extends([ft]): if parent_ft != ft and self._needs_update(parent_ft): self._load_snippets_for(parent_ft) def _parse_snippets(self, ft, filename): """Parse the 'filename' for the given 'ft'.""" with open(filename, "r", encoding="utf-8-sig") as to_read: file_data = to_read.read() self._snippets[ft] # Make sure the dictionary exists for event, data in self._parse_snippet_file(file_data, filename): if event == "error": msg, line_index = data filename = vim_helper.eval( """fnamemodify(%s, ":~:.")""" % vim_helper.escape(filename) ) raise SnippetSyntaxError(filename, line_index, msg) elif event == "clearsnippets": priority, triggers = data self._snippets[ft].clear_snippets(priority, triggers) elif event == "extends": # TODO(sirver): extends information is more global # than one snippet source. (filetypes,) = data self.update_extends(ft, filetypes) elif event == "snippet": (snippet,) = data self._snippets[ft].add_snippet(snippet) else: assert False, "Unhandled %s: %r" % (event, data) # precompile global snippets code for all snipepts we just sourced for snippet in self._snippets[ft]: snippet._precompile_globals()
3,319
Python
.py
72
36.083333
80
0.606502
SirVer/ultisnips
7,501
688
112
GPL-3.0
9/5/2024, 5:11:34 PM (Europe/Amsterdam)
12,261
common.py
SirVer_ultisnips/pythonx/UltiSnips/snippet/source/file/common.py
#!/usr/bin/env python3 # encoding: utf-8 """Common code for snipMate and UltiSnips snippet files.""" import os.path def normalize_file_path(path: str) -> str: """Calls normpath and normcase on path""" path = os.path.realpath(path) return os.path.normcase(os.path.normpath(path)) def handle_extends(tail, line_index): """Handles an extends line in a snippet.""" if tail: return "extends", ([p.strip() for p in tail.split(",")],) else: return "error", ("'extends' without file types", line_index) def handle_action(head, tail, line_index): if tail: action = tail.strip('"').replace(r"\"", '"').replace(r"\\\\", r"\\") return head, (action,) else: return "error", ("'{}' without specified action".format(head), line_index) def handle_context(tail, line_index): if tail: return "context", tail.strip('"').replace(r"\"", '"').replace(r"\\\\", r"\\") else: return "error", ("'context' without body", line_index)
1,012
Python
.py
25
35.24
85
0.623337
SirVer/ultisnips
7,501
688
112
GPL-3.0
9/5/2024, 5:11:34 PM (Europe/Amsterdam)
12,262
snippet_instance.py
SirVer_ultisnips/pythonx/UltiSnips/text_objects/snippet_instance.py
#!/usr/bin/env python3 # encoding: utf-8 """A Snippet instance is an instance of a Snippet Definition. That is, when the user expands a snippet, a SnippetInstance is created to keep track of the corresponding TextObjects. The Snippet itself is also a TextObject. """ from UltiSnips import vim_helper from UltiSnips.error import PebkacError from UltiSnips.position import Position, JumpDirection from UltiSnips.text_objects.base import EditableTextObject, NoneditableTextObject from UltiSnips.text_objects.tabstop import TabStop class SnippetInstance(EditableTextObject): """See module docstring.""" # pylint:disable=protected-access def __init__( self, snippet, parent, initial_text, start, end, visual_content, last_re, globals, context, _compiled_globals=None, ): if start is None: start = Position(0, 0) if end is None: end = Position(0, 0) self.snippet = snippet self._cts = 0 self.context = context self.locals = {"match": last_re, "context": context} self.globals = globals self._compiled_globals = _compiled_globals self.visual_content = visual_content self.current_placeholder = None EditableTextObject.__init__(self, parent, start, end, initial_text) def replace_initial_text(self, buf): """Puts the initial text of all text elements into Vim.""" def _place_initial_text(obj): """recurses on the children to do the work.""" obj.overwrite_with_initial_text(buf) if isinstance(obj, EditableTextObject): for child in obj._children: _place_initial_text(child) _place_initial_text(self) def replay_user_edits(self, cmds, ctab=None): """Replay the edits the user has done to keep endings of our Text objects in sync with reality.""" for cmd in cmds: self._do_edit(cmd, ctab) def update_textobjects(self, buf): """Update the text objects that should change automagically after the users edits have been replayed. This might also move the Cursor """ done = set() not_done = set() def _find_recursive(obj): """Finds all text objects and puts them into 'not_done'.""" cursorInsideLowest = None if isinstance(obj, EditableTextObject): if obj.start <= vim_helper.buf.cursor <= obj.end and not ( isinstance(obj, TabStop) and obj.number == 0 ): cursorInsideLowest = obj for child in obj._children: cursorInsideLowest = _find_recursive(child) or cursorInsideLowest not_done.add(obj) return cursorInsideLowest cursorInsideLowest = _find_recursive(self) if cursorInsideLowest is not None: vc = _VimCursor(cursorInsideLowest) counter = 10 while (done != not_done) and counter: # Order matters for python locals! for obj in sorted(not_done - done): if obj._update(done, buf): done.add(obj) counter -= 1 if not counter: raise PebkacError( "The snippets content did not converge: Check for Cyclic " "dependencies or random strings in your snippet. You can use " "'if not snip.c' to make sure to only expand random output " "once." ) if cursorInsideLowest is not None: vc.to_vim() cursorInsideLowest._del_child(vc) def select_next_tab(self, jump_direction: JumpDirection): """Selects the next tabstop in the direction of 'jump_direction'.""" if self._cts is None: return if jump_direction == JumpDirection.BACKWARD: current_tabstop_backup = self._cts res = self._get_prev_tab(self._cts) if res is None: self._cts = current_tabstop_backup return self._tabstops.get(self._cts, None) self._cts, ts = res return ts elif jump_direction == JumpDirection.FORWARD: res = self._get_next_tab(self._cts) if res is None: self._cts = None ts = self._get_tabstop(self, 0) if ts: return ts # TabStop 0 was deleted. It was probably killed through some # edit action. Recreate it at the end of us. start = Position(self.end.line, self.end.col) end = Position(self.end.line, self.end.col) return TabStop(self, 0, start, end) else: self._cts, ts = res return ts else: assert False, "Unknown JumpDirection: %r" % jump_direction def has_next_tab(self, jump_direction: JumpDirection): if jump_direction == JumpDirection.BACKWARD: return self._get_prev_tab(self._cts) is not None # There is always a next tabstop if we jump forward, since the snippet # instance is deleted once we reach tabstop 0. return True def _get_tabstop(self, requester, no): # SnippetInstances are completely self contained, therefore, we do not # need to ask our parent for Tabstops cached_parent = self._parent self._parent = None rv = EditableTextObject._get_tabstop(self, requester, no) self._parent = cached_parent return rv def get_tabstops(self): return self._tabstops class _VimCursor(NoneditableTextObject): """Helper class to keep track of the Vim Cursor when text objects expand and move.""" def __init__(self, parent): NoneditableTextObject.__init__( self, parent, vim_helper.buf.cursor, vim_helper.buf.cursor, tiebreaker=Position(-1, -1), ) def to_vim(self): """Moves the cursor in the Vim to our position.""" assert self._start == self._end vim_helper.buf.cursor = self._start
6,302
Python
.py
154
30.357143
85
0.59722
SirVer/ultisnips
7,501
688
112
GPL-3.0
9/5/2024, 5:11:34 PM (Europe/Amsterdam)
12,263
mirror.py
SirVer_ultisnips/pythonx/UltiSnips/text_objects/mirror.py
#!/usr/bin/env python3 # encoding: utf-8 """A Mirror object contains the same text as its related tabstop.""" from UltiSnips.text_objects.base import NoneditableTextObject class Mirror(NoneditableTextObject): """See module docstring.""" def __init__(self, parent, tabstop, token): NoneditableTextObject.__init__(self, parent, token) self._ts = tabstop def _update(self, done, buf): if self._ts.is_killed: self.overwrite(buf, "") self._parent._del_child(self) # pylint:disable=protected-access return True if self._ts not in done: return False self.overwrite(buf, self._get_text()) return True def _get_text(self): """Returns the text used for mirroring. Overwritten by base classes. """ return self._ts.current_text
873
Python
.py
23
30.173913
76
0.637232
SirVer/ultisnips
7,501
688
112
GPL-3.0
9/5/2024, 5:11:34 PM (Europe/Amsterdam)
12,264
choices.py
SirVer_ultisnips/pythonx/UltiSnips/text_objects/choices.py
#!/usr/bin/env python3 # encoding: utf-8 """Choices are enumeration values you can choose, by selecting index number. It is a special TabStop, its content are taken literally, thus said, they will not be parsed recursively. """ from UltiSnips import vim_helper from UltiSnips.position import Position from UltiSnips.text_objects.tabstop import TabStop from UltiSnips.snippet.parsing.lexer import ChoicesToken class Choices(TabStop): """See module docstring.""" def __init__(self, parent, token: ChoicesToken): self._number = token.number # for TabStop property 'number' self._initial_text = token.initial_text # empty choice will be discarded self._choice_list = [s for s in token.choice_list if len(s) > 0] self._done = False self._input_chars = list(self._initial_text) self._has_been_updated = False TabStop.__init__(self, parent, token) def _get_choices_placeholder(self) -> str: # prefix choices with index number # e.g. 'a,b,c' -> '1.a|2.b|3.c' text_segs = [] index = 1 for choice in self._choice_list: text_segs.append("%s.%s" % (index, choice)) index += 1 text = "|".join(text_segs) return text def _update(self, done, buf): if self._done: return True # expand initial text with select prefix number, only once if not self._has_been_updated: # '${1:||}' is not valid choice, should be downgraded to plain tabstop are_choices_valid = len(self._choice_list) > 0 if are_choices_valid: text = self._get_choices_placeholder() self.overwrite(buf, text) else: self._done = True self._has_been_updated = True return True def _do_edit(self, cmd, ctab=None): if self._done: # do as what parent class do TabStop._do_edit(self, cmd, ctab) return ctype, line, col, cmd_text = cmd cursor = vim_helper.get_cursor_pos() [buf_num, cursor_line] = map(int, cursor[0:2]) # trying to get what user inputted in current buffer if ctype == "I": self._input_chars.append(cmd_text) elif ctype == "D": line_text = vim_helper.buf[cursor_line - 1] self._input_chars = list(line_text[self._start.col : col]) inputted_text = "".join(self._input_chars) if not self._input_chars: return # if there are more than 9 selection candidates, # may need to wait for 2 inputs to determine selection number is_all_digits = True has_selection_terminator = False # input string sub string of pure digits inputted_text_for_num = inputted_text for [i, s] in enumerate(self._input_chars): if s == " ": # treat space as a terminator for selection has_selection_terminator = True inputted_text_for_num = inputted_text[0:i] elif not s.isdigit(): is_all_digits = False should_continue_input = False if is_all_digits or has_selection_terminator: index_strs = [ str(index) for index in list(range(1, len(self._choice_list) + 1)) ] matched_index_strs = list( filter(lambda s: s.startswith(inputted_text_for_num), index_strs) ) remained_choice_list = [] if len(matched_index_strs) == 0: remained_choice_list = [] elif has_selection_terminator: if inputted_text_for_num: num = int(inputted_text_for_num) remained_choice_list = list(self._choice_list)[num - 1 : num] elif len(matched_index_strs) == 1: num = int(inputted_text_for_num) remained_choice_list = list(self._choice_list)[num - 1 : num] else: should_continue_input = True else: remained_choice_list = [] if should_continue_input: # will wait for further input return buf = vim_helper.buf if len(remained_choice_list) == 0: # no matched choice, should quit selection and go on with inputted text overwrite_text = inputted_text_for_num self._done = True elif len(remained_choice_list) == 1: # only one match matched_choice = remained_choice_list[0] overwrite_text = matched_choice self._done = True if overwrite_text is not None: old_end_col = self._end.col # change _end.col, thus `overwrite` won't alter texts after this tabstop displayed_text_end_col = self._start.col + len(inputted_text) self._end.col = displayed_text_end_col self.overwrite(buf, overwrite_text) # notify all tabstops those in the same line and after this to adjust their positions pivot = Position(line, old_end_col) diff_col = displayed_text_end_col - old_end_col self._parent._child_has_moved( self._parent.children.index(self), pivot, Position(0, diff_col) ) vim_helper.set_cursor_from_pos([buf_num, cursor_line, self._end.col + 1]) def __repr__(self): return "Choices(%s,%r->%r,%r)" % ( self._number, self._start, self._end, self._initial_text, )
5,621
Python
.py
128
32.867188
105
0.578014
SirVer/ultisnips
7,501
688
112
GPL-3.0
9/5/2024, 5:11:34 PM (Europe/Amsterdam)
12,265
tabstop.py
SirVer_ultisnips/pythonx/UltiSnips/text_objects/tabstop.py
#!/usr/bin/env python3 # encoding: utf-8 """This is the most important TextObject. A TabStop is were the cursor comes to rest when the user taps through the Snippet. """ from UltiSnips.text_objects.base import EditableTextObject class TabStop(EditableTextObject): """See module docstring.""" def __init__(self, parent, token, start=None, end=None): if start is not None: self._number = token EditableTextObject.__init__(self, parent, start, end) else: self._number = token.number EditableTextObject.__init__(self, parent, token) parent._tabstops[self._number] = self # pylint:disable=protected-access @property def number(self): """The tabstop number.""" return self._number @property def is_killed(self): """True if this tabstop has been typed over and the user therefore can no longer jump to it.""" return self._parent is None def __repr__(self): try: text = self.current_text except IndexError: text = "<err>" return "TabStop(%s,%r->%r,%r)" % (self.number, self._start, self._end, text)
1,191
Python
.py
32
30
84
0.631533
SirVer/ultisnips
7,501
688
112
GPL-3.0
9/5/2024, 5:11:34 PM (Europe/Amsterdam)
12,266
viml_code.py
SirVer_ultisnips/pythonx/UltiSnips/text_objects/viml_code.py
#!/usr/bin/env python3 # encoding: utf-8 """Implements `!v ` VimL interpolation.""" from UltiSnips import vim_helper from UltiSnips.text_objects.base import NoneditableTextObject class VimLCode(NoneditableTextObject): """See module docstring.""" def __init__(self, parent, token): self._code = token.code.replace("\\`", "`").strip() NoneditableTextObject.__init__(self, parent, token) def _update(self, done, buf): self.overwrite(buf, vim_helper.eval(self._code)) return True
528
Python
.py
13
35.615385
61
0.688363
SirVer/ultisnips
7,501
688
112
GPL-3.0
9/5/2024, 5:11:34 PM (Europe/Amsterdam)
12,267
escaped_char.py
SirVer_ultisnips/pythonx/UltiSnips/text_objects/escaped_char.py
#!/usr/bin/env python3 # encoding: utf-8 """See module comment.""" from UltiSnips.text_objects.base import NoneditableTextObject class EscapedChar(NoneditableTextObject): r""" This class is a escape char like \$. It is handled in a text object to make sure that siblings are correctly moved after replacing the text. This is a base class without functionality just to mark it in the code. """
420
Python
.py
10
38.4
80
0.75495
SirVer/ultisnips
7,501
688
112
GPL-3.0
9/5/2024, 5:11:34 PM (Europe/Amsterdam)
12,268
__init__.py
SirVer_ultisnips/pythonx/UltiSnips/text_objects/__init__.py
#!/usr/bin/env python3 # encoding: utf-8 """Public facing classes for TextObjects.""" from UltiSnips.text_objects.escaped_char import EscapedChar from UltiSnips.text_objects.mirror import Mirror from UltiSnips.text_objects.python_code import PythonCode from UltiSnips.text_objects.shell_code import ShellCode from UltiSnips.text_objects.snippet_instance import SnippetInstance from UltiSnips.text_objects.tabstop import TabStop from UltiSnips.text_objects.transformation import Transformation from UltiSnips.text_objects.viml_code import VimLCode from UltiSnips.text_objects.visual import Visual from UltiSnips.text_objects.choices import Choices
649
Python
.py
13
48.769231
67
0.862776
SirVer/ultisnips
7,501
688
112
GPL-3.0
9/5/2024, 5:11:34 PM (Europe/Amsterdam)
12,269
base.py
SirVer_ultisnips/pythonx/UltiSnips/text_objects/base.py
#!/usr/bin/env python3 # encoding: utf-8 """Base classes for all text objects.""" from UltiSnips import vim_helper from UltiSnips.position import Position def _calc_end(text, start): """Calculate the end position of the 'text' starting at 'start.""" if len(text) == 1: new_end = start + Position(0, len(text[0])) else: new_end = Position(start.line + len(text) - 1, len(text[-1])) return new_end def _replace_text(buf, start, end, text): """Copy the given text to the current buffer, overwriting the span 'start' to 'end'.""" lines = text.split("\n") new_end = _calc_end(lines, start) before = buf[start.line][: start.col] after = buf[end.line][end.col :] new_lines = [] if len(lines): new_lines.append(before + lines[0]) new_lines.extend(lines[1:]) new_lines[-1] += after buf[start.line : end.line + 1] = new_lines return new_end # These classes use their subclasses a lot and we really do not want to expose # their functions more globally. # pylint: disable=protected-access class TextObject: """Represents any object in the text that has a span in any ways.""" def __init__( self, parent, token_or_start, end=None, initial_text="", tiebreaker=None ): self._parent = parent if end is not None: # Took 4 arguments self._start = token_or_start self._end = end self._initial_text = initial_text else: # Initialize from token self._start = token_or_start.start self._end = token_or_start.end self._initial_text = token_or_start.initial_text self._tiebreaker = tiebreaker or Position(self._start.line, self._end.line) if parent is not None: parent._add_child(self) def _move(self, pivot, diff): """Move this object by 'diff' while 'pivot' is the point of change.""" self._start.move(pivot, diff) self._end.move(pivot, diff) def __lt__(self, other): me_tuple = ( self.start.line, self.start.col, self._tiebreaker.line, self._tiebreaker.col, ) other_tuple = ( other._start.line, other._start.col, other._tiebreaker.line, other._tiebreaker.col, ) return me_tuple < other_tuple def __le__(self, other): me_tuple = ( self._start.line, self._start.col, self._tiebreaker.line, self._tiebreaker.col, ) other_tuple = ( other._start.line, other._start.col, other._tiebreaker.line, other._tiebreaker.col, ) return me_tuple <= other_tuple def __repr__(self): ct = "" try: ct = self.current_text except IndexError: ct = "<err>" return "%s(%r->%r,%r)" % (self.__class__.__name__, self._start, self._end, ct) @property def current_text(self): """The current text of this object.""" if self._start.line == self._end.line: return vim_helper.buf[self._start.line][self._start.col : self._end.col] else: lines = [vim_helper.buf[self._start.line][self._start.col :]] lines.extend(vim_helper.buf[self._start.line + 1 : self._end.line]) lines.append(vim_helper.buf[self._end.line][: self._end.col]) return "\n".join(lines) @property def start(self): """The start position.""" return self._start @property def end(self): """The end position.""" return self._end def overwrite_with_initial_text(self, buf): self.overwrite(buf, self._initial_text) def overwrite(self, buf, gtext): """Overwrite the text of this object in the Vim Buffer and update its length information. If 'gtext' is None use the initial text of this object. """ # We explicitly do not want to move our children around here as we # either have non or we are replacing text initially which means we do # not want to mess with their positions if self.current_text == gtext: return old_end = self._end self._end = _replace_text(buf, self._start, self._end, gtext) if self._parent: self._parent._child_has_moved( self._parent._children.index(self), min(old_end, self._end), self._end.delta(old_end), ) def _update(self, done, buf): """Update this object inside 'buf' which is a list of lines. Return False if you need to be called again for this edit cycle. Otherwise return True. """ raise NotImplementedError("Must be implemented by subclasses.") class EditableTextObject(TextObject): """This base class represents any object in the text that can be changed by the user.""" def __init__(self, *args, **kwargs): TextObject.__init__(self, *args, **kwargs) self._children = [] self._tabstops = {} ############## # Properties # ############## @property def children(self): """List of all children.""" return self._children @property def _editable_children(self): """List of all children that are EditableTextObjects.""" return [ child for child in self._children if isinstance(child, EditableTextObject) ] #################### # Public Functions # #################### def find_parent_for_new_to(self, pos): """Figure out the parent object for something at 'pos'.""" for children in self._editable_children: if children._start <= pos < children._end: return children.find_parent_for_new_to(pos) if children._start == pos and pos == children._end: return children.find_parent_for_new_to(pos) return self ############################### # Private/Protected functions # ############################### def _do_edit(self, cmd, ctab=None): """Apply the edit 'cmd' to this object.""" ctype, line, col, text = cmd assert ("\n" not in text) or (text == "\n") pos = Position(line, col) to_kill = set() new_cmds = [] for child in self._children: if ctype == "I": # Insertion if child._start < pos < Position( child._end.line, child._end.col ) and isinstance(child, NoneditableTextObject): to_kill.add(child) new_cmds.append(cmd) break elif (child._start <= pos <= child._end) and isinstance( child, EditableTextObject ): if pos == child.end and not child.children: try: if ctab.number != child.number: continue except AttributeError: pass child._do_edit(cmd, ctab) return else: # Deletion delend = ( pos + Position(0, len(text)) if text != "\n" else Position(line + 1, 0) ) if (child._start <= pos < child._end) and ( child._start < delend <= child._end ): # this edit command is completely for the child if isinstance(child, NoneditableTextObject): to_kill.add(child) new_cmds.append(cmd) break else: child._do_edit(cmd, ctab) return elif ( pos < child._start and child._end <= delend and child.start < delend ) or (pos <= child._start and child._end < delend): # Case: this deletion removes the child to_kill.add(child) new_cmds.append(cmd) break elif pos < child._start and (child._start < delend <= child._end): # Case: partially for us, partially for the child my_text = text[: (child._start - pos).col] c_text = text[(child._start - pos).col :] new_cmds.append((ctype, line, col, my_text)) new_cmds.append((ctype, line, col, c_text)) break elif delend >= child._end and (child._start <= pos < child._end): # Case: partially for us, partially for the child c_text = text[(child._end - pos).col :] my_text = text[: (child._end - pos).col] new_cmds.append((ctype, line, col, c_text)) new_cmds.append((ctype, line, col, my_text)) break for child in to_kill: self._del_child(child) if len(new_cmds): for child in new_cmds: self._do_edit(child) return # We have to handle this ourselves delta = Position(1, 0) if text == "\n" else Position(0, len(text)) if ctype == "D": # Makes no sense to delete in empty textobject if self._start == self._end: return delta.line *= -1 delta.col *= -1 pivot = Position(line, col) idx = -1 for cidx, child in enumerate(self._children): if child._start < pivot <= child._end: idx = cidx self._child_has_moved(idx, pivot, delta) def _move(self, pivot, diff): TextObject._move(self, pivot, diff) for child in self._children: child._move(pivot, diff) def _child_has_moved(self, idx, pivot, diff): """Called when a the child with 'idx' has moved behind 'pivot' by 'diff'.""" self._end.move(pivot, diff) for child in self._children[idx + 1 :]: child._move(pivot, diff) if self._parent: self._parent._child_has_moved( self._parent._children.index(self), pivot, diff ) def _get_next_tab(self, number): """Returns the next tabstop after 'number'.""" if not len(self._tabstops.keys()): return tno_max = max(self._tabstops.keys()) possible_sol = [] i = number + 1 while i <= tno_max: if i in self._tabstops: possible_sol.append((i, self._tabstops[i])) break i += 1 child = [c._get_next_tab(number) for c in self._editable_children] child = [c for c in child if c] possible_sol += child if not len(possible_sol): return None return min(possible_sol) def _get_prev_tab(self, number): """Returns the previous tabstop before 'number'.""" if not len(self._tabstops.keys()): return tno_min = min(self._tabstops.keys()) possible_sol = [] i = number - 1 while i >= tno_min and i > 0: if i in self._tabstops: possible_sol.append((i, self._tabstops[i])) break i -= 1 child = [c._get_prev_tab(number) for c in self._editable_children] child = [c for c in child if c] possible_sol += child if not len(possible_sol): return None return max(possible_sol) def _get_tabstop(self, requester, number): """Returns the tabstop 'number'. 'requester' is the class that is interested in this. """ if number in self._tabstops: return self._tabstops[number] for child in self._editable_children: if child is requester: continue rv = child._get_tabstop(self, number) if rv is not None: return rv if self._parent and requester is not self._parent: return self._parent._get_tabstop(self, number) def _update(self, done, buf): if all((child in done) for child in self._children): assert self not in done done.add(self) return True def _add_child(self, child): """Add 'child' as a new child of this text object.""" self._children.append(child) self._children.sort() def _del_child(self, child): """Delete this 'child'.""" child._parent = None self._children.remove(child) # If this is a tabstop, delete it. Might have been deleted already if # it was nested. try: del self._tabstops[child.number] except (AttributeError, KeyError): pass class NoneditableTextObject(TextObject): """All passive text objects that the user can't edit by hand.""" def _update(self, done, buf): return True
13,258
Python
.py
334
28.362275
88
0.53256
SirVer/ultisnips
7,501
688
112
GPL-3.0
9/5/2024, 5:11:34 PM (Europe/Amsterdam)
12,270
shell_code.py
SirVer_ultisnips/pythonx/UltiSnips/text_objects/shell_code.py
#!/usr/bin/env python3 # encoding: utf-8 """Implements `echo hi` shell code interpolation.""" import os import platform from subprocess import Popen, PIPE import stat import tempfile from UltiSnips.text_objects.base import NoneditableTextObject def _chomp(string): """Rather than rstrip(), remove only the last newline and preserve purposeful whitespace.""" if len(string) and string[-1] == "\n": string = string[:-1] if len(string) and string[-1] == "\r": string = string[:-1] return string def _run_shell_command(cmd, tmpdir): """Write the code to a temporary file.""" cmdsuf = "" if platform.system() == "Windows": # suffix required to run command on windows cmdsuf = ".bat" # turn echo off cmd = "@echo off\r\n" + cmd handle, path = tempfile.mkstemp(text=True, dir=tmpdir, suffix=cmdsuf) os.write(handle, cmd.encode("utf-8")) os.close(handle) os.chmod(path, stat.S_IRWXU) # Execute the file and read stdout proc = Popen(path, shell=True, stdout=PIPE, stderr=PIPE) proc.wait() stdout, _ = proc.communicate() os.unlink(path) return _chomp(stdout.decode("utf-8")) def _get_tmp(): """Find an executable tmp directory.""" userdir = os.path.expanduser("~") for testdir in [ tempfile.gettempdir(), os.path.join(userdir, ".cache"), os.path.join(userdir, ".tmp"), userdir, ]: if ( not os.path.exists(testdir) or not _run_shell_command("echo success", testdir) == "success" ): continue return testdir return "" class ShellCode(NoneditableTextObject): """See module docstring.""" def __init__(self, parent, token): NoneditableTextObject.__init__(self, parent, token) self._code = token.code.replace("\\`", "`") self._tmpdir = _get_tmp() def _update(self, done, buf): if not self._tmpdir: output = "Unable to find executable tmp directory, check noexec on /tmp" else: output = _run_shell_command(self._code, self._tmpdir) self.overwrite(buf, output) self._parent._del_child(self) # pylint:disable=protected-access return True
2,266
Python
.py
65
28.523077
84
0.628545
SirVer/ultisnips
7,501
688
112
GPL-3.0
9/5/2024, 5:11:34 PM (Europe/Amsterdam)
12,271
transformation.py
SirVer_ultisnips/pythonx/UltiSnips/text_objects/transformation.py
#!/usr/bin/env python3 # encoding: utf-8 """Implements TabStop transformations.""" import re import sys from UltiSnips.text import unescape, fill_in_whitespace from UltiSnips.text_objects.mirror import Mirror def _find_closing_brace(string, start_pos): """Finds the corresponding closing brace after start_pos.""" bracks_open = 1 escaped = False for idx, char in enumerate(string[start_pos:]): if char == "(": if not escaped: bracks_open += 1 elif char == ")": if not escaped: bracks_open -= 1 if not bracks_open: return start_pos + idx + 1 if char == "\\": escaped = not escaped else: escaped = False def _split_conditional(string): """Split the given conditional 'string' into its arguments.""" bracks_open = 0 args = [] carg = "" escaped = False for idx, char in enumerate(string): if char == "(": if not escaped: bracks_open += 1 elif char == ")": if not escaped: bracks_open -= 1 elif char == ":" and not bracks_open and not escaped: args.append(carg) carg = "" escaped = False continue carg += char if char == "\\": escaped = not escaped else: escaped = False args.append(carg) return args def _replace_conditional(match, string): """Replaces a conditional match in a transformation.""" conditional_match = _CONDITIONAL.search(string) while conditional_match: start = conditional_match.start() end = _find_closing_brace(string, start + 4) args = _split_conditional(string[start + 4 : end - 1]) rv = "" if match.group(int(conditional_match.group(1))): rv = unescape(_replace_conditional(match, args[0])) elif len(args) > 1: rv = unescape(_replace_conditional(match, args[1])) string = string[:start] + rv + string[end:] conditional_match = _CONDITIONAL.search(string) return string _ONE_CHAR_CASE_SWITCH = re.compile(r"\\([ul].)", re.DOTALL) _LONG_CASEFOLDINGS = re.compile(r"\\([UL].*?)\\E", re.DOTALL) _DOLLAR = re.compile(r"\$(\d+)", re.DOTALL) _CONDITIONAL = re.compile(r"\(\?(\d+):", re.DOTALL) class _CleverReplace: """Mimics TextMates replace syntax.""" def __init__(self, expression): self._expression = expression def replace(self, match): """Replaces 'match' through the correct replacement string.""" transformed = self._expression # Replace all $? with capture groups transformed = _DOLLAR.subn(lambda m: match.group(int(m.group(1))), transformed)[ 0 ] # Replace Case switches def _one_char_case_change(match): """Replaces one character case changes.""" if match.group(1)[0] == "u": return match.group(1)[-1].upper() else: return match.group(1)[-1].lower() transformed = _ONE_CHAR_CASE_SWITCH.subn(_one_char_case_change, transformed)[0] def _multi_char_case_change(match): """Replaces multi character case changes.""" if match.group(1)[0] == "U": return match.group(1)[1:].upper() else: return match.group(1)[1:].lower() transformed = _LONG_CASEFOLDINGS.subn(_multi_char_case_change, transformed)[0] transformed = _replace_conditional(match, transformed) return unescape(fill_in_whitespace(transformed)) # flag used to display only one time the lack of unidecode UNIDECODE_ALERT_RAISED = False class TextObjectTransformation: """Base class for Transformations and ${VISUAL}.""" def __init__(self, token): self._convert_to_ascii = False self._find = None if token.search is None: return flags = 0 self._match_this_many = 1 if token.options: if "g" in token.options: self._match_this_many = 0 if "i" in token.options: flags |= re.IGNORECASE if "m" in token.options: flags |= re.MULTILINE if "a" in token.options: self._convert_to_ascii = True self._find = re.compile(token.search, flags | re.DOTALL) self._replace = _CleverReplace(token.replace) def _transform(self, text): """Do the actual transform on the given text.""" global UNIDECODE_ALERT_RAISED # pylint:disable=global-statement if self._convert_to_ascii: try: import unidecode text = unidecode.unidecode(text) except Exception: # pylint:disable=broad-except if UNIDECODE_ALERT_RAISED == False: UNIDECODE_ALERT_RAISED = True sys.stderr.write( "Please install unidecode python package in order to " "be able to make ascii conversions.\n" ) if self._find is None: return text return self._find.subn(self._replace.replace, text, self._match_this_many)[0] class Transformation(Mirror, TextObjectTransformation): """See module docstring.""" def __init__(self, parent, ts, token): Mirror.__init__(self, parent, ts, token) TextObjectTransformation.__init__(self, token) def _get_text(self): return self._transform(self._ts.current_text)
5,641
Python
.py
142
30.021127
88
0.582281
SirVer/ultisnips
7,501
688
112
GPL-3.0
9/5/2024, 5:11:34 PM (Europe/Amsterdam)
12,272
visual.py
SirVer_ultisnips/pythonx/UltiSnips/text_objects/visual.py
#!/usr/bin/env python3 # encoding: utf-8 """A ${VISUAL} placeholder that will use the text that was last visually selected and insert it here. If there was no text visually selected, this will be the empty string. """ import re import textwrap from UltiSnips.indent_util import IndentUtil from UltiSnips.text_objects.transformation import TextObjectTransformation from UltiSnips.text_objects.base import NoneditableTextObject _REPLACE_NON_WS = re.compile(r"[^ \t]") class Visual(NoneditableTextObject, TextObjectTransformation): """See module docstring.""" def __init__(self, parent, token): # Find our containing snippet for visual_content snippet = parent while snippet: try: self._text = snippet.visual_content.text self._mode = snippet.visual_content.mode break except AttributeError: snippet = snippet._parent # pylint:disable=protected-access if not self._text: self._text = token.alternative_text self._mode = "v" NoneditableTextObject.__init__(self, parent, token) TextObjectTransformation.__init__(self, token) def _update(self, done, buf): if self._mode == "v": # Normal selection. text = self._text else: # Block selection or line selection. text_before = buf[self.start.line][: self.start.col] indent = _REPLACE_NON_WS.sub(" ", text_before) iu = IndentUtil() indent = iu.indent_to_spaces(indent) indent = iu.spaces_to_indent(indent) text = "" for idx, line in enumerate(textwrap.dedent(self._text).splitlines(True)): if idx != 0: text += indent text += line text = text[:-1] # Strip final '\n' text = self._transform(text) self.overwrite(buf, text) self._parent._del_child(self) # pylint:disable=protected-access return True
2,037
Python
.py
48
33.229167
85
0.623797
SirVer/ultisnips
7,501
688
112
GPL-3.0
9/5/2024, 5:11:34 PM (Europe/Amsterdam)
12,273
python_code.py
SirVer_ultisnips/pythonx/UltiSnips/text_objects/python_code.py
#!/usr/bin/env python3 # encoding: utf-8 """Implements `!p ` interpolation.""" import os from collections import namedtuple from UltiSnips import vim_helper from UltiSnips.indent_util import IndentUtil from UltiSnips.text_objects.base import NoneditableTextObject from UltiSnips.vim_state import _Placeholder import UltiSnips.snippet_manager # We'll end up compiling the global snippets for every snippet so # caching compile() should pay off from functools import lru_cache @lru_cache(maxsize=None) def cached_compile(*args): return compile(*args) class _Tabs: """Allows access to tabstop content via t[] inside of python code.""" def __init__(self, to): self._to = to def __getitem__(self, no): ts = self._to._get_tabstop(self._to, int(no)) # pylint:disable=protected-access if ts is None: return "" return ts.current_text def __setitem__(self, no, value): ts = self._to._get_tabstop(self._to, int(no)) # pylint:disable=protected-access if ts is None: return # TODO(sirver): The buffer should be passed into the object on construction. ts.overwrite(vim_helper.buf, value) _VisualContent = namedtuple("_VisualContent", ["mode", "text"]) class SnippetUtilForAction(dict): def __init__(self, *args, **kwargs): super(SnippetUtilForAction, self).__init__(*args, **kwargs) self.__dict__ = self def expand_anon(self, *args, **kwargs): UltiSnips.snippet_manager.UltiSnips_Manager.expand_anon(*args, **kwargs) self.cursor.preserve() class SnippetUtil: """Provides easy access to indentation, etc. This is the 'snip' object in python code. """ def __init__(self, initial_indent, vmode, vtext, context, parent): self._ind = IndentUtil() self._visual = _VisualContent(vmode, vtext) self._initial_indent = self._ind.indent_to_spaces(initial_indent) self._reset("") self._context = context self._start = parent.start self._end = parent.end self._parent = parent def _reset(self, cur): """Gets the snippet ready for another update. :cur: the new value for c. """ self._ind.reset() self._cur = cur self._rv = "" self._changed = False self.reset_indent() def shift(self, amount=1): """Shifts the indentation level. Note that this uses the shiftwidth because thats what code formatters use. :amount: the amount by which to shift. """ self.indent += " " * self._ind.shiftwidth * amount def unshift(self, amount=1): """Unshift the indentation level. Note that this uses the shiftwidth because thats what code formatters use. :amount: the amount by which to unshift. """ by = -self._ind.shiftwidth * amount try: self.indent = self.indent[:by] except IndexError: self.indent = "" def mkline(self, line="", indent=None): """Creates a properly set up line. :line: the text to add :indent: the indentation to have at the beginning if None, it uses the default amount """ if indent is None: indent = self.indent # this deals with the fact that the first line is # already properly indented if "\n" not in self._rv: try: indent = indent[len(self._initial_indent) :] except IndexError: indent = "" indent = self._ind.spaces_to_indent(indent) return indent + line def reset_indent(self): """Clears the indentation.""" self.indent = self._initial_indent # Utility methods @property def fn(self): # pylint:disable=no-self-use,invalid-name """The filename.""" return vim_helper.eval('expand("%:t")') or "" @property def basename(self): # pylint:disable=no-self-use """The filename without extension.""" return vim_helper.eval('expand("%:t:r")') or "" @property def ft(self): # pylint:disable=invalid-name """The filetype.""" return self.opt("&filetype", "") @property def rv(self): # pylint:disable=invalid-name """The return value. The text to insert at the location of the placeholder. """ return self._rv @rv.setter def rv(self, value): # pylint:disable=invalid-name """See getter.""" self._changed = True self._rv = value @property def _rv_changed(self): """True if rv has changed.""" return self._changed @property def c(self): # pylint:disable=invalid-name """The current text of the placeholder.""" return self._cur @property def v(self): # pylint:disable=invalid-name """Content of visual expansions.""" return self._visual @property def p(self): if self._parent.current_placeholder: return self._parent.current_placeholder return _Placeholder("", 0, 0) @property def context(self): return self._context def opt(self, option, default=None): # pylint:disable=no-self-use """Gets a Vim variable.""" if vim_helper.eval("exists('%s')" % option) == "1": try: return vim_helper.eval(option) except vim_helper.error: pass return default def __add__(self, value): """Appends the given line to rv using mkline.""" self.rv += "\n" # pylint:disable=invalid-name self.rv += self.mkline(value) return self def __lshift__(self, other): """Same as unshift.""" self.unshift(other) def __rshift__(self, other): """Same as shift.""" self.shift(other) @property def snippet_start(self): """ Returns start of the snippet in format (line, column). """ return self._start @property def snippet_end(self): """ Returns end of the snippet in format (line, column). """ return self._end @property def buffer(self): return vim_helper.buf class PythonCode(NoneditableTextObject): """See module docstring.""" def __init__(self, parent, token): # Find our containing snippet for snippet local data snippet = parent while snippet: try: self._locals = snippet.locals text = snippet.visual_content.text mode = snippet.visual_content.mode context = snippet.context break except AttributeError: snippet = snippet._parent # pylint:disable=protected-access self._snip = SnippetUtil(token.indent, mode, text, context, snippet) self._codes = ( "import re, os, vim, string, random\n" + "\n".join(snippet.globals.get("!p", [])).replace("\r\n", "\n"), token.code.replace("\\`", "`"), ) self._compiled_codes = ( snippet._compiled_globals or cached_compile(self._codes[0], "<exec-globals>", "exec"), cached_compile( token.code.replace("\\`", "`"), "<exec-interpolation-code>", "exec" ), ) NoneditableTextObject.__init__(self, parent, token) def _update(self, done, buf): path = vim_helper.eval('expand("%")') or "" ct = self.current_text self._locals.update( { "t": _Tabs(self._parent), "fn": os.path.basename(path), "path": path, "cur": ct, "res": ct, "snip": self._snip, } ) self._snip._reset(ct) # pylint:disable=protected-access for code, compiled_code in zip(self._codes, self._compiled_codes): try: exec(compiled_code, self._locals) # pylint:disable=exec-used except Exception as exception: exception.snippet_code = code raise rv = str( self._snip.rv if self._snip._rv_changed else self._locals["res"] ) # pylint:disable=protected-access if ct != rv: self.overwrite(buf, rv) return False return True
8,507
Python
.py
230
27.934783
88
0.582217
SirVer/ultisnips
7,501
688
112
GPL-3.0
9/5/2024, 5:11:34 PM (Europe/Amsterdam)
12,274
ultisnips.py
SirVer_ultisnips/rplugin/python3/deoplete/sources/ultisnips.py
from deoplete.base.source import Base class Source(Base): def __init__(self, vim): Base.__init__(self, vim) self.name = "ultisnips" self.mark = "[US]" self.rank = 8 self.is_volatile = True def gather_candidates(self, context): suggestions = [] snippets = self.vim.eval("UltiSnips#SnippetsInCurrentScope()") for trigger in snippets: suggestions.append( { "word": trigger, "menu": self.mark + " " + snippets.get(trigger, ""), "dup": 1, "kind": "snippet", } ) return suggestions
696
Python
.py
21
21.666667
72
0.493294
SirVer/ultisnips
7,501
688
112
GPL-3.0
9/5/2024, 5:11:34 PM (Europe/Amsterdam)
12,275
setup.py
gaubert_gmvault/setup.py
""" Gmvault: a tool to backup and restore your gmail account. Copyright (C) <2011-2012> <guillaume Aubert (guillaume dot aubert at gmail do com)> This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. """ import os from setuptools import setup #function to find the version in gmv_cmd def find_version(path): with open(path, 'r') as f: for line in f: index = line.find('GMVAULT_VERSION = "') if index > -1: print(line[index+19:-2]) res = line[index+19:-2] return res.strip() raise Exception("Cannot find GMVAULT_VERSION in %s\n" % path) path = os.path.join(os.path.dirname(__file__), './src/gmv/gmvault_utils.py') print("PATH = %s\n" % path) version = find_version(os.path.join(os.path.dirname(__file__), './src/gmv/gmvault_utils.py')) print("Gmvault version = %s\n" % version) README = os.path.join(os.path.dirname(__file__), './README.md') if os.path.exists(README): with open(README, 'r') as f: long_description = f.read() + 'nn' else: long_description = 'Gmvault' setup(name='gmvault', version=version, description=("Tool to backup and restore your Gmail emails at will. http://www.gmvault.org for more info"), long_description=long_description, classifiers=[ "Programming Language :: Python", "License :: OSI Approved :: GNU Affero General Public License v3", "Topic :: Communications :: Email", "Topic :: Communications :: Email :: Post-Office :: IMAP", ], keywords='gmail, email, backup, gmail backup, imap', author='Guillaume Aubert', author_email='guillaume.aubert@gmail.com', url='http://www.gmvault.org', license='AGPLv3', packages=['gmv','gmv.conf', 'gmv.conf.utils'], package_dir = {'gmv': './src/gmv'}, scripts=['./etc/scripts/gmvault'], package_data={'': ['release-note.txt']}, include_package_data=True, #install_requires=['argparse', 'Logbook==0.4.1', 'IMAPClient==0.9.2','gdata==2.0.17'] install_requires=['argparse', 'Logbook==0.10.1', 'IMAPClient==0.13', 'chardet==2.3.0'] )
2,792
Python
.py
60
39.85
113
0.648659
gaubert/gmvault
3,572
285
144
AGPL-3.0
9/5/2024, 5:11:34 PM (Europe/Amsterdam)
12,276
.pydevproject
gaubert_gmvault/.pydevproject
<?xml version="1.0" encoding="UTF-8" standalone="no"?> <?eclipse-pydev version="1.0"?> <pydev_project> <pydev_property name="org.python.pydev.PYTHON_PROJECT_INTERPRETER">Default</pydev_property> <pydev_property name="org.python.pydev.PYTHON_PROJECT_VERSION">python 2.7</pydev_property> <pydev_pathproperty name="org.python.pydev.PROJECT_SOURCE_PATH"> <path>/gmvault/src</path> </pydev_pathproperty> </pydev_project>
417
Python
.py
9
45.222222
91
0.773956
gaubert/gmvault
3,572
285
144
AGPL-3.0
9/5/2024, 5:11:34 PM (Europe/Amsterdam)
12,277
add_version.py
gaubert_gmvault/etc/utils/add_version.py
""" Gmvault: a tool to backup and restore your gmail account. Copyright (C) <since 2011> <guillaume Aubert (guillaume dot aubert at gmail do com)> This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. """ import sys import re def find_version(path): with open(path) as f: for line in f: index = line.find('GMVAULT_VERSION="') if index > -1: print(line[index+17:-2]) return line[index+17:-2] raise Exception("Cannot find GMVAULT_VERSION in %s\n" % (path)) VERSION_PATTERN = r'###GMVAULTVERSION###' VERSION_RE = re.compile(VERSION_PATTERN) def add_version(a_input, a_output, a_version): with open(a_input, 'r') as f_in: with open(a_output, 'w') as f_out: for line in f_in: line = VERSION_RE.sub(a_version, line) f_out.write(line) if __name__ == '__main__': if len(sys.argv) < 4: print("Error: need more parameters for %s." % (sys.argv[0])) print("Usage: add_version.py input_path output_path version.") exit(-1) #print("path = %s\n" % (sys.argv[1])) add_version(sys.argv[1], sys.argv[2], sys.argv[3])
1,808
Python
.py
39
39.564103
89
0.654328
gaubert/gmvault
3,572
285
144
AGPL-3.0
9/5/2024, 5:11:34 PM (Europe/Amsterdam)
12,278
find_version.py
gaubert_gmvault/etc/utils/find_version.py
""" Gmvault: a tool to backup and restore your gmail account. Copyright (C) <since 2011> <guillaume Aubert (guillaume dot aubert at gmail do com)> This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. """ import sys def find_version(path): with open(path) as f: for line in f: index = line.find('GMVAULT_VERSION = "') if index > -1: print(line[index+19:-2]) res = line[index+19:-2] return res.strip() raise Exception("Cannot find GMVAULT_VERSION in %s\n" % path) if __name__ == '__main__': if len(sys.argv) < 2: print("Error: Need the path to gmv_cmd.py") exit(-1) #print("path = %s\n" % (sys.argv[1])) find_version(sys.argv[1])
1,383
Python
.py
30
39.233333
89
0.663684
gaubert/gmvault
3,572
285
144
AGPL-3.0
9/5/2024, 5:11:34 PM (Europe/Amsterdam)
12,279
flask_stats.py
gaubert_gmvault/etc/utils/flask_stats.py
from flask import Flask import scrapping import json import datetime app = Flask(__name__) @app.route("/") def hello(): return "error 404" @app.route("/stats") def stats(): return scrapping.get_stats("JSON") if __name__ == "__main__": app.run(debug=False, host='0.0.0.0', port=8181) #app.run(debug=False, port=80)
336
Python
.py
14
21.428571
51
0.674051
gaubert/gmvault
3,572
285
144
AGPL-3.0
9/5/2024, 5:11:34 PM (Europe/Amsterdam)
12,280
scrapping.py
gaubert_gmvault/etc/utils/scrapping.py
''' Gmvault: a tool to backup and restore your gmail account. Copyright (C) <since 2011> <guillaume Aubert (guillaume dot aubert at gmail do com)> This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. ''' #quick and dirty scrapper to get number of downloads import json import datetime import mechanize import BeautifulSoup as bs def get_from_bitbucket(): print("Get info from bitbucket\n") br = mechanize.Browser() br.open("https://bitbucket.org/gaubert/gmvault-official-download/downloads") response = br.response().read() #print("response = %s\n" % response) soup = bs.BeautifulSoup(response) #body_tag = soup.body all_tables = soup.findAll('table') table = soup.find(lambda tag: tag.name=='table' and tag.has_key('id') and tag['id']=="uploaded-files") rows = table.findAll(lambda tag: tag.name=='tr') res = {} for row in rows: tds = row.findAll(lambda tag: tag.name == 'td') #print("tds = %s\n" %(tds)) td_number = 0 name = None for td in tds: if td_number == 0: #print("td.a.string = %s\n" %(td.a.string)) name = td.a.string res[name] = 0 elif td_number == 3: #print("download nb = %s\n" %(td.string)) res[name] = int(td.string) elif td_number == 4: #reset it td_number = 0 name = None td_number += 1 #print("td = %s\n" %(td)) return res def get_from_pypi(url): res = {} print("Get info from pypi (url= %s)\n" % (url)) br = mechanize.Browser() br.open(url) response = br.response().read() soup = bs.BeautifulSoup(response) table = soup.find(lambda tag: tag.name == 'table') #print("all_tables = %s\n" % (all_tables)) rows = table.findAll(lambda tag: tag.name == 'tr') #print("rows = %s\n" %(rows)) for row in rows: tds = row.findAll(lambda tag: tag.name == 'td') #print("tds = %s\n" %(tds)) #ignore tds that are too small if len(tds) < 6: #print("ignore td = %s\n" % (tds)) continue td_number = 0 name = None for td in tds: #print("td = %s\n" % (td)) if td_number == 0: #print("td.a = %s\n" %(td.a)) name = 'pypi-%s' % (td.a.string) res[name] = 0 elif td_number == 5: #print("download nb = %s\n" %(td.string)) res[name] = int(td.string) elif td_number == 6: #reset it td_number = 0 name = None td_number += 1 return res V17W1_BETA_ON_GITHUB=7612 V17_BETA_SRC_ON_GITHUB=1264 V17_BETA_MAC_ON_GITHUB=2042 WIN_TOTAL_PREVIOUS_VERSIONS=2551+4303+3648+302+V17W1_BETA_ON_GITHUB MAC_TOTAL_PREVIOUS_VERSIONS=2151+1806+1119+V17_BETA_MAC_ON_GITHUB PYPI_TOTAL_PREVIOUS_VERSIONS=872+1065+826 SRC_TOTAL_PREVIOUS_VERSIONS=970+611+V17_BETA_SRC_ON_GITHUB #LINUX is all Linux flavours available LIN_TOTAL_PREVIOUS_VERSIONS=916+325+254+SRC_TOTAL_PREVIOUS_VERSIONS+PYPI_TOTAL_PREVIOUS_VERSIONS TOTAL_PREVIOUS_VERSIONS=2551+2155+916+872+4303+1806+325+970+1065+3648+1119+254+611+826+302+V17_BETA_MAC_ON_GITHUB+V17_BETA_SRC_ON_GITHUB+V17W1_BETA_ON_GITHUB def get_stats(return_type): """ return the stats """ res = get_from_bitbucket() res.update(get_from_pypi("https://pypi.python.org/pypi/gmvault/1.8.1-beta")) res.update(get_from_pypi("https://pypi.python.org/pypi/gmvault/1.8-beta")) res.update(get_from_pypi("https://pypi.python.org/pypi/gmvault/1.7-beta")) #print("name , nb_downloads") total = 0 win_total = 0 lin_total = 0 mac_total = 0 v17_total = 0 v18_total = 0 v181_total = 0 pypi_total = 0 src_total = 0 for key in res.keys(): #print("key= %s: (%s)\n" %(key, res[key])) if key.endswith(".exe"): win_total += res[key] elif "macosx" in key: mac_total += res[key] else: lin_total += res[key] if "1.8" in key: #print("inv1.8: %s" % (key)) v18_total += res[key] elif "1.7" in key: v17_total += res[key] if "src" in key: src_total += res[key] elif "pypi" in key: pypi_total += res[key] if "1.8.1" in key: v181_total += res[key] #print("%s, %s\n" % (key, res[key])) total += res[key] total += TOTAL_PREVIOUS_VERSIONS win_total += WIN_TOTAL_PREVIOUS_VERSIONS lin_total += LIN_TOTAL_PREVIOUS_VERSIONS mac_total += MAC_TOTAL_PREVIOUS_VERSIONS pypi_total += PYPI_TOTAL_PREVIOUS_VERSIONS src_total += SRC_TOTAL_PREVIOUS_VERSIONS the_str = "" if return_type == "TEXT": the_str += "As of today %s, total of downloads (v1.7 and v1.8) = %s.\n" %(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'),total) the_str += "win total = %s,\nmac total = %s,\nlin total = %s.\n" % (win_total, mac_total, lin_total) the_str += "pypi total = %s, src total = %s since .\n" % (pypi_total, src_total) the_str += "v1.7x total = %s since (17-12-2012), v1.8x = %s since (19-03-2013).\n" % (v17_total, v18_total) the_str += "v1.8.1 total = %s since (28.04.2013).\n" % (v181_total) return the_str elif return_type == "JSON": return json.dumps({'total' : total, 'now' : datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'), \ 'win_total' : win_total, 'mac_total' : mac_total, 'lin_total' : lin_total, \ "pypi_total" : pypi_total, "src_total" : src_total, \ 'v17x_total' : v17_total, 'v18x_total' : v18_total, 'v181_total': v181_total}) if __name__ == "__main__": print(get_stats("JSON"))
6,526
Python
.py
154
34.383117
157
0.590447
gaubert/gmvault
3,572
285
144
AGPL-3.0
9/5/2024, 5:11:34 PM (Europe/Amsterdam)
12,281
memdebug.py
gaubert_gmvault/etc/utils/mem-profiling-tools/memdebug.py
# memdebug.py import cherrypy import dowser def start(port): cherrypy.tree.mount(dowser.Root()) cherrypy.config.update({ 'environment': 'embedded', 'server.socket_port': port }) #cherrypy.quickstart() cherrypy.engine.start()
263
Python
.py
11
19.454545
38
0.684
gaubert/gmvault
3,572
285
144
AGPL-3.0
9/5/2024, 5:11:34 PM (Europe/Amsterdam)
12,282
__init__.py
gaubert_gmvault/etc/utils/mem-profiling-tools/dowser/__init__.py
import cgi import gc import os localDir = os.path.join(os.getcwd(), os.path.dirname(__file__)) from StringIO import StringIO import sys import threading import time from types import FrameType, ModuleType import Image import ImageDraw import cherrypy import reftree def get_repr(obj, limit=250): return cgi.escape(reftree.get_repr(obj, limit)) class _(object): pass dictproxy = type(_.__dict__) method_types = [type(tuple.__le__), # 'wrapper_descriptor' type([1].__le__), # 'method-wrapper' type(sys.getcheckinterval), # 'builtin_function_or_method' type(cgi.FieldStorage.getfirst), # 'instancemethod' ] def url(path): try: return cherrypy.url(path) except AttributeError: return path def template(name, **params): p = {'maincss': url("/main.css"), 'home': url("/"), } p.update(params) return open(os.path.join(localDir, name)).read() % p class Root: period = 5 maxhistory = 300 def __init__(self): self.history = {} self.samples = 0 if cherrypy.__version__ >= '3.1': cherrypy.engine.subscribe('exit', self.stop) self.runthread = threading.Thread(target=self.start) self.runthread.start() def start(self): self.running = True while self.running: self.tick() time.sleep(self.period) def tick(self): gc.collect() typecounts = {} for obj in gc.get_objects(): objtype = type(obj) if objtype in typecounts: typecounts[objtype] += 1 else: typecounts[objtype] = 1 for objtype, count in typecounts.iteritems(): typename = objtype.__module__ + "." + objtype.__name__ if typename not in self.history: self.history[typename] = [0] * self.samples self.history[typename].append(count) samples = self.samples + 1 # Add dummy entries for any types which no longer exist for typename, hist in self.history.iteritems(): diff = samples - len(hist) if diff > 0: hist.extend([0] * diff) # Truncate history to self.maxhistory if samples > self.maxhistory: for typename, hist in self.history.iteritems(): hist.pop(0) else: self.samples = samples def stop(self): self.running = False def index(self, floor=0): rows = [] typenames = self.history.keys() typenames.sort() for typename in typenames: hist = self.history[typename] maxhist = max(hist) if maxhist > int(floor): row = ('<div class="typecount">%s<br />' '<img class="chart" src="%s" /><br />' 'Min: %s Cur: %s Max: %s <a href="%s">TRACE</a></div>' % (cgi.escape(typename), url("chart/%s" % typename), min(hist), hist[-1], maxhist, url("trace/%s" % typename), ) ) rows.append(row) return template("graphs.html", output="\n".join(rows)) index.exposed = True def chart(self, typename): """Return a sparkline chart of the given type.""" data = self.history[typename] height = 20.0 scale = height / max(data) im = Image.new("RGB", (len(data), int(height)), 'white') draw = ImageDraw.Draw(im) draw.line([(i, int(height - (v * scale))) for i, v in enumerate(data)], fill="#009900") del draw f = StringIO() im.save(f, "PNG") result = f.getvalue() cherrypy.response.headers["Content-Type"] = "image/png" return result chart.exposed = True def trace(self, typename, objid=None): gc.collect() if objid is None: rows = self.trace_all(typename) else: rows = self.trace_one(typename, objid) return template("trace.html", output="\n".join(rows), typename=cgi.escape(typename), objid=str(objid or '')) trace.exposed = True def trace_all(self, typename): rows = [] for obj in gc.get_objects(): objtype = type(obj) if objtype.__module__ + "." + objtype.__name__ == typename: rows.append("<p class='obj'>%s</p>" % ReferrerTree(obj).get_repr(obj)) if not rows: rows = ["<h3>The type you requested was not found.</h3>"] return rows def trace_one(self, typename, objid): rows = [] objid = int(objid) all_objs = gc.get_objects() for obj in all_objs: if id(obj) == objid: objtype = type(obj) if objtype.__module__ + "." + objtype.__name__ != typename: rows = ["<h3>The object you requested is no longer " "of the correct type.</h3>"] else: # Attributes rows.append('<div class="obj"><h3>Attributes</h3>') for k in dir(obj): v = getattr(obj, k) if type(v) not in method_types: rows.append('<p class="attr"><b>%s:</b> %s</p>' % (k, get_repr(v))) del v rows.append('</div>') # Referrers rows.append('<div class="refs"><h3>Referrers (Parents)</h3>') rows.append('<p class="desc"><a href="%s">Show the ' 'entire tree</a> of reachable objects</p>' % url("/tree/%s/%s" % (typename, objid))) tree = ReferrerTree(obj) tree.ignore(all_objs) for depth, parentid, parentrepr in tree.walk(maxdepth=1): if parentid: rows.append("<p class='obj'>%s</p>" % parentrepr) rows.append('</div>') # Referents rows.append('<div class="refs"><h3>Referents (Children)</h3>') for child in gc.get_referents(obj): rows.append("<p class='obj'>%s</p>" % tree.get_repr(child)) rows.append('</div>') break if not rows: rows = ["<h3>The object you requested was not found.</h3>"] return rows def tree(self, typename, objid): gc.collect() rows = [] objid = int(objid) all_objs = gc.get_objects() for obj in all_objs: if id(obj) == objid: objtype = type(obj) if objtype.__module__ + "." + objtype.__name__ != typename: rows = ["<h3>The object you requested is no longer " "of the correct type.</h3>"] else: rows.append('<div class="obj">') tree = ReferrerTree(obj) tree.ignore(all_objs) for depth, parentid, parentrepr in tree.walk(maxresults=1000): rows.append(parentrepr) rows.append('</div>') break if not rows: rows = ["<h3>The object you requested was not found.</h3>"] params = {'output': "\n".join(rows), 'typename': cgi.escape(typename), 'objid': str(objid), } return template("tree.html", **params) tree.exposed = True try: # CherryPy 3 from cherrypy import tools Root.main_css = tools.staticfile.handler(root=localDir, filename="main.css") except ImportError: # CherryPy 2 cherrypy.config.update({ '/': {'log_debug_info_filter.on': False}, '/main.css': { 'static_filter.on': True, 'static_filter.file': 'main.css', 'static_filter.root': localDir, }, }) class ReferrerTree(reftree.Tree): ignore_modules = True def _gen(self, obj, depth=0): if self.maxdepth and depth >= self.maxdepth: yield depth, 0, "---- Max depth reached ----" raise StopIteration if isinstance(obj, ModuleType) and self.ignore_modules: raise StopIteration refs = gc.get_referrers(obj) refiter = iter(refs) self.ignore(refs, refiter) thisfile = sys._getframe().f_code.co_filename for ref in refiter: # Exclude all frames that are from this module or reftree. if (isinstance(ref, FrameType) and ref.f_code.co_filename in (thisfile, self.filename)): continue # Exclude all functions and classes from this module or reftree. mod = getattr(ref, "__module__", "") if "dowser" in mod or "reftree" in mod or mod == '__main__': continue # Exclude all parents in our ignore list. if id(ref) in self._ignore: continue # Yield the (depth, id, repr) of our object. yield depth, 0, '%s<div class="branch">' % (" " * depth) if id(ref) in self.seen: yield depth, id(ref), "see %s above" % id(ref) else: self.seen[id(ref)] = None yield depth, id(ref), self.get_repr(ref, obj) for parent in self._gen(ref, depth + 1): yield parent yield depth, 0, '%s</div>' % (" " * depth) def get_repr(self, obj, referent=None): """Return an HTML tree block describing the given object.""" objtype = type(obj) typename = objtype.__module__ + "." + objtype.__name__ prettytype = typename.replace("__builtin__.", "") name = getattr(obj, "__name__", "") if name: prettytype = "%s %r" % (prettytype, name) key = "" if referent: key = self.get_refkey(obj, referent) return ('<a class="objectid" href="%s">%s</a> ' '<span class="typename">%s</span>%s<br />' '<span class="repr">%s</span>' % (url("/trace/%s/%s" % (typename, id(obj))), id(obj), prettytype, key, get_repr(obj, 100)) ) def get_refkey(self, obj, referent): """Return the dict key or attribute name of obj which refers to referent.""" if isinstance(obj, dict): for k, v in obj.iteritems(): if v is referent: return " (via its %r key)" % k for k in dir(obj) + ['__dict__']: if getattr(obj, k, None) is referent: return " (via its %r attribute)" % k return "" if __name__ == '__main__': ## cherrypy.config.update({"environment": "production"}) try: cherrypy.quickstart(Root()) except AttributeError: cherrypy.root = Root() cherrypy.server.start()
11,705
Python
.py
281
28.078292
84
0.504841
gaubert/gmvault
3,572
285
144
AGPL-3.0
9/5/2024, 5:11:34 PM (Europe/Amsterdam)
12,283
reftree.py
gaubert_gmvault/etc/utils/mem-profiling-tools/dowser/reftree.py
import gc import sys from types import FrameType class Tree: def __init__(self, obj): self.obj = obj self.filename = sys._getframe().f_code.co_filename self._ignore = {} def ignore(self, *objects): for obj in objects: self._ignore[id(obj)] = None def ignore_caller(self): f = sys._getframe() # = this function cur = f.f_back # = the function that called us (probably 'walk') self.ignore(cur, cur.f_builtins, cur.f_locals, cur.f_globals) caller = f.f_back # = the 'real' caller self.ignore(caller, caller.f_builtins, caller.f_locals, caller.f_globals) def walk(self, maxresults=100, maxdepth=None): """Walk the object tree, ignoring duplicates and circular refs.""" self.seen = {} self.ignore(self, self.__dict__, self.obj, self.seen, self._ignore) # Ignore the calling frame, its builtins, globals and locals self.ignore_caller() self.maxdepth = maxdepth count = 0 for result in self._gen(self.obj): yield result count += 1 if maxresults and count >= maxresults: yield 0, 0, "==== Max results reached ====" raise StopIteration def print_tree(self, maxresults=100, maxdepth=None): """Walk the object tree, pretty-printing each branch.""" self.ignore_caller() for depth, refid, rep in self.walk(maxresults, maxdepth): print ("%9d" % refid), (" " * depth * 2), rep def _repr_container(obj): return "%s of len %s: %r" % (type(obj).__name__, len(obj), obj) repr_dict = _repr_container repr_set = _repr_container repr_list = _repr_container repr_tuple = _repr_container def repr_str(obj): return "%s of len %s: %r" % (type(obj).__name__, len(obj), obj) repr_unicode = repr_str def repr_frame(obj): return "frame from %s line %s" % (obj.f_code.co_filename, obj.f_lineno) def get_repr(obj, limit=250): typename = getattr(type(obj), "__name__", None) handler = globals().get("repr_%s" % typename, repr) try: result = handler(obj) except: result = "unrepresentable object: %r" % sys.exc_info()[1] if len(result) > limit: result = result[:limit] + "..." return result class ReferentTree(Tree): def _gen(self, obj, depth=0): if self.maxdepth and depth >= self.maxdepth: yield depth, 0, "---- Max depth reached ----" raise StopIteration for ref in gc.get_referents(obj): if id(ref) in self._ignore: continue elif id(ref) in self.seen: yield depth, id(ref), "!" + get_repr(ref) continue else: self.seen[id(ref)] = None yield depth, id(ref), get_repr(ref) for child in self._gen(ref, depth + 1): yield child class ReferrerTree(Tree): def _gen(self, obj, depth=0): if self.maxdepth and depth >= self.maxdepth: yield depth, 0, "---- Max depth reached ----" raise StopIteration refs = gc.get_referrers(obj) refiter = iter(refs) self.ignore(refs, refiter) for ref in refiter: # Exclude all frames that are from this module. if isinstance(ref, FrameType): if ref.f_code.co_filename == self.filename: continue if id(ref) in self._ignore: continue elif id(ref) in self.seen: yield depth, id(ref), "!" + get_repr(ref) continue else: self.seen[id(ref)] = None yield depth, id(ref), get_repr(ref) for parent in self._gen(ref, depth + 1): yield parent class CircularReferents(Tree): def walk(self, maxresults=100, maxdepth=None): """Walk the object tree, showing circular referents.""" self.stops = 0 self.seen = {} self.ignore(self, self.__dict__, self.seen, self._ignore) # Ignore the calling frame, its builtins, globals and locals self.ignore_caller() self.maxdepth = maxdepth count = 0 for result in self._gen(self.obj): yield result count += 1 if maxresults and count >= maxresults: yield 0, 0, "==== Max results reached ====" raise StopIteration def _gen(self, obj, depth=0, trail=None): if self.maxdepth and depth >= self.maxdepth: self.stops += 1 raise StopIteration if trail is None: trail = [] for ref in gc.get_referents(obj): if id(ref) in self._ignore: continue elif id(ref) in self.seen: continue else: self.seen[id(ref)] = None refrepr = get_repr(ref) if id(ref) == id(self.obj): yield trail + [refrepr,] for child in self._gen(ref, depth + 1, trail + [refrepr,]): yield child def print_tree(self, maxresults=100, maxdepth=None): """Walk the object tree, pretty-printing each branch.""" self.ignore_caller() for trail in self.walk(maxresults, maxdepth): print trail if self.stops: print "%s paths stopped because max depth reached" % self.stops def count_objects(): d = {} for obj in gc.get_objects(): objtype = type(obj) d[objtype] = d.get(objtype, 0) + 1 d = [(v, k) for k, v in d.iteritems()] d.sort() return d
5,892
Python
.py
145
29.503448
81
0.560261
gaubert/gmvault
3,572
285
144
AGPL-3.0
9/5/2024, 5:11:34 PM (Europe/Amsterdam)
12,284
reftree.py.svn-base
gaubert_gmvault/etc/utils/mem-profiling-tools/dowser/.svn/text-base/reftree.py.svn-base
import gc import sys from types import FrameType class Tree: def __init__(self, obj): self.obj = obj self.filename = sys._getframe().f_code.co_filename self._ignore = {} def ignore(self, *objects): for obj in objects: self._ignore[id(obj)] = None def ignore_caller(self): f = sys._getframe() # = this function cur = f.f_back # = the function that called us (probably 'walk') self.ignore(cur, cur.f_builtins, cur.f_locals, cur.f_globals) caller = f.f_back # = the 'real' caller self.ignore(caller, caller.f_builtins, caller.f_locals, caller.f_globals) def walk(self, maxresults=100, maxdepth=None): """Walk the object tree, ignoring duplicates and circular refs.""" self.seen = {} self.ignore(self, self.__dict__, self.obj, self.seen, self._ignore) # Ignore the calling frame, its builtins, globals and locals self.ignore_caller() self.maxdepth = maxdepth count = 0 for result in self._gen(self.obj): yield result count += 1 if maxresults and count >= maxresults: yield 0, 0, "==== Max results reached ====" raise StopIteration def print_tree(self, maxresults=100, maxdepth=None): """Walk the object tree, pretty-printing each branch.""" self.ignore_caller() for depth, refid, rep in self.walk(maxresults, maxdepth): print ("%9d" % refid), (" " * depth * 2), rep def _repr_container(obj): return "%s of len %s: %r" % (type(obj).__name__, len(obj), obj) repr_dict = _repr_container repr_set = _repr_container repr_list = _repr_container repr_tuple = _repr_container def repr_str(obj): return "%s of len %s: %r" % (type(obj).__name__, len(obj), obj) repr_unicode = repr_str def repr_frame(obj): return "frame from %s line %s" % (obj.f_code.co_filename, obj.f_lineno) def get_repr(obj, limit=250): typename = getattr(type(obj), "__name__", None) handler = globals().get("repr_%s" % typename, repr) try: result = handler(obj) except: result = "unrepresentable object: %r" % sys.exc_info()[1] if len(result) > limit: result = result[:limit] + "..." return result class ReferentTree(Tree): def _gen(self, obj, depth=0): if self.maxdepth and depth >= self.maxdepth: yield depth, 0, "---- Max depth reached ----" raise StopIteration for ref in gc.get_referents(obj): if id(ref) in self._ignore: continue elif id(ref) in self.seen: yield depth, id(ref), "!" + get_repr(ref) continue else: self.seen[id(ref)] = None yield depth, id(ref), get_repr(ref) for child in self._gen(ref, depth + 1): yield child class ReferrerTree(Tree): def _gen(self, obj, depth=0): if self.maxdepth and depth >= self.maxdepth: yield depth, 0, "---- Max depth reached ----" raise StopIteration refs = gc.get_referrers(obj) refiter = iter(refs) self.ignore(refs, refiter) for ref in refiter: # Exclude all frames that are from this module. if isinstance(ref, FrameType): if ref.f_code.co_filename == self.filename: continue if id(ref) in self._ignore: continue elif id(ref) in self.seen: yield depth, id(ref), "!" + get_repr(ref) continue else: self.seen[id(ref)] = None yield depth, id(ref), get_repr(ref) for parent in self._gen(ref, depth + 1): yield parent class CircularReferents(Tree): def walk(self, maxresults=100, maxdepth=None): """Walk the object tree, showing circular referents.""" self.stops = 0 self.seen = {} self.ignore(self, self.__dict__, self.seen, self._ignore) # Ignore the calling frame, its builtins, globals and locals self.ignore_caller() self.maxdepth = maxdepth count = 0 for result in self._gen(self.obj): yield result count += 1 if maxresults and count >= maxresults: yield 0, 0, "==== Max results reached ====" raise StopIteration def _gen(self, obj, depth=0, trail=None): if self.maxdepth and depth >= self.maxdepth: self.stops += 1 raise StopIteration if trail is None: trail = [] for ref in gc.get_referents(obj): if id(ref) in self._ignore: continue elif id(ref) in self.seen: continue else: self.seen[id(ref)] = None refrepr = get_repr(ref) if id(ref) == id(self.obj): yield trail + [refrepr,] for child in self._gen(ref, depth + 1, trail + [refrepr,]): yield child def print_tree(self, maxresults=100, maxdepth=None): """Walk the object tree, pretty-printing each branch.""" self.ignore_caller() for trail in self.walk(maxresults, maxdepth): print trail if self.stops: print "%s paths stopped because max depth reached" % self.stops def count_objects(): d = {} for obj in gc.get_objects(): objtype = type(obj) d[objtype] = d.get(objtype, 0) + 1 d = [(v, k) for k, v in d.iteritems()] d.sort() return d
5,892
Python
.py
145
29.503448
81
0.560261
gaubert/gmvault
3,572
285
144
AGPL-3.0
9/5/2024, 5:11:34 PM (Europe/Amsterdam)
12,285
__init__.py.svn-base
gaubert_gmvault/etc/utils/mem-profiling-tools/dowser/.svn/text-base/__init__.py.svn-base
import cgi import gc import os localDir = os.path.join(os.getcwd(), os.path.dirname(__file__)) from StringIO import StringIO import sys import threading import time from types import FrameType, ModuleType import Image import ImageDraw import cherrypy import reftree def get_repr(obj, limit=250): return cgi.escape(reftree.get_repr(obj, limit)) class _(object): pass dictproxy = type(_.__dict__) method_types = [type(tuple.__le__), # 'wrapper_descriptor' type([1].__le__), # 'method-wrapper' type(sys.getcheckinterval), # 'builtin_function_or_method' type(cgi.FieldStorage.getfirst), # 'instancemethod' ] def url(path): try: return cherrypy.url(path) except AttributeError: return path def template(name, **params): p = {'maincss': url("/main.css"), 'home': url("/"), } p.update(params) return open(os.path.join(localDir, name)).read() % p class Root: period = 5 maxhistory = 300 def __init__(self): self.history = {} self.samples = 0 if cherrypy.__version__ >= '3.1': cherrypy.engine.subscribe('exit', self.stop) self.runthread = threading.Thread(target=self.start) self.runthread.start() def start(self): self.running = True while self.running: self.tick() time.sleep(self.period) def tick(self): gc.collect() typecounts = {} for obj in gc.get_objects(): objtype = type(obj) if objtype in typecounts: typecounts[objtype] += 1 else: typecounts[objtype] = 1 for objtype, count in typecounts.iteritems(): typename = objtype.__module__ + "." + objtype.__name__ if typename not in self.history: self.history[typename] = [0] * self.samples self.history[typename].append(count) samples = self.samples + 1 # Add dummy entries for any types which no longer exist for typename, hist in self.history.iteritems(): diff = samples - len(hist) if diff > 0: hist.extend([0] * diff) # Truncate history to self.maxhistory if samples > self.maxhistory: for typename, hist in self.history.iteritems(): hist.pop(0) else: self.samples = samples def stop(self): self.running = False def index(self, floor=0): rows = [] typenames = self.history.keys() typenames.sort() for typename in typenames: hist = self.history[typename] maxhist = max(hist) if maxhist > int(floor): row = ('<div class="typecount">%s<br />' '<img class="chart" src="%s" /><br />' 'Min: %s Cur: %s Max: %s <a href="%s">TRACE</a></div>' % (cgi.escape(typename), url("chart/%s" % typename), min(hist), hist[-1], maxhist, url("trace/%s" % typename), ) ) rows.append(row) return template("graphs.html", output="\n".join(rows)) index.exposed = True def chart(self, typename): """Return a sparkline chart of the given type.""" data = self.history[typename] height = 20.0 scale = height / max(data) im = Image.new("RGB", (len(data), int(height)), 'white') draw = ImageDraw.Draw(im) draw.line([(i, int(height - (v * scale))) for i, v in enumerate(data)], fill="#009900") del draw f = StringIO() im.save(f, "PNG") result = f.getvalue() cherrypy.response.headers["Content-Type"] = "image/png" return result chart.exposed = True def trace(self, typename, objid=None): gc.collect() if objid is None: rows = self.trace_all(typename) else: rows = self.trace_one(typename, objid) return template("trace.html", output="\n".join(rows), typename=cgi.escape(typename), objid=str(objid or '')) trace.exposed = True def trace_all(self, typename): rows = [] for obj in gc.get_objects(): objtype = type(obj) if objtype.__module__ + "." + objtype.__name__ == typename: rows.append("<p class='obj'>%s</p>" % ReferrerTree(obj).get_repr(obj)) if not rows: rows = ["<h3>The type you requested was not found.</h3>"] return rows def trace_one(self, typename, objid): rows = [] objid = int(objid) all_objs = gc.get_objects() for obj in all_objs: if id(obj) == objid: objtype = type(obj) if objtype.__module__ + "." + objtype.__name__ != typename: rows = ["<h3>The object you requested is no longer " "of the correct type.</h3>"] else: # Attributes rows.append('<div class="obj"><h3>Attributes</h3>') for k in dir(obj): v = getattr(obj, k) if type(v) not in method_types: rows.append('<p class="attr"><b>%s:</b> %s</p>' % (k, get_repr(v))) del v rows.append('</div>') # Referrers rows.append('<div class="refs"><h3>Referrers (Parents)</h3>') rows.append('<p class="desc"><a href="%s">Show the ' 'entire tree</a> of reachable objects</p>' % url("/tree/%s/%s" % (typename, objid))) tree = ReferrerTree(obj) tree.ignore(all_objs) for depth, parentid, parentrepr in tree.walk(maxdepth=1): if parentid: rows.append("<p class='obj'>%s</p>" % parentrepr) rows.append('</div>') # Referents rows.append('<div class="refs"><h3>Referents (Children)</h3>') for child in gc.get_referents(obj): rows.append("<p class='obj'>%s</p>" % tree.get_repr(child)) rows.append('</div>') break if not rows: rows = ["<h3>The object you requested was not found.</h3>"] return rows def tree(self, typename, objid): gc.collect() rows = [] objid = int(objid) all_objs = gc.get_objects() for obj in all_objs: if id(obj) == objid: objtype = type(obj) if objtype.__module__ + "." + objtype.__name__ != typename: rows = ["<h3>The object you requested is no longer " "of the correct type.</h3>"] else: rows.append('<div class="obj">') tree = ReferrerTree(obj) tree.ignore(all_objs) for depth, parentid, parentrepr in tree.walk(maxresults=1000): rows.append(parentrepr) rows.append('</div>') break if not rows: rows = ["<h3>The object you requested was not found.</h3>"] params = {'output': "\n".join(rows), 'typename': cgi.escape(typename), 'objid': str(objid), } return template("tree.html", **params) tree.exposed = True try: # CherryPy 3 from cherrypy import tools Root.main_css = tools.staticfile.handler(root=localDir, filename="main.css") except ImportError: # CherryPy 2 cherrypy.config.update({ '/': {'log_debug_info_filter.on': False}, '/main.css': { 'static_filter.on': True, 'static_filter.file': 'main.css', 'static_filter.root': localDir, }, }) class ReferrerTree(reftree.Tree): ignore_modules = True def _gen(self, obj, depth=0): if self.maxdepth and depth >= self.maxdepth: yield depth, 0, "---- Max depth reached ----" raise StopIteration if isinstance(obj, ModuleType) and self.ignore_modules: raise StopIteration refs = gc.get_referrers(obj) refiter = iter(refs) self.ignore(refs, refiter) thisfile = sys._getframe().f_code.co_filename for ref in refiter: # Exclude all frames that are from this module or reftree. if (isinstance(ref, FrameType) and ref.f_code.co_filename in (thisfile, self.filename)): continue # Exclude all functions and classes from this module or reftree. mod = getattr(ref, "__module__", "") if "dowser" in mod or "reftree" in mod or mod == '__main__': continue # Exclude all parents in our ignore list. if id(ref) in self._ignore: continue # Yield the (depth, id, repr) of our object. yield depth, 0, '%s<div class="branch">' % (" " * depth) if id(ref) in self.seen: yield depth, id(ref), "see %s above" % id(ref) else: self.seen[id(ref)] = None yield depth, id(ref), self.get_repr(ref, obj) for parent in self._gen(ref, depth + 1): yield parent yield depth, 0, '%s</div>' % (" " * depth) def get_repr(self, obj, referent=None): """Return an HTML tree block describing the given object.""" objtype = type(obj) typename = objtype.__module__ + "." + objtype.__name__ prettytype = typename.replace("__builtin__.", "") name = getattr(obj, "__name__", "") if name: prettytype = "%s %r" % (prettytype, name) key = "" if referent: key = self.get_refkey(obj, referent) return ('<a class="objectid" href="%s">%s</a> ' '<span class="typename">%s</span>%s<br />' '<span class="repr">%s</span>' % (url("/trace/%s/%s" % (typename, id(obj))), id(obj), prettytype, key, get_repr(obj, 100)) ) def get_refkey(self, obj, referent): """Return the dict key or attribute name of obj which refers to referent.""" if isinstance(obj, dict): for k, v in obj.iteritems(): if v is referent: return " (via its %r key)" % k for k in dir(obj) + ['__dict__']: if getattr(obj, k, None) is referent: return " (via its %r attribute)" % k return "" if __name__ == '__main__': ## cherrypy.config.update({"environment": "production"}) try: cherrypy.quickstart(Root()) except AttributeError: cherrypy.root = Root() cherrypy.server.start()
11,705
Python
.py
281
28.078292
84
0.504841
gaubert/gmvault
3,572
285
144
AGPL-3.0
9/5/2024, 5:11:34 PM (Europe/Amsterdam)
12,286
gmv_runner.py
gaubert_gmvault/src/gmv_runner.py
''' Gmvault: a tool to backup and restore your gmail account. Copyright (C) <since 2011> <guillaume Aubert (guillaume dot aubert at gmail do com)> This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. ''' import gmv.gmv_cmd gmv.gmv_cmd.bootstrap_run()
884
Python
.py
16
50.875
89
0.75406
gaubert/gmvault
3,572
285
144
AGPL-3.0
9/5/2024, 5:11:34 PM (Europe/Amsterdam)
12,287
setup_win.py
gaubert_gmvault/src/setup_win.py
''' Gmvault: a tool to backup and restore your gmail account. Copyright (C) <since 2011> <guillaume Aubert (guillaume dot aubert at gmail do com)> This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. ''' from distutils.core import setup import py2exe from glob import glob #data_files = [("Microsoft.VC90.CRT", glob(r'C:\Program Files\Microsoft Visual Studio 9.0\VC\redist\x86\Microsoft.VC90.CRT\*.*'))] #data_files = [("Microsoft.VC90.CRT", glob(r'C:\WINDOWS\WinSxS\x86_Microsoft.VC90.CRT_1fc8b3b9a1e18e3b_9.0.21022.8_x-ww_d08d0375\*.*'))] #win at work data_files = [("Microsoft.VC90.CRT", glob(r'..\etc\libs\win\Microsoft.VC90.CRT\*.*'))] #generic win setup(data_files=data_files, console=['gmv_runner.py'])
1,321
Python
.py
21
59.380952
149
0.742085
gaubert/gmvault
3,572
285
144
AGPL-3.0
9/5/2024, 5:11:34 PM (Europe/Amsterdam)
12,288
validation_tests.py
gaubert_gmvault/src/validation_tests.py
''' Gmvault: a tool to backup and restore your gmail account. Copyright (C) <since 2011> <guillaume Aubert (guillaume dot aubert at gmail do com)> This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. ''' import sys import unittest import base64 import shutil import os import ssl import gmv.gmvault as gmvault import gmv.gmvault_utils as gmvault_utils def obfuscate_string(a_str): """ use base64 to obfuscate a string """ return base64.b64encode(a_str) def deobfuscate_string(a_str): """ deobfuscate a string """ return base64.b64decode(a_str) def read_password_file(a_path): """ Read log:pass from a file in my home """ with open(a_path) as f: line = f.readline() login, passwd = line.split(":") return deobfuscate_string(login.strip()), deobfuscate_string(passwd.strip()) def delete_db_dir(a_db_dir): """ delete the db directory """ gmvault_utils.delete_all_under(a_db_dir, delete_top_dir=True) class TestGMVaultValidation(unittest.TestCase): #pylint:disable-msg=R0904 """ Validation Tests """ def __init__(self, stuff): """ constructor """ super(TestGMVaultValidation, self).__init__(stuff) self.login = None self.passwd = None self.gmvault_login = None self.gmvault_passwd = None self.default_dir = "/tmp/gmvault-tests" def setUp(self): #pylint:disable-msg=C0103 self.login, self.passwd = read_password_file('/homespace/gaubert/.ssh/passwd') self.gmvault_test_login, self.gmvault_test_passwd = read_password_file('/homespace/gaubert/.ssh/gsync_passwd') def test_help_msg_spawned_by_def(self): """ spawn python gmv_runner account > help_msg_spawned.txt check that res is 0 or 1 """ pass def test_backup_10_emails(self): """ backup 10 emails and check that they are backed => spawn a process with the options => python gmv_runner.py sync account > checkfile """ pass def test_restore_and_check(self): """ Restore emails, retrieve them and compare with originals """ db_dir = "/tmp/the_dir" def ztest_restore_on_gmail(self): """ clean db disk sync with gmail for few emails restore them on gmail test """ db_dir = '/tmp/gmail_bk' #clean db dir delete_db_dir(db_dir) credential = { 'type' : 'passwd', 'value': self.passwd} gs_credential = { 'type' : 'passwd', 'value': self.gmvault_passwd} search_req = { 'type' : 'imap', 'req': "Since 1-Nov-2011 Before 3-Nov-2011"} syncer = gmvault.GMVaulter(db_dir, 'imap.gmail.com', 993, self.login, credential, read_only_access = False, use_encryption = True) #syncer.sync(imap_req = "Since 1-Nov-2011 Before 4-Nov-2011") # Nov-2007 BigDataset syncer.sync(imap_req = search_req) restorer = gmvault.GMVaulter(db_dir, 'imap.gmail.com', 993, self.gmvault_login, gs_credential, read_only_access = False) restorer.restore() print("Done \n") def tests(): """ main test function """ suite = unittest.TestLoader().loadTestsFromTestCase(TestGMVaultValidation) unittest.TextTestRunner(verbosity=2).run(suite) if __name__ == '__main__': tests()
4,177
Python
.py
101
33.039604
138
0.653896
gaubert/gmvault
3,572
285
144
AGPL-3.0
9/5/2024, 5:11:34 PM (Europe/Amsterdam)
12,289
gmvault_essential_tests.py
gaubert_gmvault/src/gmvault_essential_tests.py
''' Gmvault: a tool to backup and restore your gmail account. Copyright (C) <since 2011> <guillaume Aubert (guillaume dot aubert at gmail do com)> This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. ''' import unittest import gmv.gmvault as gmvault import gmv.gmvault_utils as gmvault_utils import gmv.test_utils as test_utils class TestEssentialGMVault(unittest.TestCase): #pylint:disable-msg=R0904 """ Current Main test class """ def __init__(self, stuff): """ constructor """ super(TestEssentialGMVault, self).__init__(stuff) self.gsync_login = None self.gsync_passwd = None self.gmvault_test_login = None self.gmvault_test_passwd = None def setUp(self): #pylint:disable-msg=C0103 """setup""" self.gsync_login, self.gsync_passwd = test_utils.read_password_file('/homespace/gaubert/.ssh/gsync_passwd') self.gmvault_test_login, self.gmvault_test_passwd = test_utils.read_password_file('/homespace/gaubert/.ssh/gmvault_test_passwd') self.ba_login, self.ba_passwd = test_utils.read_password_file('/homespace/gaubert/.ssh/ba_passwd') #xoauth hanlding self.ga_login = 'guillaume.aubert@gmail.com' self.ga_cred = test_utils.get_oauth_cred(self.ga_login, '/homespace/gaubert/.ssh/ga_oauth') def search_for_email(self, gmvaulter, req): """ search for a particular email """ #need to check that all labels are there for emails in essential gmvaulter.src.select_folder('ALLMAIL') imap_ids = gmvaulter.src.search({ 'type' : 'imap', 'req': req, 'charset': 'utf-8' }) print("imap_ids = %s\n" % (imap_ids)) def test_restore_tricky_emails(self): """ Test_restore_tricky_emails. Restore emails with some specificities (japanese characters) in the a mailbox """ gsync_credential = { 'type' : 'passwd', 'value': self.gsync_passwd } extra_labels = [u"My-Extra-Label"] test_utils.clean_mailbox(self.gsync_login, gsync_credential) # test restore test_db_dir = "/homespace/gaubert/gmvault-dbs/essential-dbs" #test_db_dir = "/home/gmv/Dev/projects/gmvault-develop/src/test-db" #test_db_dir = "/Users/gaubert/Dev/projects/gmvault-develop/src/test-db" restorer = gmvault.GMVaulter(test_db_dir, 'imap.gmail.com', 993, \ self.gsync_login, gsync_credential, \ read_only_access = False) restorer.restore(extra_labels = extra_labels) #restore all emails from this essential-db test_utils.check_remote_mailbox_identical_to_local(self, restorer, extra_labels) def test_backup_and_restore(self): """ Backup from gmvault_test and restore """ gsync_credential = { 'type' : 'passwd', 'value': self.gsync_passwd } gmvault_test_credential = { 'type' : 'passwd', 'value': self.gmvault_test_passwd } test_utils.clean_mailbox(self.gsync_login, gsync_credential) gmvault_test_db_dir = "/tmp/backup-restore" backuper = gmvault.GMVaulter(gmvault_test_db_dir, 'imap.gmail.com', 993, \ self.gmvault_test_login, gmvault_test_credential, \ read_only_access = False) backuper.sync({ 'mode': 'full', 'type': 'imap', 'req': 'ALL' }) #check that we have x emails in the database restorer = gmvault.GMVaulter(gmvault_test_db_dir, 'imap.gmail.com', 993, \ self.gsync_login, gsync_credential, \ read_only_access = False) restorer.restore() #restore all emails from this essential-db test_utils.check_remote_mailbox_identical_to_local(self, restorer) test_utils.diff_online_mailboxes(backuper, restorer) gmvault_utils.delete_all_under(gmvault_test_db_dir, delete_top_dir = True) def ztest_delete_gsync(self): """ Simply delete gsync """ gsync_credential = { 'type' : 'passwd', 'value': self.gsync_passwd } gmvault_test_credential = { 'type' : 'passwd', 'value': self.gmvault_test_passwd } test_utils.clean_mailbox(self.gsync_login, gsync_credential) def ztest_find_identicals(self): """ """ gsync_credential = { 'type' : 'passwd', 'value': self.gsync_passwd } gmv_dir_a = "/tmp/a-db" gmv_a = gmvault.GMVaulter(gmv_dir_a, 'imap.gmail.com', 993, self.gsync_login, gsync_credential, read_only_access = True) test_utils.find_identical_emails(gmv_a) def ztest_difference(self): """ """ gsync_credential = { 'type' : 'passwd', 'value': self.gsync_passwd } gmvault_test_credential = { 'type' : 'passwd', 'value': self.gmvault_test_passwd } ba_credential = { 'type' : 'passwd', 'value': self.ba_passwd } gmv_dir_a = "/tmp/a-db" gmv_dir_b = "/tmp/b-db" gmv_a = gmvault.GMVaulter(gmv_dir_a, 'imap.gmail.com', 993, self.gsync_login, gsync_credential, read_only_access = True) #gmv_a = gmvault.GMVaulter(gmv_dir_a, 'imap.gmail.com', 993, self.gmvault_test_login, gmvault_test_credential, read_only_access = False) #gmv_b = gmvault.GMVaulter(gmv_dir_b, 'imap.gmail.com', 993, self.gmvault_test_login, gmvault_test_credential, read_only_access = False) #gmv_b = gmvault.GMVaulter(gmv_dir_b, 'imap.gmail.com', 993, self.ba_login, ba_credential, read_only_access = True) gmv_b = gmvault.GMVaulter(gmv_dir_b, 'imap.gmail.com', 993, self.ga_login, self.ga_cred, read_only_access = True) test_utils.diff_online_mailboxes(gmv_a, gmv_b) def tests(): """ main test function """ suite = unittest.TestLoader().loadTestsFromTestCase(TestEssentialGMVault) unittest.TextTestRunner(verbosity=2).run(suite) if __name__ == '__main__': tests()
6,808
Python
.py
113
49.230088
144
0.641973
gaubert/gmvault
3,572
285
144
AGPL-3.0
9/5/2024, 5:11:34 PM (Europe/Amsterdam)
12,290
gmv_cmd_tests.py
gaubert_gmvault/src/gmv_cmd_tests.py
''' Gmvault: a tool to backup and restore your gmail account. Copyright (C) <since 2011> <guillaume Aubert (guillaume dot aubert at gmail do com)> This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. ''' import sys import unittest import base64 import shutil import os import ssl import imaplib import gmv.gmvault as gmvault import gmv.gmvault_db as gmvault_db import gmv.gmvault_utils as gmvault_utils import gmv.gmv_cmd as gmv_cmd import gmv.credential_utils as credential_utils def obfuscate_string(a_str): """ use base64 to obfuscate a string """ return base64.b64encode(a_str) def deobfuscate_string(a_str): """ deobfuscate a string """ return base64.b64decode(a_str) def read_password_file(a_path): """ Read log:pass from a file in my home """ with open(a_path) as f: line = f.readline() login, passwd = line.split(":") return deobfuscate_string(login.strip()), deobfuscate_string(passwd.strip()) def delete_db_dir(a_db_dir): """ delete the db directory """ gmvault_utils.delete_all_under(a_db_dir, delete_top_dir = True) class TestGMVCMD(unittest.TestCase): #pylint:disable-msg=R0904 """ Current Main test class """ def __init__(self, stuff): """ constructor """ super(TestGMVCMD, self).__init__(stuff) self.login = None self.passwd = None self.gmvault_login = None self.gmvault_passwd = None def setUp(self): #pylint:disable-msg=C0103 self.login, self.passwd = read_password_file('/homespace/gaubert/.ssh/passwd') #self.login, self.passwd = read_password_file('/home/gmv/.ssh/passwd') #self.login, self.passwd = read_password_file('H:/.ssh/passwd') self.gsync_login, self.gsync_passwd = read_password_file('/homespace/gaubert/.ssh/gsync_passwd') #self.gsync_login, self.gsync_passwd = read_password_file('/home/gmv/.ssh/gsync_passwd') #self.gsync_login, self.gsync_passwd = read_password_file('H:/.ssh/gsync_passwd') def ztest_commandline_args(self): """ Test commandline args """ gmv_cmd.init_logging() # test 1: default sys.argv = ['gmvault.py', 'sync', self.login] gmvlt = gmv_cmd.GMVaultLauncher() args = gmvlt.parse_args() #check args self.assertEquals(args['command'], 'sync') self.assertEquals(args['type'], 'full') self.assertEquals(args['email'], self.login) self.assertEquals(args['passwd'], 'not_seen') self.assertEquals(args['oauth'], 'empty') self.assertEquals(args['request'], {'req': 'ALL', 'type': 'imap'}) self.assertEquals(args['host'],'imap.gmail.com') self.assertEquals(args['port'], 993) self.assertEquals(args['db-cleaning'], True) self.assertEquals(args['db-dir'],'%s/gmvault-db' % (os.environ['HOME'])) # test 2: do imap search sys.argv = ['gmvault.py', 'sync','-t', 'custom', '-r', 'Since 1-Nov-2011 Before 4-Nov-2011', \ '--db-dir','/tmp/new-db-1', self.login] gmvlt = gmv_cmd.GMVaultLauncher() args = gmvlt.parse_args() #check args self.assertEquals(args['command'], 'sync') self.assertEquals(args['type'], 'custom') self.assertEquals(args['email'], self.login) self.assertEquals(args['passwd'], 'not_seen') self.assertEquals(args['oauth'], 'empty') self.assertEquals(args['request'], {'req': 'Since 1-Nov-2011 Before 4-Nov-2011', 'type': 'imap'}) self.assertEquals(args['host'],'imap.gmail.com') self.assertEquals(args['port'], 993) self.assertEquals(args['db-cleaning'], True) self.assertEquals(args['db-dir'],'/tmp/new-db-1') # test 2: do gmail search sys.argv = ['gmvault.py', 'sync','-t', 'custom', '-g', 'subject:Chandeleur bis', \ '--db-dir','/tmp/new-db-1', self.login] #do same as in bootstrap gmvlt = gmv_cmd.GMVaultLauncher() args = gmvlt.parse_args() #check args self.assertEquals(args['command'], 'sync') self.assertEquals(args['type'], 'custom') self.assertEquals(args['email'], self.login) self.assertEquals(args['passwd'], 'not_seen') self.assertEquals(args['oauth'], 'empty') self.assertEquals(args['request'], {'req': 'subject:Chandeleur bis', 'type': 'gmail'}) self.assertEquals(args['host'],'imap.gmail.com') self.assertEquals(args['port'], 993) self.assertEquals(args['db-cleaning'], True) self.assertEquals(args['db-dir'],'/tmp/new-db-1') #test3 emails only sys.argv = ['gmvault.py', 'sync','-t', 'custom', '-g', 'subject:Chandeleur bis', \ '--db-dir','/tmp/new-db-1', \ '--emails-only', self.login] #with emails only gmvlt = gmv_cmd.GMVaultLauncher() args = gmvlt.parse_args() #check args self.assertEquals(args['emails_only'], True) self.assertEquals(args['chats_only'], False) self.assertEquals(args['command'], 'sync') self.assertEquals(args['type'], 'custom') self.assertEquals(args['email'], self.login) self.assertEquals(args['passwd'], 'not_seen') self.assertEquals(args['oauth'], 'empty') self.assertEquals(args['request'], {'req': 'subject:Chandeleur bis', 'type': 'gmail'}) self.assertEquals(args['host'],'imap.gmail.com') self.assertEquals(args['port'], 993) self.assertEquals(args['db-cleaning'], True) self.assertEquals(args['db-dir'],'/tmp/new-db-1') #test chats only sys.argv = ['gmvault.py', 'sync','-t', 'custom', '-g', 'subject:Chandeleur bis', \ '--db-dir','/tmp/new-db-1', \ '--chats-only', self.login] gmvlt = gmv_cmd.GMVaultLauncher() args = gmvlt.parse_args() #check args self.assertEquals(args['chats_only'], True) self.assertEquals(args['emails_only'], False) self.assertEquals(args['command'], 'sync') self.assertEquals(args['type'], 'custom') self.assertEquals(args['email'], self.login) self.assertEquals(args['passwd'], 'not_seen') self.assertEquals(args['oauth'], 'empty') self.assertEquals(args['request'], {'req': 'subject:Chandeleur bis', 'type': 'gmail'}) self.assertEquals(args['host'],'imap.gmail.com') self.assertEquals(args['port'], 993) self.assertEquals(args['db-cleaning'], True) self.assertEquals(args['db-dir'],'/tmp/new-db-1') self.assertEquals(args['ownership_control'], True) self.assertEquals(args['compression'], True) self.assertEquals(args['debug'], False) self.assertEquals(args['restart'], False) #test5 chats only sys.argv = ['gmvault.py', 'sync','-t', 'custom', '-g', 'subject:Chandeleur bis', \ '--db-dir','/tmp/new-db-1', \ '--check-db', 'no', '--resume', '--debug',\ '--no-compression', self.login] #with emails only gmvlt = gmv_cmd.GMVaultLauncher() args = gmvlt.parse_args() #check args self.assertEquals(args['chats_only'], False) self.assertEquals(args['emails_only'], False) self.assertEquals(args['command'], 'sync') self.assertEquals(args['type'], 'custom') self.assertEquals(args['email'], self.login) self.assertEquals(args['passwd'], 'not_seen') self.assertEquals(args['oauth'], 'empty') self.assertEquals(args['request'], {'req': 'subject:Chandeleur bis', 'type': 'gmail'}) self.assertEquals(args['host'],'imap.gmail.com') self.assertEquals(args['port'], 993) self.assertEquals(args['db-cleaning'], False) self.assertEquals(args['db-dir'],'/tmp/new-db-1') self.assertEquals(args['compression'], False) self.assertEquals(args['debug'], True) self.assertEquals(args['restart'], True) def zztest_cli_bad_server(self): """ Test the cli interface bad option """ sys.argv = ['gmvault', 'sync', '--server', 'imagp.gmail.com', \ '--port', '993', '--imap-req', \ 'Since 1-Nov-2011 Before 4-Nov-2011', \ self.login] gmvaulter = gmv_cmd.GMVaultLauncher() args = gmvaulter.parse_args() try: gmvaulter.run(args) except SystemExit, _: print("In Error success") def ztest_cli_bad_passwd(self): """ Test the cli interface bad option """ sys.argv = ['gmvault', '--imap-server', 'imap.gmail.com', \ '--imap-port', 993, '--imap-request', \ 'Since 1-Nov-2011 Before 4-Nov-2011', \ '--email', self.login, '--passwd', 'bar'] gmvaulter = gmv_cmd.GMVaultLauncher() args = gmvaulter.parse_args() try: gmvaulter.run(args) except SystemExit, err: print("In Error success") def ztest_cli_bad_login(self): """ Test the cli interface bad option """ sys.argv = ['gmvault', '--imap-server', 'imap.gmail.com', \ '--imap-port', 993, '--imap-request', \ 'Since 1-Nov-2011 Before 4-Nov-2011', \ '--passwd', ] gmvaulter = gmv_cmd.GMVaultLauncher() args = gmvaulter.parse_args() try: gmvaulter.run(args) except SystemExit, err: print("In Error success") def zztest_cli_host_error(self): """ Test the cli interface bad option """ sys.argv = ['gmvault.py', 'sync', '--host', \ 'imap.gmail.com', '--port', '1452', \ self.login] gmvaulter = gmv_cmd.GMVaultLauncher() try: _ = gmvaulter.parse_args() except SystemExit, err: self.assertEquals(type(err), type(SystemExit())) self.assertEquals(err.code, 2) except Exception, err: self.fail('unexpected exception: %s' % err) else: self.fail('SystemExit exception expected') def zztest_cli_(self): """ Test the cli interface bad option """ sys.argv = ['gmvault', 'sync', '--server', 'imap.gmail.com', \ '--port', '993', '--imap-req', \ 'Since 1-Nov-2011 Before 10-Nov-2011', \ '--passwd', self.login] gmvaulter = gmv_cmd.GMVaultLauncher() try: args = gmvaulter.parse_args() self.assertEquals(args['command'],'sync') self.assertEquals(args['type'],'full') self.assertEquals(args['email'], self.login) self.assertEquals(args['passwd'],'empty') self.assertEquals(args['request'], {'req': 'Since 1-Nov-2011 Before 10-Nov-2011', 'type': 'imap'}) self.assertEquals(args['oauth'], 'not_seen') self.assertEquals(args['host'],'imap.gmail.com') self.assertEquals(args['port'], 993) self.assertEquals(args['db-dir'],'./gmvault-db') except SystemExit, err: self.fail("SystemExit Exception: %s" % err) except Exception, err: self.fail('unexpected exception: %s' % err) def ztest_full_sync_gmv(self): """ full test via the command line """ sys.argv = ['gmvault.py', '--imap-server', 'imap.gmail.com', \ '--imap-port', '993', '--imap-request', \ 'Since 1-Nov-2011 Before 5-Nov-2011', '--email', \ self.login, '--passwd', self.passwd] gmvault_launcher = gmv_cmd.GMVaultLauncher() args = gmvault_launcher.parse_args() gmvault_launcher.run(args) #check all stored gmail ids gstorer = gmvault.GmailStorer(args['db-dir']) ids = gstorer.get_all_existing_gmail_ids() self.assertEquals(len(ids), 5) self.assertEquals(ids, {1384403887202624608L: '2011-11', \ 1384486067720566818L: '2011-11', \ 1384313269332005293L: '2011-11', \ 1384545182050901969L: '2011-11', \ 1384578279292583731L: '2011-11'}) #clean db dir delete_db_dir(args['db-dir']) def ztest_password_handling(self): """ Test all credentials handling """ gmv_cmd.init_logging() # test 1: enter passwd and go to interactive mode sys.argv = ['gmvault.py', '--imap-request', \ 'Since 1-Nov-2011 Before 7-Nov-2011', \ '--email', self.login, \ '--passwd', '--interactive', '--db-dir', '/tmp/new-db-1'] gmvault_launcher = gmv_cmd.GMVaultLauncher() args = gmvault_launcher.parse_args() credential = gmvault_launcher.get_credential(args, test_mode = {'activate': True, 'value' : 'a_password'}) #test_mode needed to avoid calling get_pass self.assertEquals(credential, {'type': 'passwd', 'value': 'a_password'}) # store passwd and re-read it sys.argv = ['gmvault.py', '--imap-request', \ 'Since 1-Nov-2011 Before 7-Nov-2011', \ '--email', self.login, \ '--passwd', '--save-passwd', '--db-dir', '/tmp/new-db-1'] gmvault_launcher = gmv_cmd.GMVaultLauncher() args = gmvault_launcher.parse_args() credential = gmvault_launcher.get_credential(args, test_mode = {'activate': True, 'value' : 'a_new_password'}) self.assertEquals(credential, {'type': 'passwd', 'option': 'saved', 'value': 'a_new_password'}) # now read the password sys.argv = ['gmvault.py', 'sync', '--imap-req', \ 'Since 1-Nov-2011 Before 7-Nov-2011', \ '-t', 'custom', \ '--passwd', '--db-dir', '/tmp/new-db-1', self.login] gmvault_launcher = gmv_cmd.GMVaultLauncher() args = gmvault_launcher.parse_args() credential = gmvault_launcher.get_credential(args, test_mode = {'activate': True, 'value' : "don't care"}) self.assertEquals(credential, {'type': 'passwd', 'option': 'read', 'value': 'a_new_password'}) def ztest_double_login(self): """ double login """ # now read the password sys.argv = ['gmvault.py', 'sync', '--db-dir', '/tmp/new-db-1', self.login] gmvault_launcher = gmv_cmd.GMVaultLauncher() args = gmvault_launcher.parse_args() credential = credential_utils.CredentialHelper.get_credential(args) syncer = gmvault.GMVaulter(args['db-dir'], args['host'], args['port'], \ args['email'], credential) print("First connection \n") syncer.src.connect() import time time.sleep(60*10) print("Connection 10 min later") syncer.src.connect() def ztest_oauth2_login(self): """ oauth2 login test """ # now read the password sys.argv = ['gmvault.py', 'sync', '--db-dir', '/tmp/new-db-1', self.login] gmvault_launcher = gmv_cmd.GMVaultLauncher() args = gmvault_launcher.parse_args() credential = credential_utils.CredentialHelper.get_credential(args) print("CREDENTIALS:%s" % (credential)) syncer = gmvault.GMVaulter(args['db-dir'], args['host'], args['port'], \ args['email'], credential) print("First connection \n") syncer.src.connect() #syncer = gmvault.GMVaulter(args['db-dir'], args['host'], args['port'], \ # args['email'], credential) #print("First connection \n") #syncer.src.connect() #import time #time.sleep(60*10) #print("Connection 10 min later") #syncer.src.connect() def test_oauth2_reconnect(self): """ oauth2 login test """ # now read the password sys.argv = ['gmvault.py', 'sync', '--db-dir', '/tmp/new-db-1', self.login] gmvault_launcher = gmv_cmd.GMVaultLauncher() args = gmvault_launcher.parse_args() credential = credential_utils.CredentialHelper.get_credential(args) print("CREDENTIALS:%s" % (credential)) syncer = gmvault.GMVaulter(args['db-dir'], args['host'], args['port'], \ args['email'], credential) print("First connection \n") syncer.src.connect() print("Sleep 1 sec and connect again") import time time.sleep(1) syncer.src.connect() print("Sleep 1 sec and reconnect again") time.sleep(1) syncer.src.reconnect() def ztest_debug_restore(self): """ double login """ # now read the password sys.argv = ['gmvault.py', 'restore', '--db-dir', '/Users/gaubert/Dev/projects/gmvault/src/gmv/gmvault-db', 'gsync.mtester@gmail.com'] gmv_cmd.bootstrap_run() def ztest_restore_with_labels(self): """ Test restore with labels """ sys.argv = ['gmvault.py', 'restore', '--restart', '--db-dir', '/Users/gaubert/Dev/projects/gmvault/src/gmv/gmvault-db', 'gsync.mtester@gmail.com'] gmv_cmd.bootstrap_run() def ztest_quick_sync_with_labels(self): """ Test quick sync --renew-passwd """ sys.argv = ['gmvault.py', 'sync', self.login] gmv_cmd.bootstrap_run() def ztest_simple_get_and_restore(self): """ get few emails and restore them """ db_dir = '/tmp/gmail_bk' #clean db dir delete_db_dir(db_dir) print("Synchronize\n") sys.argv = ['gmvault.py', 'sync', '-t', 'custom', '-r', 'Since 1-Nov-2011 Before 3-Nov-2011', '--db-dir', db_dir, 'guillaume.aubert@gmail.com'] gmv_cmd.bootstrap_run() print("Restore\n") sys.argv = ['gmvault.py', 'restore', '--db-dir', db_dir, 'gsync.mtester@gmail.com'] gmv_cmd.bootstrap_run() def ztest_simple_get_encrypt_and_restore(self): """ get few emails and restore them """ db_dir = '/tmp/gmail_bk' #clean db dir delete_db_dir(db_dir) print("Synchronize\n") sys.argv = ['gmvault.py', 'sync', '-t', 'custom', '--encrypt','-r', 'Since 1-Nov-2011 Before 3-Nov-2011', '--db-dir', db_dir, 'guillaume.aubert@gmail.com'] gmv_cmd.bootstrap_run() print("Restore\n") sys.argv = ['gmvault.py', 'restore', '--db-dir', db_dir, 'gsync.mtester@gmail.com'] gmv_cmd.bootstrap_run() def ztest_delete_sync_gmv(self): """ delete sync via command line """ delete_db_dir('/tmp/new-db-1') #first request to have the extra dirs sys.argv = ['gmvault.py', 'sync', '-t', 'custom', '-r', \ 'Since 1-Nov-2011 Before 7-Nov-2011', \ '--db-dir', '/tmp/new-db-1', 'guillaume.aubert@gmail.com'] #check all stored gmail ids gstorer = gmvault_db.GmailStorer('/tmp/new-db-1') gmv_cmd.bootstrap_run() ids = gstorer.get_all_existing_gmail_ids() self.assertEquals(len(ids), 9) delete_db_dir('/tmp/new-db-1') #second requests so all files after the 5 should disappear sys.argv = ['gmvault.py', 'sync', '-t', 'custom', '-r', \ 'Since 1-Nov-2011 Before 5-Nov-2011', \ '--db-dir', '/tmp/new-db-1', '-c', 'yes', 'guillaume.aubert@gmail.com'] gmv_cmd.bootstrap_run() gstorer = gmvault_db.GmailStorer('/tmp/new-db-1') ids = gstorer.get_all_existing_gmail_ids() self.assertEquals(len(ids), 5) self.assertEquals(ids, {1384403887202624608L: '2011-11', \ 1384486067720566818L: '2011-11', \ 1384313269332005293L: '2011-11', \ 1384545182050901969L: '2011-11', \ 1384578279292583731L: '2011-11'}) #clean db dir delete_db_dir('/tmp/new-db-1') def tests(): """ main test function """ suite = unittest.TestLoader().loadTestsFromTestCase(TestGMVCMD) unittest.TextTestRunner(verbosity=2).run(suite) if __name__ == '__main__': tests()
22,488
Python
.py
469
35.45629
163
0.569562
gaubert/gmvault
3,572
285
144
AGPL-3.0
9/5/2024, 5:11:34 PM (Europe/Amsterdam)
12,291
gmvault_tests.py
gaubert_gmvault/src/gmvault_tests.py
''' Gmvault: a tool to backup and restore your gmail account. Copyright (C) <since 2011> <guillaume Aubert (guillaume dot aubert at gmail do com)> This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. ''' import unittest import base64 import shutil import os import ssl import gmv.mod_imap as mod_imap import gmv.gmvault as gmvault import gmv.gmvault_utils as gmvault_utils import gmv.imap_utils as imap_utils def obfuscate_string(a_str): """ use base64 to obfuscate a string """ return base64.b64encode(a_str) def deobfuscate_string(a_str): """ deobfuscate a string """ return base64.b64decode(a_str) def read_password_file(a_path): """ Read log:pass from a file in my home """ with open(a_path) as f: line = f.readline() login, passwd = line.split(":") return deobfuscate_string(login.strip()), deobfuscate_string(passwd.strip()) def delete_db_dir(a_db_dir): """ delete the db directory """ gmvault_utils.delete_all_under(a_db_dir, delete_top_dir = True) class TestGMVault(unittest.TestCase): #pylint:disable-msg=R0904 """ Current Main test class """ def __init__(self, stuff): """ constructor """ super(TestGMVault, self).__init__(stuff) self.login = None self.passwd = None self.gmvault_login = None self.gmvault_passwd = None def setUp(self): #pylint:disable-msg=C0103 self.login, self.passwd = read_password_file('/homespace/gaubert/.ssh/passwd') self.gmvault_login, self.gmvault_passwd = read_password_file('/homespace/gaubert/.ssh/gsync_passwd') def ztest_gmvault_connect_error(self): """ Test connect error (connect to a wrong port). Too long to check """ gimap = imap_utils.GIMAPFetcher('imap.gmafil.com', 80, "badlogin", "badpassword") try: gimap.connect() except ssl.SSLError, err: msg = str(err) if not msg.startswith('[Errno 8] _ssl.c:') or not msg.endswith('EOF occurred in violation of protocol'): self.fail('received %s. Bad error message' % (msg)) def ztest_gmvault_get_capabilities(self): """ Test simple retrieval """ gimap = imap_utils.GIMAPFetcher('imap.gmail.com', 993, self.login, self.passwd) gimap.connect() self.assertEquals(('IMAP4REV1', 'UNSELECT', \ 'IDLE', 'NAMESPACE', \ 'QUOTA', 'ID', 'XLIST', \ 'CHILDREN', 'X-GM-EXT-1', \ 'XYZZY', 'SASL-IR', 'AUTH=XOAUTH') , gimap.get_capabilities()) def ztest_gmvault_check_gmailness(self): """ Test simple retrieval """ gimap = imap_utils.GIMAPFetcher('imap.gmail.com', 993, self.login, self.passwd) gimap.connect() self.assertEquals( True , gimap.check_gmailness()) def ztest_gmvault_compression(self): """ Test simple retrieval """ gimap = imap_utils.GIMAPFetcher('imap.gmail.com', 993, self.login, self.passwd) gimap.connect() gimap.enable_compression() self.assertEquals( True , gimap.check_gmailness()) criteria = ['Before 1-Jan-2011'] ids = gimap.search(criteria) self.assertEquals(len(ids), 33577) def ztest_created_nested_dirs(self): """ Try to create nested dirs """ client = mod_imap.MonkeyIMAPClient('imap.gmail.com', port = 993, use_uid = True, ssl= True) client.login(self.gmvault_login, self.gmvault_passwd) folders_info = client.list_folders() print(folders_info) folders = [ the_dir for (_, _, the_dir) in folders_info ] print('folders %s\n' %(folders)) the_dir = 'ECMWF-Archive' #dir = 'test' if the_dir not in folders: res = client.create_folder(dir) print(res) folders = [ the_dir for (_, _, dir) in folders_info ] print('folders %s\n' %(folders)) the_dir = 'ECMWF-Archive/ecmwf-simdat' #dir = 'test/test-1' if the_dir not in folders: res = client.create_folder(the_dir) print(res) def zztest_create_gmail_labels_upper_case(self): """ validate the label creation at the imap fetcher level. Use upper case """ gs_credential = { 'type' : 'passwd', 'value': self.gmvault_passwd} gimap = imap_utils.GIMAPFetcher('imap.gmail.com', 993, self.gmvault_login, gs_credential) gimap.connect() print("\nCreate labels.\n") labels_to_create = ['0','A','a', 'B/C', 'B/C/d', 'B/C/d/e', 'c/d'] existing_folders = set() existing_folders = gimap.create_gmail_labels(labels_to_create, existing_folders) print("folders = %s\n" % (existing_folders)) for label in labels_to_create: self.assertTrue( (label.lower() in existing_folders) ) labels_to_create = ['0','A','a', 'B/C', 'B/C/d', 'B/C/d/e', 'c/d', 'diablo3', 'blizzard', 'blizzard/diablo'] #labels_to_create = ['B/c', u'[Imap]/Trash', u'[Imap]/Sent', 'a', 'A', 'e/f/g', 'b/c/d', ] existing_folders = set() existing_folders = gimap.create_gmail_labels(labels_to_create, existing_folders) print("folders = %s\n" % (existing_folders)) for label in labels_to_create: self.assertTrue( (label.lower() in existing_folders) ) print("Delete labels\n") gimap.delete_gmail_labels(labels_to_create) #get existing directories (or label parts) folders = [ directory.lower() for (_, _, directory) in gimap.get_all_folders() ] for label in labels_to_create: #check that they have been deleted self.assertFalse( (label.lower() in folders) ) def zztest_create_gmail_labels_android(self): """ Handle labels with [Imap] """ gs_credential = { 'type' : 'passwd', 'value': self.gmvault_passwd} gimap = imap_utils.GIMAPFetcher('imap.gmail.com', 993, self.gmvault_login, gs_credential) gimap.connect() print("\nCreate labels.\n") labels_to_create = [u'[IMAP]/Trash', u'[IMAP]/Sent'] existing_folders = set() existing_folders = gimap.create_gmail_labels(labels_to_create, existing_folders) #get existing directories (or label parts) #print("xlist folders = %s\n" % (gimap.get_all_folders()) ) #folders = [ directory.lower() for (flags, delim, directory) in gimap.server.list_folders() ] folders = [ directory.lower() for directory in existing_folders ] print("folders = %s\n" % (folders)) for label in labels_to_create: self.assertTrue( (label.lower() in folders) ) # second creation labels_to_create = [u'[RETEST]', u'[RETEST]/test', u'[RETEST]/Trash', u'[IMAP]/Trash', u'[IMAP]/Draft', u'[IMAP]/Sent', u'[IMAP]'] existing_folders = gimap.create_gmail_labels(labels_to_create, existing_folders) folders = [ directory.lower() for directory in existing_folders ] print("folders = %s" % (folders)) for label in labels_to_create: self.assertTrue( (label.lower() in folders) ) #it isn't possible to delete the [IMAP]/Sent, [IMAP]/Draft [IMAP]/Trash labels # I give up and do not delete them in the test labels_to_delete = [u'[RETEST]', u'[RETEST]/test', u'[RETEST]/Trash'] print("Delete labels\n") # delete them gimap.delete_gmail_labels(labels_to_delete) #get existing directories (or label parts) folders = [ directory.lower() for (_, _, directory) in gimap.get_all_folders() ] for label in labels_to_delete: #check that they have been deleted self.assertFalse( (label.lower() in folders) ) def ztest_gmvault_simple_search(self): """ search all emails before 01.01.2005 """ gimap = imap_utils.GIMAPFetcher('imap.gmail.com', 993, self.login, self.passwd) gimap.connect() criteria = ['Before 1-Jan-2011'] ids = gimap.search(criteria) self.assertEquals(len(ids), 33577) def ztest_retrieve_gmail_ids(self): """ Get all uid before Sep 2004 Retrieve all GMAIL IDs """ gimap = imap_utils.GIMAPFetcher('imap.gmail.com', 993, self.login, self.passwd) gimap.connect() criteria = ['Before 1-Oct-2004'] #criteria = ['ALL'] ids = gimap.search(criteria) res = gimap.fetch(ids, [gimap.GMAIL_ID]) self.assertEquals(res, {27362: {'X-GM-MSGID': 1147537963432096749L, 'SEQ': 14535}, 27363: {'X-GM-MSGID': 1147537994018957026L, 'SEQ': 14536}}) def ztest_retrieve_all_params(self): """ Get all params for a uid Retrieve all parts for one email """ gimap = imap_utils.GIMAPFetcher('imap.gmail.com', 993, self.login, self.passwd) gimap.connect() criteria = ['Before 1-Oct-2004'] #criteria = ['ALL'] ids = gimap.search(criteria) self.assertEquals(len(ids), 2) res = gimap.fetch(ids[0], [gimap.GMAIL_ID, gimap.EMAIL_BODY, gimap.GMAIL_THREAD_ID, gimap.GMAIL_LABELS]) self.assertEquals(res[ids[0]][gimap.GMAIL_ID], 1147537963432096749L) self.assertEquals(res[ids[0]][gimap.EMAIL_BODY], \ 'Message-ID: <6999505.1094377483218.JavaMail.wwwadm@chewbacca.ecmwf.int>\r\nDate: Sun, 5 Sep 2004 09:44:43 +0000 (GMT)\r\nFrom: Guillaume.Aubert@ecmwf.int\r\nReply-To: Guillaume.Aubert@ecmwf.int\r\nTo: aubert_guillaume@yahoo.fr\r\nSubject: Fwd: [Flickr] Guillaume Aubert wants you to see their photos\r\nMime-Version: 1.0\r\nContent-Type: text/plain; charset=us-ascii\r\nContent-Transfer-Encoding: 7bit\r\nX-Mailer: jwma\r\nStatus: RO\r\nX-Status: \r\nX-Keywords: \r\nX-UID: 1\r\n\r\n\r\n') #pylint:disable-msg=C0301 def ztest_gmvault_retrieve_email_store_and_read(self): #pylint:disable-msg=C0103 """ Retrieve an email store it on disk and read it """ storage_dir = '/tmp/gmail_bk' gmvault_utils.delete_all_under(storage_dir) gimap = imap_utils.GIMAPFetcher('imap.gmail.com', 993, self.login, self.passwd) gstorer = gmvault.GmailStorer(storage_dir) gimap.connect() criteria = ['Before 1-Oct-2006'] #criteria = ['ALL'] ids = gimap.search(criteria) the_id = ids[124] res = gimap.fetch(the_id, gimap.GET_ALL_INFO) gm_id = gstorer.bury_email(res[the_id]) metadata, data = gstorer.unbury_email(gm_id) self.assertEquals(res[the_id][gimap.GMAIL_ID], metadata['gm_id']) self.assertEquals(res[the_id][gimap.EMAIL_BODY], data) self.assertEquals(res[the_id][gimap.GMAIL_THREAD_ID], metadata['thread_ids']) labels = [] for label in res[the_id][gimap.GMAIL_LABELS]: labels.append(label) self.assertEquals(labels, metadata['labels']) def ztest_gmvault_compress_retrieve_email_store_and_read(self): #pylint:disable-msg=C0103 """ Activate compression and retrieve an email store it on disk and read it """ storage_dir = '/tmp/gmail_bk' gmvault_utils.delete_all_under(storage_dir) gimap = imap_utils.GIMAPFetcher('imap.gmail.com', 993, self.login, self.passwd) gstorer = gmvault.GmailStorer(storage_dir) gimap.connect() gimap.enable_compression() criteria = ['Before 1-Oct-2006'] #criteria = ['ALL'] ids = gimap.search(criteria) the_id = ids[124] res = gimap.fetch(the_id, gimap.GET_ALL_INFO) gm_id = gstorer.bury_email(res[the_id]) metadata, data = gstorer.unbury_email(gm_id) self.assertEquals(res[the_id][gimap.GMAIL_ID], metadata['gm_id']) self.assertEquals(res[the_id][gimap.EMAIL_BODY], data) self.assertEquals(res[the_id][gimap.GMAIL_THREAD_ID], metadata['thread_ids']) labels = [] for label in res[the_id][gimap.GMAIL_LABELS]: labels.append(label) self.assertEquals(labels, metadata['labels']) def ztest_gmvault_retrieve_multiple_emails_store_and_read(self): #pylint:disable-msg=C0103 """ Retrieve emails store them it on disk and read it """ storage_dir = '/tmp/gmail_bk' gmvault_utils.delete_all_under(storage_dir) gimap = imap_utils.GIMAPFetcher('imap.gmail.com', 993, self.login, self.passwd) gstorer = gmvault.GmailStorer(storage_dir) gimap.connect() criteria = ['Before 1-Oct-2006'] #criteria = ['ALL'] ids = gimap.search(criteria) #get 30 emails for index in range(9, 40): print("retrieve email index %d\n" % (index)) the_id = ids[index] res = gimap.fetch(the_id, gimap.GET_ALL_INFO) gm_id = gstorer.bury_email(res[the_id]) print("restore email index %d\n" % (index)) metadata, data = gstorer.unbury_email(gm_id) self.assertEquals(res[the_id][gimap.GMAIL_ID], metadata['gm_id']) self.assertEquals(res[the_id][gimap.EMAIL_BODY], data) self.assertEquals(res[the_id][gimap.GMAIL_THREAD_ID], metadata['thread_ids']) labels = [] for label in res[the_id][gimap.GMAIL_LABELS]: labels.append(label) self.assertEquals(labels, metadata['labels']) def ztest_gmvault_store_gzip_email_and_read(self): #pylint:disable-msg=C0103 """ Retrieve emails store them it on disk and read it """ storage_dir = '/tmp/gmail_bk' gmvault_utils.delete_all_under(storage_dir) gimap = imap_utils.GIMAPFetcher('imap.gmail.com', 993, self.login, self.passwd) gstorer = gmvault.GmailStorer(storage_dir) gimap.connect() criteria = ['Before 1-Oct-2006'] #criteria = ['ALL'] ids = gimap.search(criteria) #get 30 emails for index in range(9, 20): print("retrieve email index %d\n" % (index)) the_id = ids[index] res = gimap.fetch(the_id, gimap.GET_ALL_INFO) gm_id = gstorer.bury_email(res[the_id], compress = True) print("restore email index %d\n" % (index)) metadata, data = gstorer.unbury_email(gm_id) self.assertEquals(res[the_id][gimap.GMAIL_ID], metadata['gm_id']) self.assertEquals(res[the_id][gimap.EMAIL_BODY], data) self.assertEquals(res[the_id][gimap.GMAIL_THREAD_ID], metadata['thread_ids']) labels = [] for label in res[the_id][gimap.GMAIL_LABELS]: labels.append(label) self.assertEquals(labels, metadata['labels']) def ztest_restore_one_email(self): """ get one email from one account and restore it """ gsource = imap_utils.GIMAPFetcher('imap.gmail.com', 993, self.login, self.passwd) gdestination = imap_utils.GIMAPFetcher('imap.gmail.com', 993, self.gmvault_login, self.gmvault_passwd, readonly_folder = False) gsource.connect() gdestination.connect() criteria = ['Before 1-Oct-2006'] #criteria = ['ALL'] ids = gsource.search(criteria) the_id = ids[0] source_email = gsource.fetch(the_id, gsource.GET_ALL_INFO) existing_labels = source_email[the_id][gsource.GMAIL_LABELS] test_labels = [] for elem in existing_labels: test_labels.append(elem) #source_email[the_id][gsource.IMAP_INTERNALDATE] = source_email[the_id][gsource.IMAP_INTERNALDATE].replace(tzinfo= gmvault_utils.UTC_TZ) dest_id = gdestination.push_email(source_email[the_id][gsource.EMAIL_BODY], \ source_email[the_id][gsource.IMAP_FLAGS] , \ source_email[the_id][gsource.IMAP_INTERNALDATE], test_labels) dest_email = gdestination.fetch(dest_id, gsource.GET_ALL_INFO) # do the checkings self.assertEquals(dest_email[dest_id][gsource.IMAP_FLAGS], source_email[the_id][gsource.IMAP_FLAGS]) self.assertEquals(dest_email[dest_id][gsource.EMAIL_BODY], source_email[the_id][gsource.EMAIL_BODY]) self.assertEquals(dest_email[dest_id][gsource.GMAIL_LABELS], source_email[the_id][gsource.GMAIL_LABELS]) #should be ok to be checked self.assertEquals(dest_email[dest_id][gsource.IMAP_INTERNALDATE], source_email[the_id][gsource.IMAP_INTERNALDATE]) def ztest_restore_10_emails(self): """ Restore 10 emails """ gsource = imap_utils.GIMAPFetcher('imap.gmail.com', 993, self.login, self.passwd) gdestination = imap_utils.GIMAPFetcher('imap.gmail.com', 993, self.gmvault_login, self.gmvault_passwd, \ readonly_folder = False) gsource.connect() gdestination.connect() criteria = ['Before 1-Oct-2008'] #criteria = ['ALL'] ids = gsource.search(criteria) #get 30 emails for index in range(9, 20): print("email nb %d\n" % (index)) the_id = ids[index] source_email = gsource.fetch(the_id, gsource.GET_ALL_INFO) existing_labels = source_email[the_id][gsource.GMAIL_LABELS] # get labels test_labels = [] for elem in existing_labels: test_labels.append(elem) dest_id = gdestination.push_email(source_email[the_id][gsource.EMAIL_BODY], \ source_email[the_id][gsource.IMAP_FLAGS] , \ source_email[the_id][gsource.IMAP_INTERNALDATE], test_labels) #retrieve email from destination email account dest_email = gdestination.fetch(dest_id, gsource.GET_ALL_INFO) #check that it has the same # do the checkings self.assertEquals(dest_email[dest_id][gsource.IMAP_FLAGS], source_email[the_id][gsource.IMAP_FLAGS]) self.assertEquals(dest_email[dest_id][gsource.EMAIL_BODY], source_email[the_id][gsource.EMAIL_BODY]) dest_labels = [] for elem in dest_email[dest_id][gsource.GMAIL_LABELS]: if not elem == '\\Important': dest_labels.append(elem) src_labels = [] for elem in source_email[the_id][gsource.GMAIL_LABELS]: if not elem == '\\Important': src_labels.append(elem) self.assertEquals(dest_labels, src_labels) def ztest_few_days_syncer(self): """ Test with the Syncer object """ syncer = gmvault.GMVaulter('/tmp/gmail_bk', 'imap.gmail.com', 993, self.login, self.passwd) syncer.sync(imap_req = "Since 1-Nov-2011 Before 4-Nov-2011") storage_dir = "%s/%s" % ('/tmp/gmail_bk/db', '2011-11') gstorer = gmvault.GmailStorer('/tmp/gmail_bk') metadata = gmvault.GMVaulter.check_email_on_disk(gstorer, 1384313269332005293) self.assertEquals(metadata['gm_id'], 1384313269332005293) metadata = gmvault.GMVaulter.check_email_on_disk(gstorer, 1384403887202624608) self.assertEquals(metadata['gm_id'], 1384403887202624608) metadata = gmvault.GMVaulter.check_email_on_disk(gstorer, 1384486067720566818) self.assertEquals(metadata['gm_id'], 1384486067720566818) def ztest_few_days_syncer_with_deletion(self): #pylint:disable-msg=C0103 """ check that there was a deletion """ db_dir = '/tmp/gmail_bk' #clean db dir delete_db_dir(db_dir) #copy test email in dest dir storage_dir = "%s/db/%s" % (db_dir, '2011-11') gmvault_utils.makedirs(storage_dir) shutil.copyfile('../etc/tests/test_few_days_syncer/2384403887202624608.eml.gz','%s/2384403887202624608.eml.gz' % (storage_dir)) shutil.copyfile('../etc/tests/test_few_days_syncer/2384403887202624608.meta','%s/2384403887202624608.meta' % (storage_dir)) syncer = gmvault.GMVaulter('/tmp/gmail_bk', 'imap.gmail.com', 993, self.login, self.passwd) syncer.sync(imap_req = "Since 1-Nov-2011 Before 2-Nov-2011", db_cleaning = True) self.assertFalse(os.path.exists('%s/2384403887202624608.eml.gz' % (storage_dir))) self.assertFalse(os.path.exists('%s/2384403887202624608.meta' % (storage_dir))) self.assertTrue(os.path.exists('%s/1384313269332005293.meta' % (storage_dir))) self.assertTrue(os.path.exists('%s/1384313269332005293.eml.gz' % (storage_dir))) def ztest_encrypt_restore_on_gmail(self): """ Doesn't work to be fixed clean db disk sync with gmail for few emails restore them on gmail test """ db_dir = '/tmp/gmail_bk' #clean db dir delete_db_dir(db_dir) credential = { 'type' : 'passwd', 'value': self.passwd} search_req = { 'type' : 'imap', 'req': "Since 1-Nov-2011 Before 3-Nov-2011"} use_encryption = True syncer = gmvault.GMVaulter(db_dir, 'imap.gmail.com', 993, self.login, credential, read_only_access = True, use_encryption = use_encryption) syncer.sync(imap_req = search_req) # check that the email can be read gstorer = gmvault.GmailStorer('/tmp/gmail_bk', use_encryption) metadata = gmvault.GMVaulter.check_email_on_disk(gstorer, 1384313269332005293) self.assertEquals(metadata['gm_id'], 1384313269332005293) email_meta, email_data = gstorer.unbury_email(1384313269332005293) self.assertTrue(email_data.startswith("Delivered-To: guillaume.aubert@gmail.com")) #print("Email Data = \n%s\n" % (email_data)) print("Done \n") def ztest_fix_bug_search_broken_gm_id_and_quarantine(self): """ Search with a gm_id and quarantine it """ db_dir = '/tmp/gmail_bk' #clean db dir delete_db_dir(db_dir) credential = { 'type' : 'passwd', 'value': self.passwd} gs_credential = { 'type' : 'passwd', 'value': self.gmvault_passwd} gstorer = gmvault.GmailStorer(db_dir) gimap = imap_utils.GIMAPFetcher('imap.gmail.com', 993, self.login, credential) gimap.connect() criteria = { 'type': 'imap', 'req' :['X-GM-MSGID 1254269417797093924']} #broken one #criteria = ['X-GM-MSGID 1254267782370534098'] #criteria = ['ALL'] ids = gimap.search(criteria) for the_id in ids: res = gimap.fetch(the_id, gimap.GET_ALL_INFO) gm_id = gstorer.bury_email(res[the_id], compress = True) syncer = gmvault.GMVaulter(db_dir, 'imap.gmail.com', 993, self.gmvault_login, gs_credential) syncer.restore() #check that the file has been quarantine quarantine_dir = '%s/quarantine' %(db_dir) self.assertTrue(os.path.exists('%s/1254269417797093924.eml.gz' % (quarantine_dir))) self.assertTrue(os.path.exists('%s/1254269417797093924.meta' % (quarantine_dir))) def ztest_fix_bug(self): """ bug with uid 142221L => empty email returned by gmail """ db_dir = '/tmp/gmail_bk' credential = { 'type' : 'passwd', 'value': self.passwd} syncer = gmvault.GMVaulter(db_dir, 'imap.gmail.com', 993, self.login, credential, 'verySecRetKeY') syncer._create_update_sync([142221L], compress = True) def test_check_flags(self): """ Check flags """ credential = { 'type' : 'passwd', 'value': self.passwd} #print("credential %s\n" % (credential)) gimap = imap_utils.GIMAPFetcher('imap.gmail.com', 993, self.login, credential) gimap.connect() imap_ids = [155182] gmail_id = 1405877259414135030 imap_ids = [155070] #res = gimap.fetch(imap_ids, [gimap.GMAIL_ID, gimap.IMAP_FLAGS]) res = gimap.fetch(imap_ids, gimap.GET_ALL_BUT_DATA) print(res) def tests(): """ main test function """ suite = unittest.TestLoader().loadTestsFromTestCase(TestGMVault) unittest.TextTestRunner(verbosity=2).run(suite) if __name__ == '__main__': tests()
27,099
Python
.py
494
41.117409
558
0.616895
gaubert/gmvault
3,572
285
144
AGPL-3.0
9/5/2024, 5:11:34 PM (Europe/Amsterdam)
12,292
setup_mac.py
gaubert_gmvault/src/setup_mac.py
""" This is a setup.py script generated by py2applet Usage: python setup.py py2app """ from setuptools import setup #APP = ['./gmv/gmv_cmd.py'] APP = ['./gmv_runner.py'] DATA_FILES = [] OPTIONS = {'argv_emulation': True, 'includes':['argparse', 'logbook','imapclient','chardet'],} setup( app=APP, data_files=DATA_FILES, options={'py2app': OPTIONS}, setup_requires=['py2app'], )
402
Python
.py
16
22.625
94
0.675393
gaubert/gmvault
3,572
285
144
AGPL-3.0
9/5/2024, 5:11:34 PM (Europe/Amsterdam)
12,293
sandbox_tests.py
gaubert_gmvault/src/sandbox_tests.py
''' Gmvault: a tool to backup and restore your gmail account. Copyright (C) <since 2011> <guillaume Aubert (guillaume dot aubert at gmail do com)> This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. ''' ''' Created on Feb 14, 2012 @author: guillaume.aubert@gmail.com Experimentation and validation of internal mechanisms ''' import unittest import base64 import socket import imaplib import gmv.gmvault_utils as gmvault_utils import gmv.imap_utils as imap_utils def obfuscate_string(a_str): """ use base64 to obfuscate a string """ return base64.b64encode(a_str) def deobfuscate_string(a_str): """ deobfuscate a string """ return base64.b64decode(a_str) def read_password_file(a_path): """ Read log:pass from a file in my home """ with open(a_path) as f: line = f.readline() login, passwd = line.split(":") return deobfuscate_string(login.strip()), deobfuscate_string(passwd.strip()) def delete_db_dir(a_db_dir): """ delete the db directory """ gmvault_utils.delete_all_under(a_db_dir, delete_top_dir = True) class TestSandbox(unittest.TestCase): #pylint:disable-msg=R0904 """ Current Main test class """ def __init__(self, stuff): """ constructor """ super(TestSandbox, self).__init__(stuff) self.login = None self.passwd = None self.gmvault_login = None self.gmvault_passwd = None def setUp(self): #pylint:disable-msg=C0103 self.login, self.passwd = read_password_file('/homespace/gaubert/.ssh/passwd') self.gmvault_login, self.gmvault_passwd = read_password_file('/homespace/gaubert/.ssh/gsync_passwd') def ztest_logger(self): """ Test the logging mechanism """ import gmv.log_utils as log_utils log_utils.LoggerFactory.setup_cli_app_handler('./gmv.log') LOG = log_utils.LoggerFactory.get_logger('gmv') #pylint:disable-msg=C0103 LOG.info("On Info") LOG.warning("On Warning") LOG.error("On Error") LOG.notice("On Notice") try: raise Exception("Exception. This is my exception") self.fail("Should never arrive here") #pylint:disable-msg=W0101 except Exception, err: #pylint:disable-msg=W0101, W0703 LOG.exception("error,", err) LOG.critical("On Critical") def ztest_encrypt_blowfish(self): """ Test encryption with blowfish """ file_path = '../etc/tests/test_few_days_syncer/2384403887202624608.eml.gz' import gzip import gmv.blowfish #create blowfish cipher cipher = gmv.blowfish.Blowfish('VerySeCretKey') gz_fd = gzip.open(file_path) content = gz_fd.read() cipher.initCTR() crypted = cipher.encryptCTR(content) cipher.initCTR() decrypted = cipher.decryptCTR(crypted) self.assertEquals(decrypted, content) def ztest_regexpr(self): """ regexpr for """ import re the_str = "Subject: Marta Gutierrez commented on her Wall post.\nMessage-ID: <c5b5deee29e373ca42cec75e4ef8384e@www.facebook.com>" regexpr = "Subject:\s+(?P<subject>.*)\s+Message-ID:\s+<(?P<msgid>.*)>" reg = re.compile(regexpr) matched = reg.match(the_str) if matched: print("Matched") print("subject=[%s],messageid=[%s]" % (matched.group('subject'), matched.group('msgid'))) def ztest_is_encrypted_regexpr(self): """ Encrypted re """ import re the_str ="1384313269332005293.eml.crypt.gz" regexpr ="[\w+,\.]+crypt[\w,\.]*" reg= re.compile(regexpr) matched = reg.match(the_str) if matched: print("\nMatched") else: print("\nUnmatched") def ztest_memory_error_bug(self): """ Try to push the memory error """ # now read the password import sys import gmv.gmv_cmd as gmv_cmd import email with open('/Users/gaubert/gmvault-data/gmvault-db-bug/db/2004-10/1399791159741721320.eml') as f: email_body = f.read() mail = email.message_from_string(email_body) print mail sys.argv = ['gmvault.py', 'restore', '--db-dir', '/Users/gaubert/gmvault-data/gmvault-db-bug', 'gsync.mtester@gmail.com'] gmv_cmd.bootstrap_run() def ztest_retry_mode(self): """ Test that the decorators are functionning properly """ class MonkeyIMAPFetcher(imap_utils.GIMAPFetcher): def __init__(self, host, port, login, credential, readonly_folder = True): """ Constructor """ super(MonkeyIMAPFetcher, self).__init__( host, port, login, credential, readonly_folder) self.connect_nb = 0 def connect(self): """ connect """ self.connect_nb += 1 @imap_utils.retry(3,1,2) def push_email(self, a_body, a_flags, a_internal_time, a_labels): """ Throw exceptions """ #raise imaplib.IMAP4.error("GIMAPFetcher cannot restore email in %s account." %("myaccount@gmail.com")) #raise imaplib.IMAP4.abort("GIMAPFetcher cannot restore email in %s account." %("myaccount@gmail.com")) raise socket.error("Error") #raise imap_utils.PushEmailError("GIMAPFetcher cannot restore email in %s account." %("myaccount@gmail.com")) imap_fetch = MonkeyIMAPFetcher(host = None, port = None, login = None, credential = None) try: imap_fetch.push_email(None, None, None, None) #except Exception, err: except imaplib.IMAP4.error, err: self.assertEquals('GIMAPFetcher cannot restore email in myaccount@gmail.com account.', str(err)) self.assertEquals(imap_fetch.connect_nb, 3) def ztest_os_walk(self): """ test os walk """ import os for root, dirs, files in os.walk('/Users/gaubert/Dev/projects/gmvault/src/gmv/gmvault-db/db'): print("root: %s, sub-dirs : %s, files = %s" % (root, dirs, files)) def ztest_get_subdir_info(self): """ test get subdir info """ import gmv.gmvault as gmv storer = gmv.GmailStorer("/Users/gaubert/gmvault-db") storer.init_sub_chats_dir() def ztest_ordered_os_walk(self): """ test ordered os walk """ import gmv.gmvault_utils as gmvu for vals in gmvu.ordered_dirwalk('/home/aubert/gmvault-db.old/db', a_wildcards="*.meta"): print("vals = %s\n" % (vals)) pass import os for root, dirs, files in os.walk('/Users/gaubert/Dev/projects/gmvault/src/gmv/gmvault-db/db'): print("root: %s, sub-dirs : %s, files = %s" % (root, dirs, files)) def ztest_logging(self): """ Test logging """ #gmv_cmd.init_logging() import gmv.log_utils as log_utils log_utils.LoggerFactory.setup_cli_app_handler(activate_log_file=True, file_path="/tmp/gmvault.log") LOG = log_utils.LoggerFactory.get_logger('gmv') LOG.critical("This is critical") LOG.info("This is info") LOG.error("This is error") LOG.debug("This is debug") def tests(): """ main test function """ suite = unittest.TestLoader().loadTestsFromTestCase(TestSandbox) unittest.TextTestRunner(verbosity=2).run(suite) if __name__ == '__main__': tests()
8,841
Python
.py
209
31.334928
137
0.610859
gaubert/gmvault
3,572
285
144
AGPL-3.0
9/5/2024, 5:11:34 PM (Europe/Amsterdam)
12,294
perf_tests.py
gaubert_gmvault/src/perf_tests.py
''' Gmvault: a tool to backup and restore your gmail account. Copyright (C) <since 2011> <guillaume Aubert (guillaume dot aubert at gmail do com)> This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. ''' import unittest import datetime import os import gmv.gmvault_utils as gmvault_utils import gmv.collections_utils as collections_utils class TestPerf(unittest.TestCase): #pylint:disable-msg=R0904 """ Current Main test class """ def __init__(self, stuff): """ constructor """ super(TestPerf, self).__init__(stuff) def setUp(self): #pylint:disable-msg=C0103 pass def _create_dirs(self, working_dir, nb_dirs, nb_files_per_dir): """ create all the dirs and files """ dirname = 'dir_%d' data_file = '%d.eml' meta_file = '%d.meta' for nb in xrange(0, nb_dirs): #make dir the_dir = '%s/%s' % (working_dir, dirname % nb) gmvault_utils.makedirs(the_dir) for file_id in xrange(0,nb_files_per_dir): #create data file with open('%s/%s_%s' % (the_dir, dirname % nb, data_file % file_id), 'w') as f: f.write("something") #create metadata file with open('%s/%s_%s' % (the_dir, dirname % nb, meta_file % file_id), 'w') as f: f.write("another info something") def test_read_lots_of_files(self): """ Test to mesure how long it takes to list over 100 000 files On server: 250 000 meta files in 50 dirs (50,5000) => 9.74 sec to list them 100 000 meta files in 20 dirs (20,5000) => 3.068 sec to list them 60 000 meta files in 60 dirs (60,1000) => 1.826 sec to list them On linux macbook pro linux virtual machine: 250 000 meta files in 50 dirs (50,5000) => 9.91 sec to list them 100 000 meta files in 20 dirs (20,5000) => 6.59 sec to list them 60 000 meta files in 60 dirs (60,1000) => 2.26 sec to list them On Win7 laptop machine: 250 000 meta files in 50 dirs (50,5000) => 56.50 sec (3min 27 sec if dir created and listed afterward) to list them 100 000 meta files in 20 dirs (20,5000) => 20.1 sec to list them 60 000 meta files in 60 dirs (60,1000) => 9.96 sec to list them """ root_dir = '/tmp/dirs' #create dirs and files #t1 = datetime.datetime.now() #self._create_dirs('/tmp/dirs', 50, 5000) #t2 = datetime.datetime.now() #print("\nTime to create dirs : %s\n" % (t2-t1)) #print("\nFiles and dirs created.\n") the_iter = gmvault_utils.dirwalk(root_dir, a_wildcards= '*.meta') t1 = datetime.datetime.now() gmail_ids = collections_utils.OrderedDict() for filepath in the_iter: directory, fname = os.path.split(filepath) gmail_ids[os.path.splitext(fname)[0]] = os.path.basename(directory) t2 = datetime.datetime.now() print("\nnb of files = %s" % (len(gmail_ids.keys()))) print("\nTime to read all meta files : %s\n" % (t2-t1)) def tests(): """ main test function """ suite = unittest.TestLoader().loadTestsFromTestCase(TestPerf) unittest.TextTestRunner(verbosity=2).run(suite) if __name__ == '__main__': tests()
4,267
Python
.py
87
37.643678
137
0.591546
gaubert/gmvault
3,572
285
144
AGPL-3.0
9/5/2024, 5:11:34 PM (Europe/Amsterdam)
12,295
gmv_cmd.py
gaubert_gmvault/src/gmv/gmv_cmd.py
# -*- coding: utf-8 -*- ''' Gmvault: a tool to backup and restore your gmail account. Copyright (C) <since 2011> <guillaume Aubert (guillaume dot aubert at gmail do com)> This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. ''' import socket import sys import datetime import os import signal import traceback import argparse import imaplib import gmv.log_utils as log_utils import gmv.gmvault_utils as gmvault_utils import gmv.gmvault as gmvault import gmv.gmvault_export as gmvault_export import gmv.collections_utils as collections_utils from gmv.cmdline_utils import CmdLineParser from gmv.credential_utils import CredentialHelper GMVAULT_VERSION = gmvault_utils.GMVAULT_VERSION GLOBAL_HELP_EPILOGUE = """Examples: a) Get help for each of the individual commands #> gmvault sync -h #> gmvault restore --help #> gmvault check -h #> gmvault export -h """ REST_HELP_EPILOGUE = """Examples: a) Complete restore of your gmail account (backed up in ~/gmvault-db) into anewfoo.bar@gmail.com #> gmvault restore -d ~/gmvault-db anewfoo.bar@gmail.com b) Quick restore (restore only the last 2 months to make regular updates) of your gmail account into anewfoo.bar@gmail.com #> gmvault restore --type quick -d ~/gmvault-db foo.bar@gmail.com c) Restart a restore after a previous error (Gmail can cut the connection if it is too long) #> gmvault restore -d ~/gmvault-db anewfoo.bar@gmail.com --resume d) Apply a label to all restored emails #> gmvault restore --apply-label "20120422-gmvault" -d ~/gmvault-db anewfoo.bar@gmail.com """ SYNC_HELP_EPILOGUE = """Examples: a) Full synchronisation with email and oauth login in ./gmvault-db #> gmvault sync foo.bar@gmail.com b) Quick daily synchronisation (only the last 2 months are scanned) #> gmvault sync --type quick foo.bar@gmail.com c) Resume Full synchronisation from where it failed to not go through your mailbox again #> gmvault sync foo.bar@gmail.com --resume d) Encrypt stored emails to save them safely anywhere #> gmvault sync foo.bar@gmail.com --encrypt d) Custom synchronisation with an IMAP request for advance users #> gmvault sync --type custom --imap-req "Since 1-Nov-2011 Before 10-Nov-2011" foo.bar@gmail.com e) Custom synchronisation with an Gmail request for advance users. Get all emails with label work and sent by foo. #> gmvault sync --type custom --gmail-req "in:work from:foo" foo.bar@gmail.com """ EXPORT_HELP_EPILOGUE = """Warning: Experimental Functionality requiring more testing. Examples: a) Export default gmvault-db ($HOME/gmvault-db or %HOME$/gmvault-db) as a maildir mailbox. #> gmvault export ~/my-mailbox-dir b) Export a gmvault-db as a mbox mailbox (compliant with Thunderbird). #> gmvault export -d /tmp/gmvault-db /tmp/a-mbox-dir c) Export only a limited set of labels from the default gmvault-db as a mbox mailbox (compliant with Thunderbird). #> gmvault export -l "label1" -l "TopLabel/LabelLev1" /tmp/a-mbox-dir d) Use one of the export type dedicated to a specific tool (dovecot or offlineIMAP) #> gmvault export -t dovecot /tmp/a-dovecot-dir """ LOG = log_utils.LoggerFactory.get_logger('gmv') class NotSeenAction(argparse.Action): #pylint:disable=R0903,w0232 """ to differenciate between a seen and non seen command """ def __call__(self, parser, namespace, values, option_string=None): if values: setattr(namespace, self.dest, 'empty') else: setattr(namespace, self.dest, values) class GMVaultLauncher(object): """ GMVault launcher handling the command parsing """ SYNC_TYPES = ['full', 'quick', 'custom'] RESTORE_TYPES = ['full', 'quick'] CHECK_TYPES = ['full'] EXPORT_TYPES = collections_utils.OrderedDict([ ('offlineimap', gmvault_export.OfflineIMAP), ('dovecot', gmvault_export.Dovecot), ('maildir', gmvault_export.OfflineIMAP), ('mbox', gmvault_export.MBox)]) EXPORT_TYPE_NAMES = ", ".join(EXPORT_TYPES) DEFAULT_GMVAULT_DB = "%s/gmvault-db" % (os.getenv("HOME", ".")) def __init__(self): """ constructor """ super(GMVaultLauncher, self).__init__() @gmvault_utils.memoized def _create_parser(self): #pylint: disable=R0915 """ Create the argument parser Return the created parser """ parser = CmdLineParser() parser.epilogue = GLOBAL_HELP_EPILOGUE parser.add_argument("-v", '--version', action='version', version='Gmvault v%s' % (GMVAULT_VERSION)) subparsers = parser.add_subparsers(title='subcommands', help='valid subcommands.') # A sync command sync_parser = subparsers.add_parser('sync', \ help='synchronize with a given gmail account.') #email argument can be optional so it should be an option sync_parser.add_argument('email', \ action='store', default='empty_$_email', help='email to sync with.') # sync typ sync_parser.add_argument('-t', '-type', '--type', \ action='store', dest='type', \ default='full', help='type of synchronisation: full|quick|custom. (default: full)') sync_parser.add_argument("-d", "--db-dir", \ action='store', help="Database root directory. (default: $HOME/gmvault-db)",\ dest="db_dir", default= self.DEFAULT_GMVAULT_DB) # for both when seen add const empty otherwise not_seen # this allow to distinguish between an empty value and a non seen option sync_parser.add_argument("-y", "--oauth2", \ help="use oauth for authentication. (default recommended method)",\ action='store_const', dest="oauth2_token", const='empty', default='not_seen') sync_parser.add_argument("-p", "--passwd", \ help="use interactive password authentication. (not recommended)", action= 'store_const' , dest="passwd", const='empty', default='not_seen') sync_parser.add_argument("--renew-oauth2-tok", \ help="renew the stored oauth token (two legged or normal) via an interactive authentication session.", action= 'store_const' , dest="oauth2_token", const='renew') sync_parser.add_argument("--renew-passwd", \ help="renew the stored password via an interactive authentication session. (not recommended)", action= 'store_const' , dest="passwd", const='renew') sync_parser.add_argument("--store-passwd", \ help="use interactive password authentication, encrypt and store the password. (not recommended)", action= 'store_const' , dest="passwd", const='store') #sync_parser.add_argument("-r", "--imap-req", type = get_unicode_commandline_arg, metavar = "REQ", \ # help="Imap request to restrict sync.",\ # dest="imap_request", default=None) sync_parser.add_argument("-r", "--imap-req", metavar = "REQ", \ help="Imap request to restrict sync.",\ dest="imap_request", default=None) sync_parser.add_argument("-g", "--gmail-req", metavar = "REQ", \ help="Gmail search request to restrict sync as defined in"\ "https://support.google.com/mail/bin/answer.py?hl=en&answer=7190",\ dest="gmail_request", default=None) # activate the resume mode --restart is deprecated sync_parser.add_argument("--resume", "--restart", \ action='store_true', dest='restart', \ default=False, help= 'Resume the sync action from the last saved gmail id.') # activate the resume mode --restart is deprecated sync_parser.add_argument("--emails-only", \ action='store_true', dest='only_emails', \ default=False, help= 'Only sync emails.') # activate the resume mode --restart is deprecated sync_parser.add_argument("--chats-only", \ action='store_true', dest='only_chats', \ default=False, help= 'Only sync chats.') sync_parser.add_argument("-e", "--encrypt", \ help="encrypt stored email messages in the database.",\ action='store_true',dest="encrypt", default=False) sync_parser.add_argument("-c", "--check-db", metavar = "VAL", \ help="enable/disable the removal from the gmvault db of the emails "\ "that have been deleted from the given gmail account. VAL = yes or no.",\ dest="db_cleaning", default=None) sync_parser.add_argument("-m", "--multiple-db-owner", \ help="Allow the email database to be synchronized with emails from multiple accounts.",\ action='store_true',dest="allow_mult_owners", default=False) # activate the restart mode sync_parser.add_argument("--no-compression", \ action='store_false', dest='compression', \ default=True, help= 'disable email storage compression (gzip).') sync_parser.add_argument("--server", metavar = "HOSTNAME", \ action='store', help="Gmail imap server hostname. (default: imap.gmail.com)",\ dest="host", default="imap.gmail.com") sync_parser.add_argument("--port", metavar = "PORT", \ action='store', help="Gmail imap server port. (default: 993)",\ dest="port", default=993) sync_parser.add_argument("--debug", "-debug", \ action='store_true', help="Activate debugging info",\ dest="debug", default=False) sync_parser.set_defaults(verb='sync') sync_parser.epilogue = SYNC_HELP_EPILOGUE # restore command rest_parser = subparsers.add_parser('restore', \ help='restore gmvault-db to a given email account.') #email argument can be optional so it should be an option rest_parser.add_argument('email', \ action='store', default='empty_$_email', help='email account to restore.') # restore typ rest_parser.add_argument('-t', '-type', '--type', \ action='store', dest='type', \ default='full', help='type of restoration: full|quick. (default: full)') # add a label rest_parser.add_argument('-a', '--apply-label' , \ action='store', dest='apply_label', \ default=None, help='Apply a label to restored emails') # activate the resume mode --restart is deprecated rest_parser.add_argument("--resume", "--restart", \ action='store_true', dest='restart', \ default=False, help= 'Restart from the last saved gmail id.') # activate the resume mode --restart is deprecated rest_parser.add_argument("--emails-only", \ action='store_true', dest='only_emails', \ default=False, help= 'Only sync emails.') # activate the resume mode --restart is deprecated rest_parser.add_argument("--chats-only", \ action='store_true', dest='only_chats', \ default=False, help= 'Only sync chats.') rest_parser.add_argument("-d", "--db-dir", \ action='store', help="Database root directory. (default: $HOME/gmvault-db)",\ dest="db_dir", default= self.DEFAULT_GMVAULT_DB) # for both when seen add const empty otherwise not_seen # this allow to distinguish between an empty value and a non seen option rest_parser.add_argument("-y", "--oauth2", \ help="use oauth for authentication. (default recommended method)",\ action='store_const', dest="oauth2_token", const='empty', default='not_seen') rest_parser.add_argument("-p", "--passwd", \ help="use interactive password authentication. (not recommended)", action= 'store_const' , dest="passwd", const='empty', default='not_seen') rest_parser.add_argument("--renew-oauth2-tok", \ help="renew the stored oauth token (two legged or normal) via an interactive authentication session.", action= 'store_const' , dest="oauth2_token", const='renew') rest_parser.add_argument("--server", metavar = "HOSTNAME", \ action='store', help="Gmail imap server hostname. (default: imap.gmail.com)",\ dest="host", default="imap.gmail.com") rest_parser.add_argument("--port", metavar = "PORT", \ action='store', help="Gmail imap server port. (default: 993)",\ dest="port", default=993) rest_parser.add_argument("--debug", "-debug", \ action='store_true', help="Activate debugging info",\ dest="debug", default=False) rest_parser.set_defaults(verb='restore') rest_parser.epilogue = REST_HELP_EPILOGUE # check_db command check_parser = subparsers.add_parser('check', \ help='check and clean the gmvault-db disk database.') #email argument check_parser.add_argument('email', \ action='store', default='empty_$_email', help='gmail account against which to check.') check_parser.add_argument("-d", "--db-dir", \ action='store', help="Database root directory. (default: $HOME/gmvault-db)",\ dest="db_dir", default= self.DEFAULT_GMVAULT_DB) # for both when seen add const empty otherwise not_seen # this allow to distinguish between an empty value and a non seen option check_parser.add_argument("-y", "--oauth2", \ help="use oauth for authentication. (default recommended method)",\ action='store_const', dest="oauth2_token", const='empty', default='not_seen') check_parser.add_argument("-p", "--passwd", \ help="use interactive password authentication. (not recommended)", action= 'store_const' , dest="passwd", const='empty', default='not_seen') check_parser.add_argument("--renew-oauth2-tok", \ help="renew the stored oauth token (two legged or normal) via an interactive authentication session.", action= 'store_const' , dest="oauth2_token", const='renew') check_parser.add_argument("--server", metavar = "HOSTNAME", \ action='store', help="Gmail imap server hostname. (default: imap.gmail.com)",\ dest="host", default="imap.gmail.com") check_parser.add_argument("--port", metavar = "PORT", \ action='store', help="Gmail imap server port. (default: 993)",\ dest="port", default=993) check_parser.add_argument("--debug", "-debug", \ action='store_true', help="Activate debugging info",\ dest="debug", default=False) check_parser.set_defaults(verb='check') # export command export_parser = subparsers.add_parser('export', \ help='Export the gmvault-db database to another format.') export_parser.add_argument('output_dir', \ action='store', help='destination directory to export to.') export_parser.add_argument("-d", "--db-dir", \ action='store', help="Database root directory. (default: $HOME/gmvault-db)",\ dest="db_dir", default= self.DEFAULT_GMVAULT_DB) export_parser.add_argument('-t', '-type', '--type', \ action='store', dest='type', \ default='mbox', help='type of export: %s. (default: mbox)' % self.EXPORT_TYPE_NAMES) export_parser.add_argument('-l', '--label', \ action='append', dest='label', \ default=None, help='specify a label to export') export_parser.add_argument("--debug", "-debug", \ action='store_true', help="Activate debugging info",\ dest="debug", default=False) export_parser.set_defaults(verb='export') export_parser.epilogue = EXPORT_HELP_EPILOGUE return parser @classmethod def _parse_common_args(cls, options, parser, parsed_args, list_of_types = []): #pylint:disable=W0102 """ Parse the common arguments for sync and restore """ #add email parsed_args['email'] = options.email parsed_args['debug'] = options.debug parsed_args['restart'] = options.restart #user entered both authentication methods if options.passwd == 'empty' and (options.oauth2_token == 'empty'): parser.error('You have to use one authentication method. '\ 'Please choose between OAuth2 and password (recommend OAuth2).') # user entered no authentication methods => go to default oauth if options.passwd == 'not_seen' and options.oauth2_token == 'not_seen': #default to xoauth options.oauth2_token = 'empty' # add passwd parsed_args['passwd'] = options.passwd # add oauth2 tok if options.oauth2_token == 'empty': parsed_args['oauth2'] = options.oauth2_token elif options.oauth2_token == 'renew': parsed_args['oauth2'] = 'renew' #add ops type if options.type: tempo_list = ['auto'] tempo_list.extend(list_of_types) if options.type.lower() in tempo_list: parsed_args['type'] = options.type.lower() else: parser.error('Unknown type for command %s. The type should be one of %s' \ % (parsed_args['command'], list_of_types)) #add db_dir parsed_args['db-dir'] = options.db_dir LOG.critical("Use gmvault-db located in %s.\n" % (parsed_args['db-dir'])) # add host parsed_args['host'] = options.host #convert to int if necessary port_type = type(options.port) try: if port_type == type('s') or port_type == type("s"): port = int(options.port) else: port = options.port except Exception, _: #pylint:disable=W0703 parser.error("--port option %s is not a number. Please check the port value" % (port)) # add port parsed_args['port'] = port return parsed_args def parse_args(self): #pylint: disable=R0912 """ Parse command line arguments :returns: a dict that contains the arguments :except Exception Error """ parser = self._create_parser() options = parser.parse_args() LOG.debug("Namespace = %s\n" % (options)) parsed_args = { } parsed_args['command'] = options.verb if parsed_args.get('command', '') == 'sync': # parse common arguments for sync and restore self._parse_common_args(options, parser, parsed_args, self.SYNC_TYPES) # handle the search requests (IMAP or GMAIL dialect) if options.imap_request and options.gmail_request: parser.error('Please use only one search request type. You can use --imap-req or --gmail-req.') elif not options.imap_request and not options.gmail_request: LOG.debug("No search request type passed: Get everything.") parsed_args['request'] = {'type': 'imap', 'req':'ALL'} elif options.gmail_request and not options.imap_request: parsed_args['request'] = { 'type': 'gmail', 'req' : self._clean_imap_or_gm_request(options.gmail_request)} else: parsed_args['request'] = { 'type':'imap', 'req' : self._clean_imap_or_gm_request(options.imap_request)} # handle emails or chats only if options.only_emails and options.only_chats: parser.error("--emails-only and --chats-only cannot be used together. Please choose one.") parsed_args['emails_only'] = options.only_emails parsed_args['chats_only'] = options.only_chats # add db-cleaning # if request passed put it False unless it has been forced by the user # default is True (db-cleaning done) #default parsed_args['db-cleaning'] = True # if there is a value then it is forced if options.db_cleaning: parsed_args['db-cleaning'] = parser.convert_to_boolean(options.db_cleaning) #elif parsed_args['request']['req'] != 'ALL' and not options.db_cleaning: # #else if we have a request and not forced put it to false # parsed_args['db-cleaning'] = False if parsed_args['db-cleaning']: LOG.critical("Activate Gmvault db cleaning.") else: LOG.critical("Disable deletion of emails that are in Gmvault db and not anymore in Gmail.") #add encryption option parsed_args['encrypt'] = options.encrypt #add ownership checking parsed_args['ownership_control'] = not options.allow_mult_owners #compression flag parsed_args['compression'] = options.compression elif parsed_args.get('command', '') == 'restore': # parse common arguments for sync and restore self._parse_common_args(options, parser, parsed_args, self.RESTORE_TYPES) # apply restore labels if there is any parsed_args['apply_label'] = options.apply_label parsed_args['restart'] = options.restart # handle emails or chats only if options.only_emails and options.only_chats: parser.error("--emails-only and --chats-only cannot be used together. Please choose one.") parsed_args['emails_only'] = options.only_emails parsed_args['chats_only'] = options.only_chats elif parsed_args.get('command', '') == 'check': #add defaults for type options.type = 'full' options.restart = False # parse common arguments for sync and restore self._parse_common_args(options, parser, parsed_args, self.CHECK_TYPES) elif parsed_args.get('command', '') == 'export': parsed_args['labels'] = options.label parsed_args['db-dir'] = options.db_dir parsed_args['output-dir'] = options.output_dir if options.type.lower() in self.EXPORT_TYPES: parsed_args['type'] = options.type.lower() else: parser.error('Unknown type for command export. The type should be one of %s' % self.EXPORT_TYPE_NAMES) parsed_args['debug'] = options.debug elif parsed_args.get('command', '') == 'config': pass #add parser parsed_args['parser'] = parser return parsed_args @classmethod def _clean_imap_or_gm_request(cls, request): """ Clean request passed by the user with the option --imap-req or --gmail-req. Windows batch script preserve the single quote and unix shell doesn't. If the request starts and ends with single quote eat them. """ LOG.debug("clean_imap_or_gm_request. original request = %s\n" % (request)) if request and (len(request) > 2) and (request[0] == "'" and request[-1] == "'"): request = request[1:-1] LOG.debug("clean_imap_or_gm_request. processed request = %s\n" % (request)) return request @classmethod def _export(cls, args): """ Export gmvault-db into another format """ export_type = cls.EXPORT_TYPES[args['type']] output_dir = export_type(args['output-dir']) LOG.critical("Export gmvault-db as a %s mailbox." % (args['type'])) exporter = gmvault_export.GMVaultExporter(args['db-dir'], output_dir, labels=args['labels']) exporter.export() output_dir.close() @classmethod def _restore(cls, args, credential): """ Execute All restore operations """ LOG.critical("Connect to Gmail server.\n") # Create a gmvault releaving read_only_access restorer = gmvault.GMVaulter(args['db-dir'], args['host'], args['port'], \ args['email'], credential, read_only_access = False) #full sync is the first one if args.get('type', '') == 'full': #call restore labels = [args['apply_label']] if args['apply_label'] else [] restorer.restore(extra_labels = labels, restart = args['restart'], \ emails_only = args['emails_only'], chats_only = args['chats_only']) elif args.get('type', '') == 'quick': #take the last two to 3 months depending on the current date # today - 2 months today = datetime.date.today() begin = today - datetime.timedelta(gmvault_utils.get_conf_defaults().getint("Restore", "quick_days", 8)) starting_dir = gmvault_utils.get_ym_from_datetime(begin) #call restore labels = [args['apply_label']] if args['apply_label'] else [] restorer.restore(pivot_dir = starting_dir, extra_labels = labels, restart = args['restart'], \ emails_only = args['emails_only'], chats_only = args['chats_only']) else: raise ValueError("Unknown synchronisation mode %s. Please use full (default), quick.") #print error report LOG.critical(restorer.get_operation_report()) @classmethod def _sync(cls, args, credential): """ Execute All synchronisation operations """ LOG.critical("Connect to Gmail server.\n") # handle credential in all levels syncer = gmvault.GMVaulter(args['db-dir'], args['host'], args['port'], \ args['email'], credential, read_only_access = True, \ use_encryption = args['encrypt']) #full sync is the first one if args.get('type', '') == 'full': #choose full sync. Ignore the request syncer.sync({ 'mode': 'full', 'type': 'imap', 'req': 'ALL' } , compress_on_disk = args['compression'], \ db_cleaning = args['db-cleaning'], ownership_checking = args['ownership_control'],\ restart = args['restart'], emails_only = args['emails_only'], chats_only = args['chats_only']) elif args.get('type', '') == 'auto': #choose auto sync. imap request = ALL and restart = True syncer.sync({ 'mode': 'auto', 'type': 'imap', 'req': 'ALL' } , compress_on_disk = args['compression'], \ db_cleaning = args['db-cleaning'], ownership_checking = args['ownership_control'],\ restart = True, emails_only = args['emails_only'], chats_only = args['chats_only']) elif args.get('type', '') == 'quick': #sync only the last x days (taken in defaults) in order to be quick #(cleaning is import here because recent days might move again # today - 2 months today = datetime.date.today() begin = today - datetime.timedelta(gmvault_utils.get_conf_defaults().getint("Sync", "quick_days", 8)) LOG.critical("Quick sync mode. Check for new emails since %s." % (begin.strftime('%d-%b-%Y'))) # today + 1 day end = today + datetime.timedelta(1) req = { 'type' : 'imap', \ 'req' : syncer.get_imap_request_btw_2_dates(begin, end), \ 'mode' : 'quick'} syncer.sync( req, \ compress_on_disk = args['compression'], \ db_cleaning = args['db-cleaning'], \ ownership_checking = args['ownership_control'], restart = args['restart'], \ emails_only = args['emails_only'], chats_only = args['chats_only']) elif args.get('type', '') == 'custom': #convert args to unicode u_str = gmvault_utils.convert_argv_to_unicode(args['request']['req']) args['request']['req'] = u_str args['request']['charset'] = 'utf-8' #for the moment always utf-8 args['request']['mode'] = 'custom' # pass an imap request. Assume that the user know what to do here LOG.critical("Perform custom synchronisation with %s request: %s.\n" \ % (args['request']['type'], args['request']['req'])) syncer.sync(args['request'], compress_on_disk = args['compression'], db_cleaning = args['db-cleaning'], \ ownership_checking = args['ownership_control'], restart = args['restart'], \ emails_only = args['emails_only'], chats_only = args['chats_only']) else: raise ValueError("Unknown synchronisation mode %s. Please use full (default), quick or custom.") #print error report LOG.critical(syncer.get_operation_report()) @classmethod def _check_db(cls, args, credential): """ Check DB """ LOG.critical("Connect to Gmail server.\n") # handle credential in all levels checker = gmvault.GMVaulter(args['db-dir'], args['host'], args['port'], \ args['email'], credential, read_only_access = True) checker.check_clean_db(db_cleaning = True) def run(self, args): #pylint:disable=R0912 """ Run the grep with the given args """ on_error = True die_with_usage = True try: if args.get('command') not in ('export'): credential = CredentialHelper.get_credential(args) if args.get('command', '') == 'sync': self._sync(args, credential) elif args.get('command', '') == 'restore': self._restore(args, credential) elif args.get('command', '') == 'check': self._check_db(args, credential) elif args.get('command', '') == 'export': self._export(args) elif args.get('command', '') == 'config': LOG.critical("Configure something. TBD.\n") on_error = False except KeyboardInterrupt, _: LOG.critical("\nCTRL-C. Stop all operations.\n") on_error = False except socket.error: LOG.critical("Error: Network problem. Please check your gmail server hostname,"\ " the internet connection or your network setup.\n") LOG.critical("=== Exception traceback ===") LOG.critical(gmvault_utils.get_exception_traceback()) LOG.critical("=== End of Exception traceback ===\n") die_with_usage = False except imaplib.IMAP4.error, imap_err: #bad login or password if str(imap_err) in ['[AUTHENTICATIONFAILED] Invalid credentials (Failure)', \ '[ALERT] Web login required: http://support.google.com/'\ 'mail/bin/answer.py?answer=78754 (Failure)', \ '[ALERT] Invalid credentials (Failure)'] : LOG.critical("ERROR: Invalid credentials, cannot login to the gmail server."\ " Please check your login and password or xoauth token.\n") die_with_usage = False else: LOG.critical("Error: %s. \n" % (imap_err) ) LOG.critical("=== Exception traceback ===") LOG.critical(gmvault_utils.get_exception_traceback()) LOG.critical("=== End of Exception traceback ===\n") except Exception, err: LOG.critical("Error: %s. \n" % (err) ) LOG.critical("=== Exception traceback ===") LOG.critical(gmvault_utils.get_exception_traceback()) LOG.critical("=== End of Exception traceback ===\n") die_with_usage = False finally: if on_error: if die_with_usage: args['parser'].die_with_usage() sys.exit(1) def init_logging(): """ init logging infrastructure """ #setup application logs: one handler for stdout and one for a log file log_utils.LoggerFactory.setup_cli_app_handler(log_utils.STANDALONE, activate_log_file=False, file_path="./gmvault.log") def activate_debug_mode(): """ Activate debugging logging """ LOG.critical("Debugging logs are going to be saved in file %s/gmvault.log.\n" % os.getenv("HOME",".")) log_utils.LoggerFactory.setup_cli_app_handler(log_utils.STANDALONE, activate_log_file=True, \ console_level= 'DEBUG', file_path="%s/gmvault.log" % os.getenv("HOME",".")) def sigusr1_handler(signum, frame): #pylint:disable=W0613 """ Signal handler to get stack trace if the program is stuck """ filename = './gmvault.traceback.txt' print("GMVAULT: Received SIGUSR1 -- Printing stack trace in %s..." % os.path.abspath(filename)) with open(filename, 'a') as f: traceback.print_stack(file=f) def register_traceback_signal(): """ To register a USR1 signal allowing to get stack trace """ signal.signal(signal.SIGUSR1, sigusr1_handler) def setup_default_conf(): """ set the environment GMVAULT_CONF_FILE which is necessary for Conf object """ gmvault_utils.get_conf_defaults() # force instanciation of conf to load the defaults def bootstrap_run(): """ temporary bootstrap """ init_logging() #force argv[0] to gmvault sys.argv[0] = "gmvault" LOG.critical("") gmvlt = GMVaultLauncher() args = gmvlt.parse_args() #activate debug if enabled if args['debug']: LOG.critical("Activate debugging information.") activate_debug_mode() # force instanciation of conf to load the defaults gmvault_utils.get_conf_defaults() gmvlt.run(args) if __name__ == '__main__': #import memdebug #memdebug.start(8080) #import sys #print("sys.argv=[%s]" %(sys.argv)) register_traceback_signal() bootstrap_run() #sys.exit(0)
38,345
Python
.py
645
43.778295
128
0.576171
gaubert/gmvault
3,572
285
144
AGPL-3.0
9/5/2024, 5:11:34 PM (Europe/Amsterdam)
12,296
cmdline_utils.py
gaubert_gmvault/src/gmv/cmdline_utils.py
''' Gmvault: a tool to backup and restore your gmail account. Copyright (C) <2011> <guillaume Aubert (guillaume dot aubert at gmail do com)> This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. ''' import argparse import sys import gmv.log_utils as log_utils LOG = log_utils.LoggerFactory.get_logger('cmdline_utils') class CmdLineParser(argparse.ArgumentParser): #pylint: disable=R0904 """ Added service to OptionParser. Comments regarding usability of the lib. By default you want to print the default in the help if you had them so the default formatter should print them Also new lines are eaten in the epilogue strings. You would use an epilogue to show examples most of the time so you want to have the possiblity to go to a new line. There should be a way to format the epilogue differently from the rest """ BOOL_TRUE = ['yes', 'true', '1'] BOOL_FALSE = ['no', 'false', '0'] BOOL_VALS = BOOL_TRUE + BOOL_FALSE def __init__(self, *args, **kwargs): """ constructor """ argparse.ArgumentParser.__init__(self, *args, **kwargs) #pylint: disable=W0142 # I like my help option message better than the default... #self.remove_option('-h') #self.add_option('-h', '--help', action='help', help='Show this message and exit.') self.epilogue = None @classmethod def convert_to_boolean(cls, val): """ Convert yes, True, true, YES to boolean True and no, False, false, NO to boolean NO """ lower_val = val.lower() if lower_val in cls.BOOL_TRUE: return True elif lower_val in cls.BOOL_FALSE: return False else: raise Exception("val %s should be in %s to be convertible to a boolean." % (val, cls.BOOL_VALS)) def print_help(self, out=sys.stderr): """ Print the help message, followed by the epilogue (if set), to the specified output file. You can define an epilogue by setting the ``epilogue`` field. :param out: file desc where to write the usage message """ super(CmdLineParser, self).print_help(out) if self.epilogue: #print >> out, '\n%s' % textwrap.fill(self.epilogue, 100, replace_whitespace = False) print >> out, '\n%s' % self.epilogue out.flush() def show_usage(self, msg=None): """ Print usage message """ self.die_with_usage(msg) def die_with_usage(self, msg=None, exit_code=2): """ Display a usage message and exit. :Parameters: msg : str If not set to ``None`` (the default), this message will be displayed before the usage message exit_code : int The process exit code. Defaults to 2. """ if msg != None: print >> sys.stderr, msg self.print_help(sys.stderr) sys.exit(exit_code) def error(self, msg): """ Overrides parent ``OptionParser`` class's ``error()`` method and forces the full usage message on error. """ self.die_with_usage("%s: error: %s\n" % (self.prog, msg)) def message(self, msg): """ Print a message """ print("%s: %s\n" % (self.prog, msg)) SYNC_HELP_EPILOGUE = """Examples: a) full synchronisation with email and password login #> gmvault --email foo.bar@gmail.com --passwd vrysecrtpasswd b) full synchronisation for german users that have to use googlemail instead of gmail #> gmvault --imap-server imap.googlemail.com --email foo.bar@gmail.com --passwd sosecrtpasswd c) restrict synchronisation with an IMAP request #> gmvault --imap-request 'Since 1-Nov-2011 Before 10-Nov-2011' --email foo.bar@gmail.com --passwd sosecrtpasswd """ def test_command_parser(): """ Test the command parser """ #parser = argparse.ArgumentParser() parser = CmdLineParser() subparsers = parser.add_subparsers(help='commands') # A sync command sync_parser = subparsers.add_parser('sync', formatter_class=argparse.ArgumentDefaultsHelpFormatter, \ help='synchronize with given gmail account') #email argument can be optional so it should be an option sync_parser.add_argument('-l', '--email', action='store', dest='email', help='email to sync with') # sync typ sync_parser.add_argument('-t', '--type', action='store', default='full-sync', help='type of synchronisation') sync_parser.add_argument("-i", "--imap-server", metavar = "HOSTNAME", \ help="Gmail imap server hostname. (default: imap.gmail.com)",\ dest="host", default="imap.gmail.com") sync_parser.add_argument("-p", "--imap-port", metavar = "PORT", \ help="Gmail imap server port. (default: 993)",\ dest="port", default=993) sync_parser.set_defaults(verb='sync') sync_parser.epilogue = SYNC_HELP_EPILOGUE # A restore command restore_parser = subparsers.add_parser('restore', help='restore email to a given email account') restore_parser.add_argument('email', action='store', help='email to sync with') restore_parser.add_argument('--recursive', '-r', default=False, action='store_true', help='Remove the contents of the directory, too', ) restore_parser.set_defaults(verb='restore') # A config command config_parser = subparsers.add_parser('config', help='add/delete/modify properties in configuration') config_parser.add_argument('dirname', action='store', help='New directory to create') config_parser.add_argument('--read-only', default=False, action='store_true', help='Set permissions to prevent writing to the directory', ) config_parser.set_defaults(verb='config') # global help #print("================ Global Help (-h)================") sys.argv = ['gmvault.py'] print(parser.parse_args()) #print("================ Global Help (--help)================") #sys.argv = ['gmvault.py', '--help'] #print(parser.parse_args()) #print("================ Sync Help (--help)================") #sys.argv = ['gmvault.py', 'sync', '-h'] #print(parser.parse_args()) #sys.argv = ['gmvault.py', 'sync', 'guillaume.aubert@gmail.com', '--type', 'quick-sync'] #print(parser.parse_args()) #print("options = %s\n" % (options)) #print("args = %s\n" % (args)) if __name__ == '__main__': test_command_parser()
7,686
Python
.py
151
40.284768
130
0.615788
gaubert/gmvault
3,572
285
144
AGPL-3.0
9/5/2024, 5:11:34 PM (Europe/Amsterdam)
12,297
credential_utils.py
gaubert_gmvault/src/gmv/credential_utils.py
''' Gmvault: a tool to backup and restore your gmail account. Copyright (C) <since 2011> <guillaume Aubert (guillaume dot aubert at gmail do com)> This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. Module handling the xauth authentication. Strongly influenced by http://code.google.com/p/googlecl/source/browse/trunk/src/googlecl/service.py and xauth part of gyb http://code.google.com/p/got-your-back/source/browse/trunk/gyb.py ''' import webbrowser import json import base64 import urllib #for urlencode import urllib2 import os import getpass import gmv.log_utils as log_utils import gmv.blowfish as blowfish import gmv.gmvault_utils as gmvault_utils LOG = log_utils.LoggerFactory.get_logger('credential_utils') def generate_permission_url(): """Generates the URL for authorizing access. This uses the "OAuth2 for Installed Applications" flow described at https://developers.google.com/accounts/docs/OAuth2InstalledApp Args: client_id: Client ID obtained by registering your app. scope: scope for access token, e.g. 'https://mail.google.com' Returns: A URL that the user should visit in their browser. """ params = {} params['client_id'] = gmvault_utils.get_conf_defaults().get("GoogleOauth2", "gmvault_client_id", "1070918343777-0eecradokiu8i77qfo8e3stbi0mkrtog.apps.googleusercontent.com") params['redirect_uri'] = gmvault_utils.get_conf_defaults().get("GoogleOauth2", "redirect_uri", 'urn:ietf:wg:oauth:2.0:oob') params['scope'] = gmvault_utils.get_conf_defaults().get("GoogleOauth2","scope",'https://mail.google.com/') params['response_type'] = 'code' account_base_url = gmvault_utils.get_conf_defaults().get("GoogleOauth2", "google_accounts_base_url", 'https://accounts.google.com') return '%s/%s?%s' % (account_base_url, 'o/oauth2/auth', gmvault_utils.format_url_params(params)) class CredentialHelper(object): """ Helper handling all credentials """ SECRET_FILEPATH = '%s/token.sec' @classmethod def get_secret_key(cls, a_filepath): """ Get secret key if it is in the file otherwise generate it and save it """ if os.path.exists(a_filepath): with open(a_filepath) as f: secret = f.read() else: secret = gmvault_utils.make_password() fdesc = os.open(a_filepath, os.O_CREAT|os.O_WRONLY, 0600) try: the_bytes = os.write(fdesc, secret) finally: os.close(fdesc) #close anyway if the_bytes < len(secret): raise Exception("Error: Cannot write secret in %s" % a_filepath) return secret @classmethod def store_passwd(cls, email, passwd): """ Encrypt and store gmail password """ passwd_file = '%s/%s.passwd' % (gmvault_utils.get_home_dir_path(), email) fdesc = os.open(passwd_file, os.O_CREAT|os.O_WRONLY, 0600) cipher = blowfish.Blowfish(cls.get_secret_key(cls.SECRET_FILEPATH % (gmvault_utils.get_home_dir_path()))) cipher.initCTR() encrypted = cipher.encryptCTR(passwd) the_bytes = os.write(fdesc, encrypted) os.close(fdesc) if the_bytes < len(encrypted): raise Exception("Error: Cannot write password in %s" % (passwd_file)) @classmethod def store_oauth2_credentials(cls, email, access_token, refresh_token, validity, type): """ store oauth_credentials """ oauth_file = '%s/%s.oauth2' % (gmvault_utils.get_home_dir_path(), email) # Open a file fdesc = os.open(oauth_file, os.O_RDWR|os.O_CREAT ) #write new content fobj = os.fdopen(fdesc, "w") #empty file fobj.truncate() fobj.seek(0, os.SEEK_SET) the_obj = { "access_token" : access_token, "refresh_token" : refresh_token, "validity" : validity, "access_creation" : gmvault_utils.get_utcnow_epoch(), "type" : type} json.dump(the_obj, fobj) fobj.close() @classmethod def read_oauth2_tok_sec(cls, email): """ Read oauth2 refresh token secret Look by default to ~/.gmvault Look for file ~/.gmvault/email.oauth2 """ gmv_dir = gmvault_utils.get_home_dir_path() #look for email.passwed in GMV_DIR user_oauth_file_path = "%s/%s.oauth2" % (gmv_dir, email) oauth_result = None if os.path.exists(user_oauth_file_path): LOG.critical("Get OAuth2 credential from %s.\n" % user_oauth_file_path) try: with open(user_oauth_file_path) as oauth_file: oauth_result = json.load(oauth_file) except Exception, _: #pylint: disable-msg=W0703 LOG.critical("Cannot read oauth credentials from %s. Force oauth credentials renewal." % user_oauth_file_path) LOG.critical("=== Exception traceback ===") LOG.critical(gmvault_utils.get_exception_traceback()) LOG.critical("=== End of Exception traceback ===\n") return oauth_result @classmethod def read_password(cls, email): """ Read password credentials Look by default to ~/.gmvault Look for file ~/.gmvault/email.passwd """ gmv_dir = gmvault_utils.get_home_dir_path() #look for email.passwed in GMV_DIR user_passwd_file_path = "%s/%s.passwd" % (gmv_dir, email) password = None if os.path.exists(user_passwd_file_path): with open(user_passwd_file_path) as f: password = f.read() cipher = blowfish.Blowfish(cls.get_secret_key(cls.SECRET_FILEPATH % (gmvault_utils.get_home_dir_path()))) cipher.initCTR() password = cipher.decryptCTR(password) return password @classmethod def get_credential(cls, args, test_mode={'activate': False, 'value': 'test_password'}): #pylint: disable-msg=W0102 """ Deal with the credentials. 1) Password --passwd passed. If --passwd passed and not password given if no password saved go in interactive mode 2) XOAuth Token """ credential = {} #first check that there is an email if not args.get('email', None): raise Exception("No email passed, Need to pass an email") if args['passwd'] in ['empty', 'store', 'renew']: # --passwd is here so look if there is a passwd in conf file # or go in interactive mode LOG.critical("Authentication performed with Gmail password.\n") passwd = cls.read_password(args['email']) #password to be renewed so need an interactive phase to get the new pass if not passwd or args['passwd'] in ['renew', 'store']: # go to interactive mode if not test_mode.get('activate', False): passwd = getpass.getpass('Please enter gmail password for %s and press ENTER:' % (args['email'])) else: passwd = test_mode.get('value', 'no_password_given') credential = { 'type' : 'passwd', 'value' : passwd} #store it in dir if asked for --store-passwd or --renew-passwd if args['passwd'] in ['renew', 'store']: LOG.critical("Store password for %s in $HOME/.gmvault." % (args['email'])) cls.store_passwd(args['email'], passwd) credential['option'] = 'saved' else: LOG.critical("Use password stored in $HOME/.gmvault dir (Storing your password here is not recommended).") credential = { 'type' : 'passwd', 'value' : passwd, 'option':'read' } # use oauth2 elif args['passwd'] in ('not_seen', None) and args['oauth2'] in (None, 'empty', 'renew', 'not_seen'): # get access token and refresh token LOG.critical("Authentication performed with Gmail OAuth2 access token.\n") renew = True if args['oauth2'] == 'renew' else False #get the oauth2 credential credential = cls.get_oauth2_credential(args['email'], renew) return credential @classmethod def _get_oauth2_acc_tok_from_ref_tok(cls, refresh_token): """Obtains a new token given a refresh token. See https://developers.google.com/accounts/docs/OAuth2InstalledApp#refresh Args: client_id: Client ID obtained by registering your app. client_secret: Client secret obtained by registering your app. refresh_token: A previously-obtained refresh token. Returns: The decoded response from the Google Accounts server, as a dict. Expected fields include 'access_token', 'expires_in', and 'refresh_token'. """ params = {} params['client_id'] = gmvault_utils.get_conf_defaults().get("GoogleOauth2", "gmvault_client_id", "1070918343777-0eecradokiu8i77qfo8e3stbi0mkrtog.apps.googleusercontent.com") params['client_secret'] = gmvault_utils.get_conf_defaults().get("GoogleOauth2", "gmvault_client_secret", "IVkl_pglv5cXzugpmnRNqtT7") params['refresh_token'] = refresh_token params['grant_type'] = 'refresh_token' account_base_url = gmvault_utils.get_conf_defaults().get("GoogleOauth2", "google_accounts_base_url", 'https://accounts.google.com') request_url = '%s/%s' % (account_base_url, 'o/oauth2/token') try: response = urllib2.urlopen(request_url, urllib.urlencode(params)).read() except Exception, err: #pylint: disable-msg=W0703 LOG.critical("Error: Problems when trying to connect to Google oauth2 endpoint: %s.\n" % (request_url)) raise err json_resp = json.loads(response) LOG.debug("json_resp = %s" % (json_resp)) return json_resp['access_token'], "normal" @classmethod def _get_authorization_tokens(cls, authorization_code): """Obtains OAuth access token and refresh token. This uses the application portion of the "OAuth2 for Installed Applications" flow at https://developers.google.com/accounts/docs/OAuth2InstalledApp#handlingtheresponse Args: client_id: Client ID obtained by registering your app. client_secret: Client secret obtained by registering your app. authorization_code: code generated by Google Accounts after user grants permission. Returns: The decoded response from the Google Accounts server, as a dict. Expected fields include 'access_token', 'expires_in', and 'refresh_token'. """ params = {} params['client_id'] = gmvault_utils.get_conf_defaults().get("GoogleOauth2", "gmvault_client_id", "1070918343777-0eecradokiu8i77qfo8e3stbi0mkrtog.apps.googleusercontent.com") params['client_secret'] = gmvault_utils.get_conf_defaults().get("GoogleOauth2", "gmvault_client_secret", "IVkl_pglv5cXzugpmnRNqtT7") params['code'] = authorization_code params['redirect_uri'] = gmvault_utils.get_conf_defaults().get("GoogleOauth2", "redirect_uri", 'urn:ietf:wg:oauth:2.0:oob') params['grant_type'] = 'authorization_code' account_base_url = gmvault_utils.get_conf_defaults().get("GoogleOauth2", "google_accounts_base_url", 'https://accounts.google.com') request_url = '%s/%s' % (account_base_url, 'o/oauth2/token') try: response = urllib2.urlopen(request_url, urllib.urlencode(params)).read() except Exception, err: #pylint: disable-msg=W0703 LOG.critical("Error: Problems when trying to connect to Google oauth2 endpoint: %s." % (request_url)) raise err return json.loads(response) @classmethod def _get_oauth2_tokens(cls, email, use_webbrowser = False, debug=False): ''' Handle the OAUTH2 workflow sequence with either a new request or based on a refresh token ''' #create permission url permission_url = generate_permission_url() #message to indicate that a browser will be opened raw_input('gmvault will now open a web browser page in order for you to grant gmvault access to your Gmail.\n'\ 'Please make sure you\'re logged into the correct Gmail account (%s) before granting access.\n'\ 'Press ENTER to open the browser.' % (email)) # run web browser otherwise print message with url if use_webbrowser: try: webbrowser.open(str(permission_url)) except Exception, err: #pylint: disable-msg=W0703 LOG.critical("Error: %s.\n" % (err) ) LOG.critical("=== Exception traceback ===") LOG.critical(gmvault_utils.get_exception_traceback()) LOG.critical("=== End of Exception traceback ===\n") verification_code = raw_input("You should now see the web page on your browser now.\n"\ "If you don\'t, you can manually open:\n\n%s\n\nOnce you've granted"\ " gmvault access, enter the verification code and press enter:\n" % (permission_url)) else: verification_code = raw_input('Please log in and/or grant access via your browser at %s ' 'then enter the verification code and press enter:' % (permission_url)) #request access and refresh token with the obtained verification code response = cls._get_authorization_tokens(verification_code) LOG.debug("get_authorization_tokens response %s" % (response)) access_tok = response['access_token'] refresh_tok = response['refresh_token'] validity = response['expires_in'] #in sec return access_tok, refresh_tok, validity, "normal" @classmethod def _generate_oauth2_auth_string(cls, username, access_token, base64_encode=True): """Generates an IMAP OAuth2 authentication string. See https://developers.google.com/google-apps/gmail/oauth2_overview Args: username: the username (email address) of the account to authenticate access_token: An OAuth2 access token. base64_encode: Whether to base64-encode the output. Returns: The SASL argument for the OAuth2 mechanism. """ auth_string = 'user=%s\1auth=Bearer %s\1\1' % (username, access_token) if base64_encode: auth_string = base64.b64encode(auth_string) return auth_string @classmethod def get_oauth2_credential(cls, email, renew_cred = False): """ Used once the connection has been lost. Return an auth_str obtained from a refresh token or with the current access token if it is still valid :param email: user email used to load refresh token from peristent file :return: credential { 'type' : 'oauth2', 'value' : auth_str, 'option':None } """ oauth2_creds = cls.read_oauth2_tok_sec(email) #workflow when you connect for the first time or want to renew the oauth2 credentials if not oauth2_creds or renew_cred: # No refresh token in stored so perform a new request if renew_cred: LOG.critical("Renew OAuth2 token (normal). Initiate interactive session to get it from Gmail.\n") else: LOG.critical("Initiate interactive session to get OAuth2 token from Gmail.\n") #interactive session with default browser initiated access_token, refresh_token, validity, type = cls._get_oauth2_tokens(email, use_webbrowser = True) if not access_token or not refresh_token: raise Exception("Cannot get OAuth2 access token from Gmail. See Gmail error message") #store newly created token cls.store_oauth2_credentials(email, access_token, refresh_token, validity, type) else: # check if the access token is still valid otherwise renew it from the refresh token now = gmvault_utils.get_utcnow_epoch() #now time as epoch seconds tok_creation = oauth2_creds['access_creation'] #creation time as epoch seconds validity = oauth2_creds['validity'] LOG.debug("oauth2 creds = %s" % (oauth2_creds['refresh_token'])) #access token is still valid then use it if now < tok_creation + validity: LOG.debug("Access Token is still valid") access_token = oauth2_creds['access_token'] else: #expired so request a new access token and store it LOG.debug("Access Token is expired. Renew it") # get a new access token based on refresh_token access_token, type = cls._get_oauth2_acc_tok_from_ref_tok(oauth2_creds['refresh_token']) # update stored information cls.store_oauth2_credentials(email, access_token, oauth2_creds['refresh_token'], validity, type) auth_str = cls._generate_oauth2_auth_string(email, access_token, base64_encode=False) LOG.debug("auth_str generated: %s" % (auth_str)) LOG.debug("Successfully read oauth2 credentials with get_oauth2_credential_from_refresh_token\n") return { 'type' : 'oauth2', 'value' : auth_str, 'option':None }
18,384
Python
.py
328
45.320122
181
0.639221
gaubert/gmvault
3,572
285
144
AGPL-3.0
9/5/2024, 5:11:34 PM (Europe/Amsterdam)
12,298
gmvault_db.py
gaubert_gmvault/src/gmv/gmvault_db.py
""" Gmvault: a tool to backup and restore your gmail account. Copyright (C) <since 2011> <guillaume Aubert (guillaume dot aubert at gmail do com)> This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. """ from contextlib import contextmanager import json import gzip import re import os import itertools import fnmatch import shutil import codecs import StringIO import gmv.blowfish as blowfish import gmv.log_utils as log_utils import gmv.collections_utils as collections_utils import gmv.gmvault_utils as gmvault_utils import gmv.imap_utils as imap_utils import gmv.credential_utils as credential_utils LOG = log_utils.LoggerFactory.get_logger('gmvault_db') class GmailStorer(object): #pylint:disable=R0902,R0904,R0914 """ Store emails on disk """ DATA_FNAME = "%s/%s.eml" METADATA_FNAME = "%s/%s.meta" CHAT_GM_LABEL = "gmvault-chats" ID_K = 'gm_id' EMAIL_K = 'email' THREAD_IDS_K = 'thread_ids' LABELS_K = 'labels' INT_DATE_K = 'internal_date' FLAGS_K = 'flags' SUBJECT_K = 'subject' MSGID_K = 'msg_id' XGM_RECV_K = 'x_gmail_received' HF_MSGID_PATTERN = r"[M,m][E,e][S,s][S,s][a,A][G,g][E,e]-[I,i][D,d]:\s+<(?P<msgid>.*)>" HF_SUB_PATTERN = r"[S,s][U,u][b,B][J,j][E,e][C,c][T,t]:\s+(?P<subject>.*)\s*" HF_XGMAIL_RECV_PATTERN = r"[X,x]-[G,g][M,m][A,a][I,i][L,l]-[R,r][E,e][C,c][E,e][I,i][V,v][E,e][D,d]:\s+(?P<received>.*)\s*" HF_MSGID_RE = re.compile(HF_MSGID_PATTERN) HF_SUB_RE = re.compile(HF_SUB_PATTERN) HF_XGMAIL_RECV_RE = re.compile(HF_XGMAIL_RECV_PATTERN) ENCRYPTED_PATTERN = r"[\w+,\.]+crypt[\w,\.]*" ENCRYPTED_RE = re.compile(ENCRYPTED_PATTERN) DB_AREA = 'db' QUARANTINE_AREA = 'quarantine' CHATS_AREA = 'chats' BIN_AREA = 'bin' SUB_CHAT_AREA = 'chats/%s' INFO_AREA = '.info' # contains metadata concerning the database ENCRYPTION_KEY_FILENAME = '.storage_key.sec' EMAIL_OWNER = '.owner_account.info' GMVAULTDB_VERSION = '.gmvault_db_version.info' def __init__(self, a_storage_dir, encrypt_data=False): """ Store on disks args: a_storage_dir: Storage directory a_use_encryption: Encryption key. If there then encrypt """ self._top_dir = a_storage_dir self._db_dir = '%s/%s' % (a_storage_dir, GmailStorer.DB_AREA) self._quarantine_dir = '%s/%s' % (a_storage_dir, GmailStorer.QUARANTINE_AREA) self._info_dir = '%s/%s' % (a_storage_dir, GmailStorer.INFO_AREA) self._chats_dir = '%s/%s' % (self._db_dir, GmailStorer.CHATS_AREA) self._bin_dir = '%s/%s' % (a_storage_dir, GmailStorer.BIN_AREA) self._sub_chats_dir = None self._sub_chats_inc = -1 self._sub_chats_nb = -1 self._limit_per_chat_dir = gmvault_utils.get_conf_defaults().getint( "General", "limit_per_chat_dir", 1500) #make dirs if not os.path.exists(self._db_dir): LOG.critical("No Storage DB in %s. Create it.\n" % a_storage_dir) gmvault_utils.makedirs(self._db_dir) gmvault_utils.makedirs(self._chats_dir) gmvault_utils.makedirs(self._quarantine_dir) gmvault_utils.makedirs(self._info_dir) self.fsystem_info_cache = {} self._encrypt_data = encrypt_data self._encryption_key = None self._cipher = None #add version if it is needed to migrate gmvault-db in the future self._create_gmvault_db_version() def _init_sub_chats_dir(self): """ get info from existing sub chats """ nb_to_dir = {} LOG.debug("LIMIT_PER_CHAT_DIR = %s" % self._limit_per_chat_dir) if os.path.exists(self._chats_dir): dirs = os.listdir(self._chats_dir) for the_dir in dirs: the_split = the_dir.split("-") if len(the_split) != 2: raise Exception("Should get 2 elements in %s" % the_split) nb_to_dir[int(the_split[1])] = the_dir if len(nb_to_dir) == 0: # no sub dir yet. Set it up self._sub_chats_nb = 0 self._sub_chats_inc = 1 self._sub_chats_dir = self.SUB_CHAT_AREA % ("subchats-%s" % (self._sub_chats_inc)) gmvault_utils.makedirs("%s/%s" % (self._db_dir, self._sub_chats_dir)) # treat when more than limit chats in max dir # treat when no dirs # add limit as attribute limit_per_dir = 2000 else: the_max = max(nb_to_dir) files = os.listdir("%s/%s" % (self._chats_dir, nb_to_dir[the_max])) self._sub_chats_nb = len(files)/2 self._sub_chats_inc = the_max self._sub_chats_dir = self.SUB_CHAT_AREA % nb_to_dir[the_max] def get_sub_chats_dir(self): """ Get sub_chats_dir """ if self._sub_chats_inc == -1: self._init_sub_chats_dir() if self._sub_chats_nb >= self._limit_per_chat_dir: self._sub_chats_inc += 1 self._sub_chats_nb = 1 self._sub_chats_dir = self.SUB_CHAT_AREA % ("subchats-%s" % (self._sub_chats_inc)) gmvault_utils.makedirs('%s/%s' % (self._db_dir, self._sub_chats_dir)) return self._sub_chats_dir else: self._sub_chats_nb += 1 return self._sub_chats_dir def _create_gmvault_db_version(self): """ Create the Gmvault database version if it doesn't already exist """ version_file = '%s/%s' % (self._info_dir, self.GMVAULTDB_VERSION) if not os.path.exists(version_file): with open(version_file, "w+") as f: f.write(gmvault_utils.GMVAULT_VERSION) def store_db_owner(self, email_owner): """ Store the email owner in .info dir. This is used to avoid synchronizing multiple email accounts in gmvault-db. Always wipe out completely the file """ owners = self.get_db_owners() if email_owner not in owners: owners.append(email_owner) with open('%s/%s' % (self._info_dir, self.EMAIL_OWNER), "w+") as f: json.dump(owners, f, ensure_ascii=False) f.flush() def get_db_owners(self): """ Get the email owner for the gmvault-db. Because except in particular cases, the db will be only linked to one email. """ fname = '%s/%s' % (self._info_dir, self.EMAIL_OWNER) if os.path.exists(fname): with open(fname, 'r') as f: list_of_owners = json.load(f) return list_of_owners return [] def get_info_dir(self): """ Return the info dir of gmvault-db """ return self._info_dir def get_encryption_cipher(self): """ Return the cipher to encrypt an decrypt. If the secret key doesn't exist, it will be generated. """ if not self._cipher: if not self._encryption_key: self._encryption_key = credential_utils.CredentialHelper.get_secret_key('%s/%s' % (self._info_dir, self.ENCRYPTION_KEY_FILENAME)) #create blowfish cipher if data needs to be encrypted self._cipher = blowfish.Blowfish(self._encryption_key) return self._cipher @classmethod def get_encryption_key_path(cls, a_root_dir): """ Return the path of the encryption key. This is used to print that information to the user """ return '%s/%s/%s' % (a_root_dir, cls.INFO_AREA, cls.ENCRYPTION_KEY_FILENAME) @classmethod def get_encryption_key(cls, a_info_dir): """ Return or generate the encryption key if it doesn't exist """ return credential_utils.CredentialHelper.get_secret_key('%s/%s' % (a_info_dir, cls.ENCRYPTION_KEY_FILENAME)) @classmethod def parse_header_fields(cls, header_fields): """ extract subject and message ids from the given header fields. Additionally, convert subject byte string to unicode and then encode in utf-8 """ subject = None msgid = None x_gmail_recv = None # look for subject matched = GmailStorer.HF_SUB_RE.search(header_fields) if matched: tempo = matched.group('subject').strip() #guess encoding and convert to utf-8 u_tempo = None encod = "not found" try: encod = gmvault_utils.guess_encoding(tempo, use_encoding_list = False) u_tempo = unicode(tempo, encoding = encod) except gmvault_utils.GuessEncoding, enc_err: #it is already in unicode so ignore encoding u_tempo = tempo except Exception, e: LOG.critical(e) LOG.critical("Warning: Guessed encoding = (%s). Ignore those characters" % (encod)) #try utf-8 u_tempo = unicode(tempo, encoding="utf-8", errors='replace') if u_tempo: subject = u_tempo.encode('utf-8') # look for a msg id matched = GmailStorer.HF_MSGID_RE.search(header_fields) if matched: msgid = matched.group('msgid').strip() # look for received xgmail id matched = GmailStorer.HF_XGMAIL_RECV_RE.search(header_fields) if matched: x_gmail_recv = matched.group('received').strip() return subject, msgid, x_gmail_recv def get_all_chats_gmail_ids(self): """ Get only chats dirs """ # first create a normal dir and sort it below with an OrderedDict # beware orderedDict preserve order by insertion and not by key order gmail_ids = {} chat_dir = '%s/%s' % (self._db_dir, self.CHATS_AREA) if os.path.exists(chat_dir): the_iter = gmvault_utils.ordered_dirwalk(chat_dir, "*.meta") #get all ids for filepath in the_iter: directory, fname = os.path.split(filepath) gmail_ids[long(os.path.splitext(fname)[0])] = os.path.basename(directory) #sort by key #used own orderedDict to be compliant with version 2.5 gmail_ids = collections_utils.OrderedDict( sorted(gmail_ids.items(), key=lambda t: t[0])) return gmail_ids def get_all_existing_gmail_ids(self, pivot_dir=None, ignore_sub_dir=('chats',)): """ get all existing gmail_ids from the database within the passed month and all posterior months """ # first create a normal dir and sort it below with an OrderedDict # beware orderedDict preserve order by insertion and not by key order gmail_ids = {} if pivot_dir is None: #the_iter = gmvault_utils.dirwalk(self._db_dir, "*.meta") the_iter = gmvault_utils.ordered_dirwalk(self._db_dir, "*.meta", ignore_sub_dir) else: # get all yy-mm dirs to list dirs = gmvault_utils.get_all_dirs_posterior_to( pivot_dir, gmvault_utils.get_all_dirs_under(self._db_dir, ignore_sub_dir)) #create all iterators and chain them to keep the same interface iter_dirs = [gmvault_utils.ordered_dirwalk('%s/%s' % (self._db_dir, the_dir), "*.meta", ignore_sub_dir) for the_dir in dirs] the_iter = itertools.chain.from_iterable(iter_dirs) #get all ids for filepath in the_iter: directory, fname = os.path.split(filepath) gmail_ids[long(os.path.splitext(fname)[0])] = os.path.basename(directory) #sort by key #used own orderedDict to be compliant with version 2.5 gmail_ids = collections_utils.OrderedDict(sorted(gmail_ids.items(), key=lambda t: t[0])) return gmail_ids def bury_chat_metadata(self, email_info, local_dir = None): """ Like bury metadata but with an extra label gmvault-chat """ extra_labels = [GmailStorer.CHAT_GM_LABEL] return self.bury_metadata(email_info, local_dir, extra_labels) def bury_metadata(self, email_info, local_dir=None, extra_labels=()): """ Store metadata info in .meta file Arguments: email_info: metadata info local_dir : intermediary dir (month dir) """ if local_dir: the_dir = '%s/%s' % (self._db_dir, local_dir) gmvault_utils.makedirs(the_dir) else: the_dir = self._db_dir meta_path = self.METADATA_FNAME % ( the_dir, email_info[imap_utils.GIMAPFetcher.GMAIL_ID]) with open(meta_path, 'w') as meta_desc: # parse header fields to extract subject and msgid subject, msgid, received = self.parse_header_fields( email_info[imap_utils.GIMAPFetcher.IMAP_HEADER_FIELDS_KEY]) # need to convert labels that are number as string # come from imap_lib when label is a number labels = [] for label in email_info[imap_utils.GIMAPFetcher.GMAIL_LABELS]: if isinstance(label, (int, long, float, complex)): label = str(label) labels.append(unicode(gmvault_utils.remove_consecutive_spaces_and_strip(label))) labels.extend(extra_labels) #add extra labels #create json structure for metadata meta_obj = { self.ID_K : email_info[imap_utils.GIMAPFetcher.GMAIL_ID], self.LABELS_K : labels, self.FLAGS_K : email_info[imap_utils.GIMAPFetcher.IMAP_FLAGS], self.THREAD_IDS_K : email_info[imap_utils.GIMAPFetcher.GMAIL_THREAD_ID], self.INT_DATE_K : gmvault_utils.datetime2e(email_info[imap_utils.GIMAPFetcher.IMAP_INTERNALDATE]), self.SUBJECT_K : subject, self.MSGID_K : msgid, self.XGM_RECV_K : received } json.dump(meta_obj, meta_desc) meta_desc.flush() return email_info[imap_utils.GIMAPFetcher.GMAIL_ID] def bury_chat(self, chat_info, local_dir=None, compress=False): """ Like bury email but with a special label: gmvault-chats Arguments: chat_info: the chat content local_dir: intermediary dir compress : if compress is True, use gzip compression """ extra_labels = ['gmvault-chats'] return self.bury_email(chat_info, local_dir, compress, extra_labels) def bury_email(self, email_info, local_dir=None, compress=False, extra_labels=()): """ store all email info in 2 files (.meta and .eml files) Arguments: email_info: the email content local_dir : intermediary dir (month dir) compress : if compress is True, use gzip compression """ if local_dir: the_dir = '%s/%s' % (self._db_dir, local_dir) gmvault_utils.makedirs(the_dir) else: the_dir = self._db_dir data_path = self.DATA_FNAME % ( the_dir, email_info[imap_utils.GIMAPFetcher.GMAIL_ID]) # TODO: First compress then encrypt # create a compressed CIOString and encrypt it #if compress: # data_path = '%s.gz' % data_path # data_desc = StringIO.StringIO() #else: # data_desc = open(data_path, 'wb') #if self._encrypt_data: # data_path = '%s.crypt2' % data_path #TODO create a wrapper fileobj that compress in io string #then chunk write #then compress #then encrypt if it is required # if the data has to be encrypted if self._encrypt_data: data_path = '%s.crypt' % data_path if compress: data_path = '%s.gz' % data_path data_desc = gzip.open(data_path, 'wb') else: data_desc = open(data_path, 'wb') try: if self._encrypt_data: # need to be done for every encryption cipher = self.get_encryption_cipher() cipher.initCTR() data = cipher.encryptCTR(email_info[imap_utils.GIMAPFetcher.EMAIL_BODY]) LOG.debug("Encrypt data.") #write encrypted data without encoding data_desc.write(data) #no encryption then utf-8 encode and write else: #convert email content to unicode data = gmvault_utils.convert_to_unicode(email_info[imap_utils.GIMAPFetcher.EMAIL_BODY]) # write in chunks of one 1 MB for chunk in gmvault_utils.chunker(data, 1048576): data_desc.write(chunk.encode('utf-8')) #store metadata info self.bury_metadata(email_info, local_dir, extra_labels) data_desc.flush() finally: data_desc.close() return email_info[imap_utils.GIMAPFetcher.GMAIL_ID] def get_directory_from_id(self, a_id, a_local_dir=None): """ If a_local_dir (yy_mm dir) is passed, check that metadata file exists and return dir Return the directory path if id located. Return None if not found """ filename = '%s.meta' % a_id #local_dir can be passed to avoid scanning the filesystem (because of WIN7 fs weaknesses) if a_local_dir: the_dir = '%s/%s' % (self._db_dir, a_local_dir) if os.path.exists(self.METADATA_FNAME % (the_dir, a_id)): return the_dir else: # first look in cache for the_dir in self.fsystem_info_cache: if filename in self.fsystem_info_cache[the_dir]: return the_dir #walk the filesystem for the_dir, _, files in os.walk(os.path.abspath(self._db_dir)): self.fsystem_info_cache[the_dir] = files for filename in fnmatch.filter(files, filename): return the_dir @contextmanager def _get_data_file_from_id(self, a_dir, a_id): """ Return data file from the id """ data_p = self.DATA_FNAME % (a_dir, a_id) # check if encrypted and compressed or not if os.path.exists('%s.crypt.gz' % data_p): f = gzip.open('%s.crypt.gz' % data_p, 'r') elif os.path.exists('%s.gz' % data_p): f = gzip.open('%s.gz' % data_p, 'r') elif os.path.exists('%s.crypt' % data_p): f = open('%s.crypt' % data_p, 'r') else: f = open(data_p) try: yield f finally: f.close() @contextmanager def _get_metadata_file_from_id(self, a_dir, a_id): """ metadata file """ f = open(self.METADATA_FNAME % (a_dir, a_id)) try: yield f finally: f.close() def quarantine_email(self, a_id): """ Quarantine the email """ #get the dir where the email is stored the_dir = self.get_directory_from_id(a_id) data = self.DATA_FNAME % (the_dir, a_id) meta = self.METADATA_FNAME % (the_dir, a_id) # check if encrypted and compressed or not if os.path.exists('%s.crypt.gz' % data): data = '%s.crypt.gz' % data elif os.path.exists('%s.gz' % data): data = '%s.gz' % data elif os.path.exists('%s.crypt' % data): data = '%s.crypt' % data #remove files if already quarantined q_data_path = os.path.join(self._quarantine_dir, os.path.basename(data)) q_meta_path = os.path.join(self._quarantine_dir, os.path.basename(meta)) if os.path.exists(q_data_path): os.remove(q_data_path) if os.path.exists(q_meta_path): os.remove(q_meta_path) if os.path.exists(data): shutil.move(data, self._quarantine_dir) else: LOG.info("Warning: %s file doesn't exist." % data) if os.path.exists(meta): shutil.move(meta, self._quarantine_dir) else: LOG.info("Warning: %s file doesn't exist." % meta) def email_encrypted(self, a_email_fn): """ True is filename contains .crypt otherwise False """ basename = os.path.basename(a_email_fn) return bool(self.ENCRYPTED_RE.match(basename)) def unbury_email(self, a_id): """ Restore the complete email info from info stored on disk Return a tuple (meta, data) """ the_dir = self.get_directory_from_id(a_id) with self._get_data_file_from_id(the_dir, a_id) as f: if self.email_encrypted(f.name): LOG.debug("Restore encrypted email %s." % a_id) # need to be done for every encryption cipher = self.get_encryption_cipher() cipher.initCTR() LOG.debug("Decrypt data.") data = cipher.decryptCTR(f.read()) else: #data = codecs.decode(f.read(), "utf-8" ) data = f.read() return self.unbury_metadata(a_id, the_dir), data def unbury_data(self, a_id, a_id_dir=None): """ Get the only the email content from the DB """ if not a_id_dir: a_id_dir = self.get_directory_from_id(a_id) with self._get_data_file_from_id(a_id_dir, a_id) as f: if self.email_encrypted(f.name): LOG.debug("Restore encrypted email %s" % a_id) # need to be done for every encryption cipher = self.get_encryption_cipher() cipher.initCTR() data = cipher.decryptCTR(f.read()) else: data = f.read() return data def unbury_metadata(self, a_id, a_id_dir=None): """ Get metadata info from DB """ if not a_id_dir: a_id_dir = self.get_directory_from_id(a_id) with self._get_metadata_file_from_id(a_id_dir, a_id) as f: metadata = json.load(f) metadata[self.INT_DATE_K] = gmvault_utils.e2datetime( metadata[self.INT_DATE_K]) # force conversion of labels as string because IMAPClient # returns a num when the label is a number (ie. '00000') and handle utf-8 new_labels = [] for label in metadata[self.LABELS_K]: if isinstance(label, (int, long, float, complex)): label = str(label) new_labels.append(unicode(label)) metadata[self.LABELS_K] = new_labels return metadata def delete_emails(self, emails_info, msg_type): """ Delete all emails and metadata with ids """ if msg_type == 'email': db_dir = self._db_dir else: db_dir = self._chats_dir move_to_bin = gmvault_utils.get_conf_defaults().get_boolean( "General", "keep_in_bin" , False) if move_to_bin: LOG.critical("Move emails to the bin:%s" % self._bin_dir) for (a_id, date_dir) in emails_info: the_dir = '%s/%s' % (db_dir, date_dir) data_p = self.DATA_FNAME % (the_dir, a_id) comp_data_p = '%s.gz' % data_p cryp_comp_data_p = '%s.crypt.gz' % data_p metadata_p = self.METADATA_FNAME % (the_dir, a_id) if move_to_bin: #move files to the bin gmvault_utils.makedirs(self._bin_dir) # create bin filenames bin_p = self.DATA_FNAME % (self._bin_dir, a_id) metadata_bin_p = self.METADATA_FNAME % (self._bin_dir, a_id) if os.path.exists(data_p): os.rename(data_p, bin_p) elif os.path.exists(comp_data_p): os.rename(comp_data_p, '%s.gz' % bin_p) elif os.path.exists(cryp_comp_data_p): os.rename(cryp_comp_data_p, '%s.crypt.gz' % bin_p) if os.path.exists(metadata_p): os.rename(metadata_p, metadata_bin_p) else: #delete files if they exists if os.path.exists(data_p): os.remove(data_p) elif os.path.exists(comp_data_p): os.remove(comp_data_p) elif os.path.exists(cryp_comp_data_p): os.remove(cryp_comp_data_p) if os.path.exists(metadata_p): os.remove(metadata_p)
26,381
Python
.py
585
33.4
127
0.557194
gaubert/gmvault
3,572
285
144
AGPL-3.0
9/5/2024, 5:11:34 PM (Europe/Amsterdam)
12,299
validation_tests.py
gaubert_gmvault/src/gmv/validation_tests.py
''' Gmvault: a tool to backup and restore your gmail account. Copyright (C) <since 2011> <guillaume Aubert (guillaume dot aubert at gmail do com)> This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. ''' import unittest import base64 import gmv.gmvault as gmvault import gmv.gmvault_utils as gmvault_utils import gmv.imap_utils as imap_utils def obfuscate_string(a_str): """ use base64 to obfuscate a string """ return base64.b64encode(a_str) def deobfuscate_string(a_str): """ deobfuscate a string """ return base64.b64decode(a_str) def read_password_file(a_path): """ Read log:pass from a file in my home """ with open(a_path) as f: line = f.readline() login, passwd = line.split(":") return deobfuscate_string(login.strip()), deobfuscate_string(passwd.strip()) def delete_db_dir(a_db_dir): """ delete the db directory """ gmvault_utils.delete_all_under(a_db_dir, delete_top_dir=True) class TestGMVaultValidation(unittest.TestCase): #pylint:disable=R0904 """ Validation Tests """ def __init__(self, stuff): """ constructor """ super(TestGMVaultValidation, self).__init__(stuff) self.test_login = None self.test_passwd = None self.default_dir = "/tmp/gmvault-tests" def setUp(self): #pylint:disable=C0103 self.test_login, self.test_passwd = read_password_file('/homespace/gaubert/.ssh/gsync_passwd') def test_help_msg_spawned_by_def(self): """ spawn python gmv_runner account > help_msg_spawned.txt check that res is 0 or 1 """ credential = { 'type' : 'passwd', 'value': self.test_passwd} test_db_dir = "/tmp/gmvault-tests" restorer = gmvault.GMVaulter(test_db_dir, 'imap.gmail.com', 993, self.test_login, credential, \ read_only_access = False) restorer.restore() #restore all emails from this essential-db #need to check that all labels are there for emails in essential gmail_ids = restorer.gstorer.get_all_existing_gmail_ids() for gm_id in gmail_ids: #get disk_metadata disk_metadata = restorer.gstorer.unbury_metadata(gm_id) # get online_metadata online_metadata = restorer.src.fetch(gm_id, imap_utils.GIMAPFetcher.GET_ALL_BUT_DATA) #compare metadata for key in disk_metadata: self.assertEquals(disk_metadata[key], online_metadata[key]) def tests(): """ main test function """ suite = unittest.TestLoader().loadTestsFromTestCase(TestGMVaultValidation) unittest.TextTestRunner(verbosity=2).run(suite) if __name__ == '__main__': tests()
3,481
Python
.py
78
36.217949
103
0.670646
gaubert/gmvault
3,572
285
144
AGPL-3.0
9/5/2024, 5:11:34 PM (Europe/Amsterdam)